feat(reports): stabilize on-demand generation, live presence and 1C fallback
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Роутер табов сайдбара и общие утилиты.
|
||||
*/
|
||||
window.escapeHtml = window.escapeHtml || function (str) {
|
||||
if (str === null || str === undefined) return '';
|
||||
return String(str)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
};
|
||||
|
||||
const SidebarManager = {
|
||||
currentTab: 'tasks',
|
||||
currentRegistrySubTab: 'exceptions',
|
||||
|
||||
init() {
|
||||
this.bindEvents();
|
||||
this.switchTab('tasks');
|
||||
},
|
||||
|
||||
bindEvents() {
|
||||
document.querySelectorAll('.sidebar-tab-btn, [data-tab]').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
const tab = e.currentTarget.dataset.tab;
|
||||
if (tab) this.switchTab(tab);
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
switchTab(tabName) {
|
||||
this.currentTab = tabName;
|
||||
|
||||
// Переключение стилей кнопок табов
|
||||
document.querySelectorAll('.sidebar-tab-btn, [data-tab]').forEach(btn => {
|
||||
const isActive = btn.dataset.tab === tabName;
|
||||
btn.classList.toggle('text-indigo-600', isActive);
|
||||
btn.classList.toggle('border-indigo-600', isActive);
|
||||
btn.classList.toggle('font-bold', isActive);
|
||||
btn.classList.toggle('text-slate-500', !isActive);
|
||||
btn.classList.toggle('border-transparent', !isActive);
|
||||
});
|
||||
|
||||
// Переключение видимости вьюх
|
||||
document.querySelectorAll('.sidebar-view').forEach(view => {
|
||||
view.classList.add('hidden');
|
||||
});
|
||||
|
||||
const targetView = document.getElementById(`sidebar-view-${tabName}`);
|
||||
if (targetView) targetView.classList.remove('hidden');
|
||||
|
||||
// Вызов профильного загрузчика
|
||||
if (tabName === 'tasks' && typeof loadTasks === 'function') {
|
||||
loadTasks();
|
||||
} else if (tabName === 'snapshots' && typeof loadSnapshotsView === 'function') {
|
||||
loadSnapshotsView();
|
||||
} else if (tabName === 'registries' && typeof switchRegistrySubTab === 'function') {
|
||||
switchRegistrySubTab(this.currentRegistrySubTab);
|
||||
} else if (tabName === 'prompts' && typeof loadPromptsView === 'function') {
|
||||
loadPromptsView();
|
||||
} else if (tabName === 'context' && typeof loadContextView === 'function') {
|
||||
loadContextView();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
SidebarManager.init();
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Модуль вкладок "Промпт" и "Контекст".
|
||||
*/
|
||||
|
||||
async function loadPromptsView() {
|
||||
const container = document.getElementById('prompts-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>`;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/v1/chat', {
|
||||
method: 'POST',
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({ message: "покажи системный промпт" })
|
||||
});
|
||||
const data = await res.json();
|
||||
const text = data.response || "Промпт не получен";
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="p-3 bg-white border border-slate-200 rounded-xl shadow-xs space-y-2">
|
||||
<div class="text-[11px] font-bold text-slate-600 flex items-center justify-between">
|
||||
<span>Текущий системный промпт</span>
|
||||
<button onclick="window.sendChatAction && window.sendChatAction('action:open_editor')" class="text-indigo-600 hover:text-indigo-800 text-[10px]">
|
||||
<i class="fa-solid fa-pen-to-square"></i> Редактор
|
||||
</button>
|
||||
</div>
|
||||
<pre class="text-[11px] font-mono text-slate-700 bg-slate-50 p-2.5 rounded-lg overflow-x-auto whitespace-pre-wrap leading-relaxed max-h-[65vh] border border-slate-100">${escapeHtml(text)}</pre>
|
||||
</div>
|
||||
`;
|
||||
} catch (e) {
|
||||
container.innerHTML = `<div class="text-center py-8 text-rose-500 text-xs">Не удалось загрузить системный промпт</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadContextView() {
|
||||
const container = document.getElementById('context-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>`;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/v1/context/state?session_id=web_session_main', { headers: AuthManager.getAuthHeaders() });
|
||||
const data = await res.json();
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="p-3 bg-white border border-slate-200 rounded-xl shadow-xs space-y-3">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-xs font-bold text-slate-800">Сессия: web_session_main</span>
|
||||
<span class="px-2 py-0.5 text-[10px] font-bold rounded-full ${data.active_state !== 'IDLE' ? 'bg-amber-100 text-amber-800' : 'bg-slate-100 text-slate-600'}">
|
||||
${escapeHtml(data.active_state)}
|
||||
</span>
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-2 text-center">
|
||||
<div class="p-2 bg-slate-50 rounded-lg border border-slate-100">
|
||||
<div class="text-xs font-bold text-slate-700">${data.total_messages || 0}</div>
|
||||
<div class="text-[10px] text-slate-400">Всего сообщений</div>
|
||||
</div>
|
||||
<div class="p-2 bg-slate-50 rounded-lg border border-slate-100">
|
||||
<div class="text-xs font-bold text-indigo-600">${data.ephemeral_messages || 0}</div>
|
||||
<div class="text-[10px] text-slate-400">Служебных (UI)</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="space-y-1.5 pt-2 border-t border-slate-100">
|
||||
<button onclick="purgeEphemeralMessages()" class="w-full py-2 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 rounded-lg text-xs font-semibold transition flex items-center justify-center gap-1.5">
|
||||
<i class="fa-solid fa-broom text-[11px]"></i> Очистить служебные карточки
|
||||
</button>
|
||||
<button onclick="clearAllChatContext()" class="w-full py-2 bg-rose-50 hover:bg-rose-100 text-rose-700 rounded-lg text-xs font-semibold transition flex items-center justify-center gap-1.5">
|
||||
<i class="fa-solid fa-trash-can text-[11px]"></i> Полный сброс контекста
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} catch (e) {
|
||||
container.innerHTML = `<div class="text-center py-8 text-rose-500 text-xs">Не удалось загрузить состояние сессии</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function purgeEphemeralMessages() {
|
||||
try {
|
||||
const res = await fetch('/api/v1/context/purge-ephemeral', {
|
||||
method: 'POST',
|
||||
headers: { ...AuthManager.getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ session_id: 'web_session_main' })
|
||||
});
|
||||
if (res.ok) loadContextView();
|
||||
} catch (e) { alert('Ошибка сети'); }
|
||||
}
|
||||
|
||||
async function clearAllChatContext() {
|
||||
if (!confirm('Полностью очистить историю сообщений диалога?')) return;
|
||||
try {
|
||||
const res = await fetch('/api/v1/context/clear-all', {
|
||||
method: 'POST',
|
||||
headers: { ...AuthManager.getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ session_id: 'web_session_main' })
|
||||
});
|
||||
if (res.ok) location.reload();
|
||||
} catch (e) { alert('Ошибка сети'); }
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
/**
|
||||
* Модуль вкладок "Реестры": исключения, удаленщики, командировки, флигель.
|
||||
*/
|
||||
|
||||
window.openAddExceptionModal = function(category) {
|
||||
const modal = document.getElementById("exception-modal");
|
||||
const catInput = document.getElementById("exception-category-input");
|
||||
const valInput = document.getElementById("exception-value-input");
|
||||
const commInput = document.getElementById("exception-comment-input");
|
||||
const headerEl = document.getElementById("exception-modal-header-text");
|
||||
const labelEl = document.getElementById("exception-value-label");
|
||||
const errEl = document.getElementById("exception-error-msg");
|
||||
|
||||
if (!modal) return;
|
||||
if (errEl) errEl.classList.add("hidden");
|
||||
if (catInput) catInput.value = category;
|
||||
if (valInput) { valInput.value = ""; valInput.focus(); }
|
||||
if (commInput) commInput.value = "";
|
||||
|
||||
const titles = {
|
||||
'include_fio': 'Белый список (ФИО)',
|
||||
'fio': 'Исключенный сотрудник (ФИО)',
|
||||
'departments': 'Исключенный отдел',
|
||||
'positions': 'Исключенная должность',
|
||||
'turnstile_fio': 'Правый турникет (ФИО)',
|
||||
'turnstile_departments': 'Правый турникет (Отделы)',
|
||||
'fligel_fio': 'Флигель (ФИО)',
|
||||
'fligel_departments': 'Флигель (Отделы)'
|
||||
};
|
||||
|
||||
const isDept = category.includes('department');
|
||||
const isPos = category.includes('position');
|
||||
|
||||
if (headerEl) headerEl.innerText = "Добавить в " + (titles[category] || "реестр");
|
||||
if (labelEl) {
|
||||
labelEl.innerText = isDept ? 'Название подразделения:' : (isPos ? 'Название должности:' : 'ФИО сотрудника:');
|
||||
}
|
||||
|
||||
modal.classList.remove("hidden");
|
||||
};
|
||||
|
||||
window.closeExceptionModal = function() {
|
||||
const modal = document.getElementById("exception-modal");
|
||||
if (modal) modal.classList.add("hidden");
|
||||
};
|
||||
|
||||
window.submitExceptionModalForm = async function(e) {
|
||||
e.preventDefault();
|
||||
const cat = document.getElementById("exception-category-input")?.value;
|
||||
const val = document.getElementById("exception-value-input")?.value.trim();
|
||||
const comm = document.getElementById("exception-comment-input")?.value.trim() || "";
|
||||
const errEl = document.getElementById("exception-error-msg");
|
||||
|
||||
if (!cat || !val) {
|
||||
if (errEl) { errEl.innerText = "Заполните поле"; errEl.classList.remove("hidden"); }
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/v1/exceptions", {
|
||||
method: "POST",
|
||||
headers: AuthManager.getAuthHeaders(),
|
||||
body: JSON.stringify({ category: cat, value: val, comment: comm })
|
||||
});
|
||||
if (res.ok) {
|
||||
closeExceptionModal();
|
||||
loadExceptionsView();
|
||||
} else {
|
||||
const data = await res.json();
|
||||
if (errEl) { errEl.innerText = data.detail || "Ошибка сохранения"; errEl.classList.remove("hidden"); }
|
||||
}
|
||||
} catch (err) {
|
||||
if (errEl) { errEl.innerText = "Ошибка соединения"; errEl.classList.remove("hidden"); }
|
||||
}
|
||||
};
|
||||
|
||||
function switchRegistrySubTab(subTab) {
|
||||
if (window.SidebarManager) {
|
||||
SidebarManager.currentRegistrySubTab = subTab;
|
||||
}
|
||||
|
||||
document.querySelectorAll('.registry-subtab-btn').forEach(btn => {
|
||||
const isActive = btn.dataset.subtab === subTab;
|
||||
btn.classList.toggle('text-indigo-600', isActive);
|
||||
btn.classList.toggle('bg-white', isActive);
|
||||
btn.classList.toggle('shadow-xs', isActive);
|
||||
btn.classList.toggle('font-bold', isActive);
|
||||
btn.classList.toggle('text-slate-600', !isActive);
|
||||
});
|
||||
|
||||
if (subTab === 'exceptions') loadExceptionsView();
|
||||
else if (subTab === 'remote') loadRemoteWorkersView();
|
||||
else if (subTab === 'local_trip') loadManualAbsencesView('LOCAL_TRIP');
|
||||
else if (subTab === 'other') loadManualAbsencesView('OTHER');
|
||||
}
|
||||
|
||||
async function loadExceptionsView() {
|
||||
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>';
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/v1/exceptions', { headers: AuthManager.getAuthHeaders() });
|
||||
if (!res.ok) throw new Error('Ошибка сети');
|
||||
const data = await res.json();
|
||||
renderExceptionsView(data || {});
|
||||
} catch (e) {
|
||||
container.innerHTML = '<div class="text-center py-8 text-rose-500 text-xs">Не удалось загрузить реестры исключений</div>';
|
||||
}
|
||||
}
|
||||
|
||||
function renderExceptionsView(exceptions) {
|
||||
const container = document.getElementById('registry-content-container');
|
||||
if (!container) return;
|
||||
|
||||
const renderCard = (title, list, category, badgeClass, subBadge) => {
|
||||
badgeClass = badgeClass || 'bg-slate-100 text-slate-700';
|
||||
subBadge = subBadge || '';
|
||||
|
||||
let tags = '<span class="text-[11px] text-slate-400 italic">Список пуст</span>';
|
||||
if (list && list.length > 0) {
|
||||
tags = list.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>' +
|
||||
'<button data-cat="' + category + '" data-val="' + val + '" class="btn-remove-exc text-slate-400 hover:text-rose-500 transition">' +
|
||||
'<i class="fa-solid fa-xmark text-[10px]"></i>' +
|
||||
'</button>' +
|
||||
'</span>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
const count = list ? list.length : 0;
|
||||
return '<div class="p-3 bg-white rounded-xl border border-slate-200 shadow-xs mb-3">' +
|
||||
'<div class="flex items-center justify-between mb-2">' +
|
||||
'<div class="flex items-center gap-1.5">' +
|
||||
'<span class="text-xs font-bold text-slate-800">' + title + ' (' + count + ')</span>' +
|
||||
subBadge +
|
||||
'</div>' +
|
||||
'<button data-add-cat="' + category + '" class="btn-add-exc text-xs font-bold text-indigo-600 hover:text-indigo-800">+ Добавить</button>' +
|
||||
'</div>' +
|
||||
'<div class="flex flex-wrap gap-1.5">' + tags + '</div>' +
|
||||
'</div>';
|
||||
};
|
||||
|
||||
container.innerHTML =
|
||||
renderCard('Белый список (ФИО)', exceptions.include_fio, 'include_fio', 'bg-indigo-50 text-indigo-700') +
|
||||
renderCard('Исключенные сотрудники (ФИО)', exceptions.fio, 'fio') +
|
||||
renderCard('Исключенные отделы', exceptions.departments, 'departments') +
|
||||
renderCard('Исключенные должности', exceptions.positions, 'positions') +
|
||||
renderCard('Пр. турникет (ФИО)', exceptions.turnstile_fio, 'turnstile_fio', 'bg-emerald-50 text-emerald-700 border border-emerald-200', '<span class="px-1.5 py-0.5 bg-emerald-50 text-emerald-700 rounded text-[9px] font-bold border border-emerald-200">Оба турникета</span>') +
|
||||
renderCard('Пр. турникет (Отделы)', exceptions.turnstile_departments, 'turnstile_departments', 'bg-emerald-50 text-emerald-700 border border-emerald-200', '<span class="px-1.5 py-0.5 bg-emerald-50 text-emerald-700 rounded text-[9px] font-bold border border-emerald-200">Оба турникета</span>') +
|
||||
renderCard('Флигель (ФИО)', exceptions.fligel_fio, 'fligel_fio', 'bg-indigo-50 text-indigo-700 border border-indigo-200', '<span class="px-1.5 py-0.5 bg-indigo-50 text-indigo-700 rounded text-[9px] font-bold border border-indigo-200">Дверь 23</span>') +
|
||||
renderCard('Флигель (Отделы)', exceptions.fligel_departments, 'fligel_departments', 'bg-indigo-50 text-indigo-700 border border-indigo-200', '<span class="px-1.5 py-0.5 bg-indigo-50 text-indigo-700 rounded text-[9px] font-bold border border-indigo-200">Дверь 23</span>');
|
||||
|
||||
container.querySelectorAll('.btn-add-exc').forEach(btn => {
|
||||
btn.addEventListener('click', e => {
|
||||
openAddExceptionModal(e.currentTarget.getAttribute('data-add-cat'));
|
||||
});
|
||||
});
|
||||
|
||||
container.querySelectorAll('.btn-remove-exc').forEach(btn => {
|
||||
btn.addEventListener('click', e => {
|
||||
const target = e.currentTarget;
|
||||
removeExceptionItem(target.getAttribute('data-cat'), target.getAttribute('data-val'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function removeExceptionItem(category, value) {
|
||||
if (!confirm('Удалить "' + value + '" из категории "' + category + '"?')) return;
|
||||
try {
|
||||
const res = await fetch('/api/v1/exceptions?category=' + encodeURIComponent(category) + '&value=' + encodeURIComponent(value), {
|
||||
method: 'DELETE',
|
||||
headers: AuthManager.getAuthHeaders()
|
||||
});
|
||||
if (res.ok) loadExceptionsView();
|
||||
else alert('Ошибка при удалении');
|
||||
} catch (e) {
|
||||
alert('Ошибка сети');
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRemoteWorkersView() {
|
||||
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>';
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/v1/remote-workers', { headers: AuthManager.getAuthHeaders() });
|
||||
const data = await res.json();
|
||||
const workers = data.workers || [];
|
||||
|
||||
let listHtml = '';
|
||||
if (workers.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 = workers.map(w => {
|
||||
const fio = escapeHtml(w.fio);
|
||||
const dept = escapeHtml(w.department || 'Все');
|
||||
const dFrom = escapeHtml(w.date_from || '—');
|
||||
const dTo = escapeHtml(w.date_to || 'бессрочно');
|
||||
|
||||
return '<div class="p-3 bg-white border border-slate-200 rounded-xl shadow-xs text-xs flex flex-col gap-1.5">' +
|
||||
'<div class="flex items-center justify-between">' +
|
||||
'<span class="font-bold text-slate-800">' + fio + '</span>' +
|
||||
'<div class="flex items-center gap-1.5">' +
|
||||
'<button data-edit-fio="' + fio + '" data-edit-dept="' + (w.department || '') + '" data-edit-from="' + (w.date_from || '') + '" data-edit-to="' + (w.date_to || '') + '" class="btn-edit-remote text-slate-400 hover:text-emerald-600 transition" title="Редактировать"><i class="fa-solid fa-pen-to-square"></i></button>' +
|
||||
'<button data-del-fio="' + fio + '" class="btn-del-remote text-slate-400 hover:text-rose-500 transition" title="Удалить"><i class="fa-solid fa-trash-can"></i></button>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<div class="flex items-center justify-between text-[11px] text-slate-500">' +
|
||||
'<span>' + dept + '</span>' +
|
||||
'<span class="font-mono text-[10px] bg-slate-100 px-1.5 py-0.5 rounded">' + dFrom + ' по ' + dTo + '</span>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
container.innerHTML =
|
||||
'<div class="flex items-center justify-between px-1 mb-2">' +
|
||||
'<span class="text-xs font-bold text-slate-700">Удаленные сотрудники: ' + workers.length + '</span>' +
|
||||
'<button id="btn-add-remote" class="px-2.5 py-1 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-bold shadow-xs transition">+ Добавить</button>' +
|
||||
'</div>' +
|
||||
'<div class="space-y-2">' + listHtml + '</div>';
|
||||
|
||||
const addBtn = document.getElementById('btn-add-remote');
|
||||
if (addBtn) {
|
||||
addBtn.addEventListener('click', () => openRemoteWorkerModal('ADD'));
|
||||
}
|
||||
|
||||
container.querySelectorAll('.btn-edit-remote').forEach(btn => {
|
||||
btn.addEventListener('click', e => {
|
||||
const t = e.currentTarget;
|
||||
openRemoteWorkerModal('EDIT', t.getAttribute('data-edit-fio'), t.getAttribute('data-edit-dept'), t.getAttribute('data-edit-from'), t.getAttribute('data-edit-to'));
|
||||
});
|
||||
});
|
||||
|
||||
container.querySelectorAll('.btn-del-remote').forEach(btn => {
|
||||
btn.addEventListener('click', e => {
|
||||
deleteRemoteWorkerItem(e.currentTarget.getAttribute('data-del-fio'));
|
||||
});
|
||||
});
|
||||
} catch (e) {
|
||||
container.innerHTML = '<div class="text-center py-8 text-rose-500 text-xs">Не удалось загрузить удаленщиков</div>';
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteRemoteWorkerItem(fio) {
|
||||
if (!confirm('Удалить сотрудника "' + fio + '"?')) return;
|
||||
try {
|
||||
const res = await fetch('/api/v1/remote-workers?fio=' + encodeURIComponent(fio), {
|
||||
method: 'DELETE',
|
||||
headers: AuthManager.getAuthHeaders()
|
||||
});
|
||||
if (res.ok) loadRemoteWorkersView();
|
||||
} catch (e) {
|
||||
alert('Ошибка сети');
|
||||
}
|
||||
}
|
||||
|
||||
async function loadManualAbsencesView(type) {
|
||||
const container = document.getElementById('registry-content-container');
|
||||
if (!container) return;
|
||||
|
||||
const isTrip = (type === 'LOCAL_TRIP');
|
||||
const titleText = isTrip ? 'Местные командировки' : 'Иные причины';
|
||||
const btnColor = isTrip ? 'bg-indigo-600 hover:bg-indigo-700' : 'bg-purple-600 hover:bg-purple-700';
|
||||
|
||||
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>';
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/v1/manual-absences/?type=' + encodeURIComponent(type), {
|
||||
headers: AuthManager.getAuthHeaders()
|
||||
});
|
||||
const data = await res.json();
|
||||
const items = data.items || [];
|
||||
|
||||
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(it => {
|
||||
const fio = escapeHtml(it.fio);
|
||||
const reason = escapeHtml(it.reason || '');
|
||||
const dept = escapeHtml(it.department || '—');
|
||||
const dStart = it.date_start ? it.date_start.replace(/-/g, '.') : '';
|
||||
const dEnd = it.date_end ? it.date_end.replace(/-/g, '.') : '';
|
||||
|
||||
// Форматирование срока
|
||||
let dateBadge = '';
|
||||
if (dStart && dEnd && dStart === dEnd) {
|
||||
dateBadge = dStart;
|
||||
} else if (dStart && dEnd) {
|
||||
dateBadge = `${dStart} — ${dEnd}`;
|
||||
} else if (dEnd) {
|
||||
dateBadge = `по ${dEnd}`;
|
||||
} else if (dStart) {
|
||||
dateBadge = `с ${dStart}`;
|
||||
} else {
|
||||
dateBadge = 'бессрочно';
|
||||
}
|
||||
|
||||
const badgeBg = isTrip
|
||||
? 'bg-indigo-50 text-indigo-700 border-indigo-200'
|
||||
: 'bg-purple-50 text-purple-700 border-purple-200';
|
||||
|
||||
return `
|
||||
<div class="p-3 bg-white border border-slate-200 rounded-xl shadow-xs text-xs flex flex-col gap-1.5 hover:border-slate-300 transition">
|
||||
<!-- 1-я строка: ФИО и кнопки управления -->
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="font-bold text-slate-800 truncate" title="${fio}">${fio}</span>
|
||||
<div class="flex items-center gap-1 shrink-0">
|
||||
<button data-edit-id="${it.id}" data-edit-fio="${fio}" data-edit-start="${it.date_start || ''}" data-edit-end="${it.date_end || ''}"
|
||||
class="btn-edit-abs text-slate-400 hover:text-indigo-600 p-1 transition" title="Редактировать сроки">
|
||||
<i class="fa-solid fa-pen-to-square"></i>
|
||||
</button>
|
||||
<button data-del-id="${it.id}"
|
||||
class="btn-del-abs text-slate-400 hover:text-rose-500 p-1 transition" title="Удалить">
|
||||
<i class="fa-solid fa-trash-can"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
${!isTrip && reason ? `<div class="text-[11px] text-slate-600 font-medium">${reason}</div>` : ''}
|
||||
|
||||
<!-- 2-я строка: Отдел слева и Четкий срок отсутствия справа -->
|
||||
<div class="flex items-center justify-between text-[11px] pt-1 border-t border-slate-100">
|
||||
<span class="text-slate-400 truncate max-w-[200px]" title="${dept}">${dept}</span>
|
||||
<span class="font-mono text-[10px] px-2 py-0.5 rounded-md border font-semibold shrink-0 ${badgeBg}">
|
||||
<i class="fa-regular fa-calendar-days mr-1 text-[9px]"></i>${dateBadge}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="flex items-center justify-between px-1 mb-2">
|
||||
<span class="text-xs font-bold text-slate-700">${titleText}: ${items.length}</span>
|
||||
<button id="btn-add-absence" class="px-2.5 py-1 ${btnColor} text-white rounded-lg text-xs font-bold shadow-xs transition">+ Добавить</button>
|
||||
</div>
|
||||
<div class="space-y-2">${listHtml}</div>
|
||||
`;
|
||||
|
||||
const addBtn = document.getElementById('btn-add-absence');
|
||||
if (addBtn) {
|
||||
addBtn.addEventListener('click', () => openManualAbsenceModal(type));
|
||||
}
|
||||
|
||||
// Слушатели кнопок редактирования
|
||||
container.querySelectorAll('.btn-edit-abs').forEach(btn => {
|
||||
btn.addEventListener('click', e => {
|
||||
const t = e.currentTarget;
|
||||
const id = t.getAttribute('data-edit-id');
|
||||
const fio = t.getAttribute('data-edit-fio');
|
||||
const start = t.getAttribute('data-edit-start');
|
||||
const end = t.getAttribute('data-edit-end');
|
||||
|
||||
openManualAbsenceModal(type, {
|
||||
id: id,
|
||||
fio: fio,
|
||||
date_start: start,
|
||||
date_end: end
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Слушатели кнопок удаления
|
||||
container.querySelectorAll('.btn-del-abs').forEach(btn => {
|
||||
btn.addEventListener('click', e => {
|
||||
deleteManualAbsenceRecord(e.currentTarget.getAttribute('data-del-id'), type);
|
||||
});
|
||||
});
|
||||
} catch (e) {
|
||||
container.innerHTML = '<div class="text-center py-8 text-rose-500 text-xs">Ошибка загрузки</div>';
|
||||
}
|
||||
}
|
||||
|
||||
// Быстрое модальное окно / диалог изменения дат
|
||||
async function openEditAbsenceDatesModal(id, fio, dateStart, dateEnd, type) {
|
||||
const newEnd = prompt(`Укажите новую дату окончания для сотрудника:\n${fio}\n(формат ГГГГ-ММ-ДД):`, dateEnd || '');
|
||||
if (newEnd === null) return;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/v1/manual-absences/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: { ...AuthManager.getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
id: parseInt(id),
|
||||
date_start: dateStart || null,
|
||||
date_end: newEnd.trim() || null
|
||||
})
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
loadManualAbsencesView(type);
|
||||
} else {
|
||||
alert('Не удалось обновить дату');
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Ошибка сети при обновлении');
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteManualAbsenceRecord(id, type) {
|
||||
if (!confirm('Удалить эту запись?')) return;
|
||||
try {
|
||||
const res = await fetch('/api/v1/manual-absences/' + encodeURIComponent(id), {
|
||||
method: 'DELETE',
|
||||
headers: AuthManager.getAuthHeaders()
|
||||
});
|
||||
if (res.ok) loadManualAbsencesView(type);
|
||||
} catch (e) {
|
||||
alert('Ошибка сети');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
/**
|
||||
* Модуль вкладки "Срезы": список снапшотов по диапазону дат, создание, инспекция и генерация отчетов.
|
||||
*/
|
||||
|
||||
// 1. Вспомогательные функции форматирования дат
|
||||
function formatDateDDMMYYYY(d) {
|
||||
const day = String(d.getDate()).padStart(2, '0');
|
||||
const month = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const year = d.getFullYear();
|
||||
return `${day}.${month}.${year}`;
|
||||
}
|
||||
|
||||
function formatDateToISO(d) {
|
||||
const year = d.getFullYear();
|
||||
const month = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(d.getDate()).padStart(2, '0');
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
function isoToBackendFormat(isoStr) {
|
||||
if (!isoStr) return '';
|
||||
if (isoStr.includes('.')) return isoStr;
|
||||
const [y, m, d] = isoStr.split('-');
|
||||
return `${d}.${m}.${y}`;
|
||||
}
|
||||
|
||||
// 2. Автозаполнение полей создания среза текущими датой и временем
|
||||
function initManualSnapshotInputs() {
|
||||
const now = new Date();
|
||||
const dateInput = document.getElementById('manual-snapshot-date');
|
||||
const timeInput = document.getElementById('manual-snapshot-time');
|
||||
|
||||
if (dateInput) {
|
||||
dateInput.value = formatDateDDMMYYYY(now);
|
||||
}
|
||||
if (timeInput) {
|
||||
const hh = String(now.getHours()).padStart(2, '0');
|
||||
const mm = String(now.getMinutes()).padStart(2, '0');
|
||||
timeInput.value = `${hh}:${mm}`;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Быстрые пресеты периода
|
||||
window.setSnapshotDatePreset = function(preset) {
|
||||
const today = new Date();
|
||||
const fromInput = document.getElementById('snapshots-date-from');
|
||||
const toInput = document.getElementById('snapshots-date-to');
|
||||
|
||||
if (!fromInput || !toInput) return;
|
||||
|
||||
if (preset === 'today') {
|
||||
const str = formatDateToISO(today);
|
||||
fromInput.value = str;
|
||||
toInput.value = str;
|
||||
} else if (preset === 'yesterday') {
|
||||
const y = new Date();
|
||||
y.setDate(today.getDate() - 1);
|
||||
const str = formatDateToISO(y);
|
||||
fromInput.value = str;
|
||||
toInput.value = str;
|
||||
} else if (preset === 'days3') {
|
||||
const start = new Date();
|
||||
start.setDate(today.getDate() - 2);
|
||||
fromInput.value = formatDateToISO(start);
|
||||
toInput.value = formatDateToISO(today);
|
||||
} else if (preset === 'days7') {
|
||||
const start = new Date();
|
||||
start.setDate(today.getDate() - 6);
|
||||
fromInput.value = formatDateToISO(start);
|
||||
toInput.value = formatDateToISO(today);
|
||||
}
|
||||
|
||||
loadSnapshotsView();
|
||||
};
|
||||
|
||||
// 4. Загрузка списка срезов с группировкой и сортировкой
|
||||
async function loadSnapshotsView() {
|
||||
// Гарантированно заполняем поля даты и времени создания среза
|
||||
initManualSnapshotInputs();
|
||||
|
||||
const listContainer = document.getElementById('snapshots-list');
|
||||
const countBadge = document.getElementById('snapshots-count-badge');
|
||||
const fromInput = document.getElementById('snapshots-date-from');
|
||||
const toInput = document.getElementById('snapshots-date-to');
|
||||
|
||||
if (!listContainer) return;
|
||||
|
||||
const todayIso = formatDateToISO(new Date());
|
||||
if (fromInput && !fromInput.value) fromInput.value = todayIso;
|
||||
if (toInput && !toInput.value) toInput.value = todayIso;
|
||||
|
||||
const dateFrom = fromInput ? isoToBackendFormat(fromInput.value) : isoToBackendFormat(todayIso);
|
||||
const dateTo = toInput ? isoToBackendFormat(toInput.value) : dateFrom;
|
||||
|
||||
listContainer.innerHTML = `<div class="text-center py-10 text-slate-400 text-xs"><i class="fa-solid fa-spinner fa-spin mr-1"></i> Загрузка срезов...</div>`;
|
||||
|
||||
try {
|
||||
const url = `/api/v1/snapshots?date_from=${encodeURIComponent(dateFrom)}&date_to=${encodeURIComponent(dateTo)}`;
|
||||
const res = await fetch(url, { headers: AuthManager.getAuthHeaders() });
|
||||
if (!res.ok) throw new Error('Ошибка сети');
|
||||
const data = await res.json();
|
||||
const snapshots = data.snapshots || [];
|
||||
|
||||
if (countBadge) countBadge.innerText = `Срезы в базе: ${snapshots.length}`;
|
||||
|
||||
if (snapshots.length === 0) {
|
||||
listContainer.innerHTML = `
|
||||
<div class="text-center py-8 text-slate-400 text-xs space-y-2">
|
||||
<p>За выбранный период срезы не найдены</p>
|
||||
<button onclick="setSnapshotDatePreset('yesterday')" class="px-2.5 py-1 text-[11px] bg-slate-100 hover:bg-slate-200 text-slate-600 rounded-lg transition font-medium shadow-2xs">
|
||||
Показать за вчера
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
// Вспомогательный ключ для сортировки от новых к старым
|
||||
function getSortKey(s) {
|
||||
const sid = (s.snapshot_id || s.id || '').toUpperCase();
|
||||
const digits = sid.replace(/\D/g, '');
|
||||
if (sid.includes('FINAL') && digits.length >= 8) {
|
||||
return `${digits.substring(0, 8)}_235959`;
|
||||
}
|
||||
return digits.padEnd(14, '0');
|
||||
}
|
||||
|
||||
snapshots.sort((a, b) => getSortKey(b).localeCompare(getSortKey(a)));
|
||||
|
||||
// Группировка по дням
|
||||
const groups = {};
|
||||
snapshots.forEach(s => {
|
||||
const sid = s.snapshot_id || s.id || '';
|
||||
let groupDate = s.date || '';
|
||||
|
||||
if (!groupDate) {
|
||||
const digits = sid.replace(/\D/g, '');
|
||||
if (digits.length >= 8) {
|
||||
const y = digits.substring(0, 4);
|
||||
const m = digits.substring(4, 6);
|
||||
const d = digits.substring(6, 8);
|
||||
groupDate = `${d}.${m}.${y}`;
|
||||
} else {
|
||||
groupDate = 'Другие срезы';
|
||||
}
|
||||
}
|
||||
|
||||
if (!groups[groupDate]) groups[groupDate] = [];
|
||||
groups[groupDate].push(s);
|
||||
});
|
||||
|
||||
// Сортировка дат по убыванию
|
||||
const sortedDates = Object.keys(groups).sort((d1, d2) => {
|
||||
const parseDate = (str) => {
|
||||
const p = str.split('.');
|
||||
return p.length === 3 ? new Date(p[2], p[1] - 1, p[0]).getTime() : 0;
|
||||
};
|
||||
return parseDate(d2) - parseDate(d1);
|
||||
});
|
||||
|
||||
let html = '';
|
||||
for (const dateLabel of sortedDates) {
|
||||
const items = groups[dateLabel];
|
||||
html += `
|
||||
<div class="pt-2 pb-1 flex items-center gap-2">
|
||||
<span class="text-[11px] font-bold text-slate-600 uppercase tracking-wider flex items-center gap-1.5">
|
||||
<i class="fa-regular fa-calendar-days text-indigo-500 text-xs"></i> ${escapeHtml(dateLabel)}
|
||||
</span>
|
||||
<div class="h-px bg-slate-200 flex-1"></div>
|
||||
<span class="text-[10px] text-slate-400 font-semibold">${items.length} срез.</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
html += items.map(s => {
|
||||
const sid = s.snapshot_id || s.id;
|
||||
const isFinal = Boolean(s.is_final) || sid.toUpperCase().includes('FINAL');
|
||||
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 || '—';
|
||||
|
||||
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">
|
||||
<div>
|
||||
<div class="flex items-center">
|
||||
<span class="text-xs font-bold font-mono text-slate-800">${escapeHtml(sid)}</span>
|
||||
${badgeFinal}
|
||||
</div>
|
||||
<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>
|
||||
${!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>
|
||||
` : ''}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
listContainer.innerHTML = html;
|
||||
} catch (e) {
|
||||
listContainer.innerHTML = `<div class="text-center py-8 text-rose-500 text-xs">Не удалось загрузить срезы</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Ручное создание среза
|
||||
async function createSnapshotManual() {
|
||||
const dateVal = document.getElementById('manual-snapshot-date')?.value || '';
|
||||
const timeVal = document.getElementById('manual-snapshot-time')?.value || '';
|
||||
const btn = document.getElementById('btn-create-snapshot');
|
||||
|
||||
if (!dateVal) { alert('Укажите дату среза'); return; }
|
||||
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = `<i class="fa-solid fa-spinner fa-spin mr-1.5"></i> Создание...`;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/v1/snapshots/create', {
|
||||
method: 'POST',
|
||||
headers: { ...AuthManager.getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ date_str: dateVal, time_str: timeVal })
|
||||
});
|
||||
if (res.ok) {
|
||||
loadSnapshotsView();
|
||||
} else {
|
||||
const data = await res.json();
|
||||
alert(`Ошибка: ${data.detail || 'Не удалось сформировать срез'}`);
|
||||
}
|
||||
} catch (e) {
|
||||
alert('Ошибка сети');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = `<i class="fa-solid fa-camera mr-1.5"></i> Сделать срез`;
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Удаление среза
|
||||
async function deleteSnapshotItem(snapshotId) {
|
||||
if (!confirm(`Удалить срез ${snapshotId}?`)) return;
|
||||
try {
|
||||
const res = await fetch('/api/v1/snapshots', {
|
||||
method: 'DELETE',
|
||||
headers: { ...AuthManager.getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ snapshot_ids: [snapshotId] })
|
||||
});
|
||||
if (res.ok) loadSnapshotsView();
|
||||
} catch (e) { alert('Ошибка сети'); }
|
||||
}
|
||||
|
||||
// 7. Генерация отчетов On-Demand
|
||||
window.generateReportDirect = async function(reportType) {
|
||||
const fromInput = document.getElementById('snapshots-date-from');
|
||||
const dateInput = fromInput ? isoToBackendFormat(fromInput.value) : '';
|
||||
|
||||
const labelMap = {
|
||||
'SVODKA': 'Сводки',
|
||||
'SIMPLIFIED': 'Упрощенного отчета',
|
||||
'DETAILED': 'Детального отчета'
|
||||
};
|
||||
|
||||
const targetLabel = labelMap[reportType] || 'отчета';
|
||||
|
||||
try {
|
||||
const 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 // ⭐️ Всегда берем последний готовый срез
|
||||
})
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
alert(`Ошибка сервера (${res.status}) при создании ${targetLabel}`);
|
||||
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('[Reports] Ошибка генерации:', e);
|
||||
alert('Сетевая ошибка при запросе формирования отчета');
|
||||
}
|
||||
};
|
||||
|
||||
// 8. Инициализация при первичной загрузке страницы
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const todayIso = formatDateToISO(new Date());
|
||||
const fromInput = document.getElementById('snapshots-date-from');
|
||||
const toInput = document.getElementById('snapshots-date-to');
|
||||
if (fromInput && !fromInput.value) fromInput.value = todayIso;
|
||||
if (toInput && !toInput.value) toInput.value = todayIso;
|
||||
|
||||
initManualSnapshotInputs();
|
||||
});
|
||||
|
||||
// Экспортируем в глобальную область, чтобы core.js при переключении вкладок вызывал эту функцию
|
||||
window.loadSnapshotsView = loadSnapshotsView;
|
||||
window.createSnapshotManual = createSnapshotManual;
|
||||
window.deleteSnapshotItem = deleteSnapshotItem;
|
||||
Reference in New Issue
Block a user