Include complete API and frontend sources for unified deployment
This commit is contained in:
1 parent
627b0ae60e
commit
d8fcae32b0
93 files changed
+53270
-3
No files matched your search
@@ -0,0 +1,105 @@
|
||||
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());
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
import User from '../models/user.js';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { AppErrorInvalid } from '../utils/errors.js';
|
||||
import jwt from '../utils/jwt.js';
|
||||
import prepareUser from '../utils/prepareUser.js';
|
||||
import admin from '../config/admin.js';
|
||||
|
||||
export default {
|
||||
user({ user }, res) {
|
||||
res.json({ user: prepareUser(user) });
|
||||
},
|
||||
|
||||
async login({ body: { login, password } }, res) {
|
||||
if (login === admin.login && password === admin.password) {
|
||||
const { jwt: token } = jwt.generate({ ...prepareUser(admin), sessionId: admin.sessionId });
|
||||
res.json({ user: prepareUser(admin), token });
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await User.findOne({ where: { login } });
|
||||
if (!user || !user.validatePassword(password)) throw new AppErrorInvalid('Login or password', 403);
|
||||
|
||||
const sessionId = uuidv4();
|
||||
const { jwt: token, iat } = jwt.generate({ ...prepareUser(user), sessionId });
|
||||
await user.update({ iat, sessionId });
|
||||
res.json({ user: prepareUser(user), token });
|
||||
},
|
||||
|
||||
async logout({ user }, res) {
|
||||
if (user.id === admin.id) return res.end();
|
||||
await user.update({ iat: null, sessionId: null });
|
||||
res.end();
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
export default {
|
||||
async getAll({ user }, res) {
|
||||
res.json({
|
||||
cases: (user.cases || []).map(task => {
|
||||
const data = task.toJSON();
|
||||
data.teams = data.teams.map(({ TeamInCase, ...team }) => ({
|
||||
...team,
|
||||
technicalComment: TeamInCase?.technicalComment || '',
|
||||
}));
|
||||
return data;
|
||||
}),
|
||||
});
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
import User from '../models/user.js';
|
||||
import Case from '../models/case.js';
|
||||
import { SystemError } from '../utils/errors.js';
|
||||
import { createExpertQrPdf } from '../utils/expert-qr-pdf.js';
|
||||
|
||||
export default async function exportExpertQr({ body }, res) {
|
||||
let url;
|
||||
try {
|
||||
url = new URL(body.baseUrl);
|
||||
} catch (e) {
|
||||
throw new SystemError(400, 'Укажите корректный адрес приложения.');
|
||||
}
|
||||
if (
|
||||
!['http:', 'https:'].includes(url.protocol) ||
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.search ||
|
||||
url.hash ||
|
||||
url.href.length > 300
|
||||
)
|
||||
throw new SystemError(400, 'Укажите адрес приложения без параметров и фрагмента #.');
|
||||
const users = await User.findAll({
|
||||
attributes: ['firstName', 'lastName', 'middleName', 'login', 'passwordForAdmin', 'role'],
|
||||
include: { model: Case, as: 'cases', attributes: ['name'], through: { attributes: [] } },
|
||||
order: [
|
||||
['lastName', 'ASC'],
|
||||
['firstName', 'ASC'],
|
||||
['id', 'ASC'],
|
||||
],
|
||||
});
|
||||
if (!users.length) throw new SystemError(404, 'Нет активных экспертов для экспорта.');
|
||||
if (users.some(user => !user.passwordForAdmin))
|
||||
throw new SystemError(
|
||||
409,
|
||||
'У некоторых экспертов не задан пароль. Задайте пароль в редактировании и повторите экспорт.'
|
||||
);
|
||||
const pdf = await createExpertQrPdf(users, url.href);
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Disposition': 'attachment; filename="experts-qr.pdf"',
|
||||
'Cache-Control': 'private, no-store',
|
||||
});
|
||||
res.send(pdf);
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
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 });
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,62 @@
|
||||
import { models } from '../models/index.js';
|
||||
import markTypesNames from '../config/markTypesNames.js';
|
||||
|
||||
const { Case, Team, User, Mark } = models;
|
||||
export default async function markDetails(req, res) {
|
||||
const cases = await Case.findAll({
|
||||
attributes: ['id', 'name'],
|
||||
include: [
|
||||
{ model: Team, as: 'teams', attributes: ['id', 'name'], through: { attributes: [] } },
|
||||
{
|
||||
model: User,
|
||||
as: 'users',
|
||||
attributes: ['id', 'firstName', 'lastName', 'middleName', 'role'],
|
||||
through: { attributes: [] },
|
||||
},
|
||||
],
|
||||
order: [['name', 'ASC']],
|
||||
});
|
||||
const marks = await Mark.findAll({
|
||||
attributes: ['caseId', 'teamId', 'userId', 'markType', 'mark'],
|
||||
where: { caseId: cases.map(c => c.id) },
|
||||
order: [['updatedAt', 'DESC']],
|
||||
});
|
||||
const lookup = new Map();
|
||||
for (const mark of marks) {
|
||||
const key = `${mark.caseId}:${mark.teamId}:${mark.userId}:${mark.markType}`;
|
||||
if (!lookup.has(key)) lookup.set(key, mark.mark);
|
||||
}
|
||||
const types = Object.keys(markTypesNames);
|
||||
const details = cases.map(task => ({
|
||||
id: task.id,
|
||||
name: task.name,
|
||||
rows: [...task.teams]
|
||||
.sort((a, b) => a.name.localeCompare(b.name, 'ru'))
|
||||
.flatMap(team =>
|
||||
[...task.users]
|
||||
.sort((a, b) => (a.lastName || '').localeCompare(b.lastName || '', 'ru'))
|
||||
.map(user => {
|
||||
const values = Object.fromEntries(
|
||||
types.map(type => [
|
||||
type,
|
||||
user.role === 'technical' && !['20', '30'].includes(type)
|
||||
? null
|
||||
: lookup.get(`${task.id}:${team.id}:${user.id}:${type}`) ?? null,
|
||||
])
|
||||
);
|
||||
const counted = user.role === 'technical' ? [values[20], values[30]] : Object.values(values);
|
||||
const complete = counted.every(value => value !== null);
|
||||
return {
|
||||
teamId: team.id,
|
||||
team: team.name,
|
||||
userId: user.id,
|
||||
role: user.role,
|
||||
expert: [user.lastName, user.firstName, user.middleName].filter(Boolean).join(' '),
|
||||
marks: values,
|
||||
total: complete ? counted.reduce((sum, value) => sum + value, 0) : null,
|
||||
};
|
||||
})
|
||||
),
|
||||
}));
|
||||
res.json({ details, criteria: markTypesNames });
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { AppErrorInvalid, SystemError } from '../utils/errors.js';
|
||||
import markTypes from '../config/markTypes.js';
|
||||
import { sequelize, models } from '../models/index.js';
|
||||
import { editableMarkTypes } from '../utils/expert-roles.js';
|
||||
|
||||
function validateExpertMark(role, markType, mark) {
|
||||
if (!Object.values(markTypes).includes(markType)) throw new AppErrorInvalid('markType');
|
||||
if (!editableMarkTypes(role).includes(markType))
|
||||
throw new SystemError(403, 'Этот критерий недоступен для вашей роли.');
|
||||
if (!Number.isInteger(mark) || mark < 0 || mark > 5) throw new AppErrorInvalid('mark');
|
||||
}
|
||||
|
||||
function accessibleTeam(user, caseId, teamId) {
|
||||
const task = user.cases.find(c => c.id === caseId);
|
||||
if (!task) throw new SystemError(403, 'You do not have access to this case');
|
||||
const team = task.teams.find(t => t.id === teamId);
|
||||
if (!team) throw new SystemError(403, 'You do not have access to this team');
|
||||
return team;
|
||||
}
|
||||
|
||||
async function saveMarks(user, caseId, teamId, entries, technicalComment) {
|
||||
accessibleTeam(user, caseId, teamId);
|
||||
if (technicalComment !== undefined) {
|
||||
if (user.role !== 'technical')
|
||||
throw new SystemError(403, 'Комментарий может редактировать только технический эксперт.');
|
||||
if (typeof technicalComment !== 'string' || technicalComment.length > 5000)
|
||||
throw new AppErrorInvalid('technicalComment');
|
||||
if (entries === undefined) entries = [];
|
||||
}
|
||||
if (!Array.isArray(entries)) throw new AppErrorInvalid('marks');
|
||||
for (const entry of entries) {
|
||||
if (!entry || typeof entry !== 'object') throw new AppErrorInvalid('marks');
|
||||
validateExpertMark(user.role, entry.markType, entry.mark);
|
||||
}
|
||||
if (new Set(entries.map(m => m.markType)).size !== entries.length) throw new AppErrorInvalid('markType');
|
||||
await sequelize.transaction(async transaction => {
|
||||
const task = await models.Case.findByPk(caseId, { transaction, lock: transaction.LOCK.UPDATE });
|
||||
if (!task) throw new SystemError(403, 'You do not have access to this case');
|
||||
const users = await task.getUsers({ transaction });
|
||||
if (!users.some(expert => expert.id === user.id)) throw new SystemError(403, 'You do not have access to this case');
|
||||
const link = await models.TeamInCase.findOne({
|
||||
where: { caseId, teamId },
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
});
|
||||
if (!link) throw new SystemError(403, 'You do not have access to this team');
|
||||
if (technicalComment !== undefined)
|
||||
await link.update({ technicalComment: technicalComment.trim() }, { transaction });
|
||||
// Technical criteria are shared by all experts of the case, including its technical expert.
|
||||
const userIds = user.role === 'technical' ? users.map(expert => expert.id) : [user.id];
|
||||
for (const { markType, mark } of entries) {
|
||||
await models.Mark.destroy({ where: { caseId, teamId, userId: userIds, markType }, force: true, transaction });
|
||||
await models.Mark.bulkCreate(
|
||||
userIds.map(userId => ({ caseId, teamId, userId, markType, mark })),
|
||||
{ transaction }
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export default {
|
||||
async get({ params: { caseId, teamId }, user }, res) {
|
||||
const team = accessibleTeam(user, caseId, teamId);
|
||||
res.json({ marks: team.marks, technicalComment: team.TeamInCase?.technicalComment || '' });
|
||||
},
|
||||
async add({ params: { caseId, teamId }, body: { markType, mark, technicalComment }, user }, res) {
|
||||
await saveMarks(user, caseId, teamId, [{ markType, mark }], technicalComment);
|
||||
res.end();
|
||||
},
|
||||
async addBatch({ params: { caseId, teamId }, body: { marks, technicalComment }, user }, res) {
|
||||
await saveMarks(user, caseId, teamId, marks, technicalComment);
|
||||
res.end();
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
import markType from '../config/markTypes.js';
|
||||
import markTypesNames from '../config/markTypesNames.js';
|
||||
|
||||
export default {
|
||||
appdata(req, res) {
|
||||
res.json({ markType, markTypesNames });
|
||||
},
|
||||
};
|
||||
Reference in new issue
Block a user