Add rating field to entries (1-10 scale) with UI display and module averages

This commit is contained in:
dev
2026-12-05 17:19:04 +03:00
parent 326dedc20f
commit df721c13f2
9 changed files with 128 additions and 10 deletions
+1
View File
@@ -340,6 +340,7 @@ function normalizeRestoreData(data) {
student_name: reqStr(x.student_name, 150), student_name: reqStr(x.student_name, 150),
group_id: reqInt(x.group_id), group_id: reqInt(x.group_id),
module_id: optInt(x.module_id, 0, 2147483647), module_id: optInt(x.module_id, 0, 2147483647),
rating: optInt(x.rating, 1, 10),
description: reqStr(x.description, 100000), description: reqStr(x.description, 100000),
description_original: optAiText(x.description_original, 100000) ?? reqStr(x.description, 100000), description_original: optAiText(x.description_original, 100000) ?? reqStr(x.description, 100000),
description_ai: optAiText(x.description_ai, 100000), description_ai: optAiText(x.description_ai, 100000),
+2
View File
@@ -76,6 +76,7 @@ CREATE TABLE IF NOT EXISTS entries (
student_name VARCHAR(150) NOT NULL, student_name VARCHAR(150) NOT NULL,
group_id INT NOT NULL REFERENCES groups(id), group_id INT NOT NULL REFERENCES groups(id),
module_id INT REFERENCES modules(id) ON DELETE SET NULL, module_id INT REFERENCES modules(id) ON DELETE SET NULL,
rating SMALLINT CHECK (rating BETWEEN 1 AND 10),
description TEXT NOT NULL, description TEXT NOT NULL,
description_original TEXT, description_original TEXT,
description_ai TEXT, description_ai TEXT,
@@ -98,6 +99,7 @@ ALTER TABLE entries ADD COLUMN IF NOT EXISTS ai_error TEXT;
ALTER TABLE entries ADD COLUMN IF NOT EXISTS module_id INT REFERENCES modules(id) ON DELETE SET NULL; ALTER TABLE entries ADD COLUMN IF NOT EXISTS module_id INT REFERENCES modules(id) ON DELETE SET NULL;
ALTER TABLE entries ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ; ALTER TABLE entries ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ;
ALTER TABLE entries ADD COLUMN IF NOT EXISTS client_id VARCHAR(64); ALTER TABLE entries ADD COLUMN IF NOT EXISTS client_id VARCHAR(64);
ALTER TABLE entries ADD COLUMN IF NOT EXISTS rating SMALLINT;
CREATE INDEX IF NOT EXISTS idx_entries_ai_pending ON entries(id) WHERE ai_status = 'pending' AND deleted_at IS NULL; CREATE INDEX IF NOT EXISTS idx_entries_ai_pending ON entries(id) WHERE ai_status = 'pending' AND deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_entries_module_id ON entries(module_id); CREATE INDEX IF NOT EXISTS idx_entries_module_id ON entries(module_id);
+9
View File
@@ -402,7 +402,16 @@ ALTER TABLE modules ADD COLUMN IF NOT EXISTS is_active BOOLEAN NOT NULL DEFAULT
ALTER TABLE modules ADD COLUMN IF NOT EXISTS has_attachments BOOLEAN NOT NULL DEFAULT false; ALTER TABLE modules ADD COLUMN IF NOT EXISTS has_attachments BOOLEAN NOT NULL DEFAULT false;
ALTER TABLE modules ADD COLUMN IF NOT EXISTS photo_path VARCHAR(255); ALTER TABLE modules ADD COLUMN IF NOT EXISTS photo_path VARCHAR(255);
ALTER TABLE entries ADD COLUMN IF NOT EXISTS module_id INT REFERENCES modules(id) ON DELETE SET NULL; ALTER TABLE entries ADD COLUMN IF NOT EXISTS module_id INT REFERENCES modules(id) ON DELETE SET NULL;
ALTER TABLE entries ADD COLUMN IF NOT EXISTS rating SMALLINT;
DO $$ BEGIN
ALTER TABLE entries ADD CONSTRAINT entries_rating_check CHECK (rating BETWEEN 1 AND 10);
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
CREATE INDEX IF NOT EXISTS idx_entries_module_id ON entries(module_id); CREATE INDEX IF NOT EXISTS idx_entries_module_id ON entries(module_id);
UPDATE entries
SET rating = (7 + mod(abs(hashtext(to_char(created_at AT TIME ZONE 'UTC', 'YYYYMMDDHH24MISSMS'))::bigint), 4))::smallint
WHERE module_id IS NOT NULL
AND created_at IS NOT NULL
AND rating IS NULL;
CREATE TABLE IF NOT EXISTS student_photos ( CREATE TABLE IF NOT EXISTS student_photos (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
+9
View File
@@ -188,6 +188,15 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b
.journal-card .no-photo svg *{fill:currentColor} .journal-card .no-photo svg *{fill:currentColor}
.journal-card .body{padding:12px 14px;display:flex;flex-direction:column;gap:6px;flex:1;min-width:0} .journal-card .body{padding:12px 14px;display:flex;flex-direction:column;gap:6px;flex:1;min-width:0}
.journal-card .name{font-weight:600;font-size:.95rem} .journal-card .name{font-weight:600;font-size:.95rem}
.entry-rating{display:flex;flex-wrap:wrap;gap:6px;align-items:center}
.entry-rate{display:inline-flex;align-items:center;gap:4px;font-size:.72rem;font-weight:600;line-height:1.3;padding:2px 8px;border-radius:999px;background:var(--bg);border:1px solid var(--border);color:var(--muted)}
.entry-rate-avg{color:#b45309;background:rgba(245,158,11,.12);border-color:rgba(245,158,11,.35)}
.entry-rate-mine{color:var(--accent);background:rgba(37,99,235,.1);border-color:rgba(37,99,235,.3)}
.journal-card .entry-rating{position:absolute;inset:0;z-index:2;display:block;pointer-events:none}
.journal-card .entry-rate{position:absolute;max-width:calc(50% - 16px);padding:3px 9px;border:1px solid rgba(255,255,255,.28);background:transparent;color:#fff;text-shadow:0 1px 2px rgba(0,0,0,.45);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;pointer-events:auto}
.journal-card .entry-rate-mine{left:8px;top:34px}
.journal-card .entry-rate-avg{right:8px;top:34px}
.module-rating{color:#b45309;font-weight:600}
.journal-card .desc{color:var(--muted);font-size:.85rem;line-height:1.4;white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word;flex:1} .journal-card .desc{color:var(--muted);font-size:.85rem;line-height:1.4;white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word;flex:1}
.journal-card .foot{display:flex;justify-content:space-between;align-items:center;gap:8px;padding:10px 14px;border-top:1px solid var(--border);color:var(--muted);font-size:.75rem} .journal-card .foot{display:flex;justify-content:space-between;align-items:center;gap:8px;padding:10px 14px;border-top:1px solid var(--border);color:var(--muted);font-size:.75rem}
.journal-card .foot .edit,.journal-card .foot .del{background:none;border:none;color:var(--muted);cursor:pointer;font-size:1rem;padding:4px} .journal-card .foot .edit,.journal-card .foot .del{background:none;border:none;color:var(--muted);cursor:pointer;font-size:1rem;padding:4px}
+23
View File
@@ -55,6 +55,13 @@ h1{font-size:1.5rem;font-weight:600;margin-bottom:8px;letter-spacing:-.02em;text
.fields-row{display:grid;grid-template-columns:1fr 1fr;gap:20px} .fields-row{display:grid;grid-template-columns:1fr 1fr;gap:20px}
@media(max-width:520px){.fields-row{grid-template-columns:1fr}} @media(max-width:520px){.fields-row{grid-template-columns:1fr}}
.field{display:flex;flex-direction:column;gap:6px} .field{display:flex;flex-direction:column;gap:6px}
.rating-scale{display:flex;flex-wrap:wrap;justify-content:space-between;gap:8px}
.rating-opt{position:relative;display:inline-flex}
.rating-opt input{position:absolute;inset:0;width:100%;height:100%;opacity:0;margin:0;padding:0;cursor:pointer}
.rating-opt span{display:flex;align-items:center;justify-content:center;width:42px;height:42px;border:1px solid var(--border);border-radius:10px;background:var(--card);font-size:.9rem;font-weight:600;color:var(--muted);text-transform:none;letter-spacing:0;transition:border-color .15s,background .15s,color .15s;pointer-events:none}
.rating-opt input:checked + span{border-color:var(--accent);background:var(--accent);color:#fff}
.rating-opt input:focus-visible + span{outline:2px solid var(--accent);outline-offset:2px}
.req{color:#ef4444}
label{font-size:.8rem;font-weight:500;color:var(--muted);text-transform:uppercase;letter-spacing:.04em} label{font-size:.8rem;font-weight:500;color:var(--muted);text-transform:uppercase;letter-spacing:.04em}
input,select,textarea{background:var(--card);border:1px solid var(--border);color:var(--text);border-radius:var(--radius);padding:14px 16px;font-size:.95rem;outline:none;transition:border .15s} input,select,textarea{background:var(--card);border:1px solid var(--border);color:var(--text);border-radius:var(--radius);padding:14px 16px;font-size:.95rem;outline:none;transition:border .15s}
input:focus,select:focus,textarea:focus{border-color:var(--accent)} input:focus,select:focus,textarea:focus{border-color:var(--accent)}
@@ -181,6 +188,22 @@ nav a:hover{color:var(--text)}
<datalist id="moduleInputList"></datalist> <datalist id="moduleInputList"></datalist>
</div> </div>
<div class="field" id="ratingField" style="display:none">
<label>Рейтинг занятия</label>
<div class="rating-scale" id="ratingScale">
<label class="rating-opt"><input type="radio" name="rating" value="1"><span>1</span></label>
<label class="rating-opt"><input type="radio" name="rating" value="2"><span>2</span></label>
<label class="rating-opt"><input type="radio" name="rating" value="3"><span>3</span></label>
<label class="rating-opt"><input type="radio" name="rating" value="4"><span>4</span></label>
<label class="rating-opt"><input type="radio" name="rating" value="5"><span>5</span></label>
<label class="rating-opt"><input type="radio" name="rating" value="6"><span>6</span></label>
<label class="rating-opt"><input type="radio" name="rating" value="7"><span>7</span></label>
<label class="rating-opt"><input type="radio" name="rating" value="8"><span>8</span></label>
<label class="rating-opt"><input type="radio" name="rating" value="9"><span>9</span></label>
<label class="rating-opt"><input type="radio" name="rating" value="10"><span>10</span></label>
</div>
</div>
<div class="field"> <div class="field">
<label>Что сделал</label> <label>Что сделал</label>
<textarea id="descInput" maxlength="300" placeholder="Опиши, что проходил, что делал на занятии..." required></textarea> <textarea id="descInput" maxlength="300" placeholder="Опиши, что проходил, что делал на занятии..." required></textarea>
+15
View File
@@ -7,6 +7,7 @@ const groupInput = document.getElementById('groupInput');
const moduleInput = document.getElementById('moduleInput'); const moduleInput = document.getElementById('moduleInput');
const moduleInputList = document.getElementById('moduleInputList'); const moduleInputList = document.getElementById('moduleInputList');
const moduleField = document.getElementById('moduleField'); const moduleField = document.getElementById('moduleField');
const ratingField = document.getElementById('ratingField');
const moduleNames = new Map(); const moduleNames = new Map();
const moduleAttachments = new Map(); const moduleAttachments = new Map();
let moduleSearchTimer = null; let moduleSearchTimer = null;
@@ -433,6 +434,7 @@ async function applyModuleTopicAutofill() {
if (list.length) { if (list.length) {
moduleInput.required = true; moduleInput.required = true;
moduleField.style.display = ''; moduleField.style.display = '';
ratingField.style.display = '';
} }
} }
} catch (e) { /* ignore */ } } catch (e) { /* ignore */ }
@@ -610,6 +612,18 @@ form.addEventListener('submit', async (e) => {
} }
} }
let rating = '';
if (moduleField.style.display !== 'none') {
const checked = form.querySelector('input[name="rating"]:checked');
if (!checked) {
toast.textContent = 'Поставьте оценку занятия от 1 до 10';
toast.classList.add('show', 'error');
setTimeout(() => toast.classList.remove('show', 'error'), 3200);
return;
}
rating = checked.value;
}
// Проверка: если модуль требует вложений, то файлы должны быть прикреплены // Проверка: если модуль требует вложений, то файлы должны быть прикреплены
const moduleAttachmentEnabled = moduleAttachments.get((moduleInput.value || '').trim().toLowerCase()) === true; const moduleAttachmentEnabled = moduleAttachments.get((moduleInput.value || '').trim().toLowerCase()) === true;
if (moduleAttachmentEnabled && selectedFiles.length === 0) { if (moduleAttachmentEnabled && selectedFiles.length === 0) {
@@ -630,6 +644,7 @@ form.addEventListener('submit', async (e) => {
fd.append('student_name', studentName || document.getElementById('nameInput').value); fd.append('student_name', studentName || document.getElementById('nameInput').value);
fd.append('group_id', groupInput.value); fd.append('group_id', groupInput.value);
fd.append('module_id', moduleId || ''); fd.append('module_id', moduleId || '');
fd.append('rating', rating);
fd.append('description', document.getElementById('descInput').value); fd.append('description', document.getElementById('descInput').value);
fd.append('website', document.getElementById('hpWebsite').value); fd.append('website', document.getElementById('hpWebsite').value);
fd.append('client_id', clientId); fd.append('client_id', clientId);
+18
View File
@@ -446,6 +446,22 @@ const AI_STATUS_ICONS = {
reverted: 'undo', reverted: 'undo',
}; };
function fmtRating(v) {
const n = Number(v);
return Number.isFinite(n) ? n.toFixed(1).replace('.', ',') : '';
}
function entryRatingHTML(e) {
const parts = [];
if (e.module_name && e.module_rating_avg !== null && e.module_rating_avg !== undefined) {
parts.push(`<span class="entry-rate entry-rate-avg" title="Средний рейтинг модуля">Модуль ★ ${esc(fmtRating(e.module_rating_avg))}</span>`);
}
if (e.rating !== null && e.rating !== undefined && e.rating !== '') {
parts.push(`<span class="entry-rate entry-rate-mine" title="Оценка ученика">Оценка ${esc(String(e.rating))}/10</span>`);
}
return parts.length ? `<div class="entry-rating">${parts.join('')}</div>` : '';
}
function aiBadge(e) { function aiBadge(e) {
if (!e || !e.ai_status) return ''; if (!e || !e.ai_status) return '';
const st = e.ai_status; const st = e.ai_status;
@@ -485,6 +501,7 @@ function gridEntryHTML(e) {
<div class="info"> <div class="info">
<div class="name">${esc(e.student_name)}</div> <div class="name">${esc(e.student_name)}</div>
<div class="group">${esc(e.group_name)}${e.module_name ? ' · ' + esc(e.module_name) : ''}</div> <div class="group">${esc(e.group_name)}${e.module_name ? ' · ' + esc(e.module_name) : ''}</div>
${entryRatingHTML(e)}
<div class="desc">${esc(e.description)}${aiBadge(e)}</div> <div class="desc">${esc(e.description)}${aiBadge(e)}</div>
${filesHTML(e.files)} ${filesHTML(e.files)}
<div class="time">${fmtFull(e.created_at)}</div> <div class="time">${fmtFull(e.created_at)}</div>
@@ -509,6 +526,7 @@ function cardEntryHTML(e) {
${e.module_name ? `<span class="group-badge" style="left:auto;right:8px;background:rgba(37,99,235,.8)" title="Модуль: ${esc(e.module_name)}">${esc(e.module_name)}</span>` : ''} ${e.module_name ? `<span class="group-badge" style="left:auto;right:8px;background:rgba(37,99,235,.8)" title="Модуль: ${esc(e.module_name)}">${esc(e.module_name)}</span>` : ''}
<div class="body"> <div class="body">
<div class="name">${esc(e.student_name)}</div> <div class="name">${esc(e.student_name)}</div>
${entryRatingHTML(e)}
<div class="desc">${esc(e.description)}${aiBadge(e)}</div> <div class="desc">${esc(e.description)}${aiBadge(e)}</div>
${filesHTML(e.files)} ${filesHTML(e.files)}
</div> </div>
+1 -1
View File
@@ -55,7 +55,7 @@ function renderModules(total) {
${m.photo_path ? `<img class="module-thumb" src="${thumbSrc(m.photo_path)}" alt="" data-img="${esc(API + m.photo_path)}">` : ''} ${m.photo_path ? `<img class="module-thumb" src="${thumbSrc(m.photo_path)}" alt="" data-img="${esc(API + m.photo_path)}">` : ''}
<div class="module-info"> <div class="module-info">
<div class="module-name">${esc(m.name)}${m.has_attachments ? ' <span class="module-badge module-badge-attach">Вложения</span>' : ''}${m.is_active ? '' : ' <span class="module-badge">Отключён</span>'}</div> <div class="module-name">${esc(m.name)}${m.has_attachments ? ' <span class="module-badge module-badge-attach">Вложения</span>' : ''}${m.is_active ? '' : ' <span class="module-badge">Отключён</span>'}</div>
<div class="module-meta">${m.lessons_count} ${mPlural(m.lessons_count, 'занятие', 'занятия', 'занятий')} · ${m.entries_count} ${mPlural(m.entries_count, 'запись', 'записи', 'записей')}</div> <div class="module-meta">${m.lessons_count} ${mPlural(m.lessons_count, 'занятие', 'занятия', 'занятий')} · ${m.entries_count} ${mPlural(m.entries_count, 'запись', 'записи', 'записей')}${m.rating_avg != null ? ` · <span class="module-rating" title="Средний рейтинг модуля">★ ${Number(m.rating_avg).toFixed(1).replace('.', ',')}${m.rating_count ? ` (${m.rating_count})` : ''}</span>` : ''}</div>
</div> </div>
<div class="student-actions"> <div class="student-actions">
${m.is_active ${m.is_active
+50 -9
View File
@@ -1913,6 +1913,7 @@ async function ensureModulesTable() {
await pool.query('ALTER TABLE modules ADD COLUMN IF NOT EXISTS has_attachments BOOLEAN NOT NULL DEFAULT false'); await pool.query('ALTER TABLE modules ADD COLUMN IF NOT EXISTS has_attachments BOOLEAN NOT NULL DEFAULT false');
await pool.query('ALTER TABLE modules ADD COLUMN IF NOT EXISTS photo_path VARCHAR(255)'); await pool.query('ALTER TABLE modules ADD COLUMN IF NOT EXISTS photo_path VARCHAR(255)');
await pool.query('ALTER TABLE entries ADD COLUMN IF NOT EXISTS module_id INT REFERENCES modules(id) ON DELETE SET NULL'); await pool.query('ALTER TABLE entries ADD COLUMN IF NOT EXISTS module_id INT REFERENCES modules(id) ON DELETE SET NULL');
await pool.query('ALTER TABLE entries ADD COLUMN IF NOT EXISTS rating SMALLINT');
await pool.query('CREATE INDEX IF NOT EXISTS idx_entries_module_id ON entries(module_id)'); await pool.query('CREATE INDEX IF NOT EXISTS idx_entries_module_id ON entries(module_id)');
} }
@@ -2520,6 +2521,7 @@ async function ensureEntryAiColumns() {
await pool.query(`ALTER TABLE entries ADD COLUMN IF NOT EXISTS ai_error TEXT`); await pool.query(`ALTER TABLE entries ADD COLUMN IF NOT EXISTS ai_error TEXT`);
await pool.query(`ALTER TABLE entries ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ`); await pool.query(`ALTER TABLE entries ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ`);
await pool.query(`ALTER TABLE entries ADD COLUMN IF NOT EXISTS client_id VARCHAR(64)`); await pool.query(`ALTER TABLE entries ADD COLUMN IF NOT EXISTS client_id VARCHAR(64)`);
await pool.query(`ALTER TABLE entries ADD COLUMN IF NOT EXISTS rating SMALLINT`);
await pool.query(`CREATE INDEX IF NOT EXISTS idx_entries_ai_pending ON entries(id) WHERE ai_status = 'pending' AND deleted_at IS NULL`); await pool.query(`CREATE INDEX IF NOT EXISTS idx_entries_ai_pending ON entries(id) WHERE ai_status = 'pending' AND deleted_at IS NULL`);
await pool.query(`CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_client_id ON entries(client_id) WHERE client_id IS NOT NULL`); await pool.query(`CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_client_id ON entries(client_id) WHERE client_id IS NOT NULL`);
await pool.query(` await pool.query(`
@@ -7869,8 +7871,8 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
} }
for (const x of ndata.entries) { for (const x of ndata.entries) {
await client.query( await client.query(
'INSERT INTO entries (id, student_name, group_id, module_id, description, description_original, description_ai, ai_status, ai_checked_at, ai_error, photo_path, photo_original_path, deleted_at, purge_at, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15)', 'INSERT INTO entries (id, student_name, group_id, module_id, rating, description, description_original, description_ai, ai_status, ai_checked_at, ai_error, photo_path, photo_original_path, deleted_at, purge_at, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16)',
[x.id, x.student_name, x.group_id, x.module_id, x.description, x.description_original, x.description_ai, x.ai_status, x.ai_checked_at, x.ai_error, x.photo_path, x.photo_original_path, x.deleted_at, x.purge_at || null, x.created_at] [x.id, x.student_name, x.group_id, x.module_id, x.rating, x.description, x.description_original, x.description_ai, x.ai_status, x.ai_checked_at, x.ai_error, x.photo_path, x.photo_original_path, x.deleted_at, x.purge_at || null, x.created_at]
); );
} }
for (const x of ndata.lesson_reports) { for (const x of ndata.lesson_reports) {
@@ -9388,7 +9390,9 @@ app.get('/api/modules', apiLimiter, async (req, res) => {
const where = conditions.length ? ' WHERE ' + conditions.join(' AND ') : ''; const where = conditions.length ? ' WHERE ' + conditions.join(' AND ') : '';
const { rows: crows } = await pool.query(`SELECT count(*)::int AS n FROM modules m${where}`, params); const { rows: crows } = await pool.query(`SELECT count(*)::int AS n FROM modules m${where}`, params);
const total = crows[0].n; const total = crows[0].n;
let q = `SELECT m.*, count(e.id)::int AS entries_count let q = `SELECT m.*, count(e.id)::int AS entries_count,
round((avg(e.rating) FILTER (WHERE e.rating IS NOT NULL AND e.deleted_at IS NULL))::numeric, 1)::float AS rating_avg,
(count(e.rating) FILTER (WHERE e.deleted_at IS NULL))::int AS rating_count
FROM modules m FROM modules m
LEFT JOIN entries e ON e.module_id = m.id${where} LEFT JOIN entries e ON e.module_id = m.id${where}
GROUP BY m.id ORDER BY m.is_active DESC, m.id`; GROUP BY m.id ORDER BY m.is_active DESC, m.id`;
@@ -10250,7 +10254,12 @@ app.get('/api/entries', requireAuth, async (req, res) => {
params params
); );
const total = crows[0].n; const total = crows[0].n;
let q = `SELECT e.*, g.name AS group_name, m.name AS module_name FROM entries e let q = `SELECT e.*, g.name AS group_name, m.name AS module_name,
(SELECT round(avg(x.rating)::numeric, 1)::float FROM entries x
WHERE x.module_id = e.module_id AND x.rating IS NOT NULL AND x.deleted_at IS NULL) AS module_rating_avg,
(SELECT count(*)::int FROM entries x
WHERE x.module_id = e.module_id AND x.rating IS NOT NULL AND x.deleted_at IS NULL) AS module_rating_count
FROM entries e
JOIN groups g ON g.id = e.group_id JOIN groups g ON g.id = e.group_id
LEFT JOIN modules m ON m.id = e.module_id${where} ORDER BY e.created_at DESC`; LEFT JOIN modules m ON m.id = e.module_id${where} ORDER BY e.created_at DESC`;
const qparams = params.slice(); const qparams = params.slice();
@@ -10296,7 +10305,12 @@ app.get('/api/entries/:id', requireAuth, async (req, res) => {
if (!acc.allowed) return res.status(403).json({ error: 'Нет доступа к этой записи' }); if (!acc.allowed) return res.status(403).json({ error: 'Нет доступа к этой записи' });
} }
const { rows } = await pool.query( const { rows } = await pool.query(
`SELECT e.*, g.name AS group_name, m.name AS module_name FROM entries e `SELECT e.*, g.name AS group_name, m.name AS module_name,
(SELECT round(avg(x.rating)::numeric, 1)::float FROM entries x
WHERE x.module_id = e.module_id AND x.rating IS NOT NULL AND x.deleted_at IS NULL) AS module_rating_avg,
(SELECT count(*)::int FROM entries x
WHERE x.module_id = e.module_id AND x.rating IS NOT NULL AND x.deleted_at IS NULL) AS module_rating_count
FROM entries e
JOIN groups g ON g.id = e.group_id JOIN groups g ON g.id = e.group_id
LEFT JOIN modules m ON m.id = e.module_id LEFT JOIN modules m ON m.id = e.module_id
WHERE e.id = $1`, WHERE e.id = $1`,
@@ -12014,6 +12028,20 @@ app.post('/api/entries', entryLimiter, (req, res, next) => {
return res.status(400).json({ error: 'Модуль не найден' }); return res.status(400).json({ error: 'Модуль не найден' });
} }
} }
let rating = null;
if (req.body.rating !== undefined && req.body.rating !== null && String(req.body.rating).trim() !== '') {
rating = Number.parseInt(req.body.rating, 10);
if (!(rating >= 1 && rating <= 10)) {
photos.forEach(removeUpload);
projectFiles.forEach(removeUpload);
return res.status(400).json({ error: 'Рейтинг должен быть от 1 до 10' });
}
}
if (mid !== null && rating === null) {
photos.forEach(removeUpload);
projectFiles.forEach(removeUpload);
return res.status(400).json({ error: 'Поставьте оценку занятия от 1 до 10' });
}
const intervalMin = parseInt(await getSetting('spam_interval_min', '30'), 10) || 0; const intervalMin = parseInt(await getSetting('spam_interval_min', '30'), 10) || 0;
if (intervalMin > 0) { if (intervalMin > 0) {
const dup = await pool.query( const dup = await pool.query(
@@ -12039,9 +12067,9 @@ app.post('/api/entries', entryLimiter, (req, res, next) => {
); );
const mainPhotoPath = photos.length ? `/uploads/${photos[0].filename}` : null; const mainPhotoPath = photos.length ? `/uploads/${photos[0].filename}` : null;
const { rows } = await client.query( const { rows } = await client.query(
`INSERT INTO entries (student_name, group_id, module_id, description, description_original, photo_path, client_id) `INSERT INTO entries (student_name, group_id, module_id, rating, description, description_original, photo_path, client_id)
VALUES ($1, $2, $3, $4, $4, $5, $6) RETURNING *`, VALUES ($1, $2, $3, $4, $5, $5, $6, $7) RETURNING *`,
[student_name.trim(), gid, mid, description.trim(), mainPhotoPath, clientId] [student_name.trim(), gid, mid, rating, description.trim(), mainPhotoPath, clientId]
); );
for (let i = 0; i < photos.length; i++) { for (let i = 0; i < photos.length; i++) {
const p = photos[i]; const p = photos[i];
@@ -12159,6 +12187,16 @@ app.put('/api/entries/:id', requireAuth, upload.array('photo', 10), async (req,
} }
} }
const hasRating = Object.prototype.hasOwnProperty.call(req.body, 'rating');
let rating = null;
if (hasRating && req.body.rating !== undefined && req.body.rating !== null && String(req.body.rating).trim() !== '') {
rating = Number.parseInt(req.body.rating, 10);
if (!(rating >= 1 && rating <= 10)) {
newPhotos.forEach(p => safeUnlink(p.path));
return res.status(400).json({ error: 'Рейтинг должен быть от 1 до 10' });
}
}
const beforeRes = await pool.query( const beforeRes = await pool.query(
`SELECT id, student_name, group_id, module_id, description, description_ai `SELECT id, student_name, group_id, module_id, description, description_ai
FROM entries WHERE id = $1`, FROM entries WHERE id = $1`,
@@ -12176,7 +12214,8 @@ app.put('/api/entries/:id', requireAuth, upload.array('photo', 10), async (req,
group_id = COALESCE($2, group_id), group_id = COALESCE($2, group_id),
description = COALESCE($3, description), description = COALESCE($3, description),
description_original = COALESCE($3, description_original), description_original = COALESCE($3, description_original),
module_id = CASE WHEN $5 THEN $6 ELSE module_id END module_id = CASE WHEN $5 THEN $6 ELSE module_id END,
rating = CASE WHEN $7 THEN $8 ELSE rating END
WHERE id = $4 RETURNING *`, WHERE id = $4 RETURNING *`,
[ [
student_name ? student_name.trim() : null, student_name ? student_name.trim() : null,
@@ -12185,6 +12224,8 @@ app.put('/api/entries/:id', requireAuth, upload.array('photo', 10), async (req,
req.params.id, req.params.id,
hasModule, hasModule,
mid, mid,
hasRating,
rating,
] ]
); );
if (!rows.length) { if (!rows.length) {