From 179ea5fd4eaec1749cbcf806175748a093980a90 Mon Sep 17 00:00:00 2001 From: Lucas-FullStackX Date: Thu, 22 Oct 2026 13:02:29 -0500 Subject: [PATCH 1/7] chore(contract): sincronizar admin 1.7.0 (CRM) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Copia local de admin-openapi.json desde free-admin (rama feat/crm-admin-api, todavía sin desplegar): suma las rutas /crm/*. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QLo4Mwi7Ms4TBuo1JffkU5 --- admin-openapi.json | 3704 ++++++++++++++++++++++++++++++++++++-------- 1 file changed, 3096 insertions(+), 608 deletions(-) diff --git a/admin-openapi.json b/admin-openapi.json index 314f732..4fe667e 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.7.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,1119 @@ } } } + }, + "/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. 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" + } + } + } + }, + "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" + } + } + } + }, + "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" + } + } + } + }, + "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" + } + } + } + }, + "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, 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" + } + } + } + }, + "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 +3509,483 @@ "Error": { "type": "object", "properties": { - "error": { - "type": "object", - "properties": { - "code": { + "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" + ] + } + }, + "required": [ + "userId", + "name", + "email", + "role" + ], + "additionalProperties": false + }, + "FeatureFlagScope": { + "type": "string", + "enum": [ + "global", + "plan", + "workspace" + ] + }, + "Page": { + "type": "object", + "properties": { + "nextCursor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "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": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "customDomain": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "customDomainVerifiedAt": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "suspended": { + "type": "boolean" + }, + "suspendedAt": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "deletedAt": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "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-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": { + "anyOf": [ + { "type": "string" }, - "message": { + { + "type": "null" + } + ] + } + }, + "required": [ + "workspaceId", + "planSlug", + "planName", + "previousPlanSlug" + ], + "additionalProperties": false + }, + "AdminWorkspacePlanDetail": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string" + }, + "orgId": { + "anyOf": [ + { "type": "string" }, - "retryable": { - "type": "boolean" + { + "type": "null" + } + ] + }, + "planSlug": { + "anyOf": [ + { + "type": "string" }, - "details": {} - }, - "required": [ - "code", - "message", - "retryable" - ], - "additionalProperties": false + { + "type": "null" + } + ] + }, + "planName": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "status": { + "anyOf": [ + { + "type": "string", + "enum": [ + "TRIALING", + "ACTIVE", + "PAST_DUE", + "CANCELLED" + ] + }, + { + "type": "null" + } + ] + }, + "startedAt": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "expiresAt": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "cancelledAt": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "stripeLinked": { + "type": "boolean" + }, + "paymentOption": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "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": { @@ -2444,28 +4003,102 @@ "VIEWER", "MINCULTURA" ] + }, + "banned": { + "type": "boolean" + }, + "bannedAt": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "homeOrganizationId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "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" - ] + "AdminUserUpdate": { + "type": "object", + "properties": { + "role": { + "type": "string", + "enum": [ + "SUPER_ADMIN", + "ADMIN", + "STAFF", + "VIEWER", + "MINCULTURA" + ] + }, + "banned": { + "type": "boolean" + } + }, + "additionalProperties": false }, - "Page": { + "AdminImpersonate": { "type": "object", "properties": { - "nextCursor": { + "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": { "anyOf": [ { "type": "string" @@ -2474,18 +4107,18 @@ "type": "null" } ] - }, - "hasMore": { - "type": "boolean" } }, "required": [ - "nextCursor", - "hasMore" + "token", + "expiresAt", + "actorUserId", + "targetUserId", + "targetOrgId" ], "additionalProperties": false }, - "AdminWorkspace": { + "AdminPlatformPlan": { "type": "object", "properties": { "id": { @@ -2497,271 +4130,378 @@ "slug": { "type": "string" }, - "type": { - "type": "string", - "enum": [ - "ARTIST", - "VENUE", - "ORGANIZER" - ] - }, - "country": { - "type": "string" + "priceMonthly": { + "type": "number" }, - "isPublished": { - "type": "boolean" + "priceYearly": { + "type": "number" }, - "webTemplate": { + "priceBiannual": { "anyOf": [ { - "type": "string" + "type": "number" }, { "type": "null" } ] }, - "customDomain": { + "maxEvents": { "anyOf": [ { - "type": "string" + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, { "type": "null" } ] }, - "customDomainVerifiedAt": { - "anyOf": [ - { - "type": "string" + "isActive": { + "type": "boolean" + }, + "sortOrder": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "features": { + "type": "object", + "properties": { + "memberships": { + "type": "boolean" }, - { - "type": "null" + "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" } - ] + }, + "required": [ + "memberships", + "content", + "fanDatabase", + "directMessages", + "streaming", + "customLanding", + "dataExport", + "seatMaps", + "customDomain", + "analytics" + ], + "additionalProperties": false }, - "suspended": { - "type": "boolean" + "createdAt": { + "type": "string" + } + }, + "required": [ + "id", + "name", + "slug", + "priceMonthly", + "priceYearly", + "priceBiannual", + "maxEvents", + "isActive", + "sortOrder", + "features", + "createdAt" + ], + "additionalProperties": false + }, + "AdminPlatformPlanCreate": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1 + }, + "slug": { + "type": "string", + "minLength": 1, + "pattern": "^[a-z0-9-]+$" + }, + "priceMonthly": { + "default": 0, + "type": "number", + "minimum": 0 + }, + "priceYearly": { + "default": 0, + "type": "number", + "minimum": 0 }, - "suspendedAt": { + "priceBiannual": { "anyOf": [ { - "type": "string" + "type": "number", + "minimum": 0 }, { "type": "null" } ] }, - "deletedAt": { + "isActive": { + "default": true, + "type": "boolean" + }, + "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": "string" + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, { "type": "null" } ] - }, - "createdAt": { - "type": "string" } }, "required": [ - "id", "name", "slug", - "type", - "country", - "isPublished", - "webTemplate", - "customDomain", - "customDomainVerifiedAt", - "suspended", - "suspendedAt", - "deletedAt", - "createdAt" + "priceMonthly", + "priceYearly", + "isActive" ], "additionalProperties": false }, - "AdminWorkspaceCreate": { + "AdminPlatformPlanUpdate": { "type": "object", "properties": { "name": { "type": "string", "minLength": 1 }, - "slug": { - "type": "string", - "minLength": 1, - "pattern": "^[a-z0-9-]+$" + "priceMonthly": { + "type": "number", + "minimum": 0 }, - "type": { - "default": "ORGANIZER", - "type": "string", - "enum": [ - "ARTIST", - "VENUE", - "ORGANIZER" + "priceYearly": { + "type": "number", + "minimum": 0 + }, + "priceBiannual": { + "anyOf": [ + { + "type": "number", + "minimum": 0 + }, + { + "type": "null" + } ] }, - "country": { - "default": "CO", - "type": "string" + "isActive": { + "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,}$" - } - }, - "required": [ - "name", - "slug", - "type", - "country" - ], - "additionalProperties": false - }, - "AdminWorkspaceUpdate": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1 + "sortOrder": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, - "slug": { - "type": "string", - "minLength": 1, - "pattern": "^[a-z0-9-]+$" + "memberships": { + "type": "boolean" }, - "type": { - "type": "string", - "enum": [ - "ARTIST", - "VENUE", - "ORGANIZER" - ] + "content": { + "type": "boolean" }, - "isPublished": { + "fanDatabase": { "type": "boolean" }, - "webTemplate": { + "directMessages": { + "type": "boolean" + }, + "streaming": { + "type": "boolean" + }, + "customLanding": { + "type": "boolean" + }, + "dataExport": { + "type": "boolean" + }, + "seatMaps": { + "type": "boolean" + }, + "customDomain": { + "type": "boolean" + }, + "analytics": { + "type": "boolean" + }, + "maxEvents": { "anyOf": [ { - "type": "string", - "minLength": 1, - "maxLength": 80 + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, { "type": "null" } ] + } + }, + "additionalProperties": false + }, + "AdminFeatureFlag": { + "type": "object", + "properties": { + "key": { + "type": "string" }, - "customDomain": { + "scope": { + "$ref": "#/components/schemas/FeatureFlagScope" + }, + "scopeId": { "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": "string" }, { "type": "null" } ] }, - "customDomainVerifiedAt": { + "enabled": { + "type": "boolean" + }, + "updatedBy": { "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": "string" }, { "type": "null" } ] - } - }, - "additionalProperties": false - }, - "AdminWorkspacePlanAssign": { - "type": "object", - "properties": { - "planSlug": { - "type": "string", - "enum": [ - "spark", - "star", - "icon", - "legend" - ] + }, + "updatedAt": { + "type": "string" } }, "required": [ - "planSlug" + "key", + "scope", + "scopeId", + "enabled", + "updatedBy", + "updatedAt" ], "additionalProperties": false }, - "AdminWorkspacePlan": { + "AdminFeatureFlagSet": { "type": "object", "properties": { - "workspaceId": { - "type": "string" - }, - "planSlug": { - "type": "string" + "scope": { + "$ref": "#/components/schemas/FeatureFlagScope" }, - "planName": { - "type": "string" + "scopeId": { + "type": "string", + "minLength": 1 }, - "previousPlanSlug": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] + "enabled": { + "type": "boolean" } }, "required": [ - "workspaceId", - "planSlug", - "planName", - "previousPlanSlug" + "scope", + "enabled" ], "additionalProperties": false }, - "AdminWorkspacePlanDetail": { + "AdminAuditEntry": { "type": "object", "properties": { - "workspaceId": { + "id": { + "type": "string" + }, + "actorUserId": { "type": "string" }, - "orgId": { + "action": { + "type": "string" + }, + "targetType": { + "type": "string" + }, + "targetId": { + "type": "string" + }, + "before": { "anyOf": [ - { - "type": "string" - }, + {}, { "type": "null" } ] }, - "planSlug": { + "after": { "anyOf": [ - { - "type": "string" - }, + {}, { "type": "null" } ] }, - "planName": { + "ipAddress": { "anyOf": [ { "type": "string" @@ -2771,23 +4511,46 @@ } ] }, - "status": { + "createdAt": { + "type": "string" + } + }, + "required": [ + "id", + "actorUserId", + "action", + "targetType", + "targetId", + "before", + "after", + "ipAddress", + "createdAt" + ], + "additionalProperties": false + }, + "AdminToken": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "tokenPrefix": { + "type": "string" + }, + "lastUsedAt": { "anyOf": [ { - "type": "string", - "enum": [ - "TRIALING", - "ACTIVE", - "PAST_DUE", - "CANCELLED" - ] + "type": "string" }, { "type": "null" } ] }, - "startedAt": { + "expiresAt": { "anyOf": [ { "type": "string" @@ -2797,7 +4560,7 @@ } ] }, - "expiresAt": { + "revokedAt": { "anyOf": [ { "type": "string" @@ -2807,7 +4570,37 @@ } ] }, - "cancelledAt": { + "createdAt": { + "type": "string" + } + }, + "required": [ + "id", + "name", + "tokenPrefix", + "lastUsedAt", + "expiresAt", + "revokedAt", + "createdAt" + ], + "additionalProperties": false + }, + "AdminTokenCreated": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "token": { + "type": "string" + }, + "createdAt": { + "type": "string" + }, + "expiresAt": { "anyOf": [ { "type": "string" @@ -2817,10 +4610,7 @@ } ] }, - "stripeLinked": { - "type": "boolean" - }, - "paymentOption": { + "lastUsedAt": { "anyOf": [ { "type": "string" @@ -2832,208 +4622,319 @@ } }, "required": [ - "workspaceId", - "orgId", - "planSlug", - "planName", - "status", - "startedAt", + "id", + "name", + "token", + "createdAt", "expiresAt", - "cancelledAt", - "stripeLinked", - "paymentOption" + "lastUsedAt" ], "additionalProperties": false }, - "AdminUserWorkspace": { + "AdminTokenCreate": { "type": "object", "properties": { - "id": { - "type": "string" - }, "name": { - "type": "string" - }, - "slug": { - "type": "string" + "type": "string", + "minLength": 1 }, - "isOwner": { - "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": [ - "id", - "name", - "slug", - "isOwner" + "name" ], "additionalProperties": false }, - "AdminUser": { + "AdminCrmChannel": { + "type": "string", + "enum": [ + "EMAIL", + "WHATSAPP" + ] + }, + "AdminCrmCampaignStatus": { + "type": "string", + "enum": [ + "SENT", + "FAILED", + "DENIED", + "PROCESSING", + "APPROVED", + "SCHEDULED", + "CANCELLED" + ] + }, + "AdminCrmAudienceFilter": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": {}, + "description": "Filtro de audiencia v2 (`{ version: 2, scope, include, except }`). Objeto opaco 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`)." + }, + "AdminCrmSender": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "freeticket" + } + }, + "required": [ + "kind" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "organization" + }, + "workspaceId": { + "type": "string", + "minLength": 1, + "maxLength": 64 + } + }, + "required": [ + "kind", + "workspaceId" + ], + "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." + }, + "AdminCrmCampaign": { "type": "object", "properties": { "id": { "type": "string" }, - "name": { + "subject": { "type": "string" }, - "email": { + "channel": { + "$ref": "#/components/schemas/AdminCrmChannel" + }, + "status": { + "type": "string", + "description": "`BroadcastStatus`" + }, + "senderName": { "type": "string" }, - "role": { + "isPlatform": { + "type": "boolean" + }, + "audienceLabel": { + "type": "string" + }, + "createdAt": { "type": "string", - "enum": [ - "SUPER_ADMIN", - "ADMIN", - "STAFF", - "VIEWER", - "MINCULTURA" + "description": "ISO 8601" + }, + "scheduledAt": { + "anyOf": [ + { + "type": "string", + "description": "ISO 8601" + }, + { + "type": "null" + } ] }, - "banned": { - "type": "boolean" + "nextBatchAt": { + "anyOf": [ + { + "type": "string", + "description": "ISO 8601" + }, + { + "type": "null" + } + ] }, - "bannedAt": { + "recipientCount": { "anyOf": [ { - "type": "string" + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, { "type": "null" } ] }, - "homeOrganizationId": { + "sentCount": { "anyOf": [ { - "type": "string" + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "failedCount": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "deliveredCount": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "readCount": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "deferredCount": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "attributed": { + "type": "object", + "properties": { + "sales": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, - { - "type": "null" + "revenueCop": { + "type": "number" + }, + "feeCop": { + "type": "number" } - ] - }, - "workspaces": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AdminUserWorkspace" - } - }, - "createdAt": { - "type": "string" + }, + "required": [ + "sales", + "revenueCop", + "feeCop" + ], + "additionalProperties": false } }, "required": [ "id", - "name", - "email", - "role", - "banned", - "bannedAt", - "homeOrganizationId", - "workspaces", - "createdAt" + "subject", + "channel", + "status", + "senderName", + "isPlatform", + "audienceLabel", + "createdAt", + "scheduledAt", + "nextBatchAt", + "recipientCount", + "sentCount", + "failedCount", + "deliveredCount", + "readCount", + "deferredCount", + "attributed" ], "additionalProperties": false }, - "AdminUserUpdate": { + "AdminCrmCampaignDetail": { "type": "object", "properties": { - "role": { - "type": "string", - "enum": [ - "SUPER_ADMIN", - "ADMIN", - "STAFF", - "VIEWER", - "MINCULTURA" - ] + "id": { + "type": "string" }, - "banned": { - "type": "boolean" - } - }, - "additionalProperties": false - }, - "AdminImpersonate": { - "type": "object", - "properties": { - "targetUserId": { - "type": "string", - "minLength": 1 + "subject": { + "type": "string" }, - "workspaceId": { + "channel": { + "$ref": "#/components/schemas/AdminCrmChannel" + }, + "status": { "type": "string", - "minLength": 1 - } - }, - "additionalProperties": false - }, - "AdminImpersonation": { - "type": "object", - "properties": { - "token": { - "type": "string" + "description": "`BroadcastStatus`" }, - "expiresAt": { + "senderName": { "type": "string" }, - "actorUserId": { - "type": "string" + "isPlatform": { + "type": "boolean" }, - "targetUserId": { + "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,154 +4946,475 @@ } ] }, - "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" + "sales": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, - "directMessages": { - "type": "boolean" + "revenueCop": { + "type": "number" }, - "streaming": { - "type": "boolean" + "feeCop": { + "type": "number" + } + }, + "required": [ + "sales", + "revenueCop", + "feeCop" + ], + "additionalProperties": false + }, + "body": { + "type": "string" + }, + "imageUrl": { + "anyOf": [ + { + "type": "string" }, - "customLanding": { - "type": "boolean" + { + "type": "null" + } + ] + }, + "templateName": { + "anyOf": [ + { + "type": "string" }, - "dataExport": { - "type": "boolean" + { + "type": "null" + } + ] + }, + "promotedEvent": { + "anyOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "slug": { + "type": "string" + } + }, + "required": [ + "id", + "name", + "slug" + ], + "additionalProperties": false }, - "seatMaps": { - "type": "boolean" + { + "type": "null" + } + ] + }, + "filter": { + "anyOf": [ + { + "$ref": "#/components/schemas/AdminCrmAudienceFilter" }, - "customDomain": { - "type": "boolean" + { + "type": "null" + } + ], + "description": "null = campaña v1 (segmento previo al CRM v2)." + }, + "batchPlan": { + "anyOf": [ + { + "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 }, - "analytics": { - "type": "boolean" + { + "type": "null" } + ] + }, + "deliveriesByStatus": { + "type": "object", + "propertyNames": { + "type": "string" }, - "required": [ - "memberships", - "content", - "fanDatabase", - "directMessages", - "streaming", - "customLanding", - "dataExport", - "seatMaps", - "customDomain", - "analytics" - ], - "additionalProperties": false + "additionalProperties": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } }, - "createdAt": { - "type": "string" + "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": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "utmSource": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "reference", + "total", + "createdAt", + "eventName", + "utmSource" + ], + "additionalProperties": false + } } }, "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", + "body", + "imageUrl", + "templateName", + "promotedEvent", + "filter", + "batchPlan", + "deliveriesByStatus", + "topErrors", + "sentByHour", + "conversions" ], "additionalProperties": false }, - "AdminPlatformPlanCreate": { + "AdminCrmPreviewInput": { "type": "object", "properties": { - "name": { - "type": "string", - "minLength": 1 + "filter": { + "$ref": "#/components/schemas/AdminCrmAudienceFilter" }, - "slug": { - "type": "string", - "minLength": 1, - "pattern": "^[a-z0-9-]+$" + "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 }, - "priceMonthly": { - "default": 0, - "type": "number", - "minimum": 0 + "sample": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "emailMasked": { + "type": "string" + }, + "phoneMasked": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "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." }, - "priceYearly": { - "default": 0, - "type": "number", - "minimum": 0 + "involvedWorkspaceIds": { + "type": "array", + "items": { + "type": "string" + } }, - "priceBiannual": { + "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": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "id", + "name", + "logoUrl" + ], + "additionalProperties": false + } + }, + "required": [ + "forced", + "organization" + ], + "additionalProperties": false } ] }, - "isActive": { - "default": true, - "type": "boolean" - }, - "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" @@ -3201,116 +5423,213 @@ } }, "required": [ - "name", - "slug", - "priceMonthly", - "priceYearly", - "isActive" + "counts", + "sample", + "involvedWorkspaceIds", + "senderChoice", + "whatsappEstimate" ], "additionalProperties": false }, - "AdminPlatformPlanUpdate": { + "AdminCrmQuotaOutlook": { "type": "object", "properties": { - "name": { - "type": "string", - "minLength": 1 + "limit": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, - "priceMonthly": { - "type": "number", - "minimum": 0 + "used": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, - "priceYearly": { - "type": "number", - "minimum": 0 + "remaining": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 }, - "priceBiannual": { + "nextFreeAt": { "anyOf": [ { - "type": "number", - "minimum": 0 + "type": "string", + "description": "ISO 8601" }, { "type": "null" } ] }, - "isActive": { - "type": "boolean" - }, - "sortOrder": { + "platformDailyShare": { "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": { - "anyOf": [ - { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 + "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" - } - ] + "required": [ + "at", + "size", + "messageId" + ], + "additionalProperties": false + } } }, + "required": [ + "limit", + "used", + "remaining", + "nextFreeAt", + "platformDailyShare", + "committed" + ], "additionalProperties": false }, - "AdminFeatureFlag": { + "AdminCrmWizardOptions": { "type": "object", "properties": { - "key": { - "type": "string" - }, - "scope": { - "$ref": "#/components/schemas/FeatureFlagScope" + "cities": { + "type": "array", + "items": { + "type": "string" + } }, - "scopeId": { - "anyOf": [ - { - "type": "string" + "facets": { + "type": "object", + "properties": { + "genre": { + "type": "array", + "items": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "label": { + "type": "string" + } + }, + "required": [ + "code", + "label" + ], + "additionalProperties": false + } }, - { - "type": "null" + "format": { + "type": "array", + "items": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "label": { + "type": "string" + } + }, + "required": [ + "code", + "label" + ], + "additionalProperties": false + } } - ] + }, + "required": [ + "genre", + "format" + ], + "additionalProperties": false + }, + "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": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "urlButtonText": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "name", + "language", + "hasImageHeader", + "body" + ], + "additionalProperties": false + } }, - "updatedBy": { + "whatsappBlockedReason": { "anyOf": [ { "type": "string" @@ -3319,76 +5638,78 @@ "type": "null" } ] - }, - "updatedAt": { - "type": "string" - } - }, - "required": [ - "key", - "scope", - "scopeId", - "enabled", - "updatedBy", - "updatedAt" - ], - "additionalProperties": false - }, - "AdminFeatureFlagSet": { - "type": "object", - "properties": { - "scope": { - "$ref": "#/components/schemas/FeatureFlagScope" - }, - "scopeId": { - "type": "string", - "minLength": 1 - }, - "enabled": { - "type": "boolean" } }, "required": [ - "scope", - "enabled" + "cities", + "facets", + "plans", + "templates", + "whatsappBlockedReason" ], "additionalProperties": false }, - "AdminAuditEntry": { + "AdminCrmEventOption": { "type": "object", "properties": { "id": { "type": "string" }, - "actorUserId": { + "name": { "type": "string" }, - "action": { + "slug": { "type": "string" }, - "targetType": { - "type": "string" + "startsAt": { + "anyOf": [ + { + "type": "string", + "description": "ISO 8601" + }, + { + "type": "null" + } + ] }, - "targetId": { - "type": "string" + "lastAt": { + "anyOf": [ + { + "type": "string", + "description": "ISO 8601" + }, + { + "type": "null" + } + ] }, - "before": { + "nextAt": { "anyOf": [ - {}, + { + "type": "string", + "description": "ISO 8601" + }, { "type": "null" } ] }, - "after": { + "dateCount": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "venueName": { "anyOf": [ - {}, + { + "type": "string" + }, { "type": "null" } ] }, - "ipAddress": { + "city": { "anyOf": [ { "type": "string" @@ -3398,36 +5719,42 @@ } ] }, - "createdAt": { + "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": { + "label": { "anyOf": [ { "type": "string" @@ -3437,7 +5764,10 @@ } ] }, - "expiresAt": { + "status": { + "type": "string" + }, + "venueName": { "anyOf": [ { "type": "string" @@ -3447,7 +5777,7 @@ } ] }, - "revokedAt": { + "city": { "anyOf": [ { "type": "string" @@ -3457,37 +5787,111 @@ } ] }, - "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": { - "type": "object", - "properties": { - "id": { - "type": "string" + "AdminCrmTiming": { + "oneOf": [ + { + "type": "object", + "properties": { + "mode": { + "type": "string", + "const": "now" + } + }, + "required": [ + "mode" + ], + "additionalProperties": false }, - "name": { - "type": "string" + { + "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 }, - "token": { - "type": "string" + { + "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": { + "channel": { + "$ref": "#/components/schemas/AdminCrmChannel" }, - "createdAt": { - "type": "string" + "sender": { + "$ref": "#/components/schemas/AdminCrmSender" }, - "expiresAt": { + "templateName": { + "description": "Plantilla de WhatsApp aprobada (obligatoria por WhatsApp; el correo la rechaza). Ver `GET /crm/options`.", "anyOf": [ { "type": "string" @@ -3497,42 +5901,126 @@ } ] }, - "lastUsedAt": { + "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" + }, + "promotedEventId": { + "description": "Show PUBLICADO que se promociona (si firma una organización, uno suyo).", + "type": "string" + }, + "filter": { + "$ref": "#/components/schemas/AdminCrmAudienceFilter" + }, + "timing": { + "$ref": "#/components/schemas/AdminCrmTiming" + } + }, + "required": [ + "channel", + "sender", + "subject", + "body", + "filter", + "timing" + ], + "additionalProperties": false + }, + "AdminCrmLaunchResult": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "APPROVED", + "SCHEDULED" + ] + }, + "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 } From b166554af55d76ef02a70e048e9c1b10ffb28b30 Mon Sep 17 00:00:00 2001 From: Lucas-FullStackX Date: Thu, 22 Oct 2026 13:06:18 -0500 Subject: [PATCH 2/7] feat(admin): autenticar ft admin con service token por FT_ADMIN_TOKEN MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit configureAdminClient manda Authorization: Bearer cuando FT_ADMIN_TOKEN está definida y cae a la cookie de sesión SUPER_ADMIN si no. El servidor ya acepta el PAT; con Bearer presente no vuelve a la cookie, así que un token malo es 401. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QLo4Mwi7Ms4TBuo1JffkU5 --- .changeset/admin-service-token.md | 5 ++++ README.md | 2 ++ src/lib/admin-auth.test.ts | 44 +++++++++++++++++++++++++++++++ src/lib/api.ts | 30 +++++++++++++++------ 4 files changed, 73 insertions(+), 8 deletions(-) create mode 100644 .changeset/admin-service-token.md create mode 100644 src/lib/admin-auth.test.ts 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 3c9db65..47aebee 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,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/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..db9dc60 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}`, }, }); From 164898ad587cc7e7db31aed84c2269e592b85510 Mon Sep 17 00:00:00 2001 From: Lucas-FullStackX Date: Thu, 22 Oct 2026 13:11:07 -0500 Subject: [PATCH 3/7] feat(admin): comandos ft admin crm para el CRM maestro MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Suma ft admin crm (contrato admin 1.7.0): campaigns list/get/cancel, batches next/stop, events search/dates, options, quota, preview y launch. - launch corre primero el preview con el mismo filtro y remitente, muestra total, alcance por correo y WhatsApp y días estimados, y recién después confirma; cancel y batches muestran la campaña antes de confirmar. Sin TTY y sin --yes, fallan. - Ninguna escritura se reintenta sola. - OUTSIDE_SEND_WINDOW dice cuándo abre la ventana y sugiere --ignore-window; DUPLICATE_CAMPAIGN muestra el existingId; QUOTA_EXHAUSTED lee Retry-After. - unwrap ya no revienta cuando details es un objeto y no una lista. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QLo4Mwi7Ms4TBuo1JffkU5 --- .changeset/admin-crm.md | 5 + README.md | 100 ++++++ src/commands/admin-crm.test.ts | 394 +++++++++++++++++++++++ src/commands/admin-crm.ts | 536 ++++++++++++++++++++++++++++++++ src/commands/admin.ts | 3 + src/destructive-confirm.test.ts | 127 ++++++++ src/lib/api.ts | 4 +- src/program.test.ts | 18 ++ 8 files changed, 1186 insertions(+), 1 deletion(-) create mode 100644 .changeset/admin-crm.md create mode 100644 src/commands/admin-crm.test.ts create mode 100644 src/commands/admin-crm.ts diff --git a/.changeset/admin-crm.md b/.changeset/admin-crm.md new file mode 100644 index 0000000..4e4d6d6 --- /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.7.0): list and inspect campaigns, search shows and dates, read options and the WhatsApp quota, preview an audience, launch a campaign, send or stop WhatsApp batches and cancel a scheduled campaign. Every write previews its target and asks for confirmation (`--yes` in scripts), and none is retried automatically. diff --git a/README.md b/README.md index 47aebee..cadac5b 100644 --- a/README.md +++ b/README.md @@ -123,6 +123,7 @@ ft sales list --status CONFIRMED --json | `ft content-videos list` · `content-posts list\|create` · `content-lives list\|get\|playback-token` | Organization content; `content-posts create --data` publishes a post or article | 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 @@ -142,6 +143,105 @@ 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 [--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. Without a TTY they refuse unless +you pass `--yes`. The CLI never retries a write on its own: if a `launch` +times out, check `campaigns list` before launching again (the backend rejects +the same channel + sender + subject within 10 minutes with +`DUPLICATE_CAMPAIGN` and prints the existing id). + +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`; +`QUOTA_EXHAUSTED` prints when the quota frees up; `INVALID_STATE` means the +campaign no longer allows that action; a 422 lists each `details[].path`. + +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. +- `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: diff --git a/src/commands/admin-crm.test.ts b/src/commands/admin-crm.test.ts new file mode 100644 index 0000000..922f1b1 --- /dev/null +++ b/src/commands/admin-crm.test.ts @@ -0,0 +1,394 @@ +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"); + expect(find(["batches", "next"]).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), "--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 } }), + "--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" }), + "--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"); + }); + + 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"); + }); +}); + +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.ts b/src/commands/admin-crm.ts new file mode 100644 index 0000000..dbd5bdf --- /dev/null +++ b/src/commands/admin-crm.ts @@ -0,0 +1,536 @@ +import chalk from "chalk"; +import type { Command } from "commander"; +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()}`; +} + +/** + * 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 this batch 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 "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."; + default: + return null; + } +} + +/** + * `unwrap` plus the CRM's named errors. Formats the envelope itself because + * `details` is not always a list here (`{ existingId }` on a duplicate). + */ +function crmUnwrap(res: SdkResult): T { + if (res.data !== undefined) return res.data; + const err = (res.error as { error?: CrmError } | undefined)?.error; + if (!err) return unwrap(res); + const status = res.response?.status; + 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); + return unwrap(res); +} + +/** `--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 confirmOrExit( + `Cancel campaign ${id}? It will not be sent`, + opts.yes, + ); + const body = crmUnwrap(await postCrmCampaignsIdCancel({ path: { id } })); + print(body.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 confirmOrExit( + `Send the next batch of campaign ${id}${opts.ignoreWindow ? " (ignoring the send window)" : ""}?`, + opts.yes, + ); + const body = crmUnwrap( + await postCrmCampaignsIdBatchesNext({ + path: { id }, + ...(opts.ignoreWindow ? { body: { ignoreSendWindow: true } } : {}), + }), + ); + print(body.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 confirmOrExit( + `Stop campaign ${id}? Pending recipients will never be sent (irreversible)`, + opts.yes, + ); + const body = crmUnwrap( + await postCrmCampaignsIdBatchesStop({ path: { id } }), + ); + print(body.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 = parseData(opts.filter) as AdminCrmAudienceFilter; + 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("--yes", "skip confirmation") + .option("--json", "raw JSON output") + .action(async (opts) => { + configureAdminClient(); + const input = parseData(opts.data) as AdminCrmLaunchInput; + 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.", + ); + // 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"; + await confirmOrExit( + `Launch to ${reach} people by ${input.channel ?? "?"}, sending ${when}?`, + opts.yes, + ); + const body = crmUnwrap(await postCrmCampaigns({ body: input })); + print(body.data, { json: opts.json }); + if (!opts.json) + console.error( + chalk.dim( + `\nFollow it with \`ft admin crm campaigns get ${body.data.id}\``, + ), + ); + }); +} diff --git a/src/commands/admin.ts b/src/commands/admin.ts index e6012fd..0d3436e 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 } 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..507ea96 100644 --- a/src/destructive-confirm.test.ts +++ b/src/destructive-confirm.test.ts @@ -17,8 +17,44 @@ 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 +64,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 +113,88 @@ 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"; + 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(); + }); +}); diff --git a/src/lib/api.ts b/src/lib/api.ts index db9dc60..c74a6d1 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -154,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 74174ca..d363f3e 100644 --- a/src/program.test.ts +++ b/src/program.test.ts @@ -46,3 +46,21 @@ test("contract 1.19 / admin 1.5 commands are wired, destructive ones behind --ye // `plan ` (assign) must survive next to the new read. expect(longs("admin workspaces plan")).toContain("--data"); }); + +test("admin 1.7 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([]); +}); From 12368bf128f5dd60b26b98b08a247f8c4214becc Mon Sep 17 00:00:00 2001 From: Lucas-FullStackX Date: Thu, 22 Oct 2026 13:17:07 -0500 Subject: [PATCH 4/7] feat(admin): ft admin crm launch --ignore-window y manejo del 413 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resincroniza admin-openapi.json 1.7.0 (free-admin 1b84d09b): POST /crm/campaigns acepta ignoreSendWindow, las escrituras y el preview pueden responder 413 PAYLOAD_TOO_LARGE y AdminCrmAudienceFilter exige version. - launch --ignore-window manda ignoreSendWindow: true; OUTSIDE_SEND_WINDOW en launch muestra cuándo abre la ventana y sugiere el flag, como batches next. - El 413 se explica (tope de 256 KB) con o sin envelope JSON. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QLo4Mwi7Ms4TBuo1JffkU5 --- .changeset/admin-crm.md | 2 +- README.md | 11 ++-- admin-openapi.json | 97 ++++++++++++++++++++++++++++++--- src/commands/admin-crm.test.ts | 98 ++++++++++++++++++++++++++++++++-- src/commands/admin-crm.ts | 23 ++++++-- 5 files changed, 215 insertions(+), 16 deletions(-) diff --git a/.changeset/admin-crm.md b/.changeset/admin-crm.md index 4e4d6d6..b42562a 100644 --- a/.changeset/admin-crm.md +++ b/.changeset/admin-crm.md @@ -2,4 +2,4 @@ "@freeticket/cli": minor --- -New `ft admin crm` commands for the master CRM (admin contract 1.7.0): list and inspect campaigns, search shows and dates, read options and the WhatsApp quota, preview an audience, launch a campaign, send or stop WhatsApp batches and cancel a scheduled campaign. Every write previews its target and asks for confirmation (`--yes` in scripts), and none is retried automatically. +New `ft admin crm` commands for the master CRM (admin contract 1.7.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. Every write previews its target and asks for confirmation (`--yes` in scripts), none is retried automatically, and `PAYLOAD_TOO_LARGE` (413) is explained. diff --git a/README.md b/README.md index cadac5b..560787b 100644 --- a/README.md +++ b/README.md @@ -161,7 +161,7 @@ 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 [--yes] +ft admin crm launch --data @campaign.json [--ignore-window] [--yes] ``` **Writes send real messages.** `launch`, `campaigns cancel`, `batches next` and @@ -175,9 +175,11 @@ the same channel + sender + subject within 10 minutes with `DUPLICATE_CAMPAIGN` and prints the existing id). 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`; +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; `INVALID_STATE` means the -campaign no longer allows that action; a 422 lists each `details[].path`. +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`. @@ -237,6 +239,9 @@ cities, genre/format codes, plans and WhatsApp templates with `options`. 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; diff --git a/admin-openapi.json b/admin-openapi.json index 4fe667e..b14d8fa 100644 --- a/admin-openapi.json +++ b/admin-openapi.json @@ -2514,7 +2514,7 @@ "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. 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`.", + "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": [] @@ -2593,6 +2593,16 @@ } } }, + "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": { @@ -2807,6 +2817,16 @@ } } }, + "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": { @@ -2926,6 +2946,16 @@ } } }, + "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": { @@ -3035,6 +3065,16 @@ } } }, + "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": { @@ -3065,7 +3105,7 @@ "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, 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`.", + "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": [] @@ -3130,6 +3170,16 @@ } } }, + "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": { @@ -4670,11 +4720,42 @@ }, "AdminCrmAudienceFilter": { "type": "object", - "propertyNames": { - "type": "string" + "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": { + "version": { + "type": "integer", + "enum": [ + 2 + ] + } }, - "additionalProperties": {}, - "description": "Filtro de audiencia v2 (`{ version: 2, scope, include, except }`). Objeto opaco 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`)." + "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": [ @@ -5922,6 +6003,10 @@ }, "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": [ diff --git a/src/commands/admin-crm.test.ts b/src/commands/admin-crm.test.ts index 922f1b1..a41aa81 100644 --- a/src/commands/admin-crm.test.ts +++ b/src/commands/admin-crm.test.ts @@ -117,9 +117,8 @@ describe("ft admin crm command tree", () => { ["batches", "stop"], ]) expect(find(p).options.map((o) => o.long)).toContain("--yes"); - expect(find(["batches", "next"]).options.map((o) => o.long)).toContain( - "--ignore-window", - ); + for (const p of [["batches", "next"], ["launch"]]) + expect(find(p).options.map((o) => o.long)).toContain("--ignore-window"); }); }); @@ -302,6 +301,99 @@ describe("ft admin crm commands", () => { 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", + "--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), "--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), "--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), "--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 })); diff --git a/src/commands/admin-crm.ts b/src/commands/admin-crm.ts index dbd5bdf..420886e 100644 --- a/src/commands/admin-crm.ts +++ b/src/commands/admin-crm.ts @@ -112,6 +112,9 @@ export function describeWhen(seconds: number, now = Date.now()): string { 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). @@ -126,7 +129,7 @@ export function crmErrorHint( 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 this batch now.", + "Retry then, or pass --ignore-window to send now.", ].join("\n"); case "DUPLICATE_CAMPAIGN": { const id = (err.details as { existingId?: string } | undefined) @@ -145,6 +148,8 @@ export function crmErrorHint( 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."; default: @@ -159,8 +164,13 @@ export function crmErrorHint( function crmUnwrap(res: SdkResult): T { if (res.data !== undefined) return res.data; const err = (res.error as { error?: CrmError } | undefined)?.error; - if (!err) return unwrap(res); const status = res.response?.status; + if (!err && status === 413) + fail( + "Error 413 [PAYLOAD_TOO_LARGE]: request body too large.", + PAYLOAD_HINT, + ); + if (!err) return unwrap(res); const lines = [ `Error ${status ?? ""} [${err.code ?? "?"}]: ${err.message ?? "unknown failure"}`, ]; @@ -482,11 +492,18 @@ export function registerAdminCrm(admin: Command): void { "--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("--yes", "skip confirmation") .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).", @@ -521,7 +538,7 @@ export function registerAdminCrm(admin: Command): void { ? "in batches" : "on schedule"; await confirmOrExit( - `Launch to ${reach} people by ${input.channel ?? "?"}, sending ${when}?`, + `Launch to ${reach} people by ${input.channel ?? "?"}, sending ${when}${input.ignoreSendWindow ? " (ignoring the send window)" : ""}?`, opts.yes, ); const body = crmUnwrap(await postCrmCampaigns({ body: input })); From 1918b7ffab91a2067e17a9f2ea0ea78f99daaa95 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 21:26:32 +0000 Subject: [PATCH 5/7] chore(contract): sincronizar admin 1.8.0 (free-admin main) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Copiado de free-admin main (18de8ae). Frente al 1.7.0 de #1055: mismas operaciones, campos y códigos de error del CRM; agrega el rol MERCH_MANAGER, los nullables pasan de anyOf a type: [T, null] y los date-time exigen segundos. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fo7cm7S4yTPG5LztA8pEVi --- admin-openapi.json | 437 ++++++++++++++------------------------------- 1 file changed, 136 insertions(+), 301 deletions(-) diff --git a/admin-openapi.json b/admin-openapi.json index b14d8fa..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.7.0", + "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": [ @@ -3605,7 +3605,8 @@ "ADMIN", "STAFF", "VIEWER", - "MINCULTURA" + "MINCULTURA", + "MERCH_MANAGER" ] } }, @@ -3629,13 +3630,9 @@ "type": "object", "properties": { "nextCursor": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "hasMore": { @@ -3675,56 +3672,36 @@ "type": "boolean" }, "webTemplate": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "customDomain": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "customDomainVerifiedAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "suspended": { "type": "boolean" }, "suspendedAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "deletedAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "createdAt": { @@ -3776,7 +3753,7 @@ "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,}$" + "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": [ @@ -3839,7 +3816,7 @@ { "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)))$" + "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" @@ -3880,13 +3857,9 @@ "type": "string" }, "previousPlanSlug": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] } }, @@ -3905,33 +3878,21 @@ "type": "string" }, "orgId": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "planSlug": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "planName": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "status": { @@ -3951,46 +3912,30 @@ ] }, "startedAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "expiresAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "cancelledAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "stripeLinked": { "type": "boolean" }, "paymentOption": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] } }, @@ -4051,30 +3996,23 @@ "ADMIN", "STAFF", "VIEWER", - "MINCULTURA" + "MINCULTURA", + "MERCH_MANAGER" ] }, "banned": { "type": "boolean" }, "bannedAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "homeOrganizationId": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "workspaces": { @@ -4110,7 +4048,8 @@ "ADMIN", "STAFF", "VIEWER", - "MINCULTURA" + "MINCULTURA", + "MERCH_MANAGER" ] }, "banned": { @@ -4149,13 +4088,9 @@ "type": "string" }, "targetOrgId": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] } }, @@ -4187,13 +4122,9 @@ "type": "number" }, "priceBiannual": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } + "type": [ + "number", + "null" ] }, "maxEvents": { @@ -4461,26 +4392,18 @@ "$ref": "#/components/schemas/FeatureFlagScope" }, "scopeId": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "enabled": { "type": "boolean" }, "updatedBy": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "updatedAt": { @@ -4552,13 +4475,9 @@ ] }, "ipAddress": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "createdAt": { @@ -4591,33 +4510,21 @@ "type": "string" }, "lastUsedAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "expiresAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "revokedAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "createdAt": { @@ -4651,23 +4558,15 @@ "type": "string" }, "expiresAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "lastUsedAt": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] } }, @@ -4691,7 +4590,7 @@ "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)))$" + "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": [ @@ -5068,23 +4967,15 @@ "type": "string" }, "imageUrl": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "templateName": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "promotedEvent": { @@ -5224,23 +5115,15 @@ "description": "ISO 8601" }, "eventName": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "utmSource": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] } }, @@ -5361,26 +5244,18 @@ "type": "object", "properties": { "name": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "emailMasked": { "type": "string" }, "phoneMasked": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "lastPurchaseAt": { @@ -5443,13 +5318,9 @@ "type": "string" }, "logoUrl": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] } }, @@ -5681,23 +5552,15 @@ "type": "string" }, "footerText": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "urlButtonText": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] } }, @@ -5711,13 +5574,9 @@ } }, "whatsappBlockedReason": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] } }, @@ -5781,23 +5640,15 @@ "maximum": 9007199254740991 }, "venueName": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "city": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "status": { @@ -5836,36 +5687,24 @@ "description": "ISO 8601" }, "label": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "status": { "type": "string" }, "venueName": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "city": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "past": { @@ -5973,13 +5812,9 @@ }, "templateName": { "description": "Plantilla de WhatsApp aprobada (obligatoria por WhatsApp; el correo la rechaza). Ver `GET /crm/options`.", - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "type": [ + "string", + "null" ] }, "subject": { From 21de6ceb34311ec3475861b681135ff0b9804b9e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 21:26:32 +0000 Subject: [PATCH 6/7] =?UTF-8?q?feat(admin):=20escrituras=20del=20CRM=20sin?= =?UTF-8?q?=20reintento=20ni=20=C3=A9xito=20supuesto,=20filtro=20v2=20vali?= =?UTF-8?q?dado?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Las 4 escrituras pasan por crmWriteOnce: un 5xx o una conexión caída se reporta como resultado desconocido y apunta a campaigns list, nunca a "retry with backoff". - RATE_LIMITED (429) con su siguiente paso. - preview/launch rechazan un filtro sin version 2 antes de mandar nada. - destructive-confirm cubre las 4 escrituras: sin TTY (también con CI=true), con TTY y respuesta no/sí, preview con el tamaño de la audiencia antes de preguntar, y un solo envío ante 500/503/429/conexión caída. - Changeset y README a admin 1.8.0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fo7cm7S4yTPG5LztA8pEVi --- .changeset/admin-crm.md | 2 +- README.md | 11 +- src/commands/admin-crm.test.ts | 17 +++ src/commands/admin-crm.ts | 79 +++++++++-- src/destructive-confirm.test.ts | 243 ++++++++++++++++++++++++++++++++ src/program.test.ts | 2 +- 6 files changed, 339 insertions(+), 15 deletions(-) diff --git a/.changeset/admin-crm.md b/.changeset/admin-crm.md index b42562a..ca5b6a3 100644 --- a/.changeset/admin-crm.md +++ b/.changeset/admin-crm.md @@ -2,4 +2,4 @@ "@freeticket/cli": minor --- -New `ft admin crm` commands for the master CRM (admin contract 1.7.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. Every write previews its target and asks for confirmation (`--yes` in scripts), none is retried automatically, and `PAYLOAD_TOO_LARGE` (413) is explained. +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), 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. 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/README.md b/README.md index 17a7d46..fc4292c 100644 --- a/README.md +++ b/README.md @@ -170,15 +170,18 @@ ft admin crm launch --data @campaign.json [--ignore-window] [--yes] 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. Without a TTY they refuse unless -you pass `--yes`. The CLI never retries a write on its own: if a `launch` -times out, check `campaigns list` before launching again (the backend rejects +you pass `--yes` (being in CI is not consent). 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). +`DUPLICATE_CAMPAIGN` and prints the existing id). 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; `INVALID_STATE` means the +`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. diff --git a/src/commands/admin-crm.test.ts b/src/commands/admin-crm.test.ts index a41aa81..bf6cc1d 100644 --- a/src/commands/admin-crm.test.ts +++ b/src/commands/admin-crm.test.ts @@ -450,6 +450,23 @@ describe("ft admin crm commands", () => { ).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 } }), + "--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", () => { diff --git a/src/commands/admin-crm.ts b/src/commands/admin-crm.ts index 420886e..a8286fd 100644 --- a/src/commands/admin-crm.ts +++ b/src/commands/admin-crm.ts @@ -152,16 +152,48 @@ export function crmErrorHint( 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 }); +} + /** * `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): T { +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; @@ -170,7 +202,11 @@ function crmUnwrap(res: SdkResult): T { "Error 413 [PAYLOAD_TOO_LARGE]: request body too large.", PAYLOAD_HINT, ); - if (!err) return unwrap(res); + 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"}`, ]; @@ -182,9 +218,31 @@ function crmUnwrap(res: SdkResult): T { } 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(); @@ -329,7 +387,9 @@ export function registerAdminCrm(admin: Command): void { `Cancel campaign ${id}? It will not be sent`, opts.yes, ); - const body = crmUnwrap(await postCrmCampaignsIdCancel({ path: { id } })); + const body = await crmWriteOnce(() => + postCrmCampaignsIdCancel({ path: { id } }), + ); print(body.data, { json: opts.json }); }); @@ -351,8 +411,8 @@ export function registerAdminCrm(admin: Command): void { `Send the next batch of campaign ${id}${opts.ignoreWindow ? " (ignoring the send window)" : ""}?`, opts.yes, ); - const body = crmUnwrap( - await postCrmCampaignsIdBatchesNext({ + const body = await crmWriteOnce(() => + postCrmCampaignsIdBatchesNext({ path: { id }, ...(opts.ignoreWindow ? { body: { ignoreSendWindow: true } } : {}), }), @@ -374,8 +434,8 @@ export function registerAdminCrm(admin: Command): void { `Stop campaign ${id}? Pending recipients will never be sent (irreversible)`, opts.yes, ); - const body = crmUnwrap( - await postCrmCampaignsIdBatchesStop({ path: { id } }), + const body = await crmWriteOnce(() => + postCrmCampaignsIdBatchesStop({ path: { id } }), ); print(body.data, { json: opts.json }); }); @@ -462,7 +522,7 @@ export function registerAdminCrm(admin: Command): void { .option("--json", "raw JSON output") .action(async (opts) => { configureAdminClient(); - const filter = parseData(opts.filter) as AdminCrmAudienceFilter; + const filter = parseFilter(parseData(opts.filter), "--filter"); const body = crmUnwrap( await postCrmAudiencePreview({ body: { @@ -509,6 +569,7 @@ export function registerAdminCrm(admin: Command): void { "--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"); // Same filter and sender the launch will use: what you confirm is what // the backend resolves. const preview = crmUnwrap( @@ -541,7 +602,7 @@ export function registerAdminCrm(admin: Command): void { `Launch to ${reach} people by ${input.channel ?? "?"}, sending ${when}${input.ignoreSendWindow ? " (ignoring the send window)" : ""}?`, opts.yes, ); - const body = crmUnwrap(await postCrmCampaigns({ body: input })); + const body = await crmWriteOnce(() => postCrmCampaigns({ body: input })); print(body.data, { json: opts.json }); if (!opts.json) console.error( diff --git a/src/destructive-confirm.test.ts b/src/destructive-confirm.test.ts index 507ea96..9064d36 100644 --- a/src/destructive-confirm.test.ts +++ b/src/destructive-confirm.test.ts @@ -13,6 +13,26 @@ 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(), @@ -128,6 +148,8 @@ describe("ft admin crm writes refuse without a TTY and without --yes", () => { // 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(), @@ -198,3 +220,224 @@ describe("ft admin crm writes refuse without a TTY and without --yes", () => { 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", + args: [ + "launch", + "--data", + JSON.stringify({ + channel: "WHATSAPP", + sender: { kind: "freeticket" }, + templateName: "promo", + subject: "Hello", + body: "Hi", + filter: { version: 2, include: [], except: [] }, + timing: { mode: "now" }, + }), + ], + write: sdk.postCrmCampaigns, + }, + { + name: "campaigns cancel", + args: ["campaigns", "cancel", "cmp_1"], + write: sdk.postCrmCampaignsIdCancel, + }, + { + name: "batches next", + args: ["batches", "next", "cmp_1"], + write: sdk.postCrmCampaignsIdBatchesNext, + }, + { + name: "batches stop", + 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, + )("$name asks on a TTY and an answer other than yes never sends", async ({ + args, + write, + }) => { + tty.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"); + }); + } +}); diff --git a/src/program.test.ts b/src/program.test.ts index 140455f..eb27a01 100644 --- a/src/program.test.ts +++ b/src/program.test.ts @@ -47,7 +47,7 @@ test("contract 1.19 / admin 1.5 commands are wired, destructive ones behind --ye expect(longs("admin workspaces plan")).toContain("--data"); }); -test("admin 1.7 CRM commands are wired under `ft admin crm`", () => { +test("admin 1.8 CRM commands are wired under `ft admin crm`", () => { const tree = new Map(walk(program)); const expected = [ "admin crm campaigns list", From 138fda6c83eb4ce0ffd0573c422aff584327e294 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 21:46:15 +0000 Subject: [PATCH 7/7] fix(admin): CRM writes name the host, launch --yes needs --expect-count, no crash on odd 2xx - Every CRM write confirmation names the API host ("... against admin.appfreeticket.com?") so a staging token aimed at prod shows. - `launch --yes` requires `--expect-count ` and stops before writing if the preview reach differs; optional (but enforced) without --yes. - A 2xx with an unexpected body no longer crashes on `body.data.id`: it warns that the write probably went through and exits 0. - Tests: sweep of admin-openapi.json (x-ft-destructive / x-ft-mcp.expose false) against CRM_WRITES; static check that every postCrm* write is called only inside crmWriteOnce(() =>; real admin SDK + fake fetch 503 sends exactly one POST on launch and batches next; "n" prompt answer. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fo7cm7S4yTPG5LztA8pEVi --- .changeset/admin-crm.md | 2 +- README.md | 20 +- src/commands/admin-crm.test.ts | 46 +++- src/commands/admin-crm.transport.test.ts | 144 ++++++++++++ src/commands/admin-crm.ts | 120 ++++++++-- src/destructive-confirm.test.ts | 273 ++++++++++++++++++++++- 6 files changed, 577 insertions(+), 28 deletions(-) create mode 100644 src/commands/admin-crm.transport.test.ts diff --git a/.changeset/admin-crm.md b/.changeset/admin-crm.md index ca5b6a3..9695286 100644 --- a/.changeset/admin-crm.md +++ b/.changeset/admin-crm.md @@ -2,4 +2,4 @@ "@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), 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. 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). +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/README.md b/README.md index fc4292c..4fe81c3 100644 --- a/README.md +++ b/README.md @@ -162,19 +162,31 @@ 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] [--yes] +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. Without a TTY they refuse unless -you pass `--yes` (being in CI is not consent). The CLI never retries a write +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). A filter without +`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 diff --git a/src/commands/admin-crm.test.ts b/src/commands/admin-crm.test.ts index bf6cc1d..fd1545a 100644 --- a/src/commands/admin-crm.test.ts +++ b/src/commands/admin-crm.test.ts @@ -246,7 +246,15 @@ describe("ft admin crm commands", () => { }, timing: { mode: "now" }, }; - await run("launch", "--data", JSON.stringify(input), "--yes", "--json"); + await run( + "launch", + "--data", + JSON.stringify(input), + "--expect-count", + "80", + "--yes", + "--json", + ); expect(sdk.postCrmAudiencePreview).toHaveBeenCalledWith({ body: { filter: input.filter, sender: input.sender }, }); @@ -271,6 +279,8 @@ describe("ft admin crm commands", () => { "launch", "--data", JSON.stringify({ filter: { version: 2 } }), + "--expect-count", + "0", "--yes", ), ).rejects.toThrow("exited"); @@ -291,6 +301,8 @@ describe("ft admin crm commands", () => { "launch", "--data", JSON.stringify({ filter: { version: 2 }, channel: "EMAIL" }), + "--expect-count", + "110", "--yes", ), ).rejects.toThrow("exited"); @@ -321,6 +333,8 @@ describe("ft admin crm commands", () => { "--data", JSON.stringify(nowInput), "--ignore-window", + "--expect-count", + "80", "--yes", "--json", ); @@ -334,7 +348,15 @@ describe("ft admin crm commands", () => { sdk.postCrmCampaigns.mockResolvedValue( ok({ id: "cmp_9", status: "APPROVED", scheduledAt: null }), ); - await run("launch", "--data", JSON.stringify(nowInput), "--yes", "--json"); + await run( + "launch", + "--data", + JSON.stringify(nowInput), + "--expect-count", + "80", + "--yes", + "--json", + ); expect(sdk.postCrmCampaigns.mock.calls[0]?.[0].body).not.toHaveProperty( "ignoreSendWindow", ); @@ -354,7 +376,14 @@ describe("ft admin crm commands", () => { ), ); await expect( - run("launch", "--data", JSON.stringify(nowInput), "--yes"), + run( + "launch", + "--data", + JSON.stringify(nowInput), + "--expect-count", + "80", + "--yes", + ), ).rejects.toThrow("exited"); expect(sdk.postCrmCampaigns).toHaveBeenCalledTimes(1); const err = stderr.join("\n"); @@ -386,7 +415,14 @@ describe("ft admin crm commands", () => { response: new Response(null, { status: 413 }), }); await expect( - run("launch", "--data", JSON.stringify(nowInput), "--yes"), + run( + "launch", + "--data", + JSON.stringify(nowInput), + "--expect-count", + "80", + "--yes", + ), ).rejects.toThrow("exited"); expect(exit).toHaveBeenCalledWith(1); const err = stderr.join("\n"); @@ -458,6 +494,8 @@ describe("ft admin crm commands", () => { "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) => { 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 index a8286fd..fba20b0 100644 --- a/src/commands/admin-crm.ts +++ b/src/commands/admin-crm.ts @@ -1,5 +1,6 @@ import chalk from "chalk"; import type { Command } from "commander"; +import { client as adminClient } from "../admin-client/client.gen"; import { getCrmCampaigns, getCrmCampaignsId, @@ -187,6 +188,62 @@ async function crmWriteOnce(call: () => Promise>): Promise { 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). @@ -383,14 +440,16 @@ export function registerAdminCrm(admin: Command): void { .action(async (id, opts) => { configureAdminClient(); await showCampaign(id); - await confirmOrExit( - `Cancel campaign ${id}? It will not be sent`, + await confirmCrmWrite( + `Cancel campaign ${id}`, + "It will not be sent", opts.yes, ); const body = await crmWriteOnce(() => postCrmCampaignsIdCancel({ path: { id } }), ); - print(body.data, { json: opts.json }); + const data = writeData(body); + if (data !== undefined) print(data, { json: opts.json }); }); // ------------------------------------------------------------------ batches @@ -407,8 +466,9 @@ export function registerAdminCrm(admin: Command): void { .action(async (id, opts) => { configureAdminClient(); await showCampaign(id); - await confirmOrExit( - `Send the next batch of campaign ${id}${opts.ignoreWindow ? " (ignoring the send window)" : ""}?`, + await confirmCrmWrite( + `Send the next batch of campaign ${id}${opts.ignoreWindow ? " (ignoring the send window)" : ""}`, + "", opts.yes, ); const body = await crmWriteOnce(() => @@ -417,7 +477,8 @@ export function registerAdminCrm(admin: Command): void { ...(opts.ignoreWindow ? { body: { ignoreSendWindow: true } } : {}), }), ); - print(body.data, { json: opts.json }); + const data = writeData(body); + if (data !== undefined) print(data, { json: opts.json }); }); batches @@ -430,14 +491,16 @@ export function registerAdminCrm(admin: Command): void { .action(async (id, opts) => { configureAdminClient(); await showCampaign(id); - await confirmOrExit( - `Stop campaign ${id}? Pending recipients will never be sent (irreversible)`, + await confirmCrmWrite( + `Stop campaign ${id}`, + "Pending recipients will never be sent (irreversible)", opts.yes, ); const body = await crmWriteOnce(() => postCrmCampaignsIdBatchesStop({ path: { id } }), ); - print(body.data, { json: opts.json }); + const data = writeData(body); + if (data !== undefined) print(data, { json: opts.json }); }); // ------------------------------------------------------------------- events @@ -556,7 +619,11 @@ export function registerAdminCrm(admin: Command): void { "--ignore-window", "WhatsApp with timing.mode now: send even outside the 9:00-20:00 Bogotá window", ) - .option("--yes", "skip confirmation") + .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(); @@ -570,6 +637,14 @@ export function registerAdminCrm(admin: Command): void { "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( @@ -598,17 +673,30 @@ export function registerAdminCrm(admin: Command): void { : input.timing?.mode === "batches" ? "in batches" : "on schedule"; - await confirmOrExit( - `Launch to ${reach} people by ${input.channel ?? "?"}, sending ${when}${input.ignoreSendWindow ? " (ignoring the send window)" : ""}?`, + 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 })); - print(body.data, { json: opts.json }); + 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 ${body.data.id}\``, - ), + chalk.dim(`\nFollow it with \`ft admin crm campaigns get ${id}\``), ); }); } diff --git a/src/destructive-confirm.test.ts b/src/destructive-confirm.test.ts index 9064d36..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, @@ -229,6 +230,7 @@ describe("ft admin crm writes refuse without a TTY and without --yes", () => { const CRM_WRITES = [ { name: "launch", + op: "postCrmCampaigns", args: [ "launch", "--data", @@ -241,21 +243,27 @@ const CRM_WRITES = [ 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, }, @@ -309,12 +317,13 @@ describe("ft admin crm writes: confirmation, preview and no retries", () => { program.parseAsync(["node", "ft", "admin", "crm", ...args, ...extra]); it.each( - CRM_WRITES, - )("$name asks on a TTY and an answer other than yes never sends", async ({ + 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 = ""; + tty.answer = answer; await expect(run(args)).rejects.toThrow("exited"); expect(tty.questions).toHaveLength(1); expect(tty.questions[0]).toMatch(/\[y\/N\] $/); @@ -441,3 +450,261 @@ describe("ft admin crm writes: confirmation, preview and no retries", () => { }); } }); + +// --------------------------------------------------------------------------- +// 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"); + }); +});