|
| 1 | +import { prisma } from "../../../prisma/client"; |
| 2 | +import { AppError } from "../../../errors/error"; |
| 3 | + |
| 4 | +const notaValores: { [key: string]: number } = { |
| 5 | + MB: 10, |
| 6 | + B: 7.5, |
| 7 | + R: 5, |
| 8 | + I: 2.5 |
| 9 | +}; |
| 10 | + |
| 11 | +export class GetRankingUseCase { |
| 12 | + async execute() { |
| 13 | + const notas = await prisma.nota.findMany({ |
| 14 | + include: { |
| 15 | + aluno: true |
| 16 | + } |
| 17 | + }); |
| 18 | + |
| 19 | + if (!notas.length) { |
| 20 | + throw new AppError("Nenhuma nota encontrada."); |
| 21 | + } |
| 22 | + |
| 23 | + const alunoNotas: { [alunoId: string]: { totalNotas: number; numeroNotas: number } } = {}; |
| 24 | + |
| 25 | + notas.forEach(nota => { |
| 26 | + const alunoId = nota.alunoId; |
| 27 | + const valorNota = notaValores[nota.mencao]; |
| 28 | + |
| 29 | + if (!alunoNotas[alunoId]) { |
| 30 | + alunoNotas[alunoId] = { |
| 31 | + totalNotas: 0, |
| 32 | + numeroNotas: 0 |
| 33 | + }; |
| 34 | + } |
| 35 | + |
| 36 | + alunoNotas[alunoId].totalNotas += valorNota; |
| 37 | + alunoNotas[alunoId].numeroNotas += 1; |
| 38 | + }); |
| 39 | + |
| 40 | + const ranking = Object.keys(alunoNotas).map(alunoId => { |
| 41 | + const { totalNotas, numeroNotas } = alunoNotas[alunoId]; |
| 42 | + const notaMaximaPossivel = 10 * numeroNotas; |
| 43 | + const rankingNota = totalNotas / notaMaximaPossivel; |
| 44 | + |
| 45 | + return { |
| 46 | + alunoId, |
| 47 | + rankingNota |
| 48 | + }; |
| 49 | + }); |
| 50 | + |
| 51 | + ranking.sort((a, b) => b.rankingNota - a.rankingNota); |
| 52 | + |
| 53 | + const alunos = await prisma.aluno.findMany({ |
| 54 | + where: { |
| 55 | + id: { |
| 56 | + in: ranking.map(r => r.alunoId) |
| 57 | + } |
| 58 | + } |
| 59 | + }); |
| 60 | + |
| 61 | + const rankingDetalhado = ranking.map(rank => { |
| 62 | + const aluno = alunos.find(a => a.id === rank.alunoId); |
| 63 | + return { |
| 64 | + aluno, |
| 65 | + rankingNota: rank.rankingNota |
| 66 | + }; |
| 67 | + }); |
| 68 | + |
| 69 | + return rankingDetalhado; |
| 70 | + } |
| 71 | +} |
0 commit comments