{
  "name": "SDR AI Agent",
  "nodes": [
    {
      "parameters": {
        "content": "## Indexmed OpenRouter API key\n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",
        "height": 240,
        "width": 694,
        "color": 6
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        39088,
        13312
      ],
      "typeVersion": 1,
      "id": "d881e28a-bad1-4fab-9067-963b09a538da",
      "name": "Sticky Note",
      "disabled": true
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "1154207f-3f6b-4a4a-82b5-a6d83b08f22e",
              "leftValue": "={{ $json.body.message_type }}",
              "rightValue": "incoming",
              "operator": {
                "type": "string",
                "operation": "equals",
                "name": "filter.operator.equals"
              }
            },
            {
              "id": "383d55d6-e864-4037-92ad-c0e00d283b54",
              "leftValue": "={{ $json.body.conversation.meta.assignee }}",
              "rightValue": "",
              "operator": {
                "type": "object",
                "operation": "empty",
                "singleValue": true
              }
            },
            {
              "id": "c45fc447-18b4-48d4-a2b8-77ec50e3c97c",
              "leftValue": "={{ $json.body.account.id }}",
              "rightValue": 4,
              "operator": {
                "type": "number",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2.2,
      "position": [
        38640,
        13728
      ],
      "id": "ab3963fd-9266-4153-92b9-38ee8538c7d3",
      "name": "FiltraSomenteCliente",
      "notesInFlow": true,
      "notes": "Excluir AND de teste\n\n\n{{ $json.body.conversation.meta.sender.identifier }}\n\n5511976800541@s.whatsapp.net\n\n### melhoria\n\n- array para inbox"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "096d9ca8-2075-4512-917e-62ff1932a445",
              "name": "account.id",
              "value": "={{ $json.body.account.id }}",
              "type": "number"
            },
            {
              "id": "4ecbcd6f-9769-4a4f-97a3-5ec081668f0b",
              "name": "content.body",
              "value": "={{ $json.body.conversation.messages[0].content }}",
              "type": "string"
            },
            {
              "id": "e3ce1450-6f96-45ac-b9be-6c275a6cb973",
              "name": "sender.name",
              "value": "={{ $json.body.conversation.messages[0].sender.name }}",
              "type": "string"
            },
            {
              "id": "9b5b3224-1f97-4052-9ed5-3ba8f0a41fb8",
              "name": "conversation.id",
              "value": "={{ $json.body.conversation.id }}",
              "type": "number"
            },
            {
              "id": "606928f4-84fc-4e67-abe0-dd33c3dca5db",
              "name": "content.type",
              "value": "={{ $json.body.content_type }}",
              "type": "string"
            },
            {
              "id": "5f8bbdbc-8c5f-45f1-9d78-3a309631f4e3",
              "name": "sender.id",
              "value": "={{ $json.body.conversation.meta.sender.id }}",
              "type": "number"
            },
            {
              "id": "62fd7d45-14de-46cd-8b1a-fbdc1a74f350",
              "name": "inbox.id",
              "value": "={{ $json.body.conversation.inbox_id }}",
              "type": "number"
            },
            {
              "id": "6ba8e6a8-6fa0-4380-bffd-ee24723d1423",
              "name": "tags",
              "value": "={{ $json.body.conversation.labels }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        38592,
        14096
      ],
      "id": "e8393980-9f39-4ba7-9127-0befd817b9fb",
      "name": "PayloadPergunta",
      "notesInFlow": true,
      "notes": "Este nó, chamado PayloadPergunta, tem a função de extrair do webhook de entrada todas as informações essenciais da conversa e organizá-las em campos padronizados para uso nos próximos passos do fluxo. Na prática, ele:\n\nCaptura o ID da conta que recebeu a mensagem, garantindo que o fluxo saiba em qual instância ou cliente ele está operando.\n\nArmazena o texto da mensagem propriamente dito, retirando-o do primeiro elemento da lista de mensagens da conversa.\n\nRegistra o nome do remetente, conforme consta no payload, para facilitar personalizações de resposta ou registros de log.\n\nGuarda o ID da conversa, permitindo rastrear e associar respostas ao mesmo diálogo.\n\nSalva o tipo de conteúdo (por exemplo, “text” ou outro formato), para que nós seguintes possam decidir como processar cada caso (texto, imagem, áudio etc.).\n\nDefine o ID do remetente extraído da metainformação da conversa, utilíssimo para buscas ou atualizações em sistemas externos.\n\nMantém o ID da caixa de entrada (inbox) onde a conversa ocorreu, caso você tenha múltiplos canais ou filas de atendimento.\n\nColeta quaisquer tags associadas à conversa, facilitando categorizações, disparos de automações condicionais ou análises posteriores.\n\nAo final dessa etapa, todos esses dados ficam disponíveis como variáveis claramente nomeadas, garantindo que cada nó subsequente possa referenciar informações de contexto sem precisar navegar diretamente pela estrutura bruta do JSON."
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "a571d948-68bc-492a-b8df-db73d0df7151",
              "name": "mensagem",
              "value": "={{ $json.text }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "1d4af71c-c079-4fd7-882c-8710f54d2677",
      "name": "Transcrição",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.3,
      "position": [
        40432,
        14016
      ]
    },
    {
      "parameters": {
        "content": "## Extração da Mensagem - configurando para chatwoot\n**Ações** \n1. Identifica e filtra por tipo da mensagem. \n2. Extrai a mensagem da conversa.\n2. Se for áudio transcreve para transformar em msg texto.\n\n\n",
        "height": 757,
        "width": 1552,
        "color": 7
      },
      "id": "18b68c34-2701-4338-a641-efe185647591",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        39376,
        13568
      ]
    },
    {
      "parameters": {
        "content": "## Entrada da Mensagem\n1. Recebe webhook do chatwoot (mensagem criada).\n2. Filtra os seguintes parâmetros (incomming, atribuidas, conta e inbox chatwoot e número [para realizar testes controlados] )",
        "height": 371,
        "width": 1270,
        "color": 3
      },
      "id": "4eabcd57-5941-43c6-86e6-c3987f96b766",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        38096,
        13568
      ]
    },
    {
      "parameters": {
        "content": "## Variáveis\n1. Devem ser atualizadas (atenção aqui).\n2. Facilita a padronização de dados no fluxo.",
        "height": 372,
        "width": 1268,
        "color": 3
      },
      "id": "f15003dc-f61a-47ec-aab6-d6d17a846553",
      "name": "Sticky Note7",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        38096,
        13952
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('w-cfg').item.json.baseUrl }}/api/v1/accounts/{{ $('PayloadPergunta').item.json.account.id }}/conversations/{{ $('PayloadPergunta').item.json.conversation.id }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "content",
              "value": "={{ $json.parte }}"
            },
            {
              "name": "message_type",
              "value": "outgoing"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        44512,
        13984
      ],
      "id": "9b7bc081-7b77-4b79-9b26-102a6d78583b",
      "name": "EnviaChatwoot",
      "credentials": {
        "httpHeaderAuth": {
          "id": "DukjhoZy36MLkfgu",
          "name": "Chatfluxx Header Auth account - Indexmed Automation"
        }
      }
    },
    {
      "parameters": {
        "content": "## Agentes\n**Double click** to edit me. [Guide](https://docs.n8n.io/workflows/sticky-notes/)",
        "height": 760,
        "width": 444,
        "color": 5
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        42192,
        13568
      ],
      "typeVersion": 1,
      "id": "e64d14a0-d387-4f84-b0cf-42fcbaa53278",
      "name": "Sticky Note6"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "89632975-c910-47bf-bea8-d5975b09f759",
              "name": "mensagem",
              "value": "={{ $('FiltraSomenteCliente').item.json.body.content }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        40144,
        13840
      ],
      "id": "232909a1-61d0-47ff-b2b0-11744b3e3381",
      "name": "pegaMensagem"
    },
    {
      "parameters": {
        "options": {
          "timezone": "America/Sao_Paulo"
        }
      },
      "type": "n8n-nodes-base.dateTime",
      "typeVersion": 2,
      "position": [
        41072,
        13920
      ],
      "id": "114f7e0a-7949-497d-9c03-9a5d81e95d33",
      "name": "Date & Time"
    },
    {
      "parameters": {
        "operation": "set",
        "key": "=inputMessage-{{ $('entradaChatwoot').item.json.body.conversation.messages[0].conversation_id }}",
        "value": "={{ $('mensagemConsolidada').item.json.mensagem }} {{ $json.messageUser }}",
        "keyType": "string"
      },
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        41600,
        13920
      ],
      "id": "87e368bc-fd53-4cd7-9cc8-73aeb47ff0d0",
      "name": "messageInsert",
      "notesInFlow": true,
      "credentials": {
        "redis": {
          "id": "FLCVkBfVQjtBZowE",
          "name": "Redis account"
        }
      },
      "notes": "- insere mensagens na key (inputMessage-conversationid) de forma incremental."
    },
    {
      "parameters": {
        "operation": "set",
        "key": "={{ String($('entradaChatwoot').item.json.body.conversation.messages[0].conversation_id) }}",
        "value": "={{ $execution.id }}",
        "keyType": "string",
        "expire": true,
        "ttl": 600
      },
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        41248,
        13920
      ],
      "id": "fa6a9fd1-d725-42b1-bd02-b79a6fad5810",
      "name": "setExecutionMarker",
      "notesInFlow": true,
      "credentials": {
        "redis": {
          "id": "FLCVkBfVQjtBZowE",
          "name": "Redis account"
        }
      },
      "notes": "- Insere a data corrente deste fluxo como valor da chave que será o 'conversationid' do chatwoot.\n\n- Deste modo não há problema o tipo de canal de entrada se é whatsapp, Instagram ou outros."
    },
    {
      "parameters": {
        "operation": "get",
        "propertyName": "executionMarker",
        "key": "={{ String($('entradaChatwoot').item.json.body.conversation.messages[0].conversation_id) }}",
        "keyType": "string",
        "options": {}
      },
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        41440,
        14160
      ],
      "id": "32f4698c-dc09-44d8-b6e6-b835b5a30d93",
      "name": "getLatestExecutionMarker",
      "notesInFlow": true,
      "credentials": {
        "redis": {
          "id": "FLCVkBfVQjtBZowE",
          "name": "Redis account"
        }
      },
      "notes": "Retorna a data futura da key. \n\nSim ela pode ser futura pois durante o WAIT que está configurando antes desse node, o cliente pode ter enviado outra mensagem durante este período de espera"
    },
    {
      "parameters": {
        "operation": "get",
        "propertyName": "messageUser",
        "key": "=inputMessage-{{ $('entradaChatwoot').item.json.body.conversation.messages[0].conversation_id }}",
        "keyType": "string",
        "options": {}
      },
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        41424,
        13920
      ],
      "id": "17a6fba7-2110-4c96-8303-0cdd860066c6",
      "name": "getMessage",
      "notesInFlow": true,
      "credentials": {
        "redis": {
          "id": "FLCVkBfVQjtBZowE",
          "name": "Redis account"
        }
      },
      "notes": "- Verifica se há mensagens do cliente na chave (Key)\n- objetivo de pedir esse GET é para incrementar novas mensagens na mesma chave sem perder as antigas."
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 1
          },
          "conditions": [
            {
              "id": "b50066ef-17e2-4cb5-8447-f3c3f4693521",
              "leftValue": "={{ $execution.id }}",
              "rightValue": "={{ $json.executionMarker }}",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "17938a0f-8663-42d7-acfc-af23580c47d9",
      "name": "confereFutureTime",
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2,
      "position": [
        41632,
        14160
      ],
      "notesInFlow": true,
      "notes": "Aqui comparamos se a data da mesma key que pegamos durante o WAIT é mais recente que a data deste fluxo que está rodando agora."
    },
    {
      "parameters": {
        "operation": "get",
        "propertyName": "messageUser",
        "key": "=inputMessage-{{ $('entradaChatwoot').item.json.body.conversation.messages[0].conversation_id }}",
        "options": {}
      },
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        41072,
        14160
      ],
      "id": "aac7e65f-ac42-4dc5-b429-61e0e159b8b6",
      "name": "messageAgregated",
      "notesInFlow": true,
      "credentials": {
        "redis": {
          "id": "FLCVkBfVQjtBZowE",
          "name": "Redis account"
        }
      },
      "notes": "- Retorna as mensagens agregadas"
    },
    {
      "parameters": {
        "amount": "={{ $('w-cfg').item.json.debounce }}"
      },
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        41248,
        14160
      ],
      "id": "44443cb6-0137-4431-b190-db280aa81249",
      "name": "tempoEspera",
      "webhookId": "ab63a793-4cd1-4b3c-b747-32d9efc44f05",
      "notesInFlow": true,
      "notes": "Selecione o tempo de deBounce (tempo para agregar mensagens multiplas do cliente dentro de um mesmo espaço de tempo evitando que o agente responda todas as mensagens picotadas do cliente.)"
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "sdr-ai-agent",
        "options": {}
      },
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        38240,
        13728
      ],
      "id": "ab6b197e-8c5c-4ad3-a6a4-5afd87d6c67d",
      "name": "entradaChatwoot",
      "webhookId": "6bf04170-342f-491d-9936-3621257111a8"
    },
    {
      "parameters": {
        "operation": "delete",
        "key": "=inputMessage-{{ $('entradaChatwoot').item.json.body.conversation.messages[0].conversation_id }}"
      },
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        41984,
        13984
      ],
      "id": "4b091688-c0bf-4238-93e4-249b0452ad6a",
      "name": "resetMessageAgregated",
      "executeOnce": true,
      "credentials": {
        "redis": {
          "id": "FLCVkBfVQjtBZowE",
          "name": "Redis account"
        }
      },
      "notes": "Reseta as mensagens agregadas"
    },
    {
      "parameters": {
        "options": {}
      },
      "id": "99c6f655-62f1-4b7d-a8cc-9a0298111967",
      "name": "Loop Over Items",
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        44096,
        13904
      ]
    },
    {
      "parameters": {
        "content": "## Reseta Debounce de Mensagens\n\n",
        "height": 764,
        "width": 296,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        41872,
        13568
      ],
      "typeVersion": 1,
      "id": "6b5fdefc-8c0f-40a1-8224-4730e1d4d0d7",
      "name": "Sticky Note11"
    },
    {
      "parameters": {
        "content": "## Efeito Humanizador (Particiona Mensagens)\n1. Recebe uma tabela com as mensagens já particionadas.\n2. Envia por Split.\n3. Setar wait de acordo com a estratégia.",
        "height": 764,
        "width": 1236,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        43456,
        13568
      ],
      "typeVersion": 1,
      "id": "88ae4b76-1386-41b6-a61f-6368c232cb5d",
      "name": "Sticky Note4"
    },
    {
      "parameters": {
        "content": "## Formata Saída de Mensagens \n",
        "height": 764,
        "width": 776,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        42656,
        13568
      ],
      "typeVersion": 1,
      "id": "bb9b76bd-b386-46b0-bc01-14b00783c4bc",
      "name": "Sticky Note5"
    },
    {
      "parameters": {
        "jsCode": "// Pega o input do nó anterior (mais robusto que referenciar por nome)\nconst raw = $input.first().json;\n\n// Cobre 3 casos: array direto, objeto com array dentro, ou objeto plano\nlet item;\nif (Array.isArray(raw)) {\n  item = raw[0];\n} else if (Array.isArray(raw.body)) {\n  item = raw.body[0];\n} else if (Array.isArray(raw.data)) {\n  item = raw.data[0];\n} else {\n  item = raw;\n}\n\n// Resolve o texto da resposta\nconst texto =\n  item?.reply ??\n  item?.output ??\n  item?.text ??\n  item?.body?.reply ??\n  item?.body?.output ??\n  item?.data?.reply ??\n  item?.data?.output;\n\nif (!texto || typeof texto !== 'string') {\n  throw new Error(\n    `Nenhum campo de texto encontrado. Keys: ${Object.keys(item || {}).join(', ')}. Sample: ${JSON.stringify(raw).slice(0, 300)}`\n  );\n}\n\nconst sessionId = item?.session_id ?? raw?.session_id ?? null;\n\n// Passo 1: Regex para domínios com múltiplos sufixos\nconst domainRegex = /\\b(?:(?!\\d\\.\\d)(?:[a-zA-Z][\\w-]*)\\.)+(?:[a-zA-Z]{2,})(?:\\.[a-zA-Z]{2,})?\\b/g;\n\n// Passo 2: Mascarar domínios trocando \".\" por \"_DOT_\"\nlet textoMascarado = texto.replace(domainRegex, m => m.replace(/\\./g, '_DOT_'));\n\n// Passo 3: Quebrar em linhas não vazias\nlet linhas = textoMascarado\n  .split('\\n')\n  .map(l => l.trim())\n  .filter(l => l.length > 0);\n\n// Passo 4: Transformar linhas em sentenças\nconst sentenceSplitRegex = /(?<!Dr\\.)(?<!Dra\\.)(?<=[.!?])\\s+(?=[A-ZÁÀÂÃÉÈÊÍÏÓÔÕÖÚÜÇ])/;\n\nlet sentencas = [];\n\nlinhas.forEach(linha => {\n  if (linha.startsWith('- ')) {\n    sentencas.push(linha.slice(2).trim());\n  } else if (/^[0-9]+\\.\\s+/.test(linha)) {\n    sentencas.push(linha.replace(/^[0-9]+\\.\\s+/, '').trim());\n  } else {\n    sentencas.push(\n      ...linha\n        .split(sentenceSplitRegex)\n        .map(p => p.trim())\n        .filter(p => p.length > 0)\n    );\n  }\n});\n\n// Passo 5: Cortar sentenças maiores que 300 caracteres sem quebrar palavras\nconst MAX_LENGTH = 300;\nlet resultados = [];\n\nsentencas.forEach(s => {\n  const t = s.trim();\n  if (t.length <= MAX_LENGTH) {\n    resultados.push(t);\n  } else {\n    let buffer = '';\n    t.split(' ').forEach(palavra => {\n      const tentativa = buffer ? `${buffer} ${palavra}` : palavra;\n      if (tentativa.length > MAX_LENGTH) {\n        if (buffer) resultados.push(buffer);\n        buffer = palavra;\n      } else {\n        buffer = tentativa;\n      }\n    });\n    if (buffer) resultados.push(buffer);\n  }\n});\n\n// Passo 6: Reverter \"_DOT_\" para \".\"\nlet revertidos = resultados.map(r => r.replace(/_DOT_/g, '.'));\n\n// Passo 7: Converter **texto** em *texto* (negrito Markdown → WhatsApp)\nlet ajustados = revertidos.map(r => r.replace(/\\*\\*(.*?)\\*\\*/g, '*$1*'));\n\n// Passo 8: Retornar partes de texto\nreturn ajustados.map((parte, index) => ({\n  json: {\n    parte,\n    index,\n    session_id: sessionId\n  }\n}));"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        43248,
        14160
      ],
      "id": "7a53f037-2196-4acc-a2d1-6c87e5cb40c4",
      "name": "particionaMensagem",
      "notesInFlow": true,
      "notes": "descrição passo a passo em português do que esse script faz:\n\nValidação de entrada\n\nLê texto de $json.output e lança erro se não existir ou não for string.\n\nMascaramento de domínios\n\nUsa uma regex para identificar domínios (ex.: exemplo.com.br) e substitui cada ponto por _DOT_ para evitar quebras indesejadas (pontos dentro de números continuam “.”).\n\nQuebra em linhas não vazias\n\nDivide o texto mascarado em linhas, remove espaços extras e filtra linhas vazias.\n\nTransformação de linhas em sentenças\n\nPara cada linha:\n\nSe começa com - : remove o traço e trata como uma sentença única.\n\nSe é numerada (ex.: 1. Texto): remove o índice e trata como sentença.\n\nCaso contrário: aplica um split inteligente usando a regex\n\n/(?<!Dr\\.)(?<!Dra\\.)(?<=[.!?])\\s+(?=[A-ZÁÀÂÃÉÈÊÍÏÓÔÕÖÚÜÇ])/\n– Só quebra após . ! ? seguido de espaço quando o próximo caractere for maiúsculo e não vier logo depois de abreviações como Dr. ou Dra..\n– Garante que “Dra. Gabriela” não seja dividida, mas divide normalmente frases como “Olá. Tudo bem?”.\n\nCorte de sentenças longas\n\nLimita cada sentença a no máximo 300 caracteres, sem quebrar palavras no meio:\n\nSe a sentença excede 300 chars, constrói um buffer palavra a palavra; sempre que o buffer ultrapassa 300, adiciona-o à lista e reinicia.\n\nRestauro dos domínios\n\nSubstitui _DOT_ de volta para . em cada parte resultante.\n\nAjuste de formatação em markdown\n\nConverte marcações de negrito **texto** para itálico *texto*.\n\nRetorno do resultado\n\nMonta o array final retornando, para cada parte, um objeto { json: { parte: \"...\" } }."
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "b6cd097d-3a3a-4cdc-a6f1-13c118a4618c",
              "name": "audio64",
              "value": "={{ $('FiltraSomenteCliente').item.json.body.conversation.messages[0].attachments[0].data_url }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "90db2766-f86f-4d0c-9a45-5ee754ef57f5",
      "name": "salvaInformaçõesAudio",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.3,
      "position": [
        39696,
        14032
      ]
    },
    {
      "parameters": {
        "url": "={{ $json.audio64 }}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        39952,
        14032
      ],
      "id": "7b5fcbc4-cfb8-4124-b4cd-690ce17591d6",
      "name": "baixaAudio",
      "retryOnFail": true
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "3bbc4d64-6aba-4f46-abbf-8dbd6d326b06",
              "name": "messageUser",
              "value": "={{ $('messageAgregated').item.json.messageUser }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        42288,
        13936
      ],
      "id": "0fe471eb-a6f6-4a10-969a-d1229f782a8c",
      "name": "mensagensAgregadas"
    },
    {
      "parameters": {
        "amount": "={{ Math.max(0.5, $json.parte.length / 15) }}"
      },
      "id": "b7b3513f-8d24-4784-b5c7-a342f911fd1d",
      "name": "intervaloPartes",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        44320,
        13984
      ],
      "webhookId": "1caa0cc0-6e20-47b9-ab71-072cf9d80ec9"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "5af1acb4-e2f5-44eb-b8f8-464efcbd4874",
              "leftValue": "={{ $('entradaChatwoot').item.json.body.content }}",
              "rightValue": "",
              "operator": {
                "type": "string",
                "operation": "exists",
                "singleValue": true
              }
            },
            {
              "id": "53283dc2-04e6-44fd-9844-25562100058c",
              "leftValue": "={{ $('entradaChatwoot').item.json.body.content }}",
              "rightValue": "",
              "operator": {
                "type": "string",
                "operation": "notEmpty",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2.2,
      "position": [
        39984,
        13840
      ],
      "id": "f7e38364-358b-460e-b42e-a57a9bb4b28a",
      "name": "separaTexto"
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                },
                "conditions": [
                  {
                    "leftValue": "={{ $('FiltraSomenteCliente').item.json.body.content_type }}",
                    "rightValue": "text",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "id": "0e5d00b6-04aa-4476-a965-4b728395c0c8"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Mensagem de Texto"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                },
                "conditions": [
                  {
                    "id": "86e7e773-8586-458f-a1fb-2890f2030230",
                    "leftValue": "={{ $('FiltraSomenteCliente').item.json.body.content_type }}",
                    "rightValue": "extendedTextMessage",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Mensagem"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                },
                "conditions": [
                  {
                    "id": "7f108034-a1be-4e90-b42e-e4f8a719e311",
                    "leftValue": "={{ $('FiltraSomenteCliente').item.json.body.content_type }}",
                    "rightValue": "editedMessage",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Mensagem Editada"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                },
                "conditions": [
                  {
                    "id": "256e7cf8-be54-4c41-ba80-2d9eb0a07563",
                    "leftValue": "={{ $('FiltraSomenteCliente').item.json.body.conversation.messages[0].attachments[0].file_type }}",
                    "rightValue": "audio",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Áudio"
            }
          ]
        },
        "options": {
          "allMatchingOutputs": true
        }
      },
      "id": "de40b76a-1b09-451a-ad90-3b0dd978d615",
      "name": "tipoMensagemChatwoot",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3,
      "position": [
        39504,
        13840
      ],
      "notesInFlow": true,
      "notes": "O nó “Tipo da Mensagem – cwoot” é um Switch que avalia o payload recebido do node FiltraSomenteCliente e o classifica em até quatro categorias distintas, criando saídas separadas para cada tipo de conteúdo:\n\nMensagem de Texto: quando o campo content_type do corpo da conversa é \"text\".\n\nMensagem: quando esse mesmo campo indica \"extendedTextMessage\", ou seja, um texto mais elaborado/várias linhas.\n\nMensagem Editada: quando o conteúdo foi alterado (\"editedMessage\").\n\nÁudio: quando há um anexo cujo file_type é \"audio\".\n\nComo a opção allMatchingOutputs está ativada, uma única entrada pode disparar simultaneamente mais de uma dessas saídas, permitindo que nós subsequentes processem cada categoria de forma independente."
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "c5c4a3bc-2dac-44ee-849f-753b4e24d55e",
              "leftValue": "={{ $json.body.conversation.inbox_id }}",
              "rightValue": 85,
              "operator": {
                "type": "number",
                "operation": "equals"
              }
            }
          ],
          "combinator": "or"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2.2,
      "position": [
        38448,
        13728
      ],
      "id": "0c336562-035f-4430-910e-53311b255318",
      "name": "FiltraInbox",
      "notesInFlow": true,
      "notes": "Filtra múltiplos Inbox de acordo com a necessidade."
    },
    {
      "parameters": {
        "content": "![Fluxo](https://f005.backblazeb2.com/file/neofluxx-media/logos/Neofluxx.png)",
        "height": 240,
        "width": 976,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        38096,
        13312
      ],
      "typeVersion": 1,
      "id": "3ef64e57-f2d7-49ba-ac32-f9cb9215b93d",
      "name": "Sticky Note3"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "d647495f-e385-42ac-9d61-bac317e9bbaa",
              "leftValue": "={{ $json.body.conversation.messages[0].sender.phone_number }}",
              "rightValue": "+5511982084044",
              "operator": {
                "type": "string",
                "operation": "equals",
                "name": "filter.operator.equals"
              }
            },
            {
              "id": "c5b42925-ea8f-48ee-ae3a-967f1eaed3a1",
              "leftValue": "={{ $json.body.conversation.messages[0].sender.phone_number }}",
              "rightValue": "+5511941119510",
              "operator": {
                "type": "string",
                "operation": "equals",
                "name": "filter.operator.equals"
              }
            },
            {
              "id": "d61ae099-b698-4718-8eec-77222b656edc",
              "leftValue": "={{ $json.body.conversation.messages[0].sender.phone_number }}",
              "rightValue": "+5511995396176",
              "operator": {
                "type": "string",
                "operation": "equals",
                "name": "filter.operator.equals"
              }
            }
          ],
          "combinator": "or"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2.2,
      "position": [
        38848,
        13728
      ],
      "id": "b54c40d6-8963-486d-9e81-8c5e4793cf0e",
      "name": "filtraNumeros",
      "disabled": true
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "4f1a2108-e7e3-4b03-98b3-81ddf4bcb73b",
              "name": "mensagem",
              "value": "={{ $json.mensagem }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        40704,
        13936
      ],
      "id": "6b3f8a9d-d795-4591-b672-c9e6a68cc980",
      "name": "mensagemConsolidada"
    },
    {
      "parameters": {
        "content": "### Padroniza Payload de Mensagem\n\n- Evita a ocorrência de erros de referência\n",
        "height": 384,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        40624,
        13776
      ],
      "typeVersion": 1,
      "id": "266d5700-4877-4401-a7f6-5bdc17bb2073",
      "name": "Sticky Note8"
    },
    {
      "parameters": {
        "content": "## ChangeLog v1.02\n- Adiciona condição 'is not empty' para o NODE Filter \"Separa Texto\"\n- Ativa a opção 'Send data to all matching outputs' no NODE Switch \"tipoMensagemChatwoot\" ",
        "width": 1264
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        38096,
        14336
      ],
      "typeVersion": 1,
      "id": "d30f2716-694e-4910-af38-718723e6e5b8",
      "name": "Sticky Note9"
    },
    {
      "parameters": {
        "content": "## Message deBounce (Agregador de Mensagens) \n\n1. Grava o timestamp atual do fluxo em gmt-03:00\n2. Solicita a última mensagem do cliente que ainda não foi processada pelo agente.\n2.1. mensagens processadas pelo agente serão automaticamente limpas.\n3. Insere novas mensagens de maneira incremental.\n4. Retorna todas as mensagens que ainda não foram processadas pelo agente.\n5. Aguarda o WAIT de acordo com a config desejada.\n6. Retorna o timestamp futuro na mesma key que é o conversationId.\n7. Compara o timestamp deste fluxo com o timestamp futuro de possível fluxo mais recenete.\n7.1. Se o timestamp futuro for mais recente interrompe o fluxo e não apaga as mensagens agregadas. Pois em um outro fluxo outra mensagem foi enviada antes do termino do WAIT deste fluxo.",
        "height": 760,
        "width": 920,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        40944,
        13568
      ],
      "typeVersion": 1,
      "id": "b26f3321-1738-4990-8b04-4a5b1e2ace18",
      "name": "Sticky Note10"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "2b3b2565-e01f-4bad-a955-84f0109bb7fc",
              "name": "agora",
              "value": "={{ $now.setZone('America/Sao_Paulo').toISO() }}",
              "type": "string"
            },
            {
              "id": "d3d9a57c-9573-4d64-b08f-43d61ee32472",
              "name": "memory_name",
              "value": "={{ $('PayloadPergunta').item.json.sender.id }}",
              "type": "string"
            },
            {
              "id": "0f251302-de6e-4bbe-9af1-72a1b740acc5",
              "name": "telefone",
              "value": "={{ $('entradaChatwoot').item.json.body.conversation.messages[0].sender.phone_number.replace(/@.*$/, '')  }}",
              "type": "string"
            },
            {
              "id": "0dbfe6e4-ea03-47f9-8494-7317c086ebab",
              "name": "debounce",
              "value": "15",
              "type": "string"
            },
            {
              "id": "e3f2c5d8-d2fd-4ca4-a6ce-2004bb8bb3b6",
              "name": "baseUrl",
              "value": "https://app.neofluxx.com",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "89d6244c-c96e-4f94-8599-5f08eb7c120d",
      "name": "w-cfg",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        38880,
        14096
      ],
      "notesInFlow": true,
      "notes": "Este nó do tipo Set, batizado como Variáveis, tem o papel de preparar e centralizar todas as informações e parâmetros que serão usados ao longo do fluxo. Na execução, ele faz o seguinte:\n\nRegistra o momento exato em que o fluxo está rodando, ajustado para o horário de Brasília (fuso de São Paulo).\n\nExtrai do webhook do Chatwoot o identificador do remetente (o número de WhatsApp), armazenando esse valor tanto como “nome de memória” quanto como “telefone”.\n\nDefine um valor de debounce para evitar que chamadas ou processamentos sejam disparados mais de uma vez em sequência rápida.\n\nArmazena a URL base da API da sua instância de chat, de modo que todos os nós seguintes possam referenciar esse endereço de forma consistente.\n\nAo final, essas variáveis ficam disponíveis para qualquer nó subsequente, garantindo que dados de contexto (como timestamp, identificação do usuário e endereço de serviço) estejam sempre prontos para uso.\n\n\nse for usar/adicionar instancia_api de evolution(colocar o link sem a barra no final)"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "2a5f1168-e4ac-48c5-a397-4ab3347d2d4a",
              "leftValue": "={{ ($('entradaChatwoot').item.json.body.conversation.labels || []).includes('agent-off') }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "false",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2.3,
      "position": [
        39072,
        13728
      ],
      "id": "1c507b87-3017-4f41-a2b1-69b48fee34ad",
      "name": "FiltraAgentTag"
    },
    {
      "parameters": {
        "resource": "audio",
        "operation": "transcribe",
        "binaryPropertyName": "={{ $('baixaAudio').item.binary.data }}",
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 2.1,
      "position": [
        40160,
        14032
      ],
      "id": "503b41dc-2007-42bd-aced-e13fabd9fe5d",
      "name": "Transcribe a recording1",
      "retryOnFail": true,
      "credentials": {
        "openAiApi": {
          "id": "EF30Y6T1kx4OkgZ0",
          "name": "OpenAi account (Indexmed)"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=http://sdr-indexmed:8000/chat",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ (() => {\n  const body = $('entradaChatwoot').first().json.body;\n  const ca = body.sender.custom_attributes || {};\n  \n  const safe = (v) => {\n    if (v === null || v === undefined) return '';\n    const s = String(v).trim();\n    if (s === '' || s === 'undefined' || s === 'null') return '';\n    return s;\n  };\n  \n  const nomeCompleto = safe(body.sender.name);\n  const primeiroNomeRaw = nomeCompleto.split(' ').filter(Boolean)[0] || 'Cliente';\n  const primeiroNome = primeiroNomeRaw.charAt(0).toUpperCase() + primeiroNomeRaw.slice(1).toLowerCase();\n  \n  const payload = {\n    message: safe($json.messageUser),\n    session_id: `cw-${body.conversation.id}`,\n    lead_data: {\n      lead_id: String(body.sender.id),\n      primeiro_nome: primeiroNome,\n      nome_completo: nomeCompleto,\n      empresa: safe(ca.empresa),\n      cargo: safe(ca.cargo),\n      email: safe(body.sender.email),\n      telefone: safe(body.sender.phone_number),\n      vidas_gerenciadas: safe(ca.vidas),\n      origem: 'form_site'\n    },\n    chatwoot: {\n      account_id: String(body.account.id),\n      conversation_id: String(body.conversation.id),\n      inbox_id: String(body.inbox.id),\n      contact_id: String(body.sender.id)\n    }\n  };\n  \n  return JSON.stringify(payload);\n})() }}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        42464,
        13936
      ],
      "id": "bd4b9390-5e56-4b71-9b7b-3a013848c95f",
      "name": "AI Agent"
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "ab9b921a-7bed-4666-858e-d8a6b88f3448",
                    "leftValue": "={{ ($json.tools_called || []).some(t => t.name === 'meeting_scheduling') }}",
                    "rightValue": "",
                    "operator": {
                      "type": "boolean",
                      "operation": "true",
                      "singleValue": true
                    }
                  },
                  {
                    "id": "e96a8337-0c74-470a-81eb-690d454205d1",
                    "leftValue": "={{ ($json.reply || '').includes('📋 Nome completo:') }}",
                    "rightValue": "",
                    "operator": {
                      "type": "boolean",
                      "operation": "true",
                      "singleValue": true
                    }
                  }
                ],
                "combinator": "or"
              },
              "renameOutput": true,
              "outputKey": "MSG_INTEIRA"
            }
          ]
        },
        "options": {
          "fallbackOutput": "extra"
        }
      },
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        42960,
        14096
      ],
      "id": "45ce0ae8-dfb5-4415-9b97-bc69c20d3946",
      "name": "detectaMsgInteira"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "54d294f4-e82a-4e2e-b725-0daa68666532",
              "name": "parte",
              "value": "={{ $json.reply }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        43232,
        13952
      ],
      "id": "91a3fc8f-6811-43dc-a4ff-38241b9d7acf",
      "name": "preparaParteUnica"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('w-cfg').item.json.baseUrl }}/api/v1/accounts/{{ $('PayloadPergunta').item.json.account.id }}/conversations/{{ $('PayloadPergunta').item.json.conversation.id }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "content",
              "value": "={{ $json.parte }}"
            },
            {
              "name": "message_type",
              "value": "outgoing"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        43632,
        13888
      ],
      "id": "c12e9467-9670-4667-9e2b-7cfd78239a3a",
      "name": "EnviaChatwootMsgUnica",
      "credentials": {
        "httpHeaderAuth": {
          "id": "DukjhoZy36MLkfgu",
          "name": "Chatfluxx Header Auth account - Indexmed Automation"
        }
      }
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        44368,
        13760
      ],
      "id": "c7d8d365-a777-4fb3-9b4c-c723326bebd6",
      "name": "No Operation, do nothing"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "5c8f65b0-9865-4517-8be2-b14451e75129",
              "leftValue": "={{ ($json.reply || '').length === 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        42784,
        13856
      ],
      "id": "161df34a-bd2a-4165-b7ac-b25a192b78b2",
      "name": "replyVazio"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=http://sdr-indexmed:8000/chat",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"message\": \"{{ $json.messageUser }}\",\n  \"session_id\": \"cw-{{ $('entradaChatwoot').first().json.body.conversation.id }}\",\n  \"lead_data\": {\n    \"lead_id\": \"{{ $('entradaChatwoot').first().json.body.sender.id }}\",\n    \"primeiro_nome\": \"{{ (() => { const nome = ($('entradaChatwoot').first().json.body.sender.name || '').trim(); const primeiroNome = nome.split(' ').filter(Boolean)[0] || 'Cliente'; return primeiroNome.charAt(0).toUpperCase() + primeiroNome.slice(1).toLowerCase(); })() }}\",\n    \"nome_completo\": \"{{ $('entradaChatwoot').first().json.body.sender.name || '' }}\",\n    \"empresa\": \"{{ $('entradaChatwoot').first().json.body.sender.custom_attributes?.empresa || '' }}\",\n    \"cargo\": \"{{ $('entradaChatwoot').first().json.body.sender.custom_attributes?.cargo || '' }}\",\n    \"email\": \"{{ $('entradaChatwoot').first().json.body.sender.email || '' }}\",\n    \"telefone\": \"{{ $('entradaChatwoot').first().json.body.sender.phone_number || '' }}\",\n    \"vidas_gerenciadas\": \"{{ $('entradaChatwoot').first().json.body.sender.custom_attributes?.vidas || '' }}\",\n    \"origem\": \"form_site\"\n  },\n  \"chatwoot\": {\n    \"account_id\": \"{{ $('entradaChatwoot').first().json.body.account.id }}\",\n    \"conversation_id\": \"{{ $('entradaChatwoot').first().json.body.conversation.id }}\",\n    \"inbox_id\": \"{{ $('entradaChatwoot').first().json.body.inbox.id }}\",\n    \"contact_id\": \"{{ $('entradaChatwoot').first().json.body.sender.id }}\"\n  }\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        42464,
        14336
      ],
      "id": "176c7bd6-30fb-4016-ba8d-e6f62e26c766",
      "name": "AI Agent1"
    }
  ],
  "pinData": {
    "entradaChatwoot": [
      {
        "json": {
          "headers": {
            "host": "webhooks-indexmed.neofluxx.com",
            "user-agent": "rest-client/2.1.0 (linux-musl x86_64) ruby/3.4.4p34",
            "content-length": "5192",
            "accept": "application/json",
            "accept-encoding": "gzip;q=1.0,deflate;q=0.6,identity;q=0.3",
            "content-type": "application/json",
            "x-forwarded-for": "5.161.95.198",
            "x-forwarded-host": "webhooks-indexmed.neofluxx.com",
            "x-forwarded-port": "443",
            "x-forwarded-proto": "https",
            "x-forwarded-server": "traefik_traefik.1",
            "x-real-ip": "5.161.95.198"
          },
          "params": {},
          "query": {},
          "body": {
            "account": {
              "id": 4,
              "name": "Indexmed"
            },
            "additional_attributes": {},
            "content_attributes": {},
            "content_type": "text",
            "content": "Estou precisando de uma ajuda de vcs.\nAtualmente trabalho para duas empresas e tenho apenas um conta, quero desvincular as duas empresas, ficando assim cada conta para sua própria empresa, vcs conseguiriam fazer isso, de alguma forma mas prática?",
            "conversation": {
              "additional_attributes": {},
              "can_reply": true,
              "channel": "Channel::Whatsapp",
              "contact_inbox": {
                "id": 40113,
                "contact_id": 49826,
                "inbox_id": 85,
                "source_id": "5534999534542",
                "created_at": "2026-04-16T15:38:16.928Z",
                "updated_at": "2026-04-16T15:38:16.928Z",
                "hmac_verified": false,
                "pubsub_token": "zmqtLuKm2b4uAsvbGsjbSz5C"
              },
              "id": 3397,
              "inbox_id": 85,
              "messages": [
                {
                  "id": 537041,
                  "content": "Estou precisando de uma ajuda de vcs. \nAtualmente trabalho para duas empresas e tenho apenas um conta, quero desvincular as duas empresas, ficando assim cada conta para sua própria empresa, vcs conseguiriam fazer isso, de alguma forma mas prática?",
                  "account_id": 4,
                  "inbox_id": 85,
                  "conversation_id": 3397,
                  "message_type": 0,
                  "created_at": 1778589085,
                  "updated_at": "2026-05-12T12:31:25.297Z",
                  "private": false,
                  "status": "sent",
                  "source_id": "wamid.HBgMNTUzNDk5NTM0NTQyFQIAEhgUM0EwNkY1MkQ4QjAxRDc1MUNGMEUA",
                  "content_type": "text",
                  "content_attributes": {},
                  "sender_type": "Contact",
                  "sender_id": 49826,
                  "external_source_ids": {},
                  "additional_attributes": {},
                  "processed_message_content": "Estou precisando de uma ajuda de vcs. \nAtualmente trabalho para duas empresas e tenho apenas um conta, quero desvincular as duas empresas, ficando assim cada conta para sua própria empresa, vcs conseguiriam fazer isso, de alguma forma mas prática?",
                  "sentiment": {},
                  "conversation": {
                    "assignee_id": null,
                    "unread_count": 2,
                    "last_activity_at": 1778589085,
                    "contact_inbox": {
                      "source_id": "5534999534542"
                    }
                  },
                  "sender": {
                    "additional_attributes": {
                      "source_id": "email:CAB8GXJ+tJMddHPtrDsj-6k6mKjKXDJ9b3c-Se2kEBEcQ_e-z6w@mail.gmail.com",
                      "avatar_url_hash": "f5ed7af1ee67b117f3ae3413021c26aedcea4010dc2a3d7f57fb4d9bf392e17e",
                      "last_avatar_sync_at": "2026-03-13T14:32:58Z"
                    },
                    "custom_attributes": {
                      "cnpj": "null",
                      "cargo": "Técnico(a) de Segurança do Trabalho",
                      "vidas": "De 101 a 500 vidas",
                      "nr_cpf": "119.440.516-94",
                      "form_name": "formulario_site",
                      "form_source": "Landing page da área informações de planos",
                      "nome_empresa": "brenda",
                      "cd_assinatura": "8959",
                      "como_conheceu": "indexmed.com.br",
                      "ds_tipo_assinatura": "Premium",
                      "ds_status_assinatura": "Ativo",
                      "empresa_area_atuacao": "n/a",
                      "nro_vidas_gerenciadas": "101 a 500",
                      "dt_validade_assinatura": "13/04/2026"
                    },
                    "email": "brendabarreto.bc@gmail.com",
                    "id": 49826,
                    "identifier": null,
                    "name": "Brenda",
                    "phone_number": "+5534999534542",
                    "thumbnail": "",
                    "blocked": false,
                    "type": "contact"
                  }
                }
              ],
              "labels": [],
              "meta": {
                "sender": {
                  "additional_attributes": {
                    "source_id": "email:CAB8GXJ+tJMddHPtrDsj-6k6mKjKXDJ9b3c-Se2kEBEcQ_e-z6w@mail.gmail.com",
                    "avatar_url_hash": "f5ed7af1ee67b117f3ae3413021c26aedcea4010dc2a3d7f57fb4d9bf392e17e",
                    "last_avatar_sync_at": "2026-03-13T14:32:58Z"
                  },
                  "custom_attributes": {
                    "cnpj": "null",
                    "cargo": "Técnico(a) de Segurança do Trabalho",
                    "vidas": "De 101 a 500 vidas",
                    "nr_cpf": "119.440.516-94",
                    "form_name": "formulario_site",
                    "form_source": "Landing page da área informações de planos",
                    "nome_empresa": "brenda",
                    "cd_assinatura": "8959",
                    "como_conheceu": "indexmed.com.br",
                    "ds_tipo_assinatura": "Premium",
                    "ds_status_assinatura": "Ativo",
                    "empresa_area_atuacao": "n/a",
                    "nro_vidas_gerenciadas": "101 a 500",
                    "dt_validade_assinatura": "13/04/2026"
                  },
                  "email": "brendabarreto.bc@gmail.com",
                  "id": 49826,
                  "identifier": null,
                  "name": "Brenda",
                  "phone_number": "+5534999534542",
                  "thumbnail": "",
                  "blocked": false,
                  "type": "contact"
                },
                "assignee": null,
                "assignee_type": null,
                "team": null,
                "hmac_verified": false
              },
              "status": "open",
              "custom_attributes": {},
              "snoozed_until": null,
              "unread_count": 2,
              "first_reply_created_at": "2026-05-12T12:29:57.370Z",
              "priority": null,
              "waiting_since": 1778589085,
              "agent_last_seen_at": 0,
              "contact_last_seen_at": 0,
              "last_activity_at": 1778589085,
              "timestamp": 1778589085,
              "created_at": 1778588962,
              "updated_at": 1778589085.3380458
            },
            "created_at": "2026-05-12T12:31:25.297Z",
            "id": 537041,
            "inbox": {
              "id": 85,
              "name": "Agente Comercial"
            },
            "message_type": "incoming",
            "private": false,
            "sender": {
              "account": {
                "id": 4,
                "name": "Indexmed"
              },
              "additional_attributes": {
                "source_id": "email:CAB8GXJ+tJMddHPtrDsj-6k6mKjKXDJ9b3c-Se2kEBEcQ_e-z6w@mail.gmail.com",
                "avatar_url_hash": "f5ed7af1ee67b117f3ae3413021c26aedcea4010dc2a3d7f57fb4d9bf392e17e",
                "last_avatar_sync_at": "2026-03-13T14:32:58Z"
              },
              "avatar": "",
              "custom_attributes": {
                "cnpj": "null",
                "cargo": "Técnico(a) de Segurança do Trabalho",
                "vidas": "De 101 a 500 vidas",
                "nr_cpf": "119.440.516-94",
                "form_name": "formulario_site",
                "form_source": "Landing page da área informações de planos",
                "nome_empresa": "brenda",
                "cd_assinatura": "8959",
                "como_conheceu": "indexmed.com.br",
                "ds_tipo_assinatura": "Premium",
                "ds_status_assinatura": "Ativo",
                "empresa_area_atuacao": "n/a",
                "nro_vidas_gerenciadas": "101 a 500",
                "dt_validade_assinatura": "13/04/2026"
              },
              "email": "brendabarreto.bc@gmail.com",
              "id": 49826,
              "identifier": null,
              "name": "Brenda",
              "phone_number": "+5534999534542",
              "thumbnail": "",
              "blocked": false
            },
            "source_id": "wamid.HBgMNTUzNDk5NTM0NTQyFQIAEhgUM0EwNkY1MkQ4QjAxRDc1MUNGMEUA",
            "event": "message_created"
          },
          "webhookUrl": "https://webhooks-indexmed.neofluxx.com/webhook/sdr-ai-agent",
          "executionMode": "production"
        },
        "pairedItem": {
          "item": 0
        }
      }
    ]
  },
  "connections": {
    "FiltraSomenteCliente": {
      "main": [
        [
          {
            "node": "filtraNumeros",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "PayloadPergunta": {
      "main": [
        [
          {
            "node": "w-cfg",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Transcrição": {
      "main": [
        [
          {
            "node": "mensagemConsolidada",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "EnviaChatwoot": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "pegaMensagem": {
      "main": [
        [
          {
            "node": "mensagemConsolidada",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Date & Time": {
      "main": [
        [
          {
            "node": "setExecutionMarker",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "messageInsert": {
      "main": [
        [
          {
            "node": "messageAgregated",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "getMessage": {
      "main": [
        [
          {
            "node": "messageInsert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "confereFutureTime": {
      "main": [
        [
          {
            "node": "resetMessageAgregated",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "messageAgregated": {
      "main": [
        [
          {
            "node": "tempoEspera",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "tempoEspera": {
      "main": [
        [
          {
            "node": "getLatestExecutionMarker",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "entradaChatwoot": {
      "main": [
        [
          {
            "node": "FiltraInbox",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Items": {
      "main": [
        [
          {
            "node": "No Operation, do nothing",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "intervaloPartes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "particionaMensagem": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "salvaInformaçõesAudio": {
      "main": [
        [
          {
            "node": "baixaAudio",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "baixaAudio": {
      "main": [
        [
          {
            "node": "Transcribe a recording1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "mensagensAgregadas": {
      "main": [
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "intervaloPartes": {
      "main": [
        [
          {
            "node": "EnviaChatwoot",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "separaTexto": {
      "main": [
        [
          {
            "node": "pegaMensagem",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "tipoMensagemChatwoot": {
      "main": [
        [
          {
            "node": "separaTexto",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "separaTexto",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "separaTexto",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "salvaInformaçõesAudio",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "FiltraInbox": {
      "main": [
        [
          {
            "node": "FiltraSomenteCliente",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "filtraNumeros": {
      "main": [
        [
          {
            "node": "FiltraAgentTag",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "mensagemConsolidada": {
      "main": [
        [
          {
            "node": "Date & Time",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "w-cfg": {
      "main": [
        [
          {
            "node": "tipoMensagemChatwoot",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "FiltraAgentTag": {
      "main": [
        [
          {
            "node": "PayloadPergunta",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Transcribe a recording1": {
      "main": [
        [
          {
            "node": "Transcrição",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent": {
      "main": [
        [
          {
            "node": "replyVazio",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "resetMessageAgregated": {
      "main": [
        [
          {
            "node": "mensagensAgregadas",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "setExecutionMarker": {
      "main": [
        [
          {
            "node": "getMessage",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "getLatestExecutionMarker": {
      "main": [
        [
          {
            "node": "confereFutureTime",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "detectaMsgInteira": {
      "main": [
        [
          {
            "node": "preparaParteUnica",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "particionaMensagem",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "preparaParteUnica": {
      "main": [
        [
          {
            "node": "EnviaChatwootMsgUnica",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "EnviaChatwootMsgUnica": {
      "main": [
        [
          {
            "node": "No Operation, do nothing",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "replyVazio": {
      "main": [
        [
          {
            "node": "No Operation, do nothing",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "detectaMsgInteira",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": true,
  "settings": {
    "executionOrder": "v1",
    "binaryMode": "separate",
    "availableInMCP": false,
    "timeSavedMode": "fixed",
    "errorWorkflow": "K2LaNGa5mWokz7en",
    "callerPolicy": "workflowsFromSameOwner"
  },
  "versionId": "cedc37dd-7875-49f4-bbc1-51cdb8497584",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "4c77d89ec915bc078747315cdb5d4cdb431200dbbb20a5e7e7e4671e8131788e"
  },
  "id": "O6Yu3ntvgMrg52mA",
  "tags": [
    {
      "updatedAt": "2026-03-10T14:18:09.880Z",
      "createdAt": "2026-03-10T14:18:09.880Z",
      "id": "sTn7EF97z7FNk8d2",
      "name": "SDR AI Agent"
    }
  ]
}