сделал настройку временных слотов
This commit is contained in:
@@ -2,13 +2,13 @@ import { api } from '../api.js';
|
||||
import { escapeHtml, showAlert, hideAlert } from '../utils.js';
|
||||
|
||||
const DAY_OPTIONS = [
|
||||
{ value: 1, label: 'Понедельник' },
|
||||
{ value: 2, label: 'Вторник' },
|
||||
{ value: 3, label: 'Среда' },
|
||||
{ value: 4, label: 'Четверг' },
|
||||
{ value: 5, label: 'Пятница' },
|
||||
{ value: 6, label: 'Суббота' },
|
||||
{ value: 7, label: 'Воскресенье' }
|
||||
{ value: 1, label: 'Понедельник', shortLabel: 'Пн' },
|
||||
{ value: 2, label: 'Вторник', shortLabel: 'Вт' },
|
||||
{ value: 3, label: 'Среда', shortLabel: 'Ср' },
|
||||
{ value: 4, label: 'Четверг', shortLabel: 'Чт' },
|
||||
{ value: 5, label: 'Пятница', shortLabel: 'Пт' },
|
||||
{ value: 6, label: 'Суббота', shortLabel: 'Сб' },
|
||||
{ value: 7, label: 'Воскресенье', shortLabel: 'Вс' }
|
||||
];
|
||||
|
||||
const SEMESTER_LABELS = {
|
||||
@@ -548,7 +548,7 @@ export async function initAcademicCalendar() {
|
||||
<tbody>
|
||||
${DAY_OPTIONS.map(day => `
|
||||
<tr>
|
||||
<th class="calendar-day-head">${escapeHtml(day.label.slice(0, 2))}</th>
|
||||
<th class="calendar-day-head">${escapeHtml(day.shortLabel)}</th>
|
||||
${weeks.map(week => {
|
||||
const row = cellByWeekAndDay.get(`${week}:${day.value}`);
|
||||
return row ? renderCalendarDay(row) : '<td class="calendar-empty-day"></td>';
|
||||
@@ -804,8 +804,7 @@ export async function initAcademicCalendar() {
|
||||
}
|
||||
|
||||
function shortDayLabel(value) {
|
||||
const label = dayLabel(value);
|
||||
return label === '-' ? '-' : label.slice(0, 2);
|
||||
return DAY_OPTIONS.find(day => String(day.value) === String(value))?.shortLabel || '-';
|
||||
}
|
||||
|
||||
function formatShortDate(value) {
|
||||
|
||||
@@ -1,159 +1,417 @@
|
||||
import { initMultiSelect } from '../utils.js';
|
||||
import { api } from '../api.js';
|
||||
import { escapeHtml, initMultiSelect, showAlert, hideAlert } from '../utils.js';
|
||||
|
||||
export function initAuditoriumWorkload() {
|
||||
// Дата по умолчанию — текущий день.
|
||||
const NO_BUILDING = '__no_building__';
|
||||
|
||||
const DAY_SHORT_LABELS = {
|
||||
1: 'Пн',
|
||||
2: 'Вт',
|
||||
3: 'Ср',
|
||||
4: 'Чт',
|
||||
5: 'Пт',
|
||||
6: 'Сб',
|
||||
7: 'Вс'
|
||||
};
|
||||
|
||||
const CAPACITY_BUCKETS = [
|
||||
{ id: 'small', name: 'До 30 мест', match: capacity => Number(capacity || 0) < 30 },
|
||||
{ id: 'medium', name: '30 - 60 мест', match: capacity => Number(capacity || 0) >= 30 && Number(capacity || 0) <= 60 },
|
||||
{ id: 'large', name: '61 - 100 мест', match: capacity => Number(capacity || 0) > 60 && Number(capacity || 0) <= 100 },
|
||||
{ id: 'xlarge', name: 'Более 100 мест', match: capacity => Number(capacity || 0) > 100 }
|
||||
];
|
||||
|
||||
export async function initAuditoriumWorkload() {
|
||||
const dateInput = document.getElementById('workload-date');
|
||||
if (dateInput) {
|
||||
const refreshButton = document.getElementById('workload-refresh');
|
||||
const headerRow = document.getElementById('workload-header-row');
|
||||
const tbody = document.getElementById('workload-tbody');
|
||||
const summary = document.getElementById('workload-summary');
|
||||
|
||||
let classrooms = [];
|
||||
let timeSlots = [];
|
||||
let equipments = [];
|
||||
let groups = [];
|
||||
let lessonsByRoomSlot = new Map();
|
||||
let failedGroupLoads = 0;
|
||||
|
||||
setDefaultDate();
|
||||
initFilters();
|
||||
bindEvents();
|
||||
await loadInitialData();
|
||||
|
||||
function setDefaultDate() {
|
||||
if (!dateInput || dateInput.value) return;
|
||||
const today = new Date();
|
||||
const yyyy = today.getFullYear();
|
||||
const mm = String(today.getMonth() + 1).padStart(2, '0');
|
||||
const dd = String(today.getDate()).padStart(2, '0');
|
||||
dateInput.value = `${yyyy}-${mm}-${dd}`;
|
||||
dateInput.value = [
|
||||
today.getFullYear(),
|
||||
String(today.getMonth() + 1).padStart(2, '0'),
|
||||
String(today.getDate()).padStart(2, '0')
|
||||
].join('-');
|
||||
}
|
||||
|
||||
// Инициализация мультиселектов.
|
||||
initMultiSelect('building-box', 'building-menu', 'building-text', 'building-checkboxes');
|
||||
initMultiSelect('capacity-box', 'capacity-menu', 'capacity-text', 'capacity-checkboxes');
|
||||
initMultiSelect('equipment-box', 'equipment-menu', 'equipment-text', 'equipment-checkboxes');
|
||||
function initFilters() {
|
||||
initMultiSelect('building-box', 'building-menu', 'building-text', 'building-checkboxes');
|
||||
initMultiSelect('capacity-box', 'capacity-menu', 'capacity-text', 'capacity-checkboxes');
|
||||
initMultiSelect('equipment-box', 'equipment-menu', 'equipment-text', 'equipment-checkboxes');
|
||||
}
|
||||
|
||||
// Заполнение фильтров начальными данными.
|
||||
populateFilters();
|
||||
function bindEvents() {
|
||||
refreshButton?.addEventListener('click', loadScheduleForSelectedDate);
|
||||
dateInput?.addEventListener('change', loadScheduleForSelectedDate);
|
||||
|
||||
// Отрисовка mock-данных в нужной ориентации сетки.
|
||||
renderMockGrid();
|
||||
}
|
||||
[
|
||||
['building-checkboxes', 'building-text', 'Все корпуса'],
|
||||
['capacity-checkboxes', 'capacity-text', 'Любая вместимость'],
|
||||
['equipment-checkboxes', 'equipment-text', 'Любое оборудование']
|
||||
].forEach(([containerId, textId, emptyText]) => {
|
||||
const container = document.getElementById(containerId);
|
||||
container?.addEventListener('change', () => {
|
||||
updateFilterText(containerId, textId, emptyText);
|
||||
renderGrid();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function populateFilters() {
|
||||
// Корпуса.
|
||||
const buildingsContainer = document.getElementById('building-checkboxes');
|
||||
const buildings = [
|
||||
{ id: 1, name: "Корпус 1 (Главный)" },
|
||||
{ id: 2, name: "Корпус 2 (Физ-мат)" },
|
||||
{ id: 3, name: "Корпус 3 (Гуманитарный)" }
|
||||
];
|
||||
buildingsContainer.innerHTML = buildings.map(item => `
|
||||
<label class="checkbox-item">
|
||||
<input type="checkbox" value="${item.id}">
|
||||
<span class="checkmark"></span>
|
||||
<span class="checkbox-label">${item.name}</span>
|
||||
</label>
|
||||
`).join('');
|
||||
async function loadInitialData() {
|
||||
setTableLoading('Загрузка аудиторий и расписания...');
|
||||
try {
|
||||
[classrooms, equipments, groups] = await Promise.all([
|
||||
api.get('/api/classrooms'),
|
||||
api.get('/api/equipments'),
|
||||
api.get('/api/groups')
|
||||
]);
|
||||
classrooms = [...classrooms].sort((a, b) => naturalCompare(a.name, b.name));
|
||||
populateFilters();
|
||||
await loadScheduleForSelectedDate();
|
||||
} catch (error) {
|
||||
setTableError(error.message || 'Ошибка загрузки данных загруженности аудиторий');
|
||||
}
|
||||
}
|
||||
|
||||
// Вместимость.
|
||||
const capacityContainer = document.getElementById('capacity-checkboxes');
|
||||
const capacities = [
|
||||
{ id: 'small', name: "До 30 мест" },
|
||||
{ id: 'medium', name: "30 - 60 мест" },
|
||||
{ id: 'large', name: "60 - 100 мест" },
|
||||
{ id: 'xlarge', name: "Более 100 мест" }
|
||||
];
|
||||
capacityContainer.innerHTML = capacities.map(item => `
|
||||
<label class="checkbox-item">
|
||||
<input type="checkbox" value="${item.id}">
|
||||
<span class="checkmark"></span>
|
||||
<span class="checkbox-label">${item.name}</span>
|
||||
</label>
|
||||
`).join('');
|
||||
async function loadScheduleForSelectedDate() {
|
||||
const date = dateInput?.value;
|
||||
if (!date) {
|
||||
showAlert('workload-alert', 'Выберите дату', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
// Оборудование.
|
||||
const equipmentContainer = document.getElementById('equipment-checkboxes');
|
||||
const equipmentList = [
|
||||
{ id: 1, name: "Проектор" },
|
||||
{ id: 2, name: "Компьютерные места" },
|
||||
{ id: 3, name: "Интерактивная доска" },
|
||||
{ id: 4, name: "Микрофон" }
|
||||
];
|
||||
equipmentContainer.innerHTML = equipmentList.map(item => `
|
||||
<label class="checkbox-item">
|
||||
<input type="checkbox" value="${item.id}">
|
||||
<span class="checkmark"></span>
|
||||
<span class="checkbox-label">${item.name}</span>
|
||||
</label>
|
||||
`).join('');
|
||||
}
|
||||
hideAlert('workload-alert');
|
||||
setTableLoading('Загрузка расписания на выбранную дату...');
|
||||
timeSlots = await api.get(`/api/admin/time-slots/effective?date=${encodeURIComponent(date)}`);
|
||||
|
||||
function renderMockGrid() {
|
||||
// В будущем данные будут загружаться из API.
|
||||
const timeslots = [
|
||||
"8:00-9:30",
|
||||
"9:40-11:10",
|
||||
"11:40-13:10",
|
||||
"13:20-14:50",
|
||||
"15:00-16:30",
|
||||
"16:50-18:20",
|
||||
"18:30-19:50",
|
||||
"20:00-21:20"
|
||||
];
|
||||
if (!groups.length) {
|
||||
lessonsByRoomSlot = new Map();
|
||||
renderGrid();
|
||||
showAlert('workload-alert', 'Группы не созданы, занятость аудиторий пуста', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const auditoriums = [
|
||||
"201", "202", "204", "205", "206", "207", "208"
|
||||
];
|
||||
const params = group => new URLSearchParams({
|
||||
groupId: String(group.id),
|
||||
startDate: date,
|
||||
endDate: date
|
||||
}).toString();
|
||||
|
||||
// Mock-расписание по аудитории и времени.
|
||||
// Ключ: "roomId_timeSlotId", значение: объект занятия
|
||||
const mockSchedule = {
|
||||
"201_8:00-9:30": { subject: "Физика", group: "ИБ-41м", teacher: "Атлетов А.Р." },
|
||||
"201_9:40-11:10": { subject: "Физика", group: "ИВТ-21-1", teacher: "Атлетов А.Р." },
|
||||
"201_11:40-13:10": { subject: "Физика", group: "ИБ-41м", teacher: "Физик В.Г." },
|
||||
"201_13:20-14:50": { subject: "Физика", group: "ИБ-41м", teacher: "Физик В.Г." },
|
||||
|
||||
"202_9:40-11:10": { subject: "Химия", group: "ИВТ-21-1", teacher: "Химоза Я.В." },
|
||||
"202_13:20-14:50": { subject: "Математика", group: "ИВТ-21-1", teacher: "Рутина Л.П." },
|
||||
"202_15:00-16:30": { subject: "Химия", group: "ИВТ-21-1", teacher: "Химоза Я.В." },
|
||||
"202_16:50-18:20": { subject: "Физика", group: "ИВТ-21-1", teacher: "Атлетов А.Р." },
|
||||
const responses = await Promise.allSettled(
|
||||
groups.map(group => api.get(`/api/schedule?${params(group)}`))
|
||||
);
|
||||
failedGroupLoads = responses.filter(response => response.status === 'rejected').length;
|
||||
const lessons = responses
|
||||
.filter(response => response.status === 'fulfilled')
|
||||
.flatMap(response => response.value || []);
|
||||
|
||||
"205_9:40-11:10": { subject: "Организация аудита ИБ", group: "ИБ-41м", teacher: "Таныгин М.О." },
|
||||
};
|
||||
lessonsByRoomSlot = groupLessons(lessons);
|
||||
renderGrid();
|
||||
|
||||
// В столбцах отображаются временные слоты, в строках — аудитории.
|
||||
const headerRow = document.getElementById('workload-header-row');
|
||||
headerRow.innerHTML = `
|
||||
<th class="top-left-cell">
|
||||
<span class="top-label">Время</span>
|
||||
<span class="bottom-label">Аудитория</span>
|
||||
</th>
|
||||
`;
|
||||
|
||||
timeslots.forEach(time => {
|
||||
const th = document.createElement('th');
|
||||
th.textContent = time;
|
||||
headerRow.appendChild(th);
|
||||
});
|
||||
if (failedGroupLoads > 0) {
|
||||
showAlert('workload-alert', `Часть групп не загрузилась: ${failedGroupLoads}. Показаны доступные данные.`, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// Строки таблицы.
|
||||
const tbody = document.getElementById('workload-tbody');
|
||||
tbody.innerHTML = '';
|
||||
|
||||
auditoriums.forEach((room) => {
|
||||
const tr = document.createElement('tr');
|
||||
|
||||
// Ячейка аудитории.
|
||||
const tdRoom = document.createElement('td');
|
||||
tdRoom.className = 'axis-cell';
|
||||
tdRoom.textContent = room;
|
||||
tr.appendChild(tdRoom);
|
||||
function populateFilters() {
|
||||
renderCheckboxes(
|
||||
'building-checkboxes',
|
||||
buildingOptions(),
|
||||
item => item.value,
|
||||
item => item.label
|
||||
);
|
||||
renderCheckboxes(
|
||||
'capacity-checkboxes',
|
||||
CAPACITY_BUCKETS,
|
||||
item => item.id,
|
||||
item => item.name
|
||||
);
|
||||
renderCheckboxes(
|
||||
'equipment-checkboxes',
|
||||
equipmentOptions(),
|
||||
item => item.id,
|
||||
item => item.name
|
||||
);
|
||||
|
||||
// Ячейки временных слотов для аудитории.
|
||||
timeslots.forEach(time => {
|
||||
const td = document.createElement('td');
|
||||
|
||||
const scheduleKey = `${room}_${time}`;
|
||||
const lesson = mockSchedule[scheduleKey];
|
||||
|
||||
if (lesson) {
|
||||
// Карточка занятия.
|
||||
td.innerHTML = `
|
||||
<div class="lesson-card">
|
||||
<div class="lesson-subject">${lesson.subject}</div>
|
||||
<div class="lesson-group">${lesson.group}</div>
|
||||
<div class="lesson-teacher">${lesson.teacher}</div>
|
||||
</div>
|
||||
`;
|
||||
updateFilterText('building-checkboxes', 'building-text', 'Все корпуса');
|
||||
updateFilterText('capacity-checkboxes', 'capacity-text', 'Любая вместимость');
|
||||
updateFilterText('equipment-checkboxes', 'equipment-text', 'Любое оборудование');
|
||||
}
|
||||
|
||||
function buildingOptions() {
|
||||
const values = new Map();
|
||||
classrooms.forEach(room => {
|
||||
const key = buildingKey(room);
|
||||
values.set(key, key === NO_BUILDING ? 'Корпус не указан' : room.building);
|
||||
});
|
||||
return Array.from(values.entries())
|
||||
.map(([value, label]) => ({ value, label }))
|
||||
.sort((a, b) => naturalCompare(a.label, b.label));
|
||||
}
|
||||
|
||||
function equipmentOptions() {
|
||||
const source = equipments.length
|
||||
? equipments
|
||||
: classrooms.flatMap(room => room.equipments || []);
|
||||
const values = new Map();
|
||||
source.forEach(item => {
|
||||
if (item?.id && item?.name) values.set(String(item.id), item.name);
|
||||
});
|
||||
return Array.from(values.entries())
|
||||
.map(([id, name]) => ({ id, name }))
|
||||
.sort((a, b) => naturalCompare(a.name, b.name));
|
||||
}
|
||||
|
||||
function renderCheckboxes(containerId, items, valueFn, labelFn) {
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) return;
|
||||
if (!items.length) {
|
||||
container.innerHTML = '<div class="workload-filter-empty">Нет данных</div>';
|
||||
return;
|
||||
}
|
||||
container.innerHTML = items.map(item => `
|
||||
<label class="checkbox-item">
|
||||
<input type="checkbox" value="${escapeHtml(valueFn(item))}">
|
||||
<span class="checkmark"></span>
|
||||
<span class="checkbox-label">${escapeHtml(labelFn(item))}</span>
|
||||
</label>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
function groupLessons(lessons) {
|
||||
const unique = new Map();
|
||||
lessons.forEach(lesson => {
|
||||
if (!lesson.classroomId || !lesson.timeSlotId) return;
|
||||
const key = [
|
||||
lesson.date,
|
||||
lesson.scheduleRuleSlotId || lesson.scheduleRuleId || '',
|
||||
lesson.classroomId,
|
||||
lesson.timeSlotId,
|
||||
lesson.subjectId || '',
|
||||
lesson.teacherId || ''
|
||||
].join(':');
|
||||
const existing = unique.get(key);
|
||||
if (existing) {
|
||||
existing.groupNames = mergeNames(existing.groupNames, lesson.groupNames);
|
||||
existing.groupIds = mergeIds(existing.groupIds, lesson.groupIds);
|
||||
return;
|
||||
}
|
||||
|
||||
tr.appendChild(td);
|
||||
unique.set(key, {
|
||||
...lesson,
|
||||
groupNames: [...(lesson.groupNames || [])],
|
||||
groupIds: [...(lesson.groupIds || [])]
|
||||
});
|
||||
});
|
||||
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
const grouped = new Map();
|
||||
unique.forEach(lesson => {
|
||||
const key = roomSlotKey(lesson.classroomId, lesson.timeSlotId);
|
||||
if (!grouped.has(key)) grouped.set(key, []);
|
||||
grouped.get(key).push(lesson);
|
||||
});
|
||||
grouped.forEach(items => {
|
||||
items.sort((a, b) => naturalCompare(a.subjectName, b.subjectName));
|
||||
});
|
||||
return grouped;
|
||||
}
|
||||
|
||||
function renderGrid() {
|
||||
const visibleClassrooms = filteredClassrooms();
|
||||
renderHeader();
|
||||
tbody.innerHTML = '';
|
||||
|
||||
if (!visibleClassrooms.length) {
|
||||
tbody.innerHTML = `<tr><td colspan="${timeSlots.length + 1}" class="loading-row">Нет аудиторий по выбранным фильтрам</td></tr>`;
|
||||
renderSummary(0, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
visibleClassrooms.forEach(room => {
|
||||
const tr = document.createElement('tr');
|
||||
const roomCell = document.createElement('td');
|
||||
roomCell.className = `axis-cell${room.isAvailable === false ? ' room-unavailable' : ''}`;
|
||||
roomCell.innerHTML = `
|
||||
<strong>${escapeHtml(room.name)}</strong>
|
||||
<span>${room.capacity ? `${escapeHtml(room.capacity)} мест` : 'Вместимость не указана'}</span>
|
||||
${room.building ? `<small>${escapeHtml(room.building)}${room.floor ? `, ${escapeHtml(room.floor)} этаж` : ''}</small>` : ''}
|
||||
`;
|
||||
tr.appendChild(roomCell);
|
||||
|
||||
timeSlots.forEach(slot => {
|
||||
const td = document.createElement('td');
|
||||
const lessons = lessonsByRoomSlot.get(roomSlotKey(room.id, slot.id)) || [];
|
||||
td.className = lessons.length ? 'workload-busy-cell' : 'workload-free-cell';
|
||||
td.innerHTML = lessons.length
|
||||
? lessons.map(renderLessonCard).join('')
|
||||
: '<span class="free-slot">Свободно</span>';
|
||||
tr.appendChild(td);
|
||||
});
|
||||
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
|
||||
const occupiedCells = countOccupiedCells(visibleClassrooms);
|
||||
renderSummary(visibleClassrooms.length, occupiedCells, visibleClassrooms.length * timeSlots.length);
|
||||
}
|
||||
|
||||
function renderHeader() {
|
||||
headerRow.innerHTML = `
|
||||
<th class="top-left-cell">
|
||||
<span class="top-label">Время</span>
|
||||
<span class="bottom-label">Аудитория</span>
|
||||
</th>
|
||||
`;
|
||||
|
||||
timeSlots.forEach(slot => {
|
||||
const th = document.createElement('th');
|
||||
th.innerHTML = `
|
||||
<strong>${escapeHtml(slot.orderNumber || '')} пара</strong>
|
||||
<span>${escapeHtml(timeSlotLabel(slot))}</span>
|
||||
${slot.scopeApplyMode === 'DEFAULT' ? '' : `<small>${escapeHtml(scopeShort(slot))}</small>`}
|
||||
`;
|
||||
headerRow.appendChild(th);
|
||||
});
|
||||
}
|
||||
|
||||
function renderLessonCard(lesson) {
|
||||
return `
|
||||
<div class="lesson-card">
|
||||
<div class="lesson-subject">${escapeHtml(lesson.subjectName || 'Без дисциплины')}</div>
|
||||
<div class="lesson-group">${escapeHtml((lesson.groupNames || []).join(', ') || 'Группа не указана')}</div>
|
||||
<div class="lesson-teacher">${escapeHtml(lesson.teacherName || 'Преподаватель не указан')}</div>
|
||||
<div class="lesson-meta">${escapeHtml([lesson.lessonTypeName, lesson.lessonFormat].filter(Boolean).join(' · '))}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function filteredClassrooms() {
|
||||
const selectedBuildings = selectedValues('building-checkboxes');
|
||||
const selectedCapacities = selectedValues('capacity-checkboxes');
|
||||
const selectedEquipment = selectedValues('equipment-checkboxes');
|
||||
|
||||
return classrooms.filter(room => {
|
||||
const buildingMatches = !selectedBuildings.length || selectedBuildings.includes(buildingKey(room));
|
||||
const capacityMatches = !selectedCapacities.length || CAPACITY_BUCKETS
|
||||
.filter(bucket => selectedCapacities.includes(bucket.id))
|
||||
.some(bucket => bucket.match(room.capacity));
|
||||
const equipmentMatches = !selectedEquipment.length || selectedEquipment.every(id =>
|
||||
(room.equipments || []).some(item => String(item.id) === String(id))
|
||||
);
|
||||
return buildingMatches && capacityMatches && equipmentMatches;
|
||||
});
|
||||
}
|
||||
|
||||
function selectedValues(containerId) {
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) return [];
|
||||
return Array.from(container.querySelectorAll('input[type="checkbox"]:checked'))
|
||||
.map(input => input.value);
|
||||
}
|
||||
|
||||
function updateFilterText(containerId, textId, emptyText) {
|
||||
const container = document.getElementById(containerId);
|
||||
const text = document.getElementById(textId);
|
||||
if (!container || !text) return;
|
||||
const checked = Array.from(container.querySelectorAll('input[type="checkbox"]:checked'));
|
||||
if (!checked.length) {
|
||||
text.textContent = emptyText;
|
||||
} else if (checked.length === 1) {
|
||||
text.textContent = checked[0].closest('.checkbox-item')?.textContent.trim() || emptyText;
|
||||
} else {
|
||||
text.textContent = `Выбрано: ${checked.length}`;
|
||||
}
|
||||
}
|
||||
|
||||
function setTableLoading(message) {
|
||||
renderHeader();
|
||||
tbody.innerHTML = `<tr><td colspan="${Math.max(timeSlots.length, 1) + 1}" class="loading-row">${escapeHtml(message)}</td></tr>`;
|
||||
if (summary) summary.textContent = '';
|
||||
}
|
||||
|
||||
function setTableError(message) {
|
||||
renderHeader();
|
||||
tbody.innerHTML = `<tr><td colspan="${Math.max(timeSlots.length, 1) + 1}" class="loading-row">${escapeHtml(message)}</td></tr>`;
|
||||
showAlert('workload-alert', message, 'error');
|
||||
}
|
||||
|
||||
function renderSummary(roomCount, occupiedCells, totalCells) {
|
||||
if (!summary) return;
|
||||
const percent = totalCells ? Math.round((occupiedCells / totalCells) * 100) : 0;
|
||||
const date = dateInput?.value ? formatDate(dateInput.value) : '-';
|
||||
const day = dateInput?.value ? dayShort(selectedIsoDay()) : '-';
|
||||
const failed = failedGroupLoads ? `, ошибок загрузки групп: ${failedGroupLoads}` : '';
|
||||
summary.textContent = `Дата: ${date}, ${day}. Аудиторий: ${roomCount}. Занятых слотов: ${occupiedCells} из ${totalCells} (${percent}%)${failed}.`;
|
||||
}
|
||||
|
||||
function countOccupiedCells(rooms) {
|
||||
return rooms.reduce((count, room) => count + timeSlots.filter(slot =>
|
||||
(lessonsByRoomSlot.get(roomSlotKey(room.id, slot.id)) || []).length > 0
|
||||
).length, 0);
|
||||
}
|
||||
|
||||
function roomSlotKey(roomId, timeSlotId) {
|
||||
return `${roomId}:${timeSlotId}`;
|
||||
}
|
||||
|
||||
function buildingKey(room) {
|
||||
return room.building ? String(room.building) : NO_BUILDING;
|
||||
}
|
||||
|
||||
function mergeNames(first = [], second = []) {
|
||||
return Array.from(new Set([...first, ...second].filter(Boolean))).sort((a, b) => naturalCompare(a, b));
|
||||
}
|
||||
|
||||
function mergeIds(first = [], second = []) {
|
||||
return Array.from(new Set([...first, ...second].filter(id => id != null)));
|
||||
}
|
||||
|
||||
function timeSlotLabel(slot) {
|
||||
return `${trimTime(slot.startTime)}-${trimTime(slot.endTime)}`;
|
||||
}
|
||||
|
||||
function selectedIsoDay() {
|
||||
if (!dateInput?.value) return null;
|
||||
const date = new Date(`${dateInput.value}T00:00:00`);
|
||||
const day = date.getDay();
|
||||
return day === 0 ? 7 : day;
|
||||
}
|
||||
|
||||
function scopeShort(slot) {
|
||||
if (slot.scopeApplyMode === 'WEEKDAY') {
|
||||
return dayShort(slot.scopeDayOfWeek);
|
||||
}
|
||||
return 'Ручн.';
|
||||
}
|
||||
|
||||
function dayShort(dayOfWeek) {
|
||||
return DAY_SHORT_LABELS[Number(dayOfWeek)] || '-';
|
||||
}
|
||||
|
||||
function trimTime(value) {
|
||||
return value ? String(value).slice(0, 5) : '';
|
||||
}
|
||||
|
||||
function formatDate(value) {
|
||||
const [year, month, day] = String(value).split('-');
|
||||
return `${day}.${month}.${year}`;
|
||||
}
|
||||
|
||||
function naturalCompare(a, b) {
|
||||
return String(a || '').localeCompare(String(b || ''), 'ru', { numeric: true, sensitivity: 'base' });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,17 +37,6 @@ export async function initSchedule() {
|
||||
const rulesTbody = document.getElementById('schedule-tbody');
|
||||
const refreshRulesButton = document.getElementById('schedule-refresh');
|
||||
|
||||
const timeSlotForm = document.getElementById('time-slot-form');
|
||||
const timeSlotFormTitle = document.getElementById('time-slot-form-title');
|
||||
const timeSlotIdInput = document.getElementById('time-slot-id');
|
||||
const timeSlotOrderInput = document.getElementById('time-slot-order');
|
||||
const timeSlotStartInput = document.getElementById('time-slot-start');
|
||||
const timeSlotEndInput = document.getElementById('time-slot-end');
|
||||
const timeSlotDurationInput = document.getElementById('time-slot-duration');
|
||||
const timeSlotResetButton = document.getElementById('time-slot-reset');
|
||||
const timeSlotsTbody = document.getElementById('time-slots-tbody');
|
||||
const refreshSlotsButton = document.getElementById('time-slots-refresh');
|
||||
|
||||
let rules = [];
|
||||
let subjects = [];
|
||||
let groups = [];
|
||||
@@ -70,10 +59,8 @@ export async function initSchedule() {
|
||||
|
||||
function bindEvents() {
|
||||
refreshRulesButton?.addEventListener('click', loadRules);
|
||||
refreshSlotsButton?.addEventListener('click', loadTimeSlots);
|
||||
ruleResetButton?.addEventListener('click', resetRuleForm);
|
||||
slotAddButton?.addEventListener('click', () => renderRuleSlots([...readRuleSlots(false), {}]));
|
||||
timeSlotResetButton?.addEventListener('click', resetTimeSlotForm);
|
||||
|
||||
ruleSlotsContainer.addEventListener('click', (event) => {
|
||||
const removeButton = event.target.closest('.schedule-slot-remove');
|
||||
@@ -84,9 +71,7 @@ export async function initSchedule() {
|
||||
});
|
||||
|
||||
ruleForm.addEventListener('submit', saveRule);
|
||||
timeSlotForm.addEventListener('submit', saveTimeSlot);
|
||||
rulesTbody.addEventListener('click', handleRuleTableClick);
|
||||
timeSlotsTbody.addEventListener('click', handleTimeSlotTableClick);
|
||||
}
|
||||
|
||||
async function loadBaseLists() {
|
||||
@@ -293,97 +278,10 @@ export async function initSchedule() {
|
||||
}
|
||||
|
||||
async function loadTimeSlots() {
|
||||
timeSlotsTbody.innerHTML = '<tr><td colspan="5" class="loading-row">Загрузка...</td></tr>';
|
||||
try {
|
||||
timeSlots = await api.get('/api/admin/time-slots');
|
||||
renderTimeSlots();
|
||||
} catch (error) {
|
||||
timeSlotsTbody.innerHTML = `<tr><td colspan="5" class="loading-row">Ошибка загрузки: ${escapeHtml(error.message)}</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderTimeSlots() {
|
||||
if (!timeSlots.length) {
|
||||
timeSlotsTbody.innerHTML = '<tr><td colspan="5" class="loading-row">Сетка пар не настроена</td></tr>';
|
||||
return;
|
||||
}
|
||||
timeSlotsTbody.innerHTML = timeSlots.map(slot => `
|
||||
<tr>
|
||||
<td>${slot.orderNumber}</td>
|
||||
<td>${escapeHtml(trimTime(slot.startTime))}</td>
|
||||
<td>${escapeHtml(trimTime(slot.endTime))}</td>
|
||||
<td>${escapeHtml(String(slot.durationMinutes ?? '-'))}</td>
|
||||
<td>
|
||||
<button class="btn-edit-classroom btn-edit-time-slot" data-id="${slot.id}">Изменить</button>
|
||||
<button class="btn-delete btn-delete-time-slot" data-id="${slot.id}">Удалить</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
async function saveTimeSlot(event) {
|
||||
event.preventDefault();
|
||||
hideAlert('time-slot-alert');
|
||||
const payload = {
|
||||
id: timeSlotIdInput.value ? Number(timeSlotIdInput.value) : null,
|
||||
orderNumber: Number(timeSlotOrderInput.value),
|
||||
startTime: timeSlotStartInput.value,
|
||||
endTime: timeSlotEndInput.value,
|
||||
durationMinutes: timeSlotDurationInput.value ? Number(timeSlotDurationInput.value) : null
|
||||
};
|
||||
try {
|
||||
if (!payload.orderNumber || !payload.startTime || !payload.endTime) {
|
||||
throw new Error('Заполните номер пары и время');
|
||||
}
|
||||
const id = timeSlotIdInput.value;
|
||||
await (id
|
||||
? api.put('/api/admin/time-slots/' + id, payload)
|
||||
: api.post('/api/admin/time-slots', payload));
|
||||
showAlert('time-slot-alert', 'Временной слот сохранён', 'success');
|
||||
resetTimeSlotForm();
|
||||
await loadTimeSlots();
|
||||
renderRuleSlots(readRuleSlots(false).length ? readRuleSlots(false) : [{}]);
|
||||
} catch (error) {
|
||||
showAlert('time-slot-alert', error.message || 'Ошибка сохранения временного слота', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleTimeSlotTableClick(event) {
|
||||
const editButton = event.target.closest('.btn-edit-time-slot');
|
||||
const deleteButton = event.target.closest('.btn-delete-time-slot');
|
||||
|
||||
if (editButton) {
|
||||
const slot = timeSlots.find(item => item.id == editButton.dataset.id);
|
||||
if (!slot) return;
|
||||
timeSlotFormTitle.textContent = 'Редактирование временного слота';
|
||||
timeSlotIdInput.value = slot.id;
|
||||
timeSlotOrderInput.value = slot.orderNumber || '';
|
||||
timeSlotStartInput.value = trimTime(slot.startTime);
|
||||
timeSlotEndInput.value = trimTime(slot.endTime);
|
||||
timeSlotDurationInput.value = slot.durationMinutes || '';
|
||||
hideAlert('time-slot-alert');
|
||||
timeSlotForm.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (deleteButton) {
|
||||
if (!confirm('Удалить временной слот?')) return;
|
||||
try {
|
||||
await api.delete('/api/admin/time-slots/' + deleteButton.dataset.id);
|
||||
showAlert('time-slot-alert', 'Временной слот удалён', 'success');
|
||||
await loadTimeSlots();
|
||||
renderRuleSlots(readRuleSlots(false).length ? readRuleSlots(false) : [{}]);
|
||||
} catch (error) {
|
||||
showAlert('time-slot-alert', error.message || 'Ошибка удаления временного слота', 'error');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function resetTimeSlotForm() {
|
||||
timeSlotForm.reset();
|
||||
timeSlotFormTitle.textContent = 'Новый временной слот';
|
||||
timeSlotIdInput.value = '';
|
||||
hideAlert('time-slot-alert');
|
||||
const slots = await api.get('/api/admin/time-slots');
|
||||
timeSlots = slots
|
||||
.filter(slot => slot.scopeApplyMode === 'DEFAULT')
|
||||
.sort((a, b) => (a.orderNumber || 0) - (b.orderNumber || 0));
|
||||
}
|
||||
|
||||
function populateSubjectSelects() {
|
||||
|
||||
Reference in New Issue
Block a user