Include complete API and frontend sources for unified deployment
This commit is contained in:
1 parent
627b0ae60e
commit
d8fcae32b0
93 files changed
+53270
-3
No files matched your search
@@ -0,0 +1,26 @@
|
||||
import { Op } from 'sequelize';
|
||||
import { models } from '../models/index.js';
|
||||
import { AppErrorInvalid, SystemError } from './errors.js';
|
||||
|
||||
export async function assignmentCases(caseIds, transaction) {
|
||||
const tasks = await models.Case.findAll({
|
||||
where: { id: caseIds },
|
||||
order: [['id', 'ASC']],
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
transaction,
|
||||
});
|
||||
if (tasks.length !== caseIds.length) throw new AppErrorInvalid('caseIds');
|
||||
return tasks;
|
||||
}
|
||||
|
||||
export async function assertTechnicalAvailable(user, tasks, transaction) {
|
||||
if (user.role !== 'technical') return;
|
||||
for (const task of tasks) {
|
||||
const assigned = await task.getUsers({
|
||||
where: { role: 'technical', id: { [Op.ne]: user.id } },
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
transaction,
|
||||
});
|
||||
if (assigned.length) throw new SystemError(409, `В кейсе «${task.name}» уже назначен технический эксперт.`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import pngjs from 'pngjs';
|
||||
import { SystemError } from './errors.js';
|
||||
|
||||
const MAX_ICON_BYTES = 1024 * 1024;
|
||||
|
||||
export function validateCaseIcon(value) {
|
||||
if (value === null || value === '') return null;
|
||||
if (typeof value !== 'string' || value.length > 22 + 4 * Math.ceil(MAX_ICON_BYTES / 3))
|
||||
throw new SystemError(400, 'Иконка должна быть PNG до 1 МБ.');
|
||||
const match = /^data:image\/png;base64,([A-Za-z0-9+/]+={0,2})$/.exec(value);
|
||||
if (!match) throw new SystemError(400, 'Иконка должна быть в формате PNG.');
|
||||
const buffer = Buffer.from(match[1], 'base64');
|
||||
const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
||||
if (
|
||||
buffer.length < 24 ||
|
||||
buffer.length > MAX_ICON_BYTES ||
|
||||
!buffer.subarray(0, 8).equals(signature) ||
|
||||
buffer.toString('ascii', 12, 16) !== 'IHDR'
|
||||
)
|
||||
throw new SystemError(400, 'Некорректный PNG-файл.');
|
||||
const width = buffer.readUInt32BE(16),
|
||||
height = buffer.readUInt32BE(20);
|
||||
if (!width || !height || width > 1024 || height > 1024)
|
||||
throw new SystemError(400, 'Размер иконки — не более 1024 × 1024 пикселей.');
|
||||
try {
|
||||
pngjs.PNG.sync.read(buffer);
|
||||
} catch (error) {
|
||||
throw new SystemError(400, 'Не удалось прочитать PNG-файл.');
|
||||
}
|
||||
return 'data:image/png;base64,' + buffer.toString('base64');
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { models, sequelize } from '../models/index.js';
|
||||
import setupAssociations from '../models/setupAssociations.js';
|
||||
|
||||
export async function initializeDbModels() {
|
||||
for (const model of Object.values(models)) if (typeof model.initialize === 'function') model.initialize(sequelize);
|
||||
setupAssociations();
|
||||
for (const model of Object.values(models)) await model.sync({ alter: true });
|
||||
if (process.env.NODE_ENV !== 'test') console.log('models initialized');
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import errorCodes from '../config/errorCodes.js';
|
||||
import { toSnakeCase } from 'js-convert-case';
|
||||
|
||||
const errorStatuses = {
|
||||
[errorCodes.NotExist.errNum]: 404,
|
||||
[errorCodes.AlreadyExists.errNum]: 409,
|
||||
[errorCodes.Missing.errNum]: 400,
|
||||
[errorCodes.Invalid.errNum]: 400,
|
||||
[errorCodes.Duplicate.errNum]: 409,
|
||||
|
||||
[errorCodes.NoFileUploaded.errNum]: 400,
|
||||
};
|
||||
|
||||
// errors for application ui
|
||||
export class AppError extends Error {
|
||||
constructor(obj, status = null) {
|
||||
super(obj.message);
|
||||
|
||||
this.errNum = obj.errNum;
|
||||
this.errCode = obj.errCode;
|
||||
this.field = obj.field;
|
||||
|
||||
this.key = obj.key ?? 'APP_ERROR';
|
||||
|
||||
this.status = status ?? errorStatuses[obj.errNum] ?? 400;
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
errNum: this.errNum,
|
||||
errCode: this.errCode,
|
||||
message: this.message,
|
||||
field: this.field,
|
||||
key: this.key,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export class AppErrorMissing extends AppError {
|
||||
constructor(parameter = 'Some', status, key) {
|
||||
super(
|
||||
{
|
||||
...errorCodes.Missing,
|
||||
message: `${parameter} parameter is missing`,
|
||||
|
||||
key: key ?? `MISSING_${toSnakeCase(parameter).toUpperCase()}`,
|
||||
},
|
||||
status
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class AppErrorInvalid extends AppError {
|
||||
constructor(parameter = 'Some', status, key) {
|
||||
super(
|
||||
{
|
||||
...errorCodes.Invalid,
|
||||
message: `${parameter} parameter is invalid`,
|
||||
|
||||
key: key ?? `INVALID_${toSnakeCase(parameter).toUpperCase()}`,
|
||||
},
|
||||
status
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class AppErrorInvalidReplaceMessage extends AppError {
|
||||
constructor(message = errorCodes.Invalid.message, status, key) {
|
||||
super(
|
||||
{
|
||||
...errorCodes.Invalid,
|
||||
message,
|
||||
|
||||
key: key ?? toSnakeCase(message).toUpperCase(),
|
||||
},
|
||||
status
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class AppErrorAlreadyExists extends AppError {
|
||||
constructor(parameter = 'Some', status, key) {
|
||||
super(
|
||||
{
|
||||
...errorCodes.AlreadyExists,
|
||||
message: `${parameter} entity already exists`,
|
||||
|
||||
key: key ?? `EXISTS_${toSnakeCase(parameter).toUpperCase()}`,
|
||||
},
|
||||
status
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class AppErrorNotExist extends AppError {
|
||||
constructor(parameter = 'Some', status, key) {
|
||||
super(
|
||||
{
|
||||
...errorCodes.NotExist,
|
||||
message: `${parameter} entity not exist`,
|
||||
|
||||
key: key ?? `DOES_NOT_EXIST_${toSnakeCase(parameter).toUpperCase()}`,
|
||||
},
|
||||
status
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class AppErrorDuplicate extends AppError {
|
||||
constructor(field = null, status, key) {
|
||||
super(
|
||||
{
|
||||
...errorCodes.Duplicate,
|
||||
field,
|
||||
|
||||
key: key ?? `DUPLICATE_${toSnakeCase(field ?? 'some').toUpperCase()}`,
|
||||
},
|
||||
status
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class AppErrorForbiddenAction extends AppError {
|
||||
constructor(status, key) {
|
||||
super(
|
||||
{
|
||||
errCode: 'Forbidden',
|
||||
message: 'You do not have access to this action',
|
||||
key: key ?? 'FORBIDDEN_ACTION',
|
||||
},
|
||||
status ?? 403
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// error for developer
|
||||
export class SystemError extends Error {
|
||||
constructor(status, err) {
|
||||
super(err);
|
||||
|
||||
this.status = status ?? 400;
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
message: this.message,
|
||||
|
||||
key: 'SYSTEM_ERROR',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function asyncRoute(route) {
|
||||
return (req, res, next = console.error) => {
|
||||
return Promise.resolve(route(req, res, next)).catch(e => next(e));
|
||||
};
|
||||
}
|
||||
|
||||
export default {
|
||||
asyncRoute,
|
||||
|
||||
AppError,
|
||||
SystemError,
|
||||
|
||||
AppErrorMissing,
|
||||
AppErrorInvalid,
|
||||
AppErrorInvalidReplaceMessage,
|
||||
AppErrorAlreadyExists,
|
||||
AppErrorNotExist,
|
||||
AppErrorDuplicate,
|
||||
AppErrorForbiddenAction,
|
||||
};
|
||||
@@ -0,0 +1,101 @@
|
||||
import PDFDocument from 'pdfkit';
|
||||
import QRCode from 'qrcode';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const font = fileURLToPath(new URL('../assets/fonts/DejaVuSans.ttf', import.meta.url));
|
||||
export function loginLink(baseUrl, user) {
|
||||
const url = new URL(baseUrl);
|
||||
url.hash = '/login?' + new URLSearchParams({ l: user.login, p: user.passwordForAdmin });
|
||||
return url.href;
|
||||
}
|
||||
|
||||
// A4, 3 × 4 cards per page. QR modules are vectors with a four-module quiet zone.
|
||||
export function createExpertQrPdf(users, baseUrl) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const doc = new PDFDocument({
|
||||
size: 'A4',
|
||||
margin: 24,
|
||||
autoFirstPage: false,
|
||||
info: { Title: 'Эксперты — QR-коды входа', Author: 'CyberGarden' },
|
||||
});
|
||||
const chunks = [];
|
||||
doc.on('data', chunk => chunks.push(chunk));
|
||||
doc.on('end', () => resolve(Buffer.concat(chunks)));
|
||||
doc.on('error', reject);
|
||||
try {
|
||||
doc.registerFont('Names', font);
|
||||
const technical = users.filter(user => user.role === 'technical');
|
||||
const regular = users.filter(user => user.role !== 'technical');
|
||||
const headingHeight = 22;
|
||||
let column = 0;
|
||||
let rowY = 24;
|
||||
let groupTitle = '';
|
||||
function cardHeight() {
|
||||
return (doc.page.height - 48 - headingHeight) / 4;
|
||||
}
|
||||
function drawHeading() {
|
||||
doc
|
||||
.font('Names')
|
||||
.fontSize(12)
|
||||
.fillColor('#2c634c')
|
||||
.text(groupTitle, 24, rowY + 4, { width: doc.page.width - 48, height: 18 });
|
||||
rowY += headingHeight;
|
||||
}
|
||||
function newPage() {
|
||||
doc.addPage();
|
||||
rowY = 24;
|
||||
column = 0;
|
||||
drawHeading();
|
||||
}
|
||||
function startGroup(title) {
|
||||
groupTitle = title;
|
||||
newPage();
|
||||
}
|
||||
function drawCard(user) {
|
||||
if (!column && rowY + cardHeight() > doc.page.height - 24 + 0.01) newPage();
|
||||
const width = (doc.page.width - 48) / 3;
|
||||
const height = cardHeight();
|
||||
const x = 24 + column * width;
|
||||
const y = rowY;
|
||||
doc.lineWidth(0.4).strokeColor('#d4d4d4').rect(x, y, width, height).stroke();
|
||||
const link = loginLink(baseUrl, user);
|
||||
const matrix = QRCode.create(link, { errorCorrectionLevel: 'M' }).modules;
|
||||
const size = 124;
|
||||
const module = size / (matrix.size + 8);
|
||||
const qrX = x + (width - size) / 2;
|
||||
const qrY = y + 12;
|
||||
doc.fillColor('#ffffff').rect(qrX, qrY, size, size).fill();
|
||||
doc.fillColor('#000000');
|
||||
for (let row = 0; row < matrix.size; row++)
|
||||
for (let col = 0; col < matrix.size; col++) {
|
||||
if (matrix.get(row, col)) doc.rect(qrX + (col + 4) * module, qrY + (row + 4) * module, module, module);
|
||||
}
|
||||
doc.fill();
|
||||
doc.link(qrX, qrY, size, size, link);
|
||||
const fullName = [user.lastName, user.firstName, user.middleName].filter(Boolean).join(' ');
|
||||
const cases = (user.cases || [])
|
||||
.map(task => task.name)
|
||||
.sort((a, b) => a.localeCompare(b, 'ru'))
|
||||
.join(', ');
|
||||
const label = user.role === 'technical' ? fullName + '\n' + (cases || 'Кейс не назначен') : fullName;
|
||||
const textOptions = { width: width - 18, align: 'center', lineGap: 2 };
|
||||
let fontSize = 11;
|
||||
doc.font('Names').fontSize(fontSize);
|
||||
while (doc.heightOfString(label, textOptions) > height - 147 && fontSize > 7) doc.fontSize(--fontSize);
|
||||
doc.fillColor('#000000').text(label, x + 9, y + 142, { ...textOptions, height: height - 147, ellipsis: true });
|
||||
if (++column === 3) {
|
||||
column = 0;
|
||||
rowY += height;
|
||||
}
|
||||
}
|
||||
if (technical.length) startGroup('Тех. эксперты');
|
||||
for (const user of technical) drawCard(user);
|
||||
if (regular.length) startGroup('Эксперты');
|
||||
for (const user of regular) drawCard(user);
|
||||
doc.end();
|
||||
} catch (error) {
|
||||
doc.destroy();
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import markTypes from '../config/markTypes.js';
|
||||
import { AppErrorInvalid } from './errors.js';
|
||||
|
||||
export const technicalMarkTypes = [markTypes.IMPLEMENTATION, markTypes.WORK];
|
||||
export function expertRole(value = 'expert') {
|
||||
if (!['expert', 'technical'].includes(value)) throw new AppErrorInvalid('role');
|
||||
return value;
|
||||
}
|
||||
export function editableMarkTypes(role) {
|
||||
return role === 'technical'
|
||||
? technicalMarkTypes
|
||||
: Object.values(markTypes).filter(type => !technicalMarkTypes.includes(type));
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
const issuer = 'HackathonApp';
|
||||
const audience = process.env.WEB_SERVICE;
|
||||
|
||||
export default {
|
||||
generate(payload = {}, options = {}) {
|
||||
if (!payload.iat) payload.iat = Math.round(+new Date() / 1000);
|
||||
|
||||
return {
|
||||
jwt: jwt.sign(payload, process.env.JWT_KEY, { issuer, audience, ...options }),
|
||||
iat: payload.iat,
|
||||
};
|
||||
},
|
||||
|
||||
verify(key) {
|
||||
return jwt.verify(key, process.env.JWT_KEY, { issuer, audience });
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
export default user => ({
|
||||
id: user.id,
|
||||
login: user.login,
|
||||
role: user.role || 'expert',
|
||||
|
||||
firstName: user.firstName ?? null,
|
||||
lastName: user.lastName ?? null,
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import crypto from 'crypto';
|
||||
|
||||
export default (howMany = 12, chars = 'abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789') => {
|
||||
const rnd = crypto.randomBytes(howMany),
|
||||
value = [],
|
||||
len = Math.min(256, chars.length),
|
||||
d = 256 / len;
|
||||
|
||||
for (let i = 0; i < howMany; i++) {
|
||||
value[i] = chars[Math.floor(rnd[i] / d)];
|
||||
}
|
||||
|
||||
return value.join('');
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
const converter = {
|
||||
а: 'a',
|
||||
б: 'b',
|
||||
в: 'v',
|
||||
г: 'g',
|
||||
д: 'd',
|
||||
е: 'e',
|
||||
ё: 'e',
|
||||
ж: 'zh',
|
||||
з: 'z',
|
||||
и: 'i',
|
||||
й: 'y',
|
||||
к: 'k',
|
||||
л: 'l',
|
||||
м: 'm',
|
||||
н: 'n',
|
||||
о: 'o',
|
||||
п: 'p',
|
||||
р: 'r',
|
||||
с: 's',
|
||||
т: 't',
|
||||
у: 'u',
|
||||
ф: 'f',
|
||||
х: 'h',
|
||||
ц: 'c',
|
||||
ч: 'ch',
|
||||
ш: 'sh',
|
||||
щ: 'sch',
|
||||
ь: '',
|
||||
ы: 'y',
|
||||
ъ: '',
|
||||
э: 'e',
|
||||
ю: 'yu',
|
||||
я: 'ya',
|
||||
|
||||
А: 'A',
|
||||
Б: 'B',
|
||||
В: 'V',
|
||||
Г: 'G',
|
||||
Д: 'D',
|
||||
Е: 'E',
|
||||
Ё: 'E',
|
||||
Ж: 'Zh',
|
||||
З: 'Z',
|
||||
И: 'I',
|
||||
Й: 'Y',
|
||||
К: 'K',
|
||||
Л: 'L',
|
||||
М: 'M',
|
||||
Н: 'N',
|
||||
О: 'O',
|
||||
П: 'P',
|
||||
Р: 'R',
|
||||
С: 'S',
|
||||
Т: 'T',
|
||||
У: 'U',
|
||||
Ф: 'F',
|
||||
Х: 'H',
|
||||
Ц: 'C',
|
||||
Ч: 'Ch',
|
||||
Ш: 'Sh',
|
||||
Щ: 'Sch',
|
||||
Ь: '',
|
||||
Ы: 'Y',
|
||||
Ъ: '',
|
||||
Э: 'E',
|
||||
Ю: 'Yu',
|
||||
Я: 'Ya',
|
||||
};
|
||||
|
||||
export default word => {
|
||||
let answer = '';
|
||||
|
||||
for (var i = 0; i < word.length; ++i) {
|
||||
if (converter[word[i]] === undefined) {
|
||||
answer += word[i];
|
||||
} else {
|
||||
answer += converter[word[i]];
|
||||
}
|
||||
}
|
||||
|
||||
return answer;
|
||||
};
|
||||
Reference in new issue
Block a user