Integra módulo de CRM (leads/opportunities); corrige 2 bugs reais do agente
- Wire LeadsModule/OpportunitiesModule em app.module.ts; adiciona os exports correspondentes ao barrel @eden/database. Bugs reais encontrados e corrigidos antes do commit (não pegos pelo próprio agente porque ele não tinha o módulo de auth disponível no worktree dele para testar de verdade — só stubado e revertido): 1. Os controllers de Leads/Opportunities liam `req.user?.id`, mas nosso JwtAuthGuard real popula `request.edenUser`, nunca `request.user` — todo evento de auditoria de lead/oportunidade estaria gravando actorId: null sempre, perdendo a atribuição de quem fez a ação. Trocado para o padrão real (@CurrentUser() + EdenAuthenticatedUser). 2. As chamadas appendAuditEvent() nos dois services omitiam o campo obrigatório `actorType` — corrigido para "user" em todas as 6 ocorrências. Também corrigidos: import de guards/decorators via um barrel "../auth" inexistente (trocado pelos caminhos reais), e os dois módulos não importavam AuthModule (necessário para o Nest resolver as dependências do JwtAuthGuard via DI). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -9,6 +9,8 @@ import { UsersModule } from "./users/users.module.js";
|
||||
import { RolesModule } from "./roles/roles.module.js";
|
||||
import { ProductsModule } from "./products/products.module.js";
|
||||
import { ResellersModule } from "./resellers/resellers.module.js";
|
||||
import { LeadsModule } from "./leads/leads.module.js";
|
||||
import { OpportunitiesModule } from "./opportunities/opportunities.module.js";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -21,6 +23,8 @@ import { ResellersModule } from "./resellers/resellers.module.js";
|
||||
RolesModule,
|
||||
ProductsModule,
|
||||
ResellersModule,
|
||||
LeadsModule,
|
||||
OpportunitiesModule,
|
||||
],
|
||||
controllers: [HealthController],
|
||||
})
|
||||
|
||||
23
apps/api/src/leads/dto/convert-lead.dto.ts
Normal file
23
apps/api/src/leads/dto/convert-lead.dto.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { IsIn, IsInt, IsOptional, IsString, Max, MaxLength, Min } from "class-validator";
|
||||
import { OPPORTUNITY_STAGES, type OpportunityStage } from "../../opportunities/dto/create-opportunity.dto";
|
||||
|
||||
/** Body for POST /v1/leads/:id/convert — the new opportunity's fields. */
|
||||
export class ConvertLeadDto {
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
title!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(OPPORTUNITY_STAGES)
|
||||
stage?: OpportunityStage;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
@Max(100)
|
||||
probability?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
}
|
||||
46
apps/api/src/leads/dto/create-lead.dto.ts
Normal file
46
apps/api/src/leads/dto/create-lead.dto.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { IsEmail, IsIn, IsOptional, IsString, IsUUID, MaxLength } from "class-validator";
|
||||
|
||||
/**
|
||||
* Plain TEXT column in the DB, no CHECK constraint (see the crm migration).
|
||||
* Validated here at the API boundary instead.
|
||||
*/
|
||||
export const LEAD_STATUSES = ["new", "contacted", "qualified", "converted", "discarded"] as const;
|
||||
export type LeadStatus = (typeof LEAD_STATUSES)[number];
|
||||
|
||||
export class CreateLeadDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
source?: string;
|
||||
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
contactName!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEmail()
|
||||
@MaxLength(320)
|
||||
contactEmail?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(40)
|
||||
contactPhone?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
companyName?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(LEAD_STATUSES)
|
||||
status?: LeadStatus;
|
||||
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
ownerId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
}
|
||||
41
apps/api/src/leads/dto/update-lead.dto.ts
Normal file
41
apps/api/src/leads/dto/update-lead.dto.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { IsEmail, IsIn, IsOptional, IsString, IsUUID, MaxLength } from "class-validator";
|
||||
import { LEAD_STATUSES, type LeadStatus } from "./create-lead.dto";
|
||||
|
||||
export class UpdateLeadDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
source?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
contactName?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEmail()
|
||||
@MaxLength(320)
|
||||
contactEmail?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(40)
|
||||
contactPhone?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
companyName?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(LEAD_STATUSES)
|
||||
status?: LeadStatus;
|
||||
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
ownerId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
}
|
||||
63
apps/api/src/leads/leads.controller.ts
Normal file
63
apps/api/src/leads/leads.controller.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { Body, Controller, Get, Param, ParseUUIDPipe, Patch, Post, Query, UseGuards } from "@nestjs/common";
|
||||
import { LeadsService } from "./leads.service.js";
|
||||
import { CreateLeadDto } from "./dto/create-lead.dto.js";
|
||||
import { UpdateLeadDto } from "./dto/update-lead.dto.js";
|
||||
import { ConvertLeadDto } from "./dto/convert-lead.dto.js";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard.js";
|
||||
import { PermissionGuard } from "../auth/permission.guard.js";
|
||||
import { RequirePermission } from "../auth/decorators/require-permission.decorator.js";
|
||||
import { CurrentUser } from "../auth/decorators/current-user.decorator.js";
|
||||
import type { EdenAuthenticatedUser } from "../auth/jwt-auth.guard.js";
|
||||
|
||||
/**
|
||||
* CRM leads (Master Prompt §6.2). Unlike Companies/Products (open-read),
|
||||
* leads/opportunities carry prospect PII — every route, including reads,
|
||||
* requires authentication AND resource+action permission (ADR-0004).
|
||||
*
|
||||
* The global ValidationPipe (whitelist+forbidNonWhitelisted, main.ts) already
|
||||
* covers mass-assignment protection for every controller — no need for a
|
||||
* second, controller-local ValidationPipe here.
|
||||
*/
|
||||
@Controller("v1/leads")
|
||||
@UseGuards(JwtAuthGuard, PermissionGuard)
|
||||
export class LeadsController {
|
||||
constructor(private readonly leadsService: LeadsService) {}
|
||||
|
||||
@Get()
|
||||
@RequirePermission("leads", "view")
|
||||
list(@Query("status") status?: string, @Query("ownerId") ownerId?: string) {
|
||||
return this.leadsService.list({ status, ownerId });
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
@RequirePermission("leads", "view")
|
||||
get(@Param("id", ParseUUIDPipe) id: string) {
|
||||
return this.leadsService.get(id);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@RequirePermission("leads", "edit")
|
||||
create(@Body() dto: CreateLeadDto, @CurrentUser() user: EdenAuthenticatedUser) {
|
||||
return this.leadsService.create(dto, user.id);
|
||||
}
|
||||
|
||||
@Patch(":id")
|
||||
@RequirePermission("leads", "edit")
|
||||
update(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Body() dto: UpdateLeadDto,
|
||||
@CurrentUser() user: EdenAuthenticatedUser,
|
||||
) {
|
||||
return this.leadsService.update(id, dto, user.id);
|
||||
}
|
||||
|
||||
@Post(":id/convert")
|
||||
@RequirePermission("leads", "edit")
|
||||
convert(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Body() dto: ConvertLeadDto,
|
||||
@CurrentUser() user: EdenAuthenticatedUser,
|
||||
) {
|
||||
return this.leadsService.convert(id, dto, user.id);
|
||||
}
|
||||
}
|
||||
12
apps/api/src/leads/leads.module.ts
Normal file
12
apps/api/src/leads/leads.module.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { AuthModule } from "../auth/auth.module.js";
|
||||
import { LeadsController } from "./leads.controller.js";
|
||||
import { LeadsService } from "./leads.service.js";
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [LeadsController],
|
||||
providers: [LeadsService],
|
||||
exports: [LeadsService],
|
||||
})
|
||||
export class LeadsModule {}
|
||||
97
apps/api/src/leads/leads.service.ts
Normal file
97
apps/api/src/leads/leads.service.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import {
|
||||
auditRepo,
|
||||
convertLeadToOpportunity,
|
||||
createLead,
|
||||
getLead,
|
||||
listLeads,
|
||||
updateLead,
|
||||
type ConvertLeadResult,
|
||||
type Lead,
|
||||
} from "@eden/database";
|
||||
import type { CreateLeadDto } from "./dto/create-lead.dto";
|
||||
import type { UpdateLeadDto } from "./dto/update-lead.dto";
|
||||
import type { ConvertLeadDto } from "./dto/convert-lead.dto";
|
||||
|
||||
export interface ListLeadsQuery {
|
||||
status?: string;
|
||||
ownerId?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class LeadsService {
|
||||
list(filter: ListLeadsQuery): Promise<Lead[]> {
|
||||
return listLeads(filter);
|
||||
}
|
||||
|
||||
async get(id: string): Promise<Lead> {
|
||||
const lead = await getLead(id);
|
||||
if (!lead) {
|
||||
throw new NotFoundException(`Lead ${id} not found`);
|
||||
}
|
||||
return lead;
|
||||
}
|
||||
|
||||
async create(dto: CreateLeadDto, actorId: string | null): Promise<Lead> {
|
||||
const lead = await createLead({ ...dto, createdBy: actorId });
|
||||
await auditRepo.appendAuditEvent({
|
||||
actorType: "user",
|
||||
actorId,
|
||||
action: "lead.created",
|
||||
resourceType: "lead",
|
||||
resourceId: lead.id,
|
||||
metadata: { status: lead.status, source: lead.source },
|
||||
});
|
||||
return lead;
|
||||
}
|
||||
|
||||
async update(id: string, dto: UpdateLeadDto, actorId: string | null): Promise<Lead> {
|
||||
const lead = await updateLead(id, dto);
|
||||
if (!lead) {
|
||||
throw new NotFoundException(`Lead ${id} not found`);
|
||||
}
|
||||
await auditRepo.appendAuditEvent({
|
||||
actorType: "user",
|
||||
actorId,
|
||||
action: "lead.updated",
|
||||
resourceType: "lead",
|
||||
resourceId: lead.id,
|
||||
metadata: { fields: Object.keys(dto) },
|
||||
});
|
||||
return lead;
|
||||
}
|
||||
|
||||
async convert(
|
||||
id: string,
|
||||
dto: ConvertLeadDto,
|
||||
actorId: string | null,
|
||||
): Promise<ConvertLeadResult> {
|
||||
const result = await convertLeadToOpportunity(id, {
|
||||
title: dto.title,
|
||||
stage: dto.stage,
|
||||
probability: dto.probability ?? null,
|
||||
notes: dto.notes ?? null,
|
||||
createdBy: actorId,
|
||||
});
|
||||
if (!result) {
|
||||
throw new NotFoundException(`Lead ${id} not found`);
|
||||
}
|
||||
await auditRepo.appendAuditEvent({
|
||||
actorType: "user",
|
||||
actorId,
|
||||
action: "lead.converted",
|
||||
resourceType: "lead",
|
||||
resourceId: result.lead.id,
|
||||
metadata: { opportunityId: result.opportunity.id },
|
||||
});
|
||||
await auditRepo.appendAuditEvent({
|
||||
actorType: "user",
|
||||
actorId,
|
||||
action: "opportunity.created",
|
||||
resourceType: "opportunity",
|
||||
resourceId: result.opportunity.id,
|
||||
metadata: { leadId: id, stage: result.opportunity.stage },
|
||||
});
|
||||
return result;
|
||||
}
|
||||
}
|
||||
49
apps/api/src/opportunities/dto/create-opportunity.dto.ts
Normal file
49
apps/api/src/opportunities/dto/create-opportunity.dto.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { IsIn, IsInt, IsOptional, IsString, IsUUID, Max, MaxLength, Min } from "class-validator";
|
||||
|
||||
/**
|
||||
* Plain TEXT column in the DB, no CHECK constraint (see the crm
|
||||
* migration). Validated here at the API boundary instead. A fully
|
||||
* configurable pipeline is a future refinement, not this MVP.
|
||||
*/
|
||||
export const OPPORTUNITY_STAGES = [
|
||||
"prospecting",
|
||||
"qualification",
|
||||
"proposal",
|
||||
"negotiation",
|
||||
"won",
|
||||
"lost",
|
||||
] as const;
|
||||
export type OpportunityStage = (typeof OPPORTUNITY_STAGES)[number];
|
||||
|
||||
export class CreateOpportunityDto {
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
leadId?: string;
|
||||
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
title!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(OPPORTUNITY_STAGES)
|
||||
stage?: OpportunityStage;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
@Max(100)
|
||||
probability?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
ownerId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(500)
|
||||
lossReason?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
}
|
||||
32
apps/api/src/opportunities/dto/update-opportunity.dto.ts
Normal file
32
apps/api/src/opportunities/dto/update-opportunity.dto.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { IsIn, IsInt, IsOptional, IsString, IsUUID, Max, MaxLength, Min } from "class-validator";
|
||||
import { OPPORTUNITY_STAGES, type OpportunityStage } from "./create-opportunity.dto";
|
||||
|
||||
export class UpdateOpportunityDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
title?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(OPPORTUNITY_STAGES)
|
||||
stage?: OpportunityStage;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
@Max(100)
|
||||
probability?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
ownerId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(500)
|
||||
lossReason?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
notes?: string;
|
||||
}
|
||||
49
apps/api/src/opportunities/opportunities.controller.ts
Normal file
49
apps/api/src/opportunities/opportunities.controller.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Body, Controller, Get, Param, ParseUUIDPipe, Patch, Post, Query, UseGuards } from "@nestjs/common";
|
||||
import { OpportunitiesService } from "./opportunities.service.js";
|
||||
import { CreateOpportunityDto } from "./dto/create-opportunity.dto.js";
|
||||
import { UpdateOpportunityDto } from "./dto/update-opportunity.dto.js";
|
||||
import { JwtAuthGuard } from "../auth/jwt-auth.guard.js";
|
||||
import { PermissionGuard } from "../auth/permission.guard.js";
|
||||
import { RequirePermission } from "../auth/decorators/require-permission.decorator.js";
|
||||
import { CurrentUser } from "../auth/decorators/current-user.decorator.js";
|
||||
import type { EdenAuthenticatedUser } from "../auth/jwt-auth.guard.js";
|
||||
|
||||
/**
|
||||
* CRM opportunities (Master Prompt §6.2). Same PII-gating rationale as
|
||||
* leads — read requires @RequirePermission('opportunities', 'view'), not
|
||||
* just authentication. Mass-assignment protection comes from the global
|
||||
* ValidationPipe (main.ts) — no controller-local pipe needed.
|
||||
*/
|
||||
@Controller("v1/opportunities")
|
||||
@UseGuards(JwtAuthGuard, PermissionGuard)
|
||||
export class OpportunitiesController {
|
||||
constructor(private readonly opportunitiesService: OpportunitiesService) {}
|
||||
|
||||
@Get()
|
||||
@RequirePermission("opportunities", "view")
|
||||
list(@Query("stage") stage?: string, @Query("ownerId") ownerId?: string) {
|
||||
return this.opportunitiesService.list({ stage, ownerId });
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
@RequirePermission("opportunities", "view")
|
||||
get(@Param("id", ParseUUIDPipe) id: string) {
|
||||
return this.opportunitiesService.get(id);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@RequirePermission("opportunities", "edit")
|
||||
create(@Body() dto: CreateOpportunityDto, @CurrentUser() user: EdenAuthenticatedUser) {
|
||||
return this.opportunitiesService.create(dto, user.id);
|
||||
}
|
||||
|
||||
@Patch(":id")
|
||||
@RequirePermission("opportunities", "edit")
|
||||
update(
|
||||
@Param("id", ParseUUIDPipe) id: string,
|
||||
@Body() dto: UpdateOpportunityDto,
|
||||
@CurrentUser() user: EdenAuthenticatedUser,
|
||||
) {
|
||||
return this.opportunitiesService.update(id, dto, user.id);
|
||||
}
|
||||
}
|
||||
12
apps/api/src/opportunities/opportunities.module.ts
Normal file
12
apps/api/src/opportunities/opportunities.module.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { AuthModule } from "../auth/auth.module.js";
|
||||
import { OpportunitiesController } from "./opportunities.controller.js";
|
||||
import { OpportunitiesService } from "./opportunities.service.js";
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [OpportunitiesController],
|
||||
providers: [OpportunitiesService],
|
||||
exports: [OpportunitiesService],
|
||||
})
|
||||
export class OpportunitiesModule {}
|
||||
64
apps/api/src/opportunities/opportunities.service.ts
Normal file
64
apps/api/src/opportunities/opportunities.service.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import {
|
||||
auditRepo,
|
||||
createOpportunity,
|
||||
getOpportunity,
|
||||
listOpportunities,
|
||||
updateOpportunity,
|
||||
type Opportunity,
|
||||
} from "@eden/database";
|
||||
import type { CreateOpportunityDto } from "./dto/create-opportunity.dto";
|
||||
import type { UpdateOpportunityDto } from "./dto/update-opportunity.dto";
|
||||
|
||||
export interface ListOpportunitiesQuery {
|
||||
stage?: string;
|
||||
ownerId?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class OpportunitiesService {
|
||||
list(filter: ListOpportunitiesQuery): Promise<Opportunity[]> {
|
||||
return listOpportunities(filter);
|
||||
}
|
||||
|
||||
async get(id: string): Promise<Opportunity> {
|
||||
const opportunity = await getOpportunity(id);
|
||||
if (!opportunity) {
|
||||
throw new NotFoundException(`Opportunity ${id} not found`);
|
||||
}
|
||||
return opportunity;
|
||||
}
|
||||
|
||||
async create(dto: CreateOpportunityDto, actorId: string | null): Promise<Opportunity> {
|
||||
const opportunity = await createOpportunity({ ...dto, createdBy: actorId });
|
||||
await auditRepo.appendAuditEvent({
|
||||
actorType: "user",
|
||||
actorId,
|
||||
action: "opportunity.created",
|
||||
resourceType: "opportunity",
|
||||
resourceId: opportunity.id,
|
||||
metadata: { stage: opportunity.stage, leadId: opportunity.leadId },
|
||||
});
|
||||
return opportunity;
|
||||
}
|
||||
|
||||
async update(
|
||||
id: string,
|
||||
dto: UpdateOpportunityDto,
|
||||
actorId: string | null,
|
||||
): Promise<Opportunity> {
|
||||
const opportunity = await updateOpportunity(id, dto);
|
||||
if (!opportunity) {
|
||||
throw new NotFoundException(`Opportunity ${id} not found`);
|
||||
}
|
||||
await auditRepo.appendAuditEvent({
|
||||
actorType: "user",
|
||||
actorId,
|
||||
action: "opportunity.updated",
|
||||
resourceType: "opportunity",
|
||||
resourceId: opportunity.id,
|
||||
metadata: { fields: Object.keys(dto) },
|
||||
});
|
||||
return opportunity;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user