Files
scud_ai/modules/web_api/static/js/sidebar/registries.js
T

670 lines
34 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Модуль вкладок "Реестры": исключения, удаленщики, командировки, флигель.
*/
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');
else if (subTab === 'schedules') loadSchedulesView();
}
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('Ошибка сети');
}
}
// ============================================================================
// ВКЛАДКА "ГРАФИКИ РАБОТЫ СОТРУДНИКОВ"
// ============================================================================
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('Сетевая ошибка при изменении графика');
}
}