feat(web): стабилизация UI, Gemini-скроллинг, роутеры контекста/снапшотов и актуализация роадмапа
This commit is contained in:
@@ -1,62 +1,75 @@
|
||||
/**
|
||||
* ===============================================================================
|
||||
* FILE: static/js/auth.js
|
||||
* ROLE: Управление сессией пользователя, токенами и корректным выходом (Logout).
|
||||
* FILE: modules/web_api/static/js/auth.js
|
||||
* ROLE: Менеджер сессий, токенов, ФИО и авторизационных заголовков.
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
const AUTH_STORAGE_KEY = "scud_auth_token";
|
||||
const USERNAME_STORAGE_KEY = "scud_username";
|
||||
const FULLNAME_STORAGE_KEY = "scud_full_name";
|
||||
const IS_ADMIN_STORAGE_KEY = "scud_is_admin";
|
||||
const USER_ID_STORAGE_KEY = "scud_user_id";
|
||||
|
||||
const AuthManager = {
|
||||
getToken() {
|
||||
let token = localStorage.getItem("auth_token") || localStorage.getItem("token");
|
||||
if (!token) {
|
||||
// Если токена нет — инициализируем рабочий дефолтный токен
|
||||
token = "dev_token_1";
|
||||
localStorage.setItem("auth_token", token);
|
||||
localStorage.setItem("user_id", "1");
|
||||
}
|
||||
return token;
|
||||
return localStorage.getItem(AUTH_STORAGE_KEY) || "";
|
||||
},
|
||||
|
||||
getUserId() {
|
||||
return parseInt(localStorage.getItem("user_id") || "1", 10);
|
||||
const uid = localStorage.getItem(USER_ID_STORAGE_KEY);
|
||||
return uid ? parseInt(uid, 10) : 1;
|
||||
},
|
||||
|
||||
getUsername() {
|
||||
return localStorage.getItem(USERNAME_STORAGE_KEY) || "";
|
||||
},
|
||||
|
||||
getFullName() {
|
||||
return localStorage.getItem(FULLNAME_STORAGE_KEY) || this.getUsername() || "Пользователь";
|
||||
},
|
||||
|
||||
isAdmin() {
|
||||
return localStorage.getItem(IS_ADMIN_STORAGE_KEY) === "true";
|
||||
},
|
||||
|
||||
isAuthenticated() {
|
||||
return Boolean(this.getToken());
|
||||
},
|
||||
|
||||
setSession(token, username, fullName, isAdmin, userId = 1) {
|
||||
localStorage.setItem(AUTH_STORAGE_KEY, token);
|
||||
localStorage.setItem(USERNAME_STORAGE_KEY, username);
|
||||
localStorage.setItem(FULLNAME_STORAGE_KEY, fullName || username);
|
||||
localStorage.setItem(IS_ADMIN_STORAGE_KEY, String(isAdmin));
|
||||
localStorage.setItem(USER_ID_STORAGE_KEY, String(userId));
|
||||
localStorage.setItem("scud_api_auth_token", token);
|
||||
localStorage.setItem("auth_token", token);
|
||||
},
|
||||
|
||||
getAuthHeaders() {
|
||||
const token = this.getToken();
|
||||
const headers = { "Content-Type": "application/json" };
|
||||
if (token) {
|
||||
headers["Authorization"] = `Bearer ${token}`;
|
||||
}
|
||||
return headers;
|
||||
},
|
||||
|
||||
logout() {
|
||||
console.log("[Auth] Выполняется выход из учетной записи...");
|
||||
|
||||
// 1. Полная очистка хранилищ браузера
|
||||
localStorage.removeItem("auth_token");
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("user_id");
|
||||
console.log("[Auth] Полный выход из системы...");
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
|
||||
// 2. Сброс авторизационных cookies (если присутствуют)
|
||||
document.cookie.split(";").forEach((cookie) => {
|
||||
const eqPos = cookie.indexOf("=");
|
||||
const name = eqPos > -1 ? cookie.substr(0, eqPos).trim() : cookie.trim();
|
||||
document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;
|
||||
});
|
||||
|
||||
// 3. Перезагрузка страницы для сброса состояния интерфейса
|
||||
window.location.reload();
|
||||
},
|
||||
|
||||
init() {
|
||||
// Привязка клика ко всем элементам с классом или id logout
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const logoutBtns = document.querySelectorAll("#logout-btn, .logout-btn, [data-action='logout']");
|
||||
logoutBtns.forEach(btn => {
|
||||
btn.addEventListener("click", (e) => {
|
||||
e.preventDefault();
|
||||
AuthManager.logout();
|
||||
});
|
||||
});
|
||||
});
|
||||
window.location.href = "/";
|
||||
}
|
||||
};
|
||||
|
||||
// Инициализация при загрузке скрипта
|
||||
AuthManager.init();
|
||||
|
||||
// Глобальная доступность функции для onclick в HTML
|
||||
window.AuthManager = AuthManager;
|
||||
window.logout = () => AuthManager.logout();
|
||||
@@ -1,67 +1,586 @@
|
||||
/**
|
||||
* ===============================================================================
|
||||
* FILE: static/js/chat/core.js
|
||||
* ROLE: Отправка сообщений в API с токеном и обработка ошибок.
|
||||
* FILE: modules/web_api/static/js/chat/core.js
|
||||
* ROLE: Ядро чата: полноэкранный Drag-and-Drop оверлей, авто-высота инпута (24px),
|
||||
* надежный расчет скролла вопроса к верху окна, крупный шрифт text-sm.
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
async function sendMessage(userMessageText) {
|
||||
const chatInput = document.getElementById("chat-input");
|
||||
const message = userMessageText || (chatInput ? chatInput.value.trim() : "");
|
||||
if (!message) return;
|
||||
let currentAttachedFile = null;
|
||||
|
||||
if (chatInput && !userMessageText) {
|
||||
chatInput.value = "";
|
||||
const CHAT_INPUT_STORAGE_KEY = "scud_chat_input_history";
|
||||
let chatInputHistory = JSON.parse(localStorage.getItem(CHAT_INPUT_STORAGE_KEY) || "[]");
|
||||
let chatHistoryIndex = -1;
|
||||
let temporaryCurrentInput = "";
|
||||
|
||||
function saveCommandToHistory(commandText) {
|
||||
if (!commandText || !commandText.trim()) return;
|
||||
const cleanCmd = commandText.trim();
|
||||
if (cleanCmd.startsWith("action:save_draft_")) return;
|
||||
|
||||
chatInputHistory = chatInputHistory.filter(item => item !== cleanCmd);
|
||||
chatInputHistory.push(cleanCmd);
|
||||
if (chatInputHistory.length > 50) chatInputHistory.shift();
|
||||
localStorage.setItem(CHAT_INPUT_STORAGE_KEY, JSON.stringify(chatInputHistory));
|
||||
chatHistoryIndex = -1;
|
||||
}
|
||||
|
||||
// ⭐️ ЕДИНАЯ ФУНКЦИЯ СКРОЛЛА: плавное выравнивание вопроса к верхней границе
|
||||
function scrollToUserMessageTop() {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return;
|
||||
|
||||
const userBubbles = container.querySelectorAll(".user-chat-bubble");
|
||||
const targetEl = userBubbles[userBubbles.length - 1] || container.lastElementChild;
|
||||
if (!targetEl) return;
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
setTimeout(() => {
|
||||
const containerTop = container.getBoundingClientRect().top;
|
||||
const targetTop = targetEl.getBoundingClientRect().top;
|
||||
|
||||
const targetScroll = container.scrollTop + (targetTop - containerTop) - 16;
|
||||
|
||||
container.scrollTo({
|
||||
top: Math.max(0, targetScroll),
|
||||
behavior: 'smooth'
|
||||
});
|
||||
}, 50);
|
||||
});
|
||||
}
|
||||
|
||||
function updateInputHeightAndFade(textarea) {
|
||||
if (!textarea) return;
|
||||
|
||||
if (!textarea.value || textarea.value.trim() === '') {
|
||||
textarea.style.height = '24px';
|
||||
textarea.style.overflowY = 'hidden';
|
||||
textarea.style.maskImage = 'none';
|
||||
textarea.style.webkitMaskImage = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
// Отображаем сообщение пользователя в чате
|
||||
if (typeof appendMessageToUI === "function") {
|
||||
appendMessageToUI("user", message);
|
||||
textarea.style.height = 'auto';
|
||||
const minHeight = 24;
|
||||
const maxHeight = 120;
|
||||
const currentScrollHeight = textarea.scrollHeight;
|
||||
|
||||
if (currentScrollHeight <= minHeight + 2) {
|
||||
textarea.style.height = minHeight + 'px';
|
||||
textarea.style.overflowY = 'hidden';
|
||||
textarea.style.maskImage = 'none';
|
||||
textarea.style.webkitMaskImage = 'none';
|
||||
} else if (currentScrollHeight > maxHeight) {
|
||||
textarea.style.height = maxHeight + 'px';
|
||||
textarea.style.overflowY = 'auto';
|
||||
textarea.style.maskImage = 'linear-gradient(to bottom, transparent 0%, black 14px, black 100%)';
|
||||
textarea.style.webkitMaskImage = 'linear-gradient(to bottom, transparent 0%, black 14px, black 100%)';
|
||||
} else {
|
||||
textarea.style.height = currentScrollHeight + 'px';
|
||||
textarea.style.overflowY = 'hidden';
|
||||
textarea.style.maskImage = 'none';
|
||||
textarea.style.webkitMaskImage = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function appendUserMessage(text, filename = null) {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return;
|
||||
|
||||
const msgId = 'user-msg-' + Date.now();
|
||||
let fileBadge = '';
|
||||
if (filename) {
|
||||
fileBadge = `
|
||||
<div class="inline-flex items-center gap-1.5 px-2.5 py-1 mb-2 bg-indigo-700/80 rounded-lg text-xs font-semibold text-white shadow-xs">
|
||||
<i class="fa-solid fa-paperclip text-xs"></i>
|
||||
<span class="truncate max-w-xs">${escapeHtml(filename)}</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// Подготовка заголовков с гарантированным токеном
|
||||
const token = (typeof AuthManager !== "undefined") ? AuthManager.getToken() : (localStorage.getItem("auth_token") || "dev_token_1");
|
||||
const userId = (typeof AuthManager !== "undefined") ? AuthManager.getUserId() : parseInt(localStorage.getItem("user_id") || "1", 10);
|
||||
const sessionId = localStorage.getItem("chat_session_id") || "web_session_main";
|
||||
const msgHtml = `
|
||||
<div id="${msgId}" class="user-chat-bubble flex gap-3 max-w-4xl mx-auto w-full justify-end pt-3 scroll-mt-4">
|
||||
<div class="flex-1 max-w-2xl bg-indigo-600 text-white rounded-2xl rounded-tr-none p-4 shadow-sm">
|
||||
${fileBadge}
|
||||
<div class="text-sm leading-relaxed whitespace-pre-wrap">${escapeHtml(text)}</div>
|
||||
</div>
|
||||
<div class="w-8 h-8 rounded-lg bg-slate-200 text-slate-600 flex items-center justify-center shrink-0 shadow-sm mt-0.5 font-bold text-sm">
|
||||
<i class="fa-solid fa-user"></i>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
container.insertAdjacentHTML("beforeend", msgHtml);
|
||||
}
|
||||
|
||||
function appendAssistantLoading() {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return null;
|
||||
|
||||
const loadingId = 'loading-' + Date.now();
|
||||
const html = `
|
||||
<div id="${loadingId}" class="flex gap-3 max-w-4xl mx-auto w-full pt-1">
|
||||
<div class="w-8 h-8 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-sm"></i>
|
||||
</div>
|
||||
<div class="flex-1 bg-white border border-slate-200 rounded-2xl rounded-tl-none p-4 shadow-sm">
|
||||
<div class="text-sm text-slate-500 flex items-center gap-2">
|
||||
<i class="fa-solid fa-spinner fa-spin text-indigo-600"></i>
|
||||
<span>ИИ обрабатывает запрос...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
container.insertAdjacentHTML("beforeend", html);
|
||||
return loadingId;
|
||||
}
|
||||
|
||||
function appendAssistantMessage(text, buttons = [], actionPayload = null) {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return;
|
||||
|
||||
let payloadHtml = '';
|
||||
let isHtmlBody = false;
|
||||
|
||||
if (actionPayload) {
|
||||
if (actionPayload.type === 'SNAPSHOTS_CARD' && typeof renderSnapshotsCard === 'function') {
|
||||
payloadHtml = renderSnapshotsCard(actionPayload.data);
|
||||
} else if (actionPayload.type === 'TASK_INTERACTIVE_CARD' && typeof renderInteractiveTaskCard === 'function') {
|
||||
payloadHtml = renderInteractiveTaskCard(actionPayload.tasks);
|
||||
} else if (actionPayload.type === 'FILE_DOWNLOAD_CARD') {
|
||||
const dlUrl = actionPayload.download_url || '#';
|
||||
const fName = actionPayload.filename || 'ROADMAP.md';
|
||||
const count = actionPayload.tasks_count || '';
|
||||
payloadHtml = `
|
||||
<div class="mt-3 p-3.5 bg-indigo-50/80 border border-indigo-200 rounded-xl flex items-center justify-between gap-3 shadow-sm">
|
||||
<div class="flex items-center gap-3 min-w-0">
|
||||
<div class="w-9 h-9 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm">
|
||||
<i class="fa-solid fa-file-lines text-base"></i>
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-bold text-slate-800 truncate">${escapeHtml(fName)}</div>
|
||||
<div class="text-xs text-slate-500">Задач выгружено: ${count} шт. · Markdown</div>
|
||||
</div>
|
||||
</div>
|
||||
<a href="${dlUrl}" download="${escapeHtml(fName)}" target="_blank"
|
||||
class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white rounded-lg text-xs font-bold shadow-sm transition flex items-center gap-1.5 shrink-0">
|
||||
<i class="fa-solid fa-download text-xs"></i>
|
||||
<span>Скачать файл</span>
|
||||
</a>
|
||||
</div>
|
||||
`;
|
||||
} else if (actionPayload.type === 'SNAPSHOT_INSPECT_CARD') {
|
||||
const records = actionPayload.records || [];
|
||||
const inspectTableId = 'inspect-table-' + Date.now();
|
||||
const searchInputId = 'inspect-search-' + Date.now();
|
||||
|
||||
const rowsHtml = records.map((r, idx) => `
|
||||
<tr class="inspect-row border-b border-slate-100 text-xs ${r.is_present ? 'bg-white' : 'bg-slate-50/60'} hover:bg-indigo-50/40"
|
||||
data-fio="${escapeHtml(r.fio).toLowerCase()}" data-dept="${escapeHtml(r.department).toLowerCase()}">
|
||||
<td class="p-2.5 text-slate-400 text-center font-mono w-10">${idx + 1}</td>
|
||||
<td class="p-2.5 font-medium text-slate-800">${escapeHtml(r.fio)}</td>
|
||||
<td class="p-2.5 text-slate-500 text-center">${escapeHtml(r.department)}</td>
|
||||
<td class="p-2.5 text-center ${r.time_in !== 'Нет входа' ? 'font-bold text-emerald-700' : 'text-slate-400'}">${escapeHtml(r.time_in)}</td>
|
||||
<td class="p-2.5 text-center text-slate-500">${escapeHtml(r.first_activity)}</td>
|
||||
<td class="p-2.5 text-center ${r.time_out !== 'Нет выхода' ? 'font-bold text-slate-800' : 'text-slate-400'}">${escapeHtml(r.time_out)}</td>
|
||||
<td class="p-2.5 text-center font-mono text-slate-600">${escapeHtml(r.in_building)}</td>
|
||||
<td class="p-2.5 text-center font-bold">${r.is_present ? '<span class="text-emerald-600">✓ Да</span>' : '<span class="text-slate-400">Нет</span>'}</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
|
||||
payloadHtml = `
|
||||
<div class="mt-3 bg-white border border-slate-200 rounded-xl overflow-hidden shadow-sm flex flex-col">
|
||||
<div class="px-4 py-3 bg-slate-100/90 border-b border-slate-200 flex items-center justify-between gap-2 flex-wrap">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-sm font-bold text-slate-800">Срез #${escapeHtml(actionPayload.snapshot_id)}</span>
|
||||
<span class="text-xs text-slate-500">· Всего: ${records.length} чел. (Присутствуют: ${actionPayload.present_count || 0})</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="text" id="${searchInputId}" placeholder="Поиск в срезе (ФИО / отдел)..."
|
||||
oninput="window.filterInspectTable('${inspectTableId}', this.value)"
|
||||
class="text-xs px-3 py-1.5 bg-white border border-slate-300 rounded-lg focus:outline-none focus:border-indigo-500 w-60" />
|
||||
<button onclick="window.sendChatAction('покажи срезы')" class="text-xs text-indigo-600 hover:underline font-semibold">Все срезы</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="max-h-96 overflow-y-auto">
|
||||
<table id="${inspectTableId}" class="w-full text-left border-collapse">
|
||||
<thead class="bg-slate-50 text-[11px] uppercase text-slate-500 sticky top-0 border-b border-slate-200 shadow-xs">
|
||||
<tr>
|
||||
<th class="p-2.5 text-center w-10">№</th>
|
||||
<th class="p-2.5">Сотрудник</th>
|
||||
<th class="p-2.5 text-center">Отдел</th>
|
||||
<th class="p-2.5 text-center">Вход</th>
|
||||
<th class="p-2.5 text-center">Активность</th>
|
||||
<th class="p-2.5 text-center">Выход</th>
|
||||
<th class="p-2.5 text-center">В здании</th>
|
||||
<th class="p-2.5 text-center">Статус</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>${rowsHtml}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else if (actionPayload.type === 'PROMPT_EDITOR') {
|
||||
const draftText = actionPayload.raw_draft || actionPayload.baseline_prompt || '';
|
||||
const editorId = 'prompt-editor-' + Date.now();
|
||||
payloadHtml = `
|
||||
<div class="mt-3 p-3.5 bg-slate-50 border border-slate-300 rounded-xl flex flex-col gap-2 shadow-inner">
|
||||
<div class="flex items-center justify-between text-xs font-bold text-slate-700">
|
||||
<span><i class="fa-solid fa-pen-to-square text-indigo-600 mr-1"></i> Инлайн-редактор системного промпта:</span>
|
||||
<span class="text-[11px] text-slate-400 font-normal">Прямое редактирование текста</span>
|
||||
</div>
|
||||
<textarea id="${editorId}" rows="14"
|
||||
class="w-full text-xs font-mono p-3 border border-slate-300 rounded-lg focus:outline-none focus:border-indigo-500 bg-white leading-relaxed resize-y">${escapeHtml(draftText)}</textarea>
|
||||
<div class="flex items-center justify-end gap-2 pt-1">
|
||||
<button type="button" onclick="window.sendChatAction('отмена')" class="px-3.5 py-1.5 text-xs text-slate-600 hover:bg-slate-200 rounded-lg transition font-medium">Отменить</button>
|
||||
<button type="button" onclick="window.submitPromptDraftToDiff('${editorId}')" class="px-4 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-bold shadow transition flex items-center gap-1.5">
|
||||
<i class="fa-solid fa-eye text-xs"></i>
|
||||
<span>Показать превью изменений</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else if (actionPayload.type === 'RULES_EDITOR') {
|
||||
const draftText = actionPayload.raw_draft || actionPayload.baseline_prompt || '';
|
||||
const editorId = 'rules-editor-' + Date.now();
|
||||
payloadHtml = `
|
||||
<div class="mt-3 p-3.5 bg-slate-50 border border-slate-300 rounded-xl flex flex-col gap-2 shadow-inner">
|
||||
<div class="flex items-center justify-between text-xs font-bold text-slate-700">
|
||||
<span><i class="fa-solid fa-book-bookmark text-emerald-600 mr-1"></i> Редактор базы знаний и правил компании:</span>
|
||||
<span class="text-[11px] text-slate-400 font-normal">Прямое изменение правил кадрового арбитража</span>
|
||||
</div>
|
||||
<textarea id="${editorId}" rows="12"
|
||||
class="w-full text-xs font-mono p-3 border border-slate-300 rounded-lg focus:outline-none focus:border-emerald-500 bg-white leading-relaxed resize-y">${escapeHtml(draftText)}</textarea>
|
||||
<div class="flex items-center justify-end gap-2 pt-1">
|
||||
<button type="button" onclick="window.sendChatAction('отмена')" class="px-3.5 py-1.5 text-xs text-slate-600 hover:bg-slate-200 rounded-lg transition font-medium">Отменить</button>
|
||||
<button type="button" onclick="window.submitRulesDraftToDiff('${editorId}')" class="px-4 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-bold shadow transition flex items-center gap-1.5">
|
||||
<i class="fa-solid fa-eye text-xs"></i>
|
||||
<span>Показать превью изменений</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else if (actionPayload.type === 'PROMPT_PREVIEW') {
|
||||
isHtmlBody = true;
|
||||
}
|
||||
}
|
||||
|
||||
let buttonsHtml = '';
|
||||
if (!actionPayload || (actionPayload.type !== 'PROMPT_EDITOR' && actionPayload.type !== 'RULES_EDITOR')) {
|
||||
const allButtons = (buttons && buttons.length > 0) ? buttons : (actionPayload && actionPayload.buttons ? actionPayload.buttons : []);
|
||||
if (allButtons && Array.isArray(allButtons) && allButtons.length > 0) {
|
||||
buttonsHtml = `
|
||||
<div class="flex flex-wrap gap-2 mt-3.5 pt-2.5 border-t border-slate-100">
|
||||
${allButtons.map(b => `
|
||||
<button onclick="window.sendChatAction('${escapeHtml(b.value || b.action || b.title || '')}')"
|
||||
class="px-3 py-1.5 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 rounded-lg text-xs font-semibold border border-indigo-200 transition">
|
||||
${escapeHtml(b.label || b.title || b.action)}
|
||||
</button>
|
||||
`).join('')}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
const bodyContent = isHtmlBody ? text : escapeHtml(text);
|
||||
|
||||
const html = `
|
||||
<div class="flex gap-3 max-w-4xl mx-auto w-full pt-1">
|
||||
<div class="w-8 h-8 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-sm"></i>
|
||||
</div>
|
||||
<div class="flex-1 bg-white border border-slate-200 rounded-2xl rounded-tl-none p-4 shadow-sm min-w-0">
|
||||
<div class="text-[11px] font-bold text-indigo-600 uppercase tracking-wider mb-1.5">ИИ-ассистент SCUD Orion AI</div>
|
||||
<div class="text-sm text-slate-800 leading-relaxed whitespace-pre-wrap">${bodyContent}</div>
|
||||
${payloadHtml}
|
||||
${buttonsHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
container.insertAdjacentHTML("beforeend", html);
|
||||
}
|
||||
|
||||
window.filterInspectTable = function(tableId, query) {
|
||||
const table = document.getElementById(tableId);
|
||||
if (!table) return;
|
||||
const q = (query || '').trim().toLowerCase();
|
||||
const rows = table.querySelectorAll('.inspect-row');
|
||||
rows.forEach(r => {
|
||||
const fio = r.getAttribute('data-fio') || '';
|
||||
const dept = r.getAttribute('data-dept') || '';
|
||||
if (!q || fio.includes(q) || dept.includes(q)) {
|
||||
r.classList.remove('hidden');
|
||||
} else {
|
||||
r.classList.add('hidden');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
window.sendChatAction = function(actionText) {
|
||||
if (!actionText || !actionText.trim()) return;
|
||||
const input = document.getElementById("user-input");
|
||||
if (input) {
|
||||
input.value = actionText.trim();
|
||||
updateInputHeightAndFade(input);
|
||||
}
|
||||
window.sendMessage();
|
||||
};
|
||||
|
||||
window.submitPromptDraftToDiff = function(editorId) {
|
||||
const textarea = document.getElementById(editorId);
|
||||
if (!textarea) return;
|
||||
const newText = textarea.value.trim();
|
||||
if (!newText) {
|
||||
alert("Текст системного промпта не может быть пустым");
|
||||
return;
|
||||
}
|
||||
|
||||
const command = `action:save_draft_prompt:::${newText}`;
|
||||
const input = document.getElementById("user-input");
|
||||
if (input) input.value = command;
|
||||
window.sendMessage();
|
||||
};
|
||||
|
||||
window.submitRulesDraftToDiff = function(editorId) {
|
||||
const textarea = document.getElementById(editorId);
|
||||
if (!textarea) return;
|
||||
const newText = textarea.value.trim();
|
||||
if (!newText) {
|
||||
alert("Правила не могут быть пустыми");
|
||||
return;
|
||||
}
|
||||
|
||||
const command = `action:save_draft_rules:::${newText}`;
|
||||
const input = document.getElementById("user-input");
|
||||
if (input) input.value = command;
|
||||
window.sendMessage();
|
||||
};
|
||||
|
||||
window.sendMessage = async function() {
|
||||
const input = document.getElementById("user-input");
|
||||
if (!input) return;
|
||||
|
||||
const messageText = input.value.trim();
|
||||
const fileToSend = currentAttachedFile;
|
||||
|
||||
if (!messageText && !fileToSend) return;
|
||||
|
||||
saveCommandToHistory(messageText);
|
||||
|
||||
input.value = "";
|
||||
input.style.height = '24px';
|
||||
input.style.overflowY = 'hidden';
|
||||
input.style.maskImage = 'none';
|
||||
input.style.webkitMaskImage = 'none';
|
||||
window.clearAttachedFile();
|
||||
|
||||
// 1. Отрисовка сообщения пользователя в ленте
|
||||
if (!messageText.startsWith("action:save_draft_prompt:::") && !messageText.startsWith("action:save_draft_rules:::")) {
|
||||
appendUserMessage(
|
||||
messageText || (fileToSend ? `Прикреплен файл: ${fileToSend.name}` : ''),
|
||||
fileToSend ? fileToSend.name : null
|
||||
);
|
||||
} else {
|
||||
appendUserMessage("Сформировать предпросмотр изменений");
|
||||
}
|
||||
|
||||
// 2. Вставка лоадера
|
||||
const loadingId = appendAssistantLoading();
|
||||
|
||||
// 3. Вызов точного скролла
|
||||
scrollToUserMessageTop();
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/v1/chat", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
message: message,
|
||||
session_id: sessionId,
|
||||
user_id: userId
|
||||
})
|
||||
let res;
|
||||
if (fileToSend) {
|
||||
const formData = new FormData();
|
||||
formData.append("file", fileToSend);
|
||||
formData.append("message", messageText);
|
||||
formData.append("session_id", "web_session_main");
|
||||
|
||||
res = await fetch("/api/v1/chat/upload", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": AuthManager.getAuthHeaders()["Authorization"]
|
||||
},
|
||||
body: formData
|
||||
});
|
||||
|
||||
if (res.status === 404) {
|
||||
res = await fetch("/api/v1/chat", {
|
||||
method: "POST",
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
message: messageText || `Загружен файл: ${fileToSend.name}`,
|
||||
session_id: "web_session_main"
|
||||
})
|
||||
});
|
||||
}
|
||||
} else {
|
||||
res = await fetch("/api/v1/chat", {
|
||||
method: "POST",
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
message: messageText,
|
||||
session_id: "web_session_main"
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
const loaderEl = document.getElementById(loadingId);
|
||||
if (loaderEl) loaderEl.remove();
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
const replyText = data.response || data.text || data.message || "Запрос выполнен.";
|
||||
const buttons = data.buttons || [];
|
||||
const actionPayload = data.action_payload || null;
|
||||
|
||||
appendAssistantMessage(replyText, buttons, actionPayload);
|
||||
|
||||
if (window.SidebarManager) {
|
||||
SidebarManager.renderContent();
|
||||
}
|
||||
} else {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
appendAssistantMessage(`⚠️ Ошибка сервера (${res.status}): ${err.detail || "Не удалось получить ответ"}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Ошибка отправки сообщения:", err);
|
||||
const loaderEl = document.getElementById(loadingId);
|
||||
if (loaderEl) loaderEl.remove();
|
||||
appendAssistantMessage("⚠️ Ошибка соединения с сервером при отправке сообщения.");
|
||||
}
|
||||
};
|
||||
|
||||
window.clearAttachedFile = function() {
|
||||
currentAttachedFile = null;
|
||||
const preview = document.getElementById("file-attachment-preview");
|
||||
const nameEl = document.getElementById("file-attachment-name");
|
||||
const fileInput = document.getElementById("file-upload-input");
|
||||
|
||||
if (preview) preview.classList.add("hidden");
|
||||
if (nameEl) nameEl.innerText = "";
|
||||
if (fileInput) fileInput.value = "";
|
||||
};
|
||||
|
||||
function handleFileSelected(file) {
|
||||
if (!file) return;
|
||||
currentAttachedFile = file;
|
||||
const preview = document.getElementById("file-attachment-preview");
|
||||
const nameEl = document.getElementById("file-attachment-name");
|
||||
|
||||
if (preview && nameEl) {
|
||||
nameEl.innerText = file.name;
|
||||
preview.classList.remove("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const input = document.getElementById("user-input");
|
||||
const fileInput = document.getElementById("file-upload-input");
|
||||
const overlay = document.getElementById("global-drag-overlay");
|
||||
|
||||
if (input) {
|
||||
input.style.lineHeight = '24px';
|
||||
input.style.height = '24px';
|
||||
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") {
|
||||
if (e.shiftKey) return;
|
||||
e.preventDefault();
|
||||
window.sendMessage();
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === "ArrowUp") {
|
||||
const isSingleLine = !input.value.includes("\n");
|
||||
const isAtBeginning = input.selectionStart === 0 && input.selectionEnd === 0;
|
||||
|
||||
if (isSingleLine || isAtBeginning) {
|
||||
if (chatInputHistory.length > 0) {
|
||||
e.preventDefault();
|
||||
if (chatHistoryIndex === -1) {
|
||||
temporaryCurrentInput = input.value;
|
||||
chatHistoryIndex = chatInputHistory.length - 1;
|
||||
} else if (chatHistoryIndex > 0) {
|
||||
chatHistoryIndex--;
|
||||
}
|
||||
input.value = chatInputHistory[chatHistoryIndex];
|
||||
updateInputHeightAndFade(input);
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
}
|
||||
}
|
||||
} else if (e.key === "ArrowDown") {
|
||||
const isSingleLine = !input.value.includes("\n");
|
||||
const isAtEnd = input.selectionStart === input.value.length;
|
||||
|
||||
if (isSingleLine || isAtEnd) {
|
||||
if (chatHistoryIndex !== -1) {
|
||||
e.preventDefault();
|
||||
if (chatHistoryIndex < chatInputHistory.length - 1) {
|
||||
chatHistoryIndex++;
|
||||
input.value = chatInputHistory[chatHistoryIndex];
|
||||
} else {
|
||||
chatHistoryIndex = -1;
|
||||
input.value = temporaryCurrentInput;
|
||||
}
|
||||
updateInputHeightAndFade(input);
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (response.status === 403) {
|
||||
console.warn("[Chat] Получен 403 Forbidden. Сбрасываем сессию и повторяем...");
|
||||
localStorage.removeItem("auth_token");
|
||||
if (typeof appendMessageToUI === "function") {
|
||||
appendMessageToUI("assistant", "⚠️ Сессия была обновлена. Пожалуйста, отправьте сообщение повторно.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Ошибка сервера (HTTP ${response.status})`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const reply = data.response || data.message || "Ответ получен без текста.";
|
||||
|
||||
if (typeof appendMessageToUI === "function") {
|
||||
appendMessageToUI("assistant", reply);
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.error("[Chat Error]:", err);
|
||||
if (typeof appendMessageToUI === "function") {
|
||||
appendMessageToUI("assistant", `⚠️ Не удалось связаться с сервером: ${err.message}`);
|
||||
}
|
||||
input.addEventListener("input", function() {
|
||||
updateInputHeightAndFade(this);
|
||||
chatHistoryIndex = -1;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (fileInput) {
|
||||
fileInput.addEventListener("change", (e) => {
|
||||
if (e.target.files && e.target.files[0]) {
|
||||
handleFileSelected(e.target.files[0]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let dragCounter = 0;
|
||||
|
||||
window.addEventListener('dragenter', (e) => {
|
||||
e.preventDefault();
|
||||
dragCounter++;
|
||||
if (overlay) {
|
||||
overlay.classList.remove('hidden');
|
||||
}
|
||||
}, false);
|
||||
|
||||
window.addEventListener('dragleave', (e) => {
|
||||
e.preventDefault();
|
||||
dragCounter--;
|
||||
if (dragCounter <= 0) {
|
||||
dragCounter = 0;
|
||||
if (overlay) {
|
||||
overlay.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
}, false);
|
||||
|
||||
window.addEventListener('dragover', (e) => {
|
||||
e.preventDefault();
|
||||
}, false);
|
||||
|
||||
window.addEventListener('drop', (e) => {
|
||||
e.preventDefault();
|
||||
dragCounter = 0;
|
||||
if (overlay) {
|
||||
overlay.classList.add('hidden');
|
||||
}
|
||||
|
||||
const dt = e.dataTransfer;
|
||||
if (dt && dt.files && dt.files[0]) {
|
||||
handleFileSelected(dt.files[0]);
|
||||
}
|
||||
}, false);
|
||||
});
|
||||
@@ -0,0 +1,472 @@
|
||||
/**
|
||||
* ===============================================================================
|
||||
* 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();
|
||||
}
|
||||
});
|
||||
@@ -1,117 +1,200 @@
|
||||
/**
|
||||
===============================================================================
|
||||
FILE: modules/web_api/static/js/tasks.js
|
||||
PROJECT: SCUD Orion AI (Unified Architecture)
|
||||
MODULE: web_api / static / js
|
||||
ROLE: Загрузка, фильтрация и рендеринг списка задач в боковой панели (Drawer).
|
||||
===============================================================================
|
||||
*/
|
||||
* ===============================================================================
|
||||
* FILE: modules/web_api/static/js/tasks.js
|
||||
* ROLE: Управление персональными задачами оператора (CRUD, фильтры, рендер).
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
let currentTaskFilter = 'IN_PROGRESS';
|
||||
let currentTasksFilter = 'ALL';
|
||||
let tasksCache = [];
|
||||
|
||||
function getTasksContainer() {
|
||||
return document.getElementById("tasks-list-container") ||
|
||||
document.getElementById("sidebar-dynamic-content") ||
|
||||
document.getElementById("tasks-list");
|
||||
}
|
||||
|
||||
async function loadTasks() {
|
||||
const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
if (!token) return;
|
||||
const container = getTasksContainer();
|
||||
if (!container) return;
|
||||
|
||||
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/tasks", {
|
||||
headers: { "Authorization": "Bearer " + token }
|
||||
headers: AuthManager.getAuthHeaders()
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
renderSidebarTasks(data.tasks || []);
|
||||
} else {
|
||||
renderSidebarError("Ошибка доступа. Авторизуйтесь снова.");
|
||||
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) {
|
||||
showAuthModal();
|
||||
return;
|
||||
}
|
||||
throw new Error(`Ошибка сервера (${res.status})`);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Ошибка загрузки задач:", e);
|
||||
renderSidebarError("Ошибка сети. Сервер недоступен.");
|
||||
|
||||
const data = await res.json();
|
||||
tasksCache = Array.isArray(data) ? data : (data.tasks || []);
|
||||
renderTasksUI();
|
||||
} catch (err) {
|
||||
console.error("[Tasks] Ошибка загрузки:", err);
|
||||
container.innerHTML = `
|
||||
<div class="p-4 text-xs text-rose-500 text-center flex flex-col items-center gap-2">
|
||||
<i class="fa-solid fa-triangle-exclamation text-base"></i>
|
||||
<span>Не удалось загрузить задачи</span>
|
||||
<button onclick="loadTasks()" class="px-2.5 py-1 bg-slate-200 hover:bg-slate-300 text-slate-700 rounded text-[11px] font-semibold transition">Повторить</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderSidebarError(msg) {
|
||||
// Поддерживаем оба варианта ID (новый и старый) для обратной совместимости
|
||||
const container = document.getElementById("tasks-list") || document.getElementById("tasks-list-container");
|
||||
if (container) {
|
||||
container.innerHTML = `<div class="text-center py-8 text-xs text-rose-500 font-semibold">${msg}</div>`;
|
||||
}
|
||||
function setTaskFilter(filter) {
|
||||
currentTasksFilter = filter;
|
||||
renderTasksUI();
|
||||
}
|
||||
|
||||
function filterTasksByTab(status) {
|
||||
currentTaskFilter = status;
|
||||
|
||||
// Сброс стилей всех кнопок-вкладок
|
||||
document.querySelectorAll('.task-tab-btn').forEach(btn => {
|
||||
btn.classList.remove('text-indigo-600', 'bg-indigo-50');
|
||||
btn.classList.add('text-slate-600');
|
||||
});
|
||||
|
||||
// Установка активного стиля для выбранной вкладки
|
||||
const activeBtnId = {
|
||||
'IN_PROGRESS': 'tab-in-progress',
|
||||
'BACKLOG': 'tab-backlog',
|
||||
'COMPLETED': 'tab-completed',
|
||||
'ALL': 'tab-all'
|
||||
}[status];
|
||||
|
||||
if (activeBtnId) {
|
||||
const btn = document.getElementById(activeBtnId);
|
||||
if (btn) {
|
||||
btn.classList.remove('text-slate-600', 'hover:bg-slate-100');
|
||||
btn.classList.add('text-indigo-600', 'bg-indigo-50');
|
||||
}
|
||||
}
|
||||
|
||||
loadTasks();
|
||||
}
|
||||
|
||||
function renderSidebarTasks(tasks) {
|
||||
const container = document.getElementById("tasks-list") || document.getElementById("tasks-list-container");
|
||||
function renderTasksUI() {
|
||||
const container = getTasksContainer();
|
||||
if (!container) return;
|
||||
|
||||
let filtered = tasks;
|
||||
if (currentTaskFilter !== 'ALL') {
|
||||
filtered = tasks.filter(t => t.status === currentTaskFilter);
|
||||
|
||||
let filtered = tasksCache;
|
||||
if (currentTasksFilter === 'IN_PROGRESS') {
|
||||
filtered = tasksCache.filter(t => t.status === 'IN_PROGRESS');
|
||||
} else if (currentTasksFilter === 'BACKLOG') {
|
||||
filtered = tasksCache.filter(t => t.status === 'BACKLOG' || t.status === 'PLANNED');
|
||||
} else if (currentTasksFilter === 'COMPLETED') {
|
||||
filtered = tasksCache.filter(t => t.status === 'COMPLETED' || t.status === 'DONE');
|
||||
}
|
||||
|
||||
const filtersHtml = `
|
||||
<div class="flex items-center gap-1 p-1 bg-slate-200/70 rounded-lg text-[11px] font-semibold mb-2">
|
||||
<button onclick="setTaskFilter('ALL')" class="flex-1 py-1 rounded text-center transition ${currentTasksFilter === 'ALL' ? 'bg-white text-indigo-700 shadow-sm' : 'text-slate-600 hover:text-slate-900'}">Все</button>
|
||||
<button onclick="setTaskFilter('IN_PROGRESS')" class="flex-1 py-1 rounded text-center transition ${currentTasksFilter === 'IN_PROGRESS' ? 'bg-white text-indigo-700 shadow-sm' : 'text-slate-600 hover:text-slate-900'}">В работе</button>
|
||||
<button onclick="setTaskFilter('BACKLOG')" class="flex-1 py-1 rounded text-center transition ${currentTasksFilter === 'BACKLOG' ? 'bg-white text-indigo-700 shadow-sm' : 'text-slate-600 hover:text-slate-900'}">Планы</button>
|
||||
<button onclick="setTaskFilter('COMPLETED')" class="flex-1 py-1 rounded text-center transition ${currentTasksFilter === 'COMPLETED' ? 'bg-white text-indigo-700 shadow-sm' : 'text-slate-600 hover:text-slate-900'}">Готово</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const addBtnHtml = `
|
||||
<div class="flex items-center justify-between px-1 mb-1.5">
|
||||
<span class="text-xs font-bold text-slate-700">Задачи: ${filtered.length}</span>
|
||||
<button onclick="openCreateTaskModal()" class="px-2 py-1 bg-indigo-600 hover:bg-indigo-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>
|
||||
`;
|
||||
|
||||
if (filtered.length === 0) {
|
||||
container.innerHTML = `<div class="text-center py-8 text-[11px] font-medium text-slate-400 bg-slate-50 rounded-xl border border-dashed border-slate-200">Нет задач в этой категории</div>`;
|
||||
container.innerHTML = `
|
||||
${filtersHtml}
|
||||
${addBtnHtml}
|
||||
<div class="text-center py-8 text-xs text-slate-400 bg-white border border-slate-200 rounded-xl p-4">
|
||||
Нет задач в выбранной категории
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML = filtered.map(t => {
|
||||
const isCompleted = t.status === 'COMPLETED';
|
||||
const priorityColor = t.priority === 'HIGH' || t.priority === 'CRITICAL'
|
||||
? 'text-rose-600 bg-rose-50 border-rose-200'
|
||||
: t.priority === 'MEDIUM'
|
||||
? 'text-amber-600 bg-amber-50 border-amber-200'
|
||||
: 'text-slate-600 bg-slate-50 border-slate-200';
|
||||
|
||||
const itemsHtml = filtered.map(t => {
|
||||
const isDone = t.status === 'COMPLETED' || t.status === 'DONE';
|
||||
const priorityColors = {
|
||||
'HIGH': 'bg-rose-50 text-rose-700 border-rose-200',
|
||||
'MEDIUM': 'bg-amber-50 text-amber-700 border-amber-200',
|
||||
'LOW': 'bg-slate-50 text-slate-600 border-slate-200'
|
||||
};
|
||||
const pClass = priorityColors[t.priority] || priorityColors['MEDIUM'];
|
||||
|
||||
return `
|
||||
<div class="p-3 bg-white border border-slate-200 rounded-xl shadow-sm hover:border-indigo-400 hover:shadow-md transition cursor-pointer flex flex-col gap-2 group"
|
||||
onclick="handleActionButtonClick('покажи задачу ${t.id}')">
|
||||
|
||||
<div class="flex flex-col p-2.5 bg-white border border-slate-200 rounded-xl text-xs gap-1.5 shadow-sm hover:border-indigo-300 transition">
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<span class="text-[10px] font-bold text-slate-400 uppercase tracking-wider group-hover:text-indigo-500 transition">#${t.id}</span>
|
||||
${isCompleted
|
||||
? `<span class="text-[10px] font-bold px-1.5 py-0.5 rounded-md bg-emerald-50 text-emerald-600 border border-emerald-200 shadow-sm"><i class="fa-solid fa-check mr-0.5"></i> Готово</span>`
|
||||
: `<span class="text-[10px] font-bold px-1.5 py-0.5 rounded-md ${priorityColor} shadow-sm">${t.priority || 'LOW'}</span>`
|
||||
}
|
||||
<div class="flex items-center gap-1.5 min-w-0">
|
||||
<button onclick="toggleTaskStatus(${t.id}, '${t.status}')" class="text-slate-400 hover:text-indigo-600 transition shrink-0">
|
||||
<i class="fa-${isDone ? 'solid fa-circle-check text-emerald-500' : 'regular fa-circle'} text-sm"></i>
|
||||
</button>
|
||||
<span class="font-bold text-slate-800 ${isDone ? 'line-through text-slate-400' : ''} truncate">${escapeHtml(t.title)}</span>
|
||||
</div>
|
||||
<span class="px-1.5 py-0.5 rounded text-[9px] font-semibold border ${pClass} shrink-0">${t.priority || 'NORMAL'}</span>
|
||||
</div>
|
||||
|
||||
<div class="text-xs font-semibold text-slate-700 leading-snug line-clamp-3">${escapeHtml(t.title || 'Без названия')}</div>
|
||||
|
||||
<div class="flex items-center justify-between text-[10px] text-slate-400 mt-1">
|
||||
<span class="bg-slate-100 px-1.5 py-0.5 rounded font-mono truncate max-w-[120px]">${escapeHtml(t.module || 'general')}</span>
|
||||
${t.due_date ? `<span class="shrink-0 font-medium text-slate-500"><i class="fa-regular fa-calendar mr-1"></i>${escapeHtml(t.due_date)}</span>` : ''}
|
||||
<div class="flex items-center justify-between text-[10px] text-slate-400 pt-1 border-t border-slate-100">
|
||||
<span>${t.task_id || ('#' + t.id)} · ${escapeHtml(t.module || 'general')}</span>
|
||||
<div class="flex items-center gap-1">
|
||||
<button onclick="deleteTaskItem(${t.id})" class="text-slate-400 hover:text-rose-600 p-0.5 transition" title="Удалить">
|
||||
<i class="fa-solid fa-trash-can text-[11px]"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
container.innerHTML = `
|
||||
${filtersHtml}
|
||||
${addBtnHtml}
|
||||
<div class="flex flex-col gap-1.5 max-h-[70vh] overflow-y-auto">
|
||||
${itemsHtml}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// Глобальная инициализация при загрузке DOM
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
// Небольшая задержка, чтобы гарантировать применение токена
|
||||
setTimeout(loadTasks, 200);
|
||||
});
|
||||
async function toggleTaskStatus(id, currentStatus) {
|
||||
const newStatus = (currentStatus === 'COMPLETED' || currentStatus === 'DONE') ? 'IN_PROGRESS' : 'COMPLETED';
|
||||
try {
|
||||
const res = await fetch(`/api/v1/tasks/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({ status: newStatus })
|
||||
});
|
||||
if (res.ok) {
|
||||
loadTasks();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Ошибка смены статуса задачи:", e);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteTaskItem(id) {
|
||||
if (!confirm("Удалить эту задачу?")) return;
|
||||
try {
|
||||
const res = await fetch(`/api/v1/tasks/${id}`, {
|
||||
method: "DELETE",
|
||||
headers: AuthManager.getAuthHeaders()
|
||||
});
|
||||
if (res.ok) {
|
||||
loadTasks();
|
||||
}
|
||||
} catch (e) {
|
||||
alert("Ошибка сети при удалении");
|
||||
}
|
||||
}
|
||||
|
||||
async function openCreateTaskModal() {
|
||||
const title = prompt("Введите описание новой задачи:");
|
||||
if (!title || !title.trim()) return;
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/v1/tasks", {
|
||||
method: "POST",
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
title: title.trim(),
|
||||
priority: "MEDIUM",
|
||||
status: "IN_PROGRESS"
|
||||
})
|
||||
});
|
||||
if (res.ok) {
|
||||
loadTasks();
|
||||
} else {
|
||||
alert("Не удалось создать задачу");
|
||||
}
|
||||
} catch (e) {
|
||||
alert("Ошибка сети");
|
||||
}
|
||||
}
|
||||
|
||||
window.loadTasks = loadTasks;
|
||||
window.setTaskFilter = setTaskFilter;
|
||||
Reference in New Issue
Block a user