import { Op } from 'sequelize'; import { v4 as uuidv4 } from 'uuid'; import { models, sequelize } from '../models/index.js'; import { AppErrorInvalid, AppErrorNotExist, AppErrorAlreadyExists } from '../utils/errors.js'; import transliteration from '../utils/transliteration.js'; import randomPassword from '../utils/random-password.js'; import markTypes from '../config/markTypes.js'; import { validateCaseIcon } from '../utils/case-icon.js'; import { expertRole } from '../utils/expert-roles.js'; import { assignmentCases, assertTechnicalAvailable } from '../utils/case-assignments.js'; const { Case, Team, User, UserInCase, Mark } = models; const include = [ { model: Team, as: 'teams', through: { attributes: ['technicalComment'] } }, { model: User, as: 'users', attributes: ['id', 'firstName', 'lastName', 'middleName', 'login', 'role'], through: { attributes: [] }, }, ]; function fields(body) { if (typeof body.name !== 'string' || !body.name.trim() || body.name.trim().length > 255) throw new AppErrorInvalid('name'); if (body.description !== undefined && (typeof body.description !== 'string' || body.description.length > 10000)) throw new AppErrorInvalid('description'); return { name: body.name.trim(), description: body.description?.trim() || '' }; } function caseFields(body) { return { ...fields(body), ...(body.icon !== undefined ? { icon: validateCaseIcon(body.icon) } : {}) }; } function expertName(body) { const firstName = typeof body.firstName === 'string' ? body.firstName.trim() : ''; const lastName = typeof body.lastName === 'string' ? body.lastName.trim() : ''; const middleName = body.middleName === undefined ? '' : typeof body.middleName === 'string' ? body.middleName.trim() : null; if ( !firstName || !lastName || firstName.length > 50 || lastName.length > 50 || middleName === null || middleName.length > 50 ) throw new AppErrorInvalid('name'); return { firstName, lastName, middleName }; } async function getCase(id, transaction) { const task = await Case.findByPk(id, { transaction }); if (!task) throw new AppErrorNotExist('case'); return task; } function ids(value) { if (!Array.isArray(value) || value.some(id => typeof id !== 'string' || !/^[0-9a-f-]{36}$/i.test(id))) throw new AppErrorInvalid('caseIds'); return [...new Set(value)]; } // Shared criteria remain available when a new expert is assigned after they were saved. async function copyOrganizerMarks(caseId, userIds, transaction) { const existing = await Mark.findAll({ where: { caseId, markType: [markTypes.WORK, markTypes.IMPLEMENTATION] }, order: [['updatedAt', 'ASC']], transaction, }); const template = new Map(existing.map(mark => [`${mark.teamId}:${mark.markType}`, mark])); for (const userId of userIds) for (const mark of template.values()) { const [current] = await Mark.findOrCreate({ where: { caseId, teamId: mark.teamId, userId, markType: mark.markType }, defaults: { mark: mark.mark }, transaction, }); if (current.mark !== mark.mark) await current.update({ mark: mark.mark }, { transaction }); } } export default { async listCases(req, res) { res.json({ cases: await Case.findAll({ include, order: [['name', 'ASC']] }) }); }, async createCase({ body }, res) { const task = await Case.create(caseFields(body)); res.status(201).json({ case: await Case.findByPk(task.id, { include }) }); }, async updateCase({ params, body }, res) { const task = await getCase(params.caseId); await task.update(caseFields(body)); res.json({ case: await Case.findByPk(task.id, { include }) }); }, async createTeam({ params, body }, res) { const payload = fields(body); const team = await sequelize.transaction(async transaction => { const task = await getCase(params.caseId, transaction); const team = await Team.create(payload, { transaction }); await task.addTeam(team, { transaction }); return team; }); res.status(201).json({ team }); }, async updateTeam({ params, body }, res) { const task = await getCase(params.caseId); const [team] = await task.getTeams({ where: { id: params.teamId } }); if (!team) throw new AppErrorNotExist('team'); await team.update(fields(body)); res.json({ team }); }, async listUsers(req, res) { res.json({ users: await User.findAll({ attributes: ['id', 'firstName', 'lastName', 'middleName', 'login', 'role', 'passwordForAdmin', 'deletedAt'], paranoid: false, include: { model: Case, as: 'cases', attributes: ['id', 'name'], through: { attributes: [] } }, order: [['firstName', 'ASC']], }), }); }, async createUser({ body }, res) { const { firstName, lastName, middleName } = expertName(body); const role = expertRole(body.role); const caseIds = body.caseIds === undefined ? [] : ids(body.caseIds); const result = await sequelize.transaction(async transaction => { const tasks = await assignmentCases(caseIds, transaction); let user = await User.findOne({ where: { firstName, lastName, ...(middleName ? { middleName } : { [Op.or]: [{ middleName: null }, { middleName: '' }] }), }, paranoid: false, transaction, }); const created = !user; if (user) { if (body.role !== undefined && user.role !== role) throw new AppErrorAlreadyExists('expert'); const previous = await user.getCases({ transaction }); const allTasks = await assignmentCases( [...new Set([...caseIds, ...previous.map(task => task.id)])], transaction ); await assertTechnicalAvailable(user, allTasks, transaction); if (user.deletedAt) await user.restore({ transaction }); } else { const password = await randomPassword(); let login = transliteration(lastName).replace(/[^a-z0-9_-]/gi, '') || 'expert'; if (await User.findOne({ where: { login }, paranoid: false, transaction })) login += '-' + uuidv4().slice(0, 8); user = await User.create( { firstName, lastName, middleName, login, role, password, passwordForAdmin: password }, { transaction } ); } await assertTechnicalAvailable(user, tasks, transaction); await user.addCases(tasks, { transaction }); for (const caseId of caseIds) await copyOrganizerMarks(caseId, [user.id], transaction); return { user, created }; }); res .status(result.created ? 201 : 200) .json({ user: { id: result.user.id, firstName, lastName, role: result.user.role, login: result.user.login } }); }, async updateUser({ params, body }, res) { const user = await User.findByPk(params.userId); if (!user) throw new AppErrorNotExist('user'); const names = expertName(body); const login = typeof body.login === 'string' ? body.login.trim() : ''; if (!/^[a-z0-9_.@-]{2,100}$/i.test(login) || login.toLowerCase() === 'admin') throw new AppErrorInvalid('login'); if (await User.findOne({ where: { login, id: { [Op.ne]: user.id } }, paranoid: false })) throw new AppErrorAlreadyExists('login'); const role = expertRole(body.role === undefined ? user.role : body.role); const payload = { ...names, login, role, iat: null, sessionId: null }; if (body.password !== undefined && body.password !== '') { if ( typeof body.password !== 'string' || body.password.length < 6 || Buffer.byteLength(body.password, 'utf8') > 72 ) throw new AppErrorInvalid('password'); payload.password = body.password; payload.passwordForAdmin = body.password; } await sequelize.transaction(async transaction => { const previous = await user.getCases({ transaction }); const tasks = await assignmentCases( previous.map(task => task.id), transaction ); await assertTechnicalAvailable({ id: user.id, role }, tasks, transaction); await user.update(payload, { transaction }); }); res.json({ user: { id: user.id, ...names, login, role } }); }, async deleteUser({ params }, res) { await sequelize.transaction(async transaction => { const user = await User.findByPk(params.userId, { transaction }); if (!user) throw new AppErrorNotExist('user'); await user.update({ iat: null, sessionId: null }, { transaction }); await user.destroy({ transaction }); }); res.status(204).end(); }, async restoreUser({ params }, res) { const user = await User.findByPk(params.userId, { paranoid: false }); if (!user) throw new AppErrorNotExist('user'); if (user.deletedAt) { await sequelize.transaction(async transaction => { const previous = await user.getCases({ transaction }); const tasks = await assignmentCases( previous.map(task => task.id), transaction ); await assertTechnicalAvailable(user, tasks, transaction); await user.restore({ transaction }); await user.update({ iat: null, sessionId: null }, { transaction }); }); } res.json({ ok: true }); }, async assignUser({ params, body }, res) { const caseIds = ids(body.caseIds); await sequelize.transaction(async transaction => { const user = await User.findByPk(params.userId, { transaction }); if (!user) throw new AppErrorNotExist('user'); const tasks = await assignmentCases(caseIds, transaction); await assertTechnicalAvailable(user, tasks, transaction); // Hard-delete only join rows, preserving every case, user and historical mark. await UserInCase.destroy({ where: { userId: user.id }, force: true, transaction }); await user.addCases(tasks, { transaction }); for (const caseId of caseIds) await copyOrganizerMarks(caseId, [user.id], transaction); }); res.json({ ok: true }); }, };