feat(audit & reports): stabilize live presence, day intervals and reports logic before topics feature

This commit is contained in:
2026-10-23 14:36:17 +03:00
parent a64f708b35
commit b5c993486d
33 changed files with 3776 additions and 1153 deletions
+501 -50
View File
@@ -919,22 +919,23 @@ ROLE: Транспортный клиент HTTP взаимодействия с
===============================================================================
"""
# ANCHOR[OLLAMA_CLIENT_IMPORTS]
import json
import urllib.request
import urllib.error
import logging
from typing import Dict, Any, Optional
import config
logger = logging.getLogger("OLLAMA_CLIENT")
OLLAMA_URL = "http://10.121.17.227:11434/api/chat"
TEXT_MODEL = "qwen2.5:14b"
VISION_MODEL = "qwen2.5vl:7b-q8_0"
# Чистый адрес 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")
LLM_OPTIONS = {
"num_predict": 8192,
"num_ctx": 8192,
"num_ctx": 16384, # Увеличенный контекст под сканы высокого разрешения
"temperature": 0.0,
"repeat_penalty": 1.0,
"presence_penalty": 0.0,
@@ -942,18 +943,22 @@ LLM_OPTIONS = {
}
# ANCHOR[OLLAMA_REQUEST_DISPATCHER]
def call_ollama_chat(
messages: list,
tools: Optional[list] = None,
is_vision: bool = False,
timeout: int = 120
timeout: int = 240,
model: Optional[str] = None
) -> Dict[str, Any]:
"""
Отправляет подготовленный массив сообщений в API Ollama.
Возвращает разобранный словарь сообщения ответа или генерирует исключение.
Отправляет массив сообщений в API Ollama.
Поддерживает явное указание модели (например, qwen3-vl:8b).
"""
model_name = VISION_MODEL if is_vision else TEXT_MODEL
if model:
model_name = model
else:
model_name = VISION_MODEL if is_vision else TEXT_MODEL
payload = {
"model": model_name,
"messages": messages,
@@ -1985,6 +1990,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(
@@ -2021,6 +2027,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("/")
@@ -2925,7 +2932,7 @@ def api_delete_remote_worker(fio: str, current_user = Depends(get_current_user))
===============================================================================
FILE: modules/web_api/routers/reports.py
ROLE: REST API On-Demand генерации отчетов:
- Сводка: за СЕГОДНЯ (оперативный контроль, текущий срез).
- Сводка: за СЕГОДНЯ (по выбранному snapshot_id или последнему срезу).
- Детальный и Упрощенный отчет: строго за ВЧЕРА по финальному срезу Y.
===============================================================================
"""
@@ -2963,13 +2970,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('_', '.')
@@ -2977,11 +2985,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({
@@ -3051,6 +3060,114 @@ def api_generate_report(req: GenerateReportRequest):
}
```
## File: `./modules/web_api/routers/schedules.py`
```py
"""
===============================================================================
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
}
```
## File: `./modules/web_api/routers/snapshots.py`
```py
"""
@@ -3766,15 +3883,15 @@ body {
<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> Сводка
<div class="grid grid-cols-3 gap-2 mb-4">
<button onclick="generateReportDirect('SIMPLIFIED')" class="flex items-center justify-center gap-1.5 px-3 py-2 bg-blue-50 text-blue-700 border border-blue-200 rounded-lg text-xs font-semibold hover:bg-blue-100 transition-all shadow-sm">
📄 Упрощ.
</button>
<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 onclick="generateReportDirect('DETAILED')" class="flex items-center justify-center gap-1.5 px-3 py-2 bg-purple-50 text-purple-700 border border-purple-200 rounded-lg text-xs font-semibold hover:bg-purple-100 transition-all shadow-sm">
📈 Детальн.
</button>
<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 onclick="generateReportDirect('LATE_ARRIVALS')" class="flex items-center justify-center gap-1.5 px-3 py-2 bg-rose-50 text-rose-700 border border-rose-200 rounded-lg text-xs font-semibold hover:bg-rose-100 transition-all shadow-sm">
⏰ Опоздания
</button>
</div>
</div>
@@ -3790,18 +3907,21 @@ body {
<!-- 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> Исключения
<div class="grid grid-cols-5 gap-1 p-1 bg-slate-200/60 rounded-xl">
<button data-subtab="exceptions" onclick="switchRegistrySubTab('exceptions')" class="registry-subtab-btn py-1 text-[10px] rounded-lg transition text-center flex items-center justify-center gap-1">
<i class="fa-solid fa-user-shield text-[9px]"></i> Искл.
</button>
<button data-subtab="remote" onclick="switchRegistrySubTab('remote')" class="registry-subtab-btn py-1 text-[11px] rounded-lg transition text-center flex items-center justify-center gap-1">
<i class="fa-solid fa-house-laptop text-[10px]"></i> Удаленщики
<button data-subtab="remote" onclick="switchRegistrySubTab('remote')" class="registry-subtab-btn py-1 text-[10px] rounded-lg transition text-center flex items-center justify-center gap-1">
<i class="fa-solid fa-house-laptop text-[9px]"></i> Удален.
</button>
<button data-subtab="local_trip" onclick="switchRegistrySubTab('local_trip')" class="registry-subtab-btn py-1 text-[11px] rounded-lg transition text-center flex items-center justify-center gap-1">
<i class="fa-solid fa-location-dot text-[10px]"></i> Мест. командир.
<button data-subtab="local_trip" onclick="switchRegistrySubTab('local_trip')" class="registry-subtab-btn py-1 text-[10px] rounded-lg transition text-center flex items-center justify-center gap-1">
<i class="fa-solid fa-location-dot text-[9px]"></i> Команд.
</button>
<button data-subtab="other" onclick="switchRegistrySubTab('other')" class="registry-subtab-btn py-1 text-[11px] rounded-lg transition text-center flex items-center justify-center gap-1">
<i class="fa-solid fa-clipboard-question text-[10px]"></i> Иное
<button data-subtab="other" onclick="switchRegistrySubTab('other')" class="registry-subtab-btn py-1 text-[10px] rounded-lg transition text-center flex items-center justify-center gap-1">
<i class="fa-solid fa-clipboard-question text-[9px]"></i> Иное
</button>
<button data-subtab="schedules" onclick="switchRegistrySubTab('schedules')" class="registry-subtab-btn py-1 text-[10px] rounded-lg transition text-center flex items-center justify-center gap-1">
<i class="fa-solid fa-business-time text-[9px]"></i> Графики
</button>
</div>
<div id="registry-content-container" class="space-y-3"></div>
@@ -6166,6 +6286,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() {
@@ -6492,6 +6613,255 @@ 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 || [];
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('Сетевая ошибка при изменении графика');
}
}
```
## File: `./modules/web_api/static/js/sidebar/snapshots.js`
@@ -6573,7 +6943,6 @@ window.setSnapshotDatePreset = function(preset) {
// 4. Загрузка списка срезов с группировкой и сортировкой
async function loadSnapshotsView() {
// Гарантированно заполняем поля даты и времени создания среза
initManualSnapshotInputs();
const listContainer = document.getElementById('snapshots-list');
@@ -6613,7 +6982,6 @@ async function loadSnapshotsView() {
return;
}
// Вспомогательный ключ для сортировки от новых к старым
function getSortKey(s) {
const sid = (s.snapshot_id || s.id || '').toUpperCase();
const digits = sid.replace(/\D/g, '');
@@ -6625,7 +6993,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 || '';
@@ -6647,7 +7014,6 @@ async function loadSnapshotsView() {
groups[groupDate].push(s);
});
// Сортировка дат по убыванию
const sortedDates = Object.keys(groups).sort((d1, d2) => {
const parseDate = (str) => {
const p = str.split('.');
@@ -6675,6 +7041,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">
@@ -6686,7 +7053,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>
` : ''}
@@ -6746,27 +7122,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
})
});
@@ -6789,7 +7241,7 @@ window.generateReportDirect = async function(reportType) {
}
};
// 8. Инициализация при первичной загрузке страницы
// 9. Инициализация при первичной загрузке страницы
document.addEventListener('DOMContentLoaded', () => {
const todayIso = formatDateToISO(new Date());
const fromInput = document.getElementById('snapshots-date-from');
@@ -6800,7 +7252,6 @@ document.addEventListener('DOMContentLoaded', () => {
initManualSnapshotInputs();
});
// Экспортируем в глобальную область, чтобы core.js при переключении вкладок вызывал эту функцию
window.loadSnapshotsView = loadSnapshotsView;
window.createSnapshotManual = createSnapshotManual;
window.deleteSnapshotItem = deleteSnapshotItem;