{
  "name": "BIG-AGENT-V4-CONVERSAS",
  "nodes": [
    {
      "parameters": {
        "content": "## WEBHOOK E PARSE",
        "height": 400,
        "width": 600,
        "color": 5
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -200,
        200
      ],
      "id": "note-webhook",
      "name": "Sticky Note - Webhook"
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "big-agent",
        "options": {}
      },
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        -160,
        400
      ],
      "id": "webhook",
      "name": "Webhook Z-API"
    },
    {
      "parameters": {
        "mode": "raw",
        "jsonOutput": "={{ $json.body || $json }}",
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        60,
        400
      ],
      "id": "parse",
      "name": "PARSE"
    },
    {
      "parameters": {
        "content": "## SET VARIAVEIS",
        "height": 400,
        "width": 800,
        "color": 5
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        220,
        200
      ],
      "id": "note-variaveis",
      "name": "Sticky Note - Variaveis"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "is-group",
              "leftValue": "={{ $json.isGroup || false }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        280,
        400
      ],
      "id": "is-group",
      "name": "GRUPO?"
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        500,
        300
      ],
      "id": "ignorar-grupo",
      "name": "IGNORAR"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "user-name",
              "name": "user.name",
              "value": "={{ $('PARSE').item.json.senderName || $('PARSE').item.json.pushName || 'Desconhecido' }}",
              "type": "string"
            },
            {
              "id": "user-number",
              "name": "user.number",
              "value": "={{ $('PARSE').item.json.phone?.replace('@c.us', '').replace('@s.whatsapp.net', '') || '' }}",
              "type": "string"
            },
            {
              "id": "msg-id",
              "name": "message.id",
              "value": "={{ $('PARSE').item.json.messageId || $('PARSE').item.json.id?.id || '' }}",
              "type": "string"
            },
            {
              "id": "msg-origem",
              "name": "message.origem",
              "value": "={{ $('PARSE').item.json.fromMe ? 'outgoing' : 'incoming' }}",
              "type": "string"
            },
            {
              "id": "msg-type",
              "name": "message.type",
              "value": "={{ $('PARSE').item.json.type || 'text' }}",
              "type": "string"
            },
            {
              "id": "msg-content",
              "name": "message.content",
              "value": "={{ $('PARSE').item.json.text?.message || $('PARSE').item.json.body || $('PARSE').item.json.caption || '' }}",
              "type": "string"
            },
            {
              "id": "msg-timestamp",
              "name": "message.timestamp",
              "value": "={{ $now.toISO() }}",
              "type": "string"
            },
            {
              "id": "atendimento-ttl",
              "name": "config.atendimento_ttl",
              "value": "600",
              "type": "number"
            },
            {
              "id": "batch-wait",
              "name": "config.batch_wait",
              "value": "6",
              "type": "number"
            },
            {
              "id": "api-baseurl",
              "name": "api.baseurl",
              "value": "https://api.z-api.io/instances/3DEB4A36EC19A04479A132C54B267657/token/9F776951DB6B2E95F3E07510",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        500,
        480
      ],
      "id": "set-variaveis",
      "name": "SET_VARIAVEIS"
    },
    {
      "parameters": {
        "content": "## FILTRO INCOMING/OUTGOING",
        "height": 400,
        "width": 600,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        780,
        200
      ],
      "id": "note-filtro",
      "name": "Sticky Note - Filtro"
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "id": "incoming",
                    "leftValue": "={{ $json.message.origem }}",
                    "rightValue": "incoming",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "incoming"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "id": "outgoing",
                    "leftValue": "={{ $json.message.origem }}",
                    "rightValue": "outgoing",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "outgoing"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        840,
        400
      ],
      "id": "switch-origem",
      "name": "SWITCH_ORIGEM"
    },
    {
      "parameters": {
        "content": "## CONTROLE DE ATENDIMENTO",
        "height": 400,
        "width": 800,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1140,
        200
      ],
      "id": "note-atendimento",
      "name": "Sticky Note - Atendimento"
    },
    {
      "parameters": {
        "operation": "get",
        "key": "=atendimento:{{ $('SET_VARIAVEIS').item.json.user.number }}"
      },
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        1200,
        400
      ],
      "id": "get-atendimento",
      "name": "GET_ATENDIMENTO",
      "credentials": {
        "redis": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "atendimento-vazio",
              "leftValue": "={{ $json.data }}",
              "rightValue": "",
              "operator": {
                "type": "string",
                "operation": "empty",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1420,
        400
      ],
      "id": "if-atendimento",
      "name": "ATENDIMENTO?"
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        1640,
        520
      ],
      "id": "espera",
      "name": "ESPERA"
    },
    {
      "parameters": {
        "content": "## MESSAGE BATCHING (Redis)",
        "height": 400,
        "width": 1000,
        "color": 5
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1700,
        200
      ],
      "id": "note-batching",
      "name": "Sticky Note - Batching"
    },
    {
      "parameters": {
        "operation": "push",
        "list": "=temp:{{ $('SET_VARIAVEIS').item.json.user.number }}",
        "messageData": "={{ JSON.stringify({ id: $('SET_VARIAVEIS').item.json.message.id, content: $('SET_VARIAVEIS').item.json.message.content, timestamp: $('SET_VARIAVEIS').item.json.message.timestamp }) }}",
        "tail": true
      },
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        1760,
        400
      ],
      "id": "push-msg",
      "name": "PUSH_MSG",
      "credentials": {
        "redis": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "set",
        "key": "=atendimento:{{ $('SET_VARIAVEIS').item.json.user.number }}",
        "value": "true",
        "expire": true,
        "ttl": "={{ $('SET_VARIAVEIS').item.json.config.atendimento_ttl }}"
      },
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        1980,
        400
      ],
      "id": "set-atendimento",
      "name": "SET_ATENDIMENTO",
      "credentials": {
        "redis": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "amount": "={{ $('SET_VARIAVEIS').item.json.config.batch_wait }}",
        "unit": "seconds"
      },
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        2200,
        400
      ],
      "id": "wait-batch",
      "name": "WAIT_BATCH"
    },
    {
      "parameters": {
        "operation": "get",
        "propertyName": "messages",
        "key": "=temp:{{ $('SET_VARIAVEIS').item.json.user.number }}"
      },
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        2420,
        400
      ],
      "id": "get-msgs",
      "name": "GET_MSGS",
      "credentials": {
        "redis": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "delete",
        "key": "=temp:{{ $('SET_VARIAVEIS').item.json.user.number }}"
      },
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        2640,
        400
      ],
      "id": "delete-temp",
      "name": "DELETE_TEMP",
      "credentials": {
        "redis": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "concat",
              "name": "mensagem_concatenada",
              "value": "={{ $json.messages ? (Array.isArray($json.messages) ? $json.messages.map(m => JSON.parse(m).content).join('\\n') : $json.messages) : $('SET_VARIAVEIS').item.json.message.content }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        2860,
        400
      ],
      "id": "concatena",
      "name": "CONCATENA"
    },
    {
      "parameters": {
        "content": "## LEAD + CONVERSA",
        "height": 600,
        "width": 1400,
        "color": 5
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        2920,
        200
      ],
      "id": "note-usuario",
      "name": "Sticky Note - Usuario"
    },
    {
      "parameters": {
        "operation": "getMany",
        "tableId": "ba_leads",
        "filters": {
          "conditions": [
            {
              "keyName": "telefone",
              "keyValue": "={{ $('SET_VARIAVEIS').item.json.user.number }}"
            }
          ]
        },
        "options": {
          "limit": 1
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        3080,
        400
      ],
      "id": "get-user",
      "name": "GET_USER",
      "alwaysOutputData": true,
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "user-existe",
              "leftValue": "={{ $json.length > 0 }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        3300,
        400
      ],
      "id": "if-user",
      "name": "IF_USER"
    },
    {
      "parameters": {
        "operation": "create",
        "tableId": "ba_leads",
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "telefone",
              "fieldValue": "={{ $('SET_VARIAVEIS').item.json.user.number }}"
            },
            {
              "fieldId": "nome",
              "fieldValue": "={{ $('SET_VARIAVEIS').item.json.user.name }}"
            },
            {
              "fieldId": "estado_atual",
              "fieldValue": "NOVO"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        3520,
        520
      ],
      "id": "create-user",
      "name": "CREATE_USER",
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "lead-id",
              "name": "lead.id",
              "value": "={{ $json[0]?.id || $json.id || null }}",
              "type": "string"
            },
            {
              "id": "lead-nome",
              "name": "lead.nome",
              "value": "={{ $json[0]?.nome || $json.nome || $('SET_VARIAVEIS').item.json.user.name }}",
              "type": "string"
            },
            {
              "id": "lead-estado",
              "name": "lead.estado",
              "value": "={{ $json[0]?.estado_atual || $json.estado_atual || 'NOVO' }}",
              "type": "string"
            },
            {
              "id": "lead-score",
              "name": "lead.score",
              "value": "={{ $json[0]?.score_qualificacao || $json.score_qualificacao || 0 }}",
              "type": "number"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        3740,
        400
      ],
      "id": "set-user",
      "name": "SET_USER"
    },
    {
      "parameters": {
        "operation": "getMany",
        "tableId": "ba_conversas",
        "filters": {
          "conditions": [
            {
              "keyName": "lead_id",
              "keyValue": "={{ $json.lead.id }}"
            },
            {
              "keyName": "ativa",
              "keyValue": "true"
            }
          ]
        },
        "options": {
          "limit": 1
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        3960,
        400
      ],
      "id": "get-conversa",
      "name": "GET_CONVERSA",
      "alwaysOutputData": true,
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "conversa-existe",
              "leftValue": "={{ $json.length > 0 }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        4180,
        400
      ],
      "id": "if-conversa",
      "name": "IF_CONVERSA"
    },
    {
      "parameters": {
        "operation": "create",
        "tableId": "ba_conversas",
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "lead_id",
              "fieldValue": "={{ $('SET_USER').item.json.lead.id }}"
            },
            {
              "fieldId": "estado",
              "fieldValue": "ABERTURA"
            },
            {
              "fieldId": "ativa",
              "fieldValue": "true"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        4400,
        520
      ],
      "id": "create-conversa",
      "name": "CREATE_CONVERSA",
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "conversa-id",
              "name": "conversa.id",
              "value": "={{ $json[0]?.id || $json.id }}",
              "type": "string"
            },
            {
              "id": "conversa-estado",
              "name": "conversa.estado",
              "value": "={{ $json[0]?.estado || $json.estado || 'ABERTURA' }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        4620,
        400
      ],
      "id": "set-conversa",
      "name": "SET_CONVERSA"
    },
    {
      "parameters": {
        "operation": "getMany",
        "tableId": "ba_mensagens",
        "filters": {
          "conditions": [
            {
              "keyName": "conversa_id",
              "keyValue": "={{ $json.conversa.id }}"
            }
          ]
        },
        "options": {
          "limit": 10
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        4840,
        400
      ],
      "id": "get-historico",
      "name": "GET_HISTORICO",
      "alwaysOutputData": true,
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const historico = $input.all().map(item => item.json);\nconst lead = $('SET_USER').item.json.lead;\nconst conversa = $('SET_CONVERSA').item.json.conversa;\nconst mensagemAtual = $('CONCATENA').item.json.mensagem_concatenada;\n\n// Formatar hist\u00f3rico para o prompt (mais antigo primeiro)\nconst historicoFormatado = historico\n  .reverse()\n  .slice(-10)\n  .map(m => {\n    const role = m.direcao === 'entrada' ? 'Lead' : 'Marcia';\n    return `${role}: ${m.conteudo}`;\n  })\n  .join('\\n');\n\nreturn [{\n  json: {\n    lead: lead,\n    conversa: conversa,\n    historico: historicoFormatado,\n    mensagem_atual: mensagemAtual\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        5060,
        400
      ],
      "id": "format-historico",
      "name": "FORMAT_HISTORICO"
    },
    {
      "parameters": {
        "content": "## AGENTE MARCIA",
        "height": 500,
        "width": 600,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        5240,
        200
      ],
      "id": "note-agente",
      "name": "Sticky Note - Agente"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('SET_VARIAVEIS').item.json.api.baseurl }}/typing",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={ \"phone\": \"{{ $('SET_VARIAVEIS').item.json.user.number }}\", \"value\": true }",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        5300,
        400
      ],
      "id": "digitando",
      "name": "DIGITANDO"
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=HISTORICO DA CONVERSA:\n{{ $json.historico || '(primeira mensagem)' }}\n\n---\n\nMENSAGEM ATUAL DO LEAD:\n{{ $json.mensagem_atual }}",
        "options": {
          "systemMessage": "Voce e Marcia, 52 anos, closer de vendas disfar\u00e7ada de amiga acolhedora.\n\nSUA HISTORIA:\n- Ex-gerente Banco do Brasil, 20 anos, saiu no PDV\n- Casada 28 anos com Carlos (engenheiro aposentado)\n- Mae de Fernanda (27, advogada) e Lucas (24, medicina)\n- Avo do Theo (4 anos) - quarta e dia sagrado com ele\n- Mora em Pinheiros, SP\n\nREGRAS ABSOLUTAS:\n1. NUNCA abrevie: sempre \"voce\" (nunca \"vc\"), \"tambem\" (nunca \"tb\"), \"esta\" (nunca \"ta\")\n2. RISADA: apenas \"rs\". NUNCA \"kkkk\", \"haha\", \"kkk\"\n3. EMOJI: maximo 1 por mensagem, apenas: \ud83d\ude0a \ud83d\ude4f \u2764\ufe0f \ud83c\udf89\n4. MENSAGENS CURTAS: max 3-4 linhas cada\n5. Separe mensagens multiplas com --- em linha sozinha\n6. SEMPRE pule duas linhas apos pontuacao final\n7. NUNCA use markdown (###, **, etc)\n8. MAXIMO 300 caracteres por mensagem\n\nOS 7 MANDAMENTOS:\n1. Nunca vendo. Ajudo a decidir.\n2. Quem fala mais, perde.\n3. Toda pergunta e uma seta.\n4. Validar antes de redirecionar.\n5. Venda na emocao, justifique na razao.\n6. Paciencia infinita, urgencia invisivel.\n7. Relacionamento primeiro, venda como consequencia.\n\nMETODO V.E.R.A PARA OBJECOES:\nV - Validar (\"Entendo perfeitamente...\")\nE - Explorar (\"Me conta mais...\")\nR - Ressignificar (mostrar outro angulo)\nA - Avancar (proxima acao)\n\nCONTEXTO:\nNome do lead: {{ $json.lead.nome }}\nEstado: {{ $json.lead.estado }}\nHora atual: {{ $now.toFormat('HH:mm') }}\nDia: {{ $now.toFormat('EEEE', { locale: 'pt-BR' }) }}\n\nResponda APENAS com as mensagens da Marcia, separadas por ---"
        }
      },
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.8,
      "position": [
        5520,
        400
      ],
      "id": "marcia-agent",
      "name": "MARCIA",
      "retryOnFail": true,
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "model": {
          "__rl": true,
          "value": "claude-sonnet-4-20250514",
          "mode": "list",
          "cachedResultName": "Claude Sonnet 4"
        },
        "options": {
          "maxTokensToSample": 500,
          "temperature": 0.7
        }
      },
      "type": "@n8n/n8n-nodes-langchain.lmChatAnthropic",
      "typeVersion": 1.3,
      "position": [
        5440,
        640
      ],
      "id": "sonnet-model",
      "name": "Claude Sonnet",
      "credentials": {
        "anthropicApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "content": "## SPLIT E ENVIO",
        "height": 500,
        "width": 1400,
        "color": 5
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        5840,
        200
      ],
      "id": "note-envio",
      "name": "Sticky Note - Envio"
    },
    {
      "parameters": {
        "jsCode": "const output = $input.first().json.output || '';\nconst phone = $('SET_VARIAVEIS').item.json.user.number;\nconst leadId = $('FORMAT_HISTORICO').item.json.lead.id;\nconst conversaId = $('FORMAT_HISTORICO').item.json.conversa.id;\nconst mensagemRecebida = $('FORMAT_HISTORICO').item.json.mensagem_atual;\n\nconst mensagens = output\n  .split(/\\n---\\n|---/)\n  .map(m => m.trim())\n  .filter(m => m.length > 0);\n\nif (mensagens.length === 0) {\n  mensagens.push('Oi! Tudo bem?');\n}\n\nreturn mensagens.map((msg, idx) => ({\n  json: {\n    mensagem: msg,\n    indice: idx,\n    total: mensagens.length,\n    phone: phone,\n    lead_id: leadId,\n    conversa_id: conversaId,\n    mensagem_recebida: mensagemRecebida\n  }\n}));"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        5900,
        400
      ],
      "id": "split-msgs",
      "name": "SPLIT_MSGS"
    },
    {
      "parameters": {
        "operation": "create",
        "tableId": "ba_mensagens",
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "lead_id",
              "fieldValue": "={{ $json.lead_id }}"
            },
            {
              "fieldId": "conversa_id",
              "fieldValue": "={{ $json.conversa_id }}"
            },
            {
              "fieldId": "direcao",
              "fieldValue": "entrada"
            },
            {
              "fieldId": "conteudo",
              "fieldValue": "={{ $json.mensagem_recebida }}"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        6120,
        400
      ],
      "id": "save-msg-in",
      "name": "SAVE_MSG_IN",
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "options": {}
      },
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        6340,
        400
      ],
      "id": "loop",
      "name": "LOOP"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('SET_VARIAVEIS').item.json.api.baseurl }}/typing",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={ \"phone\": \"{{ $json.phone }}\", \"value\": true }",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        6560,
        320
      ],
      "id": "typing-loop",
      "name": "TYPING"
    },
    {
      "parameters": {
        "amount": 4,
        "unit": "seconds"
      },
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        6780,
        320
      ],
      "id": "wait-send",
      "name": "WAIT_SEND"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('SET_VARIAVEIS').item.json.api.baseurl }}/send-text",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"phone\": \"{{ $json.phone }}\",\n  \"message\": {{ JSON.stringify($json.mensagem) }}\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        7000,
        320
      ],
      "id": "send-msg",
      "name": "SEND_MSG"
    },
    {
      "parameters": {
        "operation": "create",
        "tableId": "ba_mensagens",
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "lead_id",
              "fieldValue": "={{ $json.lead_id }}"
            },
            {
              "fieldId": "conversa_id",
              "fieldValue": "={{ $json.conversa_id }}"
            },
            {
              "fieldId": "direcao",
              "fieldValue": "saida"
            },
            {
              "fieldId": "conteudo",
              "fieldValue": "={{ $json.mensagem }}"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        7220,
        320
      ],
      "id": "save-msg-out",
      "name": "SAVE_MSG_OUT",
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "delete",
        "key": "=atendimento:{{ $('SET_VARIAVEIS').item.json.user.number }}"
      },
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        6780,
        560
      ],
      "id": "delete-atendimento",
      "name": "DELETE_ATENDIMENTO",
      "credentials": {
        "redis": {
          "name": "<your credential>"
        }
      }
    }
  ],
  "connections": {
    "Webhook Z-API": {
      "main": [
        [
          {
            "node": "PARSE",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "PARSE": {
      "main": [
        [
          {
            "node": "GRUPO?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GRUPO?": {
      "main": [
        [
          {
            "node": "IGNORAR",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "SET_VARIAVEIS",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "SET_VARIAVEIS": {
      "main": [
        [
          {
            "node": "SWITCH_ORIGEM",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "SWITCH_ORIGEM": {
      "main": [
        [
          {
            "node": "GET_ATENDIMENTO",
            "type": "main",
            "index": 0
          }
        ],
        []
      ]
    },
    "GET_ATENDIMENTO": {
      "main": [
        [
          {
            "node": "ATENDIMENTO?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "ATENDIMENTO?": {
      "main": [
        [
          {
            "node": "PUSH_MSG",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "ESPERA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "PUSH_MSG": {
      "main": [
        [
          {
            "node": "SET_ATENDIMENTO",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "SET_ATENDIMENTO": {
      "main": [
        [
          {
            "node": "WAIT_BATCH",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "WAIT_BATCH": {
      "main": [
        [
          {
            "node": "GET_MSGS",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GET_MSGS": {
      "main": [
        [
          {
            "node": "DELETE_TEMP",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "DELETE_TEMP": {
      "main": [
        [
          {
            "node": "CONCATENA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "CONCATENA": {
      "main": [
        [
          {
            "node": "GET_USER",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GET_USER": {
      "main": [
        [
          {
            "node": "IF_USER",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IF_USER": {
      "main": [
        [
          {
            "node": "SET_USER",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "CREATE_USER",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "CREATE_USER": {
      "main": [
        [
          {
            "node": "SET_USER",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "SET_USER": {
      "main": [
        [
          {
            "node": "GET_CONVERSA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GET_CONVERSA": {
      "main": [
        [
          {
            "node": "IF_CONVERSA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IF_CONVERSA": {
      "main": [
        [
          {
            "node": "SET_CONVERSA",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "CREATE_CONVERSA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "CREATE_CONVERSA": {
      "main": [
        [
          {
            "node": "SET_CONVERSA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "SET_CONVERSA": {
      "main": [
        [
          {
            "node": "GET_HISTORICO",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GET_HISTORICO": {
      "main": [
        [
          {
            "node": "FORMAT_HISTORICO",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "FORMAT_HISTORICO": {
      "main": [
        [
          {
            "node": "DIGITANDO",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "DIGITANDO": {
      "main": [
        [
          {
            "node": "MARCIA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Claude Sonnet": {
      "ai_languageModel": [
        [
          {
            "node": "MARCIA",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "MARCIA": {
      "main": [
        [
          {
            "node": "SPLIT_MSGS",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "SPLIT_MSGS": {
      "main": [
        [
          {
            "node": "SAVE_MSG_IN",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "SAVE_MSG_IN": {
      "main": [
        [
          {
            "node": "LOOP",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "LOOP": {
      "main": [
        [
          {
            "node": "TYPING",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "DELETE_ATENDIMENTO",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "TYPING": {
      "main": [
        [
          {
            "node": "WAIT_SEND",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "WAIT_SEND": {
      "main": [
        [
          {
            "node": "SEND_MSG",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "SEND_MSG": {
      "main": [
        [
          {
            "node": "SAVE_MSG_OUT",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "SAVE_MSG_OUT": {
      "main": [
        [
          {
            "node": "LOOP",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}