feat(audit & reports): stabilize live presence, day intervals and reports logic before topics feature
This commit is contained in:
@@ -133,15 +133,15 @@
|
||||
<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>
|
||||
@@ -157,18 +157,21 @@
|
||||
|
||||
<!-- 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>
|
||||
|
||||
@@ -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() {
|
||||
@@ -417,4 +418,253 @@ async function deleteManualAbsenceRecord(id, type) {
|
||||
} catch (e) {
|
||||
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('Сетевая ошибка при изменении графика');
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
Reference in New Issue
Block a user