{
  "name": "Asistente IA de clínica · WhatsApp + Calendar + HubSpot (demo EBworks)",
  "nodes": [
    {
      "parameters": {
        "updates": [
          "messages"
        ]
      },
      "id": "c1babe4e-b968-4f29-bf33-03e3ced1d8ad",
      "name": "WhatsApp Trigger",
      "type": "n8n-nodes-base.whatsAppTrigger",
      "typeVersion": 1,
      "position": [
        0,
        300
      ],
      "credentials": {
        "whatsAppTriggerApi": {
          "id": "PLACEHOLDER",
          "name": "WhatsApp OAuth (app de Meta)"
        }
      }
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "a1",
              "name": "telefono",
              "value": "={{ $json.messages?.[0]?.from }}",
              "type": "string"
            },
            {
              "id": "a2",
              "name": "nombre_perfil",
              "value": "={{ $json.contacts?.[0]?.profile?.name || '' }}",
              "type": "string"
            },
            {
              "id": "a3",
              "name": "tipo",
              "value": "={{ $json.messages?.[0]?.type }}",
              "type": "string"
            },
            {
              "id": "a4",
              "name": "texto",
              "value": "={{ $json.messages?.[0]?.text?.body || $json.messages?.[0]?.interactive?.button_reply?.title || $json.messages?.[0]?.interactive?.list_reply?.title || '' }}",
              "type": "string"
            },
            {
              "id": "a5",
              "name": "phone_number_id",
              "value": "={{ $json.metadata?.phone_number_id }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "356295be-5a02-4449-a74b-f3d0e0f01236",
      "name": "Normalizar mensaje",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        220,
        300
      ]
    },
    {
      "parameters": {
        "url": "={{ 'https://api.hubapi.com/crm/v3/objects/contacts/' + $json.telefono + '?idProperty=whatsapp_id&properties=bot_pausado,firstname' }}",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "hubspotAppToken",
        "options": {}
      },
      "id": "988bbb0a-1046-4a1a-909c-bd340857f8db",
      "name": "HubSpot · leer contacto",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        440,
        300
      ],
      "credentials": {
        "hubspotAppToken": {
          "id": "PLACEHOLDER",
          "name": "HubSpot private app (clínica)"
        }
      },
      "onError": "continueRegularOutput",
      "alwaysOutputData": true,
      "notes": "Si el contacto no existe (404) sigue igual: es un paciente nuevo."
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": false,
            "leftValue": "",
            "typeValidation": "loose"
          },
          "conditions": [
            {
              "id": "8b231bbf-2cb5-4843-bda5-a66aabb5a5c8",
              "leftValue": "={{ $json.properties?.bot_pausado }}",
              "rightValue": "true",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "c15e7961-37a7-45cf-8e62-3fa173e735cc",
      "name": "¿Atiende una persona?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        660,
        300
      ]
    },
    {
      "parameters": {
        "sendTo": "RECEPCION@CLINICA.ES",
        "subject": "={{ 'Nuevo mensaje de ' + $('Normalizar mensaje').item.json.telefono + ' (conversación en manos de recepción)' }}",
        "emailType": "text",
        "message": "={{ 'El paciente escribió: ' + $('Normalizar mensaje').item.json.texto + '\\n\\nEl asistente está en pausa. Para devolverle la conversación, poné bot_pausado = false en HubSpot.' }}",
        "options": {}
      },
      "id": "63cef500-23a0-488d-916b-6eadea15891e",
      "name": "Reenviar a recepción",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        900,
        100
      ],
      "credentials": {
        "gmailOAuth2": {
          "id": "PLACEHOLDER",
          "name": "Gmail (avisos)"
        }
      },
      "notes": "El bot NO responde mientras bot_pausado = true."
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": false,
            "leftValue": "",
            "typeValidation": "loose"
          },
          "conditions": [
            {
              "id": "84525191-0bf9-4610-b580-820844ff2c31",
              "leftValue": "={{ $('Normalizar mensaje').item.json.tipo }}",
              "rightValue": "^(text|interactive)$",
              "operator": {
                "type": "string",
                "operation": "regex"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "64f958ad-9302-4fae-9ee0-031127a8df8a",
      "name": "¿Es texto?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        900,
        400
      ]
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumberId": "={{ $('Normalizar mensaje').item.json.phone_number_id }}",
        "recipientPhoneNumber": "={{ $('Normalizar mensaje').item.json.telefono }}",
        "textBody": "Ahora mismo solo puedo leer mensajes de texto. ¿Me lo puede escribir, por favor?",
        "additionalFields": {}
      },
      "id": "7e5f0d2e-09e1-47b6-bdf3-46f2d34ce08f",
      "name": "Pedir que escriba",
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1,
      "position": [
        900,
        540
      ],
      "credentials": {
        "whatsAppApi": {
          "id": "PLACEHOLDER",
          "name": "WhatsApp Cloud API (clínica)"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": false,
            "leftValue": "",
            "typeValidation": "loose"
          },
          "conditions": [
            {
              "id": "0c9d0c4a-a04a-494c-9519-71d068da5e43",
              "leftValue": "={{ $('Normalizar mensaje').item.json.texto.toLowerCase().normalize('NFD').replace(/[\\u0300-\\u036f]/g, '') }}",
              "rightValue": "urgenc|urgente|emergenc|dolor|duele|queja|reclamaci|denuncia|abogado|sangr|hinchaz|inflamad|fiebre|persona|humano|recepci",
              "operator": {
                "type": "string",
                "operation": "regex"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "a69d8d27-8992-493c-8971-d5d80754189f",
      "name": "¿Urgencia o pide persona?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1120,
        300
      ]
    },
    {
      "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: $('Normalizar mensaje').item.json.telefono, properties: { bot_pausado: 'true', hs_lead_status: 'IN_PROGRESS', estado_asistente: 'Atendido por persona', ultimo_mensaje_whatsapp: $('Normalizar mensaje').item.json.texto, phone: '+' + $('Normalizar mensaje').item.json.telefono } }] }) }}",
        "options": {}
      },
      "id": "62b15fd8-44d3-4290-85be-b0d62c39b5b8",
      "name": "HubSpot · marcar pase a persona",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1380,
        -20
      ],
      "credentials": {
        "hubspotAppToken": {
          "id": "PLACEHOLDER",
          "name": "HubSpot private app (clínica)"
        }
      }
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumberId": "={{ $('Normalizar mensaje').item.json.phone_number_id }}",
        "recipientPhoneNumber": "={{ $('Normalizar mensaje').item.json.telefono }}",
        "textBody": "Le paso con una persona del equipo de la clínica. Le responderán por este mismo chat lo antes posible (L–V 9:00–14:00 y 16:00–20:00). Si es una urgencia grave, llame al 112.",
        "additionalFields": {}
      },
      "id": "ca7bd25d-18dd-4c7c-ac53-14ee7bcab612",
      "name": "Avisar al paciente",
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1,
      "position": [
        1600,
        -20
      ],
      "credentials": {
        "whatsAppApi": {
          "id": "PLACEHOLDER",
          "name": "WhatsApp Cloud API (clínica)"
        }
      }
    },
    {
      "parameters": {
        "sendTo": "RECEPCION@CLINICA.ES",
        "subject": "={{ 'Pase a persona: +' + $('Normalizar mensaje').item.json.telefono }}",
        "emailType": "text",
        "message": "={{ 'Paciente: ' + ($('Normalizar mensaje').item.json.nombre_perfil || 'sin nombre') + ' (+' + $('Normalizar mensaje').item.json.telefono + ')\\nÚltimo mensaje: ' + $('Normalizar mensaje').item.json.texto + '\\n\\nAbrir chat: https://wa.me/' + $('Normalizar mensaje').item.json.telefono }}",
        "options": {}
      },
      "id": "a5aafd9b-58a5-4817-be60-0dc444865609",
      "name": "Avisar a recepción",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1820,
        -20
      ],
      "credentials": {
        "gmailOAuth2": {
          "id": "PLACEHOLDER",
          "name": "Gmail (avisos)"
        }
      }
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "={{ $('Normalizar mensaje').item.json.texto }}",
        "options": {
          "systemMessage": "=Eres el asistente de WhatsApp de NOMBRE_CLINICA, clínica dental y de estética en España. Hablas en español de España, de usted, breve y amable. Máximo 3 frases por mensaje.\n\nHoy es {{ $now.setZone('Europe/Madrid').setLocale('es').toFormat(\"cccc d 'de' LLLL 'de' yyyy, HH:mm\") }} (hora de Madrid).\nPaciente: {{ $('Normalizar mensaje').item.json.nombre_perfil || 'sin nombre' }}, teléfono +{{ $('Normalizar mensaje').item.json.telefono }}.\n\nPRIMER MENSAJE (fase menú guiado): saluda y ofrece: 1) Precios 2) Pedir cita 3) Mover o cancelar cita 4) Hablar con una persona.\n\nREGLAS:\n1. Precios, horarios y servicios SOLO desde la herramienta hoja_servicios. Si un tratamiento no está, dilo y ofrece pasar con una persona. Nunca inventes un precio.\n2. Nunca des consejo médico, diagnósticos ni medicación. Ofrece una visita de valoración o una persona.\n3. Para dar cita: usa comprobar_hueco con la hora exacta y la duración del tratamiento. Si NO está libre, no reserves: usa ver_agenda y ofrece el siguiente hueco libre. Solo usa crear_cita después de que comprobar_hueco diga que está libre y el paciente confirme día, hora y nombre.\n4. Para mover o cancelar: busca sus citas con citas_del_paciente, confirma con el paciente y usa mover_cita (tras comprobar_hueco) o cancelar_cita.\n5. Horario: L–V 9:00–14:00 y 16:00–20:00, zona Europe/Madrid. Fechas en ISO 8601 con la zona de Madrid.\n6. Si no sabes algo, o el paciente está molesto, termina tu respuesta con [DERIVAR].",
          "maxIterations": 8
        }
      },
      "id": "6d5e40b1-e210-405d-aa82-3545f711eee2",
      "name": "Asistente IA",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [
        1380,
        360
      ]
    },
    {
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "claude-haiku-5-5"
        },
        "options": {
          "maxTokensToSample": 1024
        }
      },
      "id": "e373c104-14a9-4daf-bf00-15ab47f2527d",
      "name": "Claude Haiku 5.5",
      "type": "@n8n/n8n-nodes-langchain.lmChatAnthropic",
      "typeVersion": 1.3,
      "position": [
        1240,
        620
      ],
      "credentials": {
        "anthropicApi": {
          "id": "PLACEHOLDER",
          "name": "Anthropic (Claude)"
        }
      }
    },
    {
      "parameters": {
        "sessionIdType": "customKey",
        "sessionKey": "={{ $('Normalizar mensaje').item.json.telefono }}",
        "contextWindowLength": 12
      },
      "id": "28baaab1-d1d2-44df-b3bb-3895c16682d3",
      "name": "Memoria por paciente",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "typeVersion": 1.3,
      "position": [
        1390,
        620
      ]
    },
    {
      "parameters": {
        "descriptionType": "manual",
        "toolDescription": "Devuelve la hoja de servicios de la clínica: tratamiento, precio en euros, duración en minutos, horarios y datos de contacto. Úsala antes de dar cualquier precio o dato.",
        "documentId": {
          "__rl": true,
          "mode": "url",
          "value": "URL_DE_LA_HOJA_DE_SERVICIOS"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Servicios"
        },
        "options": {}
      },
      "id": "11fed776-f8f7-4076-8313-5dcfd489df8a",
      "name": "hoja_servicios",
      "type": "n8n-nodes-base.googleSheetsTool",
      "typeVersion": 4.5,
      "position": [
        1540,
        620
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "PLACEHOLDER",
          "name": "Google Sheets (clínica)"
        }
      }
    },
    {
      "parameters": {
        "descriptionType": "manual",
        "toolDescription": "Comprueba si un hueco está libre en la agenda (free/busy). Úsala SIEMPRE antes de crear o mover una cita.",
        "resource": "calendar",
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "CALENDAR_ID_DE_LA_CLINICA"
        },
        "timeMin": "={{ $fromAI('inicio', 'Inicio del hueco, ISO 8601 con zona Europe/Madrid', 'string') }}",
        "timeMax": "={{ $fromAI('fin', 'Fin del hueco (inicio + duración del tratamiento), ISO 8601', 'string') }}",
        "options": {
          "timezone": "Europe/Madrid"
        }
      },
      "id": "918c3cf9-8f47-4e2e-9b1b-1c04c3234eb4",
      "name": "comprobar_hueco",
      "type": "n8n-nodes-base.googleCalendarTool",
      "typeVersion": 1.3,
      "position": [
        1690,
        620
      ],
      "credentials": {
        "googleCalendarOAuth2Api": {
          "id": "PLACEHOLDER",
          "name": "Google Calendar (clínica)"
        }
      }
    },
    {
      "parameters": {
        "descriptionType": "manual",
        "toolDescription": "Lista las citas ya ocupadas entre dos fechas para encontrar el siguiente hueco libre.",
        "operation": "getAll",
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "CALENDAR_ID_DE_LA_CLINICA"
        },
        "limit": 100,
        "timeMin": "={{ $fromAI('desde', 'Inicio del rango, ISO 8601', 'string') }}",
        "timeMax": "={{ $fromAI('hasta', 'Fin del rango, ISO 8601', 'string') }}",
        "options": {
          "singleEvents": true,
          "orderBy": "startTime",
          "timeZone": "Europe/Madrid"
        }
      },
      "id": "a7b6827f-636b-4774-a913-dd44cfd02652",
      "name": "ver_agenda",
      "type": "n8n-nodes-base.googleCalendarTool",
      "typeVersion": 1.3,
      "position": [
        1840,
        620
      ],
      "credentials": {
        "googleCalendarOAuth2Api": {
          "id": "PLACEHOLDER",
          "name": "Google Calendar (clínica)"
        }
      }
    },
    {
      "parameters": {
        "descriptionType": "manual",
        "toolDescription": "Crea la cita. Solo después de comprobar_hueco = libre y con la confirmación del paciente.",
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "CALENDAR_ID_DE_LA_CLINICA"
        },
        "start": "={{ $fromAI('inicio', 'Inicio, ISO 8601 Europe/Madrid', 'string') }}",
        "end": "={{ $fromAI('fin', 'Fin, ISO 8601 Europe/Madrid', 'string') }}",
        "additionalFields": {
          "summary": "={{ $fromAI('tratamiento', 'Tratamiento', 'string') + ' · ' + $fromAI('nombre', 'Nombre y apellido del paciente', 'string') }}",
          "description": "={{ 'WhatsApp: +' + $('Normalizar mensaje').item.json.telefono + '\\nReservada por el asistente' }}"
        }
      },
      "id": "4e57580f-de6e-47d6-90f3-792c1a8db188",
      "name": "crear_cita",
      "type": "n8n-nodes-base.googleCalendarTool",
      "typeVersion": 1.3,
      "position": [
        1990,
        620
      ],
      "credentials": {
        "googleCalendarOAuth2Api": {
          "id": "PLACEHOLDER",
          "name": "Google Calendar (clínica)"
        }
      }
    },
    {
      "parameters": {
        "descriptionType": "manual",
        "toolDescription": "Busca las próximas citas de este paciente por su teléfono.",
        "operation": "getAll",
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "CALENDAR_ID_DE_LA_CLINICA"
        },
        "limit": 10,
        "timeMin": "={{ $now.toISO() }}",
        "options": {
          "query": "={{ $('Normalizar mensaje').item.json.telefono }}",
          "singleEvents": true,
          "orderBy": "startTime"
        }
      },
      "id": "e209a6d0-bb47-429a-bd60-5ba8b2b9cfad",
      "name": "citas_del_paciente",
      "type": "n8n-nodes-base.googleCalendarTool",
      "typeVersion": 1.3,
      "position": [
        2140,
        620
      ],
      "credentials": {
        "googleCalendarOAuth2Api": {
          "id": "PLACEHOLDER",
          "name": "Google Calendar (clínica)"
        }
      }
    },
    {
      "parameters": {
        "descriptionType": "manual",
        "toolDescription": "Mueve una cita existente a un nuevo horario (tras comprobar_hueco).",
        "operation": "update",
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "CALENDAR_ID_DE_LA_CLINICA"
        },
        "eventId": "={{ $fromAI('evento', 'ID del evento a mover', 'string') }}",
        "updateFields": {
          "start": "={{ $fromAI('inicio', 'Nuevo inicio ISO 8601', 'string') }}",
          "end": "={{ $fromAI('fin', 'Nuevo fin ISO 8601', 'string') }}"
        }
      },
      "id": "91c94345-c1fe-47cd-829a-99091e39b715",
      "name": "mover_cita",
      "type": "n8n-nodes-base.googleCalendarTool",
      "typeVersion": 1.3,
      "position": [
        2290,
        620
      ],
      "credentials": {
        "googleCalendarOAuth2Api": {
          "id": "PLACEHOLDER",
          "name": "Google Calendar (clínica)"
        }
      }
    },
    {
      "parameters": {
        "descriptionType": "manual",
        "toolDescription": "Cancela (borra) una cita del paciente tras su confirmación.",
        "operation": "delete",
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "CALENDAR_ID_DE_LA_CLINICA"
        },
        "eventId": "={{ $fromAI('evento', 'ID del evento a cancelar', 'string') }}",
        "options": {}
      },
      "id": "b09358a1-be11-45d2-963b-ffdf78a4be32",
      "name": "cancelar_cita",
      "type": "n8n-nodes-base.googleCalendarTool",
      "typeVersion": 1.3,
      "position": [
        2440,
        620
      ],
      "credentials": {
        "googleCalendarOAuth2Api": {
          "id": "PLACEHOLDER",
          "name": "Google Calendar (clínica)"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": false,
            "leftValue": "",
            "typeValidation": "loose"
          },
          "conditions": [
            {
              "id": "e664f7d0-5df4-469f-9574-979e2c52b50b",
              "leftValue": "={{ $json.output }}",
              "rightValue": "[DERIVAR]",
              "operator": {
                "type": "string",
                "operation": "contains"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "1aaf9366-66d1-4176-bac7-b5ea4efcc99e",
      "name": "¿La IA pide derivar?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1720,
        360
      ]
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumberId": "={{ $('Normalizar mensaje').item.json.phone_number_id }}",
        "recipientPhoneNumber": "={{ $('Normalizar mensaje').item.json.telefono }}",
        "textBody": "={{ $('Asistente IA').item.json.output.replace('[DERIVAR]', '').trim() }}",
        "additionalFields": {}
      },
      "id": "c62ae372-dc26-4237-ad61-b9b51eef4493",
      "name": "Responder al paciente",
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1,
      "position": [
        1940,
        380
      ],
      "credentials": {
        "whatsAppApi": {
          "id": "PLACEHOLDER",
          "name": "WhatsApp Cloud API (clínica)"
        }
      }
    },
    {
      "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: $('Normalizar mensaje').item.json.telefono, properties: { phone: '+' + $('Normalizar mensaje').item.json.telefono, firstname: $('Normalizar mensaje').item.json.nombre_perfil, estado_asistente: 'Atendido por el asistente', ultimo_mensaje_whatsapp: $('Normalizar mensaje').item.json.texto, bot_pausado: 'false' } }] }) }}",
        "options": {}
      },
      "id": "4b257946-34d0-48be-ad7d-f285dfe36b3b",
      "name": "HubSpot · guardar contacto",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2160,
        380
      ],
      "credentials": {
        "hubspotAppToken": {
          "id": "PLACEHOLDER",
          "name": "HubSpot private app (clínica)"
        }
      }
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "0 9 1 * *"
            }
          ]
        }
      },
      "id": "077115c7-b0d6-4d44-8504-7be837c25a58",
      "name": "Día 1 de cada mes, 9:00",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        900
      ]
    },
    {
      "parameters": {
        "operation": "getAll",
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "CALENDAR_ID_DE_LA_CLINICA"
        },
        "returnAll": true,
        "timeMin": "={{ $now.setZone('Europe/Madrid').minus({months: 1}).startOf('month').toISO() }}",
        "timeMax": "={{ $now.setZone('Europe/Madrid').startOf('month').toISO() }}",
        "options": {
          "singleEvents": true
        }
      },
      "id": "84b172ad-39a5-4168-9e3b-9bc8eb30117e",
      "name": "Citas del mes anterior",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1.3,
      "position": [
        240,
        820
      ],
      "credentials": {
        "googleCalendarOAuth2Api": {
          "id": "PLACEHOLDER",
          "name": "Google Calendar (clínica)"
        }
      },
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.hubapi.com/crm/v3/objects/contacts/search",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "hubspotAppToken",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ filterGroups: [{ filters: [{ propertyName: 'lastmodifieddate', operator: 'GTE', value: $now.minus({months: 1}).startOf('month').toMillis() }] }], properties: ['estado_asistente', 'bot_pausado'], limit: 100 }) }}",
        "options": {}
      },
      "id": "9383dea6-d9e3-4992-8f9f-2f45ab4ad3c6",
      "name": "Contactos del mes (HubSpot)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        240,
        1000
      ],
      "credentials": {
        "hubspotAppToken": {
          "id": "PLACEHOLDER",
          "name": "HubSpot private app (clínica)"
        }
      }
    },
    {
      "parameters": {
        "mode": "append"
      },
      "id": "4dea272d-1e87-442e-a04b-5a12ab464d94",
      "name": "Juntar datos",
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3,
      "position": [
        480,
        900
      ]
    },
    {
      "parameters": {
        "jsCode": "const citas = $('Citas del mes anterior').all().filter(i => i.json.id);\nconst asistente = citas.filter(i => (i.json.description || '').includes('Reservada por el asistente')).length;\nconst contactos = $('Contactos del mes (HubSpot)').first().json.results || [];\nconst pases = contactos.filter(c => c.properties.estado_asistente === 'Atendido por persona').length;\nconst mes = $now.setZone('Europe/Madrid').minus({ months: 1 }).setLocale('es').toFormat('LLLL yyyy');\nconst texto = `Informe mensual · ${mes}\\n\\nConversaciones: ${contactos.length}\\nCitas en agenda: ${citas.length}\\nCitas reservadas por el asistente: ${asistente}\\nPases a persona: ${pases}`;\nreturn [{ json: { texto } }];"
      },
      "id": "d935b96f-f55f-4173-981b-5ac0ad27139b",
      "name": "Armar informe",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        700,
        900
      ]
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumberId": "PHONE_NUMBER_ID_DE_LA_CLINICA",
        "recipientPhoneNumber": "TELEFONO_DEL_RESPONSABLE",
        "messageType": "template",
        "template": "informe_mensual|es",
        "components": {
          "component": [
            {
              "type": "body",
              "bodyParameters": {
                "parameter": [
                  {
                    "type": "text",
                    "text": "={{ $json.texto }}"
                  }
                ]
              }
            }
          ]
        }
      },
      "id": "f26dbf9c-407a-4f98-9361-bab15a8b3157",
      "name": "Enviar informe por WhatsApp",
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1,
      "position": [
        920,
        820
      ],
      "credentials": {
        "whatsAppApi": {
          "id": "PLACEHOLDER",
          "name": "WhatsApp Cloud API (clínica)"
        }
      },
      "notes": "Fuera de la ventana de 24 h WhatsApp exige una plantilla aprobada por Meta (informe_mensual)."
    },
    {
      "parameters": {
        "sendTo": "RESPONSABLE@CLINICA.ES",
        "subject": "Informe mensual del asistente de WhatsApp",
        "emailType": "text",
        "message": "={{ $json.texto }}",
        "options": {}
      },
      "id": "1cffe35e-2d22-4bd1-b493-bf5ee4a08f00",
      "name": "Enviar informe por correo",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        920,
        1000
      ],
      "credentials": {
        "gmailOAuth2": {
          "id": "PLACEHOLDER",
          "name": "Gmail (avisos)"
        }
      }
    },
    {
      "parameters": {
        "content": "## 1 · Entrada y filtros\nCada mensaje de WhatsApp entra por el webhook oficial (Cloud API). Si recepción tiene la conversación (`bot_pausado` en HubSpot), el bot no contesta. Urgencias, quejas o \"hablar con una persona\" van directo al pase a persona, sin pasar por la IA.",
        "width": 1000,
        "height": 150,
        "color": 5
      },
      "id": "232b9d68-5763-457d-847b-0c1f760d235f",
      "name": "Nota entrada",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -160
      ]
    },
    {
      "parameters": {
        "content": "## 2 · Asistente IA (Claude Haiku 5.5)\nPrecios solo desde la hoja de servicios. Antes de crear o mover una cita, `comprobar_hueco` (free/busy de Google Calendar): dos citas nunca se pisan. Sin consejos médicos.",
        "width": 1100,
        "height": 120,
        "color": 4
      },
      "id": "31fff4f9-ab2a-420b-b128-cae3c5459b8b",
      "name": "Nota IA",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1340,
        190
      ]
    },
    {
      "parameters": {
        "content": "## 3 · Informe mensual\nEl día 1 a las 9:00 (Madrid) cuenta citas y contactos del mes anterior y se lo manda a la clínica por WhatsApp y correo.",
        "width": 1100,
        "height": 100,
        "color": 6
      },
      "id": "cb94f12c-37f8-4954-b025-4dc9e78ea7ff",
      "name": "Nota informe",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        690
      ]
    }
  ],
  "connections": {
    "WhatsApp Trigger": {
      "main": [
        [
          {
            "node": "Normalizar mensaje",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalizar mensaje": {
      "main": [
        [
          {
            "node": "HubSpot · leer contacto",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HubSpot · leer contacto": {
      "main": [
        [
          {
            "node": "¿Atiende una persona?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿Atiende una persona?": {
      "main": [
        [
          {
            "node": "Reenviar a recepción",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "¿Es texto?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿Es texto?": {
      "main": [
        [
          {
            "node": "¿Urgencia o pide persona?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Pedir que escriba",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿Urgencia o pide persona?": {
      "main": [
        [
          {
            "node": "HubSpot · marcar pase a persona",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Asistente IA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HubSpot · marcar pase a persona": {
      "main": [
        [
          {
            "node": "Avisar al paciente",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Avisar al paciente": {
      "main": [
        [
          {
            "node": "Avisar a recepción",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Claude Haiku 5.5": {
      "ai_languageModel": [
        [
          {
            "node": "Asistente IA",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Memoria por paciente": {
      "ai_memory": [
        [
          {
            "node": "Asistente IA",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "hoja_servicios": {
      "ai_tool": [
        [
          {
            "node": "Asistente IA",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "comprobar_hueco": {
      "ai_tool": [
        [
          {
            "node": "Asistente IA",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "ver_agenda": {
      "ai_tool": [
        [
          {
            "node": "Asistente IA",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "crear_cita": {
      "ai_tool": [
        [
          {
            "node": "Asistente IA",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "citas_del_paciente": {
      "ai_tool": [
        [
          {
            "node": "Asistente IA",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "mover_cita": {
      "ai_tool": [
        [
          {
            "node": "Asistente IA",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "cancelar_cita": {
      "ai_tool": [
        [
          {
            "node": "Asistente IA",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Asistente IA": {
      "main": [
        [
          {
            "node": "¿La IA pide derivar?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿La IA pide derivar?": {
      "main": [
        [
          {
            "node": "HubSpot · marcar pase a persona",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Responder al paciente",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Responder al paciente": {
      "main": [
        [
          {
            "node": "HubSpot · guardar contacto",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Día 1 de cada mes, 9:00": {
      "main": [
        [
          {
            "node": "Citas del mes anterior",
            "type": "main",
            "index": 0
          },
          {
            "node": "Contactos del mes (HubSpot)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Citas del mes anterior": {
      "main": [
        [
          {
            "node": "Juntar datos",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Contactos del mes (HubSpot)": {
      "main": [
        [
          {
            "node": "Juntar datos",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Juntar datos": {
      "main": [
        [
          {
            "node": "Armar informe",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Armar informe": {
      "main": [
        [
          {
            "node": "Enviar informe por WhatsApp",
            "type": "main",
            "index": 0
          },
          {
            "node": "Enviar informe por correo",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "timezone": "Europe/Madrid"
  },
  "pinData": {}
}