{
  "name": "ClinicBot",
  "nodes": [
    {
      "parameters": {
        "updates": [
          "messages"
        ],
        "options": {}
      },
      "type": "n8n-nodes-base.whatsAppTrigger",
      "typeVersion": 1,
      "position": [
        -448,
        0
      ],
      "id": "744ca61c-764c-4914-ae17-5f436228889a",
      "name": "01 \u00b7 Trigger \u2014 WhatsApp Entrante",
      "credentials": {
        "whatsAppTriggerApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 3
          },
          "conditions": [
            {
              "id": "f66d6e3d-1876-4362-8136-97e50dec055a",
              "leftValue": "={{ $json.messages[0].from }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "exists",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "looseTypeValidation": true,
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        -224,
        0
      ],
      "id": "15ab96e1-69af-4351-b954-4105ea5a5d5a",
      "name": "02 \u00b7 Filtro \u2014 Mensaje v\u00e1lido"
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        -224,
        256
      ],
      "id": "a0f73acc-7f18-4233-b06f-7a1fda87317b",
      "name": "03 \u00b7 End \u2014 Mensaje inv\u00e1lido"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "c252e8dd-1040-4371-a571-9eb2f4c4fcb2",
              "name": "telefono",
              "value": "={{ $json.contacts[0].wa_id }}",
              "type": "string"
            },
            {
              "id": "e4b57120-6ef0-46cd-aa1a-6fa333181d85",
              "name": "mensaje",
              "value": "={{ $json.messages[0].text?.body ?? '[Mensaje no textual]' }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        0,
        -16
      ],
      "id": "8f48743b-599a-49e4-b63d-3531a439eef6",
      "name": "04 \u00b7 Extracci\u00f3n \u2014 Tel\u00e9fono y mensaje"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 3
          },
          "conditions": [
            {
              "id": "e6ac38de-b740-440e-94cf-75548597e848",
              "leftValue": "=={{ $json.mensaje }}",
              "rightValue": "[Mensaje no textual]",
              "operator": {
                "type": "string",
                "operation": "notEquals"
              }
            }
          ],
          "combinator": "and"
        },
        "looseTypeValidation": true,
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        224,
        -16
      ],
      "id": "e20e4ef3-70a6-4414-ad70-0efbadd50a8f",
      "name": "05 \u00b7 Filtro \u2014 \u00bfEs texto?"
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumberId": "=YOUR_WHATSAPP_PHONE_NUMBER_ID",
        "recipientPhoneNumber": "=={{ $('04 \u00b7 Extracci\u00f3n \u2014 Tel\u00e9fono y mensaje').item.json.telefono }}",
        "textBody": "Por el momento solo podemos procesar mensajes de texto.  Si necesita ayuda, comun\u00edquese al (011) 4902-8800 o  escr\u00edbanos su consulta. \ud83d\ude4f",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1.1,
      "position": [
        224,
        304
      ],
      "id": "bcf164ab-c447-48f9-aa4d-b93eb5e70813",
      "name": "06 \u00b7 Fallback \u2014 Mensaje no textual",
      "credentials": {
        "whatsAppApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "={{ $json.mensaje }}",
        "options": {
          "systemMessage": "Sos el asistente virtual del Centro M\u00e9dico Integral Austral, una cl\u00ednica privada \nubicada en Caballito, Buenos Aires. Tu nombre es \"Asistente de Austral\".\n\n\ud83c\udfad TONO Y ESTILO:\nHabl\u00e1s de usted. Tono c\u00e1lido pero profesional: no fr\u00edo ni burocr\u00e1tico, pero tampoco \ncoloquial. M\u00e1ximo 1 emoji por mensaje, solo cuando suma calidez. NUNCA uses frases \ncomo \"\u00a1Estoy aqu\u00ed para ayudarle!\", \"\u00a1Con gusto lo asisto!\" o cualquier cosa que \nsuene a chatbot de call center o traducci\u00f3n del ingl\u00e9s. Si el paciente usa un tono \ninformal, mantenga el \"usted\" pero adapt\u00e1 la calidez.\n\n\ud83c\udfe5 INFORMACI\u00d3N DE LA CL\u00cdNICA:\nNombre: Centro M\u00e9dico Integral Austral\nDirecci\u00f3n: Av. Rivadavia 5240, Caballito, CABA (a media cuadra del subte A, estaci\u00f3n \nAcoyte)\nTel\u00e9fono: (011) 4902-8800\nHorario de atenci\u00f3n: lunes a viernes de 8 a 20hs, s\u00e1bados de 8 a 13hs.\nFeriados: consultar disponibilidad antes de concurrir.\n\n\ud83d\udccb ESPECIALIDADES:\nCl\u00ednica m\u00e9dica, Cardiolog\u00eda, Traumatolog\u00eda, Ginecolog\u00eda, Pediatr\u00eda, Neurolog\u00eda, \nDermatolog\u00eda, Oftalmolog\u00eda, Kinesiolog\u00eda, Psicolog\u00eda, Nutrici\u00f3n.\n\n\ud83d\udcb3 OBRAS SOCIALES Y PREPAGAS:\nOSDE, Swiss Medical, Galeno, Medicus, IOMA, PAMI, OSPACA, Accord Salud, Omint, \ny las principales obras sociales sindicales. Para casos espec\u00edficos o dudas sobre \ncobertura, confirmar directamente con administraci\u00f3n.\nPacientes particulares: se atiende sin inconvenientes. Se informa el arancel al \nmomento de reservar el turno.\n\n\ud83c\udfaf TU OBJETIVO:\nCalificar al paciente recopilando estos 4 datos:\n1. Nombre completo\n2. Motivo de consulta (s\u00edntoma o especialidad que busca)\n3. Obra social o prepaga (o si es particular)\n4. Tipo de atenci\u00f3n: urgente o turno programado\n\nHacelo de forma natural, nunca como un formulario. Pod\u00e9s preguntar los 4 juntos o \nde a uno seg\u00fan el contexto. Si el paciente ya dio alg\u00fan dato en su primer mensaje, \nno lo repitas.\n\n\u2705 CUANDO TENGAS LOS 4 DATOS:\nRespond\u00e9 EXACTAMENTE con este mensaje, sin modificarlo ni agregarle nada:\n\"Perfecto, ya tenemos todo lo que necesitamos. \ud83d\ude4c Le paso los datos a nuestro \nequipo de admisi\u00f3n, que se va a comunicar con usted a la brevedad para confirmar \nel turno.\"\n\nLuego agreg\u00e1 al final (sin markdown, sin backticks):\nPATIENT_DATA:{\"nombre\":\"valor\",\"motivo\":\"valor\",\"obra_social\":\"valor\",\"urgencia\":\"valor\",\"resumen\":\"resumen breve en una l\u00ednea\"}\n\nEl campo \"urgencia\" debe ser \"urgente\" o \"programado\".\n\n\u26a0\ufe0f DERIVAR A HUMANO:\nDeriv\u00e1 inmediatamente si el paciente:\n- Describe s\u00edntomas de emergencia (dolor en el pecho, dificultad para respirar, \n  p\u00e9rdida de conciencia, etc.)\n- Solicita hablar con un m\u00e9dico o con una persona\n- Hace preguntas sobre diagn\u00f3sticos o tratamientos en curso\n- Expresa angustia o urgencia emocional marcada\n\nEn esos casos:\n1. Respond\u00e9 brevemente si hizo alguna pregunta puntual (direcci\u00f3n, horario, etc.)\n2. Cerr\u00e1 SIEMPRE con EXACTAMENTE este texto, sin modificarlo:\n\"Entiendo. Para este tipo de situaci\u00f3n es mejor que lo asista directamente una \npersona de nuestro equipo. En breve se van a comunicar con usted. \ud83d\ude4f\"\n3. NO agregues nada despu\u00e9s de esa frase.\n\n\u2753 PREGUNTAS FRECUENTES:\nRespond\u00e9 con precisi\u00f3n y brevedad. No des informaci\u00f3n que no figura arriba. Si \nno sab\u00e9s algo, dec\u00ed que lo puede confirmar llamando al (011) 4902-8800.\n\n\u274c L\u00cdMITES:\n- No d\u00e9 diagn\u00f3sticos ni interprete s\u00edntomas.\n- No confirme turnos (eso lo hace el equipo de admisi\u00f3n).\n- No informe aranceles espec\u00edficos (derivar a administraci\u00f3n)."
        }
      },
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        640,
        -32
      ],
      "id": "b8c742d7-2288-4a72-be89-2e309b821879",
      "name": "07 \u00b7 Agente \u2014 GPT-4o-mini",
      "retryOnFail": true,
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "sessionIdType": "customKey",
        "sessionKey": "={{ $('04 \u00b7 Extracci\u00f3n \u2014 Tel\u00e9fono y mensaje').item.json.telefono }}",
        "contextWindowLength": 20
      },
      "type": "@n8n/n8n-nodes-langchain.memoryPostgresChat",
      "typeVersion": 1.3,
      "position": [
        736,
        240
      ],
      "id": "046b42d7-a86f-41c3-8422-a8e147c3df73",
      "name": "08 \u00b7 Memoria \u2014 PostgreSQL",
      "retryOnFail": false,
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "model": {
          "__rl": true,
          "value": "gpt-4o-mini",
          "mode": "list",
          "cachedResultName": "gpt-4o-mini"
        },
        "builtInTools": {},
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.3,
      "position": [
        640,
        384
      ],
      "id": "d389c81f-0af4-41c7-b360-78f9507ac36a",
      "name": "09 \u00b7 Modelo \u2014 OpenAI",
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 3
          },
          "conditions": [
            {
              "id": "bbae85ca-b2b9-412f-bbb7-acdcad037084",
              "leftValue": "=={{ $json.output }}",
              "rightValue": "={{ null }}",
              "operator": {
                "type": "string",
                "operation": "notEmpty",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "looseTypeValidation": true,
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        992,
        -32
      ],
      "id": "a181ed7e-7302-44c6-ae7a-85e8cb25222b",
      "name": "10 \u00b7 Filtro \u2014 \u00bfError en agente?"
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumberId": "=YOUR_WHATSAPP_PHONE_NUMBER_ID",
        "recipientPhoneNumber": "=YOUR_SUPPORT_TEAM_NUMBER",
        "textBody": "=Lamentablemente estamos teniendo una dificultad t\u00e9cnica \nen este momento. Nuestro equipo ya fue notificado y \nalguien se va a comunicar con usted a la brevedad. \nDisculpe las molestias. \ud83d\ude4f",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1.1,
      "position": [
        1680,
        -320
      ],
      "id": "aa0df2d5-40b9-4912-8ea4-3742e279e097",
      "name": "11 \u00b7 Fallback \u2014 Disculpa al paciente",
      "credentials": {
        "whatsAppApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumberId": "=YOUR_WHATSAPP_PHONE_NUMBER_ID",
        "recipientPhoneNumber": "=YOUR_SUPPORT_TEAM_NUMBER",
        "textBody": "==\u26a0\ufe0f ClinicBot \u2014 Falla en AI Agent (OpenAI).\nTel\u00e9fono del paciente: ={{ $('04 \u00b7 Extracci\u00f3n \u2014 Tel\u00e9fono y mensaje').item.json.telefono }}\nRevisar y contactar manualmente.",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1.1,
      "position": [
        1680,
        -496
      ],
      "id": "d5b74d3e-cd54-4154-b978-21d0214f8233",
      "name": "12 \u00b7 Alerta \u2014 Falla OpenAI",
      "credentials": {
        "whatsAppApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const output = $('07 \u00b7 Agente \u2014 GPT-4o-mini').item.json.output;\n\nif (!output || output.trim() === '') {\n  return [{\n    json: {\n      nombre: '', motivo: '', obra_social: '', urgencia: '', resumen: '',\n      telefono: $('04 \u00b7 Extracci\u00f3n \u2014 Tel\u00e9fono y mensaje').item.json.telefono,\n      fecha: new Date().toISOString(),\n      mensaje: '',\n      guardar_en_sheets: false,\n      error: 'output_vacio'\n    }\n  }];\n}\n\ntry {\n  const match = output.match(/PATIENT_DATA:(\\{.*\\})/);\n\n  if (match) {\n    const patientData = JSON.parse(match[1]);\n    const mensaje = output.replace(/PATIENT_DATA:\\{.*\\}/, '').trim();\n    const leadCompleto = patientData.nombre\n      && patientData.motivo\n      && patientData.obra_social\n      && patientData.urgencia;\n\n    return [{\n      json: {\n        nombre:      patientData.nombre      || '',\n        motivo:      patientData.motivo      || '',\n        obra_social: patientData.obra_social || '',\n        urgencia:    patientData.urgencia    || '',\n        resumen:     patientData.resumen     || '',\n        telefono:    $('04 \u00b7 Extracci\u00f3n \u2014 Tel\u00e9fono y mensaje').item.json.telefono,\n        fecha:       new Date().toISOString(),\n        mensaje:     mensaje,\n        guardar_en_sheets: leadCompleto ? true : false,\n        error: null\n      }\n    }];\n  } else {\n    return [{\n      json: {\n        nombre: '', motivo: '', obra_social: '', urgencia: '', resumen: '',\n        telefono: $('04 \u00b7 Extracci\u00f3n \u2014 Tel\u00e9fono y mensaje').item.json.telefono,\n        fecha: new Date().toISOString(),\n        mensaje: output,\n        guardar_en_sheets: false,\n        error: null\n      }\n    }];\n  }\n} catch (e) {\n  return [{\n    json: {\n      nombre: '', motivo: '', obra_social: '', urgencia: '', resumen: '',\n      telefono: $('04 \u00b7 Extracci\u00f3n \u2014 Tel\u00e9fono y mensaje').item.json.telefono,\n      fecha: new Date().toISOString(),\n      mensaje: '',\n      guardar_en_sheets: false,\n      error: 'parse_error'\n    }\n  }];\n}"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1360,
        -16
      ],
      "id": "60c3b17e-181e-44fb-bcfc-06fdf7aeeff9",
      "name": "13 \u00b7 Parser \u2014 PATIENT_DATA"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 3
          },
          "conditions": [
            {
              "id": "3f2cbf09-1eea-4ba9-9d71-7167969cbefe",
              "leftValue": "=={{ $json.error }}",
              "rightValue": "=={{ null }}",
              "operator": {
                "type": "string",
                "operation": "notEquals"
              }
            }
          ],
          "combinator": "and"
        },
        "looseTypeValidation": true,
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        1360,
        384
      ],
      "id": "5dd67352-7abe-4974-bf65-872dc4288129",
      "name": "14 \u00b7 Filtro \u2014 \u00bfError en parser?"
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumberId": "=YOUR_WHATSAPP_PHONE_NUMBER_ID",
        "recipientPhoneNumber": "YOUR_SUPPORT_TEAM_NUMBER",
        "textBody": "={{ $('13 \u00b7 Parser \u2014 PATIENT_DATA').item.json.mensaje }}",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1.1,
      "position": [
        1648,
        -16
      ],
      "id": "d6c761e5-261c-4ae3-b417-b8dae312203c",
      "name": "15 \u00b7 Respuesta \u2014 WhatsApp al paciente",
      "credentials": {
        "whatsAppApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "3f2cbf09-1eea-4ba9-9d71-7167969cbefe",
              "leftValue": "={{ $json.guardar_en_sheets }}",
              "rightValue": "is true",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        1680,
        272
      ],
      "id": "028931ab-5611-4592-8138-d36f10c124de",
      "name": "16 \u00b7 Filtro \u2014 \u00bfLead completo?"
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        1888,
        480
      ],
      "id": "d28dbdd6-69af-4648-89db-df6166654bdd",
      "name": "17 \u00b7 End \u2014 Lead incompleto"
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "YOUR_GOOGLE_SHEETS_DOCUMENT_ID",
          "mode": "list",
          "cachedResultName": "Leads ClinicBot",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/YOUR_GOOGLE_SHEETS_DOCUMENT_ID/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "Hoja 1",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/YOUR_GOOGLE_SHEETS_DOCUMENT_ID/edit#gid=0"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "FECHA": "={{ $json.fecha }}",
            "TELEFONO": "={{ $json.telefono }}",
            "NOMBRE": "={{ $json.nombre }}",
            "MOTIVO": "={{ $json.motivo }}",
            "OBRA SOCIAL": "={{ $json.obra_social }}",
            "URGENCIA": "={{ $json.urgencia }}",
            "RESUMEN": "={{ $json.resumen }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "FECHA",
              "displayName": "FECHA",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "TELEFONO",
              "displayName": "TELEFONO",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "NOMBRE",
              "displayName": "NOMBRE",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "MOTIVO",
              "displayName": "MOTIVO",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "OBRA SOCIAL",
              "displayName": "OBRA SOCIAL",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "URGENCIA",
              "displayName": "URGENCIA",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "RESUMEN",
              "displayName": "RESUMEN",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1888,
        256
      ],
      "id": "f0d69027-967f-40d6-8db1-0b828fd46e23",
      "name": "18 \u00b7 CRM \u2014 Guardar lead en Sheets",
      "executeOnce": false,
      "credentials": {
        "googleSheetsOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 3
          },
          "conditions": [
            {
              "id": "3f2cbf09-1eea-4ba9-9d71-7167969cbefe",
              "leftValue": "=={{ $json.sheets_ok }}",
              "rightValue": "=={{ true }}",
              "operator": {
                "type": "string",
                "operation": "notEquals"
              }
            }
          ],
          "combinator": "and"
        },
        "looseTypeValidation": true,
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        2336,
        256
      ],
      "id": "dafe9b95-add0-4053-a022-79ea44877641",
      "name": "19 \u00b7 Filtro \u2014 \u00bfError en Sheets?"
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumberId": "=YOUR_WHATSAPP_PHONE_NUMBER_ID",
        "recipientPhoneNumber": "=YOUR_SUPPORT_TEAM_NUMBER",
        "textBody": "=\u26a0\ufe0f ClinicBot \u2014 Falla al guardar en Sheets.\nCargar manualmente:\nNombre: ={{ $('13 \u00b7 Parser \u2014 PATIENT_DATA').item.json.nombre }}\nMotivo: ={{ $('13 \u00b7 Parser \u2014 PATIENT_DATA').item.json.motivo }}\nObra social: ={{ $('13 \u00b7 Parser \u2014 PATIENT_DATA').item.json.obra_social }}\nUrgencia: ={{ $('13 \u00b7 Parser \u2014 PATIENT_DATA').item.json.urgencia }}\nTel\u00e9fono: ={{ $('13 \u00b7 Parser \u2014 PATIENT_DATA').item.json.telefono }}",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1.1,
      "position": [
        2544,
        0
      ],
      "id": "93ca1594-c301-42ea-86c6-d86d737c7a62",
      "name": "20 \u00b7 Alerta \u2014 Falla Sheets",
      "credentials": {
        "whatsAppApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "DELETE FROM n8n_chat_histories WHERE session_id = $1",
        "options": {
          "queryReplacement": "=={{ $('04 \u00b7 Extracci\u00f3n \u2014 Tel\u00e9fono y mensaje').item.json.telefono }}"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        2608,
        272
      ],
      "id": "3920aae6-4e53-4190-ac34-d4306c1b328b",
      "name": "21 \u00b7 Memoria \u2014 Reset sesi\u00f3n PostgreSQL",
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "return [{\n  json: {\n    sheets_ok: true\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2096,
        256
      ],
      "id": "348dce4a-e69e-4abf-be24-41d71a980296",
      "name": "Code in JavaScript"
    }
  ],
  "connections": {
    "01 \u00b7 Trigger \u2014 WhatsApp Entrante": {
      "main": [
        [
          {
            "node": "02 \u00b7 Filtro \u2014 Mensaje v\u00e1lido",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "02 \u00b7 Filtro \u2014 Mensaje v\u00e1lido": {
      "main": [
        [
          {
            "node": "04 \u00b7 Extracci\u00f3n \u2014 Tel\u00e9fono y mensaje",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "03 \u00b7 End \u2014 Mensaje inv\u00e1lido",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "04 \u00b7 Extracci\u00f3n \u2014 Tel\u00e9fono y mensaje": {
      "main": [
        [
          {
            "node": "05 \u00b7 Filtro \u2014 \u00bfEs texto?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "05 \u00b7 Filtro \u2014 \u00bfEs texto?": {
      "main": [
        [
          {
            "node": "07 \u00b7 Agente \u2014 GPT-4o-mini",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "06 \u00b7 Fallback \u2014 Mensaje no textual",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "07 \u00b7 Agente \u2014 GPT-4o-mini": {
      "main": [
        [
          {
            "node": "10 \u00b7 Filtro \u2014 \u00bfError en agente?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "08 \u00b7 Memoria \u2014 PostgreSQL": {
      "ai_memory": [
        [
          {
            "node": "07 \u00b7 Agente \u2014 GPT-4o-mini",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "09 \u00b7 Modelo \u2014 OpenAI": {
      "ai_languageModel": [
        [
          {
            "node": "07 \u00b7 Agente \u2014 GPT-4o-mini",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "10 \u00b7 Filtro \u2014 \u00bfError en agente?": {
      "main": [
        [
          {
            "node": "13 \u00b7 Parser \u2014 PATIENT_DATA",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "11 \u00b7 Fallback \u2014 Disculpa al paciente",
            "type": "main",
            "index": 0
          },
          {
            "node": "12 \u00b7 Alerta \u2014 Falla OpenAI",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "13 \u00b7 Parser \u2014 PATIENT_DATA": {
      "main": [
        [
          {
            "node": "15 \u00b7 Respuesta \u2014 WhatsApp al paciente",
            "type": "main",
            "index": 0
          },
          {
            "node": "14 \u00b7 Filtro \u2014 \u00bfError en parser?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "14 \u00b7 Filtro \u2014 \u00bfError en parser?": {
      "main": [
        [
          {
            "node": "11 \u00b7 Fallback \u2014 Disculpa al paciente",
            "type": "main",
            "index": 0
          },
          {
            "node": "12 \u00b7 Alerta \u2014 Falla OpenAI",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "16 \u00b7 Filtro \u2014 \u00bfLead completo?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "16 \u00b7 Filtro \u2014 \u00bfLead completo?": {
      "main": [
        [
          {
            "node": "18 \u00b7 CRM \u2014 Guardar lead en Sheets",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "17 \u00b7 End \u2014 Lead incompleto",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "18 \u00b7 CRM \u2014 Guardar lead en Sheets": {
      "main": [
        [
          {
            "node": "Code in JavaScript",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "19 \u00b7 Filtro \u2014 \u00bfError en Sheets?": {
      "main": [
        [
          {
            "node": "20 \u00b7 Alerta \u2014 Falla Sheets",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "21 \u00b7 Memoria \u2014 Reset sesi\u00f3n PostgreSQL",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code in JavaScript": {
      "main": [
        [
          {
            "node": "19 \u00b7 Filtro \u2014 \u00bfError en Sheets?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": true,
  "settings": {
    "executionOrder": "v1",
    "binaryMode": "separate",
    "availableInMCP": false
  },
  "versionId": "9a223972-3ba5-4c91-901c-e81a35b384fa",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "id": "knsih6Ns5nkHzQyV",
  "tags": []
}