Include complete API and frontend sources for unified deployment

This commit is contained in:
Vladimir Kutkovoy committed 2026-11-18 07:44:20 +00:00
1 parent 627b0ae60e
commit d8fcae32b0
93 files changed
+53270 -3

No files matched your search

+9 -2
View File
@@ -1,6 +1,13 @@
.env.local
artifacts/
hackathon-grading-system/
hackathon-grading-system-front/
*.sql
logo.webp
# Local secrets and generated dependencies
.env
.env.*
!.env.example
node_modules/
.nuxt/
dist/
*.log
+6 -1
View File
@@ -1,5 +1,10 @@
# CyberGarden — запуск
```bash
git clone https://git.skbkit.ru/kutkovoi/CyberGarden-Grade.git
cd CyberGarden-Grade
```
```bash
python3 deployment/init-env.py
docker compose --env-file .env.local up -d --build
@@ -43,7 +48,7 @@ docker compose --env-file .env.local exec -T api node tests/qr-pdf.js
docker compose --env-file .env.local down
```
Исходники и подробные API-описания — в отдельных Git-репозиториях `hackathon-grading-system` и `hackathon-grading-system-front`. Корневой репозиторий хранит конфигурацию развёртывания.
Репозиторий содержит весь проект: API в `hackathon-grading-system`, интерфейс в `hackathon-grading-system-front`, конфигурацию Docker Compose и инструкции запуска в корне. Подробные описания API находятся в README соответствующих каталогов.
## Технические эксперты
@@ -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,20 @@
module.exports = {
root: true,
env: {
browser: true,
node: true
},
parserOptions: {
parser: '@babel/eslint-parser',
requireConfigFile: false
},
extends: [
'@nuxtjs',
'plugin:nuxt/recommended',
'prettier'
],
plugins: [
],
// add your custom rules here
rules: {}
}
+90
View File
@@ -0,0 +1,90 @@
# Created by .ignore support plugin (hsz.mobi)
### Node template
# Logs
/logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# Nuxt generate
dist
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless
# IDE / Editor
.idea
# Service worker
sw.*
# macOS
.DS_Store
# Vim swap files
*.swp
@@ -0,0 +1,11 @@
{
"semi": false,
"arrowParens": "avoid",
"singleQuote": true,
"trailingComma": "es5",
"bracketSpacing": true,
"endOfLine": "lf",
"printWidth": 120,
"useTabs": true,
"tabWidth": 2
}
+40
View File
@@ -0,0 +1,40 @@
# CyberGarden
Nuxt 2 / Vue 2. API на Express + MySQL находится в соседнем проекте `hackathon-grading-system`.
```bash
npm ci
API_BASE_URL=http://localhost:3080 NODE_OPTIONS=--openssl-legacy-provider npm run dev
# Статическая сборка за обратным прокси /api/
API_BASE_URL=/api NODE_OPTIONS=--openssl-legacy-provider npm run generate
```
Сборка воспроизводится на Node 18. `API_BASE_URL` задаётся при сборке.
## Страницы
- `/login` — логотип, логин, пароль и вход.
- `/` — назначенные эксперту кейсы и команды, оценки 0–5.
- `/admin` — список и создание кейсов.
- `/admin/cases/:id` — изменение кейса, создание и изменение команд, два критерия организатора, список назначенных экспертов.
- `/admin/users` — добавление экспертов, просмотр данных входа, назначение одного или нескольких кейсов.
- `/admin/marks` — рейтинг, пропущенные и нулевые оценки. API использует функции из серверных `scripts/calc-positions.js` и `scripts/no-marks.js`.
Палитра и общие стили — `assets/css/app.css`. Каркас — `components/AppShell.vue`. Формы редактирования используют нативный `dialog`. Эксперт отправляет только свои критерии; отмена и ошибка сохранения сохраняют исходные данные.
## Проверки
```bash
npx eslint pages components layouts nuxt.config.js --ext .js,.vue
npx stylelint assets/css/app.css
```
На странице «Эксперты» доступны редактирование ФИО, логина и пароля, удаление с подтверждением, восстановление на вкладке «Удалённые». Оценки при удалении сохраняются. Пустое поле нового пароля оставляет прежний пароль.
Кнопка «QR-коды PDF» скачивает один PDF со всеми активными экспертами, независимо от поиска: A4, 12 карточек на страницу (3 × 4), QR-код и ФИО. В диалоге задаётся адрес приложения, доступный экспертам с телефона. Ссылка открывает форму входа с заполненными логином и паролем.
Иконки кейсов загружаются в формах создания и изменения: PNG до 256 КБ и 1024 × 1024 пикселей, с предварительным просмотром и удалением. В «Результатах» вкладка «Все оценки» показывает все критерии для каждой пары команда — эксперт, с фильтром по кейсу. Критерии технических экспертов помечены «(тех.)».
У экспертов бокового меню нет. Меню администратора скрывается кнопкой «Меню»; выбор сохраняется на компьютере. На мобильных экранах меню открывается поверх страницы и закрывается после перехода. Dev-сервер слушает `0.0.0.0`; в Docker используется порт 3081 на всех интерфейсах, API — относительный `/api/`.
Для QR-кодов адрес по умолчанию — `https://cg.vkhost.ru/`, независимо от адреса, через который открыт кабинет администратора.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,52 @@
<template>
<svg
:width="size"
:height="size"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.65"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path v-for="(path, index) in paths" :key="index" :d="path" />
</svg>
</template>
<script>
const icons = {
leaf: ['M12 21V11', 'M12 16C4 16 3 11 3 7c6 0 9 2 9 7', 'M12 11c0-6 3-8 9-8 0 6-3 9-9 9'],
grid: ['M3 3h7v7H3z', 'M14 3h7v7h-7z', 'M3 14h7v7H3z', 'M14 14h7v7h-7z'],
users: [
'M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2',
'M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8',
'M17 4a4 4 0 0 1 0 8',
'M22 21v-2a4 4 0 0 0-3-3.87',
],
chart: ['M4 20h16', 'M7 16v-5', 'M12 16V4', 'M17 16V8'],
arrow: ['M5 12h14', 'm13 6 6 6-6 6'],
back: ['M19 12H5', 'm11 6-6 6 6 6'],
check: ['m5 12 4 4L19 6'],
search: ['M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16', 'm17 17 4 4'],
logout: ['M9 21H4V3h5', 'M10 12h11', 'm17 8 4 4-4 4'],
close: ['m6 6 12 12', 'M6 18 18 6'],
plus: ['M12 5v14', 'M5 12h14'],
lock: ['M5 11h14v10H5z', 'M8 11V7a4 4 0 0 1 8 0v4'],
info: ['M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20', 'M12 11v6', 'M12 7h.01'],
clock: ['M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20', 'M12 6v6l4 2'],
file: ['M14 2H4v20h16V8z', 'M14 2v6h6', 'M8 13h8', 'M8 17h5'],
eye: ['M2 12s3-7 10-7 10 7 10 7-3 7-10 7S2 12 2 12', 'M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6'],
copy: ['M8 8h13v13H8z', 'M16 4V2H2v14h2'],
award: ['M12 15a6 6 0 1 0 0-12 6 6 0 0 0 0 12', 'm8 14-1 8 5-3 5 3-1-8'],
menu: ['M4 6h16', 'M4 12h16', 'M4 18h16'],
}
export default {
props: { name: { type: String, default: 'grid' }, size: { type: [Number, String], default: 20 } },
computed: {
paths() {
return icons[this.name] || icons.grid
},
},
}
</script>
@@ -0,0 +1,105 @@
<template>
<div class="app-shell simple-shell" :class="{ 'menu-open': isAdmin && menuOpen }">
<a class="skip-link" href="#main-content" @click.prevent="focusMain">Перейти к содержимому</a>
<button
v-if="isAdmin && menuOpen"
class="menu-backdrop"
type="button"
aria-label="Закрыть меню"
@click="toggleMenu"
/>
<aside v-if="isAdmin && menuOpen" id="admin-sidebar" class="sidebar">
<div class="sidebar-heading">
<NuxtLink to="/admin" class="brand" aria-label="CyberGarden — главная"
><img src="/logo2026.png" alt="" width="32" height="30" /><strong>CyberGarden</strong></NuxtLink
>
</div>
<nav class="main-nav" aria-label="Основная навигация">
<NuxtLink
v-for="item in navigation"
:key="item.to"
:to="item.to"
:exact="item.to !== '/admin'"
class="nav-item"
:class="{ 'current-nav': item.to === '/admin' && $route.path.startsWith('/admin/cases') }"
@click.native="closeOnMobile"
><AppIcon :name="item.icon" :size="18" /><span>{{ item.label }}</span></NuxtLink
>
</nav>
</aside>
<div class="workspace">
<header class="workspace-header">
<button
v-if="isAdmin"
class="button menu-toggle"
type="button"
:aria-expanded="String(menuOpen)"
aria-controls="admin-sidebar"
:aria-label="menuOpen ? 'Скрыть меню' : 'Показать меню'"
@click="toggleMenu"
>
<AppIcon name="menu" :size="18" /></button
><NuxtLink v-else to="/" class="compact-brand" aria-label="CyberGarden — кейсы"
><img src="/logo2026.png" width="36" height="34" alt="" /><strong>CyberGarden</strong></NuxtLink
>
<div class="header-profile">
<span>{{ fullName }}</span
><button class="icon-button" type="button" aria-label="Выйти" @click="exit">
<AppIcon name="logout" :size="18" />
</button>
</div>
</header>
<main id="main-content" class="main-content" tabindex="-1"><Nuxt /></main>
</div>
</div>
</template>
<script>
export default {
data() {
return { menuOpen: false }
},
computed: {
isAdmin() {
return this.$route.path.startsWith('/admin') || this.$auth.user?.login === 'admin'
},
fullName() {
const user = this.$auth.user || {}
return (
[
user.firstName || localStorage.getItem('user.firstName'),
user.lastName || localStorage.getItem('user.lastName'),
]
.filter(Boolean)
.join(' ') || (this.isAdmin ? 'Администратор' : 'Эксперт')
)
},
navigation() {
return [
{ to: '/admin', icon: 'file', label: 'Кейсы' },
{ to: '/admin/users', icon: 'users', label: 'Эксперты' },
{ to: '/admin/marks', icon: 'chart', label: 'Результаты' },
]
},
},
mounted() {
this.menuOpen = window.innerWidth > 800 && localStorage.getItem('admin.menuOpen') !== 'false'
},
methods: {
toggleMenu() {
this.menuOpen = !this.menuOpen
if (window.innerWidth > 800) localStorage.setItem('admin.menuOpen', String(this.menuOpen))
},
closeOnMobile() {
if (window.innerWidth <= 800) this.menuOpen = false
},
focusMain() {
const main = this.$el.querySelector('#main-content')
main.focus()
main.scrollIntoView({ block: 'start' })
},
async exit() {
await this.$auth.logout()
},
},
}
</script>
@@ -0,0 +1,6 @@
<template>
<span class="case-picture"><img v-if="src" :src="src" alt="" /><AppIcon v-else name="file" :size="22" /></span>
</template>
<script>
export default { props: { src: { type: String, default: null } } }
</script>
@@ -0,0 +1,65 @@
<template>
<div class="icon-upload field">
<label :for="inputId"><span>Иконка кейса (PNG)</span></label>
<div class="icon-upload-controls">
<CaseIcon :src="value" /><input
:id="inputId"
ref="file"
type="file"
accept="image/png,.png"
:disabled="disabled"
@change="select"
/><button v-if="value || error" class="button button-sm" type="button" :disabled="disabled" @click="remove">
Убрать
</button>
</div>
<p class="muted">До 1 МБ, не более 1024 × 1024 пикселей.</p>
<div v-if="error" class="form-error" role="alert">{{ error }}</div>
</div>
</template>
<script>
export default {
props: { value: { type: String, default: null }, disabled: Boolean },
data() {
return { error: '', inputId: 'case-icon-file' }
},
methods: {
select(event) {
this.error = ''
event.target.setCustomValidity('')
const file = event.target.files[0]
if (!file) return
if (file.type !== 'image/png' || file.size > 1024 * 1024) {
this.fail('Выберите PNG-файл размером до 1 МБ.')
return
}
event.target.setCustomValidity('Дождитесь загрузки иконки.')
const reader = new FileReader()
reader.onerror = () => this.fail('Не удалось прочитать файл.')
reader.onload = () => {
const image = new Image()
image.onload = () => {
if (image.width > 1024 || image.height > 1024) this.fail('Размер иконки — не более 1024 × 1024 пикселей.')
else {
event.target.setCustomValidity('')
this.$emit('input', reader.result)
}
}
image.onerror = () => this.fail('Не удалось прочитать PNG-файл.')
image.src = reader.result
}
reader.readAsDataURL(file)
},
fail(message) {
this.error = message
this.$refs.file.setCustomValidity(message)
},
remove() {
this.$emit('input', null)
this.error = ''
this.$refs.file.value = ''
this.$refs.file.setCustomValidity('')
},
},
}
</script>
@@ -0,0 +1,40 @@
<template>
<dialog ref="dialog" class="score-dialog form-dialog" aria-labelledby="form-dialog-title" @cancel.prevent="close">
<form @submit.prevent="$emit('save')">
<div class="dialog-header">
<h2 id="form-dialog-title">{{ title }}</h2>
<button class="icon-button" type="button" aria-label="Закрыть" :disabled="busy" @click="close">
<AppIcon name="close" />
</button>
</div>
<div class="dialog-body"><slot /></div>
<div class="dialog-footer dialog-footer-actions">
<button class="button" type="button" :disabled="busy" @click="close">Отмена</button
><button class="button button-primary" :class="{ 'button-danger': danger }" type="submit" :disabled="busy">
{{ busy ? 'Сохраняем…' : submitLabel }}
</button>
</div>
</form>
</dialog>
</template>
<script>
export default {
props: {
title: { type: String, required: true },
busy: Boolean,
danger: Boolean,
submitLabel: { type: String, default: 'Сохранить' },
},
mounted() {
this.$refs.dialog.showModal()
},
beforeDestroy() {
this.$refs.dialog.close()
},
methods: {
close() {
if (!this.busy) this.$emit('close')
},
},
}
</script>
@@ -0,0 +1,47 @@
<template>
<th scope="col" :aria-sort="active ? (direction === 'asc' ? 'ascending' : 'descending') : 'none'">
<button class="sort-header" type="button" @click="$emit('sort')">
<span><slot /></span>
<span class="sort-indicator" :class="{ active }" aria-hidden="true">{{
active ? (direction === 'asc' ? '↑' : '↓') : '↕'
}}</span>
</button>
</th>
</template>
<script>
export default {
props: {
active: { type: Boolean, default: false },
direction: { type: String, default: 'asc' },
},
}
</script>
<style scoped>
.sort-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
width: 100%;
padding: 0;
border: 0;
background: transparent;
color: inherit;
font: inherit;
text-align: left;
cursor: pointer;
}
.sort-header:hover,
.sort-header:focus-visible {
color: var(--primary, #28634c);
}
.sort-indicator {
flex-shrink: 0;
opacity: 0.45;
}
.sort-indicator.active {
opacity: 1;
}
</style>
@@ -0,0 +1,7 @@
<template>
<AppShell />
</template>
<script>
export default { name: 'Default', middleware: 'auth' }
</script>
@@ -0,0 +1,3 @@
<template>
<Nuxt />
</template>
@@ -0,0 +1,4 @@
export default function ({ $auth, redirect }) {
if (!$auth.loggedIn) return redirect('/login')
if ($auth.user?.login === 'admin') return redirect('/admin')
}
@@ -0,0 +1,103 @@
export default {
// Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode
ssr: false,
server: { host: '0.0.0.0' },
// Target: https://go.nuxtjs.dev/config-target
target: 'static',
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'Система оценки',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{
hid: 'description',
name: 'description',
content: 'Пространство оценки проектов и команд хакатона CyberGarden',
},
{ name: 'format-detection', content: 'telephone=no' },
],
link: [{ rel: 'icon', type: 'image/png', href: '/icon.png' }],
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: ['~/assets/css/app.css'],
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
// https://go.nuxtjs.dev/eslint
'@nuxtjs/eslint-module',
// https://go.nuxtjs.dev/stylelint
'@nuxtjs/stylelint-module',
// https://go.nuxtjs.dev/tailwindcss
'@nuxtjs/tailwindcss',
// https://go.nuxtjs.dev/pwa
'@nuxtjs/pwa',
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/axios
'@nuxtjs/axios',
'@nuxtjs/auth-next',
'nuxt-vue-material',
],
// Axios module configuration: https://go.nuxtjs.dev/config-axios
axios: {
baseURL: process.env.API_BASE_URL || 'https://api.cybergarden.ru',
},
vueMaterial: {},
router: {
mode: 'hash',
},
auth: {
rewriteRedirect: false,
resetOnError: true,
redirect: {
login: '/login',
logout: '/login',
home: false,
},
strategies: {
local: {
token: {
property: 'token',
maxAge: false,
},
user: {
property: 'user',
autoFetch: true,
},
endpoints: {
login: { url: '/auth/login', method: 'post' },
logout: { url: '/auth/logout', method: 'post' },
user: { url: '/auth/user', method: 'get' },
},
},
},
},
// PWA module configuration: https://go.nuxtjs.dev/pwa
pwa: {
manifest: {
name: 'CyberGarden',
start_url: '/',
lang: 'ru',
},
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {},
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,40 @@
{
"name": "hackathon-grading-system-front",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate",
"lint:js": "eslint --ext \".js,.vue\" --ignore-path .gitignore .",
"lint:style": "stylelint \"**/*.{vue,css}\" --ignore-path .gitignore",
"lint": "npm run lint:js && npm run lint:style"
},
"dependencies": {
"@nuxtjs/auth-next": "5.0.0-1637745161.ea53f98",
"@nuxtjs/axios": "^5.13.6",
"@nuxtjs/pwa": "^3.3.5",
"core-js": "^3.15.1",
"nuxt": "^2.15.7",
"nuxt-vue-material": "^1.2.0",
"sass": "^1.44.0"
},
"devDependencies": {
"@babel/eslint-parser": "^7.14.7",
"@nuxt/types": "~2.15.0",
"@nuxtjs/eslint-config": "^6.0.1",
"@nuxtjs/eslint-module": "^3.0.2",
"@nuxtjs/stylelint-module": "^4.0.0",
"@nuxtjs/tailwindcss": "^4.2.0",
"eslint": "^7.29.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-nuxt": "^2.0.0",
"eslint-plugin-vue": "^7.12.1",
"postcss": "^8.3.5",
"prettier": "^2.3.2",
"stylelint": "^13.13.1",
"stylelint-config-prettier": "^8.0.2",
"stylelint-config-standard": "^22.0.0"
}
}
@@ -0,0 +1,369 @@
<template>
<div>
<NuxtLink to="/admin" class="back-link"><AppIcon name="back" :size="15" /> Кейсы</NuxtLink>
<div class="page-heading">
<div class="case-title">
<CaseIcon :src="task.icon" />
<h1>{{ task.name }}</h1>
</div>
<button class="button" type="button" @click="editCase">Изменить</button>
</div>
<p v-if="task.description" class="plain-description">{{ task.description }}</p>
<div class="section-heading">
<h2>Команды</h2>
<button class="button button-primary" type="button" @click="editTeam()">
<AppIcon name="plus" :size="16" /> Добавить команду
</button>
</div>
<div v-if="scoreError" class="form-error" role="alert">{{ scoreError }}</div>
<div class="panel">
<div class="table-scroll">
<table class="data-table">
<thead>
<tr>
<SortHeader
v-for="column in teamColumns"
:key="column.key"
:active="teamSortKey === column.key"
:direction="teamSortDirection"
@sort="sortTeamsBy(column.key)"
>{{ column.name }}</SortHeader
>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr v-for="team in sortedTeams" :key="team.id">
<td>
<strong>{{ team.name }}</strong>
<p v-if="team.description" class="table-description">{{ team.description }}</p>
<p
v-if="team.TeamInCase && team.TeamInCase.technicalComment"
class="table-description technical-comment-text"
>
Комментарий тех. эксперта: {{ team.TeamInCase.technicalComment }}
</p>
</td>
<td>
<input
class="score-input"
type="number"
min="0"
max="5"
step="1"
:value="implementation[team.id]"
:aria-label="'Качество реализации — ' + team.name"
:disabled="savingScores"
@input="setScore(implementation, team.id, $event)"
/>
</td>
<td>
<input
class="score-input"
type="number"
min="0"
max="5"
step="1"
:value="work[team.id]"
:aria-label="'Работа на хакатоне — ' + team.name"
:disabled="savingScores"
@input="setScore(work, team.id, $event)"
/>
</td>
<td>
<button
class="button button-sm"
type="button"
:aria-label="'Изменить команду ' + team.name"
@click="editTeam(team)"
>
Изменить
</button>
</td>
</tr>
<tr v-if="!task.teams.length">
<td colspan="4" class="table-empty">Команд пока нет.</td>
</tr>
</tbody>
</table>
</div>
</div>
<div v-if="task.teams.length" class="save-row">
<span class="muted">{{
task.users.length ? 'Оценки тех. экспертов · 0–5' : 'Сначала назначьте экспертов в разделе «Эксперты».'
}}</span
><button
class="button button-primary"
type="button"
:disabled="savingScores || !task.users.length"
@click="saveScores"
>
{{ savingScores ? 'Сохраняем…' : 'Сохранить оценки' }}
</button>
</div>
<div class="section-heading" style="margin-top: 32px">
<h2>Эксперты</h2>
<div ref="assignmentPicker" class="assignment-picker" @keydown.esc.prevent.stop="closeAssignments">
<button
ref="assignmentButton"
type="button"
class="button button-sm"
:aria-expanded="String(assignmentOpen)"
aria-controls="case-expert-picker"
:disabled="savingAssignments"
@click="toggleAssignments"
>
Назначить
</button>
<div v-if="assignmentOpen" id="case-expert-picker" class="assignment-dropdown">
<input
v-model="expertSearch"
class="text-input"
type="search"
aria-label="Найти эксперта"
placeholder="Найти эксперта"
/>
<p v-if="loadingAssignments" class="muted">Загрузка…</p>
<div v-else class="assignment-options">
<label v-for="user in filteredAssignmentUsers" :key="user.id" class="checkbox-row">
<input
type="checkbox"
:checked="isAssigned(user)"
:disabled="savingAssignments"
@change="setAssignment(user, $event)"
/>
<span
>{{ [user.lastName, user.firstName, user.middleName].filter(Boolean).join(' ')
}}{{ user.role === 'technical' ? ' · Технический эксперт' : '' }}</span
>
</label>
<p v-if="!filteredAssignmentUsers.length" class="muted">Эксперты не найдены.</p>
</div>
<div v-if="assignmentError" class="form-error" role="alert">{{ assignmentError }}</div>
</div>
</div>
</div>
<div class="panel">
<div v-for="user in task.users" :key="user.id" class="simple-row">
<span>{{ [user.lastName, user.firstName, user.middleName].filter(Boolean).join(' ') }}</span>
<span v-if="user.role === 'technical'" class="badge">Технический эксперт</span>
</div>
<div v-if="!task.users.length" class="table-empty">Эксперты не назначены.</div>
</div>
<FormDialog
v-if="editor"
:title="editor === 'case' ? 'Изменить кейс' : teamId ? 'Изменить команду' : 'Новая команда'"
:busy="saving"
@close="editor = null"
@save="save"
><label class="field" for="entityName"
><span>Название</span
><input id="entityName" v-model.trim="name" class="text-input" maxlength="255" required /></label
><label class="field" for="entityDescription"
><span>Описание</span
><textarea id="entityDescription" v-model.trim="description" class="text-input" maxlength="10000" rows="3" />
</label>
<CaseIconUpload v-if="editor === 'case'" v-model="icon" :disabled="saving" />
<div v-if="error" class="form-error" role="alert">{{ error }}</div></FormDialog
>
<div v-if="message" class="toast" role="status">{{ message }}</div>
</div>
</template>
<script>
export default {
name: 'CaseDetails',
async asyncData({ $axios, params, error }) {
const [{ cases }, { marks }] = await Promise.all([$axios.$get('/admin/cases'), $axios.$get('/admin')])
const task = cases.find(c => c.id === params.id)
if (!task) {
error({ statusCode: 404, message: 'Кейс не найден' })
return {}
}
return { task, implementation: marks.implementation, work: marks.work }
},
data() {
return {
task: { name: '', teams: [], users: [] },
implementation: {},
work: {},
editor: null,
teamId: null,
name: '',
description: '',
icon: null,
saving: false,
error: '',
savingScores: false,
scoreError: '',
message: '',
timer: null,
assignmentOpen: false,
assignmentUsers: [],
expertSearch: '',
loadingAssignments: false,
savingAssignments: false,
assignmentError: '',
teamSortKey: 'name',
teamSortDirection: 'asc',
teamColumns: [
{ key: 'name', name: 'Команда' },
{ key: 'implementation', name: 'Качество реализации (тех.)' },
{ key: 'work', name: 'Работа на хакатоне (тех.)' },
],
}
},
computed: {
sortedTeams() {
const direction = this.teamSortDirection === 'asc' ? 1 : -1
return [...this.task.teams].sort((a, b) => {
const nameOrder = a.name.localeCompare(b.name, 'ru', { numeric: true, sensitivity: 'base' })
if (this.teamSortKey === 'name') return direction * nameOrder
const left = this[this.teamSortKey][a.id]
const right = this[this.teamSortKey][b.id]
const leftMissing = left === null || left === undefined || left === ''
const rightMissing = right === null || right === undefined || right === ''
if (leftMissing || rightMissing) return leftMissing === rightMissing ? nameOrder : leftMissing ? 1 : -1
return direction * (Number(left) - Number(right)) || nameOrder
})
},
filteredAssignmentUsers() {
const search = this.expertSearch.trim().toLowerCase()
return this.assignmentUsers.filter(user =>
[user.lastName, user.firstName, user.middleName].filter(Boolean).join(' ').toLowerCase().includes(search)
)
},
},
mounted() {
document.addEventListener('click', this.assignmentOutsideClick)
},
beforeDestroy() {
clearTimeout(this.timer)
document.removeEventListener('click', this.assignmentOutsideClick)
},
methods: {
sortTeamsBy(key) {
this.teamSortDirection = this.teamSortKey === key && this.teamSortDirection === 'asc' ? 'desc' : 'asc'
this.teamSortKey = key
},
isAssigned(user) {
return user.cases.some(task => task.id === this.task.id)
},
closeAssignments() {
if (this.savingAssignments) return
this.assignmentOpen = false
this.$refs.assignmentButton?.focus()
},
assignmentOutsideClick(event) {
if (!this.savingAssignments && !this.$refs.assignmentPicker?.contains(event.target)) this.assignmentOpen = false
},
async toggleAssignments() {
this.assignmentOpen = !this.assignmentOpen
if (!this.assignmentOpen) return
this.expertSearch = ''
this.assignmentError = ''
this.loadingAssignments = true
try {
const { users } = await this.$axios.$get('/admin/users')
this.assignmentUsers = users.filter(user => !user.deletedAt)
} catch (e) {
this.assignmentUsers = []
this.assignmentError = 'Не удалось загрузить экспертов.'
} finally {
this.loadingAssignments = false
}
},
async setAssignment(user, event) {
if (this.savingAssignments) return
const checked = event.target.checked
const caseIds = user.cases.filter(task => task.id !== this.task.id).map(task => task.id)
if (checked) caseIds.push(this.task.id)
this.savingAssignments = true
this.assignmentError = ''
try {
await this.$axios.$put('/admin/users/' + user.id + '/cases', { caseIds })
user.cases = user.cases.filter(task => task.id !== this.task.id)
this.task.users = this.task.users.filter(expert => expert.id !== user.id)
if (checked) {
user.cases.push({ id: this.task.id, name: this.task.name })
const { id, firstName, lastName, middleName, login, role } = user
this.task.users.push({ id, firstName, lastName, middleName, login, role })
}
} catch (e) {
event.target.checked = this.isAssigned(user)
this.assignmentError = e.response?.data?.message || 'Не удалось сохранить назначение. Попробуйте ещё раз.'
} finally {
this.savingAssignments = false
}
},
async reload() {
const { cases } = await this.$axios.$get('/admin/cases')
this.task = cases.find(c => c.id === this.$route.params.id)
},
editCase() {
this.editor = 'case'
this.name = this.task.name
this.description = this.task.description
this.icon = this.task.icon || null
this.error = ''
},
editTeam(team) {
this.editor = 'team'
this.teamId = team?.id || null
this.name = team?.name || ''
this.description = team?.description || ''
this.error = ''
},
async save() {
if (this.saving || !this.name) return
this.saving = true
this.error = ''
try {
const body = { name: this.name, description: this.description || '' }
const base = '/admin/cases/' + this.task.id
if (this.editor === 'case') await this.$axios.$put(base, { ...body, icon: this.icon })
else if (this.teamId) await this.$axios.$put(base + '/teams/' + this.teamId, body)
else await this.$axios.$post(base + '/teams', body)
await this.reload()
this.editor = null
} catch (e) {
this.error = 'Не удалось сохранить изменения.'
} finally {
this.saving = false
}
},
setScore(target, id, event) {
const value =
event.target.value === '' ? '' : Math.min(5, Math.max(0, Math.round(Number(event.target.value) || 0)))
this.$set(target, id, value)
event.target.value = value
},
async saveScores() {
if (this.savingScores) return
this.scoreError = ''
const values = this.task.teams.map(team => ({
id: team.id,
implementation: this.implementation[team.id],
work: this.work[team.id],
}))
const filled = value => value !== '' && value !== undefined && value !== null
if (values.some(m => filled(m.implementation) !== filled(m.work))) {
this.scoreError = 'Заполните оба критерия для команды.'
return
}
this.savingScores = true
try {
await this.$axios.$post('/admin', { marks: values.filter(m => filled(m.implementation) && filled(m.work)) })
this.message = 'Оценки сохранены'
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.message = ''
}, 3500)
} catch (e) {
this.scoreError = 'Не удалось сохранить оценки.'
} finally {
this.savingScores = false
}
},
},
}
</script>
@@ -0,0 +1,73 @@
<template>
<div>
<div class="page-heading">
<h1>Кейсы</h1>
<button class="button button-primary" type="button" @click="editing = true">
<AppIcon name="plus" :size="16" /> Добавить кейс
</button>
</div>
<div class="panel">
<NuxtLink v-for="task in cases" :key="task.id" :to="'/admin/cases/' + task.id" class="simple-row"
><div class="case-row-label">
<CaseIcon :src="task.icon" />
<div>
<strong>{{ task.name }}</strong>
<p>{{ task.teams.length }} команд · {{ task.users.length }} экспертов</p>
</div>
</div>
<AppIcon name="arrow" :size="18"
/></NuxtLink>
<div v-if="!cases.length" class="table-empty">Кейсов пока нет.</div>
</div>
<FormDialog
v-if="editing"
title="Новый кейс"
:busy="saving"
submit-label="Добавить"
@close="
editing = false
error = ''
"
@save="save"
><label class="field" for="caseName"
><span>Название</span
><input id="caseName" v-model.trim="name" class="text-input" maxlength="255" required /></label
><label class="field" for="caseDescription"
><span>Описание</span
><textarea id="caseDescription" v-model.trim="description" class="text-input" maxlength="10000" rows="3" />
</label>
<CaseIconUpload v-model="icon" :disabled="saving" />
<div v-if="error" class="form-error" role="alert">{{ error }}</div></FormDialog
>
</div>
</template>
<script>
export default {
name: 'AdminCases',
async asyncData({ $axios }) {
return await $axios.$get('/admin/cases')
},
data() {
return { cases: [], editing: false, name: '', description: '', icon: null, saving: false, error: '' }
},
methods: {
async save() {
if (this.saving || !this.name) return
this.saving = true
this.error = ''
try {
const { case: task } = await this.$axios.$post('/admin/cases', {
name: this.name,
description: this.description,
icon: this.icon,
})
await this.$router.push('/admin/cases/' + task.id)
} catch (e) {
this.error = 'Не удалось добавить кейс.'
} finally {
this.saving = false
}
},
},
}
</script>
@@ -0,0 +1,317 @@
<template>
<div>
<div class="page-heading">
<h1>Результаты</h1>
<button class="button" type="button" :disabled="refreshing" @click="refresh">
{{ refreshing ? 'Обновляем…' : 'Обновить' }}
</button>
</div>
<div class="toolbar">
<div class="tabs report-tabs" role="group" aria-label="Отчёт">
<button
v-for="item in tabs"
:key="item.id"
class="tab"
:class="{ active: tab === item.id }"
:aria-pressed="String(tab === item.id)"
type="button"
@click="tab = item.id"
>
{{ item.name }}
</button>
</div>
<select v-model="selectedCase" class="filter-select" aria-label="Кейс">
<option value="">Все кейсы</option>
<option v-for="(name, id) in cases" :key="id" :value="id">{{ name }}</option>
</select>
</div>
<div v-if="error" class="form-error" role="alert">{{ error }}</div>
<template v-if="tab === 'ranking'"
><section v-for="(ranking, id) in filteredPositions" :key="id" class="panel report-section">
<div class="panel-header">
<h2>{{ cases[id] }}</h2>
</div>
<div class="table-scroll">
<table class="data-table">
<thead>
<tr>
<SortHeader
v-for="column in rankingColumns"
:key="column.key"
:active="sorting.key === column.key"
:direction="sorting.direction"
@sort="sortBy(column.key)"
>{{ column.name }}</SortHeader
>
</tr>
</thead>
<tbody>
<tr v-for="[teamId, place] in sortedRanking(ranking)" :key="teamId">
<td style="width: 80px">{{ place }}</td>
<td>{{ teams[teamId] }}</td>
</tr>
</tbody>
</table>
</div>
</section>
<div v-if="!Object.keys(filteredPositions).length" class="panel table-empty">Оценок пока нет.</div></template
>
<template v-else-if="tab === 'details'">
<section v-for="task in filteredDetails" :key="task.id" class="panel report-section">
<div class="panel-header">
<h2>{{ task.name }}</h2>
</div>
<div class="table-scroll">
<table class="data-table all-marks-table">
<thead>
<tr>
<SortHeader
v-for="column in detailColumns"
:key="column.key"
:active="sorting.key === column.key"
:direction="sorting.direction"
@sort="sortBy(column.key)"
>{{ column.name }}</SortHeader
>
</tr>
</thead>
<tbody>
<tr v-for="row in sortedDetails(task.rows)" :key="row.teamId + row.userId">
<td>{{ row.team }}</td>
<td>{{ row.expert }}<span v-if="row.role === 'technical'" class="badge">Технический эксперт</span></td>
<td v-for="(_, type) in criteria" :key="type">
{{ row.marks[type] === null ? '—' : row.marks[type] }}
</td>
<td>{{ row.total === null ? '—' : row.total }}</td>
</tr>
<tr v-if="!task.rows.length">
<td :colspan="Object.keys(criteria).length + 3" class="table-empty">
Нет назначенных экспертов или команд.
</td>
</tr>
</tbody>
</table>
</div>
</section>
<div v-if="!filteredDetails.length" class="panel table-empty">Кейсов пока нет.</div>
</template>
<section v-else class="panel">
<div class="table-scroll">
<table class="data-table">
<thead>
<tr>
<SortHeader
v-for="column in reportColumns"
:key="column.key"
:active="sorting.key === column.key"
:direction="sorting.direction"
@sort="sortBy(column.key)"
>{{ column.name }}</SortHeader
>
</tr>
</thead>
<template v-if="tab === 'zero'">
<tbody v-for="group in zeroGroups" :key="group.id">
<tr v-for="(row, index) in group.rows" :key="index">
<td v-if="index === 0" :rowspan="group.rows.length">{{ group.user }}</td>
<td>{{ row.task }}</td>
<td class="assignment-cell">{{ row.teams[0] }}</td>
<td class="assignment-cell">{{ row.criterion }}</td>
<td>0</td>
</tr>
</tbody>
</template>
<tbody v-if="tab !== 'zero' || !reportRows.length">
<tr v-for="(row, index) in reportRows" :key="index">
<td>{{ row.user }}</td>
<td>{{ row.task }}</td>
<td class="assignment-cell">{{ row.teams.join(', ') }}</td>
<td v-if="tab === 'zero'">{{ row.criterion }}</td>
<td v-if="tab === 'zero'">0</td>
</tr>
<tr v-if="!reportRows.length">
<td :colspan="reportColumns.length" class="table-empty">
{{ tab === 'missing' ? 'Все оценки заполнены.' : 'Нулевых оценок нет.' }}
</td>
</tr>
</tbody>
</table>
</div>
</section>
</div>
</template>
<script>
export default {
name: 'Results',
async asyncData({ $axios }) {
const [missing, ranking, detail] = await Promise.all([
$axios.$get('/admin/marks'),
$axios.$get('/admin/positions'),
$axios.$get('/admin/marks/details'),
])
return { ...missing, ...ranking, ...detail }
},
data() {
return {
noMarks: {},
zeroMarks: {},
positions: {},
details: [],
criteria: {},
cases: {},
teams: {},
selectedCase: '',
tab: 'ranking',
sorts: {
ranking: { key: 'place', direction: 'asc' },
details: { key: '', direction: 'asc' },
missing: { key: '', direction: 'asc' },
zero: { key: '', direction: 'asc' },
},
rankingColumns: [
{ key: 'place', name: 'Место' },
{ key: 'team', name: 'Команда' },
],
missingColumns: [
{ key: 'user', name: 'Эксперт' },
{ key: 'task', name: 'Кейс' },
{ key: 'teams', name: 'Команды' },
],
refreshing: false,
error: '',
tabs: [
{ id: 'ranking', name: 'Рейтинг' },
{ id: 'details', name: 'Все оценки' },
{ id: 'missing', name: 'Без оценок' },
{ id: 'zero', name: 'Нулевые оценки' },
],
}
},
computed: {
zeroGroups() {
if (this.tab !== 'zero') return []
const groups = new Map()
for (const row of this.reportRows) {
if (!groups.has(row.userId)) groups.set(row.userId, { id: row.userId, user: row.user, rows: [] })
groups.get(row.userId).rows.push(row)
}
const direction = this.sorting.key === 'user' && this.sorting.direction === 'desc' ? -1 : 1
return [...groups.values()].sort(
(a, b) => direction * a.user.localeCompare(b.user, 'ru', { sensitivity: 'base', numeric: true })
)
},
reportColumns() {
if (this.tab !== 'zero') return this.missingColumns
return [
{ key: 'user', name: 'Эксперт' },
{ key: 'task', name: 'Кейс' },
{ key: 'teams', name: 'Команда' },
{ key: 'criterion', name: 'Критерий' },
{ key: 'value', name: 'Оценка' },
]
},
sorting() {
return this.sorts[this.tab]
},
detailColumns() {
return [
{ key: 'team', name: 'Команда' },
{ key: 'expert', name: 'Эксперт' },
...Object.entries(this.criteria).map(([type, name]) => ({
key: 'mark:' + type,
name: name + ([20, 30].includes(+type) ? ' (тех.)' : ''),
})),
{ key: 'total', name: 'Сумма' },
]
},
filteredDetails() {
return this.details.filter(task => !this.selectedCase || task.id === this.selectedCase)
},
filteredPositions() {
return this.selectedCase
? this.positions[this.selectedCase]
? { [this.selectedCase]: this.positions[this.selectedCase] }
: {}
: this.positions
},
reportRows() {
if (this.tab === 'zero') {
const rows = this.filteredDetails.flatMap(task =>
task.rows.flatMap(row => {
const types = Object.entries(row.marks)
.filter(([, value]) => value === 0)
.map(([type]) => type)
return types.length
? [
{
userId: row.userId,
user: row.expert + (row.role === 'technical' ? ' (тех.)' : ''),
task: task.name,
teams: [row.team],
criterion: types
.map(type => this.criteria[type] + ([20, 30].includes(+type) ? ' (тех.)' : ''))
.join(', '),
value: 0,
},
]
: []
})
)
return this.sortRows(rows, (row, key) => (key === 'teams' ? row.teams[0] : row[key]))
}
const data = this.noMarks
const rows = Object.entries(data).flatMap(([user, tasks]) =>
Object.entries(tasks)
.filter(([name]) => !this.selectedCase || name === this.cases[this.selectedCase])
.map(([task, teams]) => ({ user, task, teams }))
)
return this.sortRows(rows, (row, key) => (key === 'teams' ? row.teams.join(', ') : row[key]))
},
},
methods: {
sortBy(key) {
this.$set(this.sorts, this.tab, {
key,
direction: this.sorting.key === key && this.sorting.direction === 'asc' ? 'desc' : 'asc',
})
},
sortRows(rows, value) {
const { key, direction } = this.sorting
if (!key) return rows
return [...rows].sort((a, b) => {
const left = value(a, key)
const right = value(b, key)
if (left == null) return right == null ? 0 : 1
if (right == null) return -1
const result =
typeof left === 'number' && typeof right === 'number'
? left - right
: String(left).localeCompare(String(right), 'ru', { numeric: true, sensitivity: 'base' })
return direction === 'asc' ? result : -result
})
},
sortedDetails(rows) {
return this.sortRows(rows, (row, key) => (key.startsWith('mark:') ? row.marks[key.slice(5)] : row[key]))
},
sortedRanking(ranking) {
return this.sortRows(Object.entries(ranking), (row, key) => (key === 'place' ? row[1] : this.teams[row[0]]))
},
async refresh() {
this.refreshing = true
this.error = ''
try {
const [missing, ranking, detail] = await Promise.all([
this.$axios.$get('/admin/marks'),
this.$axios.$get('/admin/positions'),
this.$axios.$get('/admin/marks/details'),
])
Object.assign(this, missing, ranking, detail)
} catch (e) {
this.error = 'Не удалось обновить результаты.'
} finally {
this.refreshing = false
}
},
},
}
</script>
@@ -0,0 +1,452 @@
<template>
<div>
<div class="page-heading expert-heading">
<h1>Эксперты</h1>
<div class="expert-header-actions">
<button class="button" type="button" :disabled="!activeCount" @click="openExport">QR-коды PDF</button
><button class="button button-primary" type="button" @click="openNew">
<AppIcon name="plus" :size="16" /> Добавить эксперта
</button>
</div>
</div>
<div class="toolbar">
<div class="tabs" role="group" aria-label="Статус эксперта">
<button
v-for="tab in tabs"
:key="tab.id"
class="tab"
:class="{ active: filter === tab.id }"
:aria-pressed="String(filter === tab.id)"
type="button"
@click="filter = tab.id"
>
{{ tab.name }}
</button>
</div>
<label class="search-box"
><AppIcon name="search" :size="16" /><input
v-model="search"
type="search"
aria-label="Найти эксперта"
placeholder="Найти эксперта"
/></label>
</div>
<div v-if="pageError" class="form-error" role="alert">{{ pageError }}</div>
<div class="panel">
<div class="table-scroll">
<table class="data-table">
<thead>
<tr>
<th scope="col">Эксперт</th>
<th scope="col">Роль</th>
<th scope="col">Логин / пароль</th>
<th scope="col">Кейсы</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr v-for="user in filteredUsers" :key="user.id">
<td>{{ fullName(user) }}</td>
<td>{{ user.role === 'technical' ? 'Технический эксперт' : 'Эксперт' }}</td>
<td>
<span class="mono">{{ user.login }}</span>
<div class="password-cell">
<span class="mono">{{ revealed[user.id] ? user.passwordForAdmin || '—' : '••••••••' }}</span
><button
v-if="user.passwordForAdmin"
class="icon-button"
type="button"
:aria-label="(revealed[user.id] ? 'Скрыть пароль: ' : 'Показать пароль: ') + user.login"
:aria-pressed="String(!!revealed[user.id])"
@click="$set(revealed, user.id, !revealed[user.id])"
>
<AppIcon name="eye" :size="15" />
</button>
</div>
</td>
<td class="assignment-cell">{{ user.cases.map(c => c.name).join(', ') || 'Не назначены' }}</td>
<td>
<div class="expert-actions">
<template v-if="!user.deletedAt"
><button
class="button button-sm"
type="button"
:aria-label="'Назначить кейсы: ' + user.login"
:disabled="saving"
@click="assign(user)"
>
Кейсы</button
><button
class="button button-sm"
type="button"
:aria-label="'Изменить эксперта: ' + user.login"
:disabled="saving"
@click="openEdit(user)"
>
Изменить</button
><button
class="button button-sm danger-text"
type="button"
:aria-label="'Удалить эксперта: ' + user.login"
:disabled="saving"
@click="openDelete(user)"
>
Удалить
</button></template
><button
v-else
class="button button-sm"
type="button"
:disabled="saving"
:aria-label="'Восстановить эксперта: ' + user.login"
@click="restore(user)"
>
Восстановить
</button>
</div>
</td>
</tr>
<tr v-if="!filteredUsers.length">
<td colspan="5" class="table-empty">Эксперты не найдены.</td>
</tr>
</tbody>
</table>
</div>
</div>
<FormDialog
v-if="editor === 'new' || editor === 'edit'"
:title="editor === 'new' ? 'Новый эксперт' : 'Изменить эксперта'"
:busy="saving"
:submit-label="editor === 'new' ? 'Добавить' : 'Сохранить'"
@close="editor = null"
@save="saveUser"
><label class="field" for="lastName"
><span>Фамилия</span
><input
id="lastName"
v-model.trim="draft.lastName"
class="text-input"
maxlength="50"
autocomplete="family-name"
required /></label
><label class="field" for="firstName"
><span>Имя</span
><input
id="firstName"
v-model.trim="draft.firstName"
class="text-input"
maxlength="50"
autocomplete="given-name"
required /></label
><label class="field" for="middleName"
><span>Отчество</span
><input
id="middleName"
v-model.trim="draft.middleName"
class="text-input"
maxlength="50"
autocomplete="additional-name" /></label
><template v-if="editor === 'edit'"
><label class="field" for="expertLogin"
><span>Логин</span
><input
id="expertLogin"
v-model.trim="draft.login"
class="text-input"
minlength="2"
maxlength="100"
pattern="[a-zA-Z0-9_.@\-]+"
autocomplete="off"
required /></label
><label class="field" for="expertPassword"
><span>Новый пароль</span
><input
id="expertPassword"
v-model="draft.password"
class="text-input"
type="password"
placeholder="Не менять"
minlength="6"
maxlength="72"
autocomplete="new-password" /></label
></template>
<label class="field" for="expertRole">
<span>Роль</span>
<select id="expertRole" v-model="draft.role" class="text-input" aria-label="Роль" :disabled="saving">
<option value="expert">Эксперт</option>
<option value="technical">Технический эксперт</option>
</select>
</label>
<div v-if="editor === 'new'" class="field">
<span>Кейсы</span>
<div class="checkbox-list">
<label v-for="task in cases" :key="task.id" class="checkbox-row">
<input v-model="selectedCaseIds" type="checkbox" :value="task.id" :disabled="saving" />
<span>{{ task.name }}</span>
</label>
<p v-if="!cases.length" class="muted">Сначала добавьте кейсы.</p>
</div>
</div>
<div v-if="error" class="form-error" role="alert">{{ error }}</div></FormDialog
>
<FormDialog
v-if="editor === 'cases'"
:title="fullName(selectedUser)"
:busy="saving"
@close="editor = null"
@save="saveAssignments"
><div class="checkbox-list">
<label v-for="task in cases" :key="task.id" class="checkbox-row"
><input v-model="selectedCaseIds" type="checkbox" :value="task.id" :disabled="saving" /><span>{{
task.name
}}</span></label
>
<p v-if="!cases.length" class="muted">Сначала добавьте кейсы.</p>
</div>
<div v-if="error" class="form-error" role="alert">{{ error }}</div></FormDialog
>
<FormDialog
v-if="editor === 'delete'"
title="Удалить эксперта?"
:busy="saving"
submit-label="Удалить"
danger
@close="editor = null"
@save="deleteUser"
><p>{{ fullName(selectedUser) }}</p>
<p class="muted" style="margin-top: 12px">Доступ будет закрыт. Оценки сохранятся.</p>
<div v-if="error" class="form-error" role="alert" style="margin-top: 16px">{{ error }}</div></FormDialog
>
<FormDialog
v-if="editor === 'export'"
title="QR-коды экспертов"
:busy="exporting"
submit-label="Скачать PDF"
@close="editor = null"
@save="downloadQr"
><label class="field" for="baseUrl"
><span>Адрес приложения</span
><input
id="baseUrl"
v-model.trim="baseUrl"
class="text-input"
type="url"
maxlength="300"
placeholder="https://grading.example.ru/"
required
/></label>
<p class="muted">Все активные эксперты · A4 · 3 × 4 карточки</p>
<p v-if="localAddress" class="muted" style="margin-top: 10px">
Для входа с телефона укажите адрес, доступный экспертам.
</p>
<div v-if="error" class="form-error" role="alert" style="margin-top: 16px">{{ error }}</div></FormDialog
>
<div v-if="message" class="toast" role="status">{{ message }}</div>
</div>
</template>
<script>
export default {
name: 'Experts',
async asyncData({ $axios }) {
const [{ users }, { cases }] = await Promise.all([$axios.$get('/admin/users'), $axios.$get('/admin/cases')])
return { users, cases }
},
data() {
return {
users: [],
cases: [],
search: '',
filter: 'active',
tabs: [
{ id: 'active', name: 'Активные' },
{ id: 'deleted', name: 'Удалённые' },
],
revealed: {},
editor: null,
selectedUser: null,
selectedCaseIds: [],
draft: { firstName: '', lastName: '', middleName: '', login: '', password: '', role: 'expert' },
error: '',
pageError: '',
saving: false,
exporting: false,
baseUrl: '',
message: '',
timer: null,
}
},
computed: {
activeCount() {
return this.users.filter(u => !u.deletedAt).length
},
filteredUsers() {
const query = this.search.toLowerCase()
return this.users.filter(
u =>
(this.filter === 'deleted' ? !!u.deletedAt : !u.deletedAt) &&
`${this.fullName(u)} ${u.login}`.toLowerCase().includes(query)
)
},
localAddress() {
try {
return ['localhost', '127.0.0.1', '[::1]'].includes(new URL(this.baseUrl).hostname)
} catch (e) {
return false
}
},
},
beforeDestroy() {
clearTimeout(this.timer)
},
methods: {
fullName(user) {
return [user.lastName, user.firstName, user.middleName].filter(Boolean).join(' ')
},
async reload() {
const { users } = await this.$axios.$get('/admin/users')
this.users = users
},
notify(message) {
this.message = message
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.message = ''
}, 3500)
},
openNew() {
this.draft = { firstName: '', lastName: '', middleName: '', login: '', password: '', role: 'expert' }
this.selectedCaseIds = []
this.error = ''
this.editor = 'new'
},
openEdit(user) {
this.selectedUser = user
this.draft = {
firstName: user.firstName,
lastName: user.lastName,
middleName: user.middleName || '',
login: user.login,
password: '',
role: user.role || 'expert',
}
this.error = ''
this.editor = 'edit'
},
openDelete(user) {
this.selectedUser = user
this.error = ''
this.editor = 'delete'
},
openExport() {
this.baseUrl = 'https://cg.vkhost.ru/'
this.error = ''
this.editor = 'export'
},
assign(user) {
this.selectedUser = user
this.selectedCaseIds = user.cases.map(c => c.id)
this.error = ''
this.editor = 'cases'
},
async saveUser() {
if (this.saving) return
this.saving = true
this.error = ''
try {
if (this.editor === 'new')
await this.$axios.$post('/admin/users', { ...this.draft, caseIds: this.selectedCaseIds })
else await this.$axios.$put('/admin/users/' + this.selectedUser.id, this.draft)
await this.reload()
this.editor = null
this.revealed = {}
this.filter = 'active'
this.search = ''
this.notify('Эксперт сохранён')
} catch (e) {
this.error =
e.response?.status === 409
? e.response.data.key === 'SYSTEM_ERROR'
? e.response.data.message
: 'Эксперт или логин уже существует.'
: 'Не удалось сохранить эксперта. Проверьте ФИО, логин и пароль.'
} finally {
this.saving = false
}
},
async deleteUser() {
if (this.saving) return
this.saving = true
this.error = ''
try {
await this.$axios.$delete('/admin/users/' + this.selectedUser.id)
await this.reload()
this.editor = null
this.revealed = {}
this.notify('Эксперт удалён')
} catch (e) {
this.error = 'Не удалось удалить эксперта.'
} finally {
this.saving = false
}
},
async restore(user) {
if (this.saving) return
this.saving = true
this.pageError = ''
try {
await this.$axios.$post('/admin/users/' + user.id + '/restore')
await this.reload()
this.notify('Эксперт восстановлен')
} catch (e) {
this.pageError = e.response?.data?.message || 'Не удалось восстановить эксперта.'
} finally {
this.saving = false
}
},
async saveAssignments() {
if (this.saving) return
this.saving = true
this.error = ''
try {
await this.$axios.$put('/admin/users/' + this.selectedUser.id + '/cases', { caseIds: this.selectedCaseIds })
await this.reload()
this.editor = null
this.notify('Кейсы назначены')
} catch (e) {
this.error = e.response?.data?.message || 'Не удалось сохранить назначения.'
} finally {
this.saving = false
}
},
async downloadQr() {
if (this.exporting) return
this.exporting = true
this.error = ''
try {
const response = await this.$axios.post(
'/admin/users/qr-pdf',
{ baseUrl: this.baseUrl },
{ responseType: 'blob' }
)
const url = URL.createObjectURL(response.data)
const link = document.createElement('a')
link.href = url
link.download = 'experts-qr.pdf'
document.body.appendChild(link)
link.click()
link.remove()
setTimeout(() => URL.revokeObjectURL(url), 10000)
this.editor = null
} catch (e) {
let message = ''
try {
message = JSON.parse(await e.response.data.text()).message
} catch (ignored) {}
this.error = message || 'Не удалось скачать PDF. Попробуйте ещё раз.'
} finally {
this.exporting = false
}
},
},
}
</script>
@@ -0,0 +1,5 @@
<script>
import ExpertCases from '../index.vue'
export default { ...ExpertCases, name: 'ExpertCase' }
</script>
@@ -0,0 +1,375 @@
<template>
<div>
<button v-if="selectedCase" class="back-link" type="button" @click="home">
<AppIcon name="back" :size="15" /> Кейсы
</button>
<div class="page-heading">
<div class="case-title">
<CaseIcon v-if="selectedCase" :src="currentCase.icon" />
<h1>{{ selectedCase ? currentCase.name : 'Кейсы' }}</h1>
</div>
</div>
<div class="panel">
<button
v-for="item in items"
:key="item.id"
class="simple-row clickable-row"
type="button"
:aria-label="(selectedCase ? 'Оценить ' : 'Открыть ') + item.name"
@click="selectItem(item.id)"
>
<span class="case-row-label">
<CaseIcon v-if="!selectedCase" :src="item.icon" />
<span>
<strong>{{ item.name }}</strong>
<span v-if="item.description" class="row-description">{{ item.description }}</span>
<span v-if="!selectedCase" class="row-description"
>{{ item.teams.length }} {{ teamWord(item.teams.length) }}</span
>
<span v-if="selectedCase && isComplete(item)" class="badge team-status-mobile">Оценено</span>
</span>
</span>
<span class="row-actions">
<span v-if="selectedCase && isComplete(item)" class="badge team-status-desktop">Оценено</span
><span class="button" aria-hidden="true">
{{ selectedCase ? 'Оценить' : 'Открыть' }}
</span>
</span>
</button>
<div v-if="!items.length" class="table-empty">
{{ selectedCase ? 'Команд пока нет.' : 'Кейсы не назначены.' }}
</div>
</div>
<dialog
ref="scoreDialog"
class="score-dialog team-score-dialog"
aria-labelledby="score-title"
@cancel="closeScore"
@click="backdropClick"
>
<template v-if="team"
><div class="dialog-header">
<div>
<h2 id="score-title">{{ team.name }}</h2>
</div>
<button class="icon-button" type="button" aria-label="Закрыть оценки" :disabled="saving" @click="closeScore">
<AppIcon name="close" />
</button>
</div>
<div class="dialog-body">
<p v-if="loadingScore" class="muted" role="status">Загрузка…</p>
<div v-if="loadError" class="form-error" role="alert">
Не удалось загрузить оценки и комментарий. Откройте команду ещё раз.
</div>
<div v-if="saveError" class="form-error" role="alert">
Не удалось сохранить изменения. Попробуйте ещё раз.
</div>
<div v-for="(criterion, index) in editableCriteria" :key="criterion.type" class="score-criterion">
<div :id="'criterion-' + criterion.type" class="criterion-heading">
<span
><span class="criterion-index">0{{ index + 1 }}</span
>{{ criterion.name }}</span
><span>{{ draft[criterion.type] }} / 5</span>
</div>
<div class="score-scale" role="group" :aria-labelledby="'criterion-' + criterion.type">
<button
v-for="value in [0, 1, 2, 3, 4, 5]"
:key="value"
class="score-option"
:class="{ selected: draft[criterion.type] === value }"
:aria-pressed="String(draft[criterion.type] === value)"
:aria-label="criterion.name + ': ' + value"
:disabled="saving || loadingScore || loadError"
type="button"
@click="$set(draft, criterion.type, value)"
>
{{ value }}
</button>
</div>
<div class="scale-labels"><span>Не проявлено</span><span>Отлично</span></div>
</div>
<div v-if="isTechnicalExpert" class="field technical-comment-editor">
<label for="technicalComment">Комментарий</label>
<textarea
id="technicalComment"
v-model="draftComment"
class="text-input"
maxlength="5000"
rows="4"
:disabled="saving || loadingScore || loadError"
@input="commentSaved = false"
/>
<button
class="button button-sm"
type="button"
:disabled="saving || loadingScore || loadError"
@click="save(true)"
>
Сохранить комментарий
</button>
<p v-if="commentSaved" class="muted" role="status">Комментарий сохранён</p>
</div>
<section v-if="!isTechnicalExpert && team.technicalComment" class="technical-comment">
<h3>Комментарий тех. эксперта</h3>
<p>{{ team.technicalComment }}</p>
</section>
<div v-if="!isTechnicalExpert" class="admin-criteria">
<div class="admin-criteria-title"><AppIcon name="lock" :size="13" /> Оценки тех. экспертов</div>
<div v-for="criterion in lockedCriteria" :key="criterion.type" class="locked-score">
<span>{{ criterion.name }}</span
><strong>{{ savedMark(criterion.type) }} / 5</strong>
</div>
</div>
</div>
<div class="dialog-footer">
<div class="score-total">
Ваша оценка<strong
>{{ draftTotal }} <span>/ {{ editableCriteria.length * 5 }}</span></strong
>
</div>
<div class="dialog-footer-actions">
<button class="button button-quiet" type="button" :disabled="saving" @click="closeScore">Отмена</button
><button
class="button button-primary"
type="button"
:disabled="saving || loadingScore || loadError"
@click="save()"
>
<AppIcon name="check" :size="16" /> {{ saving ? 'Сохраняем…' : 'Сохранить оценки' }}
</button>
</div>
</div></template
>
</dialog>
<Transition name="fade"
><div v-if="saved" class="toast" role="status">
<AppIcon name="check" :size="17" /> {{ savedMessage }}
</div></Transition
>
</div>
</template>
<script>
export default {
name: 'Index',
middleware: 'home',
async asyncData({ $axios, $auth, params, error }) {
try {
const [{ cases }, appdata] = await Promise.all([$axios.$get('/cases'), $axios.$get('/system/appdata')])
if (params.id && !cases?.some(task => task.id === params.id)) {
error({ statusCode: 404, message: 'Кейс не найден' })
return {}
}
return { cases: cases || [], appdata }
} catch (e) {
await $auth.logout()
return { cases: [], appdata: { markType: {}, markTypesNames: {} } }
}
},
data() {
return {
cases: [],
appdata: { markType: {}, markTypesNames: {} },
selectedTeam: null,
showScore: false,
saving: false,
saveError: false,
loadingScore: false,
loadError: false,
scoreRequest: 0,
draftComment: '',
commentSaved: false,
savedMessage: 'Оценки сохранены',
saved: false,
draft: {},
search: '',
filter: 'all',
toastTimer: null,
tabs: [
{ id: 'all', label: 'Все' },
{ id: 'pending', label: 'К оценке' },
{ id: 'done', label: 'Оценено' },
],
}
},
computed: {
isTechnicalExpert() {
return this.$auth.user?.role === 'technical'
},
selectedCase() {
return this.$route.params.id || null
},
currentCase() {
return this.cases.find(c => c.id === this.selectedCase)
},
items() {
return this.currentCase?.teams || this.cases
},
team() {
return this.currentCase?.teams.find(t => t.id === this.selectedTeam)
},
allTeams() {
return this.cases.flatMap(c => c.teams)
},
relevantTeams() {
return this.currentCase?.teams || this.allTeams
},
completedTeams() {
return this.relevantTeams.filter(this.teamComplete).length
},
criteria() {
return Object.entries(this.appdata.markTypesNames).map(([type, name]) => ({ type: +type, name }))
},
editableCriteria() {
return this.criteria.filter(c => this.isTechnicalExpert === this.isAdminOnlyMarkType(c.type))
},
lockedCriteria() {
return this.criteria.filter(c => this.isAdminOnlyMarkType(c.type))
},
draftTotal() {
return this.editableCriteria.reduce((total, c) => total + (this.draft[c.type] || 0), 0)
},
visibleItems() {
return this.items.filter(
item =>
item.name.toLowerCase().includes(this.search.toLowerCase()) &&
(this.filter === 'all' || (this.filter === 'done' ? this.isComplete(item) : !this.isComplete(item)))
)
},
},
beforeDestroy() {
clearTimeout(this.toastTimer)
this.scoreRequest++
},
methods: {
isAdminOnlyMarkType(type) {
return type === this.appdata.markType.WORK || type === this.appdata.markType.IMPLEMENTATION
},
teamComplete(team) {
return (
this.editableCriteria.length > 0 &&
this.editableCriteria.every(c => team.marks.some(m => m.markType === c.type && m.mark !== null))
)
},
isComplete(item) {
return this.selectedCase ? this.teamComplete(item) : item.teams.length > 0 && item.teams.every(this.teamComplete)
},
itemCompleted(item) {
return this.selectedCase
? this.editableCriteria.filter(c => item.marks.some(m => m.markType === c.type && m.mark !== null)).length
: item.teams.filter(this.teamComplete).length
},
itemTotal(item) {
return this.selectedCase ? this.editableCriteria.length : item.teams.length
},
teamWord(n) {
return n % 10 === 1 && n % 100 !== 11
? 'команда'
: [2, 3, 4].includes(n % 10) && ![12, 13, 14].includes(n % 100)
? 'команды'
: 'команд'
},
savedMark(type) {
return this.team?.marks.find(m => m.markType === type)?.mark ?? '—'
},
home() {
this.$router.push('/')
},
fillDraft() {
this.commentSaved = false
this.draftComment = this.team.technicalComment || ''
this.draft = Object.fromEntries(
this.editableCriteria.map(c => [c.type, Math.min(5, Math.max(0, Number(this.savedMark(c.type)) || 0))])
)
},
async selectItem(id) {
if (!this.selectedCase) {
this.$router.push('/cases/' + id)
return
}
this.selectedTeam = id
this.saveError = false
this.loadError = false
this.loadingScore = true
const request = ++this.scoreRequest
this.showScore = true
this.fillDraft()
this.$nextTick(() => this.$refs.scoreDialog.showModal())
try {
const data = await this.$axios.$get(`/cases/${this.selectedCase}/teams/${id}/marks`)
if (request !== this.scoreRequest) return
this.$set(this.team, 'marks', data.marks)
this.$set(this.team, 'technicalComment', data.technicalComment || '')
this.fillDraft()
} catch (e) {
if (request === this.scoreRequest) this.loadError = true
} finally {
if (request === this.scoreRequest) this.loadingScore = false
}
},
closeScore(event) {
if (this.saving) {
event?.preventDefault()
return
}
this.$refs.scoreDialog.close()
this.showScore = false
this.scoreRequest++
this.loadingScore = false
},
backdropClick(event) {
if (event.target !== this.$refs.scoreDialog) return
const rect = event.target.getBoundingClientRect()
if (
event.clientX < rect.left ||
event.clientX > rect.right ||
event.clientY < rect.top ||
event.clientY > rect.bottom
)
this.closeScore(event)
},
async save(commentOnly = false) {
if (this.saving || this.loadingScore || this.loadError) return
const marks = commentOnly
? []
: this.editableCriteria.map(c => ({
markType: c.type,
mark: Math.min(5, Math.max(0, Number(this.draft[c.type]) || 0)),
}))
this.saveError = false
this.commentSaved = false
this.saving = true
try {
await this.$axios.put(`/cases/${this.selectedCase}/teams/${this.selectedTeam}/marks`, {
marks,
...(this.isTechnicalExpert ? { technicalComment: this.draftComment } : {}),
})
if (this.isTechnicalExpert) {
this.draftComment = this.draftComment.trim()
this.$set(this.team, 'technicalComment', this.draftComment)
}
for (const { markType, mark } of marks) {
const existing = this.team.marks.find(m => m.markType === markType)
if (existing) existing.mark = mark
else this.team.marks.push({ markType, mark })
}
if (!commentOnly) {
this.$refs.scoreDialog.close()
this.showScore = false
}
this.savedMessage = commentOnly ? 'Комментарий сохранён' : 'Оценки сохранены'
this.commentSaved = commentOnly
this.saved = true
clearTimeout(this.toastTimer)
this.toastTimer = setTimeout(() => {
this.saved = false
}, 4500)
} catch (e) {
this.saveError = true
} finally {
this.saving = false
}
},
},
}
</script>
@@ -0,0 +1,68 @@
<template>
<main class="login-page">
<form class="login-form" aria-label="Вход" @submit.prevent="userLogin">
<img class="login-logo" src="/logo2026.png" alt="CyberGarden" width="180" height="170" />
<h1 class="login-title">Система оценки команд</h1>
<div v-if="error" class="form-error" role="alert">{{ error }}</div>
<input
id="login"
v-model.trim="login.login"
class="text-input"
name="username"
autocomplete="username"
aria-label="Логин"
placeholder="Логин"
required
/>
<input
id="password"
v-model="login.password"
class="text-input"
name="password"
type="password"
autocomplete="current-password"
aria-label="Пароль"
placeholder="Пароль"
required
/>
<button class="button button-primary" type="submit" :disabled="loading">
{{ loading ? 'Входим…' : 'Войти' }}
</button>
</form>
</main>
</template>
<script>
export default {
name: 'Login',
layout: 'empty',
data() {
return { login: { login: '', password: '' }, loading: false, error: '' }
},
mounted() {
this.login.login = this.$route.query.l ?? ''
this.login.password = this.$route.query.p ?? ''
},
methods: {
async userLogin() {
if (this.loading) return
this.loading = true
this.error = ''
try {
const { data } = await this.$auth.loginWith('local', { data: this.login })
this.$auth.setUser(data.user)
localStorage.setItem('user.firstName', data.user.firstName || '')
localStorage.setItem('user.lastName', data.user.lastName || '')
await this.$router.push(data.user.login === 'admin' ? '/admin' : '/')
} catch (e) {
this.error =
e.response?.status === 403
? 'Проверьте логин и пароль и попробуйте ещё раз.'
: 'Не удалось войти. Проверьте соединение и попробуйте ещё раз.'
} finally {
this.loading = false
}
},
},
}
</script>
Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 319 KiB

@@ -0,0 +1 @@
export const state = () => ({})
@@ -0,0 +1,9 @@
module.exports = {
extends: [
'stylelint-config-standard',
'stylelint-config-prettier'
],
// add your custom config here
// https://stylelint.io/user-guide/configuration
rules: {}
}
+6
View File
@@ -0,0 +1,6 @@
node_modules
.env
.idea
.git
*.log
config/google-credentials.js
+13
View File
@@ -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
+16
View File
@@ -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"
}
}
+6
View File
@@ -0,0 +1,6 @@
node_modules/
.env
.idea/
.DS_Store
*.log
config/google-credentials.js
+11
View File
@@ -0,0 +1,11 @@
{
"semi": true,
"arrowParens": "avoid",
"singleQuote": true,
"trailingComma": "es5",
"bracketSpacing": true,
"endOfLine": "lf",
"printWidth": 120,
"useTabs": true,
"tabWidth": 2
}
+7
View File
@@ -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": ""
}
]
}
+70
View File
@@ -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'.
+12
View File
@@ -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
+84
View File
@@ -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();
});
+27
View File
@@ -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();
});
}
}
+35
View File
@@ -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 };
+36
View File
@@ -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' });
}
+26
View File
@@ -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',
}
);
}
}
+60
View File
@@ -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',
}
);
}
}
File diff suppressed because it is too large. Load diff
+35
View File
@@ -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"
}
}
+36
View File
@@ -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;
+12
View File
@@ -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;
+17
View File
@@ -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;
});
+53
View File
@@ -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');
}
+9
View File
@@ -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');
}
+172
View File
@@ -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));
}
+19
View File
@@ -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;
};
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 319 KiB