{
  "name": "Logixb2b — Email outbound personalizado con IA",
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "Webhook outbound → Config ICP → LLM borrador → IF unsubscribe skip → Slack revisión humana (cola envío placeholder). Incluye Asistente IA (OpenAI) configurable."
  },
  "settings": {
    "executionOrder": "v1",
    "timezone": "Europe/Madrid"
  },
  "active": false,
  "pinData": {},
  "tags": [
    {
      "name": "Logixb2b"
    },
    {
      "name": "recursos"
    },
    {
      "name": "ia"
    },
    {
      "name": "outbound"
    }
  ],
  "nodes": [
    {
      "id": "sticky-instrucciones-logix",
      "name": "INSTRUCCIONES (conectar + VPS)",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -480,
        40
      ],
      "parameters": {
        "content": "## INSTRUCCIONES — Email outbound personalizado con IA\n\n**Recurso:** `/recursos/outbound-email-ia`\n**Guía:** /ia-generativa-correos-outbound-personalizados\n**Zona:** Europe/Madrid · `active: false` al importar (tú lo activas).\n\n### 1) Importar\n1. n8n → ⋯ → **Import from File** → este JSON.\n2. El flujo llega **inactive**. No pegues secretos en el lienzo ni en el archivo.\n\n### 2) Credenciales y configuración por nodo\n- **Webhook lista prospectos** (`webhook`): sin credencial. Tras Active, copia **URL de producción** (HTTPS del VPS/Cloud). El emisor (formulario, CRM, bot) debe POST a esa URL.\n- **Config ICP** (`Set` Config): **no lleva credencial**. Aquí van URLs/placeholders (`REEMPLAZA_*`, `example.com`, `TU-CRM`). Sustituye todos antes de Active.\n- **Normalizar prospecto** (`Set`): sin credencial. Revisa expresiones `={{ }}` y campos de salida.\n- **¿Unsubscribe / opt-out?** (`IF`): sin credencial. Comprueba la condición (email, umbral, over_limit, etc.) con datos reales de prueba.\n- **Parsear borrador** (`Set`): sin credencial. Revisa expresiones `={{ }}` y campos de salida.\n- **¿Cola de envío?** (`IF`): sin credencial. Comprueba la condición (email, umbral, over_limit, etc.) con datos reales de prueba.\n- **Cola envío (placeholder HTTP)** (`HTTP Request`): abre el nodo → Authentication → elige **Header Auth / OAuth2 / Generic** según el destino. Sustituye URL de ejemplo. Activa \"Continue on Fail\" solo si el diseño lo pide.\n- **Slack — borrador para revisión** (`HTTP Request` → Slack/Teams): crea Incoming Webhook en Slack (o Adaptive Card URL en Teams). Pega la URL en **Config** o en este nodo. Auth: none (la URL ya es secreta).\n- **Preparar prompt IA** (`Set`): sin credencial. Revisa expresiones `={{ }}` y campos de salida.\n- **Asistente IA** (`AI Agent`): no lleva API key propia; debe estar cableado al nodo **Modelo OpenAI**. Revisa el prompt del sistema y que la salida pase por revisión humana (HITL) antes de escribir al CRM.\n- **Modelo OpenAI** (`OpenAI / LLM`): Credentials → **OpenAI API** (o compatible: base URL + API key). Nunca pegues la key en el JSON. El Asistente IA depende de este nodo.\n- **Aplicar salida IA** (`Set`): sin credencial. Revisa expresiones `={{ }}` y campos de salida.\n\n### 3) Orden recomendado de puesta en marcha\n1. Rellena el nodo **Config** (URLs reales, umbrales, webhooks de Slack).\n2. Crea Credentials en n8n (candado de cada nodo HTTP / Sheets / OpenAI) y **enlázalas**.\n3. Ejecuta **una vez** (Manual / Test URL del Webhook / \"Execute workflow\").\n4. Verifica CRM + Slack/Sheets (y que la IA no escriba en producción sin HITL).\n5. Solo entonces: interruptor **Active**.\n\n### 4) Producción 24/7 en VPS (UE)\nImportar en localhost no basta: webhooks y cron necesitan n8n encendido.\n\n1. VPS en UE (Hetzner/OVH/IONOS…) + Docker Compose + **Postgres** + HTTPS (Caddy/Nginx).\n2. Variables mínimas: `GENERIC_TIMEZONE=Europe/Madrid`, `WEBHOOK_URL=https://n8n.tudominio.com/`, `N8N_ENCRYPTION_KEY`, `N8N_HOST` / `N8N_PROTOCOL=https`.\n3. Firewall: solo 80/443 (+ SSH). Backups del volumen Postgres + export de workflows.\n4. Importa este JSON en la instancia de producción, vuelve a crear Credentials (no se copian solas), actualiza URLs del Config al dominio real.\n5. Pon **Active**. Prueba el Webhook de producción o espera el próximo cron.\n6. Alternativa: **n8n Cloud** (mismo JSON; Credentials en la UI Cloud).\n\n### 5) RGPD + EU AI Act (resumen)\nSi hay nodos IA sois **deployers** (Reglamento UE 2024/1689). Art. 4 alfabetización. **HITL** antes de outreach, scores masivos o pausas de cuenta. Minimiza PII en Slack/logs. Informativo — no es asesoramiento legal. /uso-responsable-de-ia-y-transparencia\n",
        "height": 1500,
        "width": 580,
        "color": 4
      }
    },
    {
      "id": "out-webhook",
      "name": "Webhook lista prospectos",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        300
      ],
      "webhookId": "outbound",
      "parameters": {
        "httpMethod": "POST",
        "path": "outbound",
        "responseMode": "onReceived",
        "options": {}
      }
    },
    {
      "id": "out-config",
      "name": "Config ICP",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        300,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "out-c1",
              "name": "icpSummary",
              "value": "SaaS B2B 20–200 empleados, España/LATAM, comprador: Director Comercial o RevOps.",
              "type": "string"
            },
            {
              "id": "out-c2",
              "name": "valueProp",
              "value": "Automatizamos el pipeline comercial con n8n para reducir trabajo manual y acelerar el ciclo de cierre.",
              "type": "string"
            },
            {
              "id": "out-c3",
              "name": "tone",
              "value": "profesional, cercano, sin hype",
              "type": "string"
            },
            {
              "id": "out-c4",
              "name": "language",
              "value": "es",
              "type": "string"
            },
            {
              "id": "out-c5",
              "name": "llmUrl",
              "value": "https://api.openai.com/v1/chat/completions",
              "type": "string"
            },
            {
              "id": "out-c6",
              "name": "apiKey",
              "value": "sustituye-con-tu-clave-del-modelo-ia",
              "type": "string"
            },
            {
              "id": "out-c7",
              "name": "model",
              "value": "gpt-4o-mini",
              "type": "string"
            },
            {
              "id": "out-c8",
              "name": "slackWebhookUrl",
              "value": "https://example.com/aviso-equipo-slack",
              "type": "string"
            },
            {
              "id": "out-c9",
              "name": "sendQueueUrl",
              "value": "https://TU-COLA-ENVIO.ejemplo/api/queue",
              "type": "string"
            },
            {
              "id": "out-c10",
              "name": "useSendQueue",
              "value": false,
              "type": "boolean"
            },
            {
              "id": "out-c11",
              "name": "optOutFooter",
              "value": "Si no deseas más correos, responde BAJA o usa el enlace de oposición de tu firma.",
              "type": "string"
            },
            {
              "id": "out-c12",
              "name": "draftedAt",
              "value": "={{ $now.setZone('Europe/Madrid').toFormat('yyyy-MM-dd HH:mm') }}",
              "type": "string"
            },
            {
              "id": "out-c13",
              "name": "rawBody",
              "value": "={{ $json.body || $json }}",
              "type": "object"
            }
          ]
        }
      }
    },
    {
      "id": "out-normalize",
      "name": "Normalizar prospecto",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        600,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "out-n1",
              "name": "email",
              "value": "={{ String($json.rawBody.email || '').trim().toLowerCase() }}",
              "type": "string"
            },
            {
              "id": "out-n2",
              "name": "name",
              "value": "={{ String($json.rawBody.name || '').trim() }}",
              "type": "string"
            },
            {
              "id": "out-n3",
              "name": "company",
              "value": "={{ String($json.rawBody.company || '').trim() }}",
              "type": "string"
            },
            {
              "id": "out-n4",
              "name": "title",
              "value": "={{ String($json.rawBody.title || '').trim() }}",
              "type": "string"
            },
            {
              "id": "out-n5",
              "name": "unsubscribed",
              "value": "={{ !!($json.rawBody.unsubscribed || $json.rawBody.optOut || $json.rawBody.opt_out) }}",
              "type": "boolean"
            },
            {
              "id": "out-n6",
              "name": "icpSummary",
              "value": "={{ $json.icpSummary }}",
              "type": "string"
            },
            {
              "id": "out-n7",
              "name": "valueProp",
              "value": "={{ $json.valueProp }}",
              "type": "string"
            },
            {
              "id": "out-n8",
              "name": "tone",
              "value": "={{ $json.tone }}",
              "type": "string"
            },
            {
              "id": "out-n9",
              "name": "language",
              "value": "={{ $json.language }}",
              "type": "string"
            },
            {
              "id": "out-n10",
              "name": "llmUrl",
              "value": "={{ $json.llmUrl }}",
              "type": "string"
            },
            {
              "id": "out-n11",
              "name": "apiKey",
              "value": "={{ $json.apiKey }}",
              "type": "string"
            },
            {
              "id": "out-n12",
              "name": "model",
              "value": "={{ $json.model }}",
              "type": "string"
            },
            {
              "id": "out-n13",
              "name": "slackWebhookUrl",
              "value": "={{ $json.slackWebhookUrl }}",
              "type": "string"
            },
            {
              "id": "out-n14",
              "name": "sendQueueUrl",
              "value": "={{ $json.sendQueueUrl }}",
              "type": "string"
            },
            {
              "id": "out-n15",
              "name": "useSendQueue",
              "value": "={{ $json.useSendQueue }}",
              "type": "boolean"
            },
            {
              "id": "out-n16",
              "name": "optOutFooter",
              "value": "={{ $json.optOutFooter }}",
              "type": "string"
            },
            {
              "id": "out-n17",
              "name": "draftedAt",
              "value": "={{ $json.draftedAt }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "out-if-optout",
      "name": "¿Unsubscribe / opt-out?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        900,
        300
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "out-cond-opt",
              "leftValue": "={{ $json.unsubscribed }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        }
      }
    },
    {
      "id": "out-skip",
      "name": "Skip — opt-out RGPD",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        1200,
        40
      ],
      "parameters": {}
    },
    {
      "id": "out-parse",
      "name": "Parsear borrador",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        2100,
        560
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "out-p1",
              "name": "subject",
              "value": "={{ (() => { try { const t = String($json.aiOutput || '{}').replace(/```json|```/g,'').trim(); return String(JSON.parse(t).subject || '(sin asunto)'); } catch(e) { return '(sin asunto)'; } })() }}",
              "type": "string"
            },
            {
              "id": "out-p2",
              "name": "body",
              "value": "={{ (() => { try { const t = String($json.aiOutput || '{}').replace(/```json|```/g,'').trim(); return String(JSON.parse(t).body || ''); } catch(e) { return String($json.aiOutput || ''); } })() }}",
              "type": "string"
            },
            {
              "id": "out-p3",
              "name": "email",
              "value": "={{ $('Normalizar prospecto').item.json.email }}",
              "type": "string"
            },
            {
              "id": "out-p4",
              "name": "name",
              "value": "={{ $('Normalizar prospecto').item.json.name }}",
              "type": "string"
            },
            {
              "id": "out-p5",
              "name": "company",
              "value": "={{ $('Normalizar prospecto').item.json.company }}",
              "type": "string"
            },
            {
              "id": "out-p6",
              "name": "slackWebhookUrl",
              "value": "={{ $('Normalizar prospecto').item.json.slackWebhookUrl }}",
              "type": "string"
            },
            {
              "id": "out-p7",
              "name": "sendQueueUrl",
              "value": "={{ $('Normalizar prospecto').item.json.sendQueueUrl }}",
              "type": "string"
            },
            {
              "id": "out-p8",
              "name": "useSendQueue",
              "value": "={{ $('Normalizar prospecto').item.json.useSendQueue }}",
              "type": "boolean"
            },
            {
              "id": "out-p9",
              "name": "draftedAt",
              "value": "={{ $('Normalizar prospecto').item.json.draftedAt }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "out-if-queue",
      "name": "¿Cola de envío?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2400,
        560
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "out-cond-queue",
              "leftValue": "={{ $json.useSendQueue }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        }
      }
    },
    {
      "id": "out-queue",
      "name": "Cola envío (placeholder HTTP)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2700,
        300
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $json.sendQueueUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ to: $json.email, subject: $json.subject, body: $json.body, status: 'pending_human_review', draftedAt: $json.draftedAt }) }}",
        "options": {
          "timeout": 15000,
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true
            }
          }
        }
      }
    },
    {
      "id": "out-slack",
      "name": "Slack — borrador para revisión",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2700,
        820
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $json.slackWebhookUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: ':email: *Borrador outbound (revisión humana)*\\nPara: ' + $json.name + ' <`' + $json.email + '`> @ ' + $json.company + '\\nAsunto: ' + $json.subject + '\\n---\\n' + $json.body + '\\n---\\nNo enviar sin editar. Hora: ' + $json.draftedAt + ' (Europe/Madrid)' }) }}",
        "options": {
          "timeout": 10000
        }
      }
    },
    {
      "id": "ai-prep-outbound-ema",
      "name": "Preparar prompt IA",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1200,
        560
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "includeOtherFields": true,
        "assignments": {
          "assignments": [
            {
              "id": "p1",
              "name": "aiPrompt",
              "value": "={{ \"Eres copywriter outbound B2B. Redacta asunto + cuerpo corto personalizado según ICP y empresa. Incluye mención a baja RGPD. Español.\\n\\nProspecto:\\n\" + JSON.stringify($json) + \"\" }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "ai-agent-outbound-ema",
      "name": "Asistente IA",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [
        1500,
        560
      ],
      "parameters": {
        "promptType": "define",
        "text": "={{ $json.aiPrompt }}",
        "options": {}
      }
    },
    {
      "id": "ai-model-outbound-ema",
      "name": "Modelo OpenAI",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.2,
      "position": [
        1500,
        840
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4o-mini"
        },
        "options": {}
      }
    },
    {
      "id": "ai-apply-outbound-ema",
      "name": "Aplicar salida IA",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1800,
        560
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "includeOtherFields": true,
        "assignments": {
          "assignments": [
            {
              "id": "a1",
              "name": "aiOutput",
              "value": "={{ $json.output || $json.text || $json.message || JSON.stringify($json) }}",
              "type": "string"
            },
            {
              "id": "a2",
              "name": "slackText",
              "value": "={{ ($json.output || $json.text || '').toString() || 'Revisa el resultado del Asistente IA.' }}",
              "type": "string"
            }
          ]
        }
      }
    }
  ],
  "connections": {
    "Webhook lista prospectos": {
      "main": [
        [
          {
            "node": "Config ICP",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Config ICP": {
      "main": [
        [
          {
            "node": "Normalizar prospecto",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalizar prospecto": {
      "main": [
        [
          {
            "node": "¿Unsubscribe / opt-out?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿Unsubscribe / opt-out?": {
      "main": [
        [
          {
            "node": "Skip — opt-out RGPD",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Preparar prompt IA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parsear borrador": {
      "main": [
        [
          {
            "node": "¿Cola de envío?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿Cola de envío?": {
      "main": [
        [
          {
            "node": "Cola envío (placeholder HTTP)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Slack — borrador para revisión",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Preparar prompt IA": {
      "main": [
        [
          {
            "node": "Asistente IA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Asistente IA": {
      "main": [
        [
          {
            "node": "Aplicar salida IA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Modelo OpenAI": {
      "ai_languageModel": [
        [
          {
            "node": "Asistente IA",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Aplicar salida IA": {
      "main": [
        [
          {
            "node": "Parsear borrador",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
