feat(etl): stable pipeline, exception registry in SQLite, multi-pass aggregation and db_cli
This commit is contained in:
+146
-245
@@ -2,263 +2,164 @@
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
|
||||
<title>SCUD Orion AI — Context Manager</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>SCUD Orion AI — Управление и Аналитика</title>
|
||||
<!-- Tailwind CSS CDN -->
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<!-- FontAwesome Icons -->
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
||||
<link rel="stylesheet" href="/static/css/styles.css">
|
||||
<link rel="stylesheet" href="/css/styles.css">
|
||||
</head>
|
||||
<body class="bg-slate-100 text-slate-800 h-[100dvh] w-full flex flex-col font-sans overflow-hidden">
|
||||
<body class="bg-slate-100 font-sans h-screen flex overflow-hidden text-slate-800">
|
||||
|
||||
<!-- ANCHOR[AUTH_MODAL]: Модальное окно входа -->
|
||||
<div id="auth-modal" class="fixed inset-0 bg-slate-900/80 backdrop-blur-md z-50 flex items-center justify-center p-4">
|
||||
<div class="bg-white rounded-2xl p-6 sm:p-8 max-w-md w-full shadow-2xl border border-slate-200">
|
||||
<div class="flex items-center space-x-3 mb-6">
|
||||
<div class="bg-indigo-600 text-white p-3 rounded-xl">
|
||||
<i class="fa-solid fa-user-shield text-xl"></i>
|
||||
</div>
|
||||
<div>
|
||||
<h2 class="text-lg font-bold text-slate-900">SCUD Orion AI</h2>
|
||||
<p class="text-xs text-slate-500">Авторизация в системе</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-xs font-semibold text-slate-700 uppercase tracking-wider mb-1">Имя пользователя</label>
|
||||
<input type="text" id="auth-username-input" placeholder="Введите логин..." required autocomplete="username"
|
||||
class="w-full bg-slate-50 border border-slate-300 rounded-xl px-4 py-2.5 text-sm text-slate-900 focus:outline-none focus:border-indigo-600 focus:bg-white transition">
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-xs font-semibold text-slate-700 uppercase tracking-wider mb-1">Пароль</label>
|
||||
<input type="password" id="auth-password-input" placeholder="Введите пароль..." required autocomplete="current-password"
|
||||
class="w-full bg-slate-50 border border-slate-300 rounded-xl px-4 py-2.5 text-sm text-slate-900 focus:outline-none focus:border-indigo-600 focus:bg-white transition">
|
||||
</div>
|
||||
|
||||
<div id="auth-error" class="hidden text-xs text-red-600 font-medium bg-red-50 p-3 rounded-xl border border-red-200"></div>
|
||||
|
||||
<button type="button" onclick="handleLogin()" id="auth-btn" class="w-full bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white font-semibold py-3 rounded-xl text-sm transition shadow-md flex items-center justify-center gap-2">
|
||||
<i class="fa-solid fa-right-to-bracket"></i>
|
||||
<span>Войти в систему</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="relative my-4">
|
||||
<div class="absolute inset-0 flex items-center"><div class="w-full border-t border-slate-200"></div></div>
|
||||
<div class="relative flex justify-center text-xs uppercase"><span class="bg-white px-2 text-slate-400 font-medium">Или</span></div>
|
||||
</div>
|
||||
|
||||
<button type="button" onclick="enableGuestMode()" class="w-full bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold py-2.5 rounded-xl text-xs transition border border-slate-300 flex items-center justify-center gap-2">
|
||||
<i class="fa-solid fa-user-ninja"></i>
|
||||
<span>Войти как гость (Локальный ИИ)</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ANCHOR[CHANGE_PWD_MODAL]: Модальное окно смены пароля -->
|
||||
<div id="change-pwd-modal" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 hidden flex items-center justify-center p-4">
|
||||
<div class="bg-white rounded-2xl p-6 max-w-sm w-full shadow-2xl border border-slate-200">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<h3 class="font-bold text-slate-800 text-sm flex items-center gap-2">
|
||||
<i class="fa-solid fa-key text-indigo-600"></i> Смена пароля
|
||||
</h3>
|
||||
<button type="button" onclick="closeChangePasswordModal()" class="text-slate-400 hover:text-slate-700">
|
||||
<i class="fa-solid fa-xmark text-lg"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="space-y-3">
|
||||
<div>
|
||||
<label class="block text-[11px] font-semibold text-slate-600 uppercase mb-1">Старый пароль</label>
|
||||
<input type="password" id="old-pwd-input" required class="w-full bg-slate-50 border border-slate-300 rounded-xl px-3 py-2 text-xs text-slate-900 focus:outline-none focus:border-indigo-600">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-[11px] font-semibold text-slate-600 uppercase mb-1">Новый пароль</label>
|
||||
<input type="password" id="new-pwd-input" required class="w-full bg-slate-50 border border-slate-300 rounded-xl px-3 py-2 text-xs text-slate-900 focus:outline-none focus:border-indigo-600">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-[11px] font-semibold text-slate-600 uppercase mb-1">Повторите новый пароль</label>
|
||||
<input type="password" id="confirm-pwd-input" required class="w-full bg-slate-50 border border-slate-300 rounded-xl px-3 py-2 text-xs text-slate-900 focus:outline-none focus:border-indigo-600">
|
||||
</div>
|
||||
|
||||
<div id="pwd-error" class="hidden text-xs text-red-600 bg-red-50 p-2 rounded-lg border border-red-200"></div>
|
||||
<div id="pwd-success" class="hidden text-xs text-emerald-600 bg-emerald-50 p-2 rounded-lg border border-emerald-200"></div>
|
||||
|
||||
<button type="button" onclick="handleChangePassword()" class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-semibold py-2.5 rounded-xl text-xs transition shadow-sm mt-2">
|
||||
Сохранить новый пароль
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ANCHOR[ADMIN_MODAL]: Модальное окно управления пользователями -->
|
||||
<div id="admin-modal" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 hidden flex items-center justify-center p-4">
|
||||
<div class="bg-white rounded-2xl p-6 max-w-lg w-full shadow-2xl border border-slate-200 flex flex-col max-h-[85vh]">
|
||||
<div class="flex justify-between items-center mb-4 pb-2 border-b border-slate-200">
|
||||
<h3 class="font-bold text-slate-800 text-sm flex items-center gap-2">
|
||||
<i class="fa-solid fa-users-gear text-indigo-600"></i> Управление пользователями
|
||||
</h3>
|
||||
<button type="button" onclick="closeAdminModal()" class="text-slate-400 hover:text-slate-700">
|
||||
<i class="fa-solid fa-xmark text-lg"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2 mb-4 bg-slate-50 p-3.5 rounded-xl border border-slate-200 shrink-0">
|
||||
<p class="text-[11px] font-bold text-slate-700 uppercase">Создать нового пользователя</p>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<input type="text" id="new-user-name" placeholder="Логин *" required class="bg-white border border-slate-300 rounded-lg px-2.5 py-1.5 text-xs">
|
||||
<input type="password" id="new-user-pwd" placeholder="Пароль *" required class="bg-white border border-slate-300 rounded-lg px-2.5 py-1.5 text-xs">
|
||||
</div>
|
||||
<input type="text" id="new-user-fullname" placeholder="ФИО (необязательно)" class="w-full bg-white border border-slate-300 rounded-lg px-2.5 py-1.5 text-xs">
|
||||
<div class="flex items-center justify-between pt-1">
|
||||
<label class="flex items-center gap-2 text-xs text-slate-700 cursor-pointer">
|
||||
<input type="checkbox" id="new-user-is-admin" class="rounded border-slate-300 text-indigo-600 focus:ring-indigo-500">
|
||||
<span>Права администратора</span>
|
||||
</label>
|
||||
<button type="button" onclick="handleCreateUser()" class="bg-indigo-600 hover:bg-indigo-700 text-white font-semibold px-4 py-1.5 rounded-lg text-xs transition">
|
||||
+ Добавить
|
||||
</button>
|
||||
</div>
|
||||
<div id="admin-msg" class="hidden text-[11px] text-red-600 pt-1"></div>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 overflow-y-auto space-y-2 pr-1" id="admin-users-list">
|
||||
<div class="text-xs text-slate-400 py-4 text-center">Загрузка пользователей...</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ANCHOR[HEADER_BAR]: Хедер интерфейса -->
|
||||
<header class="bg-white border-b border-slate-200 px-4 py-2.5 flex justify-between items-center shadow-sm shrink-0 z-20">
|
||||
<div class="flex items-center space-x-2.5">
|
||||
<div class="bg-indigo-600 text-white p-2 rounded-xl shrink-0">
|
||||
<i class="fa-solid fa-brain text-lg"></i>
|
||||
</div>
|
||||
<div>
|
||||
<h1 class="text-sm font-bold text-slate-900 leading-tight">SCUD Orion AI</h1>
|
||||
<span class="text-[11px] text-slate-500">Task & Context API</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center space-x-1.5">
|
||||
<span id="guest-badge" class="hidden text-[10px] text-amber-700 font-semibold bg-amber-50 px-2 py-0.5 rounded-full border border-amber-200">
|
||||
Гость
|
||||
</span>
|
||||
|
||||
<span id="username-badge" class="hidden text-xs text-indigo-700 font-bold bg-indigo-50 px-2.5 py-1 rounded-full border border-indigo-200">
|
||||
puh
|
||||
</span>
|
||||
|
||||
<button id="admin-users-btn" type="button" onclick="openAdminModal()" class="hidden text-slate-500 hover:text-indigo-600 transition p-2 rounded-xl" title="Управление пользователями">
|
||||
<i class="fa-solid fa-users-gear text-base"></i>
|
||||
</button>
|
||||
|
||||
<button id="change-pwd-btn" type="button" onclick="openChangePasswordModal()" class="hidden text-slate-500 hover:text-indigo-600 transition p-2 rounded-xl" title="Сменить пароль">
|
||||
<i class="fa-solid fa-key text-base"></i>
|
||||
</button>
|
||||
|
||||
<button id="tasks-drawer-btn" type="button" onclick="toggleDrawer()" class="bg-indigo-600 active:bg-indigo-700 text-white px-3 py-1.5 rounded-xl text-xs font-semibold flex items-center gap-1.5 shadow-sm">
|
||||
<i class="fa-solid fa-list-check"></i>
|
||||
<span>Задачи</span>
|
||||
<span id="task-count-badge" class="bg-white text-indigo-700 text-[10px] font-bold px-1.5 py-0.2 rounded-full">0</span>
|
||||
</button>
|
||||
|
||||
<button type="button" onclick="logout()" class="text-slate-400 hover:text-red-600 transition p-2 rounded-xl" title="Выйти">
|
||||
<i class="fa-solid fa-right-from-bracket text-base"></i>
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- ANCHOR[CHAT_MAIN_CONTAINER]: Главный контейнер чата -->
|
||||
<div class="flex-1 flex flex-col min-h-0 w-full max-w-4xl mx-auto bg-white relative overflow-hidden">
|
||||
<div id="chat-window" class="flex-1 p-3.5 overflow-y-auto space-y-3 bg-slate-50/50">
|
||||
<div id="drop-overlay" class="absolute inset-0 bg-indigo-600/10 backdrop-blur-sm border-2 border-dashed border-indigo-600 rounded-2xl hidden flex-col items-center justify-center z-30 transition-all pointer-events-none">
|
||||
<div class="bg-white p-4 rounded-2xl shadow-xl flex flex-col items-center gap-2">
|
||||
<i class="fa-solid fa-cloud-arrow-up text-3xl text-indigo-600 animate-bounce"></i>
|
||||
<p class="text-sm font-bold text-slate-800">Перетащите файл сюда</p>
|
||||
<p class="text-xs text-slate-500">Поддерживаются PDF, изображения, таблицы, TXT</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="bg-white border border-slate-200 rounded-2xl p-3.5 shadow-sm">
|
||||
<p class="text-[11px] font-bold text-indigo-600 uppercase tracking-wider mb-1">
|
||||
<i class="fa-solid fa-robot mr-1"></i> ИИ-Ассистент
|
||||
</p>
|
||||
<p class="text-slate-800 text-xs sm:text-sm leading-relaxed">
|
||||
Привет! У каждого пользователя свое изолированное пространство задач. Вы можете задавать вопросы нейросети, прикреплять файлы или ставить персональные задачи.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Превью прикрепленного файла -->
|
||||
<div id="file-preview-container" class="hidden px-4 py-2 bg-slate-100 border-t border-slate-200 flex items-center justify-between text-xs text-slate-700">
|
||||
<div class="flex items-center gap-2 truncate">
|
||||
<i class="fa-solid fa-paperclip text-indigo-600"></i>
|
||||
<span id="file-name-display" class="font-medium truncate">file.pdf</span>
|
||||
<span id="file-size-display" class="text-slate-400 text-[10px]">(0 KB)</span>
|
||||
</div>
|
||||
<button type="button" onclick="clearAttachedFile()" class="text-slate-400 hover:text-red-500 p-1 transition">
|
||||
<i class="fa-solid fa-xmark text-sm"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Поле ввода -->
|
||||
<div class="p-2.5 pb-6 bg-white border-t border-slate-200 shrink-0 z-10 shadow-lg">
|
||||
<!-- Боковая панель (Задачи и Навигация) -->
|
||||
<aside id="task-drawer" class="w-80 sm:w-96 bg-white border-r border-slate-200 flex flex-col shrink-0 h-full z-20 shadow-sm transition-all duration-300">
|
||||
<!-- Шапка панели задач -->
|
||||
<div class="p-4 border-b border-slate-200 flex items-center justify-between bg-slate-50/70">
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="file" id="file-input" class="hidden" onchange="handleFileSelect(event)" accept=".png,.jpg,.jpeg,.pdf,.txt,.csv,.xlsx">
|
||||
<button type="button" onclick="document.getElementById('file-input').click()" class="text-slate-500 hover:text-indigo-600 p-2 rounded-xl transition" title="Прикрепить файл">
|
||||
<i class="fa-solid fa-paperclip text-lg"></i>
|
||||
</button>
|
||||
|
||||
<div class="flex-1 bg-slate-100 border border-slate-300 rounded-2xl px-3 py-1.5 focus-within:border-indigo-600 focus-within:bg-white transition">
|
||||
<textarea id="user-input" rows="1" autocomplete="off" autocorrect="off" spellcheck="false"
|
||||
placeholder="Команда, вопрос или перетащите файл сюда..."
|
||||
class="w-full bg-transparent text-slate-900 text-sm focus:outline-none resize-none overflow-y-auto h-[24px] max-h-[120px] leading-[24px] fade-scroll-top no-scrollbar"></textarea>
|
||||
<div class="w-8 h-8 rounded-lg bg-indigo-600 flex items-center justify-center text-white shadow-sm">
|
||||
<i class="fa-solid fa-list-check text-sm"></i>
|
||||
</div>
|
||||
<div>
|
||||
<h2 class="font-bold text-sm text-slate-900 leading-tight">Бэклог задач</h2>
|
||||
<p class="text-[11px] text-slate-500">SCUD Orion AI Roadmap</p>
|
||||
</div>
|
||||
<button type="button" id="send-btn" onclick="sendMessage()" class="bg-indigo-600 active:bg-indigo-800 text-white font-semibold px-3.5 py-2.5 rounded-2xl text-xs sm:text-sm transition flex items-center justify-center gap-1.5 shrink-0 shadow-sm">
|
||||
<span>Отправить</span>
|
||||
<i class="fa-solid fa-paper-plane text-xs"></i>
|
||||
</button>
|
||||
</div>
|
||||
<button type="button" onclick="openAddTaskModal()" title="Добавить задачу"
|
||||
class="px-2.5 py-1.5 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 border border-indigo-200 rounded-lg text-xs font-semibold flex items-center gap-1 transition cursor-pointer">
|
||||
<i class="fa-solid fa-plus"></i>
|
||||
<span>Задача</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ANCHOR[TASK_DRAWER_CONTAINER]: Боковая панель задач -->
|
||||
<div id="drawer-backdrop" onclick="toggleDrawer()" class="fixed inset-0 bg-slate-900/50 backdrop-blur-sm hidden transition-opacity z-40"></div>
|
||||
|
||||
<aside id="task-drawer" class="fixed right-0 top-0 h-full w-full sm:w-[420px] bg-white border-l border-slate-200 shadow-2xl transform translate-x-full transition-transform duration-300 ease-in-out z-50 flex flex-col">
|
||||
<div class="p-3.5 border-b border-slate-200 flex justify-between items-center bg-slate-50 shrink-0">
|
||||
<h2 class="font-bold text-slate-800 flex items-center gap-2 text-sm">
|
||||
<i class="fa-solid fa-list-check text-indigo-600"></i> Мой реестр задач
|
||||
</h2>
|
||||
<div class="flex items-center gap-3">
|
||||
<button type="button" onclick="loadTasks()" class="text-xs text-slate-500 hover:text-indigo-600 transition p-1" title="Обновить">
|
||||
<i class="fa-solid fa-rotate-right text-sm"></i>
|
||||
</button>
|
||||
<button type="button" onclick="toggleDrawer()" class="text-slate-500 hover:text-slate-800 transition p-1">
|
||||
<i class="fa-solid fa-xmark text-lg"></i>
|
||||
</button>
|
||||
<!-- Фильтры задач -->
|
||||
<div class="px-4 py-2.5 border-b border-slate-100 flex items-center justify-between gap-1 text-xs">
|
||||
<button onclick="filterTasksByTab('IN_PROGRESS')" id="tab-in-progress" class="task-tab-btn font-semibold px-2.5 py-1 rounded-md text-indigo-600 bg-indigo-50 transition">В работе</button>
|
||||
<button onclick="filterTasksByTab('BACKLOG')" id="tab-backlog" class="task-tab-btn font-medium px-2.5 py-1 rounded-md text-slate-600 hover:bg-slate-100 transition">В планах</button>
|
||||
<button onclick="filterTasksByTab('COMPLETED')" id="tab-completed" class="task-tab-btn font-medium px-2.5 py-1 rounded-md text-slate-600 hover:bg-slate-100 transition">Готово</button>
|
||||
<button onclick="filterTasksByTab('ALL')" id="tab-all" class="task-tab-btn font-medium px-2.5 py-1 rounded-md text-slate-600 hover:bg-slate-100 transition">Все</button>
|
||||
</div>
|
||||
|
||||
<!-- Список задач с прокруткой (ID исправлен на tasks-list) -->
|
||||
<div id="tasks-list" class="flex-1 overflow-y-auto p-3 space-y-2.5">
|
||||
<div class="text-center py-8 text-xs text-slate-400">Загрузка задач...</div>
|
||||
</div>
|
||||
|
||||
<!-- Подвал панели пользователя -->
|
||||
<div class="p-3 border-t border-slate-200 bg-slate-50/50 flex items-center justify-between text-xs">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="w-7 h-7 rounded-full bg-slate-300 flex items-center justify-center text-slate-700 font-bold">
|
||||
<i class="fa-solid fa-user text-xs"></i>
|
||||
</div>
|
||||
<div class="truncate">
|
||||
<span id="current-username" class="font-semibold text-slate-900 block truncate">Александр Пушков</span>
|
||||
<span id="user-role-badge" class="text-[10px] text-indigo-600 font-medium">Администратор</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ANCHOR[DRAWER_TAB_RENAMING]: Вкладки фильтрации боковой панели -->
|
||||
<div class="flex border-b border-slate-200 bg-white px-2 pt-2 text-xs font-semibold text-slate-500 gap-1 overflow-x-auto no-scrollbar shrink-0">
|
||||
<button type="button" onclick="setFilter('ALL')" id="filter-ALL" class="px-3 py-1.5 rounded-t-lg border-b-2 border-indigo-600 text-indigo-600 font-bold whitespace-nowrap">Все</button>
|
||||
<button type="button" onclick="setFilter('IN_PROGRESS')" id="filter-IN_PROGRESS" class="px-3 py-1.5 rounded-t-lg border-b-2 border-transparent whitespace-nowrap">В работе</button>
|
||||
<button type="button" onclick="setFilter('BACKLOG')" id="filter-BACKLOG" class="px-3 py-1.5 rounded-t-lg border-b-2 border-transparent whitespace-nowrap">В планах</button>
|
||||
<button type="button" onclick="setFilter('COMPLETED')" id="filter-COMPLETED" class="px-3 py-1.5 rounded-t-lg border-b-2 border-transparent whitespace-nowrap">Завершенные</button>
|
||||
</div>
|
||||
|
||||
<div id="tasks-container" class="flex-1 overflow-y-auto p-3.5 space-y-3 bg-slate-50/50 pb-8">
|
||||
<div class="text-center text-slate-400 py-8 text-xs">Загрузка ваших задач...</div>
|
||||
<button onclick="logout()" title="Выйти" class="p-1.5 text-slate-400 hover:text-rose-600 transition">
|
||||
<i class="fa-solid fa-arrow-right-from-bracket"></i>
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Подключение скриптов интерфейса -->
|
||||
<script src="/static/js/auth.js"></script>
|
||||
<script src="/static/js/tasks.js"></script>
|
||||
<script src="/static/js/chat/task_widget.js"></script>
|
||||
<script src="/static/js/chat/core.js"></script>
|
||||
<script src="/static/js/app.js"></script>
|
||||
<!-- Основная рабочая область чата -->
|
||||
<main class="flex-1 flex flex-col min-w-0 bg-white relative h-full overflow-hidden">
|
||||
<!-- Верхний заголовок чата -->
|
||||
<header class="h-14 border-b border-slate-200 px-4 flex items-center justify-between bg-white shrink-0 z-10">
|
||||
<div class="flex items-center gap-3">
|
||||
<button type="button" onclick="toggleTaskDrawer()" class="p-1.5 text-slate-500 hover:text-indigo-600 hover:bg-slate-100 rounded-lg transition" title="Переключить боковую панель">
|
||||
<i class="fa-solid fa-bars"></i>
|
||||
</button>
|
||||
<div>
|
||||
<h1 class="font-bold text-sm text-slate-900 flex items-center gap-2">
|
||||
<span>SCUD Orion AI Assistant</span>
|
||||
<span class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-semibold bg-emerald-100 text-emerald-800">Online</span>
|
||||
</h1>
|
||||
<p class="text-[11px] text-slate-500">Система интеллектуального аудита и контроля СКУД / 1С</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 text-xs">
|
||||
<button type="button" onclick="handleActionButtonClick('покажи системный промпт')" class="px-2.5 py-1 text-slate-600 hover:text-indigo-600 hover:bg-slate-100 rounded-md border border-slate-200 transition">
|
||||
<i class="fa-solid fa-terminal mr-1"></i> Промпт
|
||||
</button>
|
||||
<button type="button" onclick="handleActionButtonClick('покажи снапшоты')" class="px-2.5 py-1 text-slate-600 hover:text-indigo-600 hover:bg-slate-100 rounded-md border border-slate-200 transition">
|
||||
<i class="fa-solid fa-camera mr-1"></i> Срезы СКУД
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Drop Overlay при перетаскивании файлов -->
|
||||
<div id="drop-overlay" class="hidden absolute inset-0 bg-indigo-600/10 backdrop-blur-[2px] border-2 border-dashed border-indigo-500 rounded-2xl m-4 z-50 items-center justify-center flex-col gap-2 pointer-events-none">
|
||||
<i class="fa-solid fa-cloud-arrow-up text-3xl text-indigo-600 animate-bounce"></i>
|
||||
<p class="text-xs font-bold text-indigo-900">Перетащите файл сюда для отправки в диалог</p>
|
||||
</div>
|
||||
|
||||
<!-- Окно сообщений с центрированием контента -->
|
||||
<div id="chat-window" class="flex-1 p-4 overflow-y-auto bg-slate-50/50 scroll-smooth">
|
||||
<!-- Центрирующая колонка для сообщений -->
|
||||
<div class="max-w-4xl w-full mx-auto space-y-4">
|
||||
|
||||
<!-- Стартовое приветственное сообщение -->
|
||||
<div class="chat-message-card bg-white border border-slate-200 rounded-2xl p-4 shadow-sm w-full">
|
||||
<p class="text-[11px] font-bold text-indigo-600 uppercase tracking-wider mb-1">
|
||||
<i class="fa-solid fa-robot mr-1"></i> ИИ-Ассистент SCUD Orion AI
|
||||
</p>
|
||||
<div class="text-slate-800 text-xs sm:text-sm leading-relaxed">
|
||||
Привет! У каждого пользователя свое изолированное пространство задач. Вы можете задавать вопросы нейросети, прикреплять файлы или ставить персональные задачи.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Невидимая распорка в самом низу для свободного скролла любого вопроса наверх -->
|
||||
<div id="chat-bottom-spacer" class="min-h-[85vh] pointer-events-none w-full"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Центрированная нижняя панель ввода -->
|
||||
<div class="p-3 bg-white border-t border-slate-200 shrink-0 z-10">
|
||||
<div class="max-w-4xl w-full mx-auto">
|
||||
<!-- Блок предпросмотра прикрепленного файла -->
|
||||
<div id="file-preview-container" class="hidden mb-2 p-2 bg-indigo-50 border border-indigo-200 rounded-xl flex items-center justify-between">
|
||||
<div class="flex items-center gap-2 min-w-0">
|
||||
<i class="fa-solid fa-file-arrow-up text-indigo-600 text-sm"></i>
|
||||
<span id="file-name-display" class="text-xs font-semibold text-slate-800 truncate"></span>
|
||||
<span id="file-size-display" class="text-[10px] text-slate-500"></span>
|
||||
</div>
|
||||
<button type="button" onclick="clearAttachedFile()" class="text-slate-400 hover:text-rose-600 transition p-1">
|
||||
<i class="fa-solid fa-xmark"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Форма отправки -->
|
||||
<form id="chat-form" onsubmit="sendMessage(event)" class="flex items-end gap-2">
|
||||
<input type="file" id="file-input" class="hidden" onchange="handleFileSelect(event)" />
|
||||
|
||||
<button type="button" onclick="document.getElementById('file-input').click()"
|
||||
title="Прикрепить файл"
|
||||
class="p-2.5 text-slate-500 hover:text-indigo-600 hover:bg-slate-100 rounded-xl transition shrink-0 cursor-pointer">
|
||||
<i class="fa-solid fa-paperclip text-sm"></i>
|
||||
</button>
|
||||
|
||||
<div class="flex-1 bg-slate-100 border border-slate-300 focus-within:border-indigo-600 focus-within:bg-white rounded-2xl p-1.5 transition flex items-center shadow-inner">
|
||||
<textarea id="user-input" rows="1"
|
||||
placeholder="Команда, вопрос или перетащите файл сюда..."
|
||||
class="w-full bg-transparent px-2 text-xs sm:text-sm text-slate-800 focus:outline-none resize-none overflow-y-auto leading-relaxed"
|
||||
style="height: 24px; max-height: 120px;"></textarea>
|
||||
</div>
|
||||
|
||||
<button type="submit" id="send-btn"
|
||||
class="bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white p-2.5 rounded-xl transition shrink-0 shadow-sm cursor-pointer">
|
||||
<i class="fa-solid fa-paper-plane text-sm"></i>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<!-- Скрипты клиентской логики -->
|
||||
<script src="/js/auth.js"></script>
|
||||
<script src="/js/tasks.js"></script>
|
||||
<script src="/js/chat/task_widget.js"></script>
|
||||
<script src="/js/chat/core.js"></script>
|
||||
<script src="/js/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,308 +1,62 @@
|
||||
function showAuthModal() {
|
||||
const el = document.getElementById("auth-modal");
|
||||
if (el) el.classList.remove("hidden");
|
||||
}
|
||||
/**
|
||||
* ===============================================================================
|
||||
* FILE: static/js/auth.js
|
||||
* ROLE: Управление сессией пользователя, токенами и корректным выходом (Logout).
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
function hideAuthModal() {
|
||||
const el = document.getElementById("auth-modal");
|
||||
if (el) el.classList.add("hidden");
|
||||
}
|
||||
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;
|
||||
},
|
||||
|
||||
async function handleLogin(e) {
|
||||
if (e && e.preventDefault) e.preventDefault();
|
||||
|
||||
const usernameInput = document.getElementById("auth-username-input");
|
||||
const passwordInput = document.getElementById("auth-password-input");
|
||||
const errorEl = document.getElementById("auth-error");
|
||||
getUserId() {
|
||||
return parseInt(localStorage.getItem("user_id") || "1", 10);
|
||||
},
|
||||
|
||||
if (!usernameInput || !passwordInput) return;
|
||||
logout() {
|
||||
console.log("[Auth] Выполняется выход из учетной записи...");
|
||||
|
||||
const username = usernameInput.value.trim();
|
||||
const password = passwordInput.value;
|
||||
// 1. Полная очистка хранилищ браузера
|
||||
localStorage.removeItem("auth_token");
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("user_id");
|
||||
sessionStorage.clear();
|
||||
|
||||
if (!username || !password) return;
|
||||
|
||||
if (errorEl) errorEl.classList.add("hidden");
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/v1/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password })
|
||||
// 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=/`;
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
// 3. Перезагрузка страницы для сброса состояния интерфейса
|
||||
window.location.reload();
|
||||
},
|
||||
|
||||
if (res.status === 200) {
|
||||
// Используем прямой строковый ключ, чтобы избежать ошибки ReferenceError
|
||||
API_TOKEN = data.token;
|
||||
CURRENT_USERNAME = data.username;
|
||||
IS_ADMIN = data.is_admin;
|
||||
IS_GUEST = false;
|
||||
|
||||
localStorage.setItem("scud_api_auth_token", data.token);
|
||||
localStorage.setItem("scud_username", data.username);
|
||||
localStorage.setItem("scud_is_admin", data.is_admin ? "true" : "false");
|
||||
localStorage.removeItem("scud_is_guest");
|
||||
|
||||
hideAuthModal();
|
||||
updateUIState();
|
||||
|
||||
if (typeof loadTasks === 'function') {
|
||||
loadTasks();
|
||||
}
|
||||
} else {
|
||||
if (errorEl) {
|
||||
errorEl.innerText = data.detail || "Ошибка авторизации";
|
||||
errorEl.classList.remove("hidden");
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Auth Error]", err);
|
||||
if (errorEl) {
|
||||
errorEl.innerText = "Ошибка соединения с сервером";
|
||||
errorEl.classList.remove("hidden");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function enableGuestMode() {
|
||||
IS_GUEST = true;
|
||||
API_TOKEN = "";
|
||||
CURRENT_USERNAME = "Гость";
|
||||
IS_ADMIN = false;
|
||||
localStorage.setItem("scud_is_guest", "true");
|
||||
hideAuthModal();
|
||||
updateUIState();
|
||||
}
|
||||
|
||||
function logout() {
|
||||
localStorage.removeItem("scud_api_auth_token");
|
||||
localStorage.removeItem("scud_username");
|
||||
localStorage.removeItem("scud_is_admin");
|
||||
localStorage.removeItem("scud_is_guest");
|
||||
API_TOKEN = "";
|
||||
CURRENT_USERNAME = "";
|
||||
IS_ADMIN = false;
|
||||
IS_GUEST = false;
|
||||
showAuthModal();
|
||||
}
|
||||
|
||||
function updateUIState() {
|
||||
const tasksBtn = document.getElementById("tasks-drawer-btn");
|
||||
const adminBtn = document.getElementById("admin-users-btn");
|
||||
const changePwdBtn = document.getElementById("change-pwd-btn");
|
||||
const guestBadge = document.getElementById("guest-badge");
|
||||
const usernameBadge = document.getElementById("username-badge");
|
||||
|
||||
if (typeof IS_GUEST !== 'undefined' && IS_GUEST) {
|
||||
if (tasksBtn) tasksBtn.classList.add("hidden");
|
||||
if (adminBtn) adminBtn.classList.add("hidden");
|
||||
if (changePwdBtn) changePwdBtn.classList.add("hidden");
|
||||
if (guestBadge) guestBadge.classList.remove("hidden");
|
||||
if (usernameBadge) usernameBadge.classList.add("hidden");
|
||||
} else {
|
||||
if (tasksBtn) tasksBtn.classList.remove("hidden");
|
||||
if (changePwdBtn) changePwdBtn.classList.remove("hidden");
|
||||
if (guestBadge) guestBadge.classList.add("hidden");
|
||||
|
||||
if (usernameBadge) {
|
||||
usernameBadge.innerText = (typeof CURRENT_USERNAME !== 'undefined' && CURRENT_USERNAME) ? CURRENT_USERNAME : "User";
|
||||
usernameBadge.classList.remove("hidden");
|
||||
}
|
||||
|
||||
if (adminBtn) {
|
||||
const isAdminUser = (typeof IS_ADMIN !== 'undefined' && IS_ADMIN) || (typeof CURRENT_USERNAME !== 'undefined' && CURRENT_USERNAME === "puh");
|
||||
if (isAdminUser) {
|
||||
adminBtn.classList.remove("hidden");
|
||||
} else {
|
||||
adminBtn.classList.add("hidden");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function openChangePasswordModal() {
|
||||
const el = document.getElementById("change-pwd-modal");
|
||||
if (el) el.classList.remove("hidden");
|
||||
}
|
||||
|
||||
function closeChangePasswordModal() {
|
||||
const el = document.getElementById("change-pwd-modal");
|
||||
if (el) el.classList.add("hidden");
|
||||
|
||||
const err = document.getElementById("pwd-error");
|
||||
const succ = document.getElementById("pwd-success");
|
||||
if (err) err.classList.add("hidden");
|
||||
if (succ) succ.classList.add("hidden");
|
||||
|
||||
document.getElementById("old-pwd-input").value = "";
|
||||
document.getElementById("new-pwd-input").value = "";
|
||||
const confirmInput = document.getElementById("confirm-pwd-input");
|
||||
if (confirmInput) confirmInput.value = "";
|
||||
}
|
||||
|
||||
async function handleChangePassword(e) {
|
||||
if (e && e.preventDefault) e.preventDefault();
|
||||
const old_password = document.getElementById("old-pwd-input").value;
|
||||
const new_password = document.getElementById("new-pwd-input").value;
|
||||
const confirmInput = document.getElementById("confirm-pwd-input");
|
||||
const confirm_password = confirmInput ? confirmInput.value : new_password;
|
||||
const errorEl = document.getElementById("pwd-error");
|
||||
const successEl = document.getElementById("pwd-success");
|
||||
|
||||
if (errorEl) errorEl.classList.add("hidden");
|
||||
if (successEl) successEl.classList.add("hidden");
|
||||
|
||||
if (new_password !== confirm_password) {
|
||||
if (errorEl) {
|
||||
errorEl.innerText = "Новые пароли не совпадают";
|
||||
errorEl.classList.remove("hidden");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const token = typeof API_TOKEN !== 'undefined' ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
const res = await fetch("/api/v1/auth/change-password", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": "Bearer " + token
|
||||
},
|
||||
body: JSON.stringify({ old_password, new_password })
|
||||
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();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (res.status === 200) {
|
||||
if (successEl) {
|
||||
successEl.innerText = "Пароль успешно изменен!";
|
||||
successEl.classList.remove("hidden");
|
||||
}
|
||||
setTimeout(closeChangePasswordModal, 1500);
|
||||
} else {
|
||||
if (errorEl) {
|
||||
errorEl.innerText = data.detail || "Ошибка при смене пароля";
|
||||
errorEl.classList.remove("hidden");
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (errorEl) {
|
||||
errorEl.innerText = "Ошибка соединения с сервером";
|
||||
errorEl.classList.remove("hidden");
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function openAdminModal() {
|
||||
const el = document.getElementById("admin-modal");
|
||||
if (el) el.classList.remove("hidden");
|
||||
loadUsersList();
|
||||
}
|
||||
// Инициализация при загрузке скрипта
|
||||
AuthManager.init();
|
||||
|
||||
function closeAdminModal() {
|
||||
const el = document.getElementById("admin-modal");
|
||||
if (el) el.classList.add("hidden");
|
||||
}
|
||||
|
||||
async function loadUsersList() {
|
||||
const listEl = document.getElementById("admin-users-list");
|
||||
if (!listEl) return;
|
||||
listEl.innerHTML = '<div class="text-xs text-slate-400 py-4 text-center">Загрузка пользователей...</div>';
|
||||
|
||||
try {
|
||||
const token = typeof API_TOKEN !== 'undefined' ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
const res = await fetch("/api/v1/admin/users", {
|
||||
headers: { "Authorization": "Bearer " + token }
|
||||
});
|
||||
const users = await res.json();
|
||||
|
||||
if (res.status === 200) {
|
||||
listEl.innerHTML = users.map(u => {
|
||||
const adminTag = u.is_admin ? '<span class="ml-1.5 text-[9px] bg-indigo-100 text-indigo-700 px-1.5 py-0.5 rounded font-bold">ADMIN</span>' : '<span class="ml-1.5 text-[9px] bg-slate-100 text-slate-600 px-1.5 py-0.5 rounded">USER</span>';
|
||||
const fullNameHtml = u.full_name ? `<div class="text-[11px] text-slate-500 font-normal">${u.full_name}</div>` : '';
|
||||
const dateStr = u.created_at ? u.created_at.split(' ')[0] : '—';
|
||||
const deleteBtn = u.username !== CURRENT_USERNAME ? `<button type="button" onclick="deleteUser(${u.id}, '${u.username}')" class="text-red-500 hover:text-red-700 p-1"><i class="fa-solid fa-trash-can"></i></button>` : '<span class="text-[10px] text-slate-400">Вы</span>';
|
||||
|
||||
return `
|
||||
<div class="flex justify-between items-center bg-slate-50 border border-slate-200 p-2.5 rounded-xl text-xs">
|
||||
<div>
|
||||
<div class="flex items-center">
|
||||
<span class="font-bold text-slate-800">${u.username}</span>
|
||||
${adminTag}
|
||||
</div>
|
||||
${fullNameHtml}
|
||||
<div class="text-[10px] text-slate-400 mt-0.5">Создан: ${dateStr}</div>
|
||||
</div>
|
||||
${deleteBtn}
|
||||
</div>
|
||||
`;
|
||||
}).join("");
|
||||
} else {
|
||||
listEl.innerHTML = `<div class="text-xs text-red-500 py-2">${users.detail}</div>`;
|
||||
}
|
||||
} catch (err) {
|
||||
listEl.innerHTML = '<div class="text-xs text-red-500 py-2">Ошибка загрузки пользователей</div>';
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreateUser(e) {
|
||||
if (e && e.preventDefault) e.preventDefault();
|
||||
const username = document.getElementById("new-user-name").value.trim();
|
||||
const password = document.getElementById("new-user-pwd").value;
|
||||
const fullNameInput = document.getElementById("new-user-fullname");
|
||||
const full_name = fullNameInput ? fullNameInput.value.trim() : "";
|
||||
const adminCheckbox = document.getElementById("new-user-is-admin");
|
||||
const is_admin = adminCheckbox ? adminCheckbox.checked : false;
|
||||
const msgEl = document.getElementById("admin-msg");
|
||||
|
||||
if (msgEl) msgEl.classList.add("hidden");
|
||||
|
||||
try {
|
||||
const token = typeof API_TOKEN !== 'undefined' ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
const res = await fetch("/api/v1/admin/users", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": "Bearer " + token
|
||||
},
|
||||
body: JSON.stringify({ username, password, full_name, is_admin })
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (res.status === 200) {
|
||||
document.getElementById("new-user-name").value = "";
|
||||
document.getElementById("new-user-pwd").value = "";
|
||||
if (fullNameInput) fullNameInput.value = "";
|
||||
if (adminCheckbox) adminCheckbox.checked = false;
|
||||
loadUsersList();
|
||||
} else {
|
||||
if (msgEl) {
|
||||
msgEl.innerText = data.detail || "Ошибка";
|
||||
msgEl.classList.remove("hidden");
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (msgEl) {
|
||||
msgEl.innerText = "Ошибка связи с сервером";
|
||||
msgEl.classList.remove("hidden");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteUser(userId, username) {
|
||||
if (!confirm("Удалить пользователя " + username + "?")) return;
|
||||
|
||||
try {
|
||||
const token = typeof API_TOKEN !== 'undefined' ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
await fetch("/api/v1/admin/users/" + userId, {
|
||||
method: "DELETE",
|
||||
headers: { "Authorization": "Bearer " + token }
|
||||
});
|
||||
loadUsersList();
|
||||
} catch (err) {
|
||||
alert("Ошибка при удалении");
|
||||
}
|
||||
}
|
||||
// Глобальная доступность функции для onclick в HTML
|
||||
window.logout = () => AuthManager.logout();
|
||||
@@ -1,531 +1,67 @@
|
||||
/**
|
||||
===============================================================================
|
||||
FILE: modules/web_api/static/js/chat/core.js
|
||||
PROJECT: SCUD Orion AI (Unified Architecture)
|
||||
MODULE: web_api / static / js / chat
|
||||
ROLE: Клиентский интерфейс диалога, Drag-and-Drop вложений, блокировка ввода
|
||||
при активных кнопках, динамический вызов инлайн-редактора и двусторонний Diff.
|
||||
===============================================================================
|
||||
*/
|
||||
* ===============================================================================
|
||||
* FILE: static/js/chat/core.js
|
||||
* ROLE: Отправка сообщений в API с токеном и обработка ошибок.
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
function updateInputHeight(el) {
|
||||
if (!el) return;
|
||||
el.style.height = "24px";
|
||||
const newHeight = Math.min(el.scrollHeight, 120);
|
||||
el.style.height = newHeight + "px";
|
||||
}
|
||||
async function sendMessage(userMessageText) {
|
||||
const chatInput = document.getElementById("chat-input");
|
||||
const message = userMessageText || (chatInput ? chatInput.value.trim() : "");
|
||||
if (!message) return;
|
||||
|
||||
let selectedFile = null;
|
||||
|
||||
function handleFileSelect(e) {
|
||||
const file = e.target.files[0];
|
||||
if (!file) return;
|
||||
|
||||
if (file.size > 15 * 1024 * 1024) {
|
||||
alert("Файл слишком большой. Максимальный размер: 15 МБ");
|
||||
e.target.value = "";
|
||||
return;
|
||||
if (chatInput && !userMessageText) {
|
||||
chatInput.value = "";
|
||||
}
|
||||
|
||||
selectedFile = file;
|
||||
const fileNameEl = document.getElementById("file-name-display");
|
||||
const fileSizeEl = document.getElementById("file-size-display");
|
||||
const previewContainer = document.getElementById("file-preview-container");
|
||||
|
||||
if (fileNameEl) fileNameEl.innerText = file.name;
|
||||
if (fileSizeEl) fileSizeEl.innerText = `(${(file.size / 1024).toFixed(1)} KB)`;
|
||||
if (previewContainer) previewContainer.classList.remove("hidden");
|
||||
}
|
||||
|
||||
function clearAttachedFile() {
|
||||
selectedFile = null;
|
||||
const fileInput = document.getElementById("file-input");
|
||||
const previewContainer = document.getElementById("file-preview-container");
|
||||
if (fileInput) fileInput.value = "";
|
||||
if (previewContainer) previewContainer.classList.add("hidden");
|
||||
}
|
||||
|
||||
function setInputLocked(isLocked) {
|
||||
const input = document.getElementById("user-input");
|
||||
const sendBtn = document.getElementById("send-btn");
|
||||
if (input) {
|
||||
input.disabled = isLocked;
|
||||
if (isLocked) {
|
||||
input.placeholder = "Выберите действие с помощью кнопок выше...";
|
||||
input.classList.add("cursor-not-allowed", "opacity-60", "bg-slate-200/50");
|
||||
} else {
|
||||
input.placeholder = "Команда, вопрос или перетащите файл сюда...";
|
||||
input.classList.remove("cursor-not-allowed", "opacity-60", "bg-slate-200/50");
|
||||
}
|
||||
}
|
||||
if (sendBtn) {
|
||||
sendBtn.disabled = isLocked;
|
||||
if (isLocked) {
|
||||
sendBtn.classList.add("opacity-40", "cursor-not-allowed");
|
||||
} else {
|
||||
sendBtn.classList.remove("opacity-40", "cursor-not-allowed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function disableAllActionButtons() {
|
||||
const allBtnContainers = document.querySelectorAll(".action-buttons-container");
|
||||
allBtnContainers.forEach(container => {
|
||||
container.querySelectorAll("button").forEach(btn => {
|
||||
btn.disabled = true;
|
||||
btn.classList.add("opacity-40", "cursor-not-allowed");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function handleActionButtonClick(text) {
|
||||
disableAllActionButtons();
|
||||
setInputLocked(false);
|
||||
const input = document.getElementById("user-input");
|
||||
if (input) {
|
||||
input.value = text;
|
||||
sendMessage();
|
||||
}
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
if (!text) return "";
|
||||
return text
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
// --- [INLINE PROMPT EDITOR & FULL DIFF BUILDER] ---
|
||||
function openInlinePromptEditor(btnEl) {
|
||||
const cardContainer = btnEl.closest(".chat-message-card");
|
||||
if (!cardContainer) return;
|
||||
|
||||
const editorContainer = cardContainer.querySelector(".inline-prompt-editor-container");
|
||||
const diffView = cardContainer.querySelector(".prompt-preview-diff-view");
|
||||
const textarea = cardContainer.querySelector(".inline-prompt-textarea");
|
||||
|
||||
if (editorContainer && textarea) {
|
||||
editorContainer.classList.remove("hidden");
|
||||
|
||||
if (diffView) {
|
||||
const targetHeight = Math.max(diffView.offsetHeight, 320);
|
||||
textarea.style.height = `${targetHeight}px`;
|
||||
}
|
||||
|
||||
textarea.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function closeInlinePromptEditor(btnEl) {
|
||||
const cardContainer = btnEl.closest(".chat-message-card");
|
||||
if (!cardContainer) return;
|
||||
const editorContainer = cardContainer.querySelector(".inline-prompt-editor-container");
|
||||
if (editorContainer) editorContainer.classList.add("hidden");
|
||||
}
|
||||
|
||||
function parsePromptIntoMap(text) {
|
||||
const map = new Map();
|
||||
if (!text) return map;
|
||||
const lines = text.split("\n");
|
||||
for (let line of lines) {
|
||||
let trimmed = line.trim();
|
||||
if (!trimmed) continue;
|
||||
const match = trimmed.match(/^(\d+)[\.\s]+(\d+)[\.\s\:\-]*(.*)$/);
|
||||
if (match) {
|
||||
const key = `${match[1]}.${match[2]}`;
|
||||
map.set(key, { sec: parseInt(match[1]), itm: parseInt(match[2]), content: match[3].trim(), full: trimmed });
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function buildHighlightedPromptHtml(newRawText, originalBaselineText) {
|
||||
const origMap = parsePromptIntoMap(originalBaselineText);
|
||||
const newMap = parsePromptIntoMap(newRawText);
|
||||
|
||||
const formattedLines = [];
|
||||
const rawLines = newRawText.split("\n");
|
||||
const handledNewKeys = new Set();
|
||||
|
||||
let currentSection = null;
|
||||
|
||||
for (let line of rawLines) {
|
||||
let trimmed = line.trim();
|
||||
if (!trimmed) {
|
||||
formattedLines.push("");
|
||||
continue;
|
||||
}
|
||||
|
||||
const secMatch = trimmed.match(/^(\d+)[\.\s\:\-]+([^\d].*)$/);
|
||||
const subMatch = trimmed.match(/^(\d+)[\.\s]+(\d+)[\.\s\:\-]*(.*)$/);
|
||||
|
||||
if (subMatch) {
|
||||
const key = `${subMatch[1]}.${subMatch[2]}`;
|
||||
handledNewKeys.add(key);
|
||||
currentSection = parseInt(subMatch[1]);
|
||||
const cleanContent = subMatch[3].trim();
|
||||
const fullItemStr = `${subMatch[1]}.${subMatch[2]}. ${cleanContent}`;
|
||||
|
||||
if (!origMap.has(key) || origMap.get(key).content !== cleanContent) {
|
||||
// Добавленный или изменённый пункт
|
||||
formattedLines.push(` <span class="text-rose-600 font-bold bg-rose-50 px-1.5 py-0.5 rounded border border-rose-300">${escapeHtml(fullItemStr)}</span>`);
|
||||
} else {
|
||||
formattedLines.push(` ${escapeHtml(fullItemStr)}`);
|
||||
}
|
||||
} else if (secMatch && !anyLower(secMatch[2].slice(0, 15))) {
|
||||
// Заголовок раздела
|
||||
currentSection = parseInt(secMatch[1]);
|
||||
formattedLines.push(escapeHtml(trimmed));
|
||||
} else {
|
||||
formattedLines.push(escapeHtml(trimmed));
|
||||
}
|
||||
// Отображаем сообщение пользователя в чате
|
||||
if (typeof appendMessageToUI === "function") {
|
||||
appendMessageToUI("user", message);
|
||||
}
|
||||
|
||||
// Добавляем удаленные пункты (были в оригинале, но отсутствуют в новом тексте)
|
||||
for (let [origKey, origObj] of origMap.entries()) {
|
||||
if (!handledNewKeys.has(origKey)) {
|
||||
const strikeMarkup = ` <span class="line-through text-rose-600 font-bold bg-rose-50 px-1.5 py-0.5 rounded border border-rose-300 opacity-80">${origKey}. ${escapeHtml(origObj.content)} [УДАЛЕНИЕ]</span>`;
|
||||
formattedLines.push(strikeMarkup);
|
||||
}
|
||||
}
|
||||
|
||||
return formattedLines.join("\n");
|
||||
}
|
||||
|
||||
function anyLower(str) {
|
||||
return /[а-яa-z]/.test(str);
|
||||
}
|
||||
|
||||
async function saveManualPromptDraft(btnEl) {
|
||||
const cardContainer = btnEl.closest(".chat-message-card");
|
||||
if (!cardContainer) return;
|
||||
|
||||
const textarea = cardContainer.querySelector(".inline-prompt-textarea");
|
||||
const previewTextEl = cardContainer.querySelector(".prompt-preview-diff-view");
|
||||
if (!textarea) return;
|
||||
|
||||
const newText = textarea.value.trim();
|
||||
if (!newText) return;
|
||||
|
||||
const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
// Подготовка заголовков с гарантированным токеном
|
||||
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";
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/v1/chat/draft", {
|
||||
const response = await fetch("/api/v1/chat", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": "Bearer " + token
|
||||
"Authorization": `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
session_id: "web_session_main",
|
||||
draft_text: newText
|
||||
message: message,
|
||||
session_id: sessionId,
|
||||
user_id: userId
|
||||
})
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
closeInlinePromptEditor(btnEl);
|
||||
if (previewTextEl) {
|
||||
const baseline = cardContainer.dataset.originalBaseline || "";
|
||||
const highlightedHtml = buildHighlightedPromptHtml(newText, baseline);
|
||||
previewTextEl.innerHTML = highlightedHtml;
|
||||
if (response.status === 403) {
|
||||
console.warn("[Chat] Получен 403 Forbidden. Сбрасываем сессию и повторяем...");
|
||||
localStorage.removeItem("auth_token");
|
||||
if (typeof appendMessageToUI === "function") {
|
||||
appendMessageToUI("assistant", "⚠️ Сессия была обновлена. Пожалуйста, отправьте сообщение повторно.");
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
alert("Ошибка сохранения черновика: " + err);
|
||||
}
|
||||
}
|
||||
|
||||
// --- [CHAT SEND PIPELINE] ---
|
||||
async function sendMessage(e) {
|
||||
if (e && e.preventDefault) e.preventDefault();
|
||||
|
||||
const input = document.getElementById("user-input");
|
||||
const chatWindow = document.getElementById("chat-window");
|
||||
const sendBtn = document.getElementById("send-btn");
|
||||
|
||||
if (!input || !chatWindow) return;
|
||||
const text = input.value.trim();
|
||||
|
||||
if (!text && !selectedFile) return;
|
||||
|
||||
disableAllActionButtons();
|
||||
|
||||
let userDisplayHtml = escapeHtml(text);
|
||||
if (selectedFile) {
|
||||
userDisplayHtml = `<div class="font-bold border-b border-indigo-400/40 pb-1 mb-1 text-[11px] flex items-center gap-1.5">
|
||||
<i class="fa-solid fa-file"></i> ${escapeHtml(selectedFile.name)}
|
||||
</div>` + userDisplayHtml;
|
||||
}
|
||||
|
||||
const userMsgHtml = `
|
||||
<div class="flex justify-end mb-3">
|
||||
<div class="bg-indigo-600 text-white rounded-2xl px-4 py-2.5 max-w-2xl text-xs sm:text-sm shadow-sm">
|
||||
${userDisplayHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
chatWindow.insertAdjacentHTML("beforeend", userMsgHtml);
|
||||
|
||||
input.value = "";
|
||||
updateInputHeight(input);
|
||||
chatWindow.scrollTop = chatWindow.scrollHeight;
|
||||
|
||||
if (sendBtn) {
|
||||
sendBtn.disabled = true;
|
||||
sendBtn.classList.add("opacity-50");
|
||||
}
|
||||
|
||||
const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
const isGuest = typeof IS_GUEST !== 'undefined' ? IS_GUEST : (localStorage.getItem("scud_is_guest") === "true");
|
||||
|
||||
const endpoint = isGuest ? "/api/v1/chat/guest" : "/api/v1/chat";
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append("session_id", "web_session_main");
|
||||
formData.append("message", text || "Проанализируй прикрепленный файл");
|
||||
|
||||
if (selectedFile instanceof File) {
|
||||
formData.append("file", selectedFile, selectedFile.name);
|
||||
}
|
||||
|
||||
const headers = {};
|
||||
if (!isGuest && token) {
|
||||
headers["Authorization"] = "Bearer " + token;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: headers,
|
||||
body: formData
|
||||
});
|
||||
|
||||
if (res.status === 401 && !isGuest) {
|
||||
if (typeof logout === 'function') logout();
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
const assistantTitle = isGuest ? "Локальная нейросеть (Гость)" : "ИИ-Ассистент SCUD Orion AI";
|
||||
const replyText = data.reply || "Пустой ответ от нейросети";
|
||||
|
||||
let actionButtonsHtml = "";
|
||||
const actionData = data.action_type || data.action;
|
||||
|
||||
if (actionData && actionData.buttons && actionData.buttons.length > 0) {
|
||||
const buttonsMarkup = actionData.buttons.map(btn => {
|
||||
let btnClasses = "bg-slate-100 hover:bg-slate-200 active:bg-slate-300 text-slate-700 border border-slate-300";
|
||||
let iconMarkup = '<i class="fa-solid fa-arrow-right text-[10px] opacity-60"></i>';
|
||||
|
||||
const labelLower = (btn.label || "").toLowerCase();
|
||||
const isPrimary = btn.style === "primary" || labelLower.includes("подтверд") || labelLower.startsWith("да");
|
||||
const isDanger = btn.style === "danger" || labelLower.includes("отмен") || labelLower.startsWith("нет") || labelLower.includes("законч") || labelLower.includes("заверш");
|
||||
const isEdit = labelLower.includes("редактир");
|
||||
|
||||
if (isPrimary) {
|
||||
btnClasses = "bg-emerald-600 hover:bg-emerald-700 active:bg-emerald-800 text-white shadow-sm";
|
||||
iconMarkup = '<i class="fa-solid fa-check"></i>';
|
||||
} else if (isDanger) {
|
||||
btnClasses = "bg-rose-50 hover:bg-rose-100 active:bg-rose-200 text-rose-700 border border-rose-300";
|
||||
iconMarkup = '<i class="fa-solid fa-xmark"></i>';
|
||||
} else if (isEdit) {
|
||||
btnClasses = "bg-indigo-50 hover:bg-indigo-100 active:bg-indigo-200 text-indigo-700 border border-indigo-300";
|
||||
iconMarkup = '<i class="fa-solid fa-pen-to-square text-xs"></i>';
|
||||
}
|
||||
|
||||
const clickHandler = isEdit ? "openInlinePromptEditor(this)" : `handleActionButtonClick('${escapeHtml(btn.value)}')`;
|
||||
|
||||
return `
|
||||
<button type="button" onclick="${clickHandler}"
|
||||
class="${btnClasses} font-semibold px-3 py-1.5 rounded-xl text-xs flex items-center gap-1.5 transition cursor-pointer">
|
||||
${iconMarkup}
|
||||
<span>${escapeHtml(btn.label)}</span>
|
||||
</button>
|
||||
`;
|
||||
}).join("");
|
||||
|
||||
actionButtonsHtml = `
|
||||
<div class="action-buttons-container flex flex-wrap items-center gap-2 mt-3 pt-2.5 border-t border-slate-100">
|
||||
${buttonsMarkup}
|
||||
</div>
|
||||
`;
|
||||
|
||||
setInputLocked(true);
|
||||
} else {
|
||||
setInputLocked(false);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Ошибка сервера (HTTP ${response.status})`);
|
||||
}
|
||||
|
||||
let previewEditorHtml = "";
|
||||
let rawDraftText = "";
|
||||
let baselineText = "";
|
||||
const data = await response.json();
|
||||
const reply = data.response || data.message || "Ответ получен без текста.";
|
||||
|
||||
if (actionData && actionData.type === "PROMPT_PREVIEW") {
|
||||
rawDraftText = actionData.raw_draft || "";
|
||||
baselineText = actionData.baseline_prompt || rawDraftText;
|
||||
previewEditorHtml = `
|
||||
<div class="inline-prompt-editor-container hidden mt-3 p-3 bg-slate-50 border border-slate-300 rounded-xl space-y-2">
|
||||
<p class="text-[11px] font-bold text-slate-700 uppercase"><i class="fa-solid fa-pen-to-square mr-1"></i> Ручное редактирование текста промпта:</p>
|
||||
<textarea class="inline-prompt-textarea w-full bg-white border border-slate-300 rounded-lg p-3 text-xs font-mono text-slate-800 focus:outline-none focus:border-indigo-600 resize-y shadow-inner leading-relaxed">${escapeHtml(rawDraftText)}</textarea>
|
||||
<div class="flex justify-end gap-2 pt-1">
|
||||
<button type="button" onclick="closeInlinePromptEditor(this)" class="px-3 py-1.5 rounded-lg text-xs text-slate-600 bg-slate-200 hover:bg-slate-300 transition">Свернуть</button>
|
||||
<button type="button" onclick="saveManualPromptDraft(this)" class="px-3.5 py-1.5 rounded-lg text-xs font-semibold text-white bg-indigo-600 hover:bg-indigo-700 shadow-sm transition">Сохранить правки</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
let interactiveWidgetHtml = "";
|
||||
if (actionData && actionData.type === "TASK_INTERACTIVE_CARD" && typeof renderInteractiveTaskCard === "function") {
|
||||
interactiveWidgetHtml = renderInteractiveTaskCard(actionData.tasks);
|
||||
}
|
||||
|
||||
const botMsgHtml = `
|
||||
<div class="chat-message-card bg-white border border-slate-200 rounded-2xl p-3.5 shadow-sm max-w-2xl mb-3" data-original-baseline="${escapeHtml(baselineText)}">
|
||||
<p class="text-[11px] font-bold text-indigo-600 uppercase tracking-wider mb-1">
|
||||
<i class="fa-solid fa-robot mr-1"></i> ${assistantTitle}
|
||||
</p>
|
||||
<div class="prompt-preview-diff-view text-slate-800 text-xs sm:text-sm whitespace-pre-wrap leading-relaxed">${replyText}</div>
|
||||
${previewEditorHtml}
|
||||
${interactiveWidgetHtml}
|
||||
${actionButtonsHtml}
|
||||
</div>
|
||||
`;
|
||||
chatWindow.insertAdjacentHTML("beforeend", botMsgHtml);
|
||||
chatWindow.scrollTop = chatWindow.scrollHeight;
|
||||
|
||||
clearAttachedFile();
|
||||
|
||||
if (!isGuest && typeof loadTasks === 'function') {
|
||||
loadTasks();
|
||||
if (typeof appendMessageToUI === "function") {
|
||||
appendMessageToUI("assistant", reply);
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.error("[Chat Error]", err);
|
||||
const errorHtml = `
|
||||
<div class="bg-red-50 border border-red-200 rounded-2xl p-3.5 max-w-2xl text-red-700 text-xs sm:text-sm mb-3">
|
||||
Ошибка связи с сервером.
|
||||
</div>
|
||||
`;
|
||||
chatWindow.insertAdjacentHTML("beforeend", errorHtml);
|
||||
chatWindow.scrollTop = chatWindow.scrollHeight;
|
||||
setInputLocked(false);
|
||||
} finally {
|
||||
const inputEl = document.getElementById("user-input");
|
||||
if (sendBtn && (!inputEl || !inputEl.disabled)) {
|
||||
sendBtn.disabled = false;
|
||||
sendBtn.classList.remove("opacity-50");
|
||||
console.error("[Chat Error]:", err);
|
||||
if (typeof appendMessageToUI === "function") {
|
||||
appendMessageToUI("assistant", `⚠️ Не удалось связаться с сервером: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- [DRAG & DROP AND KEYBOARD LISTENERS] ---
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const input = document.getElementById("user-input");
|
||||
const dropZone = document.getElementById("chat-window")?.parentElement;
|
||||
const dropOverlay = document.getElementById("drop-overlay");
|
||||
|
||||
if (input) {
|
||||
let historyIndex = -1;
|
||||
let localHistory = JSON.parse(localStorage.getItem("scud_chat_input_history") || "[]");
|
||||
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
if (input.disabled) return;
|
||||
const text = input.value.trim();
|
||||
if (text) {
|
||||
if (localHistory.length === 0 || localHistory[0] !== text) {
|
||||
localHistory.unshift(text);
|
||||
if (localHistory.length > 50) localHistory.pop();
|
||||
localStorage.setItem("scud_chat_input_history", JSON.stringify(localHistory));
|
||||
}
|
||||
historyIndex = -1;
|
||||
}
|
||||
sendMessage(e);
|
||||
updateInputHeight(input);
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === "ArrowUp") {
|
||||
const textBeforeCursor = input.value.substring(0, input.selectionStart);
|
||||
const isFirstLine = !textBeforeCursor.includes("\n");
|
||||
|
||||
if (isFirstLine && input.selectionStart === 0 && localHistory.length > 0) {
|
||||
if (historyIndex < localHistory.length - 1) {
|
||||
e.preventDefault();
|
||||
if (historyIndex === -1) {
|
||||
input.dataset.draft = input.value;
|
||||
}
|
||||
historyIndex++;
|
||||
input.value = localHistory[historyIndex];
|
||||
updateInputHeight(input);
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (e.key === "ArrowDown") {
|
||||
const textAfterCursor = input.value.substring(input.selectionEnd);
|
||||
const isLastLine = !textAfterCursor.includes("\n");
|
||||
|
||||
if (isLastLine && input.selectionEnd === input.value.length && historyIndex >= 0) {
|
||||
e.preventDefault();
|
||||
if (historyIndex > 0) {
|
||||
historyIndex--;
|
||||
input.value = localHistory[historyIndex];
|
||||
} else {
|
||||
historyIndex = -1;
|
||||
input.value = input.dataset.draft || "";
|
||||
}
|
||||
updateInputHeight(input);
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (dropZone && dropOverlay) {
|
||||
["dragenter", "dragover", "dragleave", "drop"].forEach(eventName => {
|
||||
dropZone.addEventListener(eventName, (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}, false);
|
||||
});
|
||||
|
||||
["dragenter", "dragover"].forEach(eventName => {
|
||||
dropZone.addEventListener(eventName, () => {
|
||||
dropOverlay.classList.remove("hidden");
|
||||
dropOverlay.classList.add("flex");
|
||||
}, false);
|
||||
});
|
||||
|
||||
["dragleave", "drop"].forEach(eventName => {
|
||||
dropZone.addEventListener(eventName, (e) => {
|
||||
if (eventName === "drop" || e.target === dropZone || !dropZone.contains(e.relatedTarget)) {
|
||||
dropOverlay.classList.add("hidden");
|
||||
dropOverlay.classList.remove("flex");
|
||||
}
|
||||
}, false);
|
||||
});
|
||||
|
||||
dropZone.addEventListener("drop", (e) => {
|
||||
const dt = e.dataTransfer;
|
||||
const files = dt.files;
|
||||
|
||||
if (files && files.length > 0) {
|
||||
const file = files[0];
|
||||
handleFileSelect({ target: { files: [file] } });
|
||||
|
||||
const fileInput = document.getElementById("file-input");
|
||||
if (fileInput) {
|
||||
const dataTransfer = new DataTransfer();
|
||||
dataTransfer.items.add(file);
|
||||
fileInput.files = dataTransfer.files;
|
||||
}
|
||||
}
|
||||
}, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,208 +1,445 @@
|
||||
/**
|
||||
/*
|
||||
===============================================================================
|
||||
FILE: modules/web_api/static/js/chat/task_widget.js
|
||||
ROLE: Генеративный UI интерактивных карточек задач внутри диалога чата
|
||||
(фильтры, inline-чекбоксы статусов, быстрое добавление и удаление).
|
||||
ROLE: Интерактивные виджеты задач и срезов СКУД (SNAPSHOTS_CARD) с чекбоксами.
|
||||
===============================================================================
|
||||
*/
|
||||
|
||||
let activeWidgetTasksMap = new Map();
|
||||
window.activeTaskFilter = window.activeTaskFilter || 'IN_PROGRESS';
|
||||
window.currentTasksCache = window.currentTasksCache || [];
|
||||
|
||||
function renderTaskItemsHtml(tasks, filterStatus) {
|
||||
const filtered = tasks.filter(t => {
|
||||
if (filterStatus === "ALL") return true;
|
||||
return t.status === filterStatus;
|
||||
});
|
||||
function getAuthHeaders() {
|
||||
const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
const headers = { 'Content-Type': 'application/json' };
|
||||
if (token) {
|
||||
headers['Authorization'] = 'Bearer ' + token;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
if (filtered.length === 0) {
|
||||
const label = filterStatus === 'BACKLOG' ? 'В планах' : filterStatus === 'IN_PROGRESS' ? 'В работе' : filterStatus === 'COMPLETED' ? 'Завершенные' : 'Все';
|
||||
return `<div class="text-slate-400 text-xs py-4 text-center">Нет задач со статусом «${label}»</div>`;
|
||||
window.sendChatAction = function(actionText) {
|
||||
const input = document.getElementById("user-input");
|
||||
if (input && typeof sendMessage === "function") {
|
||||
input.value = actionText;
|
||||
if (typeof setInputLocked === "function") setInputLocked(false);
|
||||
sendMessage();
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// РЕНДЕРИНГ КАРТОЧКИ СРЕЗОВ СКУД (SNAPSHOTS_CARD) С ЧЕКБОКСАМИ
|
||||
// ============================================================================
|
||||
function renderSnapshotsCard(data) {
|
||||
if (!data || !data.snapshots || !Array.isArray(data.snapshots)) return '';
|
||||
const queryDate = data.query_date || 'выбранную дату';
|
||||
const snapshots = data.snapshots;
|
||||
|
||||
if (snapshots.length === 0) {
|
||||
return `
|
||||
<div class="p-6 bg-slate-50 border border-slate-200 rounded-xl text-center text-xs text-slate-500 my-2">
|
||||
📸 За дату <b>${queryDate}</b> сохраненных снапшотов не найдено.
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return filtered.map(t => {
|
||||
const isDone = t.status === "COMPLETED";
|
||||
const isProgress = t.status === "IN_PROGRESS";
|
||||
const checkedAttr = isDone ? "checked" : "";
|
||||
const textClass = isDone ? "line-through text-slate-400" : "text-slate-800 font-medium";
|
||||
const rowsHtml = snapshots.map((s, idx) => {
|
||||
const snapId = s.snapshot_id || `ID-${idx}`;
|
||||
const snapTime = s.snapshot_time ? s.snapshot_time.split(' ')[1] || s.snapshot_time : '—';
|
||||
const count = s.record_count || 0;
|
||||
const isFinal = snapId.startsWith('Y');
|
||||
|
||||
let statusPill = `<span class="text-[10px] bg-slate-100 text-slate-600 px-2 py-0.5 rounded border border-slate-200">В планах</span>`;
|
||||
if (isDone) {
|
||||
statusPill = `<span class="text-[10px] bg-emerald-50 text-emerald-700 px-2 py-0.5 rounded border border-emerald-300 font-semibold">Завершено</span>`;
|
||||
} else if (isProgress) {
|
||||
statusPill = `<span class="text-[10px] bg-amber-50 text-amber-700 px-2 py-0.5 rounded border border-amber-300 font-semibold">В работе</span>`;
|
||||
}
|
||||
|
||||
let prioPill = "";
|
||||
if (t.priority === "HIGH") {
|
||||
prioPill = `<span class="text-[9px] bg-red-50 text-red-700 font-bold px-1.5 py-0.5 rounded border border-red-200 uppercase">HIGH</span>`;
|
||||
if (isFinal) {
|
||||
return `
|
||||
<div class="p-2.5 bg-purple-50/60 rounded-lg border border-purple-200 shadow-sm flex items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-2.5 min-w-0">
|
||||
<span class="w-4 flex justify-center text-purple-400" title="Итоговый срез защищен">
|
||||
<i class="fa-solid fa-lock text-[11px]"></i>
|
||||
</span>
|
||||
<span class="font-mono text-xs font-bold px-2 py-0.5 rounded bg-purple-100 text-purple-800 border border-purple-300">
|
||||
#${snapId}
|
||||
</span>
|
||||
<div class="flex items-center gap-3 text-xs text-slate-600">
|
||||
<span class="flex items-center gap-1 font-semibold text-purple-900">
|
||||
<i class="fa-regular fa-clock text-purple-600 text-[11px]"></i> ${snapTime}
|
||||
</span>
|
||||
<span class="flex items-center gap-1 text-slate-500">
|
||||
<i class="fa-solid fa-users text-slate-400 text-[11px]"></i> ${count} записей
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<span class="text-[10px] font-bold text-purple-700 bg-purple-100 border border-purple-200 px-2 py-0.5 rounded">
|
||||
Итоговый Y-срез
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="flex items-center justify-between p-2.5 bg-slate-50 hover:bg-slate-100/80 rounded-xl border border-slate-200 transition gap-2" id="widget-task-${t.task_id}">
|
||||
<div class="flex items-center gap-2.5 flex-1 min-w-0">
|
||||
<input type="checkbox" ${checkedAttr} onchange="toggleTaskStatusInline('${t.task_id}', this.checked)"
|
||||
class="w-4 h-4 text-indigo-600 rounded border-slate-300 focus:ring-indigo-500 cursor-pointer">
|
||||
<div class="flex flex-col min-w-0 flex-1">
|
||||
<div class="flex items-center gap-1.5 mb-0.5">
|
||||
<span class="font-mono text-[11px] font-bold text-slate-700">${t.task_id}</span>
|
||||
${prioPill}
|
||||
${statusPill}
|
||||
</div>
|
||||
<span class="text-xs ${textClass} truncate leading-tight">${escapeHtml(t.title)}</span>
|
||||
<div class="p-2.5 bg-white rounded-lg border border-slate-200 shadow-sm hover:border-slate-300 transition flex items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-2.5 min-w-0">
|
||||
<input type="checkbox" value="${snapId}" onchange="window.updateSelectedSnapshots(this)"
|
||||
class="snapshot-item-checkbox rounded border-slate-300 text-indigo-600 focus:ring-indigo-500 w-4 h-4 cursor-pointer">
|
||||
<span class="font-mono text-xs font-bold px-2 py-0.5 rounded bg-slate-100 text-slate-700 border border-slate-200">
|
||||
#${snapId}
|
||||
</span>
|
||||
<div class="flex items-center gap-3 text-xs text-slate-600">
|
||||
<span class="flex items-center gap-1 font-semibold text-slate-800">
|
||||
<i class="fa-regular fa-clock text-indigo-500 text-[11px]"></i> ${snapTime}
|
||||
</span>
|
||||
<span class="flex items-center gap-1 text-slate-500">
|
||||
<i class="fa-solid fa-users text-slate-400 text-[11px]"></i> ${count} записей
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" onclick="deleteTaskInline('${t.task_id}')" class="text-slate-400 hover:text-red-500 p-1.5 transition rounded-lg hover:bg-red-50" title="Удалить задачу">
|
||||
<button type="button" onclick="window.sendChatAction('удали снапшот ${snapId}')"
|
||||
class="p-1 text-slate-400 hover:text-rose-600 hover:bg-rose-50 rounded border border-transparent hover:border-rose-200 transition"
|
||||
title="Удалить срез">
|
||||
<i class="fa-solid fa-trash-can text-xs"></i>
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
function renderInteractiveTaskCard(tasks) {
|
||||
if (!tasks || !Array.isArray(tasks)) return "";
|
||||
const widgetId = "task_widget_" + Date.now();
|
||||
activeWidgetTasksMap.set(widgetId, { tasks: tasks, filter: "ALL" });
|
||||
|
||||
const itemsHtml = renderTaskItemsHtml(tasks, "ALL");
|
||||
}).join('');
|
||||
|
||||
return `
|
||||
<div class="task-widget-card mt-3 bg-white border border-slate-200 rounded-2xl p-3.5 shadow-sm space-y-3" id="${widgetId}">
|
||||
<div class="flex items-center gap-1 pb-2 border-b border-slate-100 overflow-x-auto no-scrollbar text-xs font-semibold">
|
||||
<button type="button" onclick="filterTaskWidget('${widgetId}', 'ALL', this)" class="widget-tab-btn px-2.5 py-1 rounded-lg bg-indigo-50 text-indigo-600 font-bold border border-indigo-200">Все</button>
|
||||
<button type="button" onclick="filterTaskWidget('${widgetId}', 'IN_PROGRESS', this)" class="widget-tab-btn px-2.5 py-1 rounded-lg text-slate-500 hover:text-slate-700">В работе</button>
|
||||
<button type="button" onclick="filterTaskWidget('${widgetId}', 'BACKLOG', this)" class="widget-tab-btn px-2.5 py-1 rounded-lg text-slate-500 hover:text-slate-700">В планах</button>
|
||||
<button type="button" onclick="filterTaskWidget('${widgetId}', 'COMPLETED', this)" class="widget-tab-btn px-2.5 py-1 rounded-lg text-slate-500 hover:text-slate-700">Завершенные</button>
|
||||
<div class="snapshots-widget-root w-full max-w-4xl mx-auto my-2 bg-slate-50 border border-slate-300 rounded-xl shadow-md overflow-hidden flex flex-col">
|
||||
<div class="px-4 py-2.5 bg-white border-b border-slate-200 flex items-center justify-between gap-2 flex-wrap">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="bg-indigo-600 text-white p-1.5 rounded-lg flex items-center justify-center">
|
||||
<i class="fa-solid fa-camera text-xs"></i>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-xs font-bold text-slate-800">Реестр срезов СКУД</span>
|
||||
<span class="text-xs text-slate-500 ml-1">за ${queryDate}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<label class="flex items-center gap-1.5 text-xs text-slate-600 cursor-pointer select-none">
|
||||
<input type="checkbox" onchange="window.toggleSelectAllSnapshots(this)" class="select-all-snapshots-cb rounded border-slate-300 text-indigo-600 focus:ring-indigo-500 w-3.5 h-3.5">
|
||||
<span>Выбрать все</span>
|
||||
</label>
|
||||
<span class="text-[11px] font-semibold bg-indigo-50 text-indigo-700 border border-indigo-200 px-2 py-0.5 rounded-full">
|
||||
Срезов: ${snapshots.length}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="widget-items-container space-y-2 max-h-72 overflow-y-auto pr-1">
|
||||
${itemsHtml}
|
||||
<div class="p-3 flex flex-col gap-2">
|
||||
${rowsHtml}
|
||||
</div>
|
||||
|
||||
<div class="pt-2 border-t border-slate-100 flex items-center gap-2">
|
||||
<input type="text" placeholder="Новая задача..." class="flex-1 bg-slate-50 border border-slate-200 rounded-xl px-3 py-1.5 text-xs text-slate-800 focus:outline-none focus:border-indigo-600 focus:bg-white transition" onkeydown="if(event.key==='Enter') addTaskInline('${widgetId}', this)">
|
||||
<button type="button" onclick="addTaskInline('${widgetId}', this.previousElementSibling)" class="bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white px-3 py-1.5 rounded-xl text-xs font-semibold shadow-sm transition flex items-center gap-1">
|
||||
<i class="fa-solid fa-plus text-[10px]"></i> Добавить
|
||||
<!-- ПОДВАЛ С КНОПКОЙ УДАЛЕНИЯ ВЫБРАННЫХ -->
|
||||
<div class="snapshot-bulk-actions-footer hidden px-4 py-2 bg-rose-50/70 border-t border-rose-200 flex items-center justify-between">
|
||||
<span class="text-xs text-rose-800 font-medium bulk-selected-counter">Выбрано: 0</span>
|
||||
<button type="button" onclick="window.submitBulkDeleteSnapshots(this)"
|
||||
class="px-3 py-1.5 bg-rose-600 hover:bg-rose-700 active:bg-rose-800 text-white font-bold rounded-lg text-xs flex items-center gap-1.5 transition shadow-sm">
|
||||
<i class="fa-solid fa-trash-can"></i>
|
||||
<span>Удалить выбранные</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function filterTaskWidget(widgetId, status, btnEl) {
|
||||
const state = activeWidgetTasksMap.get(widgetId);
|
||||
if (!state) return;
|
||||
state.filter = status;
|
||||
// ⭐️ Обработчики чекбоксов
|
||||
window.toggleSelectAllSnapshots = function(masterCb) {
|
||||
const root = masterCb.closest('.snapshots-widget-root');
|
||||
if (!root) return;
|
||||
const checkboxes = root.querySelectorAll('.snapshot-item-checkbox');
|
||||
checkboxes.forEach(cb => cb.checked = masterCb.checked);
|
||||
window.syncBulkDeleteFooter(root);
|
||||
};
|
||||
|
||||
const widgetEl = document.getElementById(widgetId);
|
||||
if (!widgetEl) return;
|
||||
window.updateSelectedSnapshots = function(itemCb) {
|
||||
const root = itemCb.closest('.snapshots-widget-root');
|
||||
if (!root) return;
|
||||
window.syncBulkDeleteFooter(root);
|
||||
};
|
||||
|
||||
widgetEl.querySelectorAll(".widget-tab-btn").forEach(b => {
|
||||
b.className = "widget-tab-btn px-2.5 py-1 rounded-lg text-slate-500 hover:text-slate-700";
|
||||
window.syncBulkDeleteFooter = function(root) {
|
||||
const checkboxes = root.querySelectorAll('.snapshot-item-checkbox:checked');
|
||||
const footer = root.querySelector('.snapshot-bulk-actions-footer');
|
||||
const counter = root.querySelector('.bulk-selected-counter');
|
||||
const masterCb = root.querySelector('.select-all-snapshots-cb');
|
||||
const allCheckboxes = root.querySelectorAll('.snapshot-item-checkbox');
|
||||
|
||||
if (masterCb) {
|
||||
masterCb.checked = allCheckboxes.length > 0 && checkboxes.length === allCheckboxes.length;
|
||||
}
|
||||
|
||||
if (checkboxes.length > 0) {
|
||||
if (footer) footer.classList.remove('hidden');
|
||||
if (counter) counter.innerText = `Выбрано дневных срезов: ${checkboxes.length}`;
|
||||
} else {
|
||||
if (footer) footer.classList.add('hidden');
|
||||
}
|
||||
};
|
||||
|
||||
// Одиночная корзина в строке снапшота:
|
||||
// onclick="window.sendChatAction('удали снапшот ${snapId}')"
|
||||
|
||||
// Кнопка пакетного удаления в подвале карточки:
|
||||
window.submitBulkDeleteSnapshots = function(btnEl) {
|
||||
const root = btnEl.closest('.snapshots-widget-root');
|
||||
if (!root) return;
|
||||
const selected = Array.from(root.querySelectorAll('.snapshot-item-checkbox:checked')).map(cb => cb.value);
|
||||
if (selected.length === 0) return;
|
||||
window.sendChatAction(`удали снапшоты ${selected.join(', ')}`);
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// РЕНДЕРИНГ КАРТОЧКИ ЗАДАЧ (TASK_INTERACTIVE_CARD)
|
||||
// ============================================================================
|
||||
function renderInteractiveTaskCard(tasks) {
|
||||
if (!tasks || !Array.isArray(tasks)) return '';
|
||||
window.currentTasksCache = tasks;
|
||||
|
||||
const counts = {
|
||||
ALL: tasks.length,
|
||||
IN_PROGRESS: tasks.filter(t => t.status === 'IN_PROGRESS' || t.status === 'PROGRESS').length,
|
||||
PLANNED: tasks.filter(t => t.status === 'BACKLOG' || t.status === 'PLANNED').length,
|
||||
COMPLETED: tasks.filter(t => t.status === 'COMPLETED' || t.status === 'DONE').length
|
||||
};
|
||||
|
||||
const currentFilter = window.activeTaskFilter || 'IN_PROGRESS';
|
||||
|
||||
const filteredTasks = tasks.filter(t => {
|
||||
const s = (t.status || 'BACKLOG').toUpperCase();
|
||||
if (currentFilter === 'ALL') return true;
|
||||
if (currentFilter === 'IN_PROGRESS') return s === 'IN_PROGRESS' || s === 'PROGRESS';
|
||||
if (currentFilter === 'PLANNED') return s === 'BACKLOG' || s === 'PLANNED';
|
||||
if (currentFilter === 'COMPLETED') return s === 'COMPLETED' || s === 'DONE';
|
||||
return true;
|
||||
});
|
||||
btnEl.className = "widget-tab-btn px-2.5 py-1 rounded-lg bg-indigo-50 text-indigo-600 font-bold border border-indigo-200";
|
||||
|
||||
const container = widgetEl.querySelector(".widget-items-container");
|
||||
if (container) {
|
||||
container.innerHTML = renderTaskItemsHtml(state.tasks, status);
|
||||
}
|
||||
const getPrioBadge = (prio) => {
|
||||
const p = (prio || 'MEDIUM').toUpperCase();
|
||||
if (p === 'HIGH' || p === 'CRITICAL') return '<span class="text-[10px] px-2 py-0.5 rounded font-bold bg-rose-100 text-rose-700 border border-rose-200">🔥 HIGH</span>';
|
||||
if (p === 'LOW') return '<span class="text-[10px] px-2 py-0.5 rounded font-semibold bg-slate-100 text-slate-600 border border-slate-200">☕ LOW</span>';
|
||||
return '<span class="text-[10px] px-2 py-0.5 rounded font-semibold bg-amber-100 text-amber-700 border border-amber-200">⚡ MEDIUM</span>';
|
||||
};
|
||||
|
||||
const getStatusBadge = (status) => {
|
||||
const s = (status || 'BACKLOG').toUpperCase();
|
||||
if (s === 'IN_PROGRESS' || s === 'PROGRESS') return '<span class="text-[10px] px-2 py-0.5 rounded font-bold bg-blue-50 text-blue-700 border border-blue-200">⚙️ В работе</span>';
|
||||
if (s === 'COMPLETED' || s === 'DONE') return '<span class="text-[10px] px-2 py-0.5 rounded font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200">✓ Готово</span>';
|
||||
return '<span class="text-[10px] px-2 py-0.5 rounded font-semibold bg-slate-50 text-slate-600 border border-slate-200">📋 В планах</span>';
|
||||
};
|
||||
|
||||
const taskRows = filteredTasks.map(t => {
|
||||
const id = t.id;
|
||||
const title = t.title || 'Без названия';
|
||||
const isDone = t.status === 'COMPLETED' || t.status === 'DONE';
|
||||
const isInProgress = t.status === 'IN_PROGRESS' || t.status === 'PROGRESS';
|
||||
|
||||
const actionBtn = isInProgress
|
||||
? `<button type="button" onclick="window.sendChatAction('заверши задачу ${id}')" class="px-2.5 py-1 text-xs font-semibold rounded bg-emerald-50 text-emerald-700 border border-emerald-300 hover:bg-emerald-100 transition-colors shadow-sm" title="Завершить задачу">✓ Готово</button>`
|
||||
: (!isDone
|
||||
? `<button type="button" onclick="window.sendChatAction('возьми в работу задачу ${id}')" class="px-2.5 py-1 text-xs font-semibold rounded bg-blue-50 text-blue-700 border border-blue-300 hover:bg-blue-100 transition-colors shadow-sm" title="Взять в работу">⚙️ В работу</button>`
|
||||
: '');
|
||||
|
||||
return `
|
||||
<div id="task-card-${id}" class="p-3 bg-white rounded-lg border border-slate-200 shadow-sm hover:border-slate-300 transition-all flex flex-col gap-2">
|
||||
<div class="task-view-mode flex items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-2 flex-wrap flex-1 min-w-0">
|
||||
<span class="text-xs font-bold px-1.5 py-0.5 rounded bg-slate-100 text-slate-700 border border-slate-200">#${id}</span>
|
||||
<span class="text-sm font-medium text-slate-900 truncate" title="${title}">${title}</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-1.5 shrink-0">
|
||||
${actionBtn}
|
||||
<button type="button" onclick="window.openTaskInlineEditor(${id})" class="p-1 text-xs text-slate-500 hover:text-indigo-600 hover:bg-slate-50 rounded border border-slate-200 transition-colors" title="Редактировать">✏️</button>
|
||||
<button type="button" onclick="window.sendChatAction('удали задачу ${id}')" class="p-1 text-xs text-slate-400 hover:text-rose-600 hover:bg-rose-50 rounded border border-slate-200 transition-colors" title="Удалить">🗑️</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="task-view-mode flex items-center gap-2 text-xs text-slate-500 flex-wrap">
|
||||
${getPrioBadge(t.priority)}
|
||||
${getStatusBadge(t.status)}
|
||||
<span class="px-1.5 py-0.5 rounded bg-slate-50 border border-slate-200 text-slate-600 font-mono text-[11px]">${t.module || 'general'}</span>
|
||||
${t.due_date ? `<span class="text-slate-500">📅 срок: <b>${t.due_date}</b></span>` : ''}
|
||||
${t.created_at ? `<span class="text-slate-400">создана: ${t.created_at.split(' ')[0]}</span>` : ''}
|
||||
</div>
|
||||
|
||||
<!-- ФОРМА ИНЛАЙН РЕДАКТИРОВАНИЯ -->
|
||||
<div id="task-editor-${id}" class="hidden flex flex-col gap-2 pt-2 border-t border-slate-100">
|
||||
<input type="text" id="task-edit-title-${id}" value="${title.replace(/"/g, '"')}" class="w-full text-xs px-2.5 py-1.5 border border-slate-300 rounded focus:border-indigo-500 focus:outline-none bg-slate-50" placeholder="Описание задачи..." />
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<input type="date" id="task-edit-date-${id}" value="${t.due_date || ''}" class="text-xs px-2 py-1 border border-slate-300 rounded focus:border-indigo-500 focus:outline-none bg-slate-50" />
|
||||
<select id="task-edit-prio-${id}" class="text-xs px-2 py-1 border border-slate-300 rounded focus:border-indigo-500 focus:outline-none bg-slate-50">
|
||||
<option value="LOW" ${t.priority === 'LOW' ? 'selected' : ''}>☕ LOW</option>
|
||||
<option value="MEDIUM" ${t.priority === 'MEDIUM' || !t.priority ? 'selected' : ''}>⚡ MEDIUM</option>
|
||||
<option value="HIGH" ${t.priority === 'HIGH' ? 'selected' : ''}>🔥 HIGH</option>
|
||||
<option value="CRITICAL" ${t.priority === 'CRITICAL' ? 'selected' : ''}>🚨 CRITICAL</option>
|
||||
</select>
|
||||
<button type="button" onclick="window.saveTaskInlineEdit(${id})" class="px-2.5 py-1 text-xs font-semibold rounded bg-indigo-600 text-white hover:bg-indigo-700 transition-colors shadow-sm">Сохранить</button>
|
||||
<button type="button" onclick="window.closeTaskInlineEditor(${id})" class="px-2 py-1 text-xs font-medium rounded text-slate-500 hover:bg-slate-100 transition-colors">Отмена</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
const emptyState = `
|
||||
<div class="p-8 text-center text-slate-400">
|
||||
<div class="text-3xl mb-2">📭</div>
|
||||
<div class="text-sm font-medium">Нет задач в категории «${currentFilter}»</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
return `
|
||||
<div class="task-widget-root w-full max-w-4xl mx-auto my-2 bg-slate-50 border border-slate-300 rounded-xl shadow-md overflow-hidden flex flex-col">
|
||||
<div class="px-4 py-3 bg-white border-b border-slate-200 flex items-center justify-between gap-2 flex-wrap">
|
||||
<div class="flex items-center gap-1.5 flex-wrap">
|
||||
<button type="button" onclick="window.switchTaskFilter('IN_PROGRESS', this)" class="px-2.5 py-1 text-xs font-bold rounded-md transition-colors ${currentFilter === 'IN_PROGRESS' ? 'bg-blue-600 text-white shadow-sm' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}">
|
||||
⚙️ В работе (${counts.IN_PROGRESS})
|
||||
</button>
|
||||
<button type="button" onclick="window.switchTaskFilter('PLANNED', this)" class="px-2.5 py-1 text-xs font-bold rounded-md transition-colors ${currentFilter === 'PLANNED' ? 'bg-indigo-600 text-white shadow-sm' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}">
|
||||
📋 В планах (${counts.PLANNED})
|
||||
</button>
|
||||
<button type="button" onclick="window.switchTaskFilter('COMPLETED', this)" class="px-2.5 py-1 text-xs font-bold rounded-md transition-colors ${currentFilter === 'COMPLETED' ? 'bg-emerald-600 text-white shadow-sm' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}">
|
||||
✓ Готово (${counts.COMPLETED})
|
||||
</button>
|
||||
<button type="button" onclick="window.switchTaskFilter('ALL', this)" class="px-2.5 py-1 text-xs font-bold rounded-md transition-colors ${currentFilter === 'ALL' ? 'bg-slate-800 text-white shadow-sm' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}">
|
||||
Все (${counts.ALL})
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button type="button" onclick="window.toggleCreateTaskForm(this)" class="px-3 py-1.5 text-xs font-bold rounded-md bg-indigo-600 hover:bg-indigo-700 text-white transition-all shadow-sm flex items-center gap-1">
|
||||
➕ Добавить задачу
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="new-task-creation-form hidden p-3 bg-indigo-50/70 border-b border-indigo-100 flex flex-col gap-2">
|
||||
<div class="text-xs font-bold text-indigo-900">Новая задача:</div>
|
||||
<input type="text" class="new-task-title w-full text-xs px-2.5 py-1.5 border border-indigo-200 rounded focus:border-indigo-500 focus:outline-none bg-white" placeholder="Что необходимо сделать?..." />
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<input type="date" class="new-task-date text-xs px-2 py-1 border border-indigo-200 rounded focus:border-indigo-500 focus:outline-none bg-white" />
|
||||
<select class="new-task-prio text-xs px-2 py-1 border border-indigo-200 rounded focus:border-indigo-500 focus:outline-none bg-white">
|
||||
<option value="LOW">☕ LOW (Низкий)</option>
|
||||
<option value="MEDIUM" selected>⚡ MEDIUM (Средний)</option>
|
||||
<option value="HIGH">🔥 HIGH (Высокий)</option>
|
||||
<option value="CRITICAL">🚨 CRITICAL (Критический)</option>
|
||||
</select>
|
||||
<select class="new-task-status text-xs px-2 py-1 border border-indigo-200 rounded focus:border-indigo-500 focus:outline-none bg-white">
|
||||
<option value="BACKLOG" selected>📋 В планы (Бэклог)</option>
|
||||
<option value="IN_PROGRESS">⚙️ Сразу в работу</option>
|
||||
</select>
|
||||
<button type="button" onclick="window.submitCreateTask(this)" class="px-3 py-1 text-xs font-bold rounded bg-indigo-600 text-white hover:bg-indigo-700 transition-colors shadow-sm">Создать</button>
|
||||
<button type="button" onclick="window.toggleCreateTaskForm(this)" class="px-2 py-1 text-xs font-medium rounded text-slate-500 hover:bg-slate-200 transition-colors">Отмена</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="p-3 overflow-y-auto max-h-[70vh] flex flex-col gap-2 task-rows-container">
|
||||
${filteredTasks.length > 0 ? taskRows : emptyState}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async function toggleTaskStatusInline(taskId, isChecked) {
|
||||
const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
const newStatus = isChecked ? "COMPLETED" : "BACKLOG";
|
||||
window.switchTaskFilter = function(filterName, btnEl) {
|
||||
window.activeTaskFilter = filterName;
|
||||
const root = btnEl ? btnEl.closest('.task-widget-root') : document.querySelector('.task-widget-root');
|
||||
if (root && window.currentTasksCache && window.currentTasksCache.length > 0) {
|
||||
root.outerHTML = renderInteractiveTaskCard(window.currentTasksCache);
|
||||
}
|
||||
};
|
||||
|
||||
window.toggleCreateTaskForm = function(btnEl) {
|
||||
const root = btnEl ? btnEl.closest('.task-widget-root') : document.querySelector('.task-widget-root');
|
||||
if (!root) return;
|
||||
const form = root.querySelector('.new-task-creation-form');
|
||||
if (form) {
|
||||
form.classList.toggle('hidden');
|
||||
if (!form.classList.contains('hidden')) {
|
||||
const input = form.querySelector('.new-task-title');
|
||||
if (input) input.focus();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.submitCreateTask = async function(btnEl) {
|
||||
const root = btnEl ? btnEl.closest('.task-widget-root') : document.querySelector('.task-widget-root');
|
||||
if (!root) return;
|
||||
|
||||
const titleInput = root.querySelector('.new-task-title');
|
||||
const dateInput = root.querySelector('.new-task-date');
|
||||
const prioInput = root.querySelector('.new-task-prio');
|
||||
const statusInput = root.querySelector('.new-task-status');
|
||||
|
||||
if (!titleInput || !titleInput.value.trim()) {
|
||||
alert('Введите описание задачи');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/v1/tasks/${taskId}`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": "Bearer " + token
|
||||
},
|
||||
body: JSON.stringify({ status: newStatus })
|
||||
const res = await fetch('/api/v1/tasks', {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
title: titleInput.value.trim(),
|
||||
due_date: dateInput ? (dateInput.value || null) : null,
|
||||
priority: prioInput ? prioInput.value : 'MEDIUM',
|
||||
status: statusInput ? statusInput.value : 'BACKLOG'
|
||||
})
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
for (let [wId, state] of activeWidgetTasksMap.entries()) {
|
||||
const targetTask = state.tasks.find(t => t.task_id === taskId);
|
||||
if (targetTask) {
|
||||
targetTask.status = newStatus;
|
||||
const widgetEl = document.getElementById(wId);
|
||||
const container = widgetEl?.querySelector(".widget-items-container");
|
||||
if (container) {
|
||||
container.innerHTML = renderTaskItemsHtml(state.tasks, state.filter);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (typeof loadTasks === "function") loadTasks();
|
||||
window.activeTaskFilter = (statusInput && statusInput.value === 'IN_PROGRESS') ? 'IN_PROGRESS' : 'PLANNED';
|
||||
window.sendChatAction('покажи задачи');
|
||||
} else {
|
||||
const err = await res.json();
|
||||
alert('Ошибка создания задачи: ' + (err.detail || 'Неизвестная ошибка'));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Task Patch Error]", err);
|
||||
} catch (e) {
|
||||
console.error('Ошибка создания задачи:', e);
|
||||
alert('Сетевая ошибка при создании задачи');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
async function deleteTaskInline(taskId) {
|
||||
if (!confirm(`Удалить задачу ${taskId}?`)) return;
|
||||
const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
window.openTaskInlineEditor = function(id) {
|
||||
const card = document.getElementById(`task-card-${id}`);
|
||||
if (!card) return;
|
||||
card.querySelectorAll('.task-view-mode').forEach(el => el.classList.add('hidden'));
|
||||
const editor = document.getElementById(`task-editor-${id}`);
|
||||
if (editor) editor.classList.remove('hidden');
|
||||
};
|
||||
|
||||
window.closeTaskInlineEditor = function(id) {
|
||||
const card = document.getElementById(`task-card-${id}`);
|
||||
if (!card) return;
|
||||
card.querySelectorAll('.task-view-mode').forEach(el => el.classList.remove('hidden'));
|
||||
const editor = document.getElementById(`task-editor-${id}`);
|
||||
if (editor) editor.classList.add('hidden');
|
||||
};
|
||||
|
||||
window.saveTaskInlineEdit = async function(id) {
|
||||
const titleInput = document.getElementById(`task-edit-title-${id}`);
|
||||
const dateInput = document.getElementById(`task-edit-date-${id}`);
|
||||
const prioInput = document.getElementById(`task-edit-prio-${id}`);
|
||||
|
||||
if (!titleInput || !titleInput.value.trim()) {
|
||||
alert('Описание задачи не может быть пустым');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/v1/tasks/${taskId}`, {
|
||||
method: "DELETE",
|
||||
headers: { "Authorization": "Bearer " + token }
|
||||
const res = await fetch(`/api/v1/tasks/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
title: titleInput.value.trim(),
|
||||
due_date: dateInput ? (dateInput.value || null) : null,
|
||||
priority: prioInput ? prioInput.value : 'MEDIUM'
|
||||
})
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
for (let [wId, state] of activeWidgetTasksMap.entries()) {
|
||||
state.tasks = state.tasks.filter(t => t.task_id !== taskId);
|
||||
const widgetEl = document.getElementById(wId);
|
||||
const container = widgetEl?.querySelector(".widget-items-container");
|
||||
if (container) {
|
||||
container.innerHTML = renderTaskItemsHtml(state.tasks, state.filter);
|
||||
}
|
||||
}
|
||||
if (typeof loadTasks === "function") loadTasks();
|
||||
window.sendChatAction('покажи задачи');
|
||||
} else {
|
||||
const err = await res.json();
|
||||
alert('Ошибка обновления задачи: ' + (err.detail || 'Неизвестная ошибка'));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Task Delete Error]", err);
|
||||
} catch (e) {
|
||||
console.error('Ошибка сохранения задачи:', e);
|
||||
alert('Сетевая ошибка при обновлении задачи');
|
||||
}
|
||||
}
|
||||
|
||||
async function addTaskInline(widgetId, inputEl) {
|
||||
if (!inputEl) return;
|
||||
const title = inputEl.value.trim();
|
||||
if (!title) return;
|
||||
|
||||
const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/v1/tasks", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": "Bearer " + token
|
||||
},
|
||||
body: JSON.stringify({ title: title, priority: "MEDIUM", module: "general" })
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
inputEl.value = "";
|
||||
const tasksRes = await fetch("/api/v1/tasks", {
|
||||
headers: { "Authorization": "Bearer " + token }
|
||||
});
|
||||
const updatedTasks = await tasksRes.json();
|
||||
|
||||
const state = activeWidgetTasksMap.get(widgetId);
|
||||
if (state) {
|
||||
state.tasks = updatedTasks;
|
||||
const widgetEl = document.getElementById(widgetId);
|
||||
const container = widgetEl?.querySelector(".widget-items-container");
|
||||
if (container) {
|
||||
container.innerHTML = renderTaskItemsHtml(updatedTasks, state.filter);
|
||||
}
|
||||
}
|
||||
if (typeof loadTasks === "function") loadTasks();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Task Add Error]", err);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1,164 +1,117 @@
|
||||
/**
|
||||
===============================================================================
|
||||
FILE: modules/web_api/static/js/tasks.js
|
||||
ROLE: Управление боковой панелью задач (Drawer), фильтрация и рендеринг карточек.
|
||||
|
||||
AI-CONTEXT-ANCHORS:
|
||||
- ANCHOR[DRAWER_TOGGLE]: Открытие и закрытие выезжающей панели.
|
||||
- ANCHOR[TASKS_FILTER]: Фильтрация списка (ALL, IN_PROGRESS, BACKLOG, COMPLETED).
|
||||
- ANCHOR[TASKS_LOAD_FETCH]: Асинхронная загрузка задач через /api/v1/tasks.
|
||||
- ANCHOR[TASKS_RENDER_DOM]: Генерация HTML-карточек в боковом меню.
|
||||
PROJECT: SCUD Orion AI (Unified Architecture)
|
||||
MODULE: web_api / static / js
|
||||
ROLE: Загрузка, фильтрация и рендеринг списка задач в боковой панели (Drawer).
|
||||
===============================================================================
|
||||
*/
|
||||
|
||||
let currentFilter = 'ALL';
|
||||
let allTasks = [];
|
||||
let currentTaskFilter = 'IN_PROGRESS';
|
||||
|
||||
// --- [SECTION 1: DRAWER TOGGLE] --- # ANCHOR[DRAWER_TOGGLE]
|
||||
function toggleDrawer() {
|
||||
if (typeof IS_GUEST !== 'undefined' && IS_GUEST) return;
|
||||
const drawer = document.getElementById("task-drawer");
|
||||
const backdrop = document.getElementById("drawer-backdrop");
|
||||
if (!drawer) return;
|
||||
|
||||
const isHidden = drawer.classList.contains("translate-x-full");
|
||||
if (isHidden) {
|
||||
drawer.classList.remove("translate-x-full");
|
||||
if (backdrop) backdrop.classList.remove("hidden");
|
||||
loadTasks();
|
||||
} else {
|
||||
drawer.classList.add("translate-x-full");
|
||||
if (backdrop) backdrop.classList.add("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
// --- [SECTION 2: FILTER CONTROL] --- # ANCHOR[TASKS_FILTER]
|
||||
function setFilter(status) {
|
||||
currentFilter = status;
|
||||
["ALL", "IN_PROGRESS", "BACKLOG", "COMPLETED"].forEach(f => {
|
||||
const btn = document.getElementById(`filter-${f}`);
|
||||
if (btn) {
|
||||
btn.className = (f === status)
|
||||
? "px-3 py-1.5 rounded-t-lg border-b-2 border-indigo-600 text-indigo-600 font-bold whitespace-nowrap"
|
||||
: "px-3 py-1.5 rounded-t-lg border-b-2 border-transparent whitespace-nowrap";
|
||||
}
|
||||
});
|
||||
renderTasks();
|
||||
}
|
||||
|
||||
// --- [SECTION 3: ASYNC DATA FETCH] --- # ANCHOR[TASKS_LOAD_FETCH]
|
||||
async function loadTasks() {
|
||||
const badge = document.getElementById("task-count-badge");
|
||||
const container = document.getElementById("tasks-container");
|
||||
|
||||
const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
const isGuest = typeof IS_GUEST !== 'undefined' ? IS_GUEST : (localStorage.getItem("scud_is_guest") === "true");
|
||||
|
||||
if (isGuest || !token) {
|
||||
if (badge) badge.innerText = "0";
|
||||
return;
|
||||
}
|
||||
if (!token) return;
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/v1/tasks", {
|
||||
headers: {
|
||||
"Authorization": "Bearer " + token,
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
headers: { "Authorization": "Bearer " + token }
|
||||
});
|
||||
|
||||
if (res.status === 401) {
|
||||
if (typeof logout === 'function') logout();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP error! status: ${res.status}`);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (Array.isArray(data)) {
|
||||
allTasks = data;
|
||||
} else if (data && Array.isArray(data.tasks)) {
|
||||
allTasks = data.tasks;
|
||||
} else if (data && typeof data === 'object') {
|
||||
allTasks = Object.values(data).find(val => Array.isArray(val)) || [];
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
renderSidebarTasks(data.tasks || []);
|
||||
} else {
|
||||
allTasks = [];
|
||||
}
|
||||
|
||||
if (badge) {
|
||||
badge.innerText = allTasks.length.toString();
|
||||
}
|
||||
|
||||
renderTasks();
|
||||
|
||||
} catch (err) {
|
||||
console.error("[Tasks Error]", err);
|
||||
if (badge) badge.innerText = "0";
|
||||
if (container) {
|
||||
container.innerHTML = `<div class="text-red-500 text-xs py-8 text-center font-medium">Ошибка обработки списка задач</div>`;
|
||||
renderSidebarError("Ошибка доступа. Авторизуйтесь снова.");
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Ошибка загрузки задач:", e);
|
||||
renderSidebarError("Ошибка сети. Сервер недоступен.");
|
||||
}
|
||||
}
|
||||
|
||||
// --- [SECTION 4: DOM RENDERING] --- # ANCHOR[TASKS_RENDER_DOM]
|
||||
function renderTasks() {
|
||||
const container = document.getElementById("tasks-container");
|
||||
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 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");
|
||||
if (!container) return;
|
||||
|
||||
if (!Array.isArray(allTasks)) {
|
||||
allTasks = [];
|
||||
let filtered = tasks;
|
||||
if (currentTaskFilter !== 'ALL') {
|
||||
filtered = tasks.filter(t => t.status === currentTaskFilter);
|
||||
}
|
||||
|
||||
const filtered = allTasks.filter(t => currentFilter === "ALL" || t.status === currentFilter);
|
||||
|
||||
if (filtered.length === 0) {
|
||||
container.innerHTML = `<div class="text-slate-400 text-xs py-8 text-center">Нет задач с выбранным фильтром</div>`;
|
||||
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>`;
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML = filtered.map(t => {
|
||||
let statusBadge = "bg-slate-100 text-slate-600 border-slate-200";
|
||||
let statusLabel = "В планах";
|
||||
let cardBg = "bg-white";
|
||||
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';
|
||||
|
||||
if (t.status === "COMPLETED") {
|
||||
statusBadge = "bg-emerald-50 text-emerald-700 border-emerald-300 font-semibold";
|
||||
statusLabel = "Завершено";
|
||||
cardBg = "bg-emerald-50/20";
|
||||
} else if (t.status === "IN_PROGRESS") {
|
||||
statusBadge = "bg-amber-50 text-amber-700 border-amber-300 font-bold";
|
||||
statusLabel = "В работе";
|
||||
cardBg = "bg-amber-50/20 border-amber-200";
|
||||
}
|
||||
|
||||
let priorityBadge = "text-slate-500 bg-slate-100 border-slate-200";
|
||||
if (t.priority === "HIGH") priorityBadge = "text-red-700 bg-red-50 border-red-200 font-bold";
|
||||
|
||||
let dueDateHtml = t.due_date ? `
|
||||
<div class="mt-2 text-[11px] text-amber-800 bg-amber-50 border border-amber-200 px-2 py-0.5 rounded-md flex items-center gap-1.5 w-fit font-medium">
|
||||
<i class="fa-solid fa-clock text-amber-600"></i>
|
||||
<span>Срок: ${t.due_date}</span>
|
||||
</div>` : "";
|
||||
|
||||
return `
|
||||
<div class="${cardBg} border border-slate-200 rounded-xl p-3.5 shadow-sm hover:shadow-md transition">
|
||||
<div class="flex justify-between items-center mb-1.5">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="font-mono text-xs font-bold text-slate-900 bg-slate-100 px-2 py-0.5 rounded border border-slate-200">${t.task_id || t.id || 'TASK'}</span>
|
||||
<span class="text-[10px] uppercase px-1.5 py-0.5 rounded border ${priorityBadge}">${t.priority || 'MEDIUM'}</span>
|
||||
</div>
|
||||
<span class="text-[10px] uppercase px-2 py-0.5 rounded border ${statusBadge}">${statusLabel}</span>
|
||||
<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 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>
|
||||
<h3 class="text-xs font-semibold text-slate-800 mb-1 leading-snug">${t.title || t.description || ''}</h3>
|
||||
<div class="text-[10px] text-slate-400 font-mono flex items-center gap-1">
|
||||
<i class="fa-solid fa-folder-closed text-slate-300"></i>
|
||||
<span>${t.module || 'General'}</span>
|
||||
|
||||
<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>
|
||||
${dueDateHtml}
|
||||
</div>
|
||||
`;
|
||||
}).join("");
|
||||
}
|
||||
}).join('');
|
||||
}
|
||||
|
||||
// Глобальная инициализация при загрузке DOM
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
// Небольшая задержка, чтобы гарантировать применение токена
|
||||
setTimeout(loadTasks, 200);
|
||||
});
|
||||
Reference in New Issue
Block a user