Files
B2BCall-dialer/packages/database/prisma/migrations/20260828164734_cdr/migration.sql
Matheus 56499f4b99 feat(cdr): call detail records, relatorios e disposicoes
Fecha agente.md secao 152-160. Registro duravel de chamadas — ate aqui o
estado de uma chamada so' vivia transitoriamente no canal Redis
b2bcall:events (pub/sub sem historico).

## Modelo

calls/call_legs/call_events (secao 153, tenant-scoped, RLS) +
dispositions (secao 89, "Call Center -> Disposicoes", personalizavel por
tenant, mesmo padrao de PauseReason). dial_attempts da especificacao nao
virou tabela nova — CallAttempt (fase Predictive Engine) ja cobre esse
conceito; Call.attemptId liga um Call a' sua tentativa de discagem.
Call.id = o proprio freeswitch_uuid da perna principal (sem suporte a
transferencia entre uuids nesta fase).

## apps/freeswitch-events/src/cdr.ts

Cada NormalizedEvent relevante faz upsert em Call + insere em call_events
(a trilha bruta). CALL_ENDED calcula os agregados em segundos (secao
155-156): ringTime/waitTime/talkTime/durationSeconds/billableSeconds.

## Dois bugs reais achados e corrigidos testando esta fase

- AGENT_OFFERED_CALL/AGENT_BRIDGE_FAILED disparam de uma thread interna
  do mod_callcenter (outbound_agent_thread_run), sem contexto de channel
  — nao tem header Unique-ID, entao callUuid ficava undefined e os dois
  eram descartados silenciosamente (Call.queueId/agentId nunca
  preenchidos mesmo com bridge/falha de bridge reais). Corrigido com
  fallback pro CC-Member-Session-UUID (data.memberSessionUuid), mesmo
  identificador ja usado pra correlacao equivalente no predictive-dialer.
- Corrida entre CALL_CREATED/CALL_ANSWERED (persistCallEvent roda sem
  await, cada evento abre sua propria transacao) podia fazer answerAt
  aparecer antes de createdAt quando o upsert que criava a linha usava
  now() do momento errado (nao do occurredAt do evento real). Corrigido
  setando createdAt explicito a partir de normalized.occurredAt.

## Relatorios (apps/api/src/reports)

GET /reports/queues (secao 159): recebidas/atendidas/abandonadas/TME/TMA/
Service Level/Abandon Rate por fila. GET /reports/agents (secao 158):
tempo logado/pausado/por estado (AgentStateEvent pareado) + chamadas
atendidas/TMA. GET /reports/campaigns (secao 160): leads/attempts/
answered/agent connected/busy/no answer/failed/callbacks/rates/TME/TMA —
"Valor Telefonia"/"Valor IA" ficam null (dependem de Billing, fase
propria).

## GET /calls e disposicao

Secao 157: filtros por data/ramal/agente/fila/campanha/trunk/telefone/
hangup cause/disposicao, sempre escopado ao tenant do JWT. PATCH
/calls/:id/disposition (secao 89): o proprio agente que atendeu marca
(compara Call.agentId contra o Agent do usuario autenticado, nunca um
agentId vindo do client), supervisor (agents.manage) pode marcar em nome
de outro agente.

Verificado ponta a ponta: campanha com 5 leads, 3 ANSWERED simulados
entrando na fila real, Call.queueId/agentId/hangupCause corretos
(confirmando a correcao da correlacao), createdAt<=answerAt em todos,
durationSeconds batendo com discard_abandoned_after; os 3 relatorios com
numeros internamente consistentes entre si e com os logs do discador
(received:3/abandoned:3/abandonRate:1, leads:5/attempts:5/answered:3/
answerRate:0.6); disposicao gravada com ownership check correto;
queue list do FreeSWITCH confirmou calls_abandoned=4 real ao final.

typecheck do workspace inteiro limpo.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X1HxY46WGU4G1zmVDNKcWw
2026-08-28 14:10:16 -03:00

167 lines
6.3 KiB
SQL

-- CreateEnum
CREATE TYPE "call_direction" AS ENUM ('INBOUND', 'OUTBOUND', 'INTERNAL');
-- CreateTable
CREATE TABLE "dispositions" (
"id" UUID NOT NULL,
"tenant_id" UUID NOT NULL,
"name" TEXT NOT NULL,
"code" TEXT NOT NULL,
"enabled" BOOLEAN NOT NULL DEFAULT true,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "dispositions_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "calls" (
"id" UUID NOT NULL,
"tenant_id" UUID NOT NULL,
"attempt_id" UUID,
"freeswitch_uuid" UUID NOT NULL,
"sip_call_id" TEXT,
"direction" "call_direction" NOT NULL DEFAULT 'INTERNAL',
"campaign_id" UUID,
"lead_id" UUID,
"queue_id" UUID,
"agent_id" UUID,
"extension_id" UUID,
"trunk_id" UUID,
"caller_number" TEXT,
"called_number" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"progress_at" TIMESTAMP(3),
"answer_at" TIMESTAMP(3),
"queue_enter_at" TIMESTAMP(3),
"agent_answer_at" TIMESTAMP(3),
"bridge_at" TIMESTAMP(3),
"end_at" TIMESTAMP(3),
"ring_time" INTEGER,
"wait_time" INTEGER,
"talk_time" INTEGER,
"duration_seconds" INTEGER,
"billable_seconds" INTEGER,
"hangup_cause" TEXT,
"disposition_id" UUID,
CONSTRAINT "calls_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "call_legs" (
"id" UUID NOT NULL,
"tenant_id" UUID NOT NULL,
"call_id" UUID NOT NULL,
"freeswitch_uuid" UUID NOT NULL,
"role" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"answered_at" TIMESTAMP(3),
"ended_at" TIMESTAMP(3),
"hangup_cause" TEXT,
CONSTRAINT "call_legs_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "call_events" (
"id" UUID NOT NULL,
"tenant_id" UUID NOT NULL,
"call_id" UUID NOT NULL,
"type" TEXT NOT NULL,
"occurred_at" TIMESTAMP(3) NOT NULL,
"data" JSONB NOT NULL DEFAULT '{}',
CONSTRAINT "call_events_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "dispositions_tenant_id_idx" ON "dispositions"("tenant_id");
-- CreateIndex
CREATE UNIQUE INDEX "dispositions_tenant_id_code_key" ON "dispositions"("tenant_id", "code");
-- CreateIndex
CREATE INDEX "calls_tenant_id_created_at_idx" ON "calls"("tenant_id", "created_at");
-- CreateIndex
CREATE INDEX "calls_tenant_id_queue_id_idx" ON "calls"("tenant_id", "queue_id");
-- CreateIndex
CREATE INDEX "calls_tenant_id_agent_id_idx" ON "calls"("tenant_id", "agent_id");
-- CreateIndex
CREATE INDEX "calls_tenant_id_campaign_id_idx" ON "calls"("tenant_id", "campaign_id");
-- CreateIndex
CREATE INDEX "call_legs_tenant_id_call_id_idx" ON "call_legs"("tenant_id", "call_id");
-- CreateIndex
CREATE UNIQUE INDEX "call_legs_freeswitch_uuid_key" ON "call_legs"("freeswitch_uuid");
-- CreateIndex
CREATE INDEX "call_events_tenant_id_call_id_occurred_at_idx" ON "call_events"("tenant_id", "call_id", "occurred_at");
-- AddForeignKey
ALTER TABLE "dispositions" ADD CONSTRAINT "dispositions_tenant_id_fkey" FOREIGN KEY ("tenant_id") REFERENCES "tenants"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "calls" ADD CONSTRAINT "calls_tenant_id_fkey" FOREIGN KEY ("tenant_id") REFERENCES "tenants"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "calls" ADD CONSTRAINT "calls_attempt_id_fkey" FOREIGN KEY ("attempt_id") REFERENCES "call_attempts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "calls" ADD CONSTRAINT "calls_campaign_id_fkey" FOREIGN KEY ("campaign_id") REFERENCES "campaigns"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "calls" ADD CONSTRAINT "calls_lead_id_fkey" FOREIGN KEY ("lead_id") REFERENCES "leads"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "calls" ADD CONSTRAINT "calls_queue_id_fkey" FOREIGN KEY ("queue_id") REFERENCES "queues"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "calls" ADD CONSTRAINT "calls_agent_id_fkey" FOREIGN KEY ("agent_id") REFERENCES "agents"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "calls" ADD CONSTRAINT "calls_extension_id_fkey" FOREIGN KEY ("extension_id") REFERENCES "extensions"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "calls" ADD CONSTRAINT "calls_trunk_id_fkey" FOREIGN KEY ("trunk_id") REFERENCES "trunks"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "calls" ADD CONSTRAINT "calls_disposition_id_fkey" FOREIGN KEY ("disposition_id") REFERENCES "dispositions"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "call_legs" ADD CONSTRAINT "call_legs_tenant_id_fkey" FOREIGN KEY ("tenant_id") REFERENCES "tenants"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "call_legs" ADD CONSTRAINT "call_legs_call_id_fkey" FOREIGN KEY ("call_id") REFERENCES "calls"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "call_events" ADD CONSTRAINT "call_events_tenant_id_fkey" FOREIGN KEY ("tenant_id") REFERENCES "tenants"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "call_events" ADD CONSTRAINT "call_events_call_id_fkey" FOREIGN KEY ("call_id") REFERENCES "calls"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- Tabelas de negocio tenant-scoped: RLS obrigatorio em todas (ver docs/TENANT_ISOLATION.md).
ALTER TABLE "dispositions" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "dispositions" FORCE ROW LEVEL SECURITY;
CREATE POLICY "tenant_isolation" ON "dispositions"
USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid);
ALTER TABLE "calls" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "calls" FORCE ROW LEVEL SECURITY;
CREATE POLICY "tenant_isolation" ON "calls"
USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid);
ALTER TABLE "call_legs" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "call_legs" FORCE ROW LEVEL SECURITY;
CREATE POLICY "tenant_isolation" ON "call_legs"
USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid);
ALTER TABLE "call_events" ENABLE ROW LEVEL SECURITY;
ALTER TABLE "call_events" FORCE ROW LEVEL SECURITY;
CREATE POLICY "tenant_isolation" ON "call_events"
USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid);