{
  "name": "Logixb2b — Scoring leads con IA",
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "Webhook → Config umbrales → LLM score → IF hot → Slack + update score en CRM. Incluye Asistente IA (OpenAI) configurable."
  },
  "settings": {
    "executionOrder": "v1",
    "timezone": "Europe/Madrid"
  },
  "active": false,
  "pinData": {},
  "tags": [
    {
      "name": "Logixb2b"
    },
    {
      "name": "recursos"
    },
    {
      "name": "ia"
    },
    {
      "name": "scoring"
    }
  ],
  "nodes": [
    {
      "id": "sticky-instrucciones-logix",
      "name": "INSTRUCCIONES (conectar + VPS)",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -480,
        40
      ],
      "parameters": {
        "content": "## INSTRUCCIONES — Scoring leads con IA\n\n**Recurso:** `/recursos/lead-scoring-ia`\n**Guía:** /scoring-predictivo-leads-ia-guia-practica\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 score-lead** (`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 scoring** (`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- **Parsear score** (`Set`): sin credencial. Revisa expresiones `={{ }}` y campos de salida.\n- **¿Lead hot?** (`IF`): sin credencial. Comprueba la condición (email, umbral, over_limit, etc.) con datos reales de prueba.\n- **Slack — lead hot** (`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- **CRM — actualizar score** (`HTTP Request` CRM): Credentials → **Header Auth** / OAuth del CRM. Sustituye `crm*Url` en el nodo **Config**. Prueba con un Lead de sandbox.\n- **CRM — score (no hot)** (`HTTP Request` CRM): Credentials → **Header Auth** / OAuth del CRM. Sustituye `crm*Url` en el nodo **Config**. Prueba con un Lead de sandbox.\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": "score-webhook",
      "name": "Webhook score-lead",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        300
      ],
      "webhookId": "score-lead",
      "parameters": {
        "httpMethod": "POST",
        "path": "score-lead",
        "responseMode": "onReceived",
        "options": {}
      }
    },
    {
      "id": "score-config",
      "name": "Config scoring",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        300,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "score-c1",
              "name": "llmUrl",
              "value": "https://api.openai.com/v1/chat/completions",
              "type": "string"
            },
            {
              "id": "score-c2",
              "name": "apiKey",
              "value": "sustituye-con-tu-clave-del-modelo-ia",
              "type": "string"
            },
            {
              "id": "score-c3",
              "name": "model",
              "value": "gpt-4o-mini",
              "type": "string"
            },
            {
              "id": "score-c4",
              "name": "hotThreshold",
              "value": 75,
              "type": "number"
            },
            {
              "id": "score-c5",
              "name": "crmUpdateUrl",
              "value": "https://TU-CRM.ejemplo/api/contacts/CONTACT_ID",
              "type": "string"
            },
            {
              "id": "score-c6",
              "name": "crmApiKey",
              "value": "sustituye-con-tu-clave-del-crm",
              "type": "string"
            },
            {
              "id": "score-c7",
              "name": "slackWebhookUrl",
              "value": "https://example.com/aviso-equipo-slack",
              "type": "string"
            },
            {
              "id": "score-c8",
              "name": "scoredAt",
              "value": "={{ $now.setZone('Europe/Madrid').toFormat('yyyy-MM-dd HH:mm') }}",
              "type": "string"
            },
            {
              "id": "score-c9",
              "name": "rawBody",
              "value": "={{ $json.body || $json }}",
              "type": "object"
            }
          ]
        }
      }
    },
    {
      "id": "score-normalize",
      "name": "Normalizar lead",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        600,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "score-n1",
              "name": "email",
              "value": "={{ String($json.rawBody.email || '').trim().toLowerCase() }}",
              "type": "string"
            },
            {
              "id": "score-n2",
              "name": "name",
              "value": "={{ String($json.rawBody.name || '').trim() }}",
              "type": "string"
            },
            {
              "id": "score-n3",
              "name": "company",
              "value": "={{ String($json.rawBody.company || '').trim() }}",
              "type": "string"
            },
            {
              "id": "score-n4",
              "name": "title",
              "value": "={{ String($json.rawBody.title || $json.rawBody.cargo || '').trim() }}",
              "type": "string"
            },
            {
              "id": "score-n5",
              "name": "notes",
              "value": "={{ String($json.rawBody.notes || $json.rawBody.message || '').trim() }}",
              "type": "string"
            },
            {
              "id": "score-n6",
              "name": "contactId",
              "value": "={{ String($json.rawBody.contactId || $json.rawBody.id || '').trim() }}",
              "type": "string"
            },
            {
              "id": "score-n7",
              "name": "llmUrl",
              "value": "={{ $json.llmUrl }}",
              "type": "string"
            },
            {
              "id": "score-n8",
              "name": "apiKey",
              "value": "={{ $json.apiKey }}",
              "type": "string"
            },
            {
              "id": "score-n9",
              "name": "model",
              "value": "={{ $json.model }}",
              "type": "string"
            },
            {
              "id": "score-n10",
              "name": "hotThreshold",
              "value": "={{ $json.hotThreshold }}",
              "type": "number"
            },
            {
              "id": "score-n11",
              "name": "crmUpdateUrl",
              "value": "={{ $json.crmUpdateUrl }}",
              "type": "string"
            },
            {
              "id": "score-n12",
              "name": "crmApiKey",
              "value": "={{ $json.crmApiKey }}",
              "type": "string"
            },
            {
              "id": "score-n13",
              "name": "slackWebhookUrl",
              "value": "={{ $json.slackWebhookUrl }}",
              "type": "string"
            },
            {
              "id": "score-n14",
              "name": "scoredAt",
              "value": "={{ $json.scoredAt }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "score-parse",
      "name": "Parsear score",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1800,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "score-p1",
              "name": "llmOk",
              "value": "={{ Number($json.statusCode) >= 200 && Number($json.statusCode) < 300 }}",
              "type": "boolean"
            },
            {
              "id": "score-p2",
              "name": "rawContent",
              "value": "={{ $json.aiOutput || $json.aiOutput || '{}' }}",
              "type": "string"
            },
            {
              "id": "score-p3",
              "name": "score",
              "value": "={{ (() => { try { const t = String($json.aiOutput || '{}').replace(/```json|```/g,'').trim(); const o = JSON.parse(t); return Number(o.score) || 0; } catch(e) { return 0; } })() }}",
              "type": "number"
            },
            {
              "id": "score-p4",
              "name": "reason",
              "value": "={{ (() => { try { const t = String($json.aiOutput || '{}').replace(/```json|```/g,'').trim(); const o = JSON.parse(t); return String(o.reason || ''); } catch(e) { return 'parse-error'; } })() }}",
              "type": "string"
            },
            {
              "id": "score-p5",
              "name": "label",
              "value": "={{ (() => { try { const t = String($json.aiOutput || '{}').replace(/```json|```/g,'').trim(); const o = JSON.parse(t); return String(o.label || 'cold'); } catch(e) { return 'cold'; } })() }}",
              "type": "string"
            },
            {
              "id": "score-p6",
              "name": "isHot",
              "value": "={{ (() => { try { const t = String($json.aiOutput || '{}').replace(/```json|```/g,'').trim(); const o = JSON.parse(t); const s = Number(o.score) || 0; return s >= Number($('Normalizar lead').item.json.hotThreshold); } catch(e) { return false; } })() }}",
              "type": "boolean"
            },
            {
              "id": "score-p7",
              "name": "email",
              "value": "={{ $('Normalizar lead').item.json.email }}",
              "type": "string"
            },
            {
              "id": "score-p8",
              "name": "name",
              "value": "={{ $('Normalizar lead').item.json.name }}",
              "type": "string"
            },
            {
              "id": "score-p9",
              "name": "company",
              "value": "={{ $('Normalizar lead').item.json.company }}",
              "type": "string"
            },
            {
              "id": "score-p10",
              "name": "contactId",
              "value": "={{ $('Normalizar lead').item.json.contactId }}",
              "type": "string"
            },
            {
              "id": "score-p11",
              "name": "crmUpdateUrl",
              "value": "={{ $('Normalizar lead').item.json.crmUpdateUrl }}",
              "type": "string"
            },
            {
              "id": "score-p12",
              "name": "crmApiKey",
              "value": "={{ $('Normalizar lead').item.json.crmApiKey }}",
              "type": "string"
            },
            {
              "id": "score-p13",
              "name": "slackWebhookUrl",
              "value": "={{ $('Normalizar lead').item.json.slackWebhookUrl }}",
              "type": "string"
            },
            {
              "id": "score-p14",
              "name": "hotThreshold",
              "value": "={{ $('Normalizar lead').item.json.hotThreshold }}",
              "type": "number"
            },
            {
              "id": "score-p15",
              "name": "scoredAt",
              "value": "={{ $('Normalizar lead').item.json.scoredAt }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "score-if-hot",
      "name": "¿Lead hot?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2100,
        300
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "score-cond-hot",
              "leftValue": "={{ $json.isHot }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        }
      }
    },
    {
      "id": "score-slack",
      "name": "Slack — lead hot",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2400,
        40
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $json.slackWebhookUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: ':dart: *Lead HOT* (score ' + $json.score + ' ≥ ' + $json.hotThreshold + ')\\nNombre: ' + $json.name + '\\nEmpresa: ' + $json.company + '\\nEmail: `' + $json.email + '`\\nMotivo: ' + $json.reason + '\\nHora (Europe/Madrid): ' + $json.scoredAt }) }}",
        "options": {
          "timeout": 10000
        }
      }
    },
    {
      "id": "score-crm",
      "name": "CRM — actualizar score",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2700,
        40
      ],
      "parameters": {
        "method": "PATCH",
        "url": "={{ $('Parsear score').item.json.crmUpdateUrl.replace('CONTACT_ID', $('Parsear score').item.json.contactId || 'CONTACT_ID') }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $('Parsear score').item.json.crmApiKey }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ score: $('Parsear score').item.json.score, score_label: $('Parsear score').item.json.label, score_reason: $('Parsear score').item.json.reason, scored_at: $('Parsear score').item.json.scoredAt }) }}",
        "options": {
          "timeout": 20000,
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true
            }
          }
        }
      }
    },
    {
      "id": "score-warm",
      "name": "CRM — score (no hot)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2400,
        560
      ],
      "parameters": {
        "method": "PATCH",
        "url": "={{ $json.crmUpdateUrl.replace('CONTACT_ID', $json.contactId || 'CONTACT_ID') }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $json.crmApiKey }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ score: $json.score, score_label: $json.label, score_reason: $json.reason, scored_at: $json.scoredAt }) }}",
        "options": {
          "timeout": 20000,
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true
            }
          }
        }
      }
    },
    {
      "id": "ai-prep-lead-scoring",
      "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 modelo de scoring. Devuelve JSON {score:0-100, reason:string} del lead B2B. Español en reason.\\n\\nLead:\\n\" + JSON.stringify($json) + \"\" }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "ai-agent-lead-scoring",
      "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-lead-scoring",
      "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-lead-scoring",
      "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 score-lead": {
      "main": [
        [
          {
            "node": "Config scoring",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Config scoring": {
      "main": [
        [
          {
            "node": "Normalizar lead",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalizar lead": {
      "main": [
        [
          {
            "node": "Preparar prompt IA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parsear score": {
      "main": [
        [
          {
            "node": "¿Lead hot?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿Lead hot?": {
      "main": [
        [
          {
            "node": "Slack — lead hot",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "CRM — score (no hot)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Slack — lead hot": {
      "main": [
        [
          {
            "node": "CRM — actualizar score",
            "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 score",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
