feat(audit & reports): stabilize live presence, day intervals and reports logic before topics feature
This commit is contained in:
@@ -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