{
  "name": "SMS booking agent (ep07 EN, Blackcircuit Labs)",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "booking-check-availability",
        "responseMode": "responseNode",
        "options": {}
      },
      "name": "Check availability",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        0
      ],
      "webhookId": "booking-check-availability"
    },
    {
      "parameters": {
        "jsCode": "// Qué días revisar: el que pidió la familia, o los próximos 14.\nconst TZ = 'America/Chicago';\nconst req = $('Check availability').first().json, a = req.body?.args || req.body || {};\nconst ahora = a.ahora ? DateTime.fromISO(a.ahora, { zone: TZ }) : DateTime.now().setZone(TZ);\nconst fecha = a.fecha || a.date || '';\nlet desde = fecha ? DateTime.fromISO(String(fecha).slice(0, 10), { zone: TZ }).startOf('day') : ahora.startOf('day');\nconst valida = desde.isValid;\nif (!valida) desde = ahora.startOf('day');\nif (desde < ahora.startOf('day')) desde = ahora.startOf('day');\nconst hasta = fecha ? desde.endOf('day') : desde.plus({ days: 14 }).endOf('day');\nreturn [{ json: { desde: desde.toISO(), hasta: hasta.toISO(), ahora: ahora.toISO(), un_dia: !!fecha, valida } }];"
      },
      "name": "Date range",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        0
      ]
    },
    {
      "parameters": {
        "operation": "getAll",
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "your-calendar@gmail.com"
        },
        "returnAll": true,
        "timeMin": "={{ $json.desde }}",
        "timeMax": "={{ $json.hasta }}",
        "options": {
          "orderBy": "startTime",
          "recurringEventHandling": "expand"
        }
      },
      "name": "Events in range",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1.3,
      "position": [
        440,
        0
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "jsCode": "const TZ = 'America/Chicago', LANG = 'en', MSG = {\"opciones\": \"Options: A) {a} (start: {ia}) or B) {b} (start: {ib}). Offer both in one text.\", \"una\": \"Only one option: {a} (start: {ia}).\", \"ninguna\": \"No open times {cuando}.\", \"dia_cerrado\": \"No appointments that day.\", \"fecha_mala\": \"I couldn't read that date. Use YYYY-MM-DD.\", \"ocupado\": \"That time is no longer free. Use check_availability again and offer two other options.\", \"fuera\": \"That time is outside booking hours or too soon. Use check_availability.\", \"apartado\": \"Held: {cuando} for {nombre} (hold id: {id}). Now repeat the day, time and name, and ask whether to confirm.\", \"confirmado\": \"Confirmed: {resumen} on {cuando}.\", \"liberado\": \"Done, the time is free again.\", \"dias\": \"in the next 14 days\"};\n// Horario de citas (cámbialo aquí y en la plantilla 2): por día de la semana (0 = domingo), tramos [desde, hasta].\nconst HORAS = { 1: [[8, 12], [14, 18]], 2: [[8, 12], [14, 18]], 3: [[8, 12], [14, 18]], 4: [[8, 12], [14, 18]], 5: [[8, 12], [14, 18]], 6: [[8, 12]] };\nconst DURACION = 30, ANTICIPACION_H = 2;\nconst fmt = (t) => { t = t.setZone(TZ).setLocale(LANG);\n  return LANG === 'es' ? t.toFormat(\"cccc d 'de' LLLL 'a las' h:mm\") + (t.hour < 12 ? ' a. m.' : ' p. m.') : t.toFormat(\"cccc, LLLL d 'at' h:mm a\"); };\nconst dentro = (t, ahora) => { const tramos = HORAS[t.weekday % 7] || []; const fin = t.plus({ minutes: DURACION });\n  return t >= ahora.plus({ hours: ANTICIPACION_H }) && tramos.some(([a, b]) => t >= t.set({ hour: a, minute: 0, second: 0 }) && fin <= t.set({ hour: b, minute: 0, second: 0 })); };\nconst choca = (t, eventos, sinId) => { const fin = t.plus({ minutes: DURACION });\n  return eventos.filter(e => e.id && e.id !== sinId && e.start?.dateTime && e.status !== 'cancelled')\n    .filter(e => t < DateTime.fromISO(e.end.dateTime) && fin > DateTime.fromISO(e.start.dateTime)); };\n\nconst r = $('Date range').first().json;\nif (!r.valida) return [{ json: { result: MSG.fecha_mala } }];\nconst ahora = DateTime.fromISO(r.ahora, { zone: TZ }), desde = DateTime.fromISO(r.desde, { zone: TZ }), hasta = DateTime.fromISO(r.hasta, { zone: TZ });\nconst eventos = $input.all().map(i => i.json);\nconst libres = [];\nfor (let d = desde; d <= hasta; d = d.plus({ days: 1 })) {\n  for (const [a, b] of HORAS[d.weekday % 7] || []) {\n    for (let t = d.set({ hour: a, minute: 0 }); t.plus({ minutes: DURACION }) <= d.set({ hour: b, minute: 0 }); t = t.plus({ minutes: DURACION })) {\n      if (dentro(t, ahora) && !choca(t, eventos).length) libres.push(t);\n    }\n  }\n}\nif (!libres.length) return [{ json: { result: r.un_dia && !(HORAS[desde.weekday % 7]) ? MSG.dia_cerrado : MSG.ninguna.replace('{cuando}', r.un_dia ? fmt(desde).split(LANG === 'es' ? ' a las' : ' at')[0] : MSG.dias) } }];\n// Dos opciones de una vez: la primera libre y otra que le dé alternativa (otro día; si se pidió un día, otra franja).\nconst a1 = libres[0];\nconst a2 = libres.find(t => r.un_dia ? t >= a1.plus({ hours: 2 }) : !t.hasSame(a1, 'day')) || libres[1];\nif (!a2) return [{ json: { result: MSG.una.replace('{a}', fmt(a1)).replace('{ia}', a1.toISO({ suppressMilliseconds: true })) } }];\nreturn [{ json: { result: MSG.opciones.replace('{a}', fmt(a1)).replace('{ia}', a1.toISO({ suppressMilliseconds: true }))\n  .replace('{b}', fmt(a2)).replace('{ib}', a2.toISO({ suppressMilliseconds: true })),\n  opciones: [a1, a2].map(t => t.toISO({ suppressMilliseconds: true })) } }];"
      },
      "name": "Open slots",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        660,
        0
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ { result: $json.result, opciones: $json.opciones } }}",
        "options": {}
      },
      "name": "Answer: open times",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        880,
        0
      ]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "booking-hold",
        "responseMode": "responseNode",
        "options": {}
      },
      "name": "Hold slot",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        200
      ],
      "webhookId": "booking-hold"
    },
    {
      "parameters": {
        "operation": "getAll",
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "your-calendar@gmail.com"
        },
        "returnAll": true,
        "timeMin": "={{ DateTime.fromISO((($('Hold slot').first().json.body.args || $('Hold slot').first().json.body).inicio || ($('Hold slot').first().json.body.args || $('Hold slot').first().json.body).start)).minus({ hours: 3 }).toISO() }}",
        "timeMax": "={{ DateTime.fromISO((($('Hold slot').first().json.body.args || $('Hold slot').first().json.body).inicio || ($('Hold slot').first().json.body.args || $('Hold slot').first().json.body).start)).plus({ hours: 3 }).toISO() }}",
        "options": {
          "recurringEventHandling": "expand",
          "showDeleted": false
        }
      },
      "name": "Events near that time",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1.3,
      "position": [
        220,
        200
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "jsCode": "const TZ = 'America/Chicago', LANG = 'en', MSG = {\"opciones\": \"Options: A) {a} (start: {ia}) or B) {b} (start: {ib}). Offer both in one text.\", \"una\": \"Only one option: {a} (start: {ia}).\", \"ninguna\": \"No open times {cuando}.\", \"dia_cerrado\": \"No appointments that day.\", \"fecha_mala\": \"I couldn't read that date. Use YYYY-MM-DD.\", \"ocupado\": \"That time is no longer free. Use check_availability again and offer two other options.\", \"fuera\": \"That time is outside booking hours or too soon. Use check_availability.\", \"apartado\": \"Held: {cuando} for {nombre} (hold id: {id}). Now repeat the day, time and name, and ask whether to confirm.\", \"confirmado\": \"Confirmed: {resumen} on {cuando}.\", \"liberado\": \"Done, the time is free again.\", \"dias\": \"in the next 14 days\"};\n// Horario de citas (cámbialo aquí y en la plantilla 2): por día de la semana (0 = domingo), tramos [desde, hasta].\nconst HORAS = { 1: [[8, 12], [14, 18]], 2: [[8, 12], [14, 18]], 3: [[8, 12], [14, 18]], 4: [[8, 12], [14, 18]], 5: [[8, 12], [14, 18]], 6: [[8, 12]] };\nconst DURACION = 30, ANTICIPACION_H = 2;\nconst fmt = (t) => { t = t.setZone(TZ).setLocale(LANG);\n  return LANG === 'es' ? t.toFormat(\"cccc d 'de' LLLL 'a las' h:mm\") + (t.hour < 12 ? ' a. m.' : ' p. m.') : t.toFormat(\"cccc, LLLL d 'at' h:mm a\"); };\nconst dentro = (t, ahora) => { const tramos = HORAS[t.weekday % 7] || []; const fin = t.plus({ minutes: DURACION });\n  return t >= ahora.plus({ hours: ANTICIPACION_H }) && tramos.some(([a, b]) => t >= t.set({ hour: a, minute: 0, second: 0 }) && fin <= t.set({ hour: b, minute: 0, second: 0 })); };\nconst choca = (t, eventos, sinId) => { const fin = t.plus({ minutes: DURACION });\n  return eventos.filter(e => e.id && e.id !== sinId && e.start?.dateTime && e.status !== 'cancelled')\n    .filter(e => t < DateTime.fromISO(e.end.dateTime) && fin > DateTime.fromISO(e.start.dateTime)); };\n\n// Antes de apartar: ¿la hora es válida y nadie la tomó?\nconst req = $('Hold slot').first().json, a = req.body?.args || req.body || {};\nconst t = DateTime.fromISO(String(a.inicio || a.start || ''), { zone: TZ });\nconst ahora = a.ahora ? DateTime.fromISO(a.ahora, { zone: TZ }) : DateTime.now().setZone(TZ);\nif (!t.isValid || !dentro(t, ahora)) return [{ json: { libre: false, result: MSG.fuera } }];\nconst eventos = $input.all().map(i => i.json);\nif (choca(t, eventos).length) return [{ json: { libre: false, result: MSG.ocupado } }];\nreturn [{ json: { libre: true, inicio: t.toISO(), fin: t.plus({ minutes: DURACION }).toISO(), nombre: a.nombre || a.name || '',\n  motivo: a.motivo || a.reason || '', telefono: a.telefono || a.phone || '' } }];"
      },
      "name": "Still free?",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        440,
        200
      ]
    },
    {
      "parameters": {
        "conditions": {
          "combinator": "and",
          "conditions": [
            {
              "leftValue": "={{ $json.libre }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ]
        }
      },
      "name": "Free?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        660,
        200
      ]
    },
    {
      "parameters": {
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "your-calendar@gmail.com"
        },
        "start": "={{ $json.inicio }}",
        "end": "={{ $json.fin }}",
        "additionalFields": {
          "summary": "=On hold: {{ $json.nombre }}{{ $json.motivo ? ' (' + $json.motivo + ')' : '' }}",
          "description": "=Phone: {{ $json.telefono }}\nHeld by Leo (AI). Becomes «Visit:» when the caller confirms."
        }
      },
      "name": "Create hold",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1.3,
      "position": [
        880,
        200
      ]
    },
    {
      "parameters": {
        "operation": "getAll",
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "your-calendar@gmail.com"
        },
        "returnAll": true,
        "timeMin": "={{ DateTime.fromISO($json.start.dateTime).minus({ hours: 3 }).toISO() }}",
        "timeMax": "={{ DateTime.fromISO($json.start.dateTime).plus({ hours: 3 }).toISO() }}",
        "options": {
          "recurringEventHandling": "expand",
          "showDeleted": false
        }
      },
      "name": "Check again",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1.3,
      "position": [
        1100,
        200
      ],
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "jsCode": "const TZ = 'America/Chicago', LANG = 'en', MSG = {\"opciones\": \"Options: A) {a} (start: {ia}) or B) {b} (start: {ib}). Offer both in one text.\", \"una\": \"Only one option: {a} (start: {ia}).\", \"ninguna\": \"No open times {cuando}.\", \"dia_cerrado\": \"No appointments that day.\", \"fecha_mala\": \"I couldn't read that date. Use YYYY-MM-DD.\", \"ocupado\": \"That time is no longer free. Use check_availability again and offer two other options.\", \"fuera\": \"That time is outside booking hours or too soon. Use check_availability.\", \"apartado\": \"Held: {cuando} for {nombre} (hold id: {id}). Now repeat the day, time and name, and ask whether to confirm.\", \"confirmado\": \"Confirmed: {resumen} on {cuando}.\", \"liberado\": \"Done, the time is free again.\", \"dias\": \"in the next 14 days\"};\n// Horario de citas (cámbialo aquí y en la plantilla 2): por día de la semana (0 = domingo), tramos [desde, hasta].\nconst HORAS = { 1: [[8, 12], [14, 18]], 2: [[8, 12], [14, 18]], 3: [[8, 12], [14, 18]], 4: [[8, 12], [14, 18]], 5: [[8, 12], [14, 18]], 6: [[8, 12]] };\nconst DURACION = 30, ANTICIPACION_H = 2;\nconst fmt = (t) => { t = t.setZone(TZ).setLocale(LANG);\n  return LANG === 'es' ? t.toFormat(\"cccc d 'de' LLLL 'a las' h:mm\") + (t.hour < 12 ? ' a. m.' : ' p. m.') : t.toFormat(\"cccc, LLLL d 'at' h:mm a\"); };\nconst dentro = (t, ahora) => { const tramos = HORAS[t.weekday % 7] || []; const fin = t.plus({ minutes: DURACION });\n  return t >= ahora.plus({ hours: ANTICIPACION_H }) && tramos.some(([a, b]) => t >= t.set({ hour: a, minute: 0, second: 0 }) && fin <= t.set({ hour: b, minute: 0, second: 0 })); };\nconst choca = (t, eventos, sinId) => { const fin = t.plus({ minutes: DURACION });\n  return eventos.filter(e => e.id && e.id !== sinId && e.start?.dateTime && e.status !== 'cancelled')\n    .filter(e => t < DateTime.fromISO(e.end.dateTime) && fin > DateTime.fromISO(e.start.dateTime)); };\n\n// Después de apartar: si otra reserva del mismo horario se creó antes que la nuestra, gana la otra.\nconst mia = $('Create hold').first().json;\nconst t = DateTime.fromISO(mia.start.dateTime);\nconst otras = choca(t, $input.all().map(i => i.json), mia.id);\nconst perdi = otras.some(e => (e.created || '') < mia.created || ((e.created || '') === mia.created && e.id < mia.id));\nreturn [{ json: { perdi, id: mia.id, result: perdi ? MSG.ocupado\n  : MSG.apartado.replace('{cuando}', fmt(t)).replace('{nombre}', $('Still free?').first().json.nombre).replace('{id}', mia.id) } }];"
      },
      "name": "Clash?",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1320,
        200
      ]
    },
    {
      "parameters": {
        "conditions": {
          "combinator": "and",
          "conditions": [
            {
              "leftValue": "={{ $json.perdi }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ]
        }
      },
      "name": "Another hold won?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1540,
        200
      ]
    },
    {
      "parameters": {
        "operation": "delete",
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "your-calendar@gmail.com"
        },
        "eventId": "={{ $('Clash?').first().json.id }}",
        "options": {}
      },
      "name": "Delete my hold",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1.3,
      "position": [
        1760,
        200
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ { result: $('Clash?').first().json.result } }}",
        "options": {}
      },
      "name": "Answer: taken",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        1980,
        200
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ { result: $json.result, id: $json.id } }}",
        "options": {}
      },
      "name": "Answer: held",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        1980,
        400
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ { result: $json.result } }}",
        "options": {}
      },
      "name": "Answer: not possible",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        880,
        400
      ]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "booking-confirm",
        "responseMode": "responseNode",
        "options": {}
      },
      "name": "Confirm booking",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        600
      ],
      "webhookId": "booking-confirm"
    },
    {
      "parameters": {
        "operation": "get",
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "your-calendar@gmail.com"
        },
        "eventId": "={{ ($('Confirm booking').first().json.body.args || $('Confirm booking').first().json.body).id || ($('Confirm booking').first().json.body.args || $('Confirm booking').first().json.body).hold_id }}",
        "options": {}
      },
      "name": "Get hold",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1.3,
      "position": [
        220,
        600
      ]
    },
    {
      "parameters": {
        "operation": "update",
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "your-calendar@gmail.com"
        },
        "eventId": "={{ $json.id }}",
        "updateFields": {
          "summary": "={{ 'Visit: ' + $json.summary.replace('On hold: ', '') }}"
        }
      },
      "name": "Turn into visit",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1.3,
      "position": [
        440,
        600
      ]
    },
    {
      "parameters": {
        "jsCode": "const TZ = 'America/Chicago', LANG = 'en', MSG = {\"opciones\": \"Options: A) {a} (start: {ia}) or B) {b} (start: {ib}). Offer both in one text.\", \"una\": \"Only one option: {a} (start: {ia}).\", \"ninguna\": \"No open times {cuando}.\", \"dia_cerrado\": \"No appointments that day.\", \"fecha_mala\": \"I couldn't read that date. Use YYYY-MM-DD.\", \"ocupado\": \"That time is no longer free. Use check_availability again and offer two other options.\", \"fuera\": \"That time is outside booking hours or too soon. Use check_availability.\", \"apartado\": \"Held: {cuando} for {nombre} (hold id: {id}). Now repeat the day, time and name, and ask whether to confirm.\", \"confirmado\": \"Confirmed: {resumen} on {cuando}.\", \"liberado\": \"Done, the time is free again.\", \"dias\": \"in the next 14 days\"};\n// Horario de citas (cámbialo aquí y en la plantilla 2): por día de la semana (0 = domingo), tramos [desde, hasta].\nconst HORAS = { 1: [[8, 12], [14, 18]], 2: [[8, 12], [14, 18]], 3: [[8, 12], [14, 18]], 4: [[8, 12], [14, 18]], 5: [[8, 12], [14, 18]], 6: [[8, 12]] };\nconst DURACION = 30, ANTICIPACION_H = 2;\nconst fmt = (t) => { t = t.setZone(TZ).setLocale(LANG);\n  return LANG === 'es' ? t.toFormat(\"cccc d 'de' LLLL 'a las' h:mm\") + (t.hour < 12 ? ' a. m.' : ' p. m.') : t.toFormat(\"cccc, LLLL d 'at' h:mm a\"); };\nconst dentro = (t, ahora) => { const tramos = HORAS[t.weekday % 7] || []; const fin = t.plus({ minutes: DURACION });\n  return t >= ahora.plus({ hours: ANTICIPACION_H }) && tramos.some(([a, b]) => t >= t.set({ hour: a, minute: 0, second: 0 }) && fin <= t.set({ hour: b, minute: 0, second: 0 })); };\nconst choca = (t, eventos, sinId) => { const fin = t.plus({ minutes: DURACION });\n  return eventos.filter(e => e.id && e.id !== sinId && e.start?.dateTime && e.status !== 'cancelled')\n    .filter(e => t < DateTime.fromISO(e.end.dateTime) && fin > DateTime.fromISO(e.start.dateTime)); };\n\nconst e = $input.first().json;\nreturn [{ json: { result: MSG.confirmado.replace('{resumen}', e.summary).replace('{cuando}', fmt(DateTime.fromISO(e.start.dateTime))).replace(/m\\.\\./g, 'm.') } }];"
      },
      "name": "Confirmation text",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        660,
        600
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ { result: $json.result } }}",
        "options": {}
      },
      "name": "Answer: confirmed",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        880,
        600
      ]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "booking-release",
        "responseMode": "responseNode",
        "options": {}
      },
      "name": "Release slot",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        800
      ],
      "webhookId": "booking-release"
    },
    {
      "parameters": {
        "operation": "delete",
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "your-calendar@gmail.com"
        },
        "eventId": "={{ ($('Release slot').first().json.body.args || $('Release slot').first().json.body).id || ($('Release slot').first().json.body.args || $('Release slot').first().json.body).hold_id }}",
        "options": {}
      },
      "name": "Delete hold",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1.3,
      "position": [
        220,
        800
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ { result: \"Done, the time is free again.\" } }}",
        "options": {}
      },
      "name": "Answer: released",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        440,
        800
      ]
    },
    {
      "parameters": {
        "toolDescription": "Returns two open times at the office. No date: the first two open times. With a date (YYYY-MM-DD): that day's.",
        "method": "POST",
        "url": "http://localhost:5678/webhook/booking-check-availability",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ date: $fromAI('date', 'Date YYYY-MM-DD if the parent asked for a day; empty otherwise', 'string') }) }}",
        "options": {}
      },
      "name": "check_availability",
      "type": "n8n-nodes-base.httpRequestTool",
      "typeVersion": 4.2,
      "position": [
        440,
        1400
      ]
    },
    {
      "parameters": {
        "toolDescription": "Holds the time the parent picked, after checking it's still free. Returns the hold id or says it's taken.",
        "method": "POST",
        "url": "http://localhost:5678/webhook/booking-hold",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ start: $fromAI('start', 'Exact start of the chosen time, as check_availability gave it (ISO)', 'string'), name: $fromAI('name', 'Name of the child', 'string'), reason: $fromAI('reason', 'checkup, vaccines or sick visit', 'string'), phone: $('Data').first().json.sesion }) }}",
        "options": {}
      },
      "name": "hold_slot",
      "type": "n8n-nodes-base.httpRequestTool",
      "typeVersion": 4.2,
      "position": [
        660,
        1400
      ]
    },
    {
      "parameters": {
        "toolDescription": "Confirms the held visit, only after the parent said yes.",
        "method": "POST",
        "url": "http://localhost:5678/webhook/booking-confirm",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ hold_id: $fromAI('hold_id', 'The hold id that hold_slot returned', 'string') }) }}",
        "options": {}
      },
      "name": "confirm_booking",
      "type": "n8n-nodes-base.httpRequestTool",
      "typeVersion": 4.2,
      "position": [
        880,
        1400
      ]
    },
    {
      "parameters": {
        "toolDescription": "Releases a held time if the parent said no or wants another one.",
        "method": "POST",
        "url": "http://localhost:5678/webhook/booking-release",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ hold_id: $fromAI('hold_id', 'The hold id that hold_slot returned', 'string') }) }}",
        "options": {}
      },
      "name": "release_slot",
      "type": "n8n-nodes-base.httpRequestTool",
      "typeVersion": 4.2,
      "position": [
        1100,
        1400
      ]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "booking-sms",
        "responseMode": "responseNode",
        "options": {}
      },
      "name": "SMS received",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        1000
      ],
      "webhookId": "booking-sms"
    },
    {
      "parameters": {
        "respondWith": "text",
        "responseBody": "<Response></Response>",
        "options": {
          "responseHeaders": {
            "entries": [
              {
                "name": "Content-Type",
                "value": "text/xml"
              }
            ]
          }
        }
      },
      "name": "Answer Twilio (empty)",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        440,
        1000
      ]
    },
    {
      "parameters": {
        "operation": "removeItemsSeenInPreviousExecutions",
        "dedupeValue": "={{ $json.body.MessageSid }}",
        "options": {}
      },
      "name": "No repeats",
      "type": "n8n-nodes-base.removeDuplicates",
      "typeVersion": 2,
      "position": [
        660,
        1000
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "name": "sesion",
              "type": "string",
              "value": "={{ $('SMS received').first().json.body.From }}"
            },
            {
              "name": "texto",
              "type": "string",
              "value": "={{ $('SMS received').first().json.body.Body }}"
            }
          ]
        }
      },
      "name": "Data",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        880,
        1000
      ]
    },
    {
      "parameters": {
        "conditions": {
          "combinator": "and",
          "conditions": [
            {
              "leftValue": "={{ ($json.texto || '').trim().toLowerCase() }}",
              "rightValue": "^(stop|stopall|unsubscribe|cancel|end|quit|optout|revoke|help|info|start|unstop)$",
              "operator": {
                "type": "string",
                "operation": "regex"
              }
            }
          ]
        }
      },
      "name": "Opt-out word?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1100,
        1000
      ]
    },
    {
      "parameters": {},
      "name": "Twilio handles it",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        0,
        1200
      ]
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "={{ $('Data').first().json.texto }}",
        "options": {
          "systemMessage": "=Today is {{ $now.setZone('America/Chicago').toFormat(\"cccc, LLLL d, yyyy, h:mm a\") }} (Central Time).\n\nYou are Leo, the AI scheduler at Dr. Paula's pediatric office in Austin, TX.\nYou answer the office's text messages. You only book, change or cancel appointments. You are not a doctor.\n\nHOW YOU TEXT\n- The first time, introduce yourself like this: \"Hi, this is Leo, the AI scheduler at Dr. Paula's office. I can help you book a visit.\"\n- Short, friendly texts. One question at a time. No emojis, no lists, no links.\n- Write times like \"Tuesday, Dec 1 at 3 PM\".\n\nHOW YOU BOOK (always in this order)\n1. Ask for the child's name and the reason: checkup, vaccines or sick visit.\n2. Use check_availability and offer the TWO options it returns, in one text, with their day and time. For example: \"Would Tuesday, Dec 1 at 3 PM or Wednesday, Dec 2 at 10 AM work?\". If they want another day, use check_availability with that date.\n3. When they pick one, use hold_slot with that start time and the child's name. If hold_slot says it's no longer free, say so and go back to step 2.\n4. If hold_slot worked, repeat the real name, day and time and ask whether to confirm. For example: \"I'm holding Tuesday, Dec 1 at 3 PM for Tom. Shall I confirm it?\"\n5. Only when they say yes, use confirm_booking with the hold id. If they say no or want another time, use release_slot and go back to step 2.\n6. When it's confirmed, say it with the real name, day and time. For example: \"You're all set: Tom on Tuesday, Dec 1 at 3 PM. Please bring the vaccine record. To change it, just text us here.\"\n- Never say an appointment is booked unless confirm_booking says it's confirmed.\n- Never offer a time that check_availability didn't give you.\n\nHEALTH QUESTIONS (you don't answer them)\n- If they ask about symptoms, fever, medicine, doses or any medical question, reply:\n  \"That's a question for Dr. Paula. I've passed her your message and the office will get back to you. If it's an emergency, call 911.\"\n  and give no advice, even if they insist.\n\nWHAT YOU NEVER DO\n- Give medical advice or say whether something \"is normal\".\n- Ask for Social Security numbers, insurance numbers or card details.\n- Text anyone first: you only reply to people who text the office.\n\nWHAT YOU KNOW ABOUT THE OFFICE\nOFFICE: Dr. Paula's pediatric office · 8 Example St, Suite 201, Austin, TX\n\nBOOKING HOURS (Central Time)\n- Monday to Friday: 8 AM to 12 PM and 2 PM to 6 PM\n- Saturday: 8 AM to 12 PM\n- Sundays and public holidays: no appointments\n- Every visit is 30 minutes. Visits are booked at least 2 hours ahead.\n\nVISIT TYPES\n- Well-child checkup\n- Vaccines\n- Sick visit (an emergency is not booked: call 911 or go to the ER)\n\nBEFORE THE VISIT\n- Arrive 10 minutes early with the vaccine record.\n- To cancel or change, text this number.\n\nLAST UPDATED: date"
        }
      },
      "name": "Leo",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        1540,
        1000
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "sessionIdType": "customKey",
        "sessionKey": "={{ $('Data').first().json.sesion }}",
        "contextWindowLength": 16
      },
      "name": "Memory per caller",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "typeVersion": 1,
      "position": [
        220,
        1400
      ]
    },
    {
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "gpt-5-mini"
        },
        "options": {}
      },
      "name": "Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.3,
      "position": [
        0,
        1400
      ]
    },
    {
      "parameters": {
        "conditions": {
          "combinator": "and",
          "conditions": [
            {
              "leftValue": "={{ $json.texto.toLowerCase() }}",
              "rightValue": "fever|temperature|cough|vomit|throw(ing|s)? up|diarrh|pain|hurt|bleed|blood|medicine|medication|dose|dosage|tylenol|motrin|advil|ibuprofen|acetaminophen|antibiotic|symptom|rash|seizure|breath|faint|allerg|reaction",
              "operator": {
                "type": "string",
                "operation": "regex"
              }
            }
          ]
        }
      },
      "name": "Health question?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1320,
        1000
      ]
    },
    {
      "parameters": {
        "sendTo": "paula@example.com",
        "subject": "Leo passed you a health question",
        "emailType": "text",
        "message": "=From: {{ $('Data').first().json.sesion }}\nMessage: {{ $('Data').first().json.texto }}\n\nLeo gave no advice and told the parent the office will get back to them. Text them back from the office line."
      },
      "name": "Email Dr. Paula",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2,
      "position": [
        220,
        1200
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "name": "output",
              "type": "string",
              "value": "That's a question for Dr. Paula. I've passed her your message and the office will get back to you. If it's an emergency, call 911."
            }
          ]
        }
      },
      "name": "Fixed health reply",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        440,
        1200
      ]
    },
    {
      "parameters": {
        "from": "+15550100000",
        "to": "={{ $('Data').first().json.sesion }}",
        "message": "={{ $json.output }}",
        "options": {}
      },
      "name": "Send reply",
      "type": "n8n-nodes-base.twilio",
      "typeVersion": 1,
      "position": [
        1980,
        1000
      ]
    },
    {
      "parameters": {
        "from": "+15550100000",
        "to": "={{ $('Data').first().json.sesion }}",
        "message": "={{ $json.output }}",
        "options": {}
      },
      "name": "Send health reply",
      "type": "n8n-nodes-base.twilio",
      "typeVersion": 1,
      "position": [
        660,
        1200
      ]
    },
    {
      "parameters": {
        "content": "## SMS booking agent (ep07, English)\n1. Assign credentials: Twilio, Google Calendar, OpenAI and Gmail.\n2. Change `your-calendar@gmail.com` in the calendar nodes and `paula@example.com` in **Email Dr. Paula**.\n3. Your hours go in **Open slots**, **Still free?** and **Clash?** (the HORAS line: hours by weekday).\n4. Put your Twilio number in **Send reply** and **Send health reply**. If n8n isn't at http://localhost:5678, change it in Leo's four tools.\n5. Activate, then paste the production URL of **SMS received** in your Twilio number's messaging webhook.\nSample data is fictional. Blackcircuit Labs.",
        "height": 300,
        "width": 420
      },
      "name": "Read me",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -520,
        -380
      ]
    }
  ],
  "connections": {
    "Check availability": {
      "main": [
        [
          {
            "node": "Date range",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Date range": {
      "main": [
        [
          {
            "node": "Events in range",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Events in range": {
      "main": [
        [
          {
            "node": "Open slots",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Open slots": {
      "main": [
        [
          {
            "node": "Answer: open times",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Hold slot": {
      "main": [
        [
          {
            "node": "Events near that time",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Events near that time": {
      "main": [
        [
          {
            "node": "Still free?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Still free?": {
      "main": [
        [
          {
            "node": "Free?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Free?": {
      "main": [
        [
          {
            "node": "Create hold",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Answer: not possible",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create hold": {
      "main": [
        [
          {
            "node": "Check again",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check again": {
      "main": [
        [
          {
            "node": "Clash?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Clash?": {
      "main": [
        [
          {
            "node": "Another hold won?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Another hold won?": {
      "main": [
        [
          {
            "node": "Delete my hold",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Answer: held",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Delete my hold": {
      "main": [
        [
          {
            "node": "Answer: taken",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Confirm booking": {
      "main": [
        [
          {
            "node": "Get hold",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get hold": {
      "main": [
        [
          {
            "node": "Turn into visit",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Turn into visit": {
      "main": [
        [
          {
            "node": "Confirmation text",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Confirmation text": {
      "main": [
        [
          {
            "node": "Answer: confirmed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Release slot": {
      "main": [
        [
          {
            "node": "Delete hold",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Delete hold": {
      "main": [
        [
          {
            "node": "Answer: released",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "SMS received": {
      "main": [
        [
          {
            "node": "Answer Twilio (empty)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Answer Twilio (empty)": {
      "main": [
        [
          {
            "node": "No repeats",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "No repeats": {
      "main": [
        [
          {
            "node": "Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Data": {
      "main": [
        [
          {
            "node": "Opt-out word?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Model": {
      "ai_languageModel": [
        [
          {
            "node": "Leo",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Memory per caller": {
      "ai_memory": [
        [
          {
            "node": "Leo",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "check_availability": {
      "ai_tool": [
        [
          {
            "node": "Leo",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "hold_slot": {
      "ai_tool": [
        [
          {
            "node": "Leo",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "confirm_booking": {
      "ai_tool": [
        [
          {
            "node": "Leo",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "release_slot": {
      "ai_tool": [
        [
          {
            "node": "Leo",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Opt-out word?": {
      "main": [
        [
          {
            "node": "Twilio handles it",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Health question?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Health question?": {
      "main": [
        [
          {
            "node": "Email Dr. Paula",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Leo",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Email Dr. Paula": {
      "main": [
        [
          {
            "node": "Fixed health reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Leo": {
      "main": [
        [
          {
            "node": "Send reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fixed health reply": {
      "main": [
        [
          {
            "node": "Send health reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "timezone": "America/Chicago"
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false,
    "generatedBy": "tools/material_flujo_agenda.py"
  }
}
