const { reqStr, optText, optDate } = require('../backup-restore'); const ACH_TYPE_NAME_MAX = 150; const ACH_VALUE_MAX = 200; const ACH_NOTE_MAX = 800; const ACH_TYPES_LIMIT = 200; const ACH_LIST_LIMIT = 200; function httpError(status, message) { const err = new Error(message); err.status = status; return err; } function achError(res, e, fallback, label) { if (e && e.status) return res.status(e.status).json({ error: e.message }); if (e && e.code === '23505') return res.status(400).json({ error: 'Такой тип уже есть' }); if (e && (e.message === 'Invalid string' || e.message === 'Invalid string length' || e.message === 'Invalid integer' || e.message === 'Invalid date')) { return res.status(400).json({ error: 'Неверные данные' }); } console.error(`${label}:`, e); return res.status(500).json({ error: fallback }); } function normAchDate(v) { if (v === null || v === undefined || v === '') return null; return optDate(v); } function achRecordFields(body) { return { typeName: reqStr(body?.type_name, ACH_TYPE_NAME_MAX), value: optText(body?.value, ACH_VALUE_MAX), achievedAt: normAchDate(body?.achieved_at), note: optText(body?.note, ACH_NOTE_MAX), }; } function achFieldsError(e) { return e.message === 'Invalid date' ? 'Некорректная дата достижения' : 'Неверные данные достижения'; } async function listTypes(pool) { const { rows } = await pool.query( 'SELECT id, name, sort_order, is_active, created_at, updated_at FROM achievement_types ORDER BY sort_order ASC, id ASC' ); return rows; } async function listActiveTypes(pool) { const { rows } = await pool.query( 'SELECT id, name FROM achievement_types WHERE is_active = true ORDER BY sort_order ASC, id ASC LIMIT $1', [ACH_TYPES_LIMIT] ); return rows; } async function createType(pool, name) { const dup = await pool.query('SELECT 1 FROM achievement_types WHERE lower(name) = lower($1) LIMIT 1', [name]); if (dup.rows.length) throw httpError(400, 'Такой тип уже есть'); const { rows } = await pool.query( `INSERT INTO achievement_types (name, sort_order) VALUES ($1, COALESCE((SELECT MIN(sort_order) FROM achievement_types), 1) - 1) RETURNING id, name, sort_order, is_active, created_at, updated_at`, [name] ); return rows[0]; } async function updateType(pool, id, name, isActive) { const prev = await pool.query('SELECT name, is_active FROM achievement_types WHERE id = $1', [id]); if (!prev.rows.length) throw httpError(404, 'Тип не найден'); const oldName = prev.rows[0].name; const effectiveActive = typeof isActive === 'boolean' ? isActive : prev.rows[0].is_active === true; const dup = await pool.query('SELECT 1 FROM achievement_types WHERE lower(name) = lower($1) AND id <> $2 LIMIT 1', [name, id]); if (dup.rows.length) throw httpError(400, 'Такой тип уже есть'); const { rows } = await pool.query( `UPDATE achievement_types SET name = $1, is_active = $2, updated_at = now() WHERE id = $3 RETURNING id, name, sort_order, is_active, created_at, updated_at`, [name, effectiveActive, id] ); let renamed = 0; if (oldName !== name) { const up = await pool.query('UPDATE student_achievements SET type_name = $1, updated_at = now() WHERE type_name = $2', [name, oldName]); renamed = up.rowCount; } return { item: rows[0], renamed }; } async function deleteType(pool, id) { const { rows } = await pool.query('DELETE FROM achievement_types WHERE id = $1 RETURNING name', [id]); if (!rows.length) throw httpError(404, 'Тип не найден'); return rows[0]; } async function reorderTypes(pool, ids) { const client = await pool.connect(); try { await client.query('BEGIN'); for (let i = 0; i < ids.length; i++) { const { rowCount } = await client.query('UPDATE achievement_types SET sort_order = $1 WHERE id = $2', [i + 1, ids[i]]); if (!rowCount) throw httpError(404, 'Тип не найден'); } await client.query('COMMIT'); } catch (e) { await client.query('ROLLBACK'); throw e; } finally { client.release(); } } const ACH_ITEM_COLS = 'id, student_id, type_name, value, achieved_at, note, author_id, created_at, updated_at'; async function listForStudent(pool, studentId) { const { rows } = await pool.query( `SELECT ${ACH_ITEM_COLS}, count(*) OVER () AS total FROM student_achievements WHERE student_id = $1 ORDER BY achieved_at DESC NULLS LAST, id DESC LIMIT $2`, [studentId, ACH_LIST_LIMIT] ); const total = rows.length ? Number(rows[0].total) : 0; const items = rows.map(({ total: _t, ...rest }) => rest); return { items, total }; } async function createRecord(pool, { studentId, typeName, value, achievedAt, note, authorId }) { const { rows } = await pool.query( `INSERT INTO student_achievements (student_id, type_name, value, achieved_at, note, author_id) VALUES ($1, $2, $3, $4, $5, $6) RETURNING ${ACH_ITEM_COLS}`, [studentId, typeName, value, achievedAt, note, authorId] ); return rows[0]; } async function updateRecord(pool, studentId, achId, { typeName, value, achievedAt, note }) { const { rows } = await pool.query( `UPDATE student_achievements SET type_name = $2, value = $3, achieved_at = $4, note = $5, updated_at = now() WHERE id = $6 AND student_id = $1 RETURNING ${ACH_ITEM_COLS}`, [studentId, typeName, value, achievedAt, note, achId] ); if (!rows.length) throw httpError(404, 'Достижение не найдено'); return rows[0]; } async function deleteRecord(pool, studentId, achId) { const { rows } = await pool.query( `DELETE FROM student_achievements WHERE id = $2 AND student_id = $1 RETURNING ${ACH_ITEM_COLS}`, [studentId, achId] ); if (!rows.length) throw httpError(404, 'Достижение не найдено'); return rows[0]; } module.exports = { ACH_TYPE_NAME_MAX, ACH_VALUE_MAX, ACH_NOTE_MAX, ACH_TYPES_LIMIT, ACH_LIST_LIMIT, achError, normAchDate, achRecordFields, achFieldsError, listTypes, listActiveTypes, createType, updateType, deleteType, reorderTypes, listForStudent, createRecord, updateRecord, deleteRecord, };