{
  "name": "Create Lead message by Forms",
  "nodes": [
    {
      "parameters": {
        "method": "=POST",
        "url": "=https://{{$('w-cfg').first().json.url}}/api/v1/accounts/{{ $('w-cfg').first().json.account_id }}/contacts",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"inbox_id\": {{ $('w-cfg').first().json.inbox_id }},\n  \"name\": \"{{ $('Normaliza Infos').item.json.lead.nome_completo }}\",\n  \"email\": \"{{ $('Normaliza Infos').item.json.lead.email }}\",\n  \"phone_number\": \"+55{{ $('Normaliza Infos').item.json.lead.telefone }}\",\n  \"custom_attributes\": {\n    \"empresa\": \"{{ $('Normaliza Infos').item.json.lead.empresa }}\",\n    \"vidas\": \"{{ $('Normaliza Infos').item.json.lead.vidas_gerenciadas }}\",\n    \"cargo\": \"{{ $('Normaliza Infos').item.json.lead.cargo }}\",\n    \"area_de_atuacao\": \"n/a\"\n  }\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        9936,
        1200
      ],
      "id": "190ab646-0465-4fc8-a6b7-353ebc24c6b9",
      "name": "Create Contact",
      "retryOnFail": true,
      "credentials": {
        "httpHeaderAuth": {
          "id": "DukjhoZy36MLkfgu",
          "name": "Chatfluxx Header Auth account - Indexmed Automation"
        }
      }
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "a41d600b-853e-4fff-aa38-d977fe618eaf",
              "name": "url",
              "value": "app.neofluxx.com",
              "type": "string"
            },
            {
              "id": "0efa7ad1-a44e-4036-8d0e-79a607e7f84f",
              "name": "account_id",
              "value": "4",
              "type": "string"
            },
            {
              "id": "1a83c306-8dd7-4218-aee1-375ef4233904",
              "name": "inbox_id",
              "value": "85",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        8064,
        1328
      ],
      "id": "e5da3e5e-5193-452c-b43c-2a7cb39472f9",
      "name": "w-cfg"
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "indexmed-lead",
        "responseMode": "responseNode",
        "options": {}
      },
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        7184,
        1328
      ],
      "id": "6116bc01-5166-4895-9bf0-cd42fb009b46",
      "name": "Webhook",
      "webhookId": "358b512e-e0e7-45cc-800d-5722ec5d7674"
    },
    {
      "parameters": {
        "respondWith": "text",
        "responseBody": "=<!DOCTYPE html>\n<html lang=\"pt-br\">\n<head>\n<meta charset=\"UTF-8\">\n<title>Indexmed</title>\n\n<style>\n\nbody{\n  font-family: Arial, Helvetica, sans-serif;\n  background:#f4f6fb;\n  display:flex;\n  align-items:center;\n  justify-content:center;\n  height:100vh;\n}\n\n.box{\n  background:white;\n  padding:40px;\n  border-radius:8px;\n  text-align:center;\n  box-shadow:0 2px 10px rgba(0,0,0,0.1);\n  width:420px;\n}\n\nh2{\n  color:#1d3f8f;\n}\n\np{\n  color:#4b5b7c;\n  font-size:16px;\n}\n\n</style>\n\n</head>\n\n<body>\n\n<div class=\"box\">\n\n<h2>Obrigado pelas informações</h2>\n\n<p>\nEm breve você receberá um contato da <b>Indexmed</b>.\n</p>\n\n</div>\n\n</body>\n</html>",
        "options": {}
      },
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.5,
      "position": [
        11248,
        1328
      ],
      "id": "4fd62610-7eca-4978-965e-9d21eb9955be",
      "name": "Respond to Webhook"
    },
    {
      "parameters": {
        "content": "https://www.indexmed.com.br/atendimento",
        "height": 240,
        "width": 1088,
        "color": 6
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        8112,
        880
      ],
      "typeVersion": 1,
      "id": "65062062-48df-451b-ad3e-fa20f4d6f7b5",
      "name": "Sticky Note1"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://{{ $('w-cfg').item.json.url }}/api/v1/accounts/{{ $('w-cfg').item.json.account_id }}/conversations",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{\n{\nsource_id:\n  $json.payload?.contact_inboxes?.find(ci => Number(ci.inbox?.id) === Number($('w-cfg').item.json.inbox_id))?.source_id ||\n  $json.contact_inboxes?.find(ci => Number(ci.inbox?.id) === Number($('w-cfg').item.json.inbox_id))?.source_id ||\n  $json.payload?.contact?.contact_inboxes?.find(ci => Number(ci.inbox?.id) === Number($('w-cfg').item.json.inbox_id))?.source_id ||\n  $('Code Resultado Final').item.json.contato?.contact_inboxes?.find(ci => Number(ci.inbox?.id) === Number($('w-cfg').item.json.inbox_id))?.source_id ||\n  '55' + $('Normaliza Infos').item.json.lead.telefone,\n\n  inbox_id: Number($('w-cfg').item.json.inbox_id),\n\n  contact_id: Number(\n    $json.payload?.id ||\n    $json.id ||\n    $json.payload?.contact?.id ||\n    $('Code Resultado Final').item.json.contato_id ||\n    0\n  ),\n\n  custom_attributes: {\n    priority_conversation_number: 3\n  },\n\n  status: 'open',\n\n  message: {\n    content: $('Prepara Messagem Template').item.json.template_message,\n    template_params: {\n      name: 'primeiro_contato',\n      category: 'MARKETING',\n      language: 'pt_BR',\n      processed_params: {\n        '1': $('Normaliza Infos').item.json.lead.primeiro_nome || '',\n        '2': $('Normaliza Infos').item.json.lead.cargo || '',\n        '3': $('Normaliza Infos').item.json.lead.empresa || '',\n        '4': $('Normaliza Infos').item.json.lead.vidas_gerenciadas || '',\n        '5': $('Normaliza Infos').item.json.lead.plano || '',\n        '6': $('Create Meetings Date').item.json.next_wednesdays_br?.[0] || '',\n        '7': $('Create Meetings Date').item.json.next_wednesdays_br?.[1] || ''\n      }\n    }\n  }\n}\n}}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        10224,
        1328
      ],
      "id": "a5ad6be8-cb52-4bb3-81ed-ae5920fd75c7",
      "name": "Create New Conversation",
      "retryOnFail": true,
      "credentials": {
        "httpHeaderAuth": {
          "id": "DukjhoZy36MLkfgu",
          "name": "Chatfluxx Header Auth account - Indexmed Automation"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// n8n Code Node\nconst now = $now.setZone('America/Sao_Paulo');\nconst WED = 3; // Quarta-feira no Luxon (Mon=1 ... Sun=7)\n\n// Calcula dias até a próxima quarta futura\nlet daysToNextWed = (WED - now.weekday + 7) % 7;\nif (daysToNextWed === 0) daysToNextWed = 7;\n\n// Primeira quarta futura às 10:00\nconst nextWed = now\n  .plus({ days: daysToNextWed })\n  .set({ hour: 10, minute: 0, second: 0, millisecond: 0 });\n\n// Segunda quarta (7 dias depois) às 10:00\nconst nextNextWed = nextWed.plus({ days: 7 });\n\nreturn [\n  {\n    json: {\n      today: now.toFormat('dd/MM/yyyy HH:mm'),\n      next_wednesdays_br: [nextWed, nextNextWed].map(d => d.toFormat('dd/MM/yyyy HH:mm')),\n      next_wednesdays_iso: [nextWed, nextNextWed].map(d => d.toISO()),\n    },\n  },\n];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        7840,
        1328
      ],
      "id": "f7f43ce8-e182-457c-a7c9-4c8e109b045c",
      "name": "Create Meetings Date"
    },
    {
      "parameters": {
        "jsCode": "// Dados do Lead\nconst lead = $('Normaliza Infos').first().json.lead;\n\nconst dadosLead = [\n  {\n    \"Empresa ou área de atuação\": lead.empresa,\n    \"Nº de vidas gerenciadas\": lead.vidas_gerenciadas,\n    \"Nome completo\": lead.nome_completo,\n    \"Cargo\": lead.cargo,\n    \"E-mail\": lead.email,\n    \"Telefone\": lead.telefone,\n    \"CNPJ\": null,\n    \"Como conheceu a Indexmed ?\": $('Webhook').first().json.body.leads[0].first_conversion.conversion_origin.source,\n    \"submittedAt\": $now.toISO(),\n    \"formMode\": \"production\"\n  }\n];\n\n// Opções de Datas\nconst datas = $('Create Meetings Date').first().json.next_wednesdays_br;\nconst opcoesDatas = `${datas[0]},${datas[1]}`;\n\n// Output\nreturn [\n  {\n    json: {\n      \"Dados do Lead\": dadosLead,\n      \"Opções de Datas\": opcoesDatas\n    }\n  }\n];\n"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        10512,
        1312
      ],
      "id": "f7cd724a-2fa3-4910-a29a-f2e2d751872a",
      "name": "Prepares data for the agent's memory"
    },
    {
      "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": [
        7120,
        880
      ],
      "typeVersion": 1,
      "id": "2e674fc2-2c61-4cf1-ac10-694fac5544e9",
      "name": "Sticky Note3"
    },
    {
      "parameters": {
        "content": "## Start\n\n1. Inicia o Flow",
        "height": 528,
        "width": 448,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        7120,
        1136
      ],
      "typeVersion": 1,
      "id": "4748be78-035e-40c3-8da0-5a854a55d821",
      "name": "Sticky Note"
    },
    {
      "parameters": {
        "content": "### Cria Contato e Conversa no Chatwoot baseado nas informações obtidas no formulário\n\n1. Cria o Contato\n2. Cria a Conversa personalizada baseado no envio de um template de mensagens da Meta",
        "height": 528,
        "width": 2016
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        8416,
        1136
      ],
      "typeVersion": 1,
      "id": "c26a06ef-9c7a-46fa-847a-0b043b628e27",
      "name": "Sticky Note2"
    },
    {
      "parameters": {
        "content": "### Prepara dados para injetar na memória do agente",
        "height": 528,
        "width": 208,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        10448,
        1136
      ],
      "typeVersion": 1,
      "id": "f32ba50f-5cdf-4ae1-9649-14274c5e0df8",
      "name": "Sticky Note4"
    },
    {
      "parameters": {
        "content": "### Responde execuçao ao Webhook",
        "height": 528,
        "width": 768,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        10672,
        1136
      ],
      "typeVersion": 1,
      "id": "d4134817-2010-4acf-9354-5084b1ed9052",
      "name": "Sticky Note6"
    },
    {
      "parameters": {
        "content": "#### Normaliza infos do Webhook e Formata 2 datas para Sessões Técnicas\n\n1. Quarta-Feira da semana corrente\n2. Quarta-Feira da semana seguinte a corrente",
        "height": 528,
        "width": 416,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        7584,
        1136
      ],
      "typeVersion": 1,
      "id": "802f5ecc-9bfd-4062-a8de-1dce6b161056",
      "name": "Sticky Note7"
    },
    {
      "parameters": {
        "content": "### Prepara variáveis para ser utilizada no flow",
        "height": 528,
        "width": 384,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        8016,
        1136
      ],
      "typeVersion": 1,
      "id": "615ba101-954c-46ba-98e7-3910bdb26d57",
      "name": "Sticky Note8"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "0ebde2cb-e0cd-460b-abc5-88b0d466e5f0",
              "name": "template_message",
              "value": "=Olá, {{ $('Normaliza Infos').item.json.lead.primeiro_nome || 'tudo bem' }}! Aqui é a Bella da Indexmed. {{ String($('Normaliza Infos').item.json.lead.cargo || '').toLowerCase() === 'outro' ? 'Vi que você trabalha na ' + ($('Normaliza Infos').item.json.lead.empresa || 'sua empresa') : 'Vi que você é ' + ($('Normaliza Infos').item.json.lead.cargo || 'profissional da área') + ' na ' + ($('Normaliza Infos').item.json.lead.empresa || 'sua empresa') }} e gerencia {{ String($('Normaliza Infos').item.json.lead.vidas_gerenciadas || 'esse volume de vidas').toLowerCase() }}.\n\nCom base nesse volume, recomendo o nosso Plano {{ $('Normaliza Infos').item.json.lead.plano || 'ideal para o seu cenário' }}, que é a solução ideal para automatizar sua gestão de SST com o melhor custo-benefício.\n\nPara você ver como nossa plataforma funciona na prática e tirar todas as suas dúvidas, nossas próximas sessões técnicas, apresentadas online com nossos especialistas, são:\n- {{ $('Create Meetings Date').item.json.next_wednesdays_br?.[0] || 'data a confirmar' }}\n- {{ $('Create Meetings Date').item.json.next_wednesdays_br?.[1] || 'data a confirmar' }}\n\nQual dessas opções funciona melhor para você?",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        8256,
        1328
      ],
      "id": "0f010fed-28bc-49af-9841-941f24f8cda1",
      "name": "Prepara Messagem Template"
    },
    {
      "parameters": {
        "method": "PUT",
        "url": "=https://{{ $('w-cfg').item.json.url }}/api/v1/accounts/{{ $('w-cfg').item.json.account_id }}/contacts/{{ $json.contato.id }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"name\": \"{{ $('Normaliza Infos').item.json.lead.nome_completo }}\",\n  \"email\": \"{{ $('Normaliza Infos').item.json.lead.email }}\",\n  \"phone_number\": \"+55{{ $('Normaliza Infos').item.json.lead.telefone }}\",\n  \"custom_attributes\": {\n    \"nome_empresa\": \"{{ $('Normaliza Infos').item.json.lead.empresa }}\",\n    \"vidas\": \"{{ $('Normaliza Infos').item.json.lead.vidas_gerenciadas }}\",\n    \"cargo\": \"{{ $('Normaliza Infos').item.json.lead.cargo }}\",\n    \"cnpj\": \"null\",\n    \"empresa_area_atuacao\": \"n/a\",\n    \"como_conheceu\": \"{{ $('Webhook').item.json.body.leads[0].first_conversion.conversion_origin.source }}\",\n    \"form_source\": \"Landing page da área informações de planos\",\n    \"form_name\": \"formulario_site\"\n  }\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        9936,
        1408
      ],
      "id": "d56f2f59-d420-4c41-af65-9c212d41dc4f",
      "name": "Update Contact",
      "credentials": {
        "httpHeaderAuth": {
          "id": "DukjhoZy36MLkfgu",
          "name": "Chatfluxx Header Auth account - Indexmed Automation"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const data = $input.first().json;\nconst item = data.body?.leads?.[0] || {};\n\nconst firstContent = item.first_conversion?.content || {};\nconst lastContent = item.last_conversion?.content || {};\n\nconst firstPayload = firstContent.__cdp__original_event?.payload || {};\nconst lastPayload = lastContent.__cdp__original_event?.payload || {};\nconst customFields = item.custom_fields || {};\n\nconst nomeCompleto =\n  lastPayload.name ||\n  firstPayload.name ||\n  lastContent.Nome ||\n  firstContent.Nome ||\n  item.name ||\n  '';\n\n//const primeiroNome = nomeCompleto.trim().split(/\\s+/)[0] || '';\nconst primeiroNome = (nomeCompleto.trim().split(/\\s+/)[0] || '').toLowerCase().replace(/^\\w/, c => c.toUpperCase());\n\nconst empresa =\n  lastContent.Empresa ||\n  firstContent.Empresa ||\n  lastPayload.company_name ||\n  firstPayload.company_name ||\n  item.company ||\n  '';\n\nconst vidasGerenciadasRaw =\n  lastPayload.cf_numero_de_vidas_gerenciadas ||\n  firstPayload.cf_numero_de_vidas_gerenciadas ||\n  lastPayload.cf_cf_numero_vidas ||\n  firstPayload.cf_cf_numero_vidas ||\n  lastContent['Número de Vidas Gerenciadas'] ||\n  firstContent['Número de Vidas Gerenciadas'] ||\n  lastContent.numero_vidas ||\n  firstContent.numero_vidas ||\n  customFields['Número de Vidas Gerenciadas'] ||\n  customFields.numero_vidas ||\n  '';\n\nconst vidasGerenciadas = String(vidasGerenciadasRaw).trim();\nconst vidasGerenciadasNorm = vidasGerenciadas.toLowerCase();\n\nconst cargo =\n  lastPayload.cf_cargo_selecao ||\n  firstPayload.cf_cargo_selecao ||\n  lastContent['Cargo - Seleção'] ||\n  firstContent['Cargo - Seleção'] ||\n  lastContent.Cargo ||\n  firstContent.Cargo ||\n  lastPayload.job_title ||\n  firstPayload.job_title ||\n  item.job_title ||\n  '';\n\nconst classificacaoNegocio =\n  lastPayload.cf_classificacao_do_negocio ||\n  firstPayload.cf_classificacao_do_negocio ||\n  lastContent['Classificação do Negócio'] ||\n  firstContent['Classificação do Negócio'] ||\n  customFields['Classificação do Negócio'] ||\n  '';\n\nconst telefoneRaw =\n  lastPayload.cf_telefone_celular ||\n  firstPayload.cf_telefone_celular ||\n  lastContent['Telefone/Celular'] ||\n  firstContent['Telefone/Celular'] ||\n  lastContent.Celular ||\n  firstContent.Celular ||\n  lastPayload.mobile_phone ||\n  firstPayload.mobile_phone ||\n  item.mobile_phone ||\n  item.phone ||\n  '';\n\nconst telefone = String(telefoneRaw)\n  .replace(/\\D/g, '')\n  .replace(/^55(\\d{10,11})$/, '$1');\n\nconst email =\n  item.email ||\n  lastPayload.email ||\n  firstPayload.email ||\n  lastContent.email_lead ||\n  firstContent.email_lead ||\n  '';\n\nconst plano =\n  ['até 100 vidas', 'de 11 a 100 vidas', 'de 101 a 500 vidas'].includes(vidasGerenciadasNorm)\n    ? 'Premium'\n    : vidasGerenciadasNorm === 'de 501 a 1000 vidas'\n    ? 'Pro'\n    : vidasGerenciadasNorm === 'acima de 1000 vidas'\n    ? 'Enterprise'\n    : 'Plano não identificado';\n\nreturn [\n  {\n    json: {\n      lead_id: item.id || '',\n      uuid: item.uuid || '',\n      classificacao_negocio: classificacaoNegocio,\n      lead_stage: item.lead_stage || '',\n      source_primeira_conversao: item.first_conversion?.source || '',\n      source_ultima_conversao: item.last_conversion?.source || '',\n      conversion_identifier:\n        lastPayload.conversion_identifier ||\n        firstPayload.conversion_identifier ||\n        lastContent.conversion_identifier ||\n        firstContent.conversion_identifier ||\n        '',\n      conversion_url:\n        lastPayload.conversion_url ||\n        firstPayload.conversion_url ||\n        lastContent.conversion_url ||\n        firstContent.conversion_url ||\n        '',\n\n      lead: {\n        primeiro_nome: primeiroNome,\n        nome_completo: nomeCompleto,\n        empresa: empresa,\n        cargo: cargo,\n        vidas_gerenciadas: vidasGerenciadas,\n        email: email,\n        telefone: telefone,\n        plano: plano\n      }\n    }\n  }\n];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        7616,
        1328
      ],
      "id": "24c018ef-f716-4e89-a0ac-9cc82483eb95",
      "name": "Normaliza Infos"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "email",
              "name": "email",
              "value": "={{ String($('Normaliza Infos').first().json.lead.email || '').trim().toLowerCase() }}",
              "type": "string"
            },
            {
              "id": "phone_digits",
              "name": "phone_digits",
              "value": "={{ String($('Normaliza Infos').first().json.lead.telefone || '').replace(/\\D/g, '') }}",
              "type": "string"
            },
            {
              "id": "phone",
              "name": "phone",
              "value": "={{ (() => { const d = String($('Normaliza Infos').first().json.lead.telefone || '').replace(/\\D/g, ''); const withDDI = d.startsWith('55') ? d : '55' + d; return '+' + withDDI; })() }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "54828825-124b-44b0-86c3-300458845a9a",
      "name": "Set Dados Busca",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        8512,
        1328
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://{{ $('w-cfg').item.json.url }}/api/v1/accounts/{{ $('w-cfg').item.json.account_id }}/contacts/filter",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"payload\": [\n    {\n      \"attribute_key\": \"email\",\n      \"filter_operator\": \"equal_to\",\n      \"values\": [\"{{ $('Set Dados Busca').item.json.email }}\"],\n      \"query_operator\": null\n    }\n  ]\n}",
        "options": {
          "response": {
            "response": {
              "fullResponse": false,
              "responseFormat": "json"
            }
          },
          "timeout": 15000
        }
      },
      "id": "acde7233-c5ff-4d12-8f10-c07d99eb02a2",
      "name": "HTTP Search by Email",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        8752,
        1328
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "DukjhoZy36MLkfgu",
          "name": "Chatfluxx Header Auth account - Indexmed Automation"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "email-found",
              "leftValue": "={{ Array.isArray($json.payload) ? $json.payload.length : 0 }}",
              "rightValue": 0,
              "operator": {
                "type": "number",
                "operation": "gt"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "cd02ac15-94f9-44e3-aadc-f1d09c6dc533",
      "name": "IF Encontrou Email?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        8992,
        1328
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://{{ $('w-cfg').item.json.url }}/api/v1/accounts/{{ $('w-cfg').item.json.account_id }}/contacts/filter",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"payload\": [\n    {\n      \"attribute_key\": \"phone_number\",\n      \"filter_operator\": \"equal_to\",\n      \"values\": [\"{{ $('Set Dados Busca').item.json.phone }}\"],\n      \"query_operator\": null\n    }\n  ]\n}",
        "options": {
          "response": {
            "response": {
              "fullResponse": false,
              "responseFormat": "json"
            }
          },
          "timeout": 15000
        }
      },
      "id": "f8f11bc3-7652-49e8-becc-8a106efc2c0b",
      "name": "HTTP Search by Phone",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        9232,
        1456
      ],
      "credentials": {
        "httpHeaderAuth": {
          "id": "DukjhoZy36MLkfgu",
          "name": "Chatfluxx Header Auth account - Indexmed Automation"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Usa $items() que é a forma segura do n8n para acessar nós.\n// Retorna [] se o nó não rodou, em vez de undefined.\n\nlet emailPayload = [];\nlet phonePayload = [];\n\ntry {\n  const items = $items('HTTP Search by Email');\n  if (items && items.length > 0 && items[0].json && Array.isArray(items[0].json.payload)) {\n    emailPayload = items[0].json.payload;\n  }\n} catch (e) {\n  emailPayload = [];\n}\n\ntry {\n  const items = $items('HTTP Search by Phone');\n  if (items && items.length > 0 && items[0].json && Array.isArray(items[0].json.payload)) {\n    phonePayload = items[0].json.payload;\n  }\n} catch (e) {\n  phonePayload = [];\n}\n\n// Como usamos /contacts/filter com equal_to, qualquer item retornado já é match exato.\n// Prioridade: email > phone (email é identificador mais forte)\nlet contato = null;\nlet encontrado_por = null;\n\nif (emailPayload.length > 0) {\n  contato = emailPayload[0];\n  encontrado_por = 'email';\n} else if (phonePayload.length > 0) {\n  contato = phonePayload[0];\n  encontrado_por = 'phone';\n}\n\n// Lê dados de busca de forma defensiva\nlet busca_email = '';\nlet busca_phone = '';\ntry {\n  const setItems = $items('Set Dados Busca');\n  if (setItems && setItems.length > 0 && setItems[0].json) {\n    busca_email = setItems[0].json.email || '';\n    busca_phone = setItems[0].json.phone || '';\n  }\n} catch (e) {}\n\nreturn [{\n  json: {\n    existe: !!contato,\n    deve_criar: !contato,\n    contato_encontrado_por: encontrado_por,\n    contato_id: contato ? contato.id : null,\n    contato: contato || null,\n    busca: {\n      email: busca_email,\n      phone: busca_phone\n    },\n    matches: {\n      email_count: emailPayload.length,\n      phone_count: phonePayload.length\n    }\n  }\n}];"
      },
      "id": "7f33101c-2683-417a-9972-ab20012100c9",
      "name": "Code Resultado Final",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        9456,
        1312
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "a5664635-c527-407f-88f4-77f1251d129d",
              "leftValue": "={{ $json.deve_criar }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        9664,
        1312
      ],
      "id": "72384ded-8cd9-43ba-aa78-e0abdc352539",
      "name": "Deve criar contato?"
    },
    {
      "parameters": {
        "jsCode": "function isValidEmail(email) {\n  if (!email || typeof email !== 'string') return false;\n\n  // bloqueia caracteres e padrões estranhos comuns em spam/teste\n  if (/[&=<>]/.test(email)) return false;\n\n  // validação simples de email\n  return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email);\n}\n\nfunction isPlaceholderPhone(phone) {\n  if (!phone || typeof phone !== 'string') return false;\n\n  const digits = phone.replace(/\\D/g, '');\n  return (\n    digits.startsWith('555') ||\n    digits === '0000000000' ||\n    digits === '00000000000' ||\n    /^(\\d)\\1+$/.test(digits)\n  );\n}\n\nfunction looksRandomName(name) {\n  if (!name || typeof name !== 'string') return true;\n\n  const clean = name.trim();\n\n  // sem espaço e com cara de string aleatória\n  if (!clean.includes(' ') && /^[A-Za-z]{6,12}$/.test(clean)) {\n    const vowels = (clean.match(/[aeiouAEIOU]/g) || []).length;\n    if (vowels <= 2) return true;\n  }\n\n  return false;\n}\n\nfunction countRepeatedValues(values) {\n  const normalized = values\n    .filter(v => v !== null && v !== undefined && v !== '')\n    .map(v => String(v).trim().toLowerCase());\n\n  const freq = {};\n  for (const v of normalized) {\n    freq[v] = (freq[v] || 0) + 1;\n  }\n\n  let maxRepeat = 0;\n  for (const key in freq) {\n    if (freq[key] > maxRepeat) maxRepeat = freq[key];\n  }\n\n  return maxRepeat;\n}\n\nreturn items.map(item => {\n  const lead = item.json.body?.leads?.[0] || item.json.leads?.[0] || item.json;\n\n  const email = lead.email || '';\n  const name = lead.name || '';\n  const company = lead.company || '';\n  const mobilePhone = lead.mobile_phone || '';\n  const personalPhone = lead.personal_phone || '';\n  const areaAtuacao = lead.custom_fields?.['Área de atuação'] || '';\n  const origem = lead.custom_fields?.['Origem'] || '';\n  const conversionOrigin = lead.first_conversion?.conversion_origin || {};\n\n  let score = 0;\n  const motivos = [];\n\n  if (!isValidEmail(email)) {\n    score += 3;\n    motivos.push('email_invalido_ou_suspeito');\n  }\n\n  if (looksRandomName(name)) {\n    score += 2;\n    motivos.push('nome_com_aparencia_aleatoria');\n  }\n\n  if (isPlaceholderPhone(mobilePhone) || isPlaceholderPhone(personalPhone) || isPlaceholderPhone(company)) {\n    score += 2;\n    motivos.push('telefone_placeholder_ou_fake');\n  }\n\n  const repeatedCount = countRepeatedValues([\n    company,\n    mobilePhone,\n    personalPhone,\n    areaAtuacao,\n  ]);\n\n  if (repeatedCount >= 2) {\n    score += 2;\n    motivos.push('mesmo_valor_repetido_em_campos_diferentes');\n  }\n\n  if (\n    String(conversionOrigin.source || '').toLowerCase() === 'unknown' &&\n    String(conversionOrigin.medium || '').toLowerCase() === 'unknown' &&\n    String(conversionOrigin.channel || '').toLowerCase() === 'unknown'\n  ) {\n    score += 1;\n    motivos.push('origem_de_conversao_desconhecida');\n  }\n\n  if (String(origem).trim().toLowerCase() === 'facebook' && String(conversionOrigin.source || '').toLowerCase() === 'unknown') {\n    score += 1;\n    motivos.push('origem_inconsistente');\n  }\n\n  let classificacao = 'lead_valido';\n\n  if (score >= 6) {\n    classificacao = 'spam';\n  } else if (score >= 3) {\n    classificacao = 'suspeito';\n  }\n\n  item.json.spam_analysis = {\n    classificacao,\n    score,\n    motivos,\n    email_analisado: email,\n    nome_analisado: name,\n  };\n\n  return item;\n});"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        7392,
        1328
      ],
      "id": "8200948c-03a8-483f-a1e0-f8a25444a92f",
      "name": "Check SPAM"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "json-memory-session",
              "name": "session_id",
              "value": "={{ $('Create New Conversation').item.json.meta?.sender?.id || $('Create New Conversation').item.json.contact_inbox?.contact_id || 0 }}",
              "type": "string"
            },
            {
              "id": "json-memory-msg",
              "name": "message_json",
              "value": "={{ JSON.stringify({ type: 'ai', content: $('Prepara Messagem Template').item.json.template_message }) }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        10784,
        1312
      ],
      "id": "f0a91719-244a-4d7a-be22-ab79e0ed31e5",
      "name": "Prepara JSON Memoria"
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO indexmed_n8n_chat_histories (session_id, message)\nVALUES ($1::bigint, $2::jsonb)",
        "options": {
          "queryReplacement": "={{ $json.session_id }},{{ $json.message_json }}"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        11008,
        1328
      ],
      "id": "f5d4cb30-75f3-4040-b89b-7a5c0e2195f0",
      "name": "Insert Abertura Postgres Memory",
      "credentials": {
        "postgres": {
          "id": "gAyiqQlRccQJQD5p",
          "name": "Postgres account"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('Start').item.json.url_base }}/api/v1/accounts/{{ $('Start').item.json.account_id }}/conversations/{{ $('Start').item.json.conversation_id }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"content\": \"🤖 *Resumo do atendimento da Bella*\\n\\n⚠️ *Motivo do handoff:* {{ $('Start').item.json.motivo }}\\n\\n📝 *Resumo:*\\n{{ $('Start').item.json.resumo }}\",\n  \"message_type\": \"outgoing\",\n  \"private\": true\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        10224,
        1152
      ],
      "id": "0072770d-4039-454b-b378-bf81c651b256",
      "name": "Envia Nota Privada",
      "retryOnFail": true,
      "credentials": {
        "httpHeaderAuth": {
          "id": "J4PQSm40Hwl2hYlW",
          "name": "Chatfluxx Auth account (Leandro)"
        }
      },
      "disabled": true
    }
  ],
  "pinData": {
    "Webhook": [
      {
        "json": {
          "headers": {
            "host": "webhooks-indexmed.neofluxx.com",
            "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36",
            "content-length": "235",
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-encoding": "gzip, deflate, br, zstd",
            "accept-language": "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7",
            "cache-control": "max-age=0",
            "content-type": "application/x-www-form-urlencoded",
            "origin": "null",
            "priority": "u=0, i",
            "sec-ch-ua": "\"Google Chrome\";v=\"147\", \"Not.A/Brand\";v=\"8\", \"Chromium\";v=\"147\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"macOS\"",
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "cross-site",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1",
            "x-forwarded-for": "191.193.136.193",
            "x-forwarded-host": "webhooks-indexmed.neofluxx.com",
            "x-forwarded-port": "443",
            "x-forwarded-proto": "https",
            "x-forwarded-server": "traefik_traefik.1",
            "x-real-ip": "191.193.136.193"
          },
          "params": {},
          "query": {},
          "body": {
            "empresa": "ACME Ltda",
            "area_atuacao": "Saúde / Clínicas / Laboratórios",
            "vidas": "De 501 a 1000 vidas",
            "nome": "João Júnior",
            "cargo": "Diretor",
            "email": "juniorbra1001@gmail.com",
            "telefone": "(11) 98208-4044",
            "origem": "Pesquisa no Google"
          },
          "webhookUrl": "https://webhooks-indexmed.neofluxx.com/webhook/indexmed-lead",
          "executionMode": "production"
        },
        "pairedItem": {
          "item": 0
        }
      }
    ]
  },
  "connections": {
    "w-cfg": {
      "main": [
        [
          {
            "node": "Prepara Messagem Template",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Contact": {
      "main": [
        [
          {
            "node": "Create New Conversation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Webhook": {
      "main": [
        [
          {
            "node": "Check SPAM",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create New Conversation": {
      "main": [
        [
          {
            "node": "Prepares data for the agent's memory",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Meetings Date": {
      "main": [
        [
          {
            "node": "w-cfg",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepares data for the agent's memory": {
      "main": [
        [
          {
            "node": "Prepara JSON Memoria",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepara Messagem Template": {
      "main": [
        [
          {
            "node": "Set Dados Busca",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update Contact": {
      "main": [
        [
          {
            "node": "Create New Conversation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normaliza Infos": {
      "main": [
        [
          {
            "node": "Create Meetings Date",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set Dados Busca": {
      "main": [
        [
          {
            "node": "HTTP Search by Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HTTP Search by Email": {
      "main": [
        [
          {
            "node": "IF Encontrou Email?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IF Encontrou Email?": {
      "main": [
        [
          {
            "node": "Code Resultado Final",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "HTTP Search by Phone",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HTTP Search by Phone": {
      "main": [
        [
          {
            "node": "Code Resultado Final",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code Resultado Final": {
      "main": [
        [
          {
            "node": "Deve criar contato?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Deve criar contato?": {
      "main": [
        [
          {
            "node": "Create Contact",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Update Contact",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check SPAM": {
      "main": [
        [
          {
            "node": "Normaliza Infos",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepara JSON Memoria": {
      "main": [
        [
          {
            "node": "Insert Abertura Postgres Memory",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Insert Abertura Postgres Memory": {
      "main": [
        [
          {
            "node": "Respond to Webhook",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": true,
  "settings": {
    "executionOrder": "v1",
    "binaryMode": "separate",
    "availableInMCP": false,
    "timeSavedMode": "fixed",
    "errorWorkflow": "K2LaNGa5mWokz7en",
    "callerPolicy": "workflowsFromSameOwner"
  },
  "versionId": "c15b6b3b-f634-4bf3-a100-303b665cec89",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "4c77d89ec915bc078747315cdb5d4cdb431200dbbb20a5e7e7e4671e8131788e"
  },
  "id": "7c1DVZ2WdIGIWqk9",
  "tags": [
    {
      "updatedAt": "2026-03-10T14:18:09.880Z",
      "createdAt": "2026-03-10T14:18:09.880Z",
      "id": "sTn7EF97z7FNk8d2",
      "name": "SDR AI Agent"
    },
    {
      "updatedAt": "2026-03-11T20:30:45.034Z",
      "createdAt": "2026-03-05T18:01:19.756Z",
      "id": "wA0iDBsSzoUzA6Wh",
      "name": "Chatfluxx"
    }
  ]
}