main.py: POST /api/admin/users/provider (RBAC, валидация ∈ALLOWED, защита владельца, сброс ""→NULL, audit-лог set_provider); GET /api/admin/users обогащён is_owner. admin.html: колонка «Провайдер» — <select> через createElement (данные не в inline-onclick), владелец → disabled=claude, confirm при выборе внешнего провайдера. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
603 lines
35 KiB
HTML
603 lines
35 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="ru">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>Админ-панель</title>
|
||
<style>
|
||
:root { --bg: #f5f0eb; --card: #fff; --text: #3a3a3a; --muted: #6b6b6b; --accent: #c4463a; --border: #d4c5b2; --sidebar: #2c2c2c; --sidebar-text: #e0d6cc; --sidebar-active: #c4463a; --green: #2d8a56; }
|
||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); display: flex; min-height: 100vh; }
|
||
|
||
/* Sidebar */
|
||
.sidebar { width: 220px; background: var(--sidebar); color: var(--sidebar-text); padding: 1.5rem 0; flex-shrink: 0; }
|
||
.sidebar h1 { font-size: 1rem; padding: 0 1.2rem .8rem; border-bottom: 1px solid #444; margin-bottom: .5rem; }
|
||
.sidebar a { display: block; padding: .6rem 1.2rem; color: var(--sidebar-text); text-decoration: none; font-size: .85rem; border-left: 3px solid transparent; transition: all .15s; }
|
||
.sidebar a:hover { background: rgba(255,255,255,.05); }
|
||
.sidebar a.active { background: rgba(255,255,255,.08); border-left-color: var(--sidebar-active); color: #fff; font-weight: 600; }
|
||
.sidebar .back { margin-top: 1rem; padding-top: .8rem; border-top: 1px solid #444; font-size: .8rem; color: #888; }
|
||
|
||
/* Main */
|
||
.main { flex: 1; padding: 2rem; overflow-y: auto; }
|
||
.page { display: none; }
|
||
.page.active { display: block; }
|
||
h2 { font-size: 1.1rem; margin-bottom: 1rem; }
|
||
table { width: 100%; border-collapse: collapse; background: var(--card); border-radius: 8px; overflow: hidden; box-shadow: 0 1px 4px rgba(0,0,0,.06); margin-bottom: 1.5rem; }
|
||
th { background: #ede5db; text-align: left; padding: 8px 12px; font-size: .8rem; font-weight: 600; }
|
||
td { padding: 6px 12px; border-top: 1px solid #eee; font-size: .85rem; }
|
||
a { color: var(--accent); text-decoration: none; }
|
||
.time { color: var(--muted); font-size: .75rem; }
|
||
.q { color: var(--muted); font-size: .8rem; max-width: 350px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||
.stat-cards { display: flex; gap: 1rem; margin-bottom: 1.5rem; flex-wrap: wrap; }
|
||
.stat-card { background: var(--card); padding: 1rem 1.2rem; border-radius: 8px; box-shadow: 0 1px 4px rgba(0,0,0,.06); min-width: 130px; }
|
||
.stat-card .num { font-size: 1.6rem; font-weight: 700; }
|
||
.stat-card .label { font-size: .75rem; color: var(--muted); }
|
||
.btn { padding: .5rem 1rem; background: var(--accent); color: #fff; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: .85rem; }
|
||
.btn:hover { background: #a83830; }
|
||
.btn-sm { padding: 2px 8px; font-size: .7rem; margin: 1px; cursor: pointer; border: 1px solid var(--border); border-radius: 3px; background: var(--card); }
|
||
.nb-badge { display:inline-flex; align-items:center; gap:.3rem; padding:2px 9px; border-radius:999px; font-size:.72rem; font-weight:600; white-space:nowrap; }
|
||
.nb-ok { background:rgba(45,138,86,.16); color:var(--green); }
|
||
.nb-aging { background:rgba(200,140,20,.20); color:#b07d10; }
|
||
.nb-stale, .nb-error { background:rgba(196,70,58,.15); color:var(--accent); }
|
||
.nb-none { background:rgba(120,120,120,.16); color:var(--muted); }
|
||
.nb-src { background:var(--card); border:1px solid var(--border); border-radius:8px; padding:.85rem 1.1rem; margin-bottom:.7rem; box-shadow:0 1px 4px rgba(0,0,0,.05); }
|
||
.nb-src h4 { margin:0; font-size:.95rem; display:flex; align-items:center; gap:.6rem; flex-wrap:wrap; }
|
||
.nb-meta { font-size:.8rem; color:var(--muted); display:flex; flex-wrap:wrap; gap:.15rem 1.3rem; margin-top:.4rem; }
|
||
.nb-meta b { color:var(--text); font-weight:600; }
|
||
.nb-bar { position:relative; height:16px; border-radius:8px; background:var(--border); overflow:hidden; margin-top:.55rem; }
|
||
.nb-bar > span { display:block; height:100%; background:var(--green); transition:width .3s; }
|
||
.nb-bar > em { position:absolute; top:0; right:8px; line-height:16px; font-size:.7rem; font-style:normal; font-weight:700; color:var(--text); }
|
||
.nb-engine { border-left:4px solid var(--accent); padding:.8rem 1.1rem; border-radius:6px; background:var(--card); margin-bottom:1.2rem; box-shadow:0 1px 4px rgba(0,0,0,.05); font-size:.9rem; }
|
||
.nb-engine.eng-ok { border-left-color:var(--green); }
|
||
|
||
/* ===== Тёмная тема (общая с чатом; выбор хранится в localStorage['theme']) ===== */
|
||
html { color-scheme: light; }
|
||
:root[data-theme="dark"] {
|
||
color-scheme: dark;
|
||
--bg: #16140f; --card: #211d17; --text: #ece4d7; --muted: #a89c8a;
|
||
--accent: #d9695c; --border: #3a332a;
|
||
--sidebar: #201c16; --sidebar-text: #d8cdbd; --sidebar-active: #d9695c; --green: #3fa066;
|
||
}
|
||
:root[data-theme="dark"] th { background: #2a2620; }
|
||
:root[data-theme="dark"] td { border-top-color: #2f2820; }
|
||
:root[data-theme="dark"] table, :root[data-theme="dark"] .stat-card { box-shadow: 0 1px 4px rgba(0,0,0,.4); }
|
||
:root[data-theme="dark"] .btn:hover { background: #c2564a; }
|
||
</style>
|
||
<script>
|
||
/* Тема до первой отрисовки (FOUC): сохранённый выбор → система → светлая */
|
||
(function(){try{var t=localStorage.getItem('theme');if(t!=='dark'&&t!=='light'){t=(window.matchMedia&&matchMedia('(prefers-color-scheme: dark)').matches)?'dark':'light';}document.documentElement.setAttribute('data-theme',t);}catch(e){}})();
|
||
function toggleTheme(){var n=document.documentElement.getAttribute('data-theme')==='dark'?'light':'dark';document.documentElement.setAttribute('data-theme',n);try{localStorage.setItem('theme',n);}catch(e){}applyThemeIcon();}
|
||
function applyThemeIcon(){var b=document.getElementById('theme-toggle');if(b)b.textContent=document.documentElement.getAttribute('data-theme')==='dark'?'☀ Светлая тема':'🌙 Тёмная тема';}
|
||
document.addEventListener('DOMContentLoaded',applyThemeIcon);
|
||
</script>
|
||
</head>
|
||
<body>
|
||
|
||
<nav class="sidebar">
|
||
<h1>Админ-панель</h1>
|
||
<a href="#dashboard" class="active" onclick="return showPage('dashboard')">Dashboard</a>
|
||
<a href="#normative" onclick="loadNormative();return showPage('normative')">Нормативная база</a>
|
||
<a href="#users" onclick="return showPage('users')">Пользователи</a>
|
||
<a href="#invites" onclick="return showPage('invites')">Приглашения</a>
|
||
<a href="#sessions" onclick="return showPage('sessions')">Сессии</a>
|
||
<a href="#audit" onclick="return showPage('audit')">Журнал</a>
|
||
<a href="#feedback" onclick="return showPage('feedback')">Жалобы</a>
|
||
<a href="#files" onclick="return showPage('files')">Файлы</a>
|
||
<a href="#" id="theme-toggle" onclick="toggleTheme();return false">🌙 Тёмная тема</a>
|
||
<a href="/" class="back">← Вернуться в чат</a>
|
||
<div class="app-version" style="position:absolute;bottom:.5rem;left:1rem;font-size:.65rem;color:#999"></div>
|
||
</nav>
|
||
|
||
<div class="main">
|
||
|
||
<!-- Dashboard -->
|
||
<div class="page active" id="page-dashboard">
|
||
<h2>Dashboard</h2>
|
||
<div class="stat-cards" id="stats"></div>
|
||
<div id="daily"></div>
|
||
</div>
|
||
|
||
<!-- Нормативная база (внешние источники) -->
|
||
<div class="page" id="page-normative">
|
||
<h2>Нормативная база — состояние внешних источников</h2>
|
||
<div style="display:flex;gap:.6rem;align-items:center;margin-bottom:1rem;flex-wrap:wrap">
|
||
<span id="nb-checked"></span>
|
||
<button class="btn" id="nb-recheck" onclick="recheckNormative()" style="padding:5px 12px;font-size:.8rem">Проверить сейчас</button>
|
||
<button class="btn-sm" onclick="loadNormative()">Обновить</button>
|
||
<span id="nb-note" style="font-size:.78rem;color:var(--muted)"></span>
|
||
</div>
|
||
<div id="nb-engine"></div>
|
||
<div id="nb-sources"></div>
|
||
<div id="nb-storage" style="font-size:.72rem;color:var(--muted);margin-top:.6rem"></div>
|
||
</div>
|
||
|
||
<!-- Users -->
|
||
<div class="page" id="page-users">
|
||
<h2>Пользователи</h2>
|
||
<table id="users">
|
||
<tr><th>Email</th><th>Роль</th><th>Статус</th><th>Провайдер</th><th>Создан</th><th>Действия</th></tr>
|
||
</table>
|
||
</div>
|
||
|
||
<!-- Invites -->
|
||
<div class="page" id="page-invites">
|
||
<h2>Приглашения</h2>
|
||
<button class="btn" onclick="createInvite()">Создать приглашение</button>
|
||
<div id="invite-result" style="margin:.8rem 0;font-size:.85rem"></div>
|
||
<table id="invites">
|
||
<tr><th>Токен</th><th>Создано</th><th>Использовано</th></tr>
|
||
</table>
|
||
</div>
|
||
|
||
<!-- Sessions -->
|
||
<div class="page" id="page-sessions">
|
||
<h2>Сессии чатов</h2>
|
||
<table id="sessions">
|
||
<tr><th>Время</th><th>Пользователь</th><th>Сообщений</th><th>Последний вопрос</th><th></th></tr>
|
||
</table>
|
||
</div>
|
||
|
||
<!-- Audit Log -->
|
||
<div class="page" id="page-audit">
|
||
<h2>Журнал действий</h2>
|
||
<div style="display:flex;gap:.5rem;margin-bottom:1rem;align-items:center;flex-wrap:wrap">
|
||
<select id="audit-user" style="padding:4px 8px;border:1px solid var(--border);border-radius:4px;font-size:.8rem">
|
||
<option value="">Все пользователи</option>
|
||
</select>
|
||
<select id="audit-action" style="padding:4px 8px;border:1px solid var(--border);border-radius:4px;font-size:.8rem">
|
||
<option value="">Все действия</option>
|
||
</select>
|
||
<button class="btn" onclick="loadAudit(0)" style="padding:4px 10px;font-size:.8rem">Фильтр</button>
|
||
</div>
|
||
<table id="audit">
|
||
<tr><th>Время</th><th>Пользователь</th><th>Действие</th><th>Путь</th><th>Детали</th><th>IP</th><th>Код</th></tr>
|
||
</table>
|
||
<button class="btn" id="audit-more" onclick="loadAuditMore()" style="margin-top:.5rem;display:none">Ещё</button>
|
||
</div>
|
||
|
||
<!-- Feedback (жалобы на ответы) -->
|
||
<div class="page" id="page-feedback">
|
||
<h2>Жалобы на ответы</h2>
|
||
<div style="display:flex;gap:.5rem;margin-bottom:1rem;align-items:center">
|
||
<button class="btn" onclick="loadFeedback()" style="padding:4px 10px;font-size:.8rem">Обновить</button>
|
||
<span id="feedback-count" style="font-size:.8rem;color:var(--text-muted, #666)"></span>
|
||
</div>
|
||
<table id="feedback-table">
|
||
<tr><th>Время</th><th>Пользователь</th><th>Комментарий</th><th>Ответ (фрагмент)</th></tr>
|
||
</table>
|
||
</div>
|
||
|
||
<!-- Files -->
|
||
<div class="page" id="page-files">
|
||
<h2>Файлы пользователей</h2>
|
||
<div style="display:flex;gap:.5rem;margin-bottom:1rem;align-items:center;flex-wrap:wrap">
|
||
<select id="files-user" onchange="onFilesUserChange()" style="padding:4px 8px;border:1px solid var(--border);border-radius:4px;font-size:.85rem;min-width:240px">
|
||
<option value="">— выберите пользователя —</option>
|
||
</select>
|
||
<button class="btn" onclick="loadFiles()" style="padding:4px 10px;font-size:.8rem">Обновить</button>
|
||
<span id="files-count" style="font-size:.8rem;color:var(--text-muted, #666)"></span>
|
||
</div>
|
||
<table id="files"></table>
|
||
</div>
|
||
|
||
</div>
|
||
|
||
<script>
|
||
let token = localStorage.getItem('token');
|
||
// Validate token on load
|
||
(async () => {
|
||
if (!token) { location.href = '/'; return; }
|
||
try {
|
||
const r = await fetch('/api/history?limit=1', {headers:{'Authorization':'Bearer '+token}});
|
||
if (r.ok) return;
|
||
} catch {}
|
||
const rt = localStorage.getItem('refresh_token');
|
||
if (rt) {
|
||
try {
|
||
const r = await fetch('/api/refresh', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({refresh_token:rt})});
|
||
if (r.ok) { const d = await r.json(); token = d.token; localStorage.setItem('token', token); return; }
|
||
} catch {}
|
||
}
|
||
localStorage.removeItem('token'); localStorage.removeItem('refresh_token');
|
||
location.href = '/';
|
||
})();
|
||
const H = {'Authorization': 'Bearer ' + token};
|
||
|
||
// Check token validity — redirect to login on 401
|
||
async function checkAuth() {
|
||
const r = await fetch('/api/admin/stats', {headers: H});
|
||
if (r.status === 401) { localStorage.removeItem('token'); window.location.href = '/'; }
|
||
}
|
||
checkAuth();
|
||
|
||
// Navigation
|
||
function showPage(name) {
|
||
document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
|
||
document.querySelectorAll('.sidebar a').forEach(a => a.classList.remove('active'));
|
||
document.getElementById('page-' + name).classList.add('active');
|
||
document.querySelector('.sidebar a[href="#' + name + '"]').classList.add('active');
|
||
// Обновляем hash без default-скролла браузера и без записи в history
|
||
// (default <a href="#x"> делает window.scrollTo + history.pushState —
|
||
// это и есть «дёрганье». Возвращаем false из onclick, default отменяется,
|
||
// мы сами тихо ставим hash через replaceState).
|
||
if (location.hash !== '#' + name) {
|
||
history.replaceState(null, '', '#' + name);
|
||
}
|
||
return false;
|
||
}
|
||
// Handle hash on load
|
||
if (location.hash) showPage(location.hash.slice(1));
|
||
|
||
// Экранирование пользовательского ввода перед вставкой в innerHTML (stored-XSS на админа:
|
||
// last_question/tab_id/username/detail — под контролем обычного юзера). Fable.
|
||
function esc(s){ return String(s==null?'':s).replace(/[&<>"']/g, c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }
|
||
|
||
// === Dashboard ===
|
||
fetch('/api/admin/stats', {headers: H}).then(r=>r.json()).then(data => {
|
||
const t = data.totals;
|
||
const card = (label, val) => `<div class="stat-card"><div class="num">${val}</div><div class="label">${label}</div></div>`;
|
||
document.getElementById('stats').innerHTML = card('Сообщений', t.messages) + card('Сессий', t.sessions) + card('Пользователей', t.users);
|
||
if (data.daily && data.daily.length > 0) {
|
||
let html = '<table><tr><th>Дата</th><th>Вопросов</th><th>Ответов</th><th>Всего</th></tr>';
|
||
for (const d of data.daily) {
|
||
html += `<tr><td>${d.day}</td><td>${d.questions}</td><td>${d.answers}</td><td>${d.total}</td></tr>`;
|
||
}
|
||
document.getElementById('daily').innerHTML = html + '</table>';
|
||
}
|
||
}).catch(()=>{});
|
||
|
||
// === Users ===
|
||
async function userAction(action, email, data={}) {
|
||
if (action === 'delete' && !confirm('Удалить ' + email + '?')) return;
|
||
const r = await fetch('/api/admin/users/' + action, {method:'POST', headers:{...H,'Content-Type':'application/json'}, body:JSON.stringify({email, ...data})});
|
||
const d = await r.json();
|
||
if (d.ok) loadUsers(); else alert(d.detail || 'Ошибка');
|
||
}
|
||
|
||
function loadUsers() {
|
||
fetch('/api/admin/users', {headers: H}).then(r=>r.json()).then(users => {
|
||
const t = document.getElementById('users');
|
||
t.innerHTML = '<tr><th>Email</th><th>Роль</th><th>Статус</th><th>Провайдер</th><th>Создан</th><th>Действия</th></tr>';
|
||
for (const u of users) {
|
||
const d = new Date(u.created_at < 1e12 ? u.created_at*1000 : u.created_at);
|
||
const tr = document.createElement('tr');
|
||
const status = u.blocked ? '<span style="color:var(--accent)">Заблокирован</span>' : (u.verified ? '<span style="color:var(--green)">Активен</span>' : '<span style="color:var(--muted)">Не подтверждён</span>');
|
||
const ts = d.toLocaleString('ru-RU',{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'});
|
||
// email/role экранируем (email задаёт сам юзер → был stored-XSS); status — из фикс-строк.
|
||
tr.innerHTML = '<td>'+esc(u.email)+'</td><td>'+esc(u.role)+'</td><td>'+status+'</td>';
|
||
// Провайдер: <select> через createElement (email/значения как ДАННЫЕ, не в inline-onclick).
|
||
const provTd = document.createElement('td');
|
||
const sel = document.createElement('select');
|
||
sel.className = 'btn-sm';
|
||
const PROV = [['','По умолчанию'],['claude','Claude'],['deepseek','DeepSeek'],['glm','GLM']];
|
||
for (const [val, label] of PROV) {
|
||
const o = document.createElement('option');
|
||
o.value = val; o.textContent = label;
|
||
sel.appendChild(o);
|
||
}
|
||
if (u.is_owner) {
|
||
sel.value = 'claude';
|
||
sel.disabled = true;
|
||
sel.title = 'Владелец (оператор) всегда на Claude';
|
||
} else {
|
||
sel.value = u.agent_provider || '';
|
||
sel.onchange = () => {
|
||
if ((sel.value === 'deepseek' || sel.value === 'glm')
|
||
&& !confirm('Переключить ' + u.email + ' на внешний провайдер (' + sel.value + ')? Запросы уйдут стороннему API.')) {
|
||
sel.value = u.agent_provider || '';
|
||
return;
|
||
}
|
||
userAction('provider', u.email, {provider: sel.value});
|
||
};
|
||
}
|
||
provTd.appendChild(sel);
|
||
tr.appendChild(provTd);
|
||
const createdTd = document.createElement('td');
|
||
createdTd.className = 'time';
|
||
createdTd.textContent = ts;
|
||
tr.appendChild(createdTd);
|
||
const actionsTd = document.createElement('td');
|
||
// обработчики — замыкания (email как ДАННЫЕ, не как код в inline-onclick: апостроф/тег ломал/инжектил)
|
||
const addBtn = (label, fn) => { const b = document.createElement('button'); b.className='btn-sm'; b.textContent=label; b.onclick=fn; actionsTd.appendChild(b); };
|
||
if (u.blocked) addBtn('Разблокировать', () => userAction('block', u.email, {blocked:false}));
|
||
else addBtn('Заблокировать', () => userAction('block', u.email, {blocked:true}));
|
||
if (!u.verified) addBtn('Подтвердить', () => userAction('verify', u.email));
|
||
addBtn(u.role==='admin'?'Сделать user':'Сделать admin', () => userAction('role', u.email, {role: u.role==='admin'?'user':'admin'}));
|
||
addBtn('Удалить', () => userAction('delete', u.email));
|
||
tr.appendChild(actionsTd);
|
||
t.appendChild(tr);
|
||
}
|
||
}).catch(()=>{});
|
||
}
|
||
loadUsers();
|
||
|
||
// === Files (admin) ===
|
||
function fmtSize(n){
|
||
if (n < 1024) return n+' B';
|
||
if (n < 1024*1024) return (n/1024).toFixed(1)+' KB';
|
||
return (n/1024/1024).toFixed(1)+' MB';
|
||
}
|
||
// dropdown файловой страницы наполняется из FS, не из БД-юзеров —
|
||
// бывают env-only / удалённые аккаунты, чьи файлы всё ещё на диске
|
||
async function loadFileUsers() {
|
||
const sel = document.getElementById('files-user');
|
||
if (!sel) return;
|
||
const r = await fetch('/api/admin/file_users', {headers: H});
|
||
if (!r.ok) return;
|
||
const d = await r.json();
|
||
const total = d.users.reduce((acc, u) => acc + u.file_count, 0);
|
||
sel.innerHTML = '<option value="__all__">Все (' + total + ')</option>';
|
||
for (const u of d.users) {
|
||
const opt = document.createElement('option');
|
||
opt.value = u.username;
|
||
opt.textContent = u.username + ' (' + u.file_count + ')';
|
||
sel.appendChild(opt);
|
||
}
|
||
// По умолчанию — «Все»; localStorage только если ранее юзер
|
||
// явно выбирал не-«все»
|
||
const saved = localStorage.getItem('admin_files_user');
|
||
sel.value = (saved && Array.from(sel.options).some(o => o.value === saved))
|
||
? saved
|
||
: '__all__';
|
||
loadFiles();
|
||
}
|
||
function onFilesUserChange() {
|
||
const v = document.getElementById('files-user').value;
|
||
if (v) localStorage.setItem('admin_files_user', v);
|
||
else localStorage.removeItem('admin_files_user');
|
||
loadFiles();
|
||
}
|
||
loadFileUsers();
|
||
async function loadFiles() {
|
||
const u = document.getElementById('files-user').value;
|
||
const tbl = document.getElementById('files');
|
||
const cnt = document.getElementById('files-count');
|
||
const isAll = (u === '__all__');
|
||
// header
|
||
tbl.innerHTML = isAll
|
||
? '<tr><th>Пользователь</th><th>Tab ID</th><th>Файл</th><th>Размер</th><th>Загружен</th><th>Действие</th></tr>'
|
||
: '<tr><th>Tab ID</th><th>Файл</th><th>Размер</th><th>Загружен</th><th>Действие</th></tr>';
|
||
cnt.textContent = '';
|
||
if (!u) return;
|
||
cnt.textContent = 'Загрузка…';
|
||
const r = await fetch('/api/admin/files?username=' + encodeURIComponent(u), {headers: H});
|
||
if (!r.ok) { cnt.textContent = 'Ошибка: ' + r.status; return; }
|
||
const d = await r.json();
|
||
cnt.textContent = 'Файлов: ' + d.count;
|
||
// Сортировка: новые сверху
|
||
const rows = d.files.slice().sort((a, b) => b.mtime - a.mtime);
|
||
for (const f of rows) {
|
||
const ts = new Date(f.mtime * 1000).toLocaleString('ru-RU', {day:'2-digit', month:'2-digit', year:'2-digit', hour:'2-digit', minute:'2-digit'});
|
||
const tr = document.createElement('tr');
|
||
const owner = f.username || u;
|
||
const dlUrl = '/api/admin/file_download?username=' + encodeURIComponent(owner)
|
||
+ '&tab_id=' + encodeURIComponent(f.tab_id)
|
||
+ '&filename=' + encodeURIComponent(f.filename);
|
||
const userCol = isAll ? '<td style="font-size:.8rem">' + esc(owner) + '</td>' : '';
|
||
tr.innerHTML = userCol
|
||
+ '<td style="font-family:monospace;font-size:.8rem">' + esc(f.tab_id) + '</td>'
|
||
+ '<td>' + esc(f.filename) + '</td>'
|
||
+ '<td>' + fmtSize(f.size) + '</td>'
|
||
+ '<td class="time">' + ts + '</td>';
|
||
// Кнопка скачивания — замыкание, а НЕ строковый onclick: имя файла юзер контролирует,
|
||
// а '-only экранирование не спасало от " в double-quoted onclick (stored-XSS на админа).
|
||
const dlTd = document.createElement('td');
|
||
const dlBtn = document.createElement('button');
|
||
dlBtn.className = 'btn-sm'; dlBtn.textContent = 'Скачать';
|
||
dlBtn.onclick = () => adminDownload(dlUrl, f.filename);
|
||
dlTd.appendChild(dlBtn);
|
||
tr.appendChild(dlTd);
|
||
tbl.appendChild(tr);
|
||
}
|
||
}
|
||
async function adminDownload(url, filename) {
|
||
// Native download streams straight to disk (works for multi-GB files; the old
|
||
// fetch→blob buffered the whole file in memory and failed on large ones).
|
||
// <a> can't send an auth header, so first fetch a short-lived signed ticket
|
||
// (with the header) and put only that in the URL — never the JWT.
|
||
const p = new URLSearchParams(url.split('?')[1]);
|
||
const r = await fetch('/api/admin/download_ticket', {
|
||
method: 'POST', headers: {...H, 'Content-Type': 'application/json'},
|
||
body: JSON.stringify({username: p.get('username'), tab_id: p.get('tab_id'), filename: p.get('filename')}),
|
||
});
|
||
if (!r.ok) { alert('Ошибка скачивания: ' + r.status); return; }
|
||
const t = await r.json();
|
||
const a = document.createElement('a');
|
||
a.href = url + '&exp=' + t.exp + '&sig=' + encodeURIComponent(t.sig);
|
||
a.download = filename;
|
||
document.body.appendChild(a); a.click(); a.remove();
|
||
}
|
||
|
||
// === Invites ===
|
||
async function createInvite() {
|
||
const r = await fetch('/api/admin/invite', {method:'POST', headers: H});
|
||
const d = await r.json();
|
||
if (d.url) {
|
||
document.getElementById('invite-result').innerHTML = '<div style="background:var(--card);padding:.8rem;border-radius:6px;border:1px solid var(--border)"><b>Ссылка:</b><br><a href="'+d.url+'" target="_blank" style="word-break:break-all;font-size:.85rem">'+d.url+'</a><br><button class="btn-sm" style="margin-top:.5rem" onclick="navigator.clipboard.writeText(\''+d.url+'\');this.textContent=\'Скопировано!\'">Копировать ссылку</button></div>';
|
||
loadInvites();
|
||
} else {
|
||
document.getElementById('invite-result').textContent = d.detail || 'Ошибка';
|
||
}
|
||
}
|
||
|
||
function loadInvites() {
|
||
fetch('/api/admin/invites', {headers: H}).then(r=>r.json()).then(invites => {
|
||
const t = document.getElementById('invites');
|
||
t.innerHTML = '<tr><th>Токен</th><th>Создано</th><th>Использовано</th><th>Истекает</th></tr>';
|
||
for (const i of invites) {
|
||
const created = new Date(i.created_at < 1e12 ? i.created_at*1000 : i.created_at);
|
||
const expires = new Date(i.expires_at < 1e12 ? i.expires_at*1000 : i.expires_at);
|
||
const expired = Date.now() > expires.getTime();
|
||
const tr = document.createElement('tr');
|
||
const url = 'https://infosmeta.ru/register?invite=' + i.token;
|
||
const used = i.used_by ? esc(i.used_by) : (expired ? '<span style="color:var(--muted)">Истёк</span>' : '<span style="color:var(--green)">Активен</span>');
|
||
tr.innerHTML = '<td style="font-size:.75rem"><a href="'+url+'" target="_blank">'+i.token.slice(0,16)+'...</a></td><td class="time">'+created.toLocaleString('ru-RU',{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'})+'</td><td style="font-size:.8rem">'+used+'</td><td class="time">'+expires.toLocaleString('ru-RU',{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'})+'</td>';
|
||
t.appendChild(tr);
|
||
}
|
||
}).catch(()=>{});
|
||
}
|
||
loadInvites();
|
||
|
||
// === Audit Log ===
|
||
let auditOffset = 0;
|
||
const AUDIT_LIMIT = 200;
|
||
|
||
async function loadAudit(offset) {
|
||
auditOffset = offset || 0;
|
||
const user = document.getElementById('audit-user').value;
|
||
const action = document.getElementById('audit-action').value;
|
||
let url = `/api/admin/audit?limit=${AUDIT_LIMIT}&offset=${auditOffset}`;
|
||
if (user) url += `&username=${encodeURIComponent(user)}`;
|
||
if (action) url += `&action=${encodeURIComponent(action)}`;
|
||
const r = await fetch(url, {headers: H});
|
||
if (!r.ok) return;
|
||
const rows = await r.json();
|
||
const t = document.getElementById('audit');
|
||
if (auditOffset === 0) t.innerHTML = '<tr><th>Время</th><th>Пользователь</th><th>Действие</th><th>Путь</th><th>Детали</th><th>IP</th><th>Код</th></tr>';
|
||
for (const row of rows) {
|
||
const d = new Date(row.timestamp < 1e12 ? row.timestamp*1000 : row.timestamp);
|
||
const ts = d.toLocaleString('ru-RU',{day:'2-digit',month:'2-digit',year:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit'});
|
||
const tr = document.createElement('tr');
|
||
const detail = esc((row.detail||'').slice(0,80));
|
||
const sc = row.status_code;
|
||
const scStyle = sc >= 400 ? 'color:var(--accent)' : '';
|
||
tr.innerHTML = `<td class="time">${ts}</td><td>${esc(row.username||'-')}</td><td><b>${esc(row.action)}</b></td><td style="font-size:.75rem">${esc(row.path)}</td><td class="q" title="${esc(row.detail||'')}">${detail}</td><td style="font-size:.75rem">${esc(row.ip||'')}</td><td style="${scStyle}">${sc||''}</td>`;
|
||
t.appendChild(tr);
|
||
}
|
||
document.getElementById('audit-more').style.display = rows.length >= AUDIT_LIMIT ? '' : 'none';
|
||
// Populate filter dropdowns from first load
|
||
if (auditOffset === 0 && rows.length > 0) {
|
||
const users = [...new Set(rows.map(r=>r.username).filter(Boolean))].sort();
|
||
const actions = [...new Set(rows.map(r=>r.action))].sort();
|
||
const uSel = document.getElementById('audit-user');
|
||
const aSel = document.getElementById('audit-action');
|
||
const curU = uSel.value, curA = aSel.value;
|
||
uSel.innerHTML = '<option value="">Все пользователи</option>' + users.map(u=>`<option value="${esc(u)}">${esc(u)}</option>`).join('');
|
||
aSel.innerHTML = '<option value="">Все действия</option>' + actions.map(a=>`<option value="${esc(a)}">${esc(a)}</option>`).join('');
|
||
uSel.value = curU; aSel.value = curA;
|
||
}
|
||
}
|
||
|
||
function loadAuditMore() {
|
||
auditOffset += AUDIT_LIMIT;
|
||
loadAudit(auditOffset);
|
||
}
|
||
loadAudit(0);
|
||
|
||
// === Жалобы (feedback) — пользовательский текст рендерим через textContent (без XSS) ===
|
||
async function loadFeedback() {
|
||
const r = await fetch('/api/admin/feedback?limit=200', {headers: H});
|
||
if (!r.ok) return;
|
||
const rows = await r.json();
|
||
const t = document.getElementById('feedback-table');
|
||
t.innerHTML = '<tr><th>Время</th><th>Пользователь</th><th>Комментарий</th><th>Ответ (фрагмент)</th></tr>';
|
||
for (const row of rows) {
|
||
const d = new Date(row.timestamp < 1e12 ? row.timestamp * 1000 : row.timestamp);
|
||
const ts = d.toLocaleString('ru-RU', {day:'2-digit',month:'2-digit',year:'2-digit',hour:'2-digit',minute:'2-digit'});
|
||
const tr = document.createElement('tr');
|
||
const cTime = document.createElement('td'); cTime.className = 'time'; cTime.textContent = ts;
|
||
const cUser = document.createElement('td'); cUser.textContent = row.username || '-';
|
||
const cComment = document.createElement('td'); cComment.textContent = row.comment || '';
|
||
const cAnswer = document.createElement('td');
|
||
cAnswer.style.fontSize = '.78rem'; cAnswer.style.color = 'var(--text-muted,#666)';
|
||
cAnswer.textContent = (row.answer || '').slice(0, 200);
|
||
tr.append(cTime, cUser, cComment, cAnswer);
|
||
t.appendChild(tr);
|
||
}
|
||
document.getElementById('feedback-count').textContent = rows.length ? (rows.length + ' жалоб') : 'Жалоб пока нет';
|
||
}
|
||
loadFeedback();
|
||
|
||
// === Sessions ===
|
||
fetch('/api/admin/sessions', {headers: H}).then(r=>r.json()).then(sessions => {
|
||
const table = document.getElementById('sessions');
|
||
for (const s of sessions) {
|
||
const d = new Date(s.last_ts < 1e12 ? s.last_ts * 1000 : s.last_ts);
|
||
const ts = d.toLocaleString('ru-RU', {day:'2-digit',month:'2-digit',year:'2-digit',hour:'2-digit',minute:'2-digit'});
|
||
const tr = document.createElement('tr');
|
||
const q = esc((s.last_question || '').slice(0, 80));
|
||
tr.innerHTML = `<td class="time">${ts}</td><td>${esc(s.username)}</td><td>${s.msg_count}</td><td class="q" title="${q}">${q}</td><td><a href="/?tab=${encodeURIComponent(s.tab_id)}" target="_blank">Открыть</a></td>`;
|
||
table.appendChild(tr);
|
||
}
|
||
}).catch(()=>{});
|
||
|
||
// === Нормативная база (внешние источники) ===
|
||
const NB_FR = {ok:['nb-ok','●','актуально'], aging:['nb-aging','◐','обновление задерживается'],
|
||
stale:['nb-stale','▲','устарело'], error:['nb-error','✕','ошибка'],
|
||
unknown:['nb-none','○','нет данных'], never:['nb-none','○','не проверялось']};
|
||
function nbBadge(fr){ const b=NB_FR[fr]||NB_FR.unknown; return `<span class="nb-badge ${b[0]}">${b[1]} ${b[2]}</span>`; }
|
||
function nbDate(s){ return s ? esc(String(s).slice(0,10)) : '—'; }
|
||
|
||
function renderNormative(d){
|
||
// «Проверено N назад» — зелёный только от свежей проверки
|
||
const c = d.checked, chFr = c.status==='ok'?'ok':(c.status==='stale'?'stale':'never');
|
||
const ago = c.age_days==null ? 'ни разу' : (c.age_days<1 ? 'сегодня' : Math.round(c.age_days)+' дн. назад');
|
||
let rep = d.last_report ? ` · последняя сводка: ${d.last_report.updates} обновл., ${d.last_report.problems} проблем` : '';
|
||
document.getElementById('nb-checked').innerHTML = `Проверка источников: ${nbBadge(chFr)} <span style="font-size:.8rem;color:var(--muted)">${esc(ago)}${esc(rep)}</span>`;
|
||
if (!d.reference_online) document.getElementById('nb-note').textContent = 'Справочник ФГИС сейчас недоступен — периоды/регионы показаны частично.';
|
||
|
||
// Движок: что реально применено к расчёту (скачано ≠ применено)
|
||
const e = d.engine; let eh, ecls='';
|
||
if (e.status==='ok'){ ecls='eng-ok';
|
||
eh = `<b>✓ Расчётный движок считает по периоду: ${esc(e.applied_period)}</b>`
|
||
+ (e.activated_at?` <span style="color:var(--muted);font-size:.8rem">(применено ${nbDate(e.activated_at)})</span>`:'')
|
||
+ (e.behind_pulled?`<br>${nbBadge('aging')} скачан более свежий период — можно применить`:''); }
|
||
else { eh = `<b>⚠ ${esc(e.message)}</b>`; }
|
||
const eng=document.getElementById('nb-engine'); eng.className='nb-engine '+ecls; eng.innerHTML=eh;
|
||
|
||
// Источники
|
||
let html='';
|
||
for (const s of d.sources){
|
||
if (s.kind==='prices'){
|
||
const pct = s.regions_total ? Math.round(100*s.regions_loaded/s.regions_total) : 0;
|
||
const miss = (s.missing_regions&&s.missing_regions.length)
|
||
? `<div class="nb-meta"><span>не загружено: ${s.missing_regions.map(esc).join(', ')}${s.missing_more?` и ещё ${s.missing_more}`:''}</span></div>` : '';
|
||
html += `<div class="nb-src"><h4>${esc(s.label)} ${nbBadge(s.freshness)}</h4>
|
||
<div class="nb-meta">
|
||
<span>Период базы: <b>${esc(s.base_period||'—')}</b></span>
|
||
<span>Загружено: <b>${nbDate(s.last_loaded)}</b></span>
|
||
<span>Регионов: <b>${s.regions_loaded}/${s.regions_total}</b> — ${pct}% (${s.zones} зон)</span>
|
||
</div>
|
||
<div class="nb-bar" title="Загружено ${pct}%"><span style="width:${pct}%"></span><em>${pct}%</em></div>${miss}</div>`;
|
||
} else {
|
||
const cnt = s.mode==='monitor'
|
||
? `Отслеживается: <b>${s.known}</b> ${esc(s.unit)}`
|
||
: `Скачано: <b>${s.downloaded}</b>${s.known?` / известно ${s.known}`:''} ${esc(s.unit)}`;
|
||
const chg = s.source_last_change?`<span>у источника изменено: <b>${nbDate(s.source_last_change)}</b></span>`:'';
|
||
html += `<div class="nb-src"><h4>${esc(s.label)} ${nbBadge(s.freshness)}</h4>
|
||
<div class="nb-meta"><span>${cnt}</span>${chg}</div></div>`;
|
||
}
|
||
}
|
||
document.getElementById('nb-sources').innerHTML = html;
|
||
document.getElementById('nb-storage').textContent = 'Хранилище: '+esc(d.storage_path||'');
|
||
}
|
||
|
||
function loadNormative(){
|
||
document.getElementById('nb-note').textContent = 'Загрузка…';
|
||
fetch('/api/admin/normative-status', {headers:H})
|
||
.then(r=>{ if(!r.ok) throw new Error(r.status); return r.json(); })
|
||
.then(d=>{ document.getElementById('nb-note').textContent=''; renderNormative(d); })
|
||
.catch(()=>{ document.getElementById('nb-note').textContent='Не удалось загрузить статус.'; });
|
||
}
|
||
|
||
async function recheckNormative(){
|
||
const btn=document.getElementById('nb-recheck'); btn.disabled=true;
|
||
const note=document.getElementById('nb-note');
|
||
try{
|
||
const r = await fetch('/api/admin/normative-recheck', {method:'POST', headers:H});
|
||
if(!r.ok) throw new Error(r.status); // 403/500 не должны показывать ложный «запущено»
|
||
note.textContent='Проверка запущена в фоне — по всем регионам это пара минут. Нажми «Обновить», когда пройдёт время.';
|
||
}
|
||
catch(e){ note.textContent='Не удалось запустить проверку (нет прав или ошибка сервера).'; }
|
||
setTimeout(()=>{ btn.disabled=false; }, 5000);
|
||
}
|
||
if (location.hash==='#normative') loadNormative();
|
||
|
||
// Версия UI — единый источник (main.py APP_VERSION → /api/version)
|
||
fetch('/api/version').then(r=>r.json()).then(d=>{
|
||
document.querySelectorAll('.app-version').forEach(e=>e.textContent='v.'+d.version);
|
||
}).catch(()=>{});
|
||
</script>
|
||
</body>
|
||
</html>
|