--- id: "PMC-005-AUTOMATION" title: "PMC-005: Módulo de Automation" type: "Module Definition" epic: "PMC-005" status: "Draft" project: "platform_marketing_content" version: "1.0.0" created_date: "2026-01-04" updated_date: "2026-01-04" --- # PMC-005: Módulo de Automation **Versión:** 1.0.0 **Fecha:** 2025-12-08 **Estado:** Definición **Prioridad:** Media --- ## Descripción General El módulo de Automation gestiona flujos automatizados entre los diferentes componentes de la plataforma. Utiliza n8n como orquestador principal para conectar CRM, motor de generación, notificaciones y sistemas externos. --- ## Objetivos 1. Automatizar flujos creativos desde brief hasta entrega 2. Integrar CRM con motor de generación 3. Disparar acciones basadas en eventos del sistema 4. Conectar con servicios externos (email, redes, etc.) 5. Reducir tareas manuales repetitivas --- ## Entidades del Dominio ### AutomationFlow ```yaml Entidad: AutomationFlow Descripción: Definición de un flujo automatizado Atributos: - id: UUID (PK) - tenant_id: UUID (FK) - name: string - description: text - type: enum [trigger_based, scheduled, manual] - trigger_event: string (evento que dispara el flujo) - n8n_workflow_id: string (ID del workflow en n8n) - is_active: boolean - last_run: timestamp - run_count: integer - config: JSONB - retry_on_failure: boolean - max_retries: number - timeout_seconds: number - created_at: timestamp - updated_at: timestamp Relaciones: - N:1 con Tenant - 1:N con AutomationRun ``` ### AutomationRun ```yaml Entidad: AutomationRun Descripción: Ejecución de un flujo automatizado Atributos: - id: UUID (PK) - flow_id: UUID (FK) - tenant_id: UUID (FK) - status: enum [running, completed, failed, cancelled] - trigger_data: JSONB (datos del evento que disparó) - output_data: JSONB (resultados) - error_message: text - started_at: timestamp - completed_at: timestamp - duration_ms: integer Relaciones: - N:1 con AutomationFlow - N:1 con Tenant ``` ### WebhookEndpoint ```yaml Entidad: WebhookEndpoint Descripción: Endpoint para recibir eventos externos Atributos: - id: UUID (PK) - tenant_id: UUID (FK) - name: string - slug: string (parte de la URL) - secret_key: string (para validación) - target_flow_id: UUID (FK) - is_active: boolean - last_called: timestamp - call_count: integer - created_at: timestamp Relaciones: - N:1 con Tenant - N:1 con AutomationFlow ``` --- ## Eventos del Sistema ### Eventos Disponibles para Triggers ```yaml CRM Events: - client.created - client.updated - brand.created - brand.updated - product.created - product.updated - opportunity.stage_changed - opportunity.won - opportunity.lost Project Events: - project.created - project.status_changed - campaign.created - campaign.status_changed - campaign.brief_completed - campaign.approved Generation Events: - job.completed - job.failed - batch.completed - model.training_completed Asset Events: - asset.created - asset.approved - asset.rejected - all_assets.approved (todos los assets de campaña) User Events: - user.created - user.invited - user.activated ``` --- ## Flujos Predefinidos (MVP) ### FLOW-001: Nuevo Producto → Generar Kit de Assets ```yaml Nombre: product_asset_kit Trigger: product.created Descripción: Al crear producto, genera pack de imágenes automáticamente Pasos: 1. Recibir evento product.created 2. Cargar datos del producto y su marca 3. Verificar si tiene imágenes de referencia 4. Llamar a GenerationService con workflow "product_photo_synthetic" 5. Esperar completación del job 6. Notificar al usuario creador Configuración: images_count: 5 auto_approve: false notify_on_complete: true ``` ### FLOW-002: Nueva Campaña → Generar Lote Inicial ```yaml Nombre: campaign_initial_batch Trigger: campaign.brief_completed Descripción: Al completar brief, genera creatividades iniciales Pasos: 1. Recibir evento campaign.brief_completed 2. Extraer deliverables del brief 3. Para cada formato solicitado: - Llamar a GenerationService - Generar imágenes según especificaciones 4. Generar copys con LLM 5. Vincular assets a la campaña 6. Cambiar estado campaña a "in_production" 7. Notificar al equipo asignado Configuración: parallel_generations: true generate_copies: true auto_link_assets: true ``` ### FLOW-003: Campaña Aprobada → Preparar Entrega ```yaml Nombre: campaign_delivery_prep Trigger: campaign.approved Descripción: Prepara paquete de entrega al aprobar campaña Pasos: 1. Recibir evento campaign.approved 2. Recopilar todos los assets aprobados 3. Generar ZIP con estructura organizada 4. Crear enlace de descarga temporal 5. Si cliente tiene acceso al portal: - Crear notificación en portal 6. Enviar email al contacto del cliente 7. Registrar entrega en historial Configuración: zip_structure: "by_format" | "flat" include_copies: true link_expiry_days: 7 notify_client: true ``` ### FLOW-004: Job Fallido → Notificar y Reintentar ```yaml Nombre: job_failure_handler Trigger: job.failed Descripción: Maneja fallos de generación Pasos: 1. Recibir evento job.failed 2. Evaluar tipo de error 3. Si error transitorio (GPU, timeout): - Reintentar hasta max_retries 4. Si error persistente: - Notificar al usuario - Crear ticket/tarea de revisión 5. Registrar en logs de auditoría Configuración: max_retries: 3 retry_delay_seconds: 60 notify_on_permanent_failure: true ``` --- ## Funcionalidades ### F-005.1: Gestión de Flujos | ID | Funcionalidad | Descripción | Prioridad | |----|---------------|-------------|-----------| | F-005.1.1 | Listar flujos | Ver flujos disponibles y activos | Alta | | F-005.1.2 | Activar/Desactivar | Toggle de flujos | Alta | | F-005.1.3 | Configurar | Ajustar parámetros de flujo | Media | | F-005.1.4 | Ver historial | Ejecuciones pasadas | Media | ### F-005.2: Ejecución Manual | ID | Funcionalidad | Descripción | Prioridad | |----|---------------|-------------|-----------| | F-005.2.1 | Ejecutar ahora | Disparar flujo manualmente | Media | | F-005.2.2 | Test run | Ejecutar en modo prueba | Baja | | F-005.2.3 | Cancelar | Detener ejecución en curso | Media | ### F-005.3: Webhooks | ID | Funcionalidad | Descripción | Prioridad | |----|---------------|-------------|-----------| | F-005.3.1 | Crear endpoint | Generar URL de webhook | Media | | F-005.3.2 | Validar payload | Verificar firma/secret | Media | | F-005.3.3 | Ver logs | Historial de llamadas | Baja | ### F-005.4: Integraciones Externas | ID | Funcionalidad | Descripción | Prioridad | |----|---------------|-------------|-----------| | F-005.4.1 | Email | Envío de notificaciones | Alta | | F-005.4.2 | Slack | Notificaciones a canales | Media | | F-005.4.3 | CRM externo | Sync bidireccional | Baja | --- ## Arquitectura de Integración n8n ```yaml Componentes: Backend (NestJS): - EventEmitter: Emite eventos del sistema - WebhookController: Recibe llamadas de n8n - AutomationService: Gestiona flujos y ejecuciones n8n Server: - Workflows definidos - Credenciales de integración - Webhooks de entrada/salida Comunicación: Backend → n8n: Webhooks HTTP POST n8n → Backend: API calls con auth token Flujo: 1. Evento ocurre en Backend (ej: product.created) 2. EventEmitter notifica a AutomationService 3. AutomationService busca flujos suscritos al evento 4. Para cada flujo activo: - POST a webhook de n8n con datos del evento 5. n8n ejecuta workflow 6. n8n llama a API del Backend para acciones 7. n8n reporta resultado via webhook de completion ``` ### Ejemplo de Webhook Payload ```json { "event": "product.created", "timestamp": "2025-12-08T10:30:00Z", "tenant_id": "uuid-tenant", "data": { "product_id": "uuid-product", "brand_id": "uuid-brand", "name": "Producto X", "description": "...", "reference_images": ["url1", "url2"] }, "metadata": { "user_id": "uuid-user", "source": "api" } } ``` --- ## API Endpoints ```yaml Base: /api/v1/automation # Flows GET /flows # Listar flujos GET /flows/:id # Detalle de flujo POST /flows/:id/activate # Activar flujo POST /flows/:id/deactivate # Desactivar flujo PUT /flows/:id/config # Configurar flujo POST /flows/:id/execute # Ejecutar manualmente # Runs GET /runs # Historial de ejecuciones GET /runs/:id # Detalle de ejecución POST /runs/:id/cancel # Cancelar ejecución # Webhooks GET /webhooks # Listar endpoints POST /webhooks # Crear endpoint DELETE /webhooks/:id # Eliminar endpoint POST /webhooks/:id/regenerate # Regenerar secret # Incoming webhooks (public, con autenticación por secret) POST /hooks/:tenant_slug/:webhook_slug ``` --- ## Reglas de Negocio ```yaml RN-005.1: Descripción: Flujos desactivados no procesan eventos Comportamiento: Eventos ignorados si flow.is_active = false RN-005.2: Descripción: Reintentos con backoff exponencial Cálculo: delay = retry_delay * (2 ^ attempt_number) RN-005.3: Descripción: Ejecuciones fallidas notifican a admins Acción: Email + notificación in-app a usuarios con rol admin RN-005.4: Descripción: Webhooks requieren validación de secret Validación: HMAC-SHA256 del payload con secret key RN-005.5: Descripción: Límite de ejecuciones por hora Validación: Rate limit según plan del tenant ``` --- ## Dependencias ```yaml Dependencias de Módulos: - PMC-001 Tenants: Configuración y límites - PMC-002 CRM: Eventos de clientes/productos - PMC-003 Projects: Eventos de campañas - PMC-004 Generation: Llamadas a generación - PMC-006 Assets: Gestión de outputs Dependencias del Catálogo: - @CATALOG_NOTIFY: path: shared/catalog/notifications/ uso: Sistema de notificaciones multi-canal incluye: - Notificaciones in-app - Notificaciones por email (SMTP/SendGrid) - Push notifications (Web Push) - Templates con variables - Preferencias por usuario templates_a_crear: - job_completed: Generacion completada - job_failed: Error en generacion - campaign_approved: Campana aprobada - campaign_delivered: Assets listos - quota_warning: 80% quota usado - quota_exceeded: Quota agotada - brand_assets_ready: Kit de marca listo docs: shared/catalog/notifications/README.md Servicios Externos: - n8n: Orquestador de workflows (self-hosted) - SMTP/SendGrid: Envío de emails (via @CATALOG_NOTIFY) - Slack API: Notificaciones (opcional) Referencia de Implementacion: - Notifications module: projects/gamilit/apps/backend/src/modules/notifications/ - Mail service: projects/gamilit/apps/backend/src/modules/mail/ - Templates: projects/gamilit/apps/backend/src/modules/mail/templates/ ``` --- ## Consideraciones de Seguridad ```yaml Autenticación: - Webhooks internos usan JWT del sistema - Webhooks externos usan HMAC con secret por endpoint - n8n autenticado con API key exclusiva Aislamiento: - Flujos aislados por tenant - Eventos solo visible para el tenant que los genera Validación: - Payload size máximo: 1MB - Rate limiting por endpoint - Timeout de ejecución: 5 minutos ``` --- ## Criterios de Aceptación - [ ] Flujos predefinidos funcionan correctamente - [ ] Eventos del sistema disparan flujos suscritos - [ ] n8n recibe y procesa webhooks - [ ] Ejecuciones se registran con estado y resultado - [ ] Reintentos automáticos funcionan en errores transitorios - [ ] Webhooks externos validan correctamente el secret - [ ] Notificaciones se envían según configuración - [ ] Rate limiting funciona según plan --- ## Referencias - [ARQUITECTURA-TECNICA.md](../00-vision-general/ARQUITECTURA-TECNICA.md) - [n8n Documentation](https://docs.n8n.io/) - [PMC-004-GENERATION.md](./PMC-004-GENERATION.md) --- **Documento generado por:** Requirements-Analyst **Fecha:** 2025-12-08