{
  "name": "Gestione lead sito con AI, CRM e follow-up",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "gestione-lead-sito",
        "responseMode": "responseNode",
        "options": {
          "allowedOrigins": "https://andreabaglioni.it,https://www.andreabaglioni.it",
          "ignoreBots": true
        }
      },
      "id": "lead-webhook",
      "name": "Webhook Lead Sito",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [120, 220],
      "webhookId": "lead-sito-ai"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            { "id": "nome", "name": "nome", "type": "string", "value": "={{ $json.body.name || $json.body.nome || '' }}" },
            { "id": "email", "name": "email", "type": "string", "value": "={{ $json.body.email || '' }}" },
            { "id": "telefono", "name": "telefono", "type": "string", "value": "={{ $json.body.phone || $json.body.telefono || '' }}" },
            { "id": "azienda", "name": "azienda", "type": "string", "value": "={{ $json.body.company || $json.body.azienda || '' }}" },
            { "id": "servizio", "name": "servizio", "type": "string", "value": "={{ $json.body.service || $json.body.servizio || 'audit-ai' }}" },
            { "id": "messaggio", "name": "messaggio", "type": "string", "value": "={{ $json.body.message || $json.body.process || $json.body.messaggio || '' }}" },
            { "id": "fonte", "name": "fonte", "type": "string", "value": "={{ $json.body.source || $headers.referer || 'sito' }}" },
            { "id": "consenso_privacy", "name": "consenso_privacy", "type": "boolean", "value": "={{ Boolean($json.body.privacy || $json.body.consent || true) }}" }
          ]
        },
        "options": {}
      },
      "id": "normalizza-lead",
      "name": "Normalizza dati lead",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [360, 220]
    },
    {
      "parameters": {
        "jsCode": "const lead = $input.first().json;\nconst testo = `${lead.servizio} ${lead.messaggio}`.toLowerCase();\nlet score = 40;\nif (lead.email) score += 10;\nif (lead.telefono) score += 10;\nif (lead.azienda) score += 10;\nif (/crm|n8n|whatsapp|automazione|software|gestionale|api|dashboard/.test(testo)) score += 20;\nif (/urgente|subito|entro|preventivo|call|budget/.test(testo)) score += 10;\nconst priorita = score >= 80 ? 'alta' : score >= 60 ? 'media' : 'bassa';\nreturn [{ json: { ...lead, score, priorita, ricevuto_il: new Date().toISOString() } }];"
      },
      "id": "calcola-score",
      "name": "Calcola score e priorita",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [600, 220]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.openai.com/v1/chat/completions",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            { "name": "Content-Type", "value": "application/json" }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"model\": \"gpt-4o-mini\",\n  \"messages\": [\n    { \"role\": \"system\", \"content\": \"Sei un assistente commerciale B2B. Qualifica lead per automazioni AI, n8n, CRM, WhatsApp AI e software su misura. Rispondi in JSON con sintesi, bisogno, prossima_azione, rischio, domande_da_fare.\" },\n    { \"role\": \"user\", \"content\": \"Lead: \" + JSON.stringify($json) }\n  ],\n  \"temperature\": 0.2\n}",
        "options": {
          "timeout": 15000
        }
      },
      "id": "qualifica-ai",
      "name": "Qualifica lead con AI",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [840, 220],
      "notes": "OpenAI: crea una credenziale HTTP Header Auth con Authorization: Bearer {{$env.OPENAI_API_KEY}}. In alternativa disattiva questo nodo e usa solo lo scoring locale."
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $env.CRM_LEADS_ENDPOINT || 'https://example.com/api/leads' }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            { "name": "Content-Type", "value": "application/json" },
            { "name": "X-API-Key", "value": "={{ $env.CRM_API_KEY || 'INSERISCI_API_KEY' }}" }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"nome\": $('Calcola score e priorita').first().json.nome,\n  \"email\": $('Calcola score e priorita').first().json.email,\n  \"telefono\": $('Calcola score e priorita').first().json.telefono,\n  \"azienda\": $('Calcola score e priorita').first().json.azienda,\n  \"servizio\": $('Calcola score e priorita').first().json.servizio,\n  \"messaggio\": $('Calcola score e priorita').first().json.messaggio,\n  \"score\": $('Calcola score e priorita').first().json.score,\n  \"priorita\": $('Calcola score e priorita').first().json.priorita,\n  \"ai_raw\": $json\n}",
        "options": {
          "timeout": 10000
        }
      },
      "id": "salva-crm",
      "name": "Salva su CRM",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [1080, 220],
      "notes": "Sostituisci CRM_LEADS_ENDPOINT con endpoint del CRM o gestionale. Non inserire segreti nel workflow esportato."
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "priorita-alta",
              "leftValue": "={{ $('Calcola score e priorita').first().json.priorita }}",
              "rightValue": "alta",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "lead-alta-priorita",
      "name": "Lead ad alta priorita?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [1320, 220]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $env.TEAM_WEBHOOK_URL || 'https://example.com/team-webhook' }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"text\": \"Nuovo lead \" + $('Calcola score e priorita').first().json.priorita + \" - \" + $('Calcola score e priorita').first().json.servizio,\n  \"lead\": $('Calcola score e priorita').first().json,\n  \"crm_response\": $('Salva su CRM').first().json\n}",
        "options": {}
      },
      "id": "notifica-team",
      "name": "Notifica team",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [1560, 120]
    },
    {
      "parameters": {
        "fromEmail": "={{ $env.MAIL_FROM || 'info@azienda.it' }}",
        "toEmail": "={{ $('Calcola score e priorita').first().json.email }}",
        "subject": "Abbiamo ricevuto la tua richiesta",
        "emailType": "text",
        "message": "=Ciao {{$('Calcola score e priorita').first().json.nome || ' '}},\n\nabbiamo ricevuto la tua richiesta su {{$('Calcola score e priorita').first().json.servizio}}.\n\nTi ricontatteremo con una prima valutazione. Se vuoi accelerare, rispondi a questa email indicando:\n- processo da automatizzare\n- strumenti usati oggi\n- urgenza\n\nA presto."
      },
      "id": "risposta-lead",
      "name": "Risposta automatica al lead",
      "type": "n8n-nodes-base.emailSend",
      "typeVersion": 2.1,
      "position": [1560, 340],
      "notes": "Configura credenziale SMTP in n8n. Per GDPR evita di includere dati sensibili non necessari."
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={ \"ok\": true, \"message\": \"Lead ricevuto\", \"priorita\": $('Calcola score e priorita').first().json.priorita }",
        "options": {
          "responseCode": 200
        }
      },
      "id": "rispondi-webhook",
      "name": "Rispondi al sito",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [1800, 220]
    }
  ],
  "connections": {
    "Webhook Lead Sito": {
      "main": [[{ "node": "Normalizza dati lead", "type": "main", "index": 0 }]]
    },
    "Normalizza dati lead": {
      "main": [[{ "node": "Calcola score e priorita", "type": "main", "index": 0 }]]
    },
    "Calcola score e priorita": {
      "main": [[{ "node": "Qualifica lead con AI", "type": "main", "index": 0 }]]
    },
    "Qualifica lead con AI": {
      "main": [[{ "node": "Salva su CRM", "type": "main", "index": 0 }]]
    },
    "Salva su CRM": {
      "main": [[{ "node": "Lead ad alta priorita?", "type": "main", "index": 0 }]]
    },
    "Lead ad alta priorita?": {
      "main": [
        [{ "node": "Notifica team", "type": "main", "index": 0 }],
        [{ "node": "Risposta automatica al lead", "type": "main", "index": 0 }]
      ]
    },
    "Notifica team": {
      "main": [[{ "node": "Risposta automatica al lead", "type": "main", "index": 0 }]]
    },
    "Risposta automatica al lead": {
      "main": [[{ "node": "Rispondi al sito", "type": "main", "index": 0 }]]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1",
    "saveDataSuccessExecution": "all",
    "saveDataErrorExecution": "all",
    "timezone": "Europe/Rome"
  },
  "staticData": null,
  "tags": [
    { "name": "lead-generation" },
    { "name": "ai" },
    { "name": "crm" }
  ],
  "triggerCount": 1,
  "updatedAt": "2026-06-02T21:45:00.000Z",
  "versionId": "lead-site-ai-v1"
}
