{
  "name": "Socio - Bom Dia Briefing",
  "nodes": [
    {
      "id": "a1b2c3d4-0001-4000-8000-000000000001",
      "name": "Todos os dias 7h",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1,
      "position": [
        240,
        300
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "0 7 * * *"
            }
          ]
        },
        "timezone": "America/Sao_Paulo"
      }
    },
    {
      "id": "a1b2c3d4-0002-4000-8000-000000000002",
      "name": "Buscar todos usuarios",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 3,
      "position": [
        460,
        300
      ],
      "parameters": {
        "method": "GET",
        "url": "https://qjgjqrhsrfxfcmxhuirf.supabase.co/rest/v1/users?select=id,name,phone,monthly_goal,dream,profile_type&phone=not.is.null&phone=not.like.uid_*&bom_dia_enabled=eq.true",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "apikey",
              "value": "<redacted-credential>"
            },
            {
              "name": "Authorization",
              "value": "<redacted-credential>"
            }
          ]
        }
      }
    },
    {
      "id": "a1b2c3d4-0003-4000-8000-000000000003",
      "name": "Loop por usuario",
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 1,
      "position": [
        680,
        300
      ],
      "parameters": {
        "batchSize": 1,
        "options": {}
      }
    },
    {
      "id": "a1b2c3d4-0004-4000-8000-000000000004",
      "name": "Buscar transacoes de ontem",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 3,
      "alwaysOutputData": true,
      "position": [
        900,
        300
      ],
      "parameters": {
        "method": "GET",
        "url": "=https://qjgjqrhsrfxfcmxhuirf.supabase.co/rest/v1/transactions?user_id=eq.{{ $('Loop por usuario').item.json.id }}&competence_date=eq.{{ new Date(Date.now() - 86400000).toISOString().substring(0,10) }}&select=type,amount,category",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "apikey",
              "value": "<redacted-credential>"
            },
            {
              "name": "Authorization",
              "value": "<redacted-credential>"
            }
          ]
        }
      },
      "settings": {
        "alwaysOutputData": true
      }
    },
    {
      "id": "a1b2c3d4-0005-4000-8000-000000000005",
      "name": "Buscar agendamentos de hoje",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 3,
      "alwaysOutputData": true,
      "position": [
        1120,
        300
      ],
      "parameters": {
        "method": "GET",
        "url": "=https://qjgjqrhsrfxfcmxhuirf.supabase.co/rest/v1/appointments?user_id=eq.{{ $('Loop por usuario').item.json.id }}&scheduled_at=gte.{{ new Date().toISOString().substring(0,10) }}T00:00:00&scheduled_at=lte.{{ new Date().toISOString().substring(0,10) }}T23:59:59&select=service,scheduled_at,price&order=scheduled_at.asc",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "apikey",
              "value": "<redacted-credential>"
            },
            {
              "name": "Authorization",
              "value": "<redacted-credential>"
            }
          ]
        }
      },
      "settings": {
        "alwaysOutputData": true
      }
    },
    {
      "id": "a1b2c3d4-0006-4000-8000-000000000006",
      "name": "Montar briefing",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1340,
        300
      ],
      "parameters": {
        "jsCode": "const user = $('Loop por usuario').item.json;\nconst txArray = $('Buscar transacoes de ontem').all().map(i => i.json).filter(t => t && t.type);\nconst receita = txArray.filter(t => t.type === 'receita').reduce((s, t) => s + parseFloat(t.amount || 0), 0);\nconst despesa = txArray.filter(t => t.type === 'despesa').reduce((s, t) => s + parseFloat(t.amount || 0), 0);\nconst liquido = receita - despesa;\nconst apts = $input.all().map(i => i.json).filter(a => a && a.scheduled_at);\nconst agendamentos = apts.length === 0 ? 'Nenhum agendamento para hoje.' : apts.map(a => { const h = new Date(a.scheduled_at).toLocaleTimeString('pt-BR', {hour:'2-digit',minute:'2-digit',timeZone:'America/Sao_Paulo'}); return `${h}: ${a.service}`; }).join('\\n');\nconst hoje = new Date().toLocaleDateString('pt-BR', {weekday:'long', day:'numeric', month:'long'});\nreturn [{ json: { userId: user.id, userName: user.name, userPhone: user.phone, meta: user.monthly_goal || 0, sonho: user.dream || '', receita: receita.toFixed(2), despesa: despesa.toFixed(2), liquido: liquido.toFixed(2), agendamentos, totalAgendamentos: apts.length, hoje } }];"
      }
    },
    {
      "id": "a1b2c3d4-0007-4000-8000-000000000007",
      "name": "Gerar briefing com IA",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 3,
      "position": [
        1560,
        300
      ],
      "parameters": {
        "method": "POST",
        "url": "https://api.openai.com/v1/chat/completions",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer <redacted-credential>"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "contentType": "raw",
        "rawContentType": "application/json",
        "body": "={{ JSON.stringify({ model: 'gpt-4o-mini', temperature: 0.7, max_tokens: 300, messages: [{ role: 'user', content: 'Voc\u00ea \u00e9 o Meu S\u00f3cio, parceiro de neg\u00f3cios de ' + $json.userName + '.\\n\\nGere o Bom Dia de hoje (' + $json.hoje + ').\\n\\nDADOS:\\n- Receita ontem: R$ ' + $json.receita + '\\n- Despesa ontem: R$ ' + $json.despesa + '\\n- L\u00edquido: R$ ' + $json.liquido + '\\n- Meta mensal: R$ ' + $json.meta + '\\n\\nAGENDA HOJE (' + $json.totalAgendamentos + ' compromisso(s)):\\n' + $json.agendamentos + '\\n\\nSonho: ' + $json.sonho + '\\n\\nEscreva em no m\u00e1ximo 6 linhas. Sauda\u00e7\u00e3o pelo nome, resultado de ontem, agenda do dia, incentivo. Use emojis. Sem asteriscos.' }] }) }}"
      }
    },
    {
      "id": "a1b2c3d4-0008-4000-8000-000000000008",
      "name": "Extrair briefing",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1780,
        300
      ],
      "parameters": {
        "jsCode": "const briefing = $input.first().json.choices[0].message.content;\nconst dados = $('Montar briefing').item.json;\nreturn [{ json: { ...dados, briefing } }];"
      }
    },
    {
      "id": "a1b2c3d4-0009-4000-8000-000000000009",
      "name": "Enviar Bom Dia WhatsApp",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 3,
      "position": [
        2000,
        300
      ],
      "continueOnFail": true,
      "parameters": {
        "method": "POST",
        "url": "https://evolution-api-production-e9a3.up.railway.app/message/sendText/meu-socio",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "apikey",
              "value": "762c9cac5efdde8e3b0aee288580ac2a3b11495fa892c757b5bc18dd2b0ec610"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "contentType": "raw",
        "rawContentType": "application/json",
        "body": "={{ JSON.stringify({ number: (($json.userPhone || '').replace(/\\D/g,'')).startsWith('55') ? ($json.userPhone.replace(/\\D/g,'')) + '@s.whatsapp.net' : '55' + ($json.userPhone.replace(/\\D/g,'')) + '@s.whatsapp.net', text: $json.briefing }) }}"
      }
    }
  ],
  "connections": {
    "Todos os dias 7h": {
      "main": [
        [
          {
            "node": "Buscar todos usuarios",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Buscar todos usuarios": {
      "main": [
        [
          {
            "node": "Loop por usuario",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop por usuario": {
      "main": [
        [
          {
            "node": "Buscar transacoes de ontem",
            "type": "main",
            "index": 0
          }
        ],
        []
      ]
    },
    "Buscar transacoes de ontem": {
      "main": [
        [
          {
            "node": "Buscar agendamentos de hoje",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Buscar agendamentos de hoje": {
      "main": [
        [
          {
            "node": "Montar briefing",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Montar briefing": {
      "main": [
        [
          {
            "node": "Gerar briefing com IA",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gerar briefing com IA": {
      "main": [
        [
          {
            "node": "Extrair briefing",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extrair briefing": {
      "main": [
        [
          {
            "node": "Enviar Bom Dia WhatsApp",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Enviar Bom Dia WhatsApp": {
      "main": [
        [
          {
            "node": "Loop por usuario",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "tags": [
    {
      "name": "socio"
    },
    {
      "name": "briefing"
    }
  ]
}