{
  "name": "MensalliZap - NPS P\u00f3s-Experimental",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "0 11 * * *"
            }
          ]
        }
      },
      "id": "schedule-trigger",
      "name": "Disparo Di\u00e1rio (11h)",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        250,
        300
      ]
    },
    {
      "parameters": {
        "method": "GET",
        "url": "https://zvlnkkmcytjtridiojxx.supabase.co/rest/v1/vw_alunos_aguardando_nps",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "apikey",
              "value": "<redacted-credential>"
            },
            {
              "name": "Authorization",
              "value": "<redacted-credential>"
            }
          ]
        },
        "options": {}
      },
      "id": "buscar-aguardando-nps",
      "name": "Buscar Aguardando NPS",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        500,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "// Criar mensagem de NPS p\u00f3s-experimental\nconst FALLBACK_NPS = 'Oi {{nomeCliente}}! \ud83d\udc4b\\n\\nVi que voc\u00ea teve sua primeira aula aqui na *{{nomeEmpresa}}* \u2014 espero que tenha curtido! \ud83d\udc9b\\n\\n*Como foi sua experi\u00eancia?*\\nMe manda uma nota de 0 a 10:\\n0 = p\u00e9ssimo   10 = excelente\\n\\nSe quiser, me conta numa mensagem o que mais gostou ou o que podemos melhorar \u2014 sua opini\u00e3o \u00e9 ouro pra n\u00f3s! \ud83d\ude4f';\n\nconst items = $input.all();\nconst results = [];\n\nfor (const item of items) {\n  const data = item.json;\n\n  let mensagem = data.template_mensagem;\n  if (!mensagem || mensagem.trim() === '') {\n    mensagem = FALLBACK_NPS;\n  }\n\n  const variaveis = {\n    '{{nomeCliente}}': (data.nome_cliente || 'aluno').split(' ')[0],\n    '{{nomeEmpresa}}': data.nome_empresa || 'nossa equipe'\n  };\n\n  Object.entries(variaveis).forEach(([chave, valor]) => {\n    mensagem = mensagem.replace(new RegExp(chave, 'g'), valor);\n  });\n\n  let telefone = String(data.telefone || '').replace(/\\D/g, '');\n  if (!telefone.startsWith('55')) telefone = '55' + telefone;\n\n  results.push({\n    json: {\n      ...data,\n      mensagem,\n      telefone,\n      evolution_url: `${data.evolution_api_url}/message/sendText/${data.evolution_instance_name}`,\n      tipo_gatilho: 'experimental'\n    }\n  });\n}\n\nreturn results;"
      },
      "id": "criar-msg-nps",
      "name": "Criar Mensagem",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        750,
        300
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $json.evolution_url }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "apikey",
              "value": "={{ $json.evolution_api_key }}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"number\": \"{{ $json.telefone }}\",\n  \"text\": {{ JSON.stringify($json.mensagem) }}\n}",
        "options": {}
      },
      "id": "enviar-whatsapp",
      "name": "Enviar WhatsApp",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1000,
        300
      ],
      "continueOnFail": true
    },
    {
      "parameters": {
        "jsCode": "// Verificar resultado do envio\nconst items = $input.all();\nconst originalItems = $('Criar Mensagem').all();\nconst results = [];\n\nfor (let i = 0; i < items.length; i++) {\n  const response = items[i].json;\n  const original = originalItems[i] ? originalItems[i].json : {};\n\n  const hasError = !!(response.error && typeof response.error === 'object' && 'message' in response.error);\n\n  if (hasError) {\n    const msg = String(response.error.message || 'Erro desconhecido');\n    results.push({\n      json: {\n        ...original,\n        envio_sucesso: false,\n        erro_mensagem: msg\n      }\n    });\n  } else {\n    results.push({\n      json: {\n        ...original,\n        envio_sucesso: true\n      }\n    });\n  }\n}\n\nreturn results;"
      },
      "id": "check-resultado",
      "name": "Check Resultado",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1250,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "boolean": [
            {
              "value1": "={{ $json.envio_sucesso }}",
              "value2": true
            }
          ]
        }
      },
      "id": "if-sucesso",
      "name": "Envio OK?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        1500,
        300
      ]
    },
    {
      "parameters": {
        "method": "PATCH",
        "url": "=https://zvlnkkmcytjtridiojxx.supabase.co/rest/v1/devedores?id=eq.{{ $('Envio OK?').item.json.devedor_id }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "apikey",
              "value": "<redacted-credential>"
            },
            {
              "name": "Authorization",
              "value": "<redacted-credential>"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            },
            {
              "name": "Prefer",
              "value": "return=minimal"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"nps_experimental_enviado_em\": \"{{ new Date().toISOString() }}\"\n}",
        "options": {}
      },
      "id": "marcar-devedor",
      "name": "Marcar Devedor",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1750,
        200
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://zvlnkkmcytjtridiojxx.supabase.co/rest/v1/nps_respostas",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "apikey",
              "value": "<redacted-credential>"
            },
            {
              "name": "Authorization",
              "value": "<redacted-credential>"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            },
            {
              "name": "Prefer",
              "value": "return=minimal"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"user_id\": \"{{ $('Envio OK?').item.json.user_id }}\",\n  \"devedor_id\": \"{{ $('Envio OK?').item.json.devedor_id }}\",\n  \"tipo_gatilho\": \"experimental\"\n}",
        "options": {}
      },
      "id": "criar-resposta-pendente",
      "name": "Criar Resposta Pendente",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2000,
        200
      ]
    },
    {
      "parameters": {
        "method": "PATCH",
        "url": "=https://zvlnkkmcytjtridiojxx.supabase.co/rest/v1/controle_planos?user_id=eq.{{ $('Envio OK?').item.json.user_id }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "apikey",
              "value": "<redacted-credential>"
            },
            {
              "name": "Authorization",
              "value": "<redacted-credential>"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            },
            {
              "name": "Prefer",
              "value": "return=minimal"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"usage_count\": {{ ($('Envio OK?').item.json.usage_count || 0) + 1 }},\n  \"updated_at\": \"{{ new Date().toISOString() }}\"\n}",
        "options": {}
      },
      "id": "incrementar-usage",
      "name": "Incrementar Usage",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2250,
        200
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://zvlnkkmcytjtridiojxx.supabase.co/rest/v1/logs_mensagens",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "apikey",
              "value": "<redacted-credential>"
            },
            {
              "name": "Authorization",
              "value": "<redacted-credential>"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            },
            {
              "name": "Prefer",
              "value": "return=minimal"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"user_id\": \"{{ $('Envio OK?').item.json.user_id }}\",\n  \"devedor_id\": \"{{ $('Envio OK?').item.json.devedor_id }}\",\n  \"telefone\": \"{{ $('Envio OK?').item.json.telefone }}\",\n  \"mensagem\": {{ JSON.stringify($('Envio OK?').item.json.mensagem) }},\n  \"status\": \"enviado\"\n}",
        "options": {}
      },
      "id": "log-nps",
      "name": "Log NPS",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2500,
        200
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://zvlnkkmcytjtridiojxx.supabase.co/rest/v1/logs_mensagens",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "apikey",
              "value": "<redacted-credential>"
            },
            {
              "name": "Authorization",
              "value": "<redacted-credential>"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            },
            {
              "name": "Prefer",
              "value": "return=minimal"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"user_id\": \"{{ $('Envio OK?').item.json.user_id }}\",\n  \"devedor_id\": \"{{ $('Envio OK?').item.json.devedor_id }}\",\n  \"telefone\": \"{{ $('Envio OK?').item.json.telefone }}\",\n  \"mensagem\": {{ JSON.stringify($('Envio OK?').item.json.mensagem) }},\n  \"status\": \"falha\",\n  \"erro\": {{ JSON.stringify($('Envio OK?').item.json.erro_mensagem || 'Erro desconhecido') }}\n}",
        "options": {}
      },
      "id": "log-falha",
      "name": "Log Falha",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1750,
        450
      ]
    }
  ],
  "connections": {
    "Disparo Di\u00e1rio (11h)": {
      "main": [
        [
          {
            "node": "Buscar Aguardando NPS",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Buscar Aguardando NPS": {
      "main": [
        [
          {
            "node": "Criar Mensagem",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Criar Mensagem": {
      "main": [
        [
          {
            "node": "Enviar WhatsApp",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Enviar WhatsApp": {
      "main": [
        [
          {
            "node": "Check Resultado",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Resultado": {
      "main": [
        [
          {
            "node": "Envio OK?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Envio OK?": {
      "main": [
        [
          {
            "node": "Marcar Devedor",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Log Falha",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Marcar Devedor": {
      "main": [
        [
          {
            "node": "Criar Resposta Pendente",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Criar Resposta Pendente": {
      "main": [
        [
          {
            "node": "Incrementar Usage",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Incrementar Usage": {
      "main": [
        [
          {
            "node": "Log NPS",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}