{
  "name": "Logixb2b — Sync lead → HubSpot",
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "Webhook hubspot-lead → normaliza → busca o crea contacto HubSpot CRM v3 → Slack con enlace a la ficha."
  },
  "settings": {
    "executionOrder": "v1",
    "timezone": "Europe/Madrid"
  },
  "active": false,
  "pinData": {},
  "tags": [
    {
      "name": "Logixb2b"
    },
    {
      "name": "recursos"
    },
    {
      "name": "crm"
    },
    {
      "name": "hubspot"
    }
  ],
  "nodes": [
    {
      "id": "sticky-instrucciones-logix",
      "name": "INSTRUCCIONES (conectar + VPS)",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -480,
        40
      ],
      "parameters": {
        "content": "## INSTRUCCIONES — Sync lead → HubSpot\n\n**Recurso:** `/recursos/hubspot-lead-sync`\n**Guía:** /como-integrar-n8n-con-hubspot\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 hubspot-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 HubSpot** (`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- **HubSpot — buscar contacto** (`HTTP Request` HubSpot): Credentials → **Header Auth** `Authorization: Bearer pat-…` (Private App). Scopes contacts/deals según el flujo.\n- **¿Contacto existe?** (`IF`): sin credencial. Comprueba la condición (email, umbral, over_limit, etc.) con datos reales de prueba.\n- **Usar contacto existente** (`Set`): sin credencial. Revisa expresiones `={{ }}` y campos de salida.\n- **HubSpot — crear contacto** (`HTTP Request` HubSpot): Credentials → **Header Auth** `Authorization: Bearer pat-…` (Private App). Scopes contacts/deals según el flujo.\n- **Resultado create** (`Set`): sin credencial. Revisa expresiones `={{ }}` y campos de salida.\n- **¿API OK?** (`IF`): sin credencial. Comprueba la condición (email, umbral, over_limit, etc.) con datos reales de prueba.\n- **Slack — contacto HubSpot** (`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": "hs-webhook",
      "name": "Webhook hubspot-lead",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        560
      ],
      "webhookId": "hubspot-lead",
      "parameters": {
        "httpMethod": "POST",
        "path": "hubspot-lead",
        "responseMode": "onReceived",
        "options": {}
      }
    },
    {
      "id": "hs-config",
      "name": "Config HubSpot",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        300,
        560
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "hs-c1",
              "name": "portalId",
              "value": "TU_PORTAL_ID",
              "type": "string"
            },
            {
              "id": "hs-c2",
              "name": "hubspotToken",
              "value": "sustituye-con-tu-clave-de-hubspot",
              "type": "string"
            },
            {
              "id": "hs-c3",
              "name": "slackWebhookUrl",
              "value": "https://example.com/aviso-equipo-slack",
              "type": "string"
            },
            {
              "id": "hs-c4",
              "name": "contactBaseUrl",
              "value": "https://app.hubspot.com/contacts/TU_PORTAL_ID/record/0-1/",
              "type": "string"
            },
            {
              "id": "hs-c5",
              "name": "receivedAt",
              "value": "={{ $now.setZone('Europe/Madrid').toFormat('yyyy-MM-dd HH:mm') }}",
              "type": "string"
            },
            {
              "id": "hs-c6",
              "name": "rawBody",
              "value": "={{ $json.body || $json }}",
              "type": "object"
            }
          ]
        }
      }
    },
    {
      "id": "hs-normalize",
      "name": "Normalizar lead",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        600,
        560
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "hs-n1",
              "name": "email",
              "value": "={{ String($json.rawBody.email || $json.rawBody.Email || '').trim().toLowerCase() }}",
              "type": "string"
            },
            {
              "id": "hs-n2",
              "name": "firstname",
              "value": "={{ String($json.rawBody.firstname || $json.rawBody.name || $json.rawBody.nombre || '').trim() }}",
              "type": "string"
            },
            {
              "id": "hs-n3",
              "name": "company",
              "value": "={{ String($json.rawBody.company || $json.rawBody.empresa || '').trim() }}",
              "type": "string"
            },
            {
              "id": "hs-n4",
              "name": "source",
              "value": "={{ String($json.rawBody.source || $json.rawBody.origen || 'webhook-n8n').trim() }}",
              "type": "string"
            },
            {
              "id": "hs-n5",
              "name": "portalId",
              "value": "={{ $json.portalId }}",
              "type": "string"
            },
            {
              "id": "hs-n6",
              "name": "hubspotToken",
              "value": "={{ $json.hubspotToken }}",
              "type": "string"
            },
            {
              "id": "hs-n7",
              "name": "slackWebhookUrl",
              "value": "={{ $json.slackWebhookUrl }}",
              "type": "string"
            },
            {
              "id": "hs-n8",
              "name": "contactBaseUrl",
              "value": "={{ $json.contactBaseUrl }}",
              "type": "string"
            },
            {
              "id": "hs-n9",
              "name": "receivedAt",
              "value": "={{ $json.receivedAt }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "hs-search",
      "name": "HubSpot — buscar contacto",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        900,
        560
      ],
      "parameters": {
        "method": "POST",
        "url": "https://api.hubapi.com/crm/v3/objects/contacts/search",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $json.hubspotToken }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ filterGroups: [{ filters: [{ propertyName: 'email', operator: 'EQ', value: $json.email }] }], properties: ['email', 'firstname', 'company'], limit: 1 }) }}",
        "options": {
          "timeout": 20000,
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true
            }
          }
        }
      }
    },
    {
      "id": "hs-if-found",
      "name": "¿Contacto existe?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1200,
        560
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "hs-cond-found",
              "leftValue": "={{ Number($json.body?.total || 0) > 0 || (Array.isArray($json.body?.results) && $json.body.results.length > 0) }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        }
      }
    },
    {
      "id": "hs-use-existing",
      "name": "Usar contacto existente",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1500,
        300
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "hs-e1",
              "name": "contactId",
              "value": "={{ $json.body.results[0].id }}",
              "type": "string"
            },
            {
              "id": "hs-e2",
              "name": "action",
              "value": "found",
              "type": "string"
            },
            {
              "id": "hs-e3",
              "name": "apiOk",
              "value": "={{ Number($json.statusCode) >= 200 && Number($json.statusCode) < 300 }}",
              "type": "boolean"
            },
            {
              "id": "hs-e4",
              "name": "statusCode",
              "value": "={{ $json.statusCode }}",
              "type": "number"
            },
            {
              "id": "hs-e5",
              "name": "email",
              "value": "={{ $('Normalizar lead').item.json.email }}",
              "type": "string"
            },
            {
              "id": "hs-e6",
              "name": "firstname",
              "value": "={{ $('Normalizar lead').item.json.firstname }}",
              "type": "string"
            },
            {
              "id": "hs-e7",
              "name": "company",
              "value": "={{ $('Normalizar lead').item.json.company }}",
              "type": "string"
            },
            {
              "id": "hs-e8",
              "name": "source",
              "value": "={{ $('Normalizar lead').item.json.source }}",
              "type": "string"
            },
            {
              "id": "hs-e9",
              "name": "slackWebhookUrl",
              "value": "={{ $('Normalizar lead').item.json.slackWebhookUrl }}",
              "type": "string"
            },
            {
              "id": "hs-e10",
              "name": "contactBaseUrl",
              "value": "={{ $('Normalizar lead').item.json.contactBaseUrl }}",
              "type": "string"
            },
            {
              "id": "hs-e11",
              "name": "receivedAt",
              "value": "={{ $('Normalizar lead').item.json.receivedAt }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "hs-create",
      "name": "HubSpot — crear contacto",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1500,
        820
      ],
      "parameters": {
        "method": "POST",
        "url": "https://api.hubapi.com/crm/v3/objects/contacts",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $('Normalizar lead').item.json.hubspotToken }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ properties: { email: $('Normalizar lead').item.json.email, firstname: $('Normalizar lead').item.json.firstname, company: $('Normalizar lead').item.json.company, hs_lead_status: 'NEW', lifecyclestage: 'lead' } }) }}",
        "options": {
          "timeout": 20000,
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true
            }
          }
        }
      }
    },
    {
      "id": "hs-after-create",
      "name": "Resultado create",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1800,
        820
      ],
      "parameters": {
        "mode": "manual",
        "duplicateItem": false,
        "assignments": {
          "assignments": [
            {
              "id": "hs-r1",
              "name": "contactId",
              "value": "={{ $json.body?.id || '' }}",
              "type": "string"
            },
            {
              "id": "hs-r2",
              "name": "action",
              "value": "created",
              "type": "string"
            },
            {
              "id": "hs-r3",
              "name": "apiOk",
              "value": "={{ Number($json.statusCode) >= 200 && Number($json.statusCode) < 300 }}",
              "type": "boolean"
            },
            {
              "id": "hs-r4",
              "name": "statusCode",
              "value": "={{ $json.statusCode }}",
              "type": "number"
            },
            {
              "id": "hs-r5",
              "name": "email",
              "value": "={{ $('Normalizar lead').item.json.email }}",
              "type": "string"
            },
            {
              "id": "hs-r6",
              "name": "firstname",
              "value": "={{ $('Normalizar lead').item.json.firstname }}",
              "type": "string"
            },
            {
              "id": "hs-r7",
              "name": "company",
              "value": "={{ $('Normalizar lead').item.json.company }}",
              "type": "string"
            },
            {
              "id": "hs-r8",
              "name": "source",
              "value": "={{ $('Normalizar lead').item.json.source }}",
              "type": "string"
            },
            {
              "id": "hs-r9",
              "name": "slackWebhookUrl",
              "value": "={{ $('Normalizar lead').item.json.slackWebhookUrl }}",
              "type": "string"
            },
            {
              "id": "hs-r10",
              "name": "contactBaseUrl",
              "value": "={{ $('Normalizar lead').item.json.contactBaseUrl }}",
              "type": "string"
            },
            {
              "id": "hs-r11",
              "name": "receivedAt",
              "value": "={{ $('Normalizar lead').item.json.receivedAt }}",
              "type": "string"
            }
          ]
        }
      }
    },
    {
      "id": "hs-if-ok",
      "name": "¿API OK?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2100,
        300
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "hs-cond-ok",
              "leftValue": "={{ $json.apiOk === true && !!$json.contactId }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        }
      }
    },
    {
      "id": "hs-slack",
      "name": "Slack — contacto HubSpot",
      "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: $json.slackText || 'Actualización Logixb2b' }) }}",
        "options": {
          "timeout": 10000
        }
      }
    },
    {
      "id": "hs-fail",
      "name": "Fallo API — sin Slack",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        2400,
        560
      ],
      "parameters": {}
    }
  ],
  "connections": {
    "Webhook hubspot-lead": {
      "main": [
        [
          {
            "node": "Config HubSpot",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Config HubSpot": {
      "main": [
        [
          {
            "node": "Normalizar lead",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalizar lead": {
      "main": [
        [
          {
            "node": "HubSpot — buscar contacto",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HubSpot — buscar contacto": {
      "main": [
        [
          {
            "node": "¿Contacto existe?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿Contacto existe?": {
      "main": [
        [
          {
            "node": "Usar contacto existente",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "HubSpot — crear contacto",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Usar contacto existente": {
      "main": [
        [
          {
            "node": "¿API OK?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HubSpot — crear contacto": {
      "main": [
        [
          {
            "node": "Resultado create",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Resultado create": {
      "main": [
        [
          {
            "node": "¿API OK?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿API OK?": {
      "main": [
        [
          {
            "node": "Slack — contacto HubSpot",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Fallo API — sin Slack",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
