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
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,9 @@ lerna-debug.log*
# Deploy secrets
*.key
app-image.tar.gz

# Arquivos locais de sessao/briefing - nunca commitar
GEMINI.md
.agy-*.txt
docs/antigravity-cli-playbook.md
docs/relatorio-seguranca-vm.md
30 changes: 21 additions & 9 deletions src/contribution-reports/contribution-reports.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
ForbiddenException,
Injectable,
NotFoundException,
Logger,
} from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import { DataSource } from 'typeorm';
Expand All @@ -21,6 +22,8 @@

@Injectable()
export class ContributionReportsService {
private readonly logger = new Logger(ContributionReportsService.name);

constructor(
@InjectDataSource() private readonly dataSource: DataSource,
private readonly notificationsService: NotificationsService,
Expand Down Expand Up @@ -88,7 +91,7 @@
});
}

async review(

Check failure on line 94 in src/contribution-reports/contribution-reports.service.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 18 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=devs-tocantins_api-engajamento2&issues=AZ-pK8svtrUo18Ga0Ncq&open=AZ-pK8svtrUo18Ga0Ncq&pullRequest=108
reportId: string,
dto: ReviewContributionReportDto,
reviewerUserId: number,
Expand Down Expand Up @@ -160,15 +163,24 @@
.getRepository(GamificationProfileEntity)
.findOne({ where: { id: submission.profileId } });
if (ownerProfile) {
await this.notificationsService.create({
userId: ownerProfile.userId,
type: NotificationType.CONTRIBUTION_REPORT_UPHELD,
title: 'Contribuição removida',
body: dto.adminNote
? `Uma contribuição sua foi removida após revisão. Motivo: ${dto.adminNote}`
: 'Uma contribuição sua foi removida após revisão de um report.',
relatedId: submission.id,
});
try {
await this.notificationsService.create({
userId: ownerProfile.userId,
type: NotificationType.CONTRIBUTION_REPORT_UPHELD,
title: 'Contribuição removida',
body: dto.adminNote
? `Uma contribuição sua foi removida após revisão. Motivo: ${dto.adminNote}`
: 'Uma contribuição sua foi removida após revisão de um report.',
relatedId: submission.id,
link: '/submissions',
payload: { submissionId: submission.id },
});
} catch (err) {
this.logger.error(
'Error sending CONTRIBUTION_REPORT_UPHELD notification',
err,
);
}
}
} else {
await this.dataSource
Expand Down
19 changes: 19 additions & 0 deletions src/database/migrations/1785000000001-UpdateNotificationEntity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class UpdateNotificationEntity1785000000001
implements MigrationInterface
{
name = 'UpdateNotificationEntity1785000000001';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "notification" ADD "payload" jsonb`);
await queryRunner.query(
`ALTER TABLE "notification" ADD "link" character varying(500)`,
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "notification" DROP COLUMN "link"`);
await queryRunner.query(`ALTER TABLE "notification" DROP COLUMN "payload"`);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class UpdateNotificationTypeEnum1785000000002
implements MigrationInterface
{
name = 'UpdateNotificationTypeEnum1785000000002';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TYPE "notification_type_enum" ADD VALUE IF NOT EXISTS 'EVENT_UPDATED'`,
);
await queryRunner.query(
`ALTER TYPE "notification_type_enum" ADD VALUE IF NOT EXISTS 'EVENT_CANCELLED'`,
);
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
public async down(queryRunner: QueryRunner): Promise<void> {
// Postgres does not support removing enum values
}
}
2 changes: 2 additions & 0 deletions src/events/events.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ import { RelationalEventPersistenceModule } from './infrastructure/persistence/r
import { UsersModule } from '../users/users.module';
import { MailModule } from '../mail/mail.module';
import { FilesModule } from '../files/files.module';
import { NotificationsModule } from '../notifications/notifications.module';

@Module({
imports: [
RelationalEventPersistenceModule,
UsersModule,
MailModule,
FilesModule,
NotificationsModule,
ScheduleModule.forRoot(),
],
controllers: [EventsController],
Expand Down
8 changes: 8 additions & 0 deletions src/events/events.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { EventsService } from './events.service';
import { EventRepository } from './infrastructure/persistence/event.repository';
import { EventSubscriptionRepository } from './infrastructure/persistence/event-subscription.repository';
import { EventsIcsService } from './events-ics.service';
import { NotificationsService } from '../notifications/notifications.service';
import { UsersService } from '../users/users.service';
import { MailService } from '../mail/mail.service';
import { FilesService } from '../files/files.service';
Expand Down Expand Up @@ -52,6 +53,9 @@ describe('EventsService', () => {
let usersService: Partial<Record<keyof UsersService, jest.Mock>>;
let mailService: Partial<Record<keyof MailService, jest.Mock>>;
let filesService: Partial<Record<keyof FilesService, jest.Mock>>;
let notificationsService: Partial<
Record<keyof NotificationsService, jest.Mock>
>;

beforeEach(() => {
repository = {
Expand Down Expand Up @@ -84,6 +88,9 @@ describe('EventsService', () => {
filesService = {
remove: jest.fn(),
};
notificationsService = {
create: jest.fn().mockResolvedValue(undefined),
};

service = new EventsService(
repository as unknown as EventRepository,
Expand All @@ -92,6 +99,7 @@ describe('EventsService', () => {
usersService as unknown as UsersService,
mailService as unknown as MailService,
filesService as unknown as FilesService,
notificationsService as unknown as NotificationsService,
);
});

Expand Down
113 changes: 92 additions & 21 deletions src/events/events.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
Injectable,
NotFoundException,
UnprocessableEntityException,
Logger,
} from '@nestjs/common';
import { CreateEventDto } from './dto/create-event.dto';
import { UpdateEventDto } from './dto/update-event.dto';
Expand All @@ -21,6 +22,8 @@ import { EventsIcsService } from './events-ics.service';
import { UsersService } from '../users/users.service';
import { MailService } from '../mail/mail.service';
import { FilesService } from '../files/files.service';
import { NotificationsService } from '../notifications/notifications.service';
import { NotificationType } from '../notifications/domain/notification-type.enum';

const COVER_IMAGE_RETENTION_MS = 3 * 24 * 60 * 60 * 1000; // 3 dias após o evento

Expand All @@ -35,13 +38,16 @@ const NOTIFIABLE_FIELD_LABELS: Record<string, string> = {

@Injectable()
export class EventsService {
private readonly logger = new Logger(EventsService.name);

constructor(
private readonly eventRepository: EventRepository,
private readonly eventSubscriptionRepository: EventSubscriptionRepository,
private readonly eventsIcsService: EventsIcsService,
private readonly usersService: UsersService,
private readonly mailService: MailService,
private readonly filesService: FilesService,
private readonly notificationsService: NotificationsService,
) {}

private validateStartAtNotInPast(startAt?: string) {
Expand Down Expand Up @@ -219,7 +225,11 @@ export class EventsService {
),
);
if (changedFields.length > 0) {
await this.notifySubscribersOfUpdate(updatedEvent, changedFields);
try {
await this.notifySubscribersOfUpdate(updatedEvent, changedFields);
} catch (err) {
this.logger.error('Error notifying subscribers of event update', err);
}
}
}

Expand Down Expand Up @@ -290,7 +300,14 @@ export class EventsService {
});

if (cancelledEvent) {
await this.notifySubscribersOfCancellation(cancelledEvent);
try {
await this.notifySubscribersOfCancellation(cancelledEvent);
} catch (err) {
this.logger.error(
'Error notifying subscribers of event cancellation',
err,
);
}
}

return cancelledEvent;
Expand Down Expand Up @@ -329,35 +346,89 @@ export class EventsService {
event: Event,
changedFields: string[],
): Promise<void> {
const subscriberEmails = await this.getSubscriberEmails(event.id);
if (subscriberEmails.length === 0) return;
const subscriberIds =
await this.eventSubscriptionRepository.findSubscriberUserIds(event.id);
if (subscriberIds.length === 0) return;

const users = await this.usersService.findByIds(subscriberIds);
if (users.length === 0) return;

const changesSummary = `Foi alterado(a): ${changedFields
.map((field) => NOTIFIABLE_FIELD_LABELS[field])
.join(', ')}.`;

await Promise.all(
subscriberEmails.map((email) =>
this.mailService.eventUpdated({
to: email,
data: { eventId: event.id, eventTitle: event.title, changesSummary },
}),
),
const results = await Promise.allSettled(
users.map(async (user) => {
await this.notificationsService.create({
userId: user.id as number,
type: NotificationType.EVENT_UPDATED,
title: `Atualização no evento: ${event.title}`,
body: changesSummary,
relatedId: event.id,
link: `/eventos/${event.id}`,
payload: { eventId: event.id },
});

if (user.email) {
await this.mailService.eventUpdated({
to: user.email,
data: {
eventId: event.id,
eventTitle: event.title,
changesSummary,
},
});
}
}),
);

results.forEach((res, index) => {
if (res.status === 'rejected') {
this.logger.error(
`Error notifying user ${users[index].id} of event update`,
res.reason,
);
}
});
}

private async notifySubscribersOfCancellation(event: Event): Promise<void> {
const subscriberEmails = await this.getSubscriberEmails(event.id);
if (subscriberEmails.length === 0) return;

await Promise.all(
subscriberEmails.map((email) =>
this.mailService.eventCancelled({
to: email,
data: { eventTitle: event.title },
}),
),
const subscriberIds =
await this.eventSubscriptionRepository.findSubscriberUserIds(event.id);
if (subscriberIds.length === 0) return;

const users = await this.usersService.findByIds(subscriberIds);
if (users.length === 0) return;

const results = await Promise.allSettled(
users.map(async (user) => {
await this.notificationsService.create({
userId: user.id as number,
type: NotificationType.EVENT_CANCELLED,
title: `Evento cancelado: ${event.title}`,
body: `O evento "${event.title}" foi cancelado.`,
relatedId: event.id,
link: `/eventos/${event.id}`,
payload: { eventId: event.id },
});

if (user.email) {
await this.mailService.eventCancelled({
to: user.email,
data: { eventTitle: event.title },
});
}
}),
);

results.forEach((res, index) => {
if (res.status === 'rejected') {
this.logger.error(
`Error notifying user ${users[index].id} of event cancellation`,
res.reason,
);
}
});
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ export class LegalDocumentsNotificationCronService {
title: 'Atualizamos nossos termos',
body: 'Revisamos a Política de Privacidade e o Termo de Serviço do legado.dev. Dê uma olhada quando puder.',
relatedId: 'legal-documents',
link: '/legal',
payload: { version: CURRENT_LEGAL_DOCUMENTS_VERSION },
});

if (user.email) {
Expand Down
57 changes: 57 additions & 0 deletions src/mail/mail-templates/mission-won.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{title}}</title>
</head>
<body style="margin: 0; padding: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f3f4f6;">
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="background-color: #f3f4f6; padding: 40px 0;">
<tr>
<td align="center">
<table border="0" cellpadding="0" cellspacing="0" width="600" style="background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 6px rgba(0,0,0,0.05); margin: 0 auto;">
<!-- Header -->
<tr>
<td align="center" style="background-color: #ffffff; padding: 30px 0; border-bottom: 1px solid #e2e8f0;">
<h1 style="margin: 0; font-size: 28px; font-weight: 700; letter-spacing: 1px;">
<span style="color: #000000;">legado</span><span style="color: #f97316;">.dev</span>
</h1>
</td>
</tr>

<!-- Content -->
<tr>
<td style="padding: 40px 30px; color: #334155; font-size: 16px; line-height: 1.6;">
<p style="margin: 0 0 16px 0;">Parabéns! Você completou a missão <strong style="color: #0f172a;">{{missionTitle}}</strong>.</p>

<p style="margin: 0 0 24px 0;">Continue o excelente trabalho. Você conquistou <strong style="color: #10b981;">{{xp}} XP</strong> por esta missão!</p>

<table border="0" cellpadding="0" cellspacing="0" width="100%" style="margin: 30px 0;">
<tr>
<td align="center">
<a href="{{url}}" style="display: inline-block; padding: 14px 32px; background-color: #2563eb; color: #ffffff; text-decoration: none; font-weight: 600; border-radius: 6px; font-size: 16px;">
Ver Voluntariado
</a>
</td>
</tr>
</table>
</td>
</tr>

<!-- Footer -->
<tr>
<td style="background-color: #f8fafc; padding: 20px; text-align: center; border-top: 1px solid #e2e8f0;">
<p style="margin: 0; color: #64748b; font-size: 14px;">
&copy; {{#if app_name}}{{app_name}}{{else}}legado.dev{{/if}}. Todos os direitos reservados.
</p>
<p style="margin: 5px 0 0 0; color: #94a3b8; font-size: 12px;">
Este é um e-mail automático, por favor não responda. Você pode ajustar suas preferências de notificação no seu perfil.
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
Loading