{
  "name": "Logixb2b — Clay al CRM (enriquecer + cualificar Leads)",
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "Manual Trigger → Config Clay/CRM → Payload de prueba (3 leads Clay) → Normalizar + qualifyScore → IF cualificado → Upsert Lead HubSpot/Pipedrive → Append Sheets → Slack resumen. Europe/Madrid. Placeholders de credenciales."
  },
  "settings": {
    "executionOrder": "v1",
    "timezone": "Europe/Madrid"
  },
  "active": false,
  "pinData": {},
  "tags": [
    {
      "name": "Logixb2b"
    },
    {
      "name": "recursos"
    },
    {
      "name": "prospeccion"
    }
  ],
  "nodes": [
    {
      "id": "sticky-instrucciones-logix",
      "name": "INSTRUCCIONES (conectar + VPS)",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -480,
        40
      ],
      "parameters": {
        "content": "## INSTRUCCIONES — Clay al CRM (enriquecer + cualificar Leads)\n\n**Recurso:** `/recursos/clay-enriquecer-leads-crm-n8n`\n**Guía:** /como-usar-clay-enriquecer-leads-automaticamente\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- **Manual Trigger clay** (`manual`): sin credencial. Úsalo para pruebas; en producción sustituye por Webhook o Schedule si quieres automatismo.\n- **Config Clay/CRM** (`Set` Config): **no lleva credencial**. Aquí van URLs/placeholders (`REEMPLAZA_*`, `example.com`, `TU-CRM`). Sustituye todos antes de Active.\n- **Payload de prueba (sample Clay)** (`Code`): sin credencial. Revisa límites/umbrales en el JS; no hardcodees secretos.\n- **Normalizar leads + qualifyScore** (`Code`): sin credencial. Revisa límites/umbrales en el JS; no hardcodees secretos.\n- **IF lead cualificado** (`IF`): sin credencial. Comprueba la condición (email, umbral, over_limit, etc.) con datos reales de prueba.\n- **Upsert Lead CRM (HubSpot/Pipedrive)** (`HTTP Request` HubSpot): Credentials → **Header Auth** `Authorization: Bearer pat-…` (Private App). Scopes contacts/deals según el flujo.\n- **Append log Clay Sheets** (`Google Sheets`): Credentials → **Google Sheets OAuth2**. Sustituye Spreadsheet ID / Sheet name. Comparte la hoja con la cuenta OAuth.\n- **Slack resumen Clay** (`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\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": "clay-trigger",
      "name": "Manual Trigger clay",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        340
      ],
      "parameters": {}
    },
    {
      "id": "clay-config",
      "name": "Config Clay/CRM",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        260,
        340
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "c1",
              "name": "crmProvider",
              "value": "hubspot",
              "type": "string"
            },
            {
              "id": "c2",
              "name": "crmBaseUrl",
              "value": "https://api.hubapi.com",
              "type": "string"
            },
            {
              "id": "c3",
              "name": "crmToken",
              "value": "REEMPLAZA_HUBSPOT_TOKEN",
              "type": "string"
            },
            {
              "id": "c4",
              "name": "pipedriveBaseUrl",
              "value": "https://REEMPLAZA_TU_EMPRESA.pipedrive.com/api/v1",
              "type": "string"
            },
            {
              "id": "c5",
              "name": "pipedriveApiToken",
              "value": "REEMPLAZA_PIPEDRIVE_API_TOKEN",
              "type": "string"
            },
            {
              "id": "c6",
              "name": "icpKeywords",
              "value": "ventas,comercial,revops,marketing,fundador,ceo,cto,head of sales",
              "type": "string"
            },
            {
              "id": "c7",
              "name": "requireVerifiedEmail",
              "value": "true",
              "type": "string"
            },
            {
              "id": "c8",
              "name": "qualifyThreshold",
              "value": "50",
              "type": "string"
            },
            {
              "id": "c9",
              "name": "sheetsId",
              "value": "REEMPLAZA_SHEETS_ID_OPCIONAL",
              "type": "string"
            },
            {
              "id": "c10",
              "name": "slackWebhookUrl",
              "value": "",
              "type": "string"
            },
            {
              "id": "c11",
              "name": "batchLabel",
              "value": "clay-leads-2026",
              "type": "string"
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "clay-sample",
      "name": "Payload de prueba (sample Clay)",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        540,
        340
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const cfg = $('Config Clay/CRM').first().json;\nconst sample = [\n  { company: 'Nortia Soluciones SL', firstName: 'Elena', lastName: 'Campos', email: 'elena.campos@nortia-example.es', title: 'Directora Comercial', country: 'España', phone: '+34611222333', emailVerified: true, phoneFound: true, emailProvider: 'proveedor-a' },\n  { company: 'Bright Data Labs SL', firstName: 'Marc', lastName: 'Soler', email: 'marc.soler@brightdata-example.es', title: 'Becario de Marketing', country: 'España', phone: '', emailVerified: false, phoneFound: false, emailProvider: '' },\n  { company: 'Vertice Industrial SA', firstName: 'Sonia', lastName: 'Ibáñez', email: 'sonia.ibanez@vertice-example.es', title: 'Head of Revenue Operations', country: 'España', phone: '+34699888777', emailVerified: true, phoneFound: true, emailProvider: 'proveedor-b' }\n];\nreturn sample.map((p) => ({ json: { ...p, crmProvider: cfg.crmProvider } }));"
      }
    },
    {
      "id": "clay-normalize",
      "name": "Normalizar leads + qualifyScore",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        800,
        340
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "language": "javaScript",
        "jsCode": "const cfg = $('Config Clay/CRM').first().json;\nconst icp = (cfg.icpKeywords || '').split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);\nconst euCountries = ['españa', 'spain', 'francia', 'france', 'alemania', 'germany', 'italia', 'italy', 'portugal', 'países bajos', 'netherlands'];\n\nconst p = item.json || {};\nconst email = (p.email || '').toLowerCase().trim();\nconst emailOk = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email);\nconst emailVerified = p.emailVerified === true || p.emailVerified === 'true';\nconst phone = (p.phone || '').trim();\nconst phoneFound = phone.length >= 8;\nconst title = (p.title || '').toLowerCase();\nconst icpMatch = icp.some((k) => title.includes(k));\nconst country = (p.country || '').toLowerCase();\nconst isEu = euCountries.includes(country);\n\nlet score = 0;\nif (emailOk) score += 20;\nif (emailVerified) score += 30;\nif (phoneFound) score += 20;\nif (icpMatch) score += 20;\nif (isEu) score += 10;\nscore = Math.max(0, Math.min(100, score));\n\nconst requireVerified = String(cfg.requireVerifiedEmail) === 'true';\nconst qualified = emailOk && score >= Number(cfg.qualifyThreshold || 50) && (!requireVerified || emailVerified);\nconst complianceFlag = isEu ? 'ok_ue_minimizar_datos' : 'revisar_base_juridica_extra_ue';\n\nreturn {\n  json: {\n    batchLabel: cfg.batchLabel,\n    crmProvider: cfg.crmProvider,\n    crmBaseUrl: cfg.crmBaseUrl,\n    crmToken: cfg.crmToken,\n    pipedriveBaseUrl: cfg.pipedriveBaseUrl,\n    pipedriveApiToken: cfg.pipedriveApiToken,\n    sheetsId: cfg.sheetsId,\n    slackWebhookUrl: cfg.slackWebhookUrl,\n    firstName: p.firstName || '',\n    lastName: p.lastName || '',\n    email,\n    emailOk,\n    emailVerified,\n    phone,\n    phoneFound,\n    title: p.title || '',\n    company: p.company || '',\n    country: p.country || '',\n    emailProvider: p.emailProvider || '',\n    icpMatch,\n    qualifyScore: score,\n    qualified,\n    complianceFlag\n  }\n};"
      }
    },
    {
      "id": "clay-if",
      "name": "IF lead cualificado",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1060,
        340
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "cd1",
              "leftValue": "={{ $json.qualified }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        }
      }
    },
    {
      "id": "clay-upsert",
      "name": "Upsert Lead CRM (HubSpot/Pipedrive)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1340,
        220
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $json.crmProvider === 'pipedrive' ? ($json.pipedriveBaseUrl + '/persons?api_token=' + $json.pipedriveApiToken) : ($json.crmBaseUrl + '/crm/v3/objects/contacts/batch/upsert') }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "={{ $json.crmProvider === 'pipedrive' ? '' : 'Bearer ' + $json.crmToken }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.crmProvider === 'pipedrive' ? { name: ($json.firstName + ' ' + $json.lastName).trim(), email: [{ value: $json.email, primary: true }], phone: $json.phone ? [{ value: $json.phone, primary: true }] : [], org_name: $json.company } : { inputs: [{ idProperty: 'email', id: $json.email, properties: { email: $json.email, firstname: $json.firstName, lastname: $json.lastName, phone: $json.phone, company: $json.company, jobtitle: $json.title, lead_source_provider: 'clay', clay_qualify_score: String($json.qualifyScore) } }] }) }}",
        "options": {
          "timeout": 30000
        }
      }
    },
    {
      "id": "clay-sheets",
      "name": "Append log Clay Sheets",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1620,
        220
      ],
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "={{ $('Config Clay/CRM').item.json.sheetsId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Clay",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "fecha": "={{ $now.setZone('Europe/Madrid').toFormat('yyyy-MM-dd HH:mm') }}",
            "batchLabel": "={{ $('Normalizar leads + qualifyScore').item.json.batchLabel }}",
            "company": "={{ $('Normalizar leads + qualifyScore').item.json.company }}",
            "email": "={{ $('Normalizar leads + qualifyScore').item.json.email }}",
            "qualifyScore": "={{ $('Normalizar leads + qualifyScore').item.json.qualifyScore }}",
            "complianceFlag": "={{ $('Normalizar leads + qualifyScore').item.json.complianceFlag }}",
            "crmProvider": "={{ $('Normalizar leads + qualifyScore').item.json.crmProvider }}",
            "estado": "upsert_ok"
          }
        },
        "options": {}
      }
    },
    {
      "id": "clay-slack",
      "name": "Slack resumen Clay",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1900,
        220
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $('Normalizar leads + qualifyScore').item.json.slackWebhookUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: 'Clay ' + $('Config Clay/CRM').item.json.batchLabel + ': ' + $('Normalizar leads + qualifyScore').item.json.company + ' (' + $('Normalizar leads + qualifyScore').item.json.email + ') score ' + $('Normalizar leads + qualifyScore').item.json.qualifyScore + ' → upsert ' + $('Normalizar leads + qualifyScore').item.json.crmProvider + '. Compliance: ' + $('Normalizar leads + qualifyScore').item.json.complianceFlag + '.' }) }}",
        "options": {
          "timeout": 15000,
          "response": {
            "response": {
              "neverError": true
            }
          }
        }
      }
    },
    {
      "id": "clay-skip",
      "name": "Skip lead no cualificado",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        1340,
        460
      ],
      "parameters": {}
    }
  ],
  "connections": {
    "Manual Trigger clay": {
      "main": [
        [
          {
            "node": "Config Clay/CRM",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Config Clay/CRM": {
      "main": [
        [
          {
            "node": "Payload de prueba (sample Clay)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Payload de prueba (sample Clay)": {
      "main": [
        [
          {
            "node": "Normalizar leads + qualifyScore",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalizar leads + qualifyScore": {
      "main": [
        [
          {
            "node": "IF lead cualificado",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IF lead cualificado": {
      "main": [
        [
          {
            "node": "Upsert Lead CRM (HubSpot/Pipedrive)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Skip lead no cualificado",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upsert Lead CRM (HubSpot/Pipedrive)": {
      "main": [
        [
          {
            "node": "Append log Clay Sheets",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Append log Clay Sheets": {
      "main": [
        [
          {
            "node": "Slack resumen Clay",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
