{
  "name": "Followup Abertura Bella — C1",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "hours"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        8480,
        4112
      ],
      "id": "c3570460-5556-43e1-9ca1-ca2e04e02f96",
      "name": "Schedule — a cada 1h"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "cfg-url",
              "name": "baseUrl",
              "value": "https://app.neofluxx.com",
              "type": "string"
            },
            {
              "id": "cfg-account",
              "name": "account_id",
              "value": "4",
              "type": "string"
            },
            {
              "id": "cfg-inbox",
              "name": "inbox_id",
              "value": "85",
              "type": "string"
            },
            {
              "id": "cfg-client",
              "name": "client_id",
              "value": "indexmed",
              "type": "string"
            },
            {
              "id": "cfg-h1",
              "name": "horas_t1",
              "value": 24,
              "type": "number"
            },
            {
              "id": "cfg-h2",
              "name": "horas_t2",
              "value": 48,
              "type": "number"
            },
            {
              "id": "cfg-henc",
              "name": "horas_enc",
              "value": 120,
              "type": "number"
            },
            {
              "id": "cfg-tpl1",
              "name": "template_1",
              "value": "reengajamento_abertura_1",
              "type": "string"
            },
            {
              "id": "cfg-tpl2",
              "name": "template_2",
              "value": "reengajamento_abertura_2",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        8704,
        4112
      ],
      "id": "9ea85715-0ff3-4e60-a975-8ed25b22a7b8",
      "name": "w-cfg"
    },
    {
      "parameters": {
        "url": "={{ $('w-cfg').item.json.baseUrl }}/api/v1/accounts/{{ $('w-cfg').item.json.account_id }}/conversations",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "inbox_id",
              "value": "={{ $('w-cfg').item.json.inbox_id }}"
            },
            {
              "name": "status",
              "value": "open"
            },
            {
              "name": "page",
              "value": "1"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        8928,
        4112
      ],
      "id": "8df99c81-3eab-42ca-9d5a-5aaa31a06ab9",
      "name": "GET Conversas Chatfluxx",
      "credentials": {
        "httpHeaderAuth": {
          "id": "DukjhoZy36MLkfgu",
          "name": "Chatfluxx Header Auth account - Indexmed Automation"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Filtra conversas candidatas ao C1:\n// - Sem mensagem incoming (lead nunca respondeu)\n// - Sem etiquetas de encerramento\n// - Criada há mais de 1h\n// Retorna array vazio se nenhuma candidata — n8n interrompe naturalmente\n\nconst conversas = $input.first().json.data?.payload || [];\nconst agora = Date.now();\nconst UMA_HORA = 60 * 60 * 1000;\n\nconst excluir = ['reunião-agendada', 'reuniao-agendada', 'agent-off', 'sem_resposta', 'desqualificado'];\n\nconst candidatas = conversas.filter(conv => {\n  const labels = (conv.labels || []).map(l => String(l).toLowerCase());\n  if (labels.some(l => excluir.includes(l))) return false;\n\n  const msgs = conv.messages || [];\n  const temIncoming = msgs.some(m => m.message_type === 'incoming' || m.message_type === 0);\n  if (temIncoming) return false;\n\n  // created_at do Chatwoot vem em epoch seconds\n  const criada = new Date(conv.created_at * 1000).getTime();\n  if (agora - criada < UMA_HORA) return false;\n\n  return true;\n});\n\nreturn candidatas.map(conv => ({\n  json: {\n    conversation_id: conv.id,\n    session_id: String(conv.meta?.sender?.id || ''),\n    contact_id: conv.meta?.sender?.id,\n    nome_lead: conv.meta?.sender?.name || '',\n    created_at: conv.created_at,\n    horas_desde_criacao: Math.floor((agora - new Date(conv.created_at * 1000).getTime()) / 3600000),\n    labels: conv.labels || []\n  }\n}));"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        9136,
        4112
      ],
      "id": "b3d830fa-2cf0-49e7-ac3b-6b827b83adf9",
      "name": "Filtra Candidatas C1"
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT $1 AS session_id_input, session_id, event_type, occurred_at\nFROM analytics.sdr_events\nWHERE client_id = 'indexmed'\n  AND session_id = $1\n  AND event_type IN ('followup_abertura_1', 'followup_abertura_2', 'sem_resposta')",
        "options": {
          "queryReplacement": "$json.session_id"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        9376,
        4112
      ],
      "id": "ee42a315-b57e-476a-b116-1db9522b1c91",
      "name": "Verifica Eventos Supabase",
      "alwaysOutputData": true,
      "credentials": {
        "postgres": {
          "id": "gAyiqQlRccQJQD5p",
          "name": "Postgres account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Processa cada candidata individualmente.\n// Busca candidatas originais + eventos do Supabase, correlaciona por session_id.\n\nconst cfg = $('w-cfg').item.json;\nconst h1 = Number(cfg.horas_t1);    // 24h\nconst h2 = Number(cfg.horas_t2);    // 48h\nconst henc = Number(cfg.horas_enc); // 120h\n\n// Calcula próximas quartas usando $now (DateTime/Luxon nativo do n8n)\nconst now = $now.setZone('America/Sao_Paulo');\nconst WED = 3;\nlet daysToNextWed = (WED - now.weekday + 7) % 7;\nif (daysToNextWed === 0) daysToNextWed = 7;\nconst nextWed = now.plus({ days: daysToNextWed }).set({ hour: 10, minute: 0, second: 0, millisecond: 0 });\nconst nextNextWed = nextWed.plus({ days: 7 });\nconst dataSessao1 = nextWed.toFormat('dd/MM/yyyy HH:mm');\nconst dataSessao2 = nextNextWed.toFormat('dd/MM/yyyy HH:mm');\n\n// Pega as candidatas originais de Filtra Candidatas C1\nconst candidatas = $('Filtra Candidatas C1').all().map(i => i.json);\n\n// Agrupa eventos por session_id a partir do input (Verifica Eventos Supabase)\nconst eventosPorSessao = {};\nfor (const item of $input.all()) {\n  const sid = String(item.json.session_id || item.json.session_id_input || '');\n  const evt = item.json.event_type;\n  if (!sid || !evt) continue;\n  if (!eventosPorSessao[sid]) eventosPorSessao[sid] = [];\n  eventosPorSessao[sid].push(evt);\n}\n\n// Decide ação para cada candidata\nconst resultado = [];\nfor (const conv of candidatas) {\n  const eventos = eventosPorSessao[conv.session_id] || [];\n  const tem_t1 = eventos.includes('followup_abertura_1');\n  const tem_t2 = eventos.includes('followup_abertura_2');\n  const encerrada = eventos.includes('sem_resposta');\n  const horas = conv.horas_desde_criacao;\n\n  let acao = 'skip';\n  let template = null;\n\n  if (encerrada) {\n    // Já foi encerrada anteriormente — skip\n    acao = 'skip';\n    \n  } else if (!tem_t1 && !tem_t2 && horas >= henc) {\n    // Caso extremo: passou de 120h sem NENHUM evento → encerrar\n    acao = 'encerrar';\n    \n  } else if (!tem_t1 && horas >= h1) {\n    // Primeira tentativa: 24h sem resposta, sem evento T1\n    acao = 'template_1';\n    template = cfg.template_1;\n    \n  } else if (tem_t1 && !tem_t2 && horas >= h2) {\n    // Segunda tentativa: 48h sem resposta, já enviou T1, ainda não enviou T2\n    acao = 'template_2';\n    template = cfg.template_2;\n    \n  } else if (tem_t2 && horas >= henc) {\n    // Última tentativa esgotada: 120h sem resposta após T2 → encerrar\n    acao = 'encerrar';\n  }\n\n  if (acao === 'skip') continue;\n\n  resultado.push({\n    json: {\n      ...conv,\n      acao,\n      template,\n      data_sessao_1: dataSessao1,\n      data_sessao_2: dataSessao2,\n      primeiro_nome: (conv.nome_lead || '').split(' ')[0]\n    }\n  });\n}\n\nreturn resultado;"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        9600,
        4112
      ],
      "id": "0e7e53f1-2748-48c8-9af1-03f57f40fca5",
      "name": "Decide Ação"
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "r1",
                    "leftValue": "={{ $json.acao }}",
                    "rightValue": "template_1",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Envia Template 1"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "r2",
                    "leftValue": "={{ $json.acao }}",
                    "rightValue": "template_2",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Envia Template 2"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "r3",
                    "leftValue": "={{ $json.acao }}",
                    "rightValue": "encerrar",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Encerra Conversa"
            }
          ]
        },
        "options": {
          "fallbackOutput": "none"
        }
      },
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        10064,
        4096
      ],
      "id": "b8eba100-9c8c-4b8c-b551-59ce419acb6d",
      "name": "Switch Ação"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('w-cfg').item.json.baseUrl }}/api/v1/accounts/{{ $('w-cfg').item.json.account_id }}/conversations/{{ $json.conversation_id }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"content\": \"{{ $json.template }}\",\n  \"message_type\": \"outgoing\",\n  \"template_params\": {\n    \"name\": \"{{ $json.template }}\",\n    \"category\": \"MARKETING\",\n    \"language\": \"pt_BR\",\n    \"processed_params\": {\n      \"1\": \"{{ $json.primeiro_nome }}\",\n      \"2\": \"{{ $json.data_sessao_1 }}\",\n      \"3\": \"{{ $json.data_sessao_2 }}\"\n    }\n  }\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        10416,
        3792
      ],
      "id": "ea762e65-63d5-429c-933b-87f21a66c705",
      "name": "Envia Template 1",
      "credentials": {
        "httpHeaderAuth": {
          "id": "DukjhoZy36MLkfgu",
          "name": "Chatfluxx Header Auth account - Indexmed Automation"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('w-cfg').item.json.baseUrl }}/api/v1/accounts/{{ $('w-cfg').item.json.account_id }}/conversations/{{ $json.conversation_id }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"content\": \"{{ $json.template }}\",\n  \"message_type\": \"outgoing\",\n  \"template_params\": {\n    \"name\": \"{{ $json.template }}\",\n    \"category\": \"MARKETING\",\n    \"language\": \"pt_BR\",\n    \"processed_params\": {\n      \"1\": \"{{ $json.primeiro_nome }}\"\n    }\n  }\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        10384,
        4032
      ],
      "id": "cc8d8ab9-9270-434e-8df2-1a08c7190f6c",
      "name": "Envia Template 2",
      "credentials": {
        "httpHeaderAuth": {
          "id": "DukjhoZy36MLkfgu",
          "name": "Chatfluxx Header Auth account - Indexmed Automation"
        }
      }
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO analytics.sdr_events (client_id, session_id, event_type, occurred_at)\nVALUES ('indexmed', $1, 'followup_abertura_2', NOW())",
        "options": {
          "queryReplacement": "$json.session_id"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        10816,
        4032
      ],
      "id": "f3992d5c-614b-4f5e-9f18-57439a7acd9c",
      "name": "Grava Evento T2",
      "credentials": {
        "postgres": {
          "id": "gAyiqQlRccQJQD5p",
          "name": "Postgres account"
        }
      }
    },
    {
      "parameters": {
        "method": "PATCH",
        "url": "={{ $('w-cfg').item.json.baseUrl }}/api/v1/accounts/{{ $('w-cfg').item.json.account_id }}/conversations/{{ $json.conversation_id }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={ \"status\": \"resolved\" }",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        10288,
        4272
      ],
      "id": "9b364bff-446d-4e06-8b3e-e7ed886345c1",
      "name": "Resolve Conversa",
      "credentials": {
        "httpHeaderAuth": {
          "id": "DukjhoZy36MLkfgu",
          "name": "Chatfluxx Header Auth account - Indexmed Automation"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('w-cfg').item.json.baseUrl }}/api/v1/accounts/{{ $('w-cfg').item.json.account_id }}/conversations/{{ $json.conversation_id }}/labels",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={ \"labels\": [\"sem_resposta\"] }",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        10512,
        4272
      ],
      "id": "2a8ec3ac-5e85-48d0-be1b-bbc0a8e1607e",
      "name": "Aplica Etiqueta sem_resposta",
      "credentials": {
        "httpHeaderAuth": {
          "id": "DukjhoZy36MLkfgu",
          "name": "Chatfluxx Header Auth account - Indexmed Automation"
        }
      }
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO analytics.sdr_events (client_id, session_id, event_type, occurred_at)\nVALUES ('indexmed', $1, 'sem_resposta', NOW())",
        "options": {
          "queryReplacement": "$json.session_id"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        10736,
        4272
      ],
      "id": "a0d95867-3e22-4d97-8033-7eb5826d1b2b",
      "name": "Grava Evento sem_resposta",
      "credentials": {
        "postgres": {
          "id": "gAyiqQlRccQJQD5p",
          "name": "Postgres account"
        }
      }
    },
    {
      "parameters": {
        "content": "INÍCIO & CONFIGURAÇÃO\n\n1. Dispara a cada 1h\n2. Define thresholds (24h, 48h, 120h)\n3. Configura URLs, inbox_id, nomes dos templates",
        "height": 800,
        "width": 448,
        "color": 3
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        8416,
        3712
      ],
      "typeVersion": 1,
      "id": "27be05c8-4f06-4d45-afce-6e559852cb7f",
      "name": "Sticky Note"
    },
    {
      "parameters": {
        "content": "BUSCA & FILTRAGEM DE CANDIDATAS\n\n1. GET /conversations (inbox 85, status open)\n2. Filtra: sem mensagem incoming\n3. Filtra: sem etiquetas de encerramento\n4. Filtra: criada há > 1h\n5. Retorna array de candidatas (ou vazio)",
        "height": 800,
        "width": 432,
        "color": 5
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        8880,
        3712
      ],
      "typeVersion": 1,
      "id": "5b747936-2769-4932-8376-c1b2f91d23a7",
      "name": "Sticky Note1"
    },
    {
      "parameters": {
        "content": "VERIFICAÇÃO & DECISÃO\n\n1. Consulta sdr_events por session_id\n2. Verifica quais eventos já dispararam\n3. Calcula próximas quartas-feiras\n4. Decide: template_1 | template_2 | encerrar | skip\n5. Emite apenas items com ação (pula skip)",
        "height": 800,
        "width": 640
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        9328,
        3712
      ],
      "typeVersion": 1,
      "id": "0ac143d8-780f-414c-938c-0c94a494fc3b",
      "name": "Sticky Note2"
    },
    {
      "parameters": {
        "content": "SWITCH & EXECUÇÃO DAS AÇÕES\n\nBranch 1 (Template 1):\n- Envia reengajamento_abertura_1\n- Grava evento followup_abertura_1\n\nBranch 2 (Template 2):\n- Envia reengajamento_abertura_2\n- Grava evento followup_abertura_2\n\nBranch 3 (Encerrar):\n- PATCH status → resolved\n- POST label → sem_resposta\n- Grava evento sem_resposta",
        "height": 800,
        "width": 1136,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        9984,
        3712
      ],
      "typeVersion": 1,
      "id": "deb41bf8-e865-4380-bf66-d460ee9889e0",
      "name": "Sticky Note3"
    },
    {
      "parameters": {
        "content": "![Fluxo](https://f005.backblazeb2.com/file/neofluxx-media/logos/Neofluxx.png)\n",
        "height": 240,
        "width": 1056,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        7808,
        3456
      ],
      "typeVersion": 1,
      "id": "3bfc177c-dae9-4fc3-bbe7-64772a65ce2f",
      "name": "Sticky Note9"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('w-cfg').item.json.baseUrl }}/api/v1/accounts/{{ $('w-cfg').item.json.account_id }}/conversations/{{ $json.conversation_id }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"content\": \"📤 Template enviado: {{ $json.template }}\\n\\nConteúdo:\\nOi, {{ $json.primeiro_nome }}! Vi que você demonstrou interesse na Indexmed. Temos sessões técnicas nos dias {{ $json.data_sessao_1 }} e {{ $json.data_sessao_2 }}. Qual funciona melhor para você?\",\n  \"message_type\": \"activity\",\n  \"private\": true\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        10608,
        3792
      ],
      "id": "0a2d3a86-5a1a-4e0c-952e-b5755f36735b",
      "name": "Msg Privada T1",
      "credentials": {
        "httpHeaderAuth": {
          "id": "DukjhoZy36MLkfgu",
          "name": "Chatfluxx Header Auth account - Indexmed Automation"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('w-cfg').item.json.baseUrl }}/api/v1/accounts/{{ $('w-cfg').item.json.account_id }}/conversations/{{ $json.conversation_id }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"content\": \"📤 Template enviado: {{ $json.template }}\\n\\nConteúdo:\\n{{ $json.primeiro_nome }}, última chamada! Sua vaga na Sessão Técnica da Indexmed ainda está disponível. Acesse também nosso teste gratuito: indexmed.com.br/cadastrar\",\n  \"message_type\": \"activity\",\n  \"private\": true\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        10608,
        4032
      ],
      "id": "7fa00e0f-ee3c-4790-b139-e809ba9152e9",
      "name": "Msg Privada T2",
      "credentials": {
        "httpHeaderAuth": {
          "id": "DukjhoZy36MLkfgu",
          "name": "Chatfluxx Header Auth account - Indexmed Automation"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Filtra items fora do horário comercial\n// Horário: Segunda a Sexta, 8h às 18h (horário de Brasília)\n\nconst now = $now.setZone('America/Sao_Paulo');\nconst diaSemana = now.weekday; // 1=Monday, 7=Sunday\nconst hora = now.hour;\n\n// Verifica se é dia útil (seg-sex)\nconst isDiaUtil = diaSemana >= 1 && diaSemana <= 5;\n\n// Verifica se está no horário comercial (8h-18h)\nconst isHorarioComercial = hora >= 8 && hora < 18;\n\n// Se não é dia útil OU não é horário comercial, descarta todos os items\nif (!isDiaUtil || !isHorarioComercial) {\n    console.log(`Fora do horário comercial: ${now.toFormat('EEEE, dd/MM/yyyy HH:mm')} - Items descartados`);\n    return [];\n}\n\n// Dentro do horário comercial: passa todos os items adiante\nreturn $input.all();"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        9808,
        4112
      ],
      "id": "9a1322bd-813d-4490-8c47-bcab579f6ac7",
      "name": "Filtro Horário Comercial"
    },
    {
      "parameters": {
        "content": "##  📤  LÓGICA DE ENVIO DE MENSAGENS\n\n**Horário de Operação:**\nSegunda a Sexta, 8h às 18h (Brasília)\n\n**Fluxo de Envio:**\n1. Schedule roda a cada 1h\n2. Busca conversas sem resposta à abertura\n3. Verifica tempo desde criação da conversa\n4. **Filtro Horário:** descarta se fora do expediente\n5. Envia template WhatsApp aprovado pela Meta\n6. Registra mensagem privada de auditoria (só agentes)\n7. Grava evento no Supabase\n\n**Templates WhatsApp:**\n- `reengajamento_abertura_1` (24h sem resposta)\n- `reengajamento_abertura_2` (48h sem resposta)\n\n**Mensagem Privada:**\nEnviada após cada template com conteúdo renderizado.\nTipo: `activity` + `private: true` → **nunca sai pro WhatsApp**\n\n**Fora do horário:**\nTemplates aguardam próximo horário comercial.\nNada se perde — evento só grava após envio bem-sucedido.",
        "height": 800,
        "width": 592,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        7808,
        3712
      ],
      "typeVersion": 1,
      "id": "600c689b-325c-48b5-9c96-74d457f96ccb",
      "name": "Sticky Note4"
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO analytics.sdr_events (client_id, session_id, event_type, occurred_at)\nVALUES ('indexmed', $1, 'followup_abertura_1', NOW())",
        "options": {
          "queryReplacement": "$json.session_id"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        10816,
        3792
      ],
      "id": "0836e173-07f1-4edb-8ac3-f318bb022736",
      "name": "Grava Evento T1",
      "credentials": {
        "postgres": {
          "id": "gAyiqQlRccQJQD5p",
          "name": "Postgres account"
        }
      }
    }
  ],
  "pinData": {
    "Schedule — a cada 1h": [
      {
        "json": {
          "timestamp": "2026-04-22T18:00:45.010-03:00",
          "Readable date": "April 22nd 2026, 6:00:45 pm",
          "Readable time": "6:00:45 pm",
          "Day of week": "Wednesday",
          "Year": "2026",
          "Month": "April",
          "Day of month": "22",
          "Hour": "18",
          "Minute": "00",
          "Second": "45",
          "Timezone": "America/Sao_Paulo (UTC-03:00)"
        },
        "pairedItem": {
          "item": 0
        }
      }
    ]
  },
  "connections": {
    "Schedule — a cada 1h": {
      "main": [
        [
          {
            "node": "w-cfg",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "w-cfg": {
      "main": [
        [
          {
            "node": "GET Conversas Chatfluxx",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GET Conversas Chatfluxx": {
      "main": [
        [
          {
            "node": "Filtra Candidatas C1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filtra Candidatas C1": {
      "main": [
        [
          {
            "node": "Verifica Eventos Supabase",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verifica Eventos Supabase": {
      "main": [
        [
          {
            "node": "Decide Ação",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Decide Ação": {
      "main": [
        [
          {
            "node": "Filtro Horário Comercial",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Switch Ação": {
      "main": [
        [
          {
            "node": "Envia Template 1",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Envia Template 2",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Resolve Conversa",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Envia Template 2": {
      "main": [
        [
          {
            "node": "Msg Privada T2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Resolve Conversa": {
      "main": [
        [
          {
            "node": "Aplica Etiqueta sem_resposta",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Aplica Etiqueta sem_resposta": {
      "main": [
        [
          {
            "node": "Grava Evento sem_resposta",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Msg Privada T1": {
      "main": [
        [
          {
            "node": "Grava Evento T1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Msg Privada T2": {
      "main": [
        [
          {
            "node": "Grava Evento T2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filtro Horário Comercial": {
      "main": [
        [
          {
            "node": "Switch Ação",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Envia Template 1": {
      "main": [
        [
          {
            "node": "Msg Privada T1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": true,
  "settings": {
    "executionOrder": "v1",
    "binaryMode": "separate",
    "availableInMCP": false,
    "timeSavedMode": "fixed",
    "errorWorkflow": "K2LaNGa5mWokz7en",
    "callerPolicy": "workflowsFromSameOwner"
  },
  "versionId": "c2d2f5f6-bbbc-4a3a-86cb-52f665651b48",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "4c77d89ec915bc078747315cdb5d4cdb431200dbbb20a5e7e7e4671e8131788e"
  },
  "id": "VBCPD9u8mMWtsT9n",
  "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"
    }
  ]
}