Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4774c8f3e1 | ||
|
|
52db96a9dc | ||
|
|
676437a958 | ||
|
|
d4a248dc33 | ||
|
|
09bd66923b | ||
|
|
b5c993486d |
Binary file not shown.
@@ -23,7 +23,7 @@ if NOW.weekday() == 0:
|
||||
else:
|
||||
DATE_YESTERDAY = (NOW - timedelta(days=1)).strftime("%d.%m.%Y")
|
||||
|
||||
OLLAMA_URL = "http://10.121.17.227:11434/api/generate"
|
||||
OLLAMA_URL = "http://192.168.11.111:11434/api/generate"
|
||||
OLLAMA_MODEL = "qwen2.5:14b"
|
||||
MODEL_NAME = OLLAMA_MODEL
|
||||
|
||||
|
||||
+71
-1
@@ -186,11 +186,81 @@ def init_all_tables() -> None:
|
||||
);
|
||||
""")
|
||||
|
||||
# 6. Индексы
|
||||
# 6. Реестры ручных отсутствий
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS manual_absences (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
absence_type TEXT NOT NULL, -- 'LOCAL_TRIP' или 'OTHER'
|
||||
fio TEXT NOT NULL,
|
||||
fio_clean TEXT NOT NULL,
|
||||
department TEXT DEFAULT '',
|
||||
position TEXT DEFAULT '',
|
||||
date_start TEXT, -- 'YYYY-MM-DD'
|
||||
date_end TEXT, -- 'YYYY-MM-DD'
|
||||
reason TEXT NOT NULL,
|
||||
comment TEXT DEFAULT '',
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
""")
|
||||
|
||||
# 7. ГРАФИКИ РАБОТЫ И РЕЖИМЫ (Справочники и привязка сотрудников)
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS work_schedule_templates (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
code TEXT UNIQUE NOT NULL, -- Код шаблона, например 'OFFICE_0900_1730'
|
||||
name TEXT NOT NULL, -- Название шаблона
|
||||
work_mode TEXT DEFAULT 'OFFICE', -- 'OFFICE', 'REMOTE', 'HYBRID', 'MATERNITY'
|
||||
norm_hours REAL NOT NULL DEFAULT 8.0, -- Норма рабочих часов в день (8.0, 4.0, 7.0 и т.д.)
|
||||
time_start TEXT, -- '09:00' или NULL (для гибких графиков)
|
||||
time_end TEXT, -- '17:30' или NULL
|
||||
lunch_break_minutes INTEGER DEFAULT 30, -- Обеденный перерыв в минутах
|
||||
is_shift INTEGER DEFAULT 0, -- 1 для сменных дежурств (22ч и т.д.)
|
||||
description TEXT, -- Дополнительное описание
|
||||
is_active INTEGER DEFAULT 1,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
""")
|
||||
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS employee_schedules (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
fio TEXT NOT NULL,
|
||||
fio_clean TEXT NOT NULL,
|
||||
department TEXT,
|
||||
position TEXT,
|
||||
schedule_template_id INTEGER NOT NULL,
|
||||
doc_basis TEXT, -- 'ТД от 14.02.2019', 'ДС от 09.01.2023'
|
||||
comment TEXT, -- Дни офиса при гибриде, специфика уборки и т.д.
|
||||
date_from TEXT DEFAULT '2026-01-01', -- Дата начала действия (YYYY-MM-DD)
|
||||
date_to TEXT DEFAULT NULL, -- Дата окончания (NULL = бессрочно)
|
||||
is_active INTEGER DEFAULT 1,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (schedule_template_id) REFERENCES work_schedule_templates(id),
|
||||
UNIQUE(fio_clean, date_from)
|
||||
);
|
||||
""")
|
||||
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS late_arrival_explanations (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
log_date TEXT NOT NULL, -- 'ДД.ММ.ГГГГ'
|
||||
fio_clean TEXT NOT NULL,
|
||||
reason TEXT NOT NULL, -- 'транспортная обстановка', 'семейные обстоятельства'
|
||||
approved_by TEXT, -- Кто согласовал (ГД, Руководитель)
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(log_date, fio_clean)
|
||||
);
|
||||
""")
|
||||
|
||||
# 8. Индексы
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_scud_date ON scud_logs(log_date);")
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_scud_fio ON scud_logs(fio_clean);")
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_mapping_scud ON person_identity_mapping(scud_fio);")
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_raw_events_date_hoz ON scud_events_raw(log_date, hoz_organ);")
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_raw_events_date_time ON scud_events_raw(log_date, time_val);")
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_manual_abs_dates ON manual_absences(date_start, date_end);")
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_manual_abs_fio ON manual_absences(fio_clean);")
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_emp_sched_fio ON employee_schedules(fio_clean);")
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_late_expl_date ON late_arrival_explanations(log_date);")
|
||||
|
||||
conn.commit()
|
||||
Binary file not shown.
@@ -11,3 +11,5 @@ fio,department,reason,date_from,date_to
|
||||
Кожокарь Татьяна Юрьевна,Все,Удаленная работа,,
|
||||
Субетто Юлия Викторовна,Все,Удаленная работа,,
|
||||
Чуркина Елена Геннадьевна,Все,Удаленная работа,,
|
||||
Сергиенко Игорь Сергеевич,Управление главных инженеров проектов №1,Удаленная работа,,
|
||||
Алирзаев Вадим Октаевич,Отдел автоматизации,Удаленная работа,19.10.2026,
|
||||
|
||||
|
+20
-179
@@ -5,12 +5,32 @@
|
||||
## [Unreleased]
|
||||
|
||||
### ✨ Добавлено (Added)
|
||||
- **Управление отчетом «Сводка» на плашках срезов:**
|
||||
- Кнопка «Сводка» перенесена из общей шапки сайдбара непосредственно в карточки каждого зафиксированного среза СКУД.
|
||||
- Поддержка прямой привязки параметров `snapshot_id` и `target_time` в генераторе `svodka_generator.py` и роутере `reports.py`.
|
||||
- **Учет индивидуальных графиков работы в Ежедневной сводке:**
|
||||
- Интеграция реестра `employee_schedules` в конвейер слияния `merger.py`.
|
||||
- Внедрение отдельного сводного блока в Excel-книге «Смена не началась (по графику позже)» с указанием планового времени выхода (например, Петренюк — 12:30).
|
||||
- Внедрен 15-минутный люфт (grace period) от времени начала смены, исключающий ложное попадание сотрудников в категорию «неизвестно».
|
||||
- **Изолированный домен работы с документами (`services/office/`):**
|
||||
- Создан специализированный пакет для постраничной обработки многостраничных PDF и сканов без ограничений контекста диалога.
|
||||
- Автоматическая сборка распознанного текста в файл Microsoft Word (`.docx`) со стандартизированным оформлением.
|
||||
- Интеграция с роутером чата и выдача контрастной карточки скачивания документа.
|
||||
|
||||
### 🛡️ Исправлено (Fixed)
|
||||
- **Калибровка физической модели оснастки «Кто в здании» (`presence_service.py`):**
|
||||
- Устранено залипание статической даты `DATE_TODAY` в долгоживущем процессе `uvicorn` за счет динамического вычисления текущего числа сервера (`datetime.now()`).
|
||||
- Приведение запроса сырых событий `SQL_RAW_EVENTS_QUERY` к единому двухконтурному стандарту с отсечением паразитных транзитных касаний правого турникета (`DoorIndex = 2`) для офисного персонала.
|
||||
- Устранена ошибка приоритета статуса флигеля: теперь физический выход сотрудника (`Direction == 'OUT'`) гарантированно переводит статус в «Вышел» даже при наличии прав доступа во флигель.
|
||||
- Ликвидирован жесткий хардкод лаборатории ИГТЛЛ в коде сервиса; привязка к флигелю переведена строго на реляционный реестр `exceptions_registry`.
|
||||
|
||||
### 📝 Запланировано (Planned)
|
||||
- **Параллельный изолированный тестовый стенд (`TASK-41`):**
|
||||
- Развертывание Staging-окружения на порту 8001 (`scud_orion_ai_dev.db`) для безопасной обкатки эмбеддингов и RAG без риска сбоев в пилотной эксплуатации.
|
||||
- **Интеллектуальное управление реестрами и периодические правила (`TASK-38`):**
|
||||
- Добавление нативного инструмента LLM для регистрации повторяющихся кадровых событий (например, «каждый вторник в командировке») с хранением в таблице `registry_recurring_rules`.
|
||||
- **Семантический роутер на базе эмбеддингов (`TASK-39`, `TASK-40`):**
|
||||
- Внедрение компактной векторной модели для сверхбыстрой классификации интентов (<100 мс) и нечеткого сопоставления сотрудников СКУД ⟷ 1С без нагрузки на генеративную LLM.
|
||||
- **Двухфазный OCR-конвейер рукописных виз и резолюций (`services/office/`):**
|
||||
- Рендеринг сканов в высоком разрешении (`250–300 DPI`) для точного захвата линий чернил.
|
||||
- Фаза 2 (Refiner на `qwen2.5:14b`): автоматическое устранение артефактов OCR, склейка абзацев и преобразование списков в таблицы Word.
|
||||
@@ -82,17 +102,6 @@
|
||||
- **Математический расчет временных границ срезов:**
|
||||
- Перевод формирования `@EndDate` в `services/scud_export.py` на цепочку функций `DATEADD` от `@StartDate`, устраняющий зависимость от регионального формата даты (`DMY` vs `MDY`).
|
||||
|
||||
## [Unreleased] - 2026-09-07
|
||||
|
||||
### Добавлено
|
||||
- Механизм Gemini-скроллинга диалогового окна: функция `scrollToUserMessageTop` в `core.js` автоматически поднимает отправленный вопрос к верхнему срезу экрана, скрывая громоздкие предыдущие ответы.
|
||||
- CSS-отступ `padding-bottom: 80vh` у `#chat-messages-container`, гарантирующий свободное вертикальное пространство для прокрутки без сдвига строки ввода.
|
||||
- Пункт 2.9 системного промпта, жестко обязывающий модель вызывать нативный инструмент `db_get_rules` при запросах Базы Знаний и регламентов вместо текстовой имитации.
|
||||
|
||||
### Запланировано
|
||||
- Рефакторинг интерпретации аппаратных кодов турникетов PERCO в `services/scud_export.py`: разделение логики разрешения прохода (`Event 28`) и факта проворота створки (`Event 32`), приоритет направления по `log.Mode` (1 — вход, 2 — выход) для устранения фантомных выходов.
|
||||
- Создание DDL-схемы и таблицы `scud_events_raw` в SQLite для гранулярного хранения всех внутридневных перемещений сотрудников (база для учета перекуров и инструмента «Кто в здании»).
|
||||
|
||||
## [0.9.5] - 2026-08-28
|
||||
|
||||
### Добавлено
|
||||
@@ -107,39 +116,6 @@
|
||||
- Устранена системная ошибка структуры OpenXML (`errorXXXXXX_01.xml`, «Обнаружена ошибка в части содержимого книги...»), возникавшая при открытии сгенерированных отчетов в MS Excel.
|
||||
- Восстановлены сворачиваемые интерактивные категории с кнопками `[+]` / `[-]` в файле ежедневной сводки (`outline_settings(symbols_below=False)`).
|
||||
|
||||
## [Unreleased] - 2026-08-28
|
||||
|
||||
### Fixed
|
||||
- **Генерация Excel-книг (`services/excel_exporter.py`, `services/scud_export.py`):** полный перевод экспорта с `openpyxl` на `xlsxwriter`, что устранило хроническую ошибку структуры OpenXML («В книге обнаружено нечитаемое содержимое...»).
|
||||
- **Группировки в Сводке:** восстановлено корректное отображение интерактивных кнопок `[+]`/`[-]` и сворачивание категорий по умолчанию (`outline_settings`, `level=1`, `collapsed=True`).
|
||||
- **Верстка и пропорции Детального отчета:** центрирование столбца «Подразделение», калибровка ширины колонок «ФИО» (+10%), «Первая активность» и «Отклонение от нормы» для плотного размещения таблицы на одном экране без горизонтальной прокрутки.
|
||||
- **Безопасное сохранение при блокировках:** внедрена функция `safe_close_workbook` для фонового сохранения резервных копий с timestamp, если файл открыт пользователем в Excel.
|
||||
- **Сетевое копирование 1С (`services/share_copier.py`):** замена `shutil.copy2` на `shutil.copyfile` для устранения сбоя `[Errno 1] Operation not permitted` при работе с SMB/CIFS-шарой.
|
||||
|
||||
## [Unreleased] - 2026-08-28
|
||||
|
||||
### Fixed
|
||||
- **Инкремент Snapshot ID (`core/repositories/scud_repo.py`):** заменена строковая сортировка `ORDER BY snapshot_id DESC` на целочисленный парсинг суффиксов, что устранило залипание номеров снапшотов (`-002`).
|
||||
|
||||
### Added
|
||||
- **Режим тихих почасовых срезов (`--export-only`):** быстрый экспорт данных СКУД напрямую в SQLite без построения отчетов для интеграции в cron.
|
||||
- **Интерактивный справочник CLI (`main_etl.py`):** полный баннер справки по всем аргументам (`-h`, `--help`, `help`).
|
||||
- **Автоматическая ротация промежуточных срезов (`services/snapshots/retention.py`):** ночная очистка устаревших почасовых срезов старше 2 дней с сохранением полуденного (`13:00`) и итогового `Y` (`23:59:59`).
|
||||
|
||||
## [Unreleased] - 2026-08-28
|
||||
|
||||
### Added
|
||||
- **Smart Snap-to-Grid Finder (`services/snapshots/finder.py`):** интеллектуальный поиск ближайшего среза СКУД в SQLite с допуском ±20 минут и поддержкой On-Demand экспорта из MS SQL при отсутствии готового среза.
|
||||
- **Параметр `--time` в `main_etl.py`:** возможность формирования оперативной сводки на произвольное время суток.
|
||||
- **Раздельные генераторы отчетов:**
|
||||
- `services/scud_etl/svodka_generator.py` — оперативная сводка за сегодня с группировками.
|
||||
- `services/scud_etl/otchet_generator.py` — суточный детальный отчет за вчера по финишному срезу `Y` (23:59:59) с учетом рабочего норматива 8.5 ч.
|
||||
|
||||
### Changed
|
||||
- **Фиксация финишного среза `Y` на `23:59:59`:** обновлено время снапшота в `services/scud_export.py`, `core/repositories/scud_repo.py` и `services/scud_etl/pipeline.py` с сохранением обратной совместимости со срезами на `22:00:00`.
|
||||
- **Путь виртуального окружения в `run_cron_etl.sh`:** скорректирован на актуальный `/home/puh/projects/scud_ai/venv/bin/python`.
|
||||
- **Игнорирование временных файлов SQLite:** добавлены `*.db-shm` и `*.db-wal` в `.gitignore`.
|
||||
|
||||
## [3.2.0] — 2026-08-27
|
||||
### 🧠 Интеллектуальный арбитраж личностей, агрегация мульти-пропусков и автозакрытие смен
|
||||
|
||||
@@ -149,140 +125,5 @@
|
||||
- Поддержка мгновенного извлечения проверенных сопоставлений в `merger.py` (время выборки < 1 мс).
|
||||
- **Агрегация дубликатов пропусков и мульти-учеток СКУД (`merger.py`)**:
|
||||
- Функция `aggregate_scud_by_person` объединяет все карты/записи одного физлица: фиксирует самый ранний вход `min(valid_ins)`, самый поздний выход `max(valid_outs)` и итоговый статус присутствия.
|
||||
- Исключено ложное попадание сотрудников с несколькими пропусками (например, Кондрашова Е.В.) в категорию «неизвестно».
|
||||
- **Интеллектуальный выбор ставки совместителей 1С (`merger.py`)**:
|
||||
- Функция `select_best_zup_position` сопоставляет множественные должности одного сотрудника в 1С со СКУД и подтягивает ставку того подразделения, где человек находится физически.
|
||||
- **Автозакрытие незакрытых смен по Правилу 8.5ч (`excel_exporter.py`)**:
|
||||
- При наличии утреннего входа и отсутствии вечернего выхода у офисных сотрудников в детальном отчете за вчера расчетный выход ставится как `Вход + 8ч 30мин`, норма 8 часов и нулевое отклонение `0:00` (вместо ложного штрафа `-8:00`).
|
||||
- **Теневой ИИ-арбитраж нераспознанных ФИО (`text_reporter.py`)**:
|
||||
- Модуль `find_ai_identity_suggestions` выявляет нечеткие совпадения и опечатки операторов СКУД, выводя рекомендации для кадровой службы в блоке «💡 Предложения ИИ по сопоставлению ФИО».
|
||||
- **Расширение CLI-утилиты (`scripts/db_cli.py`)**:
|
||||
- Добавлены команды управления связками: `python scripts/db_cli.py mapping [list|add|del]`.
|
||||
|
||||
#### 🔧 Изменено:
|
||||
- **`services/scud_etl/anomaly_detector.py`**:
|
||||
- Добавлено авто-детектирование задвоенных карточек СКУД (`DUPLICATE_SCUD_CARD`) с передачей информации в ИИ-сводку.
|
||||
- **`main_etl.py`**:
|
||||
- Восстановлена передача сырых датасетов (`raw_scud_df`, `raw_staff_df`, `raw_absent_df`) в ИИ-аудитор и генерация диагностического дампа `СКУД_Сырые_данные_ДД.ММ.ГГГГ.xlsx`.
|
||||
|
||||
---
|
||||
|
||||
## [3.1.0] — 2026-08-25
|
||||
### 🛡️ Реляционный реестр исключений, Белый список и отказоустойчивость выгрузок
|
||||
|
||||
#### ✨ Добавлено:
|
||||
- **Реляционный реестр исключений (`exceptions_registry`)**:
|
||||
- Перенос исключений (`departments`, `positions`, `fio`, `position_keywords`) и белого списка (`include_fio`) из статического JSON в базу данных SQLite (`core/schema.py`).
|
||||
- Репозиторий `services/exceptions_repo.py` с функциями CRUD и авто-миграцией из `exceptions.json`.
|
||||
- **Белый список (`include_fio`)**:
|
||||
- Поддержка явного включения сотрудников в расчет контроллинга в обход должностных и отдельских фильтров (Тарасенко А.А., Журиков М.Н.).
|
||||
- **Управление исключениями в CLI (`scripts/db_cli.py`)**:
|
||||
- Добавлены команды `exceptions list`, `exceptions add -c ... -v ...`, `exceptions del`, `exceptions sync`.
|
||||
- **Резервный загрузчик кадровых отсутствий (`data_loader.py`)**:
|
||||
- Реализован каскадный fallback: `MS SQL 1C:ЗУП` (таймаут 30с) $\rightarrow$ резервный парсинг скопированных Excel-файлов `Отсутствия_*.xlsx` $\rightarrow$ `static_reason_workers.csv`.
|
||||
|
||||
#### 🔧 Изменено:
|
||||
- **Структура отчетов Excel (`excel_exporter.py`)**:
|
||||
- Изменен базовый путь сохранения отчетов на `output/reports/ГОД/МЕСЯЦ/`.
|
||||
- В Ежедневной сводке блок «В том числе на удаленной работе» вынесен под «Итого на работе», а блок «Исключения» размещен в самом низу с поддержкой группировки.
|
||||
- Добавлена защита от блокировок Excel (`PermissionError`/`OSError`): при занятости файла создается резервная копия с временной меткой.
|
||||
- **Подключение к СКУД (`services/scud_export.py`)**:
|
||||
- Актуализирован адрес сервера MS SQL Орион (`172.16.200.147\SQL`).
|
||||
- Добавлена защита инициализации файлового логгера от ошибок доступа прав пользователей.
|
||||
|
||||
---
|
||||
|
||||
## [3.0.0] — 2026-08-21
|
||||
### 🚀 Глубокий архитектурный рефакторинг (Unified Clean Architecture)
|
||||
|
||||
#### Добавлено:
|
||||
- **Пакет ядра `core/`:**
|
||||
- `core/connection.py`: централизованный менеджер SQLite-подключений с поддержкой WAL-режима и row_factory.
|
||||
- `core/schema.py`: единая точка инициализации схемы данных и индексов.
|
||||
- `core/repositories/`: низкоуровневые репозитории `scud_repo.py` и `zup_repo.py`.
|
||||
- **Доменные сервисы `services/`:**
|
||||
- `services/tasks/`: полная изоляция логики задач (CRUD, Markdown-экспорт, генерация `ROADMAP.md`).
|
||||
- `services/prompts/`: доменный сервис системного промпта, поддержка превью, генерация HTML-Diff и пакетное удаление узлов (`BATCH_DELETE`).
|
||||
- `services/snapshots/`: бизнес-логика срезов СКУД с защитой финишных Y-снапшотов.
|
||||
- `services/knowledge/`: сервис базы знаний правил и синонимов отделов.
|
||||
- `services/scud_etl/`: модульный ETL-конвейер (`pipeline.py`, `anomaly_detector.py`, `merger.py`, `sql_queries.py`).
|
||||
- **ИИ-оркестратор `modules/ai_engine/`:**
|
||||
- Декомпозиция монолитного `agent.py` на узкие обработчики `handlers/` и динамический контекст-билдер `context_builder.py`.
|
||||
- Двухконтурная обработка: нативный Function Calling + семантический страхующий инжектор (`tool_injector.py`).
|
||||
- Интеллектуальный Topic Drift менеджер с вежливым напоминанием на 3-й шаг и автоочисткой эфемерных сообщений на 4-й.
|
||||
- **Интерфейс и UI:**
|
||||
- Кнопка «✏️ Редактировать» прямо в карточке просмотра системного промпта с инлайн-редактором.
|
||||
|
||||
#### Исправлено:
|
||||
- Устранена утечка системного промпта в постоянный контекст (`chat_messages`).
|
||||
- Исправлены ошибки несоответствия сигнатур (`TypeError: create_prompt_preview`, `save_full_prompt_draft`, `get_snapshots_registry`) в Fast-Path.
|
||||
- Устранена галлюцинация слов-паразитов («Почемучка», «Почемучто») на уровне валидации ответа.
|
||||
- Исправлено устаревшее противоречивое правило 2.3 в базе данных, блокировавшее интерактивное удаление задач.
|
||||
|
||||
#### Удалено:
|
||||
- Устаревшие файлы-дубли: `modules/web_api/llm/db/db_tasks.py`, `db_snapshots.py`, `prompt_merger.py`.
|
||||
|
||||
---
|
||||
|
||||
## [2026-08-19] — Инлайн-редактор задач, интеллектуальный ContextManager и стабилизация Function Calling
|
||||
|
||||
### ✨ Добавлено
|
||||
* **Инлайн-редактирование задач (`task_widget.js` / `tasks.py`)**:
|
||||
- Добавлена кнопка редактирования (`✏️`) на каждой карточке задачи.
|
||||
- Карточка трансформируется в инлайн-форму с тремя полями: текст задачи, HTML5-пикер календаря планируемого срока и выпадающий список важности (`LOW`, `MEDIUM`, `HIGH`, `CRITICAL`).
|
||||
- Добавлен REST API эндпоинт `PATCH /api/v1/tasks/{task_id}` с поддержкой комплексного обновления полей в SQLite.
|
||||
- В карточки выведено отображение даты создания задачи.
|
||||
* **Интеллектуальный ContextManager (`context_manager.py`)**:
|
||||
- Служебные запросы и карточки инструментов сохраняются синхронными парами (`is_ephemeral = 1`) и атомарно удаляются при завершении операций.
|
||||
- Свободные диалоги оператора (включая темы Topic Drift) сохраняются в постоянную историю (`is_ephemeral = 0`) и не стираются при закрытии сессий промпта/задач.
|
||||
* **Поддержка Y-снапшотов (`db_snapshots.py`)**:
|
||||
- Исправлен SQL-запрос `db_get_snapshots` для точного извлечения ночных и фоновых срезов с префиксом `Y` (например, `Y20260817-003`).
|
||||
|
||||
### 🔧 Изменено
|
||||
* **`modules/web_api/llm/agent.py`**:
|
||||
- Полностью удалены эвристические текстовые фильтры и принудительные сортировки инструментов.
|
||||
- Настроен нативный возврат и исполнение инструментов без зацикливания модели.
|
||||
- Устранена ошибка `UnboundLocalError` при вызове справочных инструментов.
|
||||
* **`modules/web_api/llm/schemas.py`**:
|
||||
- Очищены описания инструментов от агрессивных директив и капса, стабилизирована селективность Function Calling для Qwen 2.5.
|
||||
* **`modules/web_api/llm/core/ollama_client.py`**:
|
||||
- Оптимизированы параметры генерации для Function Calling (`repeat_penalty: 1.0`, `presence_penalty: 0.0`, `temperature: 0.0`), что исключило спам несколькими вызовами инструментов на один запрос.
|
||||
* **`modules/web_api/static/js/chat/task_widget.js`**:
|
||||
- Фильтр по умолчанию переведен на вкладку **«В работе»** (`IN_PROGRESS`).
|
||||
|
||||
---
|
||||
|
||||
## [2026-08-18] — Двухфазный жизненный цикл сессий, двусторонний Diff и Topic Drift Guard
|
||||
|
||||
### ✨ Добавлено
|
||||
* **Двусторонний клиентский Diff (`core.js`)**: Реализован алгоритм сравнения черновика с baseline-промптом. Удаленные строки остаются на экране с красным зачеркиванием `[УДАЛЕНИЕ]`, а добавленные/измененные строки выделяются красной рамкой с авто-отступами.
|
||||
* **Topic Drift Guard (`agent.py`)**: Внедрен двухуровневый контроль смены темы:
|
||||
- Мгновенный сброс стейта и зачистка эфемерных сообщений при вызове сторонних инструментов (задачи, снапшоты, база).
|
||||
- Мягкий счетчик отвлечений (`idle_turns` = 3) в свободном диалоге с выводом напоминания и кнопок из `tool_action_registry`.
|
||||
* **Команда `context purge` в CLI (`db_cli.py`)**: Добавлен флаг `--all` для полной очистки таблицы `chat_messages` и сброса стейтов сессий.
|
||||
|
||||
---
|
||||
|
||||
## [2026-08-17] — Внедрение CLI-инспекции контекста и переход на нативный Function Calling
|
||||
|
||||
### ✨ Добавлено
|
||||
* **`scripts/db_cli.py`**: Добавлена команда `context` для инспекции истории сообщений `chat_messages` по сессиям с визуальным отображением флагов `[ЭФЕМЕРНОЕ]`.
|
||||
* **`ROADMAP.md`**: Сформирована актуальная дорожная карта с планом отказа от регулярных выражений в пользу нативного Function Calling.
|
||||
|
||||
---
|
||||
|
||||
## [2026-08-15] — Реляционная архитектура системного промпта
|
||||
|
||||
### ✨ Добавлено
|
||||
* **`system_prompt_nodes`**: Создана таблица реляционных узлов промпта с индексацией по разделам и пунктам (`section_id`, `item_id`).
|
||||
* **`db_prompt_node_edit`**: Добавлен инструмент точечного добавления, изменения и удаления пунктов системного промпта.
|
||||
* **Инлайн-редактор**: Добавлен визуальный diff-просмотр изменений с подсветкой и кнопкой `[✏️ Редактировать]`.
|
||||
|
||||
---
|
||||
|
||||
## [2026-08-10] — Механизм эфемерных сообщений и очистки диалога
|
||||
|
||||
### ✨ Добавлено
|
||||
* **Эфемерные сообщения (`is_ephemeral`)**: Маркировка временных сервисных ответов и черновиков.
|
||||
* **`db_purge_ephemeral_messages`**: Механизм физической зачистки временных записей из SQLite при завершении операций.
|
||||
* **Интерактивные виджеты**: Поддержка карточек задач (`TASK_INTERACTIVE_CARD`) с кнопками быстрого действия.
|
||||
+54
-175
@@ -8,241 +8,120 @@
|
||||
|
||||
## 2. Настройка контекста и инструкций сессии (`agent.py`) `[ЗАВЕРШЕНО]`
|
||||
- [x] Передать управление диалогом языковой модели через системный блок `role: "system"`.
|
||||
- [x] При активном состоянии `PROMPT_PREVIEW` передавать модели инструкцию[cite: 2]:
|
||||
- **Подтверждение / отмена / корректировка:** продолжать работу с превью и вызывать соответствующие инструменты[cite: 2].
|
||||
- **Смена темы:** вежливо напомнить об открытом изменении и запросить решение[cite: 2].
|
||||
- [x] При активном состоянии `PROMPT_PREVIEW` передавать модели инструкцию: подтверждение / отмена / корректировка и Topic Drift Guard[cite: 2].
|
||||
- [x] Обеспечить видимость эфемерных сообщений (`is_ephemeral = 1`) для модели во время активной работы с превью[cite: 2].
|
||||
- [x] Внедрить семантический Topic Drift Guard (`idle_turns` = 3) с вопросами и кнопками из `tool_action_registry`[cite: 2].
|
||||
- [x] Реализовать детерминированный мгновенный сброс сессии и зачистку эфемерного контекста при вызове сторонних инструментов[cite: 2].
|
||||
- [x] Детерминированный сброс сессии и зачистка эфемерного контекста при вызове сторонних инструментов[cite: 2].
|
||||
|
||||
---
|
||||
|
||||
## 3. Очистка эфемерных сообщений при завершении (`fast_path.py` / `context_manager.py`) `[ЗАВЕРШЕНО]`
|
||||
- [x] Настроить удаление временных сообщений превью (`db_purge_ephemeral_messages`) строго в момент нажатия кнопок **«Подтвердить»** или **«Отменить»**[cite: 2].
|
||||
- [x] Сбрасывать состояние сессии в базе данных после фиксации решения[cite: 2].
|
||||
- [x] Внедрить прямое точечное применение изменений через `db_apply_prompt_node_action`[cite: 2].
|
||||
- [x] Добавить обработку фазы `PROMPT_FOLLOWUP` с кнопками завершения и очистки контекста[cite: 2].
|
||||
- [x] Создать `context_manager.py` для строгого разграничения служебных tool-пар (`is_ephemeral=1`) и содержательного диалога (`is_ephemeral=0`), сохраняя беседы Topic Drift в истории[cite: 2].
|
||||
- [x] Настроить удаление временных сообщений превью (`db_purge_ephemeral_messages`) при фиксации решения[cite: 2].
|
||||
- [x] Создать `context_manager.py` для строгого разграничения служебных tool-пар (`is_ephemeral=1`) и содержательного диалога (`is_ephemeral=0`)[cite: 2].
|
||||
|
||||
---
|
||||
|
||||
## 4. Инлайн-редактор в окне диалога (`core.js`) `[ЗАВЕРШЕНО]`
|
||||
- [x] Проверить работу блока ручного редактирования (`inline-prompt-editor-container`) с кнопками **«Сохранить правки»** и **«Свернуть»**[cite: 2].
|
||||
- [x] Обеспечить сохранение черновика через API (`/api/v1/chat/draft`) и отображение обновленного текста перед подтверждением[cite: 2].
|
||||
- [x] Реализовать двусторонний клиентский Diff-рендерер (одновременная подсветка добавленных строк и зачеркивание удаленных `[УДАЛЕНИЕ]`)[cite: 2].
|
||||
- [x] Добавить авто-форматирование и отступы подпунктов (`X.Y.`) при ручном сохранении черновика[cite: 2].
|
||||
|
||||
---
|
||||
|
||||
## 5. Тестирование и валидация системного промпта `[ЗАВЕРШЕНО]`
|
||||
- [x] **Нативные вызовы:** проверить добавление, редактирование и удаление пунктов через нативные вызовы модели (`db_prompt_node_edit`)[cite: 2].
|
||||
- [x] **Контекстные сценарии:** проверить поведение модели при смене темы диалога оператором (Guardrail)[cite: 2].
|
||||
- [x] **UI и очистка:** проверить ручное редактирование через кнопку в окне чата и последующую очистку контекста (`db_purge_ephemeral_messages`)[cite: 2].
|
||||
- [x] **Строгий вызов Базы Знаний:** внедрено правило 2.9 в системный промпт для пресечения текстовой имитации вызова `db_get_rules`[cite: 2].
|
||||
- [x] Проверить добавление, редактирование и удаление пунктов через нативные вызовы модели (`db_prompt_node_edit`)[cite: 2].
|
||||
- [x] Строгий вызов Базы Знаний: внедрено правило в системный промпт для пресечения текстовой имитации вызова `db_get_rules`[cite: 2].
|
||||
|
||||
---
|
||||
|
||||
## 6. Распространение архитектурного паттерна на модуль задач (`tasks`) `[ЗАВЕРШЕНО]`
|
||||
- [x] **Масштабирование UI задач:**
|
||||
- Увеличена ширина карточки до `max-w-4xl` и динамическая высота скролла до `70vh`[cite: 2].
|
||||
- Реализованы переключатели фильтрации: «В работе» (по умолчанию), «В планах», «Готово», «Все»[cite: 2].
|
||||
- Разделены кнопки действия: «В работу» (для плановых) и «Готово» (для текущих)[cite: 2].
|
||||
- [x] **Инлайн-редактирование карточки задачи:**
|
||||
- Плавная трансформация карточки в 3-строчную форму (текст, дата со встроенным пикером, выпадающий список важности)[cite: 2].
|
||||
- Отображение даты создания задачи[cite: 2].
|
||||
- Сохранение через REST API эндпоинт `PATCH /api/v1/tasks/{id}`[cite: 2].
|
||||
- [x] **Детерминированный Fast-Path и двухфазное удаление:**
|
||||
- Мгновенная смена статусов без задержек LLM[cite: 2].
|
||||
- Карточка подтверждения удаления с автоочисткой контекста[cite: 2].
|
||||
- [x] **Генерация отчетов задач в Markdown:**
|
||||
- Добавлен инструмент `db_export_tasks_markdown` для формирования Markdown-файла с группировкой по модулям и чекбоксами `[x]` / `[ ]`[cite: 2].
|
||||
- Реализован роутер безопасной отдачи файлов с сохранением имени (`/api/v1/files/download/...`)[cite: 2].
|
||||
- [x] **Доменная консолидация задач:**
|
||||
- Реализован консолидированный инструмент `db_tasks_edit(action: ["ADD", "UPDATE", "DELETE", "EXPORT"], ...)`[cite: 2].
|
||||
- [x] Масштабирование UI задач, инлайн-редактирование карточек, детерминированный Fast-Path[cite: 2].
|
||||
- [x] Инструмент `db_export_tasks_markdown` для формирования Markdown-файла с чекбоксами[cite: 2].
|
||||
- [x] Доменная консолидация операций над задачами через `db_tasks_edit`[cite: 2].
|
||||
|
||||
---
|
||||
|
||||
## 7. Распространение на модуль снапшотов (`snapshots`) `[ЗАВЕРШЕНО]`
|
||||
- [x] **Поддержка Y-снапшотов:** универсальный парсинг и поиск по `snapshot_id LIKE 'Y%'` и срезам за 22:00:00 / 23:59:59[cite: 2].
|
||||
- [x] **Single Active Snapshot View:** сохранение активного среза в контексте для аналитики с автоматической ротацией и зачисткой при запросе новых дат[cite: 2].
|
||||
- [x] **Интерактивный UI с чекбоксами и защитой срезов:**
|
||||
- Чекбоксы в строках дневных срезов и кнопка «Выбрать все» в шапке[cite: 2].
|
||||
- Защита итогового вечернего среза Y (иконка замочка `🔒`, блокировка выбора)[cite: 2].
|
||||
- Динамическая кнопка «Удалить выбранные (N)» в подвале карточки[cite: 2].
|
||||
- [x] **Декларативное управление удалением срезов:**
|
||||
- Добавлен параметр `confirmed` в схему `TOOLS_SCHEMA` для `db_delete_snapshots`, исключающий зацикливание подтверждений в LLM.
|
||||
- Двухфазное подтверждение удаления (одиночное и пакетное) с корректным счётчиком количества удаляемых элементов[cite: 2].
|
||||
- Корректное отображение времени создания срезов в интерфейсе (устранение смещения UTC относительно локального времени сервера).
|
||||
- [x] Поддержка Y-снапшотов, Single Active Snapshot View в контексте, UI с чекбоксами и защитой итоговых срезов[cite: 2].
|
||||
- [x] Декларативное двухфазное управление удалением срезов через `db_delete_snapshots`[cite: 2].
|
||||
|
||||
---
|
||||
|
||||
## 8. Глубокий архитектурный рефакторинг ядра и сервисов `[ЗАВЕРШЕНО]`
|
||||
- [x] **Выделение общего слоя ядра (`core/`):**
|
||||
- Изолированный пул соединений SQLite (`core/connection.py`) с поддержкой WAL и таймаутов[cite: 2].
|
||||
- DDL-схемы таблиц и индексов (`core/schema.py`)[cite: 2].
|
||||
- Репозитории СКУД и 1С (`core/repositories/scud_repo.py`, `core/repositories/zup_repo.py`)[cite: 2].
|
||||
- Фасад обратной совместимости (`core/database.py`)[cite: 2].
|
||||
- [x] **Декомпозиция предметных доменов (`services/`):**
|
||||
- Сервис задач (`services/tasks/`), системного промпта (`services/prompts/`), срезов СКУД (`services/snapshots/`), базы знаний (`services/knowledge/`)[cite: 2].
|
||||
- [x] **Рефакторинг ETL-конвейера (`services/scud_etl/`):**
|
||||
- Оркестратор `pipeline.py`, детектор аномалий `anomaly_detector.py`, слияние `merger.py`[cite: 2].
|
||||
- [x] **Модульный ИИ-оркестратор (`modules/ai_engine/`):**
|
||||
- Динамический строитель системного контекста (`context_builder.py`)[cite: 2].
|
||||
- Изолированные обработчики инструментов в `handlers/`[cite: 2].
|
||||
- [x] Выделение общего слоя ядра (`core/`), доменных сервисов (`services/`), рефакторинг ETL (`services/scud_etl/`) и модульный ИИ-оркестратор[cite: 2].
|
||||
|
||||
---
|
||||
|
||||
## 9. Реляционный реестр исключений, схлопывание мульти-пропусков и кадровый аудит `[ЗАВЕРШЕНО]`
|
||||
- [x] **Реестр исключений в SQLite (`exceptions_registry`):**
|
||||
- Хранение категорий `departments`, `positions`, `fio`, `position_keywords`, `include_fio` в БД[cite: 2].
|
||||
- Доменный сервис `exceptions_repo.py` и полная поддержка в CLI `scripts/db_cli.py exceptions`[cite: 2].
|
||||
- [x] **Агрегация мульти-пропусков физлиц в СКУД:**
|
||||
- Функция `aggregate_scud_by_person` в `merger.py`: объединение событий всех пропусков одного человека (ранний вход, поздний выход, присутствие)[cite: 2].
|
||||
- Автоматическая фиксация аномалий дублирования пропусков (`DUPLICATE_SCUD_CARD`)[cite: 2].
|
||||
- [x] **Умный выбор ставки совместителей 1С:ЗУП:**
|
||||
- Функция `select_best_zup_position` в `merger.py`: привязка ставки 1С по подразделению физического нахождения в СКУД[cite: 2].
|
||||
- [x] **Отказ от искусственного автозакрытия смен:**
|
||||
- Полное отключение механизма дорисовывания 8.5 часов (`calculate_autoclose_time`) по согласованию с отделом кадров.
|
||||
- Сохранение честного статуса «Нет выхода» для прозрачности кадрового аудита и выявления нарушений.
|
||||
- [x] **Кэш сопоставлений личностей (`person_identity_mapping`):**
|
||||
- Таблица в SQLite и команды `db_cli.py mapping [list|add|del]`[cite: 2].
|
||||
- Теневой режим ИИ-подсказок по нечетким ФИО в `text_reporter.py`[cite: 2].
|
||||
- [x] **Каскадный fallback кадровых отсутствий:**
|
||||
- `MS SQL ЗУП` $\rightarrow$ резервный парсинг `Отсутствия_*.xlsx` $\rightarrow$ `static_reason_workers.csv`[cite: 2].
|
||||
- [x] Реестр исключений в SQLite (`exceptions_registry`), агрегация мульти-пропусков физлиц в `merger.py`[cite: 2].
|
||||
- [x] Умный выбор ставки совместителей 1С:ЗУП, отказ от искусственного автозакрытия смен и каскадный fallback отсутствий[cite: 2].
|
||||
|
||||
---
|
||||
|
||||
## 10. Разделение генераторов и почасовые срезы `[ЗАВЕРШЕНО]`
|
||||
- [x] Разделение логики генерации на `svodka_generator.py` и `otchet_generator.py`[cite: 2].
|
||||
- [x] Перевод времени суточного среза `Y` на `23:59:59`[cite: 2].
|
||||
- [x] Интеллектуальный поиск срезов `services/snapshots/finder.py` (Snap-to-Grid ±20 мин)[cite: 2].
|
||||
- [x] Флаг `--time` и интерактивный help в `main_etl.py`[cite: 2].
|
||||
- [x] Флаг `--export-only` для почасового крона[cite: 2].
|
||||
- [x] Политика ночной ротации промежуточных срезов `services/snapshots/retention.py`[cite: 2].
|
||||
- [x] Исправление целочисленного инкремента `snapshot_id`[cite: 2].
|
||||
- [x] Перевод суточного среза `Y` на `23:59:59`, Snap-to-Grid (±20 мин), флаги CLI и ночная ротация срезов[cite: 2].
|
||||
|
||||
---
|
||||
|
||||
## 11. Стабилизация генератора отчетов и верстки `[ЗАВЕРШЕНО]`
|
||||
- [x] **Миграция на `XlsxWriter`:** полный перевод экспорта книг (`scud_export.py`, `excel_exporter.py`) на чистый генератор, устранивший ошибки OpenXML и окна восстановления при открытии[cite: 2].
|
||||
- [x] **Интективные группировки в Сводке:** восстановление сворачивания категорий по умолчанию (`level=1`, `collapsed=True`) и кнопок управления уровнями `[+]`/`[-]` (`outline_settings(symbols_below=False)`)[cite: 2].
|
||||
- [x] **Компактная экранная верстка Детального отчета:** центрирование столбца «Подразделение», расширение столбца «ФИО» (+10%, ширина 33), оптимизация ширины колонок «Первая активность» (11) и «Отклонение от нормы» (11) для отображения без горизонтальной прокрутки[cite: 2].
|
||||
- [x] **Защита от блокировок занятых файлов (Fallback Timestamp):** механизм перехвата `FileCreateError`/`OSError` в `safe_close_workbook` с сохранением копии при открытом в Excel файле[cite: 2].
|
||||
- [x] **Безопасная синхронизация 1С с сетевой шары:** переход на `shutil.copyfile` в `share_copier.py` для устранения сбоев прав доступа (`Operation not permitted`) на SMB/CIFS-ресурсах[cite: 2].
|
||||
- [x] Миграция экспорта на `XlsxWriter`, интерактивные группировки `[+]`/`[-]` в Сводке, компактная верстка Детального отчета и защита от блокировок Excel[cite: 2].
|
||||
|
||||
---
|
||||
|
||||
## 12. UI/UX веб-интерфейса и управление реестрами `[ЗАВЕРШЕНО]`
|
||||
- [x] **Паттерн Gemini-скролла:** реализация функции `scrollToUserMessageTop` в `core.js`, позиционирующей свежий вопрос пользователя строго по верхней кромке видимой области[cite: 2].
|
||||
- [x] **Полное скрытие истории:** предыдущие объемные ответы модели гарантированно вытесняются за верхний край экрана[cite: 2].
|
||||
- [x] **Стабилизация панели ввода:** настройка `padding-bottom: 80vh` для `#chat-messages-container` в `index.html`, обеспечивающая необходимый запас высоты прокрутки без сдвига строки ввода текста[cite: 2].
|
||||
- [x] **Модальные формы реестров с автокомплитом 1С:**
|
||||
- Полный отказ от браузерного `prompt()` при работе со списками исключений.
|
||||
- Единое Tailwind-окно для добавления исключений с живым поиском сотрудников по базе 1С:ЗУП (`staff-autocomplete`) и полем для комментария/основания.
|
||||
- [x] Паттерн Gemini-скролла (`scrollToUserMessageTop`)[cite: 2], фиксация панели ввода и модальные формы с автокомплитом 1С[cite: 2].
|
||||
|
||||
---
|
||||
|
||||
## 13. Архитектура обработки событий турникетов и двухконтурный учет `[ЗАВЕРШЕНО]`
|
||||
- [x] **Опора на физический факт прохода (Event 32):**
|
||||
- Устранение потери событий из-за рассинхронизации меток Event 28 (разрешение) и Event 32 (проход).
|
||||
- Переход на плоский SQL-запрос выборки первого входа (`Mode = 1`) и последнего выхода (`Mode = 2`).
|
||||
- [x] **Двухконтурная модель турникетов (Левый/Правый PERCo):**
|
||||
- Разрешение использования обоих турникетов (`DoorIndex IN (1, 2)`) для сотрудников дворовых служб (отделы `ЭТО`, `ЛЦ` и др.).
|
||||
- Защита основного пула офисных сотрудников от транзитных отметок на правом турникете (`DoorIndex = 1`).
|
||||
- Реестр «Пр. турникет» (`turnstile_fio`, `turnstile_departments`) в базе данных и веб-панели.
|
||||
- Корректное сопоставление составных ФИО (`Name + FirstName + MidName`) в запросе к `pList`.
|
||||
- [x] **Таблица сырых событий (`scud_events_raw`):**
|
||||
- Создание DDL-схемы таблицы и логирование всех физических проходов дня параллельно со снапшотами.
|
||||
## 13. Двухконтурный учет турникетов и калибровка оборудования `[ЗАВЕРШЕНО]`
|
||||
- [x] Опора на физический факт прохода (`Event 32`), двухконтурная модель турникетов (Левый/Правый PERCo) и таблица сырых перемещений `scud_events_raw`[cite: 2].
|
||||
- [x] Синхронизация фильтров дверей в `SQL_RAW_EVENTS_QUERY`: отсечение паразитных транзитных касаний правого турникета для офисного пула.
|
||||
|
||||
---
|
||||
|
||||
## 14. Миграция инфраструктуры, отказоустойчивость отчетов и Упрощенный отчет `[ЗАВЕРШЕНО]`
|
||||
- [x] **Миграция на новый сервер (Debian 12):**
|
||||
- Актуализация путей виртуального окружения в cron-скриптах (`scripts/cron/*.sh`).
|
||||
- Восстановление прямого подключения к базе 1С:ЗУП (MS SQL Server `ACCOUNT-01`).
|
||||
- Настройка автоматического CIFS-монтирования шары отчетов `//storage/SCUD/Отчеты` в `/etc/fstab` с правами пользователя.
|
||||
- [x] **Разделение статусов наличия в кадровых реестрах (`merger.py`):**
|
||||
- Выделение сотрудников, заведенных в СКУД, но не принятых в ЗУП (`not_hired_yet = True`), в отдельный раздел сводки **«Не приняты на работу»**.
|
||||
- Полное исключение непринятых сотрудников из детального суточного табеля за прошлые смены.
|
||||
- Обособление штатных сотрудников без карт СКУД (`no_scud_pass = True`) в раздел **«Нет пропуска»** с исключением их из «Неизвестных».
|
||||
- Устранение предупреждений `UserWarning: Boolean Series key will be reindexed` при вычислении метрик штата.
|
||||
- [x] **Стабилизация генерации Excel-книг (`otchet_builder.py`):**
|
||||
- Включение защитной опции `nan_inf_to_errors: True` в `xlsxwriter.Workbook`.
|
||||
- Санитизация ячеек от значений `NaN` / `None` / `pd.NA` перед записью, устранившая критический сбой `TypeError: NAN/INF not supported in write_number()`.
|
||||
- [x] **Генератор «Упрощенного отчета» (`services/reports/simplified_builder.py`):**
|
||||
- Создание генератора по эталонному шаблону: заголовок `Упрощенный отчет: c ДД.ММ.ГГГГ по ДД.ММ.ГГГГ`, сокращение ФИО до инициалов (`Фамилия И.О.`), отображение времени с текстовыми заглушками (`Нет входа (0:00)`, `Нет выхода (23:59)`).
|
||||
- Сортировка по подразделениям и алфавиту сотрудников.
|
||||
- Интеграция этапа сборки упрощенного отчета за вчера в ETL-конвейер (`main_etl.py`).
|
||||
- [x] **Компактный динамический сборщик слепков (`make_etl_snapshot.py`):**
|
||||
- Автоматический обход дерева (auto-discovery) с отсечением дублирующих архивных манифестов, временных файлов и пустых `__init__.py`.
|
||||
## 14. Миграция инфраструктуры и Упрощенный отчет `[ЗАВЕРШЕНО]`
|
||||
- [x] Миграция на Debian 12, разделение статусов «Не приняты на работу» и «Нет пропуска», генератор «Упрощенного отчета» (`simplified_builder.py`)[cite: 2].
|
||||
|
||||
---
|
||||
|
||||
## 15. ПРИОРИТЕТ 1: Внутридневной контроль, экран «Кто в здании» и On-Demand генерация `[В РАБОТЕ]`
|
||||
## 15. Внутридневной контроль и On-Demand генерация `[ЗАВЕРШЕНО]`
|
||||
- [x] **Оперативный контроль «Кто в здании прямо сейчас» (Live Presence):**
|
||||
- [x] REST API эндпоинт `GET /api/v1/presence/live` на базе таблицы `scud_events_raw` и оконной функции последнего события прохода.
|
||||
- [x] Выделенная модальная панель в веб-интерфейсе:
|
||||
- Метрики реального времени: *Штат 1С*, *В здании*, *Вышли*, *На удаленке*, *В командировке/отпуске*, *Не пришли*, *Исключения*.
|
||||
- Быстрый поиск сотрудника и фильтрация по подразделениям.
|
||||
- Учет специфики служебных входов/выходов во двор (флигель/двор).
|
||||
- [x] **On-Demand генерация отчетов из UI и сайдбара:**
|
||||
- [x] Кнопка **«Сводка»** в сайдбаре: моментальный сбор книги по последнему готовому срезу SQLite без блокирующих опросов MS SQL.
|
||||
- [x] Кнопки **«Детальн.»** и **«Упрощ.»**: строгое формирование отчетов за **ВЧЕРА** (с учетом выходных) по финальному суточному срезу `Y` (23:59:59).
|
||||
- [x] Каскадный fallback кадровых файлов: при отсутствии свежего штата за текущее утро автоматическое использование актуального среза из `zup_staff` в SQLite.
|
||||
- [x] **Атомарная публикация и отдача файлов (Report Delivery Engine):**
|
||||
- [x] Устранение 404 ошибок: рекурсивный поиск файлов в иерархии `output/reports/{ГОД}/{МЕСЯЦ}/` и декодирование URL-имён.
|
||||
- [x] Синхронизация при отдаче: автоматическая отдача прямой ссылки на скачивание в браузер.
|
||||
- [ ] **Реестр «Графики работы» (Custom Work Schedules):**
|
||||
- [ ] Таблица в SQLite `work_schedules_registry` (`fio_clean`, `department`, `schedule_type`, `norm_hours`, `time_start_window`, `time_end_window`, `valid_from`, `valid_to`).
|
||||
- [ ] Интеграция индивидуальной нормы часов (4, 7, 11, 24 ч) в калькулятор выработки `calculators.py` вместо константы 8 ч.
|
||||
- [ ] Вкладка управления графиками в сайдбаре «Реестры» с автоподбором сотрудников из 1С.
|
||||
- [x] Выделенная модальная панель со сбалансированными метриками штата 1С.
|
||||
- [x] Динамическое определение целевой даты сервера (`datetime.now()`) взамен статичной константы.
|
||||
- [x] Фиксация статуса «Вышел» по реальному направлению `Direction == 'OUT'`, устранение залипания сотрудников лабораторий флигеля.
|
||||
- [x] **Контекстная генерация отчетов из UI:**
|
||||
- [x] Перенос кнопки «Сводка» на каждую плашку среза с генерацией строго по выбранному `snapshot_id`.
|
||||
- [x] Интеграция индивидуальных графиков работы (`employee_schedules`) и выделение блока «Смена не началась (по графику позже)».
|
||||
- [x] Внедрение 15-минутного допуска (grace period) от времени начала смены.
|
||||
|
||||
---
|
||||
|
||||
## 16. ПРИОРИТЕТ 2: Кадровый арбитраж до отчетов и интеграция с MS Exchange `[В ПЛАНАХ]`
|
||||
## 16. ПРИОРИТЕТ 1: Тестовый стенд и масштабирование ИИ-ядра `[В РАБОТЕ]`
|
||||
- [ ] **TASK-41: Развертывание параллельного изолированного тестового стенда (Staging Env):**
|
||||
- [ ] Развертывание тестового контура `/home/apushkov/projects/scud_ai_dev/` на том же хосте.
|
||||
- [ ] Изоляция базы данных `scud_orion_ai_dev.db`, папок отчетов и запуск сервиса `scud-context-api-dev.service` на порту `8001`.
|
||||
- [ ] Скрипт безопасной синхронизации снимка боевой БД в Dev-контур для реалистичных тестов.
|
||||
- [ ] Регламент инжекции проверенных фич в прод (Git merge / cherry-pick).
|
||||
- [ ] **TASK-38: Интеллектуальное управление реестрами и периодические правила (Recurring Rules):**
|
||||
- [ ] Схема `manage_recurring_registry_rule` в `TOOLS_SCHEMA` для декларативного NLU-разбора свободных фраз оператора.
|
||||
- [ ] Таблица периодических правил в SQLite `registry_recurring_rules` (дни недели, диапазоны дат, основание).
|
||||
- [ ] Автоматическое наложение периодических командировок/отсутствий в конвейере сборки ежедневных отчетов.
|
||||
- [ ] **TASK-39: Локальный семантический роутер (Semantic Router на эмбеддингах):**
|
||||
- [ ] Подключение легковесной мультиязычной эмбеддинг-модели (`bge-m3` / `MiniLM`) через `faiss-cpu` или `sqlite-vss`.
|
||||
- [ ] Fast-Path классификация типовых команд оператора (<100 мс) без вызова генеративной 14B LLM.
|
||||
- [ ] **TASK-40: Векторный Entity Resolution сотрудников и отделов:**
|
||||
- [ ] Семантический поиск персон по эталонной базе 1С:ЗУП с автоматической компенсацией опечаток операторов СКУД.
|
||||
- [ ] Векторное сопоставление синонимов подразделений взамен жестких списков в коде.
|
||||
|
||||
---
|
||||
|
||||
## 17. ПРИОРИТЕТ 2: Кадровый арбитраж до отчетов и интеграция с MS Exchange `[В ПЛАНАХ]`
|
||||
- [ ] **Почтовый агент MS Exchange (Email-Driven Controller & Human-in-the-Loop):**
|
||||
- [ ] Фоновый сервис `services/mail/exchange_bot.py` для опроса служебного ящика по IMAP/SMTP (`imaplib` / `email`) или EWS (`exchangelib`).
|
||||
- [ ] Белый список доверенных отправителей (адреса сотрудников ОК, СБ и руководства).
|
||||
- [ ] **Генерация отчетов по письму:** распознавание запросов в теме/теле писем (*«Сводка на 14:00»*, *«Отчет за 22.09.2026»*) и отправка файла в ответном письме.
|
||||
- [ ] **Разрешение кадровых коллизий через почту:** обработка ответов СБ на утреннюю рассылку аномалий (подтверждение связок в `person_identity_mapping`) и регистрация командировок/служебок в `manual_absences`.
|
||||
- [ ] Двухфазный Guardrail: запрос подтверждения у кадровика по почте при низкой уверенности в сопоставлении тёзок (<90%).
|
||||
- [ ] Фоновый сервис `services/mail/exchange_bot.py` для генерации отчетов по письмам и разрешения кадровых коллизий.
|
||||
- [ ] **Интеллектуальный кадровый арбитраж ДО генерации отчетов:**
|
||||
- [ ] Перенос арбитража не сопоставившихся персон на этап [2.5] ДО сохранения Excel-файлов `сводка.xlsx` и `отчет.xlsx`.
|
||||
- [ ] **Якорный табельный номер (TabNo Matching):** извлечение `TabNo` из MS SQL СКУД Орион и 1С:ЗУП, защита от смены фамилий и опечаток.
|
||||
- [ ] 4-уровневая система предохранителей (Точный матч $\rightarrow$ Табельный номер $\rightarrow$ Кэш связок $\rightarrow$ ИИ-арбитраж).
|
||||
- [ ] Сопоставление по якорному табельному номеру (`TabNo Matching`) для защиты от смены фамилий и опечаток.
|
||||
|
||||
---
|
||||
|
||||
## 17. ПРИОРИТЕТ 3: Векторная база знаний (RAG) и внешний контекст `[В ПЛАНАХ]`
|
||||
## 18. ПРИОРИТЕТ 3: Векторная база знаний регламентов (RAG) `[В ПЛАНАХ]`
|
||||
- [ ] **Векторный поиск по регламентам компании (ChromaDB / RAG Engine):**
|
||||
- [ ] Встраиваемая векторная база для семантического поиска по ПВТР, положениям о пропускном режиме и должностным инструкциям.
|
||||
- [ ] Мгновенная выдача ссылок на пункты локальных нормативных актов при консультации оператора в чате.
|
||||
- [ ] Семантическая классификация нестандартных формулировок причин отсутствий из писем и заявлений.
|
||||
- [ ] **Внешний контекстный инструмент (Web Search Agent):**
|
||||
- [ ] Нативный инструмент `web_search` для обращения к производственному календарю РФ (переносы праздников, предпраздничные сокращенные смены по ст. 95 ТК РФ).
|
||||
- [ ] Справка по статьям Трудового кодекса РФ (сверхурочные, выходные дни).
|
||||
|
||||
---
|
||||
|
||||
## 18. Исследовательский трек: Изолированная песочница кода `[ОТЛОЖЕНО]`
|
||||
- [ ] **Docker/gVisor контур:**
|
||||
- [ ] Изолированный контейнер без доступа к внешней сети (`network: none`) с жесткими cgroups-лимитами и монтированием данных в режиме Read-Only.
|
||||
- [ ] Генерация и выполнение Python/Pandas скриптов для построения сложных графиков и нестандартной статистики на лету.
|
||||
|
||||
---
|
||||
|
||||
## 19. Доменный модуль канцелярии и документов (`services/office/`) `[В РАБОТЕ]`
|
||||
- [x] **Изоляция офисного домена от кадрового ядра СКУД:**
|
||||
- [x] Создание независимого пакета `services/office/` (`document_extractor.py`, `word_builder.py`, `service.py`).
|
||||
- [x] Снятие ограничений контекста диалога: многостраничный постраничный обход PDF вместо обрезания первой страницы.
|
||||
- [x] Генерация ГОСТ-документов Word (`.docx`) с выдачей контрастной карточки скачивания в интерфейс чата.
|
||||
- [ ] **Двухфазный конвейер OCR и глубокая нормализация (Vision + LLM Refiner):**
|
||||
- [ ] **Фаза 1 (Vision Extraction):** повышение разрешения рендеринга до `250–300 DPI` для чёткой отрисовки тонких линий шариковых ручек и штампов.
|
||||
- [ ] **Фаза 2 (LLM Post-Processing Refiner):** вычитка текста через `qwen2.5:14b`:
|
||||
- Устранение диалогового шума и случайных приветствий модели.
|
||||
- Склейка разорванных строк внутри абзацев.
|
||||
- Автоматическая сборка списков участников и табличных данных в полноценные таблицы Word (`Table Grid`).
|
||||
- [ ] **Специализированное распознавание рукописных виз и резолюций канцелярии:**
|
||||
- [ ] Распознавание наклонного и беглого почерка на полях и в шапке документов (визы «Согласовано», резолюции руководства, подписи, даты).
|
||||
- [ ] Выделение рукописных пометок в стандартизированные структурные блоки: `[Резолюция: ...]` в начале страницы.
|
||||
- [ ] **Two-Pass Context Injection:** перекрёстное сопоставление неразборчивых фамилий и инициалов с реестром участников совещания/штатом из тела самого документа.
|
||||
- [ ] Семантический поиск по ПВТР, положениям о пропускном режиме и выдача точных ссылок на статьи и пункты.
|
||||
+1435
-628
File diff suppressed because it is too large
Load Diff
@@ -15,7 +15,7 @@ import config
|
||||
logger = logging.getLogger("OLLAMA_CLIENT")
|
||||
|
||||
# Чистый адрес API chat
|
||||
OLLAMA_URL = getattr(config, "OLLAMA_CHAT_URL", "http://10.121.17.227:11434/api/chat")
|
||||
OLLAMA_URL = getattr(config, "OLLAMA_CHAT_URL", "http://192.168.11.111:11434/api/chat")
|
||||
TEXT_MODEL = getattr(config, "OLLAMA_MODEL", "qwen2.5:14b")
|
||||
VISION_MODEL = getattr(config, "VISION_MODEL", "qwen2.5vl:7b-q8_0")
|
||||
|
||||
|
||||
@@ -1,87 +1,212 @@
|
||||
"""
|
||||
===============================================================================
|
||||
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:
|
||||
"""Сохраняет сообщение в БД (is_ephemeral=1 для временных служебных шагов, 0 для постоянных)."""
|
||||
conn = get_db_connection(row_factory=True)
|
||||
import json
|
||||
from typing import List, Dict, Any, Optional
|
||||
from core.connection import get_connection as get_db_connection
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ИНИЦИАЛИЗАЦИЯ ТАБЛИЦ СЕССИЙ И СООБЩЕНИЙ
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def db_init_chat_sessions_table() -> None:
|
||||
"""Инициализирует таблицу тем диалогов (chat_sessions), если она еще не создана."""
|
||||
with get_db_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS chat_sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id INTEGER DEFAULT 1,
|
||||
title TEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
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()
|
||||
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()
|
||||
conn.close()
|
||||
|
||||
|
||||
def db_get_chat_history(session_id: str, limit: int = 50) -> list:
|
||||
"""Возвращает историю сообщений диалога для сессии."""
|
||||
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 role, content, is_ephemeral, created_at
|
||||
SELECT id, session_id, role, content, is_ephemeral, created_at
|
||||
FROM chat_messages
|
||||
WHERE session_id = ?
|
||||
ORDER BY id DESC
|
||||
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 [{"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_purge_ephemeral_messages(session_id: str) -> int:
|
||||
"""
|
||||
Физически удаляет все временные служебные сообщения выбранной сессии
|
||||
после завершения сценария работы с инструментом.
|
||||
"""
|
||||
conn = get_db_connection(row_factory=True)
|
||||
"""Физически удаляет временные служебные сообщения (превью, черновики)."""
|
||||
with get_db_connection() as conn:
|
||||
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)
|
||||
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()
|
||||
conn.close()
|
||||
return deleted
|
||||
|
||||
def db_clear_all_chat_context(session_id: str = None, purge_all: bool = False) -> int:
|
||||
"""Удаляет сообщения чата и стейты сессий."""
|
||||
with get_db_connection(row_factory=True) as conn:
|
||||
|
||||
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:
|
||||
if 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:
|
||||
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 session_states")
|
||||
cnt = cursor.rowcount
|
||||
conn.commit()
|
||||
return cnt
|
||||
|
||||
query = """
|
||||
DELETE FROM chat_messages
|
||||
WHERE is_ephemeral = 1
|
||||
OR content LIKE '%Предпросмотр изменений%'
|
||||
OR content LIKE '%Удален пункт:%'
|
||||
OR content LIKE '%добавлен пункт:%'
|
||||
"""
|
||||
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
|
||||
cursor.execute("DELETE FROM chat_messages WHERE is_ephemeral = 1")
|
||||
deleted = cursor.rowcount
|
||||
conn.commit()
|
||||
return deleted
|
||||
|
||||
|
||||
def db_update_session_title(session_id: str, new_title: str) -> None:
|
||||
"""Фоновое обновление названия сессии после суммаризации моделью."""
|
||||
db_init_chat_sessions_table()
|
||||
with get_db_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("UPDATE chat_sessions SET title = ? WHERE id = ?", (new_title.strip(), session_id))
|
||||
conn.commit()
|
||||
return cnt
|
||||
@@ -39,6 +39,7 @@ from routers.remote_workers import router as remote_workers_router
|
||||
from routers.context import router as context_router
|
||||
from routers.presence import router as presence_router
|
||||
from routers.reports import router as reports_router
|
||||
from routers.schedules import router as schedules_router
|
||||
|
||||
# ANCHOR[APP_CONFIG]
|
||||
logging.basicConfig(
|
||||
@@ -75,6 +76,7 @@ app.include_router(context_router)
|
||||
app.include_router(manual_absences_router)
|
||||
app.include_router(presence_router)
|
||||
app.include_router(reports_router)
|
||||
app.include_router(schedules_router)
|
||||
|
||||
# ANCHOR[ROOT_STATIC_ROUTES]
|
||||
@app.get("/")
|
||||
|
||||
+169
-96
@@ -1,148 +1,221 @@
|
||||
"""
|
||||
===============================================================================
|
||||
FILE: modules/web_api/routers/chat.py
|
||||
ROLE: Роутер чата с чистым разделением:
|
||||
- Диалог и команды СКУД/1С (через agent.py).
|
||||
- Парсинг и извлечение документов без обрезания (через file_parser.py).
|
||||
PROJECT: SCUD Orion AI (Unified Architecture)
|
||||
MODULE: web_api / routers
|
||||
ROLE: REST API маршрутизатор диалогов с ИИ-ассистентом, мультичатов (тем)
|
||||
и обработки прикрепленных файлов/документов.
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import uuid
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, UploadFile, File, Form
|
||||
from typing import Optional, List, Dict, Any
|
||||
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, Query, BackgroundTasks
|
||||
from pydantic import BaseModel
|
||||
|
||||
from llm.agent import process_chat_message
|
||||
from llm.file_parser import parse_uploaded_file
|
||||
from config import BASE_DIR
|
||||
from config import DATA_DIR
|
||||
from modules.web_api.routers.auth import get_current_user
|
||||
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")
|
||||
router = APIRouter(prefix="/api/v1", tags=["Chat"])
|
||||
logger = logging.getLogger("CHAT_ROUTER")
|
||||
router = APIRouter(prefix="/api/v1/chat", tags=["Chat"])
|
||||
|
||||
UPLOAD_TMP_DIR = os.path.join(BASE_DIR, "data", "uploads")
|
||||
os.makedirs(UPLOAD_TMP_DIR, exist_ok=True)
|
||||
UPLOAD_DIR = os.path.join(DATA_DIR, "uploads")
|
||||
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# СХЕМЫ ЗАПРОСОВ
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class ChatMessageRequest(BaseModel):
|
||||
message: str
|
||||
session_id: Optional[str] = "web_session_main"
|
||||
user_id: Optional[int] = 1
|
||||
session_id: Optional[str] = "session_main"
|
||||
|
||||
|
||||
def resolve_user_id(authorization: Optional[str] = None, explicit_user_id: Optional[int] = None) -> int:
|
||||
if explicit_user_id and explicit_user_id > 0:
|
||||
return explicit_user_id
|
||||
|
||||
if authorization and authorization.startswith("Bearer "):
|
||||
token = authorization.replace("Bearer ", "").strip()
|
||||
if token.isdigit():
|
||||
return int(token)
|
||||
return 1
|
||||
class CreateSessionRequest(BaseModel):
|
||||
title: Optional[str] = None
|
||||
session_id: Optional[str] = None
|
||||
|
||||
|
||||
@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:
|
||||
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(
|
||||
user_id=user_id,
|
||||
user_message=user_msg,
|
||||
session_id=session_id
|
||||
session_id=target_session
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"user_id": user_id,
|
||||
"session_id": session_id,
|
||||
"response": reply_text,
|
||||
"action_payload": action_payload
|
||||
}
|
||||
|
||||
|
||||
@router.post("/chat/upload")
|
||||
@router.post("/upload")
|
||||
async def chat_upload_endpoint(
|
||||
file: UploadFile = File(...),
|
||||
message: Optional[str] = Form(""),
|
||||
session_id: Optional[str] = Form("web_session_main"),
|
||||
authorization: Optional[str] = Header(None)
|
||||
message: Optional[str] = Form(None),
|
||||
session_id: Optional[str] = Form("session_main"),
|
||||
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:
|
||||
shutil.copyfileobj(file.file, buffer)
|
||||
file_name = file.filename or f"upload_{uuid.uuid4().hex[:6]}.dat"
|
||||
save_path = os.path.join(UPLOAD_DIR, file_name)
|
||||
|
||||
user_msg = (message or "").strip()
|
||||
msg_lower = user_msg.lower()
|
||||
fn_lower = file.filename.lower()
|
||||
try:
|
||||
with open(save_path, "wb") as f:
|
||||
content = await file.read()
|
||||
f.write(content)
|
||||
|
||||
# ⭐️ 1. ПРЯМАЯ ИЗОЛИРОВАННАЯ ОБРАБОТКА PDF/СКАНОВ В WORD ЧЕРЕЗ OFFICE МОДУЛЬ
|
||||
ocr_keywords = [
|
||||
"распознай", "распознать", "в word", "в ворд", "для ворда", "для word",
|
||||
"отформатируй", "текст для вставки", "извлеки текст", "сделай документ", "переведи в ворд"
|
||||
]
|
||||
parsed_context = parse_uploaded_file(save_path, file_name)
|
||||
|
||||
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}")
|
||||
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
|
||||
# Обновляем активность темы
|
||||
db_touch_chat_session(session_id=target_session, auto_title=f"Файл: {file_name}", user_id=user_id)
|
||||
|
||||
# Сохраняем вопрос пользователя в историю
|
||||
prompt_text = user_msg or f"Распознать документ {file.filename} для MS Word"
|
||||
db_save_chat_message(session_id, "user", prompt_text, is_ephemeral=0)
|
||||
|
||||
# Вызываем офисный сервис постраничного OCR и сборки DOCX
|
||||
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 {
|
||||
"status": "success",
|
||||
"user_id": user_id,
|
||||
"session_id": session_id,
|
||||
"response": reply_text,
|
||||
"action_payload": action_payload
|
||||
}
|
||||
|
||||
# 2. Если это не задача OCR в Word — отправляем файл в обычный диалог агента
|
||||
parsed = parse_uploaded_file(file_path, file.filename)
|
||||
file_context = parsed.get("context_text", "")
|
||||
image_b64 = parsed.get("image_b64")
|
||||
|
||||
prompt_for_agent = user_msg or f"Проанализируй документ {file.filename}"
|
||||
reply_text, history, action_payload = process_chat_message(
|
||||
user_id=user_id,
|
||||
user_message=prompt_for_agent,
|
||||
file_context=file_context,
|
||||
image_b64=image_b64,
|
||||
session_id=session_id
|
||||
user_message=message.strip() if message else "",
|
||||
file_context=parsed_context,
|
||||
session_id=target_session
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"user_id": user_id,
|
||||
"session_id": session_id,
|
||||
"response": reply_text,
|
||||
"action_payload": action_payload
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.exception(f"Ошибка при обработке файла {file_name}: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Ошибка обработки файла: {str(e)}")
|
||||
|
||||
def async_generate_topic_title(session_id: str, first_user_message: str):
|
||||
"""Фоновая генерация естественного и осмысленного названия чата через LLM."""
|
||||
try:
|
||||
from modules.web_api.llm.core.ollama_client import call_ollama_chat
|
||||
|
||||
prompt = (
|
||||
"Ты — умный редактор диалогов. Проанализируй первое сообщение пользователя и сформулируй "
|
||||
"красивое, грамматически связное и понятное человеку название для этого чата на русском языке.\n\n"
|
||||
"Требования к названию:\n"
|
||||
"1. Живой русский язык, отражающий суть вопроса (не набор ключевых слов, а связное словосочетание).\n"
|
||||
"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}")
|
||||
@@ -2,7 +2,7 @@
|
||||
===============================================================================
|
||||
FILE: modules/web_api/routers/reports.py
|
||||
ROLE: REST API On-Demand генерации отчетов:
|
||||
- Сводка: за СЕГОДНЯ (оперативный контроль, текущий срез).
|
||||
- Сводка: за СЕГОДНЯ (по выбранному snapshot_id или последнему срезу).
|
||||
- Детальный и Упрощенный отчет: строго за ВЧЕРА по финальному срезу Y.
|
||||
===============================================================================
|
||||
"""
|
||||
@@ -40,13 +40,14 @@ class GenerateReportRequest(BaseModel):
|
||||
date: Optional[str] = None # ДД.ММ.ГГГГ
|
||||
time: Optional[str] = None # ЧЧ:ММ
|
||||
report_type: str # 'SVODKA', 'DETAILED', 'SIMPLIFIED', 'ALL'
|
||||
snapshot_id: Optional[str] = None # ⭐️ ID конкретного среза (например: '20261006_1200')
|
||||
|
||||
|
||||
@router.post("/generate")
|
||||
def api_generate_report(req: GenerateReportRequest):
|
||||
"""
|
||||
Генерирует выбранный отчет:
|
||||
- SVODKA: на текущую дату (date).
|
||||
- SVODKA: по выбранному snapshot_id (или на дату/время).
|
||||
- DETAILED / SIMPLIFIED: строго за вчерашний рабочий день по финальному срезу Y.
|
||||
"""
|
||||
target_date = (req.date or DATE_TODAY).replace('_', '.')
|
||||
@@ -54,11 +55,12 @@ def api_generate_report(req: GenerateReportRequest):
|
||||
r_type = req.report_type.upper()
|
||||
results = []
|
||||
|
||||
# 1. Ежедневная сводка (за СЕГОДНЯ)
|
||||
# 1. Ежедневная сводка
|
||||
if r_type in ["SVODKA", "ALL"]:
|
||||
res_svodka = generate_svodka_service(
|
||||
target_date=target_date,
|
||||
target_time=req.time
|
||||
target_time=req.time,
|
||||
snapshot_id=req.snapshot_id # ⭐️ Передаем срез
|
||||
)
|
||||
if res_svodka.get("status") == "success":
|
||||
results.append({
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""
|
||||
===============================================================================
|
||||
FILE: modules/web_api/routers/schedules.py
|
||||
ROLE: REST API управления графиками работы и генерации отчетов по опозданиям.
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional, List, Dict, Any
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from routers.auth import get_current_user
|
||||
from services.schedules.service import (
|
||||
get_all_templates,
|
||||
get_employee_schedules_list,
|
||||
update_employee_schedule
|
||||
)
|
||||
from services.reports.opozdaniya_builder import build_opozdaniya_workbook
|
||||
from config import DATE_TODAY
|
||||
|
||||
router = APIRouter(prefix="/api/v1/schedules", tags=["Schedules"])
|
||||
|
||||
|
||||
class UpdateScheduleRequest(BaseModel):
|
||||
employee_schedule_id: int
|
||||
template_id: int
|
||||
doc_basis: Optional[str] = None
|
||||
comment: Optional[str] = None
|
||||
date_from: Optional[str] = None
|
||||
date_to: Optional[str] = None
|
||||
|
||||
|
||||
class GenerateLateReportRequest(BaseModel):
|
||||
date_from: Optional[str] = None
|
||||
date_to: Optional[str] = None
|
||||
report_type: str = "WEEKLY"
|
||||
|
||||
|
||||
@router.get("/templates")
|
||||
def api_get_templates(current_user = Depends(get_current_user)):
|
||||
return {"templates": get_all_templates()}
|
||||
|
||||
|
||||
@router.get("/employees")
|
||||
def api_get_employees_schedules(
|
||||
q: Optional[str] = Query(None, description="Поиск по ФИО"),
|
||||
department: Optional[str] = Query(None, description="Фильтр по отделу"),
|
||||
mode: Optional[str] = Query(None, description="Фильтр по режиму работы"),
|
||||
current_user = Depends(get_current_user)
|
||||
):
|
||||
return {"items": get_employee_schedules_list(fio_query=q, department=department, work_mode=mode)}
|
||||
|
||||
|
||||
@router.put("/assign")
|
||||
def api_update_schedule(req: UpdateScheduleRequest, current_user = Depends(get_current_user)):
|
||||
success = update_employee_schedule(
|
||||
employee_schedule_id=req.employee_schedule_id,
|
||||
template_id=req.template_id,
|
||||
doc_basis=req.doc_basis,
|
||||
comment=req.comment,
|
||||
date_from=req.date_from,
|
||||
date_to=req.date_to
|
||||
)
|
||||
if not success:
|
||||
raise HTTPException(status_code=400, detail="Не удалось обновить график сотрудника")
|
||||
return {"status": "success", "message": "График успешно обновлен"}
|
||||
|
||||
|
||||
@router.post("/reports/late-arrivals")
|
||||
def api_generate_late_arrivals_report(req: GenerateLateReportRequest, current_user = Depends(get_current_user)):
|
||||
"""
|
||||
Генерирует Excel-отчет по опозданиям на базе opozdaniya_builder:
|
||||
- за один день (если date_from == date_to)
|
||||
- за рабочий диапазон (по умолчанию за текущую неделю: с ПН по ПТ)
|
||||
"""
|
||||
now = datetime.now()
|
||||
if req.date_from and req.date_to:
|
||||
d_start = datetime.strptime(req.date_from.replace('_', '.'), "%d.%m.%Y")
|
||||
d_end = datetime.strptime(req.date_to.replace('_', '.'), "%d.%m.%Y")
|
||||
else:
|
||||
d_start = now - timedelta(days=now.weekday())
|
||||
d_end = now
|
||||
|
||||
dates = []
|
||||
curr = d_start
|
||||
while curr <= d_end:
|
||||
if curr.weekday() < 5:
|
||||
dates.append(curr.strftime("%d.%m.%Y"))
|
||||
curr += timedelta(days=1)
|
||||
|
||||
if not dates:
|
||||
dates = [DATE_TODAY]
|
||||
|
||||
out_path = build_opozdaniya_workbook(dates)
|
||||
filename = os.path.basename(out_path)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"filename": filename,
|
||||
"download_url": f"/api/v1/files/download/reports/{filename}",
|
||||
"dates_included": dates
|
||||
}
|
||||
@@ -18,3 +18,43 @@ body {
|
||||
min-height: 100vh;
|
||||
min-height: -webkit-fill-available;
|
||||
}
|
||||
|
||||
/* Стилизация Markdown-контента ответов ассистента в стиле Gemini */
|
||||
.chat-markdown-content h1,
|
||||
.chat-markdown-content h2,
|
||||
.chat-markdown-content h3,
|
||||
.chat-markdown-content h4 {
|
||||
font-weight: 700;
|
||||
color: #0f172a;
|
||||
margin-top: 0.85rem;
|
||||
margin-bottom: 0.35rem;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
.chat-markdown-content p {
|
||||
margin-bottom: 0.45rem;
|
||||
}
|
||||
.chat-markdown-content p:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.chat-markdown-content ul {
|
||||
list-style-type: disc;
|
||||
margin-left: 1.25rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
.chat-markdown-content ol {
|
||||
list-style-type: decimal;
|
||||
margin-left: 1.25rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
.chat-markdown-content li {
|
||||
margin-bottom: 0.2rem;
|
||||
}
|
||||
.chat-markdown-content code:not([id^="code-block-"]) {
|
||||
padding: 0.15rem 0.35rem;
|
||||
border-radius: 0.375rem;
|
||||
background-color: #f1f5f9;
|
||||
color: #4338ca;
|
||||
font-size: 0.825rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
+145
-208
@@ -3,220 +3,153 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<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>
|
||||
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="icon" href="/favicon.ico" type="image/x-icon">
|
||||
<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>
|
||||
<link rel="stylesheet" href="/static/css/styles.css?v=2.6.0">
|
||||
</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">
|
||||
|
||||
<!-- ЛЕВАЯ КОЛОНКА (САЙДБАР) -->
|
||||
<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="flex items-center justify-between border-b border-slate-200 bg-white px-1 py-1 shrink-0">
|
||||
<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> Задачи
|
||||
<!-- ЛЕВЫЙ САЙДБАР (ШИРИНА 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">
|
||||
<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>
|
||||
<span>Задачи</span>
|
||||
</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">
|
||||
<i class="fa-solid fa-camera block text-sm mb-0.5"></i> Срезы
|
||||
<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 text-xs"></i>
|
||||
<span>Срезы</span>
|
||||
</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">
|
||||
<i class="fa-solid fa-address-book block text-sm mb-0.5"></i> Реестры
|
||||
<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 text-xs"></i>
|
||||
<span>Реестры</span>
|
||||
</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">
|
||||
<i class="fa-solid fa-terminal block text-sm mb-0.5"></i> Промпт
|
||||
<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 text-xs"></i>
|
||||
<span>Промпт</span>
|
||||
</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">
|
||||
<i class="fa-solid fa-comments block text-sm mb-0.5"></i> Контекст
|
||||
<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-brain text-xs"></i>
|
||||
<span>Контекст</span>
|
||||
</button>
|
||||
</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. ЗАДАЧИ -->
|
||||
<div id="sidebar-view-tasks" class="sidebar-view w-full h-full flex flex-col">
|
||||
<div id="tasks-list" class="space-y-2 flex-1"></div>
|
||||
<div id="sidebar-view-tasks" class="sidebar-view">
|
||||
<div id="tasks-list"></div>
|
||||
</div>
|
||||
|
||||
<!-- 2. СРЕЗЫ И ОТЧЕТЫ -->
|
||||
<div id="sidebar-view-snapshots" class="sidebar-view w-full space-y-3 hidden">
|
||||
|
||||
<!-- ПЕРИОД ВЫБОРКИ СРЕЗОВ -->
|
||||
<div class="p-2.5 bg-slate-50 rounded-xl border border-slate-200 shadow-xs space-y-2">
|
||||
<!-- 2. СРЕЗЫ -->
|
||||
<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="flex items-center justify-between">
|
||||
<span class="text-[11px] font-bold text-slate-600 uppercase flex items-center gap-1.5">
|
||||
<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>
|
||||
<span class="text-xs font-bold text-slate-700">Создать срез</span>
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<div>
|
||||
<label class="text-[10px] text-slate-400 block mb-0.5">С даты:</label>
|
||||
<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">
|
||||
<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">
|
||||
<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">
|
||||
</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 class="flex items-center gap-1.5 pt-1 border-t border-slate-200/60">
|
||||
<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">
|
||||
Сегодня
|
||||
</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 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">
|
||||
<i class="fa-solid fa-camera"></i>
|
||||
<span>Сделать срез</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Панель On-Demand генерации отчетов -->
|
||||
<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-700 uppercase flex items-center gap-1.5">
|
||||
<i class="fa-solid fa-file-excel text-emerald-600"></i> Сформировать отчет:
|
||||
</div>
|
||||
<div class="grid grid-cols-3 gap-1.5">
|
||||
<button onclick="generateReportDirect('SVODKA')" class="py-2 bg-emerald-50 hover:bg-emerald-100 text-emerald-700 border border-emerald-200 rounded-lg text-[10px] font-bold transition flex items-center justify-center gap-1">
|
||||
<i class="fa-solid fa-table-list"></i> Сводка
|
||||
</button>
|
||||
<button onclick="generateReportDirect('SIMPLIFIED')" class="py-2 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 border border-indigo-200 rounded-lg text-[10px] font-bold transition flex items-center justify-center gap-1">
|
||||
<i class="fa-solid fa-file-lines"></i> Упрощ.
|
||||
</button>
|
||||
<button onclick="generateReportDirect('DETAILED')" class="py-2 bg-purple-50 hover:bg-purple-100 text-purple-700 border border-purple-200 rounded-lg text-[10px] font-bold transition flex items-center justify-center gap-1">
|
||||
<i class="fa-solid fa-chart-column"></i> Детальн.
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between pt-1">
|
||||
<div class="p-2.5 bg-white border border-slate-200 rounded-xl shadow-xs space-y-2">
|
||||
<div class="flex items-center justify-between">
|
||||
<span id="snapshots-count-badge" class="text-xs font-bold text-slate-700">Срезы в базе: 0</span>
|
||||
<button onclick="loadSnapshotsView()" class="text-slate-400 hover:text-indigo-600 text-xs transition" title="Обновить список">
|
||||
<i class="fa-solid fa-rotate-right"></i>
|
||||
</div>
|
||||
<div class="grid grid-cols-4 gap-1">
|
||||
<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 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="setSnapshotDatePreset('days7')" class="py-1 text-[10px] bg-slate-100 hover:bg-slate-200 text-slate-700 rounded font-medium">7 дней</button>
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<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">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Сетка отчетов без верхней Сводки (Сводка генерируется на плашках срезов) -->
|
||||
<div class="grid grid-cols-3 gap-2 mb-2">
|
||||
<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-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>
|
||||
</div>
|
||||
|
||||
<div id="snapshots-list" class="space-y-2"></div>
|
||||
</div>
|
||||
|
||||
<!-- 3. РЕЕСТРЫ -->
|
||||
<div id="sidebar-view-registries" class="sidebar-view w-full space-y-3 hidden">
|
||||
<div class="grid grid-cols-2 gap-1 p-1 bg-slate-200/60 rounded-xl">
|
||||
<button data-subtab="exceptions" onclick="switchRegistrySubTab('exceptions')" class="registry-subtab-btn py-1 text-[11px] rounded-lg transition text-center flex items-center justify-center gap-1">
|
||||
<i class="fa-solid fa-user-shield text-[10px]"></i> Исключения
|
||||
</button>
|
||||
<button data-subtab="remote" onclick="switchRegistrySubTab('remote')" class="registry-subtab-btn py-1 text-[11px] rounded-lg transition text-center flex items-center justify-center gap-1">
|
||||
<i class="fa-solid fa-house-laptop text-[10px]"></i> Удаленщики
|
||||
</button>
|
||||
<button data-subtab="local_trip" onclick="switchRegistrySubTab('local_trip')" class="registry-subtab-btn py-1 text-[11px] rounded-lg transition text-center flex items-center justify-center gap-1">
|
||||
<i class="fa-solid fa-location-dot text-[10px]"></i> Мест. командир.
|
||||
</button>
|
||||
<button data-subtab="other" onclick="switchRegistrySubTab('other')" class="registry-subtab-btn py-1 text-[11px] rounded-lg transition text-center flex items-center justify-center gap-1">
|
||||
<i class="fa-solid fa-clipboard-question text-[10px]"></i> Иное
|
||||
</button>
|
||||
</div>
|
||||
<div id="registry-content-container" class="space-y-3"></div>
|
||||
|
||||
<!-- 3. РЕЕСТРЫ (5 ПОДВКЛАДОК: ВКЛЮЧАЯ ГРАФИКИ РАБОТЫ) -->
|
||||
<div id="sidebar-view-registries" class="sidebar-view hidden">
|
||||
<div class="grid grid-cols-5 gap-1 p-1 bg-slate-200/60 rounded-xl mb-3">
|
||||
<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>
|
||||
<button data-subtab="remote" onclick="switchRegistrySubTab('remote')" class="registry-subtab-btn py-1 text-[10px] font-semibold rounded-lg text-slate-600">Удален.</button>
|
||||
<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>
|
||||
<button data-subtab="other" onclick="switchRegistrySubTab('other')" class="registry-subtab-btn py-1 text-[10px] font-semibold rounded-lg text-slate-600">Иное</button>
|
||||
<button data-subtab="schedules" onclick="switchRegistrySubTab('schedules')" class="registry-subtab-btn py-1 text-[10px] font-semibold rounded-lg text-slate-600">Графики</button>
|
||||
</div>
|
||||
<div id="registry-content-container"></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 id="sidebar-view-prompts" class="sidebar-view hidden">
|
||||
<div id="prompts-content-container"></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 id="sidebar-view-context" class="sidebar-view hidden">
|
||||
<div id="context-content-container"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ПОДВАЛ -->
|
||||
<div class="p-3 border-t border-slate-200 bg-slate-50 flex items-center justify-between shrink-0">
|
||||
<!-- ПОДВАЛ САЙДБАРА -->
|
||||
<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-full bg-indigo-600 text-white flex items-center justify-center font-bold text-xs shadow-sm shrink-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 flex flex-col">
|
||||
<span id="user-display-name" class="text-xs font-bold text-slate-800 truncate">Пользователь</span>
|
||||
<span id="user-display-role" class="text-[10px] text-slate-400">Оператор</span>
|
||||
<div 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 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="Сменить пароль">
|
||||
<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 type="button" onclick="AuthManager.logout()" class="p-1.5 text-slate-400 hover:text-rose-600 hover:bg-rose-50 rounded-lg transition" title="Выйти из системы">
|
||||
<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>
|
||||
@@ -247,22 +180,10 @@
|
||||
</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 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>
|
||||
@@ -273,7 +194,6 @@
|
||||
</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="Прикрепить файл">
|
||||
@@ -282,44 +202,61 @@
|
||||
<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>
|
||||
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>
|
||||
|
||||
<!-- ПОЛНОЭКРАННЫЙ ОВЕРЛЕЙ 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 id="modals-container"></div>
|
||||
|
||||
<!-- ПОДКЛЮЧЕНИЕ СКРИПТОВ -->
|
||||
<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/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/registries.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/topics.js?v=2.6.0"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||||
<script src="/static/js/chat/scroll.js?v=2.6.0"></script>
|
||||
<script src="/static/js/chat/messages.js?v=2.6.0"></script>
|
||||
<script src="/static/js/chat/input.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/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>
|
||||
</body>
|
||||
</html>
|
||||
@@ -30,7 +30,8 @@ async function loadModals() {
|
||||
'profile_modal.html',
|
||||
'admin_modal.html',
|
||||
'snapshot_inspector_modal.html',
|
||||
'presence_modal.html'
|
||||
'presence_modal.html',
|
||||
'confirm_modal.html'
|
||||
];
|
||||
|
||||
const container = document.getElementById('modals-container');
|
||||
@@ -102,6 +103,7 @@ async function handleLoginSubmit(e) {
|
||||
hideAuthModal();
|
||||
updateUIState();
|
||||
if (window.SidebarManager) SidebarManager.switchTab('tasks');
|
||||
if (window.TopicsManager && typeof window.TopicsManager.init === 'function') window.TopicsManager.init();
|
||||
} else {
|
||||
const err = await res.json();
|
||||
if (errEl) {
|
||||
@@ -249,7 +251,7 @@ async function deleteAdminUser(id, username) {
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 4. ВСПОМОГАТЕЛЬНЫЕ ФОРМАТЕРЫ И МОДАЛКА УДАЛЕНЩИКОВ
|
||||
// 4. ВСПОМОГАТЕЛЬНЫЕ ФОРМАТЕРЫ И МОДАЛКА УДАЛЕНЩИКОВ (ИЗ СНАПШОТА)
|
||||
// ============================================================================
|
||||
function dmyToYmd(str) {
|
||||
if (!str) return "";
|
||||
@@ -383,7 +385,7 @@ document.addEventListener("DOMContentLoaded", async () => {
|
||||
setupStaffAutocomplete(rwFioInput, "rw-fio-suggestions");
|
||||
}
|
||||
|
||||
//3.1 Автокомплит для местных командировок и иного
|
||||
// 3.1 Автокомплит для местных командировок и иного
|
||||
const maFioInput = document.getElementById("manual-absence-fio-input");
|
||||
if (maFioInput && typeof setupStaffAutocomplete === "function") {
|
||||
setupStaffAutocomplete(maFioInput, "manual-absence-suggestions");
|
||||
@@ -399,11 +401,11 @@ document.addEventListener("DOMContentLoaded", async () => {
|
||||
});
|
||||
}
|
||||
|
||||
// 5. Проверка сессии пользователя
|
||||
// 5. Проверка сессии пользователя и запуск менеджеров
|
||||
if (IS_GUEST) {
|
||||
hideAuthModal();
|
||||
updateUIState();
|
||||
} else if (AuthManager && AuthManager.isAuthenticated()) {
|
||||
} else if (typeof AuthManager !== 'undefined' && AuthManager.isAuthenticated()) {
|
||||
hideAuthModal();
|
||||
updateUIState();
|
||||
if (typeof loadTasks === "function") {
|
||||
@@ -412,6 +414,9 @@ document.addEventListener("DOMContentLoaded", async () => {
|
||||
if (window.SidebarManager) {
|
||||
SidebarManager.init();
|
||||
}
|
||||
if (window.TopicsManager && typeof window.TopicsManager.init === "function") {
|
||||
TopicsManager.init();
|
||||
}
|
||||
} else {
|
||||
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,389 +1,49 @@
|
||||
/**
|
||||
* ===============================================================================
|
||||
* FILE: modules/web_api/static/js/chat/core.js
|
||||
* ROLE: Ядро чата: полноэкранный Drag-and-Drop оверлей, авто-высота инпута (24px),
|
||||
* надежный расчет скролла вопроса к верху окна, крупный шрифт text-sm.
|
||||
* ROLE: Сетевой диспетчер чата: отправка сообщений и файлов на бэкенд FastAPI.
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
let currentAttachedFile = null;
|
||||
|
||||
const CHAT_INPUT_STORAGE_KEY = "scud_chat_input_history";
|
||||
let chatInputHistory = JSON.parse(localStorage.getItem(CHAT_INPUT_STORAGE_KEY) || "[]");
|
||||
let chatHistoryIndex = -1;
|
||||
let temporaryCurrentInput = "";
|
||||
|
||||
function saveCommandToHistory(commandText) {
|
||||
if (!commandText || !commandText.trim()) return;
|
||||
const cleanCmd = commandText.trim();
|
||||
if (cleanCmd.startsWith("action:save_draft_")) return;
|
||||
|
||||
chatInputHistory = chatInputHistory.filter(item => item !== cleanCmd);
|
||||
chatInputHistory.push(cleanCmd);
|
||||
if (chatInputHistory.length > 50) chatInputHistory.shift();
|
||||
localStorage.setItem(CHAT_INPUT_STORAGE_KEY, JSON.stringify(chatInputHistory));
|
||||
chatHistoryIndex = -1;
|
||||
}
|
||||
|
||||
// ⭐️ ЕДИНАЯ ФУНКЦИЯ СКРОЛЛА: выравнивание вопроса к верхней границе
|
||||
function scrollToUserMessageTop() {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return;
|
||||
|
||||
const userBubbles = container.querySelectorAll(".user-chat-bubble");
|
||||
const targetEl = userBubbles[userBubbles.length - 1];
|
||||
if (!targetEl) return;
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
const targetScroll = targetEl.offsetTop - container.offsetTop - 12;
|
||||
|
||||
container.scrollTo({
|
||||
top: Math.max(0, targetScroll),
|
||||
behavior: 'smooth'
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function updateInputHeightAndFade(textarea) {
|
||||
if (!textarea) return;
|
||||
|
||||
if (!textarea.value || textarea.value.trim() === '') {
|
||||
textarea.style.height = '32px';
|
||||
textarea.style.overflowY = 'hidden';
|
||||
textarea.style.maskImage = 'none';
|
||||
textarea.style.webkitMaskImage = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
textarea.style.height = 'auto';
|
||||
const minHeight = 32;
|
||||
const maxHeight = 140;
|
||||
const currentScrollHeight = textarea.scrollHeight;
|
||||
|
||||
if (currentScrollHeight <= minHeight + 2) {
|
||||
textarea.style.height = minHeight + 'px';
|
||||
textarea.style.overflowY = 'hidden';
|
||||
textarea.style.maskImage = 'none';
|
||||
textarea.style.webkitMaskImage = 'none';
|
||||
} else if (currentScrollHeight > maxHeight) {
|
||||
textarea.style.height = maxHeight + 'px';
|
||||
textarea.style.overflowY = 'auto';
|
||||
textarea.style.maskImage = 'linear-gradient(to bottom, transparent 0%, black 14px, black 100%)';
|
||||
textarea.style.webkitMaskImage = 'linear-gradient(to bottom, transparent 0%, black 14px, black 100%)';
|
||||
} else {
|
||||
textarea.style.height = currentScrollHeight + 'px';
|
||||
textarea.style.overflowY = 'hidden';
|
||||
textarea.style.maskImage = 'none';
|
||||
textarea.style.webkitMaskImage = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function appendUserMessage(text, filename = null) {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return;
|
||||
|
||||
const msgId = 'user-msg-' + Date.now();
|
||||
let fileBadge = '';
|
||||
if (filename) {
|
||||
fileBadge = `
|
||||
<div class="inline-flex items-center gap-1.5 px-2.5 py-1 mb-2 bg-indigo-700/80 rounded-lg text-xs font-semibold text-white shadow-xs">
|
||||
<i class="fa-solid fa-paperclip text-xs"></i>
|
||||
<span class="truncate max-w-xs">${escapeHtml(filename)}</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
const msgHtml = `
|
||||
<div id="${msgId}" class="user-chat-bubble relative flex gap-3 max-w-4xl mx-auto w-full justify-end pt-3 scroll-mt-4">
|
||||
<div class="flex-1 max-w-2xl bg-indigo-600 text-white rounded-2xl rounded-tr-none p-4 shadow-sm">
|
||||
${fileBadge}
|
||||
<div class="text-sm leading-relaxed whitespace-pre-wrap">${escapeHtml(text)}</div>
|
||||
</div>
|
||||
<div class="w-8 h-8 rounded-lg bg-slate-200 text-slate-600 flex items-center justify-center shrink-0 shadow-sm mt-0.5 font-bold text-sm">
|
||||
<i class="fa-solid fa-user"></i>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
container.insertAdjacentHTML("beforeend", msgHtml);
|
||||
}
|
||||
|
||||
function appendAssistantLoading() {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return null;
|
||||
|
||||
const loadingId = 'loading-' + Date.now();
|
||||
const html = `
|
||||
<div id="${loadingId}" class="flex gap-3 max-w-4xl mx-auto w-full pt-1">
|
||||
<div class="w-8 h-8 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm mt-0.5">
|
||||
<i class="fa-solid fa-robot text-sm"></i>
|
||||
</div>
|
||||
<div class="flex-1 bg-white border border-slate-200 rounded-2xl rounded-tl-none p-4 shadow-sm">
|
||||
<div class="text-sm text-slate-500 flex items-center gap-2">
|
||||
<i class="fa-solid fa-spinner fa-spin text-indigo-600"></i>
|
||||
<span>ИИ обрабатывает запрос...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
container.insertAdjacentHTML("beforeend", html);
|
||||
return loadingId;
|
||||
}
|
||||
|
||||
function appendAssistantMessage(text, buttons = [], actionPayload = null) {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return;
|
||||
|
||||
let payloadHtml = '';
|
||||
let isHtmlBody = false;
|
||||
|
||||
if (actionPayload) {
|
||||
if (actionPayload.type === 'SNAPSHOTS_CARD' && typeof renderSnapshotsCard === 'function') {
|
||||
payloadHtml = renderSnapshotsCard(actionPayload.data);
|
||||
} else if (actionPayload.type === 'TASK_INTERACTIVE_CARD' && typeof renderInteractiveTaskCard === 'function') {
|
||||
payloadHtml = renderInteractiveTaskCard(actionPayload.tasks);
|
||||
} else if (actionPayload.type === 'FILE_DOWNLOAD_CARD') {
|
||||
const dlUrl = actionPayload.download_url || '#';
|
||||
const fName = actionPayload.filename || '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 = '';
|
||||
if (!actionPayload || (actionPayload.type !== 'PROMPT_EDITOR' && actionPayload.type !== 'RULES_EDITOR')) {
|
||||
const allButtons = (buttons && buttons.length > 0) ? buttons : (actionPayload && actionPayload.buttons ? actionPayload.buttons : []);
|
||||
if (allButtons && Array.isArray(allButtons) && allButtons.length > 0) {
|
||||
buttonsHtml = `
|
||||
<div class="flex flex-wrap gap-2 mt-3.5 pt-2.5 border-t border-slate-100">
|
||||
${allButtons.map(b => `
|
||||
<button onclick="window.sendChatAction('${escapeHtml(b.value || b.action || b.title || '')}')"
|
||||
class="px-3 py-1.5 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 rounded-lg text-xs font-semibold border border-indigo-200 transition">
|
||||
${escapeHtml(b.label || b.title || b.action)}
|
||||
</button>
|
||||
`).join('')}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
const bodyContent = isHtmlBody ? text : escapeHtml(text);
|
||||
|
||||
const html = `
|
||||
<div class="flex gap-3 max-w-4xl mx-auto w-full pt-1">
|
||||
<div class="w-8 h-8 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm mt-0.5">
|
||||
<i class="fa-solid fa-robot text-sm"></i>
|
||||
</div>
|
||||
<div class="flex-1 bg-white border border-slate-200 rounded-2xl rounded-tl-none p-4 shadow-sm min-w-0">
|
||||
<div class="text-[11px] font-bold text-indigo-600 uppercase tracking-wider mb-1.5">ИИ-ассистент SCUD Orion AI</div>
|
||||
<div class="text-sm text-slate-800 leading-relaxed whitespace-pre-wrap">${bodyContent}</div>
|
||||
${payloadHtml}
|
||||
${buttonsHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
container.insertAdjacentHTML("beforeend", html);
|
||||
}
|
||||
|
||||
window.filterInspectTable = function(tableId, query) {
|
||||
const table = document.getElementById(tableId);
|
||||
if (!table) return;
|
||||
const q = (query || '').trim().toLowerCase();
|
||||
const rows = table.querySelectorAll('.inspect-row');
|
||||
rows.forEach(r => {
|
||||
const fio = r.getAttribute('data-fio') || '';
|
||||
const dept = r.getAttribute('data-dept') || '';
|
||||
if (!q || fio.includes(q) || dept.includes(q)) {
|
||||
r.classList.remove('hidden');
|
||||
} else {
|
||||
r.classList.add('hidden');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
window.sendChatAction = function(actionText) {
|
||||
if (!actionText || !actionText.trim()) return;
|
||||
const input = document.getElementById("user-input");
|
||||
if (input) {
|
||||
input.value = actionText.trim();
|
||||
updateInputHeightAndFade(input);
|
||||
window.ChatInput.updateInputHeightAndFade(input);
|
||||
}
|
||||
window.sendMessage();
|
||||
};
|
||||
|
||||
window.submitPromptDraftToDiff = function(editorId) {
|
||||
const textarea = document.getElementById(editorId);
|
||||
if (!textarea) return;
|
||||
const newText = textarea.value.trim();
|
||||
if (!newText) {
|
||||
alert("Текст системного промпта не может быть пустым");
|
||||
return;
|
||||
}
|
||||
|
||||
const command = `action:save_draft_prompt:::${newText}`;
|
||||
const input = document.getElementById("user-input");
|
||||
if (input) input.value = command;
|
||||
window.sendMessage();
|
||||
};
|
||||
|
||||
window.submitRulesDraftToDiff = function(editorId) {
|
||||
const textarea = document.getElementById(editorId);
|
||||
if (!textarea) return;
|
||||
const newText = textarea.value.trim();
|
||||
if (!newText) {
|
||||
alert("Правила не могут быть пустыми");
|
||||
return;
|
||||
}
|
||||
|
||||
const command = `action:save_draft_rules:::${newText}`;
|
||||
const input = document.getElementById("user-input");
|
||||
if (input) input.value = command;
|
||||
window.sendMessage();
|
||||
};
|
||||
|
||||
window.sendMessage = async function() {
|
||||
const input = document.getElementById("user-input");
|
||||
if (!input) return;
|
||||
|
||||
const messageText = input.value.trim();
|
||||
const fileToSend = currentAttachedFile;
|
||||
const fileToSend = window.ChatInput.getAttachedFile();
|
||||
|
||||
if (!messageText && !fileToSend) return;
|
||||
|
||||
saveCommandToHistory(messageText);
|
||||
window.ChatInput.saveCommandToHistory(messageText);
|
||||
window.ChatInput.resetInput(input);
|
||||
|
||||
input.value = "";
|
||||
input.style.height = '32px';
|
||||
input.style.overflowY = 'hidden';
|
||||
input.style.maskImage = 'none';
|
||||
input.style.webkitMaskImage = 'none';
|
||||
window.clearAttachedFile();
|
||||
const activeSessionId = (window.TopicsManager && typeof window.TopicsManager.getActiveSessionId === "function")
|
||||
? window.TopicsManager.getActiveSessionId()
|
||||
: "session_main";
|
||||
|
||||
// 1. Отрисовка сообщения пользователя в ленте
|
||||
if (!messageText.startsWith("action:save_draft_prompt:::") && !messageText.startsWith("action:save_draft_rules:::")) {
|
||||
appendUserMessage(
|
||||
window.appendUserMessage(
|
||||
messageText || (fileToSend ? `Прикреплен файл: ${fileToSend.name}` : ''),
|
||||
fileToSend ? fileToSend.name : null
|
||||
);
|
||||
} else {
|
||||
appendUserMessage("Сформировать предпросмотр изменений");
|
||||
window.appendUserMessage("Сформировать предпросмотр изменений");
|
||||
}
|
||||
|
||||
// 2. Вставка лоадера
|
||||
const loadingId = appendAssistantLoading();
|
||||
|
||||
// 3. Вызов точного скролла
|
||||
scrollToUserMessageTop();
|
||||
const loadingId = window.appendAssistantLoading();
|
||||
if (window.scrollToUserMessageTop) {
|
||||
window.scrollToUserMessageTop();
|
||||
}
|
||||
|
||||
try {
|
||||
let res;
|
||||
@@ -391,13 +51,11 @@ window.sendMessage = async function() {
|
||||
const formData = new FormData();
|
||||
formData.append("file", fileToSend);
|
||||
formData.append("message", messageText);
|
||||
formData.append("session_id", "web_session_main");
|
||||
formData.append("session_id", activeSessionId);
|
||||
|
||||
res = await fetch("/api/v1/chat/upload", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Authorization": AuthManager.getAuthHeaders()["Authorization"]
|
||||
},
|
||||
headers: { "Authorization": AuthManager.getAuthHeaders()["Authorization"] },
|
||||
body: formData
|
||||
});
|
||||
|
||||
@@ -407,7 +65,7 @@ window.sendMessage = async function() {
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
message: messageText || `Загружен файл: ${fileToSend.name}`,
|
||||
session_id: "web_session_main"
|
||||
session_id: activeSessionId
|
||||
})
|
||||
});
|
||||
}
|
||||
@@ -417,7 +75,7 @@ window.sendMessage = async function() {
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
message: messageText,
|
||||
session_id: "web_session_main"
|
||||
session_id: activeSessionId
|
||||
})
|
||||
});
|
||||
}
|
||||
@@ -431,151 +89,26 @@ window.sendMessage = async function() {
|
||||
const buttons = data.buttons || [];
|
||||
const actionPayload = data.action_payload || null;
|
||||
|
||||
appendAssistantMessage(replyText, buttons, actionPayload);
|
||||
window.appendAssistantMessage(replyText, buttons, actionPayload);
|
||||
|
||||
if (window.SidebarManager) {
|
||||
SidebarManager.renderContent();
|
||||
}
|
||||
|
||||
if (window.TopicsManager && typeof window.TopicsManager.loadTopics === "function") {
|
||||
window.TopicsManager.loadTopics();
|
||||
setTimeout(() => {
|
||||
window.TopicsManager.loadTopics();
|
||||
}, 2500);
|
||||
}
|
||||
} else {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
appendAssistantMessage(`⚠️ Ошибка сервера (${res.status}): ${err.detail || "Не удалось получить ответ"}`);
|
||||
window.appendAssistantMessage(`⚠️ Ошибка сервера (${res.status}): ${err.detail || "Не удалось получить ответ"}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Ошибка отправки сообщения:", err);
|
||||
const loaderEl = document.getElementById(loadingId);
|
||||
if (loaderEl) loaderEl.remove();
|
||||
appendAssistantMessage("⚠️ Ошибка соединения с сервером при отправке сообщения.");
|
||||
window.appendAssistantMessage("⚠️ Ошибка соединения с сервером при отправке сообщения.");
|
||||
}
|
||||
};
|
||||
|
||||
window.clearAttachedFile = function() {
|
||||
currentAttachedFile = null;
|
||||
const preview = document.getElementById("file-attachment-preview");
|
||||
const nameEl = document.getElementById("file-attachment-name");
|
||||
const fileInput = document.getElementById("file-upload-input");
|
||||
|
||||
if (preview) preview.classList.add("hidden");
|
||||
if (nameEl) nameEl.innerText = "";
|
||||
if (fileInput) fileInput.value = "";
|
||||
};
|
||||
|
||||
function handleFileSelected(file) {
|
||||
if (!file) return;
|
||||
currentAttachedFile = file;
|
||||
const preview = document.getElementById("file-attachment-preview");
|
||||
const nameEl = document.getElementById("file-attachment-name");
|
||||
|
||||
if (preview && nameEl) {
|
||||
nameEl.innerText = file.name;
|
||||
preview.classList.remove("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const input = document.getElementById("user-input");
|
||||
const fileInput = document.getElementById("file-upload-input");
|
||||
const overlay = document.getElementById("global-drag-overlay");
|
||||
|
||||
if (input) {
|
||||
input.style.lineHeight = '24px';
|
||||
input.style.height = '32px';
|
||||
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") {
|
||||
if (e.shiftKey) return;
|
||||
e.preventDefault();
|
||||
window.sendMessage();
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === "ArrowUp") {
|
||||
const isSingleLine = !input.value.includes("\n");
|
||||
const isAtBeginning = input.selectionStart === 0 && input.selectionEnd === 0;
|
||||
|
||||
if (isSingleLine || isAtBeginning) {
|
||||
if (chatInputHistory.length > 0) {
|
||||
e.preventDefault();
|
||||
if (chatHistoryIndex === -1) {
|
||||
temporaryCurrentInput = input.value;
|
||||
chatHistoryIndex = chatInputHistory.length - 1;
|
||||
} else if (chatHistoryIndex > 0) {
|
||||
chatHistoryIndex--;
|
||||
}
|
||||
input.value = chatInputHistory[chatHistoryIndex];
|
||||
updateInputHeightAndFade(input);
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
}
|
||||
}
|
||||
} else if (e.key === "ArrowDown") {
|
||||
const isSingleLine = !input.value.includes("\n");
|
||||
const isAtEnd = input.selectionStart === input.value.length;
|
||||
|
||||
if (isSingleLine || isAtEnd) {
|
||||
if (chatHistoryIndex !== -1) {
|
||||
e.preventDefault();
|
||||
if (chatHistoryIndex < chatInputHistory.length - 1) {
|
||||
chatHistoryIndex++;
|
||||
input.value = chatInputHistory[chatHistoryIndex];
|
||||
} else {
|
||||
chatHistoryIndex = -1;
|
||||
input.value = temporaryCurrentInput;
|
||||
}
|
||||
updateInputHeightAndFade(input);
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
input.addEventListener("input", function() {
|
||||
updateInputHeightAndFade(this);
|
||||
chatHistoryIndex = -1;
|
||||
});
|
||||
}
|
||||
|
||||
if (fileInput) {
|
||||
fileInput.addEventListener("change", (e) => {
|
||||
if (e.target.files && e.target.files[0]) {
|
||||
handleFileSelected(e.target.files[0]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let dragCounter = 0;
|
||||
|
||||
window.addEventListener('dragenter', (e) => {
|
||||
e.preventDefault();
|
||||
dragCounter++;
|
||||
if (overlay) {
|
||||
overlay.classList.remove('hidden');
|
||||
}
|
||||
}, false);
|
||||
|
||||
window.addEventListener('dragleave', (e) => {
|
||||
e.preventDefault();
|
||||
dragCounter--;
|
||||
if (dragCounter <= 0) {
|
||||
dragCounter = 0;
|
||||
if (overlay) {
|
||||
overlay.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
}, false);
|
||||
|
||||
window.addEventListener('dragover', (e) => {
|
||||
e.preventDefault();
|
||||
}, false);
|
||||
|
||||
window.addEventListener('drop', (e) => {
|
||||
e.preventDefault();
|
||||
dragCounter = 0;
|
||||
if (overlay) {
|
||||
overlay.classList.add('hidden');
|
||||
}
|
||||
|
||||
const dt = e.dataTransfer;
|
||||
if (dt && dt.files && dt.files[0]) {
|
||||
handleFileSelected(dt.files[0]);
|
||||
}
|
||||
}, false);
|
||||
});
|
||||
@@ -0,0 +1,207 @@
|
||||
/**
|
||||
* ===============================================================================
|
||||
* FILE: modules/web_api/static/js/chat/input.js
|
||||
* ROLE: Управление полем ввода (textarea), автовысота, история команд и Drag-and-Drop.
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
window.ChatInput = (function() {
|
||||
let currentAttachedFile = null;
|
||||
const CHAT_INPUT_STORAGE_KEY = "scud_chat_input_history";
|
||||
let chatInputHistory = JSON.parse(localStorage.getItem(CHAT_INPUT_STORAGE_KEY) || "[]");
|
||||
let chatHistoryIndex = -1;
|
||||
let temporaryCurrentInput = "";
|
||||
|
||||
function saveCommandToHistory(commandText) {
|
||||
if (!commandText || !commandText.trim()) return;
|
||||
const cleanCmd = commandText.trim();
|
||||
if (cleanCmd.startsWith("action:save_draft_")) return;
|
||||
|
||||
chatInputHistory = chatInputHistory.filter(item => item !== cleanCmd);
|
||||
chatInputHistory.push(cleanCmd);
|
||||
if (chatInputHistory.length > 50) chatInputHistory.shift();
|
||||
localStorage.setItem(CHAT_INPUT_STORAGE_KEY, JSON.stringify(chatInputHistory));
|
||||
chatHistoryIndex = -1;
|
||||
}
|
||||
|
||||
function updateInputHeightAndFade(textarea) {
|
||||
if (!textarea) return;
|
||||
|
||||
if (!textarea.value || textarea.value.trim() === '') {
|
||||
textarea.style.height = '32px';
|
||||
textarea.style.overflowY = 'hidden';
|
||||
textarea.style.maskImage = 'none';
|
||||
textarea.style.webkitMaskImage = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
textarea.style.height = 'auto';
|
||||
const minHeight = 32;
|
||||
const maxHeight = 140;
|
||||
const currentScrollHeight = textarea.scrollHeight;
|
||||
|
||||
if (currentScrollHeight <= minHeight + 2) {
|
||||
textarea.style.height = minHeight + 'px';
|
||||
textarea.style.overflowY = 'hidden';
|
||||
textarea.style.maskImage = 'none';
|
||||
textarea.style.webkitMaskImage = 'none';
|
||||
} else if (currentScrollHeight > maxHeight) {
|
||||
textarea.style.height = maxHeight + 'px';
|
||||
textarea.style.overflowY = 'auto';
|
||||
textarea.style.maskImage = 'linear-gradient(to bottom, transparent 0%, black 14px, black 100%)';
|
||||
textarea.style.webkitMaskImage = 'linear-gradient(to bottom, transparent 0%, black 14px, black 100%)';
|
||||
} else {
|
||||
textarea.style.height = currentScrollHeight + 'px';
|
||||
textarea.style.overflowY = 'hidden';
|
||||
textarea.style.maskImage = 'none';
|
||||
textarea.style.webkitMaskImage = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function clearAttachedFile() {
|
||||
currentAttachedFile = null;
|
||||
const preview = document.getElementById("file-attachment-preview");
|
||||
const nameEl = document.getElementById("file-attachment-name");
|
||||
const fileInput = document.getElementById("file-upload-input");
|
||||
|
||||
if (preview) preview.classList.add("hidden");
|
||||
if (nameEl) nameEl.innerText = "";
|
||||
if (fileInput) fileInput.value = "";
|
||||
}
|
||||
|
||||
function handleFileSelected(file) {
|
||||
if (!file) return;
|
||||
currentAttachedFile = file;
|
||||
const preview = document.getElementById("file-attachment-preview");
|
||||
const nameEl = document.getElementById("file-attachment-name");
|
||||
|
||||
if (preview && nameEl) {
|
||||
nameEl.innerText = file.name;
|
||||
preview.classList.remove("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
function getAttachedFile() {
|
||||
return currentAttachedFile;
|
||||
}
|
||||
|
||||
function resetInput(input) {
|
||||
if (!input) return;
|
||||
input.value = "";
|
||||
input.style.height = '32px';
|
||||
input.style.overflowY = 'hidden';
|
||||
input.style.maskImage = 'none';
|
||||
input.style.webkitMaskImage = 'none';
|
||||
clearAttachedFile();
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const input = document.getElementById("user-input");
|
||||
const fileInput = document.getElementById("file-upload-input");
|
||||
const overlay = document.getElementById("global-drag-overlay");
|
||||
|
||||
if (input) {
|
||||
input.style.lineHeight = '24px';
|
||||
input.style.height = '32px';
|
||||
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") {
|
||||
if (e.shiftKey) return;
|
||||
e.preventDefault();
|
||||
window.sendMessage();
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === "ArrowUp") {
|
||||
const isSingleLine = !input.value.includes("\n");
|
||||
const isAtBeginning = input.selectionStart === 0 && input.selectionEnd === 0;
|
||||
|
||||
if (isSingleLine || isAtBeginning) {
|
||||
if (chatInputHistory.length > 0) {
|
||||
e.preventDefault();
|
||||
if (chatHistoryIndex === -1) {
|
||||
temporaryCurrentInput = input.value;
|
||||
chatHistoryIndex = chatInputHistory.length - 1;
|
||||
} else if (chatHistoryIndex > 0) {
|
||||
chatHistoryIndex--;
|
||||
}
|
||||
input.value = chatInputHistory[chatHistoryIndex];
|
||||
updateInputHeightAndFade(input);
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
}
|
||||
}
|
||||
} else if (e.key === "ArrowDown") {
|
||||
const isSingleLine = !input.value.includes("\n");
|
||||
const isAtEnd = input.selectionStart === input.value.length;
|
||||
|
||||
if (isSingleLine || isAtEnd) {
|
||||
if (chatHistoryIndex !== -1) {
|
||||
e.preventDefault();
|
||||
if (chatHistoryIndex < chatInputHistory.length - 1) {
|
||||
chatHistoryIndex++;
|
||||
input.value = chatInputHistory[chatHistoryIndex];
|
||||
} else {
|
||||
chatHistoryIndex = -1;
|
||||
input.value = temporaryCurrentInput;
|
||||
}
|
||||
updateInputHeightAndFade(input);
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
input.addEventListener("input", function() {
|
||||
updateInputHeightAndFade(this);
|
||||
chatHistoryIndex = -1;
|
||||
});
|
||||
}
|
||||
|
||||
if (fileInput) {
|
||||
fileInput.addEventListener("change", (e) => {
|
||||
if (e.target.files && e.target.files[0]) {
|
||||
handleFileSelected(e.target.files[0]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let dragCounter = 0;
|
||||
window.addEventListener('dragenter', (e) => {
|
||||
e.preventDefault();
|
||||
dragCounter++;
|
||||
if (overlay) overlay.classList.remove('hidden');
|
||||
}, false);
|
||||
|
||||
window.addEventListener('dragleave', (e) => {
|
||||
e.preventDefault();
|
||||
dragCounter--;
|
||||
if (dragCounter <= 0) {
|
||||
dragCounter = 0;
|
||||
if (overlay) overlay.classList.add('hidden');
|
||||
}
|
||||
}, false);
|
||||
|
||||
window.addEventListener('dragover', (e) => { e.preventDefault(); }, false);
|
||||
|
||||
window.addEventListener('drop', (e) => {
|
||||
e.preventDefault();
|
||||
dragCounter = 0;
|
||||
if (overlay) overlay.classList.add('hidden');
|
||||
const dt = e.dataTransfer;
|
||||
if (dt && dt.files && dt.files[0]) {
|
||||
handleFileSelected(dt.files[0]);
|
||||
}
|
||||
}, false);
|
||||
});
|
||||
|
||||
return {
|
||||
saveCommandToHistory,
|
||||
updateInputHeightAndFade,
|
||||
clearAttachedFile,
|
||||
getAttachedFile,
|
||||
resetInput
|
||||
};
|
||||
})();
|
||||
|
||||
// Для совместимости с вызовами из HTML
|
||||
window.clearAttachedFile = window.ChatInput.clearAttachedFile;
|
||||
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* ===============================================================================
|
||||
* FILE: modules/web_api/static/js/chat/messages.js
|
||||
* ROLE: Рендеринг сообщений на базе marked.js с поддержкой marked v4-v14+.
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
function safeEscapeCode(str) {
|
||||
if (!str) return '';
|
||||
return String(str)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function renderMarkdownGemini(rawText) {
|
||||
if (!rawText || typeof rawText !== 'string') return '';
|
||||
|
||||
if (typeof marked === 'undefined') {
|
||||
return safeEscapeCode(rawText).replace(/\n/g, '<br>');
|
||||
}
|
||||
|
||||
const renderer = new marked.Renderer();
|
||||
|
||||
// Переопределяем ТОЛЬКО блоки кода (совместимо со всеми версиями marked)
|
||||
renderer.code = function(arg1, arg2) {
|
||||
// Поддержка и старых версий (code, lang), и новых (token)
|
||||
let code = '';
|
||||
let lang = 'code';
|
||||
|
||||
if (typeof arg1 === 'object' && arg1 !== null) {
|
||||
code = arg1.text || '';
|
||||
lang = arg1.lang || 'code';
|
||||
} else {
|
||||
code = arg1 || '';
|
||||
lang = arg2 || 'code';
|
||||
}
|
||||
|
||||
const language = (lang || 'code').trim();
|
||||
const blockId = 'code-block-' + Math.random().toString(36).substr(2, 9);
|
||||
|
||||
return `
|
||||
<div class="my-3 rounded-xl overflow-hidden border border-slate-700/80 bg-slate-900 shadow-md font-mono text-xs text-left">
|
||||
<div class="flex items-center justify-between px-3.5 py-1.5 bg-slate-800 border-b border-slate-700/70 text-slate-300">
|
||||
<span class="text-[11px] font-semibold tracking-wider text-slate-400 lowercase">${safeEscapeCode(language)}</span>
|
||||
<button type="button" onclick="window.copyCodeBlock('${blockId}', this)"
|
||||
class="flex items-center gap-1.5 px-2 py-1 text-[11px] text-slate-300 hover:text-white bg-slate-700/60 hover:bg-slate-700 rounded-md transition cursor-pointer">
|
||||
<i class="fa-regular fa-copy text-xs"></i>
|
||||
<span>Копировать</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="p-3.5 overflow-x-auto text-emerald-300 leading-relaxed font-mono whitespace-pre"><code id="${blockId}">${safeEscapeCode(code)}</code></div>
|
||||
</div>
|
||||
`;
|
||||
};
|
||||
|
||||
marked.setOptions({
|
||||
renderer: renderer,
|
||||
gfm: true,
|
||||
breaks: true
|
||||
});
|
||||
|
||||
return marked.parse(rawText);
|
||||
}
|
||||
|
||||
window.copyCodeBlock = function(blockId, btnElement) {
|
||||
const codeEl = document.getElementById(blockId);
|
||||
if (!codeEl) return;
|
||||
const textToCopy = codeEl.innerText;
|
||||
|
||||
function showSuccessFeedback() {
|
||||
const originalHtml = btnElement.innerHTML;
|
||||
btnElement.innerHTML = `<i class="fa-solid fa-check text-emerald-400 text-xs"></i><span class="text-emerald-400 font-bold">Скопировано!</span>`;
|
||||
btnElement.classList.add('bg-slate-800');
|
||||
setTimeout(() => {
|
||||
btnElement.innerHTML = originalHtml;
|
||||
btnElement.classList.remove('bg-slate-800');
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
navigator.clipboard.writeText(textToCopy)
|
||||
.then(showSuccessFeedback)
|
||||
.catch(() => fallbackCopy(textToCopy));
|
||||
} else {
|
||||
fallbackCopy(textToCopy);
|
||||
}
|
||||
|
||||
function fallbackCopy(text) {
|
||||
try {
|
||||
const textArea = document.createElement("textarea");
|
||||
textArea.value = text;
|
||||
textArea.style.position = "fixed";
|
||||
textArea.style.left = "-999999px";
|
||||
textArea.style.top = "-999999px";
|
||||
document.body.appendChild(textArea);
|
||||
textArea.focus();
|
||||
textArea.select();
|
||||
const successful = document.execCommand('copy');
|
||||
document.body.removeChild(textArea);
|
||||
if (successful) {
|
||||
showSuccessFeedback();
|
||||
} else {
|
||||
console.warn("Fallback execCommand copy failed");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Не удалось скопировать код в буфер:", err);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.appendUserMessage = function(text, filename = null) {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return;
|
||||
|
||||
const msgId = 'user-msg-' + Date.now();
|
||||
let fileBadge = '';
|
||||
if (filename) {
|
||||
fileBadge = `
|
||||
<div class="inline-flex items-center gap-1.5 px-2.5 py-1 mb-2 bg-indigo-700/80 rounded-lg text-xs font-semibold text-white shadow-xs">
|
||||
<i class="fa-solid fa-paperclip text-xs"></i>
|
||||
<span class="truncate max-w-xs">${safeEscapeCode(filename)}</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
const msgHtml = `
|
||||
<div id="${msgId}" class="user-chat-bubble relative flex gap-3 max-w-4xl mx-auto w-full justify-end pt-3 scroll-mt-4">
|
||||
<div class="flex-1 max-w-2xl bg-indigo-600 text-white rounded-2xl rounded-tr-none p-4 shadow-sm">
|
||||
${fileBadge}
|
||||
<div class="text-sm leading-relaxed whitespace-pre-wrap">${safeEscapeCode(text)}</div>
|
||||
</div>
|
||||
<div class="w-8 h-8 rounded-lg bg-slate-200 text-slate-600 flex items-center justify-center shrink-0 shadow-sm mt-0.5 font-bold text-sm">
|
||||
<i class="fa-solid fa-user"></i>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
container.insertAdjacentHTML("beforeend", msgHtml);
|
||||
};
|
||||
|
||||
window.appendAssistantLoading = function() {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return null;
|
||||
|
||||
const loadingId = 'loading-' + Date.now();
|
||||
const html = `
|
||||
<div id="${loadingId}" class="flex gap-3 max-w-4xl mx-auto w-full pt-1">
|
||||
<div class="w-8 h-8 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm mt-0.5">
|
||||
<i class="fa-solid fa-robot text-sm"></i>
|
||||
</div>
|
||||
<div class="flex-1 bg-white border border-slate-200 rounded-2xl rounded-tl-none p-4 shadow-sm">
|
||||
<div class="text-sm text-slate-500 flex items-center gap-2">
|
||||
<i class="fa-solid fa-spinner fa-spin text-indigo-600"></i>
|
||||
<span>ИИ обрабатывает запрос...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
container.insertAdjacentHTML("beforeend", html);
|
||||
return loadingId;
|
||||
};
|
||||
|
||||
window.appendAssistantMessage = function(text, buttons = [], actionPayload = null) {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return;
|
||||
|
||||
const payloadHtml = window.ChatCardsRenderer
|
||||
? window.ChatCardsRenderer.renderActionPayload(actionPayload)
|
||||
: '';
|
||||
|
||||
const isHtmlBody = actionPayload && actionPayload.type === 'PROMPT_PREVIEW';
|
||||
|
||||
let buttonsHtml = '';
|
||||
if (!actionPayload || (actionPayload.type !== 'PROMPT_EDITOR' && actionPayload.type !== 'RULES_EDITOR')) {
|
||||
const allButtons = (buttons && buttons.length > 0) ? buttons : (actionPayload && actionPayload.buttons ? actionPayload.buttons : []);
|
||||
if (allButtons && Array.isArray(allButtons) && allButtons.length > 0) {
|
||||
buttonsHtml = `
|
||||
<div class="flex flex-wrap gap-2 mt-3.5 pt-2.5 border-t border-slate-100">
|
||||
${allButtons.map(b => `
|
||||
<button onclick="window.sendChatAction('${safeEscapeCode(b.value || b.action || b.title || '')}')"
|
||||
class="px-3 py-1.5 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 rounded-lg text-xs font-semibold border border-indigo-200 transition">
|
||||
${safeEscapeCode(b.label || b.title || b.action)}
|
||||
</button>
|
||||
`).join('')}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
const bodyContent = isHtmlBody ? text : renderMarkdownGemini(text);
|
||||
|
||||
const html = `
|
||||
<div class="flex gap-3 max-w-4xl mx-auto w-full pt-1">
|
||||
<div class="w-8 h-8 rounded-lg bg-indigo-600 text-white flex items-center justify-center shrink-0 shadow-sm mt-0.5">
|
||||
<i class="fa-solid fa-robot text-sm"></i>
|
||||
</div>
|
||||
<div class="flex-1 bg-white border border-slate-200 rounded-2xl rounded-tl-none p-4 shadow-sm min-w-0">
|
||||
<div class="text-[11px] font-bold text-indigo-600 uppercase tracking-wider mb-1.5">ИИ-ассистент SCUD Orion AI</div>
|
||||
<div class="text-sm text-slate-800 leading-relaxed chat-markdown-content">${bodyContent}</div>
|
||||
${payloadHtml}
|
||||
${buttonsHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
container.insertAdjacentHTML("beforeend", html);
|
||||
|
||||
if (window.ensureScrollSpacerAtEnd) {
|
||||
window.ensureScrollSpacerAtEnd();
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* ===============================================================================
|
||||
* FILE: modules/web_api/static/js/chat/scroll.js
|
||||
* ROLE: Изолированный движок скролла чата (Gemini-style scroll to top).
|
||||
* ===============================================================================
|
||||
*/
|
||||
|
||||
window.scrollToUserMessageTop = function() {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
if (!container) return;
|
||||
|
||||
// Обеспечиваем невидимый эластичный спейсер в конце ленты
|
||||
let spacer = document.getElementById("chat-scroll-spacer");
|
||||
if (!spacer) {
|
||||
spacer = document.createElement("div");
|
||||
spacer.id = "chat-scroll-spacer";
|
||||
spacer.style.height = "calc(100vh - 220px)";
|
||||
spacer.style.flexShrink = "0";
|
||||
spacer.style.pointerEvents = "none";
|
||||
container.appendChild(spacer);
|
||||
} else {
|
||||
container.appendChild(spacer);
|
||||
}
|
||||
|
||||
const userBubbles = container.querySelectorAll(".user-chat-bubble");
|
||||
const targetEl = userBubbles[userBubbles.length - 1];
|
||||
if (!targetEl) return;
|
||||
|
||||
setTimeout(() => {
|
||||
const containerRect = container.getBoundingClientRect();
|
||||
const targetRect = targetEl.getBoundingClientRect();
|
||||
const targetScrollTop = container.scrollTop + (targetRect.top - containerRect.top) - 16;
|
||||
|
||||
container.scrollTo({
|
||||
top: Math.max(0, targetScrollTop),
|
||||
behavior: 'smooth'
|
||||
});
|
||||
}, 40);
|
||||
};
|
||||
|
||||
window.ensureScrollSpacerAtEnd = function() {
|
||||
const container = document.getElementById("chat-messages-container");
|
||||
const spacer = document.getElementById("chat-scroll-spacer");
|
||||
if (container && spacer) {
|
||||
container.appendChild(spacer);
|
||||
}
|
||||
};
|
||||
@@ -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
|
||||
};
|
||||
})();
|
||||
@@ -92,6 +92,7 @@ function switchRegistrySubTab(subTab) {
|
||||
else if (subTab === 'remote') loadRemoteWorkersView();
|
||||
else if (subTab === 'local_trip') loadManualAbsencesView('LOCAL_TRIP');
|
||||
else if (subTab === 'other') loadManualAbsencesView('OTHER');
|
||||
else if (subTab === 'schedules') loadSchedulesView();
|
||||
}
|
||||
|
||||
async function loadExceptionsView() {
|
||||
@@ -120,7 +121,8 @@ function renderExceptionsView(exceptions) {
|
||||
|
||||
let tags = '<span class="text-[11px] text-slate-400 italic">Список пуст</span>';
|
||||
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);
|
||||
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>' +
|
||||
@@ -191,7 +193,9 @@ async function loadRemoteWorkersView() {
|
||||
try {
|
||||
const res = await fetch('/api/v1/remote-workers', { headers: AuthManager.getAuthHeaders() });
|
||||
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 = '';
|
||||
if (workers.length === 0) {
|
||||
@@ -276,7 +280,9 @@ async function loadManualAbsencesView(type) {
|
||||
headers: AuthManager.getAuthHeaders()
|
||||
});
|
||||
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 = '';
|
||||
if (items.length === 0) {
|
||||
@@ -418,3 +424,254 @@ async function deleteManualAbsenceRecord(id, type) {
|
||||
alert('Ошибка сети');
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// ВКЛАДКА "ГРАФИКИ РАБОТЫ СОТРУДНИКОВ"
|
||||
// ============================================================================
|
||||
|
||||
let schedulesTemplatesCache = [];
|
||||
let allEmployeesSchedulesCache = [];
|
||||
|
||||
async function loadSchedulesTemplates() {
|
||||
if (schedulesTemplatesCache.length > 0) return schedulesTemplatesCache;
|
||||
try {
|
||||
const res = await fetch('/api/v1/schedules/templates', { headers: AuthManager.getAuthHeaders() });
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
schedulesTemplatesCache = data.templates || [];
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Ошибка загрузки шаблонов графиков:", e);
|
||||
}
|
||||
return schedulesTemplatesCache;
|
||||
}
|
||||
|
||||
async function loadSchedulesView() {
|
||||
const container = document.getElementById('registry-content-container');
|
||||
if (!container) return;
|
||||
|
||||
container.innerHTML = '<div class="text-center py-10 text-slate-400 text-xs"><i class="fa-solid fa-spinner fa-spin mr-1"></i> Загрузка графиков...</div>';
|
||||
|
||||
await loadSchedulesTemplates();
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/v1/schedules/employees', { headers: AuthManager.getAuthHeaders() });
|
||||
if (!res.ok) throw new Error('Ошибка сети');
|
||||
const data = await res.json();
|
||||
allEmployeesSchedulesCache = (data.items || []).slice().sort((a, b) =>
|
||||
String(a.fio || '').localeCompare(String(b.fio || ''), 'ru')
|
||||
);
|
||||
renderSchedulesList(allEmployeesSchedulesCache);
|
||||
} catch (e) {
|
||||
container.innerHTML = '<div class="text-center py-8 text-rose-500 text-xs">Не удалось загрузить графики сотрудников</div>';
|
||||
}
|
||||
}
|
||||
|
||||
function renderSchedulesList(items) {
|
||||
const container = document.getElementById('registry-content-container');
|
||||
if (!container) return;
|
||||
|
||||
const depts = Array.from(new Set(allEmployeesSchedulesCache.map(i => i.department).filter(Boolean))).sort();
|
||||
|
||||
const deptsOptions = depts.map(d => `<option value="${escapeHtml(d)}">${escapeHtml(d)}</option>`).join('');
|
||||
|
||||
const templateOptions = (currentTemplateId) => {
|
||||
return schedulesTemplatesCache.map(t => {
|
||||
const isSel = (t.id === currentTemplateId) ? 'selected' : '';
|
||||
return `<option value="${t.id}" ${isSel}>${escapeHtml(t.name)}</option>`;
|
||||
}).join('');
|
||||
};
|
||||
|
||||
let listHtml = '';
|
||||
if (items.length === 0) {
|
||||
listHtml = '<div class="text-center py-8 text-xs text-slate-400 bg-white border border-slate-200 rounded-xl p-4">Сотрудники не найдены</div>';
|
||||
} else {
|
||||
listHtml = items.map(item => {
|
||||
const id = item.id;
|
||||
const fio = escapeHtml(item.fio);
|
||||
const dept = escapeHtml(item.department || '—');
|
||||
const pos = escapeHtml(item.position || '—');
|
||||
const schedName = escapeHtml(item.schedule_name || 'Стандарт');
|
||||
const basis = escapeHtml(item.doc_basis || '');
|
||||
const comment = escapeHtml(item.comment || '');
|
||||
|
||||
let badgeColor = 'bg-slate-100 text-slate-700 border-slate-200';
|
||||
if (item.work_mode === 'REMOTE') badgeColor = 'bg-blue-50 text-blue-700 border-blue-200';
|
||||
else if (item.work_mode === 'HYBRID') badgeColor = 'bg-amber-50 text-amber-700 border-amber-200';
|
||||
else if (item.work_mode === 'MATERNITY') badgeColor = 'bg-purple-50 text-purple-700 border-purple-200';
|
||||
else if (item.norm_hours < 8) badgeColor = 'bg-emerald-50 text-emerald-700 border-emerald-200';
|
||||
|
||||
return `
|
||||
<div class="p-3 bg-white border border-slate-200 rounded-xl shadow-xs text-xs flex flex-col gap-2 hover:border-slate-300 transition" id="sched-card-${id}">
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<div class="min-w-0">
|
||||
<span class="font-bold text-slate-800 truncate block" title="${fio}">${fio}</span>
|
||||
<span class="text-[10px] text-slate-400 truncate block">${dept} · ${pos}</span>
|
||||
</div>
|
||||
<span class="text-[10px] font-semibold px-2 py-0.5 rounded-md border shrink-0 ${badgeColor}">
|
||||
${schedName}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Выпадающий список прямого переключения графика -->
|
||||
<div class="flex items-center gap-1.5 pt-1 border-t border-slate-100">
|
||||
<label class="text-[10px] text-slate-400 shrink-0">Режим:</label>
|
||||
<select onchange="quickChangeEmployeeSchedule(${id}, this.value)"
|
||||
class="text-[11px] py-1 px-1.5 bg-slate-50 border border-slate-200 rounded-lg text-slate-700 flex-1 focus:outline-none focus:border-indigo-500 font-mono">
|
||||
${templateOptions(item.template_id)}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
${basis || comment ? `
|
||||
<div class="text-[10px] text-slate-500 bg-slate-50 p-1.5 rounded-lg border border-slate-100">
|
||||
${basis ? `<span class="font-semibold text-slate-600">Основание:</span> ${basis}` : ''}
|
||||
${comment ? `<span class="block text-slate-400 mt-0.5">${comment}</span>` : ''}
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="space-y-2">
|
||||
<!-- Поиск и фильтры по графикам -->
|
||||
<div class="p-2.5 bg-white border border-slate-200 rounded-xl shadow-xs space-y-2">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-xs font-bold text-slate-700">Графики сотрудников: ${allEmployeesSchedulesCache.length}</span>
|
||||
<button onclick="loadSchedulesView()" class="text-xs text-slate-400 hover:text-indigo-600 transition" title="Обновить">
|
||||
<i class="fa-solid fa-rotate-right"></i>
|
||||
</button>
|
||||
</div>
|
||||
<input type="text" id="schedules-search-input" oninput="filterSchedulesView()"
|
||||
placeholder="Поиск по фамилии..."
|
||||
class="w-full text-xs px-2.5 py-1.5 bg-slate-50 border border-slate-200 rounded-lg focus:outline-none focus:border-indigo-500">
|
||||
<div class="grid grid-cols-2 gap-1.5">
|
||||
<select id="schedules-dept-filter" onchange="filterSchedulesView()"
|
||||
class="text-xs px-2 py-1 bg-slate-50 border border-slate-200 rounded-lg text-slate-600">
|
||||
<option value="ALL">Все отделы</option>
|
||||
${deptsOptions}
|
||||
</select>
|
||||
<select id="schedules-mode-filter" onchange="filterSchedulesView()"
|
||||
class="text-xs px-2 py-1 bg-slate-50 border border-slate-200 rounded-lg text-slate-600">
|
||||
<option value="ALL">Все режимы</option>
|
||||
<option value="OFFICE">Офис</option>
|
||||
<option value="REMOTE">Удаленка</option>
|
||||
<option value="HYBRID">Гибрид</option>
|
||||
<option value="MATERNITY">Декрет</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Список сотрудников -->
|
||||
<div class="space-y-2 max-h-[60vh] overflow-y-auto" id="schedules-items-box">
|
||||
${listHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function filterSchedulesView() {
|
||||
const q = (document.getElementById('schedules-search-input')?.value || '').toLowerCase().trim();
|
||||
const dept = document.getElementById('schedules-dept-filter')?.value || 'ALL';
|
||||
const mode = document.getElementById('schedules-mode-filter')?.value || 'ALL';
|
||||
|
||||
const filtered = allEmployeesSchedulesCache.filter(item => {
|
||||
if (dept !== 'ALL' && item.department !== dept) return false;
|
||||
if (mode !== 'ALL' && item.work_mode !== mode) return false;
|
||||
if (q && !item.fio.toLowerCase().includes(q) && !item.fio_clean.toLowerCase().includes(q)) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
const box = document.getElementById('schedules-items-box');
|
||||
if (!box) return;
|
||||
|
||||
if (filtered.length === 0) {
|
||||
box.innerHTML = '<div class="text-center py-8 text-xs text-slate-400 bg-white border border-slate-200 rounded-xl p-4">Нет сотрудников под выбранный фильтр</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const templateOptions = (currentTemplateId) => {
|
||||
return schedulesTemplatesCache.map(t => {
|
||||
const isSel = (t.id === currentTemplateId) ? 'selected' : '';
|
||||
return `<option value="${t.id}" ${isSel}>${escapeHtml(t.name)}</option>`;
|
||||
}).join('');
|
||||
};
|
||||
|
||||
box.innerHTML = filtered.map(item => {
|
||||
const id = item.id;
|
||||
const fio = escapeHtml(item.fio);
|
||||
const dept = escapeHtml(item.department || '—');
|
||||
const pos = escapeHtml(item.position || '—');
|
||||
const schedName = escapeHtml(item.schedule_name || 'Стандарт');
|
||||
const basis = escapeHtml(item.doc_basis || '');
|
||||
const comment = escapeHtml(item.comment || '');
|
||||
|
||||
let badgeColor = 'bg-slate-100 text-slate-700 border-slate-200';
|
||||
if (item.work_mode === 'REMOTE') badgeColor = 'bg-blue-50 text-blue-700 border-blue-200';
|
||||
else if (item.work_mode === 'HYBRID') badgeColor = 'bg-amber-50 text-amber-700 border-amber-200';
|
||||
else if (item.work_mode === 'MATERNITY') badgeColor = 'bg-purple-50 text-purple-700 border-purple-200';
|
||||
else if (item.norm_hours < 8) badgeColor = 'bg-emerald-50 text-emerald-700 border-emerald-200';
|
||||
|
||||
return `
|
||||
<div class="p-3 bg-white border border-slate-200 rounded-xl shadow-xs text-xs flex flex-col gap-2 hover:border-slate-300 transition" id="sched-card-${id}">
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<div class="min-w-0">
|
||||
<span class="font-bold text-slate-800 truncate block" title="${fio}">${fio}</span>
|
||||
<span class="text-[10px] text-slate-400 truncate block">${dept} · ${pos}</span>
|
||||
</div>
|
||||
<span class="text-[10px] font-semibold px-2 py-0.5 rounded-md border shrink-0 ${badgeColor}">
|
||||
${schedName}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-1.5 pt-1 border-t border-slate-100">
|
||||
<label class="text-[10px] text-slate-400 shrink-0">Режим:</label>
|
||||
<select onchange="quickChangeEmployeeSchedule(${id}, this.value)"
|
||||
class="text-[11px] py-1 px-1.5 bg-slate-50 border border-slate-200 rounded-lg text-slate-700 flex-1 focus:outline-none focus:border-indigo-500 font-mono">
|
||||
${templateOptions(item.template_id)}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
${basis || comment ? `
|
||||
<div class="text-[10px] text-slate-500 bg-slate-50 p-1.5 rounded-lg border border-slate-100">
|
||||
${basis ? `<span class="font-semibold text-slate-600">Основание:</span> ${basis}` : ''}
|
||||
${comment ? `<span class="block text-slate-400 mt-0.5">${comment}</span>` : ''}
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
async function quickChangeEmployeeSchedule(scheduleId, newTemplateId) {
|
||||
const tId = parseInt(newTemplateId, 10);
|
||||
try {
|
||||
const res = await fetch('/api/v1/schedules/assign', {
|
||||
method: 'PUT',
|
||||
headers: { ...AuthManager.getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
employee_schedule_id: scheduleId,
|
||||
template_id: tId
|
||||
})
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
const target = allEmployeesSchedulesCache.find(x => x.id === scheduleId);
|
||||
if (target) {
|
||||
target.template_id = tId;
|
||||
const tmpl = schedulesTemplatesCache.find(t => t.id === tId);
|
||||
if (tmpl) {
|
||||
target.schedule_name = tmpl.name;
|
||||
target.work_mode = tmpl.work_mode;
|
||||
target.norm_hours = tmpl.norm_hours;
|
||||
}
|
||||
}
|
||||
filterSchedulesView();
|
||||
} else {
|
||||
alert('Ошибка смены графика');
|
||||
}
|
||||
} catch (e) {
|
||||
alert('Сетевая ошибка при изменении графика');
|
||||
}
|
||||
}
|
||||
@@ -75,7 +75,6 @@ window.setSnapshotDatePreset = function(preset) {
|
||||
|
||||
// 4. Загрузка списка срезов с группировкой и сортировкой
|
||||
async function loadSnapshotsView() {
|
||||
// Гарантированно заполняем поля даты и времени создания среза
|
||||
initManualSnapshotInputs();
|
||||
|
||||
const listContainer = document.getElementById('snapshots-list');
|
||||
@@ -115,7 +114,6 @@ async function loadSnapshotsView() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Вспомогательный ключ для сортировки от новых к старым
|
||||
function getSortKey(s) {
|
||||
const sid = (s.snapshot_id || s.id || '').toUpperCase();
|
||||
const digits = sid.replace(/\D/g, '');
|
||||
@@ -127,7 +125,6 @@ async function loadSnapshotsView() {
|
||||
|
||||
snapshots.sort((a, b) => getSortKey(b).localeCompare(getSortKey(a)));
|
||||
|
||||
// Группировка по дням
|
||||
const groups = {};
|
||||
snapshots.forEach(s => {
|
||||
const sid = s.snapshot_id || s.id || '';
|
||||
@@ -149,7 +146,6 @@ async function loadSnapshotsView() {
|
||||
groups[groupDate].push(s);
|
||||
});
|
||||
|
||||
// Сортировка дат по убыванию
|
||||
const sortedDates = Object.keys(groups).sort((d1, d2) => {
|
||||
const parseDate = (str) => {
|
||||
const p = str.split('.');
|
||||
@@ -177,6 +173,7 @@ async function loadSnapshotsView() {
|
||||
const badgeFinal = isFinal ? `<span class="ml-1.5 px-1.5 py-0.5 bg-amber-100 text-amber-800 rounded text-[9px] font-bold">Финал Y</span>` : '';
|
||||
const cnt = s.record_count ?? s.count ?? s.records_count ?? 0;
|
||||
const timeStr = s.snapshot_time || s.time || '—';
|
||||
const logDate = s.date || '';
|
||||
|
||||
return `
|
||||
<div class="p-3 bg-white rounded-xl border border-slate-200 hover:border-indigo-200 transition shadow-xs flex items-center justify-between group mb-2">
|
||||
@@ -188,7 +185,16 @@ async function loadSnapshotsView() {
|
||||
<div class="text-[10px] text-slate-400 mt-0.5">${escapeHtml(timeStr)} · ${cnt} зап.</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-1.5">
|
||||
<button onclick="openSnapshotInspector('${escapeHtml(sid)}')" class="px-2.5 py-1 bg-slate-100 hover:bg-indigo-50 text-slate-600 hover:text-indigo-600 rounded-lg text-[10px] font-semibold transition">Инспекция</button>
|
||||
<!-- ⭐️ Кнопка создания сводки прямо по этому срезу -->
|
||||
<button onclick="generateSvodkaBySnapshot('${escapeHtml(sid)}', '${escapeHtml(logDate)}')"
|
||||
class="px-2 py-1 bg-emerald-50 hover:bg-emerald-100 text-emerald-700 border border-emerald-200 rounded-lg text-[10px] font-semibold transition flex items-center gap-1 shadow-2xs"
|
||||
title="Сформировать сводку по срезу ${escapeHtml(sid)}">
|
||||
<i class="fa-solid fa-file-excel text-emerald-600 text-[10px]"></i> Сводка
|
||||
</button>
|
||||
<button onclick="openSnapshotInspector('${escapeHtml(sid)}')"
|
||||
class="px-2.5 py-1 bg-slate-100 hover:bg-indigo-50 text-slate-600 hover:text-indigo-600 rounded-lg text-[10px] font-semibold transition">
|
||||
Инспекция
|
||||
</button>
|
||||
${!isFinal ? `
|
||||
<button onclick="deleteSnapshotItem('${escapeHtml(sid)}')" class="w-6 h-6 flex items-center justify-center text-slate-300 hover:text-rose-500 rounded transition opacity-0 group-hover:opacity-100" title="Удалить срез"><i class="fa-regular fa-trash-can text-[11px]"></i></button>
|
||||
` : ''}
|
||||
@@ -248,27 +254,103 @@ async function deleteSnapshotItem(snapshotId) {
|
||||
} catch (e) { alert('Ошибка сети'); }
|
||||
}
|
||||
|
||||
// 7. Генерация отчетов On-Demand
|
||||
window.generateReportDirect = async function(reportType) {
|
||||
const fromInput = document.getElementById('snapshots-date-from');
|
||||
const dateInput = fromInput ? isoToBackendFormat(fromInput.value) : '';
|
||||
// 7. Генерация Сводки строго по выбранному срезу
|
||||
window.generateSvodkaBySnapshot = async function(snapshotId, logDate) {
|
||||
if (!snapshotId) return;
|
||||
|
||||
const labelMap = {
|
||||
'SVODKA': 'Сводки',
|
||||
'SIMPLIFIED': 'Упрощенного отчета',
|
||||
'DETAILED': 'Детального отчета'
|
||||
};
|
||||
|
||||
const targetLabel = labelMap[reportType] || 'отчета';
|
||||
const btn = event?.currentTarget;
|
||||
let origHtml = '';
|
||||
if (btn) {
|
||||
origHtml = btn.innerHTML;
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = `<i class="fa-solid fa-spinner fa-spin text-[10px]"></i>`;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/v1/reports/generate', {
|
||||
method: 'POST',
|
||||
headers: { ...AuthManager.getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
report_type: 'SVODKA',
|
||||
snapshot_id: snapshotId,
|
||||
date: logDate || null
|
||||
})
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
alert(`Ошибка сервера (${res.status}) при создании сводки`);
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
const rep = data.reports?.[0];
|
||||
|
||||
if (rep && rep.status === 'success' && rep.download_url) {
|
||||
window.open(rep.download_url, '_blank');
|
||||
} else {
|
||||
alert(`Ошибка: ${rep?.error || 'Не удалось сформировать сводку'}`);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[Snapshots] Ошибка генерации сводки:', e);
|
||||
alert('Сетевая ошибка при формировании сводки');
|
||||
} finally {
|
||||
if (btn) {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = origHtml;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 8. Генерация периодических отчетов On-Demand (Упрощ., Детальн., Опоздания)
|
||||
window.generateReportDirect = async function(reportType) {
|
||||
const fromInput = document.getElementById('snapshots-date-from');
|
||||
const toInput = document.getElementById('snapshots-date-to');
|
||||
const dateFrom = fromInput ? isoToBackendFormat(fromInput.value) : '';
|
||||
const dateTo = toInput ? isoToBackendFormat(toInput.value) : dateFrom;
|
||||
|
||||
const labelMap = {
|
||||
'SVODKA': 'Сводки',
|
||||
'SIMPLIFIED': 'Упрощенного отчета',
|
||||
'DETAILED': 'Детального отчета',
|
||||
'LATE_ARRIVALS': 'Отчета по опозданиям'
|
||||
};
|
||||
|
||||
const targetLabel = labelMap[reportType] || 'отчета';
|
||||
|
||||
try {
|
||||
let res;
|
||||
if (reportType === 'LATE_ARRIVALS') {
|
||||
res = await fetch('/api/v1/schedules/reports/late-arrivals', {
|
||||
method: 'POST',
|
||||
headers: { ...AuthManager.getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
date_from: dateFrom || null,
|
||||
date_to: dateTo || null,
|
||||
report_type: (dateFrom === dateTo) ? 'DAILY' : 'WEEKLY'
|
||||
})
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
alert(`Ошибка сервера (${res.status}) при создании ${targetLabel}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
if (data.status === 'success' && data.download_url) {
|
||||
window.open(data.download_url, '_blank');
|
||||
} else {
|
||||
alert(`Ошибка: ${data.message || 'Не удалось сформировать файл'}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Для Упрощенного и Детального отчетов
|
||||
res = await fetch('/api/v1/reports/generate', {
|
||||
method: 'POST',
|
||||
headers: { ...AuthManager.getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
report_type: reportType,
|
||||
date: dateInput || null,
|
||||
time: null // ⭐️ Всегда берем последний готовый срез
|
||||
date: dateFrom || null
|
||||
})
|
||||
});
|
||||
|
||||
@@ -291,7 +373,7 @@ window.generateReportDirect = async function(reportType) {
|
||||
}
|
||||
};
|
||||
|
||||
// 8. Инициализация при первичной загрузке страницы
|
||||
// 9. Инициализация при первичной загрузке страницы
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const todayIso = formatDateToISO(new Date());
|
||||
const fromInput = document.getElementById('snapshots-date-from');
|
||||
@@ -302,7 +384,6 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
initManualSnapshotInputs();
|
||||
});
|
||||
|
||||
// Экспортируем в глобальную область, чтобы core.js при переключении вкладок вызывал эту функцию
|
||||
window.loadSnapshotsView = loadSnapshotsView;
|
||||
window.createSnapshotManual = createSnapshotManual;
|
||||
window.deleteSnapshotItem = deleteSnapshotItem;
|
||||
@@ -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>
|
||||
@@ -0,0 +1,33 @@
|
||||
<div id="rename-topic-modal" class="fixed inset-0 bg-slate-900/60 backdrop-blur-xs 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-3">
|
||||
<div class="flex items-center justify-between">
|
||||
<h3 class="text-xs font-bold text-slate-800 flex items-center gap-2">
|
||||
<i class="fa-solid fa-pencil text-indigo-600"></i>
|
||||
<span>Переименование темы</span>
|
||||
</h3>
|
||||
<button type="button" onclick="window.TopicsManager.closeRenameModal()" class="text-slate-400 hover:text-slate-600 transition">
|
||||
<i class="fa-solid fa-xmark text-sm"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form id="rename-topic-form" onsubmit="window.TopicsManager.submitRenameModal(event)" class="flex flex-col gap-3">
|
||||
<input type="hidden" id="rename-topic-session-id" value="" />
|
||||
<div>
|
||||
<label class="block text-[11px] font-semibold text-slate-600 mb-1">Название диалога:</label>
|
||||
<input type="text" id="rename-topic-input" required autocomplete="off"
|
||||
class="w-full text-xs px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:border-indigo-500 bg-slate-50 text-slate-800" />
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-end gap-2 pt-2 border-t border-slate-100">
|
||||
<button type="button" onclick="window.TopicsManager.closeRenameModal()"
|
||||
class="px-3 py-1.5 text-xs text-slate-600 hover:bg-slate-100 rounded-lg transition font-medium">
|
||||
Отмена
|
||||
</button>
|
||||
<button type="submit"
|
||||
class="px-3.5 py-1.5 bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 text-white rounded-lg text-xs font-bold transition shadow-xs">
|
||||
Сохранить
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
@@ -4,6 +4,6 @@ set -e
|
||||
cd /home/apushkov/projects/scud_ai
|
||||
mkdir -p /home/apushkov/projects/scud_ai/logs
|
||||
|
||||
echo "[CRON HOURLY START] $(date '+%Y-%m-%d %H:%M:%S')" >> /home/apushkov/projects/scud_ai/logs/cron_hourly.log
|
||||
/home/apushkov/projects/scud_ai/venv/bin/python /home/apushkov/projects/scud_ai/services/scud_export.py >> /home/apushkov/projects/scud_ai/logs/cron_hourly.log 2>&1
|
||||
echo "[CRON HOURLY FINISH] $(date '+%Y-%m-%d %H:%M:%S')" >> /home/apushkov/projects/scud_ai/logs/cron_hourly.log
|
||||
echo "[CRON SNAPSHOT START] $(date '+%Y-%m-%d %H:%M:%S')" >> /home/apushkov/projects/scud_ai/logs/cron_snapshots.log
|
||||
/home/apushkov/projects/scud_ai/venv/bin/python /home/apushkov/projects/scud_ai/services/scud_export.py >> /home/apushkov/projects/scud_ai/logs/cron_snapshots.log 2>&1
|
||||
echo "[CRON SNAPSHOT FINISH] $(date '+%Y-%m-%d %H:%M:%S')" >> /home/apushkov/projects/scud_ai/logs/cron_snapshots.log
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
cd /home/apushkov/projects/scud_ai
|
||||
mkdir -p /home/apushkov/projects/scud_ai/logs
|
||||
|
||||
echo "[CRON CLEANUP START] $(date '+%Y-%m-%d %H:%M:%S')" >> /home/apushkov/projects/scud_ai/logs/cron_cleanup.log
|
||||
/home/apushkov/projects/scud_ai/venv/bin/python -c "
|
||||
from services.snapshots.retention import cleanup_old_intermediate_snapshots, purge_day_intermediate_snapshots
|
||||
from datetime import datetime
|
||||
today_str = datetime.now().strftime('%d.%m.%Y')
|
||||
purged = purge_day_intermediate_snapshots(today_str)
|
||||
cleaned = cleanup_old_intermediate_snapshots(days_to_keep_all=2)
|
||||
print(f'Очищено дневных срезов за сегодня: {purged}, ротировано старых срезов: {cleaned}')
|
||||
" >> /home/apushkov/projects/scud_ai/logs/cron_cleanup.log 2>&1
|
||||
echo "[CRON CLEANUP FINISH] $(date '+%Y-%m-%d %H:%M:%S')" >> /home/apushkov/projects/scud_ai/logs/cron_cleanup.log
|
||||
Executable
+35
@@ -0,0 +1,35 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
PROJECT_DIR="/home/apushkov/projects/scud_ai"
|
||||
LOG_DIR="${PROJECT_DIR}/logs"
|
||||
TODAY=$(date '+%Y-%m-%d')
|
||||
LOG_FILE="${LOG_DIR}/cron_final_${TODAY}.log"
|
||||
ERR_LOG="${LOG_DIR}/cron_errors.log"
|
||||
|
||||
cd "${PROJECT_DIR}"
|
||||
mkdir -p "${LOG_DIR}"
|
||||
|
||||
echo "==================================================" >> "${LOG_FILE}"
|
||||
echo "[CRON NIGHTLY FINAL START] $(date '+%Y-%m-%d %H:%M:%S')" >> "${LOG_FILE}"
|
||||
|
||||
# 1. Запуск полного ночного цикла main_etl.py:
|
||||
# - выгружает полный финишный срез Y за сегодня до 23:59:59
|
||||
# - формирует финальные отчеты
|
||||
# - автоматически зачищает дневные промежуточные срезы (purge_day_intermediate_snapshots)
|
||||
if "${PROJECT_DIR}/venv/bin/python" "${PROJECT_DIR}/main_etl.py" >> "${LOG_FILE}" 2> >(tee -a "${ERR_LOG}" >> "${LOG_FILE}"); then
|
||||
echo "[CRON NIGHTLY FINAL - SUCCESS] $(date '+%Y-%m-%d %H:%M:%S')" >> "${LOG_FILE}"
|
||||
else
|
||||
EXIT_CODE=$?
|
||||
echo "[CRON NIGHTLY FINAL ERROR] Код ошибки: ${EXIT_CODE}" >> "${LOG_FILE}"
|
||||
fi
|
||||
|
||||
# 2. Дополнительная ротация архивных дней (старше 2 дней)
|
||||
"${PROJECT_DIR}/venv/bin/python" -c "
|
||||
from services.snapshots.retention import cleanup_old_intermediate_snapshots
|
||||
cleaned = cleanup_old_intermediate_snapshots(days_to_keep_all=2)
|
||||
print(f'[Retention] Ротировано старых архивных срезов: {cleaned}')
|
||||
" >> "${LOG_FILE}" 2>&1
|
||||
|
||||
echo "==================================================" >> "${LOG_FILE}"
|
||||
echo "" >> "${LOG_FILE}"
|
||||
@@ -1,9 +1,23 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
cd /home/apushkov/projects/scud_ai
|
||||
mkdir -p /home/apushkov/projects/scud_ai/logs
|
||||
PROJECT_DIR="/home/apushkov/projects/scud_ai"
|
||||
LOG_DIR="${PROJECT_DIR}/logs"
|
||||
TODAY=$(date '+%Y-%m-%d')
|
||||
LOG_FILE="${LOG_DIR}/cron_reports_${TODAY}.log"
|
||||
ERR_LOG="${LOG_DIR}/cron_errors.log"
|
||||
|
||||
echo "[CRON REPORTS START] $(date '+%Y-%m-%d %H:%M:%S')" >> /home/apushkov/projects/scud_ai/logs/cron_reports.log
|
||||
/home/apushkov/projects/scud_ai/venv/bin/python /home/apushkov/projects/scud_ai/main_etl.py --skip-export >> /home/apushkov/projects/scud_ai/logs/cron_reports.log 2>&1
|
||||
echo "[CRON REPORTS FINISH] $(date '+%Y-%m-%d %H:%M:%S')" >> /home/apushkov/projects/scud_ai/logs/cron_reports.log
|
||||
cd "${PROJECT_DIR}"
|
||||
mkdir -p "${LOG_DIR}"
|
||||
|
||||
echo "==================================================" >> "${LOG_FILE}"
|
||||
echo "[CRON REPORTS START] $(date '+%Y-%m-%d %H:%M:%S')" >> "${LOG_FILE}"
|
||||
|
||||
# Строго с --skip-export: расчет идет по последнему готовому снапшоту из SQLite
|
||||
if "${PROJECT_DIR}/venv/bin/python" "${PROJECT_DIR}/main_etl.py" --skip-export >> "${LOG_FILE}" 2> >(tee -a "${ERR_LOG}" >> "${LOG_FILE}"); then
|
||||
echo "[CRON REPORTS FINISH - SUCCESS] $(date '+%Y-%m-%d %H:%M:%S')" >> "${LOG_FILE}"
|
||||
else
|
||||
EXIT_CODE=$?
|
||||
echo "[CRON REPORTS ERROR] Код ошибки: ${EXIT_CODE}" >> "${LOG_FILE}"
|
||||
fi
|
||||
echo "" >> "${LOG_FILE}"
|
||||
@@ -0,0 +1,198 @@
|
||||
"""
|
||||
===============================================================================
|
||||
FILE: scripts/import_schedules.py
|
||||
ROLE: Импорт режимов работы сотрудников из файла '_СВОДНАЯ_на 04.09.2026.xlsx'
|
||||
в таблицы work_schedule_templates и employee_schedules.
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
import pandas as pd
|
||||
|
||||
# Добавляем корень проекта в путь поиска модулей
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if BASE_DIR not in sys.path:
|
||||
sys.path.insert(0, BASE_DIR)
|
||||
|
||||
from core.connection import get_connection
|
||||
from core.schema import init_all_tables
|
||||
from config import normalize_fio
|
||||
|
||||
|
||||
def find_schedules_file():
|
||||
candidates = [
|
||||
os.path.join(BASE_DIR, "_СВОДНАЯ_на 04.09.2026.xlsx"),
|
||||
os.path.join(BASE_DIR, "data", "_СВОДНАЯ_на 04.09.2026.xlsx"),
|
||||
os.path.join(BASE_DIR, "data", "uploads", "_СВОДНАЯ_на 04.09.2026.xlsx"),
|
||||
]
|
||||
for c in candidates:
|
||||
if os.path.exists(c):
|
||||
return c
|
||||
# Поиск любого файла с похожим именем
|
||||
for root, _, files in os.walk(BASE_DIR):
|
||||
for f in files:
|
||||
if "сводная" in f.lower() and f.endswith(".xlsx"):
|
||||
return os.path.join(root, f)
|
||||
return None
|
||||
|
||||
|
||||
def clean_time_str(val):
|
||||
if pd.isna(val) or val is None:
|
||||
return None
|
||||
s = str(val).strip().replace('.', ':').rstrip(':').rstrip('.')
|
||||
# Поиск ЧЧ:ММ
|
||||
m = re.search(r'(\d{1,2}):(\d{2})', s)
|
||||
if m:
|
||||
hh = int(m.group(1))
|
||||
mm = int(m.group(2))
|
||||
return f"{hh:02d}:{mm:02d}"
|
||||
return None
|
||||
|
||||
|
||||
def clean_norm_hours(val):
|
||||
if pd.isna(val) or val is None:
|
||||
return 8.0
|
||||
try:
|
||||
return float(val)
|
||||
except (ValueError, TypeError):
|
||||
s = str(val).strip()
|
||||
m = re.search(r'(\d+)', s)
|
||||
if m:
|
||||
return float(m.group(1))
|
||||
return 8.0
|
||||
|
||||
|
||||
def determine_template_code(work_mode_raw, norm_hours, time_start, time_end):
|
||||
mode = str(work_mode_raw).strip().lower() if pd.notna(work_mode_raw) else "офис"
|
||||
|
||||
if "декрет" in mode:
|
||||
return "MATERNITY", "Декретный отпуск", "MATERNITY", 0.0, None, None, 0, 0
|
||||
|
||||
if "дистанцион" in mode:
|
||||
return "REMOTE_STD", "Дистанционная работа (09:00 - 17:30)", "REMOTE", norm_hours, time_start or "09:00", time_end or "17:30", 30, 0
|
||||
|
||||
if "гибрид" in mode:
|
||||
code = f"HYBRID_{time_start.replace(':', '') if time_start else '0900'}_{time_end.replace(':', '') if time_end else '1730'}"
|
||||
name = f"Гибридный график ({time_start or '09:00'} - {time_end or '17:30'})"
|
||||
return code, name, "HYBRID", norm_hours, time_start or "09:00", time_end or "17:30", 30, 0
|
||||
|
||||
if norm_hours == 22 or (time_start == "07:00" and time_end == "07:00"):
|
||||
return "SHIFT_22H", "Суточная смена (07:00 - 07:00, 22ч)", "OFFICE", 22.0, "07:00", "07:00", 120, 1
|
||||
|
||||
if not time_start and not time_end:
|
||||
if norm_hours == 4:
|
||||
return "PART_FLEX_4H", "Неполный день гибкий (4ч)", "OFFICE", 4.0, None, None, 0, 0
|
||||
return "OFFICE_FLEX", "Гибкий офисный график", "OFFICE", norm_hours, None, None, 30, 0
|
||||
|
||||
# Стандартные офисные графики с фиксированным временем
|
||||
ts_clean = time_start.replace(':', '') if time_start else "0900"
|
||||
te_clean = time_end.replace(':', '') if time_end else "1730"
|
||||
h_str = int(norm_hours) if norm_hours.is_integer() else norm_hours
|
||||
|
||||
code = f"OFFICE_{ts_clean}_{te_clean}_{h_str}H"
|
||||
name = f"Офис {time_start} - {time_end} ({h_str}ч)"
|
||||
lunch = 30 if norm_hours >= 6 else 0
|
||||
|
||||
return code, name, "OFFICE", norm_hours, time_start, time_end, lunch, 0
|
||||
|
||||
|
||||
def run_import():
|
||||
init_all_tables()
|
||||
file_path = find_schedules_file()
|
||||
if not file_path:
|
||||
print("[❌] Файл '_СВОДНАЯ_на 04.09.2026.xlsx' не найден в корне или data/!")
|
||||
return
|
||||
|
||||
print(f"[1/3] Чтение файла: {file_path} ...")
|
||||
df_raw = pd.read_excel(file_path, header=None)
|
||||
|
||||
# Заголовок находится на строке 2 (индекс 2)
|
||||
headers = [str(h).strip() for h in df_raw.iloc[2].values[:9]]
|
||||
df = df_raw.iloc[3:, :9].copy()
|
||||
df.columns = headers
|
||||
df = df.dropna(subset=['ФИО сотрудника']).reset_index(drop=True)
|
||||
|
||||
print(f" Найдено записей сотрудников: {len(df)}")
|
||||
|
||||
# Словарь шаблонов: code -> template_id
|
||||
template_ids = {}
|
||||
|
||||
with get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
print("[2/3] Формирование справочника шаблонов графиков...")
|
||||
for _, row in df.iterrows():
|
||||
w_mode = row.get('Место работы (офис/гибрид/дистанционная работа)')
|
||||
norm_h = clean_norm_hours(row.get('Продолжительность рабочего дня'))
|
||||
t_start = clean_time_str(row.get('Начало рабочего дня'))
|
||||
t_end = clean_time_str(row.get('Окончание рабочего дня'))
|
||||
|
||||
code, name, mode_enum, norm_calc, start_val, end_val, lunch, is_shift = determine_template_code(
|
||||
w_mode, norm_h, t_start, t_end
|
||||
)
|
||||
|
||||
if code not in template_ids:
|
||||
cursor.execute("""
|
||||
INSERT INTO work_schedule_templates
|
||||
(code, name, work_mode, norm_hours, time_start, time_end, lunch_break_minutes, is_shift)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(code) DO UPDATE SET
|
||||
name = excluded.name,
|
||||
norm_hours = excluded.norm_hours,
|
||||
time_start = excluded.time_start,
|
||||
time_end = excluded.time_end
|
||||
""", (code, name, mode_enum, norm_calc, start_val, end_val, lunch, is_shift))
|
||||
|
||||
cursor.execute("SELECT id FROM work_schedule_templates WHERE code = ?", (code,))
|
||||
template_ids[code] = cursor.fetchone()[0]
|
||||
|
||||
conn.commit()
|
||||
print(f" Создано/обновлено шаблонов графиков: {len(template_ids)}")
|
||||
|
||||
print("[3/3] Привязка сотрудников к графикам...")
|
||||
imported_count = 0
|
||||
|
||||
for _, row in df.iterrows():
|
||||
fio_raw = str(row.get('ФИО сотрудника', '')).strip()
|
||||
fio_clean = normalize_fio(fio_raw)
|
||||
if not fio_clean:
|
||||
continue
|
||||
|
||||
dept = str(row.get('Подразделение', '—')).strip()
|
||||
pos = str(row.get('Должность', '—')).strip()
|
||||
w_mode = row.get('Место работы (офис/гибрид/дистанционная работа)')
|
||||
norm_h = clean_norm_hours(row.get('Продолжительность рабочего дня'))
|
||||
t_start = clean_time_str(row.get('Начало рабочего дня'))
|
||||
t_end = clean_time_str(row.get('Окончание рабочего дня'))
|
||||
|
||||
notes_col = [c for c in df.columns if 'примечани' in c.lower()]
|
||||
comment = str(row.get(notes_col[0], '')).strip() if notes_col and pd.notna(row.get(notes_col[0])) else None
|
||||
|
||||
basis_col = [c for c in df.columns if 'основани' in c.lower()]
|
||||
basis = str(row.get(basis_col[0], '')).strip() if basis_col and pd.notna(row.get(basis_col[0])) else None
|
||||
|
||||
code, _, _, _, _, _, _, _ = determine_template_code(w_mode, norm_h, t_start, t_end)
|
||||
t_id = template_ids[code]
|
||||
|
||||
cursor.execute("""
|
||||
INSERT INTO employee_schedules
|
||||
(fio, fio_clean, department, position, schedule_template_id, doc_basis, comment, date_from)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, '2026-01-01')
|
||||
ON CONFLICT(fio_clean, date_from) DO UPDATE SET
|
||||
department = excluded.department,
|
||||
position = excluded.position,
|
||||
schedule_template_id = excluded.schedule_template_id,
|
||||
doc_basis = excluded.doc_basis,
|
||||
comment = excluded.comment,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
""", (fio_raw, fio_clean, dept, pos, t_id, basis, comment))
|
||||
imported_count += 1
|
||||
|
||||
conn.commit()
|
||||
print(f"[✓] Успешно импортировано сотрудников с индивидуальными графиками: {imported_count} чел.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_import()
|
||||
@@ -196,7 +196,7 @@ def get_manual_absences_list(absence_type: Optional[str] = None) -> List[Dict[st
|
||||
if absence_type:
|
||||
query += " WHERE absence_type = ?"
|
||||
params.append(absence_type)
|
||||
query += " ORDER BY id DESC"
|
||||
query += " ORDER BY fio COLLATE NOCASE ASC"
|
||||
|
||||
cursor.execute(query, params)
|
||||
rows = cursor.fetchall()
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
===============================================================================
|
||||
FILE: services/presence_service.py
|
||||
ROLE: Сервис оперативного мониторинга («Кто в здании прямо сейчас»).
|
||||
1. Строгое соответствие общему штату 1С (286 чел.).
|
||||
1. Строгое соответствие общему штату 1С (286-292 чел.).
|
||||
2. Служебный персонал (уборщики, контролеры) маркируется как EXCLUDED
|
||||
и не искажает вкладки "Не пришли" и "В здании".
|
||||
3. Сотрудники флигеля/двора (Чупряев, Пухаренко, БЛ) при выходе через
|
||||
турникет во двор остаются со статусом "В здании (Флигель/Двор)".
|
||||
4. Динамическое определение целевой даты (защита от устаревания кэша демона).
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
@@ -16,7 +17,7 @@ from typing import Dict, Any, List, Optional
|
||||
import pandas as pd
|
||||
|
||||
from core.connection import get_connection
|
||||
from config import DATE_TODAY, normalize_fio
|
||||
from config import normalize_fio
|
||||
from services.exceptions_repo import get_all_exceptions_from_db
|
||||
from services.data_loader import load_1c_data_smart
|
||||
from services.scud_export import run_export
|
||||
@@ -51,10 +52,32 @@ def get_latest_zup_staff() -> Optional[pd.DataFrame]:
|
||||
|
||||
|
||||
def get_live_presence(date_str: Optional[str] = None, force_refresh: bool = False) -> Dict[str, Any]:
|
||||
clean_date = (date_str or DATE_TODAY).replace('_', '.')
|
||||
# =========================================================================
|
||||
# ⭐️ [ANCHOR: LIVE_DATE_DETERMINATION]
|
||||
# Определение актуальной даты: устраняем залипание импортированного DATE_TODAY.
|
||||
# Если дата не передана через параметр date_str, берем фактическое число прямо сейчас.
|
||||
# Если за текущий день событий еще нет — подтягиваем дату последнего готового среза.
|
||||
# =========================================================================
|
||||
live_today = datetime.now().strftime("%d.%m.%Y")
|
||||
clean_date = (date_str or live_today).replace('_', '.')
|
||||
data_source = "LOCAL_SQLITE"
|
||||
|
||||
# 1. Принудительный опрос MS SQL при запросе
|
||||
with get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT 1 FROM scud_events_raw WHERE log_date = ? LIMIT 1", (clean_date,))
|
||||
if not cursor.fetchone():
|
||||
cursor.execute("""
|
||||
SELECT log_date FROM scud_logs
|
||||
WHERE snapshot_time IS NOT NULL
|
||||
ORDER BY snapshot_time DESC, id DESC LIMIT 1
|
||||
""")
|
||||
last_snap_row = cursor.fetchone()
|
||||
if last_snap_row and last_snap_row[0]:
|
||||
clean_date = str(last_snap_row[0]).replace('_', '.')
|
||||
|
||||
# =========================================================================
|
||||
# 1. Принудительный опрос MS SQL Орион (по кнопке "Запросить из СКУД")
|
||||
# =========================================================================
|
||||
if force_refresh:
|
||||
logger.info(f"[Presence] Прямой опрос MS SQL Орион за {clean_date}...")
|
||||
try:
|
||||
@@ -63,7 +86,9 @@ def get_live_presence(date_str: Optional[str] = None, force_refresh: bool = Fals
|
||||
except Exception as e:
|
||||
logger.error(f"[Presence] Ошибка при обращении к MS SQL: {e}")
|
||||
|
||||
# 2. Выборка последних событий по каждому сотруднику за сегодня
|
||||
# =========================================================================
|
||||
# 2. Выборка последних физических событий по каждому сотруднику за день
|
||||
# =========================================================================
|
||||
events_raw = []
|
||||
with get_connection(row_factory=True) as conn:
|
||||
cursor = conn.cursor()
|
||||
@@ -92,7 +117,9 @@ def get_live_presence(date_str: Optional[str] = None, force_refresh: bool = Fals
|
||||
|
||||
last_events_map = {r['fio_clean']: r for r in events_raw}
|
||||
|
||||
# =========================================================================
|
||||
# 3. Штат 1С и кадровые отклонения
|
||||
# =========================================================================
|
||||
df_staff, df_abs = load_1c_data_smart(clean_date, use_db=True)
|
||||
if df_staff is None or df_staff.empty:
|
||||
df_staff = get_latest_zup_staff()
|
||||
@@ -105,7 +132,9 @@ def get_live_presence(date_str: Optional[str] = None, force_refresh: bool = Fals
|
||||
if fc and reason:
|
||||
absences_map[fc] = reason
|
||||
|
||||
# =========================================================================
|
||||
# 4. Исключения и реестр флигеля из базы данных
|
||||
# =========================================================================
|
||||
try:
|
||||
exceptions_cfg = get_all_exceptions_from_db()
|
||||
except Exception:
|
||||
@@ -115,12 +144,10 @@ def get_live_presence(date_str: Optional[str] = None, force_refresh: bool = Fals
|
||||
exc_depts = set([str(d).strip().lower() for d in exceptions_cfg.get("departments", []) if d])
|
||||
exc_positions = set([str(p).strip().lower() for p in exceptions_cfg.get("positions", []) if p])
|
||||
|
||||
# Реестр флигеля / двора (ФИО и отделы)
|
||||
# ⭐️ [ANCHOR: FLIGEL_REGISTRY_INIT]
|
||||
# Реестр флигеля / двора формируется СТРОГО по таблице exceptions_registry из БД
|
||||
fligel_fios = set([normalize_fio(f) for f in exceptions_cfg.get("fligel_fio", []) if f])
|
||||
fligel_depts = set([str(d).strip().lower() for d in exceptions_cfg.get("fligel_departments", []) if d])
|
||||
# Авто-добавление ключевых сотрудников и подразделений лаборатории БЛ
|
||||
fligel_depts.update(["бл", "бетонная лаборатория", "испытательная геотехническая лаборатория"])
|
||||
fligel_fios.update([normalize_fio("Чупряев Антон Михайлович"), normalize_fio("Пухаренко Ольга Юрьевна")])
|
||||
|
||||
# Ключевые слова технического персонала (клининг, контролеры КПП)
|
||||
default_exc_keywords = ["уборщ", "дворник", "контролер", "внутреннего контроля", "клининг"]
|
||||
@@ -137,16 +164,18 @@ def get_live_presence(date_str: Optional[str] = None, force_refresh: bool = Fals
|
||||
return False
|
||||
|
||||
def check_is_fligel(fio_c: str, dept: str) -> bool:
|
||||
# Проверяем строго персону в fligel_fio либо отдел в fligel_departments
|
||||
if fio_c in fligel_fios:
|
||||
return True
|
||||
d_lower = str(dept).strip().lower()
|
||||
return d_lower in fligel_depts or any(k in d_lower for k in ["бетонная лаб", "геотехническая лаб"])
|
||||
return d_lower in fligel_depts or any(fd in d_lower for fd in fligel_depts if fd)
|
||||
|
||||
# =========================================================================
|
||||
# 5. Формирование полного списка сотрудников
|
||||
# =========================================================================
|
||||
staff_items = []
|
||||
seen_fios = set()
|
||||
|
||||
# 5.1. Обработка всех сотрудников из официального штата 1С
|
||||
if df_staff is not None and not df_staff.empty:
|
||||
for _, s_row in df_staff.iterrows():
|
||||
fio_raw = s_row.get('ФИО', '')
|
||||
@@ -172,19 +201,25 @@ def get_live_presence(date_str: Optional[str] = None, force_refresh: bool = Fals
|
||||
is_remote = "удален" in absence_reason.lower() or "дистанцион" in absence_reason.lower()
|
||||
is_trip_or_leave = bool(absence_reason) and not is_remote
|
||||
|
||||
# ⭐️ ЛОГИКА ОПРЕДЕЛЕНИЯ СТАТУСА:
|
||||
# =========================================================================
|
||||
# ⭐️ [ANCHOR: PRESENCE_STATUS_EVALUATION]
|
||||
# ЛОГИКА ОПРЕДЕЛЕНИЯ СТАТУСА:
|
||||
# 1. Исключения (служебный персонал)
|
||||
# 2. Физический выход (OUT) — всегда статус "Вышел" (включая флигель!)
|
||||
# 3. Физический вход (IN) — "В здании (Флигель/Двор)" или "В здании"
|
||||
# 4. Официальные кадровые отсутствия 1С
|
||||
# =========================================================================
|
||||
if is_excluded:
|
||||
# Сотрудник входит в штат 1С, но имеет служебный статус исключения
|
||||
status = "EXCLUDED"
|
||||
status_label = "Исключение (Служебный)"
|
||||
elif is_fligel and has_events_today:
|
||||
# ⭐️ Сотрудник флигеля/двора: выход через турникет = внутридневной выход во двор на рабочее место
|
||||
status = "INSIDE"
|
||||
status_label = "В здании (Флигель/Двор)"
|
||||
elif direction == "OUT":
|
||||
status = "OUTSIDE"
|
||||
status_label = "Вышел"
|
||||
elif direction == "IN" or has_events_today:
|
||||
elif direction == "IN":
|
||||
if is_fligel:
|
||||
status = "INSIDE"
|
||||
status_label = "В здании (Флигель/Двор)"
|
||||
else:
|
||||
status = "INSIDE"
|
||||
status_label = "В здании"
|
||||
elif is_remote:
|
||||
@@ -222,7 +257,9 @@ def get_live_presence(date_str: Optional[str] = None, force_refresh: bool = Fals
|
||||
}
|
||||
staff_items.sort(key=lambda x: (status_order.get(x["status"], 6), x["fio"].lower()))
|
||||
|
||||
# 6. Метрики
|
||||
# =========================================================================
|
||||
# 6. Расчет сводных метрик
|
||||
# =========================================================================
|
||||
total_staff = len(staff_items)
|
||||
inside_count = sum(1 for x in staff_items if x["status"] == "INSIDE")
|
||||
outside_count = sum(1 for x in staff_items if x["status"] == "OUTSIDE")
|
||||
@@ -231,8 +268,29 @@ def get_live_presence(date_str: Optional[str] = None, force_refresh: bool = Fals
|
||||
not_entered_count = sum(1 for x in staff_items if x["status"] == "NOT_ENTERED")
|
||||
excluded_count = sum(1 for x in staff_items if x["status"] == "EXCLUDED")
|
||||
|
||||
# ⭐️ [ANCHOR: DISPLAY_TIME_CALCULATION]
|
||||
# Приоритет времени:
|
||||
# 1. Если был прямой опрос по кнопке (force_refresh) — текущее время сервера
|
||||
# 2. Если отображается готовый срез — берем паспортное время среза из scud_logs (напр. 17:00)
|
||||
# 3. Fallback — время последней отметки на турникете
|
||||
latest_event_time = "—"
|
||||
if events_raw:
|
||||
if force_refresh:
|
||||
latest_event_time = datetime.now().strftime("%H:%M")
|
||||
else:
|
||||
with get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
SELECT snapshot_time FROM scud_logs
|
||||
WHERE log_date = ? AND snapshot_time IS NOT NULL
|
||||
ORDER BY snapshot_time DESC, id DESC LIMIT 1
|
||||
""", (clean_date,))
|
||||
row = cursor.fetchone()
|
||||
if row and row[0]:
|
||||
raw_st = str(row[0]).strip()
|
||||
latest_event_time = raw_st.split()[-1][:5] if ' ' in raw_st else raw_st[:5]
|
||||
|
||||
# Если срез в базе не найден — откатываемся к последней отметке
|
||||
if latest_event_time == "—" and events_raw:
|
||||
times = [r['time_val'] for r in events_raw if r.get('time_val')]
|
||||
if times:
|
||||
max_t = max(times)
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
"""
|
||||
===============================================================================
|
||||
FILE: services/reports/opozdaniya_builder.py
|
||||
ROLE: Генератор отчета об утренних опозданиях сотрудников:
|
||||
- по дням (листы с датами ДД.ММ.ГГГГ)
|
||||
- сводный лист за период (СВОД)
|
||||
- матрица динамики по отделам (КОЛИЧЕСТВО ОПОЗДАВШИХ)
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
import math
|
||||
from datetime import datetime, timedelta, time
|
||||
from typing import List, Dict, Any, Optional
|
||||
import pandas as pd
|
||||
import xlsxwriter
|
||||
|
||||
from config import REPORTS_DIR, normalize_fio
|
||||
from core.connection import get_connection
|
||||
from core.database import load_scud_from_db_by_snapshot
|
||||
from services.schedules.service import get_employee_schedule_for_date
|
||||
from services.reports.styles import get_dated_reports_dir, safe_close_workbook, create_xlsx_format
|
||||
from services.reports.simplified_builder import format_fio_initials
|
||||
|
||||
|
||||
def parse_time_to_minutes(val) -> Optional[int]:
|
||||
"""Преобразует 'ЧЧ:ММ' или 'ЧЧ:ММ:СС' в минуты от начала суток."""
|
||||
if not val or pd.isna(val):
|
||||
return None
|
||||
s = str(val).strip()
|
||||
if s in ["Нет входа", "Нет выхода", "—", "-", "", "None", "nan"]:
|
||||
return None
|
||||
try:
|
||||
parts = s.split(':')
|
||||
hh = int(parts[0])
|
||||
mm = int(parts[1]) if len(parts) > 1 else 0
|
||||
return hh * 60 + mm
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def format_minutes_to_hhmm(minutes: Optional[int]) -> str:
|
||||
"""Форматирует количество минут в строку 'ЧЧ:ММ:00'."""
|
||||
if minutes is None or minutes <= 0:
|
||||
return "-"
|
||||
hh = minutes // 60
|
||||
mm = minutes % 60
|
||||
return f"{hh:02d}:{mm:02d}:00"
|
||||
|
||||
|
||||
def calculate_late_entry(fact_in_str: str, plan_in_str: Optional[str]) -> Optional[int]:
|
||||
"""
|
||||
Вычисляет разницу в минутах (факт - план).
|
||||
Возвращает количество минут опоздания, если факт > план, иначе None.
|
||||
"""
|
||||
if not plan_in_str or not fact_in_str:
|
||||
return None
|
||||
m_fact = parse_time_to_minutes(fact_in_str)
|
||||
m_plan = parse_time_to_minutes(plan_in_str)
|
||||
if m_fact is not None and m_plan is not None:
|
||||
diff = m_fact - m_plan
|
||||
return diff if diff > 0 else None
|
||||
return None
|
||||
|
||||
|
||||
def get_late_arrivals_data_for_date(target_date: str) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Выбирает опоздавших за конкретный день на основе СКУД и индивидуальных графиков.
|
||||
"""
|
||||
clean_date = str(target_date).replace('_', '.')
|
||||
df_scud = load_scud_from_db_by_snapshot(clean_date)
|
||||
if df_scud is None or df_scud.empty:
|
||||
return []
|
||||
|
||||
# Загружаем причины опозданий из базы, если они зафиксированы
|
||||
explanations_map = {}
|
||||
with get_connection(row_factory=True) as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT fio_clean, reason FROM late_arrival_explanations WHERE log_date = ?", (clean_date,))
|
||||
explanations_map = {r['fio_clean']: r['reason'] for r in cursor.fetchall()}
|
||||
|
||||
records = []
|
||||
for _, row in df_scud.iterrows():
|
||||
fio_raw = row.get('Сотрудник', '')
|
||||
fio_clean = row.get('fio_clean', normalize_fio(fio_raw))
|
||||
if not fio_clean:
|
||||
continue
|
||||
|
||||
time_in_str = str(row.get('Начало_дня', 'Нет входа')).strip()
|
||||
if time_in_str in ['Нет входа', '—', '', 'nan', 'None']:
|
||||
continue
|
||||
|
||||
# Индивидуальный график сотрудника на дату
|
||||
sched = get_employee_schedule_for_date(fio_clean, clean_date)
|
||||
work_mode = sched.get('work_mode', 'OFFICE')
|
||||
if work_mode in ['MATERNITY', 'REMOTE']:
|
||||
# Декретники и чистые удаленщики не попадают в реестр опоздавших в офис
|
||||
continue
|
||||
|
||||
plan_in = sched.get('time_start')
|
||||
plan_out = sched.get('time_end')
|
||||
norm_h = sched.get('norm_hours', 8.0)
|
||||
|
||||
late_minutes = calculate_late_entry(time_in_str, plan_in)
|
||||
if late_minutes and late_minutes > 0:
|
||||
time_out_str = str(row.get('Конец_дня', 'Нет выхода')).strip()
|
||||
in_bld_str = str(row.get('Находился_в_здании', '00:00')).strip()
|
||||
dept = str(row.get('Подразделение', '—')).strip()
|
||||
pos = str(row.get('Должность', '—')).strip()
|
||||
|
||||
# Отклонение от нормы
|
||||
m_in_bld = parse_time_to_minutes(in_bld_str) or 0
|
||||
lunch = sched.get('lunch_break_minutes', 30)
|
||||
work_m = max(0, m_in_bld - lunch)
|
||||
norm_m = int(norm_h * 60)
|
||||
dev_m = work_m - norm_m
|
||||
|
||||
if dev_m == 0:
|
||||
dev_str = "00:00:00"
|
||||
elif dev_m > 0:
|
||||
dev_str = f"{dev_m // 60:02d}:{dev_m % 60:02d}:00"
|
||||
else:
|
||||
abs_d = abs(dev_m)
|
||||
dev_str = f"-{abs_d // 60:02d}:{abs_d % 60:02d}:00"
|
||||
|
||||
norm_str = f"{int(norm_h):02d}:{int((norm_h % 1) * 60):02d}:00"
|
||||
plan_in_fmt = f"{plan_in}:00" if plan_in and len(plan_in) == 5 else (plan_in or "—")
|
||||
plan_out_fmt = f"{plan_out}:00" if plan_out and len(plan_out) == 5 else (plan_out or "—")
|
||||
time_in_fmt = f"{time_in_str}:00" if len(time_in_str) == 5 else time_in_str
|
||||
|
||||
records.append({
|
||||
"date": clean_date,
|
||||
"department": dept,
|
||||
"fio": fio_raw,
|
||||
"fio_short": format_fio_initials(fio_raw),
|
||||
"position": pos,
|
||||
"time_in": time_in_fmt,
|
||||
"plan_in": plan_in_fmt,
|
||||
"late_time": format_minutes_to_hhmm(late_minutes),
|
||||
"late_minutes": late_minutes,
|
||||
"time_out": time_out_str,
|
||||
"plan_out": plan_out_fmt,
|
||||
"in_building": in_bld_str,
|
||||
"norm_hours": norm_str,
|
||||
"deviation": dev_str,
|
||||
"reason": explanations_map.get(fio_clean, "")
|
||||
})
|
||||
|
||||
# Сортировка: сначала по подразделению, затем по времени опоздания (убывание)
|
||||
records.sort(key=lambda x: (x['department'].lower(), -x['late_minutes']))
|
||||
return records
|
||||
|
||||
|
||||
def build_opozdaniya_workbook(
|
||||
dates_list: List[str],
|
||||
filename: Optional[str] = None
|
||||
) -> str:
|
||||
"""
|
||||
Генерирует полную книгу Excel со страницами по дням + СВОД + КОЛИЧЕСТВО ОПОЗДАВШИХ.
|
||||
"""
|
||||
first_date = dates_list[0].replace('_', '.')
|
||||
last_date = dates_list[-1].replace('_', '.')
|
||||
|
||||
if not filename:
|
||||
if len(dates_list) == 1:
|
||||
filename = f"Опоздания за {first_date}.xlsx"
|
||||
else:
|
||||
filename = f"Опоздания с {first_date} по {last_date}.xlsx"
|
||||
|
||||
target_dir = get_dated_reports_dir(first_date)
|
||||
out_path = os.path.join(target_dir, filename)
|
||||
|
||||
wb = xlsxwriter.Workbook(out_path, {'nan_inf_to_errors': True})
|
||||
|
||||
fmt_hdr = create_xlsx_format(wb, font_name='Arial', font_size=10, bg_color='#D9E1F2', bold=True, align="center", wrap=True)
|
||||
fmt_cell_l = create_xlsx_format(wb, font_name='Arial', font_size=10, align="left")
|
||||
fmt_cell_c = create_xlsx_format(wb, font_name='Arial', font_size=10, align="center")
|
||||
fmt_cell_r = create_xlsx_format(wb, font_name='Arial', font_size=10, align="right")
|
||||
fmt_bold_c = create_xlsx_format(wb, font_name='Arial', font_size=10, bold=True, align="center")
|
||||
|
||||
headers_daily = [
|
||||
"№ пп", "Подразделение", "Сотрудник", "Должность", "Начало дня",
|
||||
"Начало рабочего дня по трудовому договору или ДС", "Время опоздания",
|
||||
"Окончание дня", "Окончание рабочего дня по ТД или ДС",
|
||||
"Находился в здании", "Норма рабочих часов в день по ТД или ДС",
|
||||
"Отклонение от нормы", "Причина"
|
||||
]
|
||||
|
||||
all_days_records = {}
|
||||
full_svod_rows = []
|
||||
|
||||
for d_str in dates_list:
|
||||
day_recs = get_late_arrivals_data_for_date(d_str)
|
||||
all_days_records[d_str] = day_recs
|
||||
full_svod_rows.extend(day_recs)
|
||||
|
||||
# 1. Формируем отдельный лист дня
|
||||
ws_day = wb.add_worksheet(d_str[:31])
|
||||
ws_day.set_row(0, 28)
|
||||
for col_idx, h_text in enumerate(headers_daily):
|
||||
ws_day.write(0, col_idx, h_text, fmt_hdr)
|
||||
|
||||
for r_idx, r_data in enumerate(day_recs, start=1):
|
||||
ws_day.set_row(r_idx, 20)
|
||||
ws_day.write(r_idx, 0, r_idx, fmt_cell_c)
|
||||
ws_day.write(r_idx, 1, r_data['department'], fmt_cell_c)
|
||||
ws_day.write(r_idx, 2, r_data['fio_short'], fmt_cell_l)
|
||||
ws_day.write(r_idx, 3, r_data['position'], fmt_cell_l)
|
||||
ws_day.write(r_idx, 4, r_data['time_in'], fmt_cell_c)
|
||||
ws_day.write(r_idx, 5, r_data['plan_in'], fmt_cell_c)
|
||||
ws_day.write(r_idx, 6, r_data['late_time'], fmt_bold_c)
|
||||
ws_day.write(r_idx, 7, r_data['time_out'], fmt_cell_c)
|
||||
ws_day.write(r_idx, 8, r_data['plan_out'], fmt_cell_c)
|
||||
ws_day.write(r_idx, 9, r_data['in_building'], fmt_cell_c)
|
||||
ws_day.write(r_idx, 10, r_data['norm_hours'], fmt_cell_c)
|
||||
ws_day.write(r_idx, 11, r_data['deviation'], fmt_cell_c)
|
||||
ws_day.write(r_idx, 12, r_data['reason'], fmt_cell_l)
|
||||
|
||||
widths = {0: 6, 1: 15, 2: 24, 3: 35, 4: 12, 5: 16, 6: 15, 7: 14, 8: 16, 9: 14, 10: 16, 11: 15, 12: 30}
|
||||
for c, w in widths.items():
|
||||
ws_day.set_column(c, c, w)
|
||||
|
||||
# 2. Лист «СВОД»
|
||||
ws_svod = wb.add_worksheet("СВОД")
|
||||
headers_svod = ["Дата"] + headers_daily[1:]
|
||||
ws_svod.set_row(0, 28)
|
||||
for col_idx, h_text in enumerate(headers_svod):
|
||||
ws_svod.write(0, col_idx, h_text, fmt_hdr)
|
||||
|
||||
for r_idx, r_data in enumerate(full_svod_rows, start=1):
|
||||
ws_svod.set_row(r_idx, 20)
|
||||
ws_svod.write(r_idx, 0, r_data['date'], fmt_cell_c)
|
||||
ws_svod.write(r_idx, 1, r_data['department'], fmt_cell_c)
|
||||
ws_svod.write(r_idx, 2, r_data['fio_short'], fmt_cell_l)
|
||||
ws_svod.write(r_idx, 3, r_data['position'], fmt_cell_l)
|
||||
ws_svod.write(r_idx, 4, r_data['time_in'], fmt_cell_c)
|
||||
ws_svod.write(r_idx, 5, r_data['plan_in'], fmt_cell_c)
|
||||
ws_svod.write(r_idx, 6, r_data['late_time'], fmt_bold_c)
|
||||
ws_svod.write(r_idx, 7, r_data['time_out'], fmt_cell_c)
|
||||
ws_svod.write(r_idx, 8, r_data['plan_out'], fmt_cell_c)
|
||||
ws_svod.write(r_idx, 9, r_data['in_building'], fmt_cell_c)
|
||||
ws_svod.write(r_idx, 10, r_data['norm_hours'], fmt_cell_c)
|
||||
ws_svod.write(r_idx, 11, r_data['deviation'], fmt_cell_c)
|
||||
ws_svod.write(r_idx, 12, r_data['reason'], fmt_cell_l)
|
||||
|
||||
widths_svod = {0: 12, 1: 15, 2: 24, 3: 35, 4: 12, 5: 16, 6: 15, 7: 14, 8: 16, 9: 14, 10: 16, 11: 15, 12: 30}
|
||||
for c, w in widths_svod.items():
|
||||
ws_svod.set_column(c, c, w)
|
||||
|
||||
# 3. Лист «КОЛИЧЕСТВО ОПОЗДАВШИХ»
|
||||
ws_matrix = wb.add_worksheet("КОЛИЧЕСТВО ОПОЗДАВШИХ")
|
||||
|
||||
depts_set = set()
|
||||
for row in full_svod_rows:
|
||||
if row['department'] and row['department'] != '—':
|
||||
depts_set.add(row['department'])
|
||||
depts_sorted = sorted(list(depts_set))
|
||||
|
||||
# Шапка
|
||||
ws_matrix.write(0, 0, "Подразделение", fmt_hdr)
|
||||
for c_idx, d_str in enumerate(dates_list, start=1):
|
||||
ws_matrix.write(0, c_idx, d_str, fmt_hdr)
|
||||
ws_matrix.write(0, len(dates_list) + 1, "ИТОГО", fmt_hdr)
|
||||
|
||||
# Строки отделов
|
||||
for r_idx, dept in enumerate(depts_sorted, start=1):
|
||||
ws_matrix.write(r_idx, 0, dept, fmt_cell_c)
|
||||
dept_total = 0
|
||||
for c_idx, d_str in enumerate(dates_list, start=1):
|
||||
cnt = sum(1 for x in all_days_records.get(d_str, []) if x['department'] == dept)
|
||||
ws_matrix.write(r_idx, c_idx, cnt, fmt_cell_c)
|
||||
dept_total += cnt
|
||||
ws_matrix.write(r_idx, len(dates_list) + 1, dept_total, fmt_bold_c)
|
||||
|
||||
# Итог
|
||||
tot_row_idx = len(depts_sorted) + 1
|
||||
ws_matrix.write(tot_row_idx, 0, "ИТОГО", fmt_hdr)
|
||||
grand_total = 0
|
||||
for c_idx, d_str in enumerate(dates_list, start=1):
|
||||
day_tot = len(all_days_records.get(d_str, []))
|
||||
ws_matrix.write(tot_row_idx, c_idx, day_tot, fmt_bold_c)
|
||||
grand_total += day_tot
|
||||
ws_matrix.write(tot_row_idx, len(dates_list) + 1, grand_total, fmt_bold_c)
|
||||
|
||||
ws_matrix.set_column(0, 0, 18)
|
||||
for c_idx in range(1, len(dates_list) + 2):
|
||||
ws_matrix.set_column(c_idx, c_idx, 12)
|
||||
|
||||
safe_close_workbook(wb, out_path, target_dir, filename)
|
||||
return out_path
|
||||
@@ -2,6 +2,7 @@
|
||||
===============================================================================
|
||||
FILE: services/reports/otchet_builder.py
|
||||
ROLE: Генератор книги Детального суточного отчета со сверкой 1С:ЗУП.
|
||||
Интеграция интервального расчета чистого времени и внутридневных отсутствий.
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
@@ -11,6 +12,7 @@ import pandas as pd
|
||||
import xlsxwriter
|
||||
from services.reports.styles import get_dated_reports_dir, format_date_ru, safe_close_workbook, create_xlsx_format
|
||||
from services.reports.calculators import calculate_deviation
|
||||
from services.reports.presence_intervals import calculate_all_employees_intervals_for_date
|
||||
|
||||
|
||||
def generate_detailed_excel(merged_df, date_str="20.08.2026", filename=None):
|
||||
@@ -35,9 +37,10 @@ def generate_detailed_excel(merged_df, date_str="20.08.2026", filename=None):
|
||||
ws.write(1, 1, "Дата:", fmt_date_lbl)
|
||||
ws.write(1, 3, date_clean, fmt_date_lbl)
|
||||
|
||||
# ⭐️ 11 колонок: добавлена колонка "время отсутствия"
|
||||
headers = [
|
||||
"№", "ФИО", "Подразделение", "время входа", "первая активность", "время выхода",
|
||||
"находился в здании", "причина отсутствия", "норма", "отклонение от нормы"
|
||||
"находился в здании", "время отсутствия", "причина отсутствия", "норма", "отклонение от нормы"
|
||||
]
|
||||
fmt_hdr = create_xlsx_format(wb, font_name='Arial', font_size=10, bg_color='#D9E1F2', bold=True, align="center", wrap=True)
|
||||
ws.set_row(3, 26)
|
||||
@@ -49,6 +52,12 @@ def generate_detailed_excel(merged_df, date_str="20.08.2026", filename=None):
|
||||
hours_col = 'Часы' if 'Часы' in df_export.columns else 'Находился_в_здании'
|
||||
chars_per_line_h = 24
|
||||
|
||||
# Пакетная загрузка внутридневных сессий и чистого времени из scud_events_raw
|
||||
try:
|
||||
intervals_cache = calculate_all_employees_intervals_for_date(date_clean)
|
||||
except Exception:
|
||||
intervals_cache = {}
|
||||
|
||||
for idx, row in df_export.reset_index(drop=True).iterrows():
|
||||
row_num = 4 + idx
|
||||
is_present = bool(row.get('Пришел', False))
|
||||
@@ -61,13 +70,31 @@ def generate_detailed_excel(merged_df, date_str="20.08.2026", filename=None):
|
||||
out_val = str(row.get(end_col, 'Нет выхода')).strip()
|
||||
if out_val.lower() in ['nan', 'none']: out_val = 'Нет выхода'
|
||||
|
||||
fio_c = row.get('fio_clean', '')
|
||||
intervals_info = intervals_cache.get(fio_c) if fio_c else None
|
||||
|
||||
# Расчет чистого времени в здании и времени отсутствия
|
||||
if intervals_info and intervals_info.get('gross_minutes', 0) > 0:
|
||||
in_building_str = intervals_info.get('net_hhmm', '00:00')
|
||||
absence_mins = intervals_info.get('absence_minutes', 0)
|
||||
exits_count = intervals_info.get('exits_count', 0)
|
||||
# Формируем строку: ЧЧ:ММ (кол-во выходов)
|
||||
if exits_count > 0 and absence_mins > 0:
|
||||
absence_time_str = f"{intervals_info.get('absence_hhmm', '00:00')} ({exits_count} вых.)"
|
||||
elif exits_count > 0:
|
||||
absence_time_str = f"00:00 ({exits_count} вых.)"
|
||||
else:
|
||||
absence_time_str = "—"
|
||||
else:
|
||||
in_building_str = str(row.get(hours_col, '00:00')).strip()
|
||||
if in_building_str.lower() in ['nan', 'none']: in_building_str = '00:00'
|
||||
absence_time_str = "—"
|
||||
|
||||
first_act_val = str(row.get('Первая_активность', '—')).strip()
|
||||
if first_act_val.lower() in ['nan', 'none']: first_act_val = '—'
|
||||
has_first_act = first_act_val not in ['—', '', 'None', 'nan']
|
||||
|
||||
# Расчет отклонения от чистого времени нахождения в здании
|
||||
deviation_val = calculate_deviation(in_building_str, reason=absence_reason if has_reason else "", norm_hours=8, lunch_minutes=30)
|
||||
|
||||
dept_raw = row.get('department_scud', row.get('department', row.get('Подразделение', '')))
|
||||
@@ -100,19 +127,20 @@ def generate_detailed_excel(merged_df, date_str="20.08.2026", filename=None):
|
||||
(first_act_val, 'center', False),
|
||||
(out_val, 'center', False),
|
||||
(in_building_str, 'center', False),
|
||||
(absence_time_str, 'center', False), # ⭐️ Новая колонка
|
||||
(val_h_str, 'left', True),
|
||||
(8, 'center', False),
|
||||
(deviation_val, 'center', False)
|
||||
]
|
||||
|
||||
for col_idx, (val, align_type, is_wrap) in enumerate(values):
|
||||
# Санитизация для исключения передачи float('nan') в _write_number
|
||||
if pd.isna(val) or val is None or str(val).strip().lower() == 'nan':
|
||||
val = ""
|
||||
fmt = create_xlsx_format(wb, font_name='Arial', font_size=10, bg_color=row_color, align=align_type, wrap=is_wrap)
|
||||
ws.write(row_num, col_idx, val, fmt)
|
||||
|
||||
col_widths = {0: 4, 1: 33, 2: 13, 3: 11, 4: 11, 5: 11, 6: 12, 7: 24, 8: 6, 9: 11}
|
||||
# Ширина 11 колонок (колонка 7 — время отсутствия)
|
||||
col_widths = {0: 4, 1: 33, 2: 13, 3: 11, 4: 11, 5: 11, 6: 12, 7: 15, 8: 24, 9: 6, 10: 11}
|
||||
for col_idx, width in col_widths.items():
|
||||
ws.set_column(col_idx, col_idx, width)
|
||||
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
"""
|
||||
===============================================================================
|
||||
FILE: services/reports/presence_intervals.py
|
||||
ROLE: Высокоточный калькулятор внутридневных интервалов присутствия на базе scud_events_raw.
|
||||
Считает:
|
||||
1. Чистое время внутри периметра (сумма всех сессий IN -> OUT).
|
||||
2. Грязное время смены (от первого входа до финального выхода).
|
||||
3. Суммарное время отсутствий/отлучек (обед, перекуры, личные дела).
|
||||
4. Количество физических выходов за пределы проходной.
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, Any, List, Optional
|
||||
from core.connection import get_connection
|
||||
|
||||
logger = logging.getLogger("PRESENCE_INTERVALS")
|
||||
|
||||
|
||||
def minutes_to_hhmm(minutes: int) -> str:
|
||||
"""Форматирует минуты в строку HH:MM."""
|
||||
if minutes < 0:
|
||||
minutes = 0
|
||||
hours = minutes // 60
|
||||
mins = minutes % 60
|
||||
return f"{hours:02d}:{mins:02d}"
|
||||
|
||||
|
||||
def parse_event_time(date_str: str, time_str: str) -> Optional[datetime]:
|
||||
"""Парсит строку времени события в datetime."""
|
||||
try:
|
||||
t_clean = str(time_str).strip()
|
||||
if ' ' in t_clean:
|
||||
# Формат: 'YYYY-MM-DD HH:MM:SS' или 'DD.MM.YYYY HH:MM:SS'
|
||||
for fmt in ("%Y-%m-%d %H:%M:%S", "%d.%m.%Y %H:%M:%S"):
|
||||
try:
|
||||
return datetime.strptime(t_clean, fmt)
|
||||
except ValueError:
|
||||
pass
|
||||
# Если только время HH:MM:SS
|
||||
d_clean = date_str.replace('_', '.')
|
||||
full_str = f"{d_clean} {t_clean[:8]}"
|
||||
return datetime.strptime(full_str, "%d.%m.%Y %H:%M:%S")
|
||||
except Exception as e:
|
||||
logger.warning(f"Ошибка парсинга времени '{time_str}' (дата {date_str}): {e}")
|
||||
return None
|
||||
|
||||
|
||||
def calculate_employee_intervals(
|
||||
fio_clean: str,
|
||||
date_str: str,
|
||||
snapshot_cutoff_dt: Optional[datetime] = None,
|
||||
events: Optional[List[Dict[str, Any]]] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Рассчитывает интервалы присутствия для одного сотрудника за указанную дату.
|
||||
|
||||
:param fio_clean: Нормализованное ФИО
|
||||
:param date_str: Дата в формате DD.MM.YYYY
|
||||
:param snapshot_cutoff_dt: Верхняя временная граница среза (если срез дневной)
|
||||
:param events: Опционально предзагруженный список событий (для пакетного расчета)
|
||||
"""
|
||||
clean_date = date_str.replace('_', '.')
|
||||
|
||||
if events is None:
|
||||
with get_connection(row_factory=True) as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
SELECT time_val, direction, door_index, mode
|
||||
FROM scud_events_raw
|
||||
WHERE log_date = ? AND fio_clean = ?
|
||||
ORDER BY time_val ASC, id ASC
|
||||
""", (clean_date, fio_clean))
|
||||
events = [dict(r) for r in cursor.fetchall()]
|
||||
|
||||
if not events:
|
||||
return {
|
||||
"first_in": "—",
|
||||
"last_out": "—",
|
||||
"gross_minutes": 0,
|
||||
"net_minutes": 0,
|
||||
"absence_minutes": 0,
|
||||
"gross_hhmm": "00:00",
|
||||
"net_hhmm": "00:00",
|
||||
"absence_hhmm": "00:00",
|
||||
"exits_count": 0,
|
||||
"is_currently_inside": False,
|
||||
"sessions": []
|
||||
}
|
||||
|
||||
# 1. Фильтрация и устранение дребезга (debounce) одинаковых направлений подряд
|
||||
parsed_events = []
|
||||
for ev in events:
|
||||
dt = parse_event_time(clean_date, ev['time_val'])
|
||||
direction = str(ev.get('direction', '')).upper()
|
||||
if dt and direction in ('IN', 'OUT'):
|
||||
parsed_events.append({
|
||||
"dt": dt,
|
||||
"direction": direction,
|
||||
"door": ev.get('door_index')
|
||||
})
|
||||
|
||||
if not parsed_events:
|
||||
return {
|
||||
"first_in": "—",
|
||||
"last_out": "—",
|
||||
"gross_minutes": 0,
|
||||
"net_minutes": 0,
|
||||
"absence_minutes": 0,
|
||||
"gross_hhmm": "00:00",
|
||||
"net_hhmm": "00:00",
|
||||
"absence_hhmm": "00:00",
|
||||
"exits_count": 0,
|
||||
"is_currently_inside": False,
|
||||
"sessions": []
|
||||
}
|
||||
|
||||
# Схлопываем быстрый дребезг (повторные касания того же направления в пределах 15 сек)
|
||||
debounced_events = [parsed_events[0]]
|
||||
for ev in parsed_events[1:]:
|
||||
last_ev = debounced_events[-1]
|
||||
delta_sec = (ev['dt'] - last_ev['dt']).total_seconds()
|
||||
if ev['direction'] == last_ev['direction'] and delta_sec < 15:
|
||||
continue # Пропускаем дубль
|
||||
debounced_events.append(ev)
|
||||
|
||||
# 2. Построение рабочих сессий (IN -> OUT)
|
||||
sessions = []
|
||||
current_in: Optional[datetime] = None
|
||||
exits_count = 0
|
||||
first_in_dt: Optional[datetime] = None
|
||||
last_out_dt: Optional[datetime] = None
|
||||
|
||||
for ev in debounced_events:
|
||||
if ev['direction'] == 'IN':
|
||||
if first_in_dt is None:
|
||||
first_in_dt = ev['dt']
|
||||
|
||||
# Если был повторный вход без закрытия предыдущего (аномалия) — закрываем прошлый по текущему
|
||||
if current_in is not None:
|
||||
sessions.append((current_in, ev['dt'], "AUTO_CLOSED"))
|
||||
current_in = ev['dt']
|
||||
|
||||
elif ev['direction'] == 'OUT':
|
||||
last_out_dt = ev['dt']
|
||||
exits_count += 1
|
||||
if current_in is not None:
|
||||
sessions.append((current_in, ev['dt'], "NORMAL"))
|
||||
current_in = None
|
||||
else:
|
||||
# Выход без зафиксированного входа (прошел с кем-то утром)
|
||||
if first_in_dt is None:
|
||||
first_in_dt = ev['dt']
|
||||
|
||||
# Если сотрудник все еще находится внутри на момент снятия среза
|
||||
is_currently_inside = current_in is not None
|
||||
if current_in is not None:
|
||||
close_dt = snapshot_cutoff_dt or debounced_events[-1]['dt']
|
||||
if close_dt > current_in:
|
||||
sessions.append((current_in, close_dt, "OPEN_SESSION"))
|
||||
|
||||
# 3. Суммирование времени
|
||||
net_seconds = sum((s[1] - s[0]).total_seconds() for s in sessions if s[1] >= s[0])
|
||||
net_minutes = int(net_seconds // 60)
|
||||
|
||||
# Грязное время (от первого входа до финала)
|
||||
end_point = last_out_dt if (last_out_dt and not is_currently_inside) else (snapshot_cutoff_dt or (sessions[-1][1] if sessions else first_in_dt))
|
||||
gross_minutes = 0
|
||||
if first_in_dt and end_point and end_point >= first_in_dt:
|
||||
gross_minutes = int((end_point - first_in_dt).total_seconds() // 60)
|
||||
|
||||
# Чистое время отсутствий между сессиями (отлучки, обед, перекуры)
|
||||
absence_minutes = max(0, gross_minutes - net_minutes)
|
||||
|
||||
first_in_str = first_in_dt.strftime("%H:%M:%S") if first_in_dt else "—"
|
||||
last_out_str = last_out_dt.strftime("%H:%M:%S") if last_out_dt else ("В здании" if is_currently_inside else "—")
|
||||
|
||||
return {
|
||||
"first_in": first_in_str,
|
||||
"last_out": last_out_str,
|
||||
"gross_minutes": gross_minutes,
|
||||
"net_minutes": net_minutes,
|
||||
"absence_minutes": absence_minutes,
|
||||
"gross_hhmm": minutes_to_hhmm(gross_minutes),
|
||||
"net_hhmm": minutes_to_hhmm(net_minutes),
|
||||
"absence_hhmm": minutes_to_hhmm(absence_minutes),
|
||||
"exits_count": exits_count,
|
||||
"is_currently_inside": is_currently_inside,
|
||||
"sessions": [
|
||||
{
|
||||
"in": s[0].strftime("%H:%M:%S"),
|
||||
"out": s[1].strftime("%H:%M:%S"),
|
||||
"duration_minutes": int((s[1] - s[0]).total_seconds() // 60),
|
||||
"type": s[2]
|
||||
}
|
||||
for s in sessions
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def calculate_all_employees_intervals_for_date(
|
||||
date_str: str,
|
||||
snapshot_cutoff_dt: Optional[datetime] = None
|
||||
) -> Dict[str, Dict[str, Any]]:
|
||||
"""
|
||||
Пакетный расчет интервалов для всех сотрудников за указанный день.
|
||||
Выполняется одним быстрым SQL-запросом.
|
||||
"""
|
||||
clean_date = date_str.replace('_', '.')
|
||||
events_by_fio: Dict[str, List[Dict[str, Any]]] = {}
|
||||
|
||||
with get_connection(row_factory=True) as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
SELECT fio_clean, time_val, direction, door_index, mode
|
||||
FROM scud_events_raw
|
||||
WHERE log_date = ?
|
||||
ORDER BY fio_clean ASC, time_val ASC, id ASC
|
||||
""", (clean_date,))
|
||||
rows = cursor.fetchall()
|
||||
for r in rows:
|
||||
fc = r['fio_clean']
|
||||
if fc not in events_by_fio:
|
||||
events_by_fio[fc] = []
|
||||
events_by_fio[fc].append(dict(r))
|
||||
|
||||
result_map = {}
|
||||
for fc, ev_list in events_by_fio.items():
|
||||
result_map[fc] = calculate_employee_intervals(
|
||||
fio_clean=fc,
|
||||
date_str=clean_date,
|
||||
snapshot_cutoff_dt=snapshot_cutoff_dt,
|
||||
events=ev_list
|
||||
)
|
||||
return result_map
|
||||
@@ -2,6 +2,7 @@
|
||||
===============================================================================
|
||||
FILE: services/reports/svodka_builder.py
|
||||
ROLE: Генератор книги Ежедневной сводки (иерархические группировки XlsxWriter).
|
||||
Поддержка категорий "Смена не началась" (по индивидуальному графику позже).
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
@@ -41,6 +42,7 @@ def generate_summary_excel(merged_df, date_str="21.08.2026", filename=None):
|
||||
is_not_hired = merged_df.get('not_hired_yet', False) == True
|
||||
is_no_pass = merged_df.get('no_scud_pass', False) == True
|
||||
is_exc = merged_df.get('is_excluded', False) == True
|
||||
is_shift_later = merged_df.get('shift_not_started', False) == True
|
||||
|
||||
# "По списку" строго по официальному штату 1С
|
||||
staff_total = len(merged_df[~is_not_hired])
|
||||
@@ -51,12 +53,12 @@ def generate_summary_excel(merged_df, date_str="21.08.2026", filename=None):
|
||||
|
||||
current_row = 3
|
||||
|
||||
# 1. Неизвестно
|
||||
# 1. Неизвестно (исключаем тех, чья смена по графику еще не началась)
|
||||
unexplained = merged_df[
|
||||
(~is_not_hired) &
|
||||
(merged_df['Пришел'] == False) &
|
||||
(merged_df['Вид_отсутствия'].isna() | (merged_df['Вид_отсутствия'].astype(str).str.strip().isin(['', 'nan', 'None']))) &
|
||||
(~is_no_pass) & (~is_exc)
|
||||
(~is_no_pass) & (~is_exc) & (~is_shift_later)
|
||||
]
|
||||
fmt_unexp_hl = create_xlsx_format(wb, bg_color='#FCE4D6', bold=True, align="left")
|
||||
fmt_unexp_hr = create_xlsx_format(wb, bg_color='#FCE4D6', bold=True, align="right")
|
||||
@@ -74,7 +76,28 @@ def generate_summary_excel(merged_df, date_str="21.08.2026", filename=None):
|
||||
ws.write(current_row, 1, "", fmt_unexp_rr)
|
||||
current_row += 1
|
||||
|
||||
# 2. Нет пропуска (в штате 1С есть, но карты СКУД нет)
|
||||
# 1.1. Смена не началась (по графику позже времени среза)
|
||||
shift_later_df = merged_df[is_shift_later & (~is_exc) & (~is_not_hired)]
|
||||
if not shift_later_df.empty:
|
||||
fmt_sl_hl = create_xlsx_format(wb, bg_color='#EDE7F6', bold=True, align="left")
|
||||
fmt_sl_hr = create_xlsx_format(wb, bg_color='#EDE7F6', bold=True, align="right")
|
||||
fmt_sl_rl = create_xlsx_format(wb, bg_color='#EDE7F6', bold=False, align="left")
|
||||
fmt_sl_rr = create_xlsx_format(wb, bg_color='#EDE7F6', bold=False, align="right")
|
||||
|
||||
ws.set_row(current_row, 20)
|
||||
ws.write(current_row, 0, "Смена не началась (по графику позже)", fmt_sl_hl)
|
||||
ws.write(current_row, 1, len(shift_later_df), fmt_sl_hr)
|
||||
current_row += 1
|
||||
|
||||
for _, row in shift_later_df.sort_values(by='Сотрудник').iterrows():
|
||||
fio = row.get('Сотрудник', '')
|
||||
t_plan = row.get('plan_time_start', '')
|
||||
ws.set_row(current_row, 20, None, {'level': 1, 'hidden': False})
|
||||
ws.write(current_row, 0, str(fio), fmt_sl_rl)
|
||||
ws.write(current_row, 1, f"с {t_plan}" if t_plan else "", fmt_sl_rr)
|
||||
current_row += 1
|
||||
|
||||
# 2. Нет в СКУД (в штате 1С есть, но карты СКУД нет)
|
||||
no_pass_df = merged_df[is_no_pass & (~is_exc) & (~is_not_hired)]
|
||||
fmt_np_hl = create_xlsx_format(wb, bg_color='#E1F5FE', bold=True, align="left")
|
||||
fmt_np_hr = create_xlsx_format(wb, bg_color='#E1F5FE', bold=True, align="right")
|
||||
@@ -93,7 +116,7 @@ def generate_summary_excel(merged_df, date_str="21.08.2026", filename=None):
|
||||
ws.write(current_row, 1, "", fmt_np_rr)
|
||||
current_row += 1
|
||||
|
||||
# 3. Не приняты на работу (в СКУД есть, но в 1С приказа еще нет)
|
||||
# 3. Нет в ЗУП (в СКУД есть, но в 1С приказа еще нет)
|
||||
not_hired_df = merged_df[is_not_hired & (~is_exc)]
|
||||
fmt_nh_hl = create_xlsx_format(wb, bg_color='#FFF0F5', bold=True, align="left")
|
||||
fmt_nh_hr = create_xlsx_format(wb, bg_color='#FFF0F5', bold=True, align="right")
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
"""
|
||||
===============================================================================
|
||||
FILE: services/schedules/service.py
|
||||
ROLE: Доменный сервис работы с индивидуальными графиками сотрудников:
|
||||
- получение шаблонов и назначений графиков
|
||||
- поиск графика сотрудника на конкретную дату с определением нормы и плана
|
||||
- обновление графика сотрудника (изменение времени, основания, дат)
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import List, Dict, Any, Optional
|
||||
from datetime import datetime
|
||||
from core.connection import get_connection
|
||||
from config import normalize_fio
|
||||
|
||||
logger = logging.getLogger("SCHEDULES_SERVICE")
|
||||
|
||||
|
||||
def get_all_templates() -> List[Dict[str, Any]]:
|
||||
"""Возвращает все доступные шаблоны графиков."""
|
||||
with get_connection(row_factory=True) as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
SELECT id, code, name, work_mode, norm_hours, time_start, time_end,
|
||||
lunch_break_minutes, is_shift, description
|
||||
FROM work_schedule_templates
|
||||
WHERE is_active = 1
|
||||
ORDER BY norm_hours DESC, time_start ASC
|
||||
""")
|
||||
return [dict(r) for r in cursor.fetchall()]
|
||||
|
||||
|
||||
def get_employee_schedules_list(
|
||||
fio_query: Optional[str] = None,
|
||||
department: Optional[str] = None,
|
||||
work_mode: Optional[str] = None
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Возвращает список сотрудников с привязанными графиками для UI.
|
||||
"""
|
||||
with get_connection(row_factory=True) as conn:
|
||||
cursor = conn.cursor()
|
||||
query = """
|
||||
SELECT
|
||||
es.id,
|
||||
es.fio,
|
||||
es.fio_clean,
|
||||
es.department,
|
||||
es.position,
|
||||
es.doc_basis,
|
||||
es.comment,
|
||||
es.date_from,
|
||||
es.date_to,
|
||||
t.id as template_id,
|
||||
t.code as template_code,
|
||||
t.name as schedule_name,
|
||||
t.work_mode,
|
||||
t.norm_hours,
|
||||
t.time_start,
|
||||
t.time_end,
|
||||
t.lunch_break_minutes
|
||||
FROM employee_schedules es
|
||||
JOIN work_schedule_templates t ON es.schedule_template_id = t.id
|
||||
WHERE es.is_active = 1
|
||||
"""
|
||||
params = []
|
||||
if fio_query:
|
||||
query += " AND (es.fio LIKE ? OR es.fio_clean LIKE ?)"
|
||||
pattern = f"%{fio_query.strip()}%"
|
||||
params.extend([pattern, pattern])
|
||||
if department and department != "ALL":
|
||||
query += " AND es.department = ?"
|
||||
params.append(department)
|
||||
if work_mode and work_mode != "ALL":
|
||||
query += " AND t.work_mode = ?"
|
||||
params.append(work_mode)
|
||||
|
||||
query += " ORDER BY es.department ASC, es.fio ASC"
|
||||
cursor.execute(query, params)
|
||||
return [dict(r) for r in cursor.fetchall()]
|
||||
|
||||
|
||||
def get_employee_schedule_for_date(fio_clean: str, target_date_str: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Возвращает индивидуальный режим сотрудника на дату target_date_str (ДД.ММ.ГГГГ).
|
||||
Если индивидуального назначения нет, возвращается стандартный офисный график (09:00 - 17:30, 8ч).
|
||||
"""
|
||||
default_schedule = {
|
||||
"work_mode": "OFFICE",
|
||||
"norm_hours": 8.0,
|
||||
"time_start": "09:00",
|
||||
"time_end": "17:30",
|
||||
"lunch_break_minutes": 30,
|
||||
"is_shift": 0,
|
||||
"doc_basis": "ТД",
|
||||
"comment": None,
|
||||
"schedule_name": "Офис 09:00 - 17:30 (8ч)"
|
||||
}
|
||||
|
||||
if not fio_clean:
|
||||
return default_schedule
|
||||
|
||||
try:
|
||||
clean_date_dmy = target_date_str.replace('_', '.')
|
||||
dt_target = datetime.strptime(clean_date_dmy, "%d.%m.%Y").strftime("%Y-%m-%d")
|
||||
except Exception:
|
||||
dt_target = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
with get_connection(row_factory=True) as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
SELECT
|
||||
t.work_mode,
|
||||
t.norm_hours,
|
||||
t.time_start,
|
||||
t.time_end,
|
||||
t.lunch_break_minutes,
|
||||
t.is_shift,
|
||||
t.name as schedule_name,
|
||||
es.doc_basis,
|
||||
es.comment
|
||||
FROM employee_schedules es
|
||||
JOIN work_schedule_templates t ON es.schedule_template_id = t.id
|
||||
WHERE es.fio_clean = ?
|
||||
AND es.is_active = 1
|
||||
AND (es.date_from IS NULL OR es.date_from <= ?)
|
||||
AND (es.date_to IS NULL OR es.date_to >= ?)
|
||||
ORDER BY es.date_from DESC
|
||||
LIMIT 1
|
||||
""", (fio_clean, dt_target, dt_target))
|
||||
|
||||
row = cursor.fetchone()
|
||||
if row:
|
||||
res = dict(row)
|
||||
# Если время не указано (напр., декрет или гибкий), возвращаем None
|
||||
return res
|
||||
|
||||
return default_schedule
|
||||
|
||||
|
||||
def update_employee_schedule(
|
||||
employee_schedule_id: int,
|
||||
template_id: int,
|
||||
doc_basis: Optional[str] = None,
|
||||
comment: Optional[str] = None,
|
||||
date_from: Optional[str] = None,
|
||||
date_to: Optional[str] = None
|
||||
) -> bool:
|
||||
"""Обновляет привязку графика сотрудника."""
|
||||
with get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
UPDATE employee_schedules
|
||||
SET schedule_template_id = ?,
|
||||
doc_basis = COALESCE(?, doc_basis),
|
||||
comment = ?,
|
||||
date_from = COALESCE(?, date_from),
|
||||
date_to = ?,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
""", (template_id, doc_basis, comment, date_from, date_to, employee_schedule_id))
|
||||
conn.commit()
|
||||
return cursor.rowcount > 0
|
||||
+67
-13
@@ -3,6 +3,7 @@
|
||||
FILE: services/scud_etl/merger.py
|
||||
ROLE: Агрегация реестров, выбор совместителей 1С по отделу СКУД и авто-связки.
|
||||
Распределение исключений в общий рабочий пул при отсутствии справок.
|
||||
Учет индивидуальных графиков работы (time_start) относительно среза сводки.
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
@@ -13,6 +14,7 @@ import pandas as pd
|
||||
from services.knowledge.service import get_department_synonyms_dict
|
||||
from config import normalize_fio, load_exceptions
|
||||
from core.connection import get_connection
|
||||
from services.schedules.service import get_employee_schedule_for_date
|
||||
|
||||
logger = logging.getLogger("SCUD_MERGER")
|
||||
|
||||
@@ -132,14 +134,17 @@ def select_best_zup_position(df_staff_1c: pd.DataFrame, df_scud_agg: pd.DataFram
|
||||
def merge_scud_and_1c(
|
||||
df_scud: pd.DataFrame,
|
||||
df_staff_1c: pd.DataFrame,
|
||||
df_absences_1c: pd.DataFrame
|
||||
df_absences_1c: pd.DataFrame,
|
||||
target_date: str = None,
|
||||
snapshot_time_str: str = None
|
||||
) -> pd.DataFrame:
|
||||
if (df_scud is None or df_scud.empty) and (df_staff_1c is None or df_staff_1c.empty):
|
||||
return pd.DataFrame(columns=[
|
||||
'Сотрудник', 'fio_clean', 'Подразделение', 'Должность',
|
||||
'Начало_дня', 'Первая_активность', 'Конец_дня', 'Находился_в_здании',
|
||||
'Пришел', 'anomaly_flag', 'причина отсутствия', 'Вид_отсутствия',
|
||||
'is_excluded', 'not_hired_yet', 'no_scud_pass'
|
||||
'is_excluded', 'not_hired_yet', 'no_scud_pass',
|
||||
'plan_time_start', 'shift_not_started'
|
||||
])
|
||||
|
||||
synonyms = get_department_synonyms_dict()
|
||||
@@ -162,7 +167,6 @@ def merge_scud_and_1c(
|
||||
r['Сотрудник'] = r.get('ФИО', fio_c)
|
||||
|
||||
if fio_c in scud_dict:
|
||||
# Сотрудник есть в СКУД — берем короткую аббревиатуру отдела из СКУД
|
||||
scud_data = scud_dict[fio_c]
|
||||
dept_scud = str(scud_data.get('Подразделение', '')).strip()
|
||||
if dept_scud and dept_scud.lower() not in ['nan', 'none', '—', 'без подразделения']:
|
||||
@@ -177,7 +181,6 @@ def merge_scud_and_1c(
|
||||
r['no_scud_pass'] = False
|
||||
r['not_hired_yet'] = False
|
||||
else:
|
||||
# Сотрудника нет в СКУД (Нет пропуска)
|
||||
r['Начало_дня'] = 'Нет входа'
|
||||
r['Первая_активность'] = '—'
|
||||
r['Конец_дня'] = 'Нет выхода'
|
||||
@@ -219,7 +222,7 @@ def merge_scud_and_1c(
|
||||
if col not in df_res.columns:
|
||||
df_res[col] = default_val
|
||||
|
||||
# Словарь синонимов и принудительное сокращение длинных отделов 1С до аббревиатур
|
||||
# Словарь синонимов подразделений
|
||||
reverse_synonyms = {v.lower(): k.upper() for k, v in synonyms.items()}
|
||||
direct_synonyms = {k.lower(): k.upper() for k in synonyms.keys()}
|
||||
all_dept_map = {
|
||||
@@ -267,16 +270,23 @@ def merge_scud_and_1c(
|
||||
manual_reasons_map = {}
|
||||
try:
|
||||
from services.manual_absences_repo import get_active_manual_absences_for_date
|
||||
target_date_val = df_res.get('Дата', pd.Series()).iloc[0] if 'Дата' in df_res.columns and not df_res.empty else None
|
||||
if target_date_val:
|
||||
m_records = get_active_manual_absences_for_date(str(target_date_val))
|
||||
from config import DATE_TODAY
|
||||
effective_date = target_date or DATE_TODAY
|
||||
m_records = get_active_manual_absences_for_date(str(effective_date))
|
||||
for mr in m_records:
|
||||
manual_reasons_map[mr['fio_clean']] = mr['reason']
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.warning(f"[Merger] Ошибка чтения manual_absences: {e}")
|
||||
|
||||
df_res["detailed_reason"] = df_res["fio_clean"].map(manual_reasons_map).fillna("")
|
||||
df_res["причина отсутствия"] = df_res["fio_clean"].map(absences_map)
|
||||
|
||||
mask_manual = df_res["причина отсутствия"].isna() | (df_res["причина отсутствия"].astype(str).str.strip().isin(['', 'nan', 'None']))
|
||||
for idx, row in df_res[mask_manual].iterrows():
|
||||
fc = row.get("fio_clean")
|
||||
if fc in manual_reasons_map:
|
||||
df_res.at[idx, "причина отсутствия"] = manual_reasons_map[fc]
|
||||
|
||||
df_res["Вид_отсутствия"] = df_res["причина отсутствия"]
|
||||
|
||||
# Исключения и белый список
|
||||
@@ -307,16 +317,56 @@ def merge_scud_and_1c(
|
||||
df_res.loc[mask_exc, "Вид_отсутствия"] = "Исключение"
|
||||
df_res.loc[mask_exc, "причина отсутствия"] = "Исключение"
|
||||
|
||||
# =========================================================================
|
||||
# УЧЕТ ГРАФИКА РАБОТЫ И ВРЕМЕНИ НАЧАЛА СМЕНЫ
|
||||
# =========================================================================
|
||||
from config import DATE_TODAY
|
||||
calc_date = target_date or DATE_TODAY
|
||||
|
||||
snap_minutes = None
|
||||
if snapshot_time_str:
|
||||
try:
|
||||
t_clean = snapshot_time_str.split()[-1][:5]
|
||||
parts = t_clean.split(':')
|
||||
snap_minutes = int(parts[0]) * 60 + int(parts[1])
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
df_res["plan_time_start"] = None
|
||||
df_res["shift_not_started"] = False
|
||||
|
||||
for idx, row in df_res.iterrows():
|
||||
fc = row.get("fio_clean")
|
||||
if not fc:
|
||||
continue
|
||||
|
||||
sched = get_employee_schedule_for_date(fc, calc_date)
|
||||
t_start = sched.get("time_start")
|
||||
df_res.at[idx, "plan_time_start"] = t_start
|
||||
|
||||
# Если отметки входа нет, но смена по графику начинается позже текущего среза
|
||||
if not row.get("Пришел", False) and t_start and snap_minutes is not None:
|
||||
try:
|
||||
sp = t_start.split(':')
|
||||
start_minutes = int(sp[0]) * 60 + int(sp[1])
|
||||
# Если срез снят до наступления смены или ровно в момент начала (+ 15 мин люфт)
|
||||
if (start_minutes + 15) > snap_minutes and start_minutes >= snap_minutes:
|
||||
df_res.at[idx, "shift_not_started"] = True
|
||||
elif start_minutes > snap_minutes:
|
||||
df_res.at[idx, "shift_not_started"] = True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return df_res
|
||||
|
||||
|
||||
def calculate_summary_metrics(df_merged: pd.DataFrame) -> Dict[str, Any]:
|
||||
# Создаем независимую копию среза штата с собственным непрерывным индексом
|
||||
df_staff_only = df_merged[~df_merged.get('not_hired_yet', False)].copy().reset_index(drop=True)
|
||||
total_staff = len(df_staff_only)
|
||||
|
||||
is_exc_staff = df_staff_only.get('is_excluded', False) == True
|
||||
is_no_pass_staff = df_staff_only.get('no_scud_pass', False) == True
|
||||
is_shift_later_staff = df_staff_only.get('shift_not_started', False) == True
|
||||
|
||||
came_to_office_mask = (df_staff_only["Начало_дня"].astype(str).str.strip().ne("Нет входа")) & (~is_exc_staff)
|
||||
exc_without_doc_mask = (is_exc_staff) & (
|
||||
@@ -341,12 +391,15 @@ def calculate_summary_metrics(df_merged: pd.DataFrame) -> Dict[str, Any]:
|
||||
)
|
||||
official_absent_count = int(has_doc_mask.sum())
|
||||
|
||||
# Неизвестно: среди тех, у кого нет официального документа и кто имеет пропуск
|
||||
# В Неизвестно попадают только те, у кого смена УЖЕ началась
|
||||
is_no_pass_remaining = df_remaining_absent.get('no_scud_pass', False) == True
|
||||
unknown = df_remaining_absent[~has_doc_mask & ~is_no_pass_remaining]
|
||||
is_shift_later_remaining = df_remaining_absent.get('shift_not_started', False) == True
|
||||
|
||||
unknown = df_remaining_absent[~has_doc_mask & ~is_no_pass_remaining & ~is_shift_later_remaining]
|
||||
unknown_count = len(unknown)
|
||||
|
||||
no_pass_count = int((is_no_pass_staff & ~is_exc_staff).sum())
|
||||
shift_not_started_count = int((is_shift_later_staff & ~is_exc_staff).sum())
|
||||
|
||||
is_not_hired_all = df_merged.get('not_hired_yet', False) == True
|
||||
is_exc_all = df_merged.get('is_excluded', False) == True
|
||||
@@ -359,6 +412,7 @@ def calculate_summary_metrics(df_merged: pd.DataFrame) -> Dict[str, Any]:
|
||||
"official_absent_count": official_absent_count,
|
||||
"no_pass_count": no_pass_count,
|
||||
"not_hired_count": not_hired_count,
|
||||
"shift_not_started_count": shift_not_started_count,
|
||||
"unknown_count": unknown_count,
|
||||
"unknown_list": unknown[["fio_clean", "Подразделение", "Должность"]].to_dict(orient="records") if not unknown.empty else []
|
||||
}
|
||||
@@ -57,12 +57,6 @@ def load_best_snapshot_for_date(date_str: str, prefer_final_y: bool = False) ->
|
||||
|
||||
|
||||
def load_1c_files_for_date(date_str: str) -> Tuple[Optional[pd.DataFrame], Optional[pd.DataFrame]]:
|
||||
"""
|
||||
Загружает штат и отсутствия с каскадным fallback:
|
||||
1. Синхронизирует свежие файлы с сетевой шары.
|
||||
2. Загружает штат и отсутствия через load_1c_data_smart(..., use_db=True).
|
||||
3. Если штат пуст — берет последний доступный срез штата из zup_staff в SQLite.
|
||||
"""
|
||||
clean_date = date_str.replace('_', '.')
|
||||
|
||||
try:
|
||||
@@ -73,7 +67,7 @@ def load_1c_files_for_date(date_str: str) -> Tuple[Optional[pd.DataFrame], Optio
|
||||
|
||||
df_staff, df_abs = load_1c_data_smart(clean_date, use_db=True)
|
||||
|
||||
# Fallback за штат: ако данашњи штат још увек није доступан, користи се претходни из базе
|
||||
# 1. Fallback для штата
|
||||
if df_staff is None or df_staff.empty:
|
||||
with get_connection(row_factory=True) as conn:
|
||||
cursor = conn.cursor()
|
||||
@@ -96,4 +90,29 @@ def load_1c_files_for_date(date_str: str) -> Tuple[Optional[pd.DataFrame], Optio
|
||||
)
|
||||
logger.info(f"[Pipeline] Для даты {clean_date} применен штат за {fallback_date} ({len(df_staff)} чел.)")
|
||||
|
||||
# 2. ⭐️ Гарантированное обогащение свежими ручными командировками и "Иным" прямо из SQLite
|
||||
try:
|
||||
from services.manual_absences_repo import get_active_manual_absences_for_date
|
||||
manual_records = get_active_manual_absences_for_date(clean_date)
|
||||
if manual_records:
|
||||
if df_abs is None:
|
||||
df_abs = pd.DataFrame(columns=['fio_clean', 'Вид_отсутствия'])
|
||||
|
||||
existing_fios = set(df_abs['fio_clean'].dropna().tolist()) if not df_abs.empty else set()
|
||||
new_manual_rows = []
|
||||
for r in manual_records:
|
||||
fc = r['fio_clean']
|
||||
if fc not in existing_fios:
|
||||
label = "Мест. командир." if r['absence_type'] == 'LOCAL_TRIP' else (r.get('reason') or "Иное")
|
||||
new_manual_rows.append({
|
||||
'fio_clean': fc,
|
||||
'Вид_отсутствия': label
|
||||
})
|
||||
existing_fios.add(fc)
|
||||
if new_manual_rows:
|
||||
df_abs = pd.concat([df_abs, pd.DataFrame(new_manual_rows)], ignore_index=True)
|
||||
logger.info(f"[Pipeline] В отчет за {clean_date} подтянуто {len(new_manual_rows)} чел. из реестров командировок/иного.")
|
||||
except Exception as e:
|
||||
logger.warning(f"[Pipeline] Ошибка наложения manual_absences: {e}")
|
||||
|
||||
return df_staff, df_abs
|
||||
@@ -7,10 +7,8 @@ ROLE: Изолированные SQL-шаблоны для MS SQL Server (СКУ
|
||||
|
||||
# 1. Основной срез СКУД с учетом турникетов и флигеля
|
||||
SQL_QUERY_TEMPLATE = r"""
|
||||
DECLARE @InputDate DATE = '{target_date}';
|
||||
DECLARE @TargetDate DATE = @InputDate;
|
||||
|
||||
DECLARE @StartDate DATETIME = CAST(@TargetDate AS DATETIME);
|
||||
DECLARE @TargetDate DATE = CONVERT(DATE, '{target_date_dmy}', 104);
|
||||
DECLARE @StartDate DATETIME = CONVERT(DATETIME, '{target_date_dmy} 00:00:00', 104);
|
||||
DECLARE @EndDate DATETIME = {end_datetime_sql};
|
||||
|
||||
WITH PercoPassages AS (
|
||||
@@ -136,8 +134,7 @@ ORDER BY p.Name ASC;
|
||||
|
||||
# 2. Сырые события физических проходов турникетов
|
||||
SQL_RAW_EVENTS_QUERY = r"""
|
||||
DECLARE @InputDate DATE = '{target_date}';
|
||||
DECLARE @StartDate DATETIME = CAST(@InputDate AS DATETIME);
|
||||
DECLARE @StartDate DATETIME = CONVERT(DATETIME, '{target_date_dmy} 00:00:00', 104);
|
||||
DECLARE @EndDate DATETIME = {end_datetime_sql};
|
||||
|
||||
SELECT
|
||||
@@ -168,8 +165,26 @@ LEFT JOIN PPost post WITH (NOLOCK) ON p.Post = post.ID
|
||||
WHERE log.TimeVal BETWEEN @StartDate AND @EndDate
|
||||
AND log.HozOrgan IS NOT NULL
|
||||
AND log.HozOrgan > 0
|
||||
AND log.Event IN (28, 32)
|
||||
-- ⭐️ Фильтрация сотрудников Ленморниипроект (исключение арендаторов и гостей)
|
||||
-- ⭐️ Учитываем физические факты прохода через проходную
|
||||
AND log.Event = 32
|
||||
AND log.Mode IN (1, 2)
|
||||
AND (
|
||||
-- Контур 1: Левый турникет открыт для всех
|
||||
log.DoorIndex = 1
|
||||
OR
|
||||
-- Контур 2: Правый турникет разрешен только для реестра двора
|
||||
(
|
||||
log.DoorIndex = 2
|
||||
AND ({turnstile_filter_sql})
|
||||
)
|
||||
OR
|
||||
-- Контур 3: Флигель 1 эт. разрешен только для реестра флигеля
|
||||
(
|
||||
log.DoorIndex = 23
|
||||
AND ({fligel_filter_sql})
|
||||
)
|
||||
)
|
||||
-- Фильтрация сотрудников Ленморниипроект (исключение арендаторов и гостей)
|
||||
AND ISNULL(p.StatusRecord, 0) = 0
|
||||
AND p.DateTimeInArchive IS NULL
|
||||
AND ISNULL(CAST(div.Name AS NVARCHAR(255)), N'') NOT LIKE N'Аренд%'
|
||||
|
||||
@@ -29,6 +29,7 @@ def generate_svodka_service(
|
||||
"""
|
||||
Формирует оперативную сводку:
|
||||
- По умолчанию берет ПОСЛЕДНИЙ готовый снапшот из базы SQLite (без долгого опроса MS SQL).
|
||||
- Передает точное время среза в расчет слияния для учета времени начала смен.
|
||||
"""
|
||||
date_clean = str(target_date or DATE_TODAY).replace('_', '.')
|
||||
applied_note = ""
|
||||
@@ -50,18 +51,24 @@ def generate_svodka_service(
|
||||
"message": f"Срез СКУД за {date_clean} не найден в базе данных."
|
||||
}
|
||||
|
||||
# Извлекаем время фактического среза для имени файла
|
||||
# Извлекаем время фактического среза для имени файла и калькулятора смен
|
||||
actual_snap_time = ""
|
||||
actual_clock_time = None
|
||||
if 'snapshot_time' in df_scud.columns and not df_scud.empty:
|
||||
raw_st = str(df_scud['snapshot_time'].iloc[0]).strip()
|
||||
if " " in raw_st:
|
||||
actual_snap_time = raw_st.split()[1][:5].replace(':', '-')
|
||||
actual_clock_time = raw_st.split()[1][:5]
|
||||
actual_snap_time = actual_clock_time.replace(':', '-')
|
||||
|
||||
# 2. Загружаем актуальные кадровые данные 1С (штат + отсутствия + реестры)
|
||||
df_staff, df_abs = load_1c_files_for_date(date_clean)
|
||||
|
||||
# 3. Слияние и расчет
|
||||
df_merged = merge_scud_and_1c(df_scud, df_staff, df_abs)
|
||||
# 3. Слияние и расчет (с передачей фактического времени среза)
|
||||
df_merged = merge_scud_and_1c(
|
||||
df_scud, df_staff, df_abs,
|
||||
target_date=date_clean,
|
||||
snapshot_time_str=actual_clock_time
|
||||
)
|
||||
metrics = calculate_summary_metrics(df_merged)
|
||||
anomalies = detect_registry_anomalies(df_merged, df_raw_scud=df_scud)
|
||||
|
||||
|
||||
@@ -265,7 +265,7 @@ def run_export(input_date: str | None = None, input_time: str | None = None, sav
|
||||
log(f"--- Обработка периода: {period_label} ({processing_date_str}) --- [Срез: {snapshot_time}]")
|
||||
|
||||
sql_query = SQL_QUERY_TEMPLATE.format(
|
||||
target_date=processing_date.strftime("%Y-%m-%d"),
|
||||
target_date_dmy=processing_date.strftime("%d.%m.%Y"),
|
||||
end_datetime_sql=end_datetime_sql,
|
||||
turnstile_filter_sql=turnstile_filter_sql,
|
||||
fligel_filter_sql=fligel_filter_sql
|
||||
@@ -289,9 +289,12 @@ def run_export(input_date: str | None = None, input_time: str | None = None, sav
|
||||
|
||||
save_scud_to_db(df, processing_date_str, snapshot_time=snapshot_time, is_yesterday=is_final)
|
||||
|
||||
# ⭐️ [ANCHOR: RAW_EVENTS_QUERY_FORMATTING]
|
||||
raw_sql = SQL_RAW_EVENTS_QUERY.format(
|
||||
target_date=processing_date.strftime("%Y-%m-%d"),
|
||||
end_datetime_sql=end_datetime_sql
|
||||
target_date_dmy=processing_date.strftime("%d.%m.%Y"),
|
||||
end_datetime_sql=end_datetime_sql,
|
||||
turnstile_filter_sql=turnstile_filter_sql,
|
||||
fligel_filter_sql=fligel_filter_sql
|
||||
)
|
||||
df_raw = pd.read_sql(raw_sql, connection)
|
||||
if len(df_raw) > 0:
|
||||
|
||||
+1635
-589
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user