{
  "name": "Lead Flow",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "lead-intake",
        "options": {}
      },
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        0,
        0
      ],
      "id": "9bb593c1-b620-42a2-aa63-feb5ce625d15",
      "name": "Webhook"
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "models/gemini-2.5-flash-lite",
          "mode": "list",
          "cachedResultName": "models/gemini-2.5-flash-lite"
        },
        "messages": {
          "values": [
            {
              "content": "=You are a lead qualification assistant. Based on this lead's message, classify them as HOT, WARM, or COLD, and give one short reason. Respond ONLY in this exact JSON format: {\"score\": \"HOT/WARM/COLD\", \"reason\": \"short reason\"}. Lead message: {{ $json.body.Message }}"
            }
          ]
        },
        "builtInTools": {},
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.googleGemini",
      "typeVersion": 1.2,
      "position": [
        208,
        0
      ],
      "id": "e39a6d3c-5040-4168-8249-c11166400fda",
      "name": "Message a model",
      "retryOnFail": true,
      "waitBetweenTries": 2000,
      "credentials": {
        "googlePalmApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "loose",
                  "version": 3
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.score }}",
                    "rightValue": "HOT",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "id": "88bd82ed-d219-4705-921e-54098751a7be"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Hot"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "loose",
                  "version": 3
                },
                "conditions": [
                  {
                    "id": "782202c0-0f36-4db5-a8d0-bd4ba5ae8b3c",
                    "leftValue": "={{ $json.score }}",
                    "rightValue": "COLD",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Cold"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "loose",
                  "version": 3
                },
                "conditions": [
                  {
                    "id": "e073e60c-9df9-4cbd-80c7-04b5d57f4cbf",
                    "leftValue": "={{ $json.score }}",
                    "rightValue": "WARM",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Warm"
            }
          ]
        },
        "looseTypeValidation": true,
        "options": {}
      },
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.4,
      "position": [
        768,
        -16
      ],
      "id": "13110db0-4723-4056-95f7-60020b92543e",
      "name": "Switch"
    },
    {
      "parameters": {
        "sendTo": "={{ $('Clean Data').item.json.email }}",
        "subject": "Thanks for your interest!",
        "emailType": "text",
        "message": "=Hi {{ $('Clean Data').item.json.name }},  Thanks for reaching out! We noticed you're interested in learning more, and we'd love to help.  A member of our team will follow up with you shortly to answer any questions and see how we can assist.  In the meantime, feel free to reply to this email with anything specific you'd like to know.  Best regards, The Team",
        "options": {}
      },
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.2,
      "position": [
        1024,
        208
      ],
      "id": "96048f0d-3d72-4189-83b6-d6b2ed03d1ac",
      "name": "Send a message",
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "sendTo": "={{ $('Clean Data').item.json.email }}",
        "subject": "We're here whenever you're ready",
        "emailType": "text",
        "message": "=Hi {{ $('Clean Data').item.json.name }}, Thanks for stopping by! We know timing isn't always right, so no pressure at all.  Whenever you're ready to explore how we can help, we'll be here. Feel free to reach out anytime.  Best regards, The Team",
        "options": {}
      },
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.2,
      "position": [
        1168,
        64
      ],
      "id": "c5e367cd-0562-43de-b9d8-1346563c9205",
      "name": "Send a message1",
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://services.leadconnectorhq.com/contacts/upsert",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBearerAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Version",
              "value": "2021-04-15"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"locationId\": \"7tqnkPblotGEoL0zKY6N\",\n  \"name\": \"{{ $('Switch').item.json.name }}\",\n  \"email\": \"{{ $('Switch').item.json.email }}\",\n  \"phone\": \"{{ $('Switch').item.json.phone }}\"\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        1376,
        -96
      ],
      "id": "6e6143c2-53e7-43b4-9c35-ca13ff9b2c95",
      "name": "Create Contact",
      "retryOnFail": true,
      "waitBetweenTries": 2000,
      "credentials": {
        "httpBearerAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://services.leadconnectorhq.com/calendars/events/appointments",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBearerAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Version",
              "value": "2021-04-15"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"calendarId\": \"HoeXHR6MByoH1yPao8ST\",\n  \"locationId\": \"7tqnkPblotGEoL0zKY6N\",\n  \"contactId\": \"{{$json.contactId}}\",\n  \"title\": \"Auto-booked call with {{$json.name}}\",\n  \"startTime\": \"{{$json.startTime}}\"\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        2000,
        -96
      ],
      "id": "4310ac40-92c3-46e1-8c28-1ab98f73e75d",
      "name": "Book Appointment",
      "retryOnFail": true,
      "waitBetweenTries": 2000,
      "credentials": {
        "httpBearerAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "url": "=https://services.leadconnectorhq.com/calendars/HoeXHR6MByoH1yPao8ST/free-slots",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBearerAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "startDate",
              "value": "={{Date.now()}}"
            },
            {
              "name": "endDate",
              "value": "={{Date.now() + 7*24*60*60*1000}}"
            },
            {
              "name": "timezone",
              "value": "Asia/Karachi"
            }
          ]
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Version",
              "value": "2021-04-15"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        1584,
        -96
      ],
      "id": "3fc5573a-7318-435f-b438-6848834dedf0",
      "name": "Get Free Slots",
      "retryOnFail": true,
      "waitBetweenTries": 2000,
      "credentials": {
        "httpBearerAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "let parsed;\ntry {\n  const geminiText = $input.first().json.content.parts[0].text;\n  const cleaned = geminiText.replace(/```json|```/g, '').trim();\n  parsed = JSON.parse(cleaned);\n  \n  // Validate the score is one of the expected values\n  if (!['HOT', 'WARM', 'COLD'].includes(parsed.score)) {\n    throw new Error('Invalid score value');\n  }\n} catch (error) {\n  // Fallback: if AI scoring fails for any reason, default to WARM\n  // (safer than HOT \u2014 avoids auto-booking on bad data; safer than COLD \u2014 doesn't lose a possibly-real lead)\n  parsed = { score: 'WARM', reason: 'Fallback: AI scoring failed, defaulting to manual review' };\n}\n\nreturn [{\n  json: {\n    name: $('Webhook').first().json.body.first_name + ' ' + $('Webhook').first().json.body.last_name,\n    email: $('Webhook').first().json.body.email,\n    phone: $('Webhook').first().json.body.phone,\n    score: parsed.score,\n    reason: parsed.reason\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        560,
        0
      ],
      "id": "233a7519-4ec3-4a9d-bc3d-1bc4a25d5a66",
      "name": "Clean Data"
    },
    {
      "parameters": {
        "jsCode": "const data = $input.first().json;\nconst dateKeys = Object.keys(data).filter(key => key !== 'traceId');\n\nlet nearestSlot = null;\nfor (const date of dateKeys.sort()) {\n  const daySlots = data[date]?.slots;\n  if (daySlots && daySlots.length > 0) {\n    nearestSlot = daySlots[0];\n    break;\n  }\n}\n\nif (!nearestSlot) {\n  throw new Error('No available slots found in the next 7 days');\n}\n\nlet contactData;\ntry {\n  contactData = $('Create Contact').first().json;\n} catch (e) {\n  contactData = $('Check For Duplicate').first().json;\n}\n\nreturn [{\n  json: {\n    name: contactData.name,\n    email: contactData.email,\n    phone: contactData.phone,\n    contactId: contactData.contact ? contactData.contact.id : contactData.contactId,\n    startTime: nearestSlot\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1792,
        -96
      ],
      "id": "14e6e602-ba92-4b25-a0fb-799f7b5f9967",
      "name": "Pick Nearest Slot"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://services.leadconnectorhq.com/contacts/search",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBearerAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Version",
              "value": "2021-07-28"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"locationId\": \"7tqnkPblotGEoL0zKY6N\",\n  \"pageLimit\": 1,\n  \"filters\": [\n    {\n      \"field\": \"email\",\n      \"operator\": \"eq\",\n      \"value\": \"{{ $json.email }}\"\n    }\n  ]\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        976,
        -224
      ],
      "id": "c92fc48e-1559-4eab-bca4-355ca497149d",
      "name": "Search Existing Contact",
      "retryOnFail": true,
      "waitBetweenTries": 2000,
      "credentials": {
        "httpBearerAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "c6bbb092-ea6f-43fb-a48d-056df44b80c6",
              "leftValue": "={{$json.contacts.length}}",
              "rightValue": 0,
              "operator": {
                "type": "number",
                "operation": "gt"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        1152,
        -224
      ],
      "id": "34303fd6-5f36-4006-b6cb-246086b419c1",
      "name": "If"
    },
    {
      "parameters": {
        "url": "https://services.leadconnectorhq.com/calendars/events",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBearerAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "locationId",
              "value": "7tqnkPblotGEoL0zKY6N"
            },
            {
              "name": "calendarId",
              "value": "=HoeXHR6MByoH1yPao8ST"
            },
            {
              "name": "startTime",
              "value": "={{Date.now()}}"
            },
            {
              "name": "endTime",
              "value": "={{Date.now() + 30*24*60*60*1000}}"
            }
          ]
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Version",
              "value": "2021-04-15"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        1376,
        -336
      ],
      "id": "4a1ca6ff-7b29-4e71-9dac-c812561946e6",
      "name": "Check Existing Appointments",
      "retryOnFail": true,
      "waitBetweenTries": 2000,
      "credentials": {
        "httpBearerAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const events = $input.first().json.events || [];\nconst targetContactId = $('Search Existing Contact').first().json.contacts[0].id;\n\nconst hasExistingAppointment = events.some(event => event.contactId === targetContactId);\n\nreturn [{\n  json: {\n    name: $('Switch').first().json.name,\n    email: $('Switch').first().json.email,\n    phone: $('Switch').first().json.phone,\n    contactId: targetContactId,\n    hasExistingAppointment: hasExistingAppointment\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1584,
        -336
      ],
      "id": "7b8ed602-d126-4f2e-87f4-985f04d4211f",
      "name": "Check For Duplicate"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "3d41aca5-91fc-41d6-98c3-4ef76737cfe2",
              "leftValue": "={{$json.hasExistingAppointment}}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        1792,
        -336
      ],
      "id": "4e795a53-85fe-4c56-9908-b236000d6758",
      "name": "Already Booked?"
    },
    {
      "parameters": {
        "sendTo": "={{$json.email}}",
        "subject": "You're already on our calendar!",
        "emailType": "text",
        "message": "=Hi {{$json.name}},  We see you already have an upcoming appointment with us. Looking forward to speaking with you soon!  If you need to make any changes, just reply to this email.",
        "options": {}
      },
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.2,
      "position": [
        2000,
        -384
      ],
      "id": "4ad6b44c-7a9f-46d8-a1e8-5cb41eafb776",
      "name": "Send a message2",
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "sendTo": "={{ $('Switch').item.json.email }}",
        "subject": "You're confirmed! \u2705",
        "emailType": "text",
        "message": "=Hi {{ $('Switch').item.json.name }},  Great news \u2014 your appointment is confirmed!  \ud83d\udcc5 Date & Time: {{ new Date($('Pick Nearest Slot').item.json.startTime).toLocaleString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: '2-digit', timeZone: 'Asia/Karachi' }) }}  We're looking forward to speaking with you. If you need to reschedule or have any questions before then, just reply to this email.  Talk soon!",
        "options": {}
      },
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.2,
      "position": [
        2208,
        -96
      ],
      "id": "f16c0901-0d85-4a83-83c1-d2f3d13d6ab6",
      "name": "Send a message3",
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      }
    }
  ],
  "connections": {
    "Webhook": {
      "main": [
        [
          {
            "node": "Message a model",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Message a model": {
      "main": [
        [
          {
            "node": "Clean Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Switch": {
      "main": [
        [
          {
            "node": "Search Existing Contact",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send a message1",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send a message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Contact": {
      "main": [
        [
          {
            "node": "Get Free Slots",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Free Slots": {
      "main": [
        [
          {
            "node": "Pick Nearest Slot",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Clean Data": {
      "main": [
        [
          {
            "node": "Switch",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pick Nearest Slot": {
      "main": [
        [
          {
            "node": "Book Appointment",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Search Existing Contact": {
      "main": [
        [
          {
            "node": "If",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "If": {
      "main": [
        [
          {
            "node": "Check Existing Appointments",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Create Contact",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Existing Appointments": {
      "main": [
        [
          {
            "node": "Check For Duplicate",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check For Duplicate": {
      "main": [
        [
          {
            "node": "Already Booked?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Already Booked?": {
      "main": [
        [
          {
            "node": "Send a message2",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Get Free Slots",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Book Appointment": {
      "main": [
        [
          {
            "node": "Send a message3",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "binaryMode": "separate",
    "availableInMCP": false,
    "timeSavedMode": "fixed",
    "errorWorkflow": "yjKKYCl3jGL9UvWt",
    "callerPolicy": "workflowsFromSameOwner"
  },
  "versionId": "d55db2a7-aba8-458b-aa7a-0db961cbdc31",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "nodeGroups": [],
  "id": "EDT0UAgIgzYr5LA3",
  "tags": []
}