{
  "name": "Followup Abertura Bella — C1",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "hours"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        10160,
        5376
      ],
      "id": "86c3a98d-ec30-4b0c-bca1-299fb9bff098",
      "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": [
        10384,
        5376
      ],
      "id": "0037f331-06b3-411d-ba7b-872b04089b38",
      "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": [
        10608,
        5376
      ],
      "id": "c486cc66-e6a7-44d1-858b-6af37ec4789f",
      "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": [
        10816,
        5376
      ],
      "id": "cb9cb643-2693-4720-af1a-3202c4944959",
      "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": [
        11056,
        5376
      ],
      "id": "6ae6c2a3-c8c6-4be4-917e-4b98dd7165ac",
      "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": [
        11280,
        5376
      ],
      "id": "c3878688-b53e-4769-a41e-2d8c852f385c",
      "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": [
        11744,
        5360
      ],
      "id": "51299627-1f43-4b14-9bd4-424e227dd92f",
      "name": "Switch Ação"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('w-cfg').first().json.baseUrl }}/api/v1/accounts/{{ $('w-cfg').first().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": [
        12096,
        5056
      ],
      "id": "6c0a0a20-bbed-4c29-8775-edac5234c700",
      "name": "Envia Template 1",
      "credentials": {
        "httpHeaderAuth": {
          "id": "DukjhoZy36MLkfgu",
          "name": "Chatfluxx Header Auth account - Indexmed Automation"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('w-cfg').first().json.baseUrl }}/api/v1/accounts/{{ $('w-cfg').first().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": [
        12064,
        5296
      ],
      "id": "e5149898-5741-4985-b965-f1655f89225a",
      "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": [
        12496,
        5296
      ],
      "id": "982baef3-1611-45aa-b727-d6aca9154aec",
      "name": "Grava Evento T2",
      "credentials": {
        "postgres": {
          "id": "gAyiqQlRccQJQD5p",
          "name": "Postgres account"
        }
      }
    },
    {
      "parameters": {
        "method": "PATCH",
        "url": "={{ $('w-cfg').first().json.baseUrl }}/api/v1/accounts/{{ $('w-cfg').first().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": [
        11968,
        5536
      ],
      "id": "920d564c-888a-48db-9115-9f33aa4544ee",
      "name": "Resolve Conversa",
      "credentials": {
        "httpHeaderAuth": {
          "id": "DukjhoZy36MLkfgu",
          "name": "Chatfluxx Header Auth account - Indexmed Automation"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('w-cfg').first().json.baseUrl }}/api/v1/accounts/{{ $('w-cfg').first().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": [
        12192,
        5536
      ],
      "id": "6c8dffc3-55fd-4ae4-8782-a761c04ad26b",
      "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": [
        12416,
        5536
      ],
      "id": "88e8e76b-7c67-4645-98e3-111658ee6702",
      "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": [
        10096,
        4976
      ],
      "typeVersion": 1,
      "id": "2eeebb29-a6c4-496c-947b-0d2369d9dde7",
      "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": [
        10560,
        4976
      ],
      "typeVersion": 1,
      "id": "555b44d9-4270-462d-94d9-3e6025da32d5",
      "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": [
        11008,
        4976
      ],
      "typeVersion": 1,
      "id": "6665bc3c-427a-4144-ae2c-7a00ebd2ac19",
      "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": [
        11664,
        4976
      ],
      "typeVersion": 1,
      "id": "134cefb2-b1c7-4f42-8a08-f2628c3016e2",
      "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": [
        9488,
        4720
      ],
      "typeVersion": 1,
      "id": "a770cd7c-6439-49f1-9362-9ba79c9ea0c3",
      "name": "Sticky Note9"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('w-cfg').first().json.baseUrl }}/api/v1/accounts/{{ $('w-cfg').first().json.account_id }}/conversations/{{ $json.conversation_id }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"content\": \"📤 Template enviado: {{ $('Switch Ação').first().json.template }}\\n\\nConteúdo:\\nOi, {{ $('Switch Ação').first().json.primeiro_nome }}! Vi que você demonstrou interesse na Indexmed. Temos sessões técnicas nos dias {{ $('Switch Ação').first().json.data_sessao_1 }} e {{ $('Switch Ação').first().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": [
        12288,
        5056
      ],
      "id": "ef36cadc-869e-43af-91e2-824fa75a707c",
      "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": [
        12288,
        5296
      ],
      "id": "203e2c31-2c8c-4fe5-897f-e2f09914ff6e",
      "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": [
        11488,
        5376
      ],
      "id": "0b5494f9-eddd-44f0-94ac-3f52d9dd924e",
      "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": [
        9488,
        4976
      ],
      "typeVersion": 1,
      "id": "04987682-72f4-4709-b610-12b10df84c36",
      "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": [
        12496,
        5056
      ],
      "id": "48200883-eeb6-4f53-88ec-0901d01b6e9f",
      "name": "Grava Evento T1",
      "credentials": {
        "postgres": {
          "id": "gAyiqQlRccQJQD5p",
          "name": "Postgres account"
        }
      }
    }
  ],
  "pinData": {
    "Schedule — a cada 1h": [
      {
        "json": {
          "timestamp": "2026-04-28T18:00:09.003-03:00",
          "Readable date": "April 28th 2026, 6:00:09 pm",
          "Readable time": "6:00:09 pm",
          "Day of week": "Tuesday",
          "Year": "2026",
          "Month": "April",
          "Day of month": "28",
          "Hour": "18",
          "Minute": "00",
          "Second": "09",
          "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": false,
  "settings": {
    "executionOrder": "v1",
    "binaryMode": "separate",
    "availableInMCP": false,
    "timeSavedMode": "fixed",
    "errorWorkflow": "K2LaNGa5mWokz7en",
    "callerPolicy": "workflowsFromSameOwner"
  },
  "versionId": "feb13ca4-2735-4e7a-b564-cfbca9757038",
  "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"
    }
  ]
}