feat: Fase 9/10 — métricas, scripts operacionais, callback/wrap-up e aceite final
Fase 9 (segurança e produção): - GET /api/metrics: endpoint Prometheus com métricas reais (chamadas, agentes, filas, CPS por campanha), protegido por permissão - scripts/backup.sh, restore.sh, healthcheck.sh, install.sh, update.sh — testados contra o ambiente real (backup.sh e healthcheck.sh rodados de verdade; install.sh/update.sh validados por inspeção, ambiente atual já provisionado) - POST /api/agent-console/dispose: aplica disposição de chamada de verdade (lacuna deixada aberta desde a Fase 6), com ações CALLBACK (agenda retorno) e DO_NOT_CALL (suprime automaticamente) - apps/dialer-worker/src/callback-sweep.ts: reativa leads com callback vencido; GET /api/callbacks para consulta - apps/dialer-worker/src/wrap-up-sweep.ts: transição automática WRAP_UP -> AVAILABLE + despausa real na fila do Asterisk. Exigiu corrigir main.ts para conectar ao AMI mesmo em DIALER_SIMULATION=true (DIALER_SIMULATION deve impedir só originação de chamada, não ações administrativas de fila) - nftables revisado (sem alterações necessárias) - Documentação completa: INSTALL, OPERATIONS, BACKUP_RESTORE, SECURITY, DATABASE, API, ASTERISK, OPENSIPS (não implementado, motivo documentado), TROUBLESHOOTING - README.md e CHANGELOG.md reescritos Fase 10 (testes e aceite): - Quality gate completo executado: build/typecheck (7 workspaces), lint, 46 testes unitários, docker compose config/ps, healthcheck — tudo verde - Aceite de segurança (seção 92): 13 itens verificados ao vivo contra o sistema real, não só por inspeção de código - Aceite Asterisk (seção 93): os 5 comandos executados e documentados, comunicação API->AMI->Asterisk validada - docs/RELATORIO_FINAL.md: relatório final no formato da seção 96 Todos os fixtures de teste desta fase foram removidos/desativados ao final. Credenciais de acesso entregues separadamente em CREDENCIAIS.txt (fora do git, nunca versionado).
This commit is contained in:
29
apps/dialer-worker/src/callback-sweep.ts
Normal file
29
apps/dialer-worker/src/callback-sweep.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { PrismaClient } from '@b2bcall/database';
|
||||
import { logger } from './logger';
|
||||
|
||||
// Ativa callbacks agendados (agente.md seção 41) cujo horário chegou. O
|
||||
// lead fica em status CALLBACK enquanto aguarda (não elegível para
|
||||
// discagem — ver lead-repository.ts, que só reserva READY/BUSY/NO_ANSWER/
|
||||
// FAILED); ao vencer, volta para READY com next_attempt_at = agora, mesmo
|
||||
// caminho de qualquer retry normal. "completed" aqui significa "já foi
|
||||
// reenfileirado para discagem", não "a ligação de retorno aconteceu" — isso
|
||||
// é registrado depois via nova disposição, como qualquer outra tentativa.
|
||||
export async function activateDueCallbacks(prisma: PrismaClient): Promise<number> {
|
||||
const due = await prisma.callback.findMany({
|
||||
where: { completed: false, scheduledAt: { lte: new Date() } },
|
||||
});
|
||||
if (due.length === 0) return 0;
|
||||
|
||||
for (const callback of due) {
|
||||
await prisma.$transaction([
|
||||
prisma.lead.updateMany({
|
||||
where: { id: callback.leadId, status: 'CALLBACK' },
|
||||
data: { status: 'READY', nextAttemptAt: new Date() },
|
||||
}),
|
||||
prisma.callback.update({ where: { id: callback.id }, data: { completed: true } }),
|
||||
]);
|
||||
}
|
||||
|
||||
logger.info({ count: due.length }, 'Callbacks vencidos reativados para discagem');
|
||||
return due.length;
|
||||
}
|
||||
@@ -3,10 +3,13 @@ import Redis from 'ioredis';
|
||||
import { AsteriskTelephonyProvider } from '@b2bcall/telephony';
|
||||
import { CampaignWorker } from './campaign-worker';
|
||||
import { reconcileOrphanedAttempts } from './reconciliation';
|
||||
import { activateDueCallbacks } from './callback-sweep';
|
||||
import { completeExpiredWrapUps } from './wrap-up-sweep';
|
||||
import { logger } from './logger';
|
||||
|
||||
const TICK_INTERVAL_MS = 2000;
|
||||
const RECONCILE_INTERVAL_MS = 60_000;
|
||||
const SWEEP_INTERVAL_MS = 15_000;
|
||||
const DIALER_SIMULATION = process.env.DIALER_SIMULATION === 'true';
|
||||
|
||||
async function main() {
|
||||
@@ -23,13 +26,17 @@ async function main() {
|
||||
|
||||
if (DIALER_SIMULATION) {
|
||||
logger.warn('DIALER_SIMULATION=true — nenhuma chamada real será originada.');
|
||||
} else {
|
||||
try {
|
||||
await telephony.connect();
|
||||
logger.info('Conectado ao AMI do Asterisk.');
|
||||
} catch (err) {
|
||||
logger.error({ err }, 'Falha ao conectar ao AMI — tentará reconectar automaticamente.');
|
||||
}
|
||||
}
|
||||
// Conecta ao AMI mesmo em modo simulação: DIALER_SIMULATION só impede
|
||||
// originação real de chamadas (campaign-worker.ts), não ações
|
||||
// administrativas de fila (pause/unpause de wrap-up, QueueAdd/Remove)
|
||||
// que precisam refletir no Asterisk de verdade para o teste do console
|
||||
// do agente fazer sentido.
|
||||
try {
|
||||
await telephony.connect();
|
||||
logger.info('Conectado ao AMI do Asterisk.');
|
||||
} catch (err) {
|
||||
logger.error({ err }, 'Falha ao conectar ao AMI — tentará reconectar automaticamente.');
|
||||
}
|
||||
|
||||
const worker = new CampaignWorker(prisma, redis, telephony);
|
||||
@@ -65,6 +72,10 @@ async function main() {
|
||||
() => void reconcileOrphanedAttempts(prisma).catch((err) => logger.error({ err }, 'Erro na reconciliação')),
|
||||
RECONCILE_INTERVAL_MS,
|
||||
);
|
||||
const sweepInterval = setInterval(() => {
|
||||
void activateDueCallbacks(prisma).catch((err) => logger.error({ err }, 'Erro ativando callbacks'));
|
||||
void completeExpiredWrapUps(prisma, telephony).catch((err) => logger.error({ err }, 'Erro concluindo wrap-ups'));
|
||||
}, SWEEP_INTERVAL_MS);
|
||||
|
||||
const shutdown = async () => {
|
||||
if (!running) return;
|
||||
@@ -72,6 +83,7 @@ async function main() {
|
||||
logger.info('Encerrando dialer-worker...');
|
||||
clearInterval(interval);
|
||||
clearInterval(reconcileInterval);
|
||||
clearInterval(sweepInterval);
|
||||
telephony.disconnect();
|
||||
await redis.quit();
|
||||
await prisma.$disconnect();
|
||||
|
||||
55
apps/dialer-worker/src/wrap-up-sweep.ts
Normal file
55
apps/dialer-worker/src/wrap-up-sweep.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { PrismaClient } from '@b2bcall/database';
|
||||
import type { TelephonyProvider } from '@b2bcall/telephony';
|
||||
import { logger } from './logger';
|
||||
|
||||
const DEFAULT_WRAP_UP_SECONDS = 30;
|
||||
|
||||
// Transição automática WRAP_UP -> AVAILABLE (agente.md seção 39). Feita por
|
||||
// varredura periódica (não por timer em memória) para sobreviver a restart
|
||||
// do worker — mesmo padrão de reconciliation.ts. O tempo de wrap-up usado é
|
||||
// o maior configurado entre as filas do agente (default conservador se ele
|
||||
// não pertencer a nenhuma fila). Também desfaz a pausa de fila aplicada no
|
||||
// início do wrap-up (ver AgentConsoleService.dispose).
|
||||
export async function completeExpiredWrapUps(prisma: PrismaClient, telephony: TelephonyProvider): Promise<number> {
|
||||
const openWrapUps = await prisma.agentStateEvent.findMany({
|
||||
where: { state: 'WRAP_UP', endedAt: null },
|
||||
include: { agent: { include: { queues: { include: { queue: true } } } } },
|
||||
});
|
||||
if (openWrapUps.length === 0) return 0;
|
||||
|
||||
const now = Date.now();
|
||||
let completed = 0;
|
||||
|
||||
for (const event of openWrapUps) {
|
||||
const wrapUpSeconds =
|
||||
event.agent.queues.length > 0
|
||||
? Math.max(...event.agent.queues.map((m) => m.queue.wrapUpTime))
|
||||
: DEFAULT_WRAP_UP_SECONDS;
|
||||
|
||||
const elapsedMs = now - event.startedAt.getTime();
|
||||
if (elapsedMs < wrapUpSeconds * 1000) continue;
|
||||
|
||||
await prisma.$transaction([
|
||||
prisma.agentStateEvent.update({ where: { id: event.id }, data: { endedAt: new Date() } }),
|
||||
prisma.agentStateEvent.create({ data: { agentId: event.agentId, state: 'AVAILABLE' } }),
|
||||
]);
|
||||
|
||||
if (event.agent.currentExtension && telephony.isConnected()) {
|
||||
const iface = `PJSIP/${event.agent.currentExtension}`;
|
||||
for (const membership of event.agent.queues) {
|
||||
try {
|
||||
await telephony.queuePause({ interface: iface, queue: membership.queue.name, paused: false });
|
||||
} catch {
|
||||
// Inofensivo se já não estiver pausado.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
completed += 1;
|
||||
}
|
||||
|
||||
if (completed > 0) {
|
||||
logger.info({ count: completed }, 'Wrap-up concluído automaticamente para agentes elegíveis');
|
||||
}
|
||||
return completed;
|
||||
}
|
||||
Reference in New Issue
Block a user