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,6 @@
|
||||
node_modules
|
||||
.env
|
||||
.idea
|
||||
.git
|
||||
*.log
|
||||
config/google-credentials.js
|
||||
@@ -0,0 +1,13 @@
|
||||
# editorconfig.org
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = tab
|
||||
indent_size = 2
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"env": {
|
||||
"node": true,
|
||||
"es2021": true
|
||||
},
|
||||
"extends": ["eslint:recommended", "plugin:prettier/recommended"],
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 12,
|
||||
"sourceType": "module"
|
||||
},
|
||||
"plugins": ["prettier"],
|
||||
"rules": {
|
||||
"prettier/prettier": "error",
|
||||
"no-prototype-builtins": "off"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
node_modules/
|
||||
.env
|
||||
.idea/
|
||||
.DS_Store
|
||||
*.log
|
||||
config/google-credentials.js
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"semi": true,
|
||||
"arrowParens": "avoid",
|
||||
"singleQuote": true,
|
||||
"trailingComma": "es5",
|
||||
"bracketSpacing": true,
|
||||
"endOfLine": "lf",
|
||||
"printWidth": 120,
|
||||
"useTabs": true,
|
||||
"tabWidth": 2
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
FROM node:18-bookworm-slim
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm ci --omit=dev
|
||||
COPY . .
|
||||
EXPOSE 3080
|
||||
CMD ["npm", "start"]
|
||||
@@ -0,0 +1,182 @@
|
||||
{
|
||||
"info": {
|
||||
"_postman_id": "33592a8c-7533-4010-bcba-8fef741d8235",
|
||||
"name": "Hackathon",
|
||||
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
|
||||
},
|
||||
"item": [
|
||||
{
|
||||
"name": "Login",
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"header": [],
|
||||
"body": {
|
||||
"mode": "raw",
|
||||
"raw": "{\n \"login\": \"admin\",\n \"password\": \"123\"\n}",
|
||||
"options": {
|
||||
"raw": {
|
||||
"language": "json"
|
||||
}
|
||||
}
|
||||
},
|
||||
"url": {
|
||||
"raw": "{{domain}}/auth/login",
|
||||
"host": [
|
||||
"{{domain}}"
|
||||
],
|
||||
"path": [
|
||||
"auth",
|
||||
"login"
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": []
|
||||
},
|
||||
{
|
||||
"name": "Cases",
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"header": [],
|
||||
"url": {
|
||||
"raw": "{{domain}}/cases",
|
||||
"host": [
|
||||
"{{domain}}"
|
||||
],
|
||||
"path": [
|
||||
"cases"
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": []
|
||||
},
|
||||
{
|
||||
"name": "Marks",
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"header": [],
|
||||
"url": {
|
||||
"raw": "{{domain}}/cases/:caseId/teams/:teamId/marks",
|
||||
"host": [
|
||||
"{{domain}}"
|
||||
],
|
||||
"path": [
|
||||
"cases",
|
||||
":caseId",
|
||||
"teams",
|
||||
":teamId",
|
||||
"marks"
|
||||
],
|
||||
"variable": [
|
||||
{
|
||||
"key": "caseId",
|
||||
"value": "514182cb-f12c-4224-8575-52dc392fc382"
|
||||
},
|
||||
{
|
||||
"key": "teamId",
|
||||
"value": "b25dd515-2124-492d-8eb5-d60617952946"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": []
|
||||
},
|
||||
{
|
||||
"name": "Marks",
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"header": [],
|
||||
"body": {
|
||||
"mode": "raw",
|
||||
"raw": "{\n \"markType\": 20,\n \"mark\": 3\n}",
|
||||
"options": {
|
||||
"raw": {
|
||||
"language": "json"
|
||||
}
|
||||
}
|
||||
},
|
||||
"url": {
|
||||
"raw": "{{domain}}/cases/:caseId/teams/:teamId/marks",
|
||||
"host": [
|
||||
"{{domain}}"
|
||||
],
|
||||
"path": [
|
||||
"cases",
|
||||
":caseId",
|
||||
"teams",
|
||||
":teamId",
|
||||
"marks"
|
||||
],
|
||||
"variable": [
|
||||
{
|
||||
"key": "caseId",
|
||||
"value": "514182cb-f12c-4224-8575-52dc392fc382"
|
||||
},
|
||||
{
|
||||
"key": "teamId",
|
||||
"value": "cd17366c-efd5-4601-a530-c4fe59088503"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": []
|
||||
},
|
||||
{
|
||||
"name": "Logout",
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"header": [],
|
||||
"url": {
|
||||
"raw": "{{domain}}/auth/logout",
|
||||
"host": [
|
||||
"{{domain}}"
|
||||
],
|
||||
"path": [
|
||||
"auth",
|
||||
"logout"
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": []
|
||||
}
|
||||
],
|
||||
"auth": {
|
||||
"type": "bearer",
|
||||
"bearer": [
|
||||
{
|
||||
"key": "token",
|
||||
"value": "{{token}}",
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
"event": [
|
||||
{
|
||||
"listen": "prerequest",
|
||||
"script": {
|
||||
"type": "text/javascript",
|
||||
"exec": [
|
||||
""
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"listen": "test",
|
||||
"script": {
|
||||
"type": "text/javascript",
|
||||
"exec": [
|
||||
""
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"variable": [
|
||||
{
|
||||
"key": "domain",
|
||||
"value": "http://localhost:3000"
|
||||
},
|
||||
{
|
||||
"key": "token",
|
||||
"value": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
# Hackathon grading API
|
||||
|
||||
Express + Sequelize + MySQL. В локальном окружении используется корневой Docker Compose.
|
||||
|
||||
## Управление
|
||||
|
||||
Все `/admin/*` требуют токен администратора.
|
||||
|
||||
- `GET /admin/cases`, `POST /admin/cases` — список и создание кейсов (`name`, `description`).
|
||||
- `PUT /admin/cases/:id` — изменение кейса.
|
||||
- `POST /admin/cases/:id/teams`, `PUT /admin/cases/:id/teams/:teamId` — создание и изменение команд (`name`, `description`).
|
||||
- `GET /admin/users`, `POST /admin/users` — эксперты и создание (`firstName`, `lastName`). Ответ списка включает назначенные `cases`, без хеша пароля и токена сессии.
|
||||
- `PUT /admin/users/:userId/cases` — заменить назначения (`caseIds: string[]`). Пустой список снимает назначения. Сами кейсы, команды, эксперты и оценки сохраняются. Повторное назначение поддерживается. При добавлении эксперта копируются уже заполненные оценки организатора.
|
||||
- `GET /admin`, `POST /admin` — оценки организатора, прежний формат.
|
||||
- `GET /admin/positions`, `GET /admin/marks` — рейтинг и пропущенные / нулевые оценки.
|
||||
|
||||
## Результаты
|
||||
|
||||
API напрямую использует функции `calculatePositions` из `scripts/calc-positions.js` и `getMissingMarks` из `scripts/no-marks.js`, без запуска дочерних процессов и повторной инициализации БД. Те же файлы остаются консольными командами:
|
||||
|
||||
```bash
|
||||
npm run show:positions
|
||||
npm run show:nomarks
|
||||
```
|
||||
|
||||
Проверка пропусков возвращает код 1, если не все критерии заполнены. Оценки учитываются внутри своего кейса; в рейтинге участвуют только текущие назначения экспертов и команд. Алгоритм мест сохранён: сумма баллов определяет место команды у каждого эксперта, сумма этих мест определяет итоговое место.
|
||||
|
||||
`scripts/export-marks-to-google.js` остаётся отдельным экспортом, требующим Google credentials и доступа к таблице. Интерфейс не запускает экспорт во внешнюю таблицу.
|
||||
|
||||
Секреты `.env` и `config/google-credentials.js` исключены из Git и Docker-образа.
|
||||
|
||||
## Проверка управления
|
||||
|
||||
На запущенном локальном Compose из корневой папки:
|
||||
|
||||
```bash
|
||||
docker compose --env-file .env.local exec -T api node tests/admin-workflow.js
|
||||
```
|
||||
|
||||
Тест создаёт временные кейс, команду и экспертов, проверяет назначения и повторные назначения, права доступа, критерии организатора и совпадение результатов API с функциями скриптов. Временные записи удаляются в `finally`; схема БД тестом не изменяется.
|
||||
|
||||
## Эксперты и QR-коды
|
||||
|
||||
- `PUT /admin/users/:userId` — изменить `firstName`, `lastName`, необязательное `middleName`, `login` и необязательный `password`. Пустой пароль оставляет текущий. Логин уникален, новый пароль — от 6 символов и не более 72 байт UTF-8. Изменение завершает действующие сессии эксперта.
|
||||
- `DELETE /admin/users/:userId` — мягкое удаление с закрытием доступа. Кейсы, назначения и оценки сохраняются.
|
||||
- `POST /admin/users/:userId/restore` — восстановление.
|
||||
- `POST /admin/users/qr-pdf`, тело `{ "baseUrl": "https://grading.example.ru/" }` — скачивание PDF всех активных экспертов. Параметр — адрес приложения без query и hash; в QR добавляется `#/login?l=...&p=...`. Если пароль для выдачи отсутствует, API возвращает 409 с просьбой задать его через редактирование.
|
||||
|
||||
PDF создаётся локально, без внешних сервисов: A4, 3 × 4 карточки на страницу, векторные QR с полями и ФИО под каждым кодом. Технические эксперты идут первыми; под их ФИО указаны назначенные кейсы. Остальные эксперты начинаются с нового листа A4. Роли не смешиваются на одном листе; горизонтального разделителя нет. Заголовки «Тех. эксперты» и «Эксперты» повторяются на страницах соответствующей группы. Кириллица поддерживается включённым шрифтом DejaVu Sans (лицензия в `assets/fonts/`). Экспорт доступен только администратору, ответ запрещает кеширование. Указывайте адрес, доступный с телефонов экспертов.
|
||||
|
||||
Поля `middleName` и `sessionId` добавляются существующим механизмом `sync({ alter: true })` при старте. UUID сессии не даёт старому токену ожить после повторного входа в ту же секунду.
|
||||
|
||||
```bash
|
||||
docker compose --env-file .env.local exec -T api node tests/expert-lifecycle.js
|
||||
node tests/qr-pdf.js
|
||||
```
|
||||
|
||||
Дополнительно проверены декодирование всех 25 QR-кодов на трёх страницах PDF, кириллические подписи и скачивание файла через браузер.
|
||||
|
||||
Иконка кейса: поле `icon` в POST/PUT `/admin/cases` — `data:image/png;base64,...`, `null` удаляет иконку, отсутствие поля в PUT сохраняет текущую. Принимаются реальные PNG до 1 МБ и не более 1024 × 1024 пикселей; подпись, размеры и содержимое проверяются сервером. Значение хранится в БД. Для назначенного эксперта иконка возвращается в `/cases`.
|
||||
|
||||
`GET /admin/marks/details` возвращает `criteria` и массив `details`: кейсы с рядами для каждой текущей пары команда — эксперт. Каждый ряд содержит `teamId`, `team`, `userId`, `expert`, `marks` по пяти типам и `total`. Пропуск — `null`, нулевая оценка — `0`. Сумма — `null`, пока не заполнены все пять критериев. Учётные данные в отчёт не включаются.
|
||||
|
||||
Проверка: `node tests/icons-and-mark-details.js` на запущенном API с настроенной БД. Тестовые записи удаляются автоматически.
|
||||
|
||||
При создании эксперта `POST /admin/users` принимает необязательный массив `caseIds`. Создание и назначения сохраняются одной транзакцией; неизвестный кейс возвращает 400 без создания эксперта. Можно передать пустой массив или не указывать поле. При повторном добавлении существующего эксперта выбранные кейсы добавляются к его назначениям.
|
||||
|
||||
Роль эксперта: `role: "expert" | "technical"` в POST/PUT `/admin/users`, по умолчанию `expert`. Возвращается при входе, в `/auth/user`, списках пользователей/назначений и детализации оценок. Технический эксперт назначается через те же `caseIds`, максимум один активный на кейс. Конфликт назначения, восстановления или смены роли возвращает 409 без частичного сохранения. Технический эксперт может POST/PUT только критерии 20 и 30 назначенных команд; обычный — только 10, 40 и 50. Проверка прав выполняется сервером. Технические оценки распространяются на всех назначенных экспертов. Технический эксперт исключён как отдельный голос из `calc-positions.js`; отчёт `no-marks.js` учитывает критерии роли.
|
||||
|
||||
Комментарий технического эксперта хранится в `teams_in_cases.technical_comment` отдельно для каждой команды и кейса. `GET /cases` возвращает `teams[].technicalComment`, `GET /cases/:caseId/teams/:teamId/marks` — `{ marks, technicalComment }`. Технический эксперт может передать необязательный `technicalComment` (строка до 5000 символов, пустая строка очищает) в PUT/POST оценок; обычному эксперту изменение запрещено (403). PUT с одним комментарием или `marks: []` не меняет оценки. Отсутствие поля сохраняет прежний комментарий. Текст и оценки обновляются одной транзакцией, доступ ограничен назначенным кейсом.
|
||||
Binary file not shown.
@@ -0,0 +1,78 @@
|
||||
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
|
||||
Upstream-Name: DejaVu fonts
|
||||
Upstream-Author: Stepan Roh <src@users.sourceforge.net> (original author),
|
||||
see /usr/share/doc/fonts-dejavu-core/AUTHORS for full list
|
||||
Source: https://dejavu-fonts.github.io/
|
||||
|
||||
Files: *
|
||||
Copyright: Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved.
|
||||
Bitstream Vera is a trademark of Bitstream, Inc.
|
||||
DejaVu changes are in public domain.
|
||||
License: bitstream-vera
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of the fonts accompanying this license ("Fonts") and associated
|
||||
documentation files (the "Font Software"), to reproduce and distribute the
|
||||
Font Software, including without limitation the rights to use, copy, merge,
|
||||
publish, distribute, and/or sell copies of the Font Software, and to permit
|
||||
persons to whom the Font Software is furnished to do so, subject to the
|
||||
following conditions:
|
||||
.
|
||||
The above copyright and trademark notices and this permission notice shall
|
||||
be included in all copies of one or more of the Font Software typefaces.
|
||||
.
|
||||
The Font Software may be modified, altered, or added to, and in particular
|
||||
the designs of glyphs or characters in the Fonts may be modified and
|
||||
additional glyphs or characters may be added to the Fonts, only if the fonts
|
||||
are renamed to names not containing either the words "Bitstream" or the word
|
||||
"Vera".
|
||||
.
|
||||
This License becomes null and void to the extent applicable to Fonts or Font
|
||||
Software that has been modified and is distributed under the "Bitstream
|
||||
Vera" names.
|
||||
.
|
||||
The Font Software may be sold as part of a larger software package but no
|
||||
copy of one or more of the Font Software typefaces may be sold by itself.
|
||||
.
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
|
||||
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
|
||||
FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
|
||||
ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
|
||||
THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
|
||||
FONT SOFTWARE.
|
||||
.
|
||||
Except as contained in this notice, the names of Gnome, the Gnome
|
||||
Foundation, and Bitstream Inc., shall not be used in advertising or
|
||||
otherwise to promote the sale, use or other dealings in this Font Software
|
||||
without prior written authorization from the Gnome Foundation or Bitstream
|
||||
Inc., respectively. For further information, contact: fonts at gnome dot
|
||||
org.
|
||||
|
||||
Files: debian/*
|
||||
Copyright: (C) 2005-2006 Peter Cernak <pce@users.sourceforge.net>
|
||||
(C) 2006-2011 Davide Viti <zinosat@tiscali.it>
|
||||
(C) 2011-2013 Christian Perrier <bubulle@debian.org>
|
||||
(C) 2013 Fabian Greffrath <fabian+debian@greffrath.com>
|
||||
License: GPL-2+
|
||||
This program is free software; you can redistribute it
|
||||
and/or modify it under the terms of the GNU General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later
|
||||
version.
|
||||
.
|
||||
This program is distributed in the hope that it will be
|
||||
useful, but WITHOUT ANY WARRANTY; without even the implied
|
||||
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
|
||||
PURPOSE. See the GNU General Public License for more
|
||||
details.
|
||||
.
|
||||
You should have received a copy of the GNU General Public
|
||||
License along with this package; if not, write to the Free
|
||||
Software Foundation, Inc., 51 Franklin St, Fifth Floor,
|
||||
Boston, MA 02110-1301 USA
|
||||
.
|
||||
On Debian systems, the full text of the GNU General Public
|
||||
License version 2 can be found in the file
|
||||
/usr/share/common-licenses/GPL-2'.
|
||||
@@ -0,0 +1,12 @@
|
||||
import 'dotenv/config';
|
||||
import { createHmac } from 'node:crypto';
|
||||
|
||||
const password = process.env.ADMIN_PASSWORD;
|
||||
if (!password) throw new Error('ADMIN_PASSWORD is required');
|
||||
|
||||
export default {
|
||||
id: '77b12261-43b2-45d4-9473-fbd4141b8857',
|
||||
login: 'admin',
|
||||
password,
|
||||
sessionId: createHmac('sha256', process.env.JWT_KEY).update(password).digest('hex'),
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
export default {
|
||||
NotExist: {
|
||||
errNum: 201,
|
||||
errCode: 'NotExist',
|
||||
message: "Something parameter doesn't exist",
|
||||
},
|
||||
AlreadyExists: {
|
||||
errNum: 202,
|
||||
errCode: 'OrderAlreadyExists',
|
||||
message: 'Something parameter already exists',
|
||||
},
|
||||
Missing: {
|
||||
errNum: 203,
|
||||
errCode: 'Missing',
|
||||
message: 'Something parameter are missing',
|
||||
},
|
||||
Invalid: {
|
||||
errNum: 204,
|
||||
errCode: 'Invalid',
|
||||
message: 'Some parameter is invalid',
|
||||
},
|
||||
Duplicate: {
|
||||
errNum: 205,
|
||||
errCode: 'Duplicate',
|
||||
message: 'Some field is not unique',
|
||||
},
|
||||
|
||||
NoFileUploaded: {
|
||||
errNum: 300,
|
||||
errCode: 'NoFileUploaded',
|
||||
message: 'No file uploaded',
|
||||
key: 'no_file_uploaded',
|
||||
},
|
||||
FileExtensionNotAllowed: {
|
||||
errNum: 301,
|
||||
errCode: 'FileExtensionNotAllowed',
|
||||
message: 'File extension is not allowed',
|
||||
key: 'file_extension_not_allowed',
|
||||
},
|
||||
FileTooLarge: {
|
||||
errNum: 302,
|
||||
errCode: 'FileTooLarge',
|
||||
message: 'File too large',
|
||||
key: 'file_too_large',
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
export default {
|
||||
IMMERSION: 10,
|
||||
IMPLEMENTATION: 20,
|
||||
WORK: 30,
|
||||
TEAM: 40,
|
||||
PRESENTATION: 50,
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
export default {
|
||||
10: 'Погруженность в проект',
|
||||
20: 'Качество реализации',
|
||||
30: 'Работа на хакатоне',
|
||||
40: 'Перспективность команды',
|
||||
50: 'Презентация проекта',
|
||||
};
|
||||
@@ -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 });
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
version: "3"
|
||||
|
||||
services:
|
||||
db:
|
||||
image: mysql:8
|
||||
command: --default-authentication-plugin=mysql_native_password --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
|
||||
ports:
|
||||
- 3306:3306
|
||||
environment:
|
||||
MYSQL_DATABASE: grading
|
||||
MYSQL_USER: grading
|
||||
MYSQL_PASSWORD: grading
|
||||
MYSQL_ROOT_PASSWORD: grading
|
||||
@@ -0,0 +1,84 @@
|
||||
import dotenv from 'dotenv';
|
||||
dotenv.config();
|
||||
import express from 'express';
|
||||
import logger from 'morgan';
|
||||
import { initializeDbModels } from './utils/db.js';
|
||||
import { AppError, SystemError } from './utils/errors.js';
|
||||
import corsMiddleware from './middlewares/cors.js';
|
||||
|
||||
import authRoute from './routes/auth.js';
|
||||
import casesRoute from './routes/cases.js';
|
||||
import systemRoute from './routes/system.js';
|
||||
import adminRoute from './routes/admin.js';
|
||||
|
||||
const app = express();
|
||||
|
||||
logger.token('body', req => {
|
||||
try {
|
||||
if (req.method === 'POST' || req.method === 'PUT') {
|
||||
return JSON.stringify(req.body);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} catch (e) {
|
||||
return 'Body parse error ' + e?.message ?? e;
|
||||
}
|
||||
});
|
||||
|
||||
if (app.get('env') === 'production') {
|
||||
app.use(
|
||||
logger('[:date[clf]] :method :url :status :response-time ms', {
|
||||
skip: req => req.baseUrl === '/system',
|
||||
})
|
||||
);
|
||||
} else if (app.get('env') === 'development' || app.get('env') === 'staging') {
|
||||
app.use(
|
||||
logger('[:date[clf]] :method :url :status :body :response-time ms', {
|
||||
skip: req => req.baseUrl === '/system',
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
app.use(express.json({ limit: '10mb' }));
|
||||
app.use(express.urlencoded({ extended: false }));
|
||||
|
||||
// ==== on server start functions
|
||||
(async function initDb() {
|
||||
try {
|
||||
await initializeDbModels();
|
||||
} catch (e) {
|
||||
if (app.get('env') !== 'test') {
|
||||
console.log(e);
|
||||
console.log('COULD NOT CONNECT TO THE DB, retrying in 5 seconds');
|
||||
}
|
||||
setTimeout(initDb, 5000);
|
||||
}
|
||||
})();
|
||||
// ====
|
||||
|
||||
app.use(corsMiddleware);
|
||||
|
||||
app.use('/system', systemRoute);
|
||||
app.use('/auth', authRoute);
|
||||
app.use('/cases', casesRoute);
|
||||
app.use('/admin', adminRoute);
|
||||
|
||||
// Handle 404 AND 500
|
||||
app
|
||||
.use((req, res) => res.status(404).json({ type: 'NOT FOUND', code: 404 }))
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
.use((error, req, res, next) => {
|
||||
console.error(error);
|
||||
|
||||
if (error instanceof AppError || error instanceof SystemError) {
|
||||
res.status(error.status).json(error.toJSON());
|
||||
} else if (error instanceof Error) {
|
||||
res.status(500).json({ message: error.message });
|
||||
} else if (error) {
|
||||
res.status(500).json(error);
|
||||
} else {
|
||||
res.status(500).json({ message: 'INTERNAL SERVER ERROR' });
|
||||
}
|
||||
});
|
||||
|
||||
app.listen(process.env.PORT || 3080, () => console.log('Listen on :' + (process.env.PORT || 3080)));
|
||||
@@ -0,0 +1,7 @@
|
||||
import cors from 'cors';
|
||||
|
||||
export default cors({
|
||||
credentials: true,
|
||||
origin: '*',
|
||||
exposedHeaders: '*',
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import jwt from '../utils/jwt.js';
|
||||
import User from '../models/user.js';
|
||||
import Case from '../models/case.js';
|
||||
import Team from '../models/team.js';
|
||||
import Mark from '../models/mark.js';
|
||||
import { AppErrorInvalid, asyncRoute } from '../utils/errors.js';
|
||||
import admin from '../config/admin.js';
|
||||
|
||||
export default asyncRoute(async (req, res, next) => {
|
||||
if (!req.headers.authorization || req.headers.authorization.split(' ')[0] !== 'Bearer')
|
||||
throw new AppErrorInvalid('token', 401);
|
||||
|
||||
try {
|
||||
req.user = jwt.verify(req.headers.authorization.split(' ')[1]);
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
throw new AppErrorInvalid('token', 401);
|
||||
}
|
||||
|
||||
if (req.user.id === admin.id) {
|
||||
if (req.user.sessionId !== admin.sessionId) throw new AppErrorInvalid('token', 401);
|
||||
req.isAdmin = true;
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await User.findByPk(req.user.id, {
|
||||
order: [
|
||||
[{ model: Case, as: 'cases' }, 'name'],
|
||||
[{ model: Case, as: 'cases' }, { model: Team, as: 'teams' }, 'name'],
|
||||
],
|
||||
include: {
|
||||
model: Case,
|
||||
as: 'cases',
|
||||
attributes: ['id', 'name', 'description', 'icon'],
|
||||
through: { attributes: [] },
|
||||
include: {
|
||||
model: Team,
|
||||
as: 'teams',
|
||||
order: 'name',
|
||||
attributes: ['id', 'name', 'description'],
|
||||
through: { attributes: ['technicalComment'] },
|
||||
include: {
|
||||
model: Mark,
|
||||
as: 'marks',
|
||||
attributes: ['id', 'markType', 'mark'],
|
||||
required: false,
|
||||
where: { userId: req.user.id },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!user || req.user.iat !== +user.iat || (user.sessionId && req.user.sessionId !== user.sessionId))
|
||||
throw new AppErrorInvalid('token', 401);
|
||||
|
||||
req.user = user;
|
||||
next();
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import sequelize from 'sequelize';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
const { DataTypes, Model } = sequelize;
|
||||
|
||||
export default class Case extends Model {
|
||||
static initialize(sequelize) {
|
||||
Case.init(
|
||||
{
|
||||
id: { type: DataTypes.UUID, primaryKey: true },
|
||||
|
||||
name: { type: DataTypes.STRING },
|
||||
description: { type: DataTypes.TEXT },
|
||||
icon: { type: DataTypes.TEXT('medium'), allowNull: true },
|
||||
},
|
||||
{
|
||||
sequelize,
|
||||
modelName: 'Case',
|
||||
tableName: 'cases',
|
||||
}
|
||||
);
|
||||
|
||||
Case.beforeCreate(c => {
|
||||
c.id = uuidv4();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import {} from 'dotenv/config';
|
||||
import { Sequelize } from 'sequelize';
|
||||
import User from './user.js';
|
||||
import Team from './team.js';
|
||||
import Case from './case.js';
|
||||
import Mark from './mark.js';
|
||||
import UserInCase from './userInCase.js';
|
||||
import TeamInCase from './teamInCase.js';
|
||||
|
||||
const { DB_NAME, DB_USER, DB_PWD, DB_HOST } = process.env;
|
||||
|
||||
export const models = {
|
||||
Case,
|
||||
Team,
|
||||
User,
|
||||
Mark,
|
||||
UserInCase,
|
||||
TeamInCase,
|
||||
};
|
||||
|
||||
export const sequelize = new Sequelize(DB_NAME, DB_USER, DB_PWD, {
|
||||
host: DB_HOST,
|
||||
dialect: 'mysql',
|
||||
dialectOptions: { multipleStatements: true },
|
||||
define: {
|
||||
charset: 'utf8mb4',
|
||||
collate: 'utf8mb4_unicode_ci',
|
||||
timestamps: true,
|
||||
underscored: true,
|
||||
paranoid: true,
|
||||
},
|
||||
logging: false,
|
||||
});
|
||||
|
||||
export default { sequelize, models };
|
||||
@@ -0,0 +1,36 @@
|
||||
import sequelize from 'sequelize';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import markTypes from '../config/markTypes.js';
|
||||
|
||||
const { DataTypes, Model } = sequelize;
|
||||
|
||||
export default class Mark extends Model {
|
||||
static initialize(sequelize) {
|
||||
Mark.init(
|
||||
{
|
||||
id: { type: DataTypes.UUID, primaryKey: true },
|
||||
|
||||
markType: {
|
||||
type: DataTypes.TINYINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
validate: { isIn: [Object.values(markTypes)] },
|
||||
},
|
||||
|
||||
mark: { type: DataTypes.TINYINT.UNSIGNED, validate: { min: 0, max: 10 } },
|
||||
},
|
||||
{
|
||||
sequelize,
|
||||
modelName: 'Mark',
|
||||
tableName: 'marks',
|
||||
}
|
||||
);
|
||||
|
||||
Mark.beforeCreate(m => {
|
||||
m.id = uuidv4();
|
||||
});
|
||||
|
||||
Mark.beforeBulkCreate(ms => {
|
||||
for (const m of ms) m.id = uuidv4();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { models } from './index.js';
|
||||
const { User, Team, Case, Mark, UserInCase, TeamInCase } = models;
|
||||
|
||||
export default function () {
|
||||
Mark.belongsTo(Team, { foreignKey: { name: 'teamId', allowNull: false }, as: 'team' });
|
||||
Team.hasMany(Mark, { foreignKey: { name: 'teamId', allowNull: false }, as: 'marks' });
|
||||
|
||||
Mark.belongsTo(User, { foreignKey: { name: 'userId', allowNull: false }, as: 'user' });
|
||||
User.hasMany(Mark, { foreignKey: { name: 'userId', allowNull: false }, as: 'marks' });
|
||||
|
||||
Mark.belongsTo(Case, { foreignKey: { name: 'caseId', allowNull: false }, as: 'case' });
|
||||
Case.hasMany(Mark, { foreignKey: { name: 'caseId', allowNull: false }, as: 'marks' });
|
||||
|
||||
Case.belongsToMany(User, { through: UserInCase, foreignKey: { name: 'caseId', allowNull: false }, as: 'users' });
|
||||
User.belongsToMany(Case, { through: UserInCase, foreignKey: { name: 'userId', allowNull: false }, as: 'cases' });
|
||||
|
||||
UserInCase.belongsTo(User, { foreignKey: { name: 'userId', allowNull: false }, as: 'user' });
|
||||
User.hasMany(UserInCase, { foreignKey: { name: 'userId', allowNull: false }, as: 'usersInCases' });
|
||||
|
||||
UserInCase.belongsTo(Case, { foreignKey: { name: 'caseId', allowNull: false }, as: 'case' });
|
||||
Case.hasMany(UserInCase, { foreignKey: { name: 'caseId', allowNull: false }, as: 'usersInCases' });
|
||||
|
||||
Case.belongsToMany(Team, { through: TeamInCase, foreignKey: { name: 'caseId', allowNull: false }, as: 'teams' });
|
||||
Team.belongsToMany(Case, { through: TeamInCase, foreignKey: { name: 'teamId', allowNull: false }, as: 'cases' });
|
||||
|
||||
TeamInCase.belongsTo(Team, { foreignKey: { name: 'teamId', allowNull: false }, as: 'team' });
|
||||
Team.hasMany(TeamInCase, { foreignKey: { name: 'teamId', allowNull: false }, as: 'teamsInCases' });
|
||||
|
||||
TeamInCase.belongsTo(Case, { foreignKey: { name: 'caseId', allowNull: false }, as: 'case' });
|
||||
Case.hasMany(TeamInCase, { foreignKey: { name: 'caseId', allowNull: false }, as: 'teamsInCases' });
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import sequelize from 'sequelize';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
const { DataTypes, Model } = sequelize;
|
||||
|
||||
export default class Team extends Model {
|
||||
static initialize(sequelize) {
|
||||
Team.init(
|
||||
{
|
||||
id: { type: DataTypes.UUID, primaryKey: true },
|
||||
|
||||
name: { type: DataTypes.STRING },
|
||||
description: { type: DataTypes.TEXT },
|
||||
},
|
||||
{
|
||||
sequelize,
|
||||
modelName: 'Team',
|
||||
tableName: 'teams',
|
||||
}
|
||||
);
|
||||
|
||||
Team.beforeCreate(t => {
|
||||
t.id = uuidv4();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import sequelize from 'sequelize';
|
||||
const { Model, DataTypes } = sequelize;
|
||||
|
||||
export default class TeamInCase extends Model {
|
||||
static initialize(sequelize) {
|
||||
TeamInCase.init(
|
||||
{ technicalComment: { type: DataTypes.TEXT, allowNull: true } },
|
||||
{
|
||||
sequelize,
|
||||
modelName: 'TeamInCase',
|
||||
tableName: 'teams_in_cases',
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import sequelize from 'sequelize';
|
||||
import bcrypt from 'bcrypt';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
const { DataTypes, Model } = sequelize;
|
||||
|
||||
export default class User extends Model {
|
||||
static initialize(sequelize) {
|
||||
User.init(
|
||||
{
|
||||
id: { type: DataTypes.UUID, primaryKey: true },
|
||||
isAdmin: { type: DataTypes.BOOLEAN, defaultValue: false, allowNull: false },
|
||||
role: {
|
||||
type: DataTypes.STRING(20),
|
||||
defaultValue: 'expert',
|
||||
allowNull: false,
|
||||
validate: { isIn: [['expert', 'technical']] },
|
||||
},
|
||||
|
||||
login: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: false,
|
||||
unique: 'login',
|
||||
},
|
||||
password: {
|
||||
type: DataTypes.STRING,
|
||||
set(val) {
|
||||
this.setDataValue('password', bcrypt.hashSync(val, bcrypt.genSaltSync()));
|
||||
},
|
||||
},
|
||||
passwordForAdmin: {
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
iat: { type: DataTypes.BIGINT },
|
||||
sessionId: { type: DataTypes.UUID },
|
||||
|
||||
firstName: { type: DataTypes.STRING, allowNull: true, validate: { len: [1, 50] } },
|
||||
middleName: { type: DataTypes.STRING, allowNull: true, validate: { len: [0, 50] } },
|
||||
lastName: { type: DataTypes.STRING, allowNull: true, validate: { len: [1, 50] } },
|
||||
},
|
||||
{
|
||||
sequelize,
|
||||
modelName: 'User',
|
||||
tableName: 'users',
|
||||
}
|
||||
);
|
||||
|
||||
User.beforeCreate(user => {
|
||||
user.id = uuidv4();
|
||||
});
|
||||
}
|
||||
|
||||
fullName() {
|
||||
return this.firstName + ' ' + this.lastName;
|
||||
}
|
||||
|
||||
validatePassword(password) {
|
||||
return bcrypt.compareSync(password, this.password);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import sequelize from 'sequelize';
|
||||
const { Model } = sequelize;
|
||||
|
||||
export default class UserInCase extends Model {
|
||||
static initialize(sequelize) {
|
||||
UserInCase.init(
|
||||
{},
|
||||
{
|
||||
sequelize,
|
||||
modelName: 'UserInCase',
|
||||
tableName: 'users_in_cases',
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+7381
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "hackathon-grading-system",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "nodemon --unhandled-rejections=warn --experimental-specifier-resolution=node .",
|
||||
"start": "node --unhandled-rejections=warn --experimental-specifier-resolution=node .",
|
||||
"show": "npm run show:nomarks && npm run show:positions",
|
||||
"show:nomarks": "node --experimental-specifier-resolution=node ./scripts/no-marks.js",
|
||||
"show:positions": "node --experimental-specifier-resolution=node ./scripts/calc-positions.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"bcrypt": "^5.0.1",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^10.0.0",
|
||||
"express": "^4.17.1",
|
||||
"js-convert-case": "^4.1.2",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
"morgan": "^1.10.0",
|
||||
"mysql2": "^2.3.2",
|
||||
"pdfkit": "0.17.2",
|
||||
"pngjs": "5.0.0",
|
||||
"qrcode": "1.5.4",
|
||||
"sequelize": "^6.37.7",
|
||||
"uuid": "^8.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"eslint": "^8.0.1",
|
||||
"eslint-config-prettier": "^8.3.0",
|
||||
"eslint-plugin-prettier": "^4.0.0",
|
||||
"google-spreadsheet": "^3.3.0",
|
||||
"nodemon": "^2.0.13",
|
||||
"prettier": "^2.4.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Router } from 'express';
|
||||
import adminCtrl from '../controllers/admin.js';
|
||||
import manage from '../controllers/manage.js';
|
||||
import exportExpertQr from '../controllers/expert-qr.js';
|
||||
import markDetails from '../controllers/mark-details.js';
|
||||
import { asyncRoute } from '../utils/errors.js';
|
||||
import verifyToken from '../middlewares/verifyToken.js';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.use(verifyToken, (req, res, next) => {
|
||||
if (!req.isAdmin) {
|
||||
res.status(403).json({ error: 'Forbidden' });
|
||||
return;
|
||||
}
|
||||
|
||||
next();
|
||||
});
|
||||
|
||||
router.route('/').get(asyncRoute(adminCtrl.get)).post(asyncRoute(adminCtrl.save));
|
||||
|
||||
router.route('/cases').get(asyncRoute(manage.listCases)).post(asyncRoute(manage.createCase));
|
||||
router.route('/cases/:caseId').put(asyncRoute(manage.updateCase));
|
||||
router.route('/cases/:caseId/teams').post(asyncRoute(manage.createTeam));
|
||||
router.route('/cases/:caseId/teams/:teamId').put(asyncRoute(manage.updateTeam));
|
||||
router.route('/users').get(asyncRoute(manage.listUsers)).post(asyncRoute(manage.createUser));
|
||||
router.route('/users/qr-pdf').post(asyncRoute(exportExpertQr));
|
||||
router.route('/users/:userId').put(asyncRoute(manage.updateUser)).delete(asyncRoute(manage.deleteUser));
|
||||
router.route('/users/:userId/restore').post(asyncRoute(manage.restoreUser));
|
||||
router.route('/users/:userId/cases').put(asyncRoute(manage.assignUser));
|
||||
|
||||
router.route('/marks/details').get(asyncRoute(markDetails));
|
||||
router.route('/marks').get(asyncRoute(adminCtrl.noMarks));
|
||||
router.route('/positions').get(asyncRoute(adminCtrl.calcPositions));
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Router } from 'express';
|
||||
import verifyToken from '../middlewares/verifyToken.js';
|
||||
import authCtrl from '../controllers/auth.js';
|
||||
import { asyncRoute } from '../utils/errors.js';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.route('/login').post(asyncRoute(authCtrl.login));
|
||||
router.route('/user').get(verifyToken, authCtrl.user);
|
||||
router.route('/logout').post(verifyToken, asyncRoute(authCtrl.logout));
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Router } from 'express';
|
||||
import verifyToken from '../middlewares/verifyToken.js';
|
||||
import { asyncRoute } from '../utils/errors.js';
|
||||
import casesCtrl from '../controllers/cases.js';
|
||||
import marksCtrl from '../controllers/marks.js';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.route('/').get(verifyToken, asyncRoute(casesCtrl.getAll));
|
||||
|
||||
router
|
||||
.route('/:caseId/teams/:teamId/marks')
|
||||
.get(verifyToken, asyncRoute(marksCtrl.get))
|
||||
.post(verifyToken, asyncRoute(marksCtrl.add))
|
||||
.put(verifyToken, asyncRoute(marksCtrl.addBatch));
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Router } from 'express';
|
||||
import systemCtrl from '../controllers/system.js';
|
||||
import { asyncRoute } from '../utils/errors.js';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.route('/appdata').get(asyncRoute(systemCtrl.appdata));
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,97 @@
|
||||
import 'dotenv/config';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolve } from 'node:path';
|
||||
import { initializeDbModels } from '../utils/db.js';
|
||||
import { sequelize } from '../models/index.js';
|
||||
import Mark from '../models/mark.js';
|
||||
import Case from '../models/case.js';
|
||||
import Team from '../models/team.js';
|
||||
import User from '../models/user.js';
|
||||
import Sequelize from 'sequelize';
|
||||
|
||||
const { Op } = Sequelize;
|
||||
|
||||
export async function calculatePositions() {
|
||||
const [marksDB, casesDB, teams] = await Promise.all([
|
||||
Mark.findAll({
|
||||
where: { mark: { [Op.ne]: null } },
|
||||
include: [
|
||||
{ model: Case, as: 'case' },
|
||||
{ model: Team, as: 'team' },
|
||||
{ model: User, as: 'user' },
|
||||
],
|
||||
}),
|
||||
Case.findAll({
|
||||
include: [
|
||||
{ model: User, as: 'users', attributes: ['id'], through: { attributes: [] } },
|
||||
{ model: Team, as: 'teams', attributes: ['id'], through: { attributes: [] } },
|
||||
],
|
||||
}),
|
||||
Team.findAll(),
|
||||
]);
|
||||
|
||||
const marks = marksDB.map(mark => mark.toJSON());
|
||||
const placesByUser = {};
|
||||
for (const m of marks) {
|
||||
if (!m.user || !m.case || !m.team || m.user.role === 'technical') continue;
|
||||
const task = casesDB.find(c => c.id === m.caseId);
|
||||
if (!task?.users.some(u => u.id === m.userId) || !task.teams.some(t => t.id === m.teamId)) continue;
|
||||
if (!placesByUser[m.user.id]) placesByUser[m.user.id] = {};
|
||||
if (!placesByUser[m.user.id][m.case.id]) placesByUser[m.user.id][m.case.id] = {};
|
||||
if (!placesByUser[m.user.id][m.case.id][m.team.id]) placesByUser[m.user.id][m.case.id][m.team.id] = 0;
|
||||
placesByUser[m.user.id][m.case.id][m.team.id] += m.mark;
|
||||
}
|
||||
|
||||
const cases = {};
|
||||
for (const userId of Object.keys(placesByUser)) {
|
||||
for (const caseId of Object.keys(placesByUser[userId])) {
|
||||
let place = 0;
|
||||
|
||||
placesByUser[userId][caseId] = Object.fromEntries(
|
||||
Object.entries(placesByUser[userId][caseId])
|
||||
.sort(([, a], [, b]) => b - a)
|
||||
.map((v, i, arr) => [v[0], v[1] !== arr[i - 1]?.[1] ? ++place : place])
|
||||
);
|
||||
if (!cases[caseId]) cases[caseId] = {};
|
||||
for (const team of Object.entries(placesByUser[userId][caseId])) {
|
||||
if (!cases[caseId][team[0]]) cases[caseId][team[0]] = 0;
|
||||
cases[caseId][team[0]] += team[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const positions = {};
|
||||
for (const [caseId, scores] of Object.entries(cases)) {
|
||||
let place = 0;
|
||||
positions[caseId] = Object.fromEntries(
|
||||
Object.entries(scores)
|
||||
.sort(([, a], [, b]) => a - b)
|
||||
.map(([id, score], index, rows) => [id, score !== rows[index - 1]?.[1] ? ++place : place])
|
||||
);
|
||||
}
|
||||
return {
|
||||
positions,
|
||||
cases: Object.fromEntries(casesDB.map(c => [c.id, c.name])),
|
||||
teams: Object.fromEntries(teams.map(t => [t.id, t.name])),
|
||||
};
|
||||
}
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
await initializeDbModels();
|
||||
const result = await calculatePositions();
|
||||
for (const [caseId, positions] of Object.entries(result.positions)) {
|
||||
console.log('\n' + result.cases[caseId]);
|
||||
console.table(Object.fromEntries(Object.entries(positions).map(([id, place]) => [result.teams[id], place])));
|
||||
}
|
||||
} finally {
|
||||
await sequelize.close();
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
|
||||
main().catch(error => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import dotenv from 'dotenv';
|
||||
dotenv.config();
|
||||
import { initializeDbModels } from '../utils/db.js';
|
||||
import { sequelize } from '../models/index.js';
|
||||
import creds from '../config/google-credentials.js';
|
||||
import { GoogleSpreadsheet } from 'google-spreadsheet';
|
||||
import Case from '../models/case.js';
|
||||
import Team from '../models/team.js';
|
||||
import Mark from '../models/mark.js';
|
||||
import User from '../models/user.js';
|
||||
import markTypesNames from '../config/markTypesNames.js';
|
||||
|
||||
const doc = new GoogleSpreadsheet('1ofOGiYrDv_Pp-rJlgjKDJR2HY0IEHnSNmI1jwCIb7JU');
|
||||
|
||||
async function start() {
|
||||
await initializeDbModels();
|
||||
await doc.useServiceAccountAuth(creds);
|
||||
await doc.loadInfo();
|
||||
|
||||
const cases = await Case.findAll({
|
||||
attributes: ['id', 'name'],
|
||||
include: [
|
||||
{ model: Team, as: 'teams', order: 'name', attributes: ['id', 'name'], through: { attributes: [] } },
|
||||
{
|
||||
model: User,
|
||||
as: 'users',
|
||||
attributes: ['id', 'firstName', 'lastName'],
|
||||
through: { attributes: [] },
|
||||
include: { model: Mark, as: 'marks' },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let xOffset = 0;
|
||||
let yOffset = 0;
|
||||
for (const c of cases) {
|
||||
const sheet = await doc.addSheet({ title: c.name });
|
||||
await sheet.loadCells();
|
||||
for (const user of c.users) {
|
||||
const userName = sheet.getCell(xOffset, yOffset);
|
||||
userName.value = user.firstName + ' ' + user.lastName;
|
||||
xOffset += 2;
|
||||
for (const team of c.teams) {
|
||||
const teamName = sheet.getCell(xOffset, yOffset);
|
||||
teamName.value = team.name;
|
||||
xOffset++;
|
||||
|
||||
for (const [typeMark, nameTypeMark] of Object.entries(markTypesNames)) {
|
||||
const markType = sheet.getCell(xOffset, yOffset);
|
||||
const mark = sheet.getCell(xOffset, yOffset + 1);
|
||||
markType.value = nameTypeMark;
|
||||
const markValue = user.marks.find(m => m.teamId === team.id && m.markType === +typeMark)?.mark;
|
||||
mark.value = markValue;
|
||||
if (!markValue || markValue === 0)
|
||||
mark.backgroundColor = {
|
||||
red: 1,
|
||||
green: 0,
|
||||
blue: 0,
|
||||
};
|
||||
xOffset++;
|
||||
}
|
||||
|
||||
xOffset++;
|
||||
}
|
||||
yOffset += 3;
|
||||
xOffset = 0;
|
||||
}
|
||||
yOffset = 0;
|
||||
await sheet.saveUpdatedCells();
|
||||
}
|
||||
|
||||
await sequelize.close();
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -0,0 +1,92 @@
|
||||
import 'dotenv/config';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolve } from 'node:path';
|
||||
import { initializeDbModels } from '../utils/db.js';
|
||||
import { sequelize } from '../models/index.js';
|
||||
import Mark from '../models/mark.js';
|
||||
import Case from '../models/case.js';
|
||||
import Team from '../models/team.js';
|
||||
import User from '../models/user.js';
|
||||
|
||||
import { editableMarkTypes } from '../utils/expert-roles.js';
|
||||
|
||||
export async function getMissingMarks() {
|
||||
const cases = await Case.findAll({
|
||||
attributes: ['id', 'name'],
|
||||
include: [
|
||||
{
|
||||
model: Team,
|
||||
as: 'teams',
|
||||
order: 'name',
|
||||
attributes: ['id', 'name'],
|
||||
through: { attributes: [] },
|
||||
include: { model: Mark, as: 'marks' },
|
||||
},
|
||||
{ model: User, as: 'users', attributes: ['id', 'firstName', 'lastName', 'role'], through: { attributes: [] } },
|
||||
],
|
||||
});
|
||||
|
||||
const noMarks = {};
|
||||
for (const c of cases) {
|
||||
for (const team of c.teams) {
|
||||
for (const user of c.users) {
|
||||
const userMark = team.marks.filter(m => m.userId === user.id && m.caseId === c.id && m.mark !== null);
|
||||
if (!editableMarkTypes(user.role).every(type => userMark.some(mark => mark.markType === type))) {
|
||||
if (!noMarks[user.firstName + ' ' + user.lastName]) noMarks[user.firstName + ' ' + user.lastName] = {};
|
||||
if (!noMarks[user.firstName + ' ' + user.lastName][c.name])
|
||||
noMarks[user.firstName + ' ' + user.lastName][c.name] = [];
|
||||
noMarks[user.firstName + ' ' + user.lastName][c.name].push(team.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const zeroMarks = {};
|
||||
for (const c of cases) {
|
||||
for (const team of c.teams) {
|
||||
for (const user of c.users) {
|
||||
const userMark = team.marks.filter(
|
||||
m =>
|
||||
m.userId === user.id &&
|
||||
m.caseId === c.id &&
|
||||
m.mark === 0 &&
|
||||
(user.role !== 'technical' || editableMarkTypes(user.role).includes(m.markType))
|
||||
);
|
||||
if (userMark.length) {
|
||||
if (!zeroMarks[user.firstName + ' ' + user.lastName]) zeroMarks[user.firstName + ' ' + user.lastName] = {};
|
||||
if (!zeroMarks[user.firstName + ' ' + user.lastName][c.name])
|
||||
zeroMarks[user.firstName + ' ' + user.lastName][c.name] = [];
|
||||
zeroMarks[user.firstName + ' ' + user.lastName][c.name].push(team.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { noMarks, zeroMarks };
|
||||
}
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
await initializeDbModels();
|
||||
const { noMarks, zeroMarks } = await getMissingMarks();
|
||||
for (const [user, cases] of Object.entries(noMarks)) {
|
||||
console.log('\n' + user);
|
||||
console.table(cases);
|
||||
}
|
||||
console.log('\nZERO MARKS');
|
||||
for (const [user, cases] of Object.entries(zeroMarks)) {
|
||||
console.log('\n' + user);
|
||||
console.table(cases);
|
||||
}
|
||||
if (Object.keys(noMarks).length) process.exitCode = 1;
|
||||
} finally {
|
||||
await sequelize.close();
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
|
||||
main().catch(error => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { initializeDbModels } from '../utils/db.js';
|
||||
import { models, sequelize } from '../models/index.js';
|
||||
|
||||
if (process.env.DB_HOST !== 'db' || process.env.WEB_SERVICE !== 'cg-grade-local') {
|
||||
throw new Error('Demo seed is only intended for the local Compose database');
|
||||
}
|
||||
|
||||
try {
|
||||
await initializeDbModels();
|
||||
const [judge] = await models.User.findOrCreate({
|
||||
where: { login: 'demo-judge' },
|
||||
defaults: {
|
||||
firstName: 'Демо', lastName: 'Эксперт',
|
||||
password: 'DemoJudge2026!', passwordForAdmin: 'DemoJudge2026!',
|
||||
},
|
||||
});
|
||||
const [task] = await models.Case.findOrCreate({
|
||||
where: { name: 'Демонстрационный кейс' },
|
||||
defaults: { description: 'Локальные данные для проверки системы оценивания.' },
|
||||
});
|
||||
await task.addUser(judge);
|
||||
for (const name of ['Демо: Альфа', 'Демо: Бета']) {
|
||||
const [team] = await models.Team.findOrCreate({
|
||||
where: { name }, defaults: { description: 'Тестовая команда.' },
|
||||
});
|
||||
await task.addTeam(team);
|
||||
}
|
||||
console.log('Demo ready: one judge, one case, two teams.');
|
||||
} finally {
|
||||
await sequelize.close();
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import admin from '../config/admin.js';
|
||||
import setupAssociations from '../models/setupAssociations.js';
|
||||
import { models, sequelize } from '../models/index.js';
|
||||
import { calculatePositions } from '../scripts/calc-positions.js';
|
||||
import { getMissingMarks } from '../scripts/no-marks.js';
|
||||
|
||||
async function main() {
|
||||
for (const model of Object.values(models)) model.initialize(sequelize);
|
||||
setupAssociations();
|
||||
await sequelize.authenticate();
|
||||
const base = process.env.GRADE_API_URL || 'http://127.0.0.1:3080';
|
||||
const suffix = Date.now().toString(36);
|
||||
const created = { cases: [], users: [], teams: [] };
|
||||
let token;
|
||||
async function request(path, { method = 'GET', body, status = 200, auth = token } = {}) {
|
||||
const response = await globalThis.fetch(base + path, {
|
||||
method,
|
||||
headers: {
|
||||
...(auth ? { Authorization: `Bearer ${auth}` } : {}),
|
||||
...(body ? { 'Content-Type': 'application/json' } : {}),
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
assert.equal(response.status, status, `${method} ${path}: ${await response.clone().text()}`);
|
||||
const text = await response.text();
|
||||
return text ? JSON.parse(text) : null;
|
||||
}
|
||||
try {
|
||||
token = (await request('/auth/login', { method: 'POST', body: { login: admin.login, password: admin.password } }))
|
||||
.token;
|
||||
await request('/admin/cases', { method: 'POST', body: { name: ' ' }, status: 400 });
|
||||
const { case: task } = await request('/admin/cases', {
|
||||
method: 'POST',
|
||||
body: { name: 'API test ' + suffix },
|
||||
status: 201,
|
||||
});
|
||||
created.cases.push(task.id);
|
||||
const { team } = await request(`/admin/cases/${task.id}/teams`, {
|
||||
method: 'POST',
|
||||
body: { name: 'Test team' },
|
||||
status: 201,
|
||||
});
|
||||
created.teams.push(team.id);
|
||||
await request(`/admin/cases/${task.id}`, {
|
||||
method: 'PUT',
|
||||
body: { name: 'Updated ' + suffix, description: 'Updated description' },
|
||||
});
|
||||
await request(`/admin/cases/${task.id}/teams/${team.id}`, { method: 'PUT', body: { name: 'Updated team' } });
|
||||
const { user } = await request('/admin/users', {
|
||||
method: 'POST',
|
||||
body: { firstName: 'API ' + suffix, lastName: 'Expert', caseIds: [task.id, task.id] },
|
||||
status: 201,
|
||||
});
|
||||
created.users.push(user.id);
|
||||
assert.deepEqual(
|
||||
(await models.UserInCase.findAll({ where: { userId: user.id } })).map(row => row.caseId),
|
||||
[task.id]
|
||||
);
|
||||
await request('/admin/users', {
|
||||
method: 'POST',
|
||||
body: { firstName: 'Invalid ' + suffix, lastName: 'Expert', caseIds: ['00000000-0000-0000-0000-000000000000'] },
|
||||
status: 400,
|
||||
});
|
||||
assert.equal(await models.User.count({ where: { firstName: 'Invalid ' + suffix }, paranoid: false }), 0);
|
||||
const { user: sameSurname } = await request('/admin/users', {
|
||||
method: 'POST',
|
||||
body: { firstName: 'API second ' + suffix, lastName: 'Expert' },
|
||||
status: 201,
|
||||
});
|
||||
created.users.push(sameSurname.id);
|
||||
assert.notEqual(user.login, sameSurname.login);
|
||||
const assign = caseIds => request(`/admin/users/${user.id}/cases`, { method: 'PUT', body: { caseIds } });
|
||||
await assign([task.id]);
|
||||
await request(`/admin/users/${user.id}/cases`, {
|
||||
method: 'PUT',
|
||||
body: { caseIds: ['00000000-0000-0000-0000-000000000000'] },
|
||||
status: 400,
|
||||
});
|
||||
assert.ok((await request('/admin/users')).users.find(u => u.id === user.id).cases.some(c => c.id === task.id));
|
||||
await assign([]);
|
||||
await assign([task.id]);
|
||||
const listed = (await request('/admin/users')).users.find(u => u.id === user.id);
|
||||
assert.ok(listed.cases.some(c => c.id === task.id));
|
||||
assert.ok(!('password' in listed));
|
||||
const judge = (
|
||||
await request('/auth/login', { method: 'POST', body: { login: user.login, password: listed.passwordForAdmin } })
|
||||
).token;
|
||||
assert.ok((await request('/cases', { auth: judge })).cases.some(c => c.id === task.id));
|
||||
await request('/admin/cases', { auth: judge, status: 403 });
|
||||
await request(`/cases/${task.id}/teams/${team.id}/marks`, {
|
||||
method: 'PUT',
|
||||
auth: judge,
|
||||
body: { marks: [{ markType: 20, mark: 5 }] },
|
||||
status: 403,
|
||||
});
|
||||
await request(`/cases/${task.id}/teams/${team.id}/marks`, {
|
||||
method: 'POST',
|
||||
auth: judge,
|
||||
body: { markType: 30, mark: 5 },
|
||||
status: 403,
|
||||
});
|
||||
await request(`/cases/${task.id}/teams/${team.id}/marks`, {
|
||||
method: 'PUT',
|
||||
auth: judge,
|
||||
body: { marks: [{ markType: 10, mark: 8 }] },
|
||||
status: 400,
|
||||
});
|
||||
|
||||
await request('/admin', { method: 'POST', body: { marks: [{ id: team.id, implementation: 3, work: 4 }] } });
|
||||
await request(`/cases/${task.id}/teams/${team.id}/marks`, {
|
||||
method: 'PUT',
|
||||
auth: judge,
|
||||
body: { marks: [10, 40, 50].map(markType => ({ markType, mark: 5 })) },
|
||||
});
|
||||
await request(`/admin/users/${sameSurname.id}/cases`, { method: 'PUT', body: { caseIds: [task.id] } });
|
||||
const copied = await models.Mark.findAll({ where: { userId: sameSurname.id, caseId: task.id } });
|
||||
assert.equal(copied.length, 2);
|
||||
const result = await request('/admin/positions');
|
||||
assert.equal(result.positions[task.id][team.id], 1);
|
||||
assert.deepEqual(result, await calculatePositions());
|
||||
assert.deepEqual(await request('/admin/marks'), await getMissingMarks());
|
||||
await assign([]);
|
||||
assert.equal((await request('/cases', { auth: judge })).cases.length, 0);
|
||||
await request(`/cases/${task.id}/teams/${team.id}/marks`, { auth: judge, status: 403 });
|
||||
console.log(
|
||||
'PASS: create/update cases and teams; expert credentials and duplicate surnames; assign/remove/reassign; invalid assignment rollback; role guards; organizer mark copying; live expert access; API/script parity.'
|
||||
);
|
||||
} finally {
|
||||
await models.Mark.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.UserInCase.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.TeamInCase.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.Team.destroy({ where: { id: created.teams }, force: true });
|
||||
await models.User.destroy({ where: { id: created.users }, force: true });
|
||||
await models.Case.destroy({ where: { id: created.cases }, force: true });
|
||||
await sequelize.close();
|
||||
}
|
||||
}
|
||||
main().catch(error => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import pngjs from 'pngjs';
|
||||
import { validateCaseIcon } from '../utils/case-icon.js';
|
||||
import admin from '../config/admin.js';
|
||||
import { models, sequelize } from '../models/index.js';
|
||||
|
||||
function image(size) {
|
||||
const png = new pngjs.PNG({ width: size, height: size });
|
||||
png.data.fill(120);
|
||||
return pngjs.PNG.sync.write(png, { deflateLevel: 0 });
|
||||
}
|
||||
|
||||
const allowed = image(450);
|
||||
const oversized = image(600);
|
||||
assert.ok(allowed.length > 256 * 1024 && allowed.length <= 1024 * 1024);
|
||||
assert.ok(oversized.length > 1024 * 1024);
|
||||
const icon = 'data:image/png;base64,' + allowed.toString('base64');
|
||||
assert.equal(validateCaseIcon(icon), icon);
|
||||
assert.throws(() => validateCaseIcon('data:image/png;base64,' + oversized.toString('base64')));
|
||||
|
||||
// Use the public proxy too: a 1 MB image exceeds 1 MB after base64 encoding.
|
||||
const base = process.env.GRADE_API_URL || 'http://web/api';
|
||||
let caseId;
|
||||
try {
|
||||
models.Case.initialize(sequelize);
|
||||
const login = await fetch(base + '/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ login: admin.login, password: admin.password }),
|
||||
});
|
||||
assert.equal(login.status, 200);
|
||||
const { token } = await login.json();
|
||||
const response = await fetch(base + '/admin/cases', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + token },
|
||||
body: JSON.stringify({ name: 'Icon size regression ' + Date.now(), icon }),
|
||||
});
|
||||
assert.equal(response.status, 201);
|
||||
const { case: task } = await response.json();
|
||||
caseId = task.id;
|
||||
assert.equal(task.icon, icon);
|
||||
const rejected = await fetch(base + '/admin/cases/' + caseId, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + token },
|
||||
body: JSON.stringify({ name: task.name, icon: 'data:image/png;base64,' + oversized.toString('base64') }),
|
||||
});
|
||||
assert.equal(rejected.status, 400);
|
||||
console.log('PASS: PNG above 256 KB accepted through proxy and stored; PNG above 1 MB rejected.');
|
||||
} finally {
|
||||
if (caseId) await models.Case.destroy({ where: { id: caseId }, force: true });
|
||||
await sequelize.close();
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { models, sequelize } from '../models/index.js';
|
||||
import setupAssociations from '../models/setupAssociations.js';
|
||||
import admin from '../config/admin.js';
|
||||
|
||||
async function main() {
|
||||
for (const model of Object.values(models)) model.initialize(sequelize);
|
||||
setupAssociations();
|
||||
const base = process.env.GRADE_API_URL || 'http://127.0.0.1:3080';
|
||||
const created = [];
|
||||
let adminToken;
|
||||
async function request(path, { method = 'GET', body, token = adminToken, status = 200, pdf = false } = {}) {
|
||||
const response = await globalThis.fetch(base + path, {
|
||||
method,
|
||||
headers: {
|
||||
...(token ? { Authorization: 'Bearer ' + token } : {}),
|
||||
...(body ? { 'Content-Type': 'application/json' } : {}),
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
assert.equal(response.status, status, `${method} ${path}`);
|
||||
if (pdf) {
|
||||
assert.match(response.headers.get('content-type'), /application\/pdf/);
|
||||
assert.match(response.headers.get('content-disposition'), /attachment/);
|
||||
assert.match(response.headers.get('cache-control'), /no-store/);
|
||||
return Buffer.from(await response.arrayBuffer());
|
||||
}
|
||||
const text = await response.text();
|
||||
return text ? JSON.parse(text) : null;
|
||||
}
|
||||
try {
|
||||
adminToken = (
|
||||
await request('/auth/login', { method: 'POST', body: { login: admin.login, password: admin.password } })
|
||||
).token;
|
||||
const suffix = Date.now().toString(36);
|
||||
const { user } = await request('/admin/users', {
|
||||
method: 'POST',
|
||||
body: { firstName: 'Тест', lastName: 'Экспорта' + suffix, middleName: 'Иванович' },
|
||||
status: 201,
|
||||
});
|
||||
created.push(user.id);
|
||||
let stored = await models.User.findByPk(user.id);
|
||||
const oldPassword = stored.passwordForAdmin;
|
||||
const task = await models.Case.findOne({
|
||||
include: { model: models.Team, as: 'teams', through: { attributes: [] } },
|
||||
});
|
||||
let retainedMark;
|
||||
if (task?.teams.length) {
|
||||
await task.addUser(stored);
|
||||
retainedMark = await models.Mark.create({
|
||||
caseId: task.id,
|
||||
teamId: task.teams[0].id,
|
||||
userId: user.id,
|
||||
markType: 10,
|
||||
mark: 4,
|
||||
});
|
||||
}
|
||||
|
||||
const oldToken = (
|
||||
await request('/auth/login', { method: 'POST', body: { login: stored.login, password: oldPassword } })
|
||||
).token;
|
||||
const edit = {
|
||||
firstName: 'Иван',
|
||||
lastName: 'Петров',
|
||||
middleName: 'Сергеевич',
|
||||
login: 'edited-' + suffix,
|
||||
password: 'New+&?#2026!',
|
||||
};
|
||||
await request(`/admin/users/${user.id}`, { method: 'PUT', body: edit });
|
||||
await request('/cases', { token: oldToken, status: 401 });
|
||||
await request('/auth/login', { method: 'POST', body: { login: user.login, password: oldPassword }, status: 403 });
|
||||
const currentToken = (
|
||||
await request('/auth/login', { method: 'POST', body: { login: edit.login, password: edit.password } })
|
||||
).token;
|
||||
await request('/cases', { token: currentToken });
|
||||
await request(`/admin/users/${user.id}`, { method: 'PUT', body: edit, token: currentToken, status: 403 });
|
||||
await request('/admin/users/qr-pdf', {
|
||||
method: 'POST',
|
||||
body: { baseUrl: 'https://grading.example.ru/' },
|
||||
token: currentToken,
|
||||
status: 403,
|
||||
});
|
||||
await request(`/admin/users/${user.id}`, { method: 'PUT', body: { ...edit, login: 'admin' }, status: 400 });
|
||||
await request(`/admin/users/${user.id}`, { method: 'PUT', body: { ...edit, password: 'x' }, status: 400 });
|
||||
await request(`/admin/users/${user.id}`, { method: 'PUT', body: { ...edit, password: '' } });
|
||||
stored = await models.User.findByPk(user.id);
|
||||
assert.equal(stored.middleName, 'Сергеевич');
|
||||
assert.ok(stored.validatePassword(edit.password));
|
||||
const pdf = await request('/admin/users/qr-pdf', {
|
||||
method: 'POST',
|
||||
body: { baseUrl: 'https://grading.example.ru/' },
|
||||
pdf: true,
|
||||
});
|
||||
assert.equal(pdf.subarray(0, 5).toString(), '%PDF-');
|
||||
for (const baseUrl of ['javascript:alert(1)', 'https://example.ru/#/login', 'https://u:p@example.ru/'])
|
||||
await request('/admin/users/qr-pdf', { method: 'POST', body: { baseUrl }, status: 400 });
|
||||
await request(`/admin/users/${user.id}`, { method: 'DELETE', status: 204 });
|
||||
await request('/cases', { token: currentToken, status: 401 });
|
||||
await request('/auth/login', { method: 'POST', body: { login: edit.login, password: edit.password }, status: 403 });
|
||||
assert.equal(await models.User.findByPk(user.id), null);
|
||||
if (retainedMark) assert.ok(await models.Mark.findByPk(retainedMark.id));
|
||||
|
||||
await request(`/admin/users/${user.id}/restore`, { method: 'POST' });
|
||||
const restored = (
|
||||
await request('/auth/login', { method: 'POST', body: { login: edit.login, password: edit.password } })
|
||||
).token;
|
||||
await request('/cases', { token: restored });
|
||||
await request('/cases', { token: currentToken, status: 401 });
|
||||
console.log(
|
||||
'PASS expert name/login/password editing; unchanged password; admin-only access; deletion, login revocation and restore; old tokens stay invalid after same-second login; PDF endpoint and URL validation.'
|
||||
);
|
||||
} finally {
|
||||
await models.Mark.destroy({ where: { userId: created }, force: true });
|
||||
await models.UserInCase.destroy({ where: { userId: created }, force: true });
|
||||
await models.User.destroy({ where: { id: created }, force: true });
|
||||
await sequelize.close();
|
||||
}
|
||||
}
|
||||
main().catch(error => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import pngjs from 'pngjs';
|
||||
import admin from '../config/admin.js';
|
||||
import { models, sequelize } from '../models/index.js';
|
||||
import setupAssociations from '../models/setupAssociations.js';
|
||||
|
||||
async function main() {
|
||||
for (const model of Object.values(models)) model.initialize(sequelize);
|
||||
setupAssociations();
|
||||
const base = process.env.GRADE_API_URL || 'http://127.0.0.1:3080';
|
||||
const created = { cases: [], teams: [], users: [] };
|
||||
let adminToken;
|
||||
async function request(path, { method = 'GET', body, status = 200, token = adminToken } = {}) {
|
||||
const res = await globalThis.fetch(base + path, {
|
||||
method,
|
||||
headers: {
|
||||
...(token ? { Authorization: 'Bearer ' + token } : {}),
|
||||
...(body ? { 'Content-Type': 'application/json' } : {}),
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
assert.equal(res.status, status, `${method} ${path}: ${await res.clone().text()}`);
|
||||
const text = await res.text();
|
||||
return text ? JSON.parse(text) : null;
|
||||
}
|
||||
try {
|
||||
adminToken = (
|
||||
await request('/auth/login', { method: 'POST', body: { login: admin.login, password: admin.password } })
|
||||
).token;
|
||||
const png = new pngjs.PNG({ width: 2, height: 2 });
|
||||
png.data.fill(120);
|
||||
const icon = 'data:image/png;base64,' + pngjs.PNG.sync.write(png).toString('base64');
|
||||
const { case: task } = await request('/admin/cases', {
|
||||
method: 'POST',
|
||||
body: { name: 'Icons test ' + Date.now(), icon },
|
||||
status: 201,
|
||||
});
|
||||
created.cases.push(task.id);
|
||||
assert.equal(task.icon, icon);
|
||||
await request('/admin/cases/' + task.id, { method: 'PUT', body: { name: task.name } });
|
||||
assert.equal((await models.Case.findByPk(task.id)).icon, icon);
|
||||
for (const invalid of [
|
||||
'data:image/jpeg;base64,AAAA',
|
||||
'data:image/png;base64,AAAA',
|
||||
'data:image/png;base64,' + Buffer.alloc(270000).toString('base64'),
|
||||
])
|
||||
await request('/admin/cases/' + task.id, {
|
||||
method: 'PUT',
|
||||
body: { name: task.name, icon: invalid },
|
||||
status: 400,
|
||||
});
|
||||
for (const name of ['A', 'B']) {
|
||||
const { team } = await request(`/admin/cases/${task.id}/teams`, { method: 'POST', body: { name }, status: 201 });
|
||||
created.teams.push(team.id);
|
||||
}
|
||||
for (const name of ['A', 'B']) {
|
||||
const { user } = await request('/admin/users', {
|
||||
method: 'POST',
|
||||
body: { firstName: name, lastName: 'Details' + Date.now() + name, middleName: 'Иванович' },
|
||||
status: 201,
|
||||
});
|
||||
created.users.push(user.id);
|
||||
await request(`/admin/users/${user.id}/cases`, { method: 'PUT', body: { caseIds: [task.id] } });
|
||||
}
|
||||
const user = await models.User.findByPk(created.users[0]);
|
||||
const judge = (
|
||||
await request('/auth/login', { method: 'POST', body: { login: user.login, password: user.passwordForAdmin } })
|
||||
).token;
|
||||
assert.equal((await request('/cases', { token: judge })).cases[0].icon, icon);
|
||||
await request('/admin/marks/details', { token: judge, status: 403 });
|
||||
await request('/admin', {
|
||||
method: 'POST',
|
||||
body: { marks: [{ id: created.teams[0], implementation: 3, work: 4 }] },
|
||||
});
|
||||
await request(`/cases/${task.id}/teams/${created.teams[0]}/marks`, {
|
||||
token: judge,
|
||||
method: 'PUT',
|
||||
body: {
|
||||
marks: [
|
||||
{ markType: 10, mark: 0 },
|
||||
{ markType: 40, mark: 2 },
|
||||
{ markType: 50, mark: 5 },
|
||||
],
|
||||
},
|
||||
});
|
||||
let report = (await request('/admin/marks/details')).details.find(c => c.id === task.id);
|
||||
assert.equal(report.rows.length, 4);
|
||||
const row = report.rows.find(r => r.teamId === created.teams[0] && r.userId === user.id);
|
||||
assert.equal(row.marks[10], 0);
|
||||
assert.equal(row.total, 14);
|
||||
assert.ok(row.expert.includes('Иванович'));
|
||||
const incomplete = report.rows.find(r => r.teamId === created.teams[0] && r.userId === created.users[1]);
|
||||
assert.equal(incomplete.marks[10], null);
|
||||
assert.equal(incomplete.marks[20], 3);
|
||||
assert.equal(incomplete.total, null);
|
||||
const { zeroMarks } = await request('/admin/marks');
|
||||
assert.ok(zeroMarks[user.firstName + ' ' + user.lastName][task.name].includes('A'));
|
||||
assert.ok(!zeroMarks[user.firstName + ' ' + user.lastName][task.name].includes('B'));
|
||||
const otherUser = await models.User.findByPk(created.users[1]);
|
||||
assert.equal(zeroMarks[otherUser.firstName + ' ' + otherUser.lastName]?.[task.name], undefined);
|
||||
await models.Mark.destroy({ where: { userId: user.id, caseId: task.id, markType: [20, 30] }, force: true });
|
||||
let missing = (await request('/admin/marks')).noMarks;
|
||||
assert.ok(!missing[user.firstName + ' ' + user.lastName][task.name].includes('A'));
|
||||
assert.ok(missing[user.firstName + ' ' + user.lastName][task.name].includes('B'));
|
||||
await request(`/cases/${task.id}/teams/${created.teams[0]}/marks`, {
|
||||
token: judge,
|
||||
method: 'PUT',
|
||||
body: { marks: [10, 40, 50].map(markType => ({ markType, mark: 0 })) },
|
||||
});
|
||||
missing = (await request('/admin/marks')).noMarks;
|
||||
assert.ok(!missing[user.firstName + ' ' + user.lastName][task.name].includes('A'));
|
||||
await models.Mark.destroy({
|
||||
where: { userId: user.id, teamId: created.teams[0], caseId: task.id, markType: 40 },
|
||||
force: true,
|
||||
});
|
||||
missing = (await request('/admin/marks')).noMarks;
|
||||
assert.ok(missing[user.firstName + ' ' + user.lastName][task.name].includes('A'));
|
||||
assert.ok(!JSON.stringify(report).includes(user.passwordForAdmin));
|
||||
await request('/admin/users/' + created.users[1], { method: 'DELETE', status: 204 });
|
||||
report = (await request('/admin/marks/details')).details.find(c => c.id === task.id);
|
||||
assert.equal(report.rows.length, 2);
|
||||
await request('/admin/cases/' + task.id, { method: 'PUT', body: { name: task.name, icon: null } });
|
||||
assert.equal((await models.Case.findByPk(task.id)).icon, null);
|
||||
console.log(
|
||||
'PASS PNG create/preserve/remove/validation; assigned expert icon; all-mark matrix; zero vs missing; totals; technical marks; deleted experts; permissions and no credential exposure.'
|
||||
);
|
||||
} finally {
|
||||
await models.Mark.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.UserInCase.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.TeamInCase.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.Team.destroy({ where: { id: created.teams }, force: true });
|
||||
await models.User.destroy({ where: { id: created.users }, force: true });
|
||||
await models.Case.destroy({ where: { id: created.cases }, force: true });
|
||||
await sequelize.close();
|
||||
}
|
||||
}
|
||||
main().catch(error => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createExpertQrPdf, loginLink } from '../utils/expert-qr-pdf.js';
|
||||
|
||||
async function main() {
|
||||
const users = Array.from({ length: 25 }, (_, i) => ({
|
||||
firstName: 'Александр',
|
||||
lastName: 'Эксперт ' + i,
|
||||
middleName: 'Александрович',
|
||||
login: 'expert-' + i,
|
||||
passwordForAdmin: 'Test+&?#%Ю2026',
|
||||
}));
|
||||
const link = new URL(loginLink('https://grading.example.ru/app/', users[0]));
|
||||
assert.equal(link.origin, 'https://grading.example.ru');
|
||||
assert.equal(link.pathname, '/app/');
|
||||
const query = new URLSearchParams(link.hash.slice('/login?'.length + 1));
|
||||
assert.equal(query.get('l'), users[0].login);
|
||||
assert.equal(query.get('p'), users[0].passwordForAdmin);
|
||||
const pdf = (await createExpertQrPdf(users, 'https://grading.example.ru/app/')).toString('latin1');
|
||||
assert.equal(pdf.slice(0, 5), '%PDF-');
|
||||
assert.equal((pdf.match(/\/Type \/Page\b/g) || []).length, 3);
|
||||
assert.equal((pdf.match(/\/Subtype \/Link\b/g) || []).length, 25);
|
||||
for (const [technicalCount, regularCount, pages] of [
|
||||
[2, 5, 2],
|
||||
[12, 1, 2],
|
||||
[13, 2, 3],
|
||||
[12, 12, 2],
|
||||
[1, 0, 1],
|
||||
]) {
|
||||
const regular = users.slice(0, regularCount).map(user => ({ ...user, role: 'expert' }));
|
||||
const technical = users.slice(0, technicalCount).map((user, i) => ({
|
||||
...user,
|
||||
role: 'technical',
|
||||
login: 'technical-' + i,
|
||||
cases: [{ name: 'Тестовый кейс ' + i }],
|
||||
}));
|
||||
const grouped = (await createExpertQrPdf([...regular, ...technical], 'https://grading.example.ru/')).toString(
|
||||
'latin1'
|
||||
);
|
||||
assert.equal((grouped.match(/\/Type \/Page\b/g) || []).length, pages);
|
||||
const links = [...grouped.matchAll(/\/URI\s*\(([^)]*)\)/g)].map(match => match[1]);
|
||||
assert.deepEqual(
|
||||
links,
|
||||
[...technical, ...regular].map(user => loginLink('https://grading.example.ru/', user))
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
'PASS QR cards and links; technical experts first; role groups start on separate pages; A4 pagination at group boundaries; reserved credentials round-trip.'
|
||||
);
|
||||
}
|
||||
main().catch(error => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,219 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import admin from '../config/admin.js';
|
||||
import { models, sequelize } from '../models/index.js';
|
||||
import setupAssociations from '../models/setupAssociations.js';
|
||||
for (const model of Object.values(models)) model.initialize(sequelize);
|
||||
setupAssociations();
|
||||
const base = process.env.GRADE_API_URL || 'http://127.0.0.1:3080';
|
||||
const suffix = Date.now().toString(36);
|
||||
const created = { cases: [], users: [], teams: [] };
|
||||
let token;
|
||||
async function req(path, body, status = 200, auth = token, method = body ? 'POST' : 'GET') {
|
||||
const res = await fetch(base + path, {
|
||||
method,
|
||||
headers: { Authorization: 'Bearer ' + auth, 'Content-Type': 'application/json' },
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
assert.equal(res.status, status, `${method} ${path}: ${await res.clone().text()}`);
|
||||
const text = await res.text();
|
||||
return text ? JSON.parse(text) : null;
|
||||
}
|
||||
async function expert(firstName, role, caseIds) {
|
||||
const { user } = await req('/admin/users', { firstName, lastName: 'Technical test ' + suffix, role, caseIds }, 201);
|
||||
created.users.push(user.id);
|
||||
return models.User.findByPk(user.id);
|
||||
}
|
||||
async function login(user) {
|
||||
return req('/auth/login', { login: user.login, password: user.passwordForAdmin });
|
||||
}
|
||||
try {
|
||||
token = (await req('/auth/login', { login: admin.login, password: admin.password })).token;
|
||||
for (const name of ['A', 'B']) {
|
||||
const { case: task } = await req('/admin/cases', { name: 'Technical ' + name + ' ' + suffix }, 201);
|
||||
created.cases.push(task.id);
|
||||
}
|
||||
const [caseId, otherCaseId] = created.cases;
|
||||
for (const name of ['A', 'B']) {
|
||||
const { team } = await req(`/admin/cases/${caseId}/teams`, { name }, 201);
|
||||
created.teams.push(team.id);
|
||||
}
|
||||
const [teamId, secondTeamId] = created.teams;
|
||||
const regular = await expert('Regular', 'expert', [caseId]);
|
||||
const technical = await expert('Technical', 'technical', [caseId]);
|
||||
const other = await expert('Other technical', 'technical', [otherCaseId]);
|
||||
await req('/admin/users', { firstName: 'Conflict', lastName: suffix, role: 'technical', caseIds: [caseId] }, 409);
|
||||
assert.equal(await models.User.count({ where: { firstName: 'Conflict', lastName: suffix }, paranoid: false }), 0);
|
||||
await req('/admin/users', { firstName: 'Invalid', lastName: suffix, role: 'admin' }, 400);
|
||||
await req(`/admin/users/${other.id}/cases`, { caseIds: [caseId, otherCaseId] }, 409, token, 'PUT');
|
||||
assert.deepEqual(
|
||||
(await other.getCases()).map(task => task.id),
|
||||
[otherCaseId]
|
||||
);
|
||||
await req(
|
||||
`/admin/users/${regular.id}`,
|
||||
{ firstName: regular.firstName, lastName: regular.lastName, login: regular.login, role: 'technical' },
|
||||
409,
|
||||
token,
|
||||
'PUT'
|
||||
);
|
||||
assert.equal((await regular.reload()).role, 'expert');
|
||||
const techLogin = await login(technical),
|
||||
regularLogin = await login(regular);
|
||||
assert.equal(techLogin.user.role, 'technical');
|
||||
const techToken = techLogin.token,
|
||||
regularToken = regularLogin.token;
|
||||
assert.equal((await req('/auth/user', null, 200, techToken)).user.role, 'technical');
|
||||
const save = (team, marks, auth = techToken, status = 200) =>
|
||||
req(`/cases/${caseId}/teams/${team}/marks`, { marks }, status, auth, 'PUT');
|
||||
await req('/admin/users', null, 403, techToken);
|
||||
await save(teamId, [{ markType: 10, mark: 5 }], techToken, 403);
|
||||
await req(`/cases/${caseId}/teams/${teamId}/marks`, { markType: 50, mark: 5 }, 403, techToken);
|
||||
await save(teamId, [{ markType: 20, mark: 5 }], regularToken, 403);
|
||||
await save(teamId, [{ markType: 20, mark: 6 }], techToken, 400);
|
||||
await save(
|
||||
teamId,
|
||||
[
|
||||
{ markType: 20, mark: 3 },
|
||||
{ markType: 10, mark: 5 },
|
||||
],
|
||||
techToken,
|
||||
403
|
||||
);
|
||||
assert.equal(await models.Mark.count({ where: { caseId } }), 0);
|
||||
const commentPath = `/cases/${caseId}/teams/${teamId}/marks`;
|
||||
const comment = 'Проверить обработку ошибок\nДемо работает локально. <b>Текст, не HTML</b>';
|
||||
await req(commentPath, { technicalComment: ' ' + comment + ' ' }, 200, techToken, 'PUT');
|
||||
assert.equal(await models.Mark.count({ where: { caseId } }), 0);
|
||||
assert.equal((await req(commentPath, null, 200, regularToken)).technicalComment, comment);
|
||||
assert.equal(
|
||||
(await req('/cases', null, 200, regularToken)).cases.find(c => c.id === caseId).teams.find(t => t.id === teamId)
|
||||
.technicalComment,
|
||||
comment
|
||||
);
|
||||
assert.equal(
|
||||
(await req('/admin/cases')).cases.find(c => c.id === caseId).teams.find(t => t.id === teamId).TeamInCase
|
||||
.technicalComment,
|
||||
comment
|
||||
);
|
||||
assert.equal(
|
||||
(await req(`/cases/${caseId}/teams/${secondTeamId}/marks`, null, 200, regularToken)).technicalComment,
|
||||
''
|
||||
);
|
||||
await req(
|
||||
commentPath,
|
||||
{ marks: [{ markType: 10, mark: 3 }], technicalComment: 'Forbidden' },
|
||||
403,
|
||||
regularToken,
|
||||
'PUT'
|
||||
);
|
||||
await req(commentPath, { markType: 10, mark: 3, technicalComment: 'Forbidden' }, 403, regularToken);
|
||||
assert.equal(await models.Mark.count({ where: { caseId } }), 0);
|
||||
for (const invalid of [null, 123, 'x'.repeat(5001)])
|
||||
await req(commentPath, { technicalComment: invalid }, 400, techToken, 'PUT');
|
||||
await req(commentPath, { technicalComment: 'Wrong', marks: [{ markType: 10, mark: 3 }] }, 403, techToken, 'PUT');
|
||||
assert.equal((await req(commentPath, null, 200, techToken)).technicalComment, comment);
|
||||
await req(commentPath, { technicalComment: 'x'.repeat(5000) }, 200, techToken, 'PUT');
|
||||
await req(commentPath, { technicalComment: '', marks: [] }, 200, techToken, 'PUT');
|
||||
assert.equal((await req(commentPath, null, 200, regularToken)).technicalComment, '');
|
||||
await req(commentPath, { technicalComment: comment }, 200, techToken, 'PUT');
|
||||
await req(
|
||||
`/cases/${otherCaseId}/teams/${teamId}/marks`,
|
||||
{ marks: [{ markType: 20, mark: 5 }] },
|
||||
403,
|
||||
techToken,
|
||||
'PUT'
|
||||
);
|
||||
await save(teamId, [
|
||||
{ markType: 20, mark: 0 },
|
||||
{ markType: 30, mark: 3 },
|
||||
]);
|
||||
await save(secondTeamId, [
|
||||
{ markType: 20, mark: 5 },
|
||||
{ markType: 30, mark: 5 },
|
||||
]);
|
||||
const visible = (await req('/cases', null, 200, regularToken)).cases
|
||||
.find(c => c.id === caseId)
|
||||
.teams.find(t => t.id === teamId).marks;
|
||||
assert.equal(visible.find(m => m.markType === 20).mark, 0);
|
||||
assert.equal(visible.find(m => m.markType === 30).mark, 3);
|
||||
const row = (await req('/admin/marks/details')).details
|
||||
.find(c => c.id === caseId)
|
||||
.rows.find(r => r.userId === technical.id && r.teamId === teamId);
|
||||
assert.equal(row.role, 'technical');
|
||||
assert.equal(row.total, 3);
|
||||
assert.equal(row.marks[10], null);
|
||||
let missing = (await req('/admin/marks')).noMarks;
|
||||
assert.equal(missing[technical.firstName + ' ' + technical.lastName]?.['Technical A ' + suffix], undefined);
|
||||
assert.ok(missing[regular.firstName + ' ' + regular.lastName]['Technical A ' + suffix]);
|
||||
await save(
|
||||
teamId,
|
||||
[
|
||||
{ markType: 10, mark: 5 },
|
||||
{ markType: 40, mark: 4 },
|
||||
{ markType: 50, mark: 3 },
|
||||
],
|
||||
regularToken
|
||||
);
|
||||
await save(
|
||||
secondTeamId,
|
||||
[10, 40, 50].map(markType => ({ markType, mark: 0 })),
|
||||
regularToken
|
||||
);
|
||||
missing = (await req('/admin/marks')).noMarks;
|
||||
assert.equal(missing[regular.firstName + ' ' + regular.lastName]?.['Technical A ' + suffix], undefined);
|
||||
const ranking = (await req('/admin/positions')).positions[caseId];
|
||||
assert.equal(ranking[teamId], 1);
|
||||
assert.equal(ranking[secondTeamId], 2);
|
||||
const late = await expert('Late', 'expert', [caseId]);
|
||||
assert.equal(await models.Mark.count({ where: { userId: late.id, caseId } }), 4);
|
||||
assert.equal((await req(commentPath, null, 200, (await login(late)).token)).technicalComment, comment);
|
||||
await req(`/cases/${caseId}/teams/${teamId}/marks`, { markType: 20, mark: 4 }, 200, techToken);
|
||||
assert.equal((await models.Mark.findOne({ where: { userId: late.id, caseId, teamId, markType: 20 } })).mark, 4);
|
||||
assert.equal((await models.Mark.findOne({ where: { userId: regular.id, caseId, teamId, markType: 10 } })).mark, 5);
|
||||
await req(`/admin/users/${technical.id}`, null, 204, token, 'DELETE');
|
||||
await req(`/admin/users/${other.id}/cases`, { caseIds: [caseId, otherCaseId] }, 200, token, 'PUT');
|
||||
await req(`/admin/users/${technical.id}/restore`, {}, 409);
|
||||
assert.ok((await models.User.findByPk(technical.id, { paranoid: false })).deletedAt);
|
||||
await req(`/admin/users/${other.id}/cases`, { caseIds: [otherCaseId] }, 200, token, 'PUT');
|
||||
await req(`/admin/users/${technical.id}/restore`, {});
|
||||
await req('/auth/user', null, 401, techToken);
|
||||
await req(`/admin/users/${technical.id}/cases`, { caseIds: [] }, 200, token, 'PUT');
|
||||
const race = await Promise.all(
|
||||
[technical.id, other.id].map(id =>
|
||||
fetch(base + `/admin/users/${id}/cases`, {
|
||||
method: 'PUT',
|
||||
headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ caseIds: [caseId] }),
|
||||
})
|
||||
)
|
||||
);
|
||||
assert.deepEqual(race.map(r => r.status).sort(), [200, 409]);
|
||||
for (const id of [technical.id, other.id]) await req(`/admin/users/${id}/cases`, { caseIds: [] }, 200, token, 'PUT');
|
||||
await req(
|
||||
`/admin/users/${regular.id}`,
|
||||
{ firstName: regular.firstName, lastName: regular.lastName, login: regular.login, role: 'technical' },
|
||||
200,
|
||||
token,
|
||||
'PUT'
|
||||
);
|
||||
await req('/auth/user', null, 401, regularToken);
|
||||
const converted = await login(regular);
|
||||
assert.equal(converted.user.role, 'technical');
|
||||
await save(teamId, [{ markType: 20, mark: 2 }], converted.token);
|
||||
await save(teamId, [{ markType: 10, mark: 2 }], converted.token, 403);
|
||||
const convertedRow = (await req('/admin/marks/details')).details
|
||||
.find(c => c.id === caseId)
|
||||
.rows.find(row => row.userId === regular.id && row.teamId === teamId);
|
||||
assert.equal(convertedRow.marks[10], null);
|
||||
console.log(
|
||||
'PASS technical role, two criteria only, case access, one technical per case including concurrent assignment/restore/role change, shared and late scores, missing reports, totals, no extra ranking vote and revoked session.'
|
||||
);
|
||||
} finally {
|
||||
await models.Mark.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.UserInCase.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.TeamInCase.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.Team.destroy({ where: { id: created.teams }, force: true });
|
||||
await models.User.destroy({ where: { id: created.users }, force: true });
|
||||
await models.Case.destroy({ where: { id: created.cases }, force: true });
|
||||
await sequelize.close();
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Op } from 'sequelize';
|
||||
import { models } from '../models/index.js';
|
||||
import { AppErrorInvalid, SystemError } from './errors.js';
|
||||
|
||||
export async function assignmentCases(caseIds, transaction) {
|
||||
const tasks = await models.Case.findAll({
|
||||
where: { id: caseIds },
|
||||
order: [['id', 'ASC']],
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
transaction,
|
||||
});
|
||||
if (tasks.length !== caseIds.length) throw new AppErrorInvalid('caseIds');
|
||||
return tasks;
|
||||
}
|
||||
|
||||
export async function assertTechnicalAvailable(user, tasks, transaction) {
|
||||
if (user.role !== 'technical') return;
|
||||
for (const task of tasks) {
|
||||
const assigned = await task.getUsers({
|
||||
where: { role: 'technical', id: { [Op.ne]: user.id } },
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
transaction,
|
||||
});
|
||||
if (assigned.length) throw new SystemError(409, `В кейсе «${task.name}» уже назначен технический эксперт.`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import pngjs from 'pngjs';
|
||||
import { SystemError } from './errors.js';
|
||||
|
||||
const MAX_ICON_BYTES = 1024 * 1024;
|
||||
|
||||
export function validateCaseIcon(value) {
|
||||
if (value === null || value === '') return null;
|
||||
if (typeof value !== 'string' || value.length > 22 + 4 * Math.ceil(MAX_ICON_BYTES / 3))
|
||||
throw new SystemError(400, 'Иконка должна быть PNG до 1 МБ.');
|
||||
const match = /^data:image\/png;base64,([A-Za-z0-9+/]+={0,2})$/.exec(value);
|
||||
if (!match) throw new SystemError(400, 'Иконка должна быть в формате PNG.');
|
||||
const buffer = Buffer.from(match[1], 'base64');
|
||||
const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
||||
if (
|
||||
buffer.length < 24 ||
|
||||
buffer.length > MAX_ICON_BYTES ||
|
||||
!buffer.subarray(0, 8).equals(signature) ||
|
||||
buffer.toString('ascii', 12, 16) !== 'IHDR'
|
||||
)
|
||||
throw new SystemError(400, 'Некорректный PNG-файл.');
|
||||
const width = buffer.readUInt32BE(16),
|
||||
height = buffer.readUInt32BE(20);
|
||||
if (!width || !height || width > 1024 || height > 1024)
|
||||
throw new SystemError(400, 'Размер иконки — не более 1024 × 1024 пикселей.');
|
||||
try {
|
||||
pngjs.PNG.sync.read(buffer);
|
||||
} catch (error) {
|
||||
throw new SystemError(400, 'Не удалось прочитать PNG-файл.');
|
||||
}
|
||||
return 'data:image/png;base64,' + buffer.toString('base64');
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { models, sequelize } from '../models/index.js';
|
||||
import setupAssociations from '../models/setupAssociations.js';
|
||||
|
||||
export async function initializeDbModels() {
|
||||
for (const model of Object.values(models)) if (typeof model.initialize === 'function') model.initialize(sequelize);
|
||||
setupAssociations();
|
||||
for (const model of Object.values(models)) await model.sync({ alter: true });
|
||||
if (process.env.NODE_ENV !== 'test') console.log('models initialized');
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import errorCodes from '../config/errorCodes.js';
|
||||
import { toSnakeCase } from 'js-convert-case';
|
||||
|
||||
const errorStatuses = {
|
||||
[errorCodes.NotExist.errNum]: 404,
|
||||
[errorCodes.AlreadyExists.errNum]: 409,
|
||||
[errorCodes.Missing.errNum]: 400,
|
||||
[errorCodes.Invalid.errNum]: 400,
|
||||
[errorCodes.Duplicate.errNum]: 409,
|
||||
|
||||
[errorCodes.NoFileUploaded.errNum]: 400,
|
||||
};
|
||||
|
||||
// errors for application ui
|
||||
export class AppError extends Error {
|
||||
constructor(obj, status = null) {
|
||||
super(obj.message);
|
||||
|
||||
this.errNum = obj.errNum;
|
||||
this.errCode = obj.errCode;
|
||||
this.field = obj.field;
|
||||
|
||||
this.key = obj.key ?? 'APP_ERROR';
|
||||
|
||||
this.status = status ?? errorStatuses[obj.errNum] ?? 400;
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
errNum: this.errNum,
|
||||
errCode: this.errCode,
|
||||
message: this.message,
|
||||
field: this.field,
|
||||
key: this.key,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export class AppErrorMissing extends AppError {
|
||||
constructor(parameter = 'Some', status, key) {
|
||||
super(
|
||||
{
|
||||
...errorCodes.Missing,
|
||||
message: `${parameter} parameter is missing`,
|
||||
|
||||
key: key ?? `MISSING_${toSnakeCase(parameter).toUpperCase()}`,
|
||||
},
|
||||
status
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class AppErrorInvalid extends AppError {
|
||||
constructor(parameter = 'Some', status, key) {
|
||||
super(
|
||||
{
|
||||
...errorCodes.Invalid,
|
||||
message: `${parameter} parameter is invalid`,
|
||||
|
||||
key: key ?? `INVALID_${toSnakeCase(parameter).toUpperCase()}`,
|
||||
},
|
||||
status
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class AppErrorInvalidReplaceMessage extends AppError {
|
||||
constructor(message = errorCodes.Invalid.message, status, key) {
|
||||
super(
|
||||
{
|
||||
...errorCodes.Invalid,
|
||||
message,
|
||||
|
||||
key: key ?? toSnakeCase(message).toUpperCase(),
|
||||
},
|
||||
status
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class AppErrorAlreadyExists extends AppError {
|
||||
constructor(parameter = 'Some', status, key) {
|
||||
super(
|
||||
{
|
||||
...errorCodes.AlreadyExists,
|
||||
message: `${parameter} entity already exists`,
|
||||
|
||||
key: key ?? `EXISTS_${toSnakeCase(parameter).toUpperCase()}`,
|
||||
},
|
||||
status
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class AppErrorNotExist extends AppError {
|
||||
constructor(parameter = 'Some', status, key) {
|
||||
super(
|
||||
{
|
||||
...errorCodes.NotExist,
|
||||
message: `${parameter} entity not exist`,
|
||||
|
||||
key: key ?? `DOES_NOT_EXIST_${toSnakeCase(parameter).toUpperCase()}`,
|
||||
},
|
||||
status
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class AppErrorDuplicate extends AppError {
|
||||
constructor(field = null, status, key) {
|
||||
super(
|
||||
{
|
||||
...errorCodes.Duplicate,
|
||||
field,
|
||||
|
||||
key: key ?? `DUPLICATE_${toSnakeCase(field ?? 'some').toUpperCase()}`,
|
||||
},
|
||||
status
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class AppErrorForbiddenAction extends AppError {
|
||||
constructor(status, key) {
|
||||
super(
|
||||
{
|
||||
errCode: 'Forbidden',
|
||||
message: 'You do not have access to this action',
|
||||
key: key ?? 'FORBIDDEN_ACTION',
|
||||
},
|
||||
status ?? 403
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// error for developer
|
||||
export class SystemError extends Error {
|
||||
constructor(status, err) {
|
||||
super(err);
|
||||
|
||||
this.status = status ?? 400;
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
message: this.message,
|
||||
|
||||
key: 'SYSTEM_ERROR',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function asyncRoute(route) {
|
||||
return (req, res, next = console.error) => {
|
||||
return Promise.resolve(route(req, res, next)).catch(e => next(e));
|
||||
};
|
||||
}
|
||||
|
||||
export default {
|
||||
asyncRoute,
|
||||
|
||||
AppError,
|
||||
SystemError,
|
||||
|
||||
AppErrorMissing,
|
||||
AppErrorInvalid,
|
||||
AppErrorInvalidReplaceMessage,
|
||||
AppErrorAlreadyExists,
|
||||
AppErrorNotExist,
|
||||
AppErrorDuplicate,
|
||||
AppErrorForbiddenAction,
|
||||
};
|
||||
@@ -0,0 +1,101 @@
|
||||
import PDFDocument from 'pdfkit';
|
||||
import QRCode from 'qrcode';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const font = fileURLToPath(new URL('../assets/fonts/DejaVuSans.ttf', import.meta.url));
|
||||
export function loginLink(baseUrl, user) {
|
||||
const url = new URL(baseUrl);
|
||||
url.hash = '/login?' + new URLSearchParams({ l: user.login, p: user.passwordForAdmin });
|
||||
return url.href;
|
||||
}
|
||||
|
||||
// A4, 3 × 4 cards per page. QR modules are vectors with a four-module quiet zone.
|
||||
export function createExpertQrPdf(users, baseUrl) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const doc = new PDFDocument({
|
||||
size: 'A4',
|
||||
margin: 24,
|
||||
autoFirstPage: false,
|
||||
info: { Title: 'Эксперты — QR-коды входа', Author: 'CyberGarden' },
|
||||
});
|
||||
const chunks = [];
|
||||
doc.on('data', chunk => chunks.push(chunk));
|
||||
doc.on('end', () => resolve(Buffer.concat(chunks)));
|
||||
doc.on('error', reject);
|
||||
try {
|
||||
doc.registerFont('Names', font);
|
||||
const technical = users.filter(user => user.role === 'technical');
|
||||
const regular = users.filter(user => user.role !== 'technical');
|
||||
const headingHeight = 22;
|
||||
let column = 0;
|
||||
let rowY = 24;
|
||||
let groupTitle = '';
|
||||
function cardHeight() {
|
||||
return (doc.page.height - 48 - headingHeight) / 4;
|
||||
}
|
||||
function drawHeading() {
|
||||
doc
|
||||
.font('Names')
|
||||
.fontSize(12)
|
||||
.fillColor('#2c634c')
|
||||
.text(groupTitle, 24, rowY + 4, { width: doc.page.width - 48, height: 18 });
|
||||
rowY += headingHeight;
|
||||
}
|
||||
function newPage() {
|
||||
doc.addPage();
|
||||
rowY = 24;
|
||||
column = 0;
|
||||
drawHeading();
|
||||
}
|
||||
function startGroup(title) {
|
||||
groupTitle = title;
|
||||
newPage();
|
||||
}
|
||||
function drawCard(user) {
|
||||
if (!column && rowY + cardHeight() > doc.page.height - 24 + 0.01) newPage();
|
||||
const width = (doc.page.width - 48) / 3;
|
||||
const height = cardHeight();
|
||||
const x = 24 + column * width;
|
||||
const y = rowY;
|
||||
doc.lineWidth(0.4).strokeColor('#d4d4d4').rect(x, y, width, height).stroke();
|
||||
const link = loginLink(baseUrl, user);
|
||||
const matrix = QRCode.create(link, { errorCorrectionLevel: 'M' }).modules;
|
||||
const size = 124;
|
||||
const module = size / (matrix.size + 8);
|
||||
const qrX = x + (width - size) / 2;
|
||||
const qrY = y + 12;
|
||||
doc.fillColor('#ffffff').rect(qrX, qrY, size, size).fill();
|
||||
doc.fillColor('#000000');
|
||||
for (let row = 0; row < matrix.size; row++)
|
||||
for (let col = 0; col < matrix.size; col++) {
|
||||
if (matrix.get(row, col)) doc.rect(qrX + (col + 4) * module, qrY + (row + 4) * module, module, module);
|
||||
}
|
||||
doc.fill();
|
||||
doc.link(qrX, qrY, size, size, link);
|
||||
const fullName = [user.lastName, user.firstName, user.middleName].filter(Boolean).join(' ');
|
||||
const cases = (user.cases || [])
|
||||
.map(task => task.name)
|
||||
.sort((a, b) => a.localeCompare(b, 'ru'))
|
||||
.join(', ');
|
||||
const label = user.role === 'technical' ? fullName + '\n' + (cases || 'Кейс не назначен') : fullName;
|
||||
const textOptions = { width: width - 18, align: 'center', lineGap: 2 };
|
||||
let fontSize = 11;
|
||||
doc.font('Names').fontSize(fontSize);
|
||||
while (doc.heightOfString(label, textOptions) > height - 147 && fontSize > 7) doc.fontSize(--fontSize);
|
||||
doc.fillColor('#000000').text(label, x + 9, y + 142, { ...textOptions, height: height - 147, ellipsis: true });
|
||||
if (++column === 3) {
|
||||
column = 0;
|
||||
rowY += height;
|
||||
}
|
||||
}
|
||||
if (technical.length) startGroup('Тех. эксперты');
|
||||
for (const user of technical) drawCard(user);
|
||||
if (regular.length) startGroup('Эксперты');
|
||||
for (const user of regular) drawCard(user);
|
||||
doc.end();
|
||||
} catch (error) {
|
||||
doc.destroy();
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import markTypes from '../config/markTypes.js';
|
||||
import { AppErrorInvalid } from './errors.js';
|
||||
|
||||
export const technicalMarkTypes = [markTypes.IMPLEMENTATION, markTypes.WORK];
|
||||
export function expertRole(value = 'expert') {
|
||||
if (!['expert', 'technical'].includes(value)) throw new AppErrorInvalid('role');
|
||||
return value;
|
||||
}
|
||||
export function editableMarkTypes(role) {
|
||||
return role === 'technical'
|
||||
? technicalMarkTypes
|
||||
: Object.values(markTypes).filter(type => !technicalMarkTypes.includes(type));
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
const issuer = 'HackathonApp';
|
||||
const audience = process.env.WEB_SERVICE;
|
||||
|
||||
export default {
|
||||
generate(payload = {}, options = {}) {
|
||||
if (!payload.iat) payload.iat = Math.round(+new Date() / 1000);
|
||||
|
||||
return {
|
||||
jwt: jwt.sign(payload, process.env.JWT_KEY, { issuer, audience, ...options }),
|
||||
iat: payload.iat,
|
||||
};
|
||||
},
|
||||
|
||||
verify(key) {
|
||||
return jwt.verify(key, process.env.JWT_KEY, { issuer, audience });
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
export default user => ({
|
||||
id: user.id,
|
||||
login: user.login,
|
||||
role: user.role || 'expert',
|
||||
|
||||
firstName: user.firstName ?? null,
|
||||
lastName: user.lastName ?? null,
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import crypto from 'crypto';
|
||||
|
||||
export default (howMany = 12, chars = 'abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789') => {
|
||||
const rnd = crypto.randomBytes(howMany),
|
||||
value = [],
|
||||
len = Math.min(256, chars.length),
|
||||
d = 256 / len;
|
||||
|
||||
for (let i = 0; i < howMany; i++) {
|
||||
value[i] = chars[Math.floor(rnd[i] / d)];
|
||||
}
|
||||
|
||||
return value.join('');
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
const converter = {
|
||||
а: 'a',
|
||||
б: 'b',
|
||||
в: 'v',
|
||||
г: 'g',
|
||||
д: 'd',
|
||||
е: 'e',
|
||||
ё: 'e',
|
||||
ж: 'zh',
|
||||
з: 'z',
|
||||
и: 'i',
|
||||
й: 'y',
|
||||
к: 'k',
|
||||
л: 'l',
|
||||
м: 'm',
|
||||
н: 'n',
|
||||
о: 'o',
|
||||
п: 'p',
|
||||
р: 'r',
|
||||
с: 's',
|
||||
т: 't',
|
||||
у: 'u',
|
||||
ф: 'f',
|
||||
х: 'h',
|
||||
ц: 'c',
|
||||
ч: 'ch',
|
||||
ш: 'sh',
|
||||
щ: 'sch',
|
||||
ь: '',
|
||||
ы: 'y',
|
||||
ъ: '',
|
||||
э: 'e',
|
||||
ю: 'yu',
|
||||
я: 'ya',
|
||||
|
||||
А: 'A',
|
||||
Б: 'B',
|
||||
В: 'V',
|
||||
Г: 'G',
|
||||
Д: 'D',
|
||||
Е: 'E',
|
||||
Ё: 'E',
|
||||
Ж: 'Zh',
|
||||
З: 'Z',
|
||||
И: 'I',
|
||||
Й: 'Y',
|
||||
К: 'K',
|
||||
Л: 'L',
|
||||
М: 'M',
|
||||
Н: 'N',
|
||||
О: 'O',
|
||||
П: 'P',
|
||||
Р: 'R',
|
||||
С: 'S',
|
||||
Т: 'T',
|
||||
У: 'U',
|
||||
Ф: 'F',
|
||||
Х: 'H',
|
||||
Ц: 'C',
|
||||
Ч: 'Ch',
|
||||
Ш: 'Sh',
|
||||
Щ: 'Sch',
|
||||
Ь: '',
|
||||
Ы: 'Y',
|
||||
Ъ: '',
|
||||
Э: 'E',
|
||||
Ю: 'Yu',
|
||||
Я: 'Ya',
|
||||
};
|
||||
|
||||
export default word => {
|
||||
let answer = '';
|
||||
|
||||
for (var i = 0; i < word.length; ++i) {
|
||||
if (converter[word[i]] === undefined) {
|
||||
answer += word[i];
|
||||
} else {
|
||||
answer += converter[word[i]];
|
||||
}
|
||||
}
|
||||
|
||||
return answer;
|
||||
};
|
||||
Reference in new issue
Block a user