{
  "name": "Calificación de leads entrantes (plano de Saphia Labs)",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "leads",
        "responseMode": "onReceived",
        "options": {}
      },
      "id": "wh",
      "name": "Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        0
      ],
      "webhookId": "saphia-leads"
    },
    {
      "parameters": {
        "jsCode": "const b = $json.body || $json;\nconst correo = String(b.correo || b.email || '').trim().toLowerCase();\nconst dominio = correo.split('@')[1] || '';\nconst gratuito = /gmail|hotmail|outlook|yahoo|icloud|live\\./.test(dominio);\nreturn [{ json: { nombre: b.nombre || '', correo, empresa: b.empresa || '', mensaje: b.mensaje || '', dominio, gratuito, url: dominio && !gratuito ? 'https://' + dominio : '' } }];"
      },
      "id": "dom",
      "name": "Code: dominio",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        260,
        0
      ]
    },
    {
      "parameters": {
        "url": "={{ $json.url || 'https://example.invalid' }}",
        "options": {
          "timeout": 15000,
          "response": {
            "response": {
              "responseFormat": "text"
            }
          }
        }
      },
      "id": "http",
      "name": "HTTP: sitio de la empresa",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        520,
        0
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "const lead = $('Code: dominio').first().json;\nconst html = typeof $json.data === 'string' ? $json.data : '';\nconst texto = html.replace(/<script[\\s\\S]*?<\\/script>/gi, ' ').replace(/<style[\\s\\S]*?<\\/style>/gi, ' ').replace(/<[^>]+>/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, 3000);\nreturn [{ json: { ...lead, sitio: texto || '(sin texto del sitio)' } }];"
      },
      "id": "clean",
      "name": "Code: texto del sitio",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        780,
        0
      ]
    },
    {
      "parameters": {
        "resource": "text",
        "operation": "message",
        "modelId": {
          "__rl": true,
          "mode": "list",
          "value": "claude-sonnet-5-5"
        },
        "messages": {
          "values": [
            {
              "role": "user",
              "content": "={{ 'LEAD\\nNombre: ' + $json.nombre + '\\nCorreo: ' + $json.correo + '\\nEmpresa: ' + $json.empresa + '\\nMensaje: ' + $json.mensaje + '\\n\\nTEXTO DEL SITIO (' + $json.dominio + ')\\n' + $json.sitio }}"
            }
          ]
        },
        "options": {
          "system": "Eres analista comercial de [organización]. Nuestro cliente ideal: [describe: sector, tamaño, país, problema que resolvemos, presupuesto típico]. Recibes un lead (nombre, correo, empresa, mensaje) y el texto de la página web de su empresa. Devuelve SOLO un JSON:\n{\"puntaje\": 0, \"justificacion\": \"2 frases con los datos que pesaron\", \"senales\": [\"...\"], \"riesgos\": [\"...\"], \"siguiente_paso\": \"llamada hoy | correo con propuesta | respuesta cortés | descartar\"}\nReglas: puntúa por encaje con el perfil, no por tamaño de la empresa; un mensaje concreto sobre nuestro problema vale más que un dominio corporativo; si no hay texto del sitio, puntúa solo con el mensaje y dilo en riesgos; nunca inventes datos de la empresa.",
          "maxTokens": 4000
        }
      },
      "id": "cl",
      "name": "Claude: puntuar lead",
      "type": "@n8n/n8n-nodes-langchain.anthropic",
      "typeVersion": 1,
      "position": [
        1040,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "const texto = ($json.content || []).filter(b => b.type === 'text').map(b => b.text).join('\\n').trim();\nconst limpio = texto.replace(/^```(?:json)?\\s*/i, '').replace(/```\\s*$/, '');\nlet r; try { r = JSON.parse(limpio); } catch (e) { r = { error: texto.slice(0, 300) }; }\nconst l = $('Code: texto del sitio').first().json;\nreturn [{ json: { fecha: $now.toISO(), nombre: l.nombre, correo: l.correo, empresa: l.empresa, dominio: l.dominio, puntaje: Number(r.puntaje) || 0, justificacion: r.justificacion || r.error || '', siguiente_paso: r.siguiente_paso || '', senales: (r.senales||[]).join(' | '), riesgos: (r.riesgos||[]).join(' | ') } }];"
      },
      "id": "parse",
      "name": "Code: leer puntaje",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1300,
        0
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "TU_SPREADSHEET_ID"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "leads"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "fecha": "={{ $json.fecha }}",
            "nombre": "={{ $json.nombre }}",
            "correo": "={{ $json.correo }}",
            "empresa": "={{ $json.empresa }}",
            "dominio": "={{ $json.dominio }}",
            "puntaje": "={{ $json.puntaje }}",
            "justificacion": "={{ $json.justificacion }}",
            "siguiente_paso": "={{ $json.siguiente_paso }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "fecha",
              "displayName": "fecha",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "nombre",
              "displayName": "nombre",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "correo",
              "displayName": "correo",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "empresa",
              "displayName": "empresa",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "dominio",
              "displayName": "dominio",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "puntaje",
              "displayName": "puntaje",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "justificacion",
              "displayName": "justificacion",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "siguiente_paso",
              "displayName": "siguiente_paso",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            }
          ]
        },
        "options": {}
      },
      "id": "sh",
      "name": "Sheets: registrar lead",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1560,
        0
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "loose",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "a",
                    "leftValue": "={{ $json.puntaje }}",
                    "rightValue": 70,
                    "operator": {
                      "type": "number",
                      "operation": "gte"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "caliente"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "loose",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "b",
                    "leftValue": "={{ $json.puntaje }}",
                    "rightValue": 40,
                    "operator": {
                      "type": "number",
                      "operation": "lt"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "frio"
            }
          ]
        },
        "options": {
          "fallbackOutput": "extra"
        }
      },
      "id": "sw",
      "name": "Switch: por puntaje",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        1820,
        0
      ]
    },
    {
      "parameters": {
        "chatId": "TU_CHAT_ID",
        "text": "=🔥 Lead calificado ({{ $json.puntaje }}/100): {{ $json.nombre }} · {{ $json.empresa || $json.dominio }}\n{{ $json.justificacion }}\nSiguiente paso: {{ $json.siguiente_paso }}",
        "additionalFields": {
          "appendAttribution": false
        }
      },
      "id": "tg",
      "name": "Telegram: alerta a ventas",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        2080,
        -120
      ]
    },
    {
      "parameters": {
        "resource": "draft",
        "subject": "Gracias por escribirnos",
        "emailType": "text",
        "message": "=Hola {{ $json.nombre.split(' ')[0] }},\n\nGracias por escribirnos. Por lo que nos cuentas, lo que necesitas no es lo que hacemos en Saphia Labs: trabajamos con empresas y colegios que quieren adoptar IA en su operación. Te deseamos mucho éxito con tu proyecto.\n\nUn saludo,\nEquipo Saphia Labs",
        "options": {
          "sendTo": "={{ $json.correo }}"
        }
      },
      "id": "gm",
      "name": "Gmail: borrador cortés",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        2080,
        140
      ]
    }
  ],
  "connections": {
    "Webhook": {
      "main": [
        [
          {
            "node": "Code: dominio",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code: dominio": {
      "main": [
        [
          {
            "node": "HTTP: sitio de la empresa",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HTTP: sitio de la empresa": {
      "main": [
        [
          {
            "node": "Code: texto del sitio",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code: texto del sitio": {
      "main": [
        [
          {
            "node": "Claude: puntuar lead",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Claude: puntuar lead": {
      "main": [
        [
          {
            "node": "Code: leer puntaje",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code: leer puntaje": {
      "main": [
        [
          {
            "node": "Sheets: registrar lead",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sheets: registrar lead": {
      "main": [
        [
          {
            "node": "Switch: por puntaje",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Switch: por puntaje": {
      "main": [
        [
          {
            "node": "Telegram: alerta a ventas",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Gmail: borrador cortés",
            "type": "main",
            "index": 0
          }
        ],
        []
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "timezone": "America/Bogota"
  },
  "meta": {
    "templateCredsSetupCompleted": false,
    "probadoEn": "n8n 2.41.6, octubre 2026",
    "preparacion": "Apunta el formulario de tu sitio al webhook (POST con nombre, correo, empresa, mensaje). Describe tu cliente ideal en el prompt del nodo de Anthropic. Crea una pestaña \"leads\" con encabezado fecha, nombre, correo, empresa, dominio, puntaje, justificacion, siguiente_paso, o reemplaza el nodo de Sheets por tu CRM. Reemplaza TU_SPREADSHEET_ID y TU_CHAT_ID.",
    "fuente": "https://saphialabs.com/recursos/flujos/#f5"
  }
}