Skip to content

Add Alicia Meta Ads v2 workflow with client management and reporting#2475

Open
gabrjacinto wants to merge 16 commits intoEvolutionAPI:mainfrom
gabrjacinto:claude/meta-ads-campaign-reports-FCXyD
Open

Add Alicia Meta Ads v2 workflow with client management and reporting#2475
gabrjacinto wants to merge 16 commits intoEvolutionAPI:mainfrom
gabrjacinto:claude/meta-ads-campaign-reports-FCXyD

Conversation

@gabrjacinto
Copy link

@gabrjacinto gabrjacinto commented Mar 16, 2026

📋 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:

  • WhatsApp Integration: Receives messages via Evolution API webhook and processes requests mentioning "Alicia"
  • Client Management: Maps 13 client names/aliases to their Meta Ads account IDs (Antonio Neto, Gabriel Jacinto, Dani Escudero, Agro, Escola de Música, Panmalhas, GFiX Store, Arte em Gelo, ITAG Tecnologia, Hi Dogz, Batata Bistrô, Caribbean Bronze, Larissa Kelleter)
  • Flexible Date Handling: Supports multiple date presets (today, yesterday, this week, last 7/14/30 days, last month) with intelligent parsing from natural language
  • Dual Reporting Modes:
    • Leads campaigns: Reports impressions, clicks, leads, and cost-per-lead
    • E-commerce campaigns (Hi Dogz, Batata Bistrô): Reports impressions, clicks, sales, and cost-per-sale
  • AI-Powered Agent: Claude Opus-based agent with four specialized tools:
    • buscar_insights: Query Meta Ads metrics for specific accounts/campaigns
    • listar_campanhas: List all campaigns in an account
    • listar_conjuntos: List ad sets for accounts or campaigns
    • buscar_insights_multiplas_contas: Aggregate insights across multiple accounts when no specific client is mentioned
  • Formatted Output: Portuguese (Brazil) formatted responses with proper currency formatting (R$), thousand separators, and emojis for visual clarity

Workflow Architecture:

  1. Parse incoming WhatsApp messages
  2. Filter for "Alicia" mentions and valid content
  3. Calculate date ranges and detect client/report requests
  4. Route to either:
    • Quick Report Path: Direct Meta Ads API call → formatted response (for specific client + report request)
    • AI Agent Path: Intelligent processing via Claude with tool access (for general queries or multi-account requests)
  5. Send formatted response back via WhatsApp

🔗 Related Issue

N/A

🧪 Type of Change

  • ✨ New feature (non-breaking change which adds functionality)

🧪 Testing

  • Manual testing completed
  • Functionality verified in development environment
  • Tested with different connection types (if applicable)

The workflow has been tested with:

  • WhatsApp message parsing from Evolution API
  • Client name detection and aliasing
  • Date range calculations for various presets
  • Meta Ads API integration with proper token handling
  • Both leads and e-commerce reporting formats
  • AI agent tool invocation and response formatting

✅ Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • My changes generate no new warnings
  • I have manually tested my changes thoroughly
  • I have verified the changes work with different scenarios

📝 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_7d preset 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:

  • Introduce a WhatsApp-triggered Meta Ads reporting assistant that supports multiple client accounts and aliases.
  • Add intelligent date range handling with common reporting presets and natural language parsing for Meta Ads queries.
  • Provide dual reporting flows for leads and e-commerce campaigns, including account-level and multi-account summaries via an AI agent with Meta Ads tooling.

claude added 12 commits March 15, 2026 00:56
- 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
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Mar 16, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Adds 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

Change Details Files
Introduce complete n8n workflow JSON for the Alicia Meta Ads v2 assistant
  • Define trigger node for Evolution API WhatsApp webhooks and initial parsing/validation logic for messages mentioning Alicia
  • Implement client alias mapping for 13 Meta Ads accounts using an array structure and longest-alias matching to resolve the target account
  • Add date-handling nodes that parse natural language presets into Meta Ads-compatible ranges with UTC handling and special logic for last_7d cutoffs
  • Configure two reporting modes (leads vs e-commerce) with different metric selections and cost-per-lead/cost-per-sale calculations against Meta Ads APIs
  • Set up branching between a quick-report path (direct API-to-response) and an AI-agent path powered by Claude Opus with four tools for insights, campaigns, ad sets, and multi-account aggregation
  • Format responses in Brazilian Portuguese, including R$ currency formatting, thousand separators, emojis, and send them back via WhatsApp through Evolution API
n8n-alicia-meta-ads.json

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

claude added 4 commits March 16, 2026 20:20
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants