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
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

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

public async up(queryRunner: QueryRunner): Promise<void> {
for (const value of ['PROJECT_IDEA_FEATURED', 'PROJECT_IDEA_CALLED']) {
await queryRunner.query(
`ALTER TYPE "notification_type_enum" ADD VALUE IF NOT EXISTS '${value}'`,
);

Check warning on line 12 in src/database/migrations/1787400000000-ProjectIdeaFeaturedAndCall.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Unexpected `await` inside a loop.

See more on https://sonarcloud.io/project/issues?id=devs-tocantins_api-engajamento2&issues=AaGFKPQ3-ChLLDlym8YP&open=AaGFKPQ3-ChLLDlym8YP&pullRequest=115
}

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<void> {
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.
}
}
2 changes: 2 additions & 0 deletions src/notifications/domain/notification-type.enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
}
12 changes: 12 additions & 0 deletions src/project-teams/domain/project-idea.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
24 changes: 24 additions & 0 deletions src/project-teams/dto/call-project-interested.dto.ts
Original file line number Diff line number Diff line change
@@ -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;
}
11 changes: 11 additions & 0 deletions src/project-teams/dto/feature-project-idea.dto.ts
Original file line number Diff line number Diff line change
@@ -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;
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ export type ProjectIdeaUpdate = Partial<
| 'rejectionReason'
| 'reviewerId'
| 'reviewedAt'
| 'featuredAt'
| 'calledAt'
>
>;
> & { groupLink?: string | null };

export abstract class ProjectIdeaRepository {
abstract create(data: {
Expand Down Expand Up @@ -52,6 +54,11 @@ export abstract class ProjectIdeaRepository {

abstract remove(id: ProjectIdea['id']): Promise<void>;

/** Tira o destaque de "projeto da vez" de todas as ideias. */
abstract clearFeatured(): Promise<void>;

abstract findGroupLink(id: ProjectIdea['id']): Promise<string | null>;

abstract upsertInterest(
ideaId: ProjectIdea['id'],
userId: number,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,13 +122,38 @@ export class ProjectIdeaRelationalRepository implements ProjectIdeaRepository {
return idea;
}

findPublic(paginationOptions: IPaginationOptions): Promise<ProjectIdea[]> {
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<ProjectIdea[]> {
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),
);
}

Expand Down Expand Up @@ -162,6 +187,23 @@ export class ProjectIdeaRelationalRepository implements ProjectIdeaRepository {
await this.ideaRepository.delete(id);
}

async clearFeatured(): Promise<void> {
await this.ideaRepository
.createQueryBuilder()
.update(ProjectIdeaEntity)
.set({ featuredAt: null })
.where('"featuredAt" IS NOT NULL')
.execute();
}

async findGroupLink(id: ProjectIdea['id']): Promise<string | null> {
const entity = await this.ideaRepository.findOne({
where: { id },
select: { id: true, groupLink: true },
});
return entity?.groupLink ?? null;
}

async upsertInterest(
ideaId: ProjectIdea['id'],
userId: number,
Expand Down
41 changes: 41 additions & 0 deletions src/project-teams/project-ideas.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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'))
Expand Down
Loading
Loading