Пользователи: цвет при создании и редактировании
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
const { normalizeStudentStatus } = require('./lib/students');
|
||||
const { normalizeUserColor } = require('./lib/users');
|
||||
const PHOTO_JOB_ACTIONS = new Set(['ai', 'ai_face', 'ai_upscale', 'enhance', 'restore', 'rollback']);
|
||||
const LESSON_REPORT_TEXT_MAX = 5000;
|
||||
const LESSON_REPORT_TOPIC_MAX = 300;
|
||||
@@ -369,6 +370,7 @@ function normalizeRestoreData(data) {
|
||||
password_hash: reqStr(x.password_hash, 255),
|
||||
name: optStr(x.name, 150),
|
||||
avatar: optUploadPath(x.avatar, 255),
|
||||
color: normalizeUserColor(x.color),
|
||||
role: (x.role === 'admin' || x.role === 'tutor') ? x.role : 'tutor',
|
||||
is_active: !!x.is_active,
|
||||
created_at: optTs(x.created_at),
|
||||
|
||||
@@ -79,6 +79,17 @@ const userAvatar = normalizeRestoreData({
|
||||
});
|
||||
ok('users.avatar сохраняется', userAvatar.users[0].avatar === '/uploads/avatar.jpg', userAvatar.users[0]);
|
||||
|
||||
const userColor = normalizeRestoreData({
|
||||
...base,
|
||||
users: [{ id: 1, username: 'u', password_hash: 'h', color: '#ff5733' }],
|
||||
});
|
||||
ok('users.color сохраняется', userColor.users[0].color === '#ff5733', userColor.users[0]);
|
||||
const badUserColor = normalizeRestoreData({
|
||||
...base,
|
||||
users: [{ id: 1, username: 'u', password_hash: 'h', color: 'red' }],
|
||||
});
|
||||
ok('users.color невалидный заменяется дефолтом', badUserColor.users[0].color === '#2563eb', badUserColor.users[0]);
|
||||
|
||||
const prompts = normalizeRestoreData({
|
||||
...base,
|
||||
user_settings: [{ user_id: 1, key: 'feedback_prompts', value: 'x'.repeat(20000) }],
|
||||
|
||||
@@ -217,6 +217,7 @@ CREATE TABLE IF NOT EXISTS users (
|
||||
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()
|
||||
|
||||
@@ -172,6 +172,7 @@ CREATE TABLE IF NOT EXISTS users (
|
||||
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()
|
||||
@@ -179,6 +180,7 @@ CREATE TABLE IF NOT EXISTS users (
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS email VARCHAR(255);
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS phone VARCHAR(50);
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS avatar VARCHAR(255);
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS color VARCHAR(7) NOT NULL DEFAULT '#2563eb';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_branches (
|
||||
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
const DEFAULT_USER_COLOR = '#2563eb';
|
||||
const USER_COLORS = ['#2563eb', '#7c3aed', '#db2777', '#dc2626', '#ea580c', '#d97706', '#16a34a', '#0d9488', '#0891b2', '#4f46e5', '#9333ea', '#475569'];
|
||||
|
||||
function normalizeUserColor(value, fallback) {
|
||||
const raw = String(value === undefined || value === null ? '' : value).trim();
|
||||
if (/^#[0-9a-fA-F]{6}$/.test(raw)) return raw.toLowerCase();
|
||||
const base = String(fallback === undefined || fallback === null ? '' : fallback).trim();
|
||||
if (/^#[0-9a-fA-F]{6}$/.test(base)) return base.toLowerCase();
|
||||
return DEFAULT_USER_COLOR;
|
||||
}
|
||||
|
||||
function randomUserColor() {
|
||||
return USER_COLORS[Math.floor(Math.random() * USER_COLORS.length)];
|
||||
}
|
||||
|
||||
module.exports = { DEFAULT_USER_COLOR, USER_COLORS, normalizeUserColor, randomUserColor };
|
||||
+18
-1
@@ -5,6 +5,9 @@ async function init() {
|
||||
document.getElementById('addUserBtn').addEventListener('click', () => openModal(null));
|
||||
document.getElementById('uCancel').addEventListener('click', closeModal);
|
||||
document.getElementById('uSave').addEventListener('click', saveUser);
|
||||
document.getElementById('uColorRandom').addEventListener('click', () => {
|
||||
document.getElementById('uColor').value = randomUserColor();
|
||||
});
|
||||
document.getElementById('uRole').addEventListener('change', () => {
|
||||
document.getElementById('uBranchesField').style.display = document.getElementById('uRole').value === 'admin' ? 'none' : '';
|
||||
});
|
||||
@@ -13,6 +16,16 @@ async function init() {
|
||||
|
||||
let branches = [];
|
||||
let editingId = null;
|
||||
const USER_COLORS = ['#2563eb', '#7c3aed', '#db2777', '#dc2626', '#ea580c', '#d97706', '#16a34a', '#0d9488', '#0891b2', '#4f46e5', '#9333ea', '#475569'];
|
||||
|
||||
function userColor(value) {
|
||||
const raw = String(value || '').trim();
|
||||
return /^#[0-9a-fA-F]{6}$/.test(raw) ? raw.toLowerCase() : USER_COLORS[0];
|
||||
}
|
||||
|
||||
function randomUserColor() {
|
||||
return USER_COLORS[Math.floor(Math.random() * USER_COLORS.length)];
|
||||
}
|
||||
|
||||
async function loadUsers() {
|
||||
const [uRes, bRes] = await Promise.all([
|
||||
@@ -37,11 +50,13 @@ function renderUsers(users) {
|
||||
const roleCls = u.role === 'admin' ? 'badge-admin' : 'badge-tutor';
|
||||
const roleTxt = u.role === 'admin' ? 'Администратор' : 'Тутор';
|
||||
const status = u.is_active ? '<span class="status-ok">Активен</span>' : '<span class="status-off">Заблокирован</span>';
|
||||
const color = userColor(u.color);
|
||||
const delBtn = u.id === currentUser.id
|
||||
? ''
|
||||
: `<button class="row-btn del" data-del="${u.id}" title="Удалить">×</button>`;
|
||||
tr.innerHTML = `
|
||||
<td>${u.id}</td>
|
||||
<td><span class="user-color-swatch" style="background:${color}" title="${color}"></span></td>
|
||||
<td>${esc(u.username)}</td>
|
||||
<td>${esc(u.name || '')}</td>
|
||||
<td><span class="${roleCls}">${roleTxt}</span></td>
|
||||
@@ -66,6 +81,7 @@ function openModal(user) {
|
||||
document.getElementById('userModalTitle').textContent = user ? `Пользователь: ${user.username}` : 'Новый пользователь';
|
||||
document.getElementById('uUsername').value = user ? user.username : '';
|
||||
document.getElementById('uName').value = user ? (user.name || '') : '';
|
||||
document.getElementById('uColor').value = user ? userColor(user.color) : randomUserColor();
|
||||
document.getElementById('uRole').value = user ? user.role : 'tutor';
|
||||
document.getElementById('uPassword').value = '';
|
||||
document.getElementById('uActive').checked = user ? user.is_active : true;
|
||||
@@ -92,13 +108,14 @@ async function saveUser() {
|
||||
const username = document.getElementById('uUsername').value.trim();
|
||||
const name = document.getElementById('uName').value.trim() || null;
|
||||
const role = document.getElementById('uRole').value;
|
||||
const color = userColor(document.getElementById('uColor').value);
|
||||
const password = document.getElementById('uPassword').value;
|
||||
const is_active = document.getElementById('uActive').checked;
|
||||
const branchSel = document.getElementById('uBranches');
|
||||
const branch_ids = role === 'admin' ? [] : [...branchSel.selectedOptions].map(o => Number(o.value));
|
||||
if (!username) { showToast('Укажите логин'); return; }
|
||||
if (!editingId && password.length < 6) { showToast('Пароль должен быть не короче 6 символов'); return; }
|
||||
const payload = { username, name, role, is_active, branch_ids };
|
||||
const payload = { username, name, role, is_active, branch_ids, color };
|
||||
if (password) payload.password = password;
|
||||
const res = await fetch(editingId ? `${API}/api/users/${editingId}` : `${API}/api/users`, {
|
||||
method: editingId ? 'PUT' : 'POST',
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Цвет</th>
|
||||
<th>Логин</th>
|
||||
<th>Имя</th>
|
||||
<th>Роль</th>
|
||||
@@ -53,6 +54,13 @@
|
||||
<label>Имя</label>
|
||||
<input type="text" id="uName" class="settings-input" placeholder="Имя Фамилия">
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label>Цвет</label>
|
||||
<div style="display:flex;align-items:center;gap:8px">
|
||||
<input type="color" id="uColor" class="settings-input user-color-input" value="#2563eb">
|
||||
<button type="button" class="btn-primary ghost" id="uColorRandom" style="padding:6px 10px">Случайный</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label>Роль</label>
|
||||
<select id="uRole" class="settings-input">
|
||||
@@ -96,6 +104,8 @@
|
||||
.row-btn:hover{background:var(--bg);color:var(--accent)}
|
||||
.row-btn.del:hover{color:#ef4444;background:rgba(239,68,68,.1)}
|
||||
.user-branches{max-width:220px;color:var(--muted);font-size:.78rem}
|
||||
.user-color-input{width:72px;height:34px;padding:2px;cursor:pointer}
|
||||
.user-color-swatch{display:inline-block;width:18px;height:18px;border-radius:50%;border:1px solid rgba(127,127,127,.4);vertical-align:middle}
|
||||
</style>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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 || [])) {
|
||||
|
||||
Reference in New Issue
Block a user