✅ Checklist: Channel Performance Agent
Status: 🟢 Implementado e Deployado em DEV
Prioridade: 5 (Último - consome dados de todos os outros)
Estimativa: 2-3 semanas
Implementado em: 2026-01-25
📋 Resumo
| Item | Valor |
|---|---|
| Código | channel-performance |
| Porta | 8024 |
| Database | csuite_context |
| Prefixo API | /v1/performance |
| Traefik Path | /channel-performance/ |
| Depende de | Todos os outros agentes de canal |
🎯 Objetivo
O cérebro de aprendizado do canal. Analisa padrões, detecta problemas, e propõe ajustes de políticas. Sem ele, o sistema executa bem, mas não evolui.
Frase-guia: Sem o Channel Performance Agent, você automatiza o passado.
📊 Tipos de Insight
| Tipo | Descrição | Ação Típica |
|---|---|---|
POLICY_GAP |
Política não cobre cenário | Criar nova regra |
POLICY_TOO_RESTRICTIVE |
Política bloqueia demais | Flexibilizar |
POLICY_TOO_LAX |
Política permite demais | Restringir |
EXECUTION_DRIFT |
Execução desviando do esperado | Corrigir processo |
CHANNEL_MISALIGNMENT |
Canal desalinhado da estratégia | Revisar segmentação |
📊 Métricas Monitoradas
| Categoria | Métricas |
|---|---|
| Onboarding | Taxa de ativação, tempo médio, risco |
| Reativação | Taxa de sucesso, custo, reincidência |
| Estados | Distribuição, transições, velocidade |
| Receita | Volume, margem, previsibilidade |
| Qualidade | Churn, NPS, reclamações |
✅ Fases de Implementação
Fase 1: Estrutura Base
- [ ] Criar diretório
/c-suite/agents/channel-performance/ - [ ] Criar
requirements.txt
fastapi==0.104.1 uvicorn==0.24.0 mysql-connector-python==8.2.0 pydantic==2.5.2 python-dotenv==1.0.0 httpx==0.25.2 pandas==2.1.3 numpy==1.26.2 - [ ] Criar
.env.example - [ ] Criar
main.py(FastAPI app) - [ ] Criar
app/__init__.py - [ ] Criar
app/settings.py - [ ] Criar
app/database.py
Fase 2: Schema SQL
- [ ] Criar
sql/schema.sql - [ ] Criar tabela
channel_performance_insights - [ ] Criar tabela
channel_performance_metrics - [ ] Criar tabela
channel_policy_proposals - [ ] Criar índices
- [ ] Executar no RDS DEV
- [ ] Criar
sql/views.sqlcom views agregadas
Fase 3: Modelos Python
- [ ] Criar
app/models.py - [ ]
InsightTypeEnum - [ ]
SeverityEnum - [ ]
SuggestedActionEnum - [ ]
PerformanceInsight - [ ]
PolicyProposal - [ ]
ChannelMetrics - [ ]
TrendData - [ ]
AnalysisRequest
Fase 4: Repository (Queries)
- [ ] Criar
app/repository.py - [ ]
save_insight(insight) - [ ]
get_insights(filters) - [ ]
get_insight_by_id(id) - [ ]
update_insight_status(id, status) - [ ]
save_metrics(date, metrics) - [ ]
get_metrics(period) - [ ]
get_trends(metric, days) - [ ]
save_proposal(proposal) - [ ]
get_pending_proposals()
Fase 5: Data Collectors
- [ ] Criar
app/collectors/__init__.py - [ ] Criar
app/collectors/state_collector.py - [ ]
collect_state_distribution() - [ ]
collect_state_transitions(period) - [ ] Criar
app/collectors/onboarding_collector.py - [ ]
collect_onboarding_metrics(period) - [ ]
collect_activation_rates() - [ ] Criar
app/collectors/reactivation_collector.py - [ ]
collect_reactivation_metrics(period) - [ ]
collect_strategy_effectiveness() - [ ] Criar
app/collectors/revenue_collector.py - [ ]
collect_revenue_metrics(period) - [ ]
collect_margin_trends()
Fase 6: Analyzers (Detectores de Padrões)
- [ ] Criar
app/analyzers/__init__.py - [ ] Criar
app/analyzers/onboarding_analyzer.py - [ ]
analyze_onboarding_patterns()- padrões de sucesso/falha - [ ]
detect_kit_effectiveness()- quais kits funcionam - [ ]
detect_region_patterns()- variações por região - [ ] Criar
app/analyzers/reactivation_analyzer.py - [ ]
analyze_strategy_effectiveness() - [ ]
detect_discount_patterns()- impacto de descontos - [ ]
detect_reincidence_patterns()- quem volta a parar - [ ] Criar
app/analyzers/state_analyzer.py - [ ]
analyze_state_flows()- fluxos de transição - [ ]
detect_bottlenecks()- onde trava - [ ]
predict_churn_risk()- risco de churn - [ ] Criar
app/analyzers/policy_analyzer.py - [ ]
detect_policy_gaps()- lacunas - [ ]
detect_excessive_exceptions()- exceções demais - [ ]
detect_misalignments()- desalinhamentos
Fase 7: Insight Generator
- [ ] Criar
app/insight_generator.py - [ ]
generate_insights()- gerar todos os insights - [ ]
classify_insight(data)- classificar tipo e severidade - [ ]
generate_recommendation(insight)- sugestão de ação - [ ]
estimate_impact(insight)- impacto estimado
Fase 8: Proposal Generator
- [ ] Criar
app/proposal_generator.py - [ ]
generate_policy_proposal(insight)- proposta de mudança - [ ]
calculate_expected_impact(proposal)- impacto esperado - [ ]
generate_experiment_plan(proposal)- plano de teste
Fase 9: Routes/API
- [ ] Criar
routes/__init__.py - [ ] Criar
routes/core.py - [ ]
GET /- info - [ ]
GET /health- health check - [ ] Criar
routes/performance.py - [ ]
GET /v1/performance/insights- listar insights - [ ]
GET /v1/performance/insights/{id}- detalhe - [ ]
POST /v1/performance/insights/{id}/action- ação sobre insight - [ ]
GET /v1/performance/metrics- métricas atuais - [ ]
GET /v1/performance/metrics/history- histórico - [ ]
GET /v1/performance/trends/{metric}- tendências - [ ]
GET /v1/performance/proposals- propostas pendentes - [ ]
POST /v1/performance/proposals/{id}/approve- aprovar - [ ]
POST /v1/performance/proposals/{id}/reject- rejeitar - [ ]
POST /v1/performance/analyze- disparar análise - [ ]
GET /v1/performance/dashboard- dados para dashboard
Fase 10: Scheduled Tasks
- [ ] Criar
app/scheduler.py - [ ] Coleta diária de métricas (todo dia às 6h)
- [ ] Análise semanal de insights (toda segunda às 8h)
- [ ] Geração de propostas mensal
Fase 11: Docker
- [ ] Criar
Dockerfile - [ ] Criar
docker-stack.yml - [ ] Criar
deploy.sh - [ ] Build local e testar
Fase 12: Deploy DEV
- [ ] Adicionar ao
docker-stack-dev.ymlprincipal - [ ] Configurar secrets
- [ ] Deploy em DEV
- [ ] Testar endpoints via curl
- [ ] Verificar logs
Fase 13: Integração Seller Cockpit (Backend)
- [ ] Criar
seller-cockpit/backend/src/services/performance.service.js - [ ] Adicionar métodos:
- [ ]
getInsights(filters) - [ ]
getMetrics() - [ ]
getTrends(metric, period) - [ ]
getDashboardData()
Fase 14: Integração Seller Cockpit (Frontend)
- [ ] Criar nova página
pages/PerformancePage.jsx - [ ] Criar componentes:
- [ ]
components/performance/InsightCard.jsx - [ ]
components/performance/MetricsOverview.jsx - [ ]
components/performance/TrendChart.jsx - [ ]
components/performance/ProposalCard.jsx - [ ] Adicionar rota
/performanceno App - [ ] Adicionar link no menu lateral
Fase 15: Documentação
- [ ] Criar
README.mdcompleto - [ ] Documentar API endpoints
- [ ] Documentar tipos de insights
- [ ] Documentar métricas
- [ ] Atualizar
AGENTS_OVERVIEW.md
Fase 16: Testes
- [ ] Testar coleta de métricas
- [ ] Testar geração de insights
- [ ] Testar classificação
- [ ] Testar propostas
- [ ] Testar visualização no Seller Cockpit
📁 Estrutura de Arquivos
channel-performance/
├── .env.example
├── Dockerfile
├── README.md
├── deploy.sh
├── docker-stack.yml
├── main.py
├── requirements.txt
├── app/
│ ├── __init__.py
│ ├── database.py
│ ├── insight_generator.py
│ ├── models.py
│ ├── proposal_generator.py
│ ├── repository.py
│ ├── scheduler.py
│ ├── settings.py
│ ├── analyzers/
│ │ ├── __init__.py
│ │ ├── onboarding_analyzer.py
│ │ ├── policy_analyzer.py
│ │ ├── reactivation_analyzer.py
│ │ └── state_analyzer.py
│ └── collectors/
│ ├── __init__.py
│ ├── onboarding_collector.py
│ ├── reactivation_collector.py
│ ├── revenue_collector.py
│ └── state_collector.py
├── routes/
│ ├── __init__.py
│ ├── core.py
│ └── performance.py
└── sql/
├── schema.sql
└── views.sql
🔌 API Endpoints
| Método | Endpoint | Descrição |
|---|---|---|
| GET | / |
Info do serviço |
| GET | /health |
Health check |
| GET | /v1/performance/insights |
Listar insights |
| GET | /v1/performance/insights/{id} |
Detalhe do insight |
| POST | /v1/performance/insights/{id}/action |
Ação sobre insight |
| GET | /v1/performance/metrics |
Métricas atuais |
| GET | /v1/performance/metrics/history |
Histórico de métricas |
| GET | /v1/performance/trends/{metric} |
Tendências |
| GET | /v1/performance/proposals |
Propostas pendentes |
| POST | /v1/performance/proposals/{id}/approve |
Aprovar proposta |
| POST | /v1/performance/proposals/{id}/reject |
Rejeitar proposta |
| POST | /v1/performance/analyze |
Disparar análise |
| GET | /v1/performance/dashboard |
Dados para dashboard |
📊 Schema SQL Principal
CREATE TABLE IF NOT EXISTS channel_performance_insights (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
org_id INT NOT NULL DEFAULT 1,
-- Classification
insight_type ENUM('POLICY_GAP', 'POLICY_TOO_RESTRICTIVE', 'POLICY_TOO_LAX', 'EXECUTION_DRIFT', 'CHANNEL_MISALIGNMENT') NOT NULL,
severity ENUM('LOW', 'MEDIUM', 'HIGH', 'CRITICAL') NOT NULL,
category VARCHAR(50), -- onboarding, reactivation, pricing, etc
-- Context
affected_segment VARCHAR(100),
affected_region VARCHAR(50),
affected_policy VARCHAR(100),
-- Analysis
title VARCHAR(255) NOT NULL,
observation TEXT NOT NULL,
evidence JSON, -- dados que suportam o insight
impact_estimate JSON, -- impacto estimado
-- Recommendation
recommendation TEXT,
suggested_action ENUM('ADJUST_PARAMETER', 'CHANGE_POLICY', 'RUN_EXPERIMENT', 'ESCALATE', 'MONITOR'),
suggested_params JSON,
-- Status
status ENUM('NEW', 'REVIEWED', 'IN_PROGRESS', 'IMPLEMENTED', 'DISMISSED') DEFAULT 'NEW',
reviewed_by VARCHAR(50),
reviewed_at DATETIME,
implementation_notes TEXT,
-- Period
analysis_period_start DATE,
analysis_period_end DATE,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_type (insight_type),
INDEX idx_severity (severity),
INDEX idx_status (status),
INDEX idx_category (category)
);
CREATE TABLE IF NOT EXISTS channel_performance_metrics (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
org_id INT NOT NULL DEFAULT 1,
period_date DATE NOT NULL,
period_type ENUM('DAILY', 'WEEKLY', 'MONTHLY') NOT NULL,
-- Onboarding Metrics
onboarding_started INT DEFAULT 0,
onboarding_completed INT DEFAULT 0,
onboarding_failed INT DEFAULT 0,
onboarding_rate DECIMAL(5,2),
avg_activation_days DECIMAL(5,1),
-- Reactivation Metrics
reactivation_attempts INT DEFAULT 0,
reactivation_won INT DEFAULT 0,
reactivation_lost INT DEFAULT 0,
reactivation_rate DECIMAL(5,2),
avg_reactivation_cost DECIMAL(10,2),
reincidence_rate DECIMAL(5,2),
-- State Distribution
accounts_new INT DEFAULT 0,
accounts_activating INT DEFAULT 0,
accounts_active INT DEFAULT 0,
accounts_stalled INT DEFAULT 0,
accounts_at_risk INT DEFAULT 0,
accounts_churned INT DEFAULT 0,
-- Transitions
transitions_to_active INT DEFAULT 0,
transitions_to_stalled INT DEFAULT 0,
transitions_to_churn INT DEFAULT 0,
-- Revenue Metrics
total_revenue DECIMAL(15,2) DEFAULT 0,
avg_margin DECIMAL(5,2),
revenue_from_new DECIMAL(15,2) DEFAULT 0,
revenue_from_reactivated DECIMAL(15,2) DEFAULT 0,
-- Quality
avg_health_score DECIMAL(5,1),
exceptions_count INT DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uk_period (org_id, period_date, period_type),
INDEX idx_date (period_date)
);
CREATE TABLE IF NOT EXISTS channel_policy_proposals (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
org_id INT NOT NULL DEFAULT 1,
insight_id BIGINT,
-- Proposal
title VARCHAR(255) NOT NULL,
description TEXT NOT NULL,
affected_policy VARCHAR(100),
-- Current vs Proposed
current_value JSON,
proposed_value JSON,
-- Impact
expected_impact TEXT,
impact_metrics JSON,
risk_assessment TEXT,
-- Experiment Plan
experiment_plan JSON,
experiment_duration_days INT,
-- Status
status ENUM('DRAFT', 'PENDING_REVIEW', 'APPROVED', 'REJECTED', 'IMPLEMENTED') DEFAULT 'DRAFT',
approved_by VARCHAR(50),
approved_at DATETIME,
rejection_reason TEXT,
implemented_at DATETIME,
implementation_results JSON,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_status (status),
INDEX idx_insight (insight_id),
FOREIGN KEY (insight_id) REFERENCES channel_performance_insights(id)
);
🎨 UI no Seller Cockpit
Nova Página: Performance
┌────────────────────────────────────────────────────────────┐
│ 📊 Performance do Canal Esta Semana │
├────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Onboarding │ │ Reativação │ │ Crescimento │ │
│ │ 78% │ │ 45% │ │ +12% │ │
│ │ ━━━━━━░ │ │ ━━━░░░ │ │ ▲ │ │
│ │ ↑ vs sem. │ │ ↓ vs sem. │ │ bom │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
│ 💡 Insights (3 novos) [Ver todos] │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ 🔴 CRITICAL: Onboarding falha 40% na região Norte │ │
│ │ Sugestão: Revisar kit inicial para a região │ │
│ ├────────────────────────────────────────────────────────┤ │
│ │ 🟠 HIGH: Desconto > 8% em reativação aumenta churn │ │
│ │ Sugestão: Reduzir limite máximo de desconto │ │
│ ├────────────────────────────────────────────────────────┤ │
│ │ 🟡 MEDIUM: SKU X tem exceções frequentes │ │
│ │ Sugestão: Revisar política de preço │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ 📈 Tendências │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ [GRÁFICO DE LINHA] │ │
│ │ Taxa de Ativação vs Reativação (últimos 30 dias) │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ 📋 Propostas Pendentes (1) │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ Ajustar limite de desconto em reativação: 8% → 5% │ │
│ │ Impacto esperado: -20% reincidência, -R$ 5k custo │ │
│ │ [✅ Aprovar] [❌ Rejeitar] │ │
│ └────────────────────────────────────────────────────────┘ │
└────────────────────────────────────────────────────────────┘
📊 Exemplos de Insights Gerados
Insight 1: Padrão de Onboarding
{
"type": "POLICY_GAP",
"severity": "HIGH",
"category": "onboarding",
"title": "Kit B tem 2x mais sucesso que Kit A na região Norte",
"observation": "Análise de 120 onboardings nos últimos 60 dias mostra que revendas iniciadas com Kit B ativam em 15 dias em média, vs 32 dias com Kit A",
"evidence": {
"kit_a_activation_rate": 0.45,
"kit_b_activation_rate": 0.78,
"sample_size": 120
},
"recommendation": "Alterar política de onboarding: Kit B deve ser padrão para região Norte",
"suggested_action": "CHANGE_POLICY"
}
Insight 2: Padrão de Reativação
{
"type": "POLICY_TOO_LAX",
"severity": "CRITICAL",
"category": "reactivation",
"title": "Descontos > 8% aumentam churn em 90 dias",
"observation": "Reativações com desconto > 8% têm 45% de reincidência em 90 dias, vs 12% para descontos <= 5%",
"evidence": {
"high_discount_reincidence": 0.45,
"low_discount_reincidence": 0.12,
"cost_difference": 15000
},
"recommendation": "Reduzir limite máximo de desconto em reativação de 10% para 5%",
"suggested_action": "ADJUST_PARAMETER"
}
✅ Critérios de Conclusão
- [ ] Coleta de métricas funcionando (diária)
- [ ] Análise gerando insights relevantes
- [ ] Insights classificados corretamente
- [ ] Propostas sendo geradas
- [ ] Workflow de aprovação funcionando
- [ ] Dashboard visível no Seller Cockpit
- [ ] Gráficos de tendência funcionando
- [ ] README completo
- [ ] Deploy em DEV funcionando
Atualizado: 2026-01-24