472 lines
25 KiB
JavaScript
472 lines
25 KiB
JavaScript
/**
|
||
* ===============================================================================
|
||
* FILE: modules/web_api/static/js/sidebar.js
|
||
* ROLE: Контроллер левого сайдбара с 5-хабовой навигацией, реестрами,
|
||
* подробным описанием управления контекстом и интеграцией чата.
|
||
* ===============================================================================
|
||
*/
|
||
|
||
// Глобальная функция безопасного экранирования HTML
|
||
window.escapeHtml = function(str) {
|
||
if (str === null || str === undefined) return '';
|
||
return String(str)
|
||
.replace(/&/g, '&')
|
||
.replace(/</g, '<')
|
||
.replace(/>/g, '>')
|
||
.replace(/"/g, '"')
|
||
.replace(/'/g, ''');
|
||
};
|
||
|
||
window.SidebarManager = {
|
||
currentHub: 'TASKS',
|
||
currentSubTab: {
|
||
'REGISTRIES': 'REMOTE'
|
||
},
|
||
|
||
hubs: [
|
||
{ id: 'TASKS', label: 'Задачи', icon: 'fa-list-check' },
|
||
{ id: 'SNAPSHOTS', label: 'Срезы', icon: 'fa-camera' },
|
||
{ id: 'REGISTRIES', label: 'Реестры', icon: 'fa-address-book' },
|
||
{ id: 'PROMPT', label: 'Промпт', icon: 'fa-terminal' },
|
||
{ id: 'CONTEXT', label: 'Контекст', icon: 'fa-comments' }
|
||
],
|
||
|
||
subTabs: {
|
||
'REGISTRIES': [
|
||
{ id: 'REMOTE', label: 'Удаленщики', icon: 'fa-house-laptop' },
|
||
{ id: 'EXCEPTIONS', label: 'Исключения', icon: 'fa-user-shield' }
|
||
]
|
||
},
|
||
|
||
init() {
|
||
this.renderHeader();
|
||
this.renderContent();
|
||
},
|
||
|
||
setHub(hubId) {
|
||
this.currentHub = hubId;
|
||
this.renderHeader();
|
||
this.renderContent();
|
||
},
|
||
|
||
setSubTab(subTabId) {
|
||
this.currentSubTab[this.currentHub] = subTabId;
|
||
this.renderHeader();
|
||
this.renderContent();
|
||
},
|
||
|
||
renderHeader() {
|
||
const headerContainer = document.getElementById("sidebar-dynamic-header");
|
||
if (!headerContainer) return;
|
||
|
||
// 1. Основные 5 Хабов
|
||
const hubsHtml = `
|
||
<div class="flex items-center border-b border-slate-200 bg-slate-50/80 px-1 pt-1.5 overflow-x-auto gap-0.5">
|
||
${this.hubs.map(h => {
|
||
const isActive = this.currentHub === h.id;
|
||
return `
|
||
<button onclick="SidebarManager.setHub('${h.id}')"
|
||
class="flex-1 py-1.5 px-1 flex flex-col items-center gap-1 border-b-2 font-bold text-[10px] transition ${
|
||
isActive
|
||
? 'border-indigo-600 text-indigo-600 bg-white rounded-t-lg shadow-sm'
|
||
: 'border-transparent text-slate-500 hover:text-slate-800 hover:bg-slate-100/60 rounded-t-lg'
|
||
}">
|
||
<i class="fa-solid ${h.icon} text-xs"></i>
|
||
<span class="truncate">${h.label}</span>
|
||
</button>
|
||
`;
|
||
}).join('')}
|
||
</div>
|
||
`;
|
||
|
||
// 2. Подвкладки (только для хабов, где они требуются, например Реестры)
|
||
let subTabsHtml = '';
|
||
if (this.subTabs[this.currentHub]) {
|
||
const currentActiveSub = this.currentSubTab[this.currentHub] || this.subTabs[this.currentHub][0].id;
|
||
subTabsHtml = `
|
||
<div class="flex items-center gap-1.5 p-1.5 bg-slate-100/90 border-b border-slate-200">
|
||
${this.subTabs[this.currentHub].map(st => {
|
||
const isSubActive = currentActiveSub === st.id;
|
||
return `
|
||
<button onclick="SidebarManager.setSubTab('${st.id}')"
|
||
class="flex-1 py-1 px-2 rounded-md text-[11px] font-semibold flex items-center justify-center gap-1.5 transition ${
|
||
isSubActive
|
||
? 'bg-white text-indigo-700 shadow-sm'
|
||
: 'text-slate-600 hover:text-slate-900 hover:bg-white/50'
|
||
}">
|
||
<i class="fa-solid ${st.icon} text-[10px]"></i>
|
||
<span>${st.label}</span>
|
||
</button>
|
||
`;
|
||
}).join('')}
|
||
</div>
|
||
`;
|
||
}
|
||
|
||
headerContainer.innerHTML = hubsHtml + subTabsHtml;
|
||
},
|
||
|
||
renderContent() {
|
||
const contentContainer = document.getElementById("sidebar-dynamic-content");
|
||
if (!contentContainer) return;
|
||
|
||
contentContainer.scrollTop = 0;
|
||
|
||
switch (this.currentHub) {
|
||
case 'TASKS':
|
||
this.renderTasksView(contentContainer);
|
||
break;
|
||
case 'SNAPSHOTS':
|
||
this.renderSnapshotsView(contentContainer);
|
||
break;
|
||
case 'REGISTRIES':
|
||
this.renderRegistriesView(contentContainer);
|
||
break;
|
||
case 'PROMPT':
|
||
this.renderPromptView(contentContainer);
|
||
break;
|
||
case 'CONTEXT':
|
||
this.renderContextView(contentContainer);
|
||
break;
|
||
default:
|
||
contentContainer.innerHTML = `<div class="p-4 text-xs text-slate-400 text-center">Раздел в разработке</div>`;
|
||
}
|
||
},
|
||
|
||
// =========================================================================
|
||
// ХАБ 1: ЗАДАЧИ
|
||
// =========================================================================
|
||
renderTasksView(container) {
|
||
container.innerHTML = `
|
||
<div id="tasks-list-container" class="flex-1 flex flex-col gap-2">
|
||
<div class="text-center py-10 text-xs text-slate-400">
|
||
<i class="fa-solid fa-spinner fa-spin mr-1"></i> Загрузка задач...
|
||
</div>
|
||
</div>
|
||
`;
|
||
if (window.loadTasks) {
|
||
window.loadTasks();
|
||
}
|
||
},
|
||
|
||
// =========================================================================
|
||
// ХАБ 2: СРЕЗЫ СКУД
|
||
// =========================================================================
|
||
async renderSnapshotsView(container) {
|
||
container.innerHTML = `<div class="text-center py-8 text-xs text-slate-400"><i class="fa-solid fa-spinner fa-spin mr-1"></i> Загрузка срезов...</div>`;
|
||
try {
|
||
const res = await fetch("/api/v1/snapshots", { headers: AuthManager.getAuthHeaders() });
|
||
const data = res.ok ? await res.json() : { snapshots: [] };
|
||
const snaps = data.snapshots || [];
|
||
|
||
if (snaps.length === 0) {
|
||
container.innerHTML = `<div class="text-center py-8 text-xs text-slate-400">Срезы СКУД не найдены</div>`;
|
||
return;
|
||
}
|
||
|
||
const itemsHtml = snaps.map(s => `
|
||
<div class="flex items-center justify-between p-2.5 bg-white border border-slate-200 rounded-xl text-xs gap-2 shadow-sm hover:border-indigo-300 transition">
|
||
<div class="min-w-0 flex-1">
|
||
<div class="flex items-center gap-1.5">
|
||
<span class="font-bold text-slate-800">${escapeHtml(s.snapshot_id)}</span>
|
||
${s.is_final ? '<span class="px-1.5 py-0.2 rounded text-[9px] font-bold bg-amber-50 text-amber-700 border border-amber-200">Финал Y</span>' : ''}
|
||
</div>
|
||
<div class="text-[10px] text-slate-400 mt-0.5">${escapeHtml(s.snapshot_time)} · ${s.record_count || 0} зап.</div>
|
||
</div>
|
||
<button onclick="window.sendChatAction('покажи срез ${escapeHtml(s.snapshot_id)}')" class="px-2 py-1 bg-slate-100 hover:bg-indigo-50 text-slate-600 hover:text-indigo-600 rounded-lg text-[10px] font-semibold transition" title="Открыть в чате">
|
||
Инспекция
|
||
</button>
|
||
</div>
|
||
`).join('');
|
||
|
||
container.innerHTML = `
|
||
<div class="p-2 flex flex-col gap-2">
|
||
<div class="flex items-center justify-between px-1">
|
||
<span class="text-xs font-bold text-slate-700">Всего срезов: ${snaps.length}</span>
|
||
<button onclick="SidebarManager.renderSnapshotsView(document.getElementById('sidebar-dynamic-content'))" class="text-slate-400 hover:text-indigo-600 p-1" title="Обновить">
|
||
<i class="fa-solid fa-arrows-rotate text-xs"></i>
|
||
</button>
|
||
</div>
|
||
<div class="flex flex-col gap-1.5 max-h-[70vh] overflow-y-auto">${itemsHtml}</div>
|
||
</div>
|
||
`;
|
||
} catch (e) {
|
||
container.innerHTML = `<div class="p-4 text-xs text-rose-500 text-center">Ошибка загрузки срезов</div>`;
|
||
}
|
||
},
|
||
|
||
// =========================================================================
|
||
// ХАБ 3: РЕЕСТРЫ (УДАЛЕНЩИКИ + ИСКЛЮЧЕНИЯ)
|
||
// =========================================================================
|
||
renderRegistriesView(container) {
|
||
const subTab = this.currentSubTab['REGISTRIES'] || 'REMOTE';
|
||
if (subTab === 'REMOTE') {
|
||
this.renderRemoteWorkersView(container);
|
||
} else {
|
||
this.renderExceptionsView(container);
|
||
}
|
||
},
|
||
|
||
async renderRemoteWorkersView(container) {
|
||
container.innerHTML = `<div class="text-center py-8 text-xs text-slate-400"><i class="fa-solid fa-spinner fa-spin mr-1"></i> Загрузка удаленщиков...</div>`;
|
||
try {
|
||
const res = await fetch("/api/v1/remote-workers", { headers: AuthManager.getAuthHeaders() });
|
||
const data = res.ok ? await res.json() : { workers: [] };
|
||
const workers = data.workers || [];
|
||
|
||
const listHtml = workers.map(w => {
|
||
const dFrom = w.date_from ? w.date_from : 'сегодня';
|
||
const dTo = w.date_to ? w.date_to : 'бессрочно';
|
||
const periodLabel = (!w.date_to) ? `с ${dFrom} (бессрочно)` : `${dFrom} — ${dTo}`;
|
||
|
||
return `
|
||
<div class="flex items-center justify-between p-2.5 bg-white border border-slate-200 rounded-xl text-xs gap-2 shadow-sm hover:border-emerald-300 transition">
|
||
<div class="min-w-0 flex-1">
|
||
<div class="font-bold text-slate-800 truncate">${escapeHtml(w.fio)}</div>
|
||
<div class="text-[10px] text-slate-400 truncate">${escapeHtml(w.department || 'Все')}</div>
|
||
<div class="mt-0.5 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[9px] font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200">
|
||
<i class="fa-regular fa-calendar-days text-[8px]"></i>
|
||
<span>${escapeHtml(periodLabel)}</span>
|
||
</div>
|
||
</div>
|
||
<div class="flex items-center gap-0.5 shrink-0">
|
||
<button onclick="openRemoteWorkerModal('EDIT', '${escapeHtml(w.fio)}', '${escapeHtml(w.department || 'Все')}', '${escapeHtml(w.date_from || '')}', '${escapeHtml(w.date_to || '')}')"
|
||
class="text-slate-400 hover:text-emerald-600 p-1.5 rounded-lg hover:bg-emerald-50 transition"
|
||
title="Изменить сроки удаленки">
|
||
<i class="fa-solid fa-pen-to-square text-xs"></i>
|
||
</button>
|
||
<button onclick="SidebarManager.deleteRemoteWorker('${escapeHtml(w.fio)}')"
|
||
class="text-slate-400 hover:text-rose-600 p-1.5 rounded-lg hover:bg-rose-50 transition"
|
||
title="Удалить">
|
||
<i class="fa-solid fa-trash-can text-xs"></i>
|
||
</button>
|
||
</div>
|
||
</div>
|
||
`;
|
||
}).join('');
|
||
|
||
container.innerHTML = `
|
||
<div class="p-2 flex flex-col gap-2.5">
|
||
<div class="flex items-center justify-between px-1">
|
||
<span class="text-xs font-bold text-slate-700">В реестре: ${workers.length} чел.</span>
|
||
<button onclick="openRemoteWorkerModal('ADD')" class="px-2 py-1 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-[11px] font-bold shadow-sm flex items-center gap-1 transition">
|
||
<i class="fa-solid fa-plus text-[10px]"></i> Добавить
|
||
</button>
|
||
</div>
|
||
<div class="flex flex-col gap-1.5 max-h-[70vh] overflow-y-auto">
|
||
${workers.length > 0 ? listHtml : '<div class="text-center py-8 text-xs text-slate-400">Список удаленщиков пуст</div>'}
|
||
</div>
|
||
</div>
|
||
`;
|
||
} catch (e) {
|
||
container.innerHTML = `<div class="p-4 text-xs text-rose-500 text-center">Ошибка загрузки реестра удаленщиков</div>`;
|
||
}
|
||
},
|
||
|
||
async deleteRemoteWorker(fio) {
|
||
if (!confirm(`Удалить сотрудника ${fio} из реестра удаленщиков?`)) return;
|
||
try {
|
||
const res = await fetch(`/api/v1/remote-workers?fio=${encodeURIComponent(fio)}`, {
|
||
method: "DELETE",
|
||
headers: AuthManager.getAuthHeaders()
|
||
});
|
||
if (res.ok) {
|
||
this.renderContent();
|
||
} else {
|
||
alert("Ошибка удаления");
|
||
}
|
||
} catch (e) {
|
||
alert("Ошибка сети");
|
||
}
|
||
},
|
||
|
||
async renderExceptionsView(container) {
|
||
container.innerHTML = `<div class="text-center py-8 text-xs text-slate-400"><i class="fa-solid fa-spinner fa-spin mr-1"></i> Загрузка исключений...</div>`;
|
||
try {
|
||
const res = await fetch("/api/v1/exceptions/", { headers: AuthManager.getAuthHeaders() });
|
||
const data = res.ok ? await res.json() : {};
|
||
const categories = [
|
||
{ key: 'include_fio', title: 'Белый список (ФИО)' },
|
||
{ key: 'fio', title: 'Исключенные сотрудники (ФИО)' },
|
||
{ key: 'departments', title: 'Исключенные отделы' },
|
||
{ key: 'positions', title: 'Исключенные должности' }
|
||
];
|
||
|
||
const html = categories.map(cat => {
|
||
const items = data[cat.key] || [];
|
||
return `
|
||
<div class="bg-white border border-slate-200 rounded-xl p-3 flex flex-col gap-2 shadow-sm">
|
||
<div class="flex items-center justify-between">
|
||
<span class="font-bold text-xs text-slate-700">${cat.title} (${items.length})</span>
|
||
<button onclick="SidebarManager.addExceptionPrompt('${cat.key}')" class="text-indigo-600 hover:text-indigo-800 text-xs font-bold">
|
||
+ Добавить
|
||
</button>
|
||
</div>
|
||
<div class="flex flex-wrap gap-1">
|
||
${items.map(it => `
|
||
<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] bg-slate-100 text-slate-700 border border-slate-200">
|
||
${escapeHtml(it)}
|
||
<button onclick="SidebarManager.deleteExceptionItem('${cat.key}', '${escapeHtml(it)}')" class="hover:text-rose-600 ml-0.5">×</button>
|
||
</span>
|
||
`).join('') || '<span class="text-[10px] text-slate-400">Пусто</span>'}
|
||
</div>
|
||
</div>
|
||
`;
|
||
}).join('');
|
||
|
||
container.innerHTML = `<div class="p-2 flex flex-col gap-2 max-h-[75vh] overflow-y-auto">${html}</div>`;
|
||
} catch (e) {
|
||
container.innerHTML = `<div class="p-4 text-xs text-rose-500 text-center">Ошибка загрузки исключений</div>`;
|
||
}
|
||
},
|
||
|
||
async addExceptionPrompt(category) {
|
||
const val = prompt(`Введите значение для категории [${category}]:`);
|
||
if (!val || !val.trim()) return;
|
||
try {
|
||
const res = await fetch("/api/v1/exceptions/", {
|
||
method: "POST",
|
||
headers: AuthManager.getAuthHeaders(),
|
||
body: JSON.stringify({ category: category, value: val.trim() })
|
||
});
|
||
if (res.ok) this.renderContent();
|
||
else alert("Ошибка добавления");
|
||
} catch (e) {
|
||
alert("Ошибка сети");
|
||
}
|
||
},
|
||
|
||
async deleteExceptionItem(category, value) {
|
||
if (!confirm(`Удалить "${value}" из ${category}?`)) return;
|
||
try {
|
||
const res = await fetch(`/api/v1/exceptions/?category=${encodeURIComponent(category)}&value=${encodeURIComponent(value)}`, {
|
||
method: "DELETE",
|
||
headers: AuthManager.getAuthHeaders()
|
||
});
|
||
if (res.ok) this.renderContent();
|
||
else alert("Ошибка удаления");
|
||
} catch (e) {
|
||
alert("Ошибка сети");
|
||
}
|
||
},
|
||
|
||
// =========================================================================
|
||
// ХАБ 4: СИСТЕМНЫЙ ПРОМПТ И БАЗА ЗНАНИЙ
|
||
// =========================================================================
|
||
renderPromptView(container) {
|
||
container.innerHTML = `
|
||
<div class="p-3 flex flex-col gap-3">
|
||
<div class="text-[11px] text-slate-600 leading-relaxed bg-white border border-slate-200 rounded-xl p-3 shadow-sm flex flex-col gap-1.5">
|
||
<span class="font-bold text-slate-800 flex items-center gap-1.5">
|
||
<i class="fa-solid fa-sliders text-indigo-600"></i> Инструкции и регламенты ИИ
|
||
</span>
|
||
<span>Управление системными директивами, базой знаний и правилами арбитража кадровых аномалий СКУД и 1С.</span>
|
||
</div>
|
||
|
||
<div class="flex flex-col gap-2">
|
||
<button onclick="window.sendChatAction('покажи системный промпт')"
|
||
class="w-full py-2 px-3 bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white rounded-xl text-xs font-bold shadow-sm flex items-center justify-center gap-2 transition">
|
||
<i class="fa-solid fa-terminal text-xs"></i>
|
||
<span>Показать системный промпт</span>
|
||
</button>
|
||
|
||
<button onclick="window.sendChatAction('покажи правила компании')"
|
||
class="w-full py-2 px-3 bg-white hover:bg-slate-50 active:bg-slate-100 text-slate-700 border border-slate-300 rounded-xl text-xs font-bold shadow-sm flex items-center justify-center gap-2 transition">
|
||
<i class="fa-solid fa-book-bookmark text-emerald-600 text-xs"></i>
|
||
<span>База знаний и правила компании</span>
|
||
</button>
|
||
</div>
|
||
</div>
|
||
`;
|
||
},
|
||
|
||
// =========================================================================
|
||
// ХАБ 5: УПРАВЛЕНИЕ КОНТЕКСТОМ СЕССИИ (С ПОДРОБНЫМ ОПИСАНИЕМ)
|
||
// =========================================================================
|
||
renderContextView(container) {
|
||
container.innerHTML = `
|
||
<div class="p-3 flex flex-col gap-3">
|
||
<div class="text-[11px] text-slate-600 leading-relaxed bg-white border border-slate-200 rounded-xl p-3 shadow-sm flex flex-col gap-2">
|
||
<span class="font-bold text-slate-800 flex items-center gap-1.5">
|
||
<i class="fa-solid fa-brain text-indigo-600"></i> Управление памятью чата
|
||
</span>
|
||
|
||
<div class="flex flex-col gap-1.5 pt-1 border-t border-slate-100">
|
||
<div class="flex items-start gap-1.5">
|
||
<span class="w-2 h-2 rounded-full bg-amber-500 mt-1 shrink-0"></span>
|
||
<div>
|
||
<span class="font-bold text-slate-700">Мягкая очистка:</span>
|
||
<span class="text-slate-500"> удаляет только служебные транзакции (карточки срезов, временные превью промпта, промежуточные подтверждения). Смысловой диалог пользователя сохраняется.</span>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="flex items-start gap-1.5">
|
||
<span class="w-2 h-2 rounded-full bg-rose-500 mt-1 shrink-0"></span>
|
||
<div>
|
||
<span class="font-bold text-slate-700">Полный сброс:</span>
|
||
<span class="text-slate-500"> полностью стирает контекст активной сессии из базы данных и очищает окно чата. Используется при переходе к новой дате или новой теме анализа.</span>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="flex flex-col gap-2">
|
||
<button onclick="window.sendChatAction('очисти контекст')"
|
||
class="w-full py-2 px-3 bg-amber-500 hover:bg-amber-600 active:bg-amber-700 text-white rounded-xl text-xs font-bold shadow-sm flex items-center justify-center gap-2 transition">
|
||
<i class="fa-solid fa-broom text-xs"></i>
|
||
<span>Мягкая очистка контекста</span>
|
||
</button>
|
||
|
||
<button onclick="SidebarManager.handleFullSessionReset()"
|
||
class="w-full py-2 px-3 bg-rose-600 hover:bg-rose-700 active:bg-rose-800 text-white rounded-xl text-xs font-bold shadow-sm flex items-center justify-center gap-2 transition">
|
||
<i class="fa-solid fa-trash-arrow-up text-xs"></i>
|
||
<span>Полный сброс сессии</span>
|
||
</button>
|
||
</div>
|
||
</div>
|
||
`;
|
||
},
|
||
|
||
async handleFullSessionReset() {
|
||
if (!confirm("Вы действительно хотите полностью очистить историю диалога и сбросить сессию чата?")) {
|
||
return;
|
||
}
|
||
|
||
// Очищаем локальное окно чата до стартового приветствия
|
||
const chatContainer = document.getElementById("chat-messages-container");
|
||
if (chatContainer) {
|
||
chatContainer.innerHTML = `
|
||
<div class="flex gap-3 max-w-4xl mx-auto w-full">
|
||
<div class="w-7 h-7 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm mt-0.5">
|
||
<i class="fa-solid fa-robot text-xs"></i>
|
||
</div>
|
||
<div class="flex-1 bg-white border border-slate-200 rounded-2xl rounded-tl-none p-4 shadow-sm">
|
||
<div class="text-[10px] font-bold text-indigo-600 uppercase tracking-wider mb-1">ИИ-ассистент SCUD Orion AI</div>
|
||
<div class="text-xs text-slate-700 leading-relaxed">
|
||
Сессия чата очищена. Память ассистента сброшена. Задайте новый вопрос или команду.
|
||
</div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
}
|
||
|
||
try {
|
||
await fetch("/api/v1/chat", {
|
||
method: "POST",
|
||
headers: AuthManager.getAuthHeaders(),
|
||
body: JSON.stringify({
|
||
message: "сбрось сессию полностью",
|
||
session_id: "web_session_main"
|
||
})
|
||
});
|
||
} catch (e) {
|
||
console.error("Ошибка запроса сброса сессии:", e);
|
||
}
|
||
}
|
||
};
|
||
|
||
document.addEventListener("DOMContentLoaded", () => {
|
||
if (window.AuthManager && AuthManager.isAuthenticated()) {
|
||
SidebarManager.init();
|
||
}
|
||
}); |