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
8 changes: 8 additions & 0 deletions backend/shared/events/access-request.event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@

export class AccessRequestEvent {
constructor(
public readonly name: string,
public readonly email: string,
public readonly cnpj: string,
) {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export interface CreateNotificationDTO {
ticketId?: string;
}


export interface CreateMessageNotificationDTO {
receiverId: string;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { NotificationType } from '../../shared/enums/notification.enum';
import { UserService } from '../../../user/user.service';
import { CreateNotificationUseCase } from '../use-cases/create-notification.use-case';
import { NotificationStreamService } from '../services/notificatio.stream.service';
import { UserRole } from '../../../shared/enums/user.enum';
import { AccessRequestEvent } from '../../../../../shared/events/access-request.event';

@Injectable()
export class AccessRequestListener {
constructor(
private readonly userService: UserService,
private readonly createNotificationUseCase: CreateNotificationUseCase,
private readonly notificationStreamService: NotificationStreamService,
) {}

@OnEvent(NotificationType.ACCESS_REQUEST)
async handle(event: AccessRequestEvent) {
console.log('[AccessRequestListener] Evento recebido:', event);

// Buscar todos os administradores
const admins = await this.userService.findAll(1, 1000, { role: UserRole.ADMIN });
if (!admins.data.length) return;

await Promise.all(
admins.data.map(async (admin) => {
const notification = await this.createNotificationUseCase.execute({
title: 'Nova solicitação de acesso',
message: 'Um novo usuário solicitou acesso ao sistema',
clientId: '',
supportAgentId: admin.id,
type: NotificationType.ACCESS_REQUEST,
});
this.notificationStreamService.send(admin.id, notification.toPrimitives());
})
);
}
}
3 changes: 3 additions & 0 deletions backend/src/modules/notification/notification.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@ import { NotificationSSEController }

import { NotificationStreamService }
from "./application/services/notificatio.stream.service";

import { TicketClosedListener } from "./application/listeners/ticket-closed.listener";
import { UserModule } from "../user/user.module";
import { TicketOpenListener } from "./application/listeners/ticket-open.listener";
import { ReceivedMessageListener } from "./application/listeners/received-message.listener";
import { AccessRequestListener } from "./application/listeners/access-request.listener";
import { CreateMessageNotificationUseCase } from "./application/use-cases/create-message-notification.use-case";
import { NotificationController } from "./presetation/controllers/notification.controller";
import { ListNotificationsUseCase } from "./application/use-cases/list-notifications.use-case";
Expand Down Expand Up @@ -57,6 +59,7 @@ import { ReadNotificationUseCase } from "./application/use-cases/read-notificati
TicketClosedListener,
TicketOpenListener,
ReceivedMessageListener,
AccessRequestListener,

{
provide: INotificationRepository,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export enum NotificationType {
TICKET_CLOSED = 'ticket_closed',
TICKET_OPEN = 'ticket_open',
NEW_MESSAGE = 'new_message',
ACCESS_REQUEST = 'access_request',
}
38 changes: 32 additions & 6 deletions backend/src/modules/user/user.access-request.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@ import { Test, TestingModule } from '@nestjs/testing';
import { getConnectionToken, MongooseModule } from '@nestjs/mongoose';
import { Connection, Types } from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { EventEmitter2 } from '@nestjs/event-emitter';

import { UserService } from './user.service';
import { UserSchema } from './user.schema';
import { AccessRequestSchema } from './accessRequest.schema';

import { CompanyService } from '../company/company.service';
import { CategoryService } from '../category/category.service';
import { JwtService } from '@nestjs/jwt';
import { EmailService } from '../email/email.service';

import { CompanySchema } from '../company/company.schema';
import { CategorySchema } from '../category/category.schema';

Expand All @@ -26,15 +29,25 @@ describe('AccessRequest (Integration)', () => {
const module: TestingModule = await Test.createTestingModule({
imports: [
MongooseModule.forRoot(mongod.getUri()),

MongooseModule.forFeature([
{ name: 'User', schema: UserSchema },
{ name: 'AccessRequest', schema: AccessRequestSchema },
{ name: 'Company', schema: CompanySchema },
{ name: 'Category', schema: CategorySchema },
]),
],

providers: [
UserService,

{
provide: EventEmitter2,
useValue: {
emit: jest.fn(),
},
},

{
provide: CompanyService,
useValue: {
Expand All @@ -44,6 +57,7 @@ describe('AccessRequest (Integration)', () => {
name: 'Empresa Teste',
cnpj: '123',
}),

findById: jest.fn().mockResolvedValue({
_id: companyId,
id: companyId.toString(),
Expand All @@ -69,25 +83,37 @@ describe('AccessRequest (Integration)', () => {
provide: EmailService,
useValue: {
sendCreatePasswordEmail: jest.fn(),
sendResetPasswordEmail: jest.fn(),
},
},
],
}).compile();

service = module.get<UserService>(UserService);
connection = module.get<Connection>(getConnectionToken());

connection = module.get<Connection>(
getConnectionToken(),
);
});

afterEach(async () => {
const collections = connection.collections;
for (const key in collections) {
await collections[key].deleteMany({});
if (connection && connection.readyState === 1) {
const collections = connection.collections;

for (const key in collections) {
await collections[key].deleteMany({});
}
}
});

afterAll(async () => {
await connection.close();
await mongod.stop();
if (connection && connection.readyState === 1) {
await connection.close();
}

if (mongod) {
await mongod.stop();
}
});

it('should create access request', async () => {
Expand Down
76 changes: 60 additions & 16 deletions backend/src/modules/user/user.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Test, TestingModule } from '@nestjs/testing';
import { getConnectionToken, MongooseModule } from '@nestjs/mongoose';
import { Connection, Types } from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { EventEmitter2 } from '@nestjs/event-emitter';

import { UserService } from './user.service';
import { UserSchema } from './user.schema';
Expand All @@ -25,15 +26,25 @@ describe('UserService (Integration)', () => {
const module: TestingModule = await Test.createTestingModule({
imports: [
MongooseModule.forRoot(mongod.getUri()),

MongooseModule.forFeature([
{ name: 'User', schema: UserSchema },
{ name: 'AccessRequest', schema: AccessRequestSchema },
{ name: 'Company', schema: CompanySchema },
{ name: 'Category', schema: CategorySchema },
]),
],

providers: [
UserService,

{
provide: EventEmitter2,
useValue: {
emit: jest.fn(),
},
},

{
provide: CompanyService,
useValue: {
Expand All @@ -42,13 +53,15 @@ describe('UserService (Integration)', () => {
name: 'Test Company',
cnpj: '123',
}),

findById: jest.fn().mockResolvedValue({
id: 'company-id',
name: 'Test Company',
cnpj: '123',
}),
},
},

{
provide: CategoryService,
useValue: {
Expand All @@ -59,12 +72,14 @@ describe('UserService (Integration)', () => {
}),
},
},

{
provide: JwtService,
useValue: {
signAsync: jest.fn().mockResolvedValue('fake-token'),
},
},

{
provide: EmailService,
useValue: {
Expand All @@ -76,19 +91,30 @@ describe('UserService (Integration)', () => {
}).compile();

service = module.get<UserService>(UserService);
connection = module.get<Connection>(getConnectionToken());

connection = module.get<Connection>(
getConnectionToken(),
);
});

afterEach(async () => {
const collections = connection.collections;
for (const key in collections) {
await collections[key].deleteMany({});
if (connection && connection.readyState === 1) {
const collections = connection.collections;

for (const key in collections) {
await collections[key].deleteMany({});
}
}
});

afterAll(async () => {
await connection.close();
await mongod.stop();
if (connection && connection.readyState === 1) {
await connection.close();
}

if (mongod) {
await mongod.stop();
}
});

it('should create user successfully', async () => {
Expand Down Expand Up @@ -128,7 +154,9 @@ describe('UserService (Integration)', () => {
UserRole.CLIENT,
);

const result = await service.findById(created._id.toString());
const result = await service.findById(
created._id.toString(),
);

expect(result).toBeDefined();
expect(result.email).toBe('test@email.com');
Expand All @@ -141,6 +169,7 @@ describe('UserService (Integration)', () => {
'Password123!',
UserRole.CLIENT,
);

await service.createUser(
'User2',
'u2@email.com',
Expand All @@ -163,14 +192,19 @@ describe('UserService (Integration)', () => {
'Password123!',
UserRole.CLIENT,
);

await service.createUser(
'Maria',
'm@email.com',
'Password123!',
UserRole.CLIENT,
);

const result = await service.findAll(1, 10, { name: 'gab' });
const result = await service.findAll(
1,
10,
{ name: 'gab' },
);

expect(result.data.length).toBe(1);
expect(result.data[0].name).toBe('Gabriel');
Expand All @@ -184,9 +218,12 @@ describe('UserService (Integration)', () => {
UserRole.CLIENT,
);

const updated = await service.updateUser(created._id.toString(), {
name: 'New Name',
});
const updated = await service.updateUser(
created._id.toString(),
{
name: 'New Name',
},
);

expect(updated.name).toBe('New Name');
});
Expand All @@ -199,9 +236,13 @@ describe('UserService (Integration)', () => {
UserRole.CLIENT,
);

await service.deleteUser(created._id.toString());
await service.deleteUser(
created._id.toString(),
);

await expect(service.findById(created._id.toString())).rejects.toThrow();
await expect(
service.findById(created._id.toString()),
).rejects.toThrow();
});

it('should throw error when email already exists on update', async () => {
Expand All @@ -220,9 +261,12 @@ describe('UserService (Integration)', () => {
);

await expect(
service.updateUser(user2._id.toString(), {
email: 'same@email.com',
}),
service.updateUser(
user2._id.toString(),
{
email: 'same@email.com',
},
),
).rejects.toThrow();
});
});
Loading
Loading