feat(chat): multi-session chat support (up to 15), human-like auto-titling, line-clamp titles and sorted registries
This commit is contained in:
Binary file not shown.
@@ -12,3 +12,4 @@ fio,department,reason,date_from,date_to
|
|||||||
Субетто Юлия Викторовна,Все,Удаленная работа,,
|
Субетто Юлия Викторовна,Все,Удаленная работа,,
|
||||||
Чуркина Елена Геннадьевна,Все,Удаленная работа,,
|
Чуркина Елена Геннадьевна,Все,Удаленная работа,,
|
||||||
Сергиенко Игорь Сергеевич,Управление главных инженеров проектов №1,Удаленная работа,,
|
Сергиенко Игорь Сергеевич,Управление главных инженеров проектов №1,Удаленная работа,,
|
||||||
|
Алирзаев Вадим Октаевич,Отдел автоматизации,Удаленная работа,19.10.2026,
|
||||||
|
|||||||
|
@@ -1,87 +1,212 @@
|
|||||||
"""
|
"""
|
||||||
|
===============================================================================
|
||||||
FILE: modules/web_api/llm/db/db_chat.py
|
FILE: modules/web_api/llm/db/db_chat.py
|
||||||
ROLE: Управление историей сообщений и очисткой эфемерного контекста.
|
PROJECT: SCUD Orion AI (Unified Architecture)
|
||||||
|
MODULE: web_api / llm / db
|
||||||
|
ROLE: Хранение истории сообщений чата, сессий тем (мультичаты) и эфемерных состояний.
|
||||||
|
===============================================================================
|
||||||
"""
|
"""
|
||||||
from typing import List, Dict, Any
|
|
||||||
from .connection import get_db_connection
|
|
||||||
|
|
||||||
def db_save_chat_message(session_id: str, role: str, content: str, is_ephemeral: int = 0) -> None:
|
import json
|
||||||
"""Сохраняет сообщение в БД (is_ephemeral=1 для временных служебных шагов, 0 для постоянных)."""
|
from typing import List, Dict, Any, Optional
|
||||||
conn = get_db_connection(row_factory=True)
|
from core.connection import get_connection as get_db_connection
|
||||||
cursor = conn.cursor()
|
|
||||||
cursor.execute("""
|
|
||||||
INSERT INTO chat_messages (session_id, role, content, is_ephemeral)
|
|
||||||
VALUES (?, ?, ?, ?)
|
|
||||||
""", (session_id, role, content, is_ephemeral))
|
|
||||||
conn.commit()
|
|
||||||
conn.close()
|
|
||||||
|
|
||||||
|
|
||||||
def db_get_chat_history(session_id: str, limit: int = 50) -> list:
|
# ---------------------------------------------------------------------------
|
||||||
"""Возвращает историю сообщений диалога для сессии."""
|
# ИНИЦИАЛИЗАЦИЯ ТАБЛИЦ СЕССИЙ И СООБЩЕНИЙ
|
||||||
with get_db_connection(row_factory=True) as conn:
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def db_init_chat_sessions_table() -> None:
|
||||||
|
"""Инициализирует таблицу тем диалогов (chat_sessions), если она еще не создана."""
|
||||||
|
with get_db_connection() as conn:
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute("""
|
cursor.execute("""
|
||||||
SELECT role, content, is_ephemeral, created_at
|
CREATE TABLE IF NOT EXISTS chat_sessions (
|
||||||
FROM chat_messages
|
id TEXT PRIMARY KEY,
|
||||||
WHERE session_id = ?
|
user_id INTEGER DEFAULT 1,
|
||||||
ORDER BY id DESC
|
title TEXT NOT NULL,
|
||||||
LIMIT ?
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
""", (session_id, limit))
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
cursor.execute("""
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_chat_sessions_user
|
||||||
|
ON chat_sessions(user_id, updated_at DESC)
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# УПРАВЛЕНИЕ ТЕМАМИ (МУЛЬТИЧАТЫ)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def db_get_chat_sessions(user_id: Optional[int] = None, limit: int = 15) -> List[Dict[str, Any]]:
|
||||||
|
"""Возвращает список сохраненных тем (до 15 штук), отсортированных по последней активности."""
|
||||||
|
db_init_chat_sessions_table()
|
||||||
|
with get_db_connection(row_factory=True) as conn:
|
||||||
|
cursor = conn.cursor()
|
||||||
|
if user_id and user_id > 0:
|
||||||
|
cursor.execute("""
|
||||||
|
SELECT id, user_id, title, created_at, updated_at
|
||||||
|
FROM chat_sessions
|
||||||
|
WHERE user_id = ?
|
||||||
|
ORDER BY updated_at DESC
|
||||||
|
LIMIT ?
|
||||||
|
""", (user_id, limit))
|
||||||
|
else:
|
||||||
|
cursor.execute("""
|
||||||
|
SELECT id, user_id, title, created_at, updated_at
|
||||||
|
FROM chat_sessions
|
||||||
|
ORDER BY updated_at DESC
|
||||||
|
LIMIT ?
|
||||||
|
""", (limit,))
|
||||||
rows = cursor.fetchall()
|
rows = cursor.fetchall()
|
||||||
return [{"role": r["role"], "content": r["content"], "is_ephemeral": r["is_ephemeral"]} for r in reversed(rows)]
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def db_create_chat_session(session_id: str, title: str, user_id: int = 1) -> Dict[str, Any]:
|
||||||
|
"""Создает новую запись темы в базе данных."""
|
||||||
|
db_init_chat_sessions_table()
|
||||||
|
with get_db_connection() as conn:
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute("""
|
||||||
|
INSERT OR REPLACE INTO chat_sessions (id, user_id, title, updated_at)
|
||||||
|
VALUES (?, ?, ?, CURRENT_TIMESTAMP)
|
||||||
|
""", (session_id, user_id, title))
|
||||||
|
conn.commit()
|
||||||
|
return {"id": session_id, "title": title, "user_id": user_id}
|
||||||
|
|
||||||
|
|
||||||
|
def db_touch_chat_session(session_id: str, auto_title: Optional[str] = None, user_id: int = 1) -> None:
|
||||||
|
"""
|
||||||
|
Обновляет метку времени updated_at сессии.
|
||||||
|
Если тема еще не была создана в chat_sessions, создает её с автозаголовком.
|
||||||
|
"""
|
||||||
|
db_init_chat_sessions_table()
|
||||||
|
with get_db_connection() as conn:
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute("SELECT id, title FROM chat_sessions WHERE id = ?", (session_id,))
|
||||||
|
row = cursor.fetchone()
|
||||||
|
if not row:
|
||||||
|
clean_title = (auto_title or "Новый диалог").strip().replace("\n", " ")
|
||||||
|
title = (clean_title[:40] + "...") if len(clean_title) > 40 else clean_title
|
||||||
|
cursor.execute("""
|
||||||
|
INSERT INTO chat_sessions (id, user_id, title, updated_at)
|
||||||
|
VALUES (?, ?, ?, CURRENT_TIMESTAMP)
|
||||||
|
""", (session_id, user_id, title))
|
||||||
|
else:
|
||||||
|
cursor.execute("""
|
||||||
|
UPDATE chat_sessions
|
||||||
|
SET updated_at = CURRENT_TIMESTAMP
|
||||||
|
WHERE id = ?
|
||||||
|
""", (session_id,))
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def db_delete_chat_session_cascade(session_id: str) -> None:
|
||||||
|
"""Каскадное физическое удаление сообщений темы, сессионных стейтов и самой темы."""
|
||||||
|
db_init_chat_sessions_table()
|
||||||
|
with get_db_connection() as conn:
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute("DELETE FROM chat_messages WHERE session_id = ?", (session_id,))
|
||||||
|
cursor.execute("DELETE FROM session_states WHERE session_id = ?", (session_id,))
|
||||||
|
cursor.execute("DELETE FROM chat_sessions WHERE id = ?", (session_id,))
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# ИСТОРИЯ И СООБЩЕНИЯ ДИАЛОГА (СТРОГО ПО СХЕМЕ: id, session_id, role, content, is_ephemeral, created_at)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def db_save_chat_message(
|
||||||
|
session_id: str,
|
||||||
|
role: str,
|
||||||
|
content: str,
|
||||||
|
tool_calls: Optional[Any] = None,
|
||||||
|
tool_call_id: Optional[str] = None,
|
||||||
|
is_ephemeral: int = 0
|
||||||
|
) -> None:
|
||||||
|
"""Сохраняет сообщение в историю чата с привязкой к session_id."""
|
||||||
|
with get_db_connection() as conn:
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute("""
|
||||||
|
INSERT INTO chat_messages (session_id, role, content, is_ephemeral)
|
||||||
|
VALUES (?, ?, ?, ?)
|
||||||
|
""", (session_id, role, content, is_ephemeral))
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def db_get_chat_history(
|
||||||
|
session_id: str,
|
||||||
|
limit: int = 50,
|
||||||
|
include_ephemeral: bool = False
|
||||||
|
) -> List[Dict[str, Any]]:
|
||||||
|
"""Возвращает историю сообщений заданной ветки в хронологическом порядке."""
|
||||||
|
with get_db_connection(row_factory=True) as conn:
|
||||||
|
cursor = conn.cursor()
|
||||||
|
if include_ephemeral:
|
||||||
|
cursor.execute("""
|
||||||
|
SELECT id, session_id, role, content, is_ephemeral, created_at
|
||||||
|
FROM chat_messages
|
||||||
|
WHERE session_id = ?
|
||||||
|
ORDER BY id ASC
|
||||||
|
LIMIT ?
|
||||||
|
""", (session_id, limit))
|
||||||
|
else:
|
||||||
|
cursor.execute("""
|
||||||
|
SELECT id, session_id, role, content, is_ephemeral, created_at
|
||||||
|
FROM chat_messages
|
||||||
|
WHERE session_id = ? AND is_ephemeral = 0
|
||||||
|
ORDER BY id ASC
|
||||||
|
LIMIT ?
|
||||||
|
""", (session_id, limit))
|
||||||
|
rows = cursor.fetchall()
|
||||||
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
|
||||||
def db_purge_ephemeral_messages(session_id: str) -> int:
|
def db_purge_ephemeral_messages(session_id: str) -> int:
|
||||||
"""
|
"""Физически удаляет временные служебные сообщения (превью, черновики)."""
|
||||||
Физически удаляет все временные служебные сообщения выбранной сессии
|
with get_db_connection() as conn:
|
||||||
после завершения сценария работы с инструментом.
|
|
||||||
"""
|
|
||||||
conn = get_db_connection(row_factory=True)
|
|
||||||
cursor = conn.cursor()
|
|
||||||
cursor.execute("DELETE FROM chat_messages WHERE session_id = ? AND is_ephemeral = 1", (session_id,))
|
|
||||||
deleted = cursor.rowcount
|
|
||||||
conn.commit()
|
|
||||||
conn.close()
|
|
||||||
return deleted
|
|
||||||
|
|
||||||
|
|
||||||
def db_clear_chat_history(session_id: str) -> None:
|
|
||||||
"""Полная очистка всех сообщений сессии."""
|
|
||||||
conn = get_db_connection(row_factory=True)
|
|
||||||
cursor = conn.cursor()
|
|
||||||
cursor.execute("DELETE FROM chat_messages WHERE session_id = ?", (session_id,))
|
|
||||||
conn.commit()
|
|
||||||
conn.close()
|
|
||||||
|
|
||||||
def db_clear_all_chat_context(session_id: str = None, purge_all: bool = False) -> int:
|
|
||||||
"""Удаляет сообщения чата и стейты сессий."""
|
|
||||||
with get_db_connection(row_factory=True) as conn:
|
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
if purge_all:
|
cursor.execute("DELETE FROM chat_messages WHERE session_id = ? AND is_ephemeral = 1", (session_id,))
|
||||||
if session_id:
|
deleted = cursor.rowcount
|
||||||
|
conn.commit()
|
||||||
|
return deleted
|
||||||
|
|
||||||
|
|
||||||
|
def db_clear_chat_history(session_id: str) -> int:
|
||||||
|
"""Полная очистка всей истории сообщений сессии."""
|
||||||
|
with get_db_connection() as conn:
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute("DELETE FROM chat_messages WHERE session_id = ?", (session_id,))
|
||||||
|
deleted = cursor.rowcount
|
||||||
|
conn.commit()
|
||||||
|
return deleted
|
||||||
|
|
||||||
|
|
||||||
|
def db_clear_all_chat_context(session_id: Optional[str] = None, purge_all: bool = False) -> int:
|
||||||
|
"""Универсальная очистка контекста для CLI и фоновых задач."""
|
||||||
|
with get_db_connection() as conn:
|
||||||
|
cursor = conn.cursor()
|
||||||
|
if session_id:
|
||||||
|
if purge_all:
|
||||||
cursor.execute("DELETE FROM chat_messages WHERE session_id = ?", (session_id,))
|
cursor.execute("DELETE FROM chat_messages WHERE session_id = ?", (session_id,))
|
||||||
cursor.execute("DELETE FROM session_states WHERE session_id = ?", (session_id,))
|
|
||||||
else:
|
else:
|
||||||
|
cursor.execute("DELETE FROM chat_messages WHERE session_id = ? AND is_ephemeral = 1", (session_id,))
|
||||||
|
else:
|
||||||
|
if purge_all:
|
||||||
cursor.execute("DELETE FROM chat_messages")
|
cursor.execute("DELETE FROM chat_messages")
|
||||||
cursor.execute("DELETE FROM session_states")
|
else:
|
||||||
cnt = cursor.rowcount
|
cursor.execute("DELETE FROM chat_messages WHERE is_ephemeral = 1")
|
||||||
conn.commit()
|
deleted = cursor.rowcount
|
||||||
return cnt
|
conn.commit()
|
||||||
|
return deleted
|
||||||
|
|
||||||
|
|
||||||
query = """
|
def db_update_session_title(session_id: str, new_title: str) -> None:
|
||||||
DELETE FROM chat_messages
|
"""Фоновое обновление названия сессии после суммаризации моделью."""
|
||||||
WHERE is_ephemeral = 1
|
db_init_chat_sessions_table()
|
||||||
OR content LIKE '%Предпросмотр изменений%'
|
with get_db_connection() as conn:
|
||||||
OR content LIKE '%Удален пункт:%'
|
cursor = conn.cursor()
|
||||||
OR content LIKE '%добавлен пункт:%'
|
cursor.execute("UPDATE chat_sessions SET title = ? WHERE id = ?", (new_title.strip(), session_id))
|
||||||
"""
|
|
||||||
if session_id:
|
|
||||||
cursor.execute(query + " AND session_id = ?", (session_id,))
|
|
||||||
cursor.execute("DELETE FROM session_states WHERE session_id = ?", (session_id,))
|
|
||||||
else:
|
|
||||||
cursor.execute(query)
|
|
||||||
cursor.execute("DELETE FROM session_states")
|
|
||||||
cnt = cursor.rowcount
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
return cnt
|
|
||||||
+168
-95
@@ -1,148 +1,221 @@
|
|||||||
"""
|
"""
|
||||||
===============================================================================
|
===============================================================================
|
||||||
FILE: modules/web_api/routers/chat.py
|
FILE: modules/web_api/routers/chat.py
|
||||||
ROLE: Роутер чата с чистым разделением:
|
PROJECT: SCUD Orion AI (Unified Architecture)
|
||||||
- Диалог и команды СКУД/1С (через agent.py).
|
MODULE: web_api / routers
|
||||||
- Парсинг и извлечение документов без обрезания (через file_parser.py).
|
ROLE: REST API маршрутизатор диалогов с ИИ-ассистентом, мультичатов (тем)
|
||||||
|
и обработки прикрепленных файлов/документов.
|
||||||
===============================================================================
|
===============================================================================
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import shutil
|
import uuid
|
||||||
import logging
|
import logging
|
||||||
from typing import Optional
|
from typing import Optional, List, Dict, Any
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, Query, BackgroundTasks
|
||||||
from fastapi import APIRouter, Header, HTTPException, UploadFile, File, Form
|
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
from llm.agent import process_chat_message
|
from config import DATA_DIR
|
||||||
from llm.file_parser import parse_uploaded_file
|
from modules.web_api.routers.auth import get_current_user
|
||||||
from config import BASE_DIR
|
from modules.web_api.llm.agent import process_chat_message
|
||||||
|
from modules.web_api.llm.file_parser import parse_uploaded_file
|
||||||
|
from modules.web_api.llm.db.db_chat import (
|
||||||
|
db_get_chat_sessions,
|
||||||
|
db_create_chat_session,
|
||||||
|
db_delete_chat_session_cascade,
|
||||||
|
db_touch_chat_session,
|
||||||
|
db_update_session_title,
|
||||||
|
db_get_chat_history
|
||||||
|
)
|
||||||
|
|
||||||
logger = logging.getLogger("CHAT_API")
|
logger = logging.getLogger("CHAT_ROUTER")
|
||||||
router = APIRouter(prefix="/api/v1", tags=["Chat"])
|
router = APIRouter(prefix="/api/v1/chat", tags=["Chat"])
|
||||||
|
|
||||||
UPLOAD_TMP_DIR = os.path.join(BASE_DIR, "data", "uploads")
|
UPLOAD_DIR = os.path.join(DATA_DIR, "uploads")
|
||||||
os.makedirs(UPLOAD_TMP_DIR, exist_ok=True)
|
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# СХЕМЫ ЗАПРОСОВ
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
class ChatMessageRequest(BaseModel):
|
class ChatMessageRequest(BaseModel):
|
||||||
message: str
|
message: str
|
||||||
session_id: Optional[str] = "web_session_main"
|
session_id: Optional[str] = "session_main"
|
||||||
user_id: Optional[int] = 1
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_user_id(authorization: Optional[str] = None, explicit_user_id: Optional[int] = None) -> int:
|
class CreateSessionRequest(BaseModel):
|
||||||
if explicit_user_id and explicit_user_id > 0:
|
title: Optional[str] = None
|
||||||
return explicit_user_id
|
session_id: Optional[str] = None
|
||||||
|
|
||||||
if authorization and authorization.startswith("Bearer "):
|
|
||||||
token = authorization.replace("Bearer ", "").strip()
|
|
||||||
if token.isdigit():
|
|
||||||
return int(token)
|
|
||||||
return 1
|
|
||||||
|
|
||||||
|
|
||||||
@router.post("/chat")
|
# ---------------------------------------------------------------------------
|
||||||
async def chat_endpoint(payload: ChatMessageRequest, authorization: Optional[str] = Header(None)):
|
# УПРАВЛЕНИЕ МУЛЬТИЧАТАМИ (СЕССИЯМИ / ТЕМАМИ)
|
||||||
user_id = resolve_user_id(authorization, payload.user_id)
|
# ---------------------------------------------------------------------------
|
||||||
session_id = payload.session_id or "web_session_main"
|
|
||||||
user_msg = payload.message.strip()
|
@router.get("/sessions")
|
||||||
|
def get_chat_sessions_endpoint(current_user=Depends(get_current_user)):
|
||||||
|
"""Возвращает список сохраненных тем пользователя (до 15 штук)."""
|
||||||
|
user_id = getattr(current_user, "id", 1)
|
||||||
|
sessions = db_get_chat_sessions(user_id=user_id, limit=15)
|
||||||
|
return {"status": "success", "sessions": sessions}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/sessions")
|
||||||
|
def create_chat_session_endpoint(payload: CreateSessionRequest, current_user=Depends(get_current_user)):
|
||||||
|
"""Создает новую тему диалога с лимитом до 15 тем."""
|
||||||
|
user_id = getattr(current_user, "id", 1)
|
||||||
|
existing_sessions = db_get_chat_sessions(user_id=user_id, limit=20)
|
||||||
|
|
||||||
|
if len(existing_sessions) >= 15:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Достигнут лимит параллельных диалогов (максимум 15 тем). Удалите неактуальные темы."
|
||||||
|
)
|
||||||
|
|
||||||
|
session_id = payload.session_id or f"topic_{uuid.uuid4().hex[:8]}"
|
||||||
|
title = (payload.title or "Новый диалог").strip()
|
||||||
|
session = db_create_chat_session(session_id=session_id, title=title, user_id=user_id)
|
||||||
|
return {"status": "success", "session": session}
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/sessions/{session_id}")
|
||||||
|
def delete_chat_session_endpoint(session_id: str, current_user=Depends(get_current_user)):
|
||||||
|
"""Каскадное удаление темы и всех её сообщений."""
|
||||||
|
if not session_id or not session_id.strip():
|
||||||
|
raise HTTPException(status_code=400, detail="Не передан session_id")
|
||||||
|
|
||||||
|
db_delete_chat_session_cascade(session_id=session_id)
|
||||||
|
return {"status": "success", "message": f"Тема '{session_id}' успешно удалена"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/history")
|
||||||
|
def get_chat_history_endpoint(
|
||||||
|
session_id: str = Query("session_main"),
|
||||||
|
limit: int = Query(50),
|
||||||
|
current_user=Depends(get_current_user)
|
||||||
|
):
|
||||||
|
"""Возвращает историю сообщений заданной темы в хронологическом порядке."""
|
||||||
|
history = db_get_chat_history(session_id=session_id, limit=limit, include_ephemeral=False)
|
||||||
|
return {"status": "success", "session_id": session_id, "history": history}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# ОТПРАВКА СООБЩЕНИЙ И ЗАГРУЗКА ФАЙЛОВ
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@router.post("")
|
||||||
|
def chat_endpoint(
|
||||||
|
payload: ChatMessageRequest,
|
||||||
|
background_tasks: BackgroundTasks,
|
||||||
|
current_user=Depends(get_current_user)
|
||||||
|
):
|
||||||
|
user_id = getattr(current_user, "id", 1)
|
||||||
|
user_msg = payload.message.strip() if payload.message else ""
|
||||||
|
target_session = payload.session_id or "session_main"
|
||||||
|
|
||||||
if not user_msg:
|
if not user_msg:
|
||||||
raise HTTPException(status_code=400, detail="Пустое сообщение")
|
raise HTTPException(status_code=400, detail="Текст сообщения не может быть пустым")
|
||||||
|
|
||||||
|
# 1. Проверяем текущее название сессии ДО обновления
|
||||||
|
sessions = db_get_chat_sessions(user_id=user_id, limit=20)
|
||||||
|
current_session = next((s for s in sessions if s.get("id") == target_session), None)
|
||||||
|
curr_title = (current_session.get("title") or "").strip() if current_session else ""
|
||||||
|
|
||||||
|
# 2. Обновляем время активности
|
||||||
|
db_touch_chat_session(session_id=target_session, auto_title=user_msg, user_id=user_id)
|
||||||
|
|
||||||
|
# 3. Запускаем LLM-именование ТОЛЬКО если название еще стандартное (первый вопрос)
|
||||||
|
default_titles = ["Новый чат", "Основной чат", "Новый диалог", "Новая тема", ""]
|
||||||
|
if not current_session or curr_title in default_titles:
|
||||||
|
background_tasks.add_task(async_generate_topic_title, target_session, user_msg)
|
||||||
|
|
||||||
reply_text, history, action_payload = process_chat_message(
|
reply_text, history, action_payload = process_chat_message(
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
user_message=user_msg,
|
user_message=user_msg,
|
||||||
session_id=session_id
|
session_id=target_session
|
||||||
)
|
)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"user_id": user_id,
|
|
||||||
"session_id": session_id,
|
|
||||||
"response": reply_text,
|
"response": reply_text,
|
||||||
"action_payload": action_payload
|
"action_payload": action_payload
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@router.post("/chat/upload")
|
@router.post("/upload")
|
||||||
async def chat_upload_endpoint(
|
async def chat_upload_endpoint(
|
||||||
file: UploadFile = File(...),
|
file: UploadFile = File(...),
|
||||||
message: Optional[str] = Form(""),
|
message: Optional[str] = Form(None),
|
||||||
session_id: Optional[str] = Form("web_session_main"),
|
session_id: Optional[str] = Form("session_main"),
|
||||||
authorization: Optional[str] = Header(None)
|
current_user=Depends(get_current_user)
|
||||||
):
|
):
|
||||||
user_id = resolve_user_id(authorization, 1)
|
"""Прием и разбор документов в контексте выбранной темы диалога."""
|
||||||
file_path = os.path.join(UPLOAD_TMP_DIR, file.filename)
|
user_id = getattr(current_user, "id", 1)
|
||||||
|
target_session = session_id or "session_main"
|
||||||
|
|
||||||
with open(file_path, "wb") as buffer:
|
file_name = file.filename or f"upload_{uuid.uuid4().hex[:6]}.dat"
|
||||||
shutil.copyfileobj(file.file, buffer)
|
save_path = os.path.join(UPLOAD_DIR, file_name)
|
||||||
|
|
||||||
user_msg = (message or "").strip()
|
try:
|
||||||
msg_lower = user_msg.lower()
|
with open(save_path, "wb") as f:
|
||||||
fn_lower = file.filename.lower()
|
content = await file.read()
|
||||||
|
f.write(content)
|
||||||
|
|
||||||
# ⭐️ 1. ПРЯМАЯ ИЗОЛИРОВАННАЯ ОБРАБОТКА PDF/СКАНОВ В WORD ЧЕРЕЗ OFFICE МОДУЛЬ
|
parsed_context = parse_uploaded_file(save_path, file_name)
|
||||||
ocr_keywords = [
|
|
||||||
"распознай", "распознать", "в word", "в ворд", "для ворда", "для word",
|
|
||||||
"отформатируй", "текст для вставки", "извлеки текст", "сделай документ", "переведи в ворд"
|
|
||||||
]
|
|
||||||
|
|
||||||
if fn_lower.endswith(".pdf") and (any(k in msg_lower for k in ocr_keywords) or not user_msg):
|
# Обновляем активность темы
|
||||||
logger.info(f"[Office] Прямой запуск распознавания PDF в Word: {file.filename}")
|
db_touch_chat_session(session_id=target_session, auto_title=f"Файл: {file_name}", user_id=user_id)
|
||||||
from services.office.service import convert_pdf_to_word_service
|
|
||||||
from modules.web_api.llm.db_tools import db_save_chat_message, db_get_chat_history
|
|
||||||
|
|
||||||
# Сохраняем вопрос пользователя в историю
|
reply_text, history, action_payload = process_chat_message(
|
||||||
prompt_text = user_msg or f"Распознать документ {file.filename} для MS Word"
|
user_id=user_id,
|
||||||
db_save_chat_message(session_id, "user", prompt_text, is_ephemeral=0)
|
user_message=message.strip() if message else "",
|
||||||
|
file_context=parsed_context,
|
||||||
# Вызываем офисный сервис постраничного OCR и сборки DOCX
|
session_id=target_session
|
||||||
office_res = convert_pdf_to_word_service(file_path, file.filename)
|
|
||||||
|
|
||||||
reply_text = (
|
|
||||||
f"📄 **{office_res['message']}**\n\n"
|
|
||||||
f"**Фрагмент первой страницы документа:**\n"
|
|
||||||
f"```text\n{office_res['preview_text']}...\n```\n\n"
|
|
||||||
f"Файл готов к скачиванию и редактированию в MS Word."
|
|
||||||
)
|
)
|
||||||
db_save_chat_message(session_id, "assistant", reply_text, is_ephemeral=0)
|
|
||||||
|
|
||||||
action_payload = {
|
|
||||||
"type": "FILE_DOWNLOAD_CARD",
|
|
||||||
"filename": office_res["filename"],
|
|
||||||
"download_url": office_res["download_url"],
|
|
||||||
"tasks_count": f"{office_res['total_pages']} стр."
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"user_id": user_id,
|
|
||||||
"session_id": session_id,
|
|
||||||
"response": reply_text,
|
"response": reply_text,
|
||||||
"action_payload": action_payload
|
"action_payload": action_payload
|
||||||
}
|
}
|
||||||
|
|
||||||
# 2. Если это не задача OCR в Word — отправляем файл в обычный диалог агента
|
except Exception as e:
|
||||||
parsed = parse_uploaded_file(file_path, file.filename)
|
logger.exception(f"Ошибка при обработке файла {file_name}: {e}")
|
||||||
file_context = parsed.get("context_text", "")
|
raise HTTPException(status_code=500, detail=f"Ошибка обработки файла: {str(e)}")
|
||||||
image_b64 = parsed.get("image_b64")
|
|
||||||
|
|
||||||
prompt_for_agent = user_msg or f"Проанализируй документ {file.filename}"
|
def async_generate_topic_title(session_id: str, first_user_message: str):
|
||||||
reply_text, history, action_payload = process_chat_message(
|
"""Фоновая генерация естественного и осмысленного названия чата через LLM."""
|
||||||
user_id=user_id,
|
try:
|
||||||
user_message=prompt_for_agent,
|
from modules.web_api.llm.core.ollama_client import call_ollama_chat
|
||||||
file_context=file_context,
|
|
||||||
image_b64=image_b64,
|
|
||||||
session_id=session_id
|
|
||||||
)
|
|
||||||
|
|
||||||
return {
|
prompt = (
|
||||||
"status": "success",
|
"Ты — умный редактор диалогов. Проанализируй первое сообщение пользователя и сформулируй "
|
||||||
"user_id": user_id,
|
"красивое, грамматически связное и понятное человеку название для этого чата на русском языке.\n\n"
|
||||||
"session_id": session_id,
|
"Требования к названию:\n"
|
||||||
"response": reply_text,
|
"1. Живой русский язык, отражающий суть вопроса (не набор ключевых слов, а связное словосочетание).\n"
|
||||||
"action_payload": action_payload
|
"2. Длина: от 3 до 6 слов (не более 40-45 символов).\n"
|
||||||
}
|
"3. Первая буква заглавная, без точки в конце, строго без кавычек и спецсимволов.\n\n"
|
||||||
|
f"Сообщение пользователя: \"{first_user_message[:250]}\"\n"
|
||||||
|
"Название чата:"
|
||||||
|
)
|
||||||
|
|
||||||
|
res = call_ollama_chat(
|
||||||
|
messages=[{"role": "user", "content": prompt}],
|
||||||
|
is_vision=False,
|
||||||
|
timeout=30
|
||||||
|
)
|
||||||
|
raw_title = res.get("content", "").strip().replace('"', '').replace("'", "").replace("«", "").replace("»", "")
|
||||||
|
raw_title = raw_title.rstrip(" .!?:;")
|
||||||
|
|
||||||
|
# Если модель выдала префикс "Название: ...", отрезаем его
|
||||||
|
if ":" in raw_title and len(raw_title.split(":", 1)[0]) < 15:
|
||||||
|
raw_title = raw_title.split(":", 1)[1].strip()
|
||||||
|
|
||||||
|
if raw_title and len(raw_title) <= 60:
|
||||||
|
# Делаем первую букву заглавной
|
||||||
|
clean_title = raw_title[0].upper() + raw_title[1:] if len(raw_title) > 1 else raw_title.upper()
|
||||||
|
db_update_session_title(session_id, clean_title)
|
||||||
|
logger.info(f"[Topics] Чат {session_id} переименован LLM в человеческое название: '{clean_title}'")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"[Topics] Не удалось фоново сгенерировать заголовок для {session_id}: {e}")
|
||||||
+205
-275
@@ -3,326 +3,256 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>SCUD Orion AI Assistant</title>
|
<title>SCUD Orion AI — Интеллектуальный контроль доступа и 1С</title>
|
||||||
<script src="https://cdn.tailwindcss.com"></script>
|
<script src="https://cdn.tailwindcss.com"></script>
|
||||||
|
<script>
|
||||||
|
tailwind.config = {
|
||||||
|
theme: {
|
||||||
|
extend: {
|
||||||
|
colors: {
|
||||||
|
brand: {
|
||||||
|
50: '#eef2ff',
|
||||||
|
100: '#e0e7ff',
|
||||||
|
500: '#6366f1',
|
||||||
|
600: '#4f46e5',
|
||||||
|
700: '#4338ca',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
||||||
<link rel="icon" href="/favicon.ico" type="image/x-icon">
|
<link rel="stylesheet" href="/static/css/styles.css?v=2.6.0">
|
||||||
<style>
|
|
||||||
* { overflow-anchor: none !important; }
|
|
||||||
#chat-messages-container, main { overflow-anchor: none !important; }
|
|
||||||
#chat-messages-container { padding-bottom: clamp(400px, 85vh, 900px) !important; }
|
|
||||||
|
|
||||||
/* ⭐️ Комфортный размер шрифта в стиле Gemini */
|
|
||||||
#chat-messages-container .message-content,
|
|
||||||
#chat-messages-container .text-sm,
|
|
||||||
#chat-messages-container .text-xs,
|
|
||||||
#chat-messages-container p,
|
|
||||||
#chat-messages-container li {
|
|
||||||
font-size: 16px !important;
|
|
||||||
line-height: 1.65 !important;
|
|
||||||
color: #1e293b !important; /* slate-800 */
|
|
||||||
}
|
|
||||||
|
|
||||||
#chat-messages-container .user-chat-bubble .text-sm,
|
|
||||||
#chat-messages-container .user-chat-bubble p,
|
|
||||||
#chat-messages-container .user-chat-bubble div {
|
|
||||||
font-size: 16px !important;
|
|
||||||
line-height: 1.6 !important;
|
|
||||||
color: #ffffff !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
#chat-messages-container pre,
|
|
||||||
#chat-messages-container code {
|
|
||||||
font-size: 14.5px !important;
|
|
||||||
line-height: 1.5 !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.user-chat-bubble { scroll-margin-top: 24px !important; }
|
|
||||||
</style>
|
|
||||||
</head>
|
</head>
|
||||||
<body class="h-full flex flex-col font-sans antialiased text-slate-800 bg-slate-100 selection:bg-indigo-500 selection:text-white">
|
<body class="h-full flex overflow-hidden font-sans text-slate-800 antialiased selection:bg-indigo-500 selection:text-white">
|
||||||
|
|
||||||
<div id="app-container" class="flex-1 flex overflow-hidden w-full h-full">
|
<!-- ЛЕВЫЙ САЙДБАР (ШИРИНА 384px - 420px ДЛЯ УДОБСТВА ТАБЛИЦ И РЕЕСТРОВ) -->
|
||||||
|
<aside class="w-96 xl:w-[410px] bg-white border-r border-slate-200 flex flex-col shrink-0 h-full select-none shadow-sm z-20">
|
||||||
<!-- ЛЕВАЯ КОЛОНКА (САЙДБАР) -->
|
<div class="p-2 border-b border-slate-200 bg-slate-50/50">
|
||||||
<aside class="w-[420px] md:w-[500px] bg-white border-r border-slate-200 flex flex-col shrink-0 h-full shadow-sm z-10 select-none">
|
<div class="grid grid-cols-5 gap-1 p-1 bg-slate-200/60 rounded-xl">
|
||||||
|
<button data-tab="tasks" class="sidebar-tab-btn py-1.5 text-xs font-bold rounded-lg transition text-center flex flex-col items-center gap-0.5">
|
||||||
<!-- НАВИГАЦИОННЫЙ ТАБ-БАР -->
|
<i class="fa-solid fa-list-check text-xs"></i>
|
||||||
<div class="flex items-center justify-between border-b border-slate-200 bg-white px-1 py-1 shrink-0">
|
<span>Задачи</span>
|
||||||
<button data-tab="tasks" class="sidebar-tab-btn flex-1 py-2 text-center text-xs border-b-2 border-transparent text-slate-500 hover:text-indigo-600 transition">
|
|
||||||
<i class="fa-solid fa-list-check block text-sm mb-0.5"></i> Задачи
|
|
||||||
</button>
|
</button>
|
||||||
<button data-tab="snapshots" class="sidebar-tab-btn flex-1 py-2 text-center text-xs border-b-2 border-transparent text-slate-500 hover:text-indigo-600 transition">
|
<button data-tab="snapshots" class="sidebar-tab-btn py-1.5 text-xs font-bold rounded-lg transition text-center flex flex-col items-center gap-0.5">
|
||||||
<i class="fa-solid fa-camera block text-sm mb-0.5"></i> Срезы
|
<i class="fa-solid fa-camera text-xs"></i>
|
||||||
|
<span>Срезы</span>
|
||||||
</button>
|
</button>
|
||||||
<button data-tab="registries" class="sidebar-tab-btn flex-1 py-2 text-center text-xs border-b-2 border-transparent text-slate-500 hover:text-indigo-600 transition">
|
<button data-tab="registries" class="sidebar-tab-btn py-1.5 text-xs font-bold rounded-lg transition text-center flex flex-col items-center gap-0.5">
|
||||||
<i class="fa-solid fa-address-book block text-sm mb-0.5"></i> Реестры
|
<i class="fa-solid fa-address-book text-xs"></i>
|
||||||
|
<span>Реестры</span>
|
||||||
</button>
|
</button>
|
||||||
<button data-tab="prompts" class="sidebar-tab-btn flex-1 py-2 text-center text-xs border-b-2 border-transparent text-slate-500 hover:text-indigo-600 transition">
|
<button data-tab="prompts" class="sidebar-tab-btn py-1.5 text-xs font-bold rounded-lg transition text-center flex flex-col items-center gap-0.5">
|
||||||
<i class="fa-solid fa-terminal block text-sm mb-0.5"></i> Промпт
|
<i class="fa-solid fa-terminal text-xs"></i>
|
||||||
|
<span>Промпт</span>
|
||||||
</button>
|
</button>
|
||||||
<button data-tab="context" class="sidebar-tab-btn flex-1 py-2 text-center text-xs border-b-2 border-transparent text-slate-500 hover:text-indigo-600 transition">
|
<button data-tab="context" class="sidebar-tab-btn py-1.5 text-xs font-bold rounded-lg transition text-center flex flex-col items-center gap-0.5">
|
||||||
<i class="fa-solid fa-comments block text-sm mb-0.5"></i> Контекст
|
<i class="fa-solid fa-brain text-xs"></i>
|
||||||
|
<span>Контекст</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- РАБОЧИЕ ОБЛАСТИ ВКЛАДОК -->
|
<!-- ОСНОВНОЙ КОНТЕЙНЕР СОДЕРЖИМОГО САЙДБАРА -->
|
||||||
<div class="flex-1 overflow-y-auto p-2 flex flex-col gap-2">
|
<div id="sidebar-tab-content" class="flex-1 overflow-y-auto p-4 space-y-4">
|
||||||
<!-- 1. ЗАДАЧИ -->
|
<!-- 1. ЗАДАЧИ -->
|
||||||
<div id="sidebar-view-tasks" class="sidebar-view w-full h-full flex flex-col">
|
<div id="sidebar-view-tasks" class="sidebar-view">
|
||||||
<div id="tasks-list" class="space-y-2 flex-1"></div>
|
<div id="tasks-list"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 2. СРЕЗЫ И ОТЧЕТЫ -->
|
<!-- 2. СРЕЗЫ -->
|
||||||
<div id="sidebar-view-snapshots" class="sidebar-view w-full space-y-3 hidden">
|
<div id="sidebar-view-snapshots" class="sidebar-view hidden">
|
||||||
|
<div class="space-y-3">
|
||||||
<!-- ПЕРИОД ВЫБОРКИ СРЕЗОВ -->
|
<div class="p-3 bg-white border border-slate-200 rounded-xl shadow-xs space-y-2">
|
||||||
<div class="p-2.5 bg-slate-50 rounded-xl border border-slate-200 shadow-xs space-y-2">
|
|
||||||
<div class="flex items-center justify-between">
|
<div class="flex items-center justify-between">
|
||||||
<span class="text-[11px] font-bold text-slate-600 uppercase flex items-center gap-1.5">
|
<span class="text-xs font-bold text-slate-700">Создать срез</span>
|
||||||
<i class="fa-regular fa-calendar text-indigo-500"></i> Период срезов:
|
|
||||||
</span>
|
|
||||||
<button onclick="loadSnapshotsView()" class="text-xs text-indigo-600 hover:text-indigo-800 font-semibold flex items-center gap-1 transition">
|
|
||||||
<i class="fa-solid fa-rotate-right text-[10px]"></i> Найти
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="grid grid-cols-2 gap-2">
|
<div class="grid grid-cols-2 gap-2">
|
||||||
<div>
|
<input type="text" id="manual-snapshot-date" placeholder="ДД.ММ.ГГГГ" class="text-xs px-2.5 py-1.5 bg-slate-50 border border-slate-200 rounded-lg">
|
||||||
<label class="text-[10px] text-slate-400 block mb-0.5">С даты:</label>
|
<input type="text" id="manual-snapshot-time" placeholder="ЧЧ:ММ" class="text-xs px-2.5 py-1.5 bg-slate-50 border border-slate-200 rounded-lg">
|
||||||
<input type="date" id="snapshots-date-from" onchange="loadSnapshotsView()"
|
|
||||||
class="w-full text-xs px-2 py-1.5 bg-white border border-slate-200 rounded-lg text-slate-700 font-mono focus:outline-none focus:border-indigo-500 cursor-pointer">
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label class="text-[10px] text-slate-400 block mb-0.5">По дату:</label>
|
|
||||||
<input type="date" id="snapshots-date-to" onchange="loadSnapshotsView()"
|
|
||||||
class="w-full text-xs px-2 py-1.5 bg-white border border-slate-200 rounded-lg text-slate-700 font-mono focus:outline-none focus:border-indigo-500 cursor-pointer">
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center gap-1.5 pt-1 border-t border-slate-200/60">
|
<button id="btn-create-snapshot" onclick="createSnapshotManual()" class="w-full py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-bold transition flex items-center justify-center gap-1.5">
|
||||||
<button onclick="setSnapshotDatePreset('today')" class="px-2 py-0.5 text-[11px] bg-white border border-slate-200 hover:bg-slate-100 rounded-md text-slate-600 font-medium transition shadow-2xs">
|
<i class="fa-solid fa-camera"></i>
|
||||||
Сегодня
|
<span>Сделать срез</span>
|
||||||
</button>
|
|
||||||
<button onclick="setSnapshotDatePreset('yesterday')" class="px-2 py-0.5 text-[11px] bg-white border border-slate-200 hover:bg-slate-100 rounded-md text-slate-600 font-medium transition shadow-2xs">
|
|
||||||
Вчера
|
|
||||||
</button>
|
|
||||||
<button onclick="setSnapshotDatePreset('days3')" class="px-2 py-0.5 text-[11px] bg-white border border-slate-200 hover:bg-slate-100 rounded-md text-slate-600 font-medium transition shadow-2xs">
|
|
||||||
3 дня
|
|
||||||
</button>
|
|
||||||
<button onclick="setSnapshotDatePreset('days7')" class="px-2 py-0.5 text-[11px] bg-white border border-slate-200 hover:bg-slate-100 rounded-md text-slate-600 font-medium transition shadow-2xs">
|
|
||||||
7 дней
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Панель создания срезов -->
|
|
||||||
<div class="p-3 bg-white rounded-xl border border-slate-200 shadow-xs space-y-2">
|
|
||||||
<div class="text-[11px] font-bold text-slate-600 uppercase flex items-center gap-1.5">
|
|
||||||
<i class="fa-regular fa-clock text-indigo-500"></i> Создать срез на дату/время:
|
|
||||||
</div>
|
|
||||||
<div class="grid grid-cols-2 gap-2">
|
|
||||||
<input type="text" id="manual-snapshot-date" placeholder="ДД.ММ.ГГГГ" class="text-xs px-2.5 py-1.5 border border-slate-200 rounded-lg text-center font-mono">
|
|
||||||
<input type="text" id="manual-snapshot-time" placeholder="ЧЧ:ММ" class="text-xs px-2.5 py-1.5 border border-slate-200 rounded-lg text-center font-mono">
|
|
||||||
</div>
|
|
||||||
<button id="btn-create-snapshot" onclick="createSnapshotManual()" class="w-full py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-bold transition flex items-center justify-center gap-1.5">
|
|
||||||
<i class="fa-solid fa-camera"></i> Сделать срез
|
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Панель On-Demand генерации отчетов -->
|
<div class="p-2.5 bg-white border border-slate-200 rounded-xl shadow-xs space-y-2">
|
||||||
<div class="p-3 bg-white rounded-xl border border-slate-200 shadow-xs space-y-2">
|
<div class="flex items-center justify-between">
|
||||||
<div class="text-[11px] font-bold text-slate-700 uppercase flex items-center gap-1.5">
|
<span id="snapshots-count-badge" class="text-xs font-bold text-slate-700">Срезы в базе: 0</span>
|
||||||
<i class="fa-solid fa-file-excel text-emerald-600"></i> Сформировать отчет:
|
|
||||||
</div>
|
</div>
|
||||||
<div class="grid grid-cols-3 gap-2 mb-4">
|
<div class="grid grid-cols-4 gap-1">
|
||||||
<button onclick="generateReportDirect('SIMPLIFIED')" class="flex items-center justify-center gap-1.5 px-3 py-2 bg-blue-50 text-blue-700 border border-blue-200 rounded-lg text-xs font-semibold hover:bg-blue-100 transition-all shadow-sm">
|
<button onclick="setSnapshotDatePreset('today')" class="py-1 text-[10px] bg-slate-100 hover:bg-slate-200 text-slate-700 rounded font-medium">Сегодня</button>
|
||||||
📄 Упрощ.
|
<button onclick="setSnapshotDatePreset('yesterday')" class="py-1 text-[10px] bg-slate-100 hover:bg-slate-200 text-slate-700 rounded font-medium">Вчера</button>
|
||||||
</button>
|
<button onclick="setSnapshotDatePreset('days3')" class="py-1 text-[10px] bg-slate-100 hover:bg-slate-200 text-slate-700 rounded font-medium">3 дня</button>
|
||||||
<button onclick="generateReportDirect('DETAILED')" class="flex items-center justify-center gap-1.5 px-3 py-2 bg-purple-50 text-purple-700 border border-purple-200 rounded-lg text-xs font-semibold hover:bg-purple-100 transition-all shadow-sm">
|
<button onclick="setSnapshotDatePreset('days7')" class="py-1 text-[10px] bg-slate-100 hover:bg-slate-200 text-slate-700 rounded font-medium">7 дней</button>
|
||||||
📈 Детальн.
|
</div>
|
||||||
</button>
|
<div class="grid grid-cols-2 gap-2">
|
||||||
<button onclick="generateReportDirect('LATE_ARRIVALS')" class="flex items-center justify-center gap-1.5 px-3 py-2 bg-rose-50 text-rose-700 border border-rose-200 rounded-lg text-xs font-semibold hover:bg-rose-100 transition-all shadow-sm">
|
<input type="date" id="snapshots-date-from" class="text-xs px-2 py-1 bg-slate-50 border border-slate-200 rounded-lg">
|
||||||
⏰ Опоздания
|
<input type="date" id="snapshots-date-to" class="text-xs px-2 py-1 bg-slate-50 border border-slate-200 rounded-lg">
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex items-center justify-between pt-1">
|
<!-- Сетка отчетов без верхней Сводки (Сводка генерируется на плашках срезов) -->
|
||||||
<span id="snapshots-count-badge" class="text-xs font-bold text-slate-700">Срезы в базе: 0</span>
|
<div class="grid grid-cols-3 gap-2 mb-2">
|
||||||
<button onclick="loadSnapshotsView()" class="text-slate-400 hover:text-indigo-600 text-xs transition" title="Обновить список">
|
<button onclick="generateReportDirect('SIMPLIFIED')" class="flex items-center justify-center gap-1 px-2.5 py-1.5 bg-blue-50 text-blue-700 border border-blue-200 rounded-lg text-xs font-semibold hover:bg-blue-100 transition shadow-xs">
|
||||||
<i class="fa-solid fa-rotate-right"></i>
|
<i class="fa-solid fa-file-lines text-[11px]"></i> <span>Упрощ.</span>
|
||||||
|
</button>
|
||||||
|
<button onclick="generateReportDirect('DETAILED')" class="flex items-center justify-center gap-1 px-2.5 py-1.5 bg-purple-50 text-purple-700 border border-purple-200 rounded-lg text-xs font-semibold hover:bg-purple-100 transition shadow-xs">
|
||||||
|
<i class="fa-solid fa-chart-line text-[11px]"></i> <span>Детальн.</span>
|
||||||
|
</button>
|
||||||
|
<button onclick="generateReportDirect('LATE_ARRIVALS')" class="flex items-center justify-center gap-1 px-2.5 py-1.5 bg-rose-50 text-rose-700 border border-rose-200 rounded-lg text-xs font-semibold hover:bg-rose-100 transition shadow-xs">
|
||||||
|
<i class="fa-solid fa-clock text-[11px]"></i> <span>Опоздания</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="snapshots-list" class="space-y-2"></div>
|
<div id="snapshots-list" class="space-y-2"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 3. РЕЕСТРЫ -->
|
|
||||||
<div id="sidebar-view-registries" class="sidebar-view w-full space-y-3 hidden">
|
|
||||||
<div class="grid grid-cols-5 gap-1 p-1 bg-slate-200/60 rounded-xl">
|
|
||||||
<button data-subtab="exceptions" onclick="switchRegistrySubTab('exceptions')" class="registry-subtab-btn py-1 text-[10px] rounded-lg transition text-center flex items-center justify-center gap-1">
|
|
||||||
<i class="fa-solid fa-user-shield text-[9px]"></i> Искл.
|
|
||||||
</button>
|
|
||||||
<button data-subtab="remote" onclick="switchRegistrySubTab('remote')" class="registry-subtab-btn py-1 text-[10px] rounded-lg transition text-center flex items-center justify-center gap-1">
|
|
||||||
<i class="fa-solid fa-house-laptop text-[9px]"></i> Удален.
|
|
||||||
</button>
|
|
||||||
<button data-subtab="local_trip" onclick="switchRegistrySubTab('local_trip')" class="registry-subtab-btn py-1 text-[10px] rounded-lg transition text-center flex items-center justify-center gap-1">
|
|
||||||
<i class="fa-solid fa-location-dot text-[9px]"></i> Команд.
|
|
||||||
</button>
|
|
||||||
<button data-subtab="other" onclick="switchRegistrySubTab('other')" class="registry-subtab-btn py-1 text-[10px] rounded-lg transition text-center flex items-center justify-center gap-1">
|
|
||||||
<i class="fa-solid fa-clipboard-question text-[9px]"></i> Иное
|
|
||||||
</button>
|
|
||||||
<button data-subtab="schedules" onclick="switchRegistrySubTab('schedules')" class="registry-subtab-btn py-1 text-[10px] rounded-lg transition text-center flex items-center justify-center gap-1">
|
|
||||||
<i class="fa-solid fa-business-time text-[9px]"></i> Графики
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div id="registry-content-container" class="space-y-3"></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 4. ПРОМПТ -->
|
|
||||||
<div id="sidebar-view-prompts" class="sidebar-view w-full space-y-3 hidden">
|
|
||||||
<div class="flex items-center justify-between pb-1 border-b border-slate-200">
|
|
||||||
<span class="text-xs font-bold text-slate-800">Системный промпт (Ollama)</span>
|
|
||||||
<button onclick="loadPromptsView()" class="text-slate-400 hover:text-indigo-600 text-xs transition" title="Обновить">
|
|
||||||
<i class="fa-solid fa-rotate-right"></i>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div id="prompts-content-container" class="space-y-2"></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 5. КОНТЕКСТ -->
|
|
||||||
<div id="sidebar-view-context" class="sidebar-view w-full space-y-3 hidden">
|
|
||||||
<div class="flex items-center justify-between pb-1 border-b border-slate-200">
|
|
||||||
<span class="text-xs font-bold text-slate-800">Мониторинг сессии</span>
|
|
||||||
<button onclick="loadContextView()" class="text-slate-400 hover:text-indigo-600 text-xs transition" title="Обновить">
|
|
||||||
<i class="fa-solid fa-rotate-right"></i>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div id="context-content-container" class="space-y-2"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- ПОДВАЛ -->
|
<!-- 3. РЕЕСТРЫ (5 ПОДВКЛАДОК: ВКЛЮЧАЯ ГРАФИКИ РАБОТЫ) -->
|
||||||
<div class="p-3 border-t border-slate-200 bg-slate-50 flex items-center justify-between shrink-0">
|
<div id="sidebar-view-registries" class="sidebar-view hidden">
|
||||||
<div class="flex items-center gap-2.5 min-w-0">
|
<div class="grid grid-cols-5 gap-1 p-1 bg-slate-200/60 rounded-xl mb-3">
|
||||||
<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">
|
<button data-subtab="exceptions" onclick="switchRegistrySubTab('exceptions')" class="registry-subtab-btn py-1 text-[10px] font-bold rounded-lg text-slate-600 bg-white shadow-xs">Искл.</button>
|
||||||
<i class="fa-solid fa-user"></i>
|
<button data-subtab="remote" onclick="switchRegistrySubTab('remote')" class="registry-subtab-btn py-1 text-[10px] font-semibold rounded-lg text-slate-600">Удален.</button>
|
||||||
</div>
|
<button data-subtab="local_trip" onclick="switchRegistrySubTab('local_trip')" class="registry-subtab-btn py-1 text-[10px] font-semibold rounded-lg text-slate-600">Команд.</button>
|
||||||
<div class="min-w-0 flex flex-col">
|
<button data-subtab="other" onclick="switchRegistrySubTab('other')" class="registry-subtab-btn py-1 text-[10px] font-semibold rounded-lg text-slate-600">Иное</button>
|
||||||
<span id="user-display-name" class="text-xs font-bold text-slate-800 truncate">Пользователь</span>
|
<button data-subtab="schedules" onclick="switchRegistrySubTab('schedules')" class="registry-subtab-btn py-1 text-[10px] font-semibold rounded-lg text-slate-600">Графики</button>
|
||||||
<span id="user-display-role" class="text-[10px] text-slate-400">Оператор</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<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>
|
|
||||||
|
|
||||||
<div class="flex items-center gap-2">
|
|
||||||
<button onclick="window.openPresenceModal()" class="flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-emerald-50 hover:bg-emerald-100 text-emerald-700 text-xs font-bold border border-emerald-200 transition shadow-xs">
|
|
||||||
<i class="fa-solid fa-building-user text-xs"></i>
|
|
||||||
<span>Кто в здании</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<!-- ЛЕНТА ЧАТА -->
|
|
||||||
<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-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-[11px] font-bold text-indigo-600 uppercase tracking-wider mb-1">ИИ-ассистент SCUD Orion AI</div>
|
|
||||||
<div class="text-sm text-slate-700 leading-relaxed">
|
|
||||||
Привет! Вы можете задавать вопросы ассистенту, управлять системным промптом, сверять кадровые нестыковки СКУД и 1С или формировать срезы и отчеты.
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
<div id="registry-content-container"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- БЕЙДЖ ПРИКРЕПЛЕННОГО ФАЙЛА -->
|
<!-- 4. ПРОМПТ -->
|
||||||
<div id="file-attachment-preview" class="hidden max-w-4xl mx-auto w-full px-4 pt-2">
|
<div id="sidebar-view-prompts" class="sidebar-view hidden">
|
||||||
<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">
|
<div id="prompts-content-container"></div>
|
||||||
<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>
|
</div>
|
||||||
|
|
||||||
<!-- СТРОКА ВВОДА -->
|
<!-- 5. КОНТЕКСТ -->
|
||||||
<div class="px-4 py-3 bg-white border-t border-slate-200">
|
<div id="sidebar-view-context" class="sidebar-view hidden">
|
||||||
<div id="chat-input-box" class="max-w-4xl mx-auto w-full flex items-end gap-3 bg-slate-50 border border-slate-300 rounded-2xl px-4 py-2.5 transition focus-within:border-indigo-500 focus-within:bg-white focus-within:ring-2 focus-within:ring-indigo-100 shadow-xs">
|
<div id="context-content-container"></div>
|
||||||
<button type="button" onclick="document.getElementById('file-upload-input').click()" class="text-slate-400 hover:text-indigo-600 p-1.5 transition shrink-0 mb-0.5" title="Прикрепить файл">
|
|
||||||
<i class="fa-solid fa-paperclip text-base"></i>
|
|
||||||
</button>
|
|
||||||
<input type="file" id="file-upload-input" class="hidden" />
|
|
||||||
|
|
||||||
<textarea id="user-input" rows="1" placeholder="Задайте вопрос, отправьте команду (Enter — отправить, Shift+Enter — перенос)..."
|
|
||||||
class="flex-1 bg-transparent border-0 focus:outline-none text-[15.5px] text-slate-800 placeholder:text-slate-400 resize-none py-1 leading-6 min-h-[32px] max-h-36" style="height: 32px;"></textarea>
|
|
||||||
|
|
||||||
<button type="button" onclick="window.sendMessage()" class="w-8 h-8 rounded-xl bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white flex items-center justify-center shrink-0 shadow-sm transition mb-0.5">
|
|
||||||
<i class="fa-solid fa-paper-plane text-xs"></i>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- ПОЛНОЭКРАННЫЙ ОВЕРЛЕЙ DRAG & DROP -->
|
|
||||||
<div id="global-drag-overlay" class="fixed inset-0 bg-indigo-950/70 backdrop-blur-xs z-50 flex items-center justify-center p-8 hidden pointer-events-none transition-all">
|
|
||||||
<div class="border-3 border-dashed border-indigo-300 rounded-3xl w-full h-full flex flex-col items-center justify-center text-white gap-4 bg-indigo-900/40">
|
|
||||||
<div class="w-20 h-20 rounded-2xl bg-white/10 flex items-center justify-center shadow-lg backdrop-blur-md border border-white/20">
|
|
||||||
<i class="fa-solid fa-cloud-arrow-up text-4xl text-indigo-200"></i>
|
|
||||||
</div>
|
|
||||||
<div class="text-xl font-bold tracking-wide">Перетащите файл в окно для загрузки</div>
|
|
||||||
<div class="text-sm text-indigo-200">Поддерживаются PDF (документы и сканы), изображения, Excel, CSV, TXT</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- КОНТЕЙНЕР ДИНАМИЧЕСКИХ МОДАЛЬНЫХ ОКОН -->
|
<!-- ПОДВАЛ САЙДБАРА -->
|
||||||
|
<div class="p-3 border-t border-slate-200 flex items-center justify-between bg-slate-50">
|
||||||
|
<div class="flex items-center gap-2.5 min-w-0">
|
||||||
|
<div class="w-8 h-8 rounded-xl bg-indigo-100 text-indigo-700 flex items-center justify-center font-bold text-xs shrink-0">
|
||||||
|
<i class="fa-solid fa-user"></i>
|
||||||
|
</div>
|
||||||
|
<div class="min-w-0">
|
||||||
|
<div id="user-display-name" class="text-xs font-bold text-slate-800 truncate">Администратор</div>
|
||||||
|
<div id="user-display-role" class="text-[10px] text-slate-400">Система</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-1">
|
||||||
|
<button onclick="openProfileModal()" class="p-1.5 text-slate-400 hover:text-indigo-600 rounded-lg transition" title="Профиль">
|
||||||
|
<i class="fa-solid fa-gear text-sm"></i>
|
||||||
|
</button>
|
||||||
|
<button onclick="AuthManager.logout()" class="p-1.5 text-slate-400 hover:text-rose-600 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>
|
||||||
|
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<button onclick="window.openPresenceModal()" class="flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-emerald-50 hover:bg-emerald-100 text-emerald-700 text-xs font-bold border border-emerald-200 transition shadow-xs">
|
||||||
|
<i class="fa-solid fa-building-user text-xs"></i>
|
||||||
|
<span>Кто в здании</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div class="flex-1 flex overflow-hidden min-h-0 relative">
|
||||||
|
<div class="flex-1 flex flex-col h-full min-w-0">
|
||||||
|
<div id="chat-messages-container" class="flex-1 overflow-y-auto p-4 md:p-6 flex flex-col gap-4"></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>
|
||||||
|
|
||||||
|
<div class="px-4 py-3 bg-white border-t border-slate-200">
|
||||||
|
<div id="chat-input-box" class="max-w-4xl mx-auto w-full flex items-end gap-3 bg-slate-50 border border-slate-300 rounded-2xl px-4 py-2.5 transition focus-within:border-indigo-500 focus-within:bg-white focus-within:ring-2 focus-within:ring-indigo-100 shadow-xs">
|
||||||
|
<button type="button" onclick="document.getElementById('file-upload-input').click()" class="text-slate-400 hover:text-indigo-600 p-1.5 transition shrink-0 mb-0.5" title="Прикрепить файл">
|
||||||
|
<i class="fa-solid fa-paperclip text-base"></i>
|
||||||
|
</button>
|
||||||
|
<input type="file" id="file-upload-input" class="hidden" />
|
||||||
|
|
||||||
|
<textarea id="user-input" rows="1" placeholder="Задайте вопрос, отправьте команду (Enter — отправить, Shift+Enter — перенос)..."
|
||||||
|
class="flex-1 bg-transparent border-0 focus:outline-none placeholder:text-slate-400 resize-none py-1 leading-6 min-h-[32px] max-h-36 font-normal text-slate-800"
|
||||||
|
style="font-size: 15.5px; height: 32px;"></textarea>
|
||||||
|
|
||||||
|
<button type="button" onclick="window.sendMessage()" class="w-8 h-8 rounded-xl bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white flex items-center justify-center shrink-0 shadow-sm transition mb-0.5">
|
||||||
|
<i class="fa-solid fa-paper-plane text-xs"></i>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ПРАВАЯ ПАНЕЛЬ «ЧАТЫ» -->
|
||||||
|
<aside id="topics-sidebar" class="w-[280px] xl:w-[320px] bg-white border-l border-slate-200 flex flex-col shrink-0 h-full select-none shadow-xs">
|
||||||
|
<div class="p-3.5 border-b border-slate-200 flex items-center justify-between gap-2 bg-slate-50/50">
|
||||||
|
<div class="flex items-center gap-1.5">
|
||||||
|
<i class="fa-solid fa-comments text-indigo-600 text-xs"></i>
|
||||||
|
<span class="text-xs font-bold text-slate-800">Чаты</span>
|
||||||
|
<span id="topics-count-badge" class="text-[10px] font-semibold bg-indigo-50 text-indigo-700 px-1.5 py-0.5 rounded-full border border-indigo-200">0/15</span>
|
||||||
|
</div>
|
||||||
|
<button onclick="window.TopicsManager.createNewTopic()"
|
||||||
|
class="px-2.5 py-1 bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white rounded-lg text-xs font-bold transition flex items-center gap-1 shadow-xs">
|
||||||
|
<i class="fa-solid fa-plus text-[10px]"></i>
|
||||||
|
<span>Новый чат</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="topics-list-container" class="flex-1 overflow-y-auto p-2.5 space-y-1.5">
|
||||||
|
<div class="text-center py-8 text-xs text-slate-400">
|
||||||
|
<i class="fa-solid fa-spinner fa-spin mr-1"></i> Загрузка чатов...
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<!-- КОНТЕЙНЕР ДЛЯ МОДАЛЬНЫХ ОКОН -->
|
||||||
<div id="modals-container"></div>
|
<div id="modals-container"></div>
|
||||||
|
|
||||||
|
<!-- ПОДКЛЮЧЕНИЕ СКРИПТОВ -->
|
||||||
<script src="/static/js/auth.js?v=2.6.0"></script>
|
<script src="/static/js/auth.js?v=2.6.0"></script>
|
||||||
<script src="/static/js/tasks.js?v=2.6.0"></script>
|
|
||||||
<script src="/static/js/manual_absences.js?v=2.6.0"></script>
|
|
||||||
<script src="/static/js/snapshot_inspector.js?v=2.6.0"></script>
|
|
||||||
|
|
||||||
<script src="/static/js/sidebar/core.js?v=2.6.0"></script>
|
<script src="/static/js/sidebar/core.js?v=2.6.0"></script>
|
||||||
<script src="/static/js/sidebar/registries.js?v=2.6.0"></script>
|
<script src="/static/js/tasks.js?v=2.6.0"></script>
|
||||||
<script src="/static/js/sidebar/snapshots.js?v=2.6.0"></script>
|
<script src="/static/js/sidebar/snapshots.js?v=2.6.0"></script>
|
||||||
|
<script src="/static/js/sidebar/registries.js?v=2.6.0"></script>
|
||||||
<script src="/static/js/sidebar/prompts_context.js?v=2.6.0"></script>
|
<script src="/static/js/sidebar/prompts_context.js?v=2.6.0"></script>
|
||||||
|
|
||||||
<script src="/static/js/presence.js?v=2.6.0"></script>
|
|
||||||
|
|
||||||
<script src="/static/js/chat/task_widget.js?v=2.6.0"></script>
|
<script src="/static/js/chat/task_widget.js?v=2.6.0"></script>
|
||||||
|
<script src="/static/js/chat/topics.js?v=2.6.0"></script>
|
||||||
|
<script src="/static/js/chat/cards.js?v=2.6.0"></script>
|
||||||
<script src="/static/js/chat/core.js?v=2.6.0"></script>
|
<script src="/static/js/chat/core.js?v=2.6.0"></script>
|
||||||
|
<script src="/static/js/presence.js?v=2.6.0"></script>
|
||||||
|
<script src="/static/js/snapshot_inspector.js?v=2.6.0"></script>
|
||||||
|
<script src="/static/js/manual_absences.js?v=2.6.0"></script>
|
||||||
<script src="/static/js/app.js?v=2.6.0"></script>
|
<script src="/static/js/app.js?v=2.6.0"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -30,7 +30,8 @@ async function loadModals() {
|
|||||||
'profile_modal.html',
|
'profile_modal.html',
|
||||||
'admin_modal.html',
|
'admin_modal.html',
|
||||||
'snapshot_inspector_modal.html',
|
'snapshot_inspector_modal.html',
|
||||||
'presence_modal.html'
|
'presence_modal.html',
|
||||||
|
'confirm_modal.html'
|
||||||
];
|
];
|
||||||
|
|
||||||
const container = document.getElementById('modals-container');
|
const container = document.getElementById('modals-container');
|
||||||
@@ -102,6 +103,7 @@ async function handleLoginSubmit(e) {
|
|||||||
hideAuthModal();
|
hideAuthModal();
|
||||||
updateUIState();
|
updateUIState();
|
||||||
if (window.SidebarManager) SidebarManager.switchTab('tasks');
|
if (window.SidebarManager) SidebarManager.switchTab('tasks');
|
||||||
|
if (window.TopicsManager && typeof window.TopicsManager.init === 'function') window.TopicsManager.init();
|
||||||
} else {
|
} else {
|
||||||
const err = await res.json();
|
const err = await res.json();
|
||||||
if (errEl) {
|
if (errEl) {
|
||||||
@@ -249,7 +251,7 @@ async function deleteAdminUser(id, username) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// 4. ВСПОМОГАТЕЛЬНЫЕ ФОРМАТЕРЫ И МОДАЛКА УДАЛЕНЩИКОВ
|
// 4. ВСПОМОГАТЕЛЬНЫЕ ФОРМАТЕРЫ И МОДАЛКА УДАЛЕНЩИКОВ (ИЗ СНАПШОТА)
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
function dmyToYmd(str) {
|
function dmyToYmd(str) {
|
||||||
if (!str) return "";
|
if (!str) return "";
|
||||||
@@ -383,7 +385,7 @@ document.addEventListener("DOMContentLoaded", async () => {
|
|||||||
setupStaffAutocomplete(rwFioInput, "rw-fio-suggestions");
|
setupStaffAutocomplete(rwFioInput, "rw-fio-suggestions");
|
||||||
}
|
}
|
||||||
|
|
||||||
//3.1 Автокомплит для местных командировок и иного
|
// 3.1 Автокомплит для местных командировок и иного
|
||||||
const maFioInput = document.getElementById("manual-absence-fio-input");
|
const maFioInput = document.getElementById("manual-absence-fio-input");
|
||||||
if (maFioInput && typeof setupStaffAutocomplete === "function") {
|
if (maFioInput && typeof setupStaffAutocomplete === "function") {
|
||||||
setupStaffAutocomplete(maFioInput, "manual-absence-suggestions");
|
setupStaffAutocomplete(maFioInput, "manual-absence-suggestions");
|
||||||
@@ -399,11 +401,11 @@ document.addEventListener("DOMContentLoaded", async () => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. Проверка сессии пользователя
|
// 5. Проверка сессии пользователя и запуск менеджеров
|
||||||
if (IS_GUEST) {
|
if (IS_GUEST) {
|
||||||
hideAuthModal();
|
hideAuthModal();
|
||||||
updateUIState();
|
updateUIState();
|
||||||
} else if (AuthManager && AuthManager.isAuthenticated()) {
|
} else if (typeof AuthManager !== 'undefined' && AuthManager.isAuthenticated()) {
|
||||||
hideAuthModal();
|
hideAuthModal();
|
||||||
updateUIState();
|
updateUIState();
|
||||||
if (typeof loadTasks === "function") {
|
if (typeof loadTasks === "function") {
|
||||||
@@ -412,6 +414,9 @@ document.addEventListener("DOMContentLoaded", async () => {
|
|||||||
if (window.SidebarManager) {
|
if (window.SidebarManager) {
|
||||||
SidebarManager.init();
|
SidebarManager.init();
|
||||||
}
|
}
|
||||||
|
if (window.TopicsManager && typeof window.TopicsManager.init === "function") {
|
||||||
|
TopicsManager.init();
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
showAuthModal();
|
showAuthModal();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,189 @@
|
|||||||
|
/**
|
||||||
|
* ===============================================================================
|
||||||
|
* FILE: modules/web_api/static/js/chat/cards.js
|
||||||
|
* ROLE: Рендеринг специализированных карточек чата:
|
||||||
|
* - Скачивание Word-документов
|
||||||
|
* - Инспекция срезов (таблица сотрудников)
|
||||||
|
* - Инлайн-редакторы промпта и правил
|
||||||
|
* ===============================================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
window.ChatCardsRenderer = {
|
||||||
|
renderActionPayload(actionPayload) {
|
||||||
|
if (!actionPayload) return '';
|
||||||
|
|
||||||
|
if (actionPayload.type === 'SNAPSHOTS_CARD' && typeof renderSnapshotsCard === 'function') {
|
||||||
|
return renderSnapshotsCard(actionPayload.data);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (actionPayload.type === 'TASK_INTERACTIVE_CARD' && typeof renderInteractiveTaskCard === 'function') {
|
||||||
|
return renderInteractiveTaskCard(actionPayload.tasks);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (actionPayload.type === 'FILE_DOWNLOAD_CARD') {
|
||||||
|
const dlUrl = actionPayload.download_url || '#';
|
||||||
|
const fName = actionPayload.filename || 'document.docx';
|
||||||
|
const count = actionPayload.tasks_count || '';
|
||||||
|
return `
|
||||||
|
<div class="mt-3 p-3.5 bg-slate-50 border border-slate-200 rounded-xl flex items-center justify-between gap-3 shadow-xs">
|
||||||
|
<div class="flex items-center gap-3 min-w-0">
|
||||||
|
<div class="w-10 h-10 rounded-xl bg-blue-600 text-white flex items-center justify-center shrink-0 shadow-sm">
|
||||||
|
<i class="fa-solid fa-file-word text-lg"></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 ? count + ' · ' : ''}Документ MS Word (.docx)</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<a href="${dlUrl}" download="${escapeHtml(fName)}" target="_blank"
|
||||||
|
class="px-4 py-2.5 bg-emerald-600 hover:bg-emerald-700 active:bg-emerald-800 text-white font-bold rounded-xl text-xs shadow-sm transition flex items-center gap-2 shrink-0">
|
||||||
|
<i class="fa-solid fa-arrow-down-to-line text-sm text-white"></i>
|
||||||
|
<span class="text-white tracking-wide">Скачать файл</span>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
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('');
|
||||||
|
|
||||||
|
return `
|
||||||
|
<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>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (actionPayload.type === 'PROMPT_EDITOR') {
|
||||||
|
const draftText = actionPayload.raw_draft || actionPayload.baseline_prompt || '';
|
||||||
|
const editorId = 'prompt-editor-' + Date.now();
|
||||||
|
return `
|
||||||
|
<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>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (actionPayload.type === 'RULES_EDITOR') {
|
||||||
|
const draftText = actionPayload.raw_draft || actionPayload.baseline_prompt || '';
|
||||||
|
const editorId = 'rules-editor-' + Date.now();
|
||||||
|
return `
|
||||||
|
<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>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
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.submitPromptDraftToDiff = function(editorId) {
|
||||||
|
const textarea = document.getElementById(editorId);
|
||||||
|
if (!textarea) return;
|
||||||
|
const newText = textarea.value.trim();
|
||||||
|
if (!newText) {
|
||||||
|
alert("Текст системного промпта не может быть пустым");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const input = document.getElementById("user-input");
|
||||||
|
if (input) input.value = `action:save_draft_prompt:::${newText}`;
|
||||||
|
window.sendMessage();
|
||||||
|
};
|
||||||
|
|
||||||
|
window.submitRulesDraftToDiff = function(editorId) {
|
||||||
|
const textarea = document.getElementById(editorId);
|
||||||
|
if (!textarea) return;
|
||||||
|
const newText = textarea.value.trim();
|
||||||
|
if (!newText) {
|
||||||
|
alert("Правила не могут быть пустыми");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const input = document.getElementById("user-input");
|
||||||
|
if (input) input.value = `action:save_draft_rules:::${newText}`;
|
||||||
|
window.sendMessage();
|
||||||
|
};
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* ===============================================================================
|
* ===============================================================================
|
||||||
* FILE: modules/web_api/static/js/chat/core.js
|
* FILE: modules/web_api/static/js/chat/core.js
|
||||||
* ROLE: Ядро чата: полноэкранный Drag-and-Drop оверлей, авто-высота инпута (24px),
|
* ROLE: Ядро чата: сессии (TopicsManager), отправка сообщений,
|
||||||
* надежный расчет скролла вопроса к верху окна, крупный шрифт text-sm.
|
* индикатор загрузки, Drag-and-Drop и автоскролл.
|
||||||
* ===============================================================================
|
* ===============================================================================
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -25,7 +25,6 @@ function saveCommandToHistory(commandText) {
|
|||||||
chatHistoryIndex = -1;
|
chatHistoryIndex = -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ⭐️ ЕДИНАЯ ФУНКЦИЯ СКРОЛЛА: выравнивание вопроса к верхней границе
|
|
||||||
function scrollToUserMessageTop() {
|
function scrollToUserMessageTop() {
|
||||||
const container = document.getElementById("chat-messages-container");
|
const container = document.getElementById("chat-messages-container");
|
||||||
if (!container) return;
|
if (!container) return;
|
||||||
@@ -36,7 +35,6 @@ function scrollToUserMessageTop() {
|
|||||||
|
|
||||||
requestAnimationFrame(() => {
|
requestAnimationFrame(() => {
|
||||||
const targetScroll = targetEl.offsetTop - container.offsetTop - 12;
|
const targetScroll = targetEl.offsetTop - container.offsetTop - 12;
|
||||||
|
|
||||||
container.scrollTo({
|
container.scrollTo({
|
||||||
top: Math.max(0, targetScroll),
|
top: Math.max(0, targetScroll),
|
||||||
behavior: 'smooth'
|
behavior: 'smooth'
|
||||||
@@ -133,132 +131,11 @@ function appendAssistantMessage(text, buttons = [], actionPayload = null) {
|
|||||||
const container = document.getElementById("chat-messages-container");
|
const container = document.getElementById("chat-messages-container");
|
||||||
if (!container) return;
|
if (!container) return;
|
||||||
|
|
||||||
let payloadHtml = '';
|
const payloadHtml = window.ChatCardsRenderer
|
||||||
let isHtmlBody = false;
|
? window.ChatCardsRenderer.renderActionPayload(actionPayload)
|
||||||
|
: '';
|
||||||
|
|
||||||
if (actionPayload) {
|
const isHtmlBody = actionPayload && actionPayload.type === 'PROMPT_PREVIEW';
|
||||||
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 || 'document.docx';
|
|
||||||
const count = actionPayload.tasks_count || '';
|
|
||||||
payloadHtml = `
|
|
||||||
<div class="mt-3 p-3.5 bg-slate-50 border border-slate-200 rounded-xl flex items-center justify-between gap-3 shadow-xs">
|
|
||||||
<div class="flex items-center gap-3 min-w-0">
|
|
||||||
<div class="w-10 h-10 rounded-xl bg-blue-600 text-white flex items-center justify-center shrink-0 shadow-sm">
|
|
||||||
<i class="fa-solid fa-file-word text-lg"></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 ? count + ' · ' : ''}Документ MS Word (.docx)</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<a href="${dlUrl}" download="${escapeHtml(fName)}" target="_blank"
|
|
||||||
class="px-4 py-2.5 bg-emerald-600 hover:bg-emerald-700 active:bg-emerald-800 text-white font-bold rounded-xl text-xs shadow-sm transition flex items-center gap-2 shrink-0">
|
|
||||||
<i class="fa-solid fa-arrow-down-to-line text-sm text-white"></i>
|
|
||||||
<span class="text-white tracking-wide">Скачать файл</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 = '';
|
let buttonsHtml = '';
|
||||||
if (!actionPayload || (actionPayload.type !== 'PROMPT_EDITOR' && actionPayload.type !== 'RULES_EDITOR')) {
|
if (!actionPayload || (actionPayload.type !== 'PROMPT_EDITOR' && actionPayload.type !== 'RULES_EDITOR')) {
|
||||||
@@ -295,22 +172,6 @@ function appendAssistantMessage(text, buttons = [], actionPayload = null) {
|
|||||||
container.insertAdjacentHTML("beforeend", html);
|
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) {
|
window.sendChatAction = function(actionText) {
|
||||||
if (!actionText || !actionText.trim()) return;
|
if (!actionText || !actionText.trim()) return;
|
||||||
const input = document.getElementById("user-input");
|
const input = document.getElementById("user-input");
|
||||||
@@ -321,36 +182,6 @@ window.sendChatAction = function(actionText) {
|
|||||||
window.sendMessage();
|
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() {
|
window.sendMessage = async function() {
|
||||||
const input = document.getElementById("user-input");
|
const input = document.getElementById("user-input");
|
||||||
if (!input) return;
|
if (!input) return;
|
||||||
@@ -369,7 +200,10 @@ window.sendMessage = async function() {
|
|||||||
input.style.webkitMaskImage = 'none';
|
input.style.webkitMaskImage = 'none';
|
||||||
window.clearAttachedFile();
|
window.clearAttachedFile();
|
||||||
|
|
||||||
// 1. Отрисовка сообщения пользователя в ленте
|
const activeSessionId = (window.TopicsManager && typeof window.TopicsManager.getActiveSessionId === "function")
|
||||||
|
? window.TopicsManager.getActiveSessionId()
|
||||||
|
: "session_main";
|
||||||
|
|
||||||
if (!messageText.startsWith("action:save_draft_prompt:::") && !messageText.startsWith("action:save_draft_rules:::")) {
|
if (!messageText.startsWith("action:save_draft_prompt:::") && !messageText.startsWith("action:save_draft_rules:::")) {
|
||||||
appendUserMessage(
|
appendUserMessage(
|
||||||
messageText || (fileToSend ? `Прикреплен файл: ${fileToSend.name}` : ''),
|
messageText || (fileToSend ? `Прикреплен файл: ${fileToSend.name}` : ''),
|
||||||
@@ -379,10 +213,7 @@ window.sendMessage = async function() {
|
|||||||
appendUserMessage("Сформировать предпросмотр изменений");
|
appendUserMessage("Сформировать предпросмотр изменений");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Вставка лоадера
|
|
||||||
const loadingId = appendAssistantLoading();
|
const loadingId = appendAssistantLoading();
|
||||||
|
|
||||||
// 3. Вызов точного скролла
|
|
||||||
scrollToUserMessageTop();
|
scrollToUserMessageTop();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -391,13 +222,11 @@ window.sendMessage = async function() {
|
|||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append("file", fileToSend);
|
formData.append("file", fileToSend);
|
||||||
formData.append("message", messageText);
|
formData.append("message", messageText);
|
||||||
formData.append("session_id", "web_session_main");
|
formData.append("session_id", activeSessionId);
|
||||||
|
|
||||||
res = await fetch("/api/v1/chat/upload", {
|
res = await fetch("/api/v1/chat/upload", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: { "Authorization": AuthManager.getAuthHeaders()["Authorization"] },
|
||||||
"Authorization": AuthManager.getAuthHeaders()["Authorization"]
|
|
||||||
},
|
|
||||||
body: formData
|
body: formData
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -407,7 +236,7 @@ window.sendMessage = async function() {
|
|||||||
headers: AuthManager.getAuthHeaders(),
|
headers: AuthManager.getAuthHeaders(),
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
message: messageText || `Загружен файл: ${fileToSend.name}`,
|
message: messageText || `Загружен файл: ${fileToSend.name}`,
|
||||||
session_id: "web_session_main"
|
session_id: activeSessionId
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -417,7 +246,7 @@ window.sendMessage = async function() {
|
|||||||
headers: AuthManager.getAuthHeaders(),
|
headers: AuthManager.getAuthHeaders(),
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
message: messageText,
|
message: messageText,
|
||||||
session_id: "web_session_main"
|
session_id: activeSessionId
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -436,6 +265,14 @@ window.sendMessage = async function() {
|
|||||||
if (window.SidebarManager) {
|
if (window.SidebarManager) {
|
||||||
SidebarManager.renderContent();
|
SidebarManager.renderContent();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (window.TopicsManager && typeof window.TopicsManager.loadTopics === "function") {
|
||||||
|
window.TopicsManager.loadTopics();
|
||||||
|
// ⭐️ Повторный запрос через 2.5 сек, когда фоновая LLM завершит суммаризацию заголовка:
|
||||||
|
setTimeout(() => {
|
||||||
|
window.TopicsManager.loadTopics();
|
||||||
|
}, 2500);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
const err = await res.json().catch(() => ({}));
|
const err = await res.json().catch(() => ({}));
|
||||||
appendAssistantMessage(`⚠️ Ошибка сервера (${res.status}): ${err.detail || "Не удалось получить ответ"}`);
|
appendAssistantMessage(`⚠️ Ошибка сервера (${res.status}): ${err.detail || "Не удалось получить ответ"}`);
|
||||||
@@ -542,13 +379,10 @@ document.addEventListener("DOMContentLoaded", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let dragCounter = 0;
|
let dragCounter = 0;
|
||||||
|
|
||||||
window.addEventListener('dragenter', (e) => {
|
window.addEventListener('dragenter', (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
dragCounter++;
|
dragCounter++;
|
||||||
if (overlay) {
|
if (overlay) overlay.classList.remove('hidden');
|
||||||
overlay.classList.remove('hidden');
|
|
||||||
}
|
|
||||||
}, false);
|
}, false);
|
||||||
|
|
||||||
window.addEventListener('dragleave', (e) => {
|
window.addEventListener('dragleave', (e) => {
|
||||||
@@ -556,23 +390,16 @@ document.addEventListener("DOMContentLoaded", () => {
|
|||||||
dragCounter--;
|
dragCounter--;
|
||||||
if (dragCounter <= 0) {
|
if (dragCounter <= 0) {
|
||||||
dragCounter = 0;
|
dragCounter = 0;
|
||||||
if (overlay) {
|
if (overlay) overlay.classList.add('hidden');
|
||||||
overlay.classList.add('hidden');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}, false);
|
}, false);
|
||||||
|
|
||||||
window.addEventListener('dragover', (e) => {
|
window.addEventListener('dragover', (e) => { e.preventDefault(); }, false);
|
||||||
e.preventDefault();
|
|
||||||
}, false);
|
|
||||||
|
|
||||||
window.addEventListener('drop', (e) => {
|
window.addEventListener('drop', (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
dragCounter = 0;
|
dragCounter = 0;
|
||||||
if (overlay) {
|
if (overlay) overlay.classList.add('hidden');
|
||||||
overlay.classList.add('hidden');
|
|
||||||
}
|
|
||||||
|
|
||||||
const dt = e.dataTransfer;
|
const dt = e.dataTransfer;
|
||||||
if (dt && dt.files && dt.files[0]) {
|
if (dt && dt.files && dt.files[0]) {
|
||||||
handleFileSelected(dt.files[0]);
|
handleFileSelected(dt.files[0]);
|
||||||
|
|||||||
@@ -0,0 +1,286 @@
|
|||||||
|
/**
|
||||||
|
* ===============================================================================
|
||||||
|
* FILE: modules/web_api/static/js/chat/topics.js
|
||||||
|
* ROLE: Управление списком сессий чатов (до 15), мгновенный "Новый чат"
|
||||||
|
* и стильное встроенное подтверждение удаления без alert/confirm.
|
||||||
|
* ===============================================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
window.TopicsManager = (function() {
|
||||||
|
let activeSessionId = localStorage.getItem("scud_active_chat_session") || "session_main";
|
||||||
|
let sessionsCache = [];
|
||||||
|
let pendingDeleteSessionId = null;
|
||||||
|
|
||||||
|
function getActiveSessionId() {
|
||||||
|
return activeSessionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function init() {
|
||||||
|
await loadTopics();
|
||||||
|
await loadTopicHistory(activeSessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadTopics() {
|
||||||
|
const container = document.getElementById("topics-list-container");
|
||||||
|
const badge = document.getElementById("topics-count-badge");
|
||||||
|
if (!container) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/v1/chat/sessions", {
|
||||||
|
headers: AuthManager.getAuthHeaders()
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
if (res.status === 401) return;
|
||||||
|
container.innerHTML = `<div class="p-3 text-xs text-rose-500 text-center">Ошибка загрузки чатов (${res.status})</div>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
sessionsCache = data.sessions || [];
|
||||||
|
|
||||||
|
if (sessionsCache.length === 0) {
|
||||||
|
await createDefaultTopic();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const exists = sessionsCache.some(s => s.id === activeSessionId);
|
||||||
|
if (!exists && sessionsCache.length > 0) {
|
||||||
|
activeSessionId = sessionsCache[0].id;
|
||||||
|
localStorage.setItem("scud_active_chat_session", activeSessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (badge) {
|
||||||
|
badge.innerText = `${sessionsCache.length}/15`;
|
||||||
|
}
|
||||||
|
|
||||||
|
renderTopicsList();
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Ошибка загрузки списка чатов:", err);
|
||||||
|
container.innerHTML = `<div class="p-3 text-xs text-rose-500 text-center">Ошибка соединения с сервером</div>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createDefaultTopic() {
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/v1/chat/sessions", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
...AuthManager.getAuthHeaders(),
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
session_id: "session_main",
|
||||||
|
title: "Основной чат"
|
||||||
|
})
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
activeSessionId = "session_main";
|
||||||
|
localStorage.setItem("scud_active_chat_session", activeSessionId);
|
||||||
|
await loadTopics();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Не удалось создать базовый чат:", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderTopicsList() {
|
||||||
|
const container = document.getElementById("topics-list-container");
|
||||||
|
if (!container) return;
|
||||||
|
|
||||||
|
if (sessionsCache.length === 0) {
|
||||||
|
container.innerHTML = `<div class="p-4 text-xs text-slate-400 text-center">Нет активных чатов</div>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
container.innerHTML = sessionsCache.map(session => {
|
||||||
|
const isActive = session.id === activeSessionId;
|
||||||
|
const activeClasses = isActive
|
||||||
|
? "bg-indigo-50 border-indigo-200 text-indigo-900 shadow-xs"
|
||||||
|
: "bg-white hover:bg-slate-50 border-slate-200 text-slate-700";
|
||||||
|
|
||||||
|
const title = escapeHtml(session.title || "Новый чат");
|
||||||
|
const timeStr = session.updated_at ? (session.updated_at.split(" ")[1] || "").slice(0, 5) : "";
|
||||||
|
|
||||||
|
return `
|
||||||
|
<div class="topic-item group flex items-center justify-between p-2.5 rounded-xl border transition cursor-pointer ${activeClasses}"
|
||||||
|
onclick="window.TopicsManager.switchTopic('${session.id}')">
|
||||||
|
<div class="flex items-start gap-2.5 min-w-0 flex-1 pr-1">
|
||||||
|
<i class="fa-solid fa-message text-xs ${isActive ? 'text-indigo-600' : 'text-slate-400'} shrink-0 mt-1"></i>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<div class="text-xs font-semibold leading-snug text-slate-800 break-words"
|
||||||
|
title="${title}"
|
||||||
|
style="display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; word-break: break-word;">
|
||||||
|
${title}
|
||||||
|
</div>
|
||||||
|
<div class="text-[10px] text-slate-400 flex items-center gap-1.5 mt-1">
|
||||||
|
${timeStr ? `<span>${timeStr}</span>` : '<span>Недавно</span>'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button type="button"
|
||||||
|
onclick="event.stopPropagation(); window.TopicsManager.askDeleteTopic('${session.id}', '${escapeHtml(title)}')"
|
||||||
|
class="opacity-0 group-hover:opacity-100 p-1 text-slate-400 hover:text-rose-600 rounded transition shrink-0"
|
||||||
|
title="Удалить чат">
|
||||||
|
<i class="fa-solid fa-trash-can text-xs"></i>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}).join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function switchTopic(sessionId) {
|
||||||
|
if (!sessionId || sessionId === activeSessionId) return;
|
||||||
|
|
||||||
|
activeSessionId = sessionId;
|
||||||
|
localStorage.setItem("scud_active_chat_session", activeSessionId);
|
||||||
|
renderTopicsList();
|
||||||
|
await loadTopicHistory(sessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadTopicHistory(sessionId) {
|
||||||
|
const container = document.getElementById("chat-messages-container");
|
||||||
|
if (!container) return;
|
||||||
|
|
||||||
|
container.innerHTML = `
|
||||||
|
<div class="flex items-center justify-center py-12 text-xs text-slate-400 gap-2">
|
||||||
|
<i class="fa-solid fa-spinner fa-spin text-indigo-600 text-sm"></i>
|
||||||
|
<span>Загрузка сообщений...</span>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/v1/chat/history?session_id=${encodeURIComponent(sessionId)}&limit=50`, {
|
||||||
|
headers: AuthManager.getAuthHeaders()
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
const data = await res.json();
|
||||||
|
const history = data.history || [];
|
||||||
|
|
||||||
|
container.innerHTML = "";
|
||||||
|
|
||||||
|
container.insertAdjacentHTML("beforeend", `
|
||||||
|
<div class="flex gap-3 max-w-4xl mx-auto w-full">
|
||||||
|
<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-[11px] font-bold text-indigo-600 uppercase tracking-wider mb-1">ИИ-ассистент SCUD Orion AI</div>
|
||||||
|
<div class="text-sm text-slate-700 leading-relaxed">
|
||||||
|
Чат готов к работе. Вы можете задать вопрос по кадровому аудиту, сформировать срез или прикрепить документ.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`);
|
||||||
|
|
||||||
|
for (const msg of history) {
|
||||||
|
if (msg.role === "user") {
|
||||||
|
appendUserMessage(msg.content);
|
||||||
|
} else if (msg.role === "assistant") {
|
||||||
|
appendAssistantMessage(msg.content);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
container.scrollTop = container.scrollHeight;
|
||||||
|
|
||||||
|
} else {
|
||||||
|
container.innerHTML = `<div class="p-4 text-center text-xs text-rose-500">Не удалось загрузить историю диалога</div>`;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Ошибка загрузки истории сообщений:", e);
|
||||||
|
container.innerHTML = `<div class="p-4 text-center text-xs text-rose-500">Ошибка соединения при загрузке истории</div>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createNewTopic() {
|
||||||
|
if (sessionsCache.length >= 15) {
|
||||||
|
alert("Достигнут лимит параллельных диалогов (максимум 15 чатов). Удалите неактуальные чаты.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const newSessionId = `chat_${Date.now().toString(36)}`;
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/v1/chat/sessions", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
...AuthManager.getAuthHeaders(),
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
session_id: newSessionId,
|
||||||
|
title: "Новый чат"
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
activeSessionId = newSessionId;
|
||||||
|
localStorage.setItem("scud_active_chat_session", activeSessionId);
|
||||||
|
await loadTopics();
|
||||||
|
await loadTopicHistory(activeSessionId);
|
||||||
|
const input = document.getElementById("user-input");
|
||||||
|
if (input) input.focus();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Ошибка создания чата:", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function askDeleteTopic(sessionId, title) {
|
||||||
|
pendingDeleteSessionId = sessionId;
|
||||||
|
const modal = document.getElementById("confirm-modal");
|
||||||
|
const msgEl = document.getElementById("confirm-modal-message");
|
||||||
|
if (msgEl) msgEl.innerText = `Удалить диалог «${title}» и всю историю сообщений?`;
|
||||||
|
if (modal) modal.classList.remove("hidden");
|
||||||
|
}
|
||||||
|
|
||||||
|
function hideDeleteModal() {
|
||||||
|
pendingDeleteSessionId = null;
|
||||||
|
const modal = document.getElementById("confirm-modal");
|
||||||
|
if (modal) modal.classList.add("hidden");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function executeDeleteTopic() {
|
||||||
|
if (!pendingDeleteSessionId) return;
|
||||||
|
const sessionId = pendingDeleteSessionId;
|
||||||
|
hideDeleteModal();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/v1/chat/sessions/${encodeURIComponent(sessionId)}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
headers: AuthManager.getAuthHeaders()
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
sessionsCache = sessionsCache.filter(s => s.id !== sessionId);
|
||||||
|
if (activeSessionId === sessionId) {
|
||||||
|
activeSessionId = sessionsCache.length > 0 ? sessionsCache[0].id : "session_main";
|
||||||
|
localStorage.setItem("scud_active_chat_session", activeSessionId);
|
||||||
|
await loadTopicHistory(activeSessionId);
|
||||||
|
}
|
||||||
|
await loadTopics();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Ошибка удаления чата:", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ⭐️ Делегирование событий на document: срабатывает всегда, даже если модалка загрузилась позже!
|
||||||
|
document.addEventListener("click", (e) => {
|
||||||
|
if (e.target.closest("#confirm-modal-btn-cancel")) {
|
||||||
|
hideDeleteModal();
|
||||||
|
} else if (e.target.closest("#confirm-modal-btn-ok")) {
|
||||||
|
executeDeleteTopic();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
init,
|
||||||
|
loadTopics,
|
||||||
|
getActiveSessionId,
|
||||||
|
switchTopic,
|
||||||
|
createNewTopic,
|
||||||
|
askDeleteTopic
|
||||||
|
};
|
||||||
|
})();
|
||||||
@@ -121,7 +121,8 @@ function renderExceptionsView(exceptions) {
|
|||||||
|
|
||||||
let tags = '<span class="text-[11px] text-slate-400 italic">Список пуст</span>';
|
let tags = '<span class="text-[11px] text-slate-400 italic">Список пуст</span>';
|
||||||
if (list && list.length > 0) {
|
if (list && list.length > 0) {
|
||||||
tags = list.map(item => {
|
const sortedList = list.slice().sort((a, b) => String(a).localeCompare(String(b), 'ru'));
|
||||||
|
tags = sortedList.map(item => {
|
||||||
const val = escapeHtml(item);
|
const val = escapeHtml(item);
|
||||||
return '<span class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-lg text-xs font-medium ' + badgeClass + '">' +
|
return '<span class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-lg text-xs font-medium ' + badgeClass + '">' +
|
||||||
'<span>' + val + '</span>' +
|
'<span>' + val + '</span>' +
|
||||||
@@ -192,7 +193,9 @@ async function loadRemoteWorkersView() {
|
|||||||
try {
|
try {
|
||||||
const res = await fetch('/api/v1/remote-workers', { headers: AuthManager.getAuthHeaders() });
|
const res = await fetch('/api/v1/remote-workers', { headers: AuthManager.getAuthHeaders() });
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
const workers = data.workers || [];
|
const workers = (data.workers || []).slice().sort((a, b) =>
|
||||||
|
String(a.fio || '').localeCompare(String(b.fio || ''), 'ru')
|
||||||
|
);
|
||||||
|
|
||||||
let listHtml = '';
|
let listHtml = '';
|
||||||
if (workers.length === 0) {
|
if (workers.length === 0) {
|
||||||
@@ -277,7 +280,9 @@ async function loadManualAbsencesView(type) {
|
|||||||
headers: AuthManager.getAuthHeaders()
|
headers: AuthManager.getAuthHeaders()
|
||||||
});
|
});
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
const items = data.items || [];
|
const items = (data.items || []).slice().sort((a, b) =>
|
||||||
|
String(a.fio || '').localeCompare(String(b.fio || ''), 'ru')
|
||||||
|
);
|
||||||
|
|
||||||
let listHtml = '';
|
let listHtml = '';
|
||||||
if (items.length === 0) {
|
if (items.length === 0) {
|
||||||
@@ -453,7 +458,9 @@ async function loadSchedulesView() {
|
|||||||
const res = await fetch('/api/v1/schedules/employees', { headers: AuthManager.getAuthHeaders() });
|
const res = await fetch('/api/v1/schedules/employees', { headers: AuthManager.getAuthHeaders() });
|
||||||
if (!res.ok) throw new Error('Ошибка сети');
|
if (!res.ok) throw new Error('Ошибка сети');
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
allEmployeesSchedulesCache = data.items || [];
|
allEmployeesSchedulesCache = (data.items || []).slice().sort((a, b) =>
|
||||||
|
String(a.fio || '').localeCompare(String(b.fio || ''), 'ru')
|
||||||
|
);
|
||||||
renderSchedulesList(allEmployeesSchedulesCache);
|
renderSchedulesList(allEmployeesSchedulesCache);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
container.innerHTML = '<div class="text-center py-8 text-rose-500 text-xs">Не удалось загрузить графики сотрудников</div>';
|
container.innerHTML = '<div class="text-center py-8 text-rose-500 text-xs">Не удалось загрузить графики сотрудников</div>';
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<div id="confirm-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-5 flex flex-col gap-4 animate-in fade-in zoom-in-95 duration-150">
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<div class="w-10 h-10 rounded-xl bg-rose-50 text-rose-600 flex items-center justify-center font-bold text-lg border border-rose-200 shrink-0">
|
||||||
|
<i class="fa-solid fa-trash-can text-sm"></i>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 class="text-sm font-bold text-slate-800" id="confirm-modal-title">Удаление чата</h3>
|
||||||
|
<p class="text-xs text-slate-500 mt-0.5" id="confirm-modal-message">Удалить этот диалог и всю историю сообщений?</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-end gap-2 pt-2 border-t border-slate-100">
|
||||||
|
<button type="button" id="confirm-modal-btn-cancel" class="px-3.5 py-1.5 text-xs text-slate-600 rounded-lg hover:bg-slate-100 font-medium transition">
|
||||||
|
Отмена
|
||||||
|
</button>
|
||||||
|
<button type="button" id="confirm-modal-btn-ok" class="px-4 py-1.5 bg-rose-600 hover:bg-rose-700 text-white rounded-lg text-xs font-bold shadow-xs transition">
|
||||||
|
Удалить
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@@ -196,7 +196,7 @@ def get_manual_absences_list(absence_type: Optional[str] = None) -> List[Dict[st
|
|||||||
if absence_type:
|
if absence_type:
|
||||||
query += " WHERE absence_type = ?"
|
query += " WHERE absence_type = ?"
|
||||||
params.append(absence_type)
|
params.append(absence_type)
|
||||||
query += " ORDER BY id DESC"
|
query += " ORDER BY fio COLLATE NOCASE ASC"
|
||||||
|
|
||||||
cursor.execute(query, params)
|
cursor.execute(query, params)
|
||||||
rows = cursor.fetchall()
|
rows = cursor.fetchall()
|
||||||
|
|||||||
Reference in New Issue
Block a user