{
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "whatsapp-agent-form-submit",
        "responseMode": "responseNode",
        "options": {
          "allowedOrigins": "*"
        }
      },
      "id": "95cbd346-77b9-4c03-935d-4ba109ab9e7b",
      "name": "Form Webhook Trigger",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        -544,
        144
      ],
      "notes": "Entry point \u2014 receives name, phone, email, website, industry, language"
    },
    {
      "parameters": {
        "jsCode": "const body = $input.first().json.body;\nconst phone = (body.phone || '').replace(/[^+\\d]/g, '');\nconst email = (body.email || '').toLowerCase().trim();\nconst name = (body.name || 'there').trim();\nconst website = (body.website || '').trim();\nconst industry = (body.industry || 'general').trim();\nconst language = (body.language || 'en').toLowerCase();\nconst hasWebsite = website.length > 3 && website.startsWith('http');\n\nif (!phone || phone.length < 7) throw new Error('Invalid phone: ' + phone);\nif (!email.includes('@')) throw new Error('Invalid email: ' + email);\n\nreturn [{ json: {\n  phone, email, name, website, industry, language, hasWebsite,\n  submittedAt: new Date().toISOString(),\n  sessionId: 'wa_' + Math.random().toString(36).substr(2, 12)\n} }];"
      },
      "id": "24d97f1e-d858-4263-846c-85c60ff2eca0",
      "name": "Validate & Normalize Input",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -320,
        144
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={\"status\":\"received\",\"message\":\"Thank you! You'll receive a WhatsApp message shortly.\",\"sessionId\":\"{{$json.sessionId}}\"}",
        "options": {}
      },
      "id": "25f6d20e-38ae-4727-a3bf-47851624de52",
      "name": "Respond to Form Immediately",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [
        -96,
        48
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "combinator": "and",
                "conditions": [
                  {
                    "leftValue": "={{$json.hasWebsite}}",
                    "rightValue": true,
                    "operator": {
                      "type": "boolean",
                      "operation": "equals"
                    }
                  }
                ],
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                }
              }
            }
          ]
        },
        "options": {}
      },
      "id": "a187e5be-43e2-41b6-a5a8-ddd809b0c4d5",
      "name": "Route: Has Website?",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3,
      "position": [
        -96,
        240
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.apollo.io/v1/people/match",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            },
            {
              "name": "Cache-Control",
              "value": "no-cache"
            }
          ]
        },
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "api_key",
              "value": "REPLACE_WITH_YOUR_APOLLO_KEY"
            },
            {
              "name": "email",
              "value": "={{$('Validate & Normalize Input').first().json.email}}"
            },
            {
              "name": "reveal_personal_emails",
              "value": false
            },
            {
              "name": "reveal_phone_number",
              "value": false
            }
          ]
        },
        "options": {
          "timeout": 8000
        }
      },
      "id": "b3975a38-e385-4cd3-8eb4-a031e51e1161",
      "name": "Apollo \u2014 Enrich Lead",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        128,
        432
      ]
    },
    {
      "parameters": {
        "operation": "emailVerifier",
        "email": "={{$('Validate & Normalize Input').first().json.email}}"
      },
      "id": "55ecd3b6-5594-4094-8ffe-167b2806172a",
      "name": "Hunter \u2014 Verify Email",
      "type": "n8n-nodes-base.hunter",
      "typeVersion": 1,
      "position": [
        128,
        624
      ],
      "credentials": {
        "hunterApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "query": "={{$('Validate & Normalize Input').first().json.industry + ' company ' + $('Validate & Normalize Input').first().json.name + ' services products reviews'}}",
        "options": {}
      },
      "id": "08428fc7-25da-4a62-b56d-0a5bfe8321ca",
      "name": "Tavily \u2014 Web Research",
      "type": "@tavily/n8n-nodes-tavily.tavily",
      "typeVersion": 1,
      "position": [
        128,
        -48
      ],
      "credentials": {
        "tavilyApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "resource": "Crawling",
        "operation": "crawl",
        "prompt": "={{$('Validate & Normalize Input').first().json.website}}",
        "crawlOptions": {},
        "requestOptions": {}
      },
      "id": "6312c509-696b-4b35-b832-fefe489fb872",
      "name": "Firecrawl \u2014 Scrape Website",
      "type": "@mendable/n8n-nodes-firecrawl.firecrawl",
      "typeVersion": 1,
      "position": [
        128,
        240
      ],
      "credentials": {
        "firecrawlApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "mode": "combine",
        "combineBy": "combineAll",
        "options": {}
      },
      "id": "b9102e19-c0d8-4aec-935a-c6c7b3de418a",
      "name": "Merge Enrichment Data",
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3,
      "position": [
        352,
        336
      ]
    },
    {
      "parameters": {
        "jsCode": "const validated = $('Validate & Normalize Input').first().json;\n\nlet crawlerData = {};\nlet tavilyData = {};\nlet apolloData = {};\nlet hunterData = {};\n\ntry { crawlerData = $('Firecrawl \u2014 Scrape Website').first()?.json || {}; } catch(e) {}\ntry { tavilyData = $('Tavily \u2014 Web Research').first()?.json || {}; } catch(e) {}\ntry { apolloData = $('Apollo \u2014 Enrich Lead').first()?.json?.person || {}; } catch(e) {}\ntry { hunterData = $('Hunter \u2014 Verify Email').first()?.json?.data || {}; } catch(e) {}\n\nconst scraped = crawlerData.content || crawlerData.text || '';\nconst tavilyResults = (tavilyData.results || []).map(r => r.content).join(' ').slice(0, 1200);\nconst businessContext = scraped.slice(0, 2000) || tavilyResults || 'No website data. Use discovery questions.';\n\nconst apolloTitle = apolloData.title || '';\nconst apolloCompany = apolloData.organization?.name || validated.industry;\nconst emailVerified = hunterData.result === 'deliverable';\n\nreturn [{ json: {\n  ...validated,\n  businessContext,\n  apolloTitle,\n  apolloCompany,\n  emailVerified,\n  hasWebsiteData: scraped.length > 100,\n  readyForOutreach: true\n} }];"
      },
      "id": "35fee5f7-13e0-44f4-b9d3-095414eb3a52",
      "name": "Build Business Context",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        576,
        336
      ]
    },
    {
      "parameters": {
        "modelId": "gpt-4o",
        "messages": {
          "values": [
            {
              "content": "You are an expert conversational copywriter for Verilyx, an AI automation agency. Write a personalised WhatsApp opening message and a set of qualification questions for an AI agent to ask.\n\nRules:\n- Warm, human, conversational \u2014 NOT salesy or corporate\n- First message must be under 80 words\n- Reference something specific about their business if context is available\n- Include 4 smart qualification questions that uncover: budget readiness, current pain points, decision-making authority, timeline\n- Respond in the contact's language\n- Output ONLY valid JSON in this shape:\n{\"opening\": \"string\", \"questions\": [\"string\"], \"disqualifiers\": [\"string\"], \"language\": \"string\"}\n\nDisqualifiers = phrases that indicate this lead is not ready (e.g. 'just browsing', 'no budget', 'my boss decides').",
              "role": "system"
            },
            {
              "content": "Contact name: {{$json.name}}\nCompany: {{$json.apolloCompany}}\nTitle: {{$json.apolloTitle}}\nIndustry: {{$json.industry}}\nLanguage: {{$json.language}}\nHas website data: {{$json.hasWebsiteData}}\nBusiness context summary: {{$json.businessContext.slice(0,800)}}"
            }
          ]
        },
        "options": {
          "maxTokens": 700,
          "temperature": 0.75
        }
      },
      "id": "c7f135ec-f596-4ed9-b81d-d8c39edeef28",
      "name": "GPT-4o \u2014 Build WhatsApp Script",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 1.4,
      "position": [
        800,
        336
      ],
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const raw = $input.first().json.message?.content\n  || $input.first().json.choices?.[0]?.message?.content\n  || '{}';\n\nlet parsed;\ntry {\n  const cleaned = raw.replace(/```json|```/g, '').trim();\n  parsed = JSON.parse(cleaned);\n} catch(e) {\n  parsed = { opening: raw, questions: [], disqualifiers: [], language: 'en' };\n}\n\nconst baseData = $('Build Business Context').first().json;\n\nreturn [{ json: {\n  ...baseData,\n  waScript: parsed,\n  openingMessage: parsed.opening || 'Hi! This is Aria from Verilyx. How can I help you today?',\n  agentQuestions: parsed.questions || [],\n  disqualifiers: parsed.disqualifiers || []\n} }];"
      },
      "id": "64b691b9-7e36-4376-b6ec-3e66f43bb49d",
      "name": "Parse WhatsApp Script",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1152,
        336
      ]
    },
    {
      "parameters": {
        "operation": "create",
        "base": {
          "__rl": true,
          "value": "appZ8yX7bM2qL1bM9",
          "mode": "id"
        },
        "table": {
          "__rl": true,
          "value": "tblXyZ123kdl2532",
          "mode": "id"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "23b533db-6ac3-476d-9f82-0c98bdd2f8e6",
      "name": "Airtable \u2014 Save Lead",
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2.1,
      "position": [
        1376,
        336
      ],
      "credentials": {
        "airtableTokenApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "from": "whatsapp:+96181312183",
        "to": "=whatsapp:{{$('Parse WhatsApp Script').first().json.phone}}",
        "message": "={{$('Parse WhatsApp Script').first().json.openingMessage}}",
        "options": {}
      },
      "id": "2b18b7fe-3eb5-486a-904c-9523eba14112",
      "name": "Twilio \u2014 Send WhatsApp Opening",
      "type": "n8n-nodes-base.twilio",
      "typeVersion": 1,
      "position": [
        1600,
        336
      ],
      "credentials": {
        "twilioApi": {
          "name": "<your credential>"
        }
      },
      "notes": "Use Twilio WhatsApp sandbox number or your approved WhatsApp Business number. Prefix 'To' with 'whatsapp:'"
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "whatsapp-inbound",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "1605a0b6-ad25-48f4-9f94-a9173844c75a",
      "name": "WhatsApp Inbound Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        -544,
        1040
      ],
      "notes": "Twilio posts every incoming WhatsApp reply here. Configure in Twilio Console \u2192 WhatsApp \u2192 Sandbox \u2192 When a message comes in."
    },
    {
      "parameters": {
        "jsCode": "const body = $input.first().json.body;\nconst from = (body.From || '').replace('whatsapp:', '');\nconst messageBody = body.Body || '';\nconst messageSid = body.MessageSid || '';\nconst sessionId = $input.first().json.query?.session || 'unknown';\nconst turnNumber = parseInt($input.first().json.query?.turn || '1');\n\nreturn [{ json: {\n  from,\n  messageBody,\n  messageSid,\n  sessionId,\n  turnNumber,\n  timestamp: new Date().toISOString()\n} }];"
      },
      "id": "865eb87d-b669-400c-b454-e3996b4d8211",
      "name": "Parse Inbound Reply",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -320,
        1040
      ]
    },
    {
      "parameters": {
        "operation": "search",
        "base": {
          "__rl": true,
          "value": "appZ8yX7bM2qL1bM9",
          "mode": "id"
        },
        "table": {
          "__rl": true,
          "value": "tblXyZ123kdl2532",
          "mode": "id"
        },
        "filterByFormula": "={phone}=\"{{$json.from}}\"",
        "options": {}
      },
      "id": "afeb1d11-a89e-4984-a4ab-85e12e30133d",
      "name": "Airtable \u2014 Load Lead Session",
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2.1,
      "position": [
        -96,
        1040
      ],
      "credentials": {
        "airtableTokenApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const session = $('Airtable \u2014 Load Lead Session').first()?.json?.fields || {};\nconst turn = $('Parse Inbound Reply').first().json;\n\nconst systemPrompt = `You are Aria, a professional and warm AI sales assistant for Verilyx, an AI automation agency. You are having a WhatsApp conversation.\n\nContact: ${session.name || 'the lead'}\nCompany: ${session.company || 'their company'}\nIndustry: ${session.industry || 'general'}\nLanguage: ${session.language || 'en'}\nBusiness context: ${(session.business_context || '').slice(0, 800)}\nQualification questions to work through naturally: ${session.agent_questions || '[]'}\nDisqualifying phrases to watch for: ${session.disqualifiers || '[]'}\n\nRules:\n- This is WhatsApp \u2014 keep replies short, 1-3 sentences max\n- Never use bullet points or markdown in WhatsApp messages\n- Ask ONE question at a time, naturally woven into conversation\n- If you detect a disqualifier, politely acknowledge and end gracefully\n- If they want to book: use the book_appointment tool\n- If they want a proposal: use the generate_proposal tool\n- If they say goodbye or the conversation is complete, end with END_CONVERSATION\n- Never reveal you are an AI unless directly asked\n- Respond only in ${session.language || 'en'}`;\n\nreturn [{ json: {\n  systemPrompt,\n  sessionId: session.session_id || turn.sessionId,\n  messageBody: turn.messageBody,\n  turnNumber: turn.turnNumber,\n  language: session.language || 'en',\n  name: session.name || '',\n  email: session.email || '',\n  phone: session.phone || turn.from\n} }];"
      },
      "id": "7be45ce7-a99c-4850-aa6f-db6d9bd67b60",
      "name": "Build Agent Context",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        128,
        1040
      ]
    },
    {
      "parameters": {
        "text": "={{$json.messageBody}}",
        "options": {
          "systemMessage": "={{$json.systemPrompt}}",
          "maxIterations": 5,
          "returnIntermediateSteps": false
        }
      },
      "id": "49c15596-b173-4fae-89e8-b24a1800efc6",
      "name": "AI Agent \u2014 WhatsApp Turn",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [
        480,
        1040
      ]
    },
    {
      "parameters": {
        "model": "gpt-4o",
        "options": {
          "maxTokens": 200,
          "temperature": 0.6
        }
      },
      "id": "08565acf-420e-4529-a1c7-31bd036de702",
      "name": "OpenAI GPT-4o Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.1,
      "position": [
        352,
        1264
      ],
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "sessionIdType": "customKey",
        "sessionKey": "={{$('Parse Inbound Reply').first().json.from}}",
        "contextWindowLength": 12
      },
      "id": "e3a28237-bd78-4b82-95b8-3ab875ae6d1c",
      "name": "WhatsApp Conversation Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "typeVersion": 1.3,
      "position": [
        480,
        1264
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.cal.com/v1/bookings",
        "sendHeaders": true,
        "parametersHeaders": {
          "values": [
            {
              "name": "Authorization"
            },
            {
              "name": "Content-Type"
            }
          ]
        },
        "sendBody": true,
        "parametersBody": {
          "values": [
            {
              "name": "eventTypeId"
            }
          ]
        },
        "placeholderDefinitions": {
          "values": [
            {
              "name": "datetime",
              "description": "ISO 8601 datetime for the meeting (e.g. 2025-06-01T14:00:00Z)",
              "type": "string"
            },
            {
              "name": "name",
              "description": "Full name of the person booking",
              "type": "string"
            },
            {
              "name": "email",
              "description": "Email address of the person booking",
              "type": "string"
            },
            {
              "name": "notes",
              "description": "Notes or agenda from the WhatsApp conversation",
              "type": "string"
            },
            {
              "name": "timezone",
              "description": "Timezone string e.g. Asia/Beirut",
              "type": "string"
            }
          ]
        }
      },
      "id": "0f7df4e5-227e-4a5b-b27b-1bfb8b9f1ab6",
      "name": "Tool: Book Meeting (Cal.com)",
      "type": "@n8n/n8n-nodes-langchain.toolHttpRequest",
      "typeVersion": 1.1,
      "position": [
        608,
        1264
      ]
    },
    {
      "parameters": {
        "name": "generate_proposal",
        "description": "Generate a custom proposal or solution document for the lead based on their business problem. Use when the lead asks for a proposal, pricing, or custom plan. Input JSON: {\"problem\": \"string\", \"context\": \"string\", \"industry\": \"string\"}",
        "jsCode": "const input = JSON.parse(query);\nconst { problem, context, industry } = input;\nconst proposal = `Custom Proposal for ${industry} Business\\n\\nProblem Identified: ${problem}\\n\\nContext: ${context}\\n\\nProposed Solution:\\n1. Discovery call to map current workflows\\n2. Identify top 3 automation opportunities\\n3. Build and deploy AI automation layer (n8n + OpenAI)\\n4. Weekly iteration sprint\\n\\nDelivery Timeline: 2-4 weeks\\nExpected ROI: 5-10x time savings in target processes.`;\nreturn { proposal, ready: true, generatedAt: new Date().toISOString() };"
      },
      "id": "f09f6809-7bc6-4deb-b211-c2021b364c0d",
      "name": "Tool: Generate Proposal",
      "type": "@n8n/n8n-nodes-langchain.toolCode",
      "typeVersion": 1.1,
      "position": [
        736,
        1264
      ]
    },
    {
      "parameters": {
        "jsCode": "const agentOutput = $('AI Agent \u2014 WhatsApp Turn').first().json.output || '';\nconst sessionData = $('Build Agent Context').first().json;\n\nconst isEnd = agentOutput.includes('END_CONVERSATION')\n  || agentOutput.toLowerCase().includes('goodbye')\n  || agentOutput.toLowerCase().includes('au revoir')\n  || agentOutput.toLowerCase().includes('\u0648\u062f\u0627\u0639\u0627\u064b');\n\nconst cleanReply = agentOutput.replace('END_CONVERSATION', '').trim();\n\nreturn [{ json: {\n  cleanReply,\n  isEnd,\n  sessionId: sessionData.sessionId,\n  phone: sessionData.phone,\n  agentOutput\n} }];"
      },
      "id": "0903089b-4ac6-4bfb-8634-b5775f513114",
      "name": "Parse Agent Reply",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        944,
        944
      ]
    },
    {
      "parameters": {
        "from": "whatsapp:+14155238886",
        "to": "=whatsapp:{{$json.phone}}",
        "message": "={{$json.cleanReply}}",
        "options": {}
      },
      "id": "a5b98098-3ecd-422e-9d49-daeec896b0d8",
      "name": "Twilio \u2014 Send WhatsApp Reply",
      "type": "n8n-nodes-base.twilio",
      "typeVersion": 1,
      "position": [
        1168,
        848
      ],
      "credentials": {
        "twilioApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "update",
        "base": {
          "__rl": true,
          "value": "appZ8yX7bM2qL1bM9",
          "mode": "id"
        },
        "table": {
          "__rl": true,
          "value": "",
          "mode": "id",
          "cachedResultName": "",
          "cachedResultUrl": ""
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "5279824c-e651-4dcb-9332-3fbae9d805e6",
      "name": "Airtable \u2014 Log Turn",
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2.1,
      "position": [
        944,
        1136
      ],
      "credentials": {
        "airtableTokenApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "combinator": "and",
                "conditions": [
                  {
                    "leftValue": "={{$json.isEnd}}",
                    "rightValue": true,
                    "operator": {
                      "type": "boolean",
                      "operation": "equals"
                    }
                  }
                ],
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                }
              },
              "renameOutput": true,
              "outputKey": "conversation_ended"
            }
          ]
        },
        "options": {}
      },
      "id": "ed64384a-2623-4e0d-bccb-76a47837d79a",
      "name": "Route: Conversation Ended?",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3,
      "position": [
        1168,
        1040
      ]
    },
    {
      "parameters": {
        "modelId": "gpt-4o",
        "messages": {
          "values": [
            {
              "content": "You are a post-conversation analyst. Analyse this WhatsApp conversation and return structured qualification data.\n\nExtract:\n1. qualified \u2014 boolean, true if the lead showed genuine interest and no disqualifiers\n2. intent \u2014 ONE of: booking | proposal | nurture | disqualified\n3. summary \u2014 2-sentence summary of the conversation\n4. pain_points \u2014 array of specific pain points mentioned\n5. budget_signal \u2014 ONE of: ready | exploring | unknown\n6. decision_maker \u2014 boolean\n7. timeline \u2014 string (e.g. 'next month', 'Q3', 'unknown')\n8. actions \u2014 array of next steps\n9. sentiment \u2014 ONE of: positive | neutral | negative\n\nOutput ONLY valid JSON. No preamble, no markdown.",
              "role": "system"
            },
            {
              "content": "Lead: {{$('Airtable \u2014 Load Lead Session').first()?.json?.fields?.name}}\nCompany: {{$('Airtable \u2014 Load Lead Session').first()?.json?.fields?.company}}\nConversation log: {{$('AI Agent \u2014 WhatsApp Turn').first().json.output}}"
            }
          ]
        },
        "options": {
          "maxTokens": 600,
          "temperature": 0.2
        }
      },
      "id": "e9d91b81-8634-4e47-946c-abf3c18a2a3f",
      "name": "GPT-4o \u2014 Analyse Conversation",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 1.4,
      "position": [
        1392,
        1040
      ],
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const raw = $input.first().json.message?.content\n  || $input.first().json.choices?.[0]?.message?.content\n  || '{}';\n\nlet analysis;\ntry {\n  const cleaned = raw.replace(/```json|```/g, '').trim();\n  analysis = JSON.parse(cleaned);\n} catch(e) {\n  analysis = { qualified: false, intent: 'nurture', summary: raw, pain_points: [], budget_signal: 'unknown', decision_maker: false, timeline: 'unknown', actions: [], sentiment: 'neutral' };\n}\n\nreturn [{ json: { ...analysis } }];"
      },
      "id": "b09537d6-5bfb-434c-b9a1-be9fb13d57ca",
      "name": "Parse Qualification Analysis",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1744,
        1040
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "combinator": "and",
                "conditions": [
                  {
                    "leftValue": "={{$json.intent}}",
                    "rightValue": "booking",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                }
              },
              "renameOutput": true,
              "outputKey": "booking"
            },
            {
              "conditions": {
                "combinator": "and",
                "conditions": [
                  {
                    "leftValue": "={{$json.intent}}",
                    "rightValue": "proposal",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                }
              },
              "renameOutput": true,
              "outputKey": "proposal"
            },
            {
              "conditions": {
                "combinator": "and",
                "conditions": [
                  {
                    "leftValue": "={{$json.intent}}",
                    "rightValue": "nurture",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                }
              },
              "renameOutput": true,
              "outputKey": "nurture"
            }
          ]
        },
        "options": {}
      },
      "id": "608ba4c2-f10f-47eb-a27a-de01f785105d",
      "name": "Route Intent",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3,
      "position": [
        1968,
        1024
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.cal.com/v1/bookings",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer REPLACE_WITH_CAL_API_KEY"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "eventTypeId",
              "value": "REPLACE_WITH_EVENT_TYPE_ID"
            },
            {
              "name": "start",
              "value": "={{new Date(Date.now() + 86400000).toISOString()}}"
            },
            {
              "name": "name",
              "value": "={{$('Airtable \u2014 Load Lead Session').first()?.json?.fields?.name || 'Lead'}}"
            },
            {
              "name": "email",
              "value": "={{$('Airtable \u2014 Load Lead Session').first()?.json?.fields?.email || ''}}"
            },
            {
              "name": "notes",
              "value": "=WhatsApp conversation: {{$('Parse Qualification Analysis').first().json.summary}}"
            },
            {
              "name": "timeZone",
              "value": "Asia/Beirut"
            }
          ]
        },
        "options": {
          "timeout": 8000
        }
      },
      "id": "f6edcb5b-d002-478b-b3c1-5524d1374424",
      "name": "Cal.com \u2014 Auto Book Meeting",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2256,
        848
      ]
    },
    {
      "parameters": {
        "modelId": "gpt-4o",
        "messages": {
          "values": [
            {
              "content": "Generate a professional, concise proposal email based on the WhatsApp conversation analysis below. Structure it as:\n\n**Subject line**\n\n**Email body** (professional HTML, ~300 words):\n- Personalised intro referencing their specific pain points\n- Recommended AI automation solution\n- Implementation timeline\n- Clear CTA to book a call\n\nBe specific to their industry and pain points. B2B professional tone. Output JSON: {\"subject\": \"string\", \"html_body\": \"string\"}",
              "role": "system"
            },
            {
              "content": "Analysis: {{JSON.stringify($json)}}\nCompany: {{$('Airtable \u2014 Load Lead Session').first()?.json?.fields?.company}}\nName: {{$('Airtable \u2014 Load Lead Session').first()?.json?.fields?.name}}"
            }
          ]
        },
        "options": {
          "maxTokens": 800,
          "temperature": 0.5
        }
      },
      "id": "a6e03196-6657-4098-afe3-c7675ceab443",
      "name": "GPT-4o \u2014 Generate Proposal Email",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 1.4,
      "position": [
        2192,
        1040
      ],
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "authentication": "serviceAccount",
        "sendTo": "={{$('Airtable \u2014 Load Lead Session').first()?.json?.fields?.email || ''}}",
        "subject": "=Your Verilyx AI Proposal \u2014 {{new Date().toLocaleDateString('en-GB')}}",
        "message": "=<html><body style='font-family:sans-serif;max-width:600px;margin:auto'><h2 style='color:#4F46E5'>Your Custom Automation Proposal</h2><p>{{$('Parse Qualification Analysis').first().json.summary}}</p><h3>Pain Points Identified</h3><ul>{{($('Parse Qualification Analysis').first().json.pain_points||[]).map(p=>'<li>'+p+'</li>').join('')}}</ul><hr/><p style='color:#888;font-size:12px'>Powered by Verilyx AI \u00b7 Built on n8n</p></body></html>",
        "options": {
          "appendAttribution": false
        }
      },
      "id": "1a3ac2aa-d0c4-4972-afef-6c3f87c3f972",
      "name": "Gmail \u2014 Send Proposal",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        2256,
        1232
      ],
      "credentials": {
        "googleApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "chatId": "=.env",
        "text": "=\ud83e\udd16 *Lead Qualified via WhatsApp*\n\ud83d\udc64 Name: {{$('Airtable \u2014 Load Lead Session').first()?.json?.fields?.name}}\n\ud83c\udfe2 Company: {{$('Airtable \u2014 Load Lead Session').first()?.json?.fields?.company}}\n\ud83c\udfaf Intent: {{$('Parse Qualification Analysis').first().json.intent}}\n\ud83d\udcb0 Budget signal: {{$('Parse Qualification Analysis').first().json.budget_signal}}\n\u23f0 Timeline: {{$('Parse Qualification Analysis').first().json.timeline}}\n\ud83d\ude0a Sentiment: {{$('Parse Qualification Analysis').first().json.sentiment}}\n\ud83d\udccb Summary: {{$('Parse Qualification Analysis').first().json.summary}}\n\u2705 Next steps: {{($('Parse Qualification Analysis').first().json.actions||[]).join(', ')}}",
        "additionalFields": {
          "parse_mode": "Markdown"
        }
      },
      "id": "bacb53e0-5fc2-46b5-bfbc-c02d92b86547",
      "name": "Telegram \u2014 Team Notification",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        2544,
        1040
      ],
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "update",
        "base": {
          "__rl": true,
          "value": "appZ8yX7bM2qL1bM9",
          "mode": "id"
        },
        "table": {
          "__rl": true,
          "value": "tblXyZ123kdl2532",
          "mode": "id"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "8a2731cf-1b8c-4fe8-b646-b61fb04e4019",
      "name": "Airtable \u2014 Final Update",
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2.1,
      "position": [
        2768,
        1040
      ],
      "credentials": {
        "airtableTokenApi": {
          "name": "<your credential>"
        }
      }
    }
  ],
  "connections": {
    "Form Webhook Trigger": {
      "main": [
        [
          {
            "node": "Validate & Normalize Input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate & Normalize Input": {
      "main": [
        [
          {
            "node": "Respond to Form Immediately",
            "type": "main",
            "index": 0
          },
          {
            "node": "Route: Has Website?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Route: Has Website?": {
      "main": [
        [
          {
            "node": "Apollo \u2014 Enrich Lead",
            "type": "main",
            "index": 0
          },
          {
            "node": "Hunter \u2014 Verify Email",
            "type": "main",
            "index": 0
          },
          {
            "node": "Tavily \u2014 Web Research",
            "type": "main",
            "index": 0
          },
          {
            "node": "Firecrawl \u2014 Scrape Website",
            "type": "main",
            "index": 0
          },
          {
            "node": "Merge Enrichment Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Apollo \u2014 Enrich Lead": {
      "main": [
        [
          {
            "node": "Merge Enrichment Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Hunter \u2014 Verify Email": {
      "main": [
        [
          {
            "node": "Merge Enrichment Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tavily \u2014 Web Research": {
      "main": [
        [
          {
            "node": "Merge Enrichment Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Firecrawl \u2014 Scrape Website": {
      "main": [
        [
          {
            "node": "Merge Enrichment Data",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Merge Enrichment Data": {
      "main": [
        [
          {
            "node": "Build Business Context",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Business Context": {
      "main": [
        [
          {
            "node": "GPT-4o \u2014 Build WhatsApp Script",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GPT-4o \u2014 Build WhatsApp Script": {
      "main": [
        [
          {
            "node": "Parse WhatsApp Script",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse WhatsApp Script": {
      "main": [
        [
          {
            "node": "Airtable \u2014 Save Lead",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Airtable \u2014 Save Lead": {
      "main": [
        [
          {
            "node": "Twilio \u2014 Send WhatsApp Opening",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "WhatsApp Inbound Webhook": {
      "main": [
        [
          {
            "node": "Parse Inbound Reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Inbound Reply": {
      "main": [
        [
          {
            "node": "Airtable \u2014 Load Lead Session",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Airtable \u2014 Load Lead Session": {
      "main": [
        [
          {
            "node": "Build Agent Context",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Agent Context": {
      "main": [
        [
          {
            "node": "AI Agent \u2014 WhatsApp Turn",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent \u2014 WhatsApp Turn": {
      "main": [
        [
          {
            "node": "Parse Agent Reply",
            "type": "main",
            "index": 0
          },
          {
            "node": "Airtable \u2014 Log Turn",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI GPT-4o Model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent \u2014 WhatsApp Turn",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "WhatsApp Conversation Memory": {
      "ai_memory": [
        [
          {
            "node": "AI Agent \u2014 WhatsApp Turn",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Tool: Book Meeting (Cal.com)": {
      "ai_tool": [
        [
          {
            "node": "AI Agent \u2014 WhatsApp Turn",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Tool: Generate Proposal": {
      "ai_tool": [
        [
          {
            "node": "AI Agent \u2014 WhatsApp Turn",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Parse Agent Reply": {
      "main": [
        [
          {
            "node": "Twilio \u2014 Send WhatsApp Reply",
            "type": "main",
            "index": 0
          },
          {
            "node": "Route: Conversation Ended?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Route: Conversation Ended?": {
      "main": [
        [
          {
            "node": "GPT-4o \u2014 Analyse Conversation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GPT-4o \u2014 Analyse Conversation": {
      "main": [
        [
          {
            "node": "Parse Qualification Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Qualification Analysis": {
      "main": [
        [
          {
            "node": "Route Intent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Route Intent": {
      "main": [
        [
          {
            "node": "Cal.com \u2014 Auto Book Meeting",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "GPT-4o \u2014 Generate Proposal Email",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Gmail \u2014 Send Proposal",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Cal.com \u2014 Auto Book Meeting": {
      "main": [
        [
          {
            "node": "Telegram \u2014 Team Notification",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GPT-4o \u2014 Generate Proposal Email": {
      "main": [
        [
          {
            "node": "Telegram \u2014 Team Notification",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gmail \u2014 Send Proposal": {
      "main": [
        [
          {
            "node": "Telegram \u2014 Team Notification",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Telegram \u2014 Team Notification": {
      "main": [
        [
          {
            "node": "Airtable \u2014 Final Update",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "meta": {
    "templateCredsSetupCompleted": true
  }
}