Skip to content

Commit

Permalink
Merge pull request VitorCarvalho67#39 from Daniel-Alvarenga/main
Browse files Browse the repository at this point in the history
Add activity routes on server
  • Loading branch information
Daniel-Alvarenga authored Jul 31, 2024
2 parents dc681f6 + 8464a82 commit 01dc8bb
Show file tree
Hide file tree
Showing 8 changed files with 192 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
-- CreateTable
CREATE TABLE `alunos_atividades` (
`alunoId` VARCHAR(191) NOT NULL,
`atividadeId` VARCHAR(191) NOT NULL,
`mencao` ENUM('I', 'R', 'B', 'MB') NOT NULL,

PRIMARY KEY (`alunoId`, `atividadeId`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- AddForeignKey
ALTER TABLE `alunos_atividades` ADD CONSTRAINT `alunos_atividades_alunoId_fkey` FOREIGN KEY (`alunoId`) REFERENCES `alunos`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `alunos_atividades` ADD CONSTRAINT `alunos_atividades_atividadeId_fkey` FOREIGN KEY (`atividadeId`) REFERENCES `atividades`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
22 changes: 21 additions & 1 deletion server/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ model Aluno {
tentativasRestantes Int @default(5)
validated Boolean @default(false)
turmas AlunoTurma[]
atividades AlunoAtividade[]
cursosExtracurriculares Extracurricular[]
vinculosAluno Vinculo[] @relation("AlunoVinculo")
vinculoComoAluno Vinculo[] @relation("VinculoComAluno")
Expand Down Expand Up @@ -133,6 +134,24 @@ model AlunoTurma {
@@map("alunos_turmas")
}

model AlunoAtividade {
alunoId String @default(uuid())
atividadeId String @default(uuid())
mencao Mencao
aluno Aluno @relation(fields: [alunoId], references: [id])
atividade Atividade @relation(fields: [atividadeId], references: [id])
@@id([alunoId, atividadeId])
@@map("alunos_atividades")
}

enum Mencao {
I
R
B
MB
}

model Extracurricular {
extracurricularId String @id @default(uuid())
alunoId String
Expand Down Expand Up @@ -234,9 +253,10 @@ model Atividade {
id String @id @default(uuid())
title String
descricao String @db.VarChar(1000)
professor Professor @relation(fields: [professorId], references: [id])
professorId String
imagem String?
alunos AlunoAtividade[]
professor Professor @relation(fields: [professorId], references: [id])
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
Expand Down
31 changes: 30 additions & 1 deletion server/src/modules/controllers/professorControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { ValidateProfessorUseCase } from "../services/professor/ValidateProfesso
import { ValidateRecoveryUseCase } from "../services/professor/ValidateRecoveryUseCase";
import { RecoveryProfessorUseCase } from "../services/professor/RecoveryProfessorUseCase";
import { RefreshTokenUseCase } from "../services/professor/RefreshTokenUseCase";
import { CreateActivityUseCase } from "../services/professor/CreateActivityUseCase";
import { RelateAlunoAtividadeUseCase } from "../services/professor/LinkAlunoActivityUseCase";

export class InitProfessorController {
async handle(req: Request, res: Response) {
Expand Down Expand Up @@ -76,4 +78,31 @@ export class RefreshTokenController {

return res.status(201).json(result);
}
}
}

export class CreateActivityController {
async handle(req: Request, res: Response) {
const professorId = req.body.entidade.id;
const {title, descricao} = req.body;
const imagem = req.file as Express.Multer.File;

const createActivityUseCase = new CreateActivityUseCase();

const result = await createActivityUseCase.execute({title, descricao, professorId, imagem});

return res.status(201).json(result);
}
}

export class RelateAlunoAtividadeController {
async handle(req: Request, res: Response) {
const professorId = req.body.entidade.id;
const {alunoId, atividadeId, mencao} = req.body;

const relateAlunoAtividadeUseCase = new RelateAlunoAtividadeUseCase();

const result = await relateAlunoAtividadeUseCase.execute({alunoId, atividadeId, professorId, mencao});

return res.status(201).json(result);
}
}
21 changes: 21 additions & 0 deletions server/src/modules/interfaces/professorDTOs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,25 @@ export interface ValidateRecoveryDTO {
email: string,
recoveryPass: string,
newPass: string
}

export interface CreateActivityDTO {
title: string;
descricao: string;
professorId: string;
imagem: Express.Multer.File;
}

export interface RelateAlunoAtividadeDTO {
alunoId: string;
atividadeId: string;
professorId: string;
mencao: Mencao;
}

export enum Mencao{
I = "I",
R = "R",
B = "B",
MB = "MB"
}
45 changes: 45 additions & 0 deletions server/src/modules/services/professor/CreateActivityUseCase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { Professor } from "@prisma/client";
import { prisma } from "../../../prisma/client";
import { AppError } from "../../../errors/error";
import { CreateActivityDTO } from "../../interfaces/professorDTOs";
import { clearUploads } from "../shared/helpers/helpers";
import { uploadToMinio } from "../../../minioService";


export class CreateActivityUseCase {
async execute({ title, descricao, professorId, imagem }: CreateActivityDTO) {
if (!title || !descricao || !professorId || !imagem) {
throw new AppError("Parâmetros insuficientes ou inválidos.");
}

const professor = await prisma.professor.findUnique({
where: { id: professorId }
});

if (!professor) {
throw new Error('Professor não encontrado');
}

const bucketName = 'boot';
const objectName = `atividades/${professor.email}/title`;

try {
const filePath = imagem.path;
await uploadToMinio(bucketName, objectName, filePath);

clearUploads();
await prisma.atividade.create({
data: {
title,
descricao,
professorId,
imagem: objectName
}
});

return "Atividade criada com sucesso1";
} catch (error) {
throw new AppError(`Error uploading image: ${error}`);
}
}
}
53 changes: 53 additions & 0 deletions server/src/modules/services/professor/LinkAlunoActivityUseCase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { prisma } from "../../../prisma/client";
import { AppError } from "../../../errors/error";
import { RelateAlunoAtividadeDTO } from "../../interfaces/professorDTOs";

export class RelateAlunoAtividadeUseCase {
async execute({ alunoId, atividadeId, professorId, mencao }: RelateAlunoAtividadeDTO) {
if (!alunoId || !atividadeId || !professorId || !mencao) {
throw new AppError("Parâmetros insuficientes ou inválidos.");
}

const atividade = await prisma.atividade.findUnique({
where: { id: atividadeId }
});

if (!atividade) {
throw new AppError("Atividade não encontrada.");
}

const professor = await prisma.professor.findUnique({
where: { id: professorId }
});

if (!professor) {
throw new AppError("Professor não encontrado.");
}

if(atividade.professorId != professorId){
throw new AppError("Professor inválido.");
}

const aluno = await prisma.aluno.findUnique({
where: { id: alunoId }
});

if (!aluno) {
throw new AppError("Aluno não encontrado.");
}

try {
await prisma.alunoAtividade.create({
data: {
alunoId,
atividadeId,
mencao
}
});

return "Aluno relacionado à atividade com sucesso.";
} catch (error) {
throw new AppError(`Erro ao relacionar aluno à atividade: ${error}`);
}
}
}
8 changes: 6 additions & 2 deletions server/src/router/routes/imports/professor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ import {
InitProfessorController,
RecoveryProfessorController,
ValidateRecoveryController,
RefreshTokenController
RefreshTokenController,
CreateActivityController,
RelateAlunoAtividadeController
} from "../../../modules/controllers/professorControllers";

export const createControllers = () => ({
Expand All @@ -29,5 +31,7 @@ export const createControllers = () => ({
getVinculosController: new GetVinculosController(),
getUnlinkedsController: new GetUnlinkedsController(),
refreshTokenController: new RefreshTokenController(),
createMessageController: new CreateMessageController()
createMessageController: new CreateMessageController(),
createActivityController: new CreateActivityController(),
relateAlunoAtividadeController :new RelateAlunoAtividadeController(),
});
2 changes: 2 additions & 0 deletions server/src/router/routes/professor.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ professorRoutes.post("/link/accept", controllers.acceptVinculoController.handle)
professorRoutes.post("/link/reject", controllers.ignoreVinculoController.handle);
professorRoutes.post("/link/delete", controllers.deleteVinculoController.handle);
professorRoutes.post("/message/send", controllers.createMessageController.handle);
professorRoutes.post("/activity/create", controllers.createActivityController.handle);
professorRoutes.post("/activity/relate", controllers.recoveryProfessorController.handle);

professorRoutes.get("/auth", (req, res) => {
res.status(200).send("Professor autenticado com sucesso.");
Expand Down

0 comments on commit 01dc8bb

Please sign in to comment.