feat(profile): personal account page with own-profile editing

Add public/profile.html + public/js/profile.js: hash-routed page with
tabs for personal data, password, AI models, prompts and branches
(admin-only), plus clickable counters for the user's own work.

Server:
- users gains email/phone/avatar (init.sql, migration.sql, ensureUserTables)
- GET /api/users/:id — self or admin, returns created_at and branch_ids
- GET /api/users/:id/stats — entries/shorts/feedbacks/lessons/groups counts
- PUT /api/users/:id/profile — name/email/phone/password, audit user.profile.update
- POST /api/users/:id/avatar — upload.single('photo'), audit user.avatar.update
- safeUser() now exposes email/phone/avatar/created_at
- users.avatar added to sweepOrphanedUploads and BROKEN_IMAGE_SOURCES
- getPersonalAiModels()/resolveUserAiProfile() for personal AI profiles;
  POST /api/shorts/ai-correct resolves them and 400s on unknown profile

Frontend:
- sidebar entry "Профиль"; .btn-secondary/.btn-xs/.muted in admin.css
- profile.js saves AI and prompt tabs as two independent PUTs
- feedback.js and shorts.js now fill model selects from
  GET /api/ai/profiles/options by role (admin sees system profiles,
  tutor sees native + own models) so the choice is actually persisted

Docs: AGENTS.md 3h updated, new section 3p.
This commit is contained in:
dev
2026-10-16 23:49:29 +03:00
parent 76cab1b97a
commit 9ae54da2e4
10 changed files with 1634 additions and 32 deletions
+144 -6
View File
@@ -1070,8 +1070,12 @@ function safeUser(u) {
id: u.id,
username: u.username,
name: u.name,
email: u.email || null,
phone: u.phone || null,
avatar: u.avatar || null,
role: u.role,
is_active: u.is_active,
created_at: u.created_at || null,
branch_ids: u.branch_ids || [],
};
}
@@ -1571,6 +1575,7 @@ async function sweepOrphanedUploads() {
pool.query('SELECT photo_path AS p FROM student_photos'),
pool.query(`SELECT value AS p FROM settings WHERE key = 'system_logo' AND value IS NOT NULL AND value <> ''`),
pool.query('SELECT photo_path AS p FROM students WHERE photo_path IS NOT NULL'),
pool.query('SELECT photo_path AS p FROM users WHERE avatar IS NOT NULL'),
pool.query('SELECT cover_path AS p FROM groups WHERE cover_path IS NOT NULL'),
pool.query('SELECT photo_original_path AS p FROM entries WHERE photo_original_path IS NOT NULL'),
pool.query('SELECT before_path AS p FROM photo_jobs WHERE before_path IS NOT NULL'),
@@ -1611,6 +1616,7 @@ const BROKEN_IMAGE_SOURCES = [
{ key: 'group_photos.photo_original_path', table: 'group_photos', column: 'photo_original_path', idColumn: 'id', kind: 'column', label: 'Оригинал фото группы' },
{ key: 'student_photos.photo_path', table: 'student_photos', column: 'photo_path', idColumn: 'id', kind: 'row', label: 'Фото ученика' },
{ key: 'students.photo_path', table: 'students', column: 'photo_path', idColumn: 'id', kind: 'column', label: 'Аватар ученика' },
{ key: 'users.avatar', table: 'users', column: 'avatar', idColumn: 'id', kind: 'column', label: 'Аватар пользователя' },
{ key: 'groups.cover_path', table: 'groups', column: 'cover_path', idColumn: 'id', kind: 'column', label: 'Обложка группы' },
{ key: 'modules.photo_path', table: 'modules', column: 'photo_path', idColumn: 'id', kind: 'column', label: 'Фото темы' },
{ key: 'bookmarks.photo_path', table: 'bookmarks', column: 'photo_path', idColumn: 'id', kind: 'column', label: 'Картинка закладки' },
@@ -2504,10 +2510,16 @@ async function ensureUserTables() {
username VARCHAR(100) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
name VARCHAR(150),
email VARCHAR(255),
phone VARCHAR(50),
avatar VARCHAR(255),
role VARCHAR(20) NOT NULL DEFAULT 'tutor' CHECK (role IN ('admin','tutor')),
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now()
)`);
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(`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,
@@ -4157,12 +4169,8 @@ app.post('/api/shorts/ai-correct', requireAuth, aiLimiter, async (req, res) => {
const text = reqStr(req.body?.text, 5000);
if (!text) return res.status(400).json({ error: 'Текст не указан' });
const profileId = req.body?.profile ? String(req.body.profile) : (req.body?.model ? String(req.body.model) : null);
let profile = null;
if (profileId && profileId !== 'native') {
const profiles = await getAiProfiles();
profile = profiles.find(p => p.id === profileId) || null;
if (!profile) return res.status(400).json({ error: 'Профиль ИИ не найден' });
}
const profile = await resolveUserAiProfile(profileId, req.user.id);
if (profileId && profileId !== 'native' && !profile) return res.status(400).json({ error: 'Профиль ИИ не найден' });
const corrected = await aiCorrectText(text, profile);
res.json({ suggestion: corrected });
} catch (e) {
@@ -4302,6 +4310,115 @@ app.put('/api/users/:id', requireAuth, requireAdmin, async (req, res) => {
}
});
// --- Own profile (any authenticated user) ---
app.get('/api/users/:id', requireAuth, async (req, res) => {
const id = Number(req.params.id);
if (!Number.isFinite(id)) return res.status(400).json({ error: 'Некорректный ID' });
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,
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]
);
if (!rows.length) return res.status(404).json({ error: 'Пользователь не найден' });
res.json(safeUser({ ...rows[0], branch_ids: rows[0].branch_ids || [] }));
});
// --- Own profile counters (own data only, not branch-scoped: a tutor sees their own work) ---
app.get('/api/users/:id/stats', requireAuth, async (req, res) => {
const id = Number(req.params.id);
if (!Number.isFinite(id)) return res.status(400).json({ error: 'Некорректный ID' });
if (req.user.id !== id && req.user.role !== 'admin') return res.status(403).json({ error: 'Для просмотра чужой статистики нужны права администратора' });
const [entries, shorts, feedbacks, lessons, groups] = await Promise.all([
pool.query(
`SELECT count(*)::int AS n FROM entries e JOIN groups g ON g.id = e.group_id
WHERE g.tutor_id = $1 AND e.deleted_at IS NULL`,
[id]
),
pool.query('SELECT count(*)::int AS n FROM short_messages WHERE author_id = $1 AND deleted_at IS NULL', [id]),
pool.query('SELECT count(*)::int AS n FROM feedbacks WHERE author_id = $1 AND deleted_at IS NULL', [id]),
pool.query('SELECT count(*)::int AS n FROM lesson_reports WHERE author_id = $1', [id]),
pool.query('SELECT count(*)::int AS n FROM groups WHERE tutor_id = $1 AND deleted_at IS NULL', [id]),
]);
res.json({
entries: entries.rows[0].n,
shorts: shorts.rows[0].n,
feedbacks: feedbacks.rows[0].n,
lessons: lessons.rows[0].n,
groups: groups.rows[0].n,
});
});
// --- Update own profile fields (name, email, phone, password) ---
app.put('/api/users/:id/profile', requireAuth, async (req, res) => {
const id = Number(req.params.id);
if (!Number.isFinite(id)) return res.status(400).json({ error: 'Некорректный ID' });
if (req.user.id !== id) return res.status(403).json({ error: 'Можно редактировать только свой профиль' });
const { rows } = await pool.query('SELECT * FROM users WHERE id = $1', [id]);
if (!rows.length) return res.status(404).json({ error: 'Пользователь не найден' });
const target = rows[0];
const name = req.body?.name !== undefined ? optStr(req.body.name, 150) : target.name;
const email = req.body?.email !== undefined ? (req.body.email === '' ? null : optStr(req.body.email, 255)) : target.email;
const phone = req.body?.phone !== undefined ? (req.body.phone === '' ? null : optStr(req.body.phone, 50)) : target.phone;
let hash = null;
if (req.body?.password) {
if (String(req.body.password).length < 6) return res.status(400).json({ error: 'Пароль должен быть не короче 6 символов' });
hash = await bcrypt.hash(String(req.body.password), 10);
}
const client = await pool.connect();
try {
await client.query('BEGIN');
if (hash) await client.query('UPDATE users SET password_hash = $1 WHERE id = $2', [hash, id]);
await client.query('UPDATE users SET name = $1, email = $2, phone = $3 WHERE id = $4', [name, email, phone, id]);
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,
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]
);
res.json(safeUser({ ...fresh.rows[0], branch_ids: fresh.rows[0].branch_ids || [] }));
} catch (e) {
await client.query('ROLLBACK').catch(() => {});
throw e;
} finally {
client.release();
}
});
const avatarUpload = upload.single('photo');
app.post('/api/users/:id/avatar', requireAuth, avatarUpload, async (req, res) => {
const id = Number(req.params.id);
if (!Number.isFinite(id)) return res.status(400).json({ error: 'Некорректный ID' });
if (req.user.id !== id) return res.status(403).json({ error: 'Можно загружать аватар только для своего профиля' });
if (!req.file) return res.status(400).json({ error: 'Файл обязателен' });
try {
await convertPhoto(req.file);
const photoPath = '/uploads/' + req.file.filename;
const { rows } = await pool.query(
'UPDATE users SET avatar = $1 WHERE id = $2 RETURNING id, avatar',
[photoPath, id]
);
if (!rows.length) {
removeUpload(req.file);
return res.status(404).json({ error: 'Пользователь не найден' });
}
await logAudit(req, 'user.avatar.update', { id, avatar: photoPath });
invalidateSessions();
res.json({ id, avatar: photoPath });
} catch (e) {
removeUpload(req.file);
console.error('POST /api/users/:id/avatar:', e);
res.status(500).json({ error: 'Не удалось загрузить аватар' });
}
});
// --- Notes (per-user, private) ---
const NOTE_TITLE_MAX = 200;
const NOTE_TEXT_MAX = 100000;
@@ -5461,6 +5578,27 @@ async function getActiveAiProfile() {
return profiles.find(p => p.id === active) || null;
}
async function getPersonalAiModels(userId) {
if (!userId) return [];
try {
const { rows } = await pool.query(`SELECT value FROM user_settings WHERE user_id = $1 AND key = 'feedback_models'`, [userId]);
const raw = rows[0] && rows[0].value;
if (!raw) return [];
const list = JSON.parse(raw);
return Array.isArray(list) ? list.filter(m => m && m.id && m.base_url && m.model) : [];
} catch (e) {
return [];
}
}
async function resolveUserAiProfile(profileId, userId) {
const id = profileId ? String(profileId) : '';
if (!id || id === 'native') return null;
const own = (await getPersonalAiModels(userId)).find(m => String(m.id) === id);
if (own) return own;
return (await getAiProfiles()).find(p => String(p.id) === id) || null;
}
function normalizeOpenAiBase(base) {
let b = String(base || '').trim().replace(/\/+$/, '');
if (!/^https?:\/\//i.test(b)) return null;