Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions apps/api/src/app/agents/dtos/agent-integration-summary.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { ApiProperty } from '@nestjs/swagger';
import { ChannelTypeEnum } from '@novu/shared';

export class AgentIntegrationSummaryDto {
@ApiProperty({ description: 'Integration document id.' })
integrationId: string;

@ApiProperty()
providerId: string;

@ApiProperty()
name: string;

@ApiProperty()
identifier: string;

@ApiProperty({ enum: ChannelTypeEnum, enumName: 'ChannelTypeEnum' })
channel: ChannelTypeEnum;

@ApiProperty()
active: boolean;
}
5 changes: 5 additions & 0 deletions apps/api/src/app/agents/dtos/agent-response.dto.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';

import { AgentIntegrationSummaryDto } from './agent-integration-summary.dto';

export class AgentResponseDto {
@ApiProperty()
_id: string;
Expand All @@ -24,4 +26,7 @@ export class AgentResponseDto {

@ApiProperty()
updatedAt: string;

@ApiPropertyOptional({ type: [AgentIntegrationSummaryDto] })
integrations?: AgentIntegrationSummaryDto[];
}
6 changes: 5 additions & 1 deletion apps/api/src/app/agents/dtos/create-agent-request.dto.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
import { SLUG_IDENTIFIER_REGEX, slugIdentifierFormatMessage } from '@novu/shared';
import { IsNotEmpty, IsOptional, IsString, Matches } from 'class-validator';

export class CreateAgentRequestDto {
@ApiProperty()
Expand All @@ -10,6 +11,9 @@ export class CreateAgentRequestDto {
@ApiProperty()
@IsString()
@IsNotEmpty()
@Matches(SLUG_IDENTIFIER_REGEX, {
message: slugIdentifierFormatMessage('identifier'),
})
identifier: string;

@ApiPropertyOptional()
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/app/agents/dtos/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './add-agent-integration-request.dto';
export * from './agent-integration-summary.dto';
export * from './agent-integration-response.dto';
export * from './agent-response.dto';
export * from './create-agent-request.dto';
Expand Down
18 changes: 15 additions & 3 deletions apps/api/src/app/agents/e2e/agents.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,20 @@ describe('Agents API - /agents #novu-v2', () => {
expect(afterDelete.status).to.equal(404);
});

it('should return 422 when identifier is not a valid slug', async () => {
const res = await session.testAgent.post('/v1/agents').send({
name: 'Invalid Slug Agent',
identifier: 'bad id with spaces',
});

expect(res.status).to.equal(422);
const messages = res.body?.errors?.general?.messages;
const text = Array.isArray(messages) ? messages.join(' ') : String(messages ?? '');

expect(text.toLowerCase()).to.contain('identifier');
expect(text.toLowerCase()).to.match(/slug|valid/);
});

it('should return 404 when agent identifier does not exist', async () => {
const res = await session.testAgent.get('/v1/agents/nonexistent-agent-id-xyz');

Expand Down Expand Up @@ -153,9 +167,7 @@ describe('Agents API - /agents #novu-v2', () => {

expect(removeRes.status).to.equal(204);

const listAfterRemove = await session.testAgent.get(
`/v1/agents/${encodeURIComponent(identifier)}/integrations`
);
const listAfterRemove = await session.testAgent.get(`/v1/agents/${encodeURIComponent(identifier)}/integrations`);

expect(listAfterRemove.body.data.length).to.equal(0);

Expand Down
17 changes: 15 additions & 2 deletions apps/api/src/app/agents/mappers/agent-response.mapper.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { AgentEntity, AgentIntegrationEntity } from '@novu/dal';
import type { AgentEntity, AgentIntegrationEntity, IntegrationEntity } from '@novu/dal';

import type { AgentIntegrationResponseDto, AgentResponseDto } from '../dtos';
import type { AgentIntegrationResponseDto, AgentIntegrationSummaryDto, AgentResponseDto } from '../dtos';

export function toAgentResponse(agent: AgentEntity): AgentResponseDto {
return {
Expand All @@ -15,6 +15,19 @@ export function toAgentResponse(agent: AgentEntity): AgentResponseDto {
};
}

export function toAgentIntegrationSummary(
integration: Pick<IntegrationEntity, '_id' | 'identifier' | 'name' | 'providerId' | 'channel' | 'active'>
): AgentIntegrationSummaryDto {
return {
integrationId: integration._id,
providerId: integration.providerId,
name: integration.name,
identifier: integration.identifier,
channel: integration.channel,
active: integration.active,
};
}

export function toAgentIntegrationResponse(
link: AgentIntegrationEntity,
integrationIdentifier: string
Expand Down
102 changes: 98 additions & 4 deletions apps/api/src/app/agents/usecases/list-agents/list-agents.usecase.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import { InstrumentUsecase } from '@novu/application-generic';
import { AgentRepository } from '@novu/dal';
import { AgentIntegrationRepository, AgentRepository, IntegrationRepository } from '@novu/dal';
import { DirectionEnum } from '@novu/shared';
import type { AgentIntegrationSummaryDto } from '../../dtos/agent-integration-summary.dto';
import { ListAgentsResponseDto } from '../../dtos/list-agents-response.dto';
import { toAgentResponse } from '../../mappers/agent-response.mapper';
import { toAgentIntegrationSummary, toAgentResponse } from '../../mappers/agent-response.mapper';
import { ListAgentsCommand } from './list-agents.command';

@Injectable()
export class ListAgents {
constructor(private readonly agentRepository: AgentRepository) {}
constructor(
private readonly agentRepository: AgentRepository,
private readonly agentIntegrationRepository: AgentIntegrationRepository,
private readonly integrationRepository: IntegrationRepository
) {}

@InstrumentUsecase()
async execute(command: ListAgentsCommand): Promise<ListAgentsResponseDto> {
Expand All @@ -28,12 +33,101 @@ export class ListAgents {
identifier: command.identifier,
});

const integrationsByAgentId = await this.loadIntegrationsForAgents(
command.environmentId,
command.organizationId,
pagination.agents
);

return {
data: pagination.agents.map((agent) => toAgentResponse(agent)),
data: pagination.agents.map((agent) => ({
...toAgentResponse(agent),
integrations: integrationsByAgentId.get(agent._id) ?? [],
})),
next: pagination.next,
previous: pagination.previous,
totalCount: pagination.totalCount,
totalCountCapped: pagination.totalCountCapped,
};
}

private async loadIntegrationsForAgents(
environmentId: string,
organizationId: string,
agents: { _id: string }[]
): Promise<Map<string, AgentIntegrationSummaryDto[]>> {
const result = new Map<string, AgentIntegrationSummaryDto[]>();

if (agents.length === 0) {
return result;
}

const agentIds = agents.map((a) => a._id);
const links = await this.agentIntegrationRepository.findLinksForAgents({
environmentId,
organizationId,
agentIds,
});

const integrationIds = [...new Set(links.map((l) => l._integrationId))];

if (integrationIds.length === 0) {
for (const id of agentIds) {
result.set(id, []);
}

return result;
}

const integrations = await this.integrationRepository.find(
{
_id: { $in: integrationIds },
_environmentId: environmentId,
_organizationId: organizationId,
},
'_id identifier name providerId channel active'
);

const summaryByIntegrationId = new Map(integrations.map((i) => [i._id, toAgentIntegrationSummary(i)] as const));

const seen = new Map<string, Set<string>>();

for (const link of links) {
const summary = summaryByIntegrationId.get(link._integrationId);

if (!summary) {
continue;
}

let dedupe = seen.get(link._agentId);

if (!dedupe) {
dedupe = new Set<string>();
seen.set(link._agentId, dedupe);
}

if (dedupe.has(summary.integrationId)) {
continue;
}

dedupe.add(summary.integrationId);
const list = result.get(link._agentId) ?? [];
list.push(summary);

result.set(link._agentId, list);
}

for (const id of agentIds) {
if (!result.has(id)) {
result.set(id, []);
} else {
const list = result.get(id) ?? [];
const sorted = [...list].sort((a, b) => a.name.localeCompare(b.name));

result.set(id, sorted);
}
}

return result;
}
}
6 changes: 3 additions & 3 deletions apps/api/src/app/workflows-v2/dtos/create-step.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
SmsControlDto,
ThrottleControlDto,
} from '@novu/application-generic';
import { StepTypeEnum } from '@novu/shared';
import { SLUG_IDENTIFIER_REGEX, StepTypeEnum, slugIdentifierFormatMessage } from '@novu/shared';
import { IsEnum, IsObject, IsOptional, IsString, Matches } from 'class-validator';

// Base DTO for common properties
Expand All @@ -27,8 +27,8 @@ export class BaseStepConfigDto {

@ApiPropertyOptional({ description: 'Unique identifier for the step' })
@IsString()
@Matches(/^[a-zA-Z0-9]+(?:[-_.][a-zA-Z0-9]+)*$/, {
message: 'stepId must be a valid slug format (letters, numbers, hyphens, dot and underscores only)',
@Matches(SLUG_IDENTIFIER_REGEX, {
message: slugIdentifierFormatMessage('stepId'),
})
@IsOptional()
stepId?: string;
Expand Down
12 changes: 9 additions & 3 deletions apps/api/src/app/workflows-v2/dtos/create-workflow.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,13 @@ import {
ThrottleControlDto,
WorkflowCommonsFields,
} from '@novu/application-generic';
import { SeverityLevelEnum, StepTypeEnum, WorkflowCreationSourceEnum } from '@novu/shared';
import {
SeverityLevelEnum,
SLUG_IDENTIFIER_REGEX,
StepTypeEnum,
slugIdentifierFormatMessage,
WorkflowCreationSourceEnum,
} from '@novu/shared';
import { Type } from 'class-transformer';
import { IsArray, IsEnum, IsOptional, IsString, Matches, ValidateNested } from 'class-validator';
import {
Expand Down Expand Up @@ -67,8 +73,8 @@ export type StepCreateDto =
export class CreateWorkflowDto extends WorkflowCommonsFields {
@ApiProperty({ description: 'Unique identifier for the workflow' })
@IsString()
@Matches(/^[a-zA-Z0-9]+(?:[-_.][a-zA-Z0-9]+)*$/, {
message: 'workflowId must be a valid slug format (letters, numbers, hyphens, dot and underscores only)',
@Matches(SLUG_IDENTIFIER_REGEX, {
message: slugIdentifierFormatMessage('workflowId'),
})
workflowId: string;

Expand Down
5 changes: 3 additions & 2 deletions apps/api/src/app/workflows-v2/dtos/duplicate-workflow.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { SLUG_IDENTIFIER_REGEX, slugIdentifierFormatMessage } from '@novu/shared';
import { IsArray, IsBoolean, IsOptional, IsString, Matches } from 'class-validator';

export class DuplicateWorkflowDto {
Expand All @@ -16,8 +17,8 @@ export class DuplicateWorkflowDto {
})
@IsOptional()
@IsString()
@Matches(/^[a-zA-Z0-9]+(?:[-_.][a-zA-Z0-9]+)*$/, {
message: 'workflowId must be a valid slug format (letters, numbers, hyphens, dot and underscores only)',
@Matches(SLUG_IDENTIFIER_REGEX, {
message: slugIdentifierFormatMessage('workflowId'),
})
workflowId?: string;

Expand Down
Loading
Loading