{
  "name": "Agente Vendas Ve\u00edculos - Completo",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "whatsapp-webhook",
        "responseMode": "onReceived"
      },
      "name": "Webhook - Recebe Mensagens WhatsApp",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [
        250,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "string": [
            {
              "value1": "={{$json[\"type\"]}}",
              "operation": "equal",
              "value2": "audio"
            }
          ]
        }
      },
      "name": "IF - Texto ou \u00c1udio",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        450,
        300
      ]
    },
    {
      "parameters": {
        "action": "GET",
        "key": "={{`human_override:${$json.sender?.id || $json.sender}`}}"
      },
      "name": "Redis - Verifica Bloqueio Humano",
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        650,
        400
      ]
    },
    {
      "parameters": {
        "conditions": {
          "string": [
            {
              "value1": "={{$json}}",
              "operation": "notEmpty",
              "value2": ""
            }
          ]
        }
      },
      "name": "IF - Bloqueio Ativo?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        850,
        400
      ]
    },
    {
      "parameters": {
        "url": "https://api.openai.com/v1/audio/transcriptions",
        "options": {},
        "responseFormat": "json",
        "headerParametersJson": "[{\"name\":\"Authorization\",\"value\":\"Bearer {{OPENAI_API_KEY}}\"}]",
        "bodyParametersJson": "[{\"name\":\"file\",\"value\":\"={{$json.audio_url}}\",\"type\":\"file\"}]",
        "returnFullResponse": false
      },
      "name": "HTTP Request - Transcri\u00e7\u00e3o \u00c1udio (Whisper/OpenAI)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 1,
      "position": [
        650,
        200
      ]
    },
    {
      "parameters": {
        "action": "SET",
        "key": "={{`msg:${$json.id}:text`}}",
        "value": "={{$json.transcript || $json.text}}",
        "expire": 3600
      },
      "name": "Redis - Cache Texto",
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        850,
        200
      ]
    },
    {
      "parameters": {
        "url": "{{SUPABASE_URL}}/rest/v1/vehicles?select=*",
        "options": {},
        "responseFormat": "json",
        "headerParametersJson": "[{\"name\":\"apikey\",\"value\":\"{{SUPABASE_KEY}}\"},{\"name\":\"Authorization\",\"value\":\"Bearer {{SUPABASE_KEY}}\"}]",
        "queryParametersJson": "[]",
        "returnFullResponse": false
      },
      "name": "Supabase - Consulta Estoque Ve\u00edculos",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 1,
      "position": [
        1050,
        300
      ]
    },
    {
      "parameters": {
        "functionCode": "const message = items[0].json;\nconst stock = items[1].json;\nconst prompt = `Voc\u00ea \u00e9 um assistente virtual especializado em vendas de ve\u00edculos. Aqui est\u00e1 o contexto do cliente:\\n${JSON.stringify(message)}\\n\\nEstoque atual dos ve\u00edculos:\\n${JSON.stringify(stock)}\\n\\nPor favor, responda apresentando os modelos dispon\u00edveis, calcule op\u00e7\u00f5es de financiamento com taxa de 2,2% ao m\u00eas para 36, 48 e 60 parcelas conforme a entrada informada pelo cliente. Al\u00e9m disso, ofere\u00e7a agendamento de visitas. Seja educado e objetivo.`;\nreturn [{ json: { prompt } }];"
      },
      "name": "Function - Preparar Prompt IA",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        1250,
        300
      ]
    },
    {
      "parameters": {
        "url": "https://api.openai.com/v1/chat/completions",
        "method": "POST",
        "headerParametersJson": "[{\"name\":\"Authorization\",\"value\":\"Bearer {{OPENAI_API_KEY}}\"},{\"name\":\"Content-Type\",\"value\":\"application/json\"}]",
        "bodyParametersJson": "[{\"name\":\"model\",\"value\":\"gpt-4o-mini\"},{\"name\":\"messages\",\"value\":[{\"role\":\"system\",\"content\":\"Voc\u00ea \u00e9 um assistente de vendas de ve\u00edculos. Qualifique o cliente, apresente modelos e condi\u00e7\u00f5es de financiamento, e agende visita.\"},{\"role\":\"user\",\"content\":\"={{$json.prompt}}\"}]}]",
        "responseFormat": "json"
      },
      "name": "OpenAI - Gerar Resposta IA",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 1,
      "position": [
        1450,
        300
      ]
    },
    {
      "parameters": {
        "functionCode": "const data = items[0].json;\nconst valor = parseFloat(data.valorVeiculo || data.valor || 0);\nconst entrada = parseFloat(data.entrada || 0);\nconst taxa = 0.022;\nconst parcelas = [36, 48, 60];\nconst saldo = Math.max(0, valor - entrada);\nfunction pmt(v, i, n) {\n  return (v * i) / (1 - Math.pow(1 + i, -n));\n}\nconst opcoes = parcelas.map(n => ({ parcelas: n, parcelaMensal: parseFloat(pmt(saldo, taxa, n).toFixed(2)) }));\nreturn [{ json: { opcoesFinanciamento: opcoes, saldo, entrada, valor } }];"
      },
      "name": "Function - Calcular Financiamento",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        1650,
        300
      ]
    },
    {
      "parameters": {
        "operation": "create",
        "calendarId": "primary",
        "start": "={{$json.start}}",
        "end": "={{$json.end}}",
        "summary": "={{$json.summary}}",
        "description": "={{$json.description}}",
        "sendNotifications": true
      },
      "name": "Google Calendar - Criar Evento",
      "type": "n8n-nodes-base.googleCalendar",
      "typeVersion": 1,
      "position": [
        1850,
        300
      ]
    },
    {
      "parameters": {
        "url": "{{CRM_API_URL}}/contacts",
        "method": "POST",
        "headerParametersJson": "[{\"name\":\"Authorization\",\"value\":\"Bearer {{CRM_TOKEN}}\"},{\"name\":\"Content-Type\",\"value\":\"application/json\"}]",
        "bodyParametersJson": "[{\"name\":\"email\",\"value\":\"={{$json.email || ''}}\"},{\"name\":\"name\",\"value\":\"={{$json.nome || ''}}\"},{\"name\":\"phone\",\"value\":\"={{$json.phone || ''}}\"}]",
        "responseFormat": "json"
      },
      "name": "CRM - Criar/Atualizar Contato",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 1,
      "position": [
        2050,
        300
      ]
    },
    {
      "parameters": {
        "waitTime": {
          "amount": 15,
          "timeUnit": "minutes"
        }
      },
      "name": "Wait - Follow-up 15 minutos",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1,
      "position": [
        2250,
        250
      ]
    },
    {
      "parameters": {
        "url": "{{WHATSAPP_API_URL}}/send-message",
        "method": "POST",
        "headerParametersJson": "[{\"name\":\"Authorization\",\"value\":\"Bearer {{WHATSAPP_TOKEN}}\"},{\"name\":\"Content-Type\",\"value\":\"application/json\"}]",
        "bodyParametersJson": "[{\"name\":\"to\",\"value\":\"={{$json.sender?.phone || $json.phone}}\"},{\"name\":\"message\",\"value\":\"Ol\u00e1! Ainda est\u00e1 interessado no ve\u00edculo? Posso ajudar.\"}]",
        "responseFormat": "json"
      },
      "name": "Send Message - Reativa\u00e7\u00e3o 15 minutos",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 1,
      "position": [
        2450,
        250
      ]
    },
    {
      "parameters": {
        "waitTime": {
          "amount": 1,
          "timeUnit": "hours"
        }
      },
      "name": "Wait - Follow-up 1 hora",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1,
      "position": [
        2650,
        250
      ]
    },
    {
      "parameters": {
        "url": "{{WHATSAPP_API_URL}}/send-message",
        "method": "POST",
        "headerParametersJson": "[{\"name\":\"Authorization\",\"value\":\"Bearer {{WHATSAPP_TOKEN}}\"},{\"name\":\"Content-Type\",\"value\":\"application/json\"}]",
        "bodyParametersJson": "[{\"name\":\"to\",\"value\":\"={{$json.sender?.phone || $json.phone}}\"},{\"name\":\"message\",\"value\":\"Oi de novo! Posso agendar sua visita para ver os ve\u00edculos.\"}]",
        "responseFormat": "json"
      },
      "name": "Send Message - Reativa\u00e7\u00e3o 1 hora",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 1,
      "position": [
        2850,
        250
      ]
    },
    {
      "parameters": {
        "waitTime": {
          "amount": 1,
          "timeUnit": "days"
        }
      },
      "name": "Wait - Follow-up 1 dia",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1,
      "position": [
        3050,
        250
      ]
    },
    {
      "parameters": {
        "url": "{{WHATSAPP_API_URL}}/send-message",
        "method": "POST",
        "headerParametersJson": "[{\"name\":\"Authorization\",\"value\":\"Bearer {{WHATSAPP_TOKEN}}\"},{\"name\":\"Content-Type\",\"value\":\"application/json\"}]",
        "bodyParametersJson": "[{\"name\":\"to\",\"value\":\"={{$json.sender?.phone || $json.phone}}\"},{\"name\":\"message\",\"value\":\"Ol\u00e1! Estamos aqui para ajudar com o financiamento e agendamento. Quer continuar?\"}]",
        "responseFormat": "json"
      },
      "name": "Send Message - Reativa\u00e7\u00e3o 1 dia",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 1,
      "position": [
        3250,
        250
      ]
    },
    {
      "parameters": {
        "sheetId": "{{GOOGLE_SHEETS_PUBLIC_ID}}",
        "range": "Sheet1",
        "event": "valueChange"
      },
      "name": "Google Sheets Trigger - Sync Supabase",
      "type": "n8n-nodes-base.googleSheetsTrigger",
      "typeVersion": 1,
      "position": [
        1050,
        600
      ]
    },
    {
      "parameters": {
        "functionCode": "const rows = items.map(i => i.json);\nreturn rows.map(r => ({ json: r }));"
      },
      "name": "Function - Transformar Dados Google Sheets",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        1250,
        600
      ]
    },
    {
      "parameters": {
        "url": "{{SUPABASE_URL}}/rest/v1/vehicles",
        "method": "POST",
        "headerParametersJson": "[{\"name\":\"apikey\",\"value\":\"{{SUPABASE_KEY}}\"},{\"name\":\"Authorization\",\"value\":\"Bearer {{SUPABASE_KEY}}\"},{\"name\":\"Content-Type\",\"value\":\"application/json\"}]",
        "bodyParametersJson": "=[]",
        "options": {
          "queryParameters": {
            "on_conflict": "id"
          }
        },
        "responseFormat": "json"
      },
      "name": "HTTP Request - Upsert Supabase",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 1,
      "position": [
        1450,
        600
      ]
    }
  ],
  "connections": {
    "Webhook - Recebe Mensagens WhatsApp": {
      "main": [
        [
          {
            "node": "IF - Texto ou \u00c1udio",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IF - Texto ou \u00c1udio": {
      "main": [
        [
          {
            "node": "HTTP Request - Transcri\u00e7\u00e3o \u00c1udio (Whisper/OpenAI)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Redis - Verifica Bloqueio Humano",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HTTP Request - Transcri\u00e7\u00e3o \u00c1udio (Whisper/OpenAI)": {
      "main": [
        [
          {
            "node": "Redis - Cache Texto",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Redis - Cache Texto": {
      "main": [
        [
          {
            "node": "Redis - Verifica Bloqueio Humano",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Redis - Verifica Bloqueio Humano": {
      "main": [
        [
          {
            "node": "IF - Bloqueio Ativo?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IF - Bloqueio Ativo?": {
      "main": [
        [
          {
            "node": "OpenAI - Gerar Resposta IA",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "CRM - Criar/Atualizar Contato",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Supabase - Consulta Estoque Ve\u00edculos": {
      "main": [
        [
          {
            "node": "Function - Preparar Prompt IA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Function - Preparar Prompt IA": {
      "main": [
        [
          {
            "node": "OpenAI - Gerar Resposta IA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI - Gerar Resposta IA": {
      "main": [
        [
          {
            "node": "Function - Calcular Financiamento",
            "type": "main",
            "index": 0
          },
          {
            "node": "Google Calendar - Criar Evento",
            "type": "main",
            "index": 0
          },
          {
            "node": "CRM - Criar/Atualizar Contato",
            "type": "main",
            "index": 0
          },
          {
            "node": "Wait - Follow-up 15 minutos",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait - Follow-up 15 minutos": {
      "main": [
        [
          {
            "node": "Send Message - Reativa\u00e7\u00e3o 15 minutos",
            "type": "main",
            "index": 0
          },
          {
            "node": "Wait - Follow-up 1 hora",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait - Follow-up 1 hora": {
      "main": [
        [
          {
            "node": "Send Message - Reativa\u00e7\u00e3o 1 hora",
            "type": "main",
            "index": 0
          },
          {
            "node": "Wait - Follow-up 1 dia",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait - Follow-up 1 dia": {
      "main": [
        [
          {
            "node": "Send Message - Reativa\u00e7\u00e3o 1 dia",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets Trigger - Sync Supabase": {
      "main": [
        [
          {
            "node": "Function - Transformar Dados Google Sheets",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Function - Transformar Dados Google Sheets": {
      "main": [
        [
          {
            "node": "HTTP Request - Upsert Supabase",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {},
  "id": "agente-vendas-veiculos-completo"
}