43 lines
1.5 KiB
JavaScript
43 lines
1.5 KiB
JavaScript
const LESSON_REPORT_EDIT_DENIED = 'Изменять отчёт о занятии может только его автор или администратор';
|
|
const LESSON_TOPIC_MATCH_WINDOW_SEC = 3600;
|
|
|
|
function lessonReportEditable(report, user) {
|
|
if (!report || !user) return false;
|
|
if (user.role === 'admin') return true;
|
|
if (report.author_id == null) return false;
|
|
return Number(report.author_id) === Number(user.id);
|
|
}
|
|
|
|
function lessonReportWriteBlocked(res, report, user) {
|
|
if (lessonReportEditable(report, user)) return false;
|
|
res.status(403).json({ error: LESSON_REPORT_EDIT_DENIED });
|
|
return true;
|
|
}
|
|
|
|
function stripLessonTopicNumber(topic) {
|
|
return String(topic || '').trim().replace(/\s*\d+\s*\/\s*\d+\s*$/, '').trim();
|
|
}
|
|
|
|
async function findCurrentLessonTopic(pool, { groupId, timezone, windowSec = LESSON_TOPIC_MATCH_WINDOW_SEC }) {
|
|
const { rows } = await pool.query(`
|
|
SELECT lr.topic
|
|
FROM lesson_reports lr
|
|
WHERE lr.group_id = $2
|
|
AND lr.lesson_date = (now() AT TIME ZONE $1)::date
|
|
AND lr.lesson_time IS NOT NULL
|
|
AND ABS(EXTRACT(EPOCH FROM (lr.lesson_time - (now() AT TIME ZONE $1)::time))) <= $3
|
|
ORDER BY ABS(EXTRACT(EPOCH FROM (lr.lesson_time - (now() AT TIME ZONE $1)::time))) ASC, lr.id DESC
|
|
LIMIT 1
|
|
`, [timezone, groupId, windowSec]);
|
|
return rows.length ? stripLessonTopicNumber(rows[0].topic) || null : null;
|
|
}
|
|
|
|
module.exports = {
|
|
LESSON_REPORT_EDIT_DENIED,
|
|
LESSON_TOPIC_MATCH_WINDOW_SEC,
|
|
lessonReportEditable,
|
|
lessonReportWriteBlocked,
|
|
stripLessonTopicNumber,
|
|
findCurrentLessonTopic,
|
|
};
|