diff --git a/backup-restore.js b/backup-restore.js index 533acee..2d56b47 100644 --- a/backup-restore.js +++ b/backup-restore.js @@ -340,6 +340,7 @@ function normalizeRestoreData(data) { student_name: reqStr(x.student_name, 150), group_id: reqInt(x.group_id), module_id: optInt(x.module_id, 0, 2147483647), + rating: optInt(x.rating, 1, 10), description: reqStr(x.description, 100000), description_original: optAiText(x.description_original, 100000) ?? reqStr(x.description, 100000), description_ai: optAiText(x.description_ai, 100000), diff --git a/db/init.sql b/db/init.sql index 3358313..b7f7a12 100644 --- a/db/init.sql +++ b/db/init.sql @@ -76,6 +76,7 @@ CREATE TABLE IF NOT EXISTS entries ( student_name VARCHAR(150) NOT NULL, group_id INT NOT NULL REFERENCES groups(id), module_id INT REFERENCES modules(id) ON DELETE SET NULL, + rating SMALLINT CHECK (rating BETWEEN 1 AND 10), description TEXT NOT NULL, description_original 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 purge_at TIMESTAMPTZ; 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_module_id ON entries(module_id); diff --git a/db/migration.sql b/db/migration.sql index 2873dad..423391b 100644 --- a/db/migration.sql +++ b/db/migration.sql @@ -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 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 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); +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 ( id SERIAL PRIMARY KEY, diff --git a/public/admin.css b/public/admin.css index 42768ba..03a73b9 100644 --- a/public/admin.css +++ b/public/admin.css @@ -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 .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} +.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 .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} diff --git a/public/index.html b/public/index.html index f1c5e07..bbd070a 100644 --- a/public/index.html +++ b/public/index.html @@ -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} @media(max-width:520px){.fields-row{grid-template-columns:1fr}} .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} 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)} @@ -181,6 +188,22 @@ nav a:hover{color:var(--text)} + +
diff --git a/public/js/index.js b/public/js/index.js index 41108dd..962d5b3 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -7,6 +7,7 @@ const groupInput = document.getElementById('groupInput'); const moduleInput = document.getElementById('moduleInput'); const moduleInputList = document.getElementById('moduleInputList'); const moduleField = document.getElementById('moduleField'); +const ratingField = document.getElementById('ratingField'); const moduleNames = new Map(); const moduleAttachments = new Map(); let moduleSearchTimer = null; @@ -433,6 +434,7 @@ async function applyModuleTopicAutofill() { if (list.length) { moduleInput.required = true; moduleField.style.display = ''; + ratingField.style.display = ''; } } } 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; 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('group_id', groupInput.value); fd.append('module_id', moduleId || ''); + fd.append('rating', rating); fd.append('description', document.getElementById('descInput').value); fd.append('website', document.getElementById('hpWebsite').value); fd.append('client_id', clientId); diff --git a/public/js/journal.js b/public/js/journal.js index 13e56c0..e29d4ee 100644 --- a/public/js/journal.js +++ b/public/js/journal.js @@ -446,6 +446,22 @@ const AI_STATUS_ICONS = { 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(`Модуль ★ ${esc(fmtRating(e.module_rating_avg))}`); + } + if (e.rating !== null && e.rating !== undefined && e.rating !== '') { + parts.push(`Оценка ${esc(String(e.rating))}/10`); + } + return parts.length ? `
${parts.join('')}
` : ''; +} + function aiBadge(e) { if (!e || !e.ai_status) return ''; const st = e.ai_status; @@ -485,6 +501,7 @@ function gridEntryHTML(e) {
${esc(e.student_name)}
${esc(e.group_name)}${e.module_name ? ' · ' + esc(e.module_name) : ''}
+ ${entryRatingHTML(e)}
${esc(e.description)}${aiBadge(e)}
${filesHTML(e.files)}
${fmtFull(e.created_at)}
@@ -509,6 +526,7 @@ function cardEntryHTML(e) { ${e.module_name ? `${esc(e.module_name)}` : ''}
${esc(e.student_name)}
+ ${entryRatingHTML(e)}
${esc(e.description)}${aiBadge(e)}
${filesHTML(e.files)}
diff --git a/public/js/modules.js b/public/js/modules.js index 470c72c..88e05d1 100644 --- a/public/js/modules.js +++ b/public/js/modules.js @@ -55,7 +55,7 @@ function renderModules(total) { ${m.photo_path ? `` : ''}
${esc(m.name)}${m.has_attachments ? ' Вложения' : ''}${m.is_active ? '' : ' Отключён'}
-
${m.lessons_count} ${mPlural(m.lessons_count, 'занятие', 'занятия', 'занятий')} · ${m.entries_count} ${mPlural(m.entries_count, 'запись', 'записи', 'записей')}
+
${m.lessons_count} ${mPlural(m.lessons_count, 'занятие', 'занятия', 'занятий')} · ${m.entries_count} ${mPlural(m.entries_count, 'запись', 'записи', 'записей')}${m.rating_avg != null ? ` · ★ ${Number(m.rating_avg).toFixed(1).replace('.', ',')}${m.rating_count ? ` (${m.rating_count})` : ''}` : ''}
${m.is_active diff --git a/server.js b/server.js index b544ca3..6ed78b6 100644 --- a/server.js +++ b/server.js @@ -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 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 rating SMALLINT'); 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 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 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 UNIQUE INDEX IF NOT EXISTS idx_entries_client_id ON entries(client_id) WHERE client_id IS NOT NULL`); await pool.query(` @@ -7869,8 +7871,8 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b } for (const x of ndata.entries) { 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)', - [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] + '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.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) { @@ -9388,7 +9390,9 @@ app.get('/api/modules', apiLimiter, async (req, res) => { 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 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 LEFT JOIN entries e ON e.module_id = m.id${where} 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 ); 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 LEFT JOIN modules m ON m.id = e.module_id${where} ORDER BY e.created_at DESC`; 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: 'Нет доступа к этой записи' }); } 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 LEFT JOIN modules m ON m.id = e.module_id WHERE e.id = $1`, @@ -12014,6 +12028,20 @@ app.post('/api/entries', entryLimiter, (req, res, next) => { 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; if (intervalMin > 0) { 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 { rows } = await client.query( - `INSERT INTO entries (student_name, group_id, module_id, description, description_original, photo_path, client_id) - VALUES ($1, $2, $3, $4, $4, $5, $6) RETURNING *`, - [student_name.trim(), gid, mid, description.trim(), mainPhotoPath, clientId] + `INSERT INTO entries (student_name, group_id, module_id, rating, description, description_original, photo_path, client_id) + VALUES ($1, $2, $3, $4, $5, $5, $6, $7) RETURNING *`, + [student_name.trim(), gid, mid, rating, description.trim(), mainPhotoPath, clientId] ); for (let i = 0; i < photos.length; 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( `SELECT id, student_name, group_id, module_id, description, description_ai 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), description = COALESCE($3, description), 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 *`, [ 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, hasModule, mid, + hasRating, + rating, ] ); if (!rows.length) {