diff --git a/.changeset/admin-crm.md b/.changeset/admin-crm.md new file mode 100644 index 0000000..9695286 --- /dev/null +++ b/.changeset/admin-crm.md @@ -0,0 +1,5 @@ +--- +"@freeticket/cli": minor +--- + +New `ft admin crm` commands for the master CRM (admin contract 1.8.0): list and inspect campaigns, search shows and dates, read options and the WhatsApp quota, preview an audience, launch a campaign (`--ignore-window` to send WhatsApp now outside 9:00-20:00), send or stop WhatsApp batches and cancel a scheduled campaign. SUPER_ADMIN only. Every write previews its target and asks for confirmation (`--yes` in scripts; no TTY and no `--yes` refuses), each prompt names the API host it writes to, and `launch --yes` requires `--expect-count ` (the reach the preview must match - WhatsApp-reachable for WHATSAPP, the total for EMAIL - or nothing is sent; optional but checked without `--yes`). None is retried: a 5xx or a dropped connection on a write reports the outcome as unknown and points at `campaigns list` instead of suggesting a retry, and a 2xx with an unexpected body warns that the write probably went through (exit 0) instead of crashing. Audience filters must be v2 (`"version": 2`) and are checked before anything is sent. `PAYLOAD_TOO_LARGE` (413) and `RATE_LIMITED` (429) are explained. The bundled admin contract moves to 1.8.0 (adds the `MERCH_MANAGER` staff role). diff --git a/.changeset/admin-service-token.md b/.changeset/admin-service-token.md new file mode 100644 index 0000000..420161f --- /dev/null +++ b/.changeset/admin-service-token.md @@ -0,0 +1,5 @@ +--- +"@freeticket/cli": minor +--- + +`ft admin` authenticates with a platform service token: set `FT_ADMIN_TOKEN` and it is sent as `Authorization: Bearer`, ahead of the session cookie. diff --git a/README.md b/README.md index ca836f5..4fe81c3 100644 --- a/README.md +++ b/README.md @@ -124,6 +124,7 @@ ft sales list --status CONFIRMED --json | `ft waitlist list [--city ]` · `waitlist create --data` | Per-city waitlist of an enterprise landing (export with personal data); `create` needs an enterprise service key | ADMIN | | `ft api-keys create ` · `list` · `revoke ` | Self-service API keys (the secret is shown once, never stored) | ADMIN | | `ft admin login` · `me` · `workspaces` · `users` · `plans` · `feature-flags` · `tokens` · `audit-log` | Superadmin, cross-tenant — needs a SUPER_ADMIN session, not an API key. Includes `admin workspaces plan ` (assisted plan assignment), `plan-show ` (current plan) and `delete ` (soft delete; suspend first) and `webTemplate` / `customDomain` on `update` | SUPER_ADMIN | +| `ft admin crm campaigns` · `batches` · `events` · `options` · `quota` · `preview` · `launch` | Master CRM: email / WhatsApp campaigns to buyers across workspaces. See [`ft admin crm`](#ft-admin-crm) | SUPER_ADMIN | > **Write operations** (`create`/`update`/`delete` and actions like `publish`, > `cancel`, `refund`) send a JSON body via `--data ` or @@ -143,6 +144,125 @@ ft sales list --status CONFIRMED --json | `--csv` | list commands | CSV output for spreadsheets/accounting | | `--data ` `--yes` | write commands | JSON body (inline or `@file`) · skip delete confirmation | +## `ft admin crm` + +The master CRM for the internal team: email and WhatsApp campaigns to buyers, +across every workspace, against `/api/admin/crm`. It needs a SUPER_ADMIN +credential — `FT_ADMIN_TOKEN` (a service token from `ft admin tokens create`) +or `ft admin login --session`. + +```bash +ft admin crm campaigns list [--channel EMAIL|WHATSAPP] [--status S] [--limit N] +ft admin crm campaigns get +ft admin crm campaigns cancel [--yes] +ft admin crm batches next [--ignore-window] [--yes] +ft admin crm batches stop [--yes] +ft admin crm events search [--purpose scope|promote|except] [--sender ] +ft admin crm events dates +ft admin crm options +ft admin crm quota +ft admin crm preview --filter @filter.json [--sender freeticket|] +ft admin crm launch --data @campaign.json [--ignore-window] [--expect-count N] [--yes] +``` + +**Writes send real messages.** `launch`, `campaigns cancel`, `batches next` and +`batches stop` first show what they are about to touch — `launch` runs the +audience preview with the same filter and sender (total, how many have email +or reachable WhatsApp, the estimated days at the daily quota); the others show +the campaign — and then ask for confirmation, naming the API host the write +goes to (`… against admin.appfreeticket.com?`) so a staging token pointed at +production stands out. Without a TTY they refuse unless you pass `--yes` +(being in CI is not consent). + +`launch --yes` also requires `--expect-count `: the number of people you +expect to reach — reachable by WhatsApp for a `WHATSAPP` campaign, the total +for `EMAIL`, the same `N` the prompt shows in `Launch to N people`. Take it from +`ft admin crm preview`. If the launch's own preview gives a different number it +stops before sending anything. Without `--yes` the flag is optional (the prompt +is the gate) but still checked when given. A script or an agent cannot launch +a campaign without declaring how many people it reaches. The CLI never retries a write +on its own: a 5xx or a dropped connection on a write is reported as "outcome +unknown" — check `campaigns list` before running it again (the backend rejects +the same channel + sender + subject within 10 minutes with +`DUPLICATE_CAMPAIGN` and prints the existing id). If a write answers 2xx but +with an unexpected body, the CLI exits 0 with a warning that it probably went +through — again, check `campaigns list` instead of running it again. A filter without +`"version": 2` is refused before anything is sent. + +Named errors get a next step: `OUTSIDE_SEND_WINDOW` (WhatsApp sends only +9:00-20:00 Bogotá) prints when the window opens and suggests `--ignore-window` (on `batches next`, and on a +`launch` by WhatsApp with `timing.mode` `now`); +`QUOTA_EXHAUSTED` prints when the quota frees up; `RATE_LIMITED` (429) says +when to run it again by hand; `INVALID_STATE` means the +campaign no longer allows that action; a 422 lists each `details[].path`; a 413 `PAYLOAD_TOO_LARGE` means the body is over +256 KB. + +Find the ids for a filter with `events search` and `events dates`, and the +cities, genre/format codes, plans and WhatsApp templates with `options`. + +### `filter.json` (audience filter v2) + +```json +{ + "version": 2, + "scope": { "level": "platform" }, + "include": [ + { "type": "purchased", "eventIds": ["evt_123"], "window": { "kind": "last_days", "days": 90 } } + ], + "except": [ + { "type": "received_campaign", "days": 7, "channel": "any" } + ] +} +``` + +- `scope` (default `platform`): `{ "level": "orgs", "workspaceIds": [...] }` or + `{ "level": "events", "eventIds": [...] }`. +- `include` conditions combine with AND; `except` with OR, evaluated across the + whole platform. Up to 12 per block, 50 ids per list. +- Condition types: `purchased`, `abandoned`, `checked_in` (with optional + `eventIds`, `dateIds` + `dateEventIds`, `window`), `city` (`cities`), + `facet` (`dimension`: `genre` | `format`, `codes`), `membership` (`state`: + `active` | `expiring` | `cancelled`, `withinDays` for `expiring`, `planIds`), + `spend` (`minCop`, `maxCop`), `received_campaign` (`except` only: `days`, + `channel`), `people` (`include` only: `emails`). +- `window`: `{ "kind": "any" }` (default), `{ "kind": "last_days", "days": 7|30|90 }` + or `{ "kind": "range", "from": "2026-09-01", "to": "2026-09-30" }` (Bogotá dates). +- Without a state condition (`purchased`, `abandoned`, `checked_in`, + `membership`, `people`) in `include`, the audience defaults to confirmed + buyers plus active members. + +### `campaign.json` + +```json +{ + "channel": "WHATSAPP", + "sender": { "kind": "freeticket" }, + "templateName": "promo_show", + "subject": "New date in Medellín", + "body": "We just opened a second show. Get your tickets before they are gone.", + "promotedEventId": "evt_123", + "filter": { + "version": 2, + "include": [{ "type": "purchased", "eventIds": ["evt_123"] }], + "except": [] + }, + "timing": { "mode": "batches", "firstAt": "2026-11-03T10:00:00-05:00", "batchSize": 50, "perDay": 3, "intervalMinutes": 120 } +} +``` + +- `sender`: `{ "kind": "freeticket" }` or `{ "kind": "organization", "workspaceId": "..." }`. + FreeTicket is mandatory when the scope spans the platform, several + organizations or events of more than one owner (`preview` tells you). +- WhatsApp needs an approved `templateName` (see `options`); email rejects one. + `imageUrl` for WhatsApp must come from the media library. +- `ignoreSendWindow` (or `--ignore-window`): WhatsApp with `timing.mode` `now` + only; sends even outside 9:00-20:00 Bogotá instead of failing with + `OUTSIDE_SEND_WINDOW`. +- `timing`: `{ "mode": "now" }` (sends on response), `{ "mode": "scheduled", "at": "" }` + or `batches` (WhatsApp only, daily cap 150 when FreeTicket signs, 200 for an + organization). WhatsApp times are moved into the 9:00-20:00 Bogotá window; + the response's `scheduledAt` is the real one. + ## Configuration `ft` resolves configuration in this precedence order: @@ -156,6 +276,8 @@ flags > environment variables > ~/.freeticket/config.json > defaults | `FT_API_URL` | `https://admin.appfreeticket.com` | API base URL (without `/api/v1`) | | `FT_API_KEY` | — | CI/headless only — a backend-issued `ft_live_...` token. Browser login (`ft login`) needs no key. When set it is the **only** account: stored logins are ignored, nothing fans out across them, and `--account` is rejected. A workspace pinned with `ft workspace use` still applies | | `FT_WORKSPACE_ID` | *home* | Default active workspace | +| `FT_ADMIN_TOKEN` | — | `ft admin` only — a platform service token (`ft admin tokens create`), sent as `Authorization: Bearer`. Takes precedence over the session cookie | +| `FT_ADMIN_SESSION` | — | `ft admin` only — a SUPER_ADMIN `better-auth.session_token` cookie (same as `ft admin login --session`) | | `FT_NO_UPDATE_CHECK` | — | Set to disable the "update available" notice (checked at most once a day; also off in CI, without a TTY, and with `--json`/`--raw`/`--csv`) | Logins are stored per account under `accounts` in `~/.freeticket/config.json` diff --git a/admin-openapi.json b/admin-openapi.json index 314f732..9bade83 100644 --- a/admin-openapi.json +++ b/admin-openapi.json @@ -2,7 +2,7 @@ "openapi": "3.1.0", "info": { "title": "FreeTicket Admin API", - "version": "1.5.1", + "version": "1.8.0", "description": "API REST de superadmin de FreeTicket (cross-tenant). Autenticación por sesión de plataforma (staff con rol SUPER_ADMIN) o por service token (PAT) vía `Authorization: Bearer ` — NO usa API key de tenant. Aislada del contrato B2B /api/v1." }, "servers": [ @@ -2389,6 +2389,1169 @@ } } } + }, + "/crm/campaigns": { + "get": { + "operationId": "getCrmCampaigns", + "tags": [ + "crm" + ], + "summary": "Listar campañas del CRM maestro (las que lanzó el equipo)", + "description": "Requiere sesión de plataforma con rol `SUPER_ADMIN`.", + "security": [ + { + "session": [] + } + ], + "parameters": [ + { + "name": "channel", + "in": "query", + "required": false, + "schema": { + "type": "string", + "enum": [ + "EMAIL", + "WHATSAPP" + ] + } + }, + { + "name": "status", + "in": "query", + "required": false, + "schema": { + "type": "string", + "enum": [ + "SENT", + "FAILED", + "DENIED", + "PROCESSING", + "APPROVED", + "SCHEDULED", + "CANCELLED" + ] + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "1-100, default 50", + "schema": { + "type": "integer", + "default": 50 + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminCrmCampaign" + } + } + }, + "required": [ + "data" + ] + } + } + } + }, + "401": { + "description": "Missing or invalid credential.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Insufficient role or resource not accessible.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Resource does not exist or is out of scope.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Request body/parameter validation failed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "post": { + "operationId": "postCrmCampaigns", + "tags": [ + "crm" + ], + "summary": "Lanzar una campaña del CRM maestro (ESCRITURA: envía mensajes)", + "description": "Requiere sesión de plataforma con rol `SUPER_ADMIN`. ESCRITURA: crea la campaña ya aprobada y, con `timing.mode = now`, empieza a enviar a toda la audiencia al responder. Un WhatsApp con `timing.mode = now` fuera de las 9:00–20:00 de Bogotá responde 409 `OUTSIDE_SEND_WINDOW` (reintentable) con `Retry-After` hasta la próxima apertura, antes de contar la audiencia; `ignoreSendWindow: true` la salta (el correo no tiene ventana; programada y lotes se ajustan solos). No expuesta por el MCP (`x-ft-mcp`). Errores: 422 con `error.details[].path` (filtro, remitente, reglas de canal, ids que no existen) o `EMPTY_AUDIENCE`; 409 `DUPLICATE_CAMPAIGN` con `error.details.existingId` si hace menos de 10 minutos se lanzó otra con el mismo canal, remitente y asunto; 409 `WHATSAPP_BLOCKED` (plantilla) o 503 `WHATSAPP_UNAVAILABLE` (Kapso no contestó, reintentable). Queda en `GET /audit-log` como `crm_campaign.launch`.", + "security": [ + { + "session": [] + } + ], + "x-ft-mcp": { + "expose": false, + "reason": "Escritura del CRM maestro: dispara o frena envíos reales a clientes. Solo por el CLI (`ft admin crm`) o el panel, no por un agente MCP." + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdminCrmLaunchInput" + } + } + } + }, + "responses": { + "201": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/AdminCrmLaunchResult" + } + }, + "required": [ + "data" + ] + } + } + } + }, + "401": { + "description": "Missing or invalid credential.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Insufficient role or resource not accessible.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Resource does not exist or is out of scope.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict: the resource does not allow this operation in its current state.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Payload too large: the request body exceeds the maximum size.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Request body/parameter validation failed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Too many requests: rate limit exceeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable: an external dependency is down or initialization failed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/crm/campaigns/{id}": { + "get": { + "operationId": "getCrmCampaignsId", + "tags": [ + "crm" + ], + "summary": "Detalle de una campaña del CRM maestro", + "description": "Requiere sesión de plataforma con rol `SUPER_ADMIN`.", + "security": [ + { + "session": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/AdminCrmCampaignDetail" + } + }, + "required": [ + "data" + ] + } + } + } + }, + "401": { + "description": "Missing or invalid credential.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Insufficient role or resource not accessible.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Resource does not exist or is out of scope.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Request body/parameter validation failed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/crm/campaigns/{id}/batches/next": { + "post": { + "operationId": "postCrmCampaignsIdBatchesNext", + "tags": [ + "crm" + ], + "summary": "Mandar ya el siguiente lote de WhatsApp (ESCRITURA: envía mensajes)", + "description": "Requiere sesión de plataforma con rol `SUPER_ADMIN`. ESCRITURA: reclama la campaña y envía hasta un lote de destinatarios pendientes al responder. Solo campañas del equipo (otra es 404). Respeta la ventana de 9:00–20:00 de Bogotá: fuera de ella responde 409 `OUTSIDE_SEND_WINDOW` (reintentable) con `Retry-After` hasta la próxima apertura; `ignoreSendWindow: true` la salta. Otros 409: `INVALID_STATE` (no hay pendientes, ya está saliendo un lote, no es WhatsApp) o `WHATSAPP_BLOCKED`; 429 `QUOTA_EXHAUSTED` con `Retry-After` si se usó el cupo diario; 503 `WHATSAPP_UNAVAILABLE`. No expuesta por el MCP (`x-ft-mcp`). Queda en `GET /audit-log` como `crm_campaign.batch_next`.", + "security": [ + { + "session": [] + } + ], + "x-ft-mcp": { + "expose": false, + "reason": "Escritura del CRM maestro: dispara o frena envíos reales a clientes. Solo por el CLI (`ft admin crm`) o el panel, no por un agente MCP." + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdminCrmBatchNextInput" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/AdminCrmBatchNextResult" + } + }, + "required": [ + "data" + ] + } + } + } + }, + "401": { + "description": "Missing or invalid credential.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Insufficient role or resource not accessible.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Resource does not exist or is out of scope.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict: the resource does not allow this operation in its current state.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Payload too large: the request body exceeds the maximum size.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Request body/parameter validation failed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Too many requests: rate limit exceeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Service unavailable: an external dependency is down or initialization failed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/crm/campaigns/{id}/batches/stop": { + "post": { + "operationId": "postCrmCampaignsIdBatchesStop", + "tags": [ + "crm" + ], + "summary": "Detener los lotes pendientes de una campaña (ESCRITURA)", + "description": "Requiere sesión de plataforma con rol `SUPER_ADMIN`. ESCRITURA irreversible: los destinatarios pendientes pasan a SKIPPED y ya no se envían. Solo campañas del equipo (otra es 404). 409 `INVALID_STATE` si no es de WhatsApp o tiene un lote saliendo (reintentar en un minuto). No expuesta por el MCP (`x-ft-mcp`). Queda en `GET /audit-log` como `crm_campaign.batch_stop`.", + "security": [ + { + "session": [] + } + ], + "x-ft-mcp": { + "expose": false, + "reason": "Escritura del CRM maestro: dispara o frena envíos reales a clientes. Solo por el CLI (`ft admin crm`) o el panel, no por un agente MCP." + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/AdminCrmBatchStopResult" + } + }, + "required": [ + "data" + ] + } + } + } + }, + "401": { + "description": "Missing or invalid credential.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Insufficient role or resource not accessible.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Resource does not exist or is out of scope.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict: the resource does not allow this operation in its current state.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Payload too large: the request body exceeds the maximum size.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Request body/parameter validation failed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Too many requests: rate limit exceeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/crm/campaigns/{id}/cancel": { + "post": { + "operationId": "postCrmCampaignsIdCancel", + "tags": [ + "crm" + ], + "summary": "Cancelar una campaña programada (ESCRITURA)", + "description": "Requiere sesión de plataforma con rol `SUPER_ADMIN`. ESCRITURA: la campaña programada no sale (queda `DENIED`, con un motivo que ve el organizador). Solo campañas del equipo (otra es 404). 409 `INVALID_STATE` si ya no está programada (salió, está saliendo o alguien la canceló antes). No expuesta por el MCP (`x-ft-mcp`). Queda en `GET /audit-log` como `crm_campaign.cancel`.", + "security": [ + { + "session": [] + } + ], + "x-ft-mcp": { + "expose": false, + "reason": "Escritura del CRM maestro: dispara o frena envíos reales a clientes. Solo por el CLI (`ft admin crm`) o el panel, no por un agente MCP." + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/AdminCrmCancelResult" + } + }, + "required": [ + "data" + ] + } + } + } + }, + "401": { + "description": "Missing or invalid credential.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Insufficient role or resource not accessible.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Resource does not exist or is out of scope.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict: the resource does not allow this operation in its current state.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Payload too large: the request body exceeds the maximum size.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Request body/parameter validation failed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Too many requests: rate limit exceeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/crm/audience/preview": { + "post": { + "operationId": "postCrmAudiencePreview", + "tags": [ + "crm" + ], + "summary": "Contar la audiencia de un filtro del CRM (solo lectura)", + "description": "Requiere sesión de plataforma con rol `SUPER_ADMIN`. Solo lectura: no crea nada. Devuelve contadores, una muestra de hasta 10 personas enmascarada en el servidor (correo, teléfono y nombre: solo la inicial), quién puede firmar y, si hay WhatsApp alcanzable, los días que tomaría con el cupo. Un filtro inválido responde 422 con `error.details[].path`.", + "security": [ + { + "session": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdminCrmPreviewInput" + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/AdminCrmAudiencePreview" + } + }, + "required": [ + "data" + ] + } + } + } + }, + "401": { + "description": "Missing or invalid credential.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Insufficient role or resource not accessible.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Resource does not exist or is out of scope.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Payload too large: the request body exceeds the maximum size.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Request body/parameter validation failed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Too many requests: rate limit exceeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/crm/quota": { + "get": { + "operationId": "getCrmQuota", + "tags": [ + "crm" + ], + "summary": "Cupo de WhatsApp y lotes comprometidos", + "description": "Requiere sesión de plataforma con rol `SUPER_ADMIN`.", + "security": [ + { + "session": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/AdminCrmQuotaOutlook" + } + }, + "required": [ + "data" + ] + } + } + } + }, + "401": { + "description": "Missing or invalid credential.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Insufficient role or resource not accessible.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Resource does not exist or is out of scope.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Request body/parameter validation failed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/crm/options": { + "get": { + "operationId": "getCrmOptions", + "tags": [ + "crm" + ], + "summary": "Opciones para armar una campaña (ciudades, facetas, planes, plantillas)", + "description": "Requiere sesión de plataforma con rol `SUPER_ADMIN`.", + "security": [ + { + "session": [] + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/AdminCrmWizardOptions" + } + }, + "required": [ + "data" + ] + } + } + } + }, + "401": { + "description": "Missing or invalid credential.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Insufficient role or resource not accessible.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Resource does not exist or is out of scope.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Request body/parameter validation failed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/crm/events": { + "get": { + "operationId": "getCrmEvents", + "tags": [ + "crm" + ], + "summary": "Buscar shows para una campaña del CRM", + "description": "Requiere sesión de plataforma con rol `SUPER_ADMIN`.", + "security": [ + { + "session": [] + } + ], + "parameters": [ + { + "name": "query", + "in": "query", + "required": false, + "description": "Texto (hasta 120 caracteres).", + "schema": { + "type": "string" + } + }, + { + "name": "purpose", + "in": "query", + "required": true, + "description": "`promote` solo devuelve shows publicados (y, con `senderWorkspaceId`, solo los de esa organización).", + "schema": { + "type": "string", + "enum": [ + "scope", + "promote", + "except" + ] + } + }, + { + "name": "senderWorkspaceId", + "in": "query", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminCrmEventOption" + } + } + }, + "required": [ + "data" + ] + } + } + } + }, + "401": { + "description": "Missing or invalid credential.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Insufficient role or resource not accessible.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Resource does not exist or is out of scope.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Request body/parameter validation failed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/crm/event-dates": { + "get": { + "operationId": "getCrmEventDates", + "tags": [ + "crm" + ], + "summary": "Funciones de unos shows (para acotar una condición)", + "description": "Requiere sesión de plataforma con rol `SUPER_ADMIN`.", + "security": [ + { + "session": [] + } + ], + "parameters": [ + { + "name": "eventIds", + "in": "query", + "required": true, + "description": "Ids de shows separados por coma (1 a 50).", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminCrmEventDateOption" + } + } + }, + "required": [ + "data" + ] + } + } + } + }, + "401": { + "description": "Missing or invalid credential.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Insufficient role or resource not accessible.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Resource does not exist or is out of scope.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Request body/parameter validation failed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } } }, "components": { @@ -2396,37 +3559,428 @@ "Error": { "type": "object", "properties": { - "error": { - "type": "object", - "properties": { - "code": { - "type": "string" - }, - "message": { - "type": "string" - }, - "retryable": { - "type": "boolean" - }, - "details": {} - }, - "required": [ - "code", - "message", - "retryable" - ], - "additionalProperties": false + "error": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "retryable": { + "type": "boolean" + }, + "details": {} + }, + "required": [ + "code", + "message", + "retryable" + ], + "additionalProperties": false + } + }, + "required": [ + "error" + ], + "additionalProperties": false + }, + "AdminMe": { + "type": "object", + "properties": { + "userId": { + "type": "string" + }, + "name": { + "type": "string" + }, + "email": { + "type": "string" + }, + "role": { + "type": "string", + "enum": [ + "SUPER_ADMIN", + "ADMIN", + "STAFF", + "VIEWER", + "MINCULTURA", + "MERCH_MANAGER" + ] + } + }, + "required": [ + "userId", + "name", + "email", + "role" + ], + "additionalProperties": false + }, + "FeatureFlagScope": { + "type": "string", + "enum": [ + "global", + "plan", + "workspace" + ] + }, + "Page": { + "type": "object", + "properties": { + "nextCursor": { + "type": [ + "string", + "null" + ] + }, + "hasMore": { + "type": "boolean" + } + }, + "required": [ + "nextCursor", + "hasMore" + ], + "additionalProperties": false + }, + "AdminWorkspace": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "slug": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "ARTIST", + "VENUE", + "ORGANIZER" + ] + }, + "country": { + "type": "string" + }, + "isPublished": { + "type": "boolean" + }, + "webTemplate": { + "type": [ + "string", + "null" + ] + }, + "customDomain": { + "type": [ + "string", + "null" + ] + }, + "customDomainVerifiedAt": { + "type": [ + "string", + "null" + ] + }, + "suspended": { + "type": "boolean" + }, + "suspendedAt": { + "type": [ + "string", + "null" + ] + }, + "deletedAt": { + "type": [ + "string", + "null" + ] + }, + "createdAt": { + "type": "string" + } + }, + "required": [ + "id", + "name", + "slug", + "type", + "country", + "isPublished", + "webTemplate", + "customDomain", + "customDomainVerifiedAt", + "suspended", + "suspendedAt", + "deletedAt", + "createdAt" + ], + "additionalProperties": false + }, + "AdminWorkspaceCreate": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1 + }, + "slug": { + "type": "string", + "minLength": 1, + "pattern": "^[a-z0-9-]+$" + }, + "type": { + "default": "ORGANIZER", + "type": "string", + "enum": [ + "ARTIST", + "VENUE", + "ORGANIZER" + ] + }, + "country": { + "default": "CO", + "type": "string" + }, + "email": { + "type": "string", + "format": "email", + "pattern": "^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$" + } + }, + "required": [ + "name", + "slug", + "type", + "country" + ], + "additionalProperties": false + }, + "AdminWorkspaceUpdate": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1 + }, + "slug": { + "type": "string", + "minLength": 1, + "pattern": "^[a-z0-9-]+$" + }, + "type": { + "type": "string", + "enum": [ + "ARTIST", + "VENUE", + "ORGANIZER" + ] + }, + "isPublished": { + "type": "boolean" + }, + "webTemplate": { + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + { + "type": "null" + } + ] + }, + "customDomain": { + "anyOf": [ + { + "type": "string", + "maxLength": 253, + "pattern": "^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+\\.?$" + }, + { + "type": "null" + } + ] + }, + "customDomainVerifiedAt": { + "anyOf": [ + { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + "AdminWorkspacePlanAssign": { + "type": "object", + "properties": { + "planSlug": { + "type": "string", + "enum": [ + "spark", + "star", + "icon", + "legend" + ] + } + }, + "required": [ + "planSlug" + ], + "additionalProperties": false + }, + "AdminWorkspacePlan": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string" + }, + "planSlug": { + "type": "string" + }, + "planName": { + "type": "string" + }, + "previousPlanSlug": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "workspaceId", + "planSlug", + "planName", + "previousPlanSlug" + ], + "additionalProperties": false + }, + "AdminWorkspacePlanDetail": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string" + }, + "orgId": { + "type": [ + "string", + "null" + ] + }, + "planSlug": { + "type": [ + "string", + "null" + ] + }, + "planName": { + "type": [ + "string", + "null" + ] + }, + "status": { + "anyOf": [ + { + "type": "string", + "enum": [ + "TRIALING", + "ACTIVE", + "PAST_DUE", + "CANCELLED" + ] + }, + { + "type": "null" + } + ] + }, + "startedAt": { + "type": [ + "string", + "null" + ] + }, + "expiresAt": { + "type": [ + "string", + "null" + ] + }, + "cancelledAt": { + "type": [ + "string", + "null" + ] + }, + "stripeLinked": { + "type": "boolean" + }, + "paymentOption": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "workspaceId", + "orgId", + "planSlug", + "planName", + "status", + "startedAt", + "expiresAt", + "cancelledAt", + "stripeLinked", + "paymentOption" + ], + "additionalProperties": false + }, + "AdminUserWorkspace": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "slug": { + "type": "string" + }, + "isOwner": { + "type": "boolean" } }, "required": [ - "error" + "id", + "name", + "slug", + "isOwner" ], "additionalProperties": false }, - "AdminMe": { + "AdminUser": { "type": "object", "properties": { - "userId": { + "id": { "type": "string" }, "name": { @@ -2442,50 +3996,114 @@ "ADMIN", "STAFF", "VIEWER", - "MINCULTURA" + "MINCULTURA", + "MERCH_MANAGER" + ] + }, + "banned": { + "type": "boolean" + }, + "bannedAt": { + "type": [ + "string", + "null" + ] + }, + "homeOrganizationId": { + "type": [ + "string", + "null" ] + }, + "workspaces": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AdminUserWorkspace" + } + }, + "createdAt": { + "type": "string" } }, "required": [ - "userId", + "id", "name", "email", - "role" + "role", + "banned", + "bannedAt", + "homeOrganizationId", + "workspaces", + "createdAt" ], "additionalProperties": false }, - "FeatureFlagScope": { - "type": "string", - "enum": [ - "global", - "plan", - "workspace" - ] - }, - "Page": { + "AdminUserUpdate": { "type": "object", "properties": { - "nextCursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "role": { + "type": "string", + "enum": [ + "SUPER_ADMIN", + "ADMIN", + "STAFF", + "VIEWER", + "MINCULTURA", + "MERCH_MANAGER" ] }, - "hasMore": { + "banned": { "type": "boolean" } }, + "additionalProperties": false + }, + "AdminImpersonate": { + "type": "object", + "properties": { + "targetUserId": { + "type": "string", + "minLength": 1 + }, + "workspaceId": { + "type": "string", + "minLength": 1 + } + }, + "additionalProperties": false + }, + "AdminImpersonation": { + "type": "object", + "properties": { + "token": { + "type": "string" + }, + "expiresAt": { + "type": "string" + }, + "actorUserId": { + "type": "string" + }, + "targetUserId": { + "type": "string" + }, + "targetOrgId": { + "type": [ + "string", + "null" + ] + } + }, "required": [ - "nextCursor", - "hasMore" + "token", + "expiresAt", + "actorUserId", + "targetUserId", + "targetOrgId" ], "additionalProperties": false }, - "AdminWorkspace": { + "AdminPlatformPlan": { "type": "object", "properties": { "id": { @@ -2497,72 +4115,85 @@ "slug": { "type": "string" }, - "type": { - "type": "string", - "enum": [ - "ARTIST", - "VENUE", - "ORGANIZER" - ] - }, - "country": { - "type": "string" - }, - "isPublished": { - "type": "boolean" + "priceMonthly": { + "type": "number" }, - "webTemplate": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] + "priceYearly": { + "type": "number" }, - "customDomain": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "priceBiannual": { + "type": [ + "number", + "null" ] }, - "customDomainVerifiedAt": { + "maxEvents": { "anyOf": [ { - "type": "string" + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, { "type": "null" } ] }, - "suspended": { + "isActive": { "type": "boolean" }, - "suspendedAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] + "sortOrder": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, - "deletedAt": { - "anyOf": [ - { - "type": "string" + "features": { + "type": "object", + "properties": { + "memberships": { + "type": "boolean" + }, + "content": { + "type": "boolean" + }, + "fanDatabase": { + "type": "boolean" + }, + "directMessages": { + "type": "boolean" + }, + "streaming": { + "type": "boolean" + }, + "customLanding": { + "type": "boolean" + }, + "dataExport": { + "type": "boolean" + }, + "seatMaps": { + "type": "boolean" }, - { - "type": "null" + "customDomain": { + "type": "boolean" + }, + "analytics": { + "type": "boolean" } - ] + }, + "required": [ + "memberships", + "content", + "fanDatabase", + "directMessages", + "streaming", + "customLanding", + "dataExport", + "seatMaps", + "customDomain", + "analytics" + ], + "additionalProperties": false }, "createdAt": { "type": "string" @@ -2572,20 +4203,18 @@ "id", "name", "slug", - "type", - "country", - "isPublished", - "webTemplate", - "customDomain", - "customDomainVerifiedAt", - "suspended", - "suspendedAt", - "deletedAt", + "priceMonthly", + "priceYearly", + "priceBiannual", + "maxEvents", + "isActive", + "sortOrder", + "features", "createdAt" ], "additionalProperties": false }, - "AdminWorkspaceCreate": { + "AdminPlatformPlanCreate": { "type": "object", "properties": { "name": { @@ -2597,86 +4226,153 @@ "minLength": 1, "pattern": "^[a-z0-9-]+$" }, - "type": { - "default": "ORGANIZER", - "type": "string", - "enum": [ - "ARTIST", - "VENUE", - "ORGANIZER" + "priceMonthly": { + "default": 0, + "type": "number", + "minimum": 0 + }, + "priceYearly": { + "default": 0, + "type": "number", + "minimum": 0 + }, + "priceBiannual": { + "anyOf": [ + { + "type": "number", + "minimum": 0 + }, + { + "type": "null" + } ] }, - "country": { - "default": "CO", - "type": "string" + "isActive": { + "default": true, + "type": "boolean" }, - "email": { - "type": "string", - "format": "email", - "pattern": "^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$" + "memberships": { + "type": "boolean" + }, + "content": { + "type": "boolean" + }, + "fanDatabase": { + "type": "boolean" + }, + "directMessages": { + "type": "boolean" + }, + "streaming": { + "type": "boolean" + }, + "customLanding": { + "type": "boolean" + }, + "dataExport": { + "type": "boolean" + }, + "seatMaps": { + "type": "boolean" + }, + "customDomain": { + "type": "boolean" + }, + "analytics": { + "type": "boolean" + }, + "maxEvents": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] } }, "required": [ "name", "slug", - "type", - "country" + "priceMonthly", + "priceYearly", + "isActive" ], "additionalProperties": false }, - "AdminWorkspaceUpdate": { + "AdminPlatformPlanUpdate": { "type": "object", "properties": { "name": { "type": "string", "minLength": 1 }, - "slug": { - "type": "string", - "minLength": 1, - "pattern": "^[a-z0-9-]+$" - }, - "type": { - "type": "string", - "enum": [ - "ARTIST", - "VENUE", - "ORGANIZER" - ] + "priceMonthly": { + "type": "number", + "minimum": 0 }, - "isPublished": { - "type": "boolean" + "priceYearly": { + "type": "number", + "minimum": 0 }, - "webTemplate": { + "priceBiannual": { "anyOf": [ { - "type": "string", - "minLength": 1, - "maxLength": 80 + "type": "number", + "minimum": 0 }, { "type": "null" } ] }, + "isActive": { + "type": "boolean" + }, + "sortOrder": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "memberships": { + "type": "boolean" + }, + "content": { + "type": "boolean" + }, + "fanDatabase": { + "type": "boolean" + }, + "directMessages": { + "type": "boolean" + }, + "streaming": { + "type": "boolean" + }, + "customLanding": { + "type": "boolean" + }, + "dataExport": { + "type": "boolean" + }, + "seatMaps": { + "type": "boolean" + }, "customDomain": { - "anyOf": [ - { - "type": "string", - "maxLength": 253, - "pattern": "^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+\\.?$" - }, - { - "type": "null" - } - ] + "type": "boolean" }, - "customDomainVerifiedAt": { + "analytics": { + "type": "boolean" + }, + "maxEvents": { "anyOf": [ { - "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, { "type": "null" @@ -2686,166 +4382,122 @@ }, "additionalProperties": false }, - "AdminWorkspacePlanAssign": { + "AdminFeatureFlag": { "type": "object", "properties": { - "planSlug": { - "type": "string", - "enum": [ - "spark", - "star", - "icon", - "legend" + "key": { + "type": "string" + }, + "scope": { + "$ref": "#/components/schemas/FeatureFlagScope" + }, + "scopeId": { + "type": [ + "string", + "null" + ] + }, + "enabled": { + "type": "boolean" + }, + "updatedBy": { + "type": [ + "string", + "null" ] + }, + "updatedAt": { + "type": "string" } }, "required": [ - "planSlug" + "key", + "scope", + "scopeId", + "enabled", + "updatedBy", + "updatedAt" ], "additionalProperties": false }, - "AdminWorkspacePlan": { + "AdminFeatureFlagSet": { "type": "object", "properties": { - "workspaceId": { - "type": "string" - }, - "planSlug": { - "type": "string" - }, - "planName": { - "type": "string" - }, - "previousPlanSlug": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] + "scope": { + "$ref": "#/components/schemas/FeatureFlagScope" + }, + "scopeId": { + "type": "string", + "minLength": 1 + }, + "enabled": { + "type": "boolean" } }, "required": [ - "workspaceId", - "planSlug", - "planName", - "previousPlanSlug" + "scope", + "enabled" ], "additionalProperties": false }, - "AdminWorkspacePlanDetail": { + "AdminAuditEntry": { "type": "object", "properties": { - "workspaceId": { + "id": { "type": "string" }, - "orgId": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] + "actorUserId": { + "type": "string" }, - "planSlug": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] + "action": { + "type": "string" }, - "planName": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] + "targetType": { + "type": "string" }, - "status": { - "anyOf": [ - { - "type": "string", - "enum": [ - "TRIALING", - "ACTIVE", - "PAST_DUE", - "CANCELLED" - ] - }, - { - "type": "null" - } - ] + "targetId": { + "type": "string" }, - "startedAt": { + "before": { "anyOf": [ - { - "type": "string" - }, + {}, { "type": "null" } ] }, - "expiresAt": { + "after": { "anyOf": [ - { - "type": "string" - }, + {}, { "type": "null" } ] }, - "cancelledAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "ipAddress": { + "type": [ + "string", + "null" ] }, - "stripeLinked": { - "type": "boolean" - }, - "paymentOption": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] + "createdAt": { + "type": "string" } }, "required": [ - "workspaceId", - "orgId", - "planSlug", - "planName", - "status", - "startedAt", - "expiresAt", - "cancelledAt", - "stripeLinked", - "paymentOption" + "id", + "actorUserId", + "action", + "targetType", + "targetId", + "before", + "after", + "ipAddress", + "createdAt" ], "additionalProperties": false }, - "AdminUserWorkspace": { + "AdminToken": { "type": "object", "properties": { "id": { @@ -2854,22 +4506,43 @@ "name": { "type": "string" }, - "slug": { + "tokenPrefix": { "type": "string" }, - "isOwner": { - "type": "boolean" + "lastUsedAt": { + "type": [ + "string", + "null" + ] + }, + "expiresAt": { + "type": [ + "string", + "null" + ] + }, + "revokedAt": { + "type": [ + "string", + "null" + ] + }, + "createdAt": { + "type": "string" } }, "required": [ "id", "name", - "slug", - "isOwner" + "tokenPrefix", + "lastUsedAt", + "expiresAt", + "revokedAt", + "createdAt" ], "additionalProperties": false }, - "AdminUser": { + "AdminTokenCreated": { "type": "object", "properties": { "id": { @@ -2878,162 +4551,224 @@ "name": { "type": "string" }, - "email": { + "token": { "type": "string" }, - "role": { - "type": "string", - "enum": [ - "SUPER_ADMIN", - "ADMIN", - "STAFF", - "VIEWER", - "MINCULTURA" - ] - }, - "banned": { - "type": "boolean" + "createdAt": { + "type": "string" }, - "bannedAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "expiresAt": { + "type": [ + "string", + "null" ] }, - "homeOrganizationId": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "lastUsedAt": { + "type": [ + "string", + "null" ] - }, - "workspaces": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AdminUserWorkspace" - } - }, - "createdAt": { - "type": "string" } }, "required": [ "id", "name", - "email", - "role", - "banned", - "bannedAt", - "homeOrganizationId", - "workspaces", - "createdAt" + "token", + "createdAt", + "expiresAt", + "lastUsedAt" ], "additionalProperties": false }, - "AdminUserUpdate": { + "AdminTokenCreate": { "type": "object", "properties": { - "role": { + "name": { "type": "string", - "enum": [ - "SUPER_ADMIN", - "ADMIN", - "STAFF", - "VIEWER", - "MINCULTURA" - ] + "minLength": 1 }, - "banned": { - "type": "boolean" + "expiresAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" } }, + "required": [ + "name" + ], "additionalProperties": false }, - "AdminImpersonate": { + "AdminCrmChannel": { + "type": "string", + "enum": [ + "EMAIL", + "WHATSAPP" + ] + }, + "AdminCrmCampaignStatus": { + "type": "string", + "enum": [ + "SENT", + "FAILED", + "DENIED", + "PROCESSING", + "APPROVED", + "SCHEDULED", + "CANCELLED" + ] + }, + "AdminCrmAudienceFilter": { "type": "object", + "description": "Filtro de audiencia v2 (`{ version: 2, scope, include, except }`). Objeto abierto en el contrato: lo valida el servidor con `audienceFilterSchema` (src/lib/crm/filter.ts). Un filtro inválido responde 422 con `error.details[].path` relativo al body (ej. `filter.scope.level`).", "properties": { - "targetUserId": { - "type": "string", - "minLength": 1 + "version": { + "type": "integer", + "enum": [ + 2 + ] + } + }, + "required": [ + "version" + ], + "additionalProperties": true, + "examples": [ + { + "version": 2, + "scope": { + "level": "platform" + }, + "include": [ + { + "type": "purchased", + "window": { + "kind": "last_days", + "days": 90 + } + } + ], + "except": [ + { + "type": "received_campaign", + "days": 7 + } + ] + } + ] + }, + "AdminCrmSender": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "freeticket" + } + }, + "required": [ + "kind" + ], + "additionalProperties": false }, - "workspaceId": { - "type": "string", - "minLength": 1 + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "organization" + }, + "workspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + }, + "required": [ + "kind", + "workspaceId" + ], + "additionalProperties": false } - }, - "additionalProperties": false + ], + "description": "Quién firma. `freeticket` es obligatorio si el alcance es la plataforma, varias organizaciones o eventos de más de un dueño: el servidor RECHAZA otra firma (422), no la corrige." }, - "AdminImpersonation": { + "AdminCrmCampaign": { "type": "object", "properties": { - "token": { + "id": { "type": "string" }, - "expiresAt": { + "subject": { "type": "string" }, - "actorUserId": { + "channel": { + "$ref": "#/components/schemas/AdminCrmChannel" + }, + "status": { + "type": "string", + "description": "`BroadcastStatus`" + }, + "senderName": { "type": "string" }, - "targetUserId": { + "isPlatform": { + "type": "boolean" + }, + "audienceLabel": { "type": "string" }, - "targetOrgId": { + "createdAt": { + "type": "string", + "description": "ISO 8601" + }, + "scheduledAt": { "anyOf": [ { - "type": "string" + "type": "string", + "description": "ISO 8601" }, { "type": "null" } ] - } - }, - "required": [ - "token", - "expiresAt", - "actorUserId", - "targetUserId", - "targetOrgId" - ], - "additionalProperties": false - }, - "AdminPlatformPlan": { - "type": "object", - "properties": { - "id": { - "type": "string" }, - "name": { - "type": "string" - }, - "slug": { - "type": "string" - }, - "priceMonthly": { - "type": "number" + "nextBatchAt": { + "anyOf": [ + { + "type": "string", + "description": "ISO 8601" + }, + { + "type": "null" + } + ] }, - "priceYearly": { - "type": "number" + "recipientCount": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] }, - "priceBiannual": { + "sentCount": { "anyOf": [ { - "type": "number" + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, { "type": "null" } ] }, - "maxEvents": { + "failedCount": { "anyOf": [ { "type": "integer", @@ -3045,240 +4780,593 @@ } ] }, - "isActive": { - "type": "boolean" + "deliveredCount": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, - "sortOrder": { + "readCount": { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, - "features": { + "deferredCount": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "attributed": { "type": "object", "properties": { - "memberships": { - "type": "boolean" - }, - "content": { - "type": "boolean" - }, - "fanDatabase": { - "type": "boolean" - }, - "directMessages": { - "type": "boolean" - }, - "streaming": { - "type": "boolean" - }, - "customLanding": { - "type": "boolean" - }, - "dataExport": { - "type": "boolean" - }, - "seatMaps": { - "type": "boolean" + "sales": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, - "customDomain": { - "type": "boolean" + "revenueCop": { + "type": "number" }, - "analytics": { - "type": "boolean" + "feeCop": { + "type": "number" } }, "required": [ - "memberships", - "content", - "fanDatabase", - "directMessages", - "streaming", - "customLanding", - "dataExport", - "seatMaps", - "customDomain", - "analytics" + "sales", + "revenueCop", + "feeCop" ], "additionalProperties": false - }, - "createdAt": { - "type": "string" } }, "required": [ "id", - "name", - "slug", - "priceMonthly", - "priceYearly", - "priceBiannual", - "maxEvents", - "isActive", - "sortOrder", - "features", - "createdAt" + "subject", + "channel", + "status", + "senderName", + "isPlatform", + "audienceLabel", + "createdAt", + "scheduledAt", + "nextBatchAt", + "recipientCount", + "sentCount", + "failedCount", + "deliveredCount", + "readCount", + "deferredCount", + "attributed" ], "additionalProperties": false }, - "AdminPlatformPlanCreate": { + "AdminCrmCampaignDetail": { "type": "object", "properties": { - "name": { + "id": { + "type": "string" + }, + "subject": { + "type": "string" + }, + "channel": { + "$ref": "#/components/schemas/AdminCrmChannel" + }, + "status": { "type": "string", - "minLength": 1 + "description": "`BroadcastStatus`" }, - "slug": { + "senderName": { + "type": "string" + }, + "isPlatform": { + "type": "boolean" + }, + "audienceLabel": { + "type": "string" + }, + "createdAt": { "type": "string", - "minLength": 1, - "pattern": "^[a-z0-9-]+$" + "description": "ISO 8601" }, - "priceMonthly": { - "default": 0, - "type": "number", - "minimum": 0 + "scheduledAt": { + "anyOf": [ + { + "type": "string", + "description": "ISO 8601" + }, + { + "type": "null" + } + ] }, - "priceYearly": { - "default": 0, - "type": "number", - "minimum": 0 + "nextBatchAt": { + "anyOf": [ + { + "type": "string", + "description": "ISO 8601" + }, + { + "type": "null" + } + ] }, - "priceBiannual": { + "recipientCount": { "anyOf": [ { - "type": "number", - "minimum": 0 + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, { "type": "null" } ] }, - "isActive": { - "default": true, - "type": "boolean" + "sentCount": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] }, - "memberships": { - "type": "boolean" + "failedCount": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] }, - "content": { - "type": "boolean" + "deliveredCount": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, - "fanDatabase": { - "type": "boolean" + "readCount": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, - "directMessages": { - "type": "boolean" + "deferredCount": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, - "streaming": { - "type": "boolean" + "attributed": { + "type": "object", + "properties": { + "sales": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "revenueCop": { + "type": "number" + }, + "feeCop": { + "type": "number" + } + }, + "required": [ + "sales", + "revenueCop", + "feeCop" + ], + "additionalProperties": false }, - "customLanding": { - "type": "boolean" + "body": { + "type": "string" }, - "dataExport": { - "type": "boolean" + "imageUrl": { + "type": [ + "string", + "null" + ] }, - "seatMaps": { - "type": "boolean" + "templateName": { + "type": [ + "string", + "null" + ] }, - "customDomain": { - "type": "boolean" + "promotedEvent": { + "anyOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "slug": { + "type": "string" + } + }, + "required": [ + "id", + "name", + "slug" + ], + "additionalProperties": false + }, + { + "type": "null" + } + ] }, - "analytics": { - "type": "boolean" + "filter": { + "anyOf": [ + { + "$ref": "#/components/schemas/AdminCrmAudienceFilter" + }, + { + "type": "null" + } + ], + "description": "null = campaña v1 (segmento previo al CRM v2)." }, - "maxEvents": { + "batchPlan": { "anyOf": [ { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 + "type": "object", + "properties": { + "batchSize": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "perDay": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "intervalMinutes": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } + }, + "required": [ + "batchSize", + "perDay", + "intervalMinutes" + ], + "additionalProperties": false }, { "type": "null" } ] + }, + "deliveriesByStatus": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } + }, + "topErrors": { + "type": "array", + "items": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "count": { + "type": "number" + } + }, + "required": [ + "error", + "count" + ], + "additionalProperties": false + } + }, + "sentByHour": { + "type": "array", + "items": { + "type": "object", + "properties": { + "hour": { + "type": "string", + "description": "ISO 8601" + }, + "count": { + "type": "number" + } + }, + "required": [ + "hour", + "count" + ], + "additionalProperties": false + } + }, + "conversions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "reference": { + "type": "string" + }, + "total": { + "type": "number" + }, + "createdAt": { + "type": "string", + "description": "ISO 8601" + }, + "eventName": { + "type": [ + "string", + "null" + ] + }, + "utmSource": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "reference", + "total", + "createdAt", + "eventName", + "utmSource" + ], + "additionalProperties": false + } } }, "required": [ - "name", - "slug", - "priceMonthly", - "priceYearly", - "isActive" + "id", + "subject", + "channel", + "status", + "senderName", + "isPlatform", + "audienceLabel", + "createdAt", + "scheduledAt", + "nextBatchAt", + "recipientCount", + "sentCount", + "failedCount", + "deliveredCount", + "readCount", + "deferredCount", + "attributed", + "body", + "imageUrl", + "templateName", + "promotedEvent", + "filter", + "batchPlan", + "deliveriesByStatus", + "topErrors", + "sentByHour", + "conversions" ], "additionalProperties": false }, - "AdminPlatformPlanUpdate": { + "AdminCrmPreviewInput": { "type": "object", "properties": { - "name": { - "type": "string", - "minLength": 1 + "filter": { + "$ref": "#/components/schemas/AdminCrmAudienceFilter" }, - "priceMonthly": { - "type": "number", - "minimum": 0 + "sender": { + "description": "Opcional. Solo SUMA bajas (las del remitente): uno que no corresponda al alcance recorta de más, nunca agrega gente.", + "$ref": "#/components/schemas/AdminCrmSender" + } + }, + "required": [ + "filter" + ], + "additionalProperties": false + }, + "AdminCrmAudiencePreview": { + "type": "object", + "properties": { + "counts": { + "type": "object", + "properties": { + "matched": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "excludedByExcept": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "excludedByFrequency": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "suppressed": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "total": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "reachableWhatsapp": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "withoutPhone": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } + }, + "required": [ + "matched", + "excludedByExcept", + "excludedByFrequency", + "suppressed", + "total", + "reachableWhatsapp", + "withoutPhone" + ], + "additionalProperties": false }, - "priceYearly": { - "type": "number", - "minimum": 0 + "sample": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": [ + "string", + "null" + ] + }, + "emailMasked": { + "type": "string" + }, + "phoneMasked": { + "type": [ + "string", + "null" + ] + }, + "lastPurchaseAt": { + "anyOf": [ + { + "type": "string", + "description": "ISO 8601" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "name", + "emailMasked", + "phoneMasked", + "lastPurchaseAt" + ], + "additionalProperties": false + }, + "description": "Hasta 10 personas, enmascaradas en el servidor." }, - "priceBiannual": { + "involvedWorkspaceIds": { + "type": "array", + "items": { + "type": "string" + } + }, + "senderChoice": { "anyOf": [ { - "type": "number", - "minimum": 0 + "type": "object", + "properties": { + "forced": { + "type": "boolean", + "const": true + } + }, + "required": [ + "forced" + ], + "additionalProperties": false }, { - "type": "null" + "type": "object", + "properties": { + "forced": { + "type": "boolean", + "const": false + }, + "organization": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "logoUrl": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "id", + "name", + "logoUrl" + ], + "additionalProperties": false + } + }, + "required": [ + "forced", + "organization" + ], + "additionalProperties": false } ] }, - "isActive": { - "type": "boolean" - }, - "sortOrder": { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - "memberships": { - "type": "boolean" - }, - "content": { - "type": "boolean" - }, - "fanDatabase": { - "type": "boolean" - }, - "directMessages": { - "type": "boolean" - }, - "streaming": { - "type": "boolean" - }, - "customLanding": { - "type": "boolean" - }, - "dataExport": { - "type": "boolean" - }, - "seatMaps": { - "type": "boolean" - }, - "customDomain": { - "type": "boolean" - }, - "analytics": { - "type": "boolean" - }, - "maxEvents": { + "whatsappEstimate": { "anyOf": [ { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 + "type": "object", + "properties": { + "days": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "dailyCap": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "remainingToday": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } + }, + "required": [ + "days", + "dailyCap", + "remainingToday" + ], + "additionalProperties": false }, { "type": "null" @@ -3286,253 +5374,573 @@ ] } }, + "required": [ + "counts", + "sample", + "involvedWorkspaceIds", + "senderChoice", + "whatsappEstimate" + ], "additionalProperties": false }, - "AdminFeatureFlag": { + "AdminCrmQuotaOutlook": { "type": "object", "properties": { - "key": { - "type": "string" + "limit": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, - "scope": { - "$ref": "#/components/schemas/FeatureFlagScope" + "used": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, - "scopeId": { + "remaining": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "nextFreeAt": { "anyOf": [ { - "type": "string" + "type": "string", + "description": "ISO 8601" }, { "type": "null" } ] }, - "enabled": { - "type": "boolean" + "platformDailyShare": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, - "updatedBy": { - "anyOf": [ - { - "type": "string" + "committed": { + "type": "array", + "items": { + "type": "object", + "properties": { + "at": { + "type": "string", + "description": "ISO 8601" + }, + "size": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "messageId": { + "type": "string" + } }, - { - "type": "null" - } - ] - }, - "updatedAt": { - "type": "string" + "required": [ + "at", + "size", + "messageId" + ], + "additionalProperties": false + } } }, "required": [ - "key", - "scope", - "scopeId", - "enabled", - "updatedBy", - "updatedAt" + "limit", + "used", + "remaining", + "nextFreeAt", + "platformDailyShare", + "committed" ], "additionalProperties": false }, - "AdminFeatureFlagSet": { + "AdminCrmWizardOptions": { "type": "object", "properties": { - "scope": { - "$ref": "#/components/schemas/FeatureFlagScope" + "cities": { + "type": "array", + "items": { + "type": "string" + } + }, + "facets": { + "type": "object", + "properties": { + "genre": { + "type": "array", + "items": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "label": { + "type": "string" + } + }, + "required": [ + "code", + "label" + ], + "additionalProperties": false + } + }, + "format": { + "type": "array", + "items": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "label": { + "type": "string" + } + }, + "required": [ + "code", + "label" + ], + "additionalProperties": false + } + } + }, + "required": [ + "genre", + "format" + ], + "additionalProperties": false }, - "scopeId": { - "type": "string", - "minLength": 1 + "plans": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "orgName": { + "type": "string" + } + }, + "required": [ + "id", + "name", + "orgName" + ], + "additionalProperties": false + } }, - "enabled": { - "type": "boolean" + "templates": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "language": { + "type": "string" + }, + "hasImageHeader": { + "type": "boolean" + }, + "body": { + "type": "string" + }, + "footerText": { + "type": [ + "string", + "null" + ] + }, + "urlButtonText": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "name", + "language", + "hasImageHeader", + "body" + ], + "additionalProperties": false + } + }, + "whatsappBlockedReason": { + "type": [ + "string", + "null" + ] } }, "required": [ - "scope", - "enabled" + "cities", + "facets", + "plans", + "templates", + "whatsappBlockedReason" ], "additionalProperties": false }, - "AdminAuditEntry": { + "AdminCrmEventOption": { "type": "object", "properties": { "id": { "type": "string" }, - "actorUserId": { - "type": "string" - }, - "action": { - "type": "string" - }, - "targetType": { + "name": { "type": "string" }, - "targetId": { + "slug": { "type": "string" }, - "before": { + "startsAt": { "anyOf": [ - {}, + { + "type": "string", + "description": "ISO 8601" + }, { "type": "null" } ] }, - "after": { + "lastAt": { "anyOf": [ - {}, + { + "type": "string", + "description": "ISO 8601" + }, { "type": "null" } ] }, - "ipAddress": { + "nextAt": { "anyOf": [ { - "type": "string" + "type": "string", + "description": "ISO 8601" }, { "type": "null" } ] }, - "createdAt": { + "dateCount": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "venueName": { + "type": [ + "string", + "null" + ] + }, + "city": { + "type": [ + "string", + "null" + ] + }, + "status": { + "type": "string" + }, + "orgName": { "type": "string" } }, "required": [ "id", - "actorUserId", - "action", - "targetType", - "targetId", - "before", - "after", - "ipAddress", - "createdAt" + "name", + "slug", + "startsAt", + "lastAt", + "nextAt", + "dateCount", + "venueName", + "city", + "status", + "orgName" ], "additionalProperties": false }, - "AdminToken": { + "AdminCrmEventDateOption": { "type": "object", "properties": { "id": { "type": "string" }, - "name": { + "eventId": { "type": "string" }, - "tokenPrefix": { - "type": "string" + "startsAt": { + "type": "string", + "description": "ISO 8601" }, - "lastUsedAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "label": { + "type": [ + "string", + "null" ] }, - "expiresAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "status": { + "type": "string" + }, + "venueName": { + "type": [ + "string", + "null" ] }, - "revokedAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "city": { + "type": [ + "string", + "null" ] }, - "createdAt": { - "type": "string" + "past": { + "type": "boolean" + }, + "buyers": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 } }, "required": [ "id", - "name", - "tokenPrefix", - "lastUsedAt", - "expiresAt", - "revokedAt", - "createdAt" + "eventId", + "startsAt", + "label", + "status", + "venueName", + "city", + "past", + "buyers" ], "additionalProperties": false }, - "AdminTokenCreated": { + "AdminCrmTiming": { + "oneOf": [ + { + "type": "object", + "properties": { + "mode": { + "type": "string", + "const": "now" + } + }, + "required": [ + "mode" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "mode": { + "type": "string", + "const": "scheduled" + }, + "at": { + "type": "string", + "description": "ISO 8601 con offset (ej. `2026-11-03T19:00:00-05:00`)." + } + }, + "required": [ + "mode", + "at" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "mode": { + "type": "string", + "const": "batches" + }, + "firstAt": { + "type": "string", + "description": "ISO 8601 con offset (ej. `2026-11-03T19:00:00-05:00`)." + }, + "batchSize": { + "type": "integer", + "minimum": 1, + "maximum": 200 + }, + "perDay": { + "type": "integer", + "minimum": 1, + "maximum": 24 + }, + "intervalMinutes": { + "type": "integer", + "minimum": 15, + "maximum": 1440 + } + }, + "required": [ + "mode", + "firstAt", + "batchSize", + "perDay", + "intervalMinutes" + ], + "additionalProperties": false + } + ], + "description": "Cuándo sale. `scheduled` y `batches` tienen que estar en el futuro. Por WhatsApp, la hora se ajusta a la ventana de 9:00–20:00 de Bogotá (la respuesta trae la real en `scheduledAt`). Lotes solo por WhatsApp, con un tope diario de 150 si firma FreeTicket y 200 si firma una organización." + }, + "AdminCrmLaunchInput": { "type": "object", "properties": { - "id": { - "type": "string" + "channel": { + "$ref": "#/components/schemas/AdminCrmChannel" }, - "name": { + "sender": { + "$ref": "#/components/schemas/AdminCrmSender" + }, + "templateName": { + "description": "Plantilla de WhatsApp aprobada (obligatoria por WhatsApp; el correo la rechaza). Ver `GET /crm/options`.", + "type": [ + "string", + "null" + ] + }, + "subject": { + "type": "string", + "minLength": 1 + }, + "body": { + "type": "string", + "minLength": 1 + }, + "imageUrl": { + "description": "Por WhatsApp tiene que salir de la biblioteca de medios propia.", "type": "string" }, - "token": { + "promotedEventId": { + "description": "Show PUBLICADO que se promociona (si firma una organización, uno suyo).", "type": "string" }, - "createdAt": { + "filter": { + "$ref": "#/components/schemas/AdminCrmAudienceFilter" + }, + "timing": { + "$ref": "#/components/schemas/AdminCrmTiming" + }, + "ignoreSendWindow": { + "description": "Solo WhatsApp con `timing.mode = now`: true = sale aunque sea fuera de las 9:00–20:00 de Bogotá. Por defecto la respeta y responde 409 `OUTSIDE_SEND_WINDOW` con `Retry-After`.", + "type": "boolean" + } + }, + "required": [ + "channel", + "sender", + "subject", + "body", + "filter", + "timing" + ], + "additionalProperties": false + }, + "AdminCrmLaunchResult": { + "type": "object", + "properties": { + "id": { "type": "string" }, - "expiresAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "status": { + "type": "string", + "enum": [ + "APPROVED", + "SCHEDULED" ] }, - "lastUsedAt": { + "scheduledAt": { "anyOf": [ { - "type": "string" + "type": "string", + "description": "ISO 8601" }, { "type": "null" } - ] + ], + "description": "Hora real de salida (ya ajustada a la ventana); null si sale ahora." } }, "required": [ "id", - "name", - "token", - "createdAt", - "expiresAt", - "lastUsedAt" + "status", + "scheduledAt" ], "additionalProperties": false }, - "AdminTokenCreate": { + "AdminCrmBatchNextInput": { "type": "object", "properties": { - "name": { - "type": "string", - "minLength": 1 + "ignoreSendWindow": { + "description": "true = manda aunque sea fuera de las 9:00–20:00 de Bogotá. Por defecto la respeta y responde 409 `OUTSIDE_SEND_WINDOW` con `Retry-After`.", + "type": "boolean" + } + }, + "additionalProperties": false + }, + "AdminCrmBatchNextResult": { + "type": "object", + "properties": { + "batch": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991, + "description": "Cuántos salen como máximo en este lote (lo envía el pipeline)." + } + }, + "required": [ + "batch" + ], + "additionalProperties": false + }, + "AdminCrmBatchStopResult": { + "type": "object", + "properties": { + "skipped": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991, + "description": "Destinatarios pendientes que ya no se enviarán." + } + }, + "required": [ + "skipped" + ], + "additionalProperties": false + }, + "AdminCrmCancelResult": { + "type": "object", + "properties": { + "id": { + "type": "string" }, - "expiresAt": { + "status": { "type": "string", - "format": "date-time", - "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$" + "const": "DENIED" } }, "required": [ - "name" + "id", + "status" ], "additionalProperties": false } diff --git a/src/commands/admin-crm.test.ts b/src/commands/admin-crm.test.ts new file mode 100644 index 0000000..fd1545a --- /dev/null +++ b/src/commands/admin-crm.test.ts @@ -0,0 +1,541 @@ +import { Command } from "commander"; +import { + afterEach, + beforeEach, + describe, + expect, + it, + type MockInstance, + vi, +} from "vitest"; + +const sdk = vi.hoisted(() => ({ + getCrmCampaigns: vi.fn(), + getCrmCampaignsId: vi.fn(), + getCrmEvents: vi.fn(), + getCrmEventDates: vi.fn(), + postCrmAudiencePreview: vi.fn(), + postCrmCampaigns: vi.fn(), + postCrmCampaignsIdBatchesNext: vi.fn(), +})); + +vi.mock("../admin-client/sdk.gen", async (importOriginal) => ({ + ...(await importOriginal()), + ...sdk, +})); + +const { crmErrorHint, describeWhen, parseSender, previewSummary } = + await import("./admin-crm"); +const { registerAdmin } = await import("./admin"); + +const PREVIEW = { + counts: { + matched: 120, + excludedByExcept: 5, + excludedByFrequency: 3, + suppressed: 2, + total: 110, + reachableWhatsapp: 80, + withoutPhone: 30, + }, + sample: [], + involvedWorkspaceIds: ["ws_1"], + senderChoice: { + forced: false as const, + organization: { id: "ws_1", name: "Teatro", logoUrl: null }, + }, + whatsappEstimate: { days: 2, dailyCap: 50, remainingToday: 30 }, +}; + +const CAMPAIGN = { + id: "cmp_1", + subject: "Hello", + channel: "WHATSAPP", + status: "PROCESSING", + senderName: "FreeTicket", + recipientCount: 110, + sentCount: 40, + failedCount: 0, + scheduledAt: null, + nextBatchAt: "2026-11-03T14:00:00.000Z", +}; + +const ok = (data: unknown) => ({ data: { data }, response: new Response() }); +const apiError = ( + status: number, + error: Record, + headers: Record = {}, +) => ({ + data: undefined, + error: { error: { retryable: false, ...error } }, + response: new Response(null, { status, headers }), +}); + +function build(): Command { + const program = new Command(); + program.exitOverride(); + registerAdmin(program); + return program; +} + +function crmTree(): Command { + const admin = build().commands.find((c) => c.name() === "admin") as Command; + return admin.commands.find((c) => c.name() === "crm") as Command; +} + +describe("ft admin crm command tree", () => { + it("registers every documented subcommand", () => { + const crm = crmTree(); + const names = (c: Command) => c.commands.map((s) => s.name()).sort(); + expect(names(crm)).toEqual([ + "batches", + "campaigns", + "events", + "launch", + "options", + "preview", + "quota", + ]); + const sub = (n: string) => + crm.commands.find((c) => c.name() === n) as Command; + expect(names(sub("campaigns"))).toEqual(["cancel", "get", "list"]); + expect(names(sub("batches"))).toEqual(["next", "stop"]); + expect(names(sub("events"))).toEqual(["dates", "search"]); + }); + + it("puts every write behind --yes", () => { + const crm = crmTree(); + const find = (path: string[]) => + path.reduce( + (c, n) => c.commands.find((s) => s.name() === n) as Command, + crm, + ); + for (const p of [ + ["launch"], + ["campaigns", "cancel"], + ["batches", "next"], + ["batches", "stop"], + ]) + expect(find(p).options.map((o) => o.long)).toContain("--yes"); + for (const p of [["batches", "next"], ["launch"]]) + expect(find(p).options.map((o) => o.long)).toContain("--ignore-window"); + }); +}); + +describe("ft admin crm commands", () => { + const env = { ...process.env }; + let stdout: string; + let stderr: string[]; + let exit: MockInstance; + + beforeEach(() => { + process.env.FT_ADMIN_TOKEN = "ftpat_test"; + stdout = ""; + stderr = []; + vi.spyOn(process.stdout, "write").mockImplementation( + (chunk: string | Uint8Array) => { + stdout += String(chunk); + return true; + }, + ); + vi.spyOn(console, "log").mockImplementation((...a) => { + stdout += `${a.join(" ")}\n`; + }); + vi.spyOn(console, "error").mockImplementation((...a) => { + stderr.push(a.join(" ")); + }); + exit = vi.spyOn(process, "exit").mockImplementation((() => { + throw new Error("exited"); + }) as never); + }); + + afterEach(() => { + process.env = { ...env }; + vi.restoreAllMocks(); + for (const fn of Object.values(sdk)) fn.mockReset(); + }); + + const run = (...args: string[]) => + build().parseAsync(["node", "ft", "admin", "crm", ...args]); + + it("campaigns list passes the filters through, upper-cased", async () => { + sdk.getCrmCampaigns.mockResolvedValue(ok([CAMPAIGN])); + await run( + "campaigns", + "list", + "--channel", + "whatsapp", + "--status", + "scheduled", + "--limit", + "5", + "--json", + ); + expect(sdk.getCrmCampaigns).toHaveBeenCalledWith({ + query: { channel: "WHATSAPP", status: "SCHEDULED", limit: 5 }, + }); + expect(JSON.parse(stdout)).toEqual([CAMPAIGN]); + }); + + it("events search sends query, purpose and the sender workspace", async () => { + sdk.getCrmEvents.mockResolvedValue(ok([])); + await run( + "events", + "search", + "stand up", + "--purpose", + "promote", + "--sender", + "ws_1", + "--json", + ); + expect(sdk.getCrmEvents).toHaveBeenCalledWith({ + query: { + query: "stand up", + purpose: "promote", + senderWorkspaceId: "ws_1", + }, + }); + }); + + it("events search defaults --purpose to scope", async () => { + sdk.getCrmEvents.mockResolvedValue(ok([])); + await run("events", "search", "jazz", "--json"); + expect(sdk.getCrmEvents.mock.calls[0]?.[0].query.purpose).toBe("scope"); + }); + + it("events dates joins every id (spaces or commas) into eventIds", async () => { + sdk.getCrmEventDates.mockResolvedValue(ok([])); + await run("events", "dates", "evt_1", "evt_2,evt_3", "--json"); + expect(sdk.getCrmEventDates).toHaveBeenCalledWith({ + query: { eventIds: "evt_1,evt_2,evt_3" }, + }); + }); + + it("preview maps --sender to the contract shape", async () => { + sdk.postCrmAudiencePreview.mockResolvedValue(ok(PREVIEW)); + const filter = { version: 2, include: [], except: [] }; + await run( + "preview", + "--filter", + JSON.stringify(filter), + "--sender", + "ws_1", + "--json", + ); + expect(sdk.postCrmAudiencePreview).toHaveBeenCalledWith({ + body: { filter, sender: { kind: "organization", workspaceId: "ws_1" } }, + }); + }); + + it("launch --yes previews with the same filter and sender, then posts once", async () => { + sdk.postCrmAudiencePreview.mockResolvedValue(ok(PREVIEW)); + sdk.postCrmCampaigns.mockResolvedValue( + ok({ id: "cmp_9", status: "APPROVED", scheduledAt: null }), + ); + const input = { + channel: "WHATSAPP", + sender: { kind: "freeticket" }, + templateName: "promo", + subject: "Hello", + body: "Hi", + filter: { + version: 2, + include: [{ type: "purchased", eventIds: ["evt_1"] }], + except: [], + }, + timing: { mode: "now" }, + }; + await run( + "launch", + "--data", + JSON.stringify(input), + "--expect-count", + "80", + "--yes", + "--json", + ); + expect(sdk.postCrmAudiencePreview).toHaveBeenCalledWith({ + body: { filter: input.filter, sender: input.sender }, + }); + expect(sdk.postCrmCampaigns).toHaveBeenCalledTimes(1); + expect(sdk.postCrmCampaigns).toHaveBeenCalledWith({ body: input }); + // Preview went to stderr; stdout is the launch result only. + expect(stderr.join("\n")).toContain("reachable by WhatsApp: 80"); + expect(stderr.join("\n")).toContain("~2 day(s)"); + expect(JSON.parse(stdout)).toEqual({ + id: "cmp_9", + status: "APPROVED", + scheduledAt: null, + }); + }); + + it("launch stops on an empty audience without posting", async () => { + sdk.postCrmAudiencePreview.mockResolvedValue( + ok({ ...PREVIEW, counts: { ...PREVIEW.counts, total: 0 } }), + ); + await expect( + run( + "launch", + "--data", + JSON.stringify({ filter: { version: 2 } }), + "--expect-count", + "0", + "--yes", + ), + ).rejects.toThrow("exited"); + expect(sdk.postCrmCampaigns).not.toHaveBeenCalled(); + }); + + it("launch shows the existing id on DUPLICATE_CAMPAIGN and does not retry", async () => { + sdk.postCrmAudiencePreview.mockResolvedValue(ok(PREVIEW)); + sdk.postCrmCampaigns.mockResolvedValue( + apiError(409, { + code: "DUPLICATE_CAMPAIGN", + message: "Ya lanzaste esta campaña.", + details: { existingId: "cmp_old" }, + }), + ); + await expect( + run( + "launch", + "--data", + JSON.stringify({ filter: { version: 2 }, channel: "EMAIL" }), + "--expect-count", + "110", + "--yes", + ), + ).rejects.toThrow("exited"); + expect(exit).toHaveBeenCalledWith(1); + expect(sdk.postCrmCampaigns).toHaveBeenCalledTimes(1); + const err = stderr.join("\n"); + expect(err).toContain("[DUPLICATE_CAMPAIGN]"); + expect(err).toContain("ft admin crm campaigns get cmp_old"); + }); + + const nowInput = { + channel: "WHATSAPP", + sender: { kind: "freeticket" }, + templateName: "promo", + subject: "Hello", + body: "Hi", + filter: { version: 2, include: [], except: [] }, + timing: { mode: "now" }, + }; + + it("launch --ignore-window sends ignoreSendWindow in the body", async () => { + sdk.postCrmAudiencePreview.mockResolvedValue(ok(PREVIEW)); + sdk.postCrmCampaigns.mockResolvedValue( + ok({ id: "cmp_9", status: "APPROVED", scheduledAt: null }), + ); + await run( + "launch", + "--data", + JSON.stringify(nowInput), + "--ignore-window", + "--expect-count", + "80", + "--yes", + "--json", + ); + expect(sdk.postCrmCampaigns).toHaveBeenCalledWith({ + body: { ...nowInput, ignoreSendWindow: true }, + }); + }); + + it("launch without the flag does not add ignoreSendWindow", async () => { + sdk.postCrmAudiencePreview.mockResolvedValue(ok(PREVIEW)); + sdk.postCrmCampaigns.mockResolvedValue( + ok({ id: "cmp_9", status: "APPROVED", scheduledAt: null }), + ); + await run( + "launch", + "--data", + JSON.stringify(nowInput), + "--expect-count", + "80", + "--yes", + "--json", + ); + expect(sdk.postCrmCampaigns.mock.calls[0]?.[0].body).not.toHaveProperty( + "ignoreSendWindow", + ); + }); + + it("launch on OUTSIDE_SEND_WINDOW says when it opens and suggests --ignore-window, once", async () => { + sdk.postCrmAudiencePreview.mockResolvedValue(ok(PREVIEW)); + sdk.postCrmCampaigns.mockResolvedValue( + apiError( + 409, + { + code: "OUTSIDE_SEND_WINDOW", + message: "Fuera de la ventana de envío.", + retryable: true, + }, + { "Retry-After": "5400" }, + ), + ); + await expect( + run( + "launch", + "--data", + JSON.stringify(nowInput), + "--expect-count", + "80", + "--yes", + ), + ).rejects.toThrow("exited"); + expect(sdk.postCrmCampaigns).toHaveBeenCalledTimes(1); + const err = stderr.join("\n"); + expect(err).toContain("[OUTSIDE_SEND_WINDOW]"); + expect(err).toContain("in 1h 30m"); + expect(err).toContain("--ignore-window"); + }); + + it("413 PAYLOAD_TOO_LARGE with the envelope explains the limit", async () => { + sdk.postCrmAudiencePreview.mockResolvedValue( + apiError(413, { + code: "PAYLOAD_TOO_LARGE", + message: "El cuerpo supera el máximo de 256 KB.", + }), + ); + await expect(run("preview", "--filter", '{"version":2}')).rejects.toThrow( + "exited", + ); + const err = stderr.join("\n"); + expect(err).toContain("Error 413 [PAYLOAD_TOO_LARGE]"); + expect(err).toContain("256 KB"); + }); + + it("413 without a JSON body (proxy) still reads as PAYLOAD_TOO_LARGE", async () => { + sdk.postCrmAudiencePreview.mockResolvedValue(ok(PREVIEW)); + sdk.postCrmCampaigns.mockResolvedValue({ + data: undefined, + error: "Request Entity Too Large", + response: new Response(null, { status: 413 }), + }); + await expect( + run( + "launch", + "--data", + JSON.stringify(nowInput), + "--expect-count", + "80", + "--yes", + ), + ).rejects.toThrow("exited"); + expect(exit).toHaveBeenCalledWith(1); + const err = stderr.join("\n"); + expect(err).toContain("[PAYLOAD_TOO_LARGE]"); + expect(err).toContain("Trim the JSON"); + }); + + it("batches next --ignore-window sends ignoreSendWindow", async () => { + sdk.getCrmCampaignsId.mockResolvedValue(ok(CAMPAIGN)); + sdk.postCrmCampaignsIdBatchesNext.mockResolvedValue(ok({ batch: 50 })); + await run("batches", "next", "cmp_1", "--ignore-window", "--yes", "--json"); + expect(sdk.postCrmCampaignsIdBatchesNext).toHaveBeenCalledWith({ + path: { id: "cmp_1" }, + body: { ignoreSendWindow: true }, + }); + }); + + it("batches next without the flag sends no body", async () => { + sdk.getCrmCampaignsId.mockResolvedValue(ok(CAMPAIGN)); + sdk.postCrmCampaignsIdBatchesNext.mockResolvedValue(ok({ batch: 50 })); + await run("batches", "next", "cmp_1", "--yes", "--json"); + expect(sdk.postCrmCampaignsIdBatchesNext).toHaveBeenCalledWith({ + path: { id: "cmp_1" }, + }); + }); + + it("OUTSIDE_SEND_WINDOW says when it opens and suggests --ignore-window, once", async () => { + sdk.getCrmCampaignsId.mockResolvedValue(ok(CAMPAIGN)); + sdk.postCrmCampaignsIdBatchesNext.mockResolvedValue( + apiError( + 409, + { + code: "OUTSIDE_SEND_WINDOW", + message: "Fuera de la ventana de envío.", + retryable: true, + }, + { "Retry-After": "3600" }, + ), + ); + await expect(run("batches", "next", "cmp_1", "--yes")).rejects.toThrow( + "exited", + ); + expect(sdk.postCrmCampaignsIdBatchesNext).toHaveBeenCalledTimes(1); + const err = stderr.join("\n"); + expect(err).toContain("[OUTSIDE_SEND_WINDOW]"); + expect(err).toContain("opens"); + expect(err).toContain("in 1h 0m"); + expect(err).toContain("--ignore-window"); + }); + + it("422 lists details[].path", async () => { + sdk.postCrmAudiencePreview.mockResolvedValue( + apiError(422, { + code: "VALIDATION_ERROR", + message: "Filtro inválido.", + details: [{ path: "filter.scope.level", message: "Invalid input" }], + }), + ); + await expect( + run("preview", "--filter", '{"version":2,"scope":{"level":"x"}}'), + ).rejects.toThrow("exited"); + expect(stderr.join("\n")).toContain("· filter.scope.level: Invalid input"); + }); + + it.each([ + ["preview", "--filter", '{"scope":{"level":"platform"}}'], + ["preview", "--filter", "[]"], + [ + "launch", + "--data", + JSON.stringify({ channel: "EMAIL", filter: { version: 1 } }), + "--expect-count", + "1", + "--yes", + ], + ])("a filter that is not v2 stops before any request: %j", async (...args) => { + await expect(run(...args)).rejects.toThrow("exited"); + expect(exit).toHaveBeenCalledWith(1); + expect(stderr.join("\n")).toMatch(/audience filter v2/); + expect(sdk.postCrmAudiencePreview).not.toHaveBeenCalled(); + expect(sdk.postCrmCampaigns).not.toHaveBeenCalled(); + }); +}); + +describe("helpers", () => { + it("parseSender", () => { + expect(parseSender("freeticket")).toEqual({ kind: "freeticket" }); + expect(parseSender("FreeTicket")).toEqual({ kind: "freeticket" }); + expect(parseSender("ws_1")).toEqual({ + kind: "organization", + workspaceId: "ws_1", + }); + }); + + it("describeWhen renders Bogotá time and the delay", () => { + const now = Date.parse("2026-11-03T02:00:00.000Z"); // 21:00 Bogotá + const s = describeWhen(12 * 3600, now); // 09:00 Bogotá + expect(s).toContain("9:00 AM (Bogotá)"); + expect(s).toContain("in 12h 0m"); + expect(s).toContain("2026-11-03T14:00:00.000Z"); + }); + + it("crmErrorHint names QUOTA_EXHAUSTED and leaves unknown codes alone", () => { + expect(crmErrorHint({ code: "QUOTA_EXHAUSTED" }, 60)).toContain( + "quota is used up", + ); + expect(crmErrorHint({ code: "NOT_FOUND" }, undefined)).toBeNull(); + }); + + it("previewSummary leaves out the WhatsApp estimate for email", () => { + const email = previewSummary(PREVIEW, "EMAIL").join("\n"); + expect(email).toContain("110 people"); + expect(email).not.toContain("day(s)"); + expect(email).toContain("Teatro (ws_1)"); + }); +}); diff --git a/src/commands/admin-crm.transport.test.ts b/src/commands/admin-crm.transport.test.ts new file mode 100644 index 0000000..90192d3 --- /dev/null +++ b/src/commands/admin-crm.transport.test.ts @@ -0,0 +1,144 @@ +import { + afterEach, + beforeEach, + describe, + expect, + it, + type MockInstance, + vi, +} from "vitest"; + +/** + * No-retry at the transport level. Here the generated admin SDK and the + * hey-api fetch client are REAL — only `globalThis.fetch` is faked — so a + * retry added anywhere below `crmWriteOnce` (an interceptor, a client option, + * a wrapper in the SDK) shows up as a second POST. The other CRM tests mock + * the SDK functions and cannot see that layer. + */ + +const { program } = await import("../program"); + +const PREVIEW = { + counts: { + matched: 12, + excludedByExcept: 1, + excludedByFrequency: 0, + suppressed: 1, + total: 10, + reachableWhatsapp: 7, + withoutPhone: 3, + }, + sample: [], + involvedWorkspaceIds: ["ws_1"], + senderChoice: { forced: true }, + whatsappEstimate: { days: 1, dailyCap: 150, remainingToday: 150 }, +}; + +const CAMPAIGN = { + id: "cmp_1", + subject: "Hello", + channel: "WHATSAPP", + status: "PROCESSING", + senderName: "FreeTicket", + recipientCount: 10, + sentCount: 0, + failedCount: 0, + scheduledAt: null, + nextBatchAt: null, +}; + +const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json" }, + }); + +type Call = { method: string; path: string }; + +describe("CRM writes reach fetch exactly once on a 503 (real admin SDK)", () => { + const env = { ...process.env }; + let calls: Call[]; + let exit: MockInstance; + let stderr: string[]; + + beforeEach(() => { + process.env.FT_ADMIN_TOKEN = "ftpat_test"; + process.env.FT_API_URL = "https://admin.example.test"; + calls = []; + stderr = []; + vi.stubGlobal( + "fetch", + vi.fn(async (input: string | URL | Request, init?: RequestInit) => { + const req = input instanceof Request ? input : new Request(input, init); + const { pathname } = new URL(req.url); + calls.push({ method: req.method, path: pathname }); + if ( + req.method === "POST" && + pathname === "/api/admin/crm/audience/preview" + ) + return json(200, { data: PREVIEW }); + if ( + req.method === "GET" && + pathname === "/api/admin/crm/campaigns/cmp_1" + ) + return json(200, { data: CAMPAIGN }); + // Every write: the server is unavailable. + return new Response("Service Unavailable", { status: 503 }); + }), + ); + vi.spyOn(console, "error").mockImplementation((...a) => { + stderr.push(a.join(" ")); + }); + vi.spyOn(console, "log").mockImplementation(() => {}); + vi.spyOn(process.stdout, "write").mockImplementation(() => true); + exit = vi.spyOn(process, "exit").mockImplementation((() => { + throw new Error("exited"); + }) as never); + }); + + afterEach(() => { + process.env = { ...env }; + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + }); + + const campaign = JSON.stringify({ + channel: "WHATSAPP", + sender: { kind: "freeticket" }, + templateName: "promo", + subject: "Hello", + body: "Hi", + filter: { version: 2, include: [], except: [] }, + timing: { mode: "now" }, + }); + + it.each([ + { + name: "launch", + args: ["launch", "--data", campaign, "--expect-count", "7", "--yes"], + read: { method: "POST", path: "/api/admin/crm/audience/preview" }, + write: { method: "POST", path: "/api/admin/crm/campaigns" }, + }, + { + name: "batches next", + args: ["batches", "next", "cmp_1", "--yes"], + read: { method: "GET", path: "/api/admin/crm/campaigns/cmp_1" }, + write: { + method: "POST", + path: "/api/admin/crm/campaigns/cmp_1/batches/next", + }, + }, + ])("$name: one read, one write, no retry", async ({ args, read, write }) => { + await expect( + program.parseAsync(["node", "ft", "admin", "crm", ...args]), + ).rejects.toThrow("exited"); + expect(exit).toHaveBeenCalledWith(1); + expect( + calls.filter((c) => c.method === write.method && c.path === write.path), + ).toHaveLength(1); + // Nothing else went out: exactly the read that shows the target, then + // the single write. + expect(calls).toEqual([read, write]); + expect(stderr.join("\n")).toContain("never retries"); + }); +}); diff --git a/src/commands/admin-crm.ts b/src/commands/admin-crm.ts new file mode 100644 index 0000000..fba20b0 --- /dev/null +++ b/src/commands/admin-crm.ts @@ -0,0 +1,702 @@ +import chalk from "chalk"; +import type { Command } from "commander"; +import { client as adminClient } from "../admin-client/client.gen"; +import { + getCrmCampaigns, + getCrmCampaignsId, + getCrmEventDates, + getCrmEvents, + getCrmOptions, + getCrmQuota, + postCrmAudiencePreview, + postCrmCampaigns, + postCrmCampaignsIdBatchesNext, + postCrmCampaignsIdBatchesStop, + postCrmCampaignsIdCancel, +} from "../admin-client/sdk.gen"; +import type { + AdminCrmAudienceFilter, + AdminCrmAudiencePreview, + AdminCrmCampaignDetail, + AdminCrmLaunchInput, + AdminCrmSender, +} from "../admin-client/types.gen"; +import { configureAdminClient, fail, unwrap } from "../lib/api"; +import { confirmOrExit, parseData } from "../lib/input"; +import { print, resolveColumns, toCsv } from "../lib/output"; + +/** + * `ft admin crm …` — the master CRM (/api/admin/crm) for the internal team. + * + * Every write sends real messages to real customers, so: + * - each one shows what it is about to touch (audience preview for `launch`, + * the campaign for `cancel` / `batches`) and then goes through + * `confirmOrExit` — no TTY and no `--yes` is a hard stop; + * - POSTs are never retried by the CLI. A timeout on `launch` may still have + * created the campaign; the backend's DUPLICATE_CAMPAIGN guard (same + * channel, sender and subject within 10 minutes) is the safety net, and the + * error points at the existing id. + */ + +const CAMPAIGN_COLUMNS = [ + "id", + "subject", + "channel", + "status", + "senderName", + "recipientCount", + "sentCount", + "failedCount", + "scheduledAt", + "nextBatchAt", + "createdAt", +]; + +const EVENT_COLUMNS = [ + "id", + "name", + "orgName", + "status", + "city", + "dateCount", + "nextAt", + "lastAt", +]; + +const DATE_COLUMNS = [ + "id", + "eventId", + "startsAt", + "label", + "status", + "venueName", + "city", + "past", + "buyers", +]; + +type SdkResult = { data?: T; error?: unknown; response: Response }; + +type CrmError = { + code?: string; + message?: string; + retryable?: boolean; + details?: unknown; +}; + +/** `Retry-After` (seconds) of a response, if the backend sent one. */ +function retryAfterSeconds(res: Response | undefined): number | undefined { + const raw = res?.headers.get("retry-after"); + if (!raw) return undefined; + const n = Number(raw); + if (Number.isFinite(n)) return n; + const at = Date.parse(raw); + return Number.isNaN(at) + ? undefined + : Math.max(0, Math.round((at - Date.now()) / 1000)); +} + +/** "Nov 3, 7:00 PM (Bogotá), in 2h 15m" for a delay in seconds. */ +export function describeWhen(seconds: number, now = Date.now()): string { + const at = new Date(now + seconds * 1000); + const local = at.toLocaleString("en-US", { + timeZone: "America/Bogota", + month: "short", + day: "numeric", + hour: "numeric", + minute: "2-digit", + }); + const mins = Math.ceil(seconds / 60); + const h = Math.floor(mins / 60); + const m = mins % 60; + const rel = h > 0 ? `${h}h ${m}m` : `${m}m`; + return `${local} (Bogotá), in ${rel} — ${at.toISOString()}`; +} + +const PAYLOAD_HINT = + "The request body is over the backend limit (256 KB). Trim the JSON: long `people` email lists, a huge `body`, or ids that could be a scope instead."; + +/** + * The error message + next step for the CRM's named errors. `null` when the + * code is not one of them (the generic `unwrap` handles it). + */ +export function crmErrorHint( + err: CrmError, + retryAfter: number | undefined, +): string | null { + switch (err.code) { + case "OUTSIDE_SEND_WINDOW": + return [ + retryAfter !== undefined + ? `The WhatsApp send window (9:00-20:00 Bogotá) opens ${describeWhen(retryAfter)}.` + : "The WhatsApp send window (9:00-20:00 Bogotá) is closed.", + "Retry then, or pass --ignore-window to send now.", + ].join("\n"); + case "DUPLICATE_CAMPAIGN": { + const id = (err.details as { existingId?: string } | undefined) + ?.existingId; + return id + ? `A campaign with the same channel, sender and subject was launched less than 10 minutes ago: ${id}\nSee it with \`ft admin crm campaigns get ${id}\`. Change the subject if this one is really different.` + : "A campaign with the same channel, sender and subject was launched less than 10 minutes ago. Check `ft admin crm campaigns list`."; + } + case "QUOTA_EXHAUSTED": + return retryAfter !== undefined + ? `The daily WhatsApp quota is used up. It frees up ${describeWhen(retryAfter)}. See \`ft admin crm quota\`.` + : "The daily WhatsApp quota is used up. See `ft admin crm quota`."; + case "INVALID_STATE": + return "The campaign does not allow this right now (already sent, a batch is going out, or nothing is pending). Check it with `ft admin crm campaigns get `."; + case "EMPTY_AUDIENCE": + return "The filter matches nobody. Adjust it and check with `ft admin crm preview`."; + case "WHATSAPP_BLOCKED": + return "WhatsApp sending is blocked for this template or sender. See `whatsappBlockedReason` in `ft admin crm options`."; + case "PAYLOAD_TOO_LARGE": + return PAYLOAD_HINT; + case "WHATSAPP_UNAVAILABLE": + return "The WhatsApp provider did not answer. Safe to retry by hand in a moment - the CLI never retries a write on its own."; + case "RATE_LIMITED": + return retryAfter !== undefined + ? `Too many CRM requests in a short time. Run it again by hand ${describeWhen(retryAfter)} - the CLI never retries a write on its own.` + : "Too many CRM requests in a short time. Wait a minute and run it again by hand - the CLI never retries a write on its own."; + default: + return null; + } +} + +/** + * After a failed write whose outcome is unknown (5xx, a dropped connection): + * the backend may have acted. Never "retry with backoff" here — that is how a + * campaign goes out twice. + */ +export const WRITE_OUTCOME_UNKNOWN_HINT = + "The write may or may not have gone through - the CLI never retries it. Check `ft admin crm campaigns list` (or `campaigns get `) before running it again."; + +/** + * Runs one CRM write exactly once. A thrown request (timeout, connection + * reset) is reported as "outcome unknown" instead of bubbling up as a stack + * trace that invites a blind re-run. + */ +async function crmWriteOnce(call: () => Promise>): Promise { + let res: SdkResult; + try { + res = await call(); + } catch (err) { + fail( + `Error: the request did not complete (${(err as Error)?.message ?? String(err)}).`, + WRITE_OUTCOME_UNKNOWN_HINT, + ); + } + return crmUnwrap(res, { write: true }); +} + +/** + * Host the admin client is pointed at (`admin.appfreeticket.com`, a staging + * host, localhost…). Named in every write confirmation so a staging token + * aimed at production — or the reverse — is visible before saying yes. + */ +export function apiHost(): string { + const base = adminClient.getConfig().baseUrl ?? ""; + try { + return new URL(base).host || base; + } catch { + return base || "(unknown host)"; + } +} + +/** `confirmOrExit` for a CRM write, naming the API host it goes to. */ +function confirmCrmWrite( + action: string, + tail: string, + yes: boolean | undefined, +): Promise { + return confirmOrExit( + `${action} against ${apiHost()}?${tail ? ` ${tail}` : ""}`, + yes, + ); +} + +/** + * A write answered 2xx but the body is not the documented `{ data: … }` + * (a proxy page, an empty body, a contract drift). The backend most likely + * acted, so this must not crash or exit non-zero — either reads as "it failed, + * run it again", which is how a campaign goes out twice. + */ +export const UNEXPECTED_WRITE_RESPONSE_HINT = + "The server accepted the request (2xx) but answered in an unexpected shape. The write PROBABLY WENT THROUGH - do not run it again. Check `ft admin crm campaigns list` (or `campaigns get `)."; + +function writeData(body: unknown): unknown { + const data = + body && typeof body === "object" + ? (body as { data?: unknown }).data + : undefined; + if (data === undefined || data === null) { + console.error(chalk.yellow(`Warning: ${UNEXPECTED_WRITE_RESPONSE_HINT}`)); + return undefined; + } + return data; +} + +/** `--expect-count `: a non-negative integer, or a hard stop. */ +export function parseExpectCount(value: unknown): number | undefined { + if (value === undefined) return undefined; + const raw = String(value).trim(); + if (!/^\d+$/.test(raw)) + fail(`Invalid --expect-count: ${raw}. Use a whole number of people.`); + return Number(raw); +} + +/** + * `unwrap` plus the CRM's named errors. Formats the envelope itself because + * `details` is not always a list here (`{ existingId }` on a duplicate). + * With `write`, a 5xx without a named code gets the "outcome unknown" hint + * instead of the generic "retry with backoff". + */ +function crmUnwrap(res: SdkResult, opts: { write?: boolean } = {}): T { + if (res.data !== undefined) return res.data; + const err = (res.error as { error?: CrmError } | undefined)?.error; + const status = res.response?.status; + if (!err && status === 413) + fail( + "Error 413 [PAYLOAD_TOO_LARGE]: request body too large.", + PAYLOAD_HINT, + ); + if (!err) { + if (opts.write && status !== undefined && status >= 500) + fail(`Error ${status}: the server failed.`, WRITE_OUTCOME_UNKNOWN_HINT); + return unwrap(res); + } + const lines = [ + `Error ${status ?? ""} [${err.code ?? "?"}]: ${err.message ?? "unknown failure"}`, + ]; + if (Array.isArray(err.details)) { + for (const d of err.details as { path?: unknown; message?: string }[]) { + const path = Array.isArray(d.path) ? d.path.join(".") : (d.path ?? ""); + lines.push(` · ${path}: ${d.message ?? ""}`.trimEnd()); + } + } + const hint = crmErrorHint(err, retryAfterSeconds(res.response)); + if (hint) fail(lines.join("\n"), hint); + if (opts.write && status !== undefined && status >= 500) + fail(lines.join("\n"), WRITE_OUTCOME_UNKNOWN_HINT); + return unwrap(res); +} + +/** + * The contract types the audience filter only as `{ version: 2, ... }` (the + * server validates the rest and answers 422 with `details[].path`). Checking + * the version here turns a v1 filter or a stray array into a clear error + * before anything is sent. + */ +export function parseFilter( + value: unknown, + flag: string, +): AdminCrmAudienceFilter { + if (!value || typeof value !== "object" || Array.isArray(value)) + fail(`${flag} must be a JSON object (audience filter v2).`); + if ((value as { version?: unknown }).version !== 2) + fail( + `${flag} must be an audience filter v2: \`{ "version": 2, "scope": …, "include": […], "except": […] }\`.`, + "See the `ft admin crm` section of the README for an example.", + ); + return value as AdminCrmAudienceFilter; +} + +/** `--sender freeticket|` → the contract's `sender`. */ +export function parseSender(value: string): AdminCrmSender { + const v = value.trim(); + if (!v) fail("Empty --sender. Use `freeticket` or a workspace id."); + return v.toLowerCase() === "freeticket" + ? { kind: "freeticket" } + : { kind: "organization", workspaceId: v }; +} + +function senderLabel(sender: AdminCrmSender | undefined): string { + if (!sender) return "(not set)"; + return sender.kind === "freeticket" + ? "FreeTicket" + : `organization ${sender.workspaceId}`; +} + +/** + * Human summary of a preview, on stderr so `--json` stays clean on stdout. + * Exported for tests. + */ +export function previewSummary( + p: AdminCrmAudiencePreview, + channel?: string, +): string[] { + const c = p.counts; + const lines = [ + `${chalk.bold("Audience")}: ${c.total} people`, + ` matched ${c.matched} · excluded by "except" ${c.excludedByExcept} · by frequency ${c.excludedByFrequency} · unsubscribed ${c.suppressed}`, + ` with email: ${c.total} · reachable by WhatsApp: ${c.reachableWhatsapp} · without phone: ${c.withoutPhone}`, + ]; + if (p.whatsappEstimate && channel !== "EMAIL") { + const e = p.whatsappEstimate; + lines.push( + ` WhatsApp: ~${e.days} day(s) to reach everyone (cap ${e.dailyCap}/day, ${e.remainingToday} left today)`, + ); + } + if (p.senderChoice?.forced) { + lines.push( + " sender: must be FreeTicket (the scope spans several organizations)", + ); + } else if (p.senderChoice && "organization" in p.senderChoice) { + const o = p.senderChoice.organization; + lines.push(` sender: can sign as FreeTicket or ${o.name} (${o.id})`); + } + return lines; +} + +/** Shows a campaign before a write on it, and returns it. */ +async function showCampaign(id: string): Promise { + const c = crmUnwrap(await getCrmCampaignsId({ path: { id } })).data; + console.error( + [ + `${chalk.bold(c.subject)} (${c.id})`, + ` ${c.channel} · ${c.status} · sender ${c.senderName}`, + ` recipients ${c.recipientCount ?? "?"} · sent ${c.sentCount ?? 0} · failed ${c.failedCount ?? 0}`, + c.scheduledAt ? ` scheduled at ${c.scheduledAt}` : null, + c.nextBatchAt ? ` next batch at ${c.nextBatchAt}` : null, + ] + .filter(Boolean) + .join("\n"), + ); + return c; +} + +type TableOpts = { + json?: boolean; + csv?: boolean; + columns?: string; + full?: boolean; +}; + +function printRows(rows: unknown[], opts: TableOpts, fallback: string[]): void { + const columns = resolveColumns(opts, fallback); + if (opts.csv) { + process.stdout.write(`${toCsv(rows, columns)}\n`); + return; + } + print(rows, { + json: opts.json, + columns, + columnsExplicit: Boolean(opts.columns), + }); +} + +function tableOptions(cmd: Command): Command { + return cmd + .option("--columns ", "comma-separated columns to display") + .option("--full", "show every field instead of the curated columns") + .option("--csv", "CSV output") + .option("--json", "raw JSON output"); +} + +export function registerAdminCrm(admin: Command): void { + const crm = admin + .command("crm") + .description( + "Master CRM: email / WhatsApp campaigns to buyers (writes send real messages)", + ); + + // ---------------------------------------------------------------- campaigns + const campaigns = crm.command("campaigns").description("CRM campaigns"); + + tableOptions( + campaigns + .command("list") + .description("List campaigns, newest first") + .option("--channel ", "EMAIL | WHATSAPP") + .option( + "--status ", + "SENT | FAILED | DENIED | PROCESSING | APPROVED | SCHEDULED | CANCELLED", + ) + .option("--limit ", "max results (server default 50)"), + ).action(async (opts) => { + configureAdminClient(); + const query: Record = {}; + if (opts.channel) query.channel = String(opts.channel).toUpperCase(); + if (opts.status) query.status = String(opts.status).toUpperCase(); + if (opts.limit !== undefined) query.limit = Number(opts.limit); + const body = crmUnwrap(await getCrmCampaigns({ query: query as never })); + printRows(body.data, opts, CAMPAIGN_COLUMNS); + }); + + campaigns + .command("get ") + .description("Campaign detail: deliveries, errors, conversions") + .option("--json", "raw JSON output") + .action(async (id, opts) => { + configureAdminClient(); + const body = crmUnwrap(await getCrmCampaignsId({ path: { id } })); + print(body.data, { json: opts.json }); + }); + + campaigns + .command("cancel ") + .description("Cancel a SCHEDULED campaign so it never goes out") + .option("--yes", "skip confirmation") + .option("--json", "raw JSON output") + .action(async (id, opts) => { + configureAdminClient(); + await showCampaign(id); + await confirmCrmWrite( + `Cancel campaign ${id}`, + "It will not be sent", + opts.yes, + ); + const body = await crmWriteOnce(() => + postCrmCampaignsIdCancel({ path: { id } }), + ); + const data = writeData(body); + if (data !== undefined) print(data, { json: opts.json }); + }); + + // ------------------------------------------------------------------ batches + const batches = crm + .command("batches") + .description("WhatsApp batch sending of a campaign"); + + batches + .command("next ") + .description("Send the next batch of pending recipients now") + .option("--ignore-window", "send even outside the 9:00-20:00 Bogotá window") + .option("--yes", "skip confirmation") + .option("--json", "raw JSON output") + .action(async (id, opts) => { + configureAdminClient(); + await showCampaign(id); + await confirmCrmWrite( + `Send the next batch of campaign ${id}${opts.ignoreWindow ? " (ignoring the send window)" : ""}`, + "", + opts.yes, + ); + const body = await crmWriteOnce(() => + postCrmCampaignsIdBatchesNext({ + path: { id }, + ...(opts.ignoreWindow ? { body: { ignoreSendWindow: true } } : {}), + }), + ); + const data = writeData(body); + if (data !== undefined) print(data, { json: opts.json }); + }); + + batches + .command("stop ") + .description( + "Stop batch sending: pending recipients are skipped (irreversible)", + ) + .option("--yes", "skip confirmation") + .option("--json", "raw JSON output") + .action(async (id, opts) => { + configureAdminClient(); + await showCampaign(id); + await confirmCrmWrite( + `Stop campaign ${id}`, + "Pending recipients will never be sent (irreversible)", + opts.yes, + ); + const body = await crmWriteOnce(() => + postCrmCampaignsIdBatchesStop({ path: { id } }), + ); + const data = writeData(body); + if (data !== undefined) print(data, { json: opts.json }); + }); + + // ------------------------------------------------------------------- events + const events = crm + .command("events") + .description("Find shows and dates for a filter"); + + tableOptions( + events + .command("search ") + .description("Search shows by name") + .option( + "--purpose

", + "scope | promote | except (promote = published shows only)", + "scope", + ) + .option( + "--sender ", + "with --purpose promote: only shows of this organization", + ), + ).action(async (query, opts) => { + configureAdminClient(); + const purpose = String(opts.purpose); + if (!["scope", "promote", "except"].includes(purpose)) + fail(`Invalid --purpose: ${purpose}. Use scope, promote or except.`); + const body = crmUnwrap( + await getCrmEvents({ + query: { + query, + purpose: purpose as "scope" | "promote" | "except", + ...(opts.sender ? { senderWorkspaceId: opts.sender } : {}), + }, + }), + ); + printRows(body.data, opts, EVENT_COLUMNS); + }); + + tableOptions( + events + .command("dates ") + .description("Dates (functions) of one or more shows, with buyer counts"), + ).action(async (eventIds: string[], opts) => { + configureAdminClient(); + const ids = eventIds + .flatMap((v) => v.split(",")) + .map((v) => v.trim()) + .filter(Boolean); + const body = crmUnwrap( + await getCrmEventDates({ query: { eventIds: ids.join(",") } }), + ); + printRows(body.data, opts, DATE_COLUMNS); + }); + + // ------------------------------------------------------------ options/quota + crm + .command("options") + .description("Cities, genres/formats, plans and WhatsApp templates") + .option("--json", "raw JSON output") + .action(async (opts) => { + configureAdminClient(); + print(crmUnwrap(await getCrmOptions({})).data, { json: opts.json }); + }); + + crm + .command("quota") + .description("WhatsApp daily quota: used, remaining, committed batches") + .option("--json", "raw JSON output") + .action(async (opts) => { + configureAdminClient(); + print(crmUnwrap(await getCrmQuota({})).data, { json: opts.json }); + }); + + // ------------------------------------------------------------------ preview + crm + .command("preview") + .description("Count an audience without creating anything") + .requiredOption( + "--filter ", + "audience filter v2 (inline JSON or @filter.json)", + ) + .option("--sender ", "freeticket | ") + .option("--json", "raw JSON output") + .action(async (opts) => { + configureAdminClient(); + const filter = parseFilter(parseData(opts.filter), "--filter"); + const body = crmUnwrap( + await postCrmAudiencePreview({ + body: { + filter, + ...(opts.sender ? { sender: parseSender(opts.sender) } : {}), + }, + }), + ); + if (opts.json) { + print(body.data, { json: true }); + return; + } + console.log(previewSummary(body.data).join("\n")); + if (body.data.sample.length > 0) { + console.log(chalk.dim("\nSample (masked):")); + print(body.data.sample, {}); + } + }); + + // ------------------------------------------------------------------- launch + crm + .command("launch") + .description( + "Create an approved campaign (timing.mode now sends right away). Previews the audience first", + ) + .requiredOption( + "--data ", + "campaign JSON: channel, sender, subject, body, filter, timing (inline or @campaign.json)", + ) + .option( + "--ignore-window", + "WhatsApp with timing.mode now: send even outside the 9:00-20:00 Bogotá window", + ) + .option( + "--expect-count ", + "people you expect to reach (the N of `Launch to N people`); the launch stops if the preview differs. Required with --yes", + ) + .option("--yes", "skip confirmation (requires --expect-count)") + .option("--json", "raw JSON output") + .action(async (opts) => { + configureAdminClient(); + const input = parseData(opts.data) as AdminCrmLaunchInput; + // The flag wins over the file, so the confirmation below tells the truth. + if (opts.ignoreWindow && input && typeof input === "object") + input.ignoreSendWindow = true; + if (!input || typeof input !== "object" || !input.filter) + fail( + "--data needs a `filter` (and channel, sender, subject, body, timing).", + "See the `ft admin crm` section of the README for a campaign.json example.", + ); + parseFilter(input.filter, "--data.filter"); + const expected = parseExpectCount(opts.expectCount); + // --yes skips the human; then the caller must state the reach up front, + // so a script or an agent cannot launch to an audience it never sized. + if (opts.yes && expected === undefined) + fail( + "Refusing: launch --yes needs --expect-count (the number of people you expect to reach). Nothing was sent.", + "Size the audience first with `ft admin crm preview --filter …` (reachable by WhatsApp for WHATSAPP, the total for EMAIL), then pass that number.", + ); + // Same filter and sender the launch will use: what you confirm is what + // the backend resolves. + const preview = crmUnwrap( + await postCrmAudiencePreview({ + body: { + filter: input.filter, + ...(input.sender ? { sender: input.sender } : {}), + }, + }), + ).data; + console.error( + [ + `${chalk.bold(input.subject ?? "(no subject)")} · ${input.channel ?? "?"} · sender ${senderLabel(input.sender)} · timing ${input.timing?.mode ?? "?"}`, + ...previewSummary(preview, input.channel), + ].join("\n"), + ); + if (preview.counts.total === 0) + fail("The audience is empty: nothing to launch."); + const reach = + input.channel === "WHATSAPP" + ? preview.counts.reachableWhatsapp + : preview.counts.total; + const when = + input.timing?.mode === "now" + ? "right now" + : input.timing?.mode === "batches" + ? "in batches" + : "on schedule"; + if (expected !== undefined && expected !== reach) + fail( + `Refusing: the preview reaches ${reach} people, --expect-count says ${expected}. Nothing was sent.`, + "The audience changed or the filter is not the one you sized. Check it with `ft admin crm preview` and pass the number you mean to reach.", + ); + await confirmCrmWrite( + `Launch to ${reach} people by ${input.channel ?? "?"}, sending ${when}${input.ignoreSendWindow ? " (ignoring the send window)" : ""}`, + "", + opts.yes, + ); + const body = await crmWriteOnce(() => postCrmCampaigns({ body: input })); + const data = writeData(body); + if (data === undefined) return; + print(data, { json: opts.json }); + const id = (data as { id?: unknown }).id; + if (typeof id !== "string" || !id) { + console.error( + chalk.yellow(`Warning: ${UNEXPECTED_WRITE_RESPONSE_HINT}`), + ); + return; + } + if (!opts.json) + console.error( + chalk.dim(`\nFollow it with \`ft admin crm campaigns get ${id}\``), + ); + }); +} diff --git a/src/commands/admin.ts b/src/commands/admin.ts index fd99a4e..b417be7 100644 --- a/src/commands/admin.ts +++ b/src/commands/admin.ts @@ -32,6 +32,7 @@ import { configureAdminClient, unwrap } from "../lib/api"; import { CONFIG_PATH, loadConfig, saveConfig } from "../lib/config"; import { confirmOrExit, parseData, parseLimit } from "../lib/input"; import { print, printNextCursor, resolveColumns, toCsv } from "../lib/output"; +import { registerAdminCrm } from "./admin-crm"; type SdkFn = ( opts: any, @@ -298,6 +299,8 @@ export function registerAdmin(program: Command): void { ]; for (const spec of resources) registerAdminResource(admin, spec); + + registerAdminCrm(admin); } function registerAdminResource(parent: Command, spec: AdminResource): void { diff --git a/src/destructive-confirm.test.ts b/src/destructive-confirm.test.ts index e6a6e61..5097ce5 100644 --- a/src/destructive-confirm.test.ts +++ b/src/destructive-confirm.test.ts @@ -1,3 +1,4 @@ +import { readFileSync } from "node:fs"; import { afterEach, beforeEach, @@ -13,12 +14,68 @@ import { * without --yes must exit 1 BEFORE the SDK call. The generated SDK functions * are mocked so nothing could reach the network even if the gate regressed. */ +/** What the fake TTY answers to the [y/N] prompt, and every prompt shown. */ +const tty = vi.hoisted(() => ({ + answer: "n", + questions: [] as string[], + onAsk: undefined as (() => void) | undefined, +})); + +vi.mock("node:readline", async (importOriginal) => { + const real = await importOriginal(); + const createInterface = () => ({ + question: (q: string, cb: (a: string) => void) => { + tty.questions.push(q); + tty.onAsk?.(); + cb(tty.answer); + }, + close: () => {}, + }); + return { ...real, default: { ...real, createInterface }, createInterface }; +}); + const sdk = vi.hoisted(() => ({ postEventsIdCancel: vi.fn(), deleteStaffId: vi.fn(), deleteWorkspacesId: vi.fn(), + // CRM writes, plus the reads they show before confirming. + postCrmCampaigns: vi.fn(), + postCrmCampaignsIdCancel: vi.fn(), + postCrmCampaignsIdBatchesNext: vi.fn(), + postCrmCampaignsIdBatchesStop: vi.fn(), + postCrmAudiencePreview: vi.fn(), + getCrmCampaignsId: vi.fn(), })); +const PREVIEW = { + counts: { + matched: 12, + excludedByExcept: 1, + excludedByFrequency: 0, + suppressed: 1, + total: 10, + reachableWhatsapp: 7, + withoutPhone: 3, + }, + sample: [], + involvedWorkspaceIds: ["ws_1"], + senderChoice: { forced: true }, + whatsappEstimate: { days: 1, dailyCap: 150, remainingToday: 150 }, +}; + +const CAMPAIGN = { + id: "cmp_1", + subject: "Hello", + channel: "WHATSAPP", + status: "SCHEDULED", + senderName: "FreeTicket", + recipientCount: 10, + sentCount: 0, + failedCount: 0, + scheduledAt: null, + nextBatchAt: null, +}; + vi.mock("./client/sdk.gen", async (importOriginal) => ({ ...(await importOriginal()), postEventsIdCancel: sdk.postEventsIdCancel, @@ -28,6 +85,12 @@ vi.mock("./client/sdk.gen", async (importOriginal) => ({ vi.mock("./admin-client/sdk.gen", async (importOriginal) => ({ ...(await importOriginal()), deleteWorkspacesId: sdk.deleteWorkspacesId, + postCrmCampaigns: sdk.postCrmCampaigns, + postCrmCampaignsIdCancel: sdk.postCrmCampaignsIdCancel, + postCrmCampaignsIdBatchesNext: sdk.postCrmCampaignsIdBatchesNext, + postCrmCampaignsIdBatchesStop: sdk.postCrmCampaignsIdBatchesStop, + postCrmAudiencePreview: sdk.postCrmAudiencePreview, + getCrmCampaignsId: sdk.getCrmCampaignsId, })); const { program } = await import("./program"); @@ -71,3 +134,577 @@ describe("destructive commands refuse without a TTY and without --yes", () => { expect(fn).not.toHaveBeenCalled(); }); }); + +describe("ft admin crm writes refuse without a TTY and without --yes", () => { + const tty = process.stdin.isTTY; + const env = { ...process.env }; + let exit: MockInstance; + let stderr: MockInstance; + + beforeEach(() => { + Object.defineProperty(process.stdin, "isTTY", { + value: false, + configurable: true, + }); + // The CRM shows what it is about to touch before asking, so it needs a + // credential to get that far. The reads are mocked; nothing leaves. + process.env.FT_ADMIN_TOKEN = "ftpat_test"; + // Being in CI is not consent: only --yes is. + process.env.CI = "true"; + sdk.postCrmAudiencePreview.mockResolvedValue({ + data: { data: PREVIEW }, + response: new Response(), + }); + sdk.getCrmCampaignsId.mockResolvedValue({ + data: { data: CAMPAIGN }, + response: new Response(), + }); + stderr = vi.spyOn(console, "error").mockImplementation(() => {}); + exit = vi.spyOn(process, "exit").mockImplementation((() => { + throw new Error("exited"); + }) as never); + }); + + afterEach(() => { + Object.defineProperty(process.stdin, "isTTY", { + value: tty, + configurable: true, + }); + process.env = { ...env }; + vi.restoreAllMocks(); + for (const fn of Object.values(sdk)) fn.mockReset(); + }); + + const campaign = JSON.stringify({ + channel: "WHATSAPP", + sender: { kind: "freeticket" }, + templateName: "promo", + subject: "Hello", + body: "Hi", + filter: { version: 2, include: [], except: [] }, + timing: { mode: "now" }, + }); + + it.each([ + [ + ["launch", "--data", campaign], + sdk.postCrmCampaigns, + sdk.postCrmAudiencePreview, + ], + [ + ["campaigns", "cancel", "cmp_1"], + sdk.postCrmCampaignsIdCancel, + sdk.getCrmCampaignsId, + ], + [ + ["batches", "next", "cmp_1"], + sdk.postCrmCampaignsIdBatchesNext, + sdk.getCrmCampaignsId, + ], + [ + ["batches", "stop", "cmp_1"], + sdk.postCrmCampaignsIdBatchesStop, + sdk.getCrmCampaignsId, + ], + ])("ft admin crm %j exits 1 and never calls the write", async (args, write, read) => { + await expect( + program.parseAsync(["node", "ft", "admin", "crm", ...(args as string[])]), + ).rejects.toThrow("exited"); + expect(exit).toHaveBeenCalledWith(1); + // It got as far as showing the target (preview / campaign)... + expect(read).toHaveBeenCalledTimes(1); + // ...and the exit is the confirmation gate, not anything earlier. + const messages = stderr.mock.calls.map((c) => String(c[0])); + expect(messages.some((m) => /^Refusing: .*no TTY to confirm/.test(m))).toBe( + true, + ); + expect(write).not.toHaveBeenCalled(); + }); +}); + +// --------------------------------------------------------------------------- +// The four CRM writes send real messages to real customers. Beyond the no-TTY +// gate above: an interactive "no" stops them, an interactive "yes" sends once, +// `launch` shows the audience size before asking, and no failure is retried. + +const CRM_WRITES = [ + { + name: "launch", + op: "postCrmCampaigns", + args: [ + "launch", + "--data", + JSON.stringify({ + channel: "WHATSAPP", + sender: { kind: "freeticket" }, + templateName: "promo", + subject: "Hello", + body: "Hi", + filter: { version: 2, include: [], except: [] }, + timing: { mode: "now" }, + }), + // WhatsApp reach of PREVIEW. Required with --yes, checked without it. + "--expect-count", + "7", + ], + write: sdk.postCrmCampaigns, + }, + { + name: "campaigns cancel", + op: "postCrmCampaignsIdCancel", + args: ["campaigns", "cancel", "cmp_1"], + write: sdk.postCrmCampaignsIdCancel, + }, + { + name: "batches next", + op: "postCrmCampaignsIdBatchesNext", + args: ["batches", "next", "cmp_1"], + write: sdk.postCrmCampaignsIdBatchesNext, + }, + { + name: "batches stop", + op: "postCrmCampaignsIdBatchesStop", + args: ["batches", "stop", "cmp_1"], + write: sdk.postCrmCampaignsIdBatchesStop, + }, +] as const; + +describe("ft admin crm writes: confirmation, preview and no retries", () => { + const isTTY = process.stdin.isTTY; + const env = { ...process.env }; + let exit: MockInstance; + let stderr: string[]; + + beforeEach(() => { + Object.defineProperty(process.stdin, "isTTY", { + value: true, + configurable: true, + }); + process.env.FT_ADMIN_TOKEN = "ftpat_test"; + tty.answer = "n"; + tty.questions = []; + tty.onAsk = undefined; + stderr = []; + sdk.postCrmAudiencePreview.mockResolvedValue({ + data: { data: PREVIEW }, + response: new Response(), + }); + sdk.getCrmCampaignsId.mockResolvedValue({ + data: { data: CAMPAIGN }, + response: new Response(), + }); + vi.spyOn(console, "error").mockImplementation((...a) => { + stderr.push(a.join(" ")); + }); + vi.spyOn(console, "log").mockImplementation(() => {}); + vi.spyOn(process.stdout, "write").mockImplementation(() => true); + exit = vi.spyOn(process, "exit").mockImplementation((() => { + throw new Error("exited"); + }) as never); + }); + + afterEach(() => { + Object.defineProperty(process.stdin, "isTTY", { + value: isTTY, + configurable: true, + }); + process.env = { ...env }; + vi.restoreAllMocks(); + for (const fn of Object.values(sdk)) fn.mockReset(); + }); + + const run = (args: readonly string[], ...extra: string[]) => + program.parseAsync(["node", "ft", "admin", "crm", ...args, ...extra]); + + it.each( + CRM_WRITES.flatMap((w) => ["", "n"].map((answer) => ({ ...w, answer }))), + )("$name asks on a TTY and the answer $answer never sends", async ({ + args, + write, + answer, + }) => { + tty.answer = answer; + await expect(run(args)).rejects.toThrow("exited"); + expect(tty.questions).toHaveLength(1); + expect(tty.questions[0]).toMatch(/\[y\/N\] $/); + expect(exit).toHaveBeenCalledWith(1); + expect(stderr).toContain("Aborted."); + expect(write).not.toHaveBeenCalled(); + }); + + it.each( + CRM_WRITES, + )("$name sends exactly once after an interactive yes", async ({ + args, + write, + }) => { + tty.answer = "y"; + write.mockResolvedValue({ + data: { data: { id: "cmp_1", status: "APPROVED" } }, + response: new Response(), + }); + await run(args, "--json"); + expect(tty.questions).toHaveLength(1); + expect(write).toHaveBeenCalledTimes(1); + }); + + it("launch prints the audience size before asking, and asks with the reach", async () => { + const order: string[] = []; + sdk.postCrmAudiencePreview.mockImplementation(async () => { + order.push("preview"); + return { data: { data: PREVIEW }, response: new Response() }; + }); + vi.spyOn(console, "error").mockImplementation((...a) => { + order.push(`stderr:${a.join(" ")}`); + }); + tty.onAsk = () => order.push("ask"); + await expect(run(CRM_WRITES[0].args)).rejects.toThrow("exited"); + const askedAt = order.indexOf("ask"); + const summary = order.findIndex( + (l) => l.includes("Audience") && l.includes("10 people"), + ); + expect(order[0]).toBe("preview"); + expect(summary).toBeGreaterThan(0); + expect(summary).toBeLessThan(askedAt); + // WhatsApp: the question names who can actually be reached (7 of 10). + expect(tty.questions[0]).toContain("Launch to 7 people by WHATSAPP"); + expect(sdk.postCrmCampaigns).not.toHaveBeenCalled(); + }); + + it("launch with --yes still shows the preview (only the question is skipped)", async () => { + sdk.postCrmCampaigns.mockResolvedValue({ + data: { data: { id: "cmp_9", status: "APPROVED" } }, + response: new Response(), + }); + await run(CRM_WRITES[0].args, "--yes", "--json"); + expect(tty.questions).toHaveLength(0); + expect(sdk.postCrmAudiencePreview).toHaveBeenCalledTimes(1); + expect(stderr.join("\n")).toContain("10 people"); + expect(sdk.postCrmCampaigns).toHaveBeenCalledTimes(1); + }); + + const failures = [ + [ + "500 without an envelope", + () => ({ + data: undefined, + error: "Internal Server Error", + response: new Response(null, { status: 500 }), + }), + /never retries/, + ], + [ + "503 with an envelope", + () => ({ + data: undefined, + error: { + error: { + code: "SERVICE_UNAVAILABLE", + message: "down", + retryable: true, + }, + }, + response: new Response(null, { status: 503 }), + }), + /never retries/, + ], + [ + "429 RATE_LIMITED", + () => ({ + data: undefined, + error: { + error: { + code: "RATE_LIMITED", + message: "slow down", + retryable: true, + }, + }, + response: new Response(null, { + status: 429, + headers: { "Retry-After": "30" }, + }), + }), + /never retries a write/, + ], + ] as const; + + for (const { name, args, write } of CRM_WRITES) { + it.each( + failures, + )(`${name} on %s is sent once and not retried`, async (_label, response, hint) => { + write.mockResolvedValue(response()); + await expect(run(args, "--yes")).rejects.toThrow("exited"); + expect(exit).toHaveBeenCalledWith(1); + expect(write).toHaveBeenCalledTimes(1); + expect(stderr.join("\n")).toMatch(hint); + expect(stderr.join("\n")).not.toMatch(/retry with backoff/i); + }); + + it(`${name} on a dropped connection is sent once and reports the outcome as unknown`, async () => { + write.mockRejectedValue(new TypeError("fetch failed")); + await expect(run(args, "--yes")).rejects.toThrow("exited"); + expect(write).toHaveBeenCalledTimes(1); + const err = stderr.join("\n"); + expect(err).toContain("fetch failed"); + expect(err).toContain("may or may not have gone through"); + }); + } +}); + +// --------------------------------------------------------------------------- +// No CRM write may slip past the gate: the contract's own markers and the +// source of the command are both swept, so a new write (or a refactor that +// calls the SDK directly) fails here instead of shipping unconfirmed. + +describe("every CRM write the admin contract flags is covered by the gate tests", () => { + type Op = { + operationId?: string; + "x-ft-destructive"?: unknown; + "x-ft-mcp"?: { expose?: boolean }; + }; + const spec = JSON.parse( + readFileSync(new URL("../admin-openapi.json", import.meta.url), "utf8"), + ) as { paths: Record> }; + const flagged = Object.values(spec.paths) + .flatMap((ops) => Object.values(ops)) + .filter( + (op) => + op && + typeof op === "object" && + (op["x-ft-destructive"] !== undefined || + op["x-ft-mcp"]?.expose === false), + ) + .map((op) => op.operationId); + + it("finds the flagged operations (the sweep is not vacuous)", () => { + expect(flagged.length).toBeGreaterThanOrEqual(4); + expect(flagged.every((id) => typeof id === "string")).toBe(true); + }); + + it.each(flagged)("%s is in CRM_WRITES", (id) => { + expect(CRM_WRITES.map((w) => w.op)).toContain(id); + }); + + it.each(CRM_WRITES)("CRM_WRITES $name mocks the SDK function $op", ({ + op, + write, + }) => { + expect(write).toBe(sdk[op]); + }); +}); + +describe("admin-crm.ts calls every CRM write SDK function only through crmWriteOnce", () => { + const source = readFileSync( + new URL("./commands/admin-crm.ts", import.meta.url), + "utf8", + ); + // Everything after the last import statement: any mention there is a use. + const imports = [...source.matchAll(/^import [^;]*;$/gm)]; + const last = imports.at(-1); + const body = source.slice((last?.index ?? 0) + (last?.[0].length ?? 0)); + const uses = [...body.matchAll(/\bpostCrm\w+/g)].filter( + (m) => m[0] !== "postCrmAudiencePreview", + ); + + it("uses each of the four writes", () => { + expect(new Set(uses.map((m) => m[0]))).toEqual( + new Set(CRM_WRITES.map((w) => w.op)), + ); + }); + + it.each( + uses.map((m) => [m[0], m.index ?? 0] as const), + )("%s (offset %i) is a call wrapped in crmWriteOnce(() =>", (name, at) => { + const before = body.slice(0, at); + const after = body.slice(at + name.length); + expect(before).toMatch(/crmWriteOnce\(\(\)\s*=>\s*$/); + expect(after).toMatch(/^\(/); + }); +}); + +/** TTY + credential + mocked reads, shared by the CRM blocks below. */ +function crmHarness() { + const state = { + stderr: [] as string[], + stdout: "", + exit: undefined as unknown as MockInstance, + }; + const isTTY = process.stdin.isTTY; + const env = { ...process.env }; + beforeEach(() => { + Object.defineProperty(process.stdin, "isTTY", { + value: true, + configurable: true, + }); + process.env.FT_ADMIN_TOKEN = "ftpat_test"; + tty.answer = "n"; + tty.questions = []; + tty.onAsk = undefined; + state.stderr = []; + state.stdout = ""; + sdk.postCrmAudiencePreview.mockResolvedValue({ + data: { data: PREVIEW }, + response: new Response(), + }); + sdk.getCrmCampaignsId.mockResolvedValue({ + data: { data: CAMPAIGN }, + response: new Response(), + }); + vi.spyOn(console, "error").mockImplementation((...a) => { + state.stderr.push(a.join(" ")); + }); + vi.spyOn(console, "log").mockImplementation((...a) => { + state.stdout += `${a.join(" ")}\n`; + }); + vi.spyOn(process.stdout, "write").mockImplementation((chunk) => { + state.stdout += String(chunk); + return true; + }); + state.exit = vi.spyOn(process, "exit").mockImplementation((() => { + throw new Error("exited"); + }) as never); + }); + afterEach(() => { + Object.defineProperty(process.stdin, "isTTY", { + value: isTTY, + configurable: true, + }); + process.env = { ...env }; + vi.restoreAllMocks(); + for (const fn of Object.values(sdk)) fn.mockReset(); + }); + const run = (args: readonly string[], ...extra: string[]) => + program.parseAsync(["node", "ft", "admin", "crm", ...args, ...extra]); + return { state, run }; +} + +describe("ft admin crm launch --expect-count", () => { + const { state, run } = crmHarness(); + // CRM_WRITES[0].args without its `--expect-count 7`. + const launchArgs = CRM_WRITES[0].args.slice(0, 3); + const created = () => + sdk.postCrmCampaigns.mockResolvedValue({ + data: { data: { id: "cmp_9", status: "APPROVED" } }, + response: new Response(), + }); + + it("--yes without --expect-count exits 1 and never writes", async () => { + created(); + await expect(run(launchArgs, "--yes")).rejects.toThrow("exited"); + expect(state.exit).toHaveBeenCalledWith(1); + expect(state.stderr.join("\n")).toMatch(/--expect-count/); + expect(sdk.postCrmCampaigns).not.toHaveBeenCalled(); + }); + + it.each([ + ["with --yes", "10"], // the total, but WhatsApp reaches 7 + ["with --yes", "8"], + ["without --yes", "3"], // optional there, but enforced when given + ])("%s with a count that does not match the preview (%s) exits 1 and never writes", async (yes, count) => { + created(); + tty.answer = "y"; + await expect( + run( + launchArgs, + "--expect-count", + count, + ...(yes === "with --yes" ? ["--yes"] : []), + ), + ).rejects.toThrow("exited"); + expect(state.exit).toHaveBeenCalledWith(1); + expect(sdk.postCrmAudiencePreview).toHaveBeenCalledTimes(1); + expect(state.stderr.join("\n")).toContain( + `the preview reaches 7 people, --expect-count says ${count}`, + ); + expect(tty.questions).toHaveLength(0); + expect(sdk.postCrmCampaigns).not.toHaveBeenCalled(); + }); + + it("--yes with a matching count writes exactly once", async () => { + created(); + await run(launchArgs, "--expect-count", "7", "--yes", "--json"); + expect(state.exit).not.toHaveBeenCalled(); + expect(sdk.postCrmCampaigns).toHaveBeenCalledTimes(1); + }); + + it("without --yes, --expect-count is optional (the prompt is the gate)", async () => { + created(); + tty.answer = "y"; + await run(launchArgs, "--json"); + expect(tty.questions).toHaveLength(1); + expect(sdk.postCrmCampaigns).toHaveBeenCalledTimes(1); + }); + + it.each([ + "-1", + "abc", + "7.5", + "", + ])("rejects --expect-count %j before any request", async (count) => { + await expect( + run(launchArgs, `--expect-count=${count}`, "--yes"), + ).rejects.toThrow("exited"); + expect(state.exit).toHaveBeenCalledWith(1); + expect(state.stderr.join("\n")).toContain("Invalid --expect-count"); + expect(sdk.postCrmAudiencePreview).not.toHaveBeenCalled(); + expect(sdk.postCrmCampaigns).not.toHaveBeenCalled(); + }); +}); + +describe("ft admin crm writes name the API host in the confirmation", () => { + const { run } = crmHarness(); + + it.each(CRM_WRITES)("$name asks against the configured host", async ({ + args, + write, + }) => { + process.env.FT_API_URL = "https://staging.freeticket.test"; + await expect(run(args)).rejects.toThrow("exited"); + expect(tty.questions).toHaveLength(1); + expect(tty.questions[0]).toContain("against staging.freeticket.test"); + expect(write).not.toHaveBeenCalled(); + }); +}); + +describe("ft admin crm writes on a 2xx with an unexpected body", () => { + const { state, run } = crmHarness(); + const odd = [ + ["an empty object", {}], + ["null", null], + ["a string", "Created"], + ["data: null", { data: null }], + ["data without an id", { data: { status: "APPROVED" } }], + ] as const; + + it.each( + odd, + )("launch on %s does not crash, exits 0 and says it probably went through", async (_label, body) => { + sdk.postCrmCampaigns.mockResolvedValue({ + data: body, + response: new Response(null, { status: 201 }), + }); + await expect(run(CRM_WRITES[0].args, "--yes")).resolves.toBeDefined(); + expect(state.exit).not.toHaveBeenCalled(); + expect(sdk.postCrmCampaigns).toHaveBeenCalledTimes(1); + const err = state.stderr.join("\n"); + expect(err).toContain("PROBABLY WENT THROUGH"); + expect(err).toContain("ft admin crm campaigns list"); + expect(err).not.toContain("campaigns get undefined"); + }); + + it.each( + CRM_WRITES.slice(1), + )("$name on a null body does not crash and says it probably went through", async ({ + args, + write, + }) => { + write.mockResolvedValue({ + data: null, + response: new Response(null, { status: 200 }), + }); + await expect(run(args, "--yes")).resolves.toBeDefined(); + expect(state.exit).not.toHaveBeenCalled(); + expect(write).toHaveBeenCalledTimes(1); + expect(state.stderr.join("\n")).toContain("PROBABLY WENT THROUGH"); + }); +}); diff --git a/src/lib/admin-auth.test.ts b/src/lib/admin-auth.test.ts new file mode 100644 index 0000000..89b26b5 --- /dev/null +++ b/src/lib/admin-auth.test.ts @@ -0,0 +1,44 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { client as adminClient } from "../admin-client/client.gen"; +import { configureAdminClient } from "./api"; + +const saved = { ...process.env }; + +describe("configureAdminClient", () => { + beforeEach(() => { + process.env.FT_API_URL = "http://admin.localhost:3000"; + delete process.env.FT_ADMIN_TOKEN; + delete process.env.FT_ADMIN_SESSION; + }); + afterEach(() => { + process.env = { ...saved }; + vi.restoreAllMocks(); + }); + + function headers(): Headers { + return new Headers( + adminClient.getConfig().headers as ConstructorParameters< + typeof Headers + >[0], + ); + } + + it("sends FT_ADMIN_TOKEN as a Bearer service token, without the cookie", () => { + process.env.FT_ADMIN_TOKEN = "ftpat_test"; + process.env.FT_ADMIN_SESSION = "cookie_should_lose"; + configureAdminClient(); + expect(adminClient.getConfig().baseUrl).toBe( + "http://admin.localhost:3000/api/admin", + ); + expect(headers().get("authorization")).toBe("Bearer ftpat_test"); + expect(headers().get("cookie")).toBeNull(); + }); + + it("falls back to the session cookie when no token is set", () => { + process.env.FT_ADMIN_SESSION = "sess_123"; + configureAdminClient(); + expect(headers().get("cookie")).toBe("better-auth.session_token=sess_123"); + // The Bearer from the previous test must not linger on the singleton. + expect(headers().get("authorization")).toBeNull(); + }); +}); diff --git a/src/lib/api.ts b/src/lib/api.ts index 3026154..c74a6d1 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -71,23 +71,37 @@ export function configureClient( } /** - * Configures the superadmin client (/api/admin). Auth is a better-auth session - * cookie of a SUPER_ADMIN — NOT an API key (the admin contract issues no keys). - * MVP: paste the session token via FT_ADMIN_SESSION; converges to a service - * token once the backend ships it (see free-admin#157). - * ponytail: cookie header until the Bearer service-token lands. + * Configures the superadmin client (/api/admin). Two credentials, in order: + * + * 1. `FT_ADMIN_TOKEN` — a platform service token (PAT, minted with + * `ft admin tokens create`), sent as `Authorization: Bearer`. The headless + * path for CI and scripts. With a Bearer present the backend never falls + * back to the cookie, so a bad token is a 401, not a silent session. + * 2. The SUPER_ADMIN better-auth session cookie (`FT_ADMIN_SESSION` or + * `ft admin login`). */ export function configureAdminClient(): void { const cfg = loadConfig(); + const baseUrl = `${cfg.apiUrl.replace(/\/$/, "")}/api/admin`; + const token = process.env.FT_ADMIN_TOKEN?.trim(); + if (token) { + adminClient.setConfig({ + baseUrl, + // setConfig merges headers: null drops a credential left by an earlier call. + headers: { Authorization: `Bearer ${token}`, Cookie: null }, + }); + return; + } if (!cfg.adminSession) { fail( - "No superadmin session. Export FT_ADMIN_SESSION with a SUPER_ADMIN better-auth session token.", - "Log in to the admin panel in your browser and copy the `better-auth.session_token` cookie.", + "No superadmin credential. Export FT_ADMIN_TOKEN with a service token, or FT_ADMIN_SESSION with a SUPER_ADMIN better-auth session token.", + "Mint a token with `ft admin tokens create`, or log in to the admin panel and copy the `better-auth.session_token` cookie (`ft admin login --session `).", ); } adminClient.setConfig({ - baseUrl: `${cfg.apiUrl.replace(/\/$/, "")}/api/admin`, + baseUrl, headers: { + Authorization: null, Cookie: `better-auth.session_token=${cfg.adminSession}`, }, }); @@ -140,7 +154,9 @@ export function unwrap(res: { const lines = [ `Error ${status ?? ""} [${err.code ?? "?"}]: ${err.message ?? "unknown failure"}`.trim(), ]; - for (const d of err.details ?? []) + // `details` is a list of field errors on a 422, but an object elsewhere + // (e.g. `{ existingId }` on a duplicate): only the list is printable. + for (const d of Array.isArray(err.details) ? err.details : []) lines.push(` · ${d.path ?? ""}: ${d.message ?? ""}`.trimEnd()); fail(lines.join("\n"), hintFor(status)); } diff --git a/src/program.test.ts b/src/program.test.ts index 195d221..eb27a01 100644 --- a/src/program.test.ts +++ b/src/program.test.ts @@ -47,6 +47,24 @@ test("contract 1.19 / admin 1.5 commands are wired, destructive ones behind --ye expect(longs("admin workspaces plan")).toContain("--data"); }); +test("admin 1.8 CRM commands are wired under `ft admin crm`", () => { + const tree = new Map(walk(program)); + const expected = [ + "admin crm campaigns list", + "admin crm campaigns get", + "admin crm campaigns cancel", + "admin crm batches next", + "admin crm batches stop", + "admin crm events search", + "admin crm events dates", + "admin crm options", + "admin crm quota", + "admin crm preview", + "admin crm launch", + ]; + expect(expected.filter((p) => !tree.has(p))).toEqual([]); +}); + test("contract 1.24: waitlist list/create are wired, list filters by --city", () => { const tree = new Map(walk(program)); expect(tree.has("waitlist list")).toBe(true);