{
  "id": "MirraWaAssistant01",
  "name": "WhatsApp + Instagram AI assistant: replies, lead sheet, HubSpot, hand-off, reminders (Mirra Aesthetics demo)",
  "nodes": [
    {
      "parameters": {
        "content": "## WhatsApp / Instagram AI assistant (Mirra Aesthetics demo)\n1. Meta (WhatsApp Cloud API + Instagram) or Twilio posts every message here.\n2. The webhook answers **200 at once** (Meta retries slow webhooks), then the flow runs.\n3. `bot.php` (the demo's own code) answers from the price list + FAQ with tools: buttons, lists, location, booking, hand-off.\n4. Replies go out via Graph API `/messages` (or Twilio). Lead row → Google Sheets, contact → HubSpot, hand-off → Slack.\n\n**Env vars:** META_VERIFY_TOKEN, META_APP_SECRET, BOT_URL, CLINIC_LAT, CLINIC_LNG, CLINIC_MAPS_URL, NODE_FUNCTION_ALLOW_BUILTIN=crypto\n**Credentials:** WhatsApp system-user token (HTTP Header Auth), Bot token (HTTP Header Auth), Google Sheets, HubSpot private app, Slack, Twilio",
        "height": 300,
        "width": 760
      },
      "id": "89082415-7cf0-58c6-aa01-8778e9e17873",
      "name": "Note: overview",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -60,
        -380
      ]
    },
    {
      "parameters": {
        "content": "## 24-hour customer service window\nFree-form replies (text, buttons, lists) are allowed only within **24 h of the customer's last message**. This flow always replies inside that window.\n\nAnything later (reminders, follow-ups, re-engagement) must be an **approved message template** (category Utility or Marketing), see the reminder branch below. Template approval usually takes minutes to a day.",
        "height": 300,
        "width": 520,
        "color": "6"
      },
      "id": "677483dc-30f4-55d9-8823-ee9acb96b8a6",
      "name": "Note: 24h window",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1680,
        -380
      ]
    },
    {
      "parameters": {
        "httpMethod": "GET",
        "path": "wa-assistant",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "bff8bf0b-f8a1-5248-bd82-68210c5acd81",
      "name": "Meta: verify webhook (GET)",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        -40
      ],
      "webhookId": "1da10d4d-8703-59c7-b334-74e5271c62af"
    },
    {
      "parameters": {
        "jsCode": "// Meta calls GET ?hub.mode=subscribe&hub.verify_token=...&hub.challenge=... once, when you save the webhook URL.\nconst q = $input.first().json.query || {};\nconst ok = q['hub.mode'] === 'subscribe' && q['hub.verify_token'] === $env.META_VERIFY_TOKEN;\nreturn [{ json: { ok, challenge: ok ? String(q['hub.challenge'] || '') : 'forbidden' } }];"
      },
      "id": "7cd050be-860f-5e0a-98a8-8b4249515ea9",
      "name": "Check verify token",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        -40
      ]
    },
    {
      "parameters": {
        "respondWith": "text",
        "responseBody": "={{ $json.challenge }}",
        "options": {
          "responseCode": "={{ $json.ok ? 200 : 403 }}"
        }
      },
      "id": "184076e2-5891-5414-bff1-5335ea1f7bdc",
      "name": "Return hub.challenge",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        440,
        -40
      ]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "wa-assistant",
        "responseMode": "onReceived",
        "options": {
          "rawBody": true
        }
      },
      "id": "de9acbe9-2652-5c00-99be-68e581d60510",
      "name": "Meta webhook: WhatsApp + Instagram",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        200
      ],
      "webhookId": "edc1ebc9-daa1-5ab9-96a8-c1084962c026"
    },
    {
      "parameters": {
        "jsCode": "// 1) Verify the X-Hub-Signature-256 header (HMAC-SHA256 of the raw body with the Meta app secret).\n//    Needs NODE_FUNCTION_ALLOW_BUILTIN=crypto and the webhook option \"Raw body\" on.\n// 2) Turn WhatsApp Cloud API and Instagram messaging payloads into one simple shape.\n// 3) Skip delivery/read statuses, echoes and duplicates (Meta retries deliveries).\nconst crypto = require('crypto');\nconst item = $input.first();\nconst raw = item.binary?.data ? Buffer.from(item.binary.data.data, 'base64') : Buffer.from(JSON.stringify(item.json.body));\nconst sig = (item.json.headers || {})['x-hub-signature-256'] || '';\nconst expected = 'sha256=' + crypto.createHmac('sha256', $env.META_APP_SECRET).update(raw).digest('hex');\nif (sig.length !== expected.length || !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))) return [];\n\nconst body = item.json.body || JSON.parse(raw.toString('utf8'));\nconst seen = $getWorkflowStaticData('global');\nseen.ids = seen.ids || [];\nconst out = [];\nconst push = (m) => {\n  if (!m.text || seen.ids.includes(m.message_id)) return;\n  seen.ids.push(m.message_id); if (seen.ids.length > 500) seen.ids.shift();\n  out.push({ json: { ...m, text: String(m.text).slice(0, 500) } });\n};\n\nfor (const entry of body.entry || []) {\n  // WhatsApp Cloud API: entry[].changes[].value.messages[]\n  for (const ch of entry.changes || []) {\n    const v = ch.value || {};\n    const names = Object.fromEntries((v.contacts || []).map((c) => [c.wa_id, c.profile?.name || '']));\n    for (const m of v.messages || []) {\n      const i = m.interactive || {};\n      const reply = i.button_reply || i.list_reply || null;\n      push({\n        provider: 'meta', channel: 'whatsapp', phone_number_id: v.metadata?.phone_number_id, user_id: m.from, name: names[m.from] || '',\n        message_id: m.id,\n        text: m.type === 'text' ? m.text?.body : reply ? reply.title : m.type === 'button' ? m.button?.text\n          : m.type === 'location' ? `[Shared a location: ${m.location?.latitude}, ${m.location?.longitude}]`\n          : `[Sent a ${m.type}. Please reply with text]`,\n        reply_id: reply ? reply.id : '',\n      });\n    }\n  }\n  // Instagram DMs (Messenger API for Instagram): entry[].messaging[]\n  for (const ev of entry.messaging || []) {\n    if (!ev.message || ev.message.is_echo) continue;\n    push({\n      provider: 'meta', channel: 'instagram', user_id: ev.sender.id, name: '', message_id: ev.message.mid,\n      text: ev.message.text || (ev.message.attachments ? '[Sent an attachment. Please reply with text]' : ''),\n      reply_id: ev.message.quick_reply?.payload || '',\n    });\n  }\n}\nreturn out;"
      },
      "id": "81475c08-e7bb-5661-a718-8d8cd2cf3ea3",
      "name": "Verify signature + normalise",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        200
      ]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "wa-assistant-twilio",
        "responseMode": "onReceived",
        "options": {
          "responseData": "noData"
        }
      },
      "id": "25288ad2-678b-5af2-ba9f-a8cfcfd0827b",
      "name": "Twilio webhook (alternative)",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        420
      ],
      "webhookId": "e70cd6f9-66ec-5411-9e1e-aa5dbdf3a0b8"
    },
    {
      "parameters": {
        "jsCode": "// Twilio WhatsApp sends application/x-www-form-urlencoded: From=whatsapp:+9715..., Body, ProfileName, ButtonPayload.\n// Validate X-Twilio-Signature in production (HMAC-SHA1 of URL + sorted params with the auth token).\nconst b = $input.first().json.body || {};\nif (!b.From || !b.MessageSid) return [];\nreturn [{ json: {\n  provider: 'twilio', channel: 'whatsapp', user_id: String(b.From).replace('whatsapp:', ''), name: b.ProfileName || '',\n  message_id: b.MessageSid, text: String(b.ButtonText || b.Body || '').slice(0, 500), reply_id: b.ButtonPayload || '',\n  to: b.To,\n} }];"
      },
      "id": "f41eccd2-2adf-58bd-a0e2-d1d508e42680",
      "name": "Normalise Twilio",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        420
      ]
    },
    {
      "parameters": {},
      "id": "f92ee06f-79a8-58e3-b23e-ca096691d997",
      "name": "Merge channels",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        440,
        300
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $env.BOT_URL }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ channel: $json.channel, user_id: $json.user_id, name: $json.name, text: $json.text, reply_id: $json.reply_id }) }}",
        "options": {
          "timeout": 45000
        }
      },
      "id": "692ac85a-805e-5b5b-9b49-397d8944b2bf",
      "name": "Ask the assistant",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        660,
        300
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "bot-token",
          "name": "Assistant bot token (Bearer)"
        }
      },
      "retryOnFail": true,
      "maxTries": 2,
      "waitBetweenTries": 1500
    },
    {
      "parameters": {
        "jsCode": "// Assistant messages -> provider payloads. WhatsApp limits: 3 reply buttons (20 chars), list rows 10 (24 chars title, 72 description).\nconst inMsg = $('Merge channels').first().json;\nconst res = $input.first().json;\nconst clip = (s, n) => String(s || '').slice(0, n);\nconst out = [];\nfor (const m of res.messages || []) {\n  let text = m.text || '';\n  if (m.type === 'booking') text = `✅ Consultation confirmed (${m.ref})\\n${m.name} · ${m.slot}\\n${m.address}`;\n  if (m.type === 'system') continue; // internal note, not sent to the customer\n\n  if (inMsg.provider === 'twilio') {\n    // Interactive messages on Twilio need pre-approved Content templates; send plain text with the options listed.\n    const it = m.interactive;\n    if (it?.type === 'buttons') text += '\\n\\n' + it.buttons.map((b, i) => `${i + 1}. ${b.title}`).join('\\n');\n    if (m.type === 'location') text = `${m.name}\\n${m.address}\\n${$env.CLINIC_MAPS_URL || ''}`;\n    out.push({ json: { provider: 'twilio', form: { From: inMsg.to, To: 'whatsapp:' + inMsg.user_id, Body: clip(text, 1600) } } });\n    continue;\n  }\n\n  if (inMsg.channel === 'instagram') {\n    const it = m.interactive;\n    const options = it?.type === 'buttons' ? it.buttons : it?.type === 'list' ? it.sections.flatMap((s) => s.rows).slice(0, 13) : [];\n    if (m.type === 'location') text = `${m.name}\\n${m.address}`;\n    const message = { text: clip(text, 1000) };\n    if (options.length) message.quick_replies = options.map((o) => ({ content_type: 'text', title: clip(o.title, 20), payload: o.id }));\n    out.push({ json: { provider: 'meta', url: `${'https://graph.facebook.com/v21.0'}/me/messages`, body: { recipient: { id: inMsg.user_id }, messaging_type: 'RESPONSE', message } } });\n    continue;\n  }\n\n  const base = { messaging_product: 'whatsapp', recipient_type: 'individual', to: inMsg.user_id };\n  let payload;\n  if (m.type === 'location') {\n    payload = { ...base, type: 'location', location: { latitude: Number($env.CLINIC_LAT), longitude: Number($env.CLINIC_LNG), name: m.name, address: m.address } };\n  } else if (m.interactive?.type === 'buttons') {\n    payload = { ...base, type: 'interactive', interactive: { type: 'button', body: { text: clip(text, 1024) },\n      action: { buttons: m.interactive.buttons.slice(0, 3).map((b) => ({ type: 'reply', reply: { id: clip(b.id, 256), title: clip(b.title, 20) } })) } } };\n  } else if (m.interactive?.type === 'list') {\n    payload = { ...base, type: 'interactive', interactive: { type: 'list', body: { text: clip(text, 1024) },\n      action: { button: clip(m.interactive.button, 20), sections: m.interactive.sections.map((s) => ({ title: clip(s.title, 24),\n        rows: s.rows.map((r) => ({ id: clip(r.id, 200), title: clip(r.title, 24), description: clip(r.description, 72) })) })) } } };\n  } else {\n    payload = { ...base, type: 'text', text: { preview_url: false, body: clip(text, 4096) } };\n  }\n  out.push({ json: { provider: 'meta', url: `${'https://graph.facebook.com/v21.0'}/${inMsg.phone_number_id}/messages`, body: payload } });\n}\nreturn out;"
      },
      "id": "b2f41844-2844-5dd4-9046-6c036c0cf868",
      "name": "Build channel messages",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        900,
        160
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.provider }}",
                    "rightValue": "meta",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Meta"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.provider }}",
                    "rightValue": "twilio",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Twilio"
            }
          ]
        },
        "options": {}
      },
      "id": "8ba40ce8-e707-5fe8-9aae-a6500673d835",
      "name": "Meta or Twilio?",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        1120,
        160
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $json.url }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.body) }}",
        "options": {
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 400
            }
          }
        }
      },
      "id": "8fd9f750-7b86-53cf-899c-768201687b26",
      "name": "Send via Graph API",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1360,
        80
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "wa-token",
          "name": "WhatsApp system user token (Bearer)"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://api.twilio.com/2010-04-01/Accounts/{{ $env.TWILIO_ACCOUNT_SID }}/Messages.json",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "twilioApi",
        "sendBody": true,
        "contentType": "form-urlencoded",
        "bodyParameters": {
          "parameters": [
            {
              "name": "From",
              "value": "={{ $json.form.From }}"
            },
            {
              "name": "To",
              "value": "={{ $json.form.To }}"
            },
            {
              "name": "Body",
              "value": "={{ $json.form.Body }}"
            }
          ]
        },
        "options": {}
      },
      "id": "4513f332-08f6-530b-aacc-1a628d6742e5",
      "name": "Send via Twilio",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1360,
        240
      ],
      "credentials": {
        "twilioApi": {
          "id": "twilio-demo",
          "name": "Twilio (demo)"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// One row per customer (key = WhatsApp number / Instagram id). Phone is stored masked in the sheet for privacy.\nconst inMsg = $('Merge channels').first().json;\nconst r = $('Ask the assistant').first().json;\nconst L = r.lead || {};\nreturn [{ json: {\n  key: `${inMsg.channel}:${inMsg.user_id}`,\n  updated: new Date().toISOString(),\n  name: L.name || inMsg.name || '',\n  phone: inMsg.channel === 'whatsapp' ? '+' + String(inMsg.user_id).replace(/^\\+/, '').replace(/\\d(?=\\d{4})/g, '•') : '',\n  channel: inMsg.channel, interest: L.interest || '', budget: L.budget || '', timing: L.timing || '',\n  slot: L.slot || '', booking: L.booking || '', status: L.status || 'New',\n  has_lead: Boolean(L.name || L.interest || L.budget), handoff: Boolean(r.handoff),\n  handoff_reason: r.handoff?.reason || '', handoff_summary: r.handoff?.summary || '',\n  wa_id: inMsg.user_id, engine: r.engine, cost: r.cost,\n} }];"
      },
      "id": "96caed84-1b08-5121-8ec8-ece16891c323",
      "name": "Lead fields",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        900,
        460
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          },
          "conditions": [
            {
              "id": "cca4ded9-e190-5db6-876e-1173d25c0cc1",
              "leftValue": "={{ $json.has_lead }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "9dc7a2e9-3daf-5d55-b7fe-3c6b75bc368a",
      "name": "Lead info captured?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1120,
        460
      ]
    },
    {
      "parameters": {
        "operation": "appendOrUpdate",
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "1MirraLeadsDemoSheetId-replace-me",
          "cachedResultName": "Mirra – WhatsApp leads"
        },
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "gid=0",
          "cachedResultName": "Leads"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Key": "={{ $json.key }}",
            "Updated": "={{ $json.updated }}",
            "Name": "={{ $json.name }}",
            "Phone": "={{ $json.phone }}",
            "Channel": "={{ $json.channel }}",
            "Interest": "={{ $json.interest }}",
            "Budget": "={{ $json.budget }}",
            "Timing": "={{ $json.timing }}",
            "Slot": "={{ $json.slot }}",
            "Booking": "={{ $json.booking }}",
            "Status": "={{ $json.status }}"
          },
          "matchingColumns": [
            "Key"
          ],
          "schema": []
        },
        "options": {}
      },
      "id": "22aa919d-a190-568d-b22f-5cc5fcc20b67",
      "name": "Google Sheets: upsert lead row",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1360,
        400
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "gs-demo",
          "name": "Google Sheets (demo)"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.hubapi.com/crm/v3/objects/contacts/batch/upsert",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "hubspotAppToken",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ inputs: [{ idProperty: 'whatsapp_id', id: $('Lead fields').first().json.wa_id, properties: { firstname: $('Lead fields').first().json.name, hs_lead_status: $('Lead fields').first().json.status === 'Booked' ? 'IN_PROGRESS' : 'NEW', lifecyclestage: 'lead', treatment_interest: $('Lead fields').first().json.interest, budget_range: $('Lead fields').first().json.budget, consultation_slot: $('Lead fields').first().json.slot, lead_channel: $('Lead fields').first().json.channel } }] }) }}",
        "options": {}
      },
      "id": "bc672da8-59f2-5023-97ff-a19b93122be1",
      "name": "HubSpot: upsert contact",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1600,
        400
      ],
      "credentials": {
        "hubspotAppToken": {
          "id": "hubspot-demo",
          "name": "HubSpot private app (demo)"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          },
          "conditions": [
            {
              "id": "135ba01c-799e-54bd-a9b2-a64a0a7a1390",
              "leftValue": "={{ $('Lead fields').first().json.handoff }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "fd241c56-11fe-5ab5-83d1-63ca6309e2ef",
      "name": "Hand-off?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1120,
        640
      ]
    },
    {
      "parameters": {
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "name",
          "value": "#front-desk"
        },
        "text": "=:raising_hand: *WhatsApp hand-off* ({{ $('Lead fields').first().json.handoff_reason }}) from {{ $('Lead fields').first().json.name || 'a customer' }} on {{ $('Lead fields').first().json.channel }}\n{{ $('Lead fields').first().json.handoff_summary }}\nReply from the shared inbox; the bot is paused for this chat.",
        "otherOptions": {}
      },
      "id": "08d030a0-f32b-5947-bbe7-d7cce93a7cb5",
      "name": "Slack: #front-desk",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.2,
      "position": [
        1360,
        620
      ],
      "credentials": {
        "slackApi": {
          "id": "slack-demo",
          "name": "Slack (demo)"
        }
      }
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "days",
              "triggerAtHour": 10
            }
          ]
        }
      },
      "id": "82c6102f-ba11-59a8-aea7-65a03a8edd75",
      "name": "Every day 10:00",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        860
      ]
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "1MirraLeadsDemoSheetId-replace-me",
          "cachedResultName": "Mirra – WhatsApp leads"
        },
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "gid=0",
          "cachedResultName": "Leads"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "Status",
              "lookupValue": "Booked"
            }
          ]
        },
        "options": {}
      },
      "id": "d751eed2-0e51-5c0a-9885-8c577f7ae7af",
      "name": "Google Sheets: tomorrow's bookings",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        220,
        860
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "gs-demo",
          "name": "Google Sheets (demo)"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          },
          "conditions": [
            {
              "id": "c45140b0-97cc-5796-a6d3-65b086f45a75",
              "leftValue": "={{ $json.Slot.startsWith($now.plus({ days: 1 }).toFormat('ccc')) }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "83edff33-6e42-5e4b-bbd7-b64c79e8f4e4",
      "name": "Slot is tomorrow?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        440,
        860
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v21.0/{{ $env.WA_PHONE_NUMBER_ID }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ messaging_product: 'whatsapp', to: $json.Key.split(':')[1], type: 'template', template: { name: 'appointment_reminder', language: { code: 'en' }, components: [{ type: 'body', parameters: [{ type: 'text', text: $json.Name }, { type: 'text', text: $json.Slot }] }] } }) }}",
        "options": {}
      },
      "id": "e7f053d3-5b68-5815-a95d-f64b4ad99247",
      "name": "Send template: appointment_reminder",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        660,
        840
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "wa-token",
          "name": "WhatsApp system user token (Bearer)"
        }
      }
    },
    {
      "parameters": {
        "content": "**Template `appointment_reminder` (Utility)**\n\"Hi {{1}}, a reminder of your free skin consultation at Mirra Aesthetics on {{2}}. Reply here to reschedule.\"\nSubmit it in WhatsApp Manager → Message templates before going live.",
        "height": 200,
        "width": 420,
        "color": "4"
      },
      "id": "7e12279d-6ab9-5912-8f60-d31df5684d21",
      "name": "Note: template",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        880,
        780
      ]
    }
  ],
  "connections": {
    "Meta: verify webhook (GET)": {
      "main": [
        [
          {
            "node": "Check verify token",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check verify token": {
      "main": [
        [
          {
            "node": "Return hub.challenge",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Meta webhook: WhatsApp + Instagram": {
      "main": [
        [
          {
            "node": "Verify signature + normalise",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify signature + normalise": {
      "main": [
        [
          {
            "node": "Merge channels",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Twilio webhook (alternative)": {
      "main": [
        [
          {
            "node": "Normalise Twilio",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalise Twilio": {
      "main": [
        [
          {
            "node": "Merge channels",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge channels": {
      "main": [
        [
          {
            "node": "Ask the assistant",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ask the assistant": {
      "main": [
        [
          {
            "node": "Build channel messages",
            "type": "main",
            "index": 0
          },
          {
            "node": "Lead fields",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build channel messages": {
      "main": [
        [
          {
            "node": "Meta or Twilio?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Meta or Twilio?": {
      "main": [
        [
          {
            "node": "Send via Graph API",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send via Twilio",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Lead fields": {
      "main": [
        [
          {
            "node": "Lead info captured?",
            "type": "main",
            "index": 0
          },
          {
            "node": "Hand-off?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Lead info captured?": {
      "main": [
        [
          {
            "node": "Google Sheets: upsert lead row",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets: upsert lead row": {
      "main": [
        [
          {
            "node": "HubSpot: upsert contact",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Hand-off?": {
      "main": [
        [
          {
            "node": "Slack: #front-desk",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Every day 10:00": {
      "main": [
        [
          {
            "node": "Google Sheets: tomorrow's bookings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets: tomorrow's bookings": {
      "main": [
        [
          {
            "node": "Slot is tomorrow?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Slot is tomorrow?": {
      "main": [
        [
          {
            "node": "Send template: appointment_reminder",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "timezone": "Asia/Dubai"
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": []
}