feat(entitlements,campaigns): plans/quotas + campanhas, leads, lista de bloqueio
Fecha duas fases: Plans/Entitlements (agente.md secao 56-62), que tinha
ficado pra trás desde o inicio, e Campanhas/Leads/Lista de Bloqueio (secao
63-71).
## Plans/Entitlements
A ordem de implementacao da propria especificacao (secao 232) coloca
Plans/Entitlements logo depois de PostgreSQL RLS, bem antes de FreeSWITCH
— mas o build seguiu direto sem essa peca, e toda fase desde entao
documentou "quota depende de Plans/Entitlements" como pendencia
(EXTENSIONS.md, TRUNKS.md, AGENTS.md, QUEUES.md, agora todas atualizadas).
Fechado agora porque Campanhas precisa de max_campaigns e o proximo CPS
Limiter vai precisar de max_cps/max_concurrent_calls.
- plans: catalogo compartilhado entre tenants (sem RLS, nao e' tenant-
scoped) com todos os campos de entitlement da secao 56. Campo de limite
null = "sem limite", nunca "sem plano" — tenants.plan_id e' obrigatorio,
nunca null (secao 56: nao espalhar `if plan == PRO` pelo codigo).
- Migration hand-escrita: cria plans, insere seed "trial", faz backfill de
plan_id pros tenants ja existentes, so' depois torna NOT NULL (Postgres
nao deixa NOT NULL sem default em tabela nao-vazia).
- packages/entitlements (pacote novo): assertQuota/assertFeatureEnabled,
erros mapeados pra 403 no DomainExceptionFilter.
- Retrofit em Extensions/Trunks/Agents/Queues: contam linhas ativas e
checam quota antes de criar.
## Campanhas, Leads, Lista de Bloqueio
Deliberadamente so' o modelo/CRUD/maquina de estados — o motor que de fato
origina chamadas (PredictiveDialerEngine, secao 72-86: dados em tempo
real, EWMA, CPS distribuido, reserva atomica de lead, lock de campanha,
bgapi originate, controle de abandono, retry) e' um sistema grande o
suficiente pra merecer fase propria (secao 72: "nao e' so' `for lead ->
originate`").
- campaigns/leads/suppression_entries (tenant-scoped, RLS).
- Maquina de estados da campanha (secao 64-66): start/pause/drain/stop com
tabela de transicoes validas — transicao invalida retorna 400, nunca
ignora silenciosamente. Apagar bloqueado enquanto RUNNING/DRAINING.
- packages/shared/src/phone.ts (secao 70): normalizacao dedicada,
preparada pra E.164 completo, so' BR implementado.
- Importacao CSV em batches de 1000 (secao 69): detecta duplicado (dentro
do CSV + contra leads existentes), checa lista de bloqueio (importa como
DO_NOT_CALL, nao descarta), retorna {total, valid, invalid, duplicates,
imported, suppressed}.
- Lista de bloqueio (secao 71): CRUD tenant-scoped.
Verificado ponta a ponta: campanha com queueId/trunkId invalido e
pacingMin > pacingMax rejeitados; CSV de 5 linhas (1 invalida, 1
duplicada, 1 bloqueada) importado corretamente; start->pause->drain->stop
e transicoes invalidas todas corretas; 3a campanha rejeitada por quota
(max_campaigns=2 do plano trial); 6a extensao rejeitada por quota
(max_extensions=5). Suites de teste existentes (tenant-isolation, auth)
atualizadas pro novo Tenant.planId obrigatorio e passando.
typecheck do workspace inteiro limpo.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X1HxY46WGU4G1zmVDNKcWw
This commit is contained in:
@@ -11,6 +11,7 @@
|
||||
"dependencies": {
|
||||
"@b2bcall/auth": "workspace:*",
|
||||
"@b2bcall/database": "workspace:*",
|
||||
"@b2bcall/entitlements": "workspace:*",
|
||||
"@b2bcall/shared": "workspace:*",
|
||||
"@b2bcall/telephony": "workspace:*",
|
||||
"@fastify/cors": "11.3.0",
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
} from "@nestjs/common";
|
||||
import { getPrismaClient, withTenantContext } from "@b2bcall/database";
|
||||
import { recordAuditEvent, type AccessTokenClaims } from "@b2bcall/auth";
|
||||
import { assertQuota } from "@b2bcall/entitlements";
|
||||
import { JwtAuthGuard } from "../common/guards/jwt-auth.guard";
|
||||
import { PermissionGuard } from "../common/guards/permission.guard";
|
||||
import { RequirePermission } from "../common/decorators/require-permission.decorator";
|
||||
@@ -30,6 +31,11 @@ export class AgentsController {
|
||||
const prisma = getPrismaClient();
|
||||
const tenantId = user.tenantId!;
|
||||
|
||||
const activeCount = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.agent.count({ where: { tenantId, deletedAt: null } }),
|
||||
);
|
||||
await assertQuota(tenantId, "maxAgents", activeCount);
|
||||
|
||||
const agent = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.agent.create({
|
||||
data: {
|
||||
|
||||
@@ -8,6 +8,9 @@ import { QueuesModule } from "./queues/queues.module";
|
||||
import { AgentsModule } from "./agents/agents.module";
|
||||
import { PauseReasonsModule } from "./pause-reasons/pause-reasons.module";
|
||||
import { RealtimeModule } from "./realtime/realtime.module";
|
||||
import { CampaignsModule } from "./campaigns/campaigns.module";
|
||||
import { LeadsModule } from "./leads/leads.module";
|
||||
import { SuppressionModule } from "./suppression/suppression.module";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -20,6 +23,9 @@ import { RealtimeModule } from "./realtime/realtime.module";
|
||||
AgentsModule,
|
||||
PauseReasonsModule,
|
||||
RealtimeModule,
|
||||
CampaignsModule,
|
||||
LeadsModule,
|
||||
SuppressionModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
223
apps/api/src/campaigns/campaigns.controller.ts
Normal file
223
apps/api/src/campaigns/campaigns.controller.ts
Normal file
@@ -0,0 +1,223 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
NotFoundException,
|
||||
Param,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from "@nestjs/common";
|
||||
import { getPrismaClient, withTenantContext, type CampaignStatus } from "@b2bcall/database";
|
||||
import { recordAuditEvent, type AccessTokenClaims } from "@b2bcall/auth";
|
||||
import { assertQuota } from "@b2bcall/entitlements";
|
||||
import { JwtAuthGuard } from "../common/guards/jwt-auth.guard";
|
||||
import { PermissionGuard } from "../common/guards/permission.guard";
|
||||
import { RequirePermission } from "../common/decorators/require-permission.decorator";
|
||||
import { CurrentUser } from "../common/decorators/current-user.decorator";
|
||||
import { CreateCampaignDto } from "./dto/create-campaign.dto";
|
||||
|
||||
/**
|
||||
* Transições de status válidas (agente.md secao 64-66). O motor que de fato
|
||||
* origina chamadas em RUNNING (PredictiveDialerEngine) é uma fase à parte —
|
||||
* aqui só a máquina de estados e o CRUD.
|
||||
*/
|
||||
const ALLOWED_TRANSITIONS: Record<string, CampaignStatus[]> = {
|
||||
start: ["DRAFT", "READY", "PAUSED", "WAITING_SCHEDULE"],
|
||||
pause: ["RUNNING"],
|
||||
drain: ["RUNNING", "PAUSED"],
|
||||
stop: ["DRAFT", "READY", "WAITING_SCHEDULE", "RUNNING", "PAUSED", "DRAINING"],
|
||||
};
|
||||
|
||||
const TARGET_STATUS: Record<string, CampaignStatus> = {
|
||||
start: "RUNNING",
|
||||
pause: "PAUSED",
|
||||
drain: "DRAINING",
|
||||
stop: "STOPPED",
|
||||
};
|
||||
|
||||
@UseGuards(JwtAuthGuard, PermissionGuard)
|
||||
@Controller("campaigns")
|
||||
export class CampaignsController {
|
||||
@RequirePermission("campaigns.create")
|
||||
@Post()
|
||||
async create(@CurrentUser() user: AccessTokenClaims, @Body() dto: CreateCampaignDto) {
|
||||
const prisma = getPrismaClient();
|
||||
const tenantId = user.tenantId!;
|
||||
|
||||
const activeCount = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.campaign.count({ where: { tenantId, deletedAt: null } }),
|
||||
);
|
||||
await assertQuota(tenantId, "maxCampaigns", activeCount);
|
||||
|
||||
const [queue, trunk] = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
Promise.all([
|
||||
tx.queue.findFirst({ where: { id: dto.queueId, tenantId, deletedAt: null } }),
|
||||
tx.trunk.findFirst({ where: { id: dto.trunkId, tenantId, deletedAt: null } }),
|
||||
]),
|
||||
);
|
||||
if (!queue) throw new BadRequestException("Fila nao encontrada neste tenant");
|
||||
if (!trunk) throw new BadRequestException("Tronco nao encontrado neste tenant");
|
||||
|
||||
if (dto.pacingMin !== undefined && dto.pacingMax !== undefined && dto.pacingMin > dto.pacingMax) {
|
||||
throw new BadRequestException("pacingMin nao pode ser maior que pacingMax");
|
||||
}
|
||||
|
||||
const campaign = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.campaign.create({
|
||||
data: {
|
||||
tenantId,
|
||||
name: dto.name,
|
||||
description: dto.description,
|
||||
queueId: dto.queueId,
|
||||
trunkId: dto.trunkId,
|
||||
callerIdName: dto.callerIdName,
|
||||
callerIdNumber: dto.callerIdNumber,
|
||||
timezone: dto.timezone ?? "America/Sao_Paulo",
|
||||
startDate: dto.startDate,
|
||||
endDate: dto.endDate,
|
||||
daysOfWeek: dto.daysOfWeek ?? [],
|
||||
startTime: dto.startTime,
|
||||
endTime: dto.endTime,
|
||||
maxCps: dto.maxCps,
|
||||
maxConcurrentCalls: dto.maxConcurrentCalls,
|
||||
pacingInitial: dto.pacingInitial ?? 1.0,
|
||||
pacingMin: dto.pacingMin ?? 1.0,
|
||||
pacingMax: dto.pacingMax ?? 3.0,
|
||||
targetAbandonRate: dto.targetAbandonRate ?? 0.03,
|
||||
ringTimeout: dto.ringTimeout ?? 30,
|
||||
maxAttempts: dto.maxAttempts ?? 3,
|
||||
recordingEnabled: dto.recordingEnabled ?? false,
|
||||
avmdEnabled: dto.avmdEnabled ?? false,
|
||||
aiTranscriptionEnabled: dto.aiTranscriptionEnabled ?? false,
|
||||
aiAnalysisEnabled: dto.aiAnalysisEnabled ?? false,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await recordAuditEvent(prisma, {
|
||||
action: "CAMPAIGN_CREATE",
|
||||
tenantId,
|
||||
userId: user.sub,
|
||||
entityType: "campaign",
|
||||
entityId: campaign.id,
|
||||
after: { name: campaign.name },
|
||||
});
|
||||
|
||||
return campaign;
|
||||
}
|
||||
|
||||
@RequirePermission("campaigns.view")
|
||||
@Get()
|
||||
async list(@CurrentUser() user: AccessTokenClaims) {
|
||||
const prisma = getPrismaClient();
|
||||
const tenantId = user.tenantId!;
|
||||
return withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.campaign.findMany({ where: { deletedAt: null }, orderBy: { name: "asc" } }),
|
||||
);
|
||||
}
|
||||
|
||||
@RequirePermission("campaigns.view")
|
||||
@Get(":id")
|
||||
async get(@CurrentUser() user: AccessTokenClaims, @Param("id") id: string) {
|
||||
const prisma = getPrismaClient();
|
||||
const tenantId = user.tenantId!;
|
||||
const campaign = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.campaign.findFirst({ where: { id, deletedAt: null } }),
|
||||
);
|
||||
if (!campaign) throw new NotFoundException();
|
||||
return campaign;
|
||||
}
|
||||
|
||||
@RequirePermission("campaigns.start")
|
||||
@Post(":id/start")
|
||||
async start(@CurrentUser() user: AccessTokenClaims, @Param("id") id: string) {
|
||||
return this.transition(user, id, "start", "CAMPAIGN_START");
|
||||
}
|
||||
|
||||
@RequirePermission("campaigns.pause")
|
||||
@Post(":id/pause")
|
||||
async pause(@CurrentUser() user: AccessTokenClaims, @Param("id") id: string) {
|
||||
return this.transition(user, id, "pause", "CAMPAIGN_PAUSE");
|
||||
}
|
||||
|
||||
@RequirePermission("campaigns.stop")
|
||||
@Post(":id/drain")
|
||||
async drain(@CurrentUser() user: AccessTokenClaims, @Param("id") id: string) {
|
||||
return this.transition(user, id, "drain", "CAMPAIGN_DRAIN");
|
||||
}
|
||||
|
||||
@RequirePermission("campaigns.stop")
|
||||
@Post(":id/stop")
|
||||
async stop(@CurrentUser() user: AccessTokenClaims, @Param("id") id: string) {
|
||||
return this.transition(user, id, "stop", "CAMPAIGN_STOP");
|
||||
}
|
||||
|
||||
private async transition(
|
||||
user: AccessTokenClaims,
|
||||
id: string,
|
||||
action: keyof typeof TARGET_STATUS,
|
||||
auditAction: string,
|
||||
) {
|
||||
const prisma = getPrismaClient();
|
||||
const tenantId = user.tenantId!;
|
||||
|
||||
const campaign = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.campaign.findFirst({ where: { id, tenantId, deletedAt: null } }),
|
||||
);
|
||||
if (!campaign) throw new NotFoundException();
|
||||
|
||||
if (!ALLOWED_TRANSITIONS[action].includes(campaign.status)) {
|
||||
throw new BadRequestException(
|
||||
`Nao e' possivel "${action}" uma campanha em status ${campaign.status}`,
|
||||
);
|
||||
}
|
||||
|
||||
const updated = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.campaign.update({ where: { id }, data: { status: TARGET_STATUS[action] } }),
|
||||
);
|
||||
|
||||
await recordAuditEvent(prisma, {
|
||||
action: auditAction,
|
||||
tenantId,
|
||||
userId: user.sub,
|
||||
entityType: "campaign",
|
||||
entityId: id,
|
||||
before: { status: campaign.status },
|
||||
after: { status: updated.status },
|
||||
});
|
||||
|
||||
return { status: updated.status };
|
||||
}
|
||||
|
||||
@RequirePermission("campaigns.update")
|
||||
@Delete(":id")
|
||||
@HttpCode(HttpStatus.NO_CONTENT)
|
||||
async remove(@CurrentUser() user: AccessTokenClaims, @Param("id") id: string) {
|
||||
const prisma = getPrismaClient();
|
||||
const tenantId = user.tenantId!;
|
||||
|
||||
const campaign = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.campaign.findFirst({ where: { id, tenantId, deletedAt: null } }),
|
||||
);
|
||||
if (!campaign) throw new NotFoundException();
|
||||
if (campaign.status === "RUNNING" || campaign.status === "DRAINING") {
|
||||
throw new BadRequestException("Pare a campanha antes de apaga-la");
|
||||
}
|
||||
|
||||
await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.campaign.update({ where: { id }, data: { deletedAt: new Date() } }),
|
||||
);
|
||||
|
||||
await recordAuditEvent(prisma, {
|
||||
action: "CAMPAIGN_DELETE",
|
||||
tenantId,
|
||||
userId: user.sub,
|
||||
entityType: "campaign",
|
||||
entityId: id,
|
||||
});
|
||||
}
|
||||
}
|
||||
7
apps/api/src/campaigns/campaigns.module.ts
Normal file
7
apps/api/src/campaigns/campaigns.module.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { CampaignsController } from "./campaigns.controller";
|
||||
|
||||
@Module({
|
||||
controllers: [CampaignsController],
|
||||
})
|
||||
export class CampaignsModule {}
|
||||
138
apps/api/src/campaigns/dto/create-campaign.dto.ts
Normal file
138
apps/api/src/campaigns/dto/create-campaign.dto.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import {
|
||||
ArrayMaxSize,
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsDateString,
|
||||
IsInt,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
Matches,
|
||||
Max,
|
||||
MaxLength,
|
||||
Min,
|
||||
} from "class-validator";
|
||||
|
||||
export class CreateCampaignDto {
|
||||
@IsString()
|
||||
@MaxLength(120)
|
||||
name!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(500)
|
||||
description?: string;
|
||||
|
||||
@IsUUID()
|
||||
queueId!: string;
|
||||
|
||||
@IsUUID()
|
||||
trunkId!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(80)
|
||||
callerIdName?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Matches(/^[0-9]{2,20}$/)
|
||||
callerIdNumber?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(64)
|
||||
timezone?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
startDate?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
endDate?: string;
|
||||
|
||||
// 1=segunda ... 7=domingo (ISO-8601).
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ArrayMaxSize(7)
|
||||
@IsInt({ each: true })
|
||||
@Min(1, { each: true })
|
||||
@Max(7, { each: true })
|
||||
daysOfWeek?: number[];
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Matches(/^([01]\d|2[0-3]):[0-5]\d$/)
|
||||
startTime?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Matches(/^([01]\d|2[0-3]):[0-5]\d$/)
|
||||
endTime?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(1000)
|
||||
maxCps?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(100000)
|
||||
maxConcurrentCalls?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0.1)
|
||||
@Max(10)
|
||||
pacingInitial?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0.1)
|
||||
@Max(10)
|
||||
pacingMin?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0.1)
|
||||
@Max(10)
|
||||
pacingMax?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@Max(1)
|
||||
targetAbandonRate?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(5)
|
||||
@Max(120)
|
||||
ringTimeout?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(20)
|
||||
maxAttempts?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
recordingEnabled?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
avmdEnabled?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
aiTranscriptionEnabled?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
aiAnalysisEnabled?: boolean;
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
InvalidRefreshTokenError,
|
||||
NotATenantMemberError,
|
||||
} from "@b2bcall/auth";
|
||||
import { QuotaExceededError, FeatureNotEnabledError } from "@b2bcall/entitlements";
|
||||
|
||||
/**
|
||||
* Traduz erros de domínio de packages/auth para HTTP, sem nunca vazar stack
|
||||
@@ -43,6 +44,11 @@ export class DomainExceptionFilter implements ExceptionFilter {
|
||||
return;
|
||||
}
|
||||
|
||||
if (exception instanceof QuotaExceededError || exception instanceof FeatureNotEnabledError) {
|
||||
reply.status(HttpStatus.FORBIDDEN).send({ message: exception.message });
|
||||
return;
|
||||
}
|
||||
|
||||
console.error(exception);
|
||||
reply.status(HttpStatus.INTERNAL_SERVER_ERROR).send({ message: "Erro interno" });
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
import { getPrismaClient, withTenantContext } from "@b2bcall/database";
|
||||
import { generateStrongPassword, encryptSecret } from "@b2bcall/shared";
|
||||
import { recordAuditEvent, type AccessTokenClaims } from "@b2bcall/auth";
|
||||
import { assertQuota } from "@b2bcall/entitlements";
|
||||
import { JwtAuthGuard } from "../common/guards/jwt-auth.guard";
|
||||
import { PermissionGuard } from "../common/guards/permission.guard";
|
||||
import { RequirePermission } from "../common/decorators/require-permission.decorator";
|
||||
@@ -60,6 +61,11 @@ export class ExtensionsController {
|
||||
);
|
||||
}
|
||||
|
||||
const activeCount = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.extension.count({ where: { tenantId, deletedAt: null } }),
|
||||
);
|
||||
await assertQuota(tenantId, "maxExtensions", activeCount);
|
||||
|
||||
const plainPassword = generateStrongPassword();
|
||||
|
||||
const extension = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
|
||||
128
apps/api/src/leads/csv-import.ts
Normal file
128
apps/api/src/leads/csv-import.ts
Normal file
@@ -0,0 +1,128 @@
|
||||
import { normalizePhone } from "@b2bcall/shared";
|
||||
import { getPrismaClient, withTenantContext, type Prisma } from "@b2bcall/database";
|
||||
|
||||
export interface ImportSummary {
|
||||
total: number;
|
||||
valid: number;
|
||||
invalid: number;
|
||||
duplicates: number;
|
||||
imported: number;
|
||||
suppressed: number;
|
||||
}
|
||||
|
||||
/** Parser de CSV mínimo: separa por vírgula, aceita campos entre aspas com
|
||||
* vírgula/aspas escapada dentro (`""`) — não é RFC 4180 completo, mas cobre
|
||||
* o "formato mínimo" pedido (agente.md secao 69). */
|
||||
function parseCsvLine(line: string): string[] {
|
||||
const fields: string[] = [];
|
||||
let current = "";
|
||||
let inQuotes = false;
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const char = line[i];
|
||||
if (inQuotes) {
|
||||
if (char === '"' && line[i + 1] === '"') {
|
||||
current += '"';
|
||||
i++;
|
||||
} else if (char === '"') {
|
||||
inQuotes = false;
|
||||
} else {
|
||||
current += char;
|
||||
}
|
||||
} else if (char === '"') {
|
||||
inQuotes = true;
|
||||
} else if (char === ",") {
|
||||
fields.push(current.trim());
|
||||
current = "";
|
||||
} else {
|
||||
current += char;
|
||||
}
|
||||
}
|
||||
fields.push(current.trim());
|
||||
return fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Importa leads em streaming/batches (agente.md secao 69) — processa linha
|
||||
* a linha em vez de materializar tudo na memória antes de validar, e insere
|
||||
* em lotes (`createMany`). Detecta duplicados dentro do próprio CSV e
|
||||
* contra leads já existentes na campanha (mesmo `phoneNormalized`); leads
|
||||
* que batem na lista de bloqueio do tenant (secao 71) são importados já
|
||||
* como `DO_NOT_CALL`, não descartados — fica registrado, só não é discado.
|
||||
*/
|
||||
export async function importLeadsFromCsv(
|
||||
tenantId: string,
|
||||
campaignId: string,
|
||||
csv: string,
|
||||
): Promise<ImportSummary> {
|
||||
const prisma = getPrismaClient();
|
||||
|
||||
const lines = csv.split(/\r?\n/).filter((line) => line.trim().length > 0);
|
||||
if (lines.length === 0) {
|
||||
return { total: 0, valid: 0, invalid: 0, duplicates: 0, imported: 0, suppressed: 0 };
|
||||
}
|
||||
|
||||
const header = parseCsvLine(lines[0]).map((h) => h.toLowerCase());
|
||||
const nameIdx = header.findIndex((h) => h === "nome" || h === "name");
|
||||
const phoneIdx = header.findIndex((h) => h === "telefone" || h === "phone");
|
||||
if (phoneIdx === -1) {
|
||||
throw new Error('CSV precisa de uma coluna "telefone" (ou "phone") no cabecalho');
|
||||
}
|
||||
const dataLines = lines.slice(1);
|
||||
|
||||
const [existingPhones, suppressed] = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
Promise.all([
|
||||
tx.lead.findMany({ where: { campaignId, tenantId }, select: { phoneNormalized: true } }),
|
||||
tx.suppressionEntry.findMany({ where: { tenantId }, select: { phoneNormalized: true } }),
|
||||
]),
|
||||
);
|
||||
const seen = new Set(existingPhones.map((l) => l.phoneNormalized));
|
||||
const suppressedSet = new Set(suppressed.map((s) => s.phoneNormalized));
|
||||
|
||||
const summary: ImportSummary = { total: 0, valid: 0, invalid: 0, duplicates: 0, imported: 0, suppressed: 0 };
|
||||
const toInsert: Prisma.LeadCreateManyInput[] = [];
|
||||
|
||||
const BATCH_SIZE = 1000;
|
||||
for (const line of dataLines) {
|
||||
summary.total++;
|
||||
const fields = parseCsvLine(line);
|
||||
const phoneRaw = fields[phoneIdx];
|
||||
const name = nameIdx >= 0 ? fields[nameIdx] : undefined;
|
||||
|
||||
const normalized = phoneRaw ? normalizePhone(phoneRaw) : null;
|
||||
if (!normalized) {
|
||||
summary.invalid++;
|
||||
continue;
|
||||
}
|
||||
if (seen.has(normalized)) {
|
||||
summary.duplicates++;
|
||||
continue;
|
||||
}
|
||||
seen.add(normalized);
|
||||
summary.valid++;
|
||||
|
||||
const isSuppressed = suppressedSet.has(normalized);
|
||||
if (isSuppressed) summary.suppressed++;
|
||||
|
||||
toInsert.push({
|
||||
tenantId,
|
||||
campaignId,
|
||||
name: name || null,
|
||||
phoneOriginal: phoneRaw,
|
||||
phoneNormalized: normalized,
|
||||
status: isSuppressed ? "DO_NOT_CALL" : "NEW",
|
||||
});
|
||||
|
||||
if (toInsert.length >= BATCH_SIZE) {
|
||||
const batch = toInsert.splice(0, toInsert.length);
|
||||
await withTenantContext(prisma, tenantId, (tx) => tx.lead.createMany({ data: batch }));
|
||||
summary.imported += batch.length;
|
||||
}
|
||||
}
|
||||
|
||||
if (toInsert.length > 0) {
|
||||
await withTenantContext(prisma, tenantId, (tx) => tx.lead.createMany({ data: toInsert }));
|
||||
summary.imported += toInsert.length;
|
||||
}
|
||||
|
||||
return summary;
|
||||
}
|
||||
16
apps/api/src/leads/dto/create-lead.dto.ts
Normal file
16
apps/api/src/leads/dto/create-lead.dto.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { IsObject, IsOptional, IsString, MaxLength } from "class-validator";
|
||||
|
||||
export class CreateLeadDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
name?: string;
|
||||
|
||||
@IsString()
|
||||
@MaxLength(40)
|
||||
phone!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
customFields?: Record<string, unknown>;
|
||||
}
|
||||
10
apps/api/src/leads/dto/import-leads.dto.ts
Normal file
10
apps/api/src/leads/dto/import-leads.dto.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { IsString, MaxLength } from "class-validator";
|
||||
|
||||
export class ImportLeadsDto {
|
||||
// Formato minimo (agente.md secao 69): "nome,telefone" por linha, com
|
||||
// cabecalho. O wizard visual (Upload -> Preview -> Mapeamento -> ...) e'
|
||||
// fase Frontend — este endpoint recebe o CSV ja como texto no corpo.
|
||||
@IsString()
|
||||
@MaxLength(5_000_000)
|
||||
csv!: string;
|
||||
}
|
||||
174
apps/api/src/leads/leads.controller.ts
Normal file
174
apps/api/src/leads/leads.controller.ts
Normal file
@@ -0,0 +1,174 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
NotFoundException,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from "@nestjs/common";
|
||||
import { getPrismaClient, withTenantContext, type LeadStatus, type Prisma } from "@b2bcall/database";
|
||||
import { normalizePhone } from "@b2bcall/shared";
|
||||
import { recordAuditEvent, type AccessTokenClaims } from "@b2bcall/auth";
|
||||
import { JwtAuthGuard } from "../common/guards/jwt-auth.guard";
|
||||
import { PermissionGuard } from "../common/guards/permission.guard";
|
||||
import { RequirePermission } from "../common/decorators/require-permission.decorator";
|
||||
import { CurrentUser } from "../common/decorators/current-user.decorator";
|
||||
import { CreateLeadDto } from "./dto/create-lead.dto";
|
||||
import { ImportLeadsDto } from "./dto/import-leads.dto";
|
||||
import { importLeadsFromCsv } from "./csv-import";
|
||||
|
||||
const LEAD_STATUSES: LeadStatus[] = [
|
||||
"NEW",
|
||||
"READY",
|
||||
"RESERVED",
|
||||
"ORIGINATING",
|
||||
"RINGING",
|
||||
"ANSWERED",
|
||||
"QUEUEING",
|
||||
"CONNECTED_AGENT",
|
||||
"BUSY",
|
||||
"NO_ANSWER",
|
||||
"FAILED",
|
||||
"VOICEMAIL",
|
||||
"CALLBACK",
|
||||
"COMPLETED",
|
||||
"DO_NOT_CALL",
|
||||
"MAX_ATTEMPTS",
|
||||
];
|
||||
|
||||
async function findCampaignOrThrow(tenantId: string, campaignId: string) {
|
||||
const prisma = getPrismaClient();
|
||||
const campaign = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.campaign.findFirst({ where: { id: campaignId, tenantId, deletedAt: null } }),
|
||||
);
|
||||
if (!campaign) throw new NotFoundException("Campanha nao encontrada");
|
||||
return campaign;
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, PermissionGuard)
|
||||
@Controller("campaigns/:campaignId/leads")
|
||||
export class LeadsController {
|
||||
@RequirePermission("campaigns.update")
|
||||
@Post()
|
||||
async create(
|
||||
@CurrentUser() user: AccessTokenClaims,
|
||||
@Param("campaignId") campaignId: string,
|
||||
@Body() dto: CreateLeadDto,
|
||||
) {
|
||||
const prisma = getPrismaClient();
|
||||
const tenantId = user.tenantId!;
|
||||
await findCampaignOrThrow(tenantId, campaignId);
|
||||
|
||||
const normalized = normalizePhone(dto.phone);
|
||||
if (!normalized) {
|
||||
throw new BadRequestException("Telefone invalido");
|
||||
}
|
||||
|
||||
const suppressed = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.suppressionEntry.findFirst({ where: { tenantId, phoneNormalized: normalized } }),
|
||||
);
|
||||
|
||||
const lead = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.lead.create({
|
||||
data: {
|
||||
tenantId,
|
||||
campaignId,
|
||||
name: dto.name,
|
||||
phoneOriginal: dto.phone,
|
||||
phoneNormalized: normalized,
|
||||
status: suppressed ? "DO_NOT_CALL" : "NEW",
|
||||
customFields: (dto.customFields ?? {}) as Prisma.InputJsonValue,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await recordAuditEvent(prisma, {
|
||||
action: "LEAD_CREATE",
|
||||
tenantId,
|
||||
userId: user.sub,
|
||||
entityType: "lead",
|
||||
entityId: lead.id,
|
||||
});
|
||||
|
||||
return lead;
|
||||
}
|
||||
|
||||
@RequirePermission("campaigns.update")
|
||||
@Post("import")
|
||||
async import(
|
||||
@CurrentUser() user: AccessTokenClaims,
|
||||
@Param("campaignId") campaignId: string,
|
||||
@Body() dto: ImportLeadsDto,
|
||||
) {
|
||||
const prisma = getPrismaClient();
|
||||
const tenantId = user.tenantId!;
|
||||
await findCampaignOrThrow(tenantId, campaignId);
|
||||
|
||||
let summary;
|
||||
try {
|
||||
summary = await importLeadsFromCsv(tenantId, campaignId, dto.csv);
|
||||
} catch (err) {
|
||||
throw new BadRequestException(err instanceof Error ? err.message : "CSV invalido");
|
||||
}
|
||||
|
||||
await recordAuditEvent(prisma, {
|
||||
action: "LEAD_IMPORT",
|
||||
tenantId,
|
||||
userId: user.sub,
|
||||
entityType: "campaign",
|
||||
entityId: campaignId,
|
||||
after: summary as unknown as Prisma.InputJsonValue,
|
||||
});
|
||||
|
||||
return summary;
|
||||
}
|
||||
|
||||
@RequirePermission("campaigns.view")
|
||||
@Get()
|
||||
async list(
|
||||
@CurrentUser() user: AccessTokenClaims,
|
||||
@Param("campaignId") campaignId: string,
|
||||
@Query("status") status?: string,
|
||||
) {
|
||||
const prisma = getPrismaClient();
|
||||
const tenantId = user.tenantId!;
|
||||
await findCampaignOrThrow(tenantId, campaignId);
|
||||
|
||||
const statusFilter = LEAD_STATUSES.includes(status as LeadStatus) ? (status as LeadStatus) : undefined;
|
||||
if (status && !statusFilter) {
|
||||
throw new BadRequestException("status invalido");
|
||||
}
|
||||
|
||||
return withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.lead.findMany({
|
||||
where: { campaignId, tenantId, ...(statusFilter ? { status: statusFilter } : {}) },
|
||||
orderBy: { createdAt: "asc" },
|
||||
take: 500,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@RequirePermission("campaigns.update")
|
||||
@Delete(":leadId")
|
||||
@HttpCode(HttpStatus.NO_CONTENT)
|
||||
async remove(
|
||||
@CurrentUser() user: AccessTokenClaims,
|
||||
@Param("campaignId") campaignId: string,
|
||||
@Param("leadId") leadId: string,
|
||||
) {
|
||||
const prisma = getPrismaClient();
|
||||
const tenantId = user.tenantId!;
|
||||
await findCampaignOrThrow(tenantId, campaignId);
|
||||
|
||||
const result = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.lead.deleteMany({ where: { id: leadId, campaignId, tenantId } }),
|
||||
);
|
||||
if (result.count === 0) throw new NotFoundException();
|
||||
}
|
||||
}
|
||||
7
apps/api/src/leads/leads.module.ts
Normal file
7
apps/api/src/leads/leads.module.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { LeadsController } from "./leads.controller";
|
||||
|
||||
@Module({
|
||||
controllers: [LeadsController],
|
||||
})
|
||||
export class LeadsModule {}
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
} from "@nestjs/common";
|
||||
import { getPrismaClient, withTenantContext } from "@b2bcall/database";
|
||||
import { recordAuditEvent, type AccessTokenClaims } from "@b2bcall/auth";
|
||||
import { assertQuota } from "@b2bcall/entitlements";
|
||||
import { JwtAuthGuard } from "../common/guards/jwt-auth.guard";
|
||||
import { PermissionGuard } from "../common/guards/permission.guard";
|
||||
import { RequirePermission } from "../common/decorators/require-permission.decorator";
|
||||
@@ -34,6 +35,11 @@ export class QueuesController {
|
||||
const prisma = getPrismaClient();
|
||||
const tenantId = user.tenantId!;
|
||||
|
||||
const activeCount = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.queue.count({ where: { tenantId, deletedAt: null } }),
|
||||
);
|
||||
await assertQuota(tenantId, "maxQueues", activeCount);
|
||||
|
||||
const queue = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.queue.create({
|
||||
data: {
|
||||
|
||||
12
apps/api/src/suppression/dto/create-suppression-entry.dto.ts
Normal file
12
apps/api/src/suppression/dto/create-suppression-entry.dto.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { IsOptional, IsString, MaxLength } from "class-validator";
|
||||
|
||||
export class CreateSuppressionEntryDto {
|
||||
@IsString()
|
||||
@MaxLength(40)
|
||||
phone!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
reason?: string;
|
||||
}
|
||||
82
apps/api/src/suppression/suppression.controller.ts
Normal file
82
apps/api/src/suppression/suppression.controller.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
NotFoundException,
|
||||
Param,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from "@nestjs/common";
|
||||
import { getPrismaClient, withTenantContext } from "@b2bcall/database";
|
||||
import { normalizePhone } from "@b2bcall/shared";
|
||||
import { recordAuditEvent, type AccessTokenClaims } from "@b2bcall/auth";
|
||||
import { JwtAuthGuard } from "../common/guards/jwt-auth.guard";
|
||||
import { PermissionGuard } from "../common/guards/permission.guard";
|
||||
import { RequirePermission } from "../common/decorators/require-permission.decorator";
|
||||
import { CurrentUser } from "../common/decorators/current-user.decorator";
|
||||
import { CreateSuppressionEntryDto } from "./dto/create-suppression-entry.dto";
|
||||
|
||||
/**
|
||||
* Lista de bloqueio (agente.md secao 71) — "Discador -> Lista de Bloqueio".
|
||||
* A checagem obrigatória antes de qualquer originate é responsabilidade da
|
||||
* fase Predictive Engine/CPS Limiter; aqui só o CRUD.
|
||||
*/
|
||||
@UseGuards(JwtAuthGuard, PermissionGuard)
|
||||
@Controller("suppression")
|
||||
export class SuppressionController {
|
||||
@RequirePermission("campaigns.update")
|
||||
@Post()
|
||||
async create(@CurrentUser() user: AccessTokenClaims, @Body() dto: CreateSuppressionEntryDto) {
|
||||
const prisma = getPrismaClient();
|
||||
const tenantId = user.tenantId!;
|
||||
|
||||
const normalized = normalizePhone(dto.phone);
|
||||
if (!normalized) {
|
||||
throw new BadRequestException("Telefone invalido");
|
||||
}
|
||||
|
||||
const entry = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.suppressionEntry.upsert({
|
||||
where: { tenantId_phoneNormalized: { tenantId, phoneNormalized: normalized } },
|
||||
update: { reason: dto.reason },
|
||||
create: { tenantId, phoneNormalized: normalized, reason: dto.reason },
|
||||
}),
|
||||
);
|
||||
|
||||
await recordAuditEvent(prisma, {
|
||||
action: "SUPPRESSION_ENTRY_CREATE",
|
||||
tenantId,
|
||||
userId: user.sub,
|
||||
entityType: "suppression_entry",
|
||||
entityId: entry.id,
|
||||
});
|
||||
|
||||
return entry;
|
||||
}
|
||||
|
||||
@RequirePermission("campaigns.view")
|
||||
@Get()
|
||||
async list(@CurrentUser() user: AccessTokenClaims) {
|
||||
const prisma = getPrismaClient();
|
||||
const tenantId = user.tenantId!;
|
||||
return withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.suppressionEntry.findMany({ where: { tenantId }, orderBy: { createdAt: "desc" } }),
|
||||
);
|
||||
}
|
||||
|
||||
@RequirePermission("campaigns.update")
|
||||
@Delete(":id")
|
||||
@HttpCode(HttpStatus.NO_CONTENT)
|
||||
async remove(@CurrentUser() user: AccessTokenClaims, @Param("id") id: string) {
|
||||
const prisma = getPrismaClient();
|
||||
const tenantId = user.tenantId!;
|
||||
const result = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.suppressionEntry.deleteMany({ where: { id, tenantId } }),
|
||||
);
|
||||
if (result.count === 0) throw new NotFoundException();
|
||||
}
|
||||
}
|
||||
7
apps/api/src/suppression/suppression.module.ts
Normal file
7
apps/api/src/suppression/suppression.module.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { SuppressionController } from "./suppression.controller";
|
||||
|
||||
@Module({
|
||||
controllers: [SuppressionController],
|
||||
})
|
||||
export class SuppressionModule {}
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
import { getPrismaClient, withTenantContext } from "@b2bcall/database";
|
||||
import { encryptSecret } from "@b2bcall/shared";
|
||||
import { recordAuditEvent, type AccessTokenClaims } from "@b2bcall/auth";
|
||||
import { assertQuota } from "@b2bcall/entitlements";
|
||||
import { JwtAuthGuard } from "../common/guards/jwt-auth.guard";
|
||||
import { PermissionGuard } from "../common/guards/permission.guard";
|
||||
import { RequirePermission } from "../common/decorators/require-permission.decorator";
|
||||
@@ -72,6 +73,11 @@ export class TrunksController {
|
||||
const prisma = getPrismaClient();
|
||||
const tenantId = user.tenantId!;
|
||||
|
||||
const activeCount = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.trunk.count({ where: { tenantId, deletedAt: null } }),
|
||||
);
|
||||
await assertQuota(tenantId, "maxTrunks", activeCount);
|
||||
|
||||
const trunk = await withTenantContext(prisma, tenantId, (tx) =>
|
||||
tx.trunk.create({
|
||||
data: {
|
||||
|
||||
Reference in New Issue
Block a user