diff --git a/src/database/migrations/1787400000000-ProjectIdeaFeaturedAndCall.ts b/src/database/migrations/1787400000000-ProjectIdeaFeaturedAndCall.ts new file mode 100644 index 0000000..c1a84c0 --- /dev/null +++ b/src/database/migrations/1787400000000-ProjectIdeaFeaturedAndCall.ts @@ -0,0 +1,38 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class ProjectIdeaFeaturedAndCall1787400000000 + implements MigrationInterface +{ + name = 'ProjectIdeaFeaturedAndCall1787400000000'; + + public async up(queryRunner: QueryRunner): Promise { + for (const value of ['PROJECT_IDEA_FEATURED', 'PROJECT_IDEA_CALLED']) { + await queryRunner.query( + `ALTER TYPE "notification_type_enum" ADD VALUE IF NOT EXISTS '${value}'`, + ); + } + + await queryRunner.query( + `ALTER TABLE "project_idea" ADD COLUMN "featuredAt" TIMESTAMP`, + ); + await queryRunner.query( + `ALTER TABLE "project_idea" ADD COLUMN "groupLink" character varying(300)`, + ); + await queryRunner.query( + `ALTER TABLE "project_idea" ADD COLUMN "calledAt" TIMESTAMP`, + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "project_idea" DROP COLUMN "calledAt"`, + ); + await queryRunner.query( + `ALTER TABLE "project_idea" DROP COLUMN "groupLink"`, + ); + await queryRunner.query( + `ALTER TABLE "project_idea" DROP COLUMN "featuredAt"`, + ); + // PostgreSQL não remove valores de enum; os tipos de notificação ficam. + } +} diff --git a/src/notifications/domain/notification-type.enum.ts b/src/notifications/domain/notification-type.enum.ts index 10a4f23..7ac5071 100644 --- a/src/notifications/domain/notification-type.enum.ts +++ b/src/notifications/domain/notification-type.enum.ts @@ -14,4 +14,6 @@ export enum NotificationType { PROJECT_IDEA_REJECTED = 'PROJECT_IDEA_REJECTED', PROJECT_IDEA_INTEREST = 'PROJECT_IDEA_INTEREST', PROJECT_TEAM_MEMBER_ADDED = 'PROJECT_TEAM_MEMBER_ADDED', + PROJECT_IDEA_FEATURED = 'PROJECT_IDEA_FEATURED', + PROJECT_IDEA_CALLED = 'PROJECT_IDEA_CALLED', } diff --git a/src/project-teams/domain/project-idea.ts b/src/project-teams/domain/project-idea.ts index 4e88de7..6bbfec2 100644 --- a/src/project-teams/domain/project-idea.ts +++ b/src/project-teams/domain/project-idea.ts @@ -34,6 +34,18 @@ export class ProjectIdea { @ApiProperty({ nullable: true }) reviewedAt: Date | null; + @ApiProperty({ + nullable: true, + description: 'Preenchido quando o projeto é o "projeto da vez"', + }) + featuredAt: Date | null; + + @ApiProperty({ + nullable: true, + description: 'Quando os interessados foram chamados para o grupo', + }) + calledAt: Date | null; + @ApiProperty({ type: Number, description: 'Quantidade de pessoas que demonstraram interesse', diff --git a/src/project-teams/dto/call-project-interested.dto.ts b/src/project-teams/dto/call-project-interested.dto.ts new file mode 100644 index 0000000..510e785 --- /dev/null +++ b/src/project-teams/dto/call-project-interested.dto.ts @@ -0,0 +1,24 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { IsOptional, IsString, IsUrl, MaxLength } from 'class-validator'; + +export class CallProjectInterestedDto { + @ApiProperty({ + example: 'https://chat.whatsapp.com/abc123', + description: 'Link do grupo (WhatsApp, Discord, Telegram...)', + }) + @IsUrl( + { protocols: ['https'], require_protocol: true }, + { message: 'Informe um link https válido para o grupo.' }, + ) + @MaxLength(300) + groupLink: string; + + @ApiPropertyOptional({ + example: 'Vamos começar sábado às 9h.', + description: 'Recado opcional enviado junto da notificação', + }) + @IsOptional() + @IsString() + @MaxLength(300) + message?: string; +} diff --git a/src/project-teams/dto/feature-project-idea.dto.ts b/src/project-teams/dto/feature-project-idea.dto.ts new file mode 100644 index 0000000..951d242 --- /dev/null +++ b/src/project-teams/dto/feature-project-idea.dto.ts @@ -0,0 +1,11 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsBoolean } from 'class-validator'; + +export class FeatureProjectIdeaDto { + @ApiProperty({ + type: Boolean, + description: 'true marca como projeto da vez; false remove o destaque', + }) + @IsBoolean() + featured: boolean; +} diff --git a/src/project-teams/infrastructure/persistence/project-idea.repository.ts b/src/project-teams/infrastructure/persistence/project-idea.repository.ts index 910425a..0ceaa82 100644 --- a/src/project-teams/infrastructure/persistence/project-idea.repository.ts +++ b/src/project-teams/infrastructure/persistence/project-idea.repository.ts @@ -17,8 +17,10 @@ export type ProjectIdeaUpdate = Partial< | 'rejectionReason' | 'reviewerId' | 'reviewedAt' + | 'featuredAt' + | 'calledAt' > ->; +> & { groupLink?: string | null }; export abstract class ProjectIdeaRepository { abstract create(data: { @@ -52,6 +54,11 @@ export abstract class ProjectIdeaRepository { abstract remove(id: ProjectIdea['id']): Promise; + /** Tira o destaque de "projeto da vez" de todas as ideias. */ + abstract clearFeatured(): Promise; + + abstract findGroupLink(id: ProjectIdea['id']): Promise; + abstract upsertInterest( ideaId: ProjectIdea['id'], userId: number, diff --git a/src/project-teams/infrastructure/persistence/relational/entities/project-idea.entity.ts b/src/project-teams/infrastructure/persistence/relational/entities/project-idea.entity.ts index 12ebd22..770d7e8 100644 --- a/src/project-teams/infrastructure/persistence/relational/entities/project-idea.entity.ts +++ b/src/project-teams/infrastructure/persistence/relational/entities/project-idea.entity.ts @@ -54,6 +54,17 @@ export class ProjectIdeaEntity extends EntityRelationalHelper { @Column({ type: 'timestamp', nullable: true, default: null }) reviewedAt: Date | null; + /** Preenchido enquanto este for o "projeto da vez" (só um por vez). */ + @Column({ type: 'timestamp', nullable: true, default: null }) + featuredAt: Date | null; + + @Column({ type: 'varchar', length: 300, nullable: true, default: null }) + groupLink: string | null; + + /** Quando quem propôs chamou os interessados pela primeira vez. */ + @Column({ type: 'timestamp', nullable: true, default: null }) + calledAt: Date | null; + @CreateDateColumn() createdAt: Date; diff --git a/src/project-teams/infrastructure/persistence/relational/mappers/project.mapper.ts b/src/project-teams/infrastructure/persistence/relational/mappers/project.mapper.ts index fc87b77..fc6caee 100644 --- a/src/project-teams/infrastructure/persistence/relational/mappers/project.mapper.ts +++ b/src/project-teams/infrastructure/persistence/relational/mappers/project.mapper.ts @@ -44,6 +44,8 @@ export class ProjectMapper { idea.author = ProjectMapper.userSummary(raw.author); idea.reviewerId = raw.reviewerId; idea.reviewedAt = raw.reviewedAt; + idea.featuredAt = raw.featuredAt ?? null; + idea.calledAt = raw.calledAt ?? null; idea.interestCount = extras.interestCount; idea.teamId = extras.teamId; idea.createdAt = raw.createdAt; diff --git a/src/project-teams/infrastructure/persistence/relational/repositories/project-idea.repository.ts b/src/project-teams/infrastructure/persistence/relational/repositories/project-idea.repository.ts index 51b6834..6613820 100644 --- a/src/project-teams/infrastructure/persistence/relational/repositories/project-idea.repository.ts +++ b/src/project-teams/infrastructure/persistence/relational/repositories/project-idea.repository.ts @@ -122,13 +122,38 @@ export class ProjectIdeaRelationalRepository implements ProjectIdeaRepository { return idea; } - findPublic(paginationOptions: IPaginationOptions): Promise { - return this.findList( - { - status: In([ProjectIdeaStatus.APPROVED, ProjectIdeaStatus.TEAM_FORMED]), - }, - { createdAt: 'DESC' }, - paginationOptions, + /** Projeto da vez primeiro, depois os mais pedidos e, por fim, os mais novos. */ + async findPublic( + paginationOptions: IPaginationOptions, + ): Promise { + const rows = await this.ideaRepository + .createQueryBuilder('idea') + .select('idea.id', 'id') + .addSelect( + `(SELECT COUNT(DISTINCT interest."userId") FROM "project_idea_interest" interest WHERE interest."ideaId" = idea.id)`, + 'interestCount', + ) + .where('idea.status IN (:...statuses)', { + statuses: [ProjectIdeaStatus.APPROVED, ProjectIdeaStatus.TEAM_FORMED], + }) + .orderBy('(idea."featuredAt" IS NULL)', 'ASC') + .addOrderBy('"interestCount"', 'DESC') + .addOrderBy('idea."createdAt"', 'DESC') + .offset((paginationOptions.page - 1) * paginationOptions.limit) + .limit(paginationOptions.limit) + .getRawMany<{ id: string }>(); + if (rows.length === 0) { + return []; + } + + const ids = rows.map((row) => row.id); + const entities = await this.ideaRepository.find({ + where: { id: In(ids) }, + relations: IDEA_RELATIONS, + }); + const byId = new Map(entities.map((entity) => [entity.id, entity])); + return this.enrich( + ids.map((id) => byId.get(id)).filter((entity) => !!entity), ); } @@ -162,6 +187,23 @@ export class ProjectIdeaRelationalRepository implements ProjectIdeaRepository { await this.ideaRepository.delete(id); } + async clearFeatured(): Promise { + await this.ideaRepository + .createQueryBuilder() + .update(ProjectIdeaEntity) + .set({ featuredAt: null }) + .where('"featuredAt" IS NOT NULL') + .execute(); + } + + async findGroupLink(id: ProjectIdea['id']): Promise { + const entity = await this.ideaRepository.findOne({ + where: { id }, + select: { id: true, groupLink: true }, + }); + return entity?.groupLink ?? null; + } + async upsertInterest( ideaId: ProjectIdea['id'], userId: number, diff --git a/src/project-teams/project-ideas.controller.ts b/src/project-teams/project-ideas.controller.ts index 3fd5be5..0f617e4 100644 --- a/src/project-teams/project-ideas.controller.ts +++ b/src/project-teams/project-ideas.controller.ts @@ -36,6 +36,8 @@ import { ProjectIdeaInterest, SuggestedVacancy, } from './domain/project-idea'; +import { CallProjectInterestedDto } from './dto/call-project-interested.dto'; +import { FeatureProjectIdeaDto } from './dto/feature-project-idea.dto'; import { CreateProjectIdeaDto } from './dto/create-project-idea.dto'; import { CreateProjectIdeaRoleDto } from './dto/create-project-idea-role.dto'; import { FindProjectsDto } from './dto/find-projects.dto'; @@ -172,6 +174,45 @@ export class ProjectIdeasController { return this.ideasService.remove(id, req.user.id, canManageAny(req)); } + @Patch(':id/feature') + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt'), RolesGuard) + @Roles(RoleEnum.admin, RoleEnum.moderator) + @ApiParam({ name: 'id', type: String, required: true }) + @ApiOkResponse({ type: ProjectIdea }) + feature( + @Param('id', ParseUUIDPipe) id: string, + @Body() dto: FeatureProjectIdeaDto, + ) { + return this.ideasService.feature(id, dto.featured); + } + + @Post(':id/call') + @HttpCode(HttpStatus.OK) + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @ApiParam({ name: 'id', type: String, required: true }) + callInterested( + @Param('id', ParseUUIDPipe) id: string, + @Body() dto: CallProjectInterestedDto, + @Request() req, + ) { + return this.ideasService.callInterested( + id, + dto, + req.user.id, + canManageAny(req), + ); + } + + @Get(':id/group') + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @ApiParam({ name: 'id', type: String, required: true }) + getGroup(@Param('id', ParseUUIDPipe) id: string, @Request() req) { + return this.ideasService.getGroup(id, req.user.id, canManageAny(req)); + } + @Put(':id/interest') @ApiBearerAuth() @UseGuards(AuthGuard('jwt')) diff --git a/src/project-teams/project-ideas.service.spec.ts b/src/project-teams/project-ideas.service.spec.ts new file mode 100644 index 0000000..544184e --- /dev/null +++ b/src/project-teams/project-ideas.service.spec.ts @@ -0,0 +1,169 @@ +import { + ForbiddenException, + UnprocessableEntityException, +} from '@nestjs/common'; +import { ProjectIdea } from './domain/project-idea'; +import { ProjectIdeaStatus } from './domain/project-idea-status.enum'; +import { ProjectIdeasService } from './project-ideas.service'; + +const AUTHOR = 1; + +function makeIdea(overrides: Partial = {}): ProjectIdea { + return { + id: 'idea-1', + title: 'Gestão de doadores', + description: 'desc', + tags: [], + status: ProjectIdeaStatus.APPROVED, + authorId: AUTHOR, + featuredAt: null, + calledAt: null, + ...overrides, + } as ProjectIdea; +} + +function setup(idea: ProjectIdea, interestedIds: number[]) { + const ideaRepository = { + findById: jest.fn().mockResolvedValue(idea), + findInterests: jest + .fn() + .mockResolvedValue(interestedIds.map((userId) => ({ userId }))), + findUserInterests: jest.fn().mockResolvedValue([]), + findGroupLink: jest.fn().mockResolvedValue('https://chat.example/abc'), + clearFeatured: jest.fn().mockResolvedValue(undefined), + update: jest.fn().mockImplementation((_id, payload) => ({ + ...idea, + ...payload, + })), + }; + const notificationsService = { + create: jest.fn().mockResolvedValue(undefined), + }; + const rewardsService = { grant: jest.fn().mockResolvedValue(undefined) }; + const service = new ProjectIdeasService( + ideaRepository as never, + notificationsService as never, + rewardsService as never, + ); + return { service, ideaRepository, notificationsService, rewardsService }; +} + +describe('ProjectIdeasService - projeto da vez e chamada', () => { + describe('feature', () => { + it('should desmarcar os outros, marcar este e avisar os interessados', async () => { + const { service, ideaRepository, notificationsService } = setup( + makeIdea(), + [AUTHOR, 2, 3], + ); + + await service.feature('idea-1', true); + + expect(ideaRepository.clearFeatured).toHaveBeenCalled(); + expect(ideaRepository.update).toHaveBeenCalledWith('idea-1', { + featuredAt: expect.any(Date), + }); + // autor não é avisado do próprio projeto + expect(notificationsService.create).toHaveBeenCalledTimes(2); + }); + + it('should não repetir nada se já é o projeto da vez', async () => { + const { service, ideaRepository } = setup( + makeIdea({ featuredAt: new Date() }), + [2], + ); + + await service.feature('idea-1', true); + + expect(ideaRepository.clearFeatured).not.toHaveBeenCalled(); + expect(ideaRepository.update).not.toHaveBeenCalled(); + }); + + it('should remover o destaque', async () => { + const { service, ideaRepository } = setup( + makeIdea({ featuredAt: new Date() }), + [2], + ); + + await service.feature('idea-1', false); + + expect(ideaRepository.update).toHaveBeenCalledWith('idea-1', { + featuredAt: null, + }); + }); + }); + + describe('callInterested', () => { + const dto = { groupLink: 'https://chat.whatsapp.com/abc' }; + + it('should chamar os interessados e dar XP na primeira chamada', async () => { + const { service, notificationsService, rewardsService } = setup( + makeIdea(), + [2, 2, 3], + ); + + const result = await service.callInterested('idea-1', dto, AUTHOR, false); + + expect(result.notified).toBe(2); + expect(notificationsService.create).toHaveBeenCalledTimes(2); + const rewards = rewardsService.grant.mock.calls[0][0]; + expect(rewards.map((r: { userId: number }) => r.userId)).toEqual([ + AUTHOR, + 2, + 3, + ]); + }); + + it('should não dar XP de novo em chamadas seguintes', async () => { + const { service, rewardsService } = setup( + makeIdea({ calledAt: new Date() }), + [2], + ); + + await service.callInterested('idea-1', dto, AUTHOR, false); + + expect(rewardsService.grant).not.toHaveBeenCalled(); + }); + + it('should recusar quem não propôs o projeto', async () => { + const { service } = setup(makeIdea(), [2]); + + await expect( + service.callInterested('idea-1', dto, 99, false), + ).rejects.toBeInstanceOf(ForbiddenException); + }); + + it('should recusar quando não há interessados', async () => { + const { service } = setup(makeIdea(), [AUTHOR]); + + await expect( + service.callInterested('idea-1', dto, AUTHOR, false), + ).rejects.toBeInstanceOf(UnprocessableEntityException); + }); + }); + + describe('getGroup', () => { + it('should negar o link a quem não tem interesse', async () => { + const { service } = setup(makeIdea({ calledAt: new Date() }), [2]); + + await expect( + service.getGroup('idea-1', 99, false), + ).rejects.toBeInstanceOf(ForbiddenException); + }); + + it('should entregar o link à pessoa que propôs', async () => { + const { service } = setup(makeIdea({ calledAt: new Date() }), [2]); + + const result = await service.getGroup('idea-1', AUTHOR, false); + + expect(result.groupLink).toBe('https://chat.example/abc'); + }); + + it('should não entregar link antes da chamada', async () => { + const { service } = setup(makeIdea(), [2]); + + const result = await service.getGroup('idea-1', AUTHOR, false); + + expect(result.groupLink).toBeNull(); + }); + }); +}); diff --git a/src/project-teams/project-ideas.service.ts b/src/project-teams/project-ideas.service.ts index 3eb9342..e3ae337 100644 --- a/src/project-teams/project-ideas.service.ts +++ b/src/project-teams/project-ideas.service.ts @@ -16,12 +16,18 @@ import { } from './domain/project-idea'; import { ProjectIdeaStatus } from './domain/project-idea-status.enum'; import { PROJECT_ROLE_LABELS, ProjectRole } from './domain/project-role.enum'; +import { CallProjectInterestedDto } from './dto/call-project-interested.dto'; import { CreateProjectIdeaRoleDto } from './dto/create-project-idea-role.dto'; import { CreateProjectIdeaDto } from './dto/create-project-idea.dto'; import { ReviewProjectIdeaDto } from './dto/review-project-idea.dto'; import { SetProjectInterestDto } from './dto/set-project-interest.dto'; import { UpdateProjectIdeaDto } from './dto/update-project-idea.dto'; import { ProjectIdeaRepository } from './infrastructure/persistence/project-idea.repository'; +import { + PROJECT_AUTHOR_XP, + PROJECT_PARTICIPANT_XP, + ProjectRewardsService, +} from './project-rewards.service'; import { suggestVacancies } from './vacancy-suggestions'; const PUBLIC_STATUSES = [ @@ -37,6 +43,7 @@ export class ProjectIdeasService { constructor( private readonly ideaRepository: ProjectIdeaRepository, private readonly notificationsService: NotificationsService, + private readonly rewardsService: ProjectRewardsService, ) {} private async getOrFail(id: ProjectIdea['id']): Promise { @@ -333,6 +340,143 @@ export class ProjectIdeasService { } } + /** Ids únicos de quem tem interesse, sem contar quem propôs. */ + private async interestedUserIds(idea: ProjectIdea): Promise { + const interests = await this.ideaRepository.findInterests(idea.id); + return [...new Set(interests.map((interest) => interest.userId))].filter( + (userId) => userId !== idea.authorId, + ); + } + + private notifyMany( + userIds: number[], + notification: { + type: NotificationType; + title: string; + body: string; + idea: ProjectIdea; + }, + ) { + return Promise.all( + userIds.map((userId) => + this.notificationsService + .create({ + userId, + type: notification.type, + title: notification.title, + body: notification.body, + relatedId: notification.idea.id, + link: `/projetos/${notification.idea.id}`, + payload: { ideaId: notification.idea.id }, + }) + .catch(() => undefined), + ), + ); + } + + /** Moderação escolhe o "projeto da vez"; só existe um por vez. */ + async feature(id: ProjectIdea['id'], featured: boolean) { + const idea = await this.findPublicDetail(id); + if (!featured) { + return this.ideaRepository.update(id, { featuredAt: null }); + } + if (idea.featuredAt) { + return idea; + } + + await this.ideaRepository.clearFeatured(); + const updated = await this.ideaRepository.update(id, { + featuredAt: new Date(), + }); + await this.notifyMany(await this.interestedUserIds(idea), { + type: NotificationType.PROJECT_IDEA_FEATURED, + title: `Projeto da vez: ${idea.title}`, + body: 'O projeto em que você marcou interesse foi escolhido como projeto da vez.', + idea, + }); + return updated; + } + + /** + * Quem propôs (ou a moderação) chama os interessados para o grupo. O XP + * é dado uma única vez por projeto, na primeira chamada. + */ + async callInterested( + id: ProjectIdea['id'], + dto: CallProjectInterestedDto, + userId: number, + canManageAny: boolean, + ) { + const idea = await this.findPublicDetail(id); + this.assertAuthorOrAdmin( + idea, + userId, + canManageAny, + 'Apenas quem propôs o projeto ou a moderação pode chamar os interessados.', + ); + + const interestedIds = await this.interestedUserIds(idea); + if (interestedIds.length === 0) { + throw new UnprocessableEntityException({ + status: HttpStatus.UNPROCESSABLE_ENTITY, + errors: { interested: 'Ainda não há interessados para chamar.' }, + }); + } + + const firstCall = !idea.calledAt; + const updated = await this.ideaRepository.update(id, { + groupLink: dto.groupLink, + calledAt: idea.calledAt ?? new Date(), + }); + + const message = dto.message?.trim(); + await this.notifyMany(interestedIds, { + type: NotificationType.PROJECT_IDEA_CALLED, + title: `Vamos começar: ${idea.title}`, + body: message + ? `${message} Abra o projeto para entrar no grupo.` + : 'Quem propôs o projeto chamou os interessados. Abra o projeto para entrar no grupo.', + idea, + }); + + if (firstCall) { + await this.rewardsService.grant([ + { + userId: idea.authorId, + amount: PROJECT_AUTHOR_XP, + description: `Projeto colocado em ação: ${idea.title}`, + }, + ...interestedIds.map((interestedId) => ({ + userId: interestedId, + amount: PROJECT_PARTICIPANT_XP, + description: `Participação no projeto: ${idea.title}`, + })), + ]); + } + + return { notified: interestedIds.length, calledAt: updated?.calledAt }; + } + + /** Link do grupo, visível só para quem propôs, interessados e moderação. */ + async getGroup(id: ProjectIdea['id'], userId: number, canManageAny: boolean) { + const idea = await this.findPublicDetail(id); + const allowed = + canManageAny || + idea.authorId === userId || + (await this.ideaRepository.findUserInterests(id, userId)).length > 0; + if (!allowed) { + throw new ForbiddenException( + 'Apenas quem tem interesse no projeto pode ver o grupo.', + ); + } + return { + groupLink: idea.calledAt + ? await this.ideaRepository.findGroupLink(id) + : null, + calledAt: idea.calledAt, + }; + } + async removeInterest(id: ProjectIdea['id'], userId: number, role?: string) { await this.findPublicDetail(id); await this.ideaRepository.removeInterest(id, userId, role); diff --git a/src/project-teams/project-rewards.service.ts b/src/project-teams/project-rewards.service.ts new file mode 100644 index 0000000..1659347 --- /dev/null +++ b/src/project-teams/project-rewards.service.ts @@ -0,0 +1,70 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { InjectDataSource } from '@nestjs/typeorm'; +import { DataSource, EntityManager } from 'typeorm'; +import { GamificationProfileEntity } from '../gamification-profiles/infrastructure/persistence/relational/entities/gamification-profile.entity'; +import { TransactionCategoryEnum } from '../transactions/domain/transaction-category.enum'; +import { TransactionEntity } from '../transactions/infrastructure/persistence/relational/entities/transaction.entity'; + +/** XP de quem propôs a ideia quando chama os interessados. */ +export const PROJECT_AUTHOR_XP = 20; +/** XP de cada pessoa interessada que foi chamada para o grupo. */ +export const PROJECT_PARTICIPANT_XP = 5; + +@Injectable() +export class ProjectRewardsService { + private readonly logger = new Logger(ProjectRewardsService.name); + + constructor(@InjectDataSource() private readonly dataSource: DataSource) {} + + /** + * Dá XP a cada usuário da lista. Falhar na recompensa nunca deve impedir + * a chamada, então os erros só são registrados. + */ + async grant( + rewards: { userId: number; amount: number; description: string }[], + ): Promise { + for (const reward of rewards) { + try { + await this.dataSource.transaction((manager) => + this.grantOne(manager, reward), + ); + } catch (error) { + this.logger.error( + `Falha ao dar XP ao usuário ${reward.userId}`, + error instanceof Error ? error.stack : String(error), + ); + } + } + } + + private async grantOne( + manager: EntityManager, + reward: { userId: number; amount: number; description: string }, + ): Promise { + const profile = await manager.findOne(GamificationProfileEntity, { + where: { userId: reward.userId }, + select: { id: true }, + }); + if (!profile) { + return; + } + for (const column of [ + 'totalXp', + 'currentMonthlyXp', + 'currentYearlyXp', + ] as const) { + await manager.increment( + GamificationProfileEntity, + { id: profile.id }, + column, + reward.amount, + ); + } + await manager.save(TransactionEntity, { + profile: { id: profile.id }, + category: TransactionCategoryEnum.XP_REWARD, + amount: reward.amount, + description: reward.description, + }); + } +} diff --git a/src/project-teams/project-teams.module.ts b/src/project-teams/project-teams.module.ts index 12646a1..c65b468 100644 --- a/src/project-teams/project-teams.module.ts +++ b/src/project-teams/project-teams.module.ts @@ -3,13 +3,14 @@ import { NotificationsModule } from '../notifications/notifications.module'; import { RelationalProjectTeamsPersistenceModule } from './infrastructure/persistence/relational/relational-persistence.module'; import { ProjectIdeasController } from './project-ideas.controller'; import { ProjectIdeasService } from './project-ideas.service'; +import { ProjectRewardsService } from './project-rewards.service'; import { ProjectTeamsController } from './project-teams.controller'; import { ProjectTeamsService } from './project-teams.service'; @Module({ imports: [RelationalProjectTeamsPersistenceModule, NotificationsModule], controllers: [ProjectIdeasController, ProjectTeamsController], - providers: [ProjectIdeasService, ProjectTeamsService], + providers: [ProjectIdeasService, ProjectTeamsService, ProjectRewardsService], exports: [ProjectIdeasService, ProjectTeamsService], }) export class ProjectTeamsModule {}