✅ Checklist: Account State Agent
Status: � Implementado e Deployado em DEV
Prioridade: 1 (FUNDAÇÃO - outros agentes dependem deste)
Estimativa: 1-2 semanas
Progresso: ✅ Completo - Deploy funcionando em DEV
Implementado em: 2026-01-25
📋 Resumo
| Item | Valor |
|---|---|
| Código | account-state |
| Porta | 8020 |
| Database | csuite_context |
| Prefixo API | /v1/state |
| Traefik Path | /account-state/ |
🎯 Objetivo
Declarar o estado atual de cada conta/revenda baseado em dados objetivos. É o "batimento cardíaco" do canal - todos os outros agentes consomem esse estado.
📊 Estados
NEW → ACTIVATING → ACTIVE → STALLED → AT_RISK → CHURN
| Estado | Trigger | Ação Padrão |
|---|---|---|
NEW |
Cadastro | Iniciar Onboarding |
ACTIVATING |
1ª compra | Acompanhar |
ACTIVE |
2ª compra | Crescimento |
STALLED |
Inativo > ciclo × 1.5 | Reativação |
AT_RISK |
Stalled + contatos falharam | Urgente |
CHURN |
Sem resposta prolongada | Arquivar |
✅ Fases de Implementação
Fase 1: Estrutura Base ✅
- [x] Criar diretório
/c-suite/agents/account-state/ - [x] Criar
requirements.txt - [x] Criar
.env.example - [x] Criar
main.py(FastAPI app) - [x] Criar
app/__init__.py - [x] Criar
app/settings.py - [x] Criar
app/database.py
Fase 2: Schema SQL ✅
- [x] Criar
sql/schema.sql - [x] Criar tabela
channel_account_states - [x] Criar tabela
channel_state_history(log de transições) - [x] Criar índices
- [ ] Executar no RDS DEV
- [x] Criar
sql/views.sql(views de monitoramento)
Fase 3: Modelos Python ✅
- [x] Criar
app/models.py - [x]
AccountStateEnum - [x]
AccountStateData - [x]
EvaluateRequest - [x]
EvaluateResponse - [x]
StateHistoryEntry
Fase 4: Repository (Queries) ✅
- [x] Criar
app/repository.py - [x]
get_account_state(account_id) - [x]
upsert_account_state(account_id, state, health_score) - [x]
get_state_history(account_id, limit) - [x]
list_by_state(state, page, page_size) - [x]
get_state_summary()- contagem por estado - [x]
get_reactivation_candidates()- candidatos (was_active_before)
Fase 5: Heuristics (Lógica de Decisão) ✅
- [x] Criar
app/heuristics.py - [x]
calculate_state(account_data)- determina estado - [x]
calculate_health_score(account_data)- 0-100 - [x]
should_allow_transition(current, new)- anti-flap - [x]
get_transition_reason(old, new)- motivo
Fase 6: Routes/API ✅
- [x] Criar
routes/__init__.py - [x] Criar
routes/core.py - [x]
GET /- info - [x]
GET /health- health check - [x] Criar
routes/state.py - [x]
POST /v1/state/evaluate- avaliar/atualizar estado - [x]
POST /v1/state/evaluate/bulk- avaliar múltiplas - [x]
GET /v1/state/account/{account_id}- consultar - [x]
GET /v1/state/by-state/{state}- listar por estado - [x]
GET /v1/state/history/{account_id}- histórico - [x]
GET /v1/state/summary- dashboard - [x]
GET /v1/state/candidates/reactivation- para Reactivation Agent
Fase 7: Policies ✅
- [x] Criar
policies/__init__.py - [x] Criar
policies/transitions.py - [x] Regras de transição permitidas
- [x] Janelas mínimas (anti-flap)
- [x] Thresholds por estado
- [x] Cores e ícones para UI
Fase 8: Docker ✅
- [x] Criar
Dockerfile - [x] Criar
docker-stack.yml - [x] Criar
deploy.sh - [ ] Build local e testar
Fase 9: Deploy DEV ✅
- [x] Configurar docker-stack.yml com Traefik
- [x] Configurar secrets
- [x] Deploy em DEV
- [x] Testar endpoints via curl
- [x] Verificar logs
Fase 10: Integração Seller Cockpit (Backend) ✅
- [x] Criar
seller-cockpit/backend/src/services/state.service.js - [x] Adicionar métodos:
- [x]
getAccountState(accountId) - [x]
evaluateAccount(accountData) - [x]
getStateSummary() - [x]
getReactivationCandidates() - [x] Criar
seller-cockpit/backend/src/routes/state.routes.js - [x] Registrar rotas em
app.js - [ ] Atualizar
aggregator.service.jspara incluir estado nas actions
Fase 11: Integração Seller Cockpit (Frontend) ✅
- [x] Criar
services/state.service.js - [x] Criar componente
components/common/AccountStateBadge.jsx - [x] Criar componente
components/dashboard/StateSummaryCard.jsx - [x] Criar estilos para cada estado (cores)
- [ ] Adicionar badge em cada cliente no
InboxPage.jsx - [ ] Adicionar StateSummaryCard no
DashboardPage.jsx
Fase 12: Documentação ✅
- [x] Criar
README.mdcompleto - [x] Documentar API endpoints
- [x] Adicionar exemplos de uso
- [ ] Atualizar
AGENTS_OVERVIEW.md
Fase 13: Testes
- [x] Testar cada endpoint isoladamente
- [x] Testar fluxo completo de transição de estados
- [ ] Testar anti-flap
- [ ] Testar integração visual com Seller Cockpit
- [ ] Validar que badge aparece corretamente
📁 Estrutura de Arquivos
account-state/
├── .env.example
├── Dockerfile
├── README.md
├── deploy.sh
├── docker-stack.yml
├── main.py
├── requirements.txt
├── app/
│ ├── __init__.py
│ ├── database.py
│ ├── heuristics.py
│ ├── models.py
│ ├── repository.py
│ └── settings.py
├── policies/
│ ├── __init__.py
│ └── transitions.py
├── routes/
│ ├── __init__.py
│ ├── core.py
│ └── state.py
└── sql/
├── schema.sql
└── views.sql
🔌 API Endpoints
| Método | Endpoint | Descrição |
|---|---|---|
| GET | / |
Info do serviço |
| GET | /health |
Health check |
| POST | /v1/state/evaluate |
Avaliar e atualizar estado |
| GET | /v1/state/account/{id} |
Consultar estado de uma conta |
| GET | /v1/state/by-state/{state} |
Listar contas por estado |
| GET | /v1/state/history/{id} |
Histórico de transições |
| GET | /v1/state/summary |
Resumo (contagem por estado) |
| GET | /v1/state/candidates/reactivation |
Candidatos à reativação |
📊 Schema SQL Principal
CREATE TABLE IF NOT EXISTS channel_account_states (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
org_id INT NOT NULL DEFAULT 1,
account_id VARCHAR(100) NOT NULL,
account_type ENUM('customer', 'reseller', 'lead') NOT NULL DEFAULT 'customer',
-- State
current_state ENUM('NEW','ACTIVATING','ACTIVE','STALLED','AT_RISK','CHURN') NOT NULL,
previous_state ENUM('NEW','ACTIVATING','ACTIVE','STALLED','AT_RISK','CHURN'),
health_score INT DEFAULT 100 CHECK (health_score >= 0 AND health_score <= 100),
-- Metrics
last_order_at DATETIME,
last_contact_at DATETIME,
expected_cycle_days INT DEFAULT 30,
days_since_order INT,
failed_contact_attempts INT DEFAULT 0,
total_orders INT DEFAULT 0,
total_value DECIMAL(15,2) DEFAULT 0,
-- Timestamps
state_changed_at DATETIME NOT NULL,
evaluated_at DATETIME NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uk_account (org_id, account_id, account_type),
INDEX idx_state (current_state),
INDEX idx_health (health_score),
INDEX idx_stalled (current_state, days_since_order)
);
🎨 Cores dos Estados (Frontend)
.state-new { background: #3498db; } /* Azul */
.state-activating { background: #f39c12; } /* Amarelo */
.state-active { background: #27ae60; } /* Verde */
.state-stalled { background: #e67e22; } /* Laranja */
.state-at-risk { background: #e74c3c; } /* Vermelho */
.state-churn { background: #95a5a6; } /* Cinza */
✅ Critérios de Conclusão
- [ ] Todos os endpoints funcionando
- [ ] States transitando corretamente
- [ ] Anti-flap funcionando
- [ ] Badge visível no Seller Cockpit
- [ ] Resumo no Dashboard do Seller Cockpit
- [ ] README completo
- [ ] Deploy em DEV funcionando
Atualizado: 2026-01-24