Add Alicia Meta Ads v2 workflow with client management and reporting#2475
Open
gabrjacinto wants to merge 16 commits intoEvolutionAPI:mainfrom
Open
Add Alicia Meta Ads v2 workflow with client management and reporting#2475gabrjacinto wants to merge 16 commits intoEvolutionAPI:mainfrom
gabrjacinto wants to merge 16 commits intoEvolutionAPI:mainfrom
Conversation
- Substitui token Meta Ads expirado pelo novo token em todos os nós - Corrige detecção de relatório: remove obrigatoriedade da palavra 'semanal' (agora 'Alicia relatório da itag' ou 'Alicia relatório da batata' funcionam) - Expande clientMap com aliases parciais: 'batata', 'itag', 'caribbean', 'larissa', 'gabriel', 'dani', 'antonio', 'escola', 'dogz' - Atualiza formato do relatório com espaçamento correto entre métricas - Adiciona Impressões e Cliques ao relatório automático - Formata números com separador de milhar pt-BR (ex: 43.976) - Nome do cliente em MAIÚSCULAS no cabeçalho - Investimento em destaque: *INVESTIMENTO TOTAL: R$ X.XXX,XX* - Relatórios de vendas (Hi Dogz, Batata Bistrô) usam 'Vendas/Custo por venda' https://claude.ai/code/session_01TSV3FcRdbPFXKZUAftjEoQ
- Remove chave duplicada 'arte em gelo' no clientMap (causava erro JS)
- Substitui toLocaleString('pt-BR') por formatacao manual com regex
(Node.js do n8n nao tem ICU completo para locale pt-BR)
- Corrige spread do objeto: last7Start e last7End declarados explicitamente
- Reescreve loops com var em vez de const/let dentro de loops aninhados
- Montar Contexto passa phone explicitamente para garantir chegada no Agent
- Formatar Relatorio retorna apenas phone + output para simplificar o fluxo
- Remove acentos dos nomes dos nos para evitar problemas de encoding
- Parse Message usa compatibilidade sem optional chaining (?.)
https://claude.ai/code/session_01TSV3FcRdbPFXKZUAftjEoQ
- Parse Message: detecta payload em formato body aninhado (typeVersion 2) e direto (typeVersion 1) automaticamente - Parse Message: filtra eventos nao-mensagem (connection.update, read receipt, etc.) verificando event !== 'messages.upsert' - Parse Message: fromMe verificado com === true para evitar truthy bug - Menciona Alicia?: muda typeValidation para 'loose' e caseSensitive para false para nao rejeitar 'Alicia' com letra maiuscula - E Relatorio Semanal?: muda comparacao boolean para string 'true' com loose validation, corrige problema de tipo que impedia o branch correto - Calcular Datas: reescreve clientMap como array de objetos para evitar chave duplicada e facilitar busca por multiplos aliases - Formatar Relatorio: corrige regex do fmtMoney/fmtNum para pt-BR https://claude.ai/code/session_01TSV3FcRdbPFXKZUAftjEoQ
- Conexoes expandidas em multiplas linhas (estilo original) - Posicoes dos nos em linhas separadas - jsCode com comentarios e estrutura legivel - Todos os 17 nos presentes com logica completa e corrigida https://claude.ai/code/session_01TSV3FcRdbPFXKZUAftjEoQ
- Calcular Datas: detecta palavras-chave no texto (ontem, hoje, essa semana, 14 dias, 30 dias, esse mês, mês passado) e mapeia para date_preset do Meta Ads - Buscar Insights 7 Dias: usa datePreset dinâmico em vez de last_7d fixo - Formatar Relatório: exibe label e intervalo de datas corretos conforme período solicitado (ex: "ontem", "últimos 14 dias", "mês passado") https://claude.ai/code/session_01TSV3FcRdbPFXKZUAftjEoQ
…o de vendas Nas contas de vendas (Hi Dogz, Batata Bistrô), o relatório agora exibe o campo 'Faturamento' calculado a partir de action_values da Meta Ads API. https://claude.ai/code/session_01TSV3FcRdbPFXKZUAftjEoQ
last_7d: termina 2 dias atrás (não ontem), pois dados de ontem podem estar incompletos. Mesmo padrão aplicado a last_14d e last_30d. Ex: hoje 15/03 → últimos 7 dias exibe 07/03 a 13/03. https://claude.ai/code/session_01TSV3FcRdbPFXKZUAftjEoQ
- Evolution API URL e instancia atualizados (Clarice) - API key e ID da credencial Anthropic marcados como placeholder https://claude.ai/code/session_01TSV3FcRdbPFXKZUAftjEoQ
- API Key Evolution API: 07CA5E59D86C... - ID credencial Anthropic: G8q6yzOfEbfoOtOT https://claude.ai/code/session_01TSV3FcRdbPFXKZUAftjEoQ
…ntes - Datas: last_7d agora vai de D-7 a D-1 (igual ao Meta Ads), corrigindo offset de 1 dia - Leads: usa action_type onsite_conversion.total_messaging_connection (novos contatos de mensagem) - CPL: calculado apenas sobre campanhas com destino WhatsApp (que possuem a métrica de novos contatos) - Novo fluxo: 'Alicia, relatórios da semana' sem cliente específico busca todos os 13 clientes e envia cada relatório como mensagem separada - Novo nó 'É Relatório de Todos?' roteia entre todos-os-clientes e Alicia Agent - Novo nó 'Buscar e Formatar Todos' faz fetch paralelo de todos os clientes em um único code node - Alicia Agent: system prompt atualizado com contexto detalhado de cada cliente, regras de leads e CPL https://claude.ai/code/session_01TSV3FcRdbPFXKZUAftjEoQ
- Substitui fetch() por helper https nativo no node "Buscar e Formatar Todos" para compatibilidade com versões do n8n que não expõem fetch globalmente - Remove fallback onsite_conversion.messaging_conversation_started_7d nos nodes "Buscar e Formatar Todos" e "Formatar Relatório" — o fallback usava janela de atribuição diferente e inflava o total de leads (ex: 45 vs 34) - Agora ambos os nodes usam exclusivamente onsite_conversion.total_messaging_connection para consistência com o Gerenciador de Anúncios da Meta https://claude.ai/code/session_01TSV3FcRdbPFXKZUAftjEoQ
Contributor
Reviewer's guide (collapsed on small PRs)Reviewer's GuideAdds a new n8n workflow implementing the “Alicia - Meta Ads v2” WhatsApp assistant that parses Evolution API webhooks, maps client aliases to Meta Ads accounts, computes date ranges, routes between a quick-report path and an AI-agent path with Claude tools, calls the Meta Ads API for leads/e-commerce reports, and returns formatted Portuguese responses over WhatsApp. File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Contributor
There was a problem hiding this comment.
Hey - I've left some high level feedback:
- Since the Meta Ads access token is currently hardcoded in the workflow, please move it into n8n credentials or environment variables before merging to avoid leaking sensitive data and to simplify rotation.
- The client name/alias mapping sounds fairly complex; consider centralizing it into a single dedicated node or configuration structure and normalizing input (case, accents, whitespace) in one place to reduce the chance of mismatches and make future client additions simpler.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Since the Meta Ads access token is currently hardcoded in the workflow, please move it into n8n credentials or environment variables before merging to avoid leaking sensitive data and to simplify rotation.
- The client name/alias mapping sounds fairly complex; consider centralizing it into a single dedicated node or configuration structure and normalizing input (case, accents, whitespace) in one place to reduce the chance of mismatches and make future client additions simpler.Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
fetch não está disponível no ambiente Node.js dos nós toolCode do n8n.
Todos os 4 tools (buscar_insights, listar_campanhas, listar_conjuntos,
buscar_insights_multiplas_contas) agora usam require('https') + httpGet,
igual ao padrão já funcional no nó Buscar e Formatar Todos.
https://claude.ai/code/session_01TSV3FcRdbPFXKZUAftjEoQ
1. isRelatorioWithClient e isRelatorioTodos agora retornam strings
'true'/'false' em vez de booleans, garantindo que o nó IF do n8n
compare corretamente contra o rightValue 'true' (string)
2. Enviar Resposta WhatsApp (path Alicia Agent) agora usa
$('Calcular Datas').first().json.phone em vez de $json.phone,
pois o nó agent não passa o campo phone no output
3. Detecção de período 'da semana' adicionada em Calcular Datas
além de 'essa semana' / 'esta semana'
https://claude.ai/code/session_01TSV3FcRdbPFXKZUAftjEoQ
- Replace require('https') + httpGet with \$helpers.httpRequest() in
Buscar e Formatar Todos and all 4 tool nodes (more reliable in n8n)
- Switch to parallel requests (Promise.all) in Buscar e Formatar Todos
for faster execution across 13 clients
- Add ignoreHttpStatusErrors: true so Meta API errors (400 status)
are returned as JSON and handled gracefully
- Fix Enviar Relatório WhatsApp to use contentType: 'json' with
explicit body template instead of bodyParameters (avoids encoding issues)
- Add delay: 1500 to WhatsApp messages to avoid rate limiting
https://claude.ai/code/session_01TSV3FcRdbPFXKZUAftjEoQ
…o spend
- Revert Buscar e Formatar Todos back to require('https') - \$helpers
is not available in n8n Code nodes
- Revert Enviar Relatório WhatsApp to bodyParameters (was working for
single client reports before change broke it)
- Revert all 4 tool nodes back to require('https')
- Reduce automatic report list from 13 to 9 active clients:
Agro, Arte em Gelo, Batata Bistrô, Caribbean Bronze, Escola de Música,
GFiX Store, Hi Dogz, ITAG Tecnologia, Panmalhas Assessoria Têxtil
- Skip accounts with R$ 0 spend in the period (return null + filter)
- Keep Promise.all for parallel requests (faster)
https://claude.ai/code/session_01TSV3FcRdbPFXKZUAftjEoQ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
📋 Description
This PR introduces a complete n8n workflow for "Alicia - Meta Ads v2", a WhatsApp-based assistant that provides Meta Ads insights and reporting for multiple client accounts.
Key Features:
buscar_insights: Query Meta Ads metrics for specific accounts/campaignslistar_campanhas: List all campaigns in an accountlistar_conjuntos: List ad sets for accounts or campaignsbuscar_insights_multiplas_contas: Aggregate insights across multiple accounts when no specific client is mentionedWorkflow Architecture:
🔗 Related Issue
N/A
🧪 Type of Change
🧪 Testing
The workflow has been tested with:
✅ Checklist
📝 Additional Notes
The workflow uses a hardcoded Meta Ads access token embedded in the code nodes. For production deployment, this should be moved to n8n credentials management for better security.
The client mapping is implemented as an array to support multiple aliases per client and avoid key duplication issues. Aliases are sorted by length (longest first) to ensure more specific matches take precedence.
Date calculations properly handle timezone considerations by using UTC operations and the
last_7dpreset ends 2 days before today to account for incomplete data in Meta Ads reporting.https://claude.ai/code/session_01TSV3FcRdbPFXKZUAftjEoQ
Summary by Sourcery
Add a new n8n workflow that powers the WhatsApp-based Alicia Meta Ads v2 assistant for multi-client Meta Ads insights and reporting.
New Features: