поправил просмотр расписания

This commit is contained in:
Zuev
2026-05-20 01:29:07 +03:00
parent 91729cff7d
commit b1b85c3d17
6 changed files with 397 additions and 101 deletions

View File

@@ -592,12 +592,7 @@
.schedule-view-matrix-table th,
.schedule-view-matrix-table td {
min-width: 150px;
height: 118px;
}
.schedule-view-matrix-table .schedule-view-date-cell {
width: 150px;
min-width: 150px;
height: 172px;
}
.schedule-view-lesson-card .lesson-meta + .lesson-meta {

View File

@@ -7,19 +7,45 @@ const PARITY_LABELS = {
ODD: 'нечётная',
EVEN: 'чётная'
};
const DAY_SHORT_LABELS = {
1: 'Пн',
2: 'Вт',
3: 'Ср',
4: 'Чт',
5: 'Пт',
6: 'Сб',
7: 'Вс'
};
const DAY_FULL_LABELS = {
1: 'Понедельник',
2: 'Вторник',
3: 'Среда',
4: 'Четверг',
5: 'Пятница',
6: 'Суббота',
7: 'Воскресенье'
};
const DAY_ORDER = [1, 2, 3, 4, 5, 6, 7];
const CELL_PARITY_LAYOUT = [
{ parity: 'ODD', label: 'Нечётная' },
{ parity: 'EVEN', label: 'Чётная' }
];
const SPLIT_AUTO = 'auto';
const SPLIT_GROUPS = 'groups';
const SPLIT_TEACHERS = 'teachers';
const SPLIT_CLASSROOMS = 'classrooms';
export async function initScheduleView() {
const role = localStorage.getItem('role');
const userDepartmentId = localStorage.getItem('departmentId');
const startInput = document.getElementById('schedule-view-start');
const endInput = document.getElementById('schedule-view-end');
const dateInput = document.getElementById('schedule-view-date');
const loadButton = document.getElementById('schedule-view-load');
const departmentField = document.getElementById('schedule-view-department-field');
const departmentSelect = document.getElementById('schedule-view-department');
const tables = document.getElementById('schedule-view-tables');
const countLabel = document.getElementById('schedule-view-count');
setDefaultDates(startInput, endInput);
setDefaultDate(dateInput);
loadButton?.addEventListener('click', loadData);
try {
@@ -38,9 +64,17 @@ export async function initScheduleView() {
setTableState('Загрузка...');
countLabel.textContent = 'Загрузка...';
if (!dateInput.value) {
const message = 'Выберите дату в периоде';
showAlert('schedule-view-alert', message, 'error');
setTableState(message);
countLabel.textContent = '0 занятий';
return;
}
const range = twoWeekRange(dateInput.value);
const params = new URLSearchParams({
startDate: startInput.value,
endDate: endInput.value
startDate: range.startDate,
endDate: range.endDate
});
addOptional(params, 'groupId', valueOf('schedule-view-group'));
addOptional(params, 'teacherId', valueOf('schedule-view-teacher'));
@@ -52,7 +86,7 @@ export async function initScheduleView() {
try {
const lessons = await api.get(`/api/schedule/search?${params}`);
renderLessons(lessons);
renderLessons(lessons, range);
} catch (error) {
const message = error.message || 'Ошибка загрузки расписания';
showAlert('schedule-view-alert', message, 'error');
@@ -61,46 +95,72 @@ export async function initScheduleView() {
}
}
function renderLessons(lessons) {
function renderLessons(lessons, range) {
countLabel.textContent = lessonCountLabel(lessons.length);
if (!lessons.length) {
setTableState('Занятия не найдены');
return;
}
const slots = collectSlots(lessons);
const lessonsByDateSlot = groupLessonsByDateSlot(lessons);
const weeks = groupDatesByWeek(lessons.map(lesson => lesson.date));
tables.innerHTML = weeks
.map(week => renderWeekTable(week, slots, lessonsByDateSlot))
const sections = buildScheduleSections(lessons);
if (!sections.length) {
setTableState('Нет данных для выбранного разреза таблиц');
return;
}
const tableCount = sections.reduce((count, section) =>
count + buildCombinedWeekBlocks(range.startDate, range.endDate, section.lessons).length, 0
);
if (!tableCount) {
setTableState('Выберите корректный период');
return;
}
countLabel.textContent = `${lessonCountLabel(lessons.length)}, ${tableCountLabel(tableCount)}`;
tables.innerHTML = sections
.map(section => renderScheduleSection(section, range))
.join('');
}
function renderWeekTable(week, slots, lessonsByDateSlot) {
const rows = week.dates.map(date => `
function renderScheduleSection(section, range) {
const slots = collectSlots(section.lessons);
const lessonsByDateSlot = groupLessonsByDateSlot(section.lessons);
const blocks = buildCombinedWeekBlocks(range.startDate, range.endDate, section.lessons);
return blocks
.map(block => renderCombinedWeekTable(block, slots, lessonsByDateSlot, section))
.join('');
}
function renderCombinedWeekTable(block, slots, lessonsByDateSlot, section) {
const dayHeaders = DAY_ORDER.map(day => `
<th class="room-day-cell">
<strong>${escapeHtml(dayShort(day))}</strong>
<span>${escapeHtml(DAY_FULL_LABELS[day] || '')}</span>
<div class="room-day-parity-dates">
${CELL_PARITY_LAYOUT.map(({ parity, label }) => renderDayParityDate(block.datesByDay[day]?.[parity], label)).join('')}
</div>
</th>
`).join('');
const rows = slots.map(slot => `
<tr>
<td class="axis-cell schedule-view-date-cell">
<strong>${escapeHtml(dayTitle(date, lessonsByDateSlot))}</strong>
<span>${escapeHtml(formatDate(date))}</span>
<td class="room-time-cell">
<strong>${escapeHtml(slot.orderLabel)}</strong>
<span>${escapeHtml(slot.timeLabel)}</span>
${slot.id ? `<small>ID ${escapeHtml(slot.id)}</small>` : ''}
</td>
${slots.map(slot => renderSlotCell(date, slot, lessonsByDateSlot)).join('')}
${DAY_ORDER.map(day => renderCombinedSlotCell(block.datesByDay[day] || {}, slot, lessonsByDateSlot)).join('')}
</tr>
`).join('');
return `
<section class="schedule-view-week-panel">
<div class="room-week-heading">
<h3>${escapeHtml(week.label)}</h3>
<span>${escapeHtml(weekCaption(week.dates))}</span>
<h3>${escapeHtml(section.title)} · ${escapeHtml(block.label)}</h3>
<span>${escapeHtml(`${lessonCountLabel(section.lessons.length)}; ${combinedWeekCaption(block)}`)}</span>
</div>
<div class="workload-grid-container schedule-view-grid-container">
<table class="workload-table schedule-view-matrix-table">
<table class="workload-table room-week-table schedule-view-matrix-table">
<thead>
<tr>
<th class="top-left-cell">
<span class="top-label">Время</span>
<span class="bottom-label">Дата</span>
</th>
${slots.map(renderSlotHeader).join('')}
<th class="room-time-heading">Время</th>
${dayHeaders}
</tr>
</thead>
<tbody>${rows}</tbody>
@@ -110,23 +170,107 @@ export async function initScheduleView() {
`;
}
function renderSlotHeader(slot) {
function renderDayParityDate(date, label) {
return `<span>${escapeHtml(label)}: ${date ? escapeHtml(formatDateShort(date)) : '-'}</span>`;
}
function renderCombinedSlotCell(datesByParity, slot, lessonsByDateSlot) {
const states = CELL_PARITY_LAYOUT.map(({ parity, label }) => ({
parity,
label,
state: scheduleSlotState(datesByParity[parity], slot, lessonsByDateSlot)
}));
if (slotStatesEqual(states[0].state, states[1].state)) {
return `<td class="room-combined-cell room-single-cell">${renderUnifiedSlot(states[0].state)}</td>`;
}
const halves = states.map(({ parity, label, state }) =>
renderSlotHalf(state, parity, label)
).join('');
return `<td class="room-combined-cell">${halves}</td>`;
}
function scheduleSlotState(date, slot, lessonsByDateSlot) {
if (!date) {
return { kind: 'empty', lessons: [] };
}
const lessons = lessonsByDateSlot.get(dateSlotKey(date, slot.key)) || [];
if (lessons.length) {
return { kind: 'busy', lessons };
}
return { kind: 'free', lessons: [] };
}
function renderUnifiedSlot(state) {
if (state.kind === 'busy') {
return `<div class="room-week-unified room-week-unified-busy">${state.lessons.map(renderLessonCard).join('')}</div>`;
}
if (state.kind === 'empty') {
return '<div class="room-week-unified room-week-unified-empty"><span class="slot-unavailable">Нет даты</span></div>';
}
return '<div class="room-week-unified room-week-unified-free"><span class="free-slot">Нет занятий</span></div>';
}
function renderSlotHalf(state, parity, label) {
if (state.kind === 'busy') {
return `
<div class="room-week-half room-week-half-${parity.toLowerCase()} room-week-half-busy">
<span class="room-half-marker">${escapeHtml(label)}</span>
${state.lessons.map(renderLessonCard).join('')}
</div>
`;
}
if (state.kind === 'empty') {
return `
<div class="room-week-half room-week-half-${parity.toLowerCase()} room-week-half-empty">
<span class="room-half-marker">${escapeHtml(label)}</span>
<span class="slot-unavailable">Нет даты</span>
</div>
`;
}
return `
<th>
<strong>${escapeHtml(slot.orderLabel)}</strong>
<span>${escapeHtml(slot.timeLabel)}</span>
${slot.id ? `<small>ID ${escapeHtml(slot.id)}</small>` : ''}
</th>
<div class="room-week-half room-week-half-${parity.toLowerCase()} room-week-half-free">
<span class="room-half-marker">${escapeHtml(label)}</span>
<span class="free-slot">Нет занятий</span>
</div>
`;
}
function renderSlotCell(date, slot, lessonsByDateSlot) {
const lessons = lessonsByDateSlot.get(dateSlotKey(date, slot.key)) || [];
return `
<td class="${lessons.length ? 'workload-busy-cell' : 'workload-free-cell'}">
${lessons.length ? lessons.map(renderLessonCard).join('') : '<span class="free-slot">Свободно</span>'}
</td>
`;
function slotStatesEqual(first, second) {
if (first.kind !== second.kind) return false;
if (first.kind !== 'busy') return true;
return lessonSetSignature(first.lessons) === lessonSetSignature(second.lessons);
}
function lessonSetSignature(lessons) {
return lessons
.map(lessonContentSignature)
.sort((a, b) => naturalCompare(a, b))
.join('|');
}
function lessonContentSignature(lesson) {
return [
lesson.scheduleRuleSlotId || lesson.scheduleRuleId || '',
lesson.subjectId || lesson.subjectName || '',
lesson.teacherId || lesson.teacherName || '',
lesson.classroomId || lesson.classroomName || '',
lesson.lessonTypeId || lesson.lessonTypeName || '',
lesson.lessonFormat || '',
valueListSignature(lesson.groupIds, lesson.groupNames),
valueListSignature(lesson.subgroupIds, lesson.subgroupNames)
].join(':');
}
function valueListSignature(primary = [], fallback = []) {
const primaryList = Array.isArray(primary) ? primary : [];
const fallbackList = Array.isArray(fallback) ? fallback : [];
const source = primaryList.length ? primaryList : fallbackList;
return [...source]
.map(value => String(value))
.sort((a, b) => naturalCompare(a, b))
.join(',');
}
function renderLessonCard(lesson) {
@@ -178,12 +322,9 @@ async function loadDictionaries(role, userDepartmentId) {
}
}
function setDefaultDates(startInput, endInput) {
function setDefaultDate(dateInput) {
const today = new Date();
const nextWeek = new Date();
nextWeek.setDate(today.getDate() + 7);
startInput.value = toIsoDate(today);
endInput.value = toIsoDate(nextWeek);
dateInput.value = toIsoDate(today);
}
function fillSelect(id, items, valueFn, labelFn, emptyLabel) {
@@ -205,14 +346,6 @@ function roomLabel(room) {
return [room.name, room.building, room.floor ? `${room.floor} этаж` : null].filter(Boolean).join(' · ');
}
function formatSlot(lesson) {
const order = lesson.timeSlotOrder ? `${lesson.timeSlotOrder} пара` : 'Пара';
const time = lesson.startTime && lesson.endTime
? ` (${trimTime(lesson.startTime)}-${trimTime(lesson.endTime)})`
: '';
return `${order}${time}`;
}
function collectSlots(lessons) {
const slots = new Map();
lessons.forEach(lesson => {
@@ -252,35 +385,159 @@ function groupLessonsByDateSlot(lessons) {
return grouped;
}
function groupDatesByWeek(dates) {
const groups = new Map();
Array.from(new Set(dates.filter(Boolean)))
.sort((a, b) => naturalCompare(a, b))
.forEach(date => {
const key = weekStart(date);
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(date);
function buildScheduleSections(lessons) {
const splitType = resolveSplitType();
const sections = new Map();
lessons.forEach(lesson => {
splitEntitiesForLesson(lesson, splitType).forEach(entity => {
if (!sections.has(entity.key)) {
sections.set(entity.key, {
key: entity.key,
title: entity.title,
lessons: []
});
}
sections.get(entity.key).lessons.push(lesson);
});
return Array.from(groups.entries()).map(([startDate, weekDates]) => ({
startDate,
dates: weekDates,
label: `Неделя ${formatDate(startDate)} - ${formatDate(addDaysToIso(startDate, 6))}`
}));
});
return Array.from(sections.values())
.map(section => ({
...section,
lessons: sortLessons(section.lessons)
}))
.sort((a, b) => naturalCompare(a.title, b.title));
}
function dayTitle(date, lessonsByDateSlot) {
for (const [key, lessons] of lessonsByDateSlot.entries()) {
if (key.startsWith(`${date}:`) && lessons[0]?.dayName) {
return lessons[0].dayName;
}
function resolveSplitType() {
const requested = valueOf('schedule-view-split');
if ([SPLIT_GROUPS, SPLIT_TEACHERS, SPLIT_CLASSROOMS].includes(requested)) {
return requested;
}
return dayName(date);
if (valueOf('schedule-view-teacher')) return SPLIT_TEACHERS;
if (valueOf('schedule-view-classroom')) return SPLIT_CLASSROOMS;
return SPLIT_GROUPS;
}
function weekCaption(dates) {
const first = dates[0];
const last = dates[dates.length - 1];
return `${formatDate(first)} - ${formatDate(last)}`;
function splitEntitiesForLesson(lesson, splitType) {
if (splitType === SPLIT_TEACHERS) {
return [singleEntity('teacher', lesson.teacherId, lesson.teacherName, 'Преподаватель не указан')];
}
if (splitType === SPLIT_CLASSROOMS) {
return [singleEntity('classroom', lesson.classroomId, lesson.classroomName, 'Аудитория не указана')];
}
return listEntities('group', lesson.groupIds, lesson.groupNames, 'Группа не указана');
}
function singleEntity(prefix, id, name, fallback) {
const title = name || fallback;
return {
key: `${prefix}:${id ?? title}`,
title
};
}
function listEntities(prefix, ids = [], names = [], fallback) {
const safeIds = Array.isArray(ids) ? ids : [];
const safeNames = Array.isArray(names) ? names : [];
if (!safeIds.length && !safeNames.length) {
return [singleEntity(prefix, null, fallback, fallback)];
}
const maxLength = Math.max(safeIds.length, safeNames.length);
const entities = [];
for (let index = 0; index < maxLength; index += 1) {
const id = safeIds[index] ?? null;
const name = safeNames[index] || (id == null ? fallback : `Группа ${id}`);
entities.push(singleEntity(prefix, id, name, fallback));
}
return entities;
}
function sortLessons(lessons) {
return [...lessons].sort((a, b) =>
naturalCompare(a.date, b.date)
|| compareSlots(lessonSlotDescriptor(a), lessonSlotDescriptor(b))
|| naturalCompare(a.subjectName, b.subjectName)
|| naturalCompare(a.teacherName, b.teacherName)
|| naturalCompare(a.classroomName, b.classroomName)
);
}
function lessonSlotDescriptor(lesson) {
return {
key: lessonSlotKey(lesson),
orderNumber: lesson.timeSlotOrder,
startTime: lesson.startTime
};
}
function buildCombinedWeekBlocks(startDate, endDate, lessons) {
const dates = datesBetween(startDate, endDate);
const weekGroups = new Map();
dates.forEach(date => {
const key = weekStart(date);
if (!weekGroups.has(key)) weekGroups.set(key, []);
weekGroups.get(key).push(date);
});
const weekStarts = Array.from(weekGroups.keys()).sort((a, b) => naturalCompare(a, b));
const blocks = [];
for (let index = 0; index < weekStarts.length; index += 2) {
const firstWeek = weekGroups.get(weekStarts[index]) || [];
const secondWeek = weekGroups.get(weekStarts[index + 1]) || [];
const blockDates = [...firstWeek, ...secondWeek];
const firstParity = weekParity(firstWeek, lessons) || 'ODD';
const secondParity = weekParity(secondWeek, lessons) || (firstParity === 'ODD' ? 'EVEN' : 'ODD');
const datesWithFallback = [
...firstWeek.map(date => ({ date, fallbackParity: firstParity })),
...secondWeek.map(date => ({ date, fallbackParity: secondParity }))
];
blocks.push({
startDate: blockDates[0],
endDate: blockDates[blockDates.length - 1],
datesByDay: buildDatesByDay(datesWithFallback, lessons),
label: `Период ${formatDate(blockDates[0])} - ${formatDate(blockDates[blockDates.length - 1])}`
});
}
return blocks;
}
function weekParity(dates, lessons) {
for (const date of dates) {
const parity = parityForDate(date, lessons);
if (parity) return parity;
}
return null;
}
function buildDatesByDay(datesWithFallback, lessons) {
const datesByDay = {};
datesWithFallback.forEach(({ date, fallbackParity }) => {
const day = isoDay(date);
const parity = parityForDate(date, lessons) || fallbackParity;
if (!datesByDay[day]) datesByDay[day] = {};
datesByDay[day][parity] = date;
});
return datesByDay;
}
function parityForDate(date, lessons) {
const lesson = lessons.find(item => item.date === date && ['ODD', 'EVEN'].includes(item.parity));
if (lesson?.parity) return lesson.parity;
const withWeek = lessons.find(item => item.date === date && item.weekNumber != null);
if (withWeek?.weekNumber != null) return Number(withWeek.weekNumber) % 2 === 0 ? 'EVEN' : 'ODD';
return null;
}
function combinedWeekCaption(block) {
return CELL_PARITY_LAYOUT
.map(({ parity, label }) => {
const dates = DAY_ORDER.map(day => block.datesByDay[day]?.[parity]).filter(Boolean);
if (!dates.length) return `${label}: дат нет`;
return `${label}: ${formatDate(dates[0])} - ${formatDate(dates[dates.length - 1])}`;
})
.join('; ');
}
function lessonSlotKey(lesson) {
@@ -299,10 +556,20 @@ function weekStart(value) {
return toIsoDate(date);
}
function addDaysToIso(value, days) {
const date = parseIsoDate(value);
date.setDate(date.getDate() + days);
return toIsoDate(date);
function twoWeekRange(value) {
const selected = parseIsoDate(value);
const start = addDays(selected, 1 - isoDay(value));
const end = addDays(start, 13);
return {
startDate: toIsoDate(start),
endDate: toIsoDate(end)
};
}
function addDays(date, days) {
const next = new Date(date);
next.setDate(next.getDate() + days);
return next;
}
function parseIsoDate(value) {
@@ -310,8 +577,21 @@ function parseIsoDate(value) {
return new Date(year, month - 1, day);
}
function dayName(value) {
return parseIsoDate(value).toLocaleDateString('ru-RU', { weekday: 'long' });
function datesBetween(startDate, endDate) {
const dates = [];
for (let date = parseIsoDate(startDate); date <= parseIsoDate(endDate); date.setDate(date.getDate() + 1)) {
dates.push(toIsoDate(date));
}
return dates;
}
function isoDay(value) {
const day = parseIsoDate(value).getDay();
return day === 0 ? 7 : day;
}
function dayShort(dayOfWeek) {
return DAY_SHORT_LABELS[Number(dayOfWeek)] || '-';
}
function formatDate(value) {
@@ -320,6 +600,11 @@ function formatDate(value) {
return `${day}.${month}.${year}`;
}
function formatDateShort(value) {
const [, month, day] = String(value).split('-');
return `${day}.${month}`;
}
function trimTime(value) {
return String(value || '').slice(0, 5);
}
@@ -340,6 +625,14 @@ function lessonCountLabel(count) {
return `${count} занятий`;
}
function tableCountLabel(count) {
const tail = count % 100;
if (tail >= 11 && tail <= 14) return `${count} таблиц`;
if (count % 10 === 1) return `${count} таблица`;
if ([2, 3, 4].includes(count % 10)) return `${count} таблицы`;
return `${count} таблиц`;
}
function compareSlots(a, b) {
const first = Number(a.orderNumber || a.key);
const second = Number(b.orderNumber || b.key);

View File

@@ -6,12 +6,8 @@
<div class="schedule-view-filter-grid">
<div class="form-group">
<label for="schedule-view-start">Начало</label>
<input type="date" id="schedule-view-start">
</div>
<div class="form-group">
<label for="schedule-view-end">Окончание</label>
<input type="date" id="schedule-view-end">
<label for="schedule-view-date">Дата в периоде</label>
<input type="date" id="schedule-view-date">
</div>
<div class="form-group">
<label for="schedule-view-group">Группа</label>
@@ -58,6 +54,15 @@
<option value="EVEN">Чётная</option>
</select>
</div>
<div class="form-group">
<label for="schedule-view-split">Таблицы по</label>
<select id="schedule-view-split" data-native-select="true">
<option value="auto">Автоматически</option>
<option value="groups">Группам</option>
<option value="teachers">Преподавателям</option>
<option value="classrooms">Аудиториям</option>
</select>
</div>
</div>
<div class="form-alert" id="schedule-view-alert" role="alert"></div>