Files

1049 lines
41 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(async () => {
if (!(await checkAuth())) return;
buildSidebar('profile');
const API = location.origin;
const userId = currentUser?.id;
const PROMPT_LIMIT = 15000;
const MODELS_LIMIT = 10;
function escapeHtml(s) { return String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#039;'); }
const els = {
name: document.getElementById('pfName'),
email: document.getElementById('pfEmail'),
phone: document.getElementById('pfPhone'),
nameErr: document.getElementById('pfNameErr'),
emailErr: document.getElementById('pfEmailErr'),
phoneErr: document.getElementById('pfPhoneErr'),
oldPassword: document.getElementById('pfOldPassword'),
newPassword: document.getElementById('pfNewPassword'),
newPasswordConfirm: document.getElementById('pfNewPasswordConfirm'),
oldPasswordErr: document.getElementById('pfOldPasswordErr'),
newPasswordErr: document.getElementById('pfNewPasswordErr'),
newPasswordConfirmErr: document.getElementById('pfNewPasswordConfirmErr'),
passwordFields: document.getElementById('passwordFields'),
togglePassword: document.getElementById('togglePassword'),
btnSave: document.getElementById('btnSave'),
btnCancel: document.getElementById('btnCancel'),
btnLogout: document.getElementById('btnLogout'),
avatar: document.getElementById('profileAvatar'),
avatarImg: null,
avatarEmpty: document.getElementById('avatarEmpty'),
avatarFile: document.getElementById('avatarFile'),
imgModal: document.getElementById('imgModal'),
imgModalSrc: document.getElementById('imgModalSrc'),
nameDisplay: document.getElementById('profileName'),
meta: document.getElementById('profileMeta'),
badges: document.getElementById('profileBadges'),
actions: document.getElementById('profileActions'),
stats: document.getElementById('profileStats'),
branchesCard: document.getElementById('pfBranchesTab'),
branchesCount: document.getElementById('pfBranchesCount'),
branchesList: document.getElementById('pfBranchesList'),
formActions: document.getElementById('profileFormActions'),
modelSelect: document.getElementById('pfDefaultModel'),
modelsList: document.getElementById('pfModelsList'),
modelsCount: document.getElementById('pfModelsCount'),
modelEdit: document.getElementById('pfModelEdit'),
modelFormTitle: document.getElementById('pfModelFormTitle'),
modelAdd: document.getElementById('pfModelAdd'),
modelCancel: document.getElementById('pfMCancel'),
modelSave: document.getElementById('pfMSave'),
modelTest: document.getElementById('pfMTest'),
modelTestStatus: document.getElementById('pfMTestStatus'),
mName: document.getElementById('pfMName'),
mModel: document.getElementById('pfMModel'),
mUrl: document.getElementById('pfMUrl'),
mKey: document.getElementById('pfMKey'),
mKeyToggle: document.getElementById('pfMKeyToggle'),
mMaxTok: document.getElementById('pfMMaxTok'),
mNameErr: document.getElementById('pfMNameErr'),
mModelErr: document.getElementById('pfMModelErr'),
mUrlErr: document.getElementById('pfMUrlErr'),
mMaxTokErr: document.getElementById('pfMMaxTokErr'),
aiStatus: document.getElementById('pfAiStatus'),
aiSave: document.getElementById('pfAiSave'),
aiReset: document.getElementById('pfAiReset'),
aiSaveHint: document.getElementById('pfAiSaveHint'),
promptTpl: document.getElementById('pfPromptTpl'),
promptTplName: document.getElementById('pfPromptTplName'),
promptTplAdd: document.getElementById('pfPromptTplAdd'),
promptTplDel: document.getElementById('pfPromptTplDel'),
promptTplCount: document.getElementById('pfPromptTplCount'),
promptText: document.getElementById('pfPromptText'),
promptCount: document.getElementById('pfPromptCount'),
promptReset: document.getElementById('pfPromptReset'),
promptSave: document.getElementById('pfPromptSave'),
promptStatus: document.getElementById('pfPromptStatus'),
promptSaveHint: document.getElementById('pfPromptSaveHint'),
promptKeys: document.getElementById('pfPromptKeys'),
promptDefault: document.getElementById('pfPromptDefaultText'),
promptUseDefault: document.getElementById('pfPromptUseDefault'),
};
const tabButtons = Array.from(document.querySelectorAll('.sp-tab'));
const tabPanels = Array.from(document.querySelectorAll('[id^="tab-"]'));
const dirty = { general: false, ai: false, prompts: false };
let isPasswordVisible = false;
let avatarFile = null;
let myModels = [];
let modelEditIdx = null;
let promptTpls = null;
let userSettings = { settings: {}, defaults: {} };
let settingsLoaded = false;
let aiLoaded = false;
let modelOptionsLoaded = false;
let activeTab = 'general';
let aiBaseline = '';
let promptsBaseline = '';
let generalBaseline = '';
function clearErrors() {
for (const k of Object.keys(els)) {
if (k.endsWith('Err') && els[k]) els[k].textContent = '';
}
}
function showError(key, msg) {
if (els[key]) els[key].textContent = msg;
}
function setLoading(btn, loading) {
if (!btn) return;
btn.disabled = loading;
btn.textContent = loading ? 'Сохранение...' : 'Сохранить';
}
function setStatus(el, ok, msg) {
if (!el) return;
el.hidden = false;
el.innerHTML = `<span class="ai-badge ai-badge-${ok ? 'done' : 'error'}">${escapeHtml(msg)}</span>`;
if (ok) setTimeout(() => { el.hidden = true; el.innerHTML = ''; }, 2500);
}
function clearStatus(el) {
if (!el) return;
el.hidden = true;
el.innerHTML = '';
}
function setIcon(el, name) {
if (!el) return;
const icon = (el.matches && el.matches('[data-lucide]')) ? el : el.querySelector('[data-lucide]');
if (!icon) return;
const fresh = document.createElement('i');
fresh.setAttribute('data-lucide', name);
icon.replaceWith(fresh);
renderIcons();
}
function initials(name, username) {
const n = (name || username || '').trim();
if (!n) return '?';
const parts = n.split(/\s+/).filter(Boolean);
if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();
return n[0].toUpperCase();
}
function renderMeta(user) {
const meta = [];
if (user.username) meta.push({ icon: 'at-sign', text: user.username });
if (user.email) meta.push({ icon: 'mail', text: user.email });
if (user.phone) meta.push({ icon: 'phone', text: user.phone });
if (user.created_at) meta.push({ icon: 'calendar', text: `в системе с ${fmtDateFull(user.created_at)}` });
els.meta.innerHTML = meta.map(m =>
`<span class="sp-meta-span"><i data-lucide="${m.icon}"></i><b>${esc(m.text)}</b></span>`
).join('');
renderIcons();
}
function renderBadges(user) {
els.badges.innerHTML = '';
const roleChip = document.createElement('span');
roleChip.className = 'sp-chip accent';
roleChip.innerHTML = '<i data-lucide="' + (user.role === 'admin' ? 'shield-check' : 'user') + '"></i>' + esc(user.role === 'admin' ? 'Администратор' : 'Тутор');
els.badges.appendChild(roleChip);
if (user.branch_ids && user.branch_ids.length) {
const bChip = document.createElement('span');
bChip.className = 'sp-chip';
bChip.innerHTML = '<i data-lucide="building-2"></i>' + esc(user.branch_ids.length + ' филиал' + (user.branch_ids.length === 1 ? 'й' : 'ев'));
els.badges.appendChild(bChip);
}
const statusChip = document.createElement('span');
statusChip.className = 'sp-chip ' + (user.is_active ? 'accent' : '');
statusChip.innerHTML = '<i data-lucide="' + (user.is_active ? 'check-circle-2' : 'ban') + '"></i>' + esc(user.is_active ? 'Активно' : 'Заблокировано');
els.badges.appendChild(statusChip);
renderIcons();
}
function renderStats(stats) {
els.stats.innerHTML = '';
const s = stats || {};
const card = (ic, value, label, href) => {
const el = document.createElement('button');
el.type = 'button';
el.className = 'sp-stat';
el.innerHTML = '<div class="sp-stat-ic"><i data-lucide="' + ic + '"></i></div><div class="sp-stat-num">' + esc(value) + '</div><div class="sp-stat-label">' + esc(label) + '</div>';
if (href) {
el.addEventListener('click', () => { location.href = href; });
el.title = label;
} else {
el.disabled = true;
}
return el;
};
els.stats.appendChild(card('book-open', s.entries || 0, 'Записей в журнале', 'journal.html'));
els.stats.appendChild(card('zap', s.shorts || 0, 'Коротких сообщений', 'shorts.html'));
els.stats.appendChild(card('message-square-heart', s.feedbacks || 0, 'Отзывов', 'feedback.html'));
els.stats.appendChild(card('notebook-pen', s.lessons || 0, 'Отчётов о занятиях', 'lessons.html'));
els.stats.appendChild(card('users', s.groups || 0, 'Групп', 'groups.html'));
renderIcons();
}
async function loadStats() {
if (!userId) return;
try {
const res = await fetch(`${API}/api/users/${userId}/stats`, { headers: hdr() });
if (res.status === 401) { cleanupSession(); return; }
if (!res.ok) return;
renderStats(await res.json());
} catch (e) {}
}
function renderBranches(branchIds) {
if (!userId || currentUser.role !== 'admin') return;
els.branchesCard.hidden = false;
els.branchesList.innerHTML = '';
if (!branchIds || !branchIds.length) {
els.branchesCount.textContent = '';
els.branchesList.innerHTML = '<span class="sp-hint">Не назначены</span>';
return;
}
els.branchesCount.textContent = branchIds.length ? `${branchIds.length}` : '';
els.branchesCount.hidden = !branchIds.length;
fetch(`${API}/api/users/branches`, { headers: hdr() })
.then(r => r.ok ? r.json() : [])
.then(branches => {
const byId = {};
for (const b of branches) byId[b.id] = b.name || ('Филиал #' + b.id);
for (const id of branchIds) {
const tag = document.createElement('span');
tag.className = 'sp-chip';
tag.innerHTML = '<i data-lucide="building-2"></i><b>' + esc(byId[id] || ('Филиал #' + id)) + '</b>';
els.branchesList.appendChild(tag);
}
renderIcons();
});
}
function fillForm(user) {
els.name.value = user.name || '';
els.email.value = user.email || '';
els.phone.value = user.phone || '';
els.nameDisplay.textContent = user.name || user.username || '—';
renderMeta(user);
renderBadges(user);
renderBranches(user.branch_ids);
const avatar = user.avatar;
if (avatar) {
const img = document.createElement('img');
img.src = thumbSrc(avatar);
img.alt = 'Аватар';
img.dataset.full = avatar;
els.avatar.insertBefore(img, els.avatarEmpty);
els.avatarImg = img;
els.avatarEmpty.style.display = 'none';
} else {
els.avatarEmpty.textContent = initials(user.name, user.username);
els.avatarEmpty.style.display = '';
if (els.avatarImg) { els.avatarImg.remove(); els.avatarImg = null; }
}
if (currentUser.role !== 'admin') els.branchesCard.hidden = true;
generalBaseline = generalSnapshot();
setDirty('general', false);
}
function generalSnapshot() {
return JSON.stringify({
name: els.name.value.trim(),
email: els.email.value.trim(),
phone: els.phone.value.trim(),
password: isPasswordVisible ? [els.oldPassword.value, els.newPassword.value, els.newPasswordConfirm.value] : [],
});
}
function collectForm() {
const data = {};
const name = els.name.value.trim();
const email = els.email.value.trim();
const phone = els.phone.value.trim();
if (name !== '') data.name = name;
if (email !== '') data.email = email;
else data.email = null;
if (phone !== '') data.phone = phone;
else data.phone = null;
if (isPasswordVisible) {
data.password = els.newPassword.value;
data.oldPassword = els.oldPassword.value;
data.confirm = els.newPasswordConfirm.value;
}
return data;
}
function validateForm(data) {
clearErrors();
let ok = true;
if (data.name !== undefined && data.name.length > 150) {
showError('nameErr', 'Имя не может быть длиннее 150 символов'); ok = false;
}
if (data.email !== undefined && data.email !== null && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
showError('emailErr', 'Некорректный email'); ok = false;
}
if (data.phone !== undefined && data.phone !== null && data.phone.length > 50) {
showError('phoneErr', 'Телефон не может быть длиннее 50 символов'); ok = false;
}
if (isPasswordVisible) {
if (!data.oldPassword) {
showError('oldPasswordErr', 'Введите текущий пароль'); ok = false;
}
if (!data.password || data.password.length < 6) {
showError('newPasswordErr', 'Новый пароль не короче 6 символов'); ok = false;
}
if (data.password !== data.confirm) {
showError('newPasswordConfirmErr', 'Пароли не совпадают'); ok = false;
}
}
return ok;
}
async function loadProfile() {
if (!userId) return;
try {
const res = await fetch(`${API}/api/users/${userId}`, { headers: hdr() });
if (res.status === 401) { cleanupSession(); return; }
if (!res.ok) throw new Error('Не удалось загрузить профиль');
const user = await res.json();
fillForm(user);
} catch (e) {
showToast(e.message || 'Ошибка загрузки профиля', true);
}
}
async function saveProfile() {
const data = collectForm();
if (!validateForm(data)) return;
const body = {};
if (data.name !== undefined) body.name = data.name;
if (data.email !== undefined) body.email = data.email;
if (data.phone !== undefined) body.phone = data.phone;
if (data.password) {
body.password = data.password;
body.old_password = data.oldPassword;
}
setLoading(els.btnSave, true);
clearErrors();
try {
const res = await fetch(`${API}/api/users/${userId}/profile`, {
method: 'PUT',
headers: hdrJson(),
body: JSON.stringify(body),
});
if (res.status === 401) { cleanupSession(); return; }
const json = await res.json();
if (!res.ok) throw new Error(json.error || 'Не удалось сохранить');
showToast('Профиль обновлён');
setDirty('general', false);
await loadProfile();
} catch (e) {
showToast(e.message || 'Ошибка сохранения', true);
} finally {
setLoading(els.btnSave, false);
}
}
async function loadUserSettings() {
try {
const r = await fetch(`${API}/api/user-settings`, { headers: hdr() });
if (!r.ok) return;
const j = await r.json();
userSettings.settings = j.settings || {};
userSettings.defaults = j.defaults || {};
parseMyModels();
} catch (e) {}
}
function parseMyModels() {
try { myModels = JSON.parse(userSettings.settings.feedback_models || '[]'); } catch (e) { myModels = []; }
if (!Array.isArray(myModels)) myModels = [];
}
async function ensureSettings() {
if (settingsLoaded) return;
await loadUserSettings();
settingsLoaded = true;
}
async function loadAiTab() {
const firstLoad = !aiLoaded;
await ensureSettings();
if (firstLoad && els.modelSelect && !els.modelSelect.value && userSettings.settings.feedback_profile) {
els.modelSelect.value = userSettings.settings.feedback_profile;
}
await refreshModelSelects();
renderModelsList();
aiLoaded = true;
aiBaseline = aiSnapshot();
setDirty('ai', false);
}
async function loadPromptsTab() {
await ensureSettings();
if (promptTpls === null) {
promptTpls = parsePromptTemplates();
renderPromptTemplates();
promptsBaseline = promptsSnapshot();
setDirty('prompts', false);
}
renderDefaultPrompt();
}
function renderDefaultPrompt() {
if (els.promptDefault) els.promptDefault.textContent = userSettings.defaults.feedback_prompt || 'Системный шаблон недоступен';
}
function aiSnapshot() {
return JSON.stringify({ profile: els.modelSelect ? els.modelSelect.value : '', models: myModels });
}
function promptsSnapshot() {
return JSON.stringify(promptTpls);
}
function setDirty(tab, value) {
dirty[tab] = !!value;
const btn = tabButtons.find(b => b.dataset.tab === tab);
if (btn) btn.classList.toggle('dirty', !!value);
if (tab === 'ai' && els.aiSaveHint) {
els.aiSaveHint.textContent = dirty.ai ? 'Есть несохранённые изменения' : 'Все изменения сохранены';
els.aiSaveHint.classList.toggle('warn', dirty.ai);
}
if (tab === 'prompts' && els.promptSaveHint) {
els.promptSaveHint.textContent = dirty.prompts ? 'Есть несохранённые изменения' : 'Все изменения сохранены';
els.promptSaveHint.classList.toggle('warn', dirty.prompts);
}
}
function hasUnsaved() {
return dirty.general || dirty.ai || dirty.prompts;
}
function renderModelsList() {
if (!els.modelsList) return;
if (els.modelsCount) els.modelsCount.textContent = myModels.length ? `${myModels.length} / ${MODELS_LIMIT}` : `0 / ${MODELS_LIMIT}`;
if (!myModels.length) {
els.modelsList.innerHTML = '<div class="sp-model-empty"><i data-lucide="cpu"></i><span>Своих моделей нет — используются системные</span></div>';
renderIcons();
return;
}
const cur = els.modelSelect ? els.modelSelect.value : '';
els.modelsList.innerHTML = myModels.map((m, i) => `
<div class="sp-model-row${cur === m.id ? ' is-default' : ''}">
<div class="sp-model-info">
<span class="sp-model-name">${escapeHtml(m.name)}${cur === m.id ? '<span class="sp-count">по умолчанию</span>' : ''}</span>
<span class="sp-model-sub">${escapeHtml(m.model)}</span>
<span class="sp-model-sub">${escapeHtml(m.base_url || '')}</span>
<span class="ai-test-status" data-mstat="${i}"></span>
</div>
<div class="sp-model-acts">
${cur === m.id ? '' : `<button type="button" class="btn-xs" data-mdefault="${i}" title="Сделать моделью по умолчанию"><i data-lucide="star"></i>По умолчанию</button>`}
<button type="button" class="btn-xs" data-mcheck="${i}" title="Проверить подключение"><i data-lucide="plug-zap"></i>Проверить</button>
<button type="button" class="btn-xs" data-medit="${i}"><i data-lucide="pencil"></i>Изменить</button>
<button type="button" class="btn-xs danger" data-mdel="${i}"><i data-lucide="trash-2"></i>Удалить</button>
</div>
</div>`).join('');
renderIcons();
}
async function checkModel(model, statusEl, btn) {
if (!model || !statusEl) return;
const label = btn ? btn.innerHTML : '';
if (btn) { btn.disabled = true; btn.innerHTML = '<i data-lucide="plug-zap"></i>Проверка…'; renderIcons(); }
statusEl.textContent = 'Проверка…';
let html;
try {
const r = await fetch(`${API}/api/user-settings/models/test`, {
method: 'POST',
headers: { ...hdr(), 'Content-Type': 'application/json' },
body: JSON.stringify({ model })
});
const d = await r.json().catch(() => ({}));
html = d.ok
? `<span class="ok">✓ Работает (${escapeHtml(d.latency_ms)} мс)${d.sample ? ` — «${escapeHtml(d.sample)}»` : ''}</span>`
: `<span class="fail">✗ ${escapeHtml(d.error || 'Не удалось подключиться')}</span>`;
} catch (e) {
html = `<span class="fail">✗ ${escapeHtml(e.message || 'Сеть недоступна')}</span>`;
}
if (statusEl.isConnected) statusEl.innerHTML = html;
if (btn && btn.isConnected) { btn.disabled = false; btn.innerHTML = label; renderIcons(); }
}
function clearModelErrors() {
for (const e of [els.mNameErr, els.mModelErr, els.mUrlErr, els.mMaxTokErr]) if (e) e.textContent = '';
for (const i of [els.mName, els.mModel, els.mUrl, els.mMaxTok]) if (i) i.classList.remove('invalid');
}
function modelError(input, errEl, msg) {
if (input) input.classList.add('invalid');
if (errEl) errEl.textContent = msg;
}
function showModelForm(idx) {
modelEditIdx = idx;
const m = idx == null ? null : myModels[idx];
clearModelErrors();
els.mName.value = m ? m.name : '';
els.mModel.value = m ? m.model : '';
els.mUrl.value = m ? m.base_url : '';
els.mKey.value = m ? (m.api_key || '') : '';
els.mMaxTok.value = m && m.max_tokens ? m.max_tokens : '';
els.mKey.type = 'password';
setIcon(els.mKeyToggle, 'eye');
if (els.modelFormTitle) els.modelFormTitle.textContent = m ? 'Изменение модели' : 'Новая модель';
els.modelEdit.hidden = false;
els.modelEdit.scrollIntoView({ block: 'nearest' });
els.mName.focus();
}
function hideModelForm() {
els.modelEdit.hidden = true;
clearModelErrors();
modelEditIdx = null;
}
function saveModelForm() {
clearModelErrors();
const name = els.mName.value.trim();
const model = els.mModel.value.trim();
const base = els.mUrl.value.trim().replace(/\/+$/, '');
const key = els.mKey.value.trim();
const tok = els.mMaxTok.value.trim();
let maxTokens = null;
let firstBad = null;
if (!name) { modelError(els.mName, els.mNameErr, 'Укажите название модели'); firstBad = firstBad || els.mName; }
if (!model) { modelError(els.mModel, els.mModelErr, 'Укажите имя модели'); firstBad = firstBad || els.mModel; }
if (base) {
try {
const u = new URL(base);
if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new Error('bad');
} catch (e) {
modelError(els.mUrl, els.mUrlErr, 'Base URL должен начинаться с http:// или https://');
firstBad = firstBad || els.mUrl;
}
} else {
modelError(els.mUrl, els.mUrlErr, 'Укажите адрес подключения');
firstBad = firstBad || els.mUrl;
}
if (tok) {
maxTokens = parseInt(tok, 10);
if (!Number.isFinite(maxTokens) || maxTokens < 16 || maxTokens > 131072) {
modelError(els.mMaxTok, els.mMaxTokErr, 'Допустимо 16–131072');
firstBad = firstBad || els.mMaxTok;
}
}
if (modelEditIdx == null && myModels.length >= MODELS_LIMIT) {
modelError(els.mName, els.mNameErr, `Не больше ${MODELS_LIMIT} моделей`);
firstBad = firstBad || els.mName;
}
if (firstBad) { firstBad.focus(); return; }
const entry = {
id: modelEditIdx == null ? `me-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}` : myModels[modelEditIdx].id,
name, model, base_url: base, api_key: key, max_tokens: maxTokens
};
if (modelEditIdx == null) myModels.push(entry); else myModels[modelEditIdx] = entry;
hideModelForm();
renderModelsList();
setDirty('ai', true);
}
function deleteModel(i) {
const m = myModels[i];
if (!m) return;
if (!confirm(`Удалить модель «${escapeHtml(m.name)}»?`)) return;
myModels.splice(i, 1);
if (els.modelSelect && els.modelSelect.value === m.id) els.modelSelect.value = '';
renderModelsList();
setDirty('ai', true);
}
function makeDefaultModel(i) {
const m = myModels[i];
if (!m || !els.modelSelect) return;
els.modelSelect.value = m.id;
if (els.modelSelect.value !== m.id) return;
renderModelsList();
setDirty('ai', true);
}
async function refreshModelSelects() {
const dst = els.modelSelect;
if (!dst) return;
const keep = dst.value;
await loadAiProfiles();
if (keep && dst.value !== keep) {
const o = document.createElement('option');
o.value = keep;
o.textContent = `${keep} (недоступна)`;
dst.appendChild(o);
dst.value = keep;
}
}
async function loadAiProfiles() {
const dst = els.modelSelect;
if (!dst) return;
try {
const r = await fetch(`${API}/api/ai/profiles/options`, { headers: hdr() });
if (!r.ok) return;
const d = await r.json();
const keep = dst.value;
dst.innerHTML = '<option value="">Активная модель системы</option>';
if (myModels.length) {
const mine = document.createElement('optgroup');
mine.label = 'Мои модели';
myModels.forEach(m => {
const o = document.createElement('option');
o.value = m.id;
o.textContent = m.name;
mine.appendChild(o);
});
dst.appendChild(mine);
}
const sys = document.createElement('optgroup');
sys.label = 'Системные';
const nativeOpt = document.createElement('option');
nativeOpt.value = 'native';
nativeOpt.textContent = d.native && d.native.name ? d.native.name : 'Нативная (llama.cpp)';
sys.appendChild(nativeOpt);
(d.profiles || []).forEach(p => {
const o = document.createElement('option');
o.value = p.id;
o.textContent = p.name;
sys.appendChild(o);
});
dst.appendChild(sys);
dst.value = keep && [...dst.options].some(o => o.value === keep) ? keep : '';
modelOptionsLoaded = true;
} catch (e) {}
}
function updatePromptCount() {
const el = els.promptCount;
const ta = els.promptText;
if (!el || !ta) return;
el.textContent = `${ta.value.length} / ${PROMPT_LIMIT}`;
el.classList.toggle('warn', ta.value.length > PROMPT_LIMIT * 0.9);
}
function parsePromptTemplates() {
let data = null;
try { data = JSON.parse(userSettings.settings.feedback_prompts || ''); } catch (e) {}
let items = data && Array.isArray(data.items) ? data.items : [];
items = items
.filter(t => t && typeof t === 'object' && String(t.id || '').trim())
.map(t => ({ id: String(t.id).trim(), name: String(t.name || '').trim() || 'Шаблон', text: String(t.text || '').slice(0, PROMPT_LIMIT) }));
if (!items.length) items = [{ id: 'tpl-legacy', name: 'Шаблон', text: userSettings.settings.feedback_prompt || '' }];
let active = data ? String(data.active || '').trim() : '';
if (!items.some(t => t.id === active)) active = items[0].id;
return { active, items };
}
function renderPromptTemplates() {
const sel = els.promptTpl;
if (!sel || !promptTpls) return;
const name = els.promptTplName;
const del = els.promptTplDel;
const ta = els.promptText;
sel.innerHTML = promptTpls.items.map(t => `<option value="${escapeHtml(t.id)}">${escapeHtml(t.name)}</option>`).join('');
sel.value = promptTpls.active;
const act = promptTpls.items.find(t => t.id === promptTpls.active);
if (name) name.value = act ? act.name : '';
if (del) del.disabled = promptTpls.items.length <= 1;
if (els.promptTplCount) els.promptTplCount.textContent = `Шаблонов: ${promptTpls.items.length} / 20`;
if (ta && act) ta.value = act.text;
updatePromptCount();
}
function promptTextSync() {
const ta = els.promptText;
const act = promptTpls && promptTpls.items.find(t => t.id === promptTpls.active);
if (ta && act) act.text = ta.value;
updatePromptCount();
if (promptTpls) setDirty('prompts', promptsSnapshot() !== promptsBaseline);
}
function addPromptTemplate() {
if (!promptTpls) return;
if (promptTpls.items.length >= 20) { showToast('Не больше 20 шаблонов', true); return; }
promptTextSync();
const id = `tpl-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
promptTpls.items.push({ id, name: `Шаблон ${promptTpls.items.length + 1}`, text: '' });
promptTpls.active = id;
renderPromptTemplates();
const name = els.promptTplName;
if (name) { name.focus(); name.select(); }
}
function deletePromptTemplate() {
if (!promptTpls || promptTpls.items.length <= 1) return;
promptTextSync();
const act = promptTpls.items.find(t => t.id === promptTpls.active);
if (!confirm(`Удалить шаблон «${act ? act.name : ''}»?`)) return;
const idx = promptTpls.items.findIndex(t => t.id === promptTpls.active);
promptTpls.items.splice(idx, 1);
promptTpls.active = promptTpls.items[Math.min(idx, promptTpls.items.length - 1)].id;
renderPromptTemplates();
setDirty('prompts', promptsSnapshot() !== promptsBaseline);
}
function resetAiTab() {
if (!dirty.ai) return;
try {
const parsed = JSON.parse(aiBaseline);
myModels = Array.isArray(parsed.models) ? parsed.models : [];
if (els.modelSelect) els.modelSelect.value = parsed.profile || '';
} catch (e) {}
hideModelForm();
renderModelsList();
void refreshModelSelects();
clearStatus(els.aiStatus);
setDirty('ai', false);
showToast('Изменения отменены');
}
function resetPromptsTab() {
if (!dirty.prompts) return;
promptTpls = parsePromptTemplates();
renderPromptTemplates();
clearStatus(els.promptStatus);
promptsBaseline = promptsSnapshot();
setDirty('prompts', false);
showToast('Изменения отменены');
}
async function putUserSettings(settings) {
try {
const r = await fetch(`${API}/api/user-settings`, {
method: 'PUT',
headers: { ...hdr(), 'Content-Type': 'application/json' },
body: JSON.stringify({ settings }),
});
const j = await r.json().catch(() => ({}));
if (!r.ok) return { ok: false, error: j.error || 'Не удалось сохранить' };
return { ok: true, data: j };
} catch (e) {
return { ok: false, error: e.message || 'Не удалось сохранить' };
}
}
function applySettingsResponse(j) {
userSettings.settings = (j && j.settings) || userSettings.settings;
userSettings.defaults = (j && j.defaults) || userSettings.defaults;
}
async function saveAiSettings() {
if (!modelOptionsLoaded) {
setStatus(els.aiStatus, false, 'Список моделей не загружен — сохраните позже');
showToast('Список моделей не загружен', true);
return;
}
if (!dirty.ai) { showToast('Нет изменений для сохранения'); return; }
els.aiSave.disabled = true;
try {
const res = await putUserSettings({
feedback_profile: els.modelSelect.value || '',
feedback_models: myModels.length ? JSON.stringify(myModels) : '',
});
if (!res.ok) {
setStatus(els.aiStatus, false, res.error);
showToast(res.error, true);
return;
}
applySettingsResponse(res.data);
parseMyModels();
await refreshModelSelects();
renderModelsList();
aiBaseline = aiSnapshot();
setDirty('ai', false);
setStatus(els.aiStatus, true, 'Сохранено');
showToast('Настройки ИИ сохранены');
} finally {
els.aiSave.disabled = false;
}
}
async function savePromptSettings() {
if (!promptTpls) return;
promptTextSync();
promptTpls.items.forEach(t => { t.name = String(t.name || '').trim() || 'Шаблон'; });
const activeTpl = promptTpls.items.find(t => t.id === promptTpls.active);
if (!dirty.prompts) { showToast('Нет изменений для сохранения'); return; }
els.promptSave.disabled = true;
try {
const res = await putUserSettings({
feedback_prompt: activeTpl ? activeTpl.text.trim() : '',
feedback_prompts: JSON.stringify(promptTpls),
});
if (!res.ok) {
setStatus(els.promptStatus, false, res.error);
showToast(res.error, true);
return;
}
applySettingsResponse(res.data);
promptTpls = parsePromptTemplates();
renderPromptTemplates();
renderDefaultPrompt();
promptsBaseline = promptsSnapshot();
setDirty('prompts', false);
setStatus(els.promptStatus, true, 'Сохранено');
showToast('Промпт сохранён');
} finally {
els.promptSave.disabled = false;
}
}
function activateTab(name) {
const btn = tabButtons.find(b => b.dataset.tab === name);
if (!btn || btn.hidden || !document.getElementById('tab-' + name)) name = 'general';
activeTab = name;
tabButtons.forEach(b => {
const on = b.dataset.tab === name;
b.classList.toggle('active', on);
b.setAttribute('aria-selected', on ? 'true' : 'false');
});
tabPanels.forEach(p => { p.style.display = p.id === 'tab-' + name ? '' : 'none'; });
if (els.formActions) els.formActions.style.display = (name === 'general' || name === 'password') ? '' : 'none';
if (history.replaceState) history.replaceState(null, '', '#' + name);
if (name === 'ai') void loadAiTab();
if (name === 'prompts') void loadPromptsTab();
}
async function uploadAvatar() {
if (!avatarFile) return;
const formData = new FormData();
formData.append('photo', avatarFile);
setLoading(els.btnSave, true);
try {
const res = await fetch(`${API}/api/users/${userId}/avatar`, {
method: 'POST',
headers: hdr(),
body: formData,
});
if (res.status === 401) { cleanupSession(); return; }
if (!res.ok) throw new Error('Не удалось загрузить аватар');
const json = await res.json();
if (json.avatar) {
if (els.avatarImg) els.avatarImg.src = thumbSrc(json.avatar);
else {
const img = document.createElement('img');
img.src = thumbSrc(json.avatar);
img.alt = 'Аватар';
img.dataset.full = json.avatar;
els.avatar.insertBefore(img, els.avatarEmpty);
els.avatarImg = img;
els.avatarEmpty.style.display = 'none';
}
els.avatarImg.dataset.full = json.avatar;
}
showToast('Аватар обновлён');
} catch (e) {
showToast(e.message || 'Ошибка загрузки аватара', true);
} finally {
setLoading(els.btnSave, false);
}
}
function previewAvatar(src) {
if (!els.imgModal || !els.imgModalSrc || !src) return;
els.imgModalSrc.src = src;
els.imgModal.classList.add('open');
}
document.getElementById('avatarFile').addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
if (!file.type.startsWith('image/')) { showToast('Выберите изображение', true); return; }
if (file.size > 5 * 1024 * 1024) { showToast('Размер аватара не более 5 МБ', true); return; }
avatarFile = file;
const url = URL.createObjectURL(file);
if (els.avatarImg) els.avatarImg.src = url;
else {
const img = document.createElement('img');
img.src = url;
img.alt = 'Аватар';
els.avatar.insertBefore(img, els.avatarEmpty);
els.avatarImg = img;
els.avatarEmpty.style.display = 'none';
}
uploadAvatar();
});
els.togglePassword.addEventListener('click', () => {
isPasswordVisible = !isPasswordVisible;
els.passwordFields.style.display = isPasswordVisible ? '' : 'none';
setIcon(els.togglePassword, isPasswordVisible ? 'lock-open' : 'lock');
els.oldPassword.value = '';
els.newPassword.value = '';
els.newPasswordConfirm.value = '';
if (!isPasswordVisible) setDirty('general', generalSnapshot() !== generalBaseline);
});
els.btnSave.addEventListener('click', saveProfile);
els.btnCancel.addEventListener('click', () => { loadProfile(); });
els.btnLogout.addEventListener('click', () => { doLogout(); });
for (const input of [els.name, els.email, els.phone, els.oldPassword, els.newPassword, els.newPasswordConfirm]) {
if (input) input.addEventListener('input', () => setDirty('general', generalSnapshot() !== generalBaseline));
}
els.avatar.addEventListener('click', (e) => {
if (e.target.closest('.avatar-upload')) return;
if (!els.avatarImg) return;
const full = els.avatarImg.dataset.full;
previewAvatar(full ? `${API}${full}` : els.avatarImg.src);
});
if (els.imgModal) els.imgModal.addEventListener('click', () => els.imgModal.classList.remove('open'));
tabButtons.forEach(tab => {
tab.addEventListener('click', () => activateTab(tab.dataset.tab));
});
window.addEventListener('hashchange', () => {
const name = location.hash.replace('#', '');
if (name && name !== activeTab) activateTab(name);
});
window.addEventListener('beforeunload', (e) => {
if (!hasUnsaved()) return;
e.preventDefault();
e.returnValue = '';
});
els.modelAdd.addEventListener('click', () => showModelForm(null));
els.modelCancel.addEventListener('click', hideModelForm);
els.modelSave.addEventListener('click', saveModelForm);
els.modelTest.addEventListener('click', () => {
const tok = els.mMaxTok.value.trim();
checkModel({
name: els.mName.value.trim() || 'Моя модель',
model: els.mModel.value.trim(),
base_url: els.mUrl.value.trim(),
api_key: els.mKey.value.trim(),
max_tokens: tok ? parseInt(tok, 10) : null
}, els.modelTestStatus, els.modelTest);
});
els.modelsList.addEventListener('click', (e) => {
const def = e.target.closest('[data-mdefault]');
if (def) { makeDefaultModel(parseInt(def.dataset.mdefault, 10)); return; }
const chk = e.target.closest('[data-mcheck]');
if (chk) {
const row = chk.closest('.sp-model-row');
const m = myModels[parseInt(chk.dataset.mcheck, 10)];
if (row) checkModel(m, row.querySelector('.ai-test-status'), chk);
return;
}
const ed = e.target.closest('[data-medit]');
if (ed) { showModelForm(parseInt(ed.dataset.medit, 10)); return; }
const del = e.target.closest('[data-mdel]');
if (del) deleteModel(parseInt(del.dataset.mdel, 10));
});
els.mKeyToggle.addEventListener('click', () => {
const hidden = els.mKey.type === 'password';
els.mKey.type = hidden ? 'text' : 'password';
setIcon(els.mKeyToggle, hidden ? 'eye-off' : 'eye');
});
els.modelEdit.addEventListener('keydown', (e) => {
if (e.key === 'Escape') { hideModelForm(); return; }
if (e.key === 'Enter' && e.target.tagName !== 'BUTTON') { e.preventDefault(); saveModelForm(); }
});
els.modelSelect.addEventListener('change', () => {
renderModelsList();
setDirty('ai', aiSnapshot() !== aiBaseline);
});
els.aiSave.addEventListener('click', saveAiSettings);
els.aiReset.addEventListener('click', resetAiTab);
els.promptTpl.addEventListener('change', () => {
if (!promptTpls) return;
promptTextSync();
promptTpls.active = els.promptTpl.value;
renderPromptTemplates();
setDirty('prompts', promptsSnapshot() !== promptsBaseline);
});
els.promptTplName.addEventListener('input', (e) => {
if (!promptTpls) return;
const act = promptTpls.items.find(t => t.id === promptTpls.active);
if (!act) return;
act.name = e.target.value;
const sel = els.promptTpl;
if (sel && sel.options[sel.selectedIndex]) sel.options[sel.selectedIndex].textContent = e.target.value;
setDirty('prompts', promptsSnapshot() !== promptsBaseline);
});
els.promptTplAdd.addEventListener('click', addPromptTemplate);
els.promptTplDel.addEventListener('click', deletePromptTemplate);
els.promptText.addEventListener('input', promptTextSync);
els.promptText.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); savePromptSettings(); }
});
els.promptKeys.addEventListener('click', (e) => {
const key = e.target.closest('.fb-key');
const ta = els.promptText;
const code = key && key.querySelector('code');
if (!ta || !code) return;
const token = code.textContent.trim();
const start = ta.selectionStart ?? ta.value.length;
const end = ta.selectionEnd ?? start;
ta.value = ta.value.slice(0, start) + token + ta.value.slice(end);
ta.focus();
ta.setSelectionRange(start + token.length, start + token.length);
promptTextSync();
});
els.promptUseDefault.addEventListener('click', () => {
const fallback = userSettings.defaults.feedback_prompt || '';
if (!fallback) return;
if (els.promptText.value.trim() && !confirm('Заменить текущий текст шаблона системным?')) return;
els.promptText.value = fallback;
promptTextSync();
els.promptText.focus();
});
els.promptReset.addEventListener('click', resetPromptsTab);
els.promptSave.addEventListener('click', savePromptSettings);
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && els.imgModal && els.imgModal.classList.contains('open')) {
els.imgModal.classList.remove('open');
return;
}
if (!(e.ctrlKey || e.metaKey) || (e.key !== 's' && e.key !== 'S') || e.shiftKey || e.altKey) return;
e.preventDefault();
if (activeTab === 'ai') saveAiSettings();
else if (activeTab === 'prompts') savePromptSettings();
else if (activeTab === 'general' || activeTab === 'password') saveProfile();
});
const initialTab = location.hash.replace('#', '') || 'general';
activateTab(initialTab);
loadProfile().then(() => {
if (initialTab !== 'general' && activeTab === 'general') activateTab(initialTab);
});
loadStats();
renderIcons();
})();