import Team from '../models/team.js'; import { AppErrorMissing, AppErrorInvalid } from '../utils/errors.js'; import User from '../models/user.js'; import Case from '../models/case.js'; import markTypes from '../config/markTypes.js'; import Mark from '../models/mark.js'; import { calculatePositions } from '../scripts/calc-positions.js'; import { getMissingMarks } from '../scripts/no-marks.js'; export default { async get(req, res) { const teams = await Team.findAll({ order: [[{ model: Case, as: 'cases' }, 'name'], ['name']], include: [{ model: Case, as: 'cases' }], }); const marks = await Mark.findAll({ where: { markType: [markTypes.WORK, markTypes.IMPLEMENTATION], teamId: teams.map(t => t.id) }, }); res.json({ teams, marks: { work: marks.filter(m => m.markType === markTypes.WORK).reduce((p, c) => ({ ...p, [c.teamId]: c.mark }), {}), implementation: marks .filter(m => m.markType === markTypes.IMPLEMENTATION) .reduce((p, c) => ({ ...p, [c.teamId]: c.mark }), {}), }, }); }, async save({ body: { marks } }, res) { if (!Array.isArray(marks)) throw new AppErrorMissing('marks'); if (marks.some(m => !m || !m.id || ![m.implementation, m.work].every(v => Number.isInteger(v) && v >= 0 && v <= 5))) throw new AppErrorInvalid('marks'); marks = marks.filter(m => m && m.id && m.implementation !== undefined && m.work !== undefined); if (!marks.length) return res.end(); const teams = await Team.findAll({ where: { id: marks.map(m => m.id) }, attributes: ['id'], include: { model: Case, as: 'cases', attributes: ['id'], through: { attributes: [] }, include: { model: User, as: 'users', attributes: ['id'], through: { attributes: [] } }, }, }); if (teams.length !== marks.length) throw new AppErrorMissing('team'); const byTeamId = Object.fromEntries(marks.map(m => [m.id, m])); for (const team of teams) { const firstCase = team.cases?.[0]; if (!firstCase) continue; const payload = byTeamId[team.id]; if (!payload) continue; const caseId = firstCase.id; const userIds = firstCase.users.map(u => u.id); await Mark.destroy({ where: { teamId: team.id, caseId, userId: userIds, markType: [markTypes.WORK, markTypes.IMPLEMENTATION], }, force: true, }); const rows = []; for (const user of firstCase.users) { rows.push({ teamId: team.id, caseId, userId: user.id, markType: markTypes.IMPLEMENTATION, mark: payload.implementation, }); rows.push({ teamId: team.id, caseId, userId: user.id, markType: markTypes.WORK, mark: payload.work, }); } if (rows.length) await Mark.bulkCreate(rows); } res.end(); }, async noMarks(req, res) { res.json(await getMissingMarks()); }, async calcPositions(req, res) { res.json(await calculatePositions()); }, };