feat(web): стабилизация UI, Gemini-скроллинг, роутеры контекста/снапшотов и актуализация роадмапа
This commit is contained in:
+77
-195
@@ -3,19 +3,11 @@
|
||||
FILE: modules/web_api/llm/agent.py
|
||||
PROJECT: SCUD Orion AI (Unified Architecture)
|
||||
MODULE: web_api / llm (Core Agent Coordinator)
|
||||
ROLE: Нативный оркестратор диалога, диспетчер инструментов (Function Calling)
|
||||
и управление сессионными стейтами через ContextManager.
|
||||
|
||||
AI-CONTEXT-ANCHORS:
|
||||
- ANCHOR[AGENT_IMPORTS]: Системные и доменные импорты.
|
||||
- ANCHOR[AGENT_MAIN_PIPELINE]: Основная точка входа process_chat_message.
|
||||
- ANCHOR[AGENT_SYSTEM_PROMPT]: Формирование динамического контекста.
|
||||
- ANCHOR[AGENT_TOOL_DISPATCHER]: Исполнение нативных вызовов инструментов.
|
||||
- ANCHOR[AGENT_TOPIC_DRIFT]: Защита контекста и обработка свободных тем.
|
||||
ROLE: Нативный оркестратор диалога, диспетчер Function Calling,
|
||||
передача активных срезов в контекст модели и терминальные вызовы.
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
# ANCHOR[AGENT_IMPORTS]
|
||||
import sys
|
||||
import json
|
||||
import logging
|
||||
@@ -27,7 +19,7 @@ from .db_tools import (
|
||||
db_apply_prompt_node_action,
|
||||
db_get_tool_action,
|
||||
db_get_tasks,
|
||||
db_update_task_status,
|
||||
db_update_task_details,
|
||||
db_delete_task,
|
||||
db_add_task,
|
||||
db_tasks_edit,
|
||||
@@ -70,7 +62,6 @@ if not logger.handlers:
|
||||
logger.addHandler(handler)
|
||||
|
||||
|
||||
# ANCHOR[AGENT_MAIN_PIPELINE]
|
||||
def process_chat_message(
|
||||
user_id: int,
|
||||
user_message: str,
|
||||
@@ -90,7 +81,7 @@ def process_chat_message(
|
||||
|
||||
full_user_content = f"{user_message}\n\n[СОДЕРЖИМОЕ ПРИКРЕПЛЕННОГО ФАЙЛА]:\n{file_context}" if file_context else user_message
|
||||
|
||||
# 1. Быстрый перехват строго системных кнопок UI (подтверждение превью промпта)
|
||||
# 1. Быстрый перехват системных кнопок UI и терминальных действий без задержек LLM
|
||||
fast_path_res = handle_fast_path_intercept(session_id, user_message, full_user_content, session_state)
|
||||
if fast_path_res:
|
||||
return fast_path_res
|
||||
@@ -99,7 +90,6 @@ def process_chat_message(
|
||||
db_save_chat_message(session_id, "user", full_user_content, is_ephemeral=0)
|
||||
db_history = db_get_chat_history(session_id, limit=20)
|
||||
|
||||
# ANCHOR[AGENT_SYSTEM_PROMPT]
|
||||
calendar_context = get_dynamic_calendar_context()
|
||||
user_info = f"Пользователь ID={user_id}" if user_id != 0 else "Гость"
|
||||
|
||||
@@ -111,52 +101,50 @@ def process_chat_message(
|
||||
|
||||
active_state_context = ""
|
||||
if current_state_type == "PROMPT_PREVIEW":
|
||||
active_state_context = (
|
||||
"\n[ТЕКУЩИЙ РЕЖИМ: ПРЕДПРОСМОТР СИСТЕМНОГО ПРОМПТА]\n"
|
||||
"- Открыт предпросмотр изменений промпта. Для любых правок вызывай db_prompt_node_edit.\n"
|
||||
)
|
||||
elif current_state_type == "PROMPT_FOLLOWUP":
|
||||
active_state_context = (
|
||||
"\n[ТЕКУЩИЙ РЕЖИМ: СЕССИЯ РЕДАКТИРОВАНИЯ ПРОМПТА]\n"
|
||||
"- Оператор просматривает или редактирует системный промпт.\n"
|
||||
"- На любые команды вида 'удали пункт X.Y' или 'удали X.Y' ТЫ ОБЯЗАН ВЫЗВАТЬ db_prompt_node_edit с action='DELETE', section_id=X, item_id=Y.\n"
|
||||
"- На любые команды 'добавь пункт X.Y ...' вызывай action='ADD'.\n"
|
||||
"- Запрещено путать ADD и DELETE.\n"
|
||||
)
|
||||
active_state_context = "\n[ТЕКУЩИЙ РЕЖИМ: ПРЕДПРОСМОТР СИСТЕМНОГО ПРОМПТА]\n- Открыт предпросмотр изменений промпта.\n"
|
||||
elif current_state_type == "SNAPSHOTS_VIEW":
|
||||
active_date = state_data.get("query_date", "выбранную дату")
|
||||
active_state_context = f"\n[ТЕКУЩИЙ РЕЖИМ: ПРОСМОТР СНАПШОТОВ СКУД]\n- Отображаются срезы за {active_date}.\n"
|
||||
elif current_state_type == "SNAPSHOT_INSPECT":
|
||||
snap_id = state_data.get("snapshot_id", "")
|
||||
snap_date = state_data.get("log_date", "")
|
||||
records = state_data.get("records", [])
|
||||
|
||||
lines = []
|
||||
for r in records:
|
||||
st = "Присутствовал" if r.get("is_present") else "Отсутствовал"
|
||||
lines.append(f"- {r.get('fio')}: Отдел={r.get('department')}, Вход={r.get('time_in')}, Активность={r.get('first_activity')}, Выход={r.get('time_out')}, ВремяВЗдании={r.get('in_building')}, Статус={st}")
|
||||
|
||||
dump_str = "\n".join(lines)
|
||||
active_state_context = (
|
||||
f"\n[ТЕКУЩИЙ РЕЖИМ: ПРОСМОТР СНАПШОТОВ СКУД]\n"
|
||||
f"- Сейчас на экране отображаются снапшоты за {active_date}.\n"
|
||||
f"- Ты можешь форматировать, фильтровать или анализировать этот текущий срез.\n"
|
||||
f"- Если оператор запрашивает ДРУГУЮ дату или день недели, отличную от {active_date} (например: 'за вчера', 'а за 13.08', 'покажи за сегодня') — "
|
||||
f"ТЫ ОБЯЗАН СРАЗУ ВЫЗВАТЬ db_get_snapshots(date_str=...).\n"
|
||||
f"- Запрещено генерировать текст за другую дату по памяти.\n"
|
||||
)
|
||||
elif current_state_type == "SNAPSHOT_DELETE_CONFIRM":
|
||||
active_state_context = (
|
||||
"\n[ВНИМАНИЕ: ОЖИДАЕТСЯ ПОДТВЕРЖДЕНИЕ УДАЛЕНИЯ СНАПШОТОВ]\n"
|
||||
)
|
||||
elif current_state_type == "TASK_DELETE_CONFIRM":
|
||||
active_state_context = (
|
||||
"\n[ВНИМАНИЕ: ОЖИДАЕТСЯ ПОДТВЕРЖДЕНИЕ УДАЛЕНИЯ ЗАДАЧИ]\n"
|
||||
f"\n[ТЕКУЩИЙ РЕЖИМ: АКТИВНА ИНСПЕКЦИЯ СРЕЗА СКУД #{snap_id} ЗА {snap_date}]\n"
|
||||
f"Оператор сейчас изучает срез #{snap_id}. При любых вопросах о сотрудниках, их времени входа/выхода, отделах или присутствии — "
|
||||
f"ТЫ ОБЯЗАН брать данные исключительно из этого списка активного среза:\n{dump_str}\n"
|
||||
)
|
||||
|
||||
# ⭐️ Промпт с поддержкой Topic Drift и защитой от переспросов по задачам
|
||||
system_prompt_content = (
|
||||
f"Ты — интеллектуальный ассистент SCUD Orion AI.\n"
|
||||
f"Ты управляешь задачами, аналитикой СКУД и системными настройками исключительно через инструменты (tools).\n\n"
|
||||
f"Твоя основная роль — помощь оператору в кадровом аудите СКУД/1С, управлении задачами и настройками системы.\n\n"
|
||||
f"СТРОГИЕ ПРАВИЛА:\n"
|
||||
f"1. К оператору всегда обращайся на Вы.\n"
|
||||
f"2. Для получения данных всегда вызывай соответствующий инструмент:\n"
|
||||
f" - Снапшоты и срезы логов СКУД за любые даты и дни недели -> db_get_snapshots\n"
|
||||
f" - Удаление снапшотов -> db_delete_snapshots\n"
|
||||
f" - Задачи и бэклог (просмотр, создание, смена статуса, удаление, экспорт) -> db_get_tasks, db_tasks_edit\n"
|
||||
f"2. Для работы с данными системы ВСЕГДА вызывай соответствующие инструменты (tools):\n"
|
||||
f" - Снапшоты и срезы СКУД -> db_get_snapshots\n"
|
||||
f" - Удаление срезов -> db_delete_snapshots\n"
|
||||
f" - Задачи и бэклог -> db_get_tasks, db_tasks_edit\n"
|
||||
f" - Системный промпт -> db_get_system_prompt, db_prompt_node_edit\n"
|
||||
f" - База знаний и регламенты -> db_get_rules\n"
|
||||
f" - Аномалии СКУД/1С -> db_get_anomalies\n"
|
||||
f" - База знаний -> db_get_rules\n"
|
||||
f" - Статистика БД -> db_get_stats\n"
|
||||
f" - Справка -> db_get_reference\n"
|
||||
f"3. Запрещено сочинять данные от себя без вызова инструментов.\n\n"
|
||||
f"3. ЗАДАЧИ:\n"
|
||||
f" - При любых запросах на просмотр задач (включая опечатки вроде 'змдачи', 'таски', 'дела', 'покажи задачи') — "
|
||||
f"ТЫ ОБЯЗАН СРАЗУ ВЫЗВАТЬ db_get_tasks без лишних вопросов!\n"
|
||||
f" - КАТЕГОРИЧЕСКИ ЗАПРЕЩЕНО переспрашивать у оператора фильтры, статус или категорию задач текстом! "
|
||||
f"Интерактивная карточка в интерфейсе содержит все нужные фильтры.\n"
|
||||
f"4. ПРАВИЛА И РЕГЛАМЕНТЫ: При любых вопросах о правилах компании или арбитраже ТЫ ОБЯЗАН СРАЗУ вызвать db_get_rules.\n"
|
||||
f"5. Запрещено выдумывать факты и цифры по системе СКУД/1С без вызова инструментов.\n"
|
||||
f"6. ОБЩИЙ ДИАЛОГ: На любые отвлечённые, познавательные, научные или бытовые вопросы "
|
||||
f"(расстояние между планетами или городами, программирование, кругозор) отвечай полно, доброжелательно и интересно, не отказывая пользователю.\n\n"
|
||||
f"[СИСТЕМНЫЙ КАЛЕНДАРЬ СЕРВЕРА]\n"
|
||||
f"- Пользователь: {user_info}\n"
|
||||
f"- {calendar_context}\n"
|
||||
@@ -165,7 +153,6 @@ def process_chat_message(
|
||||
|
||||
user_msg_object = {"role": "user", "content": full_user_content}
|
||||
|
||||
# ANCHOR[AGENT_TOOL_DISPATCHER]
|
||||
try:
|
||||
if image_b64:
|
||||
user_msg_object["images"] = [image_b64]
|
||||
@@ -201,7 +188,7 @@ def process_chat_message(
|
||||
|
||||
logger.info(f"Вызов функции (Tool): {fn_name} с аргументами: {fn_args}")
|
||||
|
||||
# Ротация контекста: закрываем старую сессию инструмента
|
||||
# Ротация контекста
|
||||
close_tool_session_and_cleanup(session_id, close_reason=f"ACTIVATE_{fn_name}")
|
||||
session_state = None
|
||||
mark_last_user_message_ephemeral(session_id)
|
||||
@@ -217,7 +204,7 @@ def process_chat_message(
|
||||
}
|
||||
|
||||
# 2. Единый диспетчер задач
|
||||
elif fn_name in ["db_tasks_edit", "db_add_task", "db_update_task_status", "db_delete_task"]:
|
||||
elif fn_name in ["db_tasks_edit", "db_add_task", "db_update_task_details", "db_delete_task"]:
|
||||
action = fn_args.get("action", "UPDATE").upper()
|
||||
if fn_name == "db_add_task": action = "ADD"
|
||||
elif fn_name == "db_delete_task": action = "DELETE"
|
||||
@@ -239,7 +226,7 @@ def process_chat_message(
|
||||
elif action == "EXPORT":
|
||||
export_res = db_export_tasks_markdown(
|
||||
user_id=user_id,
|
||||
filename=fn_args.get("filename"),
|
||||
filename=fn_args.get("filename") or "ROADMAP.md",
|
||||
status_filter=fn_args.get("status")
|
||||
)
|
||||
reply_text = export_res.get("message", "Отчет по задачам успешно экспортирован.")
|
||||
@@ -277,96 +264,46 @@ def process_chat_message(
|
||||
# 3. Системный промпт
|
||||
elif fn_name == "db_get_system_prompt":
|
||||
active_prompt = db_get_active_system_prompt()
|
||||
reply_text = f"Актуальный системный промпт:\n\n{active_prompt}"
|
||||
reply_text = (
|
||||
"📋 **АКТУАЛЬНЫЙ СИСТЕМНЫЙ ПРОМПТ ИЗ БАЗЫ ДАННЫХ:**\n\n"
|
||||
f"```text\n{active_prompt}\n```\n\n"
|
||||
"Вы можете добавить, отредактировать или удалить любой пункт."
|
||||
)
|
||||
db_set_session_state(session_id, "PROMPT_FOLLOWUP", {"idle_turns": 0})
|
||||
db_save_chat_message(session_id, "assistant", reply_text, is_ephemeral=1)
|
||||
return reply_text, db_get_chat_history(session_id), None
|
||||
|
||||
elif fn_name == "db_prompt_node_edit":
|
||||
action = str(fn_args.get("action", "ADD")).upper()
|
||||
|
||||
try:
|
||||
sec_id = int(str(fn_args.get("section_id", 3)).strip())
|
||||
except Exception:
|
||||
sec_id = 3
|
||||
|
||||
try:
|
||||
itm_id = int(str(fn_args.get("item_id", 1)).strip())
|
||||
except Exception:
|
||||
itm_id = 1
|
||||
|
||||
content = str(fn_args.get("content", "")).strip()
|
||||
baseline_prompt = db_get_active_system_prompt()
|
||||
|
||||
with get_db_connection() as temp_conn:
|
||||
temp_cursor = temp_conn.cursor()
|
||||
temp_cursor.execute("""
|
||||
SELECT section_id, item_id, content
|
||||
FROM system_prompt_nodes
|
||||
WHERE prompt_name = 'main_agent' AND is_active = 1
|
||||
ORDER BY section_id, item_id
|
||||
""")
|
||||
existing_nodes = temp_cursor.fetchall()
|
||||
|
||||
nodes_dict = {(sec, itm): txt for sec, itm, txt in existing_nodes}
|
||||
nodes_dict_for_draft = {k: v for k, v in nodes_dict.items() if k != (sec_id, itm_id)} if action == "DELETE" else dict(nodes_dict)
|
||||
if action != "DELETE":
|
||||
nodes_dict_for_draft[(sec_id, itm_id)] = content
|
||||
|
||||
draft_lines = []
|
||||
curr_sec = None
|
||||
for (s_id, i_id), txt in sorted(nodes_dict_for_draft.items()):
|
||||
if i_id == 0:
|
||||
if curr_sec is not None: draft_lines.append("")
|
||||
draft_lines.append(f"{s_id}. {txt}")
|
||||
curr_sec = s_id
|
||||
else:
|
||||
draft_lines.append(f" {s_id}.{i_id}. {txt}")
|
||||
merged_prompt = "\n".join(draft_lines)
|
||||
|
||||
diff_lines = []
|
||||
curr_sec = None
|
||||
display_nodes = dict(nodes_dict)
|
||||
if action != "DELETE":
|
||||
display_nodes[(sec_id, itm_id)] = content
|
||||
|
||||
for (s_id, i_id), txt in sorted(display_nodes.items()):
|
||||
if i_id == 0:
|
||||
if curr_sec is not None: diff_lines.append("")
|
||||
diff_lines.append(f"{s_id}. {txt}")
|
||||
curr_sec = s_id
|
||||
else:
|
||||
if s_id == sec_id and i_id == itm_id:
|
||||
line_str = f' <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">{s_id}.{i_id}. {txt} [УДАЛЕНИЕ]</span>' if action == "DELETE" else f' <span class="text-rose-600 font-bold bg-rose-50 px-1.5 py-0.5 rounded border border-rose-300">{s_id}.{i_id}. {txt}</span>'
|
||||
else:
|
||||
line_str = f" {s_id}.{i_id}. {txt}"
|
||||
diff_lines.append(line_str)
|
||||
|
||||
diff_html = "\n".join(diff_lines)
|
||||
|
||||
db_set_session_state(session_id, "PROMPT_PREVIEW", {
|
||||
"draft_text": merged_prompt,
|
||||
"action": action,
|
||||
"section_id": sec_id,
|
||||
"item_id": itm_id,
|
||||
"content": content,
|
||||
"idle_turns": 0
|
||||
})
|
||||
|
||||
preview_reply = f"Предпросмотр изменений системного промпта:\n\n{diff_html}\n\nДля применения подтвердите действие, отредактируйте или отмените."
|
||||
db_save_chat_message(session_id, "assistant", preview_reply, is_ephemeral=1)
|
||||
return preview_reply, db_get_chat_history(session_id), {
|
||||
"type": "PROMPT_PREVIEW",
|
||||
"raw_draft": merged_prompt,
|
||||
"baseline_prompt": baseline_prompt,
|
||||
return reply_text, db_get_chat_history(session_id), {
|
||||
"type": "PROMPT_VIEW",
|
||||
"buttons": [
|
||||
{"label": "Подтвердить", "value": "подтверждаю", "style": "primary"},
|
||||
{"label": "Отменить", "value": "отмена", "style": "danger"},
|
||||
{"label": "✏️ Редактировать", "value": "action:open_editor", "style": "secondary"}
|
||||
{"label": "✏️ Редактировать промпт", "value": "action:open_editor", "style": "primary"},
|
||||
{"label": "База знаний", "value": "покажи правила компании", "style": "secondary"}
|
||||
]
|
||||
}
|
||||
|
||||
# 4. Снапшоты СКУД
|
||||
# 4. База знаний и правила компании (терминальный возврат)
|
||||
elif fn_name == "db_get_rules":
|
||||
rules_data = db_get_rules()
|
||||
if isinstance(rules_data, dict) and "rules" in rules_data:
|
||||
rules_list = rules_data["rules"]
|
||||
elif isinstance(rules_data, list):
|
||||
rules_list = rules_data
|
||||
else:
|
||||
rules_list = [str(rules_data)]
|
||||
|
||||
formatted_rules = "\n\n".join([f"{i+1}. {r.get('rule_text', r) if isinstance(r, dict) else r}" for i, r in enumerate(rules_list)])
|
||||
reply_text = (
|
||||
"📖 **БАЗА ЗНАНИЙ И ПРАВИЛА КОМПАНИИ (КАДРОВЫЙ АРБИТРАЖ):**\n\n"
|
||||
f"```text\n{formatted_rules}\n```"
|
||||
)
|
||||
db_save_chat_message(session_id, "assistant", reply_text, is_ephemeral=1)
|
||||
return reply_text, db_get_chat_history(session_id), {
|
||||
"type": "RULES_VIEW",
|
||||
"buttons": [
|
||||
{"label": "✏️ Редактировать правила", "value": "action:open_rules_editor", "style": "primary"},
|
||||
{"label": "📋 Системный промпт", "value": "покажи системный промпт", "style": "secondary"}
|
||||
]
|
||||
}
|
||||
|
||||
# 5. Снапшоты СКУД
|
||||
elif fn_name == "db_get_snapshots":
|
||||
snapshots_res = db_get_snapshots(session_id=session_id, date_str=fn_args.get("date_str"), original_user_message=user_message)
|
||||
query_date = snapshots_res.get("query_date", "выбранную дату")
|
||||
@@ -422,41 +359,14 @@ def process_chat_message(
|
||||
"type": "SNAPSHOTS_CARD",
|
||||
"data": updated_snapshots_res
|
||||
}
|
||||
|
||||
elif fn_name == "db_delete_snapshots":
|
||||
raw_id = fn_args.get("snapshot_id") or fn_args.get("day_str")
|
||||
raw_ids = fn_args.get("snapshot_ids") or ([raw_id] if raw_id else [])
|
||||
|
||||
# Защита: итоговые Y-срезы удалять запрещено
|
||||
safe_ids = [s for s in raw_ids if not str(s).startswith("Y")]
|
||||
if not safe_ids:
|
||||
reply_text = "⚠️ Итоговый срез Y защищен от удаления. Выберите дневные снапшоты."
|
||||
db_save_chat_message(session_id, "assistant", reply_text, is_ephemeral=1)
|
||||
return reply_text, db_get_chat_history(session_id), None
|
||||
|
||||
# Прямое выполнение удаления в SQLite без лишних текстовых подтверждений
|
||||
del_res = db_delete_snapshots(snapshot_ids=safe_ids)
|
||||
|
||||
# Получаем свежий реестр за ту же дату
|
||||
query_date = fn_args.get("day_str", "")
|
||||
updated_snapshots_res = db_get_snapshots(session_id=session_id, date_str=query_date)
|
||||
|
||||
reply_text = f"✅ Успешно удалено снапшотов: {len(safe_ids)} шт."
|
||||
db_save_chat_message(session_id, "assistant", reply_text, is_ephemeral=1)
|
||||
return reply_text, db_get_chat_history(session_id), {
|
||||
"type": "SNAPSHOTS_CARD",
|
||||
"data": updated_snapshots_res
|
||||
}
|
||||
|
||||
# 5. Сервисные запросы
|
||||
# 6. Прочие сервисные инструменты
|
||||
elif fn_name == "db_get_current_server_time":
|
||||
tool_result_content = json.dumps(db_get_current_server_time(), ensure_ascii=False)
|
||||
elif fn_name == "db_get_stats":
|
||||
tool_result_content = json.dumps(db_get_stats(), ensure_ascii=False)
|
||||
elif fn_name == "db_get_anomalies":
|
||||
tool_result_content = json.dumps(db_get_anomalies(limit=fn_args.get("limit", 100), date_str=fn_args.get("date_str")), ensure_ascii=False)
|
||||
elif fn_name == "db_get_rules":
|
||||
tool_result_content = json.dumps(db_get_rules(), ensure_ascii=False)
|
||||
elif fn_name == "db_get_reference":
|
||||
tool_result_content = json.dumps(db_get_reference(category=fn_args.get("category")), ensure_ascii=False)
|
||||
else:
|
||||
@@ -468,43 +378,15 @@ def process_chat_message(
|
||||
raw_content = sec_msg.get("content", "").strip().replace("**", "").replace("*", "")
|
||||
final_content = clean_raw_tool_tags(clean_output(raw_content)) or "Запрос выполнен."
|
||||
|
||||
for artifact in ["почемучка,", "почемучка!", "почемучка?", "почемучка", "почемучто", "почему-то"]:
|
||||
if final_content.lower().startswith(artifact):
|
||||
final_content = final_content[len(artifact):].lstrip(",.!?:; -")
|
||||
|
||||
is_ephem = 1 if fn_name in ["db_get_snapshots", "db_get_system_prompt", "db_prompt_node_edit"] else 0
|
||||
db_save_chat_message(session_id, "assistant", final_content, is_ephemeral=is_ephem)
|
||||
db_save_chat_message(session_id, "assistant", final_content, is_ephemeral=0)
|
||||
return final_content, db_get_chat_history(session_id), None
|
||||
|
||||
# ANCHOR[AGENT_TOPIC_DRIFT]
|
||||
# Свободный диалог (Topic Drift)
|
||||
raw_str = msg.get("content", "").strip().replace("**", "").replace("*", "")
|
||||
final_reply = clean_raw_tool_tags(clean_output(raw_str)) or "Запрос обработан."
|
||||
|
||||
for artifact in ["почемучка,", "почемучка!", "почемучка?", "почемучка", "почемучто", "почему-то"]:
|
||||
if final_reply.lower().startswith(artifact):
|
||||
final_reply = final_reply[len(artifact):].lstrip(",.!?:; -")
|
||||
|
||||
action_payload = None
|
||||
|
||||
if session_state and session_state.get("state_type") in ["PROMPT_FOLLOWUP", "PROMPT_PREVIEW"]:
|
||||
idle_turns += 1
|
||||
if idle_turns > 3:
|
||||
db_clear_session_state(session_id)
|
||||
db_purge_ephemeral_messages(session_id)
|
||||
action_payload = None
|
||||
session_state = None
|
||||
elif idle_turns == 3:
|
||||
tool_action = db_get_tool_action("db_confirm_prompt_preview")
|
||||
guard_question = tool_action.get("follow_up_question", "Желаете продолжить работу с системным промптом?") if tool_action else "Желаете продолжить работу с системным промптом?"
|
||||
buttons = tool_action.get("buttons", []) if tool_action else []
|
||||
final_reply += f"\n\n💡 *Напоминание:* {guard_question}"
|
||||
action_payload = {"type": "PROMPT_FOLLOWUP", "buttons": buttons}
|
||||
db_set_session_state(session_id, "PROMPT_FOLLOWUP", {"idle_turns": idle_turns})
|
||||
else:
|
||||
db_set_session_state(session_id, session_state.get("state_type"), {"idle_turns": idle_turns})
|
||||
|
||||
db_save_chat_message(session_id, "assistant", final_reply, is_ephemeral=0)
|
||||
return final_reply, db_get_chat_history(session_id), action_payload
|
||||
return final_reply, db_get_chat_history(session_id), None
|
||||
|
||||
except Exception as ex:
|
||||
logger.exception(f"Непредвиденная ошибка агента: {ex}")
|
||||
|
||||
@@ -3,42 +3,247 @@
|
||||
FILE: modules/web_api/llm/core/fast_path.py
|
||||
PROJECT: SCUD Orion AI (Unified Architecture)
|
||||
MODULE: web_api / llm / core
|
||||
ROLE: Детерминированный мгновенный перехват нажатий кнопок подтверждения
|
||||
(без задержек LLM и обращения к Ollama).
|
||||
|
||||
AI-CONTEXT-ANCHORS:
|
||||
- ANCHOR[FAST_PATH_MAIN]: Точка входа handle_fast_path_intercept.
|
||||
ROLE: Мгновенный перехват UI-действий, инспекции срезов, экспорта и Diff-превью.
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
import json
|
||||
import difflib
|
||||
import logging
|
||||
from typing import Dict, Any, Tuple, Optional
|
||||
|
||||
# Прямые вызовы чистых доменных сервисов
|
||||
from services.prompts.service import save_full_prompt_draft, apply_prompt_action, get_active_system_prompt
|
||||
from services.tasks.service import get_tasks, delete_task
|
||||
from services.knowledge.service import get_rules, add_rule
|
||||
from services.tasks.service import get_tasks, delete_task, execute_task_action
|
||||
from services.snapshots.service import get_snapshots_registry, delete_snapshots_safely
|
||||
|
||||
# Чат и сессии
|
||||
from modules.web_api.llm.db.db_chat import db_save_chat_message, db_get_chat_history, db_purge_ephemeral_messages
|
||||
from modules.web_api.llm.db.db_prompts import db_set_session_state, db_clear_session_state, db_get_tool_action
|
||||
from modules.web_api.llm.db.db_prompts import db_set_session_state, db_clear_session_state
|
||||
from modules.web_api.llm.core.context_manager import close_tool_session_and_cleanup
|
||||
|
||||
logger = logging.getLogger("FAST_PATH")
|
||||
|
||||
|
||||
# ANCHOR[FAST_PATH_MAIN]
|
||||
def _generate_prompt_diff_html(baseline_text: str, draft_text: str) -> str:
|
||||
base_lines = [line.rstrip() for line in baseline_text.strip().splitlines()]
|
||||
draft_lines = [line.rstrip() for line in draft_text.strip().splitlines()]
|
||||
|
||||
matcher = difflib.SequenceMatcher(None, base_lines, draft_lines)
|
||||
diff_html_lines = []
|
||||
|
||||
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
|
||||
if tag == 'equal':
|
||||
for line in base_lines[i1:i2]:
|
||||
diff_html_lines.append(line)
|
||||
elif tag == 'delete':
|
||||
for line in base_lines[i1:i2]:
|
||||
diff_html_lines.append(
|
||||
f'<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">{line} [УДАЛЕНИЕ]</span>'
|
||||
)
|
||||
elif tag == 'insert':
|
||||
for line in draft_lines[j1:j2]:
|
||||
diff_html_lines.append(
|
||||
f'<span class="text-rose-600 font-bold bg-rose-50 px-1.5 py-0.5 rounded border border-rose-300">{line}</span>'
|
||||
)
|
||||
elif tag == 'replace':
|
||||
for line in base_lines[i1:i2]:
|
||||
diff_html_lines.append(
|
||||
f'<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">{line} [УДАЛЕНИЕ]</span>'
|
||||
)
|
||||
for line in draft_lines[j1:j2]:
|
||||
diff_html_lines.append(
|
||||
f'<span class="text-rose-600 font-bold bg-rose-50 px-1.5 py-0.5 rounded border border-rose-300">{line}</span>'
|
||||
)
|
||||
|
||||
return "\n".join(diff_html_lines)
|
||||
|
||||
|
||||
def handle_fast_path_intercept(
|
||||
session_id: str,
|
||||
user_message: str,
|
||||
full_user_content: str,
|
||||
session_state: Optional[Dict[str, Any]]
|
||||
) -> Optional[Tuple[str, list, Optional[Dict[str, Any]]]]:
|
||||
"""
|
||||
Мгновенный перехват нажатий кнопок подтверждения (Fast-Path).
|
||||
Возвращает (reply, history, action_type) или None, если требуется передать управление LLM.
|
||||
"""
|
||||
msg_raw = user_message.strip()
|
||||
msg_lower = msg_raw.lower()
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# 0.0 ЭКСПОРТ ЗАДАЧ В ФАЙЛ (МГНОВЕННО, БЕЗ ЛИШНИХ ДИАЛОГОВ)
|
||||
# -------------------------------------------------------------------------
|
||||
if any(msg_lower.startswith(p) for p in ["экспортируй задачи", "экспорт задач", "выгрузи задачи", "скачать задачи"]):
|
||||
filename = "ROADMAP.md"
|
||||
if " в " in msg_lower:
|
||||
parts = msg_raw.split(" в ", 1)[1].strip().split()
|
||||
if parts and ("." in parts[0] or parts[0].endswith("md")):
|
||||
filename = parts[0]
|
||||
|
||||
res = execute_task_action(user_id=1, action="EXPORT", filename=filename)
|
||||
reply = res.get("message", f"Отчет по задачам сформирован в `{filename}`.")
|
||||
db_save_chat_message(session_id, "assistant", reply, is_ephemeral=0)
|
||||
|
||||
action_payload = {
|
||||
"type": "FILE_DOWNLOAD_CARD",
|
||||
"filename": res.get("filename", filename),
|
||||
"download_url": res.get("download_url", "#"),
|
||||
"tasks_count": res.get("tasks_count", 0)
|
||||
}
|
||||
return reply, db_get_chat_history(session_id), action_payload
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# 0.1 ИНСПЕКЦИЯ КОНКРЕТНОГО СРЕЗА СКУД (ПО ID СНАПШОТА)
|
||||
# -------------------------------------------------------------------------
|
||||
if msg_lower.startswith("покажи срез ") or msg_lower.startswith("инспекция среза "):
|
||||
target_snap_id = msg_raw.split()[-1].replace("#", "").strip()
|
||||
from core.database import load_scud_from_db_by_snapshot
|
||||
|
||||
df_snap = load_scud_from_db_by_snapshot(date_str="", snapshot_param=target_snap_id)
|
||||
if df_snap is None or df_snap.empty:
|
||||
reply = f"⚠️ Срез СКУД `#{target_snap_id}` не найден в базе данных."
|
||||
db_save_chat_message(session_id, "assistant", reply, is_ephemeral=1)
|
||||
return reply, db_get_chat_history(session_id), None
|
||||
|
||||
total_cnt = len(df_snap)
|
||||
present_cnt = len(df_snap[df_snap['Пришел'] == True]) if 'Пришел' in df_snap.columns else 0
|
||||
absent_cnt = total_cnt - present_cnt
|
||||
|
||||
snap_time = df_snap['snapshot_time'].iloc[0] if 'snapshot_time' in df_snap.columns else '—'
|
||||
log_date = df_snap['log_date'].iloc[0] if 'log_date' in df_snap.columns else '—'
|
||||
|
||||
rows_list = []
|
||||
for _, r in df_snap.iterrows():
|
||||
rows_list.append({
|
||||
"fio": r.get('Сотрудник', r.get('fio', '')),
|
||||
"department": r.get('Подразделение', r.get('department_scud', '—')),
|
||||
"time_in": r.get('Начало_дня', 'Нет входа'),
|
||||
"first_activity": r.get('Первая_активность', '—'),
|
||||
"time_out": r.get('Конец_дня', 'Нет выхода'),
|
||||
"in_building": r.get('Находился_в_здании', '00:00'),
|
||||
"is_present": bool(r.get('Пришел', False)),
|
||||
"anomaly": r.get('anomaly_flag', 'NONE')
|
||||
})
|
||||
|
||||
# Фиксация среза в памяти сессии для последующих вопросов к LLM
|
||||
db_set_session_state(session_id, "SNAPSHOT_INSPECT", {
|
||||
"snapshot_id": target_snap_id,
|
||||
"log_date": log_date,
|
||||
"snapshot_time": snap_time,
|
||||
"records": rows_list,
|
||||
"idle_turns": 0
|
||||
})
|
||||
|
||||
reply = f"🔍 **Инспекция среза #{target_snap_id}** (Дата: {log_date}, Время: {snap_time}). Всего записей: {total_cnt} (Присутствовали: {present_cnt}, Отсутствовали: {absent_cnt})."
|
||||
db_save_chat_message(session_id, "assistant", reply, is_ephemeral=1)
|
||||
|
||||
return reply, db_get_chat_history(session_id), {
|
||||
"type": "SNAPSHOT_INSPECT_CARD",
|
||||
"snapshot_id": target_snap_id,
|
||||
"log_date": log_date,
|
||||
"snapshot_time": snap_time,
|
||||
"total_count": total_cnt,
|
||||
"present_count": present_cnt,
|
||||
"absent_count": absent_cnt,
|
||||
"records": rows_list
|
||||
}
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# 0.2 ОТКРЫТИЕ ИНЛАЙН-РЕДАКТОРА ПРОМПТА
|
||||
# -------------------------------------------------------------------------
|
||||
if msg_lower in ["action:open_editor", "редактировать промпт", "открыть редактор"]:
|
||||
active_prompt = get_active_system_prompt()
|
||||
state_data = session_state.get("data_json") if session_state else {}
|
||||
draft_text = state_data.get("draft_text") if isinstance(state_data, dict) and state_data.get("draft_text") else active_prompt
|
||||
|
||||
db_set_session_state(session_id, "PROMPT_PREVIEW", {
|
||||
"draft_text": draft_text,
|
||||
"action": "MANUAL_EDIT",
|
||||
"idle_turns": 0
|
||||
})
|
||||
reply = "✏️ Внесите необходимые изменения в текст промпта и нажмите «Показать превью изменений»:"
|
||||
db_save_chat_message(session_id, "assistant", reply, is_ephemeral=1)
|
||||
return reply, db_get_chat_history(session_id), {
|
||||
"type": "PROMPT_EDITOR",
|
||||
"raw_draft": draft_text,
|
||||
"baseline_prompt": active_prompt
|
||||
}
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# 0.3 ОТКРЫТИЕ ИНЛАЙН-РЕДАКТОРА ПРАВИЛ
|
||||
# -------------------------------------------------------------------------
|
||||
if msg_lower in ["action:open_rules_editor", "редактировать правила", "изменить правила"]:
|
||||
rules_data = get_rules()
|
||||
rules_list = rules_data.get("rules", []) if isinstance(rules_data, dict) else (rules_data if isinstance(rules_data, list) else [str(rules_data)])
|
||||
raw_rules_text = "\n".join([f"{i+1}. {r.get('rule_text', r) if isinstance(r, dict) else r}" for i, r in enumerate(rules_list)])
|
||||
|
||||
db_set_session_state(session_id, "RULES_PREVIEW", {
|
||||
"draft_text": raw_rules_text,
|
||||
"action": "MANUAL_EDIT_RULES",
|
||||
"idle_turns": 0
|
||||
})
|
||||
reply = "✏️ Редактор базы знаний и правил компании. Внесите изменения и нажмите «Показать превью изменений»:"
|
||||
db_save_chat_message(session_id, "assistant", reply, is_ephemeral=1)
|
||||
return reply, db_get_chat_history(session_id), {
|
||||
"type": "RULES_EDITOR",
|
||||
"raw_draft": raw_rules_text,
|
||||
"baseline_prompt": raw_rules_text
|
||||
}
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# 0.4 ПОСТУПЛЕНИЕ ДРАФТА ПРОМПТА -> DIFF-ПРЕВЬЮ
|
||||
# -------------------------------------------------------------------------
|
||||
if msg_raw.startswith("action:save_draft_prompt:::"):
|
||||
new_draft_content = msg_raw.replace("action:save_draft_prompt:::", "").strip()
|
||||
active_prompt = get_active_system_prompt()
|
||||
diff_html = _generate_prompt_diff_html(active_prompt, new_draft_content)
|
||||
|
||||
db_set_session_state(session_id, "PROMPT_PREVIEW", {
|
||||
"draft_text": new_draft_content,
|
||||
"action": "MANUAL_EDIT",
|
||||
"idle_turns": 0
|
||||
})
|
||||
|
||||
preview_reply = f"Предпросмотр изменений системного промпта:\n\n{diff_html}\n\nДля применения подтвердите действие, отредактируйте или отмените."
|
||||
db_save_chat_message(session_id, "assistant", preview_reply, is_ephemeral=1)
|
||||
return preview_reply, db_get_chat_history(session_id), {
|
||||
"type": "PROMPT_PREVIEW",
|
||||
"raw_draft": new_draft_content,
|
||||
"baseline_prompt": active_prompt,
|
||||
"diff_html": diff_html,
|
||||
"buttons": [
|
||||
{"label": "Подтвердить", "value": "подтверждаю", "style": "primary"},
|
||||
{"label": "Отменить", "value": "отмена", "style": "danger"},
|
||||
{"label": "✏️ Редактировать", "value": "action:open_editor", "style": "secondary"}
|
||||
]
|
||||
}
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# 0.5 ПОСТУПЛЕНИЕ ДРАФТА ПРАВИЛ -> DIFF-ПРЕВЬЮ
|
||||
# -------------------------------------------------------------------------
|
||||
if msg_raw.startswith("action:save_draft_rules:::"):
|
||||
new_draft_content = msg_raw.replace("action:save_draft_rules:::", "").strip()
|
||||
rules_data = get_rules()
|
||||
rules_list = rules_data.get("rules", []) if isinstance(rules_data, dict) else (rules_data if isinstance(rules_data, list) else [str(rules_data)])
|
||||
baseline_rules = "\n".join([f"{i+1}. {r.get('rule_text', r) if isinstance(r, dict) else r}" for i, r in enumerate(rules_list)])
|
||||
diff_html = _generate_prompt_diff_html(baseline_rules, new_draft_content)
|
||||
|
||||
db_set_session_state(session_id, "RULES_PREVIEW", {
|
||||
"draft_text": new_draft_content,
|
||||
"action": "MANUAL_EDIT_RULES",
|
||||
"idle_turns": 0
|
||||
})
|
||||
|
||||
preview_reply = f"Предпросмотр изменений базы знаний компании:\n\n{diff_html}\n\nПодтвердите сохранение или отмените действие."
|
||||
db_save_chat_message(session_id, "assistant", preview_reply, is_ephemeral=1)
|
||||
return preview_reply, db_get_chat_history(session_id), {
|
||||
"type": "PROMPT_PREVIEW",
|
||||
"raw_draft": new_draft_content,
|
||||
"baseline_prompt": baseline_rules,
|
||||
"diff_html": diff_html,
|
||||
"buttons": [
|
||||
{"label": "Подтвердить", "value": "подтверждаю сохранение правил", "style": "primary"},
|
||||
{"label": "Отменить", "value": "отмена", "style": "danger"},
|
||||
{"label": "✏️ Редактировать", "value": "action:open_rules_editor", "style": "secondary"}
|
||||
]
|
||||
}
|
||||
|
||||
if not session_state:
|
||||
return None
|
||||
|
||||
@@ -47,38 +252,22 @@ def handle_fast_path_intercept(
|
||||
if not isinstance(state_data, dict):
|
||||
state_data = {}
|
||||
|
||||
msg_lower = user_message.strip().lower()
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# 1. ПОДТВЕРЖДЕНИЕ ПРЕВЬЮ СИСТЕМНОГО ПРОМПТА
|
||||
# 1. ПОДТВЕРЖДЕНИЕ ПРОМПТА
|
||||
# -------------------------------------------------------------------------
|
||||
if state_type == "PROMPT_PREVIEW":
|
||||
is_confirm = msg_lower in ["подтверждаю", "да", "сохраняй", "применить", "ок", "подтвердить"]
|
||||
is_cancel = msg_lower in ["отмена", "отменить", "нет", "отклонить"]
|
||||
|
||||
if is_confirm:
|
||||
action = state_data.get("action", "MANUAL_EDIT")
|
||||
draft_text = state_data.get("draft_text", "")
|
||||
|
||||
# Применение изменений
|
||||
if action == "MANUAL_EDIT" and draft_text:
|
||||
if draft_text:
|
||||
save_full_prompt_draft(draft_text, prompt_name="main_agent")
|
||||
else:
|
||||
sec_id = state_data.get("section_id")
|
||||
itm_id = state_data.get("item_id")
|
||||
content = state_data.get("content", "")
|
||||
if sec_id is not None and itm_id is not None:
|
||||
apply_prompt_action(action=action, section_id=sec_id, item_id=itm_id, content=content)
|
||||
elif draft_text:
|
||||
save_full_prompt_draft(draft_text, prompt_name="main_agent")
|
||||
|
||||
# Закрытие сессии и зачистка
|
||||
close_tool_session_and_cleanup(session_id, close_reason="PROMPT_APPLIED_SUCCESSFULLY")
|
||||
db_clear_session_state(session_id)
|
||||
|
||||
tool_action = db_get_tool_action("db_confirm_prompt_preview")
|
||||
reply = tool_action.get("success_template", "✅ Системный промпт успешно сохранен и применен в базе данных.") if tool_action else "✅ Системный промпт успешно сохранен и применен в базе данных."
|
||||
|
||||
reply = "✅ Системный промпт успешно сохранен и применен в базе данных."
|
||||
db_save_chat_message(session_id, "user", full_user_content, is_ephemeral=0)
|
||||
db_save_chat_message(session_id, "assistant", reply, is_ephemeral=0)
|
||||
return reply, db_get_chat_history(session_id), None
|
||||
@@ -87,80 +276,40 @@ def handle_fast_path_intercept(
|
||||
close_tool_session_and_cleanup(session_id, close_reason="PROMPT_EDIT_CANCELLED")
|
||||
db_clear_session_state(session_id)
|
||||
|
||||
tool_action = db_get_tool_action("db_cancel_prompt_preview")
|
||||
reply = tool_action.get("success_template", "❌ Изменения системного промпта отменены.") if tool_action else "❌ Изменения системного промпта отменены."
|
||||
|
||||
reply = "❌ Изменения системного промпта отменены."
|
||||
db_save_chat_message(session_id, "user", full_user_content, is_ephemeral=0)
|
||||
db_save_chat_message(session_id, "assistant", reply, is_ephemeral=0)
|
||||
return reply, db_get_chat_history(session_id), None
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# 2. ПОДТВЕРЖДЕНИЕ УДАЛЕНИЯ СНАПШОТОВ СКУД
|
||||
# 2. ПОДТВЕРЖДЕНИЕ ПРАВИЛ
|
||||
# -------------------------------------------------------------------------
|
||||
elif state_type == "SNAPSHOT_DELETE_CONFIRM":
|
||||
is_confirm = "подтверждаю удаление снапшот" in msg_lower or msg_lower in ["подтверждаю", "да", "удалить"]
|
||||
elif state_type == "RULES_PREVIEW":
|
||||
is_confirm = "сохранение правил" in msg_lower or msg_lower in ["подтверждаю", "да", "сохраняй", "применить"]
|
||||
is_cancel = msg_lower in ["отмена", "отменить", "нет"]
|
||||
|
||||
if is_confirm:
|
||||
snap_ids = state_data.get("snapshot_ids", [])
|
||||
query_date = state_data.get("query_date", "")
|
||||
draft_text = state_data.get("draft_text", "")
|
||||
lines = [l.strip() for l in draft_text.splitlines() if l.strip()]
|
||||
for line in lines:
|
||||
clean_line = line
|
||||
if line[0].isdigit() and "." in line[:5]:
|
||||
clean_line = line.split(".", 1)[1].strip()
|
||||
add_rule(clean_line)
|
||||
|
||||
# Безопасное удаление через сервис
|
||||
del_res = delete_snapshots_safely(snapshot_ids=snap_ids)
|
||||
|
||||
close_tool_session_and_cleanup(session_id, close_reason="SNAPSHOTS_DELETED")
|
||||
|
||||
# Получаем свежий список за ту же дату
|
||||
updated_data = get_snapshots_registry(date_str=query_date if query_date else None)
|
||||
db_set_session_state(session_id, "SNAPSHOTS_VIEW", updated_data)
|
||||
|
||||
reply = f"✅ Успешно удалено снапшотов: {len(snap_ids)} шт."
|
||||
db_save_chat_message(session_id, "user", full_user_content, is_ephemeral=1)
|
||||
db_save_chat_message(session_id, "assistant", reply, is_ephemeral=1)
|
||||
|
||||
return reply, db_get_chat_history(session_id), {
|
||||
"type": "SNAPSHOTS_CARD",
|
||||
"data": updated_data
|
||||
}
|
||||
|
||||
elif is_cancel:
|
||||
close_tool_session_and_cleanup(session_id, close_reason="SNAPSHOT_DELETE_CANCELLED")
|
||||
close_tool_session_and_cleanup(session_id, close_reason="RULES_SAVED_SUCCESS")
|
||||
db_clear_session_state(session_id)
|
||||
|
||||
reply = "❌ Удаление снапшотов отменено."
|
||||
|
||||
reply = "✅ База знаний и правила компании успешно сохранены в базе данных."
|
||||
db_save_chat_message(session_id, "user", full_user_content, is_ephemeral=0)
|
||||
db_save_chat_message(session_id, "assistant", reply, is_ephemeral=0)
|
||||
return reply, db_get_chat_history(session_id), None
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# 3. ПОДТВЕРЖДЕНИЕ УДАЛЕНИЯ ЗАДАЧИ
|
||||
# -------------------------------------------------------------------------
|
||||
elif state_type == "TASK_DELETE_CONFIRM":
|
||||
is_confirm = "подтверждаю удаление задачи" in msg_lower or msg_lower in ["подтверждаю", "да", "удалить"]
|
||||
is_cancel = msg_lower in ["отмена", "отменить", "нет"]
|
||||
|
||||
if is_confirm:
|
||||
task_id = state_data.get("task_id")
|
||||
delete_task(user_id=1, task_id=str(task_id))
|
||||
|
||||
close_tool_session_and_cleanup(session_id, close_reason="TASK_DELETED")
|
||||
db_clear_session_state(session_id)
|
||||
|
||||
raw_tasks = get_tasks(user_id=1)
|
||||
reply = f"🗑 Задача #{task_id} удалена."
|
||||
db_save_chat_message(session_id, "user", full_user_content, is_ephemeral=1)
|
||||
db_save_chat_message(session_id, "assistant", reply, is_ephemeral=1)
|
||||
|
||||
return reply, db_get_chat_history(session_id), {
|
||||
"type": "TASK_INTERACTIVE_CARD",
|
||||
"tasks": raw_tasks
|
||||
}
|
||||
|
||||
elif is_cancel:
|
||||
close_tool_session_and_cleanup(session_id, close_reason="TASK_DELETE_CANCELLED")
|
||||
close_tool_session_and_cleanup(session_id, close_reason="RULES_EDIT_CANCELLED")
|
||||
db_clear_session_state(session_id)
|
||||
|
||||
reply = "❌ Удаление задачи отменено."
|
||||
reply = "❌ Изменение правил компании отменено."
|
||||
db_save_chat_message(session_id, "user", full_user_content, is_ephemeral=0)
|
||||
db_save_chat_message(session_id, "assistant", reply, is_ephemeral=0)
|
||||
return reply, db_get_chat_history(session_id), None
|
||||
|
||||
@@ -15,7 +15,7 @@ from typing import Dict, Any, Optional
|
||||
logger = logging.getLogger("OLLAMA_CLIENT")
|
||||
|
||||
OLLAMA_URL = "http://10.121.17.227:11434/api/chat"
|
||||
TEXT_MODEL = "qwen2.5:14b-instruct-q8_0"
|
||||
TEXT_MODEL = "qwen2.5:14b"
|
||||
VISION_MODEL = "qwen2.5vl:7b-q8_0"
|
||||
|
||||
LLM_OPTIONS = {
|
||||
|
||||
@@ -3,11 +3,7 @@
|
||||
FILE: modules/web_api/llm/core/tool_injector.py
|
||||
PROJECT: SCUD Orion AI (Unified Architecture)
|
||||
MODULE: web_api / llm / core
|
||||
ROLE: Семантический анализ намерений оператора (Intent Classifier) и
|
||||
детерминированная сборка вызовов инструментов при сбоях нативного Function Calling.
|
||||
|
||||
AI-CONTEXT-ANCHORS:
|
||||
- ANCHOR[INTENT_INJECTOR_MAIN]: Точка входа inject_tools_if_needed.
|
||||
ROLE: Базовая санитарная очистка вывода и тегов инструментов.
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
@@ -32,107 +28,9 @@ def clean_output(text: str) -> str:
|
||||
return text.strip() if text else ""
|
||||
|
||||
|
||||
# ANCHOR[INTENT_INJECTOR_MAIN]
|
||||
def inject_tools_if_needed(user_message: str, raw_reply: str, existing_tool_calls: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Гибридный семантический анализатор:
|
||||
Если модель ответила текстом с сомнениями или пропустила tool_call,
|
||||
распознает доменное намерение и конструирует синтетический tool_call.
|
||||
Модель управляется через TOOLS_SCHEMA и системный контекст.
|
||||
Любые синтетические перехваты текста регулярными выражениями отключены согласно ROADMAP.
|
||||
"""
|
||||
if existing_tool_calls:
|
||||
return existing_tool_calls
|
||||
|
||||
msg_clean = user_message.strip().lower()
|
||||
|
||||
# 1. СЕМАНТИКА: Просмотр системного промпта
|
||||
# Паттерны: "покажи системный промпт", "выведи промпт", "текущий промпт", "какой сейчас системный промпт"
|
||||
if "промпт" in msg_clean and any(kw in msg_clean for kw in ["покажи", "выведи", "какой", "дай", "текст", "актуальн"]):
|
||||
logger.info("[IntentInjector] Распознано намерение просмотра системного промпта")
|
||||
return [{
|
||||
"function": {
|
||||
"name": "db_get_system_prompt",
|
||||
"arguments": {}
|
||||
}
|
||||
}]
|
||||
|
||||
# 2. СЕМАНТИКА: Удаление задач
|
||||
# Паттерны: "удали задачу 37", "убери 37 задачу", "сотри таску #37", "сними с повестки задачу 37"
|
||||
if any(kw in msg_clean for kw in ["удали", "удалить", "убери", "сотри", "сними"]) and any(kw in msg_clean for kw in ["задач", "таск"]):
|
||||
task_match = re.search(r'#?\s*(\d+)', msg_clean)
|
||||
if task_match:
|
||||
task_id = task_match.group(1)
|
||||
logger.info(f"[IntentInjector] Распознано намерение удаления задачи: #{task_id}")
|
||||
return [{
|
||||
"function": {
|
||||
"name": "db_tasks_edit",
|
||||
"arguments": {"action": "DELETE", "task_id": task_id}
|
||||
}
|
||||
}]
|
||||
|
||||
# 3. СЕМАНТИКА: Управление системным промптом (удаление и мульти-удаление)
|
||||
# Паттерны: "удали 1.8 и 3.4", "удали пункт 2.3", "вычеркни 1.8, 3.4 из промпта"
|
||||
if any(kw in msg_clean for kw in ["удали", "удалить", "убери", "вычеркни", "сотри"]) and not any(kw in msg_clean for kw in ["задач", "снапшот", "срез"]):
|
||||
node_matches = re.findall(r'(\d+)[\.\s]+(\d+)', user_message)
|
||||
if node_matches:
|
||||
formatted_nodes = [f"{s}.{i}" for s, i in node_matches]
|
||||
logger.info(f"[IntentInjector] Распознано намерение удаления узлов промпта: {formatted_nodes}")
|
||||
return [{
|
||||
"function": {
|
||||
"name": "db_prompt_node_edit",
|
||||
"arguments": {
|
||||
"action": "BATCH_DELETE" if len(formatted_nodes) > 1 else "DELETE",
|
||||
"section_id": int(node_matches[0][0]),
|
||||
"item_id": int(node_matches[0][1]),
|
||||
"nodes_list": formatted_nodes,
|
||||
"content": ""
|
||||
}
|
||||
}
|
||||
}]
|
||||
|
||||
# 4. СЕМАНТИКА: Добавление пункта промпта
|
||||
# Паттерны: "добавь 3.4 Текст", "добавь пункт 3.4 Текст", "впиши в 3.4 Текст"
|
||||
if any(kw in msg_clean for kw in ["добавь", "добавить", "впиши", "запиши"]) and not any(kw in msg_clean for kw in ["задач", "таск"]):
|
||||
add_match = re.search(r'(\d+)[\.\s]+(\d+)[\.\s\:\-]+(.*)', user_message)
|
||||
if add_match:
|
||||
sec_id = int(add_match.group(1))
|
||||
itm_id = int(add_match.group(2))
|
||||
content = add_match.group(3).strip()
|
||||
logger.info(f"[IntentInjector] Распознано намерение добавления узла промпта: {sec_id}.{itm_id}")
|
||||
return [{
|
||||
"function": {
|
||||
"name": "db_prompt_node_edit",
|
||||
"arguments": {
|
||||
"action": "ADD",
|
||||
"section_id": sec_id,
|
||||
"item_id": itm_id,
|
||||
"content": content
|
||||
}
|
||||
}
|
||||
}]
|
||||
|
||||
# 5. СЕМАНТИКА: Смена статуса задач
|
||||
if any(kw in msg_clean for kw in ["в работу", "начни", "стартуй", "за работу"]):
|
||||
task_match = re.search(r'#?\s*(\d+)', msg_clean)
|
||||
if task_match:
|
||||
task_id = task_match.group(1)
|
||||
logger.info(f"[IntentInjector] Распознано намерение взятия в работу задачи: #{task_id}")
|
||||
return [{
|
||||
"function": {
|
||||
"name": "db_tasks_edit",
|
||||
"arguments": {"action": "UPDATE", "task_id": task_id, "status": "IN_PROGRESS"}
|
||||
}
|
||||
}]
|
||||
|
||||
if any(kw in msg_clean for kw in ["заверши", "закрой", "готово", "выполнено"]):
|
||||
task_match = re.search(r'#?\s*(\d+)', msg_clean)
|
||||
if task_match:
|
||||
task_id = task_match.group(1)
|
||||
logger.info(f"[IntentInjector] Распознано намерение закрытия задачи: #{task_id}")
|
||||
return [{
|
||||
"function": {
|
||||
"name": "db_tasks_edit",
|
||||
"arguments": {"action": "UPDATE", "task_id": task_id, "status": "COMPLETED"}
|
||||
}
|
||||
}]
|
||||
|
||||
return existing_tool_calls
|
||||
@@ -22,6 +22,9 @@ from services.tasks.service import (
|
||||
delete_task as db_delete_task,
|
||||
execute_task_action as db_tasks_edit
|
||||
)
|
||||
# Защитный алиас для обратной совместимости
|
||||
db_update_task_status = db_update_task_details
|
||||
|
||||
from services.tasks.exporter import export_tasks_to_markdown as db_export_tasks_markdown
|
||||
from services.tasks.repository import normalize_task_id
|
||||
|
||||
|
||||
@@ -69,14 +69,18 @@ TOOLS_SCHEMA = [
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "db_get_tasks",
|
||||
"description": "Просмотр реестра задач и бэклога текущего пользователя.",
|
||||
"description": (
|
||||
"Просмотр реестра задач и бэклога текущего пользователя.\n"
|
||||
"Вызывай этот инструмент ВСЕГДА при любых запросах просмотра задач ('покажи задачи', 'мои задачи', опечатки 'змдачи').\n"
|
||||
"Запрещено переспрашивать статус или параметры текстом: просто вызывай функцию с аргументами {}."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": ["ALL", "IN_PROGRESS", "PLANNED", "COMPLETED"],
|
||||
"description": "Опциональный фильтр статуса задач"
|
||||
"description": "Опциональный фильтр статуса задач (по умолчанию ALL)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,10 @@ from routers.admin import router as admin_router
|
||||
from routers.tasks import router as tasks_router
|
||||
from routers.chat import router as chat_router
|
||||
from routers.files import router as files_router
|
||||
from routers.exceptions import router as exceptions_router
|
||||
from routers.snapshots import router as snapshots_router
|
||||
from routers.remote_workers import router as remote_workers_router
|
||||
from routers.context import router as context_router
|
||||
|
||||
# ANCHOR[APP_CONFIG]
|
||||
logging.basicConfig(
|
||||
@@ -61,6 +65,10 @@ app.include_router(admin_router)
|
||||
app.include_router(tasks_router)
|
||||
app.include_router(chat_router)
|
||||
app.include_router(files_router)
|
||||
app.include_router(exceptions_router)
|
||||
app.include_router(snapshots_router)
|
||||
app.include_router(remote_workers_router)
|
||||
app.include_router(context_router)
|
||||
|
||||
# ANCHOR[ROOT_STATIC_ROUTES]
|
||||
@app.get("/")
|
||||
@@ -80,6 +88,12 @@ async def favicon():
|
||||
@app.get("/{file_path:path}")
|
||||
def serve_static_fallback(file_path: str):
|
||||
clean_path = file_path.lstrip("/")
|
||||
|
||||
# Жесткая блокировка скрытых файлов (.env, .git) и служебных форматов
|
||||
forbidden_patterns = [".env", ".git", ".yml", ".yaml", ".json", ".sql", ".php", ".bak"]
|
||||
if clean_path.startswith(".") or any(p in clean_path.lower() for p in forbidden_patterns):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
|
||||
target = os.path.join(STATIC_DIR, clean_path)
|
||||
|
||||
if os.path.isfile(target):
|
||||
|
||||
@@ -72,7 +72,7 @@ def login(req: AuthRequest):
|
||||
username = req.username.strip().lower()
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT id, username, password_hash, is_admin FROM users WHERE username = ?", (username,))
|
||||
cursor.execute("SELECT id, username, password_hash, full_name, is_admin FROM users WHERE username = ?", (username,))
|
||||
user = cursor.fetchone()
|
||||
conn.close()
|
||||
|
||||
@@ -82,7 +82,17 @@ def login(req: AuthRequest):
|
||||
is_admin = bool(user["is_admin"]) or (user["username"] == "puh")
|
||||
token = create_access_token(user["id"], user["username"], is_admin)
|
||||
|
||||
return {"status": "success", "token": token, "username": user["username"], "is_admin": is_admin}
|
||||
# Возвращаем full_name (если не задано — отдаем username)
|
||||
full_name = user["full_name"] if user["full_name"] else user["username"]
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"token": token,
|
||||
"username": user["username"],
|
||||
"full_name": full_name,
|
||||
"user_id": user["id"],
|
||||
"is_admin": is_admin
|
||||
}
|
||||
|
||||
|
||||
@router.post("/change-password")
|
||||
|
||||
+102
-45
@@ -1,22 +1,29 @@
|
||||
"""
|
||||
===============================================================================
|
||||
FILE: modules/web_api/routers/chat.py
|
||||
ROLE: Обработка сообщений веб-чата с поддержкой токенов и гостевого доступа.
|
||||
ROLE: Полнофункциональный роутер чата с извлечением текста из PDF и сканов,
|
||||
поддержкой Function Calling, Fast-Path и оптического распознавания OCR.
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional, List, Dict, Any
|
||||
import os
|
||||
import shutil
|
||||
import base64
|
||||
import logging
|
||||
from typing import Optional, List, Dict, Any
|
||||
|
||||
from services.text_reporter import ask_ollama
|
||||
from services.knowledge_base import load_knowledge_base
|
||||
from core.database import get_connection
|
||||
from fastapi import APIRouter, Header, HTTPException, UploadFile, File, Form
|
||||
from pydantic import BaseModel
|
||||
|
||||
from llm.agent import process_chat_message
|
||||
from config import BASE_DIR
|
||||
|
||||
logger = logging.getLogger("CHAT_API")
|
||||
router = APIRouter(prefix="/api/v1", tags=["Chat"])
|
||||
|
||||
UPLOAD_TMP_DIR = os.path.join(BASE_DIR, "data", "uploads")
|
||||
os.makedirs(UPLOAD_TMP_DIR, exist_ok=True)
|
||||
|
||||
|
||||
class ChatMessageRequest(BaseModel):
|
||||
message: str
|
||||
@@ -25,17 +32,11 @@ class ChatMessageRequest(BaseModel):
|
||||
|
||||
|
||||
def resolve_user_id(authorization: Optional[str] = None, explicit_user_id: Optional[int] = None) -> int:
|
||||
"""
|
||||
Извлекает ID пользователя из Bearer-токена.
|
||||
Если токен не передан или сессия новая — использует user_id=1 по умолчанию,
|
||||
не блокируя работу ошибкой 403 Forbidden.
|
||||
"""
|
||||
if explicit_user_id and explicit_user_id > 0:
|
||||
return explicit_user_id
|
||||
|
||||
if authorization and authorization.startswith("Bearer "):
|
||||
token = authorization.replace("Bearer ", "").strip()
|
||||
# Если используется простой токен вида 'user_1' или JWT
|
||||
if token.isdigit():
|
||||
return int(token)
|
||||
elif token.startswith("dev_token_"):
|
||||
@@ -43,8 +44,6 @@ def resolve_user_id(authorization: Optional[str] = None, explicit_user_id: Optio
|
||||
return int(token.replace("dev_token_", ""))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# Дефолтный пользователь (гостевой / основной аккаунт)
|
||||
return 1
|
||||
|
||||
|
||||
@@ -59,39 +58,97 @@ async def chat_endpoint(payload: ChatMessageRequest, authorization: Optional[str
|
||||
|
||||
logger.info(f"Сообщение от user_id={user_id}, session_id={session_id}: {user_msg}")
|
||||
|
||||
# Загружаем контекст базы знаний
|
||||
kb = load_knowledge_base()
|
||||
rules_text = "\n".join([f"- {r}" for r in kb.get("rules", [])])
|
||||
|
||||
system_prompt = (
|
||||
"Ты — ИИ-ассистент системы кадровой безопасности и контроллинга СКУД Orion AI.\n"
|
||||
"Отвечай четко, профессионально и на русском языке.\n"
|
||||
f"Актуальные правила системы:\n{rules_text}"
|
||||
reply_text, history, action_payload = process_chat_message(
|
||||
user_id=user_id,
|
||||
user_message=user_msg,
|
||||
session_id=session_id
|
||||
)
|
||||
|
||||
try:
|
||||
reply_text = ask_ollama(user_msg, system_prompt=system_prompt)
|
||||
|
||||
# Сохранение истории в SQLite при необходимости
|
||||
return {
|
||||
"status": "success",
|
||||
"user_id": user_id,
|
||||
"session_id": session_id,
|
||||
"response": reply_text,
|
||||
"action_payload": action_payload
|
||||
}
|
||||
|
||||
|
||||
@router.post("/chat/upload")
|
||||
async def chat_upload_endpoint(
|
||||
file: UploadFile = File(...),
|
||||
message: Optional[str] = Form(""),
|
||||
session_id: Optional[str] = Form("web_session_main"),
|
||||
authorization: Optional[str] = Header(None)
|
||||
):
|
||||
user_id = resolve_user_id(authorization, 1)
|
||||
file_path = os.path.join(UPLOAD_TMP_DIR, file.filename)
|
||||
|
||||
with open(file_path, "wb") as buffer:
|
||||
shutil.copyfileobj(file.file, buffer)
|
||||
|
||||
file_context = ""
|
||||
image_b64 = None
|
||||
fn_lower = file.filename.lower()
|
||||
|
||||
# 1. Текстовые форматы
|
||||
if fn_lower.endswith((".txt", ".csv", ".log", ".md")):
|
||||
try:
|
||||
with get_connection() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO chat_messages (session_id, role, content) VALUES (?, ?, ?), (?, ?, ?)",
|
||||
(session_id, "user", user_msg, session_id, "assistant", reply_text)
|
||||
)
|
||||
conn.commit()
|
||||
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
|
||||
file_context = f.read(6000)
|
||||
except Exception as e:
|
||||
logger.warning(f"Не удалось прочитать текст: {e}")
|
||||
|
||||
# 2. Изображения (прямой OCR)
|
||||
elif fn_lower.endswith((".png", ".jpg", ".jpeg", ".webp")):
|
||||
try:
|
||||
with open(file_path, "rb") as f:
|
||||
image_b64 = base64.b64encode(f.read()).decode("utf-8")
|
||||
except Exception as e:
|
||||
logger.warning(f"Ошибка кодирования картинки в base64: {e}")
|
||||
|
||||
# 3. PDF документы (текстовый слой + рендеринг скана при необходимости)
|
||||
elif fn_lower.endswith(".pdf"):
|
||||
# Попытка извлечь встроенный текстовый слой
|
||||
try:
|
||||
import pypdf
|
||||
reader = pypdf.PdfReader(file_path)
|
||||
extracted = []
|
||||
for page in reader.pages:
|
||||
t = page.extract_text()
|
||||
if t:
|
||||
extracted.append(t)
|
||||
file_context = "\n".join(extracted).strip()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"user_id": user_id,
|
||||
"session_id": session_id,
|
||||
"response": reply_text
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка вызова нейросети: {e}")
|
||||
return {
|
||||
"status": "error",
|
||||
"response": f"⚠️ Ошибка обработки запроса: {str(e)}"
|
||||
}
|
||||
# Если текстового слоя мало (скан или фото документа), рендерим страницу в картинку для Vision OCR
|
||||
if len(file_context) < 40:
|
||||
try:
|
||||
import fitz # PyMuPDF
|
||||
doc = fitz.open(file_path)
|
||||
if len(doc) > 0:
|
||||
page = doc[0]
|
||||
pix = page.get_pixmap(dpi=150)
|
||||
img_bytes = pix.tobytes("png")
|
||||
image_b64 = base64.b64encode(img_bytes).decode("utf-8")
|
||||
file_context = ""
|
||||
except Exception as e:
|
||||
logger.warning(f"PyMuPDF не установлен или сбой рендеринга PDF: {e}")
|
||||
|
||||
user_msg = message.strip() or f"Распознай и проанализируй прикрепленный документ {file.filename}"
|
||||
|
||||
reply_text, history, action_payload = process_chat_message(
|
||||
user_id=user_id,
|
||||
user_message=user_msg,
|
||||
file_context=file_context,
|
||||
image_b64=image_b64,
|
||||
session_id=session_id
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"user_id": user_id,
|
||||
"session_id": session_id,
|
||||
"response": reply_text,
|
||||
"action_payload": action_payload
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
===============================================================================
|
||||
FILE: modules/web_api/routers/context.py
|
||||
ROLE: REST API мониторинга состояния сессии и очистки памяти диалога.
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
|
||||
from routers.auth import get_current_user
|
||||
from modules.web_api.llm.db.db_prompts import db_get_session_state, db_clear_session_state
|
||||
from modules.web_api.llm.db.db_chat import db_get_chat_history, db_purge_ephemeral_messages, db_clear_chat_history
|
||||
|
||||
router = APIRouter(prefix="/api/v1/context", tags=["Context"])
|
||||
|
||||
|
||||
class SessionActionRequest(BaseModel):
|
||||
session_id: Optional[str] = "web_session_main"
|
||||
|
||||
|
||||
@router.get("/state")
|
||||
def api_get_context_state(session_id: str = "web_session_main", current_user = Depends(get_current_user)):
|
||||
state = db_get_session_state(session_id) or {}
|
||||
history = db_get_chat_history(session_id, limit=50)
|
||||
|
||||
ephemeral_count = sum(1 for m in history if dict(m).get("is_ephemeral") == 1)
|
||||
total_messages = len(history)
|
||||
|
||||
return {
|
||||
"session_id": session_id,
|
||||
"active_state": state.get("state_type", "IDLE"),
|
||||
"state_data": state.get("data_json", {}),
|
||||
"total_messages": total_messages,
|
||||
"ephemeral_messages": ephemeral_count
|
||||
}
|
||||
|
||||
|
||||
@router.post("/purge-ephemeral")
|
||||
def api_purge_ephemeral(req: SessionActionRequest, current_user = Depends(get_current_user)):
|
||||
purged = db_purge_ephemeral_messages(req.session_id)
|
||||
return {"status": "success", "purged_count": purged}
|
||||
|
||||
|
||||
@router.post("/clear-all")
|
||||
def api_clear_all_context(req: SessionActionRequest, current_user = Depends(get_current_user)):
|
||||
db_clear_session_state(req.session_id)
|
||||
db_clear_chat_history(req.session_id)
|
||||
return {"status": "success", "message": "Контекст сессии полностью очищен"}
|
||||
@@ -0,0 +1,157 @@
|
||||
"""
|
||||
===============================================================================
|
||||
FILE: modules/web_api/routers/remote_workers.py
|
||||
ROLE: REST API реестра удаленщиков (CRUD, редактирование сроков, автоочистка).
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
import pandas as pd
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional, List, Dict, Any
|
||||
|
||||
from routers.auth import get_current_user
|
||||
from config import BASE_DIR, DATA_DIR
|
||||
|
||||
router = APIRouter(prefix="/api/v1/remote-workers", tags=["RemoteWorkers"])
|
||||
CSV_PATH = os.path.join(DATA_DIR, "static_reason_workers.csv")
|
||||
|
||||
|
||||
def _load_workers() -> List[Dict[str, Any]]:
|
||||
"""Читает CSV, гарантирует структуру колонок и удаляет просроченные записи."""
|
||||
if not os.path.exists(CSV_PATH):
|
||||
return []
|
||||
try:
|
||||
df = pd.read_csv(CSV_PATH, dtype=str, on_bad_lines='skip').fillna("")
|
||||
for col in ["fio", "department", "reason", "date_from", "date_to"]:
|
||||
if col not in df.columns:
|
||||
df[col] = ""
|
||||
|
||||
today_date = datetime.now().date()
|
||||
valid_workers = []
|
||||
has_expired = False
|
||||
|
||||
for row in df.to_dict(orient="records"):
|
||||
fio = str(row.get("fio", "")).strip()
|
||||
if not fio:
|
||||
continue
|
||||
|
||||
d_to_str = str(row.get("date_to", "")).strip()
|
||||
if d_to_str and d_to_str.lower() not in ["nan", "none", ""]:
|
||||
try:
|
||||
d_to = datetime.strptime(d_to_str.replace('_', '.'), "%d.%m.%Y").date()
|
||||
# Если срок завершился вчера или ранее — запись удаляется из файла
|
||||
if today_date > d_to:
|
||||
has_expired = True
|
||||
continue
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
valid_workers.append(row)
|
||||
|
||||
# Синхронная перезапись файла при обнаружении истекших сроков
|
||||
if has_expired:
|
||||
_save_workers(valid_workers)
|
||||
|
||||
return valid_workers
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def _save_workers(workers: List[Dict[str, Any]]):
|
||||
"""Сохраняет актуальный список в CSV с сохранением колонок."""
|
||||
df = pd.DataFrame(workers)
|
||||
for col in ["fio", "department", "reason", "date_from", "date_to"]:
|
||||
if col not in df.columns:
|
||||
df[col] = ""
|
||||
os.makedirs(os.path.dirname(CSV_PATH), exist_ok=True)
|
||||
df.to_csv(CSV_PATH, index=False, encoding="utf-8")
|
||||
|
||||
|
||||
class RemoteWorkerItem(BaseModel):
|
||||
fio: str
|
||||
department: Optional[str] = "Все"
|
||||
reason: Optional[str] = "Удаленная работа"
|
||||
date_from: Optional[str] = ""
|
||||
date_to: Optional[str] = ""
|
||||
|
||||
|
||||
class UpdateDatesRequest(BaseModel):
|
||||
fio: str
|
||||
date_from: Optional[str] = ""
|
||||
date_to: Optional[str] = ""
|
||||
|
||||
|
||||
@router.get("")
|
||||
def api_get_remote_workers(current_user = Depends(get_current_user)):
|
||||
return {"workers": _load_workers()}
|
||||
|
||||
|
||||
@router.post("")
|
||||
def api_add_remote_worker(item: RemoteWorkerItem, current_user = Depends(get_current_user)):
|
||||
workers = _load_workers()
|
||||
fio_clean = item.fio.strip()
|
||||
if not fio_clean:
|
||||
raise HTTPException(status_code=400, detail="ФИО не может быть пустым")
|
||||
|
||||
# Если начало не указано — берем сегодня
|
||||
today_str = datetime.now().strftime("%d.%m.%Y")
|
||||
date_from = item.date_from.strip() if item.date_from and item.date_from.strip() else today_str
|
||||
date_to = item.date_to.strip() if item.date_to else ""
|
||||
|
||||
# Проверка на совпадение ФИО (обновление существующей записи)
|
||||
for w in workers:
|
||||
if str(w.get("fio", "")).strip().lower() == fio_clean.lower():
|
||||
w["department"] = item.department.strip() if item.department else (w.get("department") or "Все")
|
||||
w["reason"] = item.reason.strip() if item.reason else (w.get("reason") or "Удаленная работа")
|
||||
w["date_from"] = date_from
|
||||
w["date_to"] = date_to
|
||||
_save_workers(workers)
|
||||
return {"status": "success", "message": "Срок удаленки обновлен", "workers": workers}
|
||||
|
||||
workers.append({
|
||||
"fio": fio_clean,
|
||||
"department": item.department.strip() if item.department else "Все",
|
||||
"reason": item.reason.strip() if item.reason else "Удаленная работа",
|
||||
"date_from": date_from,
|
||||
"date_to": date_to
|
||||
})
|
||||
_save_workers(workers)
|
||||
return {"status": "success", "workers": workers}
|
||||
|
||||
|
||||
@router.put("")
|
||||
def api_update_worker_dates(req: UpdateDatesRequest, current_user = Depends(get_current_user)):
|
||||
"""Редактирование срока удаленки (продление или сокращение)."""
|
||||
workers = _load_workers()
|
||||
target_fio = req.fio.strip().lower()
|
||||
found = False
|
||||
|
||||
for w in workers:
|
||||
if str(w.get("fio", "")).strip().lower() == target_fio:
|
||||
w["date_from"] = req.date_from.strip() if req.date_from is not None else w.get("date_from", "")
|
||||
w["date_to"] = req.date_to.strip() if req.date_to is not None else w.get("date_to", "")
|
||||
found = True
|
||||
break
|
||||
|
||||
if not found:
|
||||
raise HTTPException(status_code=404, detail="Сотрудник не найден в списке")
|
||||
|
||||
_save_workers(workers)
|
||||
return {"status": "success", "message": "Сроки успешно изменены", "workers": workers}
|
||||
|
||||
|
||||
@router.delete("")
|
||||
def api_delete_remote_worker(fio: str, current_user = Depends(get_current_user)):
|
||||
workers = _load_workers()
|
||||
fio_clean = fio.strip().lower()
|
||||
initial_len = len(workers)
|
||||
workers = [w for w in workers if str(w.get("fio", "")).strip().lower() != fio_clean]
|
||||
|
||||
if len(workers) == initial_len:
|
||||
raise HTTPException(status_code=404, detail="Сотрудник не найден")
|
||||
|
||||
_save_workers(workers)
|
||||
return {"status": "success", "workers": workers}
|
||||
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
===============================================================================
|
||||
FILE: modules/web_api/routers/snapshots.py
|
||||
ROLE: REST API эндпоинты для управления и моментального создания срезов СКУД.
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional, List, Dict, Any
|
||||
|
||||
from routers.auth import get_current_user
|
||||
from services.snapshots.service import get_snapshots_registry, delete_snapshots_safely
|
||||
from services.scud_export import run_export
|
||||
|
||||
router = APIRouter(prefix="/api/v1/snapshots", tags=["Snapshots"])
|
||||
|
||||
|
||||
class CreateSnapshotRequest(BaseModel):
|
||||
date_str: Optional[str] = None
|
||||
|
||||
|
||||
class DeleteSnapshotsRequest(BaseModel):
|
||||
snapshot_ids: List[str]
|
||||
|
||||
|
||||
@router.get("")
|
||||
def api_get_snapshots(date_str: Optional[str] = None, current_user = Depends(get_current_user)):
|
||||
return get_snapshots_registry(date_str=date_str)
|
||||
|
||||
|
||||
@router.post("/create")
|
||||
def api_create_instant_snapshot(req: CreateSnapshotRequest, current_user = Depends(get_current_user)):
|
||||
"""Моментальный опрос MS SQL СКУД и запись свежего среза в SQLite."""
|
||||
try:
|
||||
success = run_export(input_date=req.date_str, save_xlsx=True, debug=False)
|
||||
if not success:
|
||||
raise HTTPException(status_code=500, detail="Ошибка при обращении к MS SQL Орион")
|
||||
|
||||
fresh_data = get_snapshots_registry(date_str=req.date_str)
|
||||
return {"status": "success", "message": "Срез успешно создан", "data": fresh_data}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Ошибка создания среза: {str(e)}")
|
||||
|
||||
|
||||
@router.delete("")
|
||||
def api_delete_snapshots(req: DeleteSnapshotsRequest, current_user = Depends(get_current_user)):
|
||||
safe_ids = [s for s in req.snapshot_ids if not str(s).startswith("Y")]
|
||||
if not safe_ids:
|
||||
raise HTTPException(status_code=400, detail="Итоговый Y-срез защищен от удаления")
|
||||
|
||||
res = delete_snapshots_safely(snapshot_ids=safe_ids)
|
||||
return {"status": "success", "deleted_count": res.get("deleted_count", len(safe_ids))}
|
||||
+574
-134
@@ -1,165 +1,605 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<html lang="ru" class="h-full bg-slate-100">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>SCUD Orion AI — Управление и Аналитика</title>
|
||||
<!-- Tailwind CSS CDN -->
|
||||
<title>SCUD Orion AI Assistant</title>
|
||||
<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="/css/styles.css">
|
||||
<link rel="icon" href="/favicon.ico" type="image/x-icon">
|
||||
<style>
|
||||
|
||||
/* Запрещаем браузеру насильно удерживать скролл внизу при появлении ответа */
|
||||
* {
|
||||
overflow-anchor: none !important;
|
||||
}
|
||||
|
||||
#chat-messages-container, main {
|
||||
overflow-anchor: none !important;
|
||||
}
|
||||
|
||||
/* ⭐️ Воздух снизу для возможности поднятия вопроса на самый верх */
|
||||
#chat-messages-container {
|
||||
/*
|
||||
clamp(минимальный отступ, желаемый адаптивный, максимальный предел)
|
||||
Это гарантирует, что на огромных экранах отступ не раздуется до бесконечности,
|
||||
а на маленьких — не сожмет ленту в ноль.
|
||||
*/
|
||||
padding-bottom: clamp(400px, 85vh, 900px) !important;
|
||||
}
|
||||
|
||||
/* Принудительное увеличение шрифта сообщений чата */
|
||||
#chat-messages-container .message-content,
|
||||
#chat-messages-container .text-xs,
|
||||
#chat-messages-container .text-sm {
|
||||
font-size: 14.5px !important;
|
||||
line-height: 1.6 !important;
|
||||
}
|
||||
#chat-messages-container pre,
|
||||
#chat-messages-container code {
|
||||
font-size: 13.5px !important;
|
||||
}
|
||||
/* Смещение для точной прокрутки под фиксированный заголовок */
|
||||
.user-chat-bubble {
|
||||
scroll-margin-top: 24px !important;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="bg-slate-100 font-sans h-screen flex overflow-hidden text-slate-800">
|
||||
<body class="h-full flex flex-col font-sans antialiased text-slate-800 bg-slate-100 selection:bg-indigo-500 selection:text-white">
|
||||
|
||||
<!-- Боковая панель (Задачи и Навигация) -->
|
||||
<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">
|
||||
<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 id="app-container" class="flex-1 flex overflow-hidden w-full h-full">
|
||||
|
||||
<!-- ЛЕВАЯ КОЛОНКА (ДИНАМИЧЕСКИЙ САЙДБАР 5-ХАБОВ) -->
|
||||
<aside class="w-80 md:w-96 bg-white border-r border-slate-200 flex flex-col shrink-0 h-full shadow-sm z-10 select-none">
|
||||
|
||||
<!-- ДИНАМИЧЕСКИЙ ТАБ-БАР ХАБОВ И ПОДВКЛАДОК -->
|
||||
<div id="sidebar-dynamic-header" class="shrink-0 bg-slate-50 border-b border-slate-200"></div>
|
||||
|
||||
<!-- ДИНАМИЧЕСКИЙ КОНТЕНТНЫЙ СЛОТ -->
|
||||
<div id="sidebar-dynamic-content" class="flex-1 overflow-y-auto p-2 flex flex-col gap-2">
|
||||
<div id="tasks-list-container" class="flex-1 flex flex-col gap-2">
|
||||
<div class="text-center py-10 text-xs text-slate-400">
|
||||
<i class="fa-solid fa-spinner fa-spin mr-1"></i> Загрузка...
|
||||
</div>
|
||||
</div>
|
||||
</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 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 class="p-3 border-t border-slate-200 bg-slate-50 flex items-center justify-between shrink-0">
|
||||
<div class="flex items-center gap-2.5 min-w-0">
|
||||
<div class="w-8 h-8 rounded-full bg-indigo-600 text-white flex items-center justify-center font-bold text-xs shadow-sm shrink-0">
|
||||
<i class="fa-solid fa-user"></i>
|
||||
</div>
|
||||
<div class="min-w-0 flex flex-col">
|
||||
<span id="user-display-name" class="text-xs font-bold text-slate-800 truncate">Пользователь</span>
|
||||
<span id="user-display-role" class="text-[10px] text-slate-400">Оператор</span>
|
||||
</div>
|
||||
</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>
|
||||
<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>
|
||||
|
||||
<!-- Основная рабочая область чата -->
|
||||
<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 class="flex items-center gap-1">
|
||||
<button id="admin-panel-btn" type="button" onclick="openAdminModal()" class="hidden p-1.5 text-slate-400 hover:text-indigo-600 hover:bg-slate-200 rounded-lg transition" title="Управление пользователями">
|
||||
<i class="fa-solid fa-users-gear text-sm"></i>
|
||||
</button>
|
||||
|
||||
<button type="button" onclick="openProfileModal()" class="p-1.5 text-slate-400 hover:text-slate-700 hover:bg-slate-200 rounded-lg transition" title="Сменить пароль">
|
||||
<i class="fa-solid fa-gear text-sm"></i>
|
||||
</button>
|
||||
|
||||
<button type="button" onclick="AuthManager.logout()" class="p-1.5 text-slate-400 hover:text-rose-600 hover:bg-rose-50 rounded-lg transition" title="Выйти из системы">
|
||||
<i class="fa-solid fa-arrow-right-from-bracket text-sm"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- ПРАВАЯ ОБЛАСТЬ (ЧАТ И ИИ-АССИСТЕНТ) -->
|
||||
<main class="flex-1 flex flex-col h-full min-w-0 bg-slate-50 relative">
|
||||
<header class="h-14 bg-white border-b border-slate-200 px-4 flex items-center justify-between shrink-0 shadow-sm z-10">
|
||||
<div class="flex items-center gap-2.5">
|
||||
<div class="w-7 h-7 rounded-lg bg-indigo-600 text-white flex items-center justify-center shadow-sm">
|
||||
<i class="fa-solid fa-robot text-xs"></i>
|
||||
</div>
|
||||
<div>
|
||||
<div class="flex items-center gap-2">
|
||||
<h1 class="text-sm font-bold text-slate-800">SCUD Orion AI Assistant</h1>
|
||||
<span class="inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200">Online</span>
|
||||
</div>
|
||||
<p class="text-[10px] text-slate-400">Система интеллектуального аудита и контроля СКУД / 1С</p>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Невидимая распорка в самом низу для свободного скролла любого вопроса наверх -->
|
||||
<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 id="chat-messages-container" class="flex-1 overflow-y-auto p-4 md:p-6 flex flex-col gap-4">
|
||||
<div class="flex gap-3 max-w-4xl mx-auto w-full">
|
||||
<div class="w-7 h-7 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm mt-0.5">
|
||||
<i class="fa-solid fa-robot text-xs"></i>
|
||||
</div>
|
||||
<button type="button" onclick="clearAttachedFile()" class="text-slate-400 hover:text-rose-600 transition p-1">
|
||||
<div class="flex-1 bg-white border border-slate-200 rounded-2xl rounded-tl-none p-4 shadow-sm">
|
||||
<div class="text-[10px] font-bold text-indigo-600 uppercase tracking-wider mb-1">ИИ-ассистент SCUD Orion AI</div>
|
||||
<div class="text-xs text-slate-700 leading-relaxed">
|
||||
Привет! Вы можете задавать вопросы ассистенту, управлять системным промптом, сверять кадровые нестыковки СКУД и 1С или формировать срезы и отчеты.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- БЕЙДЖ ПРИКРЕПЛЕННОГО ФАЙЛА -->
|
||||
<div id="file-attachment-preview" class="hidden max-w-4xl mx-auto w-full px-4 pt-2">
|
||||
<div class="inline-flex items-center gap-2 px-3 py-1 bg-indigo-50 border border-indigo-200 rounded-xl text-xs text-indigo-700 shadow-sm">
|
||||
<i class="fa-solid fa-file text-indigo-600"></i>
|
||||
<span id="file-attachment-name" class="font-medium truncate max-w-xs"></span>
|
||||
<button type="button" onclick="clearAttachedFile()" class="text-indigo-400 hover:text-rose-600 ml-1">
|
||||
<i class="fa-solid fa-xmark"></i>
|
||||
</button>
|
||||
</div>
|
||||
</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>
|
||||
<!-- Контейнер строки ввода сообщения -->
|
||||
<div class="px-4 py-2 bg-white border-t border-slate-200">
|
||||
<div id="chat-input-box" class="max-w-4xl mx-auto w-full flex items-center gap-2 bg-slate-50 border border-slate-300 rounded-xl px-2.5 py-1 transition focus-within:border-indigo-500 focus-within:bg-white focus-within:ring-1 focus-within:ring-indigo-100">
|
||||
<!-- Скрепка файлов -->
|
||||
<button type="button" onclick="document.getElementById('file-upload-input').click()" class="text-slate-400 hover:text-indigo-600 p-1 transition shrink-0">
|
||||
<i class="fa-solid fa-paperclip text-xs"></i>
|
||||
</button>
|
||||
<input type="file" id="file-upload-input" class="hidden" />
|
||||
|
||||
<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>
|
||||
<!-- Поле ввода -->
|
||||
<textarea id="user-input" rows="1" placeholder="Команда, вопрос (Enter - отправить, Shift+Enter - перенос строки)..."
|
||||
class="flex-1 bg-transparent border-0 focus:outline-none text-xs text-slate-800 resize-none py-0 leading-5" style="height: 24px; line-height: 24px;"></textarea>
|
||||
|
||||
<!-- Кнопка отправки -->
|
||||
<button type="button" onclick="window.sendMessage()" class="w-6 h-6 rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white flex items-center justify-center shrink-0 shadow-sm transition">
|
||||
<i class="fa-solid fa-paper-plane text-[10px]"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- МОДАЛЬНОЕ ОКНО: УДАЛЕННЫЙ СОТРУДНИК -->
|
||||
<div id="remote-worker-modal" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-4 hidden">
|
||||
<div class="bg-white rounded-2xl shadow-2xl border border-slate-200 max-w-md w-full p-6 flex flex-col gap-4">
|
||||
<div class="flex items-center justify-between">
|
||||
<h3 id="remote-modal-title" class="text-sm font-bold text-slate-800 flex items-center gap-2">
|
||||
<i class="fa-solid fa-house-laptop text-emerald-600"></i>
|
||||
<span>Параметры удаленной работы</span>
|
||||
</h3>
|
||||
<button type="button" onclick="closeRemoteWorkerModal()" class="text-slate-400 hover:text-slate-600">
|
||||
<i class="fa-solid fa-xmark"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form id="remote-worker-form" onsubmit="handleRemoteWorkerSubmit(event)" class="flex flex-col gap-3">
|
||||
<input type="hidden" id="rw-mode" value="ADD" />
|
||||
|
||||
<div>
|
||||
<label class="block text-[11px] font-bold text-slate-600 mb-1">ФИО сотрудника:</label>
|
||||
<input type="text" id="rw-fio" required placeholder="Например: Иванов Иван Иванович"
|
||||
class="w-full text-xs px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:border-emerald-500 bg-slate-50" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-[11px] font-bold text-slate-600 mb-1">Подразделение:</label>
|
||||
<input type="text" id="rw-dept" placeholder="Все"
|
||||
class="w-full text-xs px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:border-emerald-500 bg-slate-50" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label class="block text-[11px] font-bold text-slate-600 mb-1">Дата начала:</label>
|
||||
<input type="date" id="rw-date-from"
|
||||
class="w-full text-xs px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:border-emerald-500 bg-slate-50 text-slate-700" />
|
||||
<span class="text-[10px] text-slate-400 mt-0.5 block">Пусто = с сегодняшнего дня</span>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-[11px] font-bold text-slate-600 mb-1">Дата окончания:</label>
|
||||
<input type="date" id="rw-date-to"
|
||||
class="w-full text-xs px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:border-emerald-500 bg-slate-50 text-slate-700" />
|
||||
<span class="text-[10px] text-slate-400 mt-0.5 block">Пусто = бессрочно</span>
|
||||
</div>
|
||||
</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>
|
||||
<div id="rw-error" class="text-[11px] font-semibold text-rose-600 hidden"></div>
|
||||
|
||||
<div class="flex items-center justify-end gap-2 mt-2 pt-2 border-t border-slate-100">
|
||||
<button type="button" onclick="closeRemoteWorkerModal()"
|
||||
class="px-3.5 py-1.5 text-xs text-slate-600 rounded-lg hover:bg-slate-100 font-medium transition">
|
||||
Отмена
|
||||
</button>
|
||||
</form>
|
||||
<button type="submit" id="rw-submit-btn"
|
||||
class="px-4 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-bold shadow transition">
|
||||
Сохранить
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- МОДАЛЬНОЕ ОКНО АВТОРИЗАЦИИ -->
|
||||
<div id="auth-modal" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-4 hidden">
|
||||
<div class="bg-white rounded-2xl shadow-2xl border border-slate-200 max-w-sm w-full p-6 flex flex-col gap-4">
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="w-10 h-10 rounded-xl bg-indigo-600 text-white flex items-center justify-center font-bold text-lg shadow">
|
||||
<i class="fa-solid fa-shield-halved"></i>
|
||||
</div>
|
||||
<div>
|
||||
<h2 class="text-sm font-bold text-slate-800">Авторизация в системе</h2>
|
||||
<p class="text-[11px] text-slate-400">SCUD Orion AI Security Access</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form id="auth-form" onsubmit="handleLoginSubmit(event)" class="flex flex-col gap-3">
|
||||
<div>
|
||||
<label class="block text-[11px] font-bold text-slate-600 mb-1">Имя пользователя:</label>
|
||||
<input type="text" id="auth-username" required class="w-full text-xs px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:border-indigo-500 bg-slate-50" placeholder="Логин" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-[11px] font-bold text-slate-600 mb-1">Пароль:</label>
|
||||
<input type="password" id="auth-password" required class="w-full text-xs px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:border-indigo-500 bg-slate-50" placeholder="••••••••" />
|
||||
</div>
|
||||
<div id="auth-error" class="text-[11px] font-semibold text-rose-600 hidden"></div>
|
||||
<button type="submit" class="w-full py-2 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-lg text-xs shadow transition mt-1">
|
||||
Войти в систему
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- МОДАЛЬНОЕ ОКНО СМЕНЫ ПАРОЛЯ -->
|
||||
<div id="profile-modal" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-4 hidden">
|
||||
<div class="bg-white rounded-2xl shadow-2xl border border-slate-200 max-w-sm w-full p-6 flex flex-col gap-4">
|
||||
<div class="flex items-center justify-between">
|
||||
<h3 class="text-sm font-bold text-slate-800 flex items-center gap-1.5">
|
||||
<i class="fa-solid fa-key text-indigo-600"></i> Смена пароля
|
||||
</h3>
|
||||
<button onclick="closeProfileModal()" class="text-slate-400 hover:text-slate-600"><i class="fa-solid fa-xmark"></i></button>
|
||||
</div>
|
||||
<form onsubmit="handleChangePassword(event)" class="flex flex-col gap-3">
|
||||
<div>
|
||||
<label class="block text-[11px] font-bold text-slate-600 mb-1">Текущий пароль:</label>
|
||||
<input type="password" id="old-pass" required class="w-full text-xs px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:border-indigo-500" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-[11px] font-bold text-slate-600 mb-1">Новый пароль (мин. 4 симв.):</label>
|
||||
<input type="password" id="new-pass" required class="w-full text-xs px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:border-indigo-500" />
|
||||
</div>
|
||||
<div id="pass-error" class="text-[11px] font-semibold text-rose-600 hidden"></div>
|
||||
<div class="flex items-center justify-end gap-2 mt-2">
|
||||
<button type="button" onclick="closeProfileModal()" class="px-3 py-1.5 text-xs text-slate-600 rounded-lg hover:bg-slate-100 font-medium">Отмена</button>
|
||||
<button type="submit" class="px-4 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-bold shadow transition">Сохранить</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- МОДАЛЬНОЕ ОКНО ПАНЕЛИ АДМИНИСТРАТОРА -->
|
||||
<div id="admin-modal" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-4 hidden">
|
||||
<div class="bg-white rounded-2xl shadow-2xl border border-slate-200 max-w-lg w-full p-6 flex flex-col gap-4 max-h-[85vh]">
|
||||
<div class="flex items-center justify-between">
|
||||
<h3 class="text-sm font-bold text-slate-800 flex items-center gap-1.5">
|
||||
<i class="fa-solid fa-users-gear text-indigo-600"></i> Управление учетными записями
|
||||
</h3>
|
||||
<button onclick="closeAdminModal()" class="text-slate-400 hover:text-slate-600"><i class="fa-solid fa-xmark"></i></button>
|
||||
</div>
|
||||
|
||||
<form onsubmit="handleCreateUser(event)" class="p-3 bg-slate-50 border border-slate-200 rounded-xl flex flex-col gap-2">
|
||||
<span class="text-xs font-bold text-slate-700">Создать нового пользователя:</span>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<input type="text" id="new-user-username" placeholder="Логин" required class="text-xs px-2.5 py-1.5 border border-slate-300 rounded-lg bg-white" />
|
||||
<input type="password" id="new-user-password" placeholder="Пароль" required class="text-xs px-2.5 py-1.5 border border-slate-300 rounded-lg bg-white" />
|
||||
</div>
|
||||
<input type="text" id="new-user-fullname" placeholder="ФИО" class="text-xs px-2.5 py-1.5 border border-slate-300 rounded-lg bg-white" />
|
||||
<div class="flex items-center justify-between">
|
||||
<label class="flex items-center gap-1.5 text-xs text-slate-600 cursor-pointer">
|
||||
<input type="checkbox" id="new-user-admin" class="rounded border-slate-300 text-indigo-600" />
|
||||
<span>Права администратора</span>
|
||||
</label>
|
||||
<button type="submit" class="px-3 py-1 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-bold shadow">
|
||||
Создать
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="flex-1 overflow-y-auto flex flex-col gap-1.5" id="admin-users-list">
|
||||
<div class="text-center py-4 text-xs text-slate-400">Загрузка пользователей...</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- Скрипты клиентской логики -->
|
||||
<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>
|
||||
<!-- ПОДКЛЮЧЕНИЕ СКРИПТОВ (Версия v=2.5.6) -->
|
||||
<script src="/static/js/auth.js?v=2.5.6"></script>
|
||||
<script src="/static/js/tasks.js?v=2.5.6"></script>
|
||||
<script src="/static/js/sidebar.js?v=2.5.6"></script>
|
||||
<script src="/static/js/chat/task_widget.js?v=2.5.6"></script>
|
||||
<script src="/static/js/chat/core.js?v=2.5.6"></script>
|
||||
<script src="/static/js/app.js?v=2.5.6"></script>
|
||||
|
||||
<script>
|
||||
function showAuthModal() {
|
||||
const modal = document.getElementById("auth-modal");
|
||||
if (modal) modal.classList.remove("hidden");
|
||||
}
|
||||
|
||||
function hideAuthModal() {
|
||||
const modal = document.getElementById("auth-modal");
|
||||
if (modal) modal.classList.add("hidden");
|
||||
}
|
||||
|
||||
function updateUIState() {
|
||||
const nameEl = document.getElementById("user-display-name");
|
||||
const roleEl = document.getElementById("user-display-role");
|
||||
const adminBtn = document.getElementById("admin-panel-btn");
|
||||
|
||||
if (nameEl) nameEl.innerText = AuthManager.getFullName();
|
||||
if (roleEl) roleEl.innerText = AuthManager.isAdmin() ? "Администратор" : "Оператор";
|
||||
|
||||
if (adminBtn) {
|
||||
if (AuthManager.isAdmin()) {
|
||||
adminBtn.classList.remove("hidden");
|
||||
} else {
|
||||
adminBtn.classList.add("hidden");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLoginSubmit(e) {
|
||||
e.preventDefault();
|
||||
const uInput = document.getElementById("auth-username");
|
||||
const pInput = document.getElementById("auth-password");
|
||||
const errEl = document.getElementById("auth-error");
|
||||
errEl.classList.add("hidden");
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/v1/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
username: uInput.value.trim(),
|
||||
password: pInput.value
|
||||
})
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
AuthManager.setSession(data.token, data.username, data.full_name, data.is_admin, data.user_id);
|
||||
hideAuthModal();
|
||||
updateUIState();
|
||||
if (window.SidebarManager) SidebarManager.setHub('TASKS');
|
||||
} else {
|
||||
const err = await res.json();
|
||||
errEl.innerText = err.detail || "Неверный логин или пароль";
|
||||
errEl.classList.remove("hidden");
|
||||
}
|
||||
} catch (err) {
|
||||
errEl.innerText = "Ошибка соединения с сервером";
|
||||
errEl.classList.remove("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
function openProfileModal() {
|
||||
document.getElementById("profile-modal").classList.remove("hidden");
|
||||
}
|
||||
function closeProfileModal() {
|
||||
document.getElementById("profile-modal").classList.add("hidden");
|
||||
}
|
||||
async function handleChangePassword(e) {
|
||||
e.preventDefault();
|
||||
const oldP = document.getElementById("old-pass").value;
|
||||
const newP = document.getElementById("new-pass").value;
|
||||
const errEl = document.getElementById("pass-error");
|
||||
errEl.classList.add("hidden");
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/v1/auth/change-password", {
|
||||
method: "POST",
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({ old_password: oldP, new_password: newP })
|
||||
});
|
||||
if (res.ok) {
|
||||
alert("Пароль успешно изменен");
|
||||
closeProfileModal();
|
||||
} else {
|
||||
const err = await res.json();
|
||||
errEl.innerText = err.detail || "Ошибка изменения пароля";
|
||||
errEl.classList.remove("hidden");
|
||||
}
|
||||
} catch (e) {
|
||||
errEl.innerText = "Ошибка сети";
|
||||
errEl.classList.remove("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
function openAdminModal() {
|
||||
document.getElementById("admin-modal").classList.remove("hidden");
|
||||
loadAdminUsers();
|
||||
}
|
||||
function closeAdminModal() {
|
||||
document.getElementById("admin-modal").classList.add("hidden");
|
||||
}
|
||||
async function loadAdminUsers() {
|
||||
const listEl = document.getElementById("admin-users-list");
|
||||
listEl.innerHTML = `<div class="text-center py-4 text-xs text-slate-400"><i class="fa-solid fa-spinner fa-spin mr-1"></i> Загрузка...</div>`;
|
||||
try {
|
||||
const res = await fetch("/api/v1/admin/users", { headers: AuthManager.getAuthHeaders() });
|
||||
if (res.ok) {
|
||||
const users = await res.json();
|
||||
listEl.innerHTML = users.map(u => `
|
||||
<div class="flex items-center justify-between p-2.5 bg-slate-50 border border-slate-200 rounded-xl text-xs">
|
||||
<div>
|
||||
<div class="font-bold text-slate-800">${escapeHtml(u.full_name || u.username)} <span class="text-slate-400 font-mono text-[10px]">(${escapeHtml(u.username)})</span></div>
|
||||
<div class="text-[10px] ${u.is_admin ? 'text-indigo-600 font-bold' : 'text-slate-400'}">${u.is_admin ? 'Администратор' : 'Оператор'}</div>
|
||||
</div>
|
||||
<button onclick="deleteAdminUser(${u.id}, '${escapeHtml(u.username)}')" class="text-slate-400 hover:text-rose-600 p-1.5" title="Удалить">
|
||||
<i class="fa-solid fa-trash-can"></i>
|
||||
</button>
|
||||
</div>
|
||||
`).join('');
|
||||
} else {
|
||||
listEl.innerHTML = `<div class="text-center py-4 text-xs text-rose-500">Ошибка загрузки пользователей</div>`;
|
||||
}
|
||||
} catch (e) {
|
||||
listEl.innerHTML = `<div class="text-center py-4 text-xs text-rose-500">Ошибка сети</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreateUser(e) {
|
||||
e.preventDefault();
|
||||
const u = document.getElementById("new-user-username").value;
|
||||
const p = document.getElementById("new-user-password").value;
|
||||
const f = document.getElementById("new-user-fullname").value;
|
||||
const a = document.getElementById("new-user-admin").checked;
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/v1/admin/users", {
|
||||
method: "POST",
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({ username: u, password: p, full_name: f, is_admin: a })
|
||||
});
|
||||
if (res.ok) {
|
||||
document.getElementById("new-user-username").value = "";
|
||||
document.getElementById("new-user-password").value = "";
|
||||
document.getElementById("new-user-fullname").value = "";
|
||||
document.getElementById("new-user-admin").checked = false;
|
||||
loadAdminUsers();
|
||||
} else {
|
||||
const err = await res.json();
|
||||
alert(err.detail || "Ошибка создания пользователя");
|
||||
}
|
||||
} catch (e) {
|
||||
alert("Ошибка сети");
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteAdminUser(id, username) {
|
||||
if (!confirm(`Удалить пользователя ${username}?`)) return;
|
||||
try {
|
||||
const res = await fetch(`/api/v1/admin/users/${id}`, {
|
||||
method: "DELETE",
|
||||
headers: AuthManager.getAuthHeaders()
|
||||
});
|
||||
if (res.ok) {
|
||||
loadAdminUsers();
|
||||
} else {
|
||||
const err = await res.json();
|
||||
alert(err.detail || "Ошибка удаления");
|
||||
}
|
||||
} catch (e) {
|
||||
alert("Ошибка сети");
|
||||
}
|
||||
}
|
||||
|
||||
function dmyToYmd(str) {
|
||||
if (!str) return "";
|
||||
const parts = str.replace(/_/g, '.').split('.');
|
||||
if (parts.length === 3) return `${parts[2]}-${parts[1].padStart(2, '0')}-${parts[0].padStart(2, '0')}`;
|
||||
return "";
|
||||
}
|
||||
|
||||
function ymdToDmy(str) {
|
||||
if (!str) return "";
|
||||
const parts = str.split('-');
|
||||
if (parts.length === 3) return `${parts[2]}.${parts[1]}.${parts[0]}`;
|
||||
return "";
|
||||
}
|
||||
|
||||
function openRemoteWorkerModal(mode = 'ADD', fio = '', dept = 'Все', dateFrom = '', dateTo = '') {
|
||||
const modal = document.getElementById("remote-worker-modal");
|
||||
const titleEl = document.getElementById("remote-modal-title");
|
||||
const modeInput = document.getElementById("rw-mode");
|
||||
const fioInput = document.getElementById("rw-fio");
|
||||
const deptInput = document.getElementById("rw-dept");
|
||||
const fromInput = document.getElementById("rw-date-from");
|
||||
const toInput = document.getElementById("rw-date-to");
|
||||
const errEl = document.getElementById("rw-error");
|
||||
|
||||
errEl.classList.add("hidden");
|
||||
modeInput.value = mode;
|
||||
|
||||
if (mode === 'EDIT') {
|
||||
titleEl.innerHTML = `<i class="fa-solid fa-pen-to-square text-emerald-600"></i><span>Изменение сроков удаленки</span>`;
|
||||
fioInput.value = fio;
|
||||
fioInput.readOnly = true;
|
||||
fioInput.classList.add("bg-slate-100", "text-slate-500", "cursor-not-allowed");
|
||||
deptInput.value = dept || "Все";
|
||||
deptInput.readOnly = true;
|
||||
deptInput.classList.add("bg-slate-100", "text-slate-500", "cursor-not-allowed");
|
||||
fromInput.value = dmyToYmd(dateFrom);
|
||||
toInput.value = dmyToYmd(dateTo);
|
||||
} else {
|
||||
titleEl.innerHTML = `<i class="fa-solid fa-house-laptop text-emerald-600"></i><span>Добавление удаленщика</span>`;
|
||||
fioInput.value = "";
|
||||
fioInput.readOnly = false;
|
||||
fioInput.classList.remove("bg-slate-100", "text-slate-500", "cursor-not-allowed");
|
||||
deptInput.value = "Все";
|
||||
deptInput.readOnly = false;
|
||||
deptInput.classList.remove("bg-slate-100", "text-slate-500", "cursor-not-allowed");
|
||||
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
fromInput.value = today;
|
||||
toInput.value = "";
|
||||
}
|
||||
|
||||
modal.classList.remove("hidden");
|
||||
}
|
||||
|
||||
function closeRemoteWorkerModal() {
|
||||
document.getElementById("remote-worker-modal").classList.add("hidden");
|
||||
}
|
||||
|
||||
async function handleRemoteWorkerSubmit(e) {
|
||||
e.preventDefault();
|
||||
const mode = document.getElementById("rw-mode").value;
|
||||
const fio = document.getElementById("rw-fio").value.trim();
|
||||
const dept = document.getElementById("rw-dept").value.trim() || "Все";
|
||||
const fromVal = ymdToDmy(document.getElementById("rw-date-from").value);
|
||||
const toVal = ymdToDmy(document.getElementById("rw-date-to").value);
|
||||
const errEl = document.getElementById("rw-error");
|
||||
errEl.classList.add("hidden");
|
||||
|
||||
const method = (mode === 'EDIT') ? "PUT" : "POST";
|
||||
const payload = (mode === 'EDIT')
|
||||
? { fio: fio, date_from: fromVal, date_to: toVal }
|
||||
: { fio: fio, department: dept, reason: "Удаленная работа", date_from: fromVal, date_to: toVal };
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/v1/remote-workers", {
|
||||
method: method,
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
closeRemoteWorkerModal();
|
||||
if (window.SidebarManager) SidebarManager.renderContent();
|
||||
} else {
|
||||
const err = await res.json();
|
||||
errEl.innerText = err.detail || "Ошибка сохранения";
|
||||
errEl.classList.remove("hidden");
|
||||
}
|
||||
} catch (err) {
|
||||
errEl.innerText = "Ошибка соединения с сервером";
|
||||
errEl.classList.remove("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
if (window.AuthManager && AuthManager.isAuthenticated()) {
|
||||
updateUIState();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- Глобальная Drag-and-Drop зона на весь экран -->
|
||||
<div id="global-drag-overlay"
|
||||
class="fixed inset-0 bg-indigo-900/40 backdrop-blur-xs z-50 hidden flex items-center justify-center pointer-events-none transition-all duration-200">
|
||||
<div class="bg-white border-2 border-dashed border-indigo-500 rounded-3xl p-10 flex flex-col items-center gap-3 shadow-2xl scale-100 transition-transform">
|
||||
<div class="w-16 h-16 rounded-2xl bg-indigo-50 text-indigo-600 flex items-center justify-center text-3xl shadow-inner">
|
||||
<i class="fa-solid fa-cloud-arrow-up animate-bounce"></i>
|
||||
</div>
|
||||
<div class="text-base font-bold text-slate-800">Перетащите файл в любую точку окна</div>
|
||||
<div class="text-xs text-slate-500 font-medium">PDF-документы, сканы, отчеты или изображения</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,62 +1,75 @@
|
||||
/**
|
||||
* ===============================================================================
|
||||
* FILE: static/js/auth.js
|
||||
* ROLE: Управление сессией пользователя, токенами и корректным выходом (Logout).
|
||||
* FILE: modules/web_api/static/js/auth.js
|
||||
* ROLE: Менеджер сессий, токенов, ФИО и авторизационных заголовков.
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
const AUTH_STORAGE_KEY = "scud_auth_token";
|
||||
const USERNAME_STORAGE_KEY = "scud_username";
|
||||
const FULLNAME_STORAGE_KEY = "scud_full_name";
|
||||
const IS_ADMIN_STORAGE_KEY = "scud_is_admin";
|
||||
const USER_ID_STORAGE_KEY = "scud_user_id";
|
||||
|
||||
const AuthManager = {
|
||||
getToken() {
|
||||
let token = localStorage.getItem("auth_token") || localStorage.getItem("token");
|
||||
if (!token) {
|
||||
// Если токена нет — инициализируем рабочий дефолтный токен
|
||||
token = "dev_token_1";
|
||||
localStorage.setItem("auth_token", token);
|
||||
localStorage.setItem("user_id", "1");
|
||||
}
|
||||
return token;
|
||||
return localStorage.getItem(AUTH_STORAGE_KEY) || "";
|
||||
},
|
||||
|
||||
getUserId() {
|
||||
return parseInt(localStorage.getItem("user_id") || "1", 10);
|
||||
const uid = localStorage.getItem(USER_ID_STORAGE_KEY);
|
||||
return uid ? parseInt(uid, 10) : 1;
|
||||
},
|
||||
|
||||
getUsername() {
|
||||
return localStorage.getItem(USERNAME_STORAGE_KEY) || "";
|
||||
},
|
||||
|
||||
getFullName() {
|
||||
return localStorage.getItem(FULLNAME_STORAGE_KEY) || this.getUsername() || "Пользователь";
|
||||
},
|
||||
|
||||
isAdmin() {
|
||||
return localStorage.getItem(IS_ADMIN_STORAGE_KEY) === "true";
|
||||
},
|
||||
|
||||
isAuthenticated() {
|
||||
return Boolean(this.getToken());
|
||||
},
|
||||
|
||||
setSession(token, username, fullName, isAdmin, userId = 1) {
|
||||
localStorage.setItem(AUTH_STORAGE_KEY, token);
|
||||
localStorage.setItem(USERNAME_STORAGE_KEY, username);
|
||||
localStorage.setItem(FULLNAME_STORAGE_KEY, fullName || username);
|
||||
localStorage.setItem(IS_ADMIN_STORAGE_KEY, String(isAdmin));
|
||||
localStorage.setItem(USER_ID_STORAGE_KEY, String(userId));
|
||||
localStorage.setItem("scud_api_auth_token", token);
|
||||
localStorage.setItem("auth_token", token);
|
||||
},
|
||||
|
||||
getAuthHeaders() {
|
||||
const token = this.getToken();
|
||||
const headers = { "Content-Type": "application/json" };
|
||||
if (token) {
|
||||
headers["Authorization"] = `Bearer ${token}`;
|
||||
}
|
||||
return headers;
|
||||
},
|
||||
|
||||
logout() {
|
||||
console.log("[Auth] Выполняется выход из учетной записи...");
|
||||
|
||||
// 1. Полная очистка хранилищ браузера
|
||||
localStorage.removeItem("auth_token");
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("user_id");
|
||||
console.log("[Auth] Полный выход из системы...");
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
|
||||
// 2. Сброс авторизационных cookies (если присутствуют)
|
||||
document.cookie.split(";").forEach((cookie) => {
|
||||
const eqPos = cookie.indexOf("=");
|
||||
const name = eqPos > -1 ? cookie.substr(0, eqPos).trim() : cookie.trim();
|
||||
document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;
|
||||
});
|
||||
|
||||
// 3. Перезагрузка страницы для сброса состояния интерфейса
|
||||
window.location.reload();
|
||||
},
|
||||
|
||||
init() {
|
||||
// Привязка клика ко всем элементам с классом или id logout
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const logoutBtns = document.querySelectorAll("#logout-btn, .logout-btn, [data-action='logout']");
|
||||
logoutBtns.forEach(btn => {
|
||||
btn.addEventListener("click", (e) => {
|
||||
e.preventDefault();
|
||||
AuthManager.logout();
|
||||
});
|
||||
});
|
||||
});
|
||||
window.location.href = "/";
|
||||
}
|
||||
};
|
||||
|
||||
// Инициализация при загрузке скрипта
|
||||
AuthManager.init();
|
||||
|
||||
// Глобальная доступность функции для onclick в HTML
|
||||
window.AuthManager = AuthManager;
|
||||
window.logout = () => AuthManager.logout();
|
||||
@@ -1,67 +1,586 @@
|
||||
/**
|
||||
* ===============================================================================
|
||||
* FILE: static/js/chat/core.js
|
||||
* ROLE: Отправка сообщений в API с токеном и обработка ошибок.
|
||||
* FILE: modules/web_api/static/js/chat/core.js
|
||||
* ROLE: Ядро чата: полноэкранный Drag-and-Drop оверлей, авто-высота инпута (24px),
|
||||
* надежный расчет скролла вопроса к верху окна, крупный шрифт text-sm.
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
async function sendMessage(userMessageText) {
|
||||
const chatInput = document.getElementById("chat-input");
|
||||
const message = userMessageText || (chatInput ? chatInput.value.trim() : "");
|
||||
if (!message) return;
|
||||
let currentAttachedFile = null;
|
||||
|
||||
if (chatInput && !userMessageText) {
|
||||
chatInput.value = "";
|
||||
const CHAT_INPUT_STORAGE_KEY = "scud_chat_input_history";
|
||||
let chatInputHistory = JSON.parse(localStorage.getItem(CHAT_INPUT_STORAGE_KEY) || "[]");
|
||||
let chatHistoryIndex = -1;
|
||||
let temporaryCurrentInput = "";
|
||||
|
||||
function saveCommandToHistory(commandText) {
|
||||
if (!commandText || !commandText.trim()) return;
|
||||
const cleanCmd = commandText.trim();
|
||||
if (cleanCmd.startsWith("action:save_draft_")) return;
|
||||
|
||||
chatInputHistory = chatInputHistory.filter(item => item !== cleanCmd);
|
||||
chatInputHistory.push(cleanCmd);
|
||||
if (chatInputHistory.length > 50) chatInputHistory.shift();
|
||||
localStorage.setItem(CHAT_INPUT_STORAGE_KEY, JSON.stringify(chatInputHistory));
|
||||
chatHistoryIndex = -1;
|
||||
}
|
||||
|
||||
// ⭐️ ЕДИНАЯ ФУНКЦИЯ СКРОЛЛА: плавное выравнивание вопроса к верхней границе
|
||||
function scrollToUserMessageTop() {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return;
|
||||
|
||||
const userBubbles = container.querySelectorAll(".user-chat-bubble");
|
||||
const targetEl = userBubbles[userBubbles.length - 1] || container.lastElementChild;
|
||||
if (!targetEl) return;
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
setTimeout(() => {
|
||||
const containerTop = container.getBoundingClientRect().top;
|
||||
const targetTop = targetEl.getBoundingClientRect().top;
|
||||
|
||||
const targetScroll = container.scrollTop + (targetTop - containerTop) - 16;
|
||||
|
||||
container.scrollTo({
|
||||
top: Math.max(0, targetScroll),
|
||||
behavior: 'smooth'
|
||||
});
|
||||
}, 50);
|
||||
});
|
||||
}
|
||||
|
||||
function updateInputHeightAndFade(textarea) {
|
||||
if (!textarea) return;
|
||||
|
||||
if (!textarea.value || textarea.value.trim() === '') {
|
||||
textarea.style.height = '24px';
|
||||
textarea.style.overflowY = 'hidden';
|
||||
textarea.style.maskImage = 'none';
|
||||
textarea.style.webkitMaskImage = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
// Отображаем сообщение пользователя в чате
|
||||
if (typeof appendMessageToUI === "function") {
|
||||
appendMessageToUI("user", message);
|
||||
textarea.style.height = 'auto';
|
||||
const minHeight = 24;
|
||||
const maxHeight = 120;
|
||||
const currentScrollHeight = textarea.scrollHeight;
|
||||
|
||||
if (currentScrollHeight <= minHeight + 2) {
|
||||
textarea.style.height = minHeight + 'px';
|
||||
textarea.style.overflowY = 'hidden';
|
||||
textarea.style.maskImage = 'none';
|
||||
textarea.style.webkitMaskImage = 'none';
|
||||
} else if (currentScrollHeight > maxHeight) {
|
||||
textarea.style.height = maxHeight + 'px';
|
||||
textarea.style.overflowY = 'auto';
|
||||
textarea.style.maskImage = 'linear-gradient(to bottom, transparent 0%, black 14px, black 100%)';
|
||||
textarea.style.webkitMaskImage = 'linear-gradient(to bottom, transparent 0%, black 14px, black 100%)';
|
||||
} else {
|
||||
textarea.style.height = currentScrollHeight + 'px';
|
||||
textarea.style.overflowY = 'hidden';
|
||||
textarea.style.maskImage = 'none';
|
||||
textarea.style.webkitMaskImage = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function appendUserMessage(text, filename = null) {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return;
|
||||
|
||||
const msgId = 'user-msg-' + Date.now();
|
||||
let fileBadge = '';
|
||||
if (filename) {
|
||||
fileBadge = `
|
||||
<div class="inline-flex items-center gap-1.5 px-2.5 py-1 mb-2 bg-indigo-700/80 rounded-lg text-xs font-semibold text-white shadow-xs">
|
||||
<i class="fa-solid fa-paperclip text-xs"></i>
|
||||
<span class="truncate max-w-xs">${escapeHtml(filename)}</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// Подготовка заголовков с гарантированным токеном
|
||||
const token = (typeof AuthManager !== "undefined") ? AuthManager.getToken() : (localStorage.getItem("auth_token") || "dev_token_1");
|
||||
const userId = (typeof AuthManager !== "undefined") ? AuthManager.getUserId() : parseInt(localStorage.getItem("user_id") || "1", 10);
|
||||
const sessionId = localStorage.getItem("chat_session_id") || "web_session_main";
|
||||
const msgHtml = `
|
||||
<div id="${msgId}" class="user-chat-bubble flex gap-3 max-w-4xl mx-auto w-full justify-end pt-3 scroll-mt-4">
|
||||
<div class="flex-1 max-w-2xl bg-indigo-600 text-white rounded-2xl rounded-tr-none p-4 shadow-sm">
|
||||
${fileBadge}
|
||||
<div class="text-sm leading-relaxed whitespace-pre-wrap">${escapeHtml(text)}</div>
|
||||
</div>
|
||||
<div class="w-8 h-8 rounded-lg bg-slate-200 text-slate-600 flex items-center justify-center shrink-0 shadow-sm mt-0.5 font-bold text-sm">
|
||||
<i class="fa-solid fa-user"></i>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
container.insertAdjacentHTML("beforeend", msgHtml);
|
||||
}
|
||||
|
||||
function appendAssistantLoading() {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return null;
|
||||
|
||||
const loadingId = 'loading-' + Date.now();
|
||||
const html = `
|
||||
<div id="${loadingId}" class="flex gap-3 max-w-4xl mx-auto w-full pt-1">
|
||||
<div class="w-8 h-8 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm mt-0.5">
|
||||
<i class="fa-solid fa-robot text-sm"></i>
|
||||
</div>
|
||||
<div class="flex-1 bg-white border border-slate-200 rounded-2xl rounded-tl-none p-4 shadow-sm">
|
||||
<div class="text-sm text-slate-500 flex items-center gap-2">
|
||||
<i class="fa-solid fa-spinner fa-spin text-indigo-600"></i>
|
||||
<span>ИИ обрабатывает запрос...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
container.insertAdjacentHTML("beforeend", html);
|
||||
return loadingId;
|
||||
}
|
||||
|
||||
function appendAssistantMessage(text, buttons = [], actionPayload = null) {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return;
|
||||
|
||||
let payloadHtml = '';
|
||||
let isHtmlBody = false;
|
||||
|
||||
if (actionPayload) {
|
||||
if (actionPayload.type === 'SNAPSHOTS_CARD' && typeof renderSnapshotsCard === 'function') {
|
||||
payloadHtml = renderSnapshotsCard(actionPayload.data);
|
||||
} else if (actionPayload.type === 'TASK_INTERACTIVE_CARD' && typeof renderInteractiveTaskCard === 'function') {
|
||||
payloadHtml = renderInteractiveTaskCard(actionPayload.tasks);
|
||||
} else if (actionPayload.type === 'FILE_DOWNLOAD_CARD') {
|
||||
const dlUrl = actionPayload.download_url || '#';
|
||||
const fName = actionPayload.filename || 'ROADMAP.md';
|
||||
const count = actionPayload.tasks_count || '';
|
||||
payloadHtml = `
|
||||
<div class="mt-3 p-3.5 bg-indigo-50/80 border border-indigo-200 rounded-xl flex items-center justify-between gap-3 shadow-sm">
|
||||
<div class="flex items-center gap-3 min-w-0">
|
||||
<div class="w-9 h-9 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm">
|
||||
<i class="fa-solid fa-file-lines text-base"></i>
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-bold text-slate-800 truncate">${escapeHtml(fName)}</div>
|
||||
<div class="text-xs text-slate-500">Задач выгружено: ${count} шт. · Markdown</div>
|
||||
</div>
|
||||
</div>
|
||||
<a href="${dlUrl}" download="${escapeHtml(fName)}" target="_blank"
|
||||
class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white rounded-lg text-xs font-bold shadow-sm transition flex items-center gap-1.5 shrink-0">
|
||||
<i class="fa-solid fa-download text-xs"></i>
|
||||
<span>Скачать файл</span>
|
||||
</a>
|
||||
</div>
|
||||
`;
|
||||
} else if (actionPayload.type === 'SNAPSHOT_INSPECT_CARD') {
|
||||
const records = actionPayload.records || [];
|
||||
const inspectTableId = 'inspect-table-' + Date.now();
|
||||
const searchInputId = 'inspect-search-' + Date.now();
|
||||
|
||||
const rowsHtml = records.map((r, idx) => `
|
||||
<tr class="inspect-row border-b border-slate-100 text-xs ${r.is_present ? 'bg-white' : 'bg-slate-50/60'} hover:bg-indigo-50/40"
|
||||
data-fio="${escapeHtml(r.fio).toLowerCase()}" data-dept="${escapeHtml(r.department).toLowerCase()}">
|
||||
<td class="p-2.5 text-slate-400 text-center font-mono w-10">${idx + 1}</td>
|
||||
<td class="p-2.5 font-medium text-slate-800">${escapeHtml(r.fio)}</td>
|
||||
<td class="p-2.5 text-slate-500 text-center">${escapeHtml(r.department)}</td>
|
||||
<td class="p-2.5 text-center ${r.time_in !== 'Нет входа' ? 'font-bold text-emerald-700' : 'text-slate-400'}">${escapeHtml(r.time_in)}</td>
|
||||
<td class="p-2.5 text-center text-slate-500">${escapeHtml(r.first_activity)}</td>
|
||||
<td class="p-2.5 text-center ${r.time_out !== 'Нет выхода' ? 'font-bold text-slate-800' : 'text-slate-400'}">${escapeHtml(r.time_out)}</td>
|
||||
<td class="p-2.5 text-center font-mono text-slate-600">${escapeHtml(r.in_building)}</td>
|
||||
<td class="p-2.5 text-center font-bold">${r.is_present ? '<span class="text-emerald-600">✓ Да</span>' : '<span class="text-slate-400">Нет</span>'}</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
|
||||
payloadHtml = `
|
||||
<div class="mt-3 bg-white border border-slate-200 rounded-xl overflow-hidden shadow-sm flex flex-col">
|
||||
<div class="px-4 py-3 bg-slate-100/90 border-b border-slate-200 flex items-center justify-between gap-2 flex-wrap">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-sm font-bold text-slate-800">Срез #${escapeHtml(actionPayload.snapshot_id)}</span>
|
||||
<span class="text-xs text-slate-500">· Всего: ${records.length} чел. (Присутствуют: ${actionPayload.present_count || 0})</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="text" id="${searchInputId}" placeholder="Поиск в срезе (ФИО / отдел)..."
|
||||
oninput="window.filterInspectTable('${inspectTableId}', this.value)"
|
||||
class="text-xs px-3 py-1.5 bg-white border border-slate-300 rounded-lg focus:outline-none focus:border-indigo-500 w-60" />
|
||||
<button onclick="window.sendChatAction('покажи срезы')" class="text-xs text-indigo-600 hover:underline font-semibold">Все срезы</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="max-h-96 overflow-y-auto">
|
||||
<table id="${inspectTableId}" class="w-full text-left border-collapse">
|
||||
<thead class="bg-slate-50 text-[11px] uppercase text-slate-500 sticky top-0 border-b border-slate-200 shadow-xs">
|
||||
<tr>
|
||||
<th class="p-2.5 text-center w-10">№</th>
|
||||
<th class="p-2.5">Сотрудник</th>
|
||||
<th class="p-2.5 text-center">Отдел</th>
|
||||
<th class="p-2.5 text-center">Вход</th>
|
||||
<th class="p-2.5 text-center">Активность</th>
|
||||
<th class="p-2.5 text-center">Выход</th>
|
||||
<th class="p-2.5 text-center">В здании</th>
|
||||
<th class="p-2.5 text-center">Статус</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>${rowsHtml}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else if (actionPayload.type === 'PROMPT_EDITOR') {
|
||||
const draftText = actionPayload.raw_draft || actionPayload.baseline_prompt || '';
|
||||
const editorId = 'prompt-editor-' + Date.now();
|
||||
payloadHtml = `
|
||||
<div class="mt-3 p-3.5 bg-slate-50 border border-slate-300 rounded-xl flex flex-col gap-2 shadow-inner">
|
||||
<div class="flex items-center justify-between text-xs font-bold text-slate-700">
|
||||
<span><i class="fa-solid fa-pen-to-square text-indigo-600 mr-1"></i> Инлайн-редактор системного промпта:</span>
|
||||
<span class="text-[11px] text-slate-400 font-normal">Прямое редактирование текста</span>
|
||||
</div>
|
||||
<textarea id="${editorId}" rows="14"
|
||||
class="w-full text-xs font-mono p-3 border border-slate-300 rounded-lg focus:outline-none focus:border-indigo-500 bg-white leading-relaxed resize-y">${escapeHtml(draftText)}</textarea>
|
||||
<div class="flex items-center justify-end gap-2 pt-1">
|
||||
<button type="button" onclick="window.sendChatAction('отмена')" class="px-3.5 py-1.5 text-xs text-slate-600 hover:bg-slate-200 rounded-lg transition font-medium">Отменить</button>
|
||||
<button type="button" onclick="window.submitPromptDraftToDiff('${editorId}')" class="px-4 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-bold shadow transition flex items-center gap-1.5">
|
||||
<i class="fa-solid fa-eye text-xs"></i>
|
||||
<span>Показать превью изменений</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else if (actionPayload.type === 'RULES_EDITOR') {
|
||||
const draftText = actionPayload.raw_draft || actionPayload.baseline_prompt || '';
|
||||
const editorId = 'rules-editor-' + Date.now();
|
||||
payloadHtml = `
|
||||
<div class="mt-3 p-3.5 bg-slate-50 border border-slate-300 rounded-xl flex flex-col gap-2 shadow-inner">
|
||||
<div class="flex items-center justify-between text-xs font-bold text-slate-700">
|
||||
<span><i class="fa-solid fa-book-bookmark text-emerald-600 mr-1"></i> Редактор базы знаний и правил компании:</span>
|
||||
<span class="text-[11px] text-slate-400 font-normal">Прямое изменение правил кадрового арбитража</span>
|
||||
</div>
|
||||
<textarea id="${editorId}" rows="12"
|
||||
class="w-full text-xs font-mono p-3 border border-slate-300 rounded-lg focus:outline-none focus:border-emerald-500 bg-white leading-relaxed resize-y">${escapeHtml(draftText)}</textarea>
|
||||
<div class="flex items-center justify-end gap-2 pt-1">
|
||||
<button type="button" onclick="window.sendChatAction('отмена')" class="px-3.5 py-1.5 text-xs text-slate-600 hover:bg-slate-200 rounded-lg transition font-medium">Отменить</button>
|
||||
<button type="button" onclick="window.submitRulesDraftToDiff('${editorId}')" class="px-4 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-bold shadow transition flex items-center gap-1.5">
|
||||
<i class="fa-solid fa-eye text-xs"></i>
|
||||
<span>Показать превью изменений</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else if (actionPayload.type === 'PROMPT_PREVIEW') {
|
||||
isHtmlBody = true;
|
||||
}
|
||||
}
|
||||
|
||||
let buttonsHtml = '';
|
||||
if (!actionPayload || (actionPayload.type !== 'PROMPT_EDITOR' && actionPayload.type !== 'RULES_EDITOR')) {
|
||||
const allButtons = (buttons && buttons.length > 0) ? buttons : (actionPayload && actionPayload.buttons ? actionPayload.buttons : []);
|
||||
if (allButtons && Array.isArray(allButtons) && allButtons.length > 0) {
|
||||
buttonsHtml = `
|
||||
<div class="flex flex-wrap gap-2 mt-3.5 pt-2.5 border-t border-slate-100">
|
||||
${allButtons.map(b => `
|
||||
<button onclick="window.sendChatAction('${escapeHtml(b.value || b.action || b.title || '')}')"
|
||||
class="px-3 py-1.5 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 rounded-lg text-xs font-semibold border border-indigo-200 transition">
|
||||
${escapeHtml(b.label || b.title || b.action)}
|
||||
</button>
|
||||
`).join('')}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
const bodyContent = isHtmlBody ? text : escapeHtml(text);
|
||||
|
||||
const html = `
|
||||
<div class="flex gap-3 max-w-4xl mx-auto w-full pt-1">
|
||||
<div class="w-8 h-8 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm mt-0.5">
|
||||
<i class="fa-solid fa-robot text-sm"></i>
|
||||
</div>
|
||||
<div class="flex-1 bg-white border border-slate-200 rounded-2xl rounded-tl-none p-4 shadow-sm min-w-0">
|
||||
<div class="text-[11px] font-bold text-indigo-600 uppercase tracking-wider mb-1.5">ИИ-ассистент SCUD Orion AI</div>
|
||||
<div class="text-sm text-slate-800 leading-relaxed whitespace-pre-wrap">${bodyContent}</div>
|
||||
${payloadHtml}
|
||||
${buttonsHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
container.insertAdjacentHTML("beforeend", html);
|
||||
}
|
||||
|
||||
window.filterInspectTable = function(tableId, query) {
|
||||
const table = document.getElementById(tableId);
|
||||
if (!table) return;
|
||||
const q = (query || '').trim().toLowerCase();
|
||||
const rows = table.querySelectorAll('.inspect-row');
|
||||
rows.forEach(r => {
|
||||
const fio = r.getAttribute('data-fio') || '';
|
||||
const dept = r.getAttribute('data-dept') || '';
|
||||
if (!q || fio.includes(q) || dept.includes(q)) {
|
||||
r.classList.remove('hidden');
|
||||
} else {
|
||||
r.classList.add('hidden');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
window.sendChatAction = function(actionText) {
|
||||
if (!actionText || !actionText.trim()) return;
|
||||
const input = document.getElementById("user-input");
|
||||
if (input) {
|
||||
input.value = actionText.trim();
|
||||
updateInputHeightAndFade(input);
|
||||
}
|
||||
window.sendMessage();
|
||||
};
|
||||
|
||||
window.submitPromptDraftToDiff = function(editorId) {
|
||||
const textarea = document.getElementById(editorId);
|
||||
if (!textarea) return;
|
||||
const newText = textarea.value.trim();
|
||||
if (!newText) {
|
||||
alert("Текст системного промпта не может быть пустым");
|
||||
return;
|
||||
}
|
||||
|
||||
const command = `action:save_draft_prompt:::${newText}`;
|
||||
const input = document.getElementById("user-input");
|
||||
if (input) input.value = command;
|
||||
window.sendMessage();
|
||||
};
|
||||
|
||||
window.submitRulesDraftToDiff = function(editorId) {
|
||||
const textarea = document.getElementById(editorId);
|
||||
if (!textarea) return;
|
||||
const newText = textarea.value.trim();
|
||||
if (!newText) {
|
||||
alert("Правила не могут быть пустыми");
|
||||
return;
|
||||
}
|
||||
|
||||
const command = `action:save_draft_rules:::${newText}`;
|
||||
const input = document.getElementById("user-input");
|
||||
if (input) input.value = command;
|
||||
window.sendMessage();
|
||||
};
|
||||
|
||||
window.sendMessage = async function() {
|
||||
const input = document.getElementById("user-input");
|
||||
if (!input) return;
|
||||
|
||||
const messageText = input.value.trim();
|
||||
const fileToSend = currentAttachedFile;
|
||||
|
||||
if (!messageText && !fileToSend) return;
|
||||
|
||||
saveCommandToHistory(messageText);
|
||||
|
||||
input.value = "";
|
||||
input.style.height = '24px';
|
||||
input.style.overflowY = 'hidden';
|
||||
input.style.maskImage = 'none';
|
||||
input.style.webkitMaskImage = 'none';
|
||||
window.clearAttachedFile();
|
||||
|
||||
// 1. Отрисовка сообщения пользователя в ленте
|
||||
if (!messageText.startsWith("action:save_draft_prompt:::") && !messageText.startsWith("action:save_draft_rules:::")) {
|
||||
appendUserMessage(
|
||||
messageText || (fileToSend ? `Прикреплен файл: ${fileToSend.name}` : ''),
|
||||
fileToSend ? fileToSend.name : null
|
||||
);
|
||||
} else {
|
||||
appendUserMessage("Сформировать предпросмотр изменений");
|
||||
}
|
||||
|
||||
// 2. Вставка лоадера
|
||||
const loadingId = appendAssistantLoading();
|
||||
|
||||
// 3. Вызов точного скролла
|
||||
scrollToUserMessageTop();
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/v1/chat", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
message: message,
|
||||
session_id: sessionId,
|
||||
user_id: userId
|
||||
})
|
||||
let res;
|
||||
if (fileToSend) {
|
||||
const formData = new FormData();
|
||||
formData.append("file", fileToSend);
|
||||
formData.append("message", messageText);
|
||||
formData.append("session_id", "web_session_main");
|
||||
|
||||
res = await fetch("/api/v1/chat/upload", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": AuthManager.getAuthHeaders()["Authorization"]
|
||||
},
|
||||
body: formData
|
||||
});
|
||||
|
||||
if (res.status === 404) {
|
||||
res = await fetch("/api/v1/chat", {
|
||||
method: "POST",
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
message: messageText || `Загружен файл: ${fileToSend.name}`,
|
||||
session_id: "web_session_main"
|
||||
})
|
||||
});
|
||||
}
|
||||
} else {
|
||||
res = await fetch("/api/v1/chat", {
|
||||
method: "POST",
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
message: messageText,
|
||||
session_id: "web_session_main"
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
const loaderEl = document.getElementById(loadingId);
|
||||
if (loaderEl) loaderEl.remove();
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
const replyText = data.response || data.text || data.message || "Запрос выполнен.";
|
||||
const buttons = data.buttons || [];
|
||||
const actionPayload = data.action_payload || null;
|
||||
|
||||
appendAssistantMessage(replyText, buttons, actionPayload);
|
||||
|
||||
if (window.SidebarManager) {
|
||||
SidebarManager.renderContent();
|
||||
}
|
||||
} else {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
appendAssistantMessage(`⚠️ Ошибка сервера (${res.status}): ${err.detail || "Не удалось получить ответ"}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Ошибка отправки сообщения:", err);
|
||||
const loaderEl = document.getElementById(loadingId);
|
||||
if (loaderEl) loaderEl.remove();
|
||||
appendAssistantMessage("⚠️ Ошибка соединения с сервером при отправке сообщения.");
|
||||
}
|
||||
};
|
||||
|
||||
window.clearAttachedFile = function() {
|
||||
currentAttachedFile = null;
|
||||
const preview = document.getElementById("file-attachment-preview");
|
||||
const nameEl = document.getElementById("file-attachment-name");
|
||||
const fileInput = document.getElementById("file-upload-input");
|
||||
|
||||
if (preview) preview.classList.add("hidden");
|
||||
if (nameEl) nameEl.innerText = "";
|
||||
if (fileInput) fileInput.value = "";
|
||||
};
|
||||
|
||||
function handleFileSelected(file) {
|
||||
if (!file) return;
|
||||
currentAttachedFile = file;
|
||||
const preview = document.getElementById("file-attachment-preview");
|
||||
const nameEl = document.getElementById("file-attachment-name");
|
||||
|
||||
if (preview && nameEl) {
|
||||
nameEl.innerText = file.name;
|
||||
preview.classList.remove("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const input = document.getElementById("user-input");
|
||||
const fileInput = document.getElementById("file-upload-input");
|
||||
const overlay = document.getElementById("global-drag-overlay");
|
||||
|
||||
if (input) {
|
||||
input.style.lineHeight = '24px';
|
||||
input.style.height = '24px';
|
||||
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") {
|
||||
if (e.shiftKey) return;
|
||||
e.preventDefault();
|
||||
window.sendMessage();
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === "ArrowUp") {
|
||||
const isSingleLine = !input.value.includes("\n");
|
||||
const isAtBeginning = input.selectionStart === 0 && input.selectionEnd === 0;
|
||||
|
||||
if (isSingleLine || isAtBeginning) {
|
||||
if (chatInputHistory.length > 0) {
|
||||
e.preventDefault();
|
||||
if (chatHistoryIndex === -1) {
|
||||
temporaryCurrentInput = input.value;
|
||||
chatHistoryIndex = chatInputHistory.length - 1;
|
||||
} else if (chatHistoryIndex > 0) {
|
||||
chatHistoryIndex--;
|
||||
}
|
||||
input.value = chatInputHistory[chatHistoryIndex];
|
||||
updateInputHeightAndFade(input);
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
}
|
||||
}
|
||||
} else if (e.key === "ArrowDown") {
|
||||
const isSingleLine = !input.value.includes("\n");
|
||||
const isAtEnd = input.selectionStart === input.value.length;
|
||||
|
||||
if (isSingleLine || isAtEnd) {
|
||||
if (chatHistoryIndex !== -1) {
|
||||
e.preventDefault();
|
||||
if (chatHistoryIndex < chatInputHistory.length - 1) {
|
||||
chatHistoryIndex++;
|
||||
input.value = chatInputHistory[chatHistoryIndex];
|
||||
} else {
|
||||
chatHistoryIndex = -1;
|
||||
input.value = temporaryCurrentInput;
|
||||
}
|
||||
updateInputHeightAndFade(input);
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (response.status === 403) {
|
||||
console.warn("[Chat] Получен 403 Forbidden. Сбрасываем сессию и повторяем...");
|
||||
localStorage.removeItem("auth_token");
|
||||
if (typeof appendMessageToUI === "function") {
|
||||
appendMessageToUI("assistant", "⚠️ Сессия была обновлена. Пожалуйста, отправьте сообщение повторно.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Ошибка сервера (HTTP ${response.status})`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const reply = data.response || data.message || "Ответ получен без текста.";
|
||||
|
||||
if (typeof appendMessageToUI === "function") {
|
||||
appendMessageToUI("assistant", reply);
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.error("[Chat Error]:", err);
|
||||
if (typeof appendMessageToUI === "function") {
|
||||
appendMessageToUI("assistant", `⚠️ Не удалось связаться с сервером: ${err.message}`);
|
||||
}
|
||||
input.addEventListener("input", function() {
|
||||
updateInputHeightAndFade(this);
|
||||
chatHistoryIndex = -1;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (fileInput) {
|
||||
fileInput.addEventListener("change", (e) => {
|
||||
if (e.target.files && e.target.files[0]) {
|
||||
handleFileSelected(e.target.files[0]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let dragCounter = 0;
|
||||
|
||||
window.addEventListener('dragenter', (e) => {
|
||||
e.preventDefault();
|
||||
dragCounter++;
|
||||
if (overlay) {
|
||||
overlay.classList.remove('hidden');
|
||||
}
|
||||
}, false);
|
||||
|
||||
window.addEventListener('dragleave', (e) => {
|
||||
e.preventDefault();
|
||||
dragCounter--;
|
||||
if (dragCounter <= 0) {
|
||||
dragCounter = 0;
|
||||
if (overlay) {
|
||||
overlay.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
}, false);
|
||||
|
||||
window.addEventListener('dragover', (e) => {
|
||||
e.preventDefault();
|
||||
}, false);
|
||||
|
||||
window.addEventListener('drop', (e) => {
|
||||
e.preventDefault();
|
||||
dragCounter = 0;
|
||||
if (overlay) {
|
||||
overlay.classList.add('hidden');
|
||||
}
|
||||
|
||||
const dt = e.dataTransfer;
|
||||
if (dt && dt.files && dt.files[0]) {
|
||||
handleFileSelected(dt.files[0]);
|
||||
}
|
||||
}, false);
|
||||
});
|
||||
@@ -0,0 +1,472 @@
|
||||
/**
|
||||
* ===============================================================================
|
||||
* FILE: modules/web_api/static/js/sidebar.js
|
||||
* ROLE: Контроллер левого сайдбара с 5-хабовой навигацией, реестрами,
|
||||
* подробным описанием управления контекстом и интеграцией чата.
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
// Глобальная функция безопасного экранирования HTML
|
||||
window.escapeHtml = function(str) {
|
||||
if (str === null || str === undefined) return '';
|
||||
return String(str)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
};
|
||||
|
||||
window.SidebarManager = {
|
||||
currentHub: 'TASKS',
|
||||
currentSubTab: {
|
||||
'REGISTRIES': 'REMOTE'
|
||||
},
|
||||
|
||||
hubs: [
|
||||
{ id: 'TASKS', label: 'Задачи', icon: 'fa-list-check' },
|
||||
{ id: 'SNAPSHOTS', label: 'Срезы', icon: 'fa-camera' },
|
||||
{ id: 'REGISTRIES', label: 'Реестры', icon: 'fa-address-book' },
|
||||
{ id: 'PROMPT', label: 'Промпт', icon: 'fa-terminal' },
|
||||
{ id: 'CONTEXT', label: 'Контекст', icon: 'fa-comments' }
|
||||
],
|
||||
|
||||
subTabs: {
|
||||
'REGISTRIES': [
|
||||
{ id: 'REMOTE', label: 'Удаленщики', icon: 'fa-house-laptop' },
|
||||
{ id: 'EXCEPTIONS', label: 'Исключения', icon: 'fa-user-shield' }
|
||||
]
|
||||
},
|
||||
|
||||
init() {
|
||||
this.renderHeader();
|
||||
this.renderContent();
|
||||
},
|
||||
|
||||
setHub(hubId) {
|
||||
this.currentHub = hubId;
|
||||
this.renderHeader();
|
||||
this.renderContent();
|
||||
},
|
||||
|
||||
setSubTab(subTabId) {
|
||||
this.currentSubTab[this.currentHub] = subTabId;
|
||||
this.renderHeader();
|
||||
this.renderContent();
|
||||
},
|
||||
|
||||
renderHeader() {
|
||||
const headerContainer = document.getElementById("sidebar-dynamic-header");
|
||||
if (!headerContainer) return;
|
||||
|
||||
// 1. Основные 5 Хабов
|
||||
const hubsHtml = `
|
||||
<div class="flex items-center border-b border-slate-200 bg-slate-50/80 px-1 pt-1.5 overflow-x-auto gap-0.5">
|
||||
${this.hubs.map(h => {
|
||||
const isActive = this.currentHub === h.id;
|
||||
return `
|
||||
<button onclick="SidebarManager.setHub('${h.id}')"
|
||||
class="flex-1 py-1.5 px-1 flex flex-col items-center gap-1 border-b-2 font-bold text-[10px] transition ${
|
||||
isActive
|
||||
? 'border-indigo-600 text-indigo-600 bg-white rounded-t-lg shadow-sm'
|
||||
: 'border-transparent text-slate-500 hover:text-slate-800 hover:bg-slate-100/60 rounded-t-lg'
|
||||
}">
|
||||
<i class="fa-solid ${h.icon} text-xs"></i>
|
||||
<span class="truncate">${h.label}</span>
|
||||
</button>
|
||||
`;
|
||||
}).join('')}
|
||||
</div>
|
||||
`;
|
||||
|
||||
// 2. Подвкладки (только для хабов, где они требуются, например Реестры)
|
||||
let subTabsHtml = '';
|
||||
if (this.subTabs[this.currentHub]) {
|
||||
const currentActiveSub = this.currentSubTab[this.currentHub] || this.subTabs[this.currentHub][0].id;
|
||||
subTabsHtml = `
|
||||
<div class="flex items-center gap-1.5 p-1.5 bg-slate-100/90 border-b border-slate-200">
|
||||
${this.subTabs[this.currentHub].map(st => {
|
||||
const isSubActive = currentActiveSub === st.id;
|
||||
return `
|
||||
<button onclick="SidebarManager.setSubTab('${st.id}')"
|
||||
class="flex-1 py-1 px-2 rounded-md text-[11px] font-semibold flex items-center justify-center gap-1.5 transition ${
|
||||
isSubActive
|
||||
? 'bg-white text-indigo-700 shadow-sm'
|
||||
: 'text-slate-600 hover:text-slate-900 hover:bg-white/50'
|
||||
}">
|
||||
<i class="fa-solid ${st.icon} text-[10px]"></i>
|
||||
<span>${st.label}</span>
|
||||
</button>
|
||||
`;
|
||||
}).join('')}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
headerContainer.innerHTML = hubsHtml + subTabsHtml;
|
||||
},
|
||||
|
||||
renderContent() {
|
||||
const contentContainer = document.getElementById("sidebar-dynamic-content");
|
||||
if (!contentContainer) return;
|
||||
|
||||
contentContainer.scrollTop = 0;
|
||||
|
||||
switch (this.currentHub) {
|
||||
case 'TASKS':
|
||||
this.renderTasksView(contentContainer);
|
||||
break;
|
||||
case 'SNAPSHOTS':
|
||||
this.renderSnapshotsView(contentContainer);
|
||||
break;
|
||||
case 'REGISTRIES':
|
||||
this.renderRegistriesView(contentContainer);
|
||||
break;
|
||||
case 'PROMPT':
|
||||
this.renderPromptView(contentContainer);
|
||||
break;
|
||||
case 'CONTEXT':
|
||||
this.renderContextView(contentContainer);
|
||||
break;
|
||||
default:
|
||||
contentContainer.innerHTML = `<div class="p-4 text-xs text-slate-400 text-center">Раздел в разработке</div>`;
|
||||
}
|
||||
},
|
||||
|
||||
// =========================================================================
|
||||
// ХАБ 1: ЗАДАЧИ
|
||||
// =========================================================================
|
||||
renderTasksView(container) {
|
||||
container.innerHTML = `
|
||||
<div id="tasks-list-container" class="flex-1 flex flex-col gap-2">
|
||||
<div class="text-center py-10 text-xs text-slate-400">
|
||||
<i class="fa-solid fa-spinner fa-spin mr-1"></i> Загрузка задач...
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
if (window.loadTasks) {
|
||||
window.loadTasks();
|
||||
}
|
||||
},
|
||||
|
||||
// =========================================================================
|
||||
// ХАБ 2: СРЕЗЫ СКУД
|
||||
// =========================================================================
|
||||
async renderSnapshotsView(container) {
|
||||
container.innerHTML = `<div class="text-center py-8 text-xs text-slate-400"><i class="fa-solid fa-spinner fa-spin mr-1"></i> Загрузка срезов...</div>`;
|
||||
try {
|
||||
const res = await fetch("/api/v1/snapshots", { headers: AuthManager.getAuthHeaders() });
|
||||
const data = res.ok ? await res.json() : { snapshots: [] };
|
||||
const snaps = data.snapshots || [];
|
||||
|
||||
if (snaps.length === 0) {
|
||||
container.innerHTML = `<div class="text-center py-8 text-xs text-slate-400">Срезы СКУД не найдены</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
const itemsHtml = snaps.map(s => `
|
||||
<div class="flex items-center justify-between p-2.5 bg-white border border-slate-200 rounded-xl text-xs gap-2 shadow-sm hover:border-indigo-300 transition">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="font-bold text-slate-800">${escapeHtml(s.snapshot_id)}</span>
|
||||
${s.is_final ? '<span class="px-1.5 py-0.2 rounded text-[9px] font-bold bg-amber-50 text-amber-700 border border-amber-200">Финал Y</span>' : ''}
|
||||
</div>
|
||||
<div class="text-[10px] text-slate-400 mt-0.5">${escapeHtml(s.snapshot_time)} · ${s.record_count || 0} зап.</div>
|
||||
</div>
|
||||
<button onclick="window.sendChatAction('покажи срез ${escapeHtml(s.snapshot_id)}')" class="px-2 py-1 bg-slate-100 hover:bg-indigo-50 text-slate-600 hover:text-indigo-600 rounded-lg text-[10px] font-semibold transition" title="Открыть в чате">
|
||||
Инспекция
|
||||
</button>
|
||||
</div>
|
||||
`).join('');
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="p-2 flex flex-col gap-2">
|
||||
<div class="flex items-center justify-between px-1">
|
||||
<span class="text-xs font-bold text-slate-700">Всего срезов: ${snaps.length}</span>
|
||||
<button onclick="SidebarManager.renderSnapshotsView(document.getElementById('sidebar-dynamic-content'))" class="text-slate-400 hover:text-indigo-600 p-1" title="Обновить">
|
||||
<i class="fa-solid fa-arrows-rotate text-xs"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1.5 max-h-[70vh] overflow-y-auto">${itemsHtml}</div>
|
||||
</div>
|
||||
`;
|
||||
} catch (e) {
|
||||
container.innerHTML = `<div class="p-4 text-xs text-rose-500 text-center">Ошибка загрузки срезов</div>`;
|
||||
}
|
||||
},
|
||||
|
||||
// =========================================================================
|
||||
// ХАБ 3: РЕЕСТРЫ (УДАЛЕНЩИКИ + ИСКЛЮЧЕНИЯ)
|
||||
// =========================================================================
|
||||
renderRegistriesView(container) {
|
||||
const subTab = this.currentSubTab['REGISTRIES'] || 'REMOTE';
|
||||
if (subTab === 'REMOTE') {
|
||||
this.renderRemoteWorkersView(container);
|
||||
} else {
|
||||
this.renderExceptionsView(container);
|
||||
}
|
||||
},
|
||||
|
||||
async renderRemoteWorkersView(container) {
|
||||
container.innerHTML = `<div class="text-center py-8 text-xs text-slate-400"><i class="fa-solid fa-spinner fa-spin mr-1"></i> Загрузка удаленщиков...</div>`;
|
||||
try {
|
||||
const res = await fetch("/api/v1/remote-workers", { headers: AuthManager.getAuthHeaders() });
|
||||
const data = res.ok ? await res.json() : { workers: [] };
|
||||
const workers = data.workers || [];
|
||||
|
||||
const listHtml = workers.map(w => {
|
||||
const dFrom = w.date_from ? w.date_from : 'сегодня';
|
||||
const dTo = w.date_to ? w.date_to : 'бессрочно';
|
||||
const periodLabel = (!w.date_to) ? `с ${dFrom} (бессрочно)` : `${dFrom} — ${dTo}`;
|
||||
|
||||
return `
|
||||
<div class="flex items-center justify-between p-2.5 bg-white border border-slate-200 rounded-xl text-xs gap-2 shadow-sm hover:border-emerald-300 transition">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="font-bold text-slate-800 truncate">${escapeHtml(w.fio)}</div>
|
||||
<div class="text-[10px] text-slate-400 truncate">${escapeHtml(w.department || 'Все')}</div>
|
||||
<div class="mt-0.5 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[9px] font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200">
|
||||
<i class="fa-regular fa-calendar-days text-[8px]"></i>
|
||||
<span>${escapeHtml(periodLabel)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-0.5 shrink-0">
|
||||
<button onclick="openRemoteWorkerModal('EDIT', '${escapeHtml(w.fio)}', '${escapeHtml(w.department || 'Все')}', '${escapeHtml(w.date_from || '')}', '${escapeHtml(w.date_to || '')}')"
|
||||
class="text-slate-400 hover:text-emerald-600 p-1.5 rounded-lg hover:bg-emerald-50 transition"
|
||||
title="Изменить сроки удаленки">
|
||||
<i class="fa-solid fa-pen-to-square text-xs"></i>
|
||||
</button>
|
||||
<button onclick="SidebarManager.deleteRemoteWorker('${escapeHtml(w.fio)}')"
|
||||
class="text-slate-400 hover:text-rose-600 p-1.5 rounded-lg hover:bg-rose-50 transition"
|
||||
title="Удалить">
|
||||
<i class="fa-solid fa-trash-can text-xs"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="p-2 flex flex-col gap-2.5">
|
||||
<div class="flex items-center justify-between px-1">
|
||||
<span class="text-xs font-bold text-slate-700">В реестре: ${workers.length} чел.</span>
|
||||
<button onclick="openRemoteWorkerModal('ADD')" class="px-2 py-1 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-[11px] font-bold shadow-sm flex items-center gap-1 transition">
|
||||
<i class="fa-solid fa-plus text-[10px]"></i> Добавить
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1.5 max-h-[70vh] overflow-y-auto">
|
||||
${workers.length > 0 ? listHtml : '<div class="text-center py-8 text-xs text-slate-400">Список удаленщиков пуст</div>'}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} catch (e) {
|
||||
container.innerHTML = `<div class="p-4 text-xs text-rose-500 text-center">Ошибка загрузки реестра удаленщиков</div>`;
|
||||
}
|
||||
},
|
||||
|
||||
async deleteRemoteWorker(fio) {
|
||||
if (!confirm(`Удалить сотрудника ${fio} из реестра удаленщиков?`)) return;
|
||||
try {
|
||||
const res = await fetch(`/api/v1/remote-workers?fio=${encodeURIComponent(fio)}`, {
|
||||
method: "DELETE",
|
||||
headers: AuthManager.getAuthHeaders()
|
||||
});
|
||||
if (res.ok) {
|
||||
this.renderContent();
|
||||
} else {
|
||||
alert("Ошибка удаления");
|
||||
}
|
||||
} catch (e) {
|
||||
alert("Ошибка сети");
|
||||
}
|
||||
},
|
||||
|
||||
async renderExceptionsView(container) {
|
||||
container.innerHTML = `<div class="text-center py-8 text-xs text-slate-400"><i class="fa-solid fa-spinner fa-spin mr-1"></i> Загрузка исключений...</div>`;
|
||||
try {
|
||||
const res = await fetch("/api/v1/exceptions/", { headers: AuthManager.getAuthHeaders() });
|
||||
const data = res.ok ? await res.json() : {};
|
||||
const categories = [
|
||||
{ key: 'include_fio', title: 'Белый список (ФИО)' },
|
||||
{ key: 'fio', title: 'Исключенные сотрудники (ФИО)' },
|
||||
{ key: 'departments', title: 'Исключенные отделы' },
|
||||
{ key: 'positions', title: 'Исключенные должности' }
|
||||
];
|
||||
|
||||
const html = categories.map(cat => {
|
||||
const items = data[cat.key] || [];
|
||||
return `
|
||||
<div class="bg-white border border-slate-200 rounded-xl p-3 flex flex-col gap-2 shadow-sm">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="font-bold text-xs text-slate-700">${cat.title} (${items.length})</span>
|
||||
<button onclick="SidebarManager.addExceptionPrompt('${cat.key}')" class="text-indigo-600 hover:text-indigo-800 text-xs font-bold">
|
||||
+ Добавить
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
${items.map(it => `
|
||||
<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] bg-slate-100 text-slate-700 border border-slate-200">
|
||||
${escapeHtml(it)}
|
||||
<button onclick="SidebarManager.deleteExceptionItem('${cat.key}', '${escapeHtml(it)}')" class="hover:text-rose-600 ml-0.5">×</button>
|
||||
</span>
|
||||
`).join('') || '<span class="text-[10px] text-slate-400">Пусто</span>'}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
container.innerHTML = `<div class="p-2 flex flex-col gap-2 max-h-[75vh] overflow-y-auto">${html}</div>`;
|
||||
} catch (e) {
|
||||
container.innerHTML = `<div class="p-4 text-xs text-rose-500 text-center">Ошибка загрузки исключений</div>`;
|
||||
}
|
||||
},
|
||||
|
||||
async addExceptionPrompt(category) {
|
||||
const val = prompt(`Введите значение для категории [${category}]:`);
|
||||
if (!val || !val.trim()) return;
|
||||
try {
|
||||
const res = await fetch("/api/v1/exceptions/", {
|
||||
method: "POST",
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({ category: category, value: val.trim() })
|
||||
});
|
||||
if (res.ok) this.renderContent();
|
||||
else alert("Ошибка добавления");
|
||||
} catch (e) {
|
||||
alert("Ошибка сети");
|
||||
}
|
||||
},
|
||||
|
||||
async deleteExceptionItem(category, value) {
|
||||
if (!confirm(`Удалить "${value}" из ${category}?`)) return;
|
||||
try {
|
||||
const res = await fetch(`/api/v1/exceptions/?category=${encodeURIComponent(category)}&value=${encodeURIComponent(value)}`, {
|
||||
method: "DELETE",
|
||||
headers: AuthManager.getAuthHeaders()
|
||||
});
|
||||
if (res.ok) this.renderContent();
|
||||
else alert("Ошибка удаления");
|
||||
} catch (e) {
|
||||
alert("Ошибка сети");
|
||||
}
|
||||
},
|
||||
|
||||
// =========================================================================
|
||||
// ХАБ 4: СИСТЕМНЫЙ ПРОМПТ И БАЗА ЗНАНИЙ
|
||||
// =========================================================================
|
||||
renderPromptView(container) {
|
||||
container.innerHTML = `
|
||||
<div class="p-3 flex flex-col gap-3">
|
||||
<div class="text-[11px] text-slate-600 leading-relaxed bg-white border border-slate-200 rounded-xl p-3 shadow-sm flex flex-col gap-1.5">
|
||||
<span class="font-bold text-slate-800 flex items-center gap-1.5">
|
||||
<i class="fa-solid fa-sliders text-indigo-600"></i> Инструкции и регламенты ИИ
|
||||
</span>
|
||||
<span>Управление системными директивами, базой знаний и правилами арбитража кадровых аномалий СКУД и 1С.</span>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<button onclick="window.sendChatAction('покажи системный промпт')"
|
||||
class="w-full py-2 px-3 bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white rounded-xl text-xs font-bold shadow-sm flex items-center justify-center gap-2 transition">
|
||||
<i class="fa-solid fa-terminal text-xs"></i>
|
||||
<span>Показать системный промпт</span>
|
||||
</button>
|
||||
|
||||
<button onclick="window.sendChatAction('покажи правила компании')"
|
||||
class="w-full py-2 px-3 bg-white hover:bg-slate-50 active:bg-slate-100 text-slate-700 border border-slate-300 rounded-xl text-xs font-bold shadow-sm flex items-center justify-center gap-2 transition">
|
||||
<i class="fa-solid fa-book-bookmark text-emerald-600 text-xs"></i>
|
||||
<span>База знаний и правила компании</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
},
|
||||
|
||||
// =========================================================================
|
||||
// ХАБ 5: УПРАВЛЕНИЕ КОНТЕКСТОМ СЕССИИ (С ПОДРОБНЫМ ОПИСАНИЕМ)
|
||||
// =========================================================================
|
||||
renderContextView(container) {
|
||||
container.innerHTML = `
|
||||
<div class="p-3 flex flex-col gap-3">
|
||||
<div class="text-[11px] text-slate-600 leading-relaxed bg-white border border-slate-200 rounded-xl p-3 shadow-sm flex flex-col gap-2">
|
||||
<span class="font-bold text-slate-800 flex items-center gap-1.5">
|
||||
<i class="fa-solid fa-brain text-indigo-600"></i> Управление памятью чата
|
||||
</span>
|
||||
|
||||
<div class="flex flex-col gap-1.5 pt-1 border-t border-slate-100">
|
||||
<div class="flex items-start gap-1.5">
|
||||
<span class="w-2 h-2 rounded-full bg-amber-500 mt-1 shrink-0"></span>
|
||||
<div>
|
||||
<span class="font-bold text-slate-700">Мягкая очистка:</span>
|
||||
<span class="text-slate-500"> удаляет только служебные транзакции (карточки срезов, временные превью промпта, промежуточные подтверждения). Смысловой диалог пользователя сохраняется.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-start gap-1.5">
|
||||
<span class="w-2 h-2 rounded-full bg-rose-500 mt-1 shrink-0"></span>
|
||||
<div>
|
||||
<span class="font-bold text-slate-700">Полный сброс:</span>
|
||||
<span class="text-slate-500"> полностью стирает контекст активной сессии из базы данных и очищает окно чата. Используется при переходе к новой дате или новой теме анализа.</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<button onclick="window.sendChatAction('очисти контекст')"
|
||||
class="w-full py-2 px-3 bg-amber-500 hover:bg-amber-600 active:bg-amber-700 text-white rounded-xl text-xs font-bold shadow-sm flex items-center justify-center gap-2 transition">
|
||||
<i class="fa-solid fa-broom text-xs"></i>
|
||||
<span>Мягкая очистка контекста</span>
|
||||
</button>
|
||||
|
||||
<button onclick="SidebarManager.handleFullSessionReset()"
|
||||
class="w-full py-2 px-3 bg-rose-600 hover:bg-rose-700 active:bg-rose-800 text-white rounded-xl text-xs font-bold shadow-sm flex items-center justify-center gap-2 transition">
|
||||
<i class="fa-solid fa-trash-arrow-up text-xs"></i>
|
||||
<span>Полный сброс сессии</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
},
|
||||
|
||||
async handleFullSessionReset() {
|
||||
if (!confirm("Вы действительно хотите полностью очистить историю диалога и сбросить сессию чата?")) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Очищаем локальное окно чата до стартового приветствия
|
||||
const chatContainer = document.getElementById("chat-messages-container");
|
||||
if (chatContainer) {
|
||||
chatContainer.innerHTML = `
|
||||
<div class="flex gap-3 max-w-4xl mx-auto w-full">
|
||||
<div class="w-7 h-7 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm mt-0.5">
|
||||
<i class="fa-solid fa-robot text-xs"></i>
|
||||
</div>
|
||||
<div class="flex-1 bg-white border border-slate-200 rounded-2xl rounded-tl-none p-4 shadow-sm">
|
||||
<div class="text-[10px] font-bold text-indigo-600 uppercase tracking-wider mb-1">ИИ-ассистент SCUD Orion AI</div>
|
||||
<div class="text-xs text-slate-700 leading-relaxed">
|
||||
Сессия чата очищена. Память ассистента сброшена. Задайте новый вопрос или команду.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
try {
|
||||
await fetch("/api/v1/chat", {
|
||||
method: "POST",
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
message: "сбрось сессию полностью",
|
||||
session_id: "web_session_main"
|
||||
})
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("Ошибка запроса сброса сессии:", e);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
if (window.AuthManager && AuthManager.isAuthenticated()) {
|
||||
SidebarManager.init();
|
||||
}
|
||||
});
|
||||
@@ -1,117 +1,200 @@
|
||||
/**
|
||||
===============================================================================
|
||||
FILE: modules/web_api/static/js/tasks.js
|
||||
PROJECT: SCUD Orion AI (Unified Architecture)
|
||||
MODULE: web_api / static / js
|
||||
ROLE: Загрузка, фильтрация и рендеринг списка задач в боковой панели (Drawer).
|
||||
===============================================================================
|
||||
*/
|
||||
* ===============================================================================
|
||||
* FILE: modules/web_api/static/js/tasks.js
|
||||
* ROLE: Управление персональными задачами оператора (CRUD, фильтры, рендер).
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
let currentTaskFilter = 'IN_PROGRESS';
|
||||
let currentTasksFilter = 'ALL';
|
||||
let tasksCache = [];
|
||||
|
||||
function getTasksContainer() {
|
||||
return document.getElementById("tasks-list-container") ||
|
||||
document.getElementById("sidebar-dynamic-content") ||
|
||||
document.getElementById("tasks-list");
|
||||
}
|
||||
|
||||
async function loadTasks() {
|
||||
const token = typeof API_TOKEN !== 'undefined' && API_TOKEN ? API_TOKEN : localStorage.getItem("scud_api_auth_token");
|
||||
if (!token) return;
|
||||
const container = getTasksContainer();
|
||||
if (!container) return;
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="text-center py-8 text-xs text-slate-400">
|
||||
<i class="fa-solid fa-spinner fa-spin mr-1"></i> Загрузка задач...
|
||||
</div>
|
||||
`;
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/v1/tasks", {
|
||||
headers: { "Authorization": "Bearer " + token }
|
||||
headers: AuthManager.getAuthHeaders()
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
renderSidebarTasks(data.tasks || []);
|
||||
} else {
|
||||
renderSidebarError("Ошибка доступа. Авторизуйтесь снова.");
|
||||
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) {
|
||||
showAuthModal();
|
||||
return;
|
||||
}
|
||||
throw new Error(`Ошибка сервера (${res.status})`);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Ошибка загрузки задач:", e);
|
||||
renderSidebarError("Ошибка сети. Сервер недоступен.");
|
||||
|
||||
const data = await res.json();
|
||||
tasksCache = Array.isArray(data) ? data : (data.tasks || []);
|
||||
renderTasksUI();
|
||||
} catch (err) {
|
||||
console.error("[Tasks] Ошибка загрузки:", err);
|
||||
container.innerHTML = `
|
||||
<div class="p-4 text-xs text-rose-500 text-center flex flex-col items-center gap-2">
|
||||
<i class="fa-solid fa-triangle-exclamation text-base"></i>
|
||||
<span>Не удалось загрузить задачи</span>
|
||||
<button onclick="loadTasks()" class="px-2.5 py-1 bg-slate-200 hover:bg-slate-300 text-slate-700 rounded text-[11px] font-semibold transition">Повторить</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderSidebarError(msg) {
|
||||
// Поддерживаем оба варианта ID (новый и старый) для обратной совместимости
|
||||
const container = document.getElementById("tasks-list") || document.getElementById("tasks-list-container");
|
||||
if (container) {
|
||||
container.innerHTML = `<div class="text-center py-8 text-xs text-rose-500 font-semibold">${msg}</div>`;
|
||||
}
|
||||
function setTaskFilter(filter) {
|
||||
currentTasksFilter = filter;
|
||||
renderTasksUI();
|
||||
}
|
||||
|
||||
function filterTasksByTab(status) {
|
||||
currentTaskFilter = status;
|
||||
|
||||
// Сброс стилей всех кнопок-вкладок
|
||||
document.querySelectorAll('.task-tab-btn').forEach(btn => {
|
||||
btn.classList.remove('text-indigo-600', 'bg-indigo-50');
|
||||
btn.classList.add('text-slate-600');
|
||||
});
|
||||
|
||||
// Установка активного стиля для выбранной вкладки
|
||||
const activeBtnId = {
|
||||
'IN_PROGRESS': 'tab-in-progress',
|
||||
'BACKLOG': 'tab-backlog',
|
||||
'COMPLETED': 'tab-completed',
|
||||
'ALL': 'tab-all'
|
||||
}[status];
|
||||
|
||||
if (activeBtnId) {
|
||||
const btn = document.getElementById(activeBtnId);
|
||||
if (btn) {
|
||||
btn.classList.remove('text-slate-600', 'hover:bg-slate-100');
|
||||
btn.classList.add('text-indigo-600', 'bg-indigo-50');
|
||||
}
|
||||
}
|
||||
|
||||
loadTasks();
|
||||
}
|
||||
|
||||
function renderSidebarTasks(tasks) {
|
||||
const container = document.getElementById("tasks-list") || document.getElementById("tasks-list-container");
|
||||
function renderTasksUI() {
|
||||
const container = getTasksContainer();
|
||||
if (!container) return;
|
||||
|
||||
let filtered = tasks;
|
||||
if (currentTaskFilter !== 'ALL') {
|
||||
filtered = tasks.filter(t => t.status === currentTaskFilter);
|
||||
|
||||
let filtered = tasksCache;
|
||||
if (currentTasksFilter === 'IN_PROGRESS') {
|
||||
filtered = tasksCache.filter(t => t.status === 'IN_PROGRESS');
|
||||
} else if (currentTasksFilter === 'BACKLOG') {
|
||||
filtered = tasksCache.filter(t => t.status === 'BACKLOG' || t.status === 'PLANNED');
|
||||
} else if (currentTasksFilter === 'COMPLETED') {
|
||||
filtered = tasksCache.filter(t => t.status === 'COMPLETED' || t.status === 'DONE');
|
||||
}
|
||||
|
||||
const filtersHtml = `
|
||||
<div class="flex items-center gap-1 p-1 bg-slate-200/70 rounded-lg text-[11px] font-semibold mb-2">
|
||||
<button onclick="setTaskFilter('ALL')" class="flex-1 py-1 rounded text-center transition ${currentTasksFilter === 'ALL' ? 'bg-white text-indigo-700 shadow-sm' : 'text-slate-600 hover:text-slate-900'}">Все</button>
|
||||
<button onclick="setTaskFilter('IN_PROGRESS')" class="flex-1 py-1 rounded text-center transition ${currentTasksFilter === 'IN_PROGRESS' ? 'bg-white text-indigo-700 shadow-sm' : 'text-slate-600 hover:text-slate-900'}">В работе</button>
|
||||
<button onclick="setTaskFilter('BACKLOG')" class="flex-1 py-1 rounded text-center transition ${currentTasksFilter === 'BACKLOG' ? 'bg-white text-indigo-700 shadow-sm' : 'text-slate-600 hover:text-slate-900'}">Планы</button>
|
||||
<button onclick="setTaskFilter('COMPLETED')" class="flex-1 py-1 rounded text-center transition ${currentTasksFilter === 'COMPLETED' ? 'bg-white text-indigo-700 shadow-sm' : 'text-slate-600 hover:text-slate-900'}">Готово</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const addBtnHtml = `
|
||||
<div class="flex items-center justify-between px-1 mb-1.5">
|
||||
<span class="text-xs font-bold text-slate-700">Задачи: ${filtered.length}</span>
|
||||
<button onclick="openCreateTaskModal()" class="px-2 py-1 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-[11px] font-bold shadow-sm flex items-center gap-1 transition">
|
||||
<i class="fa-solid fa-plus text-[10px]"></i> Новая
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
if (filtered.length === 0) {
|
||||
container.innerHTML = `<div class="text-center py-8 text-[11px] font-medium text-slate-400 bg-slate-50 rounded-xl border border-dashed border-slate-200">Нет задач в этой категории</div>`;
|
||||
container.innerHTML = `
|
||||
${filtersHtml}
|
||||
${addBtnHtml}
|
||||
<div class="text-center py-8 text-xs text-slate-400 bg-white border border-slate-200 rounded-xl p-4">
|
||||
Нет задач в выбранной категории
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML = filtered.map(t => {
|
||||
const isCompleted = t.status === 'COMPLETED';
|
||||
const priorityColor = t.priority === 'HIGH' || t.priority === 'CRITICAL'
|
||||
? 'text-rose-600 bg-rose-50 border-rose-200'
|
||||
: t.priority === 'MEDIUM'
|
||||
? 'text-amber-600 bg-amber-50 border-amber-200'
|
||||
: 'text-slate-600 bg-slate-50 border-slate-200';
|
||||
|
||||
const itemsHtml = filtered.map(t => {
|
||||
const isDone = t.status === 'COMPLETED' || t.status === 'DONE';
|
||||
const priorityColors = {
|
||||
'HIGH': 'bg-rose-50 text-rose-700 border-rose-200',
|
||||
'MEDIUM': 'bg-amber-50 text-amber-700 border-amber-200',
|
||||
'LOW': 'bg-slate-50 text-slate-600 border-slate-200'
|
||||
};
|
||||
const pClass = priorityColors[t.priority] || priorityColors['MEDIUM'];
|
||||
|
||||
return `
|
||||
<div class="p-3 bg-white border border-slate-200 rounded-xl shadow-sm hover:border-indigo-400 hover:shadow-md transition cursor-pointer flex flex-col gap-2 group"
|
||||
onclick="handleActionButtonClick('покажи задачу ${t.id}')">
|
||||
|
||||
<div class="flex flex-col p-2.5 bg-white border border-slate-200 rounded-xl text-xs gap-1.5 shadow-sm hover:border-indigo-300 transition">
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<span class="text-[10px] font-bold text-slate-400 uppercase tracking-wider group-hover:text-indigo-500 transition">#${t.id}</span>
|
||||
${isCompleted
|
||||
? `<span class="text-[10px] font-bold px-1.5 py-0.5 rounded-md bg-emerald-50 text-emerald-600 border border-emerald-200 shadow-sm"><i class="fa-solid fa-check mr-0.5"></i> Готово</span>`
|
||||
: `<span class="text-[10px] font-bold px-1.5 py-0.5 rounded-md ${priorityColor} shadow-sm">${t.priority || 'LOW'}</span>`
|
||||
}
|
||||
<div class="flex items-center gap-1.5 min-w-0">
|
||||
<button onclick="toggleTaskStatus(${t.id}, '${t.status}')" class="text-slate-400 hover:text-indigo-600 transition shrink-0">
|
||||
<i class="fa-${isDone ? 'solid fa-circle-check text-emerald-500' : 'regular fa-circle'} text-sm"></i>
|
||||
</button>
|
||||
<span class="font-bold text-slate-800 ${isDone ? 'line-through text-slate-400' : ''} truncate">${escapeHtml(t.title)}</span>
|
||||
</div>
|
||||
<span class="px-1.5 py-0.5 rounded text-[9px] font-semibold border ${pClass} shrink-0">${t.priority || 'NORMAL'}</span>
|
||||
</div>
|
||||
|
||||
<div class="text-xs font-semibold text-slate-700 leading-snug line-clamp-3">${escapeHtml(t.title || 'Без названия')}</div>
|
||||
|
||||
<div class="flex items-center justify-between text-[10px] text-slate-400 mt-1">
|
||||
<span class="bg-slate-100 px-1.5 py-0.5 rounded font-mono truncate max-w-[120px]">${escapeHtml(t.module || 'general')}</span>
|
||||
${t.due_date ? `<span class="shrink-0 font-medium text-slate-500"><i class="fa-regular fa-calendar mr-1"></i>${escapeHtml(t.due_date)}</span>` : ''}
|
||||
<div class="flex items-center justify-between text-[10px] text-slate-400 pt-1 border-t border-slate-100">
|
||||
<span>${t.task_id || ('#' + t.id)} · ${escapeHtml(t.module || 'general')}</span>
|
||||
<div class="flex items-center gap-1">
|
||||
<button onclick="deleteTaskItem(${t.id})" class="text-slate-400 hover:text-rose-600 p-0.5 transition" title="Удалить">
|
||||
<i class="fa-solid fa-trash-can text-[11px]"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
container.innerHTML = `
|
||||
${filtersHtml}
|
||||
${addBtnHtml}
|
||||
<div class="flex flex-col gap-1.5 max-h-[70vh] overflow-y-auto">
|
||||
${itemsHtml}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// Глобальная инициализация при загрузке DOM
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
// Небольшая задержка, чтобы гарантировать применение токена
|
||||
setTimeout(loadTasks, 200);
|
||||
});
|
||||
async function toggleTaskStatus(id, currentStatus) {
|
||||
const newStatus = (currentStatus === 'COMPLETED' || currentStatus === 'DONE') ? 'IN_PROGRESS' : 'COMPLETED';
|
||||
try {
|
||||
const res = await fetch(`/api/v1/tasks/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({ status: newStatus })
|
||||
});
|
||||
if (res.ok) {
|
||||
loadTasks();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Ошибка смены статуса задачи:", e);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteTaskItem(id) {
|
||||
if (!confirm("Удалить эту задачу?")) return;
|
||||
try {
|
||||
const res = await fetch(`/api/v1/tasks/${id}`, {
|
||||
method: "DELETE",
|
||||
headers: AuthManager.getAuthHeaders()
|
||||
});
|
||||
if (res.ok) {
|
||||
loadTasks();
|
||||
}
|
||||
} catch (e) {
|
||||
alert("Ошибка сети при удалении");
|
||||
}
|
||||
}
|
||||
|
||||
async function openCreateTaskModal() {
|
||||
const title = prompt("Введите описание новой задачи:");
|
||||
if (!title || !title.trim()) return;
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/v1/tasks", {
|
||||
method: "POST",
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
title: title.trim(),
|
||||
priority: "MEDIUM",
|
||||
status: "IN_PROGRESS"
|
||||
})
|
||||
});
|
||||
if (res.ok) {
|
||||
loadTasks();
|
||||
} else {
|
||||
alert("Не удалось создать задачу");
|
||||
}
|
||||
} catch (e) {
|
||||
alert("Ошибка сети");
|
||||
}
|
||||
}
|
||||
|
||||
window.loadTasks = loadTasks;
|
||||
window.setTaskFilter = setTaskFilter;
|
||||
Reference in New Issue
Block a user