fix(feedback): короткие сообщения считаются использованными только при отправке отзыва
- POST /api/feedbacks больше не ставит short_messages.used: черновик не расходует короткие сообщения - установка/снятие used только в PUT /:id/sent, защита при снятии — по другим неудалённым ОТПРАВЛЕННЫМ отзывам - редактирование отправленного отзыва синхронизирует добавленные/удалённые short_message_ids - удаление/восстановление отзыва освобождает/помечает его короткие сообщения - restore сохраняет feedbacks.sent_at (раньше терялся) - migration.sql: освобождение коротких, привязанных к неотправленным черновикам + ALTER used
This commit is contained in:
@@ -2664,6 +2664,7 @@ async function ensureShortMessagesTable() {
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now()
|
||||
)`);
|
||||
await pool.query(`ALTER TABLE short_messages ADD COLUMN IF NOT EXISTS used BOOLEAN NOT NULL DEFAULT false`);
|
||||
await pool.query(`ALTER TABLE short_messages ADD COLUMN IF NOT EXISTS used_at DATE`);
|
||||
await pool.query(`ALTER TABLE short_messages ADD COLUMN IF NOT EXISTS author_id INT REFERENCES users(id) ON DELETE SET NULL`);
|
||||
await pool.query(`CREATE INDEX IF NOT EXISTS idx_short_messages_date ON short_messages(lesson_date DESC)`);
|
||||
@@ -2948,6 +2949,27 @@ async function feedbackById(user, id) {
|
||||
return row;
|
||||
}
|
||||
|
||||
const SHORTS_MARK_USED_SQL = `UPDATE short_messages SET used = true, used_at = CURRENT_DATE WHERE id = ANY($1::int[]) AND deleted_at IS NULL`;
|
||||
const SHORTS_RELEASE_SQL = `UPDATE short_messages sm SET used = false, used_at = NULL
|
||||
WHERE sm.id = ANY($1::int[]) AND sm.deleted_at IS NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM feedbacks f WHERE f.id <> $2 AND f.deleted_at IS NULL AND f.sent_at IS NOT NULL AND sm.id = ANY(f.short_message_ids))`;
|
||||
|
||||
function feedbackShortIds(fb) {
|
||||
return Array.isArray(fb?.short_message_ids) ? fb.short_message_ids : [];
|
||||
}
|
||||
|
||||
async function shortsMarkUsed(q, ids) {
|
||||
if (!ids.length) return false;
|
||||
await q.query(SHORTS_MARK_USED_SQL, [ids]);
|
||||
return true;
|
||||
}
|
||||
|
||||
async function shortsRelease(q, ids, fbId) {
|
||||
if (!ids.length) return false;
|
||||
await q.query(SHORTS_RELEASE_SQL, [ids, fbId]);
|
||||
return true;
|
||||
}
|
||||
|
||||
function parseFeedbackDate(s) {
|
||||
const str = typeof s === 'string' ? s.trim() : '';
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(str)) return null;
|
||||
@@ -3074,13 +3096,9 @@ app.post('/api/feedbacks', requireAuth, async (req, res) => {
|
||||
[feedbackDate, groupId, resident, topic, pastReview, shortIds, text || '', aiCheck ? 'pending' : 'none', aiProfile || null, req.user.id, branchId]
|
||||
);
|
||||
const fb = insert.rows[0];
|
||||
if (shortIds.length) {
|
||||
await client.query(`UPDATE short_messages SET used = true, used_at = CURRENT_DATE WHERE id = ANY($1::int[]) AND deleted_at IS NULL`, [shortIds]);
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
await logAudit(req, 'feedback.create', { id: fb.id, group_id: groupId, resident, ai_check: aiCheck, ai_profile: aiProfile || null, ai_status: fb.ai_status, short_count: shortIds.length });
|
||||
invalidateFeedbacks();
|
||||
invalidateShorts();
|
||||
if (aiCheck) wakeFeedbackWorker();
|
||||
res.status(201).json(fb);
|
||||
} catch (e) {
|
||||
@@ -3263,15 +3281,35 @@ app.put('/api/feedbacks/:id', requireAuth, async (req, res) => {
|
||||
}
|
||||
const aiCheck = !!req.body?.ai_check;
|
||||
const aiProfile = optStr(req.body?.ai_profile, 100);
|
||||
await pool.query(
|
||||
`UPDATE feedbacks SET feedback_date=$1, group_id=$2, resident=$3, topic=$4, past_review=$5, short_message_ids=$6, text=$7, ai_profile=$8,
|
||||
ai_status = CASE WHEN $9::boolean AND ai_status IN ('none','error','done','skipped') THEN 'pending' ELSE ai_status END,
|
||||
ai_error = CASE WHEN $9::boolean AND ai_status IN ('none','error','done','skipped') THEN NULL ELSE ai_error END,
|
||||
ai_checked_at = CASE WHEN $9::boolean AND ai_status IN ('none','error','done','skipped') THEN NULL ELSE ai_checked_at END,
|
||||
updated_at=now() WHERE id=$10`,
|
||||
[feedbackDate, groupId, resident, topic, pastReview, shortIds, text || '', aiProfile || null, aiCheck, id]
|
||||
);
|
||||
const prevShortIds = feedbackShortIds(fb);
|
||||
const addedShorts = shortIds.filter(sid => !prevShortIds.includes(sid));
|
||||
const removedShorts = prevShortIds.filter(sid => !shortIds.includes(sid));
|
||||
const wasSent = !!fb.sent_at;
|
||||
const client = await pool.connect();
|
||||
let shortsTouched = false;
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
await client.query(
|
||||
`UPDATE feedbacks SET feedback_date=$1, group_id=$2, resident=$3, topic=$4, past_review=$5, short_message_ids=$6, text=$7, ai_profile=$8,
|
||||
ai_status = CASE WHEN $9::boolean AND ai_status IN ('none','error','done','skipped') THEN 'pending' ELSE ai_status END,
|
||||
ai_error = CASE WHEN $9::boolean AND ai_status IN ('none','error','done','skipped') THEN NULL ELSE ai_error END,
|
||||
ai_checked_at = CASE WHEN $9::boolean AND ai_status IN ('none','error','done','skipped') THEN NULL ELSE ai_checked_at END,
|
||||
updated_at=now() WHERE id=$10`,
|
||||
[feedbackDate, groupId, resident, topic, pastReview, shortIds, text || '', aiProfile || null, aiCheck, id]
|
||||
);
|
||||
if (wasSent) {
|
||||
shortsTouched = (await shortsMarkUsed(client, addedShorts)) || shortsTouched;
|
||||
shortsTouched = (await shortsRelease(client, removedShorts, id)) || shortsTouched;
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
invalidateFeedbacks();
|
||||
if (shortsTouched) invalidateShorts();
|
||||
if (aiCheck) wakeFeedbackWorker();
|
||||
await logAudit(req, 'feedback.update', { id, ai_check: aiCheck, ai_profile: aiProfile || null });
|
||||
res.json({ ok: true });
|
||||
@@ -3285,10 +3323,26 @@ app.delete('/api/feedbacks/:id', requireAuth, async (req, res) => {
|
||||
if (fb.forbidden) return res.status(403).json({ error: 'Нет доступа' });
|
||||
const d = await pool.query('SELECT COALESCE((SELECT value::int FROM settings WHERE key=\'trash_purge_days\'),30) AS d');
|
||||
const days = d.rows[0]?.d || 30;
|
||||
const upd = await pool.query('UPDATE feedbacks SET deleted_at=now(), purge_at = now() + ($1 || \' days\')::interval WHERE id=$2 AND deleted_at IS NULL', [days, id]);
|
||||
if (!upd.rowCount) return res.status(404).json({ error: 'Уже удалён' });
|
||||
const client = await pool.connect();
|
||||
let shortsTouched = false;
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const upd = await client.query('UPDATE feedbacks SET deleted_at=now(), purge_at = now() + ($1 || \' days\')::interval WHERE id=$2 AND deleted_at IS NULL', [days, id]);
|
||||
if (!upd.rowCount) {
|
||||
await client.query('ROLLBACK');
|
||||
return res.status(404).json({ error: 'Уже удалён' });
|
||||
}
|
||||
if (fb.sent_at) shortsTouched = await shortsRelease(client, feedbackShortIds(fb), id);
|
||||
await client.query('COMMIT');
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
await logAudit(req, 'feedback.delete', { id });
|
||||
invalidateFeedbacks();
|
||||
if (shortsTouched) invalidateShorts();
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
@@ -3298,10 +3352,26 @@ app.put('/api/feedbacks/:id/restore', requireAuth, async (req, res) => {
|
||||
const fb = await feedbackById(req.user, id);
|
||||
if (!fb) return res.status(404).json({ error: 'Not found' });
|
||||
if (fb.forbidden) return res.status(403).json({ error: 'Нет доступа' });
|
||||
const upd = await pool.query('UPDATE feedbacks SET deleted_at=NULL, purge_at=NULL WHERE id=$1 AND deleted_at IS NOT NULL', [id]);
|
||||
if (!upd.rowCount) return res.status(404).json({ error: 'Не удалён' });
|
||||
const client = await pool.connect();
|
||||
let shortsTouched = false;
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const upd = await client.query('UPDATE feedbacks SET deleted_at=NULL, purge_at=NULL WHERE id=$1 AND deleted_at IS NOT NULL', [id]);
|
||||
if (!upd.rowCount) {
|
||||
await client.query('ROLLBACK');
|
||||
return res.status(404).json({ error: 'Не удалён' });
|
||||
}
|
||||
if (fb.sent_at) shortsTouched = await shortsMarkUsed(client, feedbackShortIds(fb));
|
||||
await client.query('COMMIT');
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
await logAudit(req, 'feedback.restore', { id });
|
||||
invalidateFeedbacks();
|
||||
if (shortsTouched) invalidateShorts();
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
@@ -3311,10 +3381,26 @@ app.delete('/api/feedbacks/:id/permanent', requireAuth, async (req, res) => {
|
||||
const fb = await feedbackById(req.user, id);
|
||||
if (!fb) return res.status(404).json({ error: 'Not found' });
|
||||
if (fb.forbidden) return res.status(403).json({ error: 'Нет доступа' });
|
||||
const del = await pool.query('DELETE FROM feedbacks WHERE id=$1 AND deleted_at IS NOT NULL', [id]);
|
||||
if (!del.rowCount) return res.status(404).json({ error: 'Не удалён' });
|
||||
const client = await pool.connect();
|
||||
let shortsTouched = false;
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const del = await client.query('DELETE FROM feedbacks WHERE id=$1 AND deleted_at IS NOT NULL', [id]);
|
||||
if (!del.rowCount) {
|
||||
await client.query('ROLLBACK');
|
||||
return res.status(404).json({ error: 'Не удалён' });
|
||||
}
|
||||
if (fb.sent_at) shortsTouched = await shortsRelease(client, feedbackShortIds(fb), id);
|
||||
await client.query('COMMIT');
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
await logAudit(req, 'feedback.permanent-delete', { id });
|
||||
invalidateFeedbacks();
|
||||
if (shortsTouched) invalidateShorts();
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
@@ -3327,20 +3413,14 @@ app.put('/api/feedbacks/:id/sent', requireAuth, async (req, res) => {
|
||||
if (fb.forbidden) return res.status(403).json({ error: 'Нет доступа' });
|
||||
const sent = typeof req.body?.sent === 'boolean' ? req.body.sent : null;
|
||||
if (sent === null) return res.status(400).json({ error: 'Некорректный статус' });
|
||||
const shortIds = Array.isArray(fb.short_message_ids) ? fb.short_message_ids : [];
|
||||
const shortIds = feedbackShortIds(fb);
|
||||
const client = await pool.connect();
|
||||
let shortsTouched = false;
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
await client.query('UPDATE feedbacks SET sent_at = $1, updated_at = now() WHERE id = $2 AND deleted_at IS NULL', [sent ? new Date() : null, id]);
|
||||
if (shortIds.length) {
|
||||
if (sent) {
|
||||
await client.query('UPDATE short_messages SET used = true, used_at = CURRENT_DATE WHERE id = ANY($1::int[]) AND deleted_at IS NULL', [shortIds]);
|
||||
} else {
|
||||
await client.query(`UPDATE short_messages sm SET used = false, used_at = NULL
|
||||
WHERE sm.id = ANY($1::int[]) AND sm.deleted_at IS NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM feedbacks f WHERE f.deleted_at IS NULL AND f.id <> $2 AND sm.id = ANY(f.short_message_ids))`, [shortIds, id]);
|
||||
}
|
||||
}
|
||||
if (sent) shortsTouched = await shortsMarkUsed(client, shortIds);
|
||||
else shortsTouched = await shortsRelease(client, shortIds, id);
|
||||
await client.query('COMMIT');
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
@@ -3350,7 +3430,7 @@ app.put('/api/feedbacks/:id/sent', requireAuth, async (req, res) => {
|
||||
}
|
||||
await logAudit(req, 'feedback.sent', { id, sent, short_count: shortIds.length });
|
||||
invalidateFeedbacks();
|
||||
invalidateShorts();
|
||||
if (shortsTouched) invalidateShorts();
|
||||
res.json({ ok: true, sent });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
@@ -4438,8 +4518,8 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
|
||||
const okUser = x.author_id == null || (await client.query('SELECT 1 FROM users WHERE id = $1', [x.author_id])).rowCount;
|
||||
const okBranch = x.branch_id == null || (await client.query('SELECT 1 FROM branches WHERE id = $1', [x.branch_id])).rowCount;
|
||||
await client.query(
|
||||
'INSERT INTO feedbacks (id, feedback_date, group_id, resident, topic, past_review, short_message_ids, text, ai_status, ai_checked_at, ai_error, ai_profile, ai_prompt, ai_model, ai_duration_ms, author_id, branch_id, deleted_at, purge_at, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21)',
|
||||
[x.id, x.feedback_date, okGroup ? x.group_id : null, x.resident, x.topic, x.past_review, Array.isArray(x.short_message_ids) ? x.short_message_ids : [], x.text || '', x.ai_status || 'none', x.ai_checked_at, x.ai_error, x.ai_profile, x.ai_prompt, x.ai_model, x.ai_duration_ms, okUser ? x.author_id : null, okBranch ? x.branch_id : null, x.deleted_at, x.purge_at, x.created_at, x.updated_at]
|
||||
'INSERT INTO feedbacks (id, feedback_date, group_id, resident, topic, past_review, short_message_ids, text, ai_status, ai_checked_at, ai_error, ai_profile, ai_prompt, ai_model, ai_duration_ms, sent_at, author_id, branch_id, deleted_at, purge_at, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22)',
|
||||
[x.id, x.feedback_date, okGroup ? x.group_id : null, x.resident, x.topic, x.past_review, Array.isArray(x.short_message_ids) ? x.short_message_ids : [], x.text || '', x.ai_status || 'none', x.ai_checked_at, x.ai_error, x.ai_profile, x.ai_prompt, x.ai_model, x.ai_duration_ms, x.sent_at, okUser ? x.author_id : null, okBranch ? x.branch_id : null, x.deleted_at, x.purge_at, x.created_at, x.updated_at]
|
||||
);
|
||||
}
|
||||
for (const x of ndata.audit_log) {
|
||||
|
||||
Reference in New Issue
Block a user