Пользователи: цвет при создании и редактировании

This commit is contained in:
dev
2026-11-28 12:34:15 +03:00
parent cde281fd89
commit c9d477b6c5
8 changed files with 79 additions and 14 deletions
+19 -13
View File
@@ -12,6 +12,7 @@ const { createZipWriter, renderStudentReport } = require('./student-report');
const { createStorage, mimeFor } = require('./storage');
const { createRedis } = require('./redis');
const { buildEntryDiff, textDiff, normalizeEditSource, stripDiffs } = require('./diff');
const { DEFAULT_USER_COLOR, normalizeUserColor, randomUserColor } = require('./lib/users');
const {
PHOTO_JOB_ACTIONS,
LESSON_REPORT_TEXT_MAX,
@@ -1336,6 +1337,7 @@ function safeUser(u) {
email: u.email || null,
phone: u.phone || null,
avatar: u.avatar || null,
color: normalizeUserColor(u.color),
role: u.role,
is_active: u.is_active,
created_at: u.created_at || null,
@@ -1349,7 +1351,7 @@ async function loadUserByToken(token) {
const cached = await cache.get(key);
if (cached !== undefined) return cached;
const { rows } = await pool.query(
`SELECT u.id, u.username, u.name, u.role, u.is_active,
`SELECT u.id, u.username, u.name, u.color, u.role, u.is_active,
COALESCE(array_agg(ub.branch_id) FILTER (WHERE ub.branch_id IS NOT NULL), '{}') AS branch_ids
FROM sessions s
JOIN users u ON u.id = s.user_id
@@ -2832,6 +2834,7 @@ async function ensureUserTables() {
email VARCHAR(255),
phone VARCHAR(50),
avatar VARCHAR(255),
color VARCHAR(7) NOT NULL DEFAULT '#2563eb',
role VARCHAR(20) NOT NULL DEFAULT 'tutor' CHECK (role IN ('admin','tutor')),
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now()
@@ -2839,6 +2842,7 @@ async function ensureUserTables() {
await pool.query('ALTER TABLE users ADD COLUMN IF NOT EXISTS email VARCHAR(255)');
await pool.query('ALTER TABLE users ADD COLUMN IF NOT EXISTS phone VARCHAR(50)');
await pool.query('ALTER TABLE users ADD COLUMN IF NOT EXISTS avatar VARCHAR(255)');
await pool.query('ALTER TABLE users ADD COLUMN IF NOT EXISTS color VARCHAR(7) NOT NULL DEFAULT \'#2563eb\'');
await pool.query(`CREATE TABLE IF NOT EXISTS user_branches (
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
branch_id INT NOT NULL REFERENCES branches(id) ON DELETE CASCADE,
@@ -4715,7 +4719,7 @@ app.post('/api/shorts/ai-correct', requireAuth, aiLimiter, async (req, res) => {
// --- Users (admin only) ---
app.get('/api/users', requireAuth, requireAdmin, async (_, res) => {
const { rows } = await pool.query(
`SELECT u.id, u.username, u.name, u.role, u.is_active, u.created_at,
`SELECT u.id, u.username, u.name, u.color, u.role, u.is_active, u.created_at,
COALESCE(array_agg(ub.branch_id) FILTER (WHERE ub.branch_id IS NOT NULL), '{}') AS branch_ids
FROM users u
LEFT JOIN user_branches ub ON ub.user_id = u.id
@@ -4769,6 +4773,7 @@ app.post('/api/users', requireAuth, requireAdmin, async (req, res) => {
const name = optStr(req.body?.name, 150);
const role = req.body?.role === 'admin' ? 'admin' : 'tutor';
const isActive = req.body?.is_active !== false;
const color = normalizeUserColor(req.body?.color, randomUserColor());
let branchIds = Array.isArray(req.body?.branch_ids) ?
[...new Set(req.body.branch_ids.map(Number).filter(Boolean))] : [];
if (role === 'admin') branchIds = [];
@@ -4778,15 +4783,15 @@ app.post('/api/users', requireAuth, requireAdmin, async (req, res) => {
try {
await client.query('BEGIN');
const { rows } = await client.query(
'INSERT INTO users (username, password_hash, name, role, is_active) VALUES ($1, $2, $3, $4, $5) RETURNING *',
[username, hash, name, role, isActive]
'INSERT INTO users (username, password_hash, name, role, is_active, color) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *',
[username, hash, name, role, isActive, color]
);
const user = rows[0];
for (const b of branchIds) {
await client.query('INSERT INTO user_branches (user_id, branch_id) VALUES ($1, $2)', [user.id, b]);
}
await client.query('COMMIT');
await logAudit(req, 'user.create', { id: user.id, username: user.username, role });
await logAudit(req, 'user.create', { id: user.id, username: user.username, role, color });
res.status(201).json(safeUser({ ...user, branch_ids: branchIds }));
} catch (e) {
await client.query('ROLLBACK').catch(() => {});
@@ -4811,6 +4816,7 @@ app.put('/api/users/:id', requireAuth, requireAdmin, async (req, res) => {
const name = req.body?.name !== undefined ? optStr(req.body.name, 150) : target.name;
const newRole = req.body?.role ? (req.body.role === 'admin' ? 'admin' : 'tutor') : target.role;
const isActive = req.body?.is_active !== undefined ? req.body.is_active !== false : target.is_active;
const color = req.body?.color !== undefined ? normalizeUserColor(req.body.color, target.color) : normalizeUserColor(target.color);
let branchIds = null;
if (Array.isArray(req.body?.branch_ids)) {
branchIds = [...new Set(req.body.branch_ids.map(Number).filter(Boolean))];
@@ -4827,8 +4833,8 @@ app.put('/api/users/:id', requireAuth, requireAdmin, async (req, res) => {
await client.query('UPDATE users SET password_hash = $1 WHERE id = $2', [hash, id]);
}
await client.query(
'UPDATE users SET name = $1, role = $2, is_active = $3 WHERE id = $4',
[name, newRole, isActive, id]
'UPDATE users SET name = $1, role = $2, is_active = $3, color = $4 WHERE id = $5',
[name, newRole, isActive, color, id]
);
if (branchIds !== null) {
await client.query('DELETE FROM user_branches WHERE user_id = $1', [id]);
@@ -4844,9 +4850,9 @@ app.put('/api/users/:id', requireAuth, requireAdmin, async (req, res) => {
await client.query('COMMIT');
invalidateSessions();
invalidateApiKeys();
await logAudit(req, 'user.update', { id, role: newRole, is_active: isActive });
await logAudit(req, 'user.update', { id, role: newRole, is_active: isActive, color });
const fresh = await pool.query(
`SELECT u.id, u.username, u.name, u.role, u.is_active, u.created_at,
`SELECT u.id, u.username, u.name, u.color, u.role, u.is_active, u.created_at,
COALESCE(array_agg(ub.branch_id) FILTER (WHERE ub.branch_id IS NOT NULL), '{}') AS branch_ids
FROM users u LEFT JOIN user_branches ub ON ub.user_id = u.id WHERE u.id = $1 GROUP BY u.id`,
[id]
@@ -4868,7 +4874,7 @@ app.get('/api/users/:id', requireAuth, async (req, res) => {
const isOwn = req.user.id === id;
if (!isOwn && req.user.role !== 'admin') return res.status(403).json({ error: 'Для просмотра чужого профиля нужны права администратора' });
const { rows } = await pool.query(
`SELECT u.id, u.username, u.name, u.email, u.phone, u.avatar, u.role, u.is_active, u.created_at,
`SELECT u.id, u.username, u.name, u.email, u.phone, u.avatar, u.color, u.role, u.is_active, u.created_at,
COALESCE(array_agg(ub.branch_id) FILTER (WHERE ub.branch_id IS NOT NULL), '{}') AS branch_ids
FROM users u LEFT JOIN user_branches ub ON ub.user_id = u.id WHERE u.id = $1 GROUP BY u.id`,
[id]
@@ -4933,7 +4939,7 @@ app.put('/api/users/:id/profile', requireAuth, async (req, res) => {
await client.query('COMMIT');
await logAudit(req, 'user.profile.update', { id });
const fresh = await pool.query(
`SELECT u.id, u.username, u.name, u.email, u.phone, u.avatar, u.role, u.is_active, u.created_at,
`SELECT u.id, u.username, u.name, u.email, u.phone, u.avatar, u.color, u.role, u.is_active, u.created_at,
COALESCE(array_agg(ub.branch_id) FILTER (WHERE ub.branch_id IS NOT NULL), '{}') AS branch_ids
FROM users u LEFT JOIN user_branches ub ON ub.user_id = u.id WHERE u.id = $1 GROUP BY u.id`,
[id]
@@ -7875,8 +7881,8 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
}
for (const x of ndata.users) {
await client.query(
'INSERT INTO users (id, username, password_hash, name, avatar, role, is_active, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)',
[x.id, x.username, x.password_hash, x.name, x.avatar, x.role, x.is_active, x.created_at]
'INSERT INTO users (id, username, password_hash, name, avatar, color, role, is_active, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)',
[x.id, x.username, x.password_hash, x.name, x.avatar, normalizeUserColor(x.color, DEFAULT_USER_COLOR), x.role, x.is_active, x.created_at]
);
}
for (const x of (ndata.user_settings || [])) {