{
  "name": "Logixb2b — Cualificación de leads con IA",
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "Webhook lead → LLM score MQL/SQL → si alto: Slack + CRM; si no: ruta nurture/NoOp. Incluye Asistente IA (OpenAI) configurable."
  },
  "settings": {
    "executionOrder": "v1",
    "timezone": "Europe/Madrid"
  },
  "active": false,
  "pinData": {},
  "tags": [
    {
      "name": "Logixb2b"
    },
    {
      "name": "recursos"
    },
    {
      "name": "ia"
    },
    {
      "name": "cualificacion"
    }
  ],
  "nodes": [
    {
      "id": "sticky-instrucciones-logix",
      "name": "INSTRUCCIONES (conectar + VPS)",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -480,
        40
      ],
      "parameters": {
        "content": "## INSTRUCCIONES — Cualificación de leads con IA\n\n**Recurso:** `/recursos/cualificacion-leads-ia`\n**Guía:** /como-automatizar-cualificacion-leads-con-ia\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 lead entrante** (`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 cualificación** (`Set` Config): **no lleva credencial**. Aquí van URLs/placeholders (`REEMPLAZA_*`, `example.com`, `TU-CRM`). Sustituye todos antes de Active.\n- **Normalizar lead** (`Set`): sin credencial. Revisa expresiones `={{ }}` y campos de salida.\n- **Guardar score** (`Set`): sin credencial. Revisa expresiones `={{ }}` y campos de salida.\n- **¿Score alto?** (`IF`): sin credencial. Comprueba la condición (email, umbral, over_limit, etc.) con datos reales de prueba.\n- **CRM update cualificación** (`HTTP Request` CRM): Credentials → **Header Auth** / OAuth del CRM. Sustituye `crm*Url` en el nodo **Config**. Prueba con un Lead de sandbox.\n- **Slack lead cualificado** (`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": "wh-lead",
      "name": "Webhook lead entrante",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        300
      ],
      "webhookId": "wh-lead",
      "parameters": {
        "httpMethod": "POST",
        "path": "lead-cualificacion-ia",
        "responseMode": "onReceived",
        "options": {}
      }
    },
    {
      "id": "set-config",
      "name": "Config cualificación",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        300,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "c1",
              "name": "llmUrl",
              "value": "https://api.openai.com/v1/chat/completions",
              "type": "string"
            },
            {
              "id": "c2",
              "name": "apiKey",
              "value": "sustituye-con-tu-clave-del-modelo-ia",
              "type": "string"
            },
            {
              "id": "c3",
              "name": "model",
              "value": "gpt-4o-mini",
              "type": "string"
            },
            {
              "id": "c4",
              "name": "scoreThreshold",
              "value": 70,
              "type": "number"
            },
            {
              "id": "c5",
              "name": "crmUpdateUrl",
              "value": "https://TU-CRM.ejemplo/api/contacts/qualify",
              "type": "string"
            },
            {
              "id": "c6",
              "name": "slackWebhookUrl",
              "value": "https://example.com/aviso-equipo-slack",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "set-norm",
      "name": "Normalizar lead",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        600,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "n1",
              "name": "email",
              "value": "={{ ($('Webhook lead entrante').item.json.body || $('Webhook lead entrante').item.json).email || '' }}",
              "type": "string"
            },
            {
              "id": "n2",
              "name": "name",
              "value": "={{ ($('Webhook lead entrante').item.json.body || $('Webhook lead entrante').item.json).name || '' }}",
              "type": "string"
            },
            {
              "id": "n3",
              "name": "company",
              "value": "={{ ($('Webhook lead entrante').item.json.body || $('Webhook lead entrante').item.json).company || '' }}",
              "type": "string"
            },
            {
              "id": "n4",
              "name": "title",
              "value": "={{ ($('Webhook lead entrante').item.json.body || $('Webhook lead entrante').item.json).title || ($('Webhook lead entrante').item.json.body || $('Webhook lead entrante').item.json).jobTitle || '' }}",
              "type": "string"
            },
            {
              "id": "n5",
              "name": "employees",
              "value": "={{ ($('Webhook lead entrante').item.json.body || $('Webhook lead entrante').item.json).employees || ($('Webhook lead entrante').item.json.body || $('Webhook lead entrante').item.json).companySize || '' }}",
              "type": "string"
            },
            {
              "id": "n6",
              "name": "need",
              "value": "={{ ($('Webhook lead entrante').item.json.body || $('Webhook lead entrante').item.json).need || ($('Webhook lead entrante').item.json.body || $('Webhook lead entrante').item.json).message || '' }}",
              "type": "string"
            },
            {
              "id": "n7",
              "name": "llmUrl",
              "value": "={{ $('Config cualificación').item.json.llmUrl }}",
              "type": "string"
            },
            {
              "id": "n8",
              "name": "apiKey",
              "value": "={{ $('Config cualificación').item.json.apiKey }}",
              "type": "string"
            },
            {
              "id": "n9",
              "name": "model",
              "value": "={{ $('Config cualificación').item.json.model }}",
              "type": "string"
            },
            {
              "id": "n10",
              "name": "scoreThreshold",
              "value": "={{ $('Config cualificación').item.json.scoreThreshold }}",
              "type": "number"
            },
            {
              "id": "n11",
              "name": "crmUpdateUrl",
              "value": "={{ $('Config cualificación').item.json.crmUpdateUrl }}",
              "type": "string"
            },
            {
              "id": "n12",
              "name": "slackWebhookUrl",
              "value": "={{ $('Config cualificación').item.json.slackWebhookUrl }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "set-score",
      "name": "Guardar score",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1800,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "s1",
              "name": "score",
              "value": "={{ (() => { try { return Number(JSON.parse($json.aiOutput).score); } catch(e) { return 0; } })() }}",
              "type": "number"
            },
            {
              "id": "s2",
              "name": "label",
              "value": "={{ (() => { try { return JSON.parse($json.aiOutput).label; } catch(e) { return 'nurture'; } })() }}",
              "type": "string"
            },
            {
              "id": "s3",
              "name": "motivo",
              "value": "={{ (() => { try { return JSON.parse($json.aiOutput).motivo; } catch(e) { return ''; } })() }}",
              "type": "string"
            },
            {
              "id": "s4",
              "name": "email",
              "value": "={{ $('Normalizar lead').item.json.email }}",
              "type": "string"
            },
            {
              "id": "s5",
              "name": "name",
              "value": "={{ $('Normalizar lead').item.json.name }}",
              "type": "string"
            },
            {
              "id": "s6",
              "name": "company",
              "value": "={{ $('Normalizar lead').item.json.company }}",
              "type": "string"
            },
            {
              "id": "s7",
              "name": "scoreThreshold",
              "value": "={{ $('Normalizar lead').item.json.scoreThreshold }}",
              "type": "number"
            },
            {
              "id": "s8",
              "name": "crmUpdateUrl",
              "value": "={{ $('Normalizar lead').item.json.crmUpdateUrl }}",
              "type": "string"
            },
            {
              "id": "s9",
              "name": "slackWebhookUrl",
              "value": "={{ $('Normalizar lead').item.json.slackWebhookUrl }}",
              "type": "string"
            },
            {
              "id": "s10",
              "name": "isHigh",
              "value": "={{ (() => { try { return Number(JSON.parse($json.aiOutput).score); } catch(e) { return 0; } })() >= Number($('Normalizar lead').item.json.scoreThreshold) }}",
              "type": "boolean"
            }
          ]
        }
      }
    },
    {
      "id": "if-high",
      "name": "¿Score alto?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2100,
        300
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "if-high-cond",
              "leftValue": "={{ $json.isHigh }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        }
      }
    },
    {
      "id": "http-crm",
      "name": "CRM update cualificación",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2400,
        40
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $json.crmUpdateUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ email: $json.email, score: $json.score, label: $json.label, motivo: $json.motivo, route: 'closer' }) }}",
        "options": {
          "timeout": 30000
        }
      }
    },
    {
      "id": "http-slack",
      "name": "Slack lead cualificado",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2700,
        40
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $('Guardar score').item.json.slackWebhookUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: ':white_check_mark: *Lead cualificado* (' + $('Guardar score').item.json.label + ')\\n' + $('Guardar score').item.json.name + ' · ' + $('Guardar score').item.json.company + '\\nScore: ' + $('Guardar score').item.json.score + ' — ' + $('Guardar score').item.json.motivo }) }}",
        "options": {
          "timeout": 10000
        }
      }
    },
    {
      "id": "noop-low",
      "name": "Baja prioridad — NoOp",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        2400,
        560
      ],
      "parameters": {}
    },
    {
      "id": "ai-prep-cualificacio",
      "name": "Preparar prompt IA",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        900,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "includeOtherFields": true,
        "assignments": {
          "assignments": [
            {
              "id": "p1",
              "name": "aiPrompt",
              "value": "={{ \"Eres un qualifier B2B. Devuelve JSON {score:0-100, label:MQL|SQL|DESCARTAR, reason:string} según el lead. Español en reason.\\n\\nLead:\\n\" + JSON.stringify($json) + \"\" }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "ai-agent-cualificacio",
      "name": "Asistente IA",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [
        1200,
        300
      ],
      "parameters": {
        "promptType": "define",
        "text": "={{ $json.aiPrompt }}",
        "options": {}
      }
    },
    {
      "id": "ai-model-cualificacio",
      "name": "Modelo OpenAI",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.2,
      "position": [
        1200,
        580
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4o-mini"
        },
        "options": {}
      }
    },
    {
      "id": "ai-apply-cualificacio",
      "name": "Aplicar salida IA",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1500,
        300
      ],
      "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 lead entrante": {
      "main": [
        [
          {
            "node": "Config cualificación",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Config cualificación": {
      "main": [
        [
          {
            "node": "Normalizar lead",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalizar lead": {
      "main": [
        [
          {
            "node": "Preparar prompt IA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Guardar score": {
      "main": [
        [
          {
            "node": "¿Score alto?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿Score alto?": {
      "main": [
        [
          {
            "node": "CRM update cualificación",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Baja prioridad — NoOp",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "CRM update cualificación": {
      "main": [
        [
          {
            "node": "Slack lead cualificado",
            "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": "Guardar score",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
