{
  "active": false,
  "connections": {
    "Missed Call Webhook": {
      "main": [
        [
          {
            "node": "Is Missed Call?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Is Missed Call?": {
      "main": [
        [
          {
            "node": "Consent Present?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Done \u2014 Text-Back",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Consent Present?": {
      "main": [
        [
          {
            "node": "Build Text-Back",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Done \u2014 Text-Back",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Text-Back": {
      "main": [
        [
          {
            "node": "Send Text-Back",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Text-Back": {
      "main": [
        [
          {
            "node": "Log Text-Back",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Text-Back": {
      "main": [
        [
          {
            "node": "Done \u2014 Text-Back",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Inbound SMS Webhook": {
      "main": [
        [
          {
            "node": "Route Reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Route Reply": {
      "main": [
        [
          {
            "node": "Reply Is Quote?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Reply Is Quote?": {
      "main": [
        [
          {
            "node": "Send Quote Link",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Reply Is Urgent?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Quote Link": {
      "main": [
        [
          {
            "node": "Log SMS Reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log SMS Reply": {
      "main": [
        [
          {
            "node": "Done \u2014 SMS Reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Reply Is Urgent?": {
      "main": [
        [
          {
            "node": "Send Urgent Reply",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Reply Is Opt-Out?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Urgent Reply": {
      "main": [
        [
          {
            "node": "Alert Owner \u2014 Urgent Reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Alert Owner \u2014 Urgent Reply": {
      "main": [
        [
          {
            "node": "Log SMS Reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Reply Is Opt-Out?": {
      "main": [
        [
          {
            "node": "Log Opt-Out",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Alert Owner \u2014 Needs Human",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Opt-Out": {
      "main": [
        [
          {
            "node": "Confirm Opt-Out",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Confirm Opt-Out": {
      "main": [
        [
          {
            "node": "Done \u2014 SMS Reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Alert Owner \u2014 Needs Human": {
      "main": [
        [
          {
            "node": "Log Needs Human",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Needs Human": {
      "main": [
        [
          {
            "node": "Done \u2014 SMS Reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Web Lead Form": {
      "main": [
        [
          {
            "node": "Lead Valid?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Lead Valid?": {
      "main": [
        [
          {
            "node": "Build Gemini Prompt",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Log Invalid Lead",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Gemini Prompt": {
      "main": [
        [
          {
            "node": "Gemini \u2014 Draft Reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gemini \u2014 Draft Reply": {
      "main": [
        [
          {
            "node": "Parse AI Reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse AI Reply": {
      "main": [
        [
          {
            "node": "Send Instant Reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Instant Reply": {
      "main": [
        [
          {
            "node": "Log Lead to Sheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Lead to Sheet": {
      "main": [
        [
          {
            "node": "Done \u2014 Web Lead",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Invalid Lead": {
      "main": [
        [
          {
            "node": "Alert Owner \u2014 Invalid Lead",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Alert Owner \u2014 Invalid Lead": {
      "main": [
        [
          {
            "node": "Done \u2014 Web Lead",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Daily Follow-Up Check": {
      "main": [
        [
          {
            "node": "Read Lead Log",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read Lead Log": {
      "main": [
        [
          {
            "node": "Pick Follow-Ups",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pick Follow-Ups": {
      "main": [
        [
          {
            "node": "Send Follow-Up",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Follow-Up": {
      "main": [
        [
          {
            "node": "Update Lead Row",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update Lead Row": {
      "main": [
        [
          {
            "node": "Done \u2014 Follow-Up",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "name": "NEVER MISS A LEAD \u2014 Demo (Missed-Call Text-Back + Instant Lead Reply + Follow-Up)",
  "nodes": [
    {
      "id": "6fcf8afc-5d58-44a9-8a34-95f373e7c597",
      "name": "Missed Call Webhook",
      "parameters": {
        "httpMethod": "POST",
        "options": {},
        "path": "missed-call",
        "responseMode": "onReceived"
      },
      "position": [
        0,
        0
      ],
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2
    },
    {
      "id": "4f4ab90c-2ed3-4569-a0bc-5f3de4e15bbc",
      "name": "Is Missed Call?",
      "parameters": {
        "conditions": {
          "combinator": "or",
          "conditions": [
            {
              "id": "miss-no-answer",
              "leftValue": "={{ $json.CallStatus }}",
              "operator": {
                "operation": "equals",
                "type": "string"
              },
              "rightValue": "no-answer"
            },
            {
              "id": "miss-busy",
              "leftValue": "={{ $json.CallStatus }}",
              "operator": {
                "operation": "equals",
                "type": "string"
              },
              "rightValue": "busy"
            },
            {
              "id": "miss-failed",
              "leftValue": "={{ $json.CallStatus }}",
              "operator": {
                "operation": "equals",
                "type": "string"
              },
              "rightValue": "failed"
            }
          ],
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          }
        },
        "options": {}
      },
      "position": [
        260,
        0
      ],
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2
    },
    {
      "id": "ddac4142-b37a-4fe5-a317-7936dd613e24",
      "name": "Consent Present?",
      "parameters": {
        "conditions": {
          "combinator": "and",
          "conditions": [
            {
              "id": "consent-present",
              "leftValue": "={{ $json.consent_source }}",
              "operator": {
                "operation": "notEmpty",
                "type": "string"
              }
            },
            {
              "id": "consent-not-none",
              "leftValue": "={{ $json.consent_source }}",
              "operator": {
                "operation": "notEquals",
                "type": "string"
              },
              "rightValue": "none"
            }
          ],
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          }
        },
        "options": {}
      },
      "position": [
        520,
        0
      ],
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2
    },
    {
      "id": "c923e40f-a88c-4244-8b03-60f729bdf4aa",
      "name": "Build Text-Back",
      "parameters": {
        "jsCode": "const items = $input.all();\nreturn items.map(item => {\n  const j = item.json;\n  const business = $vars.BUSINESS_NAME;\n  const message = 'Hi, this is ' + business + ' \\u2014 sorry we missed your call. Are you looking for a quote or an urgent repair? Reply 1 for a quote, 2 for urgent. Reply STOP to opt out.';\n  return { json: {\n    caller_number: j.caller_number,\n    to: j.caller_number,\n    fromNumber: $vars.CLIENT_TWILIO_NUMBER,\n    message: message,\n    event: 'missed_call_textback',\n    consent_source: j.consent_source,\n    sent_at: $now\n  } };\n});\n"
      },
      "position": [
        780,
        0
      ],
      "type": "n8n-nodes-base.code",
      "typeVersion": 2
    },
    {
      "id": "b8aba137-fec3-4e88-b329-3a1eae5e5b84",
      "name": "Send Text-Back",
      "parameters": {
        "resource": "message",
        "operation": "send",
        "from": "={{ $vars.CLIENT_TWILIO_NUMBER }}",
        "to": "={{ $json.to }}",
        "message": "={{ $json.message }}"
      },
      "position": [
        1040,
        0
      ],
      "type": "n8n-nodes-base.twilio",
      "typeVersion": 1,
      "credentials": {
        "twilioApi": {
          "id": null,
          "name": "CLIENT TWILIO CREDENTIAL - create in n8n from the client's own Twilio account"
        }
      }
    },
    {
      "id": "2d554dab-2de6-4f52-8b62-7c565c3a52dd",
      "name": "Log Text-Back",
      "parameters": {
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "caller_number": "={{ $json.caller_number }}",
            "event": "={{ $json.event }}",
            "message": "={{ $json.message }}",
            "consent_source": "={{ $json.consent_source }}",
            "sent_at": "={{ $json.sent_at }}"
          }
        },
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "={{ $vars.LEAD_SHEET_URL }}"
        },
        "operation": "append",
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "Lead Log"
        }
      },
      "position": [
        1300,
        0
      ],
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.2,
      "credentials": {
        "googleSheetsOAuth2": {
          "id": null,
          "name": "CLIENT GOOGLE SHEETS CREDENTIAL - owner's Google account in n8n"
        }
      }
    },
    {
      "id": "ff3bf9af-0c0c-41ad-8c45-328a8d53a64a",
      "name": "Done \u2014 Text-Back",
      "parameters": {},
      "position": [
        1560,
        0
      ],
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1
    },
    {
      "id": "52de3656-a561-4f41-8c9e-120b49932f9c",
      "name": "Inbound SMS Webhook",
      "parameters": {
        "httpMethod": "POST",
        "options": {},
        "path": "inbound-sms",
        "responseMode": "onReceived"
      },
      "position": [
        0,
        320
      ],
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2
    },
    {
      "id": "3f585618-ca6b-4fa1-8cca-e77185aaa485",
      "name": "Route Reply",
      "parameters": {
        "jsCode": "const items = $input.all();\nconst OPT_OUT = ['stop', 'quit', 'end', 'revoke', 'opt out', 'cancel', 'unsubscribe'];\nreturn items.map(item => {\n  const body = String(item.json.Body || '').trim().toLowerCase();\n  let route = 'human';\n  if (body === '1' || body === 'quote') route = 'quote';\n  else if (body === '2' || body === 'urgent') route = 'urgent';\n  else if (OPT_OUT.indexOf(body) !== -1) route = 'optout';\n  return { json: {\n    from_number: item.json.From,\n    body_raw: item.json.Body || '',\n    body_normalised: body,\n    route: route,\n    received_at: $now\n  } };\n});\n"
      },
      "position": [
        260,
        320
      ],
      "type": "n8n-nodes-base.code",
      "typeVersion": 2
    },
    {
      "id": "5740bdcc-d6c3-4f4f-aa0f-7745b2770e3c",
      "name": "Reply Is Quote?",
      "parameters": {
        "conditions": {
          "combinator": "and",
          "conditions": [
            {
              "id": "route-quote",
              "leftValue": "={{ $json.route }}",
              "operator": {
                "operation": "equals",
                "type": "string"
              },
              "rightValue": "quote"
            }
          ],
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          }
        },
        "options": {}
      },
      "position": [
        520,
        320
      ],
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2
    },
    {
      "id": "04e0c84e-b404-487f-a0f1-7059174ef92f",
      "name": "Reply Is Urgent?",
      "parameters": {
        "conditions": {
          "combinator": "and",
          "conditions": [
            {
              "id": "route-urgent",
              "leftValue": "={{ $json.route }}",
              "operator": {
                "operation": "equals",
                "type": "string"
              },
              "rightValue": "urgent"
            }
          ],
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          }
        },
        "options": {}
      },
      "position": [
        520,
        560
      ],
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2
    },
    {
      "id": "bd1d69a5-2e36-4585-8a8f-bc7e39249c14",
      "name": "Reply Is Opt-Out?",
      "parameters": {
        "conditions": {
          "combinator": "and",
          "conditions": [
            {
              "id": "route-optout",
              "leftValue": "={{ $json.route }}",
              "operator": {
                "operation": "equals",
                "type": "string"
              },
              "rightValue": "optout"
            }
          ],
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          }
        },
        "options": {}
      },
      "position": [
        520,
        800
      ],
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2
    },
    {
      "id": "e230906e-c00a-48b5-8e8e-b777b4ed21e3",
      "name": "Send Quote Link",
      "parameters": {
        "resource": "message",
        "operation": "send",
        "from": "={{ $vars.CLIENT_TWILIO_NUMBER }}",
        "to": "={{ $json.from_number }}",
        "message": "=Hi \u2014 here is the quote form: {{ $vars.QUOTE_FORM_URL }} \u2014 it takes about a minute. A team member will call you once it is in. Reply STOP to opt out."
      },
      "position": [
        780,
        320
      ],
      "type": "n8n-nodes-base.twilio",
      "typeVersion": 1,
      "credentials": {
        "twilioApi": {
          "id": null,
          "name": "CLIENT TWILIO CREDENTIAL - create in n8n from the client's own Twilio account"
        }
      }
    },
    {
      "id": "6c411229-1c90-441f-a39c-d6898f8cba80",
      "name": "Send Urgent Reply",
      "parameters": {
        "resource": "message",
        "operation": "send",
        "from": "={{ $vars.CLIENT_TWILIO_NUMBER }}",
        "to": "={{ $json.from_number }}",
        "message": "=Thanks \u2014 marked as urgent. A technician will call you within 15 minutes. If it is an emergency (gas, water leak, no power), call the business number directly. Reply STOP to opt out."
      },
      "position": [
        780,
        560
      ],
      "type": "n8n-nodes-base.twilio",
      "typeVersion": 1,
      "credentials": {
        "twilioApi": {
          "id": null,
          "name": "CLIENT TWILIO CREDENTIAL - create in n8n from the client's own Twilio account"
        }
      }
    },
    {
      "id": "0fc5fc7e-1b68-405a-a1c6-a8c25ae2edcb",
      "name": "Alert Owner \u2014 Urgent Reply",
      "parameters": {
        "emailType": "text",
        "message": "=A lead replied URGENT (2) and was told a technician will call within 15 minutes.\n\nFrom: {{ $json.from_number }}\nMessage: {{ $json.body_raw }}\nReceived: {{ $json.received_at }}\n\nCall them now \u2014 the 15-minute promise is live.",
        "options": {},
        "sendTo": "={{ $vars.OWNER_EMAIL }}",
        "subject": "=URGENT lead reply \u2014 needs a call within 15 minutes"
      },
      "position": [
        1040,
        560
      ],
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "credentials": {
        "gmailOAuth2": {
          "id": null,
          "name": "CLIENT GMAIL CREDENTIAL - owner's Gmail OAuth in n8n"
        }
      }
    },
    {
      "id": "ba82f660-ef56-4693-85b5-00790e5e5242",
      "name": "Log SMS Reply",
      "parameters": {
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "caller_number": "={{ $json.from_number }}",
            "event": "={{ 'reply_routed_' + $json.route }}",
            "message": "={{ $json.body_raw }}",
            "consent_source": "={{ 'inbound reply' }}",
            "sent_at": "={{ $json.received_at }}"
          }
        },
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "={{ $vars.LEAD_SHEET_URL }}"
        },
        "operation": "append",
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "Lead Log"
        }
      },
      "position": [
        1040,
        320
      ],
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.2,
      "credentials": {
        "googleSheetsOAuth2": {
          "id": null,
          "name": "CLIENT GOOGLE SHEETS CREDENTIAL - owner's Google account in n8n"
        }
      }
    },
    {
      "id": "dd0ac537-524d-4497-878f-cc5cc783abe4",
      "name": "Log Opt-Out",
      "parameters": {
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "caller_number": "={{ $json.from_number }}",
            "event": "={{ 'opted_out' }}",
            "message": "={{ $json.body_raw }}",
            "consent_source": "={{ 'inbound reply' }}",
            "sent_at": "={{ $json.received_at }}"
          }
        },
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "={{ $vars.LEAD_SHEET_URL }}"
        },
        "operation": "append",
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "Opt-Outs"
        }
      },
      "position": [
        780,
        800
      ],
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.2,
      "credentials": {
        "googleSheetsOAuth2": {
          "id": null,
          "name": "CLIENT GOOGLE SHEETS CREDENTIAL - owner's Google account in n8n"
        }
      }
    },
    {
      "id": "c55e6492-9d63-4f9e-8b79-66f1cb752106",
      "name": "Confirm Opt-Out",
      "parameters": {
        "resource": "message",
        "operation": "send",
        "from": "={{ $vars.CLIENT_TWILIO_NUMBER }}",
        "to": "={{ $json.from_number }}",
        "message": "=You are opted out \u2014 we will not text you again. Thank you."
      },
      "position": [
        1040,
        800
      ],
      "type": "n8n-nodes-base.twilio",
      "typeVersion": 1,
      "credentials": {
        "twilioApi": {
          "id": null,
          "name": "CLIENT TWILIO CREDENTIAL - create in n8n from the client's own Twilio account"
        }
      }
    },
    {
      "id": "b716ad0e-736c-42b4-b7b1-55ac8f824d69",
      "name": "Alert Owner \u2014 Needs Human",
      "parameters": {
        "emailType": "text",
        "message": "=A lead replied with a message the automated reply could not handle. It has NOT been answered automatically \u2014 please reply yourself.\n\nFrom: {{ $json.from_number }}\nMessage: {{ $json.body_raw }}\nReceived: {{ $json.received_at }}",
        "options": {},
        "sendTo": "={{ $vars.OWNER_EMAIL }}",
        "subject": "=Lead reply needs a human \u2014 {{ $json.from_number }}"
      },
      "position": [
        780,
        1040
      ],
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "credentials": {
        "gmailOAuth2": {
          "id": null,
          "name": "CLIENT GMAIL CREDENTIAL - owner's Gmail OAuth in n8n"
        }
      }
    },
    {
      "id": "23685da7-19cf-4774-b65c-b579ced846dd",
      "name": "Log Needs Human",
      "parameters": {
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "caller_number": "={{ $json.from_number }}",
            "event": "={{ 'needs_human' }}",
            "message": "={{ $json.body_raw }}",
            "consent_source": "={{ 'inbound reply' }}",
            "sent_at": "={{ $json.received_at }}"
          }
        },
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "={{ $vars.LEAD_SHEET_URL }}"
        },
        "operation": "append",
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "Lead Log"
        }
      },
      "position": [
        1040,
        1040
      ],
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.2,
      "credentials": {
        "googleSheetsOAuth2": {
          "id": null,
          "name": "CLIENT GOOGLE SHEETS CREDENTIAL - owner's Google account in n8n"
        }
      }
    },
    {
      "id": "cdc319ee-b015-4380-9843-2a9d37d6e2d9",
      "name": "Done \u2014 SMS Reply",
      "parameters": {},
      "position": [
        1300,
        320
      ],
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1
    },
    {
      "id": "f0b68cab-1f6a-4fd5-ac04-520d4c6981df",
      "name": "Web Lead Form",
      "parameters": {
        "httpMethod": "POST",
        "options": {},
        "path": "web-lead",
        "responseMode": "onReceived"
      },
      "position": [
        0,
        1280
      ],
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2
    },
    {
      "id": "2635ec4a-f655-4ea6-9638-eeb41991480a",
      "name": "Lead Valid?",
      "parameters": {
        "conditions": {
          "combinator": "and",
          "conditions": [
            {
              "id": "valid-name",
              "leftValue": "={{ $json.name }}",
              "operator": {
                "operation": "notEmpty",
                "type": "string"
              }
            },
            {
              "id": "valid-phone",
              "leftValue": "={{ $json.phone }}",
              "operator": {
                "operation": "regex",
                "type": "string"
              },
              "rightValue": "^\\+?[0-9 ()\\-]{7,}$"
            },
            {
              "id": "valid-service",
              "leftValue": "={{ $json.service }}",
              "operator": {
                "operation": "notEmpty",
                "type": "string"
              }
            },
            {
              "id": "valid-consent",
              "leftValue": "={{ $json.consent }}",
              "operator": {
                "operation": "equals",
                "type": "string"
              },
              "rightValue": true
            }
          ],
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          }
        },
        "options": {}
      },
      "position": [
        260,
        1280
      ],
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2
    },
    {
      "id": "d018877e-68b5-4b82-954f-9c63de90e927",
      "name": "Build Gemini Prompt",
      "parameters": {
        "jsCode": "const items = $input.all();\nreturn items.map(item => {\n  const j = item.json;\n  const prompt = 'You are the receptionist for ' + $vars.BUSINESS_NAME + ', a ' + (j.trade || 'home services') + ' contractor. A new lead just submitted the website form: name ' + j.name + ', service needed: ' + j.service + ', postcode ' + (j.postcode || 'not given') + ', message: ' + (j.message || 'none') + '. Write ONE short SMS reply (under 300 characters) that: thanks them by first name, confirms we received their request, says a team member will call within one working day, and asks one useful follow-up question about timing. Plain, friendly, human. Do not invent prices, dates or promises. Sign off with the business name.';\n  return { json: {\n    name: j.name, first_name: String(j.name || '').split(' ')[0],\n    phone: j.phone, trade: j.trade || 'home services', service: j.service,\n    postcode: j.postcode || '', message_text: j.message || '',\n    consent_source: j.consent_source, received_at: j.received_at || $now,\n    prompt: prompt\n  } };\n});\n"
      },
      "position": [
        520,
        1280
      ],
      "type": "n8n-nodes-base.code",
      "typeVersion": 2
    },
    {
      "id": "9618f4be-6432-4e9c-af40-41d7d7410af0",
      "name": "Gemini \u2014 Draft Reply",
      "parameters": {
        "method": "POST",
        "url": "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-lite:generateContent",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "x-goog-api-key",
              "value": "={{ $vars.GEMINI_API_KEY }}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\"contents\": [{\"parts\": [{\"text\": {{ JSON.stringify($json.prompt) }} }]}], \"generationConfig\": {\"maxOutputTokens\": 120, \"temperature\": 0.7}}",
        "options": {
          "timeout": 30000,
          "response": {
            "response": {
              "responseFormat": "json"
            }
          }
        }
      },
      "position": [
        780,
        1280
      ],
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2
    },
    {
      "id": "2f998720-245c-4508-b2a8-987a42774bc3",
      "name": "Parse AI Reply",
      "parameters": {
        "jsCode": "const items = $input.all();\nreturn items.map(item => {\n  const j = item.json;\n  let text = '';\n  try { text = j.gemini_response.candidates[0].content.parts[0].text || ''; } catch (e) { text = ''; }\n  text = String(text).trim();\n  const firstName = String(j.name || '').split(' ')[0];\n  const fallback = 'Hi ' + firstName + ', thanks for getting in touch with ' + $vars.BUSINESS_NAME + '. We received your ' + j.service + ' request and a team member will call you within one working day. When is a good time to reach you? Reply STOP to opt out.';\n  const usable = text.length >= 20 && text.length <= 600;\n  const reply = usable ? text : fallback;\n  return { json: {\n    name: j.name, first_name: firstName, phone: j.phone, trade: j.trade,\n    service: j.service, postcode: j.postcode || '', consent_source: j.consent_source,\n    received_at: j.received_at, ai_reply: reply, used_fallback: !usable,\n    reply_sent_at: $now, to: j.phone, message: reply\n  } };\n});\n"
      },
      "position": [
        1040,
        1280
      ],
      "type": "n8n-nodes-base.code",
      "typeVersion": 2
    },
    {
      "id": "5da49772-1b49-4d2c-9e8b-33da2f817130",
      "name": "Send Instant Reply",
      "parameters": {
        "resource": "message",
        "operation": "send",
        "from": "={{ $vars.CLIENT_TWILIO_NUMBER }}",
        "to": "={{ $json.to }}",
        "message": "={{ $json.message }}"
      },
      "position": [
        1300,
        1280
      ],
      "type": "n8n-nodes-base.twilio",
      "typeVersion": 1,
      "credentials": {
        "twilioApi": {
          "id": null,
          "name": "CLIENT TWILIO CREDENTIAL - create in n8n from the client's own Twilio account"
        }
      }
    },
    {
      "id": "486dad56-f0fe-47f2-89a3-5a56d4477674",
      "name": "Log Lead to Sheet",
      "parameters": {
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "name": "={{ $json.name }}",
            "phone": "={{ $json.phone }}",
            "trade": "={{ $json.trade }}",
            "service": "={{ $json.service }}",
            "message": "={{ $json.message }}",
            "consent_source": "={{ $json.consent_source }}",
            "received_at": "={{ $json.received_at }}",
            "reply_sent_at": "={{ $json.reply_sent_at }}",
            "response_seconds": "={{ Math.round((new Date($json.reply_sent_at) - new Date($json.received_at)) / 1000) }}",
            "status": "={{ 'awaiting' }}",
            "followups_sent": "={{ 0 }}",
            "next_followup_due": "={{ new Date(new Date($json.received_at).getTime() + 24*60*60*1000).toISOString().slice(0,10) }}",
            "used_fallback": "={{ $json.used_fallback }}"
          }
        },
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "={{ $vars.LEAD_SHEET_URL }}"
        },
        "operation": "append",
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "Lead Log"
        }
      },
      "position": [
        1560,
        1280
      ],
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.2,
      "credentials": {
        "googleSheetsOAuth2": {
          "id": null,
          "name": "CLIENT GOOGLE SHEETS CREDENTIAL - owner's Google account in n8n"
        }
      }
    },
    {
      "id": "8fad11d3-603f-4c80-82f4-096c9b4b5345",
      "name": "Done \u2014 Web Lead",
      "parameters": {},
      "position": [
        1820,
        1280
      ],
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1
    },
    {
      "id": "efbc3b97-0d97-4be2-835b-307cd700cc8c",
      "name": "Log Invalid Lead",
      "parameters": {
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "name": "={{ $json.name }}",
            "phone": "={{ $json.phone }}",
            "service": "={{ $json.service }}",
            "message": "={{ 'missing name, bad phone, missing service, or no SMS consent' }}",
            "received_at": "={{ $now }}"
          }
        },
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "={{ $vars.LEAD_SHEET_URL }}"
        },
        "operation": "append",
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "Invalid Submissions"
        }
      },
      "position": [
        520,
        1520
      ],
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.2,
      "credentials": {
        "googleSheetsOAuth2": {
          "id": null,
          "name": "CLIENT GOOGLE SHEETS CREDENTIAL - owner's Google account in n8n"
        }
      }
    },
    {
      "id": "717057ad-f5d4-47ae-ac8a-a7cd778667be",
      "name": "Alert Owner \u2014 Invalid Lead",
      "parameters": {
        "emailType": "text",
        "message": "=A web-lead form submission could not be processed (missing name, invalid phone, missing service, or no SMS consent). It was logged on the 'Invalid Submissions' tab and NO text was sent.\n\nSubmitted data: {{ JSON.stringify($json) }}",
        "options": {},
        "sendTo": "={{ $vars.OWNER_EMAIL }}",
        "subject": "=Invalid web-lead submission \u2014 needs review"
      },
      "position": [
        780,
        1520
      ],
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "credentials": {
        "gmailOAuth2": {
          "id": null,
          "name": "CLIENT GMAIL CREDENTIAL - owner's Gmail OAuth in n8n"
        }
      }
    },
    {
      "id": "9fd1c0be-3165-47f0-9dd0-00c3be943203",
      "name": "Daily Follow-Up Check",
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "0 9 * * *"
            }
          ]
        }
      },
      "position": [
        0,
        1760
      ],
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2
    },
    {
      "id": "d726d335-0cb8-4e5f-990b-8dc32f3a4718",
      "name": "Read Lead Log",
      "parameters": {
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "={{ $vars.LEAD_SHEET_URL }}"
        },
        "operation": "read",
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "Lead Log"
        }
      },
      "position": [
        260,
        1760
      ],
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.2,
      "credentials": {
        "googleSheetsOAuth2": {
          "id": null,
          "name": "CLIENT GOOGLE SHEETS CREDENTIAL - owner's Google account in n8n"
        }
      }
    },
    {
      "id": "ed175234-da53-479c-b587-e9945c506473",
      "name": "Pick Follow-Ups",
      "parameters": {
        "jsCode": "const items = $input.all();\nconst out = [];\nconst DAY_MS = 24 * 60 * 60 * 1000;\nconst SCHEDULE = [1, 3, 7];\nconst MESSAGES = {\n  1: function (lead) { return 'Hi ' + lead.first_name + \", it's \" + $vars.BUSINESS_NAME + ' \\u2014 just checking in on your ' + lead.service + ' request. Still need help? Reply YES and we\\'ll call you today. Reply STOP to opt out.'; },\n  3: function (lead) { return 'Hi ' + lead.first_name + ', ' + $vars.BUSINESS_NAME + ' here. We sent your ' + lead.service + ' quote details \\u2014 would you like us to book a visit? Reply YES or STOP to opt out.'; },\n  7: function (lead) { return 'Hi ' + lead.first_name + ', last nudge from ' + $vars.BUSINESS_NAME + ' about your ' + lead.service + ' request. If you still need us, reply YES and we\\'ll call. Otherwise no need to reply \\u2014 reply STOP to opt out.'; }\n};\nfor (const item of items) {\n  const lead = item.json;\n  if (lead.status === 'booked' || lead.status === 'said_no' || lead.opted_out === true) continue;\n  const sent = lead.followups_sent || 0;\n  if (sent >= SCHEDULE.length) continue;\n  const first = new Date(lead.first_contact_at);\n  const now = new Date($now);\n  const days = Math.floor((now - first) / DAY_MS);\n  const dueDay = SCHEDULE[sent];\n  if (days < dueDay) continue;\n  const nextDueDay = SCHEDULE[sent + 1];\n  const nextDue = nextDueDay === undefined ? 'done'\n    : new Date(first.getTime() + nextDueDay * DAY_MS).toISOString().slice(0, 10);\n  out.push({ json: {\n    name: lead.name, first_name: lead.first_name, phone: lead.phone,\n    service: lead.service, status: lead.status,\n    followup_day: dueDay, followup_number: sent + 1,\n    followup_message: MESSAGES[dueDay](lead),\n    to: lead.phone, message: MESSAGES[dueDay](lead),\n    next_followup_due: nextDue,\n    new_status: nextDueDay === undefined ? 'followup_done' : 'awaiting',\n    last_followup_at: $now\n  } });\n}\nreturn out;\n"
      },
      "position": [
        520,
        1760
      ],
      "type": "n8n-nodes-base.code",
      "typeVersion": 2
    },
    {
      "id": "5ecd3466-0f12-4732-9e66-90b921f4dd3c",
      "name": "Send Follow-Up",
      "parameters": {
        "resource": "message",
        "operation": "send",
        "from": "={{ $vars.CLIENT_TWILIO_NUMBER }}",
        "to": "={{ $json.to }}",
        "message": "={{ $json.followup_message }}"
      },
      "position": [
        780,
        1760
      ],
      "type": "n8n-nodes-base.twilio",
      "typeVersion": 1,
      "credentials": {
        "twilioApi": {
          "id": null,
          "name": "CLIENT TWILIO CREDENTIAL - create in n8n from the client's own Twilio account"
        }
      }
    },
    {
      "id": "00ec631e-748b-4370-982f-cd80d33097cc",
      "name": "Update Lead Row",
      "parameters": {
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "followups_sent": "={{ $json.followup_number }}",
            "last_followup_at": "={{ $json.last_followup_at }}",
            "next_followup_due": "={{ $json.next_followup_due }}",
            "status": "={{ $json.new_status }}"
          }
        },
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "={{ $vars.LEAD_SHEET_URL }}"
        },
        "operation": "update",
        "options": {},
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "Lead Log"
        },
        "columnToMatchOn": "phone",
        "valueToMatchOn": "={{ $json.phone }}"
      },
      "position": [
        1040,
        1760
      ],
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.2,
      "credentials": {
        "googleSheetsOAuth2": {
          "id": null,
          "name": "CLIENT GOOGLE SHEETS CREDENTIAL - owner's Google account in n8n"
        }
      }
    },
    {
      "id": "813f64b2-9a06-471a-88c5-730003398928",
      "name": "Done \u2014 Follow-Up",
      "parameters": {},
      "position": [
        1300,
        1760
      ],
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1
    }
  ],
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  }
}