Files
WhatIDo/lib/quiz-ai-jobs.js
T
dev ef4d7cc472 Тесты и опросы: генерация ИИ, критерии оценки, версия 2.0
- ИИ-генерация черновиков тестов (lib/quiz-ai.js, quiz-ai-jobs, quiz-ai.selftest.js)
- Критерии оценки (quiz_grade_scales/quiz_grade_ranges, lib/quiz-grades.js, public/js/grade-scales.js)
- Версия 2.0 формата бэкапа, добавление таблиц тестов в BACKUP_TABLES
- Обновление AGENTS.md под новый функционал тестов/опросов
2026-12-02 14:27:57 +03:00

199 lines
6.6 KiB
JavaScript

'use strict';
const JOB_STATUSES = new Set(['pending', 'processing', 'done', 'error']);
const PRUNE_DAYS = 7;
const HISTORY_DEFAULT_LIMIT = 20;
const HISTORY_MAX_LIMIT = 100;
function publicJob(row) {
if (!row) return null;
return {
id: row.id,
user_id: row.user_id,
status: JOB_STATUSES.has(row.status) ? row.status : 'pending',
kind: row.kind,
count: row.question_count,
questions: row.questions == null ? null : Number(row.questions),
model: row.model || null,
quiz_id: row.quiz_id == null ? null : Number(row.quiz_id),
error: row.error || null,
created_at: row.created_at,
updated_at: row.updated_at,
finished_at: row.finished_at,
};
}
function historyJob(row) {
const job = publicJob(row);
if (!job) return null;
job.user_name = row.user_name || null;
job.user_username = row.user_username || null;
job.prompt = row.prompt || '';
job.difficulty = row.difficulty || 'medium';
job.profile = row.profile || '';
job.attempts = Number(row.attempts) || 0;
return job;
}
async function listQuizAiJobs(pool, user, options = {}) {
const limit = Math.max(1, Math.min(HISTORY_MAX_LIMIT, parseInt(options.limit, 10) || HISTORY_DEFAULT_LIMIT));
const offset = Math.max(0, parseInt(options.offset, 10) || 0);
const own = user.role !== 'admin';
const where = own ? 'WHERE j.user_id = $1' : '';
const params = own ? [user.id] : [];
params.push(limit, offset);
const { rows } = await pool.query(
`SELECT j.*, u.name AS user_name, u.username AS user_username
FROM quiz_ai_jobs j
LEFT JOIN users u ON u.id = j.user_id
${where}
ORDER BY j.id DESC
LIMIT $${params.length - 1} OFFSET $${params.length}`,
params
);
const { rows: countRows } = await pool.query(
`SELECT count(*)::int AS total FROM quiz_ai_jobs j ${where}`,
own ? [user.id] : []
);
return { items: rows.map(historyJob), total: countRows[0] ? countRows[0].total : 0 };
}
async function ensureQuizAiJobsTable(pool) {
await pool.query(`CREATE TABLE IF NOT EXISTS quiz_ai_jobs (
id SERIAL PRIMARY KEY,
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
prompt TEXT NOT NULL,
kind VARCHAR(16) NOT NULL DEFAULT 'test',
question_count INT NOT NULL DEFAULT 10,
difficulty VARCHAR(16) NOT NULL DEFAULT 'medium',
profile TEXT NOT NULL DEFAULT '',
status VARCHAR(16) NOT NULL DEFAULT 'pending',
attempts INT NOT NULL DEFAULT 0,
quiz_id INT REFERENCES quizzes(id) ON DELETE SET NULL,
questions INT,
model TEXT,
error TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
finished_at TIMESTAMPTZ
)`);
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS attempts INT NOT NULL DEFAULT 0');
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS profile TEXT NOT NULL DEFAULT \'\'');
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS quiz_id INT REFERENCES quizzes(id) ON DELETE SET NULL');
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS questions INT');
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS model TEXT');
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS error TEXT');
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS finished_at TIMESTAMPTZ');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_ai_jobs_status ON quiz_ai_jobs(status, id)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_ai_jobs_user ON quiz_ai_jobs(user_id, status)');
}
async function createQuizAiJob(pool, user, request) {
const { rows } = await pool.query(
`INSERT INTO quiz_ai_jobs (user_id, prompt, kind, question_count, difficulty, profile)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING *`,
[user.id, request.prompt, request.kind, request.count, request.difficulty, request.profile]
);
return publicJob(rows[0]);
}
async function findActiveQuizAiJob(pool, userId) {
const { rows } = await pool.query(
`SELECT * FROM quiz_ai_jobs
WHERE user_id = $1 AND status IN ('pending', 'processing')
ORDER BY id DESC LIMIT 1`,
[userId]
);
return rows.length ? publicJob(rows[0]) : null;
}
async function getQuizAiJob(pool, id, user) {
const { rows } = await pool.query('SELECT * FROM quiz_ai_jobs WHERE id = $1', [id]);
if (!rows.length) return null;
const row = rows[0];
if (user.role !== 'admin' && Number(row.user_id) !== Number(user.id)) return null;
return publicJob(row);
}
async function claimQuizAiJob(pool) {
const client = await pool.connect();
try {
await client.query('BEGIN');
const { rows } = await client.query(
`SELECT id, user_id, prompt, kind, question_count, difficulty, profile
FROM quiz_ai_jobs
WHERE status = 'pending'
ORDER BY id ASC LIMIT 1
FOR UPDATE SKIP LOCKED`
);
if (!rows.length) {
await client.query('COMMIT');
return null;
}
await client.query(
`UPDATE quiz_ai_jobs
SET status = 'processing', attempts = attempts + 1, updated_at = now()
WHERE id = $1`,
[rows[0].id]
);
await client.query('COMMIT');
return rows[0];
} catch (e) {
await client.query('ROLLBACK').catch(() => {});
throw e;
} finally {
client.release();
}
}
async function finishQuizAiJob(pool, id, result) {
const { rows } = await pool.query(
`UPDATE quiz_ai_jobs
SET status = 'done', quiz_id = $2, questions = $3, model = $4,
error = NULL, updated_at = now(), finished_at = now()
WHERE id = $1
RETURNING *`,
[id, result.quiz.id, result.questions, result.model]
);
return rows[0] || null;
}
async function failQuizAiJob(pool, id, message) {
const { rows } = await pool.query(
`UPDATE quiz_ai_jobs
SET status = 'error', error = $2, updated_at = now(), finished_at = now()
WHERE id = $1
RETURNING *`,
[id, String(message || '').slice(0, 500)]
);
return rows[0] || null;
}
async function resetStaleQuizAiJobs(pool) {
await pool.query(`UPDATE quiz_ai_jobs SET status = 'pending', updated_at = now() WHERE status = 'processing'`);
}
async function pruneQuizAiJobs(pool, days = PRUNE_DAYS) {
const keep = Math.max(1, parseInt(days, 10) || PRUNE_DAYS);
await pool.query(
`DELETE FROM quiz_ai_jobs
WHERE status IN ('done', 'error')
AND updated_at < now() - ($1::int * interval '1 day')`,
[keep]
);
}
module.exports = {
ensureQuizAiJobsTable,
createQuizAiJob,
findActiveQuizAiJob,
getQuizAiJob,
listQuizAiJobs,
claimQuizAiJob,
finishQuizAiJob,
failQuizAiJob,
resetStaleQuizAiJobs,
pruneQuizAiJobs,
};