diff --git a/deploy.sh b/deploy.sh index a00bc8a..3af07e2 100755 --- a/deploy.sh +++ b/deploy.sh @@ -1,5 +1,5 @@ #!/bin/bash -# deploy.sh — sincroniza o código e reconstrói o container na VM +# deploy.sh — Faz o build local e envia a imagem pronta para a VM # Uso: ./deploy.sh set -e @@ -7,28 +7,32 @@ set -e SSH_KEY="ssh-key-2026-04-01.key" REMOTE="ubuntu@136.248.75.34" COMPOSE="docker-compose.prod.yaml" +IMAGE_NAME="api-legado-dev:latest" +TAR_FILE="app-image.tar.gz" if [ ! -f "$SSH_KEY" ]; then echo "Erro: chave SSH '$SSH_KEY' não encontrada. Execute a partir da raiz do projeto." exit 1 fi -echo "==> Sincronizando código..." -rsync -avz \ - --exclude='.git' \ - --exclude='node_modules' \ - --exclude='dist' \ - --exclude='.env' \ - --exclude='.env.prod' \ - --exclude='ssh-key-*.key' \ +echo "==> [1/4] Realizando o build da imagem localmente para AMD64..." +# Usa o buildx do docker para construir a imagem cross-platform +docker buildx build --platform linux/amd64 -t $IMAGE_NAME -f Dockerfile . --load + +echo "==> [2/4] Compactando a imagem Docker (isso pode demorar um pouco)..." +docker save $IMAGE_NAME | gzip > $TAR_FILE + +echo "==> [3/4] Enviando a imagem e configuração para a VM..." +rsync -avP \ -e "ssh -i $SSH_KEY -o StrictHostKeyChecking=no" \ - . "$REMOTE:~/app/" + $TAR_FILE $COMPOSE "$REMOTE:~/app/" -echo "==> Reconstruindo e subindo container..." +echo "==> [4/4] Carregando a imagem e reiniciando os containers na VM..." ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no "$REMOTE" \ "cd ~/app && \ + echo 'Carregando imagem no Docker...' && \ + gunzip -c $TAR_FILE | sudo docker load && \ sudo docker compose -f $COMPOSE down && \ - sudo docker compose -f $COMPOSE build --no-cache && \ sudo docker compose -f $COMPOSE up -d" echo "==> Aguardando API..." diff --git a/docs/archive/file-uploading.md b/docs/archive/file-uploading.md index 54cac1f..845775f 100644 --- a/docs/archive/file-uploading.md +++ b/docs/archive/file-uploading.md @@ -68,10 +68,9 @@ AWS_S3_ENDPOINT=http://minio:9000 O recurso `/api/v1/files/upload` aceita Multipart Form. Ele te devolve um Modelo `File` base contendo o ID e Path (`caminho`) para você atrelar a qualquer outra entidade. -### Exemplo de upload de Avatar: -1. Cliente envia o arquivo via Requisição POST `api/v1/files/upload`. -2. O Backend te devolve o ID. -3. Você passa esse ID para atualizar seu Usuário em `PATCH /api/v1/auth/me`. +**Formatos Suportados:** +- Imagens: `.jpg`, `.jpeg`, `.png`, `.webp`, `.gif`. +- Tamanho máximo: Configurado via `FILE_MAX_FILE_SIZE` no `.env`. ## Fluxo de Upload `s3` diff --git a/docs/auth.md b/docs/auth.md index d7966a7..50958e0 100644 --- a/docs/auth.md +++ b/docs/auth.md @@ -16,15 +16,21 @@ O sistema de Login padrão permite criar conta e entrar usando E-mail e Senha tradicional. +**Importante: Confirmação de E-mail Obrigatória** +Após o cadastro (`POST /api/v1/auth/email/register`), o usuário é criado com o status `INACTIVE`. O sistema envia automaticamente um e-mail de ativação. Enquanto o e-mail não for confirmado, qualquer tentativa de login via formulário ou rede social retornará um erro `422 (inactive)`. + ```mermaid sequenceDiagram participant A as Frontend (Web/Mobile) participant B as Backend API + participant C as E-mail (SMTP) A->>B: 1. Cadastro com E-mail e Senha (Sign up) - A->>B: 2. Login com E-mail e Senha (Sign in) - B->>A: 3. Responde com Token JWT - A->>B: 4. Faz requisições posteriores usando o JWT no Header + B-->>C: 2. Dispara e-mail de ativação + C-->>A: 3. Usuário clica no link de confirmação + A->>B: 4. Chama API de confirmação + A->>B: 5. Login com E-mail e Senha (Sign in) + B->>A: 6. Responde com Token JWT ``` ## Fluxo de Autenticação com Login Social @@ -37,12 +43,12 @@ sequenceDiagram participant A as Frontend (Web/Mobile) participant C as Backend API - A->>B: 1. Autenticação através do provedor - B->>A: 2. Retorna o Access Token de redes sociais - A->>C: 3. Envia esse Access Token para o Backend via API - C->>A: 4. Valida e responde com Token JWT da nossa plataforma - A->>C: 5. Faz requisições posteriores usando o JWT no Header -``` +## Segurança e Rate Limiting + +A API possui proteção contra ataques de força bruta e spam de e-mails usando `ThrottlerGuard`: +- **Esqueci minha senha:** Limite de 3 tentativas por minuto e 10 por hora. +- **Cadastro de conta:** Limite de 5 tentativas por minuto e 10 por hora. +- **Login:** Limite de 5 tentativas por minuto e 20 por hora. Para autenticar com serviços externos: 1. No Frontend, o usuário se loga usando o SDK do Google ou o fluxo OAuth do GitHub, resultando num Access token. diff --git a/docs/project-teams.md b/docs/project-teams.md new file mode 100644 index 0000000..8edef8a --- /dev/null +++ b/docs/project-teams.md @@ -0,0 +1,19 @@ +# Times de Projetos + +Módulo `src/project-teams`: membros propõem ideias de projeto, a moderação aprova, outros membros demonstram interesse em vagas e o autor forma o time. + +## Fluxo + +1. Membro cria uma ideia (`POST /v1/project-ideas`) — status `PENDING`. +2. Moderador/admin revisa (`PATCH /v1/project-ideas/:id/review`) — `APPROVED` ou `REJECTED` (com motivo). O autor é notificado. +3. Membros marcam interesse em um cargo (`PUT /v1/project-ideas/:id/interest`); o autor vê os interessados e as vagas sugeridas (`GET /v1/project-ideas/:id/suggested-vacancies`). +4. O autor cria o time (`POST /v1/project-teams`) e adiciona membros (`POST /v1/project-teams/:id/members`) — a ideia passa para `TEAM_FORMED`. + +## Endpoints + +- `project-ideas`: criar, listar, `mine`, `pending`, detalhe, `:id/manage`, `:id/review`, editar, excluir, `:id/interest` (PUT/DELETE/GET), `:id/interests`, `:id/suggested-vacancies`. +- `project-teams`: criar, listar, `mine`, detalhe, editar, `:id/members` (POST), `:id/members/:userId` (DELETE). + +## Banco + +Migration `CreateProjectTeams`: tabelas `project_idea`, `project_idea_interest`, `project_team`, `project_team_member`, `project_team_vacancy`, enums de papel/status e novos tipos de notificação (`PROJECT_IDEA_APPROVED`, `PROJECT_IDEA_REJECTED`, `PROJECT_IDEA_INTEREST`, `PROJECT_TEAM_MEMBER_ADDED`). Roda automaticamente na subida do container (`migration:run:prod`). diff --git a/docs/translations.md b/docs/translations.md index 086a128..677cf3b 100644 --- a/docs/translations.md +++ b/docs/translations.md @@ -11,16 +11,20 @@ O dev-starter já vem pronto para garantir respostas API Poliglotas caso seu Front-end exija ou mude de língua no Painel do Usuário! Assim, o Backend não reenvia os retornos hardcoded (chumbados e sempre iguais), e sim lê um dicionário local a depender da chave. +## Configuração de Idioma + +O sistema está configurado para usar **`pt-BR` (Português Brasileiro)** como idioma padrão e de fallback. Se a tradução de uma chave não for encontrada ou o cabeçalho de idioma for omitido, o sistema responderá em português. + ## Como adicionar novas traduções 1. Vá à raiz em `src/i18n`. -2. O Boilerplate sempre checa os JSONs em pastas atreladas. Existe o `en` atualmente. -3. Você cria a pasta `pt-BR` e espelha os arquivos copiando e modificando (exemplo, copie os valores do JSON dict de validações e converta as regras "Missing Field" do class-validator para português!) +2. O Boilerplate sempre checa os JSONs em pastas atreladas (`en` e `pt-BR`). +3. Caso adicione uma nova chave, lembre-se de atualizar ambos os arquivos para manter a consistência. ## Como usar arquivos traduzidos para o Front 1. Adicione/configure o Fetch das APIs com o novo cabeçalho (`Header`) contendo a requisição: - **`x-custom-lang`**: `pt-BR` -2. Ao receber esta flag de custom-lang no contexto do request (ou via Cookie local), o `i18n-module` se vira e transforma todas as Exceptions globais! + **`x-custom-lang`**: `en` (para inglês) ou `pt-BR`. +2. Se o cabeçalho for omitido, o backend assumirá `pt-BR` automaticamente. ## Como verificar um I18N direto num serviço diff --git a/package-lock.json b/package-lock.json index 1bbb124..74f670a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6088,7 +6088,7 @@ "version": "1.13.4", "resolved": "https://registry.npmjs.org/@swc/core/-/core-1.13.4.tgz", "integrity": "sha512-bCq2GCuKV16DSOOEdaRqHMm1Ok4YEoLoNdgdzp8BS/Hxxr/0NVCHBUgRLLRy/TlJGv20Idx+djd5FIDvsnqMaw==", - "devOptional": true, + "dev": true, "hasInstallScript": true, "license": "Apache-2.0", "dependencies": { @@ -6130,6 +6130,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "Apache-2.0 AND MIT", "optional": true, "os": [ @@ -6146,6 +6147,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "Apache-2.0 AND MIT", "optional": true, "os": [ @@ -6162,6 +6164,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "Apache-2.0", "optional": true, "os": [ @@ -6178,6 +6181,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "Apache-2.0 AND MIT", "optional": true, "os": [ @@ -6194,6 +6198,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "Apache-2.0 AND MIT", "optional": true, "os": [ @@ -6210,6 +6215,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "Apache-2.0 AND MIT", "optional": true, "os": [ @@ -6226,6 +6232,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "Apache-2.0 AND MIT", "optional": true, "os": [ @@ -6242,6 +6249,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "Apache-2.0 AND MIT", "optional": true, "os": [ @@ -6258,6 +6266,7 @@ "cpu": [ "ia32" ], + "dev": true, "license": "Apache-2.0 AND MIT", "optional": true, "os": [ @@ -6274,6 +6283,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "Apache-2.0 AND MIT", "optional": true, "os": [ @@ -6287,14 +6297,14 @@ "version": "0.1.3", "resolved": "https://registry.npmjs.org/@swc/counter/-/counter-0.1.3.tgz", "integrity": "sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ==", - "devOptional": true, + "dev": true, "license": "Apache-2.0" }, "node_modules/@swc/types": { "version": "0.1.27", "resolved": "https://registry.npmjs.org/@swc/types/-/types-0.1.27.tgz", "integrity": "sha512-K6h3iUlqeM946U4sXFYeahefR1YBbXJvko+hv8WS8/0BNJ4OHiHRywMnQUJCqkR7Y9+hqQ1TvEpiKqUhz7NEFg==", - "devOptional": true, + "dev": true, "license": "Apache-2.0", "dependencies": { "@swc/counter": "^0.1.3" diff --git a/src/activities/activities.controller.spec.ts b/src/activities/activities.controller.spec.ts index b0a341f..82e53b8 100644 --- a/src/activities/activities.controller.spec.ts +++ b/src/activities/activities.controller.spec.ts @@ -11,13 +11,16 @@ const mockActivity: Activity = { title: 'Artigo Publicado', description: 'Publicou um artigo técnico em blog reconhecido', fixedReward: 100, + auditorReward: 10, isHidden: false, secretCode: null, requiresProof: true, requiresDescription: false, cooldownHours: 24, + requiresActivityDate: false, effortTiers: null, isFreeform: false, + createsGithubIssue: false, createdAt: new Date('2026-01-01'), updatedAt: new Date('2026-01-01'), }; @@ -62,6 +65,7 @@ describe('ActivitiesController', () => { title: 'Artigo Publicado', description: 'Publicou um artigo técnico em blog reconhecido', fixedReward: 100, + auditorReward: 10, isHidden: false, secretCode: null, requiresProof: true, diff --git a/src/activities/activities.controller.ts b/src/activities/activities.controller.ts index f68743e..bcab0e1 100644 --- a/src/activities/activities.controller.ts +++ b/src/activities/activities.controller.ts @@ -92,6 +92,8 @@ export class ActivitiesController { return infinityPagination( await this.activitiesService.findPublicWithPagination({ paginationOptions: { page, limit }, + search: query?.search, + view: query?.view, }), { page, limit }, ); diff --git a/src/activities/activities.service.ts b/src/activities/activities.service.ts index df6d5c4..dd6adf7 100644 --- a/src/activities/activities.service.ts +++ b/src/activities/activities.service.ts @@ -25,13 +25,16 @@ export class ActivitiesService { title: createActivityDto.title, description: createActivityDto.description, fixedReward: createActivityDto.fixedReward, + auditorReward: createActivityDto.auditorReward, isHidden: createActivityDto.isHidden ?? false, secretCode: createActivityDto.secretCode ?? null, requiresProof: createActivityDto.requiresProof ?? false, requiresDescription: createActivityDto.requiresDescription ?? false, cooldownHours: createActivityDto.cooldownHours ?? 0, + requiresActivityDate: createActivityDto.requiresActivityDate ?? false, effortTiers: createActivityDto.effortTiers ?? null, isFreeform: createActivityDto.isFreeform ?? false, + createsGithubIssue: createActivityDto.createsGithubIssue ?? false, }); } @@ -72,6 +75,9 @@ export class ActivitiesService { ...(updateActivityDto.fixedReward !== undefined && { fixedReward: updateActivityDto.fixedReward, }), + ...(updateActivityDto.auditorReward !== undefined && { + auditorReward: updateActivityDto.auditorReward, + }), ...(updateActivityDto.isHidden !== undefined && { isHidden: updateActivityDto.isHidden, }), @@ -84,12 +90,18 @@ export class ActivitiesService { ...(updateActivityDto.cooldownHours !== undefined && { cooldownHours: updateActivityDto.cooldownHours, }), + ...(updateActivityDto.requiresActivityDate !== undefined && { + requiresActivityDate: updateActivityDto.requiresActivityDate, + }), ...(updateActivityDto.effortTiers !== undefined && { effortTiers: updateActivityDto.effortTiers, }), ...(updateActivityDto.isFreeform !== undefined && { isFreeform: updateActivityDto.isFreeform, }), + ...(updateActivityDto.createsGithubIssue !== undefined && { + createsGithubIssue: updateActivityDto.createsGithubIssue, + }), }); } @@ -99,14 +111,20 @@ export class ActivitiesService { findPublicWithPagination({ paginationOptions, + search, + view, }: { paginationOptions: IPaginationOptions; + search?: string; + view?: 'card' | 'list'; }) { return this.activityRepository.findPublicWithPagination({ paginationOptions: { page: paginationOptions.page, limit: paginationOptions.limit, }, + search, + view, }); } diff --git a/src/activities/domain/activity.ts b/src/activities/domain/activity.ts index af6c6cc..aaf6ee2 100644 --- a/src/activities/domain/activity.ts +++ b/src/activities/domain/activity.ts @@ -64,6 +64,20 @@ export class Activity { }) cooldownHours: number; + @ApiProperty({ + type: Number, + description: 'XP concedido ao moderador que revisar esta atividade', + example: 10, + }) + auditorReward: number; + + @ApiProperty({ + type: Boolean, + description: 'Exige preenchimento da data em que a atividade foi realizada', + example: false, + }) + requiresActivityDate: boolean = false; + @ApiProperty({ type: [EffortTier], nullable: true, @@ -80,6 +94,14 @@ export class Activity { }) isFreeform: boolean; + @ApiProperty({ + type: Boolean, + description: + 'Se true, ao aprovar a submissão o sistema cria a issue de verdade no GitHub', + example: false, + }) + createsGithubIssue: boolean; + @ApiProperty() createdAt: Date; diff --git a/src/activities/dto/create-activity.dto.ts b/src/activities/dto/create-activity.dto.ts index 5374e79..4e65dc2 100644 --- a/src/activities/dto/create-activity.dto.ts +++ b/src/activities/dto/create-activity.dto.ts @@ -30,6 +30,11 @@ export class CreateActivityDto { @Min(1) fixedReward: number; + @ApiProperty({ example: 10 }) + @IsInt() + @Min(0) + auditorReward: number; + @ApiProperty({ example: false, required: false }) @IsOptional() @IsBoolean() @@ -58,6 +63,11 @@ export class CreateActivityDto { @Min(0) cooldownHours?: number; + @ApiProperty({ example: false, required: false }) + @IsOptional() + @IsBoolean() + requiresActivityDate?: boolean; + @ApiPropertyOptional({ type: [EffortTier], description: @@ -77,4 +87,13 @@ export class CreateActivityDto { @IsOptional() @IsBoolean() isFreeform?: boolean; + + @ApiPropertyOptional({ + example: false, + description: + 'Se true, ao aprovar a submissão o sistema cria a issue de verdade no GitHub', + }) + @IsOptional() + @IsBoolean() + createsGithubIssue?: boolean; } diff --git a/src/activities/dto/find-all-activities.dto.ts b/src/activities/dto/find-all-activities.dto.ts index 97bb2b4..1e81d03 100644 --- a/src/activities/dto/find-all-activities.dto.ts +++ b/src/activities/dto/find-all-activities.dto.ts @@ -1,5 +1,5 @@ import { ApiPropertyOptional } from '@nestjs/swagger'; -import { IsNumber, IsOptional } from 'class-validator'; +import { IsNumber, IsOptional, IsString, IsIn } from 'class-validator'; import { Transform } from 'class-transformer'; export class FindAllActivitiesDto { @@ -14,4 +14,14 @@ export class FindAllActivitiesDto { @IsNumber() @IsOptional() limit?: number; + + @ApiPropertyOptional() + @IsString() + @IsOptional() + search?: string; + + @ApiPropertyOptional({ enum: ['card', 'list'] }) + @IsIn(['card', 'list']) + @IsOptional() + view?: 'card' | 'list'; } diff --git a/src/activities/infrastructure/persistence/activity.repository.ts b/src/activities/infrastructure/persistence/activity.repository.ts index 656a73c..a41ce4e 100644 --- a/src/activities/infrastructure/persistence/activity.repository.ts +++ b/src/activities/infrastructure/persistence/activity.repository.ts @@ -27,8 +27,12 @@ export abstract class ActivityRepository { abstract findPublicWithPagination({ paginationOptions, + search, + view, }: { paginationOptions: IPaginationOptions; + search?: string; + view?: 'card' | 'list'; }): Promise; abstract findBySecretCode( diff --git a/src/activities/infrastructure/persistence/relational/entities/activity.entity.ts b/src/activities/infrastructure/persistence/relational/entities/activity.entity.ts index e8ca0a2..439222b 100644 --- a/src/activities/infrastructure/persistence/relational/entities/activity.entity.ts +++ b/src/activities/infrastructure/persistence/relational/entities/activity.entity.ts @@ -39,12 +39,21 @@ export class ActivityEntity extends EntityRelationalHelper { @Column({ type: 'int', default: 0 }) cooldownHours: number; + @Column({ type: 'int', default: 10 }) + auditorReward: number; + + @Column({ type: 'boolean', default: false }) + requiresActivityDate: boolean; + @Column({ type: 'jsonb', nullable: true, default: null }) effortTiers: EffortTier[] | null; @Column({ type: 'boolean', default: false }) isFreeform: boolean; + @Column({ type: 'boolean', default: false }) + createsGithubIssue: boolean; + @CreateDateColumn() createdAt: Date; diff --git a/src/activities/infrastructure/persistence/relational/mappers/activity.mapper.ts b/src/activities/infrastructure/persistence/relational/mappers/activity.mapper.ts index 0a2d5dd..62ec3b4 100644 --- a/src/activities/infrastructure/persistence/relational/mappers/activity.mapper.ts +++ b/src/activities/infrastructure/persistence/relational/mappers/activity.mapper.ts @@ -13,8 +13,11 @@ export class ActivityMapper { domainEntity.requiresProof = raw.requiresProof; domainEntity.requiresDescription = raw.requiresDescription; domainEntity.cooldownHours = raw.cooldownHours; + domainEntity.auditorReward = raw.auditorReward; + domainEntity.requiresActivityDate = raw.requiresActivityDate; domainEntity.effortTiers = raw.effortTiers; domainEntity.isFreeform = raw.isFreeform; + domainEntity.createsGithubIssue = raw.createsGithubIssue; domainEntity.createdAt = raw.createdAt; domainEntity.updatedAt = raw.updatedAt; @@ -34,8 +37,11 @@ export class ActivityMapper { persistenceEntity.requiresProof = domainEntity.requiresProof; persistenceEntity.requiresDescription = domainEntity.requiresDescription; persistenceEntity.cooldownHours = domainEntity.cooldownHours; + persistenceEntity.auditorReward = domainEntity.auditorReward; + persistenceEntity.requiresActivityDate = domainEntity.requiresActivityDate; persistenceEntity.effortTiers = domainEntity.effortTiers; persistenceEntity.isFreeform = domainEntity.isFreeform; + persistenceEntity.createsGithubIssue = domainEntity.createsGithubIssue; persistenceEntity.createdAt = domainEntity.createdAt; persistenceEntity.updatedAt = domainEntity.updatedAt; diff --git a/src/activities/infrastructure/persistence/relational/repositories/activity.repository.ts b/src/activities/infrastructure/persistence/relational/repositories/activity.repository.ts index f09971a..e711775 100644 --- a/src/activities/infrastructure/persistence/relational/repositories/activity.repository.ts +++ b/src/activities/infrastructure/persistence/relational/repositories/activity.repository.ts @@ -82,16 +82,43 @@ export class ActivityRelationalRepository implements ActivityRepository { async findPublicWithPagination({ paginationOptions, + search, + view, }: { paginationOptions: IPaginationOptions; + search?: string; + view?: 'card' | 'list'; }): Promise { - const entities = await this.activityRepository.find({ - where: { isHidden: false }, - skip: (paginationOptions.page - 1) * paginationOptions.limit, - take: paginationOptions.limit, - }); + const query = this.activityRepository.createQueryBuilder('activity'); - return entities.map((entity) => ActivityMapper.toDomain(entity)); + query.andWhere('activity.isHidden = :isHidden', { isHidden: false }); + + if (search) { + query.andWhere( + '(activity.title ILIKE :search OR activity.description ILIKE :search)', + { search: `%${search}%` }, + ); + } + + query.skip((paginationOptions.page - 1) * paginationOptions.limit); + query.take(paginationOptions.limit); + query.orderBy('activity.createdAt', 'DESC'); + + const entities = await query.getMany(); + const mapped = entities.map((entity) => ActivityMapper.toDomain(entity)); + + if (view === 'card') { + return mapped.map( + (a) => + ({ + id: a.id, + title: a.title, + fixedReward: a.fixedReward, + createdAt: a.createdAt, + }) as Activity, + ); + } + return mapped; } async findBySecretCode( diff --git a/src/app.module.ts b/src/app.module.ts index eec4ec9..1d9162d 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -48,6 +48,7 @@ import { NotificationsModule } from './notifications/notifications.module'; import { ContributionReportsModule } from './contribution-reports/contribution-reports.module'; import { EventsModule } from './events/events.module'; +import { ProjectTeamsModule } from './project-teams/project-teams.module'; import { LearningTracksModule } from './learning-tracks/learning-tracks.module'; @@ -107,6 +108,7 @@ import { AuditLogsModule } from './audit-logs/audit-logs.module'; ActivitiesModule, GamificationProfilesModule, EventsModule, + ProjectTeamsModule, ConfigModule.forRoot({ isGlobal: true, load: [ diff --git a/src/auth-github/auth-github.service.ts b/src/auth-github/auth-github.service.ts index 01e29e0..67df076 100644 --- a/src/auth-github/auth-github.service.ts +++ b/src/auth-github/auth-github.service.ts @@ -71,6 +71,7 @@ export class AuthGitHubService { id: number; name?: string; login: string; + avatar_url?: string; }; const emails = (await emailsRes.json()) as Array<{ @@ -95,6 +96,7 @@ export class AuthGitHubService { email: primaryEmail, firstName, lastName: rest.join(' ') || undefined, + picture: user.avatar_url, }; } } diff --git a/src/auth-github/config/github-config.type.ts b/src/auth-github/config/github-config.type.ts index e429b5f..0b415f8 100644 --- a/src/auth-github/config/github-config.type.ts +++ b/src/auth-github/config/github-config.type.ts @@ -1,4 +1,5 @@ export type GitHubConfig = { clientId?: string; clientSecret?: string; + botToken?: string; }; diff --git a/src/auth-github/config/github.config.ts b/src/auth-github/config/github.config.ts index 66fc1b4..56fac70 100644 --- a/src/auth-github/config/github.config.ts +++ b/src/auth-github/config/github.config.ts @@ -11,6 +11,10 @@ class EnvironmentVariablesValidator { @IsString() @IsOptional() GITHUB_CLIENT_SECRET: string; + + @IsString() + @IsOptional() + GITHUB_BOT_TOKEN: string; } export default registerAs('github', () => { @@ -18,5 +22,6 @@ export default registerAs('github', () => { return { clientId: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, + botToken: process.env.GITHUB_BOT_TOKEN, }; }); diff --git a/src/auth-google/auth-google.service.ts b/src/auth-google/auth-google.service.ts index b267009..da7570f 100644 --- a/src/auth-google/auth-google.service.ts +++ b/src/auth-google/auth-google.service.ts @@ -39,12 +39,14 @@ export class AuthGoogleService { email: string; given_name?: string; family_name?: string; + picture?: string; }; return { id: data.sub, email: data.email, firstName: data.given_name, lastName: data.family_name, + picture: data.picture, }; } diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index d72928d..7b5094b 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -12,7 +12,6 @@ import { JwtService } from '@nestjs/jwt'; import bcrypt from 'bcryptjs'; import { AuthEmailLoginDto } from './dto/auth-email-login.dto'; import { AuthUpdateDto } from './dto/auth-update.dto'; -import { AuthProvidersEnum } from './auth-providers.enum'; import { SocialInterface } from '../social/interfaces/social.interface'; import { AuthRegisterLoginDto } from './dto/auth-register-login.dto'; import { NullableType } from '../utils/types/nullable.type'; @@ -79,15 +78,6 @@ export class AuthService { }); } - if (user.provider !== AuthProvidersEnum.email) { - throw new UnprocessableEntityException({ - status: HttpStatus.UNPROCESSABLE_ENTITY, - errors: { - email: `needLoginViaProvider:${user.provider}`, - }, - }); - } - if (!user.password) { throw new UnprocessableEntityException({ status: HttpStatus.UNPROCESSABLE_ENTITY, @@ -191,6 +181,13 @@ export class AuthService { id: StatusEnum.active, }; + let photo; + if (socialData.picture) { + photo = await this.filesService.create({ + path: socialData.picture, + } as any); + } + user = await this.usersService.create({ email: socialEmail ?? null, firstName: socialData.firstName ?? null, @@ -199,6 +196,7 @@ export class AuthService { provider: authProvider, role, status, + ...(photo && { photo: { id: photo.id } }), }); user = await this.usersService.findById(user.id); @@ -226,6 +224,15 @@ export class AuthService { }); } + if (user.status?.id?.toString() === StatusEnum.inactive.toString()) { + throw new UnprocessableEntityException({ + status: HttpStatus.UNPROCESSABLE_ENTITY, + errors: { + user: 'inactive', + }, + }); + } + const hash = crypto .createHash('sha256') .update(randomStringGenerator()) diff --git a/src/database/migrations/1776637614206-AddRequiresFieldsToMission.ts b/src/database/migrations/1776637614206-AddRequiresFieldsToMission.ts new file mode 100644 index 0000000..2fc542e --- /dev/null +++ b/src/database/migrations/1776637614206-AddRequiresFieldsToMission.ts @@ -0,0 +1,67 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddRequiresFieldsToMission1776637614206 + implements MigrationInterface +{ + name = 'AddRequiresFieldsToMission1776637614206'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "mission_submission" DROP CONSTRAINT IF EXISTS "FK_mission_submission_mission"`, + ); + await queryRunner.query( + `DROP INDEX IF EXISTS "public"."IDX_notification_userId"`, + ); + await queryRunner.query( + `ALTER TABLE "mission_submission" DROP CONSTRAINT IF EXISTS "UQ_mission_submission_profile"`, + ); + await queryRunner.query( + `ALTER TABLE IF EXISTS "contribution_report" DROP CONSTRAINT IF EXISTS "UQ_report_submission_reporter"`, + ); + await queryRunner.query( + `ALTER TABLE "mission" ADD "requiresProof" boolean NOT NULL DEFAULT false`, + ); + await queryRunner.query( + `ALTER TABLE "mission" ADD "requiresDescription" boolean NOT NULL DEFAULT false`, + ); + await queryRunner.query( + `ALTER TABLE "mission_submission" ADD CONSTRAINT "FK_2747f390542d85c30f86a0f2d9f" FOREIGN KEY ("missionId") REFERENCES "mission"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`, + ); + await queryRunner.query( + `ALTER TABLE "mission_submission" ADD CONSTRAINT "FK_1cb8bca775940a52071f1da35b8" FOREIGN KEY ("profileId") REFERENCES "gamification_profile"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`, + ); + await queryRunner.query( + `ALTER TABLE "mission_submission" ADD CONSTRAINT "FK_e169877bdc7e15a5ef5d71e028c" FOREIGN KEY ("reviewerId") REFERENCES "user"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`, + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "mission_submission" DROP CONSTRAINT "FK_e169877bdc7e15a5ef5d71e028c"`, + ); + await queryRunner.query( + `ALTER TABLE "mission_submission" DROP CONSTRAINT "FK_1cb8bca775940a52071f1da35b8"`, + ); + await queryRunner.query( + `ALTER TABLE "mission_submission" DROP CONSTRAINT "FK_2747f390542d85c30f86a0f2d9f"`, + ); + await queryRunner.query( + `ALTER TABLE "mission" DROP COLUMN "requiresDescription"`, + ); + await queryRunner.query( + `ALTER TABLE "mission" DROP COLUMN "requiresProof"`, + ); + await queryRunner.query( + `ALTER TABLE "contribution_report" ADD CONSTRAINT "UQ_report_submission_reporter" UNIQUE ("reporterProfileId", "submissionId")`, + ); + await queryRunner.query( + `ALTER TABLE "mission_submission" ADD CONSTRAINT "UQ_mission_submission_profile" UNIQUE ("missionId", "profileId")`, + ); + await queryRunner.query( + `CREATE INDEX "IDX_notification_userId" ON "notification" ("userId") `, + ); + await queryRunner.query( + `ALTER TABLE "mission_submission" ADD CONSTRAINT "FK_mission_submission_mission" FOREIGN KEY ("missionId") REFERENCES "mission"("id") ON DELETE CASCADE ON UPDATE NO ACTION`, + ); + } +} diff --git a/src/database/migrations/1777217102853-AddAuditorAndParticipationRewards.ts b/src/database/migrations/1777217102853-AddAuditorAndParticipationRewards.ts new file mode 100644 index 0000000..7834d7e --- /dev/null +++ b/src/database/migrations/1777217102853-AddAuditorAndParticipationRewards.ts @@ -0,0 +1,31 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddAuditorAndParticipationRewards1777217102853 + implements MigrationInterface +{ + name = 'AddAuditorAndParticipationRewards1777217102853'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "activity" ADD "auditorReward" integer NOT NULL DEFAULT '10'`, + ); + await queryRunner.query( + `ALTER TABLE "mission" ADD "participationReward" integer NOT NULL DEFAULT '50'`, + ); + await queryRunner.query( + `ALTER TABLE "mission" ADD "auditorReward" integer NOT NULL DEFAULT '20'`, + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "mission" DROP COLUMN "auditorReward"`, + ); + await queryRunner.query( + `ALTER TABLE "mission" DROP COLUMN "participationReward"`, + ); + await queryRunner.query( + `ALTER TABLE "activity" DROP COLUMN "auditorReward"`, + ); + } +} diff --git a/src/database/migrations/1777400000000-AddActivityDateFields.ts b/src/database/migrations/1777400000000-AddActivityDateFields.ts new file mode 100644 index 0000000..39aab76 --- /dev/null +++ b/src/database/migrations/1777400000000-AddActivityDateFields.ts @@ -0,0 +1,26 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddActivityDateFields1777400000000 implements MigrationInterface { + name = 'AddActivityDateFields1777400000000'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "activity" ADD "requiresActivityDate" boolean NOT NULL DEFAULT false`, + ); + await queryRunner.query( + `ALTER TABLE "submission" ADD "activityDate" TIMESTAMP DEFAULT NULL`, + ); + await queryRunner.query( + `ALTER TYPE notification_type_enum ADD VALUE IF NOT EXISTS 'NEW_SUBMISSION_PENDING'`, + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "submission" DROP COLUMN "activityDate"`, + ); + await queryRunner.query( + `ALTER TABLE "activity" DROP COLUMN "requiresActivityDate"`, + ); + } +} diff --git a/src/database/migrations/1787100000000-AddGithubIssueFieldsToActivityAndSubmission.ts b/src/database/migrations/1787100000000-AddGithubIssueFieldsToActivityAndSubmission.ts new file mode 100644 index 0000000..b09e758 --- /dev/null +++ b/src/database/migrations/1787100000000-AddGithubIssueFieldsToActivityAndSubmission.ts @@ -0,0 +1,50 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddGithubIssueFieldsToActivityAndSubmission1787100000000 + implements MigrationInterface +{ + name = 'AddGithubIssueFieldsToActivityAndSubmission1787100000000'; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "activity" ADD "createsGithubIssue" boolean NOT NULL DEFAULT false`, + ); + + await queryRunner.query( + `CREATE TYPE "public"."submission_githubrepo_enum" AS ENUM('FRONT', 'API')`, + ); + await queryRunner.query( + `ALTER TABLE "submission" ADD "githubRepo" "public"."submission_githubrepo_enum"`, + ); + + await queryRunner.query( + `CREATE TYPE "public"."submission_issuecategory_enum" AS ENUM('BUG', 'MELHORIA', 'DUVIDA', 'OUTRO')`, + ); + await queryRunner.query( + `ALTER TABLE "submission" ADD "issueCategory" "public"."submission_issuecategory_enum"`, + ); + + await queryRunner.query( + `ALTER TABLE "submission" ADD "githubIssueUrl" varchar`, + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "submission" DROP COLUMN "githubIssueUrl"`, + ); + await queryRunner.query( + `ALTER TABLE "submission" DROP COLUMN "issueCategory"`, + ); + await queryRunner.query( + `DROP TYPE "public"."submission_issuecategory_enum"`, + ); + await queryRunner.query( + `ALTER TABLE "submission" DROP COLUMN "githubRepo"`, + ); + await queryRunner.query(`DROP TYPE "public"."submission_githubrepo_enum"`); + await queryRunner.query( + `ALTER TABLE "activity" DROP COLUMN "createsGithubIssue"`, + ); + } +} diff --git a/src/database/migrations/1787200000000-CreateProjectTeams.ts b/src/database/migrations/1787200000000-CreateProjectTeams.ts new file mode 100644 index 0000000..23c52f7 --- /dev/null +++ b/src/database/migrations/1787200000000-CreateProjectTeams.ts @@ -0,0 +1,100 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class CreateProjectTeams1787200000000 implements MigrationInterface { + name = 'CreateProjectTeams1787200000000'; + + public async up(queryRunner: QueryRunner): Promise { + for (const value of [ + 'PROJECT_IDEA_APPROVED', + 'PROJECT_IDEA_REJECTED', + 'PROJECT_IDEA_INTEREST', + 'PROJECT_TEAM_MEMBER_ADDED', + ]) { + await queryRunner.query( + `ALTER TYPE "notification_type_enum" ADD VALUE IF NOT EXISTS '${value}'`, + ); + } + + await queryRunner.query( + `CREATE TYPE "public"."project_role_enum" AS ENUM('FRONTEND', 'BACKEND', 'DATABASE', 'REQUIREMENTS_ANALYST', 'UX_DESIGNER', 'QA', 'DEVOPS', 'MOBILE', 'PROJECT_MANAGER')`, + ); + await queryRunner.query( + `CREATE TYPE "public"."project_idea_status_enum" AS ENUM('PENDING', 'APPROVED', 'REJECTED', 'TEAM_FORMED')`, + ); + await queryRunner.query( + `CREATE TYPE "public"."project_team_status_enum" AS ENUM('RECRUITING', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED')`, + ); + + await queryRunner.query( + `CREATE TABLE "project_idea" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "title" character varying(150) NOT NULL, "description" text NOT NULL, "tags" character varying array NOT NULL DEFAULT '{}', "status" "public"."project_idea_status_enum" NOT NULL DEFAULT 'PENDING', "rejectionReason" text, "authorId" integer NOT NULL, "reviewerId" integer, "reviewedAt" TIMESTAMP, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_project_idea_id" PRIMARY KEY ("id"))`, + ); + await queryRunner.query( + `CREATE INDEX "IDX_project_idea_status_createdAt" ON "project_idea" ("status", "createdAt")`, + ); + await queryRunner.query( + `ALTER TABLE "project_idea" ADD CONSTRAINT "FK_project_idea_authorId" FOREIGN KEY ("authorId") REFERENCES "user"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`, + ); + await queryRunner.query( + `ALTER TABLE "project_idea" ADD CONSTRAINT "FK_project_idea_reviewerId" FOREIGN KEY ("reviewerId") REFERENCES "user"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`, + ); + + await queryRunner.query( + `CREATE TABLE "project_idea_interest" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "ideaId" uuid NOT NULL, "userId" integer NOT NULL, "role" "public"."project_role_enum" NOT NULL, "message" text, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_project_idea_interest_id" PRIMARY KEY ("id"))`, + ); + await queryRunner.query( + `CREATE UNIQUE INDEX "IDX_project_idea_interest_ideaId_userId" ON "project_idea_interest" ("ideaId", "userId")`, + ); + await queryRunner.query( + `ALTER TABLE "project_idea_interest" ADD CONSTRAINT "FK_project_idea_interest_ideaId" FOREIGN KEY ("ideaId") REFERENCES "project_idea"("id") ON DELETE CASCADE ON UPDATE NO ACTION`, + ); + await queryRunner.query( + `ALTER TABLE "project_idea_interest" ADD CONSTRAINT "FK_project_idea_interest_userId" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`, + ); + + await queryRunner.query( + `CREATE TABLE "project_team" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "ideaId" uuid NOT NULL, "name" character varying(150) NOT NULL, "description" text, "status" "public"."project_team_status_enum" NOT NULL DEFAULT 'RECRUITING', "repoUrl" character varying, "ownerId" integer NOT NULL, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "UQ_project_team_ideaId" UNIQUE ("ideaId"), CONSTRAINT "PK_project_team_id" PRIMARY KEY ("id"))`, + ); + await queryRunner.query( + `ALTER TABLE "project_team" ADD CONSTRAINT "FK_project_team_ideaId" FOREIGN KEY ("ideaId") REFERENCES "project_idea"("id") ON DELETE CASCADE ON UPDATE NO ACTION`, + ); + await queryRunner.query( + `ALTER TABLE "project_team" ADD CONSTRAINT "FK_project_team_ownerId" FOREIGN KEY ("ownerId") REFERENCES "user"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`, + ); + + await queryRunner.query( + `CREATE TABLE "project_team_vacancy" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "teamId" uuid NOT NULL, "role" "public"."project_role_enum" NOT NULL, "quantity" integer NOT NULL, CONSTRAINT "PK_project_team_vacancy_id" PRIMARY KEY ("id"))`, + ); + await queryRunner.query( + `CREATE UNIQUE INDEX "IDX_project_team_vacancy_teamId_role" ON "project_team_vacancy" ("teamId", "role")`, + ); + await queryRunner.query( + `ALTER TABLE "project_team_vacancy" ADD CONSTRAINT "FK_project_team_vacancy_teamId" FOREIGN KEY ("teamId") REFERENCES "project_team"("id") ON DELETE CASCADE ON UPDATE NO ACTION`, + ); + + await queryRunner.query( + `CREATE TABLE "project_team_member" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "teamId" uuid NOT NULL, "userId" integer NOT NULL, "role" "public"."project_role_enum" NOT NULL, "createdAt" TIMESTAMP NOT NULL DEFAULT now(), CONSTRAINT "PK_project_team_member_id" PRIMARY KEY ("id"))`, + ); + await queryRunner.query( + `CREATE UNIQUE INDEX "IDX_project_team_member_teamId_userId" ON "project_team_member" ("teamId", "userId")`, + ); + await queryRunner.query( + `ALTER TABLE "project_team_member" ADD CONSTRAINT "FK_project_team_member_teamId" FOREIGN KEY ("teamId") REFERENCES "project_team"("id") ON DELETE CASCADE ON UPDATE NO ACTION`, + ); + await queryRunner.query( + `ALTER TABLE "project_team_member" ADD CONSTRAINT "FK_project_team_member_userId" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`, + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(`DROP TABLE "project_team_member"`); + await queryRunner.query(`DROP TABLE "project_team_vacancy"`); + await queryRunner.query(`DROP TABLE "project_team"`); + await queryRunner.query(`DROP TABLE "project_idea_interest"`); + await queryRunner.query(`DROP TABLE "project_idea"`); + await queryRunner.query(`DROP TYPE "public"."project_team_status_enum"`); + await queryRunner.query(`DROP TYPE "public"."project_idea_status_enum"`); + await queryRunner.query(`DROP TYPE "public"."project_role_enum"`); + // Note: PostgreSQL doesn't support removing enum values; the new + // notification types remain defined. + } +} diff --git a/src/events/events.service.spec.ts b/src/events/events.service.spec.ts index b40e817..fa90c95 100644 --- a/src/events/events.service.spec.ts +++ b/src/events/events.service.spec.ts @@ -114,7 +114,7 @@ describe('EventsService', () => { description: 'desc', category: EventCategory.MEETUP, modality: EventModality.PRESENCIAL, - startAt: '2026-08-15T19:00:00.000Z', + startAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), location: 'Rua Exemplo, 123', }; repository.create!.mockResolvedValue(buildEvent()); diff --git a/src/files/files.service.ts b/src/files/files.service.ts index 271f6bb..31d1d65 100644 --- a/src/files/files.service.ts +++ b/src/files/files.service.ts @@ -17,6 +17,10 @@ export class FilesService { private readonly configService: ConfigService, ) {} + create(data: FileType): Promise { + return this.fileRepository.create(data); + } + findById(id: FileType['id']): Promise> { return this.fileRepository.findById(id); } @@ -25,6 +29,53 @@ export class FilesService { return this.fileRepository.findByIds(ids); } + findByPath(path: string): Promise> { + return this.fileRepository.findByPath(path); + } + + /** Extrai a chave de storage de uma URL completa (assinada ou pública). */ + extractStoragePath(urlOrKey: string): string { + if (!/^https?:\/\//i.test(urlOrKey)) return urlOrKey; + try { + const { pathname } = new URL(urlOrKey); + // URLs S3 path-style vêm como /{bucket}/{key} — o bucket não faz + // parte da path armazenada no registro de file, então é descartado. + const bucket = this.configService.get('file.awsDefaultS3Bucket', { + infer: true, + }); + const decoded = decodeURIComponent(pathname.replace(/^\//, '')); + return bucket && decoded.startsWith(`${bucket}/`) + ? decoded.slice(bucket.length + 1) + : decoded; + } catch { + return urlOrKey; + } + } + + /** + * Remove o arquivo de storage referenciado por uma URL (proofUrl de + * submissão, por ex.), resolvendo a URL para o registro de file + * correspondente primeiro. Best-effort: nunca lança — só loga em caso de + * falha, pra nunca quebrar o fluxo que chamou (review/cancel de + * submissão), que já efetivou a mudança principal antes de chamar isto. + */ + async removeByUrl(urlOrKey: string | null | undefined): Promise { + if (!urlOrKey) return; + try { + const path = this.extractStoragePath(urlOrKey); + const file = await this.findByPath(path); + if (!file) { + this.logger.warn(`Nenhum arquivo encontrado para a path "${path}"`); + return; + } + await this.remove(file.id); + } catch (err) { + this.logger.warn( + `Falha ao remover arquivo pela URL "${urlOrKey}": ${err}`, + ); + } + } + /** * Deletes a file both from the database and from the underlying storage * (when using an S3-compatible driver). Safe to call with an id that no diff --git a/src/files/infrastructure/persistence/file.repository.ts b/src/files/infrastructure/persistence/file.repository.ts index 363f483..2f21de3 100644 --- a/src/files/infrastructure/persistence/file.repository.ts +++ b/src/files/infrastructure/persistence/file.repository.ts @@ -8,5 +8,7 @@ export abstract class FileRepository { abstract findByIds(ids: FileType['id'][]): Promise; + abstract findByPath(path: string): Promise>; + abstract remove(id: FileType['id']): Promise; } diff --git a/src/files/infrastructure/persistence/relational/repositories/file.repository.ts b/src/files/infrastructure/persistence/relational/repositories/file.repository.ts index 34b48df..dd69b2a 100644 --- a/src/files/infrastructure/persistence/relational/repositories/file.repository.ts +++ b/src/files/infrastructure/persistence/relational/repositories/file.repository.ts @@ -44,6 +44,14 @@ export class FileRelationalRepository implements FileRepository { return entities.map((entity) => FileMapper.toDomain(entity)); } + async findByPath(path: string): Promise> { + const entity = await this.fileRepository.findOne({ + where: { path }, + }); + + return entity ? FileMapper.toDomain(entity) : null; + } + async remove(id: FileType['id']): Promise { await this.fileRepository.delete(id); } diff --git a/src/files/infrastructure/uploader/local/files.module.ts b/src/files/infrastructure/uploader/local/files.module.ts index 411fddf..c764c03 100644 --- a/src/files/infrastructure/uploader/local/files.module.ts +++ b/src/files/infrastructure/uploader/local/files.module.ts @@ -24,7 +24,7 @@ const infrastructurePersistenceModule = RelationalFilePersistenceModule; useFactory: (configService: ConfigService) => { return { fileFilter: (request, file, callback) => { - if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/i)) { + if (!file.originalname.match(/\.(jpg|jpeg|png|gif|webp)$/i)) { return callback( new UnprocessableEntityException({ status: HttpStatus.UNPROCESSABLE_ENTITY, diff --git a/src/files/infrastructure/uploader/mock/files.module.ts b/src/files/infrastructure/uploader/mock/files.module.ts index 293ac19..a6ae2ea 100644 --- a/src/files/infrastructure/uploader/mock/files.module.ts +++ b/src/files/infrastructure/uploader/mock/files.module.ts @@ -19,7 +19,7 @@ const infrastructurePersistenceModule = RelationalFilePersistenceModule; infrastructurePersistenceModule, MulterModule.register({ fileFilter: (request, file, callback) => { - if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/i)) { + if (!file.originalname.match(/\.(jpg|jpeg|png|gif|webp)$/i)) { return callback( new UnprocessableEntityException({ status: HttpStatus.UNPROCESSABLE_ENTITY, diff --git a/src/files/infrastructure/uploader/s3-presigned/files.module.ts b/src/files/infrastructure/uploader/s3-presigned/files.module.ts index ef79f91..774f121 100644 --- a/src/files/infrastructure/uploader/s3-presigned/files.module.ts +++ b/src/files/infrastructure/uploader/s3-presigned/files.module.ts @@ -41,7 +41,7 @@ const infrastructurePersistenceModule = RelationalFilePersistenceModule; return { fileFilter: (request, file, callback) => { - if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/i)) { + if (!file.originalname.match(/\.(jpg|jpeg|png|gif|webp)$/i)) { return callback( new UnprocessableEntityException({ status: HttpStatus.UNPROCESSABLE_ENTITY, diff --git a/src/files/infrastructure/uploader/s3-presigned/files.service.ts b/src/files/infrastructure/uploader/s3-presigned/files.service.ts index 7d2c8ba..d8f567b 100644 --- a/src/files/infrastructure/uploader/s3-presigned/files.service.ts +++ b/src/files/infrastructure/uploader/s3-presigned/files.service.ts @@ -49,7 +49,7 @@ export class FilesS3PresignedService { }); } - if (!file.fileName.match(/\.(jpg|jpeg|png|gif)$/i)) { + if (!file.fileName.match(/\.(jpg|jpeg|png|gif|webp)$/i)) { throw new UnprocessableEntityException({ status: HttpStatus.UNPROCESSABLE_ENTITY, errors: { diff --git a/src/files/infrastructure/uploader/s3/files.module.ts b/src/files/infrastructure/uploader/s3/files.module.ts index 83fa863..cd7a967 100644 --- a/src/files/infrastructure/uploader/s3/files.module.ts +++ b/src/files/infrastructure/uploader/s3/files.module.ts @@ -41,7 +41,7 @@ const infrastructurePersistenceModule = RelationalFilePersistenceModule; return { fileFilter: (request, file, callback) => { - if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/i)) { + if (!file.originalname.match(/\.(jpg|jpeg|png|gif|webp)$/i)) { return callback( new UnprocessableEntityException({ status: HttpStatus.UNPROCESSABLE_ENTITY, diff --git a/src/gamification-profiles/gamification-profiles-cron.service.ts b/src/gamification-profiles/gamification-profiles-cron.service.ts index c53c0d6..a028049 100644 --- a/src/gamification-profiles/gamification-profiles-cron.service.ts +++ b/src/gamification-profiles/gamification-profiles-cron.service.ts @@ -1,33 +1,62 @@ -import { Injectable, Logger } from '@nestjs/common'; +import { Injectable, Logger, OnModuleInit } from '@nestjs/common'; import { Cron, CronExpression } from '@nestjs/schedule'; import { GamificationProfilesService } from './gamification-profiles.service'; -const DEFAULT_MONTHLY_TOKENS = 5; +const DEFAULT_DAILY_TOKENS = 5; +const DEFAULT_MONTHLY_TOKENS = DEFAULT_DAILY_TOKENS; @Injectable() -export class GamificationProfilesCronService { +export class GamificationProfilesCronService implements OnModuleInit { private readonly logger = new Logger(GamificationProfilesCronService.name); constructor( private readonly gamificationProfilesService: GamificationProfilesService, ) {} + async onModuleInit() { + this.logger.log( + 'Executando recarga inicial de Tokens de Gratidão na inicialização...', + ); + try { + await this.gamificationProfilesService.replenishDailyTokens( + DEFAULT_DAILY_TOKENS, + ); + this.logger.log( + `Recarga inicial concluída. gratitudeTokens = ${DEFAULT_DAILY_TOKENS}.`, + ); + } catch (err) { + this.logger.error('Falha na recarga inicial de tokens', err); + } + } + + @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT) + async handleDailyTokenReplenishment() { + this.logger.log('Recarregando Tokens de Gratidão diariamente...'); + try { + await this.gamificationProfilesService.replenishDailyTokens( + DEFAULT_DAILY_TOKENS, + ); + this.logger.log( + `Recarga diária concluída. gratitudeTokens = ${DEFAULT_DAILY_TOKENS}.`, + ); + } catch (err) { + this.logger.error('Falha na recarga diária de tokens', err); + } + } + @Cron(CronExpression.EVERY_1ST_DAY_OF_MONTH_AT_MIDNIGHT) async handleMonthlyReset() { - this.logger.log('Iniciando reset mensal de XP e Tokens de Gratidão...'); + this.logger.log('Iniciando reset mensal de XP...'); try { await this.gamificationProfilesService.resetMonthlyXpAndTokens( DEFAULT_MONTHLY_TOKENS, ); - this.logger.log( - `Reset mensal concluído. currentMonthlyXp zerado; gratitudeTokens recarregados para ${DEFAULT_MONTHLY_TOKENS}.`, - ); + this.logger.log('Reset mensal concluído. currentMonthlyXp zerado.'); } catch (err) { this.logger.error('Falha no reset mensal', err); } } - // Executa às 00h00 do dia 1° de janeiro (reinicia ranking anual) @Cron('0 0 1 1 *') async handleYearlyReset() { this.logger.log('Iniciando reset anual de XP (currentYearlyXp)...'); diff --git a/src/gamification-profiles/gamification-profiles.service.ts b/src/gamification-profiles/gamification-profiles.service.ts index cfcb829..4b2aace 100644 --- a/src/gamification-profiles/gamification-profiles.service.ts +++ b/src/gamification-profiles/gamification-profiles.service.ts @@ -131,10 +131,65 @@ export class GamificationProfilesService { ); } + replenishDailyTokens(defaultTokens: number) { + return this.gamificationProfileRepository.replenishDailyTokens( + defaultTokens, + ); + } + resetYearlyXp() { return this.gamificationProfileRepository.resetYearlyXp(); } + async zeroOutProfile( + userId: number, + reason: string, + anonymize: boolean = false, + ): Promise { + const profile = + await this.gamificationProfileRepository.findByUserId(userId); + if (!profile) return; + + const queryRunner = this.dataSource.createQueryRunner(); + await queryRunner.connect(); + await queryRunner.startTransaction(); + + try { + const updateData: any = { + totalXp: 0, + currentMonthlyXp: 0, + currentYearlyXp: 0, + }; + + if (anonymize) { + updateData.username = `deletado_${profile.id}_${Math.floor(Math.random() * 10000)}`; + updateData.githubUsername = null; + } + + await queryRunner.manager.update( + GamificationProfileEntity, + { id: profile.id }, + updateData, + ); + + if (profile.totalXp > 0) { + await queryRunner.manager.save(TransactionEntity, { + profile: { id: profile.id }, + category: TransactionCategoryEnum.PENALTY, + amount: -profile.totalXp, + description: reason, + }); + } + + await queryRunner.commitTransaction(); + } catch (err) { + await queryRunner.rollbackTransaction(); + throw err; + } finally { + await queryRunner.release(); + } + } + async applyPenalty( profileId: GamificationProfile['id'], dto: ApplyPenaltyDto, diff --git a/src/gamification-profiles/infrastructure/persistence/gamification-profile.repository.ts b/src/gamification-profiles/infrastructure/persistence/gamification-profile.repository.ts index 96c4274..cc017f0 100644 --- a/src/gamification-profiles/infrastructure/persistence/gamification-profile.repository.ts +++ b/src/gamification-profiles/infrastructure/persistence/gamification-profile.repository.ts @@ -43,5 +43,7 @@ export abstract class GamificationProfileRepository { abstract resetMonthlyXpAndTokens(defaultTokens: number): Promise; + abstract replenishDailyTokens(defaultTokens: number): Promise; + abstract resetYearlyXp(): Promise; } diff --git a/src/gamification-profiles/infrastructure/persistence/relational/mappers/gamification-profile.mapper.ts b/src/gamification-profiles/infrastructure/persistence/relational/mappers/gamification-profile.mapper.ts index 1ebe4fb..19cb270 100644 --- a/src/gamification-profiles/infrastructure/persistence/relational/mappers/gamification-profile.mapper.ts +++ b/src/gamification-profiles/infrastructure/persistence/relational/mappers/gamification-profile.mapper.ts @@ -24,9 +24,11 @@ export class GamificationProfileMapper { domainEntity.isBanned = raw.user?.isBanned ?? false; domainEntity.firstName = raw.user?.firstName ?? undefined; domainEntity.lastName = raw.user?.lastName ?? undefined; + domainEntity.photo = raw.user?.photo + ? FileMapper.toDomain(raw.user.photo) + : null; domainEntity.createdAt = raw.createdAt; domainEntity.updatedAt = raw.updatedAt; - return domainEntity; } diff --git a/src/gamification-profiles/infrastructure/persistence/relational/repositories/gamification-profile.repository.ts b/src/gamification-profiles/infrastructure/persistence/relational/repositories/gamification-profile.repository.ts index 1000701..056e5c7 100644 --- a/src/gamification-profiles/infrastructure/persistence/relational/repositories/gamification-profile.repository.ts +++ b/src/gamification-profiles/infrastructure/persistence/relational/repositories/gamification-profile.repository.ts @@ -97,7 +97,7 @@ export class GamificationProfileRelationalRepository const entityMap = new Map(); const entities = await this.gamificationProfileRepository.find({ where: { id: In(ids) }, - relations: { user: true }, + relations: { user: { photo: true } }, }); entities.forEach((e) => entityMap.set(e.id, e)); @@ -113,10 +113,12 @@ export class GamificationProfileRelationalRepository ): Promise> { const entity = await this.gamificationProfileRepository.findOne({ where: { id }, - relations: { user: true }, + relations: { user: { photo: true, role: true } }, }); - return entity ? GamificationProfileMapper.toDomain(entity) : null; + if (!entity) return null; + if (entity.user?.role?.id === 1) return null; + return GamificationProfileMapper.toDomain(entity); } async findByIds( @@ -124,7 +126,7 @@ export class GamificationProfileRelationalRepository ): Promise { const entities = await this.gamificationProfileRepository.find({ where: { id: In(ids) }, - relations: { user: true }, + relations: { user: { photo: true } }, }); return entities.map((entity) => GamificationProfileMapper.toDomain(entity)); @@ -163,7 +165,7 @@ export class GamificationProfileRelationalRepository ): Promise> { const entity = await this.gamificationProfileRepository.findOne({ where: { userId }, - relations: { user: true }, + relations: { user: { photo: true } }, }); return entity ? GamificationProfileMapper.toDomain(entity) : null; @@ -174,20 +176,35 @@ export class GamificationProfileRelationalRepository ): Promise> { const entity = await this.gamificationProfileRepository.findOne({ where: { username }, - relations: { user: true }, + relations: { user: { photo: true, role: true } }, }); - return entity ? GamificationProfileMapper.toDomain(entity) : null; + if (!entity) return null; + if (entity.user?.role?.id === 1) return null; + return GamificationProfileMapper.toDomain(entity); } async resetMonthlyXpAndTokens(defaultTokens: number): Promise { - await this.gamificationProfileRepository.update( - {}, - { currentMonthlyXp: 0, gratitudeTokens: defaultTokens }, - ); + await this.gamificationProfileRepository + .createQueryBuilder() + .update(GamificationProfileEntity) + .set({ currentMonthlyXp: 0, gratitudeTokens: defaultTokens }) + .execute(); + } + + async replenishDailyTokens(defaultTokens: number): Promise { + await this.gamificationProfileRepository + .createQueryBuilder() + .update(GamificationProfileEntity) + .set({ gratitudeTokens: defaultTokens }) + .execute(); } async resetYearlyXp(): Promise { - await this.gamificationProfileRepository.update({}, { currentYearlyXp: 0 }); + await this.gamificationProfileRepository + .createQueryBuilder() + .update(GamificationProfileEntity) + .set({ currentYearlyXp: 0 }) + .execute(); } } diff --git a/src/github-issues/domain/github-issue-category.enum.ts b/src/github-issues/domain/github-issue-category.enum.ts new file mode 100644 index 0000000..f9d480a --- /dev/null +++ b/src/github-issues/domain/github-issue-category.enum.ts @@ -0,0 +1,6 @@ +export enum GithubIssueCategory { + BUG = 'BUG', + MELHORIA = 'MELHORIA', + DUVIDA = 'DUVIDA', + OUTRO = 'OUTRO', +} diff --git a/src/github-issues/domain/github-repo-target.enum.ts b/src/github-issues/domain/github-repo-target.enum.ts new file mode 100644 index 0000000..89f16fa --- /dev/null +++ b/src/github-issues/domain/github-repo-target.enum.ts @@ -0,0 +1,4 @@ +export enum GithubRepoTarget { + FRONT = 'FRONT', + API = 'API', +} diff --git a/src/github-issues/github-issues.module.ts b/src/github-issues/github-issues.module.ts new file mode 100644 index 0000000..7c8c28f --- /dev/null +++ b/src/github-issues/github-issues.module.ts @@ -0,0 +1,8 @@ +import { Module } from '@nestjs/common'; +import { GithubIssuesService } from './github-issues.service'; + +@Module({ + providers: [GithubIssuesService], + exports: [GithubIssuesService], +}) +export class GithubIssuesModule {} diff --git a/src/github-issues/github-issues.service.ts b/src/github-issues/github-issues.service.ts new file mode 100644 index 0000000..b092b42 --- /dev/null +++ b/src/github-issues/github-issues.service.ts @@ -0,0 +1,92 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { AllConfigType } from '../config/config.type'; +import { GithubRepoTarget } from './domain/github-repo-target.enum'; +import { GithubIssueCategory } from './domain/github-issue-category.enum'; + +const REPO_BY_TARGET: Record< + GithubRepoTarget, + { owner: string; repo: string } +> = { + [GithubRepoTarget.FRONT]: { + owner: 'devs-tocantins', + repo: 'front-engajamento', + }, + [GithubRepoTarget.API]: { + owner: 'devs-tocantins', + repo: 'api-engajamento', + }, +}; + +const LABEL_BY_CATEGORY: Record = { + [GithubIssueCategory.BUG]: 'bug', + [GithubIssueCategory.MELHORIA]: 'melhoria', + [GithubIssueCategory.DUVIDA]: 'duvida', + [GithubIssueCategory.OUTRO]: 'outro', +}; + +export type CreatedGithubIssue = { + url: string; + number: number; +}; + +@Injectable() +export class GithubIssuesService { + private readonly logger = new Logger(GithubIssuesService.name); + + constructor(private readonly configService: ConfigService) {} + + /** + * Cria a issue de verdade no repositório correspondente. Lança em caso de + * falha — quem chama decide se isso deve bloquear o fluxo (ver uso em + * SubmissionsService.review, que trata a falha como best-effort). + */ + async createIssue({ + repoTarget, + category, + title, + body, + }: { + repoTarget: GithubRepoTarget; + category: GithubIssueCategory; + title: string; + body: string; + }): Promise { + const token = this.configService.get('github.botToken', { infer: true }); + if (!token) { + throw new Error('GITHUB_BOT_TOKEN não configurado.'); + } + + const { owner, repo } = REPO_BY_TARGET[repoTarget]; + const label = LABEL_BY_CATEGORY[category]; + + const response = await fetch( + `https://api.github.com/repos/${owner}/${repo}/issues`, + { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + Accept: 'application/vnd.github+json', + 'Content-Type': 'application/json', + 'X-GitHub-Api-Version': '2022-11-28', + }, + body: JSON.stringify({ title, body, labels: [label] }), + }, + ); + + if (!response.ok) { + const errorBody = await response.text(); + throw new Error( + `GitHub API retornou ${response.status} ao criar issue em ${owner}/${repo}: ${errorBody}`, + ); + } + + const data = (await response.json()) as { + html_url: string; + number: number; + }; + this.logger.log(`Issue criada: ${data.html_url}`); + + return { url: data.html_url, number: data.number }; + } +} diff --git a/src/mail/mail-templates/pending-submissions-digest.hbs b/src/mail/mail-templates/pending-submissions-digest.hbs new file mode 100644 index 0000000..733786c --- /dev/null +++ b/src/mail/mail-templates/pending-submissions-digest.hbs @@ -0,0 +1,44 @@ + + + + + + Submissões pendentes + + + + + + + + + + + + + + + +
+ {{app_name}} +
+

+ 📋 Submissões aguardando revisão +

+

+ Há {{count}} submissão(ões) pendente(s) + aguardando sua análise no painel de moderação. +

+
+ + Revisar submissões + +
+

+ Este e-mail foi enviado automaticamente às 6h pelo {{app_name}}.
+ Somente moderadores e administradores recebem este resumo. +

+
+ + diff --git a/src/mail/mail.service.ts b/src/mail/mail.service.ts index c4b6e41..57e98c7 100644 --- a/src/mail/mail.service.ts +++ b/src/mail/mail.service.ts @@ -57,10 +57,10 @@ export class MailService { title: emailConfirmTitle, url: url.toString(), actionTitle: emailConfirmTitle, - app_name: this.configService.get('app.name', { infer: true }), - text1, - text2, - text3, + app_name: this.configService.get('app.name', { infer: true }) || 'App', + text1: text1 || 'Bem-vindo!', + text2: text2 || 'Confirme seu e-mail para usar o', + text3: text3 || 'Clique no botão abaixo para confirmar.', }, }); } @@ -112,13 +112,14 @@ export class MailService { title: resetPasswordTitle, url: url.toString(), actionTitle: resetPasswordTitle, - app_name: this.configService.get('app.name', { - infer: true, - }), - text1, - text2, - text3, - text4, + app_name: + this.configService.get('app.name', { + infer: true, + }) || 'App', + text1: text1 || 'Esqueceu sua senha?', + text2: text2 || 'Recebemos um pedido para redefinir a senha do', + text3: text3 || 'Clique no botão abaixo para criar uma nova senha.', + text4: text4 || 'Se não foi você, ignore este e-mail.', }, }); } @@ -163,10 +164,10 @@ export class MailService { title: emailConfirmTitle, url: url.toString(), actionTitle: emailConfirmTitle, - app_name: this.configService.get('app.name', { infer: true }), - text1, - text2, - text3, + app_name: this.configService.get('app.name', { infer: true }) || 'App', + text1: text1 || 'Bem-vindo!', + text2: text2 || 'Confirme seu e-mail para usar o', + text3: text3 || 'Clique no botão abaixo para confirmar.', }, }); } @@ -268,6 +269,35 @@ export class MailService { }); } + async sendPendingSubmissionsDigest( + mailData: MailData<{ count: number }>, + ): Promise { + const adminUrl = + this.configService.getOrThrow('app.frontendDomain', { infer: true }) + + '/moderation'; + const appName = this.configService.get('app.name', { infer: true }); + + await this.mailerService.sendMail({ + to: mailData.to, + subject: `[${appName || 'App'}] ${mailData.data.count} submissão(ões) aguardando revisão`, + text: `Há ${mailData.data.count} submissão(ões) pendente(s). Acesse: ${adminUrl}`, + templatePath: path.join( + this.configService.getOrThrow('app.workingDirectory', { + infer: true, + }), + 'src', + 'mail', + 'mail-templates', + 'pending-submissions-digest.hbs', + ), + context: { + count: mailData.data.count, + adminUrl, + app_name: appName || 'App', + }, + }); + } + async submissionApproved( mailData: MailData<{ submissionId: string; activityTitle: string }>, ): Promise { diff --git a/src/mailer/mailer.service.ts b/src/mailer/mailer.service.ts index 8b10b8e..d25f0be 100644 --- a/src/mailer/mailer.service.ts +++ b/src/mailer/mailer.service.ts @@ -42,20 +42,31 @@ export class MailerService { if (templatePath) { const template = await fs.readFile(templatePath, 'utf-8'); html = Handlebars.compile(template, { - strict: true, + strict: false, })(context); } - await this.transporter.sendMail({ - ...mailOptions, - from: mailOptions.from - ? mailOptions.from - : `"${this.configService.get('mail.defaultName', { - infer: true, - })}" <${this.configService.get('mail.defaultEmail', { - infer: true, - })}>`, - html: mailOptions.html ? mailOptions.html : html, - }); + try { + console.log( + `[MAILER] Preparando envio de e-mail para: ${mailOptions.to}`, + ); + const info = await this.transporter.sendMail({ + ...mailOptions, + from: mailOptions.from + ? mailOptions.from + : `"${this.configService.get('mail.defaultName', { + infer: true, + })}" <${this.configService.get('mail.defaultEmail', { + infer: true, + })}>`, + html: mailOptions.html ? mailOptions.html : html, + }); + console.log( + `[MAILER] E-mail enviado com sucesso! MessageID: ${info.messageId}`, + ); + } catch (error: any) { + console.error(`[MAILER] Falha crítica ao enviar e-mail:`, error); + throw error; + } } } diff --git a/src/missions/domain/mission.ts b/src/missions/domain/mission.ts index b7db521..9e81fc3 100644 --- a/src/missions/domain/mission.ts +++ b/src/missions/domain/mission.ts @@ -21,6 +21,12 @@ export class Mission { @ApiProperty({ type: Number }) xpReward: number; + @ApiProperty({ type: Number }) + participationReward: number; + + @ApiProperty({ type: Number }) + auditorReward: number; + @ApiProperty({ enum: MissionStatus }) status: MissionStatus; @@ -38,6 +44,12 @@ export class Mission { }) isSecret: boolean; + @ApiProperty({ type: Boolean, default: false }) + requiresProof: boolean; + + @ApiProperty({ type: Boolean, default: false }) + requiresDescription: boolean; + @ApiProperty() createdAt: Date; diff --git a/src/missions/dto/create-mission.dto.ts b/src/missions/dto/create-mission.dto.ts index 4bca274..2dbd0eb 100644 --- a/src/missions/dto/create-mission.dto.ts +++ b/src/missions/dto/create-mission.dto.ts @@ -36,6 +36,16 @@ export class CreateMissionDto { @Min(1) xpReward: number; + @ApiProperty({ example: 50 }) + @IsInt() + @Min(0) + participationReward: number; + + @ApiProperty({ example: 20 }) + @IsInt() + @Min(0) + auditorReward: number; + @ApiPropertyOptional({ default: false, description: 'Se true, não aparece na listagem pública', @@ -43,4 +53,14 @@ export class CreateMissionDto { @IsOptional() @IsBoolean() isSecret?: boolean; + + @ApiPropertyOptional({ default: false }) + @IsOptional() + @IsBoolean() + requiresProof?: boolean; + + @ApiPropertyOptional({ default: false }) + @IsOptional() + @IsBoolean() + requiresDescription?: boolean; } diff --git a/src/missions/dto/find-all-missions.dto.ts b/src/missions/dto/find-all-missions.dto.ts new file mode 100644 index 0000000..cb37ebe --- /dev/null +++ b/src/missions/dto/find-all-missions.dto.ts @@ -0,0 +1,27 @@ +import { ApiPropertyOptional } from '@nestjs/swagger'; +import { IsNumber, IsOptional, IsString, IsIn } from 'class-validator'; +import { Transform } from 'class-transformer'; + +export class FindAllMissionsDto { + @ApiPropertyOptional() + @Transform(({ value }) => (value ? Number(value) : 1)) + @IsNumber() + @IsOptional() + page?: number; + + @ApiPropertyOptional() + @Transform(({ value }) => (value ? Number(value) : 10)) + @IsNumber() + @IsOptional() + limit?: number; + + @ApiPropertyOptional() + @IsString() + @IsOptional() + search?: string; + + @ApiPropertyOptional({ enum: ['card', 'list'] }) + @IsIn(['card', 'list']) + @IsOptional() + view?: 'card' | 'list'; +} diff --git a/src/missions/dto/review-mission-submission.dto.ts b/src/missions/dto/review-mission-submission.dto.ts index 02d7165..03e43e0 100644 --- a/src/missions/dto/review-mission-submission.dto.ts +++ b/src/missions/dto/review-mission-submission.dto.ts @@ -1,5 +1,11 @@ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; -import { IsEnum, IsOptional, IsString, MaxLength } from 'class-validator'; +import { + IsEnum, + IsOptional, + IsBoolean, + IsString, + MaxLength, +} from 'class-validator'; import { MissionSubmissionStatus } from '../domain/mission-submission-status.enum'; export class ReviewMissionSubmissionDto { @@ -14,4 +20,9 @@ export class ReviewMissionSubmissionDto { @IsString() @MaxLength(500) feedback?: string; + + @ApiPropertyOptional() + @IsOptional() + @IsBoolean() + isWinner?: boolean; } diff --git a/src/missions/infrastructure/persistence/relational/entities/mission.entity.ts b/src/missions/infrastructure/persistence/relational/entities/mission.entity.ts index c28b8c9..f7c3ebc 100644 --- a/src/missions/infrastructure/persistence/relational/entities/mission.entity.ts +++ b/src/missions/infrastructure/persistence/relational/entities/mission.entity.ts @@ -25,6 +25,12 @@ export class MissionEntity extends EntityRelationalHelper { @Column({ type: 'int' }) xpReward: number; + @Column({ type: 'int', default: 50 }) + participationReward: number; + + @Column({ type: 'int', default: 20 }) + auditorReward: number; + @Column({ type: 'enum', enum: MissionStatus, default: MissionStatus.OPEN }) status: MissionStatus; @@ -34,6 +40,12 @@ export class MissionEntity extends EntityRelationalHelper { @Column({ type: 'boolean', default: false }) isSecret: boolean; + @Column({ type: 'boolean', default: false }) + requiresProof: boolean; + + @Column({ type: 'boolean', default: false }) + requiresDescription: boolean; + @CreateDateColumn() createdAt: Date; diff --git a/src/missions/missions.controller.ts b/src/missions/missions.controller.ts index 6cacb62..7fb6f0c 100644 --- a/src/missions/missions.controller.ts +++ b/src/missions/missions.controller.ts @@ -10,6 +10,7 @@ import { Post, Request, UseGuards, + Query, } from '@nestjs/common'; import { ApiBearerAuth, @@ -25,9 +26,15 @@ import { RoleEnum } from '../roles/roles.enum'; import { MissionsService } from './missions.service'; import { CreateMissionDto } from './dto/create-mission.dto'; import { SubmitMissionDto } from './dto/submit-mission.dto'; +import { FindAllMissionsDto } from './dto/find-all-missions.dto'; import { ReviewMissionSubmissionDto } from './dto/review-mission-submission.dto'; import { Mission } from './domain/mission'; import { MissionSubmission } from './domain/mission-submission'; +import { + InfinityPaginationResponse, + InfinityPaginationResponseDto, +} from '../utils/dto/infinity-pagination-response.dto'; +import { infinityPagination } from '../utils/infinity-pagination'; @ApiTags('Missions') @Controller({ path: 'missions', version: '1' }) @@ -37,9 +44,18 @@ export class MissionsController { // ── Public ─────────────────────────────────────────────────────────────────── @Get() - @ApiOkResponse({ type: [Mission] }) - findOpen() { - return this.missionsService.findOpen(); + @ApiOkResponse({ type: InfinityPaginationResponse(Mission) }) + async findOpen( + @Query() query: FindAllMissionsDto, + ): Promise> { + const page = query?.page ?? 1; + let limit = query?.limit ?? 10; + if (limit > 50) limit = 50; + + return infinityPagination( + await this.missionsService.findOpen({ ...query, page, limit }), + { page, limit }, + ); } @Get(':id') @@ -49,6 +65,29 @@ export class MissionsController { return this.missionsService.findById(id); } + @Get(':id/participants') + @ApiParam({ name: 'id', type: String }) + @ApiOkResponse({ + schema: { + properties: { + count: { type: 'number' }, + participants: { + type: 'array', + items: { + properties: { + username: { type: 'string' }, + status: { type: 'string' }, + submittedAt: { type: 'string', format: 'date-time' }, + }, + }, + }, + }, + }, + }) + findParticipants(@Param('id') id: string) { + return this.missionsService.findParticipants(id); + } + // ── Authenticated user ──────────────────────────────────────────────────────── @Post(':id/submit') @@ -88,9 +127,18 @@ export class MissionsController { @ApiBearerAuth() @UseGuards(AuthGuard('jwt'), RolesGuard) @Roles(RoleEnum.admin, RoleEnum.moderator) - @ApiOkResponse({ type: [Mission] }) - findAll() { - return this.missionsService.findAll(); + @ApiOkResponse({ type: InfinityPaginationResponse(Mission) }) + async findAll( + @Query() query: FindAllMissionsDto, + ): Promise> { + const page = query?.page ?? 1; + let limit = query?.limit ?? 10; + if (limit > 50) limit = 50; + + return infinityPagination( + await this.missionsService.findAll({ ...query, page, limit }), + { page, limit }, + ); } @Patch(':id') diff --git a/src/missions/missions.service.ts b/src/missions/missions.service.ts index 78da24d..c32be43 100644 --- a/src/missions/missions.service.ts +++ b/src/missions/missions.service.ts @@ -10,9 +10,12 @@ import { InjectDataSource } from '@nestjs/typeorm'; import { DataSource } from 'typeorm'; import { CreateMissionDto } from './dto/create-mission.dto'; import { SubmitMissionDto } from './dto/submit-mission.dto'; +import { FindAllMissionsDto } from './dto/find-all-missions.dto'; import { ReviewMissionSubmissionDto } from './dto/review-mission-submission.dto'; import { MissionStatus } from './domain/mission-status.enum'; import { MissionSubmissionStatus } from './domain/mission-submission-status.enum'; +import { TransactionEntity } from '../transactions/infrastructure/persistence/relational/entities/transaction.entity'; +import { TransactionCategoryEnum } from '../transactions/domain/transaction-category.enum'; import { MissionEntity } from './infrastructure/persistence/relational/entities/mission.entity'; import { MissionSubmissionEntity } from './infrastructure/persistence/relational/entities/mission-submission.entity'; import { GamificationProfileEntity } from '../gamification-profiles/infrastructure/persistence/relational/entities/gamification-profile.entity'; @@ -40,24 +43,86 @@ export class MissionsService { description: dto.description ?? null, requirements: dto.requirements ?? null, xpReward: dto.xpReward, + participationReward: dto.participationReward, + auditorReward: dto.auditorReward, isSecret: dto.isSecret ?? false, + requiresProof: dto.requiresProof ?? false, + requiresDescription: dto.requiresDescription ?? false, status: MissionStatus.OPEN, winnerId: null, }); return this.dataSource.getRepository(MissionEntity).save(mission); } - async findAll() { - return this.dataSource.getRepository(MissionEntity).find({ - order: { createdAt: 'DESC' }, - }); + async findAll(dto?: FindAllMissionsDto) { + const page = dto?.page ?? 1; + const limit = dto?.limit ?? 10; + const search = dto?.search; + const view = dto?.view; + + const query = this.dataSource + .getRepository(MissionEntity) + .createQueryBuilder('mission'); + + if (search) { + query.andWhere( + '(mission.title ILIKE :search OR mission.description ILIKE :search)', + { search: `%${search}%` }, + ); + } + + query.orderBy('mission.createdAt', 'DESC'); + query.skip((page - 1) * limit).take(limit); + + const missions = await query.getMany(); + + if (view === 'card') { + return missions.map((m) => ({ + id: m.id, + title: m.title, + xpReward: m.xpReward, + status: m.status, + createdAt: m.createdAt, + })); + } + return missions; } - async findOpen() { - return this.dataSource.getRepository(MissionEntity).find({ - where: { status: MissionStatus.OPEN, isSecret: false }, - order: { createdAt: 'DESC' }, - }); + async findOpen(dto?: FindAllMissionsDto) { + const page = dto?.page ?? 1; + const limit = dto?.limit ?? 10; + const search = dto?.search; + const view = dto?.view; + + const query = this.dataSource + .getRepository(MissionEntity) + .createQueryBuilder('mission'); + + query.andWhere('mission.status = :status', { status: MissionStatus.OPEN }); + query.andWhere('mission.isSecret = :isSecret', { isSecret: false }); + + if (search) { + query.andWhere( + '(mission.title ILIKE :search OR mission.description ILIKE :search)', + { search: `%${search}%` }, + ); + } + + query.orderBy('mission.createdAt', 'DESC'); + query.skip((page - 1) * limit).take(limit); + + const missions = await query.getMany(); + + if (view === 'card') { + return missions.map((m) => ({ + id: m.id, + title: m.title, + xpReward: m.xpReward, + status: m.status, + createdAt: m.createdAt, + })); + } + return missions; } async findById(id: string) { @@ -75,7 +140,19 @@ export class MissionsService { ...(dto.description !== undefined && { description: dto.description }), ...(dto.requirements !== undefined && { requirements: dto.requirements }), ...(dto.xpReward !== undefined && { xpReward: dto.xpReward }), + ...(dto.participationReward !== undefined && { + participationReward: dto.participationReward, + }), + ...(dto.auditorReward !== undefined && { + auditorReward: dto.auditorReward, + }), ...(dto.isSecret !== undefined && { isSecret: dto.isSecret }), + ...(dto.requiresProof !== undefined && { + requiresProof: dto.requiresProof, + }), + ...(dto.requiresDescription !== undefined && { + requiresDescription: dto.requiresDescription, + }), }); return this.dataSource.getRepository(MissionEntity).save(mission); } @@ -131,6 +208,28 @@ export class MissionsService { }); } + async findParticipants(missionId: string): Promise<{ + count: number; + participants: { username: string; status: string; submittedAt: Date }[]; + }> { + await this.findById(missionId); + const submissions = await this.dataSource + .getRepository(MissionSubmissionEntity) + .find({ + where: { missionId }, + relations: { profile: true }, + order: { createdAt: 'ASC' }, + }); + return { + count: submissions.length, + participants: submissions.map((s) => ({ + username: s.profile?.username ?? 'desconhecido', + status: s.status, + submittedAt: s.createdAt, + })), + }; + } + async findMySubmission(missionId: string, userId: number) { const profile = await this.dataSource .getRepository(GamificationProfileEntity) @@ -173,15 +272,11 @@ export class MissionsService { throw new BadRequestException('Feedback é obrigatório ao rejeitar.'); } - if (dto.status === MissionSubmissionStatus.APPROVED) { - // Check no other submission is already approved - const alreadyApproved = await this.dataSource - .getRepository(MissionSubmissionEntity) - .findOne({ - where: { missionId, status: MissionSubmissionStatus.APPROVED }, - }); - if (alreadyApproved) { - throw new ConflictException('Esta missão já tem um vencedor.'); + const isWinner = dto.isWinner === true; + + if (isWinner && dto.status === MissionSubmissionStatus.APPROVED) { + if (mission.status === MissionStatus.CLOSED) { + throw new ConflictException('Esta missão já foi encerrada.'); } } @@ -189,60 +284,103 @@ export class MissionsService { await queryRunner.connect(); await queryRunner.startTransaction(); try { + const awardedXp = + dto.status === MissionSubmissionStatus.APPROVED + ? isWinner + ? mission.xpReward + : mission.participationReward + : 0; + await queryRunner.manager.update(MissionSubmissionEntity, submissionId, { status: dto.status, feedback: dto.feedback ?? null, reviewerId: reviewerUserId, reviewedAt: new Date(), - awardedXp: - dto.status === MissionSubmissionStatus.APPROVED - ? mission.xpReward - : 0, + awardedXp, }); if (dto.status === MissionSubmissionStatus.APPROVED) { - // Grant XP to winner await queryRunner.manager.increment( GamificationProfileEntity, { id: submission.profileId }, 'totalXp', - mission.xpReward, + awardedXp, ); await queryRunner.manager.increment( GamificationProfileEntity, { id: submission.profileId }, 'currentMonthlyXp', - mission.xpReward, + awardedXp, ); await queryRunner.manager.increment( GamificationProfileEntity, { id: submission.profileId }, 'currentYearlyXp', - mission.xpReward, + awardedXp, ); - // Close mission and record winner - await queryRunner.manager.update(MissionEntity, missionId, { - status: MissionStatus.CLOSED, - winnerId: submission.profileId, + await queryRunner.manager.save(TransactionEntity, { + profile: { id: submission.profileId }, + category: TransactionCategoryEnum.XP_REWARD, + amount: awardedXp, + description: isWinner + ? `Venceu a missão: ${mission.title}` + : `Participação na missão: ${mission.title}`, }); - // Auto-reject remaining pending submissions - await queryRunner.manager - .createQueryBuilder() - .update(MissionSubmissionEntity) - .set({ - status: MissionSubmissionStatus.REJECTED, - feedback: 'A missão foi concluída por outro participante.', - reviewerId: reviewerUserId, - reviewedAt: new Date(), - }) - .where('missionId = :missionId AND status = :status AND id != :id', { - missionId, - status: MissionSubmissionStatus.PENDING, - id: submissionId, - }) - .execute(); + if (isWinner) { + await queryRunner.manager.update(MissionEntity, missionId, { + status: MissionStatus.CLOSED, + winnerId: submission.profileId, + }); + + await queryRunner.manager + .createQueryBuilder() + .update(MissionSubmissionEntity) + .set({ + status: MissionSubmissionStatus.REJECTED, + feedback: 'A missão foi concluída por outro participante.', + reviewerId: reviewerUserId, + reviewedAt: new Date(), + }) + .where( + 'missionId = :missionId AND status = :status AND id != :id', + { + missionId, + status: MissionSubmissionStatus.PENDING, + id: submissionId, + }, + ) + .execute(); + } + } + + if (reviewerProfile) { + await queryRunner.manager.increment( + GamificationProfileEntity, + { id: reviewerProfile.id }, + 'totalXp', + mission.auditorReward, + ); + await queryRunner.manager.increment( + GamificationProfileEntity, + { id: reviewerProfile.id }, + 'currentMonthlyXp', + mission.auditorReward, + ); + await queryRunner.manager.increment( + GamificationProfileEntity, + { id: reviewerProfile.id }, + 'currentYearlyXp', + mission.auditorReward, + ); + + await queryRunner.manager.save(TransactionEntity, { + profile: { id: reviewerProfile.id }, + category: TransactionCategoryEnum.AUDITOR_REWARD, + amount: mission.auditorReward, + description: `Recompensa por auditoria de missão: ${mission.title}`, + }); } await queryRunner.commitTransaction(); diff --git a/src/notifications/domain/notification-type.enum.ts b/src/notifications/domain/notification-type.enum.ts index e9902db..10a4f23 100644 --- a/src/notifications/domain/notification-type.enum.ts +++ b/src/notifications/domain/notification-type.enum.ts @@ -4,9 +4,14 @@ export enum NotificationType { SUBMISSION_REJECTED = 'SUBMISSION_REJECTED', CONTRIBUTION_REPORT_UPHELD = 'CONTRIBUTION_REPORT_UPHELD', CONTRIBUTION_REPORT_RECEIVED = 'CONTRIBUTION_REPORT_RECEIVED', + NEW_SUBMISSION_PENDING = 'NEW_SUBMISSION_PENDING', TRACK_MILESTONE_APPROVED = 'TRACK_MILESTONE_APPROVED', TRACK_BADGE_GRANTED = 'TRACK_BADGE_GRANTED', LEGAL_DOCUMENT_UPDATED = 'LEGAL_DOCUMENT_UPDATED', EVENT_UPDATED = 'EVENT_UPDATED', EVENT_CANCELLED = 'EVENT_CANCELLED', + PROJECT_IDEA_APPROVED = 'PROJECT_IDEA_APPROVED', + PROJECT_IDEA_REJECTED = 'PROJECT_IDEA_REJECTED', + PROJECT_IDEA_INTEREST = 'PROJECT_IDEA_INTEREST', + PROJECT_TEAM_MEMBER_ADDED = 'PROJECT_TEAM_MEMBER_ADDED', } diff --git a/src/project-teams/domain/project-idea-status.enum.ts b/src/project-teams/domain/project-idea-status.enum.ts new file mode 100644 index 0000000..00e3ca2 --- /dev/null +++ b/src/project-teams/domain/project-idea-status.enum.ts @@ -0,0 +1,6 @@ +export enum ProjectIdeaStatus { + PENDING = 'PENDING', + APPROVED = 'APPROVED', + REJECTED = 'REJECTED', + TEAM_FORMED = 'TEAM_FORMED', +} diff --git a/src/project-teams/domain/project-idea.ts b/src/project-teams/domain/project-idea.ts new file mode 100644 index 0000000..d84c133 --- /dev/null +++ b/src/project-teams/domain/project-idea.ts @@ -0,0 +1,92 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { ProjectIdeaStatus } from './project-idea-status.enum'; +import { ProjectRole } from './project-role.enum'; +import { ProjectUserSummary } from './project-user-summary'; + +export class ProjectIdea { + @ApiProperty({ type: String }) + id: string; + + @ApiProperty({ type: String }) + title: string; + + @ApiProperty({ type: String }) + description: string; + + @ApiProperty({ type: [String], example: ['nestjs', 'react'] }) + tags: string[]; + + @ApiProperty({ enum: ProjectIdeaStatus }) + status: ProjectIdeaStatus; + + @ApiProperty({ type: String, nullable: true }) + rejectionReason: string | null; + + @ApiProperty({ type: Number }) + authorId: number; + + @ApiProperty({ type: () => ProjectUserSummary, nullable: true }) + author?: ProjectUserSummary | null; + + @ApiProperty({ type: Number, nullable: true }) + reviewerId: number | null; + + @ApiProperty({ nullable: true }) + reviewedAt: Date | null; + + @ApiProperty({ + type: Number, + description: 'Quantidade de pessoas que demonstraram interesse', + }) + interestCount: number; + + @ApiProperty({ + type: String, + nullable: true, + description: 'ID do time criado a partir da ideia, se já existir', + }) + teamId: string | null; + + @ApiProperty() + createdAt: Date; + + @ApiProperty() + updatedAt: Date; +} + +export class ProjectIdeaInterest { + @ApiProperty({ type: String }) + id: string; + + @ApiProperty({ type: String }) + ideaId: string; + + @ApiProperty({ type: Number }) + userId: number; + + @ApiProperty({ type: () => ProjectUserSummary, nullable: true }) + user?: ProjectUserSummary | null; + + @ApiProperty({ enum: ProjectRole }) + role: ProjectRole; + + @ApiProperty({ type: String, nullable: true }) + message: string | null; + + @ApiProperty() + createdAt: Date; +} + +export class SuggestedVacancy { + @ApiProperty({ enum: ProjectRole }) + role: ProjectRole; + + @ApiProperty({ type: Number }) + quantity: number; + + @ApiProperty({ type: Number }) + interestedCount: number; + + @ApiProperty({ type: String }) + reason: string; +} diff --git a/src/project-teams/domain/project-role.enum.ts b/src/project-teams/domain/project-role.enum.ts new file mode 100644 index 0000000..969bda4 --- /dev/null +++ b/src/project-teams/domain/project-role.enum.ts @@ -0,0 +1,11 @@ +export enum ProjectRole { + FRONTEND = 'FRONTEND', + BACKEND = 'BACKEND', + DATABASE = 'DATABASE', + REQUIREMENTS_ANALYST = 'REQUIREMENTS_ANALYST', + UX_DESIGNER = 'UX_DESIGNER', + QA = 'QA', + DEVOPS = 'DEVOPS', + MOBILE = 'MOBILE', + PROJECT_MANAGER = 'PROJECT_MANAGER', +} diff --git a/src/project-teams/domain/project-team-status.enum.ts b/src/project-teams/domain/project-team-status.enum.ts new file mode 100644 index 0000000..43f4c25 --- /dev/null +++ b/src/project-teams/domain/project-team-status.enum.ts @@ -0,0 +1,6 @@ +export enum ProjectTeamStatus { + RECRUITING = 'RECRUITING', + IN_PROGRESS = 'IN_PROGRESS', + COMPLETED = 'COMPLETED', + CANCELLED = 'CANCELLED', +} diff --git a/src/project-teams/domain/project-team.ts b/src/project-teams/domain/project-team.ts new file mode 100644 index 0000000..e2a1e25 --- /dev/null +++ b/src/project-teams/domain/project-team.ts @@ -0,0 +1,73 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { ProjectRole } from './project-role.enum'; +import { ProjectTeamStatus } from './project-team-status.enum'; +import { ProjectUserSummary } from './project-user-summary'; + +export class ProjectTeamVacancy { + @ApiProperty({ enum: ProjectRole }) + role: ProjectRole; + + @ApiProperty({ type: Number }) + quantity: number; + + @ApiProperty({ type: Number, description: 'Vagas já preenchidas' }) + filled: number; +} + +export class ProjectTeamMember { + @ApiProperty({ type: String }) + id: string; + + @ApiProperty({ type: Number }) + userId: number; + + @ApiProperty({ type: () => ProjectUserSummary, nullable: true }) + user?: ProjectUserSummary | null; + + @ApiProperty({ enum: ProjectRole }) + role: ProjectRole; + + @ApiProperty() + createdAt: Date; +} + +export class ProjectTeam { + @ApiProperty({ type: String }) + id: string; + + @ApiProperty({ type: String }) + ideaId: string; + + @ApiProperty({ type: String }) + ideaTitle: string; + + @ApiProperty({ type: String }) + name: string; + + @ApiProperty({ type: String, nullable: true }) + description: string | null; + + @ApiProperty({ enum: ProjectTeamStatus }) + status: ProjectTeamStatus; + + @ApiProperty({ type: String, nullable: true }) + repoUrl: string | null; + + @ApiProperty({ type: Number }) + ownerId: number; + + @ApiProperty({ type: () => ProjectUserSummary, nullable: true }) + owner?: ProjectUserSummary | null; + + @ApiProperty({ type: () => [ProjectTeamVacancy] }) + vacancies: ProjectTeamVacancy[]; + + @ApiProperty({ type: () => [ProjectTeamMember] }) + members: ProjectTeamMember[]; + + @ApiProperty() + createdAt: Date; + + @ApiProperty() + updatedAt: Date; +} diff --git a/src/project-teams/domain/project-user-summary.ts b/src/project-teams/domain/project-user-summary.ts new file mode 100644 index 0000000..f131e4b --- /dev/null +++ b/src/project-teams/domain/project-user-summary.ts @@ -0,0 +1,16 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { FileType } from '../../files/domain/file'; + +export class ProjectUserSummary { + @ApiProperty({ type: Number }) + id: number; + + @ApiProperty({ type: String, nullable: true }) + firstName: string | null; + + @ApiProperty({ type: String, nullable: true }) + lastName: string | null; + + @ApiProperty({ type: () => FileType, nullable: true }) + photo?: FileType | null; +} diff --git a/src/project-teams/dto/add-project-team-member.dto.ts b/src/project-teams/dto/add-project-team-member.dto.ts new file mode 100644 index 0000000..6f536cc --- /dev/null +++ b/src/project-teams/dto/add-project-team-member.dto.ts @@ -0,0 +1,13 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsEnum, IsInt } from 'class-validator'; +import { ProjectRole } from '../domain/project-role.enum'; + +export class AddProjectTeamMemberDto { + @ApiProperty({ example: 12, description: 'Usuário que demonstrou interesse' }) + @IsInt() + userId: number; + + @ApiProperty({ enum: ProjectRole }) + @IsEnum(ProjectRole) + role: ProjectRole; +} diff --git a/src/project-teams/dto/create-project-idea.dto.ts b/src/project-teams/dto/create-project-idea.dto.ts new file mode 100644 index 0000000..b8dce18 --- /dev/null +++ b/src/project-teams/dto/create-project-idea.dto.ts @@ -0,0 +1,50 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { Transform } from 'class-transformer'; +import { + ArrayMaxSize, + IsArray, + IsOptional, + IsString, + MaxLength, + MinLength, +} from 'class-validator'; + +export class CreateProjectIdeaDto { + @ApiProperty({ example: 'Plataforma de doação de alimentos' }) + @IsString() + @MinLength(5) + @MaxLength(150) + title: string; + + @ApiProperty({ + example: 'Conectar mercados e ONGs para reduzir o desperdício de comida.', + }) + @IsString() + @MinLength(20) + @MaxLength(5000) + description: string; + + @ApiPropertyOptional({ + type: [String], + example: ['nestjs', 'react'], + description: 'Tecnologias/temas do projeto (máx. 8)', + }) + @IsOptional() + @IsArray() + @ArrayMaxSize(8) + @IsString({ each: true }) + @MaxLength(30, { each: true }) + @Transform(({ value }) => + Array.isArray(value) + ? Array.from( + new Set( + value + .filter((tag) => typeof tag === 'string') + .map((tag: string) => tag.trim().toLowerCase()) + .filter(Boolean), + ), + ) + : value, + ) + tags?: string[]; +} diff --git a/src/project-teams/dto/create-project-team.dto.ts b/src/project-teams/dto/create-project-team.dto.ts new file mode 100644 index 0000000..cbee4c9 --- /dev/null +++ b/src/project-teams/dto/create-project-team.dto.ts @@ -0,0 +1,87 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { Type } from 'class-transformer'; +import { + ArrayMaxSize, + ArrayMinSize, + IsArray, + IsEnum, + IsInt, + IsOptional, + IsString, + IsUUID, + IsUrl, + Max, + MaxLength, + Min, + MinLength, + ValidateNested, +} from 'class-validator'; +import { ProjectRole } from '../domain/project-role.enum'; + +export class ProjectVacancyDto { + @ApiProperty({ enum: ProjectRole, example: ProjectRole.FRONTEND }) + @IsEnum(ProjectRole) + role: ProjectRole; + + @ApiProperty({ example: 2, minimum: 1, maximum: 10 }) + @IsInt() + @Min(1) + @Max(10) + quantity: number; +} + +export class ProjectInitialMemberDto { + @ApiProperty({ example: 12, description: 'Usuário que demonstrou interesse' }) + @IsInt() + userId: number; + + @ApiProperty({ enum: ProjectRole, example: ProjectRole.BACKEND }) + @IsEnum(ProjectRole) + role: ProjectRole; +} + +export class CreateProjectTeamDto { + @ApiProperty({ type: String, description: 'Ideia aprovada de origem' }) + @IsUUID() + ideaId: string; + + @ApiProperty({ example: 'Time Doação Digital' }) + @IsString() + @MinLength(3) + @MaxLength(150) + name: string; + + @ApiPropertyOptional({ example: 'Vamos construir o MVP em 3 meses.' }) + @IsOptional() + @IsString() + @MaxLength(2000) + description?: string; + + @ApiPropertyOptional({ example: 'https://github.com/devs-tocantins/doacao' }) + @IsOptional() + @IsUrl() + repoUrl?: string; + + @ApiProperty({ + type: () => [ProjectVacancyDto], + description: 'Cargos e quantidade de vagas do time', + }) + @IsArray() + @ArrayMinSize(1) + @ArrayMaxSize(9) + @ValidateNested({ each: true }) + @Type(() => ProjectVacancyDto) + vacancies: ProjectVacancyDto[]; + + @ApiPropertyOptional({ + type: () => [ProjectInitialMemberDto], + description: + 'Interessados já escolhidos para o time, com o cargo de cada um', + }) + @IsOptional() + @IsArray() + @ArrayMaxSize(50) + @ValidateNested({ each: true }) + @Type(() => ProjectInitialMemberDto) + members?: ProjectInitialMemberDto[]; +} diff --git a/src/project-teams/dto/find-projects.dto.ts b/src/project-teams/dto/find-projects.dto.ts new file mode 100644 index 0000000..dfb0b7e --- /dev/null +++ b/src/project-teams/dto/find-projects.dto.ts @@ -0,0 +1,26 @@ +import { ApiPropertyOptional } from '@nestjs/swagger'; +import { Transform } from 'class-transformer'; +import { IsEnum, IsNumber, IsOptional } from 'class-validator'; +import { ProjectTeamStatus } from '../domain/project-team-status.enum'; + +export class FindProjectsDto { + @ApiPropertyOptional() + @Transform(({ value }) => (value ? Number(value) : 1)) + @IsNumber() + @IsOptional() + page?: number; + + @ApiPropertyOptional() + @Transform(({ value }) => (value ? Number(value) : 10)) + @IsNumber() + @IsOptional() + limit?: number; + + @ApiPropertyOptional({ + enum: ProjectTeamStatus, + description: 'Filtro de status (apenas na listagem de times)', + }) + @IsOptional() + @IsEnum(ProjectTeamStatus) + status?: ProjectTeamStatus; +} diff --git a/src/project-teams/dto/review-project-idea.dto.ts b/src/project-teams/dto/review-project-idea.dto.ts new file mode 100644 index 0000000..3fe1577 --- /dev/null +++ b/src/project-teams/dto/review-project-idea.dto.ts @@ -0,0 +1,27 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { IsEnum, IsOptional, IsString } from 'class-validator'; +import { ProjectIdeaStatus } from '../domain/project-idea-status.enum'; + +const allowedStatuses = [ + ProjectIdeaStatus.APPROVED, + ProjectIdeaStatus.REJECTED, +]; + +export class ReviewProjectIdeaDto { + @ApiProperty({ + enum: allowedStatuses, + description: 'Decisão do moderador: APPROVED ou REJECTED', + }) + @IsEnum(allowedStatuses, { + message: 'status deve ser APPROVED ou REJECTED', + }) + status: ProjectIdeaStatus.APPROVED | ProjectIdeaStatus.REJECTED; + + @ApiPropertyOptional({ + type: String, + description: 'Motivo obrigatório em caso de rejeição', + }) + @IsOptional() + @IsString() + rejectionReason?: string; +} diff --git a/src/project-teams/dto/set-project-interest.dto.ts b/src/project-teams/dto/set-project-interest.dto.ts new file mode 100644 index 0000000..d453fd1 --- /dev/null +++ b/src/project-teams/dto/set-project-interest.dto.ts @@ -0,0 +1,21 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { IsEnum, IsOptional, IsString, MaxLength } from 'class-validator'; +import { ProjectRole } from '../domain/project-role.enum'; + +export class SetProjectInterestDto { + @ApiProperty({ + enum: ProjectRole, + example: ProjectRole.FRONTEND, + description: 'Cargo em que a pessoa gostaria de atuar', + }) + @IsEnum(ProjectRole) + role: ProjectRole; + + @ApiPropertyOptional({ + example: 'Tenho 2 anos de React e tempo nos fins de semana.', + }) + @IsOptional() + @IsString() + @MaxLength(500) + message?: string; +} diff --git a/src/project-teams/dto/update-project-idea.dto.ts b/src/project-teams/dto/update-project-idea.dto.ts new file mode 100644 index 0000000..b3e1a34 --- /dev/null +++ b/src/project-teams/dto/update-project-idea.dto.ts @@ -0,0 +1,4 @@ +import { PartialType } from '@nestjs/swagger'; +import { CreateProjectIdeaDto } from './create-project-idea.dto'; + +export class UpdateProjectIdeaDto extends PartialType(CreateProjectIdeaDto) {} diff --git a/src/project-teams/dto/update-project-team.dto.ts b/src/project-teams/dto/update-project-team.dto.ts new file mode 100644 index 0000000..6e76d3f --- /dev/null +++ b/src/project-teams/dto/update-project-team.dto.ts @@ -0,0 +1,57 @@ +import { ApiPropertyOptional } from '@nestjs/swagger'; +import { Type } from 'class-transformer'; +import { + ArrayMaxSize, + ArrayMinSize, + IsArray, + IsEnum, + IsOptional, + IsString, + IsUrl, + MaxLength, + MinLength, + ValidateIf, + ValidateNested, +} from 'class-validator'; +import { ProjectTeamStatus } from '../domain/project-team-status.enum'; +import { ProjectVacancyDto } from './create-project-team.dto'; + +export class UpdateProjectTeamDto { + @ApiPropertyOptional() + @IsOptional() + @IsString() + @MinLength(3) + @MaxLength(150) + name?: string; + + @ApiPropertyOptional({ nullable: true }) + @IsOptional() + @IsString() + @MaxLength(2000) + description?: string | null; + + @ApiPropertyOptional({ + nullable: true, + description: 'Link do repositório. Envie null para remover.', + }) + @ValidateIf((_, value) => value !== null && value !== undefined) + @IsUrl() + repoUrl?: string | null; + + @ApiPropertyOptional({ enum: ProjectTeamStatus }) + @IsOptional() + @IsEnum(ProjectTeamStatus) + status?: ProjectTeamStatus; + + @ApiPropertyOptional({ + type: () => [ProjectVacancyDto], + description: 'Substitui todas as vagas do time', + }) + @IsOptional() + @IsArray() + @ArrayMinSize(1) + @ArrayMaxSize(9) + @ValidateNested({ each: true }) + @Type(() => ProjectVacancyDto) + vacancies?: ProjectVacancyDto[]; +} diff --git a/src/project-teams/infrastructure/persistence/project-idea.repository.ts b/src/project-teams/infrastructure/persistence/project-idea.repository.ts new file mode 100644 index 0000000..b6a2ef7 --- /dev/null +++ b/src/project-teams/infrastructure/persistence/project-idea.repository.ts @@ -0,0 +1,72 @@ +import { NullableType } from '../../../utils/types/nullable.type'; +import { IPaginationOptions } from '../../../utils/types/pagination-options'; +import { ProjectIdea, ProjectIdeaInterest } from '../../domain/project-idea'; +import { ProjectIdeaStatus } from '../../domain/project-idea-status.enum'; +import { ProjectRole } from '../../domain/project-role.enum'; + +export type ProjectIdeaUpdate = Partial< + Pick< + ProjectIdea, + | 'title' + | 'description' + | 'tags' + | 'status' + | 'rejectionReason' + | 'reviewerId' + | 'reviewedAt' + > +>; + +export abstract class ProjectIdeaRepository { + abstract create(data: { + title: string; + description: string; + tags: string[]; + authorId: number; + }): Promise; + + abstract findById(id: ProjectIdea['id']): Promise>; + + /** Ideias aprovadas (com ou sem time já formado). */ + abstract findPublic( + paginationOptions: IPaginationOptions, + ): Promise; + + abstract findByAuthorId( + authorId: number, + paginationOptions: IPaginationOptions, + ): Promise; + + abstract findByStatus( + status: ProjectIdeaStatus, + paginationOptions: IPaginationOptions, + ): Promise; + + abstract update( + id: ProjectIdea['id'], + payload: ProjectIdeaUpdate, + ): Promise; + + abstract remove(id: ProjectIdea['id']): Promise; + + abstract upsertInterest( + ideaId: ProjectIdea['id'], + userId: number, + role: ProjectRole, + message: string | null, + ): Promise; + + abstract removeInterest( + ideaId: ProjectIdea['id'], + userId: number, + ): Promise; + + abstract findInterest( + ideaId: ProjectIdea['id'], + userId: number, + ): Promise>; + + abstract findInterests( + ideaId: ProjectIdea['id'], + ): Promise; +} diff --git a/src/project-teams/infrastructure/persistence/project-team.repository.ts b/src/project-teams/infrastructure/persistence/project-team.repository.ts new file mode 100644 index 0000000..b21b011 --- /dev/null +++ b/src/project-teams/infrastructure/persistence/project-team.repository.ts @@ -0,0 +1,60 @@ +import { NullableType } from '../../../utils/types/nullable.type'; +import { IPaginationOptions } from '../../../utils/types/pagination-options'; +import { ProjectRole } from '../../domain/project-role.enum'; +import { ProjectTeam } from '../../domain/project-team'; +import { ProjectTeamStatus } from '../../domain/project-team-status.enum'; + +export type ProjectTeamVacancyInput = { role: ProjectRole; quantity: number }; +export type ProjectTeamMemberInput = { userId: number; role: ProjectRole }; + +export type ProjectTeamUpdate = Partial< + Pick +>; + +export abstract class ProjectTeamRepository { + /** + * Cria o time com vagas e membros iniciais e marca a ideia de origem como + * TEAM_FORMED, tudo na mesma transação. + */ + abstract create(data: { + ideaId: string; + name: string; + description: string | null; + repoUrl: string | null; + ownerId: number; + vacancies: ProjectTeamVacancyInput[]; + members: ProjectTeamMemberInput[]; + }): Promise; + + abstract findById(id: ProjectTeam['id']): Promise>; + + abstract findByIdeaId(ideaId: string): Promise>; + + abstract findPublic( + paginationOptions: IPaginationOptions, + status?: ProjectTeamStatus, + ): Promise; + + /** Times em que o usuário é dono ou membro. */ + abstract findByUserId( + userId: number, + paginationOptions: IPaginationOptions, + ): Promise; + + abstract update( + id: ProjectTeam['id'], + payload: ProjectTeamUpdate, + ): Promise; + + abstract replaceVacancies( + id: ProjectTeam['id'], + vacancies: ProjectTeamVacancyInput[], + ): Promise; + + abstract addMember( + id: ProjectTeam['id'], + member: ProjectTeamMemberInput, + ): Promise; + + abstract removeMember(id: ProjectTeam['id'], userId: number): Promise; +} diff --git a/src/project-teams/infrastructure/persistence/relational/entities/project-idea-interest.entity.ts b/src/project-teams/infrastructure/persistence/relational/entities/project-idea-interest.entity.ts new file mode 100644 index 0000000..0dc2742 --- /dev/null +++ b/src/project-teams/infrastructure/persistence/relational/entities/project-idea-interest.entity.ts @@ -0,0 +1,43 @@ +import { + Column, + CreateDateColumn, + Entity, + Index, + JoinColumn, + ManyToOne, + PrimaryGeneratedColumn, +} from 'typeorm'; +import { EntityRelationalHelper } from '../../../../../utils/relational-entity-helper'; +import { UserEntity } from '../../../../../users/infrastructure/persistence/relational/entities/user.entity'; +import { ProjectRole } from '../../../../domain/project-role.enum'; +import { ProjectIdeaEntity } from './project-idea.entity'; + +@Entity({ name: 'project_idea_interest' }) +@Index(['ideaId', 'userId'], { unique: true }) +export class ProjectIdeaInterestEntity extends EntityRelationalHelper { + @PrimaryGeneratedColumn('uuid') + id: string; + + @Column({ type: 'uuid' }) + ideaId: string; + + @ManyToOne(() => ProjectIdeaEntity, { eager: false, onDelete: 'CASCADE' }) + @JoinColumn({ name: 'ideaId' }) + idea: ProjectIdeaEntity; + + @Column({ type: 'int' }) + userId: number; + + @ManyToOne(() => UserEntity, { eager: false }) + @JoinColumn({ name: 'userId' }) + user: UserEntity; + + @Column({ type: 'enum', enum: ProjectRole, enumName: 'project_role_enum' }) + role: ProjectRole; + + @Column({ type: 'text', nullable: true, default: null }) + message: string | null; + + @CreateDateColumn() + createdAt: Date; +} 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 new file mode 100644 index 0000000..12ebd22 --- /dev/null +++ b/src/project-teams/infrastructure/persistence/relational/entities/project-idea.entity.ts @@ -0,0 +1,62 @@ +import { + Column, + CreateDateColumn, + Entity, + Index, + JoinColumn, + ManyToOne, + PrimaryGeneratedColumn, + UpdateDateColumn, +} from 'typeorm'; +import { EntityRelationalHelper } from '../../../../../utils/relational-entity-helper'; +import { UserEntity } from '../../../../../users/infrastructure/persistence/relational/entities/user.entity'; +import { ProjectIdeaStatus } from '../../../../domain/project-idea-status.enum'; + +@Entity({ name: 'project_idea' }) +@Index(['status', 'createdAt']) +export class ProjectIdeaEntity extends EntityRelationalHelper { + @PrimaryGeneratedColumn('uuid') + id: string; + + @Column({ type: 'varchar', length: 150 }) + title: string; + + @Column({ type: 'text' }) + description: string; + + @Column({ type: 'varchar', array: true, default: () => `'{}'` }) + tags: string[]; + + @Column({ + type: 'enum', + enum: ProjectIdeaStatus, + default: ProjectIdeaStatus.PENDING, + }) + status: ProjectIdeaStatus; + + @Column({ type: 'text', nullable: true, default: null }) + rejectionReason: string | null; + + @Column({ type: 'int' }) + authorId: number; + + @ManyToOne(() => UserEntity, { eager: false }) + @JoinColumn({ name: 'authorId' }) + author: UserEntity; + + @Column({ type: 'int', nullable: true, default: null }) + reviewerId: number | null; + + @ManyToOne(() => UserEntity, { nullable: true, eager: false }) + @JoinColumn({ name: 'reviewerId' }) + reviewer: UserEntity | null; + + @Column({ type: 'timestamp', nullable: true, default: null }) + reviewedAt: Date | null; + + @CreateDateColumn() + createdAt: Date; + + @UpdateDateColumn() + updatedAt: Date; +} diff --git a/src/project-teams/infrastructure/persistence/relational/entities/project-team-member.entity.ts b/src/project-teams/infrastructure/persistence/relational/entities/project-team-member.entity.ts new file mode 100644 index 0000000..037f09c --- /dev/null +++ b/src/project-teams/infrastructure/persistence/relational/entities/project-team-member.entity.ts @@ -0,0 +1,43 @@ +import { + Column, + CreateDateColumn, + Entity, + Index, + JoinColumn, + ManyToOne, + PrimaryGeneratedColumn, +} from 'typeorm'; +import { EntityRelationalHelper } from '../../../../../utils/relational-entity-helper'; +import { UserEntity } from '../../../../../users/infrastructure/persistence/relational/entities/user.entity'; +import { ProjectRole } from '../../../../domain/project-role.enum'; +import { ProjectTeamEntity } from './project-team.entity'; + +@Entity({ name: 'project_team_member' }) +@Index(['teamId', 'userId'], { unique: true }) +export class ProjectTeamMemberEntity extends EntityRelationalHelper { + @PrimaryGeneratedColumn('uuid') + id: string; + + @Column({ type: 'uuid' }) + teamId: string; + + @ManyToOne(() => ProjectTeamEntity, (team) => team.members, { + eager: false, + onDelete: 'CASCADE', + }) + @JoinColumn({ name: 'teamId' }) + team: ProjectTeamEntity; + + @Column({ type: 'int' }) + userId: number; + + @ManyToOne(() => UserEntity, { eager: false }) + @JoinColumn({ name: 'userId' }) + user: UserEntity; + + @Column({ type: 'enum', enum: ProjectRole, enumName: 'project_role_enum' }) + role: ProjectRole; + + @CreateDateColumn() + createdAt: Date; +} diff --git a/src/project-teams/infrastructure/persistence/relational/entities/project-team-vacancy.entity.ts b/src/project-teams/infrastructure/persistence/relational/entities/project-team-vacancy.entity.ts new file mode 100644 index 0000000..e5efb17 --- /dev/null +++ b/src/project-teams/infrastructure/persistence/relational/entities/project-team-vacancy.entity.ts @@ -0,0 +1,34 @@ +import { + Column, + Entity, + Index, + JoinColumn, + ManyToOne, + PrimaryGeneratedColumn, +} from 'typeorm'; +import { EntityRelationalHelper } from '../../../../../utils/relational-entity-helper'; +import { ProjectRole } from '../../../../domain/project-role.enum'; +import { ProjectTeamEntity } from './project-team.entity'; + +@Entity({ name: 'project_team_vacancy' }) +@Index(['teamId', 'role'], { unique: true }) +export class ProjectTeamVacancyEntity extends EntityRelationalHelper { + @PrimaryGeneratedColumn('uuid') + id: string; + + @Column({ type: 'uuid' }) + teamId: string; + + @ManyToOne(() => ProjectTeamEntity, (team) => team.vacancies, { + eager: false, + onDelete: 'CASCADE', + }) + @JoinColumn({ name: 'teamId' }) + team: ProjectTeamEntity; + + @Column({ type: 'enum', enum: ProjectRole, enumName: 'project_role_enum' }) + role: ProjectRole; + + @Column({ type: 'int' }) + quantity: number; +} diff --git a/src/project-teams/infrastructure/persistence/relational/entities/project-team.entity.ts b/src/project-teams/infrastructure/persistence/relational/entities/project-team.entity.ts new file mode 100644 index 0000000..99f97bd --- /dev/null +++ b/src/project-teams/infrastructure/persistence/relational/entities/project-team.entity.ts @@ -0,0 +1,65 @@ +import { + Column, + CreateDateColumn, + Entity, + JoinColumn, + ManyToOne, + OneToMany, + OneToOne, + PrimaryGeneratedColumn, + UpdateDateColumn, +} from 'typeorm'; +import { EntityRelationalHelper } from '../../../../../utils/relational-entity-helper'; +import { UserEntity } from '../../../../../users/infrastructure/persistence/relational/entities/user.entity'; +import { ProjectTeamStatus } from '../../../../domain/project-team-status.enum'; +import { ProjectIdeaEntity } from './project-idea.entity'; +import { ProjectTeamVacancyEntity } from './project-team-vacancy.entity'; +import { ProjectTeamMemberEntity } from './project-team-member.entity'; + +@Entity({ name: 'project_team' }) +export class ProjectTeamEntity extends EntityRelationalHelper { + @PrimaryGeneratedColumn('uuid') + id: string; + + @Column({ type: 'uuid', unique: true }) + ideaId: string; + + @OneToOne(() => ProjectIdeaEntity, { eager: false, onDelete: 'CASCADE' }) + @JoinColumn({ name: 'ideaId' }) + idea: ProjectIdeaEntity; + + @Column({ type: 'varchar', length: 150 }) + name: string; + + @Column({ type: 'text', nullable: true, default: null }) + description: string | null; + + @Column({ + type: 'enum', + enum: ProjectTeamStatus, + default: ProjectTeamStatus.RECRUITING, + }) + status: ProjectTeamStatus; + + @Column({ type: 'varchar', nullable: true, default: null }) + repoUrl: string | null; + + @Column({ type: 'int' }) + ownerId: number; + + @ManyToOne(() => UserEntity, { eager: false }) + @JoinColumn({ name: 'ownerId' }) + owner: UserEntity; + + @OneToMany(() => ProjectTeamVacancyEntity, (vacancy) => vacancy.team) + vacancies: ProjectTeamVacancyEntity[]; + + @OneToMany(() => ProjectTeamMemberEntity, (member) => member.team) + members: ProjectTeamMemberEntity[]; + + @CreateDateColumn() + createdAt: Date; + + @UpdateDateColumn() + updatedAt: 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 new file mode 100644 index 0000000..f0bd45e --- /dev/null +++ b/src/project-teams/infrastructure/persistence/relational/mappers/project.mapper.ts @@ -0,0 +1,101 @@ +import { FileMapper } from '../../../../../files/infrastructure/persistence/relational/mappers/file.mapper'; +import { UserEntity } from '../../../../../users/infrastructure/persistence/relational/entities/user.entity'; +import { + ProjectIdea, + ProjectIdeaInterest, +} from '../../../../domain/project-idea'; +import { + ProjectTeam, + ProjectTeamMember, + ProjectTeamVacancy, +} from '../../../../domain/project-team'; +import { ProjectUserSummary } from '../../../../domain/project-user-summary'; +import { ProjectIdeaEntity } from '../entities/project-idea.entity'; +import { ProjectIdeaInterestEntity } from '../entities/project-idea-interest.entity'; +import { ProjectTeamEntity } from '../entities/project-team.entity'; + +export class ProjectMapper { + static userSummary(raw?: UserEntity | null): ProjectUserSummary | null { + if (!raw) { + return null; + } + const summary = new ProjectUserSummary(); + summary.id = raw.id as number; + summary.firstName = raw.firstName ?? null; + summary.lastName = raw.lastName ?? null; + summary.photo = raw.photo ? FileMapper.toDomain(raw.photo) : null; + return summary; + } + + static ideaToDomain( + raw: ProjectIdeaEntity, + extras: { interestCount: number; teamId: string | null }, + ): ProjectIdea { + const idea = new ProjectIdea(); + idea.id = raw.id; + idea.title = raw.title; + idea.description = raw.description; + idea.tags = raw.tags ?? []; + idea.status = raw.status; + idea.rejectionReason = raw.rejectionReason; + idea.authorId = raw.authorId; + idea.author = ProjectMapper.userSummary(raw.author); + idea.reviewerId = raw.reviewerId; + idea.reviewedAt = raw.reviewedAt; + idea.interestCount = extras.interestCount; + idea.teamId = extras.teamId; + idea.createdAt = raw.createdAt; + idea.updatedAt = raw.updatedAt; + return idea; + } + + static interestToDomain(raw: ProjectIdeaInterestEntity): ProjectIdeaInterest { + const interest = new ProjectIdeaInterest(); + interest.id = raw.id; + interest.ideaId = raw.ideaId; + interest.userId = raw.userId; + interest.user = ProjectMapper.userSummary(raw.user); + interest.role = raw.role; + interest.message = raw.message; + interest.createdAt = raw.createdAt; + return interest; + } + + static teamToDomain(raw: ProjectTeamEntity): ProjectTeam { + const members = (raw.members ?? []) + .map((m) => { + const member = new ProjectTeamMember(); + member.id = m.id; + member.userId = m.userId; + member.user = ProjectMapper.userSummary(m.user); + member.role = m.role; + member.createdAt = m.createdAt; + return member; + }) + .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime()); + + const vacancies = (raw.vacancies ?? []).map((v) => { + const vacancy = new ProjectTeamVacancy(); + vacancy.role = v.role; + vacancy.quantity = v.quantity; + vacancy.filled = members.filter((m) => m.role === v.role).length; + return vacancy; + }); + + const team = new ProjectTeam(); + team.id = raw.id; + team.ideaId = raw.ideaId; + team.ideaTitle = raw.idea?.title ?? raw.name; + team.name = raw.name; + team.description = raw.description; + team.status = raw.status; + team.repoUrl = raw.repoUrl; + team.ownerId = raw.ownerId; + team.owner = ProjectMapper.userSummary(raw.owner); + team.vacancies = vacancies; + team.members = members; + team.createdAt = raw.createdAt; + team.updatedAt = raw.updatedAt; + return team; + } +} diff --git a/src/project-teams/infrastructure/persistence/relational/relational-persistence.module.ts b/src/project-teams/infrastructure/persistence/relational/relational-persistence.module.ts new file mode 100644 index 0000000..4a4b07d --- /dev/null +++ b/src/project-teams/infrastructure/persistence/relational/relational-persistence.module.ts @@ -0,0 +1,35 @@ +import { Module } from '@nestjs/common'; +import { TypeOrmModule } from '@nestjs/typeorm'; +import { ProjectIdeaRepository } from '../project-idea.repository'; +import { ProjectTeamRepository } from '../project-team.repository'; +import { ProjectIdeaEntity } from './entities/project-idea.entity'; +import { ProjectIdeaInterestEntity } from './entities/project-idea-interest.entity'; +import { ProjectTeamEntity } from './entities/project-team.entity'; +import { ProjectTeamMemberEntity } from './entities/project-team-member.entity'; +import { ProjectTeamVacancyEntity } from './entities/project-team-vacancy.entity'; +import { ProjectIdeaRelationalRepository } from './repositories/project-idea.repository'; +import { ProjectTeamRelationalRepository } from './repositories/project-team.repository'; + +@Module({ + imports: [ + TypeOrmModule.forFeature([ + ProjectIdeaEntity, + ProjectIdeaInterestEntity, + ProjectTeamEntity, + ProjectTeamVacancyEntity, + ProjectTeamMemberEntity, + ]), + ], + providers: [ + { + provide: ProjectIdeaRepository, + useClass: ProjectIdeaRelationalRepository, + }, + { + provide: ProjectTeamRepository, + useClass: ProjectTeamRelationalRepository, + }, + ], + exports: [ProjectIdeaRepository, ProjectTeamRepository], +}) +export class RelationalProjectTeamsPersistenceModule {} 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 new file mode 100644 index 0000000..1824158 --- /dev/null +++ b/src/project-teams/infrastructure/persistence/relational/repositories/project-idea.repository.ts @@ -0,0 +1,187 @@ +import { Injectable } from '@nestjs/common'; +import { InjectRepository } from '@nestjs/typeorm'; +import { In, Repository } from 'typeorm'; +import { NullableType } from '../../../../../utils/types/nullable.type'; +import { IPaginationOptions } from '../../../../../utils/types/pagination-options'; +import { + ProjectIdea, + ProjectIdeaInterest, +} from '../../../../domain/project-idea'; +import { ProjectIdeaStatus } from '../../../../domain/project-idea-status.enum'; +import { ProjectRole } from '../../../../domain/project-role.enum'; +import { + ProjectIdeaRepository, + ProjectIdeaUpdate, +} from '../../project-idea.repository'; +import { ProjectIdeaEntity } from '../entities/project-idea.entity'; +import { ProjectIdeaInterestEntity } from '../entities/project-idea-interest.entity'; +import { ProjectTeamEntity } from '../entities/project-team.entity'; +import { ProjectMapper } from '../mappers/project.mapper'; + +const IDEA_RELATIONS = { author: { photo: true } }; + +@Injectable() +export class ProjectIdeaRelationalRepository implements ProjectIdeaRepository { + constructor( + @InjectRepository(ProjectIdeaEntity) + private readonly ideaRepository: Repository, + @InjectRepository(ProjectIdeaInterestEntity) + private readonly interestRepository: Repository, + @InjectRepository(ProjectTeamEntity) + private readonly teamRepository: Repository, + ) {} + + /** Anexa contagem de interessados e id do time a cada ideia. */ + private async enrich(entities: ProjectIdeaEntity[]): Promise { + if (entities.length === 0) { + return []; + } + const ids = entities.map((entity) => entity.id); + + const counts = await this.interestRepository + .createQueryBuilder('interest') + .select('interest.ideaId', 'ideaId') + .addSelect('COUNT(*)', 'count') + .where('interest.ideaId IN (:...ids)', { ids }) + .groupBy('interest.ideaId') + .getRawMany<{ ideaId: string; count: string }>(); + const countByIdea = new Map(counts.map((c) => [c.ideaId, Number(c.count)])); + + const teams = await this.teamRepository.find({ + where: { ideaId: In(ids) }, + select: { id: true, ideaId: true }, + }); + const teamByIdea = new Map(teams.map((t) => [t.ideaId, t.id])); + + return entities.map((entity) => + ProjectMapper.ideaToDomain(entity, { + interestCount: countByIdea.get(entity.id) ?? 0, + teamId: teamByIdea.get(entity.id) ?? null, + }), + ); + } + + private async findList( + where: Record, + order: Record, + paginationOptions: IPaginationOptions, + ): Promise { + const entities = await this.ideaRepository.find({ + where, + order, + relations: IDEA_RELATIONS, + skip: (paginationOptions.page - 1) * paginationOptions.limit, + take: paginationOptions.limit, + }); + return this.enrich(entities); + } + + async create(data: { + title: string; + description: string; + tags: string[]; + authorId: number; + }): Promise { + const saved = await this.ideaRepository.save( + this.ideaRepository.create({ + ...data, + status: ProjectIdeaStatus.PENDING, + }), + ); + return (await this.findById(saved.id)) as ProjectIdea; + } + + async findById(id: ProjectIdea['id']): Promise> { + const entity = await this.ideaRepository.findOne({ + where: { id }, + relations: IDEA_RELATIONS, + }); + if (!entity) { + return null; + } + const [idea] = await this.enrich([entity]); + return idea; + } + + findPublic(paginationOptions: IPaginationOptions): Promise { + return this.findList( + { + status: In([ProjectIdeaStatus.APPROVED, ProjectIdeaStatus.TEAM_FORMED]), + }, + { createdAt: 'DESC' }, + paginationOptions, + ); + } + + findByAuthorId( + authorId: number, + paginationOptions: IPaginationOptions, + ): Promise { + return this.findList( + { authorId }, + { createdAt: 'DESC' }, + paginationOptions, + ); + } + + findByStatus( + status: ProjectIdeaStatus, + paginationOptions: IPaginationOptions, + ): Promise { + return this.findList({ status }, { createdAt: 'ASC' }, paginationOptions); + } + + async update( + id: ProjectIdea['id'], + payload: ProjectIdeaUpdate, + ): Promise { + await this.ideaRepository.update(id, payload); + return this.findById(id); + } + + async remove(id: ProjectIdea['id']): Promise { + await this.ideaRepository.delete(id); + } + + async upsertInterest( + ideaId: ProjectIdea['id'], + userId: number, + role: ProjectRole, + message: string | null, + ): Promise { + const existing = await this.interestRepository.findOne({ + where: { ideaId, userId }, + }); + const saved = await this.interestRepository.save( + existing + ? Object.assign(existing, { role, message }) + : this.interestRepository.create({ ideaId, userId, role, message }), + ); + return ProjectMapper.interestToDomain(saved); + } + + async removeInterest(ideaId: ProjectIdea['id'], userId: number) { + await this.interestRepository.delete({ ideaId, userId }); + } + + async findInterest( + ideaId: ProjectIdea['id'], + userId: number, + ): Promise> { + const entity = await this.interestRepository.findOne({ + where: { ideaId, userId }, + }); + return entity ? ProjectMapper.interestToDomain(entity) : null; + } + + async findInterests( + ideaId: ProjectIdea['id'], + ): Promise { + const entities = await this.interestRepository.find({ + where: { ideaId }, + relations: { user: { photo: true } }, + order: { createdAt: 'ASC' }, + }); + return entities.map((entity) => ProjectMapper.interestToDomain(entity)); + } +} diff --git a/src/project-teams/infrastructure/persistence/relational/repositories/project-team.repository.ts b/src/project-teams/infrastructure/persistence/relational/repositories/project-team.repository.ts new file mode 100644 index 0000000..26a067d --- /dev/null +++ b/src/project-teams/infrastructure/persistence/relational/repositories/project-team.repository.ts @@ -0,0 +1,186 @@ +import { Injectable } from '@nestjs/common'; +import { InjectRepository } from '@nestjs/typeorm'; +import { In, Repository } from 'typeorm'; +import { NullableType } from '../../../../../utils/types/nullable.type'; +import { IPaginationOptions } from '../../../../../utils/types/pagination-options'; +import { ProjectIdeaStatus } from '../../../../domain/project-idea-status.enum'; +import { ProjectTeam } from '../../../../domain/project-team'; +import { ProjectTeamStatus } from '../../../../domain/project-team-status.enum'; +import { + ProjectTeamMemberInput, + ProjectTeamRepository, + ProjectTeamUpdate, + ProjectTeamVacancyInput, +} from '../../project-team.repository'; +import { ProjectIdeaEntity } from '../entities/project-idea.entity'; +import { ProjectTeamEntity } from '../entities/project-team.entity'; +import { ProjectTeamMemberEntity } from '../entities/project-team-member.entity'; +import { ProjectTeamVacancyEntity } from '../entities/project-team-vacancy.entity'; +import { ProjectMapper } from '../mappers/project.mapper'; + +const TEAM_RELATIONS = { + idea: true, + owner: { photo: true }, + vacancies: true, + members: { user: { photo: true } }, +}; + +@Injectable() +export class ProjectTeamRelationalRepository implements ProjectTeamRepository { + constructor( + @InjectRepository(ProjectTeamEntity) + private readonly teamRepository: Repository, + @InjectRepository(ProjectTeamVacancyEntity) + private readonly vacancyRepository: Repository, + @InjectRepository(ProjectTeamMemberEntity) + private readonly memberRepository: Repository, + ) {} + + async create(data: { + ideaId: string; + name: string; + description: string | null; + repoUrl: string | null; + ownerId: number; + vacancies: ProjectTeamVacancyInput[]; + members: ProjectTeamMemberInput[]; + }): Promise { + const teamId = await this.teamRepository.manager.transaction( + async (manager) => { + const team = await manager.save( + manager.create(ProjectTeamEntity, { + ideaId: data.ideaId, + name: data.name, + description: data.description, + repoUrl: data.repoUrl, + ownerId: data.ownerId, + status: ProjectTeamStatus.RECRUITING, + }), + ); + await manager.save( + data.vacancies.map((vacancy) => + manager.create(ProjectTeamVacancyEntity, { + teamId: team.id, + ...vacancy, + }), + ), + ); + if (data.members.length > 0) { + await manager.save( + data.members.map((member) => + manager.create(ProjectTeamMemberEntity, { + teamId: team.id, + ...member, + }), + ), + ); + } + await manager.update(ProjectIdeaEntity, data.ideaId, { + status: ProjectIdeaStatus.TEAM_FORMED, + }); + return team.id; + }, + ); + return (await this.findById(teamId)) as ProjectTeam; + } + + async findById(id: ProjectTeam['id']): Promise> { + const entity = await this.teamRepository.findOne({ + where: { id }, + relations: TEAM_RELATIONS, + }); + return entity ? ProjectMapper.teamToDomain(entity) : null; + } + + async findByIdeaId(ideaId: string): Promise> { + const entity = await this.teamRepository.findOne({ + where: { ideaId }, + relations: TEAM_RELATIONS, + }); + return entity ? ProjectMapper.teamToDomain(entity) : null; + } + + private async loadInOrder(ids: string[]): Promise { + if (ids.length === 0) { + return []; + } + const entities = await this.teamRepository.find({ + where: { id: In(ids) }, + relations: TEAM_RELATIONS, + }); + const byId = new Map(entities.map((entity) => [entity.id, entity])); + return ids + .map((id) => byId.get(id)) + .filter((entity): entity is ProjectTeamEntity => !!entity) + .map((entity) => ProjectMapper.teamToDomain(entity)); + } + + async findPublic( + paginationOptions: IPaginationOptions, + status?: ProjectTeamStatus, + ): Promise { + const rows = await this.teamRepository.find({ + where: status ? { status } : {}, + order: { createdAt: 'DESC' }, + select: { id: true }, + skip: (paginationOptions.page - 1) * paginationOptions.limit, + take: paginationOptions.limit, + }); + return this.loadInOrder(rows.map((row) => row.id)); + } + + async findByUserId( + userId: number, + paginationOptions: IPaginationOptions, + ): Promise { + // Filtro feito numa query separada: um `where` em `members` no find + // principal descartaria os demais membros do resultado carregado. + const rows = await this.teamRepository + .createQueryBuilder('team') + .leftJoin('team.members', 'member') + .where('team.ownerId = :userId OR member.userId = :userId', { userId }) + .select(['team.id', 'team.createdAt']) + .orderBy('team.createdAt', 'DESC') + .skip((paginationOptions.page - 1) * paginationOptions.limit) + .take(paginationOptions.limit) + .getMany(); + return this.loadInOrder(rows.map((row) => row.id)); + } + + async update( + id: ProjectTeam['id'], + payload: ProjectTeamUpdate, + ): Promise { + if (Object.keys(payload).length > 0) { + await this.teamRepository.update(id, payload); + } + return this.findById(id); + } + + async replaceVacancies( + id: ProjectTeam['id'], + vacancies: ProjectTeamVacancyInput[], + ): Promise { + await this.vacancyRepository.manager.transaction(async (manager) => { + await manager.delete(ProjectTeamVacancyEntity, { teamId: id }); + await manager.save( + vacancies.map((vacancy) => + manager.create(ProjectTeamVacancyEntity, { teamId: id, ...vacancy }), + ), + ); + }); + } + + async addMember( + id: ProjectTeam['id'], + member: ProjectTeamMemberInput, + ): Promise { + await this.memberRepository.save( + this.memberRepository.create({ teamId: id, ...member }), + ); + } + + async removeMember(id: ProjectTeam['id'], userId: number): Promise { + await this.memberRepository.delete({ teamId: id, userId }); + } +} diff --git a/src/project-teams/project-ideas.controller.ts b/src/project-teams/project-ideas.controller.ts new file mode 100644 index 0000000..188a3cb --- /dev/null +++ b/src/project-teams/project-ideas.controller.ts @@ -0,0 +1,231 @@ +import { + Body, + Controller, + Delete, + Get, + HttpCode, + HttpStatus, + Param, + ParseUUIDPipe, + Patch, + Post, + Put, + Query, + Request, + UseGuards, +} from '@nestjs/common'; +import { AuthGuard } from '@nestjs/passport'; +import { + ApiBearerAuth, + ApiCreatedResponse, + ApiOkResponse, + ApiParam, + ApiTags, +} from '@nestjs/swagger'; +import { Roles } from '../roles/roles.decorator'; +import { RoleEnum } from '../roles/roles.enum'; +import { RolesGuard } from '../roles/roles.guard'; +import { + InfinityPaginationResponse, + InfinityPaginationResponseDto, +} from '../utils/dto/infinity-pagination-response.dto'; +import { infinityPagination } from '../utils/infinity-pagination'; +import { + ProjectIdea, + ProjectIdeaInterest, + SuggestedVacancy, +} from './domain/project-idea'; +import { CreateProjectIdeaDto } from './dto/create-project-idea.dto'; +import { FindProjectsDto } from './dto/find-projects.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 { ProjectIdeasService } from './project-ideas.service'; + +function canManageAny(req): boolean { + const roleId = Number(req.user?.role?.id); + return roleId === RoleEnum.admin || roleId === RoleEnum.moderator; +} + +function pagination(query: FindProjectsDto) { + const page = query?.page ?? 1; + const limit = Math.min(query?.limit ?? 10, 50); + return { page, limit }; +} + +@ApiTags('Project ideas') +@Controller({ path: 'project-ideas', version: '1' }) +export class ProjectIdeasController { + constructor(private readonly ideasService: ProjectIdeasService) {} + + @Post() + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @ApiCreatedResponse({ type: ProjectIdea }) + create(@Body() dto: CreateProjectIdeaDto, @Request() req) { + return this.ideasService.create(dto, req.user.id); + } + + @Get() + @ApiOkResponse({ + type: InfinityPaginationResponse(ProjectIdea), + description: 'Ideias aprovadas, abertas a interessados.', + }) + async findAll( + @Query() query: FindProjectsDto, + ): Promise> { + const options = pagination(query); + return infinityPagination( + await this.ideasService.findPublic(options), + options, + ); + } + + @Get('mine') + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @ApiOkResponse({ type: InfinityPaginationResponse(ProjectIdea) }) + async findMine( + @Query() query: FindProjectsDto, + @Request() req, + ): Promise> { + const options = pagination(query); + return infinityPagination( + await this.ideasService.findMine(req.user.id, options), + options, + ); + } + + @Get('pending') + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt'), RolesGuard) + @Roles(RoleEnum.admin, RoleEnum.moderator) + @ApiOkResponse({ type: InfinityPaginationResponse(ProjectIdea) }) + async findPending( + @Query() query: FindProjectsDto, + ): Promise> { + const options = pagination(query); + return infinityPagination( + await this.ideasService.findPending(options), + options, + ); + } + + @Get(':id') + @ApiParam({ name: 'id', type: String, required: true }) + @ApiOkResponse({ type: ProjectIdea }) + findById(@Param('id', ParseUUIDPipe) id: string) { + return this.ideasService.findPublicDetail(id); + } + + @Get(':id/manage') + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @ApiParam({ name: 'id', type: String, required: true }) + @ApiOkResponse({ + type: ProjectIdea, + description: 'Detalhe em qualquer status, só para o autor ou moderação.', + }) + findForManagement(@Param('id', ParseUUIDPipe) id: string, @Request() req) { + return this.ideasService.findForManagement( + id, + req.user.id, + canManageAny(req), + ); + } + + @Patch(':id/review') + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt'), RolesGuard) + @Roles(RoleEnum.admin, RoleEnum.moderator) + @ApiParam({ name: 'id', type: String, required: true }) + @ApiOkResponse({ type: ProjectIdea }) + review( + @Param('id', ParseUUIDPipe) id: string, + @Body() dto: ReviewProjectIdeaDto, + @Request() req, + ) { + return this.ideasService.review(id, dto, req.user.id); + } + + @Patch(':id') + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @ApiParam({ name: 'id', type: String, required: true }) + @ApiOkResponse({ type: ProjectIdea }) + update( + @Param('id', ParseUUIDPipe) id: string, + @Body() dto: UpdateProjectIdeaDto, + @Request() req, + ) { + return this.ideasService.update(id, dto, req.user.id, canManageAny(req)); + } + + @Delete(':id') + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @HttpCode(HttpStatus.NO_CONTENT) + @ApiParam({ name: 'id', type: String, required: true }) + remove(@Param('id', ParseUUIDPipe) id: string, @Request() req) { + return this.ideasService.remove(id, req.user.id, canManageAny(req)); + } + + @Put(':id/interest') + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @ApiParam({ name: 'id', type: String, required: true }) + @ApiOkResponse({ type: ProjectIdeaInterest }) + setInterest( + @Param('id', ParseUUIDPipe) id: string, + @Body() dto: SetProjectInterestDto, + @Request() req, + ) { + return this.ideasService.setInterest(id, req.user.id, dto); + } + + @Delete(':id/interest') + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @HttpCode(HttpStatus.NO_CONTENT) + @ApiParam({ name: 'id', type: String, required: true }) + removeInterest(@Param('id', ParseUUIDPipe) id: string, @Request() req) { + return this.ideasService.removeInterest(id, req.user.id); + } + + @Get(':id/interest') + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @ApiParam({ name: 'id', type: String, required: true }) + getMyInterest(@Param('id', ParseUUIDPipe) id: string, @Request() req) { + return this.ideasService.getMyInterest(id, req.user.id); + } + + @Get(':id/interests') + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @ApiParam({ name: 'id', type: String, required: true }) + @ApiOkResponse({ + type: [ProjectIdeaInterest], + description: 'Lista de interessados, visível ao autor da ideia.', + }) + listInterests(@Param('id', ParseUUIDPipe) id: string, @Request() req) { + return this.ideasService.listInterests(id, req.user.id, canManageAny(req)); + } + + @Get(':id/suggested-vacancies') + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @ApiParam({ name: 'id', type: String, required: true }) + @ApiOkResponse({ + type: [SuggestedVacancy], + description: + 'Vagas sugeridas para o time com base no interesse e no texto da ideia.', + }) + suggestedVacancies(@Param('id', ParseUUIDPipe) id: string, @Request() req) { + return this.ideasService.suggestVacancies( + id, + req.user.id, + canManageAny(req), + ); + } +} diff --git a/src/project-teams/project-ideas.service.ts b/src/project-teams/project-ideas.service.ts new file mode 100644 index 0000000..748e4da --- /dev/null +++ b/src/project-teams/project-ideas.service.ts @@ -0,0 +1,300 @@ +import { + BadRequestException, + ForbiddenException, + HttpStatus, + Injectable, + NotFoundException, + UnprocessableEntityException, +} from '@nestjs/common'; +import { NotificationType } from '../notifications/domain/notification-type.enum'; +import { NotificationsService } from '../notifications/notifications.service'; +import { IPaginationOptions } from '../utils/types/pagination-options'; +import { ProjectIdea, SuggestedVacancy } from './domain/project-idea'; +import { ProjectIdeaStatus } from './domain/project-idea-status.enum'; +import { ProjectRole } from './domain/project-role.enum'; +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 { suggestVacancies } from './vacancy-suggestions'; + +const PUBLIC_STATUSES = [ + ProjectIdeaStatus.APPROVED, + ProjectIdeaStatus.TEAM_FORMED, +]; + +@Injectable() +export class ProjectIdeasService { + constructor( + private readonly ideaRepository: ProjectIdeaRepository, + private readonly notificationsService: NotificationsService, + ) {} + + private async getOrFail(id: ProjectIdea['id']): Promise { + const idea = await this.ideaRepository.findById(id); + if (!idea) { + throw new NotFoundException('Ideia não encontrada.'); + } + return idea; + } + + private assertAuthorOrAdmin( + idea: ProjectIdea, + userId: number, + canManageAny: boolean, + message: string, + ) { + if (idea.authorId !== userId && !canManageAny) { + throw new ForbiddenException(message); + } + } + + create(dto: CreateProjectIdeaDto, authorId: number) { + return this.ideaRepository.create({ + title: dto.title, + description: dto.description, + tags: dto.tags ?? [], + authorId, + }); + } + + findPublic(paginationOptions: IPaginationOptions) { + return this.ideaRepository.findPublic(paginationOptions); + } + + findMine(authorId: number, paginationOptions: IPaginationOptions) { + return this.ideaRepository.findByAuthorId(authorId, paginationOptions); + } + + findPending(paginationOptions: IPaginationOptions) { + return this.ideaRepository.findByStatus( + ProjectIdeaStatus.PENDING, + paginationOptions, + ); + } + + async findPublicDetail(id: ProjectIdea['id']): Promise { + const idea = await this.getOrFail(id); + if (!PUBLIC_STATUSES.includes(idea.status)) { + throw new NotFoundException('Ideia não encontrada.'); + } + return idea; + } + + async findForManagement( + id: ProjectIdea['id'], + userId: number, + canManageAny: boolean, + ): Promise { + const idea = await this.getOrFail(id); + this.assertAuthorOrAdmin( + idea, + userId, + canManageAny, + 'Você não tem permissão para visualizar esta ideia.', + ); + return idea; + } + + async update( + id: ProjectIdea['id'], + dto: UpdateProjectIdeaDto, + userId: number, + canManageAny: boolean, + ) { + const idea = await this.getOrFail(id); + this.assertAuthorOrAdmin( + idea, + userId, + canManageAny, + 'Você não tem permissão para editar esta ideia.', + ); + if ( + !canManageAny && + idea.status !== ProjectIdeaStatus.PENDING && + idea.status !== ProjectIdeaStatus.REJECTED + ) { + throw new UnprocessableEntityException({ + status: HttpStatus.UNPROCESSABLE_ENTITY, + errors: { + status: 'Só é possível editar ideias pendentes ou rejeitadas.', + }, + }); + } + + return this.ideaRepository.update(id, { + ...(dto.title !== undefined && { title: dto.title }), + ...(dto.description !== undefined && { description: dto.description }), + ...(dto.tags !== undefined && { tags: dto.tags }), + // Autor que corrige uma ideia rejeitada reenvia para nova revisão. + ...(!canManageAny && + idea.status === ProjectIdeaStatus.REJECTED && { + status: ProjectIdeaStatus.PENDING, + rejectionReason: null, + reviewerId: null, + reviewedAt: null, + }), + }); + } + + async review( + id: ProjectIdea['id'], + dto: ReviewProjectIdeaDto, + reviewerId: number, + ) { + const idea = await this.getOrFail(id); + if (idea.status !== ProjectIdeaStatus.PENDING) { + throw new UnprocessableEntityException({ + status: HttpStatus.UNPROCESSABLE_ENTITY, + errors: { status: 'Apenas ideias pendentes podem ser revisadas.' }, + }); + } + const rejecting = dto.status === ProjectIdeaStatus.REJECTED; + if (rejecting && !dto.rejectionReason?.trim()) { + throw new UnprocessableEntityException({ + status: HttpStatus.UNPROCESSABLE_ENTITY, + errors: { + rejectionReason: 'Informe o motivo da rejeição.', + }, + }); + } + + const updated = await this.ideaRepository.update(id, { + status: dto.status, + rejectionReason: rejecting ? dto.rejectionReason!.trim() : null, + reviewerId, + reviewedAt: new Date(), + }); + + await this.notificationsService + .create({ + userId: idea.authorId, + type: rejecting + ? NotificationType.PROJECT_IDEA_REJECTED + : NotificationType.PROJECT_IDEA_APPROVED, + title: rejecting + ? `Ideia rejeitada: ${idea.title}` + : `Ideia aprovada: ${idea.title}`, + body: rejecting + ? `Motivo: ${dto.rejectionReason!.trim()}` + : 'Sua ideia já está visível. Acompanhe os interessados e monte o time!', + relatedId: idea.id, + link: `/projetos/${idea.id}`, + payload: { ideaId: idea.id }, + }) + .catch(() => undefined); + + return updated; + } + + async remove(id: ProjectIdea['id'], userId: number, canManageAny: boolean) { + const idea = await this.getOrFail(id); + this.assertAuthorOrAdmin( + idea, + userId, + canManageAny, + 'Você não tem permissão para excluir esta ideia.', + ); + if (idea.status === ProjectIdeaStatus.TEAM_FORMED && !canManageAny) { + throw new UnprocessableEntityException({ + status: HttpStatus.UNPROCESSABLE_ENTITY, + errors: { + status: 'Ideias com time formado não podem ser excluídas.', + }, + }); + } + await this.ideaRepository.remove(id); + } + + async setInterest( + id: ProjectIdea['id'], + userId: number, + dto: SetProjectInterestDto, + ) { + const idea = await this.findPublicDetail(id); + if (idea.authorId === userId) { + throw new BadRequestException( + 'Você é o autor da ideia — monte o time pela página dela.', + ); + } + + const existing = await this.ideaRepository.findInterest(id, userId); + const interest = await this.ideaRepository.upsertInterest( + id, + userId, + dto.role, + dto.message?.trim() || null, + ); + + if (!existing) { + await this.notificationsService + .create({ + userId: idea.authorId, + type: NotificationType.PROJECT_IDEA_INTEREST, + title: `Novo interessado em: ${idea.title}`, + body: 'Alguém quer participar do seu projeto. Veja a lista de interessados.', + relatedId: idea.id, + link: `/projetos/${idea.id}`, + payload: { ideaId: idea.id, userId }, + }) + .catch(() => undefined); + } + + return interest; + } + + async removeInterest(id: ProjectIdea['id'], userId: number) { + await this.findPublicDetail(id); + await this.ideaRepository.removeInterest(id, userId); + } + + async getMyInterest(id: ProjectIdea['id'], userId: number) { + const interest = await this.ideaRepository.findInterest(id, userId); + return { + interested: !!interest, + role: interest?.role ?? null, + message: interest?.message ?? null, + }; + } + + async listInterests( + id: ProjectIdea['id'], + userId: number, + canManageAny: boolean, + ) { + const idea = await this.getOrFail(id); + this.assertAuthorOrAdmin( + idea, + userId, + canManageAny, + 'Apenas o autor da ideia pode ver os interessados.', + ); + return this.ideaRepository.findInterests(id); + } + + async suggestVacancies( + id: ProjectIdea['id'], + userId: number, + canManageAny: boolean, + ): Promise { + const idea = await this.getOrFail(id); + this.assertAuthorOrAdmin( + idea, + userId, + canManageAny, + 'Apenas o autor da ideia pode ver as sugestões de vagas.', + ); + + const interests = await this.ideaRepository.findInterests(id); + const interestByRole: Partial> = {}; + for (const interest of interests) { + interestByRole[interest.role] = (interestByRole[interest.role] ?? 0) + 1; + } + + return suggestVacancies({ + text: [idea.title, idea.description, ...idea.tags].join(' '), + interestByRole, + }); + } +} diff --git a/src/project-teams/project-teams.controller.ts b/src/project-teams/project-teams.controller.ts new file mode 100644 index 0000000..2114121 --- /dev/null +++ b/src/project-teams/project-teams.controller.ts @@ -0,0 +1,143 @@ +import { + Body, + Controller, + Delete, + Get, + HttpCode, + HttpStatus, + Param, + ParseIntPipe, + ParseUUIDPipe, + Patch, + Post, + Query, + Request, + UseGuards, +} from '@nestjs/common'; +import { AuthGuard } from '@nestjs/passport'; +import { + ApiBearerAuth, + ApiCreatedResponse, + ApiOkResponse, + ApiParam, + ApiTags, +} from '@nestjs/swagger'; +import { RoleEnum } from '../roles/roles.enum'; +import { + InfinityPaginationResponse, + InfinityPaginationResponseDto, +} from '../utils/dto/infinity-pagination-response.dto'; +import { infinityPagination } from '../utils/infinity-pagination'; +import { ProjectTeam } from './domain/project-team'; +import { AddProjectTeamMemberDto } from './dto/add-project-team-member.dto'; +import { CreateProjectTeamDto } from './dto/create-project-team.dto'; +import { FindProjectsDto } from './dto/find-projects.dto'; +import { UpdateProjectTeamDto } from './dto/update-project-team.dto'; +import { ProjectTeamsService } from './project-teams.service'; + +function canManageAny(req): boolean { + const roleId = Number(req.user?.role?.id); + return roleId === RoleEnum.admin || roleId === RoleEnum.moderator; +} + +function pagination(query: FindProjectsDto) { + const page = query?.page ?? 1; + const limit = Math.min(query?.limit ?? 10, 50); + return { page, limit }; +} + +@ApiTags('Project teams') +@Controller({ path: 'project-teams', version: '1' }) +export class ProjectTeamsController { + constructor(private readonly teamsService: ProjectTeamsService) {} + + @Post() + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @ApiCreatedResponse({ type: ProjectTeam }) + create(@Body() dto: CreateProjectTeamDto, @Request() req) { + return this.teamsService.create(dto, req.user.id); + } + + @Get() + @ApiOkResponse({ type: InfinityPaginationResponse(ProjectTeam) }) + async findAll( + @Query() query: FindProjectsDto, + ): Promise> { + const options = pagination(query); + return infinityPagination( + await this.teamsService.findPublic(options, query?.status), + options, + ); + } + + @Get('mine') + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @ApiOkResponse({ + type: InfinityPaginationResponse(ProjectTeam), + description: 'Times em que o usuário é dono ou membro.', + }) + async findMine( + @Query() query: FindProjectsDto, + @Request() req, + ): Promise> { + const options = pagination(query); + return infinityPagination( + await this.teamsService.findMine(req.user.id, options), + options, + ); + } + + @Get(':id') + @ApiParam({ name: 'id', type: String, required: true }) + @ApiOkResponse({ type: ProjectTeam }) + findById(@Param('id', ParseUUIDPipe) id: string) { + return this.teamsService.findById(id); + } + + @Patch(':id') + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @ApiParam({ name: 'id', type: String, required: true }) + @ApiOkResponse({ type: ProjectTeam }) + update( + @Param('id', ParseUUIDPipe) id: string, + @Body() dto: UpdateProjectTeamDto, + @Request() req, + ) { + return this.teamsService.update(id, dto, req.user.id, canManageAny(req)); + } + + @Post(':id/members') + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @ApiParam({ name: 'id', type: String, required: true }) + @ApiCreatedResponse({ type: ProjectTeam }) + addMember( + @Param('id', ParseUUIDPipe) id: string, + @Body() dto: AddProjectTeamMemberDto, + @Request() req, + ) { + return this.teamsService.addMember(id, dto, req.user.id, canManageAny(req)); + } + + @Delete(':id/members/:userId') + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @HttpCode(HttpStatus.NO_CONTENT) + @ApiParam({ name: 'id', type: String, required: true }) + @ApiParam({ name: 'userId', type: Number, required: true }) + removeMember( + @Param('id', ParseUUIDPipe) id: string, + @Param('userId', ParseIntPipe) userId: number, + @Request() req, + ) { + return this.teamsService.removeMember( + id, + userId, + req.user.id, + canManageAny(req), + ); + } +} diff --git a/src/project-teams/project-teams.module.ts b/src/project-teams/project-teams.module.ts new file mode 100644 index 0000000..12646a1 --- /dev/null +++ b/src/project-teams/project-teams.module.ts @@ -0,0 +1,15 @@ +import { Module } from '@nestjs/common'; +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 { ProjectTeamsController } from './project-teams.controller'; +import { ProjectTeamsService } from './project-teams.service'; + +@Module({ + imports: [RelationalProjectTeamsPersistenceModule, NotificationsModule], + controllers: [ProjectIdeasController, ProjectTeamsController], + providers: [ProjectIdeasService, ProjectTeamsService], + exports: [ProjectIdeasService, ProjectTeamsService], +}) +export class ProjectTeamsModule {} diff --git a/src/project-teams/project-teams.service.ts b/src/project-teams/project-teams.service.ts new file mode 100644 index 0000000..e5e9b79 --- /dev/null +++ b/src/project-teams/project-teams.service.ts @@ -0,0 +1,286 @@ +import { + ForbiddenException, + HttpStatus, + Injectable, + NotFoundException, + UnprocessableEntityException, +} from '@nestjs/common'; +import { NotificationType } from '../notifications/domain/notification-type.enum'; +import { NotificationsService } from '../notifications/notifications.service'; +import { IPaginationOptions } from '../utils/types/pagination-options'; +import { ProjectIdeaStatus } from './domain/project-idea-status.enum'; +import { ProjectRole } from './domain/project-role.enum'; +import { ProjectTeam } from './domain/project-team'; +import { ProjectTeamStatus } from './domain/project-team-status.enum'; +import { AddProjectTeamMemberDto } from './dto/add-project-team-member.dto'; +import { CreateProjectTeamDto } from './dto/create-project-team.dto'; +import { UpdateProjectTeamDto } from './dto/update-project-team.dto'; +import { ProjectIdeaRepository } from './infrastructure/persistence/project-idea.repository'; +import { + ProjectTeamMemberInput, + ProjectTeamRepository, + ProjectTeamVacancyInput, +} from './infrastructure/persistence/project-team.repository'; + +const CLOSED_STATUSES = [ + ProjectTeamStatus.COMPLETED, + ProjectTeamStatus.CANCELLED, +]; + +function unprocessable(field: string, message: string) { + return new UnprocessableEntityException({ + status: HttpStatus.UNPROCESSABLE_ENTITY, + errors: { [field]: message }, + }); +} + +@Injectable() +export class ProjectTeamsService { + constructor( + private readonly teamRepository: ProjectTeamRepository, + private readonly ideaRepository: ProjectIdeaRepository, + private readonly notificationsService: NotificationsService, + ) {} + + private async getOrFail(id: ProjectTeam['id']): Promise { + const team = await this.teamRepository.findById(id); + if (!team) { + throw new NotFoundException('Time não encontrado.'); + } + return team; + } + + private assertOwnerOrAdmin( + team: ProjectTeam, + userId: number, + canManageAny: boolean, + message: string, + ) { + if (team.ownerId !== userId && !canManageAny) { + throw new ForbiddenException(message); + } + } + + private assertUniqueRoles(vacancies: ProjectTeamVacancyInput[]) { + const roles = vacancies.map((vacancy) => vacancy.role); + if (new Set(roles).size !== roles.length) { + throw unprocessable('vacancies', 'Cada cargo só pode aparecer uma vez.'); + } + } + + /** Garante que há vaga livre no cargo para mais uma pessoa. */ + private assertHasOpenVacancy( + vacancies: ProjectTeamVacancyInput[], + members: ProjectTeamMemberInput[], + role: ProjectRole, + ) { + const vacancy = vacancies.find((v) => v.role === role); + if (!vacancy) { + throw unprocessable('role', 'O time não tem vagas para este cargo.'); + } + const filled = members.filter((m) => m.role === role).length; + if (filled >= vacancy.quantity) { + throw unprocessable( + 'role', + 'Todas as vagas deste cargo já foram preenchidas.', + ); + } + } + + private async assertInterested(ideaId: string, userId: number) { + const interest = await this.ideaRepository.findInterest(ideaId, userId); + if (!interest) { + throw unprocessable( + 'userId', + 'Só é possível adicionar quem demonstrou interesse na ideia.', + ); + } + } + + private async notifyAdded( + team: ProjectTeam, + members: ProjectTeamMemberInput[], + ) { + await Promise.allSettled( + members.map((member) => + this.notificationsService.create({ + userId: member.userId, + type: NotificationType.PROJECT_TEAM_MEMBER_ADDED, + title: `Você entrou no time: ${team.name}`, + body: `Projeto "${team.ideaTitle}".`, + relatedId: team.id, + link: `/projetos/times/${team.id}`, + payload: { teamId: team.id }, + }), + ), + ); + } + + async create( + dto: CreateProjectTeamDto, + userId: number, + ): Promise { + const idea = await this.ideaRepository.findById(dto.ideaId); + if (!idea) { + throw new NotFoundException('Ideia não encontrada.'); + } + if (idea.authorId !== userId) { + throw new ForbiddenException( + 'Apenas o autor da ideia pode montar o time.', + ); + } + if (idea.status === ProjectIdeaStatus.TEAM_FORMED) { + throw unprocessable('ideaId', 'Esta ideia já tem um time formado.'); + } + if (idea.status !== ProjectIdeaStatus.APPROVED) { + throw unprocessable( + 'ideaId', + 'A ideia precisa estar aprovada para montar um time.', + ); + } + + const vacancies = dto.vacancies.map(({ role, quantity }) => ({ + role, + quantity, + })); + this.assertUniqueRoles(vacancies); + + const members: ProjectTeamMemberInput[] = []; + for (const member of dto.members ?? []) { + if (member.userId === userId) { + throw unprocessable('members', 'O autor já é o dono do time.'); + } + if (members.some((m) => m.userId === member.userId)) { + throw unprocessable('members', 'Pessoa repetida na lista de membros.'); + } + await this.assertInterested(idea.id, member.userId); + this.assertHasOpenVacancy(vacancies, members, member.role); + members.push({ userId: member.userId, role: member.role }); + } + + const team = await this.teamRepository.create({ + ideaId: idea.id, + name: dto.name, + description: dto.description?.trim() || null, + repoUrl: dto.repoUrl ?? null, + ownerId: userId, + vacancies, + members, + }); + await this.notifyAdded(team, members); + return team; + } + + findPublic( + paginationOptions: IPaginationOptions, + status?: ProjectTeamStatus, + ) { + return this.teamRepository.findPublic(paginationOptions, status); + } + + findMine(userId: number, paginationOptions: IPaginationOptions) { + return this.teamRepository.findByUserId(userId, paginationOptions); + } + + findById(id: ProjectTeam['id']) { + return this.getOrFail(id); + } + + async update( + id: ProjectTeam['id'], + dto: UpdateProjectTeamDto, + userId: number, + canManageAny: boolean, + ) { + const team = await this.getOrFail(id); + this.assertOwnerOrAdmin( + team, + userId, + canManageAny, + 'Você não tem permissão para editar este time.', + ); + + if (dto.vacancies) { + const vacancies = dto.vacancies.map(({ role, quantity }) => ({ + role, + quantity, + })); + this.assertUniqueRoles(vacancies); + for (const role of new Set(team.members.map((m) => m.role))) { + const filled = team.members.filter((m) => m.role === role).length; + const vacancy = vacancies.find((v) => v.role === role); + if (!vacancy || vacancy.quantity < filled) { + throw unprocessable( + 'vacancies', + 'Não é possível reduzir as vagas abaixo do número de membros do cargo.', + ); + } + } + await this.teamRepository.replaceVacancies(id, vacancies); + } + + return this.teamRepository.update(id, { + ...(dto.name !== undefined && { name: dto.name }), + ...(dto.description !== undefined && { + description: dto.description?.trim() || null, + }), + ...(dto.repoUrl !== undefined && { repoUrl: dto.repoUrl }), + ...(dto.status !== undefined && { status: dto.status }), + }); + } + + async addMember( + id: ProjectTeam['id'], + dto: AddProjectTeamMemberDto, + userId: number, + canManageAny: boolean, + ) { + const team = await this.getOrFail(id); + this.assertOwnerOrAdmin( + team, + userId, + canManageAny, + 'Apenas o dono do time pode adicionar membros.', + ); + if (CLOSED_STATUSES.includes(team.status)) { + throw unprocessable('status', 'Este time não está mais montando equipe.'); + } + if (dto.userId === team.ownerId) { + throw unprocessable('userId', 'O dono já faz parte do time.'); + } + if (team.members.some((m) => m.userId === dto.userId)) { + throw unprocessable('userId', 'Esta pessoa já está no time.'); + } + await this.assertInterested(team.ideaId, dto.userId); + this.assertHasOpenVacancy( + team.vacancies, + team.members.map((m) => ({ userId: m.userId, role: m.role })), + dto.role, + ); + + await this.teamRepository.addMember(id, { + userId: dto.userId, + role: dto.role, + }); + await this.notifyAdded(team, [{ userId: dto.userId, role: dto.role }]); + return this.getOrFail(id); + } + + async removeMember( + id: ProjectTeam['id'], + memberUserId: number, + actorId: number, + canManageAny: boolean, + ) { + const team = await this.getOrFail(id); + if (memberUserId !== actorId && team.ownerId !== actorId && !canManageAny) { + throw new ForbiddenException( + 'Você não tem permissão para remover este membro.', + ); + } + if (!team.members.some((m) => m.userId === memberUserId)) { + throw new NotFoundException('Membro não encontrado neste time.'); + } + await this.teamRepository.removeMember(id, memberUserId); + } +} diff --git a/src/project-teams/vacancy-suggestions.spec.ts b/src/project-teams/vacancy-suggestions.spec.ts new file mode 100644 index 0000000..3f11ee1 --- /dev/null +++ b/src/project-teams/vacancy-suggestions.spec.ts @@ -0,0 +1,54 @@ +import { ProjectRole } from './domain/project-role.enum'; +import { suggestVacancies } from './vacancy-suggestions'; + +const quantityOf = ( + suggestions: ReturnType, + role: ProjectRole, +) => suggestions.find((s) => s.role === role)?.quantity ?? 0; + +describe('suggestVacancies', () => { + it('should sugerir ao menos os cargos essenciais mesmo sem interessados', () => { + const result = suggestVacancies({ + text: 'um site simples', + interestByRole: {}, + }); + + expect(quantityOf(result, ProjectRole.FRONTEND)).toBe(1); + expect(quantityOf(result, ProjectRole.BACKEND)).toBe(1); + expect(quantityOf(result, ProjectRole.REQUIREMENTS_ANALYST)).toBe(1); + expect(quantityOf(result, ProjectRole.DATABASE)).toBe(0); + }); + + it('should usar o número de interessados, respeitando o teto do cargo', () => { + const result = suggestVacancies({ + text: '', + interestByRole: { + [ProjectRole.FRONTEND]: 2, + [ProjectRole.BACKEND]: 9, + }, + }); + + expect(quantityOf(result, ProjectRole.FRONTEND)).toBe(2); + expect(quantityOf(result, ProjectRole.BACKEND)).toBe(3); + }); + + it('should incluir cargos que só têm interessados', () => { + const result = suggestVacancies({ + text: '', + interestByRole: { [ProjectRole.QA]: 1 }, + }); + + expect(quantityOf(result, ProjectRole.QA)).toBe(1); + }); + + it('should adicionar cargos a partir de palavras-chave da ideia', () => { + const result = suggestVacancies({ + text: 'Aplicativo mobile com banco de dados e deploy em docker', + interestByRole: {}, + }); + + expect(quantityOf(result, ProjectRole.MOBILE)).toBe(1); + expect(quantityOf(result, ProjectRole.DATABASE)).toBe(1); + expect(quantityOf(result, ProjectRole.DEVOPS)).toBe(1); + }); +}); diff --git a/src/project-teams/vacancy-suggestions.ts b/src/project-teams/vacancy-suggestions.ts new file mode 100644 index 0000000..17d2140 --- /dev/null +++ b/src/project-teams/vacancy-suggestions.ts @@ -0,0 +1,103 @@ +import { SuggestedVacancy } from './domain/project-idea'; +import { ProjectRole } from './domain/project-role.enum'; + +// Máximo de vagas sugeridas por cargo, mesmo que haja mais interessados. +const MAX_SUGGESTED: Record = { + [ProjectRole.FRONTEND]: 3, + [ProjectRole.BACKEND]: 3, + [ProjectRole.DATABASE]: 1, + [ProjectRole.REQUIREMENTS_ANALYST]: 1, + [ProjectRole.UX_DESIGNER]: 1, + [ProjectRole.QA]: 1, + [ProjectRole.DEVOPS]: 1, + [ProjectRole.MOBILE]: 2, + [ProjectRole.PROJECT_MANAGER]: 1, +}; + +// Cargos que quase todo projeto precisa, independente do texto da ideia. +const ESSENTIAL_ROLES: ProjectRole[] = [ + ProjectRole.FRONTEND, + ProjectRole.BACKEND, + ProjectRole.REQUIREMENTS_ANALYST, +]; + +// Pistas no título/descrição/tags que sugerem um cargo a mais. +const KEYWORD_RULES: { role: ProjectRole; pattern: RegExp; reason: string }[] = + [ + { + role: ProjectRole.MOBILE, + pattern: /\b(app|mobile|android|ios|flutter|react native)\b/, + reason: 'A ideia menciona aplicativo mobile', + }, + { + role: ProjectRole.DATABASE, + pattern: + /(banco de dados|database|sql|postgres|mysql|mongo|dados|relat[óo]rio)/, + reason: 'A ideia envolve armazenamento ou análise de dados', + }, + { + role: ProjectRole.UX_DESIGNER, + pattern: /\b(design|ux|ui|interface|prot[óo]tipo|figma)\b/, + reason: 'A ideia destaca a experiência/interface do usuário', + }, + { + role: ProjectRole.DEVOPS, + pattern: /(deploy|docker|infra|ci\/cd|kubernetes|nuvem|cloud)/, + reason: 'A ideia menciona infraestrutura ou deploy', + }, + { + role: ProjectRole.QA, + pattern: /(teste|qualidade|\bqa\b)/, + reason: 'A ideia destaca testes/qualidade', + }, + ]; + +/** + * Sugere vagas para o time a partir do interesse demonstrado por cargo e de + * pistas no texto da ideia. A quantidade de cada cargo é o maior valor entre + * o mínimo exigido (essencial/pista) e o número de interessados, limitado ao + * teto do cargo. + */ +export function suggestVacancies(input: { + text: string; + interestByRole: Partial>; +}): SuggestedVacancy[] { + const text = input.text.toLowerCase(); + + return Object.values(ProjectRole) + .map((role) => { + const interestedCount = input.interestByRole[role] ?? 0; + + let minimum = 0; + let reason = ''; + if (ESSENTIAL_ROLES.includes(role)) { + minimum = 1; + reason = 'Cargo essencial para a maioria dos projetos'; + } + const keywordRule = KEYWORD_RULES.find( + (rule) => rule.role === role && rule.pattern.test(text), + ); + if (keywordRule) { + minimum = 1; + reason = keywordRule.reason; + } + if (interestedCount > 0) { + reason = `${interestedCount} ${ + interestedCount === 1 ? 'interessado' : 'interessados' + } neste cargo`; + } + + const quantity = Math.min( + Math.max(minimum, interestedCount), + MAX_SUGGESTED[role], + ); + + const suggestion = new SuggestedVacancy(); + suggestion.role = role; + suggestion.quantity = quantity; + suggestion.interestedCount = interestedCount; + suggestion.reason = reason; + return suggestion; + }) + .filter((suggestion) => suggestion.quantity > 0); +} diff --git a/src/social/interfaces/social.interface.ts b/src/social/interfaces/social.interface.ts index 90bb515..6d98837 100644 --- a/src/social/interfaces/social.interface.ts +++ b/src/social/interfaces/social.interface.ts @@ -3,4 +3,5 @@ export interface SocialInterface { firstName?: string; lastName?: string; email?: string; + picture?: string; } diff --git a/src/submissions/domain/submission.ts b/src/submissions/domain/submission.ts index fc90a10..d4eb0dd 100644 --- a/src/submissions/domain/submission.ts +++ b/src/submissions/domain/submission.ts @@ -2,6 +2,8 @@ import { ApiProperty } from '@nestjs/swagger'; import { SubmissionStatus } from './submission-status.enum'; import { SubmissionContributionKind } from './submission-contribution-kind.enum'; import { EffortLevel } from '../../activities/domain/effort-level.enum'; +import { GithubRepoTarget } from '../../github-issues/domain/github-repo-target.enum'; +import { GithubIssueCategory } from '../../github-issues/domain/github-issue-category.enum'; export class Submission { @ApiProperty({ @@ -107,6 +109,33 @@ export class Submission { }) reviewedAt: Date | null; + @ApiProperty({ + nullable: true, + description: 'Data em que a atividade foi realizada', + }) + activityDate: Date | null; + + @ApiProperty({ + enum: GithubRepoTarget, + nullable: true, + description: 'Repositório onde a issue deve ser criada, se aplicável', + }) + githubRepo: GithubRepoTarget | null; + + @ApiProperty({ + enum: GithubIssueCategory, + nullable: true, + description: 'Classificação da issue (bug, melhoria, dúvida, outro)', + }) + issueCategory: GithubIssueCategory | null; + + @ApiProperty({ + type: String, + nullable: true, + description: 'URL da issue criada no GitHub após aprovação', + }) + githubIssueUrl: string | null; + @ApiProperty() createdAt: Date; diff --git a/src/submissions/dto/create-submission.dto.ts b/src/submissions/dto/create-submission.dto.ts index a6f3115..676c4b9 100644 --- a/src/submissions/dto/create-submission.dto.ts +++ b/src/submissions/dto/create-submission.dto.ts @@ -1,6 +1,7 @@ import { ApiPropertyOptional } from '@nestjs/swagger'; import { IsBoolean, + IsDateString, IsEnum, IsOptional, IsString, @@ -9,6 +10,8 @@ import { } from 'class-validator'; import { Transform } from 'class-transformer'; import { EffortLevel } from '../../activities/domain/effort-level.enum'; +import { GithubRepoTarget } from '../../github-issues/domain/github-repo-target.enum'; +import { GithubIssueCategory } from '../../github-issues/domain/github-issue-category.enum'; export class CreateSubmissionDto { @ApiPropertyOptional({ @@ -44,7 +47,7 @@ export class CreateSubmissionDto { }) @IsOptional() @IsString() - @MaxLength(500) + @MaxLength(2048) @Transform(({ value }) => value?.trim() ?? null) proofUrl?: string | null; @@ -78,4 +81,31 @@ export class CreateSubmissionDto { @IsOptional() @IsEnum(EffortLevel) effortLevel?: EffortLevel; + + @ApiPropertyOptional({ + example: '2026-08-15', + description: + 'Data em que a atividade foi realizada (ISO 8601). Obrigatório se a atividade exigir data.', + }) + @IsOptional() + @IsDateString() + activityDate?: string | null; + + @ApiPropertyOptional({ + enum: GithubRepoTarget, + description: + 'Repositório onde a issue deve ser criada. Obrigatório quando a atividade tem createsGithubIssue.', + }) + @IsOptional() + @IsEnum(GithubRepoTarget) + githubRepo?: GithubRepoTarget; + + @ApiPropertyOptional({ + enum: GithubIssueCategory, + description: + 'Classificação da issue. Obrigatória quando a atividade tem createsGithubIssue.', + }) + @IsOptional() + @IsEnum(GithubIssueCategory) + issueCategory?: GithubIssueCategory; } diff --git a/src/submissions/infrastructure/persistence/relational/entities/submission.entity.ts b/src/submissions/infrastructure/persistence/relational/entities/submission.entity.ts index 3507c18..e0678a2 100644 --- a/src/submissions/infrastructure/persistence/relational/entities/submission.entity.ts +++ b/src/submissions/infrastructure/persistence/relational/entities/submission.entity.ts @@ -15,6 +15,8 @@ import { ActivityEntity } from '../../../../../activities/infrastructure/persist import { UserEntity } from '../../../../../users/infrastructure/persistence/relational/entities/user.entity'; import { TrackItemEntity } from '../../../../../track-items/infrastructure/persistence/relational/entities/track-item.entity'; import { EffortLevel } from '../../../../../activities/domain/effort-level.enum'; +import { GithubRepoTarget } from '../../../../../github-issues/domain/github-repo-target.enum'; +import { GithubIssueCategory } from '../../../../../github-issues/domain/github-issue-category.enum'; @Entity({ name: 'submission', @@ -97,6 +99,28 @@ export class SubmissionEntity extends EntityRelationalHelper { @Column({ type: 'timestamp', nullable: true, default: null }) reviewedAt: Date | null; + @Column({ type: 'timestamp', nullable: true, default: null }) + activityDate: Date | null; + + @Column({ + type: 'enum', + enum: GithubRepoTarget, + nullable: true, + default: null, + }) + githubRepo: GithubRepoTarget | null; + + @Column({ + type: 'enum', + enum: GithubIssueCategory, + nullable: true, + default: null, + }) + issueCategory: GithubIssueCategory | null; + + @Column({ type: 'varchar', nullable: true, default: null }) + githubIssueUrl: string | null; + @CreateDateColumn() createdAt: Date; diff --git a/src/submissions/infrastructure/persistence/relational/mappers/submission.mapper.ts b/src/submissions/infrastructure/persistence/relational/mappers/submission.mapper.ts index 98c4366..1f20148 100644 --- a/src/submissions/infrastructure/persistence/relational/mappers/submission.mapper.ts +++ b/src/submissions/infrastructure/persistence/relational/mappers/submission.mapper.ts @@ -19,6 +19,10 @@ export class SubmissionMapper { domainEntity.awardedXp = raw.awardedXp; domainEntity.reviewerId = raw.reviewerId; domainEntity.reviewedAt = raw.reviewedAt; + domainEntity.activityDate = raw.activityDate; + domainEntity.githubRepo = raw.githubRepo; + domainEntity.issueCategory = raw.issueCategory; + domainEntity.githubIssueUrl = raw.githubIssueUrl; domainEntity.createdAt = raw.createdAt; domainEntity.updatedAt = raw.updatedAt; @@ -44,6 +48,10 @@ export class SubmissionMapper { persistenceEntity.awardedXp = domainEntity.awardedXp; persistenceEntity.reviewerId = domainEntity.reviewerId; persistenceEntity.reviewedAt = domainEntity.reviewedAt; + persistenceEntity.activityDate = domainEntity.activityDate; + persistenceEntity.githubRepo = domainEntity.githubRepo; + persistenceEntity.issueCategory = domainEntity.issueCategory; + persistenceEntity.githubIssueUrl = domainEntity.githubIssueUrl; persistenceEntity.createdAt = domainEntity.createdAt; persistenceEntity.updatedAt = domainEntity.updatedAt; diff --git a/src/submissions/submissions-cron.service.ts b/src/submissions/submissions-cron.service.ts new file mode 100644 index 0000000..d14c802 --- /dev/null +++ b/src/submissions/submissions-cron.service.ts @@ -0,0 +1,55 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { Cron } from '@nestjs/schedule'; +import { SubmissionsService } from './submissions.service'; +import { UsersService } from '../users/users.service'; +import { MailService } from '../mail/mail.service'; +import { RoleEnum } from '../roles/roles.enum'; + +@Injectable() +export class SubmissionsCronService { + private readonly logger = new Logger(SubmissionsCronService.name); + + constructor( + private readonly submissionsService: SubmissionsService, + private readonly usersService: UsersService, + private readonly mailService: MailService, + ) {} + + @Cron('0 6 * * *') + async handlePendingSubmissionsDigest() { + const pending = await this.submissionsService.findPending({ + page: 1, + limit: 1000, + }); + + if (pending.length === 0) return; + + const moderators = await this.usersService.findManyWithPagination({ + filterOptions: { + roles: [{ id: RoleEnum.moderator }, { id: RoleEnum.admin }], + }, + sortOptions: [], + paginationOptions: { page: 1, limit: 500 }, + }); + + let sent = 0; + for (const user of moderators) { + if (!user.email) continue; + try { + await this.mailService.sendPendingSubmissionsDigest({ + to: user.email as string, + data: { count: pending.length }, + }); + sent++; + } catch (err) { + this.logger.error( + `Falha ao enviar digest para ${user.email}: ${(err as Error).message}`, + ); + } + } + + this.logger.log( + `Digest de submissões pendentes enviado para ${sent} moderador(es). Total pendente: ${pending.length}`, + ); + } +} diff --git a/src/submissions/submissions.controller.spec.ts b/src/submissions/submissions.controller.spec.ts index 7257832..4ec3aa4 100644 --- a/src/submissions/submissions.controller.spec.ts +++ b/src/submissions/submissions.controller.spec.ts @@ -27,6 +27,10 @@ const mockSubmission: Submission = { awardedXp: 0, reviewerId: null, reviewedAt: null, + activityDate: null, + githubRepo: null, + issueCategory: null, + githubIssueUrl: null, createdAt: new Date('2026-01-01'), updatedAt: new Date('2026-01-01'), }; diff --git a/src/submissions/submissions.module.ts b/src/submissions/submissions.module.ts index 6c7af1e..b23c34b 100644 --- a/src/submissions/submissions.module.ts +++ b/src/submissions/submissions.module.ts @@ -2,7 +2,9 @@ import { // do not remove this comment Module, } from '@nestjs/common'; +import { ScheduleModule } from '@nestjs/schedule'; import { SubmissionsService } from './submissions.service'; +import { SubmissionsCronService } from './submissions-cron.service'; import { SubmissionsController } from './submissions.controller'; import { RelationalSubmissionPersistenceModule } from './infrastructure/persistence/relational/relational-persistence.module'; import { GamificationProfilesModule } from '../gamification-profiles/gamification-profiles.module'; @@ -14,6 +16,9 @@ import { TrackItemCompletionsModule } from '../track-item-completions/track-item import { LearningTracksModule } from '../learning-tracks/learning-tracks.module'; import { AuditLogsModule } from '../audit-logs/audit-logs.module'; import { MailModule } from '../mail/mail.module'; +import { FilesModule } from '../files/files.module'; +import { UsersModule } from '../users/users.module'; +import { GithubIssuesModule } from '../github-issues/github-issues.module'; @Module({ imports: [ @@ -28,9 +33,13 @@ import { MailModule } from '../mail/mail.module'; LearningTracksModule, AuditLogsModule, MailModule, + FilesModule, + UsersModule, + GithubIssuesModule, + ScheduleModule.forRoot(), ], controllers: [SubmissionsController], - providers: [SubmissionsService], + providers: [SubmissionsService, SubmissionsCronService], exports: [SubmissionsService, RelationalSubmissionPersistenceModule], }) export class SubmissionsModule {} diff --git a/src/submissions/submissions.service.spec.ts b/src/submissions/submissions.service.spec.ts index cc2920e..0236d03 100644 --- a/src/submissions/submissions.service.spec.ts +++ b/src/submissions/submissions.service.spec.ts @@ -4,6 +4,9 @@ import { BadRequestException, NotFoundException } from '@nestjs/common'; import { SubmissionsService } from './submissions.service'; import { SubmissionRepository } from './infrastructure/persistence/submission.repository'; import { MailService } from '../mail/mail.service'; +import { FilesService } from '../files/files.service'; +import { UsersService } from '../users/users.service'; +import { GithubIssuesService } from '../github-issues/github-issues.service'; import { GamificationProfilesService } from '../gamification-profiles/gamification-profiles.service'; import { ActivitiesService } from '../activities/activities.service'; import { BadgeEvaluatorService } from '../badges/badge-evaluator.service'; @@ -24,6 +27,8 @@ import { TrackItem } from '../track-items/domain/track-item'; import { TrackItemType } from '../track-items/domain/track-item-type.enum'; import { TrackItemStatus } from '../track-items/domain/track-item-status.enum'; import { TrackItemProofFormat } from '../track-items/domain/track-item-proof-format.enum'; +import { GithubRepoTarget } from '../github-issues/domain/github-repo-target.enum'; +import { GithubIssueCategory } from '../github-issues/domain/github-issue-category.enum'; const mockProfile: GamificationProfile = { id: 'profile-1', @@ -52,8 +57,11 @@ const mockActivity: Activity = { requiresProof: false, requiresDescription: false, cooldownHours: 0, + auditorReward: 10, + requiresActivityDate: false, effortTiers: null, isFreeform: false, + createsGithubIssue: false, createdAt: new Date('2026-01-01'), updatedAt: new Date('2026-01-01'), }; @@ -112,6 +120,10 @@ function makeSubmission(overrides: Partial = {}): Submission { awardedXp: 0, reviewerId: null, reviewedAt: null, + activityDate: null, + githubRepo: null, + issueCategory: null, + githubIssueUrl: null, createdAt: new Date('2026-01-01'), updatedAt: new Date('2026-01-01'), ...overrides, @@ -139,6 +151,9 @@ describe('SubmissionsService', () => { let mockLearningTracksService: Partial< Record >; + let mockGithubIssuesService: Partial< + Record + >; const mockQueryRunner = { connect: jest.fn(), @@ -154,11 +169,14 @@ describe('SubmissionsService', () => { }, }; + const mockGenericRepository = { + findOne: jest.fn().mockResolvedValue(mockProfile), + update: jest.fn().mockResolvedValue(undefined), + }; + const mockDataSource = { createQueryRunner: jest.fn().mockReturnValue(mockQueryRunner), - getRepository: jest.fn().mockReturnValue({ - findOne: jest.fn().mockResolvedValue(mockProfile), - }), + getRepository: jest.fn().mockReturnValue(mockGenericRepository), }; beforeEach(async () => { @@ -198,6 +216,15 @@ describe('SubmissionsService', () => { const mockMailService = { submissionApproved: jest.fn(), }; + const mockFilesService = { + removeByUrl: jest.fn().mockResolvedValue(undefined), + }; + const mockUsersService = { + findManyWithPagination: jest.fn().mockResolvedValue([]), + }; + mockGithubIssuesService = { + createIssue: jest.fn().mockResolvedValue({ url: '', number: 0 }), + }; const module: TestingModule = await Test.createTestingModule({ providers: [ @@ -227,6 +254,9 @@ describe('SubmissionsService', () => { }, { provide: LearningTracksService, useValue: mockLearningTracksService }, { provide: MailService, useValue: mockMailService }, + { provide: FilesService, useValue: mockFilesService }, + { provide: UsersService, useValue: mockUsersService }, + { provide: GithubIssuesService, useValue: mockGithubIssuesService }, { provide: getDataSourceToken(), useValue: mockDataSource }, ], }).compile(); @@ -508,6 +538,88 @@ describe('SubmissionsService', () => { }); }); + describe('create — issue do GitHub', () => { + const mockGithubIssueActivity: Activity = { + ...mockActivity, + createsGithubIssue: true, + }; + + it('should throw BadRequestException when createsGithubIssue and customTitle is missing', async () => { + mockActivitiesService.findById!.mockResolvedValue( + mockGithubIssueActivity, + ); + + await expect( + service.create( + { + activityId: 'activity-1', + githubRepo: GithubRepoTarget.API, + issueCategory: GithubIssueCategory.BUG, + }, + 1, + ), + ).rejects.toThrow(BadRequestException); + }); + + it('should throw BadRequestException when createsGithubIssue and githubRepo is missing', async () => { + mockActivitiesService.findById!.mockResolvedValue( + mockGithubIssueActivity, + ); + + await expect( + service.create( + { + activityId: 'activity-1', + customTitle: 'Botão de login não funciona no mobile', + issueCategory: GithubIssueCategory.BUG, + }, + 1, + ), + ).rejects.toThrow(BadRequestException); + }); + + it('should throw BadRequestException when createsGithubIssue and issueCategory is missing', async () => { + mockActivitiesService.findById!.mockResolvedValue( + mockGithubIssueActivity, + ); + + await expect( + service.create( + { + activityId: 'activity-1', + customTitle: 'Botão de login não funciona no mobile', + githubRepo: GithubRepoTarget.API, + }, + 1, + ), + ).rejects.toThrow(BadRequestException); + }); + + it('should create the submission with githubRepo and issueCategory when valid', async () => { + mockActivitiesService.findById!.mockResolvedValue( + mockGithubIssueActivity, + ); + + await service.create( + { + activityId: 'activity-1', + customTitle: 'Botão de login não funciona no mobile', + description: 'Ao clicar em login pelo celular, nada acontece.', + githubRepo: GithubRepoTarget.FRONT, + issueCategory: GithubIssueCategory.BUG, + }, + 1, + ); + + expect(mockSubmissionRepository.create).toHaveBeenCalledWith( + expect.objectContaining({ + githubRepo: GithubRepoTarget.FRONT, + issueCategory: GithubIssueCategory.BUG, + }), + ); + }); + }); + describe('review — aprovação de marco de trilha', () => { it('should create a track_item_completion and credit journeyXp on approval', async () => { mockSubmissionRepository.findById!.mockResolvedValue( @@ -634,7 +746,7 @@ describe('SubmissionsService', () => { ); }); - it('should award 3 XP to the moderator on approval', async () => { + it('should award the activity auditorReward to the moderator on approval', async () => { mockSubmissionRepository.findById!.mockResolvedValue( makeSubmission({ trackItemId: 'item-1' }), ); @@ -649,31 +761,71 @@ describe('SubmissionsService', () => { expect.anything(), { id: 'moderator-profile' }, 'totalXp', - 3, + mockActivity.auditorReward, ); expect(mockQueryRunner.manager.increment).toHaveBeenCalledWith( expect.anything(), { id: 'moderator-profile' }, 'currentMonthlyXp', - 3, + mockActivity.auditorReward, ); expect(mockQueryRunner.manager.increment).toHaveBeenCalledWith( expect.anything(), { id: 'moderator-profile' }, 'currentYearlyXp', - 3, + mockActivity.auditorReward, ); expect(mockQueryRunner.manager.save).toHaveBeenCalledWith( expect.anything(), expect.objectContaining({ profile: { id: 'moderator-profile' }, category: 'AUDITOR_REWARD', - amount: 3, + amount: mockActivity.auditorReward, description: `Revisão de submissão: ${mockActivity.title}`, }), ); }); + it('should create the GitHub issue and persist the URL on approval', async () => { + mockActivitiesService.findById!.mockResolvedValue({ + ...mockActivity, + createsGithubIssue: true, + }); + mockSubmissionRepository.findById!.mockResolvedValue( + makeSubmission({ + customTitle: 'Botão de login não funciona no mobile', + description: 'Ao clicar em login pelo celular, nada acontece.', + githubRepo: GithubRepoTarget.FRONT, + issueCategory: GithubIssueCategory.BUG, + }), + ); + mockGithubIssuesService.createIssue!.mockResolvedValue({ + url: 'https://github.com/devs-tocantins/front-engajamento/issues/42', + number: 42, + }); + + await service.review( + 'submission-1', + { status: SubmissionStatus.APPROVED }, + 2, + ); + + expect(mockGithubIssuesService.createIssue).toHaveBeenCalledWith( + expect.objectContaining({ + repoTarget: GithubRepoTarget.FRONT, + category: GithubIssueCategory.BUG, + title: 'Botão de login não funciona no mobile', + }), + ); + expect(mockGenericRepository.update).toHaveBeenCalledWith( + 'submission-1', + expect.objectContaining({ + githubIssueUrl: + 'https://github.com/devs-tocantins/front-engajamento/issues/42', + }), + ); + }); + it('should NOT award XP to the moderator on rejection', async () => { mockSubmissionRepository.findById!.mockResolvedValue( makeSubmission({ trackItemId: 'item-1' }), diff --git a/src/submissions/submissions.service.ts b/src/submissions/submissions.service.ts index 99f6a94..6312056 100644 --- a/src/submissions/submissions.service.ts +++ b/src/submissions/submissions.service.ts @@ -39,8 +39,10 @@ import { AuditActionEnum } from '../audit-logs/domain/audit-action.enum'; import { MailService } from '../mail/mail.service'; import { UserEntity } from '../users/infrastructure/persistence/relational/entities/user.entity'; import { NotificationPreferenceEntity } from '../notifications/infrastructure/persistence/relational/entities/notification-preference.entity'; - -const MODERATOR_REWARD_XP = 3; +import { FilesService } from '../files/files.service'; +import { UsersService } from '../users/users.service'; +import { RoleEnum } from '../roles/roles.enum'; +import { GithubIssuesService } from '../github-issues/github-issues.service'; @Injectable() export class SubmissionsService { @@ -57,6 +59,9 @@ export class SubmissionsService { private readonly learningTracksService: LearningTracksService, private readonly mailService: MailService, private readonly auditLogsService: AuditLogsService, + private readonly filesService: FilesService, + private readonly usersService: UsersService, + private readonly githubIssuesService: GithubIssuesService, @InjectDataSource() private readonly dataSource: DataSource, ) {} @@ -179,6 +184,30 @@ export class SubmissionsService { ); } + if (activity.requiresActivityDate && !createSubmissionDto.activityDate) { + throw new BadRequestException( + 'Esta atividade exige a data em que foi realizada (activityDate).', + ); + } + + if (activity.createsGithubIssue) { + if (!createSubmissionDto.customTitle) { + throw new BadRequestException( + 'Esta atividade exige um título (customTitle) para a issue.', + ); + } + if (!createSubmissionDto.githubRepo) { + throw new BadRequestException( + 'Esta atividade exige o repositório de destino (githubRepo).', + ); + } + if (!createSubmissionDto.issueCategory) { + throw new BadRequestException( + 'Esta atividade exige a classificação da issue (issueCategory).', + ); + } + } + if (activity.effortTiers && activity.effortTiers.length > 0) { if (!createSubmissionDto.effortLevel) { throw new BadRequestException( @@ -230,6 +259,12 @@ export class SubmissionsService { description: createSubmissionDto.description ?? null, customTitle: createSubmissionDto.customTitle ?? null, declaredEffort: createSubmissionDto.effortLevel ?? null, + activityDate: createSubmissionDto.activityDate + ? new Date(createSubmissionDto.activityDate) + : null, + githubRepo: createSubmissionDto.githubRepo ?? null, + issueCategory: createSubmissionDto.issueCategory ?? null, + githubIssueUrl: null, status: isTestOut ? SubmissionStatus.APPROVED : SubmissionStatus.PENDING, feedback: null, awardedXp: 0, @@ -237,6 +272,8 @@ export class SubmissionsService { reviewedAt: isTestOut ? now : null, }); + void this.notifyModeratorsNewSubmission(submission.id); + if (trackItem) { if (existingCompletion) { await this.trackItemCompletionsService.remove(existingCompletion.id); @@ -263,6 +300,38 @@ export class SubmissionsService { return submission; } + private async notifyModeratorsNewSubmission(submissionId: string) { + try { + const moderators = await this.usersService.findManyWithPagination({ + filterOptions: { + roles: [{ id: RoleEnum.moderator }, { id: RoleEnum.admin }], + }, + sortOptions: null, + paginationOptions: { page: 1, limit: 500 }, + }); + + for (const mod of moderators) { + void this.notificationsService + .create({ + userId: Number(mod.id), + type: NotificationType.NEW_SUBMISSION_PENDING, + title: 'Nova submissão aguardando revisão', + body: 'Uma nova submissão de atividade está aguardando sua revisão.', + relatedId: submissionId, + link: `/moderation?open=${submissionId}`, + }) + .catch((err) => + this.logger.error( + 'Error sending NEW_SUBMISSION_PENDING notification', + err, + ), + ); + } + } catch (err) { + this.logger.error('Error notifying moderators of new submission', err); + } + } + // Resolve o XP efetivo: override do moderador ao aprovar > faixa declarada // pelo usuário > fixedReward. Mantém a atividade "confiança + moderação" // descrita no plano: o usuário se autodeclara, o moderador confirma/ajusta. @@ -347,7 +416,9 @@ export class SubmissionsService { detail.activityTitle = submission.customTitle ?? activity.title; detail.activityDescription = activity.description; detail.description = submission.description; - detail.activityDate = null; + detail.activityDate = submission.activityDate + ? submission.activityDate.toISOString() + : null; detail.awardedXp = submission.awardedXp; detail.hasProof = !!submission.proofUrl; detail.createdAt = submission.createdAt; @@ -525,25 +596,25 @@ export class SubmissionsService { GamificationProfileEntity, { id: moderatorProfile.id }, 'totalXp', - MODERATOR_REWARD_XP, + activity.auditorReward, ); await queryRunner.manager.increment( GamificationProfileEntity, { id: moderatorProfile.id }, 'currentMonthlyXp', - MODERATOR_REWARD_XP, + activity.auditorReward, ); await queryRunner.manager.increment( GamificationProfileEntity, { id: moderatorProfile.id }, 'currentYearlyXp', - MODERATOR_REWARD_XP, + activity.auditorReward, ); await queryRunner.manager.save(TransactionEntity, { profile: { id: moderatorProfile.id }, category: TransactionCategoryEnum.AUDITOR_REWARD, - amount: MODERATOR_REWARD_XP, + amount: activity.auditorReward, description: `Revisão de submissão: ${activity.title}`, }); } @@ -631,6 +702,32 @@ export class SubmissionsService { } catch (err) { this.logger.error('Error sending submissionApproved email', err); } + + if ( + activity.createsGithubIssue && + submission.githubRepo && + submission.issueCategory + ) { + try { + const authorLabel = ownerProfile.githubUsername + ? `@${ownerProfile.githubUsername}` + : `usuário #${ownerProfile.userId}`; + const issue = await this.githubIssuesService.createIssue({ + repoTarget: submission.githubRepo, + category: submission.issueCategory, + title: submission.customTitle ?? activity.title, + body: `${submission.description ?? ''}\n\n---\nAberto via legado.dev por ${authorLabel}.`, + }); + await this.dataSource.getRepository(SubmissionEntity).update(id, { + githubIssueUrl: issue.url, + }); + } catch (err) { + this.logger.error( + 'Error creating GitHub issue for submission', + err, + ); + } + } } } else if (reviewDto.status === SubmissionStatus.REJECTED) { const ownerProfile = await this.dataSource @@ -687,6 +784,10 @@ export class SubmissionsService { }); } + if (reviewDto.status === SubmissionStatus.REJECTED && submission.proofUrl) { + void this.filesService.removeByUrl(submission.proofUrl); + } + return this.submissionRepository.findById(id); } @@ -746,6 +847,10 @@ export class SubmissionsService { description: null, customTitle: null, declaredEffort: null, + activityDate: null, + githubRepo: null, + issueCategory: null, + githubIssueUrl: null, status: SubmissionStatus.APPROVED, feedback: null, awardedXp: activity.fixedReward, @@ -812,7 +917,11 @@ export class SubmissionsService { ); } - return this.submissionRepository.remove(id); + await this.submissionRepository.remove(id); + + if (submission.proofUrl) { + void this.filesService.removeByUrl(submission.proofUrl); + } } remove(id: Submission['id']) { diff --git a/src/track-items/track-items.service.spec.ts b/src/track-items/track-items.service.spec.ts index df6c4d8..fa35d9f 100644 --- a/src/track-items/track-items.service.spec.ts +++ b/src/track-items/track-items.service.spec.ts @@ -249,6 +249,7 @@ describe('TrackItemsService — evaluateSectionCompletion', () => { description: 'Comprovação exclusiva do marco de trilha "Suba uma API REST em produção".', fixedReward: 50, + auditorReward: 10, isHidden: true, requiresProof: true, requiresDescription: false, diff --git a/src/track-items/track-items.service.ts b/src/track-items/track-items.service.ts index d536bd2..946bbfd 100644 --- a/src/track-items/track-items.service.ts +++ b/src/track-items/track-items.service.ts @@ -63,6 +63,7 @@ export class TrackItemsService { title: `Prova: ${createTrackItemDto.title}`, description: `Comprovação exclusiva do marco de trilha "${createTrackItemDto.title}".`, fixedReward: grantsCommunityXp ? communityXpReward : 0, + auditorReward: 10, isHidden: true, requiresProof: true, requiresDescription: false, diff --git a/src/transactions/infrastructure/persistence/relational/repositories/transaction.repository.ts b/src/transactions/infrastructure/persistence/relational/repositories/transaction.repository.ts index 8a3f360..55fa848 100644 --- a/src/transactions/infrastructure/persistence/relational/repositories/transaction.repository.ts +++ b/src/transactions/infrastructure/persistence/relational/repositories/transaction.repository.ts @@ -7,6 +7,7 @@ import { Transaction } from '../../../../domain/transaction'; import { TransactionRepository } from '../../transaction.repository'; import { TransactionMapper } from '../mappers/transaction.mapper'; import { IPaginationOptions } from '../../../../../utils/types/pagination-options'; +import { TransactionCategoryEnum } from '../../../../domain/transaction-category.enum'; @Injectable() export class TransactionRelationalRepository implements TransactionRepository { @@ -93,4 +94,27 @@ export class TransactionRelationalRepository implements TransactionRepository { return entities.map((entity) => TransactionMapper.toDomain(entity)); } + + async findTokenTransactionsByProfileId( + profileId: string, + paginationOptions: IPaginationOptions, + ): Promise { + const entities = await this.transactionRepository.find({ + where: [ + { + profile: { id: profileId }, + category: TransactionCategoryEnum.TOKEN_REWARD, + }, + { + profile: { id: profileId }, + category: TransactionCategoryEnum.TOKEN_TRANSFER, + }, + ], + order: { createdAt: 'DESC' }, + skip: (paginationOptions.page - 1) * paginationOptions.limit, + take: paginationOptions.limit, + }); + + return entities.map((entity) => TransactionMapper.toDomain(entity)); + } } diff --git a/src/transactions/infrastructure/persistence/transaction.repository.ts b/src/transactions/infrastructure/persistence/transaction.repository.ts index 6347ec1..13d290c 100644 --- a/src/transactions/infrastructure/persistence/transaction.repository.ts +++ b/src/transactions/infrastructure/persistence/transaction.repository.ts @@ -29,4 +29,9 @@ export abstract class TransactionRepository { profileId: string, paginationOptions: IPaginationOptions, ): Promise; + + abstract findTokenTransactionsByProfileId( + profileId: string, + paginationOptions: IPaginationOptions, + ): Promise; } diff --git a/src/transactions/transactions.controller.ts b/src/transactions/transactions.controller.ts index 8940c2b..1369587 100644 --- a/src/transactions/transactions.controller.ts +++ b/src/transactions/transactions.controller.ts @@ -10,6 +10,8 @@ import { Query, Request, NotFoundException, + ParseIntPipe, + DefaultValuePipe, } from '@nestjs/common'; import { TransactionsService } from './transactions.service'; import { CreateTransactionDto } from './dto/create-transaction.dto'; @@ -35,8 +37,6 @@ import { FindAllTransactionsDto } from './dto/find-all-transactions.dto'; import { GamificationProfilesService } from '../gamification-profiles/gamification-profiles.service'; @ApiTags('Transactions') -@ApiBearerAuth() -@UseGuards(AuthGuard('jwt')) @Controller({ path: 'transactions', version: '1', @@ -47,29 +47,44 @@ export class TransactionsController { private readonly gamificationProfilesService: GamificationProfilesService, ) {} + @Get('profile/:profileId/tokens') + @ApiParam({ name: 'profileId', type: String, required: true }) + @ApiOkResponse({ type: InfinityPaginationResponse(Transaction) }) + async findProfileTokens( + @Param('profileId') profileId: string, + @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number, + @Query('limit', new DefaultValuePipe(20), ParseIntPipe) limit: number, + ): Promise> { + if (limit > 50) limit = 50; + return infinityPagination( + await this.transactionsService.findTokenTransactionsByProfileId( + profileId, + { page, limit }, + ), + { page, limit }, + ); + } + @Post() - @UseGuards(RolesGuard) + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt'), RolesGuard) @Roles(RoleEnum.admin) - @ApiCreatedResponse({ - type: Transaction, - }) + @ApiCreatedResponse({ type: Transaction }) create(@Body() createTransactionDto: CreateTransactionDto) { return this.transactionsService.create(createTransactionDto); } @Get('me') - @ApiOkResponse({ - type: InfinityPaginationResponse(Transaction), - }) + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt')) + @ApiOkResponse({ type: InfinityPaginationResponse(Transaction) }) async findMine( @Query() query: FindAllTransactionsDto, @Request() req, ): Promise> { const page = query?.page ?? 1; let limit = query?.limit ?? 20; - if (limit > 50) { - limit = 50; - } + if (limit > 50) limit = 50; const profile = await this.gamificationProfilesService.findByUserId( req.user.id, @@ -88,57 +103,41 @@ export class TransactionsController { } @Get() - @UseGuards(RolesGuard) + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt'), RolesGuard) @Roles(RoleEnum.admin) - @ApiOkResponse({ - type: InfinityPaginationResponse(Transaction), - }) + @ApiOkResponse({ type: InfinityPaginationResponse(Transaction) }) async findAll( @Query() query: FindAllTransactionsDto, ): Promise> { const page = query?.page ?? 1; let limit = query?.limit ?? 10; - if (limit > 50) { - limit = 50; - } + if (limit > 50) limit = 50; return infinityPagination( await this.transactionsService.findAllWithPagination({ - paginationOptions: { - page, - limit, - }, + paginationOptions: { page, limit }, }), { page, limit }, ); } @Get(':id') - @UseGuards(RolesGuard) + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt'), RolesGuard) @Roles(RoleEnum.admin) - @ApiParam({ - name: 'id', - type: String, - required: true, - }) - @ApiOkResponse({ - type: Transaction, - }) + @ApiParam({ name: 'id', type: String, required: true }) + @ApiOkResponse({ type: Transaction }) findById(@Param('id') id: string) { return this.transactionsService.findById(id); } @Patch(':id') - @UseGuards(RolesGuard) + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt'), RolesGuard) @Roles(RoleEnum.admin) - @ApiParam({ - name: 'id', - type: String, - required: true, - }) - @ApiOkResponse({ - type: Transaction, - }) + @ApiParam({ name: 'id', type: String, required: true }) + @ApiOkResponse({ type: Transaction }) update( @Param('id') id: string, @Body() updateTransactionDto: UpdateTransactionDto, @@ -147,13 +146,10 @@ export class TransactionsController { } @Delete(':id') - @UseGuards(RolesGuard) + @ApiBearerAuth() + @UseGuards(AuthGuard('jwt'), RolesGuard) @Roles(RoleEnum.admin) - @ApiParam({ - name: 'id', - type: String, - required: true, - }) + @ApiParam({ name: 'id', type: String, required: true }) remove(@Param('id') id: string) { return this.transactionsService.remove(id); } diff --git a/src/transactions/transactions.service.ts b/src/transactions/transactions.service.ts index c11915c..32fe3ac 100644 --- a/src/transactions/transactions.service.ts +++ b/src/transactions/transactions.service.ts @@ -86,4 +86,14 @@ export class TransactionsService { paginationOptions, ); } + + findTokenTransactionsByProfileId( + profileId: string, + paginationOptions: IPaginationOptions, + ) { + return this.transactionRepository.findTokenTransactionsByProfileId( + profileId, + paginationOptions, + ); + } } diff --git a/src/users/users.module.ts b/src/users/users.module.ts index 5a9e78b..dd486ad 100644 --- a/src/users/users.module.ts +++ b/src/users/users.module.ts @@ -11,6 +11,8 @@ import { RelationalUserPersistenceModule } from './infrastructure/persistence/re import { FilesModule } from '../files/files.module'; import { AuditLogsModule } from '../audit-logs/audit-logs.module'; +import { GamificationProfilesModule } from '../gamification-profiles/gamification-profiles.module'; + const infrastructurePersistenceModule = RelationalUserPersistenceModule; @Module({ @@ -19,6 +21,7 @@ const infrastructurePersistenceModule = RelationalUserPersistenceModule; infrastructurePersistenceModule, FilesModule, AuditLogsModule, + GamificationProfilesModule, ], controllers: [UsersController], providers: [UsersService, UsersCronService], diff --git a/src/users/users.service.ts b/src/users/users.service.ts index 76a9a54..1bdef14 100644 --- a/src/users/users.service.ts +++ b/src/users/users.service.ts @@ -3,6 +3,7 @@ import { Injectable, UnprocessableEntityException, } from '@nestjs/common'; +import crypto from 'crypto'; import { CreateUserDto } from './dto/create-user.dto'; import { NullableType } from '../utils/types/nullable.type'; import { FilterUserDto, SortUserDto } from './dto/query-user.dto'; @@ -21,6 +22,7 @@ import { UpdateUserDto } from './dto/update-user.dto'; import { CURRENT_LEGAL_DOCUMENTS_VERSION } from '../legal-documents/legal-documents.constants'; import { AuditLogsService } from '../audit-logs/audit-logs.service'; import { AuditActionEnum } from '../audit-logs/domain/audit-action.enum'; +import { GamificationProfilesService } from '../gamification-profiles/gamification-profiles.service'; @Injectable() export class UsersService { @@ -28,6 +30,7 @@ export class UsersService { private readonly usersRepository: UserRepository, private readonly filesService: FilesService, private readonly auditLogsService: AuditLogsService, + private readonly gamificationProfilesService: GamificationProfilesService, ) {} async create(createUserDto: CreateUserDto): Promise { @@ -189,9 +192,7 @@ export class UsersService { let password: string | undefined = undefined; if (updateUserDto.password) { - const userObject = await this.usersRepository.findById(id); - - if (userObject && userObject?.password !== updateUserDto.password) { + if (oldUserObject?.password !== updateUserDto.password) { const salt = await bcrypt.genSalt(); password = await bcrypt.hash(updateUserDto.password, salt); } @@ -293,6 +294,13 @@ export class UsersService { }); if (updatedUser) { + const oldPhoto = oldUserObject?.photo; + const photoChanged = + photo !== undefined && oldPhoto?.id && oldPhoto.id !== photo?.id; + if (photoChanged) { + void this.filesService.remove(oldPhoto!.id); + } + if ( updateUserDto.role?.id !== undefined && oldRole !== updateUserDto.role.id @@ -324,6 +332,26 @@ export class UsersService { } async remove(id: User['id']): Promise { + const user = await this.usersRepository.findById(id); + if (!user) return; + + const randomHash = crypto.randomBytes(4).toString('hex'); + const anonymizedEmail = `deleted-${id}-${randomHash}@legado.dev`; + + await this.usersRepository.update(id, { + firstName: 'Usuário', + lastName: 'Deletado', + email: anonymizedEmail, + socialId: null, + photo: null, + }); + + await this.gamificationProfilesService.zeroOutProfile( + Number(id), + 'Conta excluída', + true, + ); + await this.usersRepository.remove(id); } }