Миллион изменений, создание вкладки "Расписание занятий"
This commit is contained in:
@@ -26,7 +26,6 @@ import { initClassrooms } from './views/classrooms.js';
|
||||
import { initSubjects } from './views/subjects.js';
|
||||
import {initSchedule} from "./views/schedule.js";
|
||||
import {initDatabase} from "./views/database.js";
|
||||
import {initDepartment} from "./views/department.js";
|
||||
import {initDepartmentsData} from "./views/departments-data.js";
|
||||
import {initAuditoriumWorkload} from "./views/auditorium-workload.js";
|
||||
|
||||
@@ -41,7 +40,6 @@ const ROUTES = {
|
||||
schedule: { title: 'Расписание занятий', file: 'views/schedule.html', init: initSchedule },
|
||||
'auditorium-workload': { title: 'Загруженность аудиторий', file: 'views/auditorium-workload.html', init: initAuditoriumWorkload },
|
||||
database: { title: 'База данных', file: 'views/database.html', init: initDatabase },
|
||||
department: { title: 'Кафедры', file: 'views/department.html', init: initDepartment },
|
||||
'departments-data': { title: 'Создание кафедры/специальности', file: 'views/departments-data.html', init: initDepartmentsData },
|
||||
};
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ function renderMockGrid() {
|
||||
];
|
||||
|
||||
// Mock schedule data mapped by room and time
|
||||
// Key: "roomId_timeSlotId", Value: Lesson object
|
||||
// Ключ: "roomId_timeSlotId", значение: объект занятия
|
||||
const mockSchedule = {
|
||||
"201_8:00-9:30": { subject: "Физика", group: "ИБ-41м", teacher: "Атлетов А.Р." },
|
||||
"201_9:40-11:10": { subject: "Физика", group: "ИВТ-21-1", teacher: "Атлетов А.Р." },
|
||||
|
||||
@@ -1,456 +0,0 @@
|
||||
import { api } from '../api.js';
|
||||
import { escapeHtml, showAlert, hideAlert } from '../utils.js';
|
||||
|
||||
// Ключ для хранения данных в sessionStorage
|
||||
const STORAGE_KEY = 'department_schedule_blocks';
|
||||
|
||||
export async function initDepartment() {
|
||||
const form = document.getElementById('department-schedule-form');
|
||||
const departmentSelect = document.getElementById('filter-department');
|
||||
const container = document.getElementById('schedule-blocks-container');
|
||||
|
||||
let departments = [];
|
||||
|
||||
// Загрузка кафедр
|
||||
try {
|
||||
departments = await api.get('/api/departments');
|
||||
departmentSelect.innerHTML = '<option value="">Выберите кафедру...</option>' +
|
||||
departments.map(d => `<option value="${d.id}">${escapeHtml(d.departmentName || d.name)}</option>`).join('');
|
||||
} catch (e) {
|
||||
departmentSelect.innerHTML = '<option value="">Ошибка загрузки</option>';
|
||||
}
|
||||
|
||||
// ===== Восстанавливаем ранее загруженные таблицы из sessionStorage =====
|
||||
restoreScheduleBlocks();
|
||||
|
||||
form.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
hideAlert('schedule-form-alert');
|
||||
|
||||
const departmentId = departmentSelect.value;
|
||||
const period = document.getElementById('filter-period').value;
|
||||
const semesterType = document.querySelector('input[name="semesterType"]:checked')?.value;
|
||||
|
||||
if (!departmentId || !period || !semesterType) {
|
||||
showAlert('schedule-form-alert', 'Заполните все поля', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const deptName = departmentSelect.options[departmentSelect.selectedIndex].text;
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({ departmentId, semesterType, period });
|
||||
const data = await api.get(`/api/department/schedule?${params.toString()}`);
|
||||
|
||||
const semesterName = semesterType === 'spring' ? 'весенний' : (semesterType === 'autumn' ? 'осенний' : semesterType);
|
||||
const periodName = period.replace('-', '/');
|
||||
|
||||
renderScheduleBlock(deptName, semesterName, periodName, data, departmentId, semesterType, period);
|
||||
|
||||
// НЕ сбрасываем форму — фильтры остаются заполненными (fix #3)
|
||||
|
||||
} catch (err) {
|
||||
showAlert('schedule-form-alert', err.message || 'Ошибка загрузки данных', 'error');
|
||||
}
|
||||
});
|
||||
|
||||
// ===== Уникальный ключ для таблицы по параметрам =====
|
||||
function blockKey(departmentId, semesterType, period) {
|
||||
return `${departmentId}_${semesterType}_${period}`;
|
||||
}
|
||||
|
||||
// ===== Рендер блока таблицы (с дедупликацией — fix #6) =====
|
||||
function renderScheduleBlock(deptName, semester, period, schedule, departmentId, semesterType, rawPeriod) {
|
||||
const key = blockKey(departmentId, semesterType, rawPeriod);
|
||||
|
||||
// Удаляем ранее загруженный блок с тем же ключом
|
||||
const existing = container.querySelector(`[data-block-key="${key}"]`);
|
||||
if (existing) existing.remove();
|
||||
|
||||
const details = document.createElement('details');
|
||||
details.className = 'table-item';
|
||||
details.open = true;
|
||||
details.setAttribute('data-block-key', key);
|
||||
details.innerHTML = `
|
||||
<summary>
|
||||
<div class="chev" aria-hidden="true">
|
||||
<svg viewBox="0 0 20 20" class="chev-icon" focusable="false" aria-hidden="true">
|
||||
<path d="M5.5 7.5L10 12l4.5-4.5" fill="none" stroke="currentColor" stroke-width="2"
|
||||
stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="title title-multiline">
|
||||
<span class="title-main">Данные к составлению расписания</span>
|
||||
<span class="title-sub">Кафедра: <b>${escapeHtml(deptName)}</b></span>
|
||||
<span class="title-sub">Семестр: <b>${escapeHtml(semester)}</b></span>
|
||||
<span class="title-sub">Уч. год: <b>${escapeHtml(period)}</b></span>
|
||||
</div>
|
||||
<div class="meta">${Array.isArray(schedule) ? schedule.length : 0} записей</div>
|
||||
</summary>
|
||||
<div class="content">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Специальность</th>
|
||||
<th>Курс/семестр</th>
|
||||
<th>Группа</th>
|
||||
<th>Дисциплина</th>
|
||||
<th>Вид занятий</th>
|
||||
<th>Часов в неделю</th>
|
||||
<th>Деление на подгруппы</th>
|
||||
<th>Преподаватель</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${renderRows(schedule)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
|
||||
container.prepend(details);
|
||||
|
||||
// Сохраняем в sessionStorage
|
||||
saveScheduleBlock(key, { deptName, semester, period, schedule, departmentId, semesterType, rawPeriod });
|
||||
}
|
||||
|
||||
function renderRows(schedule) {
|
||||
if (!Array.isArray(schedule) || schedule.length === 0) {
|
||||
return '<tr><td colspan="8" class="loading-row">Нет данных</td></tr>';
|
||||
}
|
||||
return schedule.map(r => `
|
||||
<tr>
|
||||
<td>${escapeHtml(r.specialityCode || '-')}</td>
|
||||
<td>${(() => {
|
||||
const course = r.groupCourse || '-';
|
||||
const semester = r.semester || '-';
|
||||
if (course === '-' && semester === '-') return '-';
|
||||
return `${course} | ${semester}`;
|
||||
})()}</td>
|
||||
<td>${escapeHtml(r.groupName || '-')}</td>
|
||||
<td>${escapeHtml(r.subjectName || '-')}</td>
|
||||
<td>${escapeHtml(r.lessonType || '-')}</td>
|
||||
<td>${escapeHtml(r.numberOfHours || '-')}</td>
|
||||
<td>${r.division === true ? '✓' : ''}</td>
|
||||
<td>${(() => {
|
||||
const jobTitle = r.teacherJobTitle || '-';
|
||||
const teacherName = r.teacherName || '-';
|
||||
if (jobTitle === '-' && teacherName === '-') return '-';
|
||||
return `${jobTitle}, ${teacherName}`;
|
||||
})()}</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
// ===== Persistence: sessionStorage (fix #4) =====
|
||||
function saveScheduleBlock(key, blockData) {
|
||||
try {
|
||||
const stored = JSON.parse(sessionStorage.getItem(STORAGE_KEY) || '{}');
|
||||
stored[key] = blockData;
|
||||
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(stored));
|
||||
} catch (e) {
|
||||
console.warn('Ошибка сохранения в sessionStorage:', e);
|
||||
}
|
||||
}
|
||||
|
||||
function restoreScheduleBlocks() {
|
||||
try {
|
||||
const stored = JSON.parse(sessionStorage.getItem(STORAGE_KEY) || '{}');
|
||||
const keys = Object.keys(stored);
|
||||
if (keys.length === 0) return;
|
||||
|
||||
keys.forEach(key => {
|
||||
const b = stored[key];
|
||||
renderScheduleBlock(b.deptName, b.semester, b.period, b.schedule, b.departmentId, b.semesterType, b.rawPeriod);
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('Ошибка восстановления из sessionStorage:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================
|
||||
// ЛОГИКА ДЛЯ ФУНКЦИОНАЛА "СОЗДАТЬ ЗАПИСЬ (К/Ф)"
|
||||
// Два модальных окна поверх всего контента в одном оверлее
|
||||
// =========================================================
|
||||
const btnCreateSchedule = document.getElementById('btn-create-schedule');
|
||||
const csOverlay = document.getElementById('cs-overlay');
|
||||
|
||||
const modalCreateSchedule = document.getElementById('modal-create-schedule');
|
||||
const modalCreateScheduleClose = document.getElementById('modal-create-schedule-close');
|
||||
const formCreateSchedule = document.getElementById('create-schedule-form');
|
||||
|
||||
const modalViewSchedules = document.getElementById('modal-view-schedules');
|
||||
const btnSaveSchedules = document.getElementById('btn-save-schedules');
|
||||
const preparedSchedulesTbody = document.getElementById('prepared-schedules-tbody');
|
||||
|
||||
const csGroupSelect = document.getElementById('cs-group');
|
||||
const csSubjectSelect = document.getElementById('cs-subject');
|
||||
const csTeacherSelect = document.getElementById('cs-teacher');
|
||||
const csDepartmentIdInput = document.getElementById('cs-department-id');
|
||||
|
||||
let preparedSchedules = [];
|
||||
let csGroups = [];
|
||||
let csSubjects = [];
|
||||
let csTeachers = [];
|
||||
|
||||
const SEMESTER_LABELS = { autumn: 'Осенний', spring: 'Весенний' };
|
||||
const LESSON_TYPE_LABELS = { 1: 'Лекция', 2: 'Практическая работа', 3: 'Лабораторная работа' };
|
||||
|
||||
const localDepartmentId = localStorage.getItem('departmentId');
|
||||
|
||||
// ===== Загрузка справочников =====
|
||||
async function loadDictionariesForSchedule() {
|
||||
try {
|
||||
csGroups = await api.get('/api/groups');
|
||||
csGroupSelect.innerHTML = '<option value="">Выберите группу</option>' +
|
||||
csGroups.map(g => `<option value="${g.id}">${escapeHtml(g.name)}</option>`).join('');
|
||||
|
||||
csSubjects = await api.get('/api/subjects');
|
||||
csSubjectSelect.innerHTML = '<option value="">Выберите дисциплину</option>' +
|
||||
csSubjects.map(s => `<option value="${s.id}">${escapeHtml(s.name)}</option>`).join('');
|
||||
|
||||
// Загрузка преподавателей: сначала по кафедре, при ошибке — все преподаватели
|
||||
csTeachers = [];
|
||||
if (localDepartmentId) {
|
||||
try {
|
||||
csTeachers = await api.get(`/api/users/teachers/${localDepartmentId}`);
|
||||
} catch (e) {
|
||||
console.warn('Не удалось загрузить преподавателей для кафедры, загружаем всех:', e);
|
||||
}
|
||||
}
|
||||
// Фолбэк: загружаем всех преподавателей
|
||||
if (!Array.isArray(csTeachers) || csTeachers.length === 0) {
|
||||
try {
|
||||
csTeachers = await api.get('/api/users/teachers');
|
||||
} catch (e2) {
|
||||
console.error('Ошибка загрузки всех преподавателей:', e2);
|
||||
}
|
||||
}
|
||||
if (Array.isArray(csTeachers) && csTeachers.length > 0) {
|
||||
csTeacherSelect.innerHTML = '<option value="">Выберите преподавателя</option>' +
|
||||
csTeachers.map(t => `<option value="${t.id}">${escapeHtml(t.fullName || t.username)}</option>`).join('');
|
||||
} else {
|
||||
csTeacherSelect.innerHTML = '<option value="">Нет преподавателей</option>';
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Ошибка загрузки справочников:', e);
|
||||
}
|
||||
}
|
||||
|
||||
loadDictionariesForSchedule();
|
||||
|
||||
// ===== Открытие / Закрытие оверлея =====
|
||||
function openOverlay() {
|
||||
csOverlay.classList.add('open');
|
||||
document.body.style.overflow = 'hidden';
|
||||
}
|
||||
|
||||
function closeOverlay() {
|
||||
csOverlay.classList.remove('open');
|
||||
document.body.style.overflow = '';
|
||||
hideAlert('create-schedule-alert');
|
||||
hideAlert('save-schedules-alert');
|
||||
}
|
||||
|
||||
function updateTableVisibility() {
|
||||
modalViewSchedules.style.display = preparedSchedules.length > 0 ? '' : 'none';
|
||||
}
|
||||
|
||||
// ===== Кнопка «Создать запись» =====
|
||||
btnCreateSchedule.addEventListener('click', () => {
|
||||
if (localDepartmentId) {
|
||||
csDepartmentIdInput.value = localDepartmentId;
|
||||
} else {
|
||||
showAlert('schedule-form-alert', 'Требуется перезайти (отсутствует ID кафедры)', 'error');
|
||||
return;
|
||||
}
|
||||
openOverlay();
|
||||
});
|
||||
|
||||
// ===== Закрытие =====
|
||||
modalCreateScheduleClose.addEventListener('click', closeOverlay);
|
||||
|
||||
csOverlay.addEventListener('click', (e) => {
|
||||
if (e.target === csOverlay || e.target.classList.contains('cs-overlay-scroll')) {
|
||||
closeOverlay();
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape' && csOverlay.classList.contains('open')) {
|
||||
closeOverlay();
|
||||
}
|
||||
});
|
||||
|
||||
// ===== Рендер таблицы подготовленных записей =====
|
||||
function renderPreparedSchedules() {
|
||||
if (preparedSchedules.length === 0) {
|
||||
preparedSchedulesTbody.innerHTML = '<tr><td colspan="9" class="loading-row">Нет записей</td></tr>';
|
||||
return;
|
||||
}
|
||||
preparedSchedulesTbody.innerHTML = preparedSchedules.map((s, index) => {
|
||||
const groupName = csGroups.find(g => g.id == s.groupId)?.name || s.groupId;
|
||||
const subjectName = csSubjects.find(sub => sub.id == s.subjectsId)?.name || s.subjectsId;
|
||||
const teacherName = csTeachers.find(t => t.id == s.teacherId)?.fullName
|
||||
|| csTeachers.find(t => t.id == s.teacherId)?.username || s.teacherId;
|
||||
const lessonTypeName = LESSON_TYPE_LABELS[s.lessonTypeId] || 'Неизвестно';
|
||||
const semLabel = SEMESTER_LABELS[s.semesterType] || s.semesterType;
|
||||
const periodDisplay = s.period.replace('-', '/');
|
||||
const divText = s.isDivision ? '✓' : '';
|
||||
const hasError = !!s._errorMsg;
|
||||
const rowStyle = hasError ? ' style="background: rgba(239, 68, 68, 0.08);"' : '';
|
||||
let row = `
|
||||
<tr${rowStyle}>
|
||||
<td>${escapeHtml(periodDisplay)}</td>
|
||||
<td>${escapeHtml(semLabel)}</td>
|
||||
<td>${escapeHtml(String(groupName))}</td>
|
||||
<td>${escapeHtml(String(subjectName))}</td>
|
||||
<td>${escapeHtml(lessonTypeName)}</td>
|
||||
<td>${s.numberOfHours}</td>
|
||||
<td>${divText}</td>
|
||||
<td>${escapeHtml(String(teacherName))}</td>
|
||||
<td><button type="button" class="btn-delete" data-index="${index}">Удалить</button></td>
|
||||
</tr>`;
|
||||
if (hasError) {
|
||||
row += `<tr style="background: rgba(239, 68, 68, 0.05);">
|
||||
<td colspan="9" style="color: var(--error); font-size: 0.85rem; padding: 0.4rem 0.85rem;">
|
||||
⚠ ${escapeHtml(s._errorMsg)}
|
||||
</td>
|
||||
</tr>`;
|
||||
}
|
||||
return row;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
// ===== Удаление строки из таблицы =====
|
||||
preparedSchedulesTbody.addEventListener('click', (e) => {
|
||||
if (e.target.classList.contains('btn-delete')) {
|
||||
const idx = parseInt(e.target.getAttribute('data-index'), 10);
|
||||
preparedSchedules.splice(idx, 1);
|
||||
renderPreparedSchedules();
|
||||
updateTableVisibility();
|
||||
}
|
||||
});
|
||||
|
||||
// ===== Очистка полей формы (частичная) =====
|
||||
function clearFormFields() {
|
||||
document.getElementById('cs-hours').value = '';
|
||||
document.getElementById('cs-division').checked = false;
|
||||
}
|
||||
|
||||
// ===== Добавление записи в список =====
|
||||
formCreateSchedule.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
hideAlert('create-schedule-alert');
|
||||
|
||||
const depId = csDepartmentIdInput.value;
|
||||
const period = document.getElementById('cs-period').value;
|
||||
const semesterType = document.querySelector('input[name="csSemesterType"]:checked')?.value;
|
||||
const groupId = csGroupSelect.value;
|
||||
const subjectId = csSubjectSelect.value;
|
||||
const lessonTypeId = document.getElementById('cs-lesson-type').value;
|
||||
const hours = document.getElementById('cs-hours').value;
|
||||
const isDivision = document.getElementById('cs-division').checked;
|
||||
const teacherId = csTeacherSelect.value;
|
||||
|
||||
if (!period || !semesterType || !groupId || !subjectId || !lessonTypeId || !hours || !teacherId) {
|
||||
showAlert('create-schedule-alert', 'Заполните все обязательные поля', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const newRecord = {
|
||||
departmentId: Number(depId),
|
||||
groupId: Number(groupId),
|
||||
subjectsId: Number(subjectId),
|
||||
lessonTypeId: Number(lessonTypeId),
|
||||
numberOfHours: Number(hours),
|
||||
isDivision: isDivision,
|
||||
teacherId: Number(teacherId),
|
||||
semesterType: semesterType,
|
||||
period: period
|
||||
};
|
||||
|
||||
// Проверка на дубликат
|
||||
const isDuplicate = preparedSchedules.some(s =>
|
||||
s.period === newRecord.period &&
|
||||
s.semesterType === newRecord.semesterType &&
|
||||
s.groupId === newRecord.groupId &&
|
||||
s.subjectsId === newRecord.subjectsId &&
|
||||
s.lessonTypeId === newRecord.lessonTypeId &&
|
||||
s.numberOfHours === newRecord.numberOfHours &&
|
||||
s.isDivision === newRecord.isDivision &&
|
||||
s.teacherId === newRecord.teacherId
|
||||
);
|
||||
|
||||
if (isDuplicate) {
|
||||
showAlert('create-schedule-alert', 'Такая запись уже есть в списке', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
preparedSchedules.push(newRecord);
|
||||
|
||||
clearFormFields();
|
||||
|
||||
showAlert('create-schedule-alert', 'Запись добавлена ✓', 'success');
|
||||
setTimeout(() => hideAlert('create-schedule-alert'), 4000); // fix #1: 4 секунды
|
||||
|
||||
renderPreparedSchedules();
|
||||
updateTableVisibility();
|
||||
});
|
||||
|
||||
// ===== Сохранение в БД =====
|
||||
btnSaveSchedules.addEventListener('click', async () => {
|
||||
if (preparedSchedules.length === 0) {
|
||||
showAlert('save-schedules-alert', 'Нет записей для сохранения', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
btnSaveSchedules.disabled = true;
|
||||
btnSaveSchedules.textContent = 'Сохранение...';
|
||||
hideAlert('save-schedules-alert');
|
||||
|
||||
let errors = 0;
|
||||
let saved = 0;
|
||||
const failedRecords = [];
|
||||
|
||||
for (const record of preparedSchedules) {
|
||||
try {
|
||||
await api.post('/api/department/schedule/create', record);
|
||||
saved++;
|
||||
} catch (err) {
|
||||
console.error('Ошибка сохранения записи:', err);
|
||||
errors++;
|
||||
const isDuplicate = err.status === 409 ||
|
||||
(err.message && err.message.toLowerCase().includes('уже существует'));
|
||||
failedRecords.push({
|
||||
...record,
|
||||
_errorMsg: isDuplicate
|
||||
? 'Такая запись уже есть в базе данных'
|
||||
: (err.message || 'Ошибка сохранения')
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
btnSaveSchedules.disabled = false;
|
||||
btnSaveSchedules.textContent = 'Сохранить в БД';
|
||||
|
||||
if (errors === 0) {
|
||||
showAlert('save-schedules-alert', `Все записи (${saved}) успешно сохранены!`, 'success');
|
||||
preparedSchedules = [];
|
||||
renderPreparedSchedules();
|
||||
updateTableVisibility();
|
||||
setTimeout(closeOverlay, 2000);
|
||||
} else {
|
||||
preparedSchedules = failedRecords;
|
||||
renderPreparedSchedules();
|
||||
if (saved > 0) {
|
||||
showAlert('save-schedules-alert',
|
||||
`Сохранено: ${saved}. Ошибок: ${errors}. Проблемные записи отмечены в таблице.`, 'error');
|
||||
} else {
|
||||
showAlert('save-schedules-alert',
|
||||
`Не удалось сохранить. Ошибок: ${errors}. Проблемные записи отмечены в таблице.`, 'error');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
@@ -7,6 +7,12 @@ export async function initDepartmentsData() {
|
||||
|
||||
const createDeptForm = document.getElementById('create-department-form');
|
||||
const createSpecForm = document.getElementById('create-specialty-form');
|
||||
const editDeptForm = document.getElementById('edit-department-form');
|
||||
const editSpecForm = document.getElementById('edit-specialty-form');
|
||||
const editDeptModal = document.getElementById('modal-edit-department');
|
||||
const editSpecModal = document.getElementById('modal-edit-specialty');
|
||||
const editDeptClose = document.getElementById('modal-edit-department-close');
|
||||
const editSpecClose = document.getElementById('modal-edit-specialty-close');
|
||||
|
||||
let departments = [];
|
||||
let specialties = [];
|
||||
@@ -17,7 +23,7 @@ export async function initDepartmentsData() {
|
||||
departments = await api.get('/api/departments');
|
||||
renderDepartments();
|
||||
} catch (e) {
|
||||
deptTbody.innerHTML = '<tr><td colspan="3" class="loading-row">-</td></tr>';
|
||||
deptTbody.innerHTML = '<tr><td colspan="4" class="loading-row">-</td></tr>';
|
||||
}
|
||||
|
||||
// Load Specialties
|
||||
@@ -25,13 +31,13 @@ export async function initDepartmentsData() {
|
||||
specialties = await api.get('/api/specialties');
|
||||
renderSpecialties();
|
||||
} catch (e) {
|
||||
specTbody.innerHTML = '<tr><td colspan="3" class="loading-row">-</td></tr>';
|
||||
specTbody.innerHTML = '<tr><td colspan="4" class="loading-row">-</td></tr>';
|
||||
}
|
||||
}
|
||||
|
||||
function renderDepartments() {
|
||||
if (!departments || !departments.length) {
|
||||
deptTbody.innerHTML = '<tr><td colspan="3" class="loading-row">-</td></tr>';
|
||||
deptTbody.innerHTML = '<tr><td colspan="4" class="loading-row">-</td></tr>';
|
||||
return;
|
||||
}
|
||||
deptTbody.innerHTML = departments.map(d => `
|
||||
@@ -39,13 +45,17 @@ export async function initDepartmentsData() {
|
||||
<td>${d.id}</td>
|
||||
<td>${escapeHtml(d.departmentName || d.name)}</td>
|
||||
<td>${escapeHtml(String(d.departmentCode || d.code))}</td>
|
||||
<td>
|
||||
<button class="btn-edit-classroom btn-edit-department" data-id="${d.id}">Изменить</button>
|
||||
<button class="btn-delete btn-delete-department" data-id="${d.id}">Удалить</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
function renderSpecialties() {
|
||||
if (!specialties || !specialties.length) {
|
||||
specTbody.innerHTML = '<tr><td colspan="3" class="loading-row">-</td></tr>';
|
||||
specTbody.innerHTML = '<tr><td colspan="4" class="loading-row">-</td></tr>';
|
||||
return;
|
||||
}
|
||||
specTbody.innerHTML = specialties.map(s => `
|
||||
@@ -53,6 +63,10 @@ export async function initDepartmentsData() {
|
||||
<td>${s.id}</td>
|
||||
<td>${escapeHtml(s.specialityName || s.name)}</td>
|
||||
<td>${escapeHtml(s.specialityCode || s.specialtyCode || s.specialty_code)}</td>
|
||||
<td>
|
||||
<button class="btn-edit-classroom btn-edit-specialty" data-id="${s.id}">Изменить</button>
|
||||
<button class="btn-delete btn-delete-specialty" data-id="${s.id}">Удалить</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
}
|
||||
@@ -78,6 +92,34 @@ export async function initDepartmentsData() {
|
||||
}
|
||||
});
|
||||
|
||||
deptTbody.addEventListener('click', async (e) => {
|
||||
const editBtn = e.target.closest('.btn-edit-department');
|
||||
const deleteBtn = e.target.closest('.btn-delete-department');
|
||||
|
||||
if (editBtn) {
|
||||
const department = departments.find(item => item.id == editBtn.dataset.id);
|
||||
if (!department) return;
|
||||
|
||||
document.getElementById('edit-dept-id').value = department.id;
|
||||
document.getElementById('edit-dept-name').value = department.departmentName || department.name || '';
|
||||
document.getElementById('edit-dept-code').value = department.departmentCode || department.code || '';
|
||||
hideAlert('edit-dept-alert');
|
||||
editDeptModal.classList.add('open');
|
||||
return;
|
||||
}
|
||||
|
||||
if (deleteBtn) {
|
||||
if (!confirm('Удалить кафедру?')) return;
|
||||
try {
|
||||
await api.delete('/api/departments/' + deleteBtn.dataset.id);
|
||||
showAlert('create-dept-alert', 'Кафедра удалена', 'success');
|
||||
await loadData();
|
||||
} catch (error) {
|
||||
showAlert('create-dept-alert', error.message || 'Ошибка удаления кафедры', 'error');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
createSpecForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
hideAlert('create-spec-alert');
|
||||
@@ -99,5 +141,86 @@ export async function initDepartmentsData() {
|
||||
}
|
||||
});
|
||||
|
||||
loadData();
|
||||
specTbody.addEventListener('click', async (e) => {
|
||||
const editBtn = e.target.closest('.btn-edit-specialty');
|
||||
const deleteBtn = e.target.closest('.btn-delete-specialty');
|
||||
|
||||
if (editBtn) {
|
||||
const speciality = specialties.find(item => item.id == editBtn.dataset.id);
|
||||
if (!speciality) return;
|
||||
|
||||
document.getElementById('edit-spec-id').value = speciality.id;
|
||||
document.getElementById('edit-spec-name').value = speciality.specialityName || speciality.name || '';
|
||||
document.getElementById('edit-spec-code').value = speciality.specialityCode || speciality.specialtyCode || speciality.specialty_code || '';
|
||||
hideAlert('edit-spec-alert');
|
||||
editSpecModal.classList.add('open');
|
||||
return;
|
||||
}
|
||||
|
||||
if (deleteBtn) {
|
||||
if (!confirm('Удалить специальность?')) return;
|
||||
try {
|
||||
await api.delete('/api/specialties/' + deleteBtn.dataset.id);
|
||||
showAlert('create-spec-alert', 'Специальность удалена', 'success');
|
||||
await loadData();
|
||||
} catch (error) {
|
||||
showAlert('create-spec-alert', error.message || 'Ошибка удаления специальности', 'error');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
editDeptForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
hideAlert('edit-dept-alert');
|
||||
const id = document.getElementById('edit-dept-id').value;
|
||||
const name = document.getElementById('edit-dept-name').value.trim();
|
||||
const code = document.getElementById('edit-dept-code').value.trim();
|
||||
|
||||
if (!name || !code) {
|
||||
showAlert('edit-dept-alert', 'Заполните все поля', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await api.put('/api/departments/' + id, { departmentName: name, departmentCode: Number(code) });
|
||||
editDeptModal.classList.remove('open');
|
||||
showAlert('create-dept-alert', `Кафедра "${name}" обновлена`, 'success');
|
||||
await loadData();
|
||||
} catch (error) {
|
||||
showAlert('edit-dept-alert', error.message || 'Ошибка обновления кафедры', 'error');
|
||||
}
|
||||
});
|
||||
|
||||
editSpecForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
hideAlert('edit-spec-alert');
|
||||
const id = document.getElementById('edit-spec-id').value;
|
||||
const name = document.getElementById('edit-spec-name').value.trim();
|
||||
const code = document.getElementById('edit-spec-code').value.trim();
|
||||
|
||||
if (!name || !code) {
|
||||
showAlert('edit-spec-alert', 'Заполните все поля', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await api.put('/api/specialties/' + id, { specialityName: name, specialityCode: code });
|
||||
editSpecModal.classList.remove('open');
|
||||
showAlert('create-spec-alert', `Специальность "${name}" обновлена`, 'success');
|
||||
await loadData();
|
||||
} catch (error) {
|
||||
showAlert('edit-spec-alert', error.message || 'Ошибка обновления специальности', 'error');
|
||||
}
|
||||
});
|
||||
|
||||
editDeptClose.addEventListener('click', () => editDeptModal.classList.remove('open'));
|
||||
editSpecClose.addEventListener('click', () => editSpecModal.classList.remove('open'));
|
||||
editDeptModal.addEventListener('click', (e) => {
|
||||
if (e.target === editDeptModal) editDeptModal.classList.remove('open');
|
||||
});
|
||||
editSpecModal.addEventListener('click', (e) => {
|
||||
if (e.target === editSpecModal) editSpecModal.classList.remove('open');
|
||||
});
|
||||
|
||||
await loadData();
|
||||
}
|
||||
|
||||
@@ -6,15 +6,25 @@ export async function initGroups() {
|
||||
const groupsTbody = document.getElementById('groups-tbody');
|
||||
const createGroupForm = document.getElementById('create-group-form');
|
||||
const newGroupEfSelect = document.getElementById('new-group-ef');
|
||||
const newGroupDepartmentSelect = document.getElementById('new-group-department');
|
||||
const newGroupSpecialitySelect = document.getElementById('new-group-speciality-code');
|
||||
const filterEfSelect = document.getElementById('filter-ef');
|
||||
|
||||
let allGroups = [];
|
||||
let educationForms = [];
|
||||
let departments = [];
|
||||
let specialties = [];
|
||||
|
||||
async function loadInitialData() {
|
||||
try {
|
||||
educationForms = await fetchEducationForms();
|
||||
[educationForms, departments, specialties] = await Promise.all([
|
||||
fetchEducationForms(),
|
||||
api.get('/api/departments'),
|
||||
api.get('/api/specialties')
|
||||
]);
|
||||
populateEfSelects(educationForms);
|
||||
populateDepartmentSelect(departments);
|
||||
populateSpecialitySelect(specialties);
|
||||
await loadGroups();
|
||||
} catch (e) {
|
||||
groupsTbody.innerHTML = '<tr><td colspan="8" class="loading-row">Ошибка загрузки данных</td></tr>';
|
||||
@@ -49,6 +59,7 @@ export async function initGroups() {
|
||||
if (currentVal && forms.find(f => f.id == currentVal)) {
|
||||
newGroupEfSelect.value = currentVal;
|
||||
}
|
||||
syncSelects(newGroupEfSelect);
|
||||
|
||||
// Filter select
|
||||
const currentFilter = filterEfSelect.value;
|
||||
@@ -57,6 +68,59 @@ export async function initGroups() {
|
||||
`<option value="${ef.id}">${escapeHtml(ef.name)}</option>`
|
||||
).join('');
|
||||
if (currentFilter) filterEfSelect.value = currentFilter;
|
||||
syncSelects(filterEfSelect);
|
||||
}
|
||||
|
||||
function populateDepartmentSelect(items) {
|
||||
const currentVal = newGroupDepartmentSelect.value;
|
||||
if (!items || !items.length) {
|
||||
newGroupDepartmentSelect.innerHTML = '<option value="">Нет кафедр</option>';
|
||||
return;
|
||||
}
|
||||
|
||||
newGroupDepartmentSelect.innerHTML = '<option value="">Выберите кафедру</option>' +
|
||||
items.map(department => {
|
||||
const name = department.departmentName || department.name || 'Без названия';
|
||||
const code = department.departmentCode || department.code || department.id;
|
||||
return `<option value="${department.id}">${escapeHtml(name)} (${escapeHtml(String(code))})</option>`;
|
||||
}).join('');
|
||||
if (currentVal && items.find(department => department.id == currentVal)) {
|
||||
newGroupDepartmentSelect.value = currentVal;
|
||||
}
|
||||
syncSelects(newGroupDepartmentSelect);
|
||||
}
|
||||
|
||||
function populateSpecialitySelect(items) {
|
||||
const currentVal = newGroupSpecialitySelect.value;
|
||||
if (!items || !items.length) {
|
||||
newGroupSpecialitySelect.innerHTML = '<option value="">Нет специальностей</option>';
|
||||
return;
|
||||
}
|
||||
|
||||
newGroupSpecialitySelect.innerHTML = '<option value="">Выберите специальность</option>' +
|
||||
items.map(speciality => {
|
||||
const name = speciality.specialityName || speciality.name || 'Без названия';
|
||||
const code = speciality.specialityCode || speciality.specialtyCode || speciality.specialty_code || speciality.id;
|
||||
return `<option value="${speciality.id}">${escapeHtml(code)} — ${escapeHtml(name)}</option>`;
|
||||
}).join('');
|
||||
if (currentVal && items.find(speciality => speciality.id == currentVal)) {
|
||||
newGroupSpecialitySelect.value = currentVal;
|
||||
}
|
||||
syncSelects(newGroupSpecialitySelect);
|
||||
}
|
||||
|
||||
function departmentLabel(departmentId) {
|
||||
const department = departments.find(item => item.id == departmentId);
|
||||
if (!department) return departmentId || '-';
|
||||
return department.departmentName || department.name || departmentId;
|
||||
}
|
||||
|
||||
function specialityLabel(specialityId) {
|
||||
const speciality = specialties.find(item => item.id == specialityId);
|
||||
if (!speciality) return specialityId || '-';
|
||||
const code = speciality.specialityCode || speciality.specialtyCode || speciality.specialty_code || speciality.id;
|
||||
const name = speciality.specialityName || speciality.name || '';
|
||||
return name ? `${code} — ${name}` : code;
|
||||
}
|
||||
|
||||
function renderGroups(groups) {
|
||||
@@ -70,9 +134,9 @@ export async function initGroups() {
|
||||
<td>${escapeHtml(g.name)}</td>
|
||||
<td>${escapeHtml(g.groupSize)}</td>
|
||||
<td><span class="badge badge-ef">${escapeHtml(g.educationFormName)}</span></td>
|
||||
<td>${g.departmentId || '-'}</td>
|
||||
<td>${escapeHtml(departmentLabel(g.departmentId))}</td>
|
||||
<td>${g.course || '-'}</td>
|
||||
<td>${escapeHtml(g.specialityCode || '-')}</td>
|
||||
<td>${escapeHtml(specialityLabel(g.specialityCode))}</td>
|
||||
<td><button class="btn-delete" data-id="${g.id}">Удалить</button></td>
|
||||
</tr>`).join('');
|
||||
}
|
||||
@@ -83,16 +147,16 @@ export async function initGroups() {
|
||||
const name = document.getElementById('new-group-name').value.trim();
|
||||
const groupSize = document.getElementById('new-group-size').value;
|
||||
const educationFormId = newGroupEfSelect.value;
|
||||
const departmentId = document.getElementById('new-group-department').value;
|
||||
const course = document.getElementById('new-group-course').value;
|
||||
const specialityCode = document.getElementById('new-group-speciality-code').value.trim();
|
||||
const departmentId = newGroupDepartmentSelect.value;
|
||||
const yearStartStudy = document.getElementById('new-group-yearStartStudy').value;
|
||||
const specialityCode = newGroupSpecialitySelect.value;
|
||||
|
||||
if (!name) { showAlert('create-group-alert', 'Введите название группы', 'error'); return; }
|
||||
if (!groupSize) { showAlert('create-group-alert', 'Введите размер группы', 'error'); return; }
|
||||
if (!educationFormId) { showAlert('create-group-alert', 'Выберите форму обучения', 'error'); return; }
|
||||
if (!departmentId) { showAlert('create-group-alert', 'Введите ID кафедры', 'error'); return; }
|
||||
if (!course) { showAlert('create-group-alert', 'Введите курс', 'error'); return; }
|
||||
if (!specialityCode) { showAlert('create-group-alert', 'Введите код специальности', 'error'); return; }
|
||||
if (!departmentId) { showAlert('create-group-alert', 'Выберите кафедру', 'error'); return; }
|
||||
if (!yearStartStudy) { showAlert('create-group-alert', 'Введите год начала обучения', 'error'); return; }
|
||||
if (!specialityCode) { showAlert('create-group-alert', 'Выберите специальность', 'error'); return; }
|
||||
|
||||
try {
|
||||
const data = await api.post('/api/groups', {
|
||||
@@ -100,11 +164,12 @@ export async function initGroups() {
|
||||
groupSize: Number(groupSize),
|
||||
educationFormId: Number(educationFormId),
|
||||
departmentId: Number(departmentId),
|
||||
course: Number(course),
|
||||
specialityCode: specialityCode
|
||||
yearStartStudy: Number(yearStartStudy),
|
||||
specialityCode: Number(specialityCode)
|
||||
});
|
||||
showAlert('create-group-alert', `Группа "${escapeHtml(data.name || name)}" создана`, 'success');
|
||||
createGroupForm.reset();
|
||||
syncSelects(newGroupEfSelect, newGroupDepartmentSelect, newGroupSpecialitySelect);
|
||||
loadGroups();
|
||||
} catch (e) {
|
||||
showAlert('create-group-alert', e.message || 'Ошибка создания', 'error');
|
||||
@@ -123,5 +188,11 @@ export async function initGroups() {
|
||||
}
|
||||
});
|
||||
|
||||
loadInitialData();
|
||||
await loadInitialData();
|
||||
|
||||
function syncSelects(...selects) {
|
||||
selects.filter(Boolean).forEach(select => {
|
||||
select.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
1482
frontend/admin/js/views/schedule.js
Executable file → Normal file
1482
frontend/admin/js/views/schedule.js
Executable file → Normal file
File diff suppressed because it is too large
Load Diff
431
frontend/admin/js/views/users.js
Executable file → Normal file
431
frontend/admin/js/views/users.js
Executable file → Normal file
@@ -8,173 +8,20 @@ export async function initUsers() {
|
||||
const usersTbody = document.getElementById('users-tbody');
|
||||
const createForm = document.getElementById('create-form');
|
||||
|
||||
// ===== Оверлей (cs-overlay) =====
|
||||
const usersOverlay = document.getElementById('users-overlay');
|
||||
|
||||
// ===== 1-е модальное окно: Добавить занятие =====
|
||||
const modalAddLesson = document.getElementById('modal-add-lesson');
|
||||
const modalAddLessonClose = document.getElementById('modal-add-lesson-close');
|
||||
const addLessonForm = document.getElementById('add-lesson-form');
|
||||
|
||||
const lessonGroupSelect = document.getElementById('lesson-group');
|
||||
const lessonDisciplineSelect = document.getElementById('lesson-discipline');
|
||||
const lessonClassroomSelect = document.getElementById('lesson-classroom');
|
||||
const lessonTypeSelect = document.getElementById('lesson-type');
|
||||
const lessonOnlineFormat = document.getElementById('format-online');
|
||||
const lessonOfflineFormat = document.getElementById('format-offline');
|
||||
const lessonUserId = document.getElementById('lesson-user-id');
|
||||
const lessonDaySelect = document.getElementById('lesson-day');
|
||||
const weekUpper = document.getElementById('week-upper');
|
||||
const weekLower = document.getElementById('week-lower');
|
||||
const lessonTimeSelect = document.getElementById('lesson-time');
|
||||
|
||||
// ===== 2-е модальное окно: Просмотр занятий =====
|
||||
const modalViewLessons = document.getElementById('modal-view-lessons');
|
||||
const lessonsContainer = document.getElementById('lessons-container');
|
||||
const modalTeacherName = document.getElementById('modal-teacher-name');
|
||||
|
||||
let currentLessonsTeacherId = null;
|
||||
let currentLessonsTeacherName = '';
|
||||
// ===== Данные =====
|
||||
let groups = [];
|
||||
let subjects = [];
|
||||
let classrooms = [];
|
||||
|
||||
const weekdaysTimes = [
|
||||
"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:00"
|
||||
];
|
||||
|
||||
const saturdayTimes = [
|
||||
"8:20-9:50",
|
||||
"10:00-11:30",
|
||||
"11:40-13:10",
|
||||
"13:20-14:50"
|
||||
];
|
||||
|
||||
// =========================================================
|
||||
// Загрузка справочников
|
||||
// =========================================================
|
||||
async function loadGroups() {
|
||||
try {
|
||||
groups = await api.get('/api/groups');
|
||||
renderGroupOptions();
|
||||
} catch (e) {
|
||||
console.error('Ошибка загрузки групп:', e);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadSubjects() {
|
||||
try {
|
||||
subjects = await api.get('/api/subjects');
|
||||
renderSubjectOptions();
|
||||
} catch (e) {
|
||||
console.error('Ошибка загрузки дисциплин:', e);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadClassrooms() {
|
||||
try {
|
||||
classrooms = await api.get('/api/classrooms');
|
||||
renderClassroomsOptions();
|
||||
} catch (e) {
|
||||
console.error('Ошибка загрузки аудиторий:', e);
|
||||
}
|
||||
}
|
||||
|
||||
function renderGroupOptions() {
|
||||
if (!groups || groups.length === 0) {
|
||||
lessonGroupSelect.innerHTML = '<option value="">Нет доступных групп</option>';
|
||||
return;
|
||||
}
|
||||
|
||||
lessonGroupSelect.innerHTML =
|
||||
'<option value="">Выберите группу</option>' +
|
||||
groups.map(g => {
|
||||
let optionText = escapeHtml(g.name);
|
||||
if (g.groupSize) optionText += ` (численность: ${g.groupSize} чел.)`;
|
||||
return `<option value="${g.id}">${optionText}</option>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderSubjectOptions() {
|
||||
lessonDisciplineSelect.innerHTML =
|
||||
'<option value="">Выберите дисциплину</option>' +
|
||||
subjects.map(s => `<option value="${s.id}">${escapeHtml(s.name)}</option>`).join('');
|
||||
}
|
||||
|
||||
function renderClassroomsOptions() {
|
||||
if (!classrooms || classrooms.length === 0) {
|
||||
lessonClassroomSelect.innerHTML = '<option value="">Нет доступных аудиторий</option>';
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedGroupId = lessonGroupSelect.value;
|
||||
const selectedGroup = groups?.find(g => g.id == selectedGroupId);
|
||||
const groupSize = selectedGroup?.groupSize || 0;
|
||||
|
||||
lessonClassroomSelect.innerHTML =
|
||||
'<option value="">Выберите аудиторию</option>' +
|
||||
classrooms.map(c => {
|
||||
let optionText = escapeHtml(c.name);
|
||||
|
||||
if (c.capacity) optionText += ` (вместимость: ${c.capacity} чел.)`;
|
||||
|
||||
if (c.isAvailable === false) {
|
||||
optionText += ` ❌ Занята`;
|
||||
} else if (selectedGroupId && groupSize > 0 && c.capacity && groupSize > c.capacity) {
|
||||
optionText += ` ⚠️ Недостаточно места`;
|
||||
}
|
||||
|
||||
return `<option value="${c.id}">${optionText}</option>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
lessonGroupSelect.addEventListener('change', function () {
|
||||
renderClassroomsOptions();
|
||||
requestAnimationFrame(() => syncAddLessonHeight());
|
||||
});
|
||||
|
||||
function updateTimeOptions(dayValue) {
|
||||
let times = [];
|
||||
if (dayValue === "Суббота") {
|
||||
times = saturdayTimes;
|
||||
} else if (dayValue && dayValue !== '') {
|
||||
times = weekdaysTimes;
|
||||
} else {
|
||||
lessonTimeSelect.innerHTML = '<option value="">Сначала выберите день</option>';
|
||||
lessonTimeSelect.disabled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
lessonTimeSelect.innerHTML =
|
||||
'<option value="">Выберите время</option>' +
|
||||
times.map(t => `<option value="${t}">${t}</option>`).join('');
|
||||
lessonTimeSelect.disabled = false;
|
||||
}
|
||||
|
||||
// =========================================================
|
||||
// Пользователи
|
||||
// =========================================================
|
||||
async function loadUsers() {
|
||||
try {
|
||||
const users = await api.get('/api/users');
|
||||
renderUsers(users);
|
||||
} catch (e) {
|
||||
usersTbody.innerHTML =
|
||||
'<tr><td colspan="8" class="loading-row">Ошибка загрузки: ' +
|
||||
'<tr><td colspan="7" class="loading-row">Ошибка загрузки: ' +
|
||||
escapeHtml(e.message) + '</td></tr>';
|
||||
}
|
||||
}
|
||||
|
||||
function renderUsers(users) {
|
||||
if (!users || !users.length) {
|
||||
usersTbody.innerHTML = '<tr><td colspan="8" class="loading-row">Нет пользователей</td></tr>';
|
||||
usersTbody.innerHTML = '<tr><td colspan="7" class="loading-row">Нет пользователей</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -184,148 +31,15 @@ export async function initUsers() {
|
||||
<td>${escapeHtml(u.username)}</td>
|
||||
<td>${escapeHtml(u.fullName || '-')}</td>
|
||||
<td>${escapeHtml(u.jobTitle || '-')}</td>
|
||||
<td>${u.departmentName || '-'}</td>
|
||||
<td>${escapeHtml(u.departmentName || '-')}</td>
|
||||
<td><span class="badge ${ROLE_BADGE[u.role] || ''}">${ROLE_LABELS[u.role] || escapeHtml(u.role)}</span></td>
|
||||
<td>
|
||||
<button class="btn-delete" data-id="${u.id}">Удалить</button>
|
||||
</td>
|
||||
<td>
|
||||
<button class="btn-add-lesson" data-id="${u.id}" data-name="${escapeHtml(u.username)}">Добавить занятие</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
// ===== Открытие / закрытие оверлея =====
|
||||
function openOverlay() {
|
||||
if (usersOverlay) usersOverlay.classList.add('open');
|
||||
}
|
||||
function closeOverlay() {
|
||||
if (usersOverlay) usersOverlay.classList.remove('open');
|
||||
if (modalViewLessons) modalViewLessons.style.display = 'none';
|
||||
resetLessonForm();
|
||||
}
|
||||
|
||||
// =========================================================
|
||||
// 1-я модалка: добавление занятия
|
||||
// =========================================================
|
||||
function resetLessonForm() {
|
||||
addLessonForm.reset();
|
||||
lessonUserId.value = '';
|
||||
|
||||
if (weekUpper) weekUpper.checked = false;
|
||||
if (weekLower) weekLower.checked = false;
|
||||
|
||||
if (lessonOfflineFormat) lessonOfflineFormat.checked = true;
|
||||
if (lessonOnlineFormat) lessonOnlineFormat.checked = false;
|
||||
|
||||
lessonTimeSelect.innerHTML = '<option value="">Сначала выберите день</option>';
|
||||
lessonTimeSelect.disabled = true;
|
||||
|
||||
hideAlert('add-lesson-alert');
|
||||
}
|
||||
|
||||
function openAddLessonModal(userId) {
|
||||
lessonUserId.value = userId;
|
||||
|
||||
lessonDaySelect.value = '';
|
||||
updateTimeOptions('');
|
||||
|
||||
openOverlay();
|
||||
}
|
||||
|
||||
addLessonForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
hideAlert('add-lesson-alert');
|
||||
|
||||
const userId = lessonUserId.value;
|
||||
const groupId = lessonGroupSelect.value;
|
||||
const subjectId = lessonDisciplineSelect.value;
|
||||
const classroomId = lessonClassroomSelect.value;
|
||||
const lessonType = lessonTypeSelect.value;
|
||||
const dayOfWeek = lessonDaySelect.value;
|
||||
const timeSlot = lessonTimeSelect.value;
|
||||
|
||||
const lessonFormat = document.querySelector('input[name="lessonFormat"]:checked')?.value;
|
||||
|
||||
if (!groupId) { showAlert('add-lesson-alert', 'Выберите группу', 'error'); return; }
|
||||
if (!subjectId) { showAlert('add-lesson-alert', 'Выберите дисциплину', 'error'); return; }
|
||||
if (!classroomId) { showAlert('add-lesson-alert', 'Выберите аудиторию', 'error'); return; }
|
||||
if (!dayOfWeek) { showAlert('add-lesson-alert', 'Выберите день недели', 'error'); return; }
|
||||
if (!timeSlot) { showAlert('add-lesson-alert', 'Выберите время', 'error'); return; }
|
||||
|
||||
const weekUpperChecked = weekUpper?.checked || false;
|
||||
const weekLowerChecked = weekLower?.checked || false;
|
||||
|
||||
if (!weekUpperChecked && !weekLowerChecked) {
|
||||
showAlert('add-lesson-alert', 'Не выбран тип недели', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
let weekType = null;
|
||||
if (weekUpperChecked && weekLowerChecked) weekType = 'Обе';
|
||||
else if (weekUpperChecked) weekType = 'Верхняя';
|
||||
else if (weekLowerChecked) weekType = 'Нижняя';
|
||||
|
||||
try {
|
||||
await api.post('/api/users/lessons/create', {
|
||||
teacherId: parseInt(userId),
|
||||
groupId: parseInt(groupId),
|
||||
subjectId: parseInt(subjectId),
|
||||
classroomId: parseInt(classroomId),
|
||||
typeLesson: lessonType,
|
||||
lessonFormat: lessonFormat,
|
||||
day: dayOfWeek,
|
||||
week: weekType,
|
||||
time: timeSlot
|
||||
});
|
||||
|
||||
if (modalViewLessons?.style.display !== 'none' && currentLessonsTeacherId == userId) {
|
||||
await loadTeacherLessons(currentLessonsTeacherId, currentLessonsTeacherName);
|
||||
}
|
||||
|
||||
showAlert('add-lesson-alert', 'Занятие добавлено ✓', 'success');
|
||||
|
||||
lessonGroupSelect.selectedIndex = 0;
|
||||
lessonDisciplineSelect.selectedIndex = 0;
|
||||
lessonClassroomSelect.selectedIndex = 0;
|
||||
lessonTypeSelect.selectedIndex = 0;
|
||||
lessonDaySelect.selectedIndex = 0;
|
||||
lessonTimeSelect.innerHTML = '<option value="">Сначала выберите день</option>';
|
||||
lessonTimeSelect.disabled = true;
|
||||
|
||||
weekUpper.checked = false;
|
||||
weekLower.checked = false;
|
||||
document.querySelector('input[name="lessonFormat"][value="Очно"]').checked = true;
|
||||
|
||||
setTimeout(() => {
|
||||
hideAlert('add-lesson-alert');
|
||||
}, 3000);
|
||||
} catch (err) {
|
||||
showAlert('add-lesson-alert', err.message || 'Ошибка добавления занятия', 'error');
|
||||
}
|
||||
});
|
||||
|
||||
lessonDaySelect.addEventListener('change', function () {
|
||||
updateTimeOptions(this.value);
|
||||
});
|
||||
|
||||
if (modalAddLessonClose) {
|
||||
modalAddLessonClose.addEventListener('click', () => closeOverlay());
|
||||
}
|
||||
|
||||
// Клик по оверлею (мимо модалок) закрывает всё
|
||||
if (usersOverlay) {
|
||||
usersOverlay.querySelector('.cs-overlay-scroll')?.addEventListener('click', (e) => {
|
||||
if (e.target.classList.contains('cs-overlay-scroll')) {
|
||||
closeOverlay();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// =========================================================
|
||||
// Создание пользователя
|
||||
// =========================================================
|
||||
createForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
hideAlert('create-alert');
|
||||
@@ -343,9 +57,9 @@ export async function initUsers() {
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await api.post('/api/users', {
|
||||
username,
|
||||
password,
|
||||
const data = await api.post('/api/users', {
|
||||
username,
|
||||
password,
|
||||
role,
|
||||
fullName,
|
||||
jobTitle,
|
||||
@@ -359,133 +73,18 @@ export async function initUsers() {
|
||||
}
|
||||
});
|
||||
|
||||
// =========================================================
|
||||
// Инициализация
|
||||
// =========================================================
|
||||
await Promise.all([loadUsers(), loadGroups(), loadSubjects(), loadClassrooms()]);
|
||||
|
||||
// =========================================================
|
||||
// 2-я модалка: просмотр занятий
|
||||
// =========================================================
|
||||
async function loadTeacherLessons(teacherId, teacherName) {
|
||||
try {
|
||||
lessonsContainer.innerHTML = '<div class="loading-lessons">Загрузка занятий...</div>';
|
||||
|
||||
modalTeacherName.textContent = teacherName
|
||||
? `Занятия преподавателя: ${teacherName}`
|
||||
: 'Занятия преподавателя';
|
||||
|
||||
const lessons = await api.get(`/api/users/lessons/${teacherId}`);
|
||||
|
||||
if (!lessons || lessons.length === 0) {
|
||||
lessonsContainer.innerHTML = '<div class="no-lessons">У преподавателя пока нет занятий</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const daysOrder = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'];
|
||||
const lessonsByDay = {};
|
||||
|
||||
lessons.forEach(lesson => {
|
||||
if (!lessonsByDay[lesson.day]) lessonsByDay[lesson.day] = [];
|
||||
lessonsByDay[lesson.day].push(lesson);
|
||||
});
|
||||
|
||||
Object.keys(lessonsByDay).forEach(day => {
|
||||
lessonsByDay[day].sort((a, b) => a.time.localeCompare(b.time));
|
||||
});
|
||||
|
||||
let html = '';
|
||||
|
||||
daysOrder.forEach(day => {
|
||||
if (!lessonsByDay[day]) return;
|
||||
|
||||
html += `<div class="lesson-day-divider">${day}</div>`;
|
||||
|
||||
lessonsByDay[day].forEach(lesson => {
|
||||
html += `
|
||||
<div class="lesson-card">
|
||||
<div class="lesson-card-header">
|
||||
<span class="lesson-group">${escapeHtml(lesson.groupName)}</span>
|
||||
<span class="lesson-time">${escapeHtml(lesson.time)}</span>
|
||||
</div>
|
||||
<div class="lesson-card-body">
|
||||
<div class="lesson-subject">${escapeHtml(lesson.subjectName)}</div>
|
||||
<div class="lesson-details">
|
||||
<span class="lesson-detail-item">${escapeHtml(lesson.typeLesson)}</span>
|
||||
<span class="lesson-detail-item">${escapeHtml(lesson.lessonFormat)}</span>
|
||||
<span class="lesson-detail-item">${escapeHtml(lesson.week)}</span>
|
||||
<span class="lesson-detail-item">${escapeHtml(lesson.classroomName)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
});
|
||||
|
||||
lessonsContainer.innerHTML = html;
|
||||
} catch (e) {
|
||||
lessonsContainer.innerHTML = `<div class="no-lessons">Ошибка загрузки: ${escapeHtml(e.message)}</div>`;
|
||||
console.error('Ошибка загрузки занятий:', e);
|
||||
}
|
||||
}
|
||||
|
||||
function openViewLessonsModal(teacherId, teacherName) {
|
||||
currentLessonsTeacherId = teacherId;
|
||||
currentLessonsTeacherName = teacherName || '';
|
||||
|
||||
if (modalViewLessons) modalViewLessons.style.display = '';
|
||||
loadTeacherLessons(teacherId, teacherName);
|
||||
}
|
||||
|
||||
function closeViewLessonsModal() {
|
||||
if (modalViewLessons) modalViewLessons.style.display = 'none';
|
||||
currentLessonsTeacherId = null;
|
||||
currentLessonsTeacherName = '';
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key !== 'Escape') return;
|
||||
if (usersOverlay?.classList.contains('open')) {
|
||||
closeOverlay();
|
||||
}
|
||||
});
|
||||
|
||||
// =========================================================
|
||||
// ЕДИНЫЙ обработчик кликов по таблице (ВАЖНО: без дубля)
|
||||
// =========================================================
|
||||
usersTbody.addEventListener('click', async (e) => {
|
||||
const deleteBtn = e.target.closest('.btn-delete');
|
||||
if (deleteBtn) {
|
||||
if (!confirm('Удалить пользователя?')) return;
|
||||
try {
|
||||
await api.delete('/api/users/' + deleteBtn.dataset.id);
|
||||
loadUsers();
|
||||
} catch (err) {
|
||||
alert(err.message || 'Ошибка удаления');
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!deleteBtn) return;
|
||||
|
||||
const addLessonBtn = e.target.closest('.btn-add-lesson');
|
||||
if (addLessonBtn) {
|
||||
e.preventDefault();
|
||||
|
||||
const teacherId = addLessonBtn.dataset.id;
|
||||
const teacherName = addLessonBtn.dataset.name;
|
||||
|
||||
openAddLessonModal(teacherId);
|
||||
openViewLessonsModal(teacherId, teacherName);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const viewLessonsBtn = e.target.closest('.btn-view-lessons');
|
||||
if (viewLessonsBtn) {
|
||||
e.preventDefault();
|
||||
const teacherId = viewLessonsBtn.dataset.id;
|
||||
const teacherName = viewLessonsBtn.dataset.name;
|
||||
openViewLessonsModal(teacherId, teacherName);
|
||||
return;
|
||||
if (!confirm('Удалить пользователя?')) return;
|
||||
try {
|
||||
await api.delete('/api/users/' + deleteBtn.dataset.id);
|
||||
loadUsers();
|
||||
} catch (err) {
|
||||
alert(err.message || 'Ошибка удаления');
|
||||
}
|
||||
});
|
||||
|
||||
await loadUsers();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user