обновил дизайн, добавил дашборд
This commit is contained in:
@@ -92,6 +92,41 @@ export async function refreshAccessToken() {
|
||||
return refreshPromise;
|
||||
}
|
||||
|
||||
const cache = new Map();
|
||||
|
||||
const CACHABLE_PREFIXES = [
|
||||
'/api/departments',
|
||||
'/api/specialties',
|
||||
'/api/education-forms',
|
||||
'/api/users/teachers',
|
||||
'/api/equipments',
|
||||
'/api/classrooms'
|
||||
];
|
||||
|
||||
function invalidateCache(url) {
|
||||
const cacheKeysToClear = [
|
||||
'/api/departments',
|
||||
'/api/specialties',
|
||||
'/api/education-forms',
|
||||
'/api/users',
|
||||
'/api/equipments',
|
||||
'/api/classrooms'
|
||||
];
|
||||
for (const prefix of cacheKeysToClear) {
|
||||
if (url.includes(prefix)) {
|
||||
for (const cacheKey of cache.keys()) {
|
||||
if (cacheKey.includes(prefix)) {
|
||||
cache.delete(cacheKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function clearCache() {
|
||||
cache.clear();
|
||||
}
|
||||
|
||||
export async function logout() {
|
||||
try {
|
||||
await fetch('/api/auth/logout', {
|
||||
@@ -102,6 +137,7 @@ export async function logout() {
|
||||
console.warn('Не удалось завершить серверную сессию:', e.message);
|
||||
} finally {
|
||||
clearAuthState();
|
||||
clearCache();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,8 +157,26 @@ export function clearAuthState() {
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: (url) => apiFetch(url, 'GET'),
|
||||
post: (url, body) => apiFetch(url, 'POST', body),
|
||||
put: (url, body) => apiFetch(url, 'PUT', body),
|
||||
delete: (url, body = null) => apiFetch(url, 'DELETE', body)
|
||||
get: async (url) => {
|
||||
const isCachable = CACHABLE_PREFIXES.some(prefix => url.startsWith(prefix));
|
||||
if (isCachable) {
|
||||
if (!cache.has(url)) {
|
||||
cache.set(url, await apiFetch(url, 'GET'));
|
||||
}
|
||||
return cache.get(url);
|
||||
}
|
||||
return apiFetch(url, 'GET');
|
||||
},
|
||||
post: async (url, body) => {
|
||||
invalidateCache(url);
|
||||
return apiFetch(url, 'POST', body);
|
||||
},
|
||||
put: async (url, body) => {
|
||||
invalidateCache(url);
|
||||
return apiFetch(url, 'PUT', body);
|
||||
},
|
||||
delete: async (url, body = null) => {
|
||||
invalidateCache(url);
|
||||
return apiFetch(url, 'DELETE', body);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -99,6 +99,35 @@ export class CustomSelect {
|
||||
this.menu.innerHTML = '';
|
||||
const options = Array.from(this.originalSelect.options);
|
||||
|
||||
// Show search input if more than 6 options exist
|
||||
if (options.length > 6) {
|
||||
const searchLi = document.createElement('li');
|
||||
searchLi.className = 'custom-select-search-container';
|
||||
const searchInput = document.createElement('input');
|
||||
searchInput.type = 'text';
|
||||
searchInput.placeholder = 'Поиск...';
|
||||
searchInput.className = 'custom-select-search-input';
|
||||
searchInput.addEventListener('click', (e) => e.stopPropagation());
|
||||
searchInput.addEventListener('input', (e) => {
|
||||
const query = e.target.value.toLowerCase();
|
||||
const items = this.menu.querySelectorAll('.custom-select-item');
|
||||
items.forEach(item => {
|
||||
if (item.classList.contains('placeholder-item')) return;
|
||||
const text = item.textContent.toLowerCase();
|
||||
if (text.includes(query)) {
|
||||
item.style.display = '';
|
||||
} else {
|
||||
item.style.display = 'none';
|
||||
}
|
||||
});
|
||||
});
|
||||
searchLi.appendChild(searchInput);
|
||||
this.menu.appendChild(searchLi);
|
||||
this.searchInput = searchInput;
|
||||
} else {
|
||||
this.searchInput = null;
|
||||
}
|
||||
|
||||
if (options.length === 0) {
|
||||
const li = document.createElement('li');
|
||||
li.className = 'custom-select-item disabled';
|
||||
@@ -171,7 +200,22 @@ export class CustomSelect {
|
||||
|
||||
if (!isOpen) {
|
||||
this.layerParent?.classList.add('select-layer-active');
|
||||
this.originalSelect.closest('.form-group, .form-field')?.classList.add('select-layer-active');
|
||||
this.wrapper.classList.add('open');
|
||||
|
||||
if (this.searchInput) {
|
||||
this.searchInput.value = '';
|
||||
const items = this.menu.querySelectorAll('.custom-select-item');
|
||||
items.forEach(item => {
|
||||
if (!item.classList.contains('placeholder-item')) {
|
||||
item.style.display = '';
|
||||
}
|
||||
});
|
||||
setTimeout(() => {
|
||||
this.searchInput.focus();
|
||||
}, 50);
|
||||
}
|
||||
|
||||
// Scroll selected item into view
|
||||
const selectedItem = this.menu.querySelector('.selected');
|
||||
if (selectedItem) {
|
||||
@@ -194,6 +238,7 @@ export class CustomSelect {
|
||||
close() {
|
||||
this.wrapper.classList.remove('open');
|
||||
this.layerParent?.classList.remove('select-layer-active');
|
||||
this.originalSelect.closest('.form-group, .form-field')?.classList.remove('select-layer-active');
|
||||
}
|
||||
|
||||
handleItemClick(e, index) {
|
||||
|
||||
@@ -20,47 +20,106 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
startDropdownAutoObserver();
|
||||
});
|
||||
|
||||
import { initUsers } from './views/users.js';
|
||||
import { initGroups } from './views/groups.js';
|
||||
import { initEduForms } from './views/edu-forms.js';
|
||||
import { initEquipments } from './views/equipments.js';
|
||||
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 {initDepartmentsData} from "./views/departments-data.js";
|
||||
import {initAuditoriumWorkload} from "./views/auditorium-workload.js";
|
||||
import {initProfiles} from "./views/profiles.js";
|
||||
import {initAcademicCalendar} from "./views/academic-calendar.js";
|
||||
import {initScheduleView} from "./views/schedule-view.js";
|
||||
import {initDepartmentWorkspace} from "./views/department-workspace.js";
|
||||
|
||||
// Configuration
|
||||
const ROUTES = {
|
||||
users: { title: 'Управление пользователями', file: '/admin/views/users.html', init: initUsers },
|
||||
groups: { title: 'Управление группами', file: '/admin/views/groups.html', init: initGroups },
|
||||
'edu-forms': { title: 'Формы обучения', file: '/admin/views/edu-forms.html', init: initEduForms },
|
||||
equipments: { title: 'Оборудование', file: '/admin/views/equipments.html', init: initEquipments },
|
||||
classrooms: { title: 'Аудитории', file: '/admin/views/classrooms.html', init: initClassrooms },
|
||||
subjects: { title: 'Дисциплины и преподаватели', file: '/admin/views/subjects.html', init: initSubjects },
|
||||
'department-workspace': { title: 'Кабинет кафедры', file: '/admin/views/department-workspace.html', init: initDepartmentWorkspace },
|
||||
'schedule-view': { title: 'Просмотр расписаний', file: '/admin/views/schedule-view.html', init: initScheduleView },
|
||||
schedule: { title: 'Расписание занятий', file: '/admin/views/schedule.html', init: initSchedule },
|
||||
'academic-calendar': { title: 'Календарный учебный график', file: '/admin/views/academic-calendar.html', init: initAcademicCalendar },
|
||||
'auditorium-workload': { title: 'Загруженность', file: '/admin/views/auditorium-workload.html', init: initAuditoriumWorkload },
|
||||
database: { title: 'База данных', file: '/admin/views/database.html', init: initDatabase },
|
||||
'departments-data': { title: 'Создание кафедры/специальности', file: '/admin/views/departments-data.html', init: initDepartmentsData },
|
||||
profiles: { title: 'Профили обучения', file: '/admin/views/profiles.html', init: initProfiles },
|
||||
dashboard: {
|
||||
title: 'Дашборд',
|
||||
file: '/admin/views/dashboard.html',
|
||||
init: async () => {
|
||||
const module = await import('./views/dashboard.js');
|
||||
await module.initDashboard();
|
||||
}
|
||||
},
|
||||
users: {
|
||||
title: 'Управление пользователями',
|
||||
file: '/admin/views/users.html',
|
||||
init: async () => {
|
||||
const module = await import('./views/users.js');
|
||||
await module.initUsers();
|
||||
}
|
||||
},
|
||||
groups: {
|
||||
title: 'Управление группами',
|
||||
file: '/admin/views/groups.html',
|
||||
init: async () => {
|
||||
const module = await import('./views/groups.js');
|
||||
await module.initGroups();
|
||||
}
|
||||
},
|
||||
classrooms: {
|
||||
title: 'Аудиторный фонд',
|
||||
file: '/admin/views/classrooms.html',
|
||||
init: async () => {
|
||||
const module = await import('./views/classrooms.js');
|
||||
await module.initClassrooms();
|
||||
}
|
||||
},
|
||||
subjects: {
|
||||
title: 'Дисциплины',
|
||||
file: '/admin/views/subjects.html',
|
||||
init: async () => {
|
||||
const module = await import('./views/subjects.js');
|
||||
await module.initSubjects();
|
||||
}
|
||||
},
|
||||
'university-structure': {
|
||||
title: 'Структура вуза',
|
||||
file: '/admin/views/university-structure.html',
|
||||
init: async () => {
|
||||
const module = await import('./views/university-structure.js');
|
||||
await module.initUniversityStructure();
|
||||
}
|
||||
},
|
||||
'department-workspace': {
|
||||
title: 'Кабинет кафедры',
|
||||
file: '/admin/views/department-workspace.html',
|
||||
init: async () => {
|
||||
const module = await import('./views/department-workspace.js');
|
||||
await module.initDepartmentWorkspace();
|
||||
}
|
||||
},
|
||||
'schedule-view': {
|
||||
title: 'Просмотр расписаний',
|
||||
file: '/admin/views/schedule-view.html',
|
||||
init: async () => {
|
||||
const module = await import('./views/schedule-view.js');
|
||||
await module.initScheduleView();
|
||||
}
|
||||
},
|
||||
schedule: {
|
||||
title: 'Расписание занятий',
|
||||
file: '/admin/views/schedule.html',
|
||||
init: async () => {
|
||||
const module = await import('./views/schedule.js');
|
||||
await module.initSchedule();
|
||||
}
|
||||
},
|
||||
'academic-calendar': {
|
||||
title: 'Календарный учебный график',
|
||||
file: '/admin/views/academic-calendar.html',
|
||||
init: async () => {
|
||||
const module = await import('./views/academic-calendar.js');
|
||||
await module.initAcademicCalendar();
|
||||
}
|
||||
},
|
||||
'auditorium-workload': {
|
||||
title: 'Загруженность',
|
||||
file: '/admin/views/auditorium-workload.html',
|
||||
init: async () => {
|
||||
const module = await import('./views/auditorium-workload.js');
|
||||
await module.initAuditoriumWorkload();
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
const ROLE_NAVIGATION = {
|
||||
ADMIN: {
|
||||
defaultTab: 'users',
|
||||
tabs: Object.keys(ROUTES)
|
||||
defaultTab: 'dashboard',
|
||||
tabs: ['dashboard', 'schedule', 'academic-calendar', 'auditorium-workload', 'schedule-view', 'classrooms', 'groups', 'university-structure', 'subjects', 'users']
|
||||
},
|
||||
EDUCATION_OFFICE: {
|
||||
defaultTab: 'schedule-view',
|
||||
tabs: ['schedule-view', 'schedule', 'academic-calendar', 'auditorium-workload', 'classrooms', 'equipments']
|
||||
defaultTab: 'dashboard',
|
||||
tabs: ['dashboard', 'schedule', 'academic-calendar', 'auditorium-workload', 'schedule-view', 'classrooms']
|
||||
},
|
||||
DEPARTMENT: {
|
||||
defaultTab: 'department-workspace',
|
||||
@@ -176,10 +235,13 @@ async function switchTab(tab) {
|
||||
|
||||
// Initialize logic for the tab
|
||||
if (ROUTES[tab].init) {
|
||||
ROUTES[tab].init();
|
||||
await ROUTES[tab].init();
|
||||
}
|
||||
|
||||
currentTab = tab;
|
||||
if (window.location.hash !== `#${tab}`) {
|
||||
window.location.hash = tab;
|
||||
}
|
||||
} catch (e) {
|
||||
appContent.innerHTML = `<div class="form-alert error">Ошибка загрузки вкладки: ${e.message}</div>`;
|
||||
console.error(e);
|
||||
@@ -211,3 +273,10 @@ function configureRoleInterface() {
|
||||
|
||||
const hashTab = window.location.hash.replace('#', '');
|
||||
switchTab(allowedTabs.has(hashTab) ? hashTab : roleNavigation.defaultTab);
|
||||
|
||||
window.addEventListener('hashchange', () => {
|
||||
const hashTab = window.location.hash.replace('#', '');
|
||||
if (allowedTabs.has(hashTab) && hashTab !== currentTab) {
|
||||
switchTab(hashTab);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -68,13 +68,6 @@ const CELL_PARITY_LAYOUT = [
|
||||
{ parity: 'EVEN', label: 'Чётная' }
|
||||
];
|
||||
|
||||
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');
|
||||
const refreshButton = document.getElementById('workload-refresh');
|
||||
@@ -89,6 +82,7 @@ export async function initAuditoriumWorkload() {
|
||||
const roomTables = document.getElementById('room-workload-tables');
|
||||
const overviewFilters = Array.from(document.querySelectorAll('.workload-overview-filter'));
|
||||
const dateLabel = dateInput?.closest('.form-group')?.querySelector('label');
|
||||
const minCapacityInput = document.getElementById('workload-min-capacity');
|
||||
|
||||
let classrooms = [];
|
||||
let teachers = [];
|
||||
@@ -117,7 +111,6 @@ export async function initAuditoriumWorkload() {
|
||||
|
||||
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');
|
||||
}
|
||||
|
||||
@@ -142,7 +135,6 @@ export async function initAuditoriumWorkload() {
|
||||
|
||||
[
|
||||
['building-checkboxes', 'building-text', 'Все корпуса'],
|
||||
['capacity-checkboxes', 'capacity-text', 'Любая вместимость'],
|
||||
['equipment-checkboxes', 'equipment-text', 'Любое оборудование']
|
||||
].forEach(([containerId, textId, emptyText]) => {
|
||||
const container = document.getElementById(containerId);
|
||||
@@ -153,6 +145,12 @@ export async function initAuditoriumWorkload() {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
minCapacityInput?.addEventListener('input', () => {
|
||||
if (currentView === DISPLAY_ALL) {
|
||||
renderGrid();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function loadInitialData() {
|
||||
@@ -345,12 +343,6 @@ export async function initAuditoriumWorkload() {
|
||||
item => item.value,
|
||||
item => item.label
|
||||
);
|
||||
renderCheckboxes(
|
||||
'capacity-checkboxes',
|
||||
CAPACITY_BUCKETS,
|
||||
item => item.id,
|
||||
item => item.name
|
||||
);
|
||||
renderCheckboxes(
|
||||
'equipment-checkboxes',
|
||||
equipmentOptions(),
|
||||
@@ -359,7 +351,6 @@ export async function initAuditoriumWorkload() {
|
||||
);
|
||||
|
||||
updateFilterText('building-checkboxes', 'building-text', 'Все корпуса');
|
||||
updateFilterText('capacity-checkboxes', 'capacity-text', 'Любая вместимость');
|
||||
updateFilterText('equipment-checkboxes', 'equipment-text', 'Любое оборудование');
|
||||
}
|
||||
|
||||
@@ -934,14 +925,12 @@ export async function initAuditoriumWorkload() {
|
||||
|
||||
function filteredClassrooms() {
|
||||
const selectedBuildings = selectedValues('building-checkboxes');
|
||||
const selectedCapacities = selectedValues('capacity-checkboxes');
|
||||
const minCapacity = parseInt(minCapacityInput?.value || '0', 10) || 0;
|
||||
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 capacityMatches = !minCapacity || Number(room.capacity || 0) >= minCapacity;
|
||||
const equipmentMatches = !selectedEquipment.length || selectedEquipment.every(id =>
|
||||
(room.equipments || []).some(item => String(item.id) === String(id))
|
||||
);
|
||||
|
||||
@@ -1,6 +1,34 @@
|
||||
import { api } from '../api.js';
|
||||
import { escapeHtml, showAlert, hideAlert, initMultiSelect, updateSelectText } from '../utils.js';
|
||||
import { fetchEquipments, renderEquipmentCheckboxes } from './equipments.js';
|
||||
|
||||
async function fetchEquipments() {
|
||||
try {
|
||||
return await api.get('/api/equipments');
|
||||
} catch (e) {
|
||||
console.error("Failed to fetch equipments", e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function renderEquipmentCheckboxes(equipments, containerId, selectTextId, selectedIds = []) {
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) return;
|
||||
|
||||
if (!equipments || !equipments.length) {
|
||||
container.innerHTML = '<p class="text-muted"><small>Оборудование отсутствует</small></p>';
|
||||
updateSelectText(containerId, selectTextId);
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML = equipments.map(eq => `
|
||||
<label class="checkbox-container">
|
||||
<input type="checkbox" value="${eq.id}" ${selectedIds.includes(eq.id) ? 'checked' : ''}>
|
||||
<span>${escapeHtml(eq.name)}</span>
|
||||
</label>
|
||||
`).join('');
|
||||
|
||||
updateSelectText(containerId, selectTextId);
|
||||
}
|
||||
|
||||
export async function initClassrooms() {
|
||||
const classroomsTbody = document.getElementById('classrooms-tbody');
|
||||
@@ -191,5 +219,82 @@ export async function initClassrooms() {
|
||||
}
|
||||
});
|
||||
|
||||
// Элементы модалки оборудования
|
||||
const btnManageEquipments = document.getElementById('btn-manage-equipments');
|
||||
const modalManageEquipments = document.getElementById('modal-manage-equipments');
|
||||
const modalManageEquipmentsClose = document.getElementById('modal-manage-equipments-close');
|
||||
const manageEquipmentForm = document.getElementById('manage-equipment-form');
|
||||
const manageEquipmentNameInput = document.getElementById('manage-equipment-name');
|
||||
const manageEquipmentTbody = document.getElementById('manage-equipments-tbody');
|
||||
|
||||
btnManageEquipments.addEventListener('click', openManageEquipmentsModal);
|
||||
modalManageEquipmentsClose.addEventListener('click', () => modalManageEquipments.classList.remove('open'));
|
||||
modalManageEquipments.addEventListener('click', (e) => {
|
||||
if (e.target === modalManageEquipments) modalManageEquipments.classList.remove('open');
|
||||
});
|
||||
|
||||
async function openManageEquipmentsModal() {
|
||||
hideAlert('manage-equipment-alert');
|
||||
manageEquipmentForm.reset();
|
||||
modalManageEquipments.classList.add('open');
|
||||
await loadManageEquipments();
|
||||
}
|
||||
|
||||
async function loadManageEquipments() {
|
||||
manageEquipmentTbody.innerHTML = '<tr><td colspan="3" class="loading-row">Загрузка...</td></tr>';
|
||||
try {
|
||||
allEquipments = await fetchEquipments();
|
||||
renderManageEquipmentsTable();
|
||||
// Обновим чекбоксы на основной странице
|
||||
renderEquipmentCheckboxes(allEquipments, 'equipment-checkboxes', 'equipment-select-text');
|
||||
} catch (e) {
|
||||
manageEquipmentTbody.innerHTML = '<tr><td colspan="3" class="loading-row">Ошибка загрузки</td></tr>';
|
||||
}
|
||||
}
|
||||
|
||||
function renderManageEquipmentsTable() {
|
||||
if (!allEquipments || !allEquipments.length) {
|
||||
manageEquipmentTbody.innerHTML = '<tr><td colspan="3" class="loading-row">Нет оборудования</td></tr>';
|
||||
return;
|
||||
}
|
||||
manageEquipmentTbody.innerHTML = allEquipments.map(eq => `
|
||||
<tr>
|
||||
<td>${eq.id}</td>
|
||||
<td>${escapeHtml(eq.name)}</td>
|
||||
<td><button class="btn-delete btn-delete-equipment" data-id="${eq.id}">Удалить</button></td>
|
||||
</tr>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
manageEquipmentForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
hideAlert('manage-equipment-alert');
|
||||
const name = manageEquipmentNameInput.value.trim();
|
||||
if (!name) {
|
||||
showAlert('manage-equipment-alert', 'Введите название', 'error');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const data = await api.post('/api/equipments', { name });
|
||||
showAlert('manage-equipment-alert', `Оборудование "${escapeHtml(data.name)}" добавлено`, 'success');
|
||||
manageEquipmentForm.reset();
|
||||
await loadManageEquipments();
|
||||
} catch (err) {
|
||||
showAlert('manage-equipment-alert', err.message || 'Ошибка добавления', 'error');
|
||||
}
|
||||
});
|
||||
|
||||
manageEquipmentTbody.addEventListener('click', async (e) => {
|
||||
const btnDelete = e.target.closest('.btn-delete-equipment');
|
||||
if (!btnDelete) return;
|
||||
if (!confirm('Удалить оборудование из каталога?')) return;
|
||||
try {
|
||||
await api.delete('/api/equipments/' + btnDelete.dataset.id);
|
||||
await loadManageEquipments();
|
||||
} catch (err) {
|
||||
alert(err.message || 'Ошибка удаления');
|
||||
}
|
||||
});
|
||||
|
||||
loadInitialData();
|
||||
}
|
||||
|
||||
322
frontend/admin/js/views/dashboard.js
Normal file
322
frontend/admin/js/views/dashboard.js
Normal file
@@ -0,0 +1,322 @@
|
||||
import { api } from '../api.js';
|
||||
import { escapeHtml, showAlert, hideAlert } from '../utils.js';
|
||||
|
||||
export async function initDashboard() {
|
||||
// DOM Элементы
|
||||
const metricGroups = document.getElementById('metric-groups');
|
||||
const metricStudents = document.getElementById('metric-students');
|
||||
const metricTeachers = document.getElementById('metric-teachers');
|
||||
const metricClassrooms = document.getElementById('metric-classrooms');
|
||||
|
||||
const currentTimeSlot = document.getElementById('current-time-slot');
|
||||
const currentLessonsTbody = document.getElementById('current-lessons-tbody');
|
||||
const freeClassroomsList = document.getElementById('free-classrooms-list');
|
||||
const conflictsContainer = document.getElementById('conflicts-container');
|
||||
const btnRecheck = document.getElementById('btn-recheck-conflicts');
|
||||
|
||||
let departments = [];
|
||||
let classrooms = [];
|
||||
let groups = [];
|
||||
let teachers = [];
|
||||
let todayLessons = [];
|
||||
let timeSlots = [];
|
||||
|
||||
btnRecheck.addEventListener('click', async () => {
|
||||
btnRecheck.disabled = true;
|
||||
btnRecheck.textContent = '...';
|
||||
await checkConflicts();
|
||||
btnRecheck.textContent = 'Перепроверить';
|
||||
btnRecheck.disabled = false;
|
||||
});
|
||||
|
||||
async function loadData() {
|
||||
try {
|
||||
// Загружаем базовые справочники
|
||||
[departments, classrooms, groups, teachers] = await Promise.all([
|
||||
api.get('/api/departments'),
|
||||
api.get('/api/classrooms?includeArchived=false'),
|
||||
api.get('/api/groups?includeArchived=false'),
|
||||
api.get('/api/users/teachers')
|
||||
]);
|
||||
|
||||
// Выводим метрики
|
||||
metricGroups.textContent = groups.length;
|
||||
const totalStudents = groups.reduce((acc, g) => acc + (g.groupSize || 0), 0);
|
||||
metricStudents.textContent = totalStudents;
|
||||
metricTeachers.textContent = teachers.length;
|
||||
|
||||
const todayStr = new Date().toISOString().split('T')[0];
|
||||
|
||||
// Загружаем временные слоты и сегодняшнее расписание
|
||||
const lessonsPromises = departments.map(d =>
|
||||
api.get(`/api/schedule/search?departmentId=${d.id}&startDate=${todayStr}&endDate=${todayStr}`).catch(() => [])
|
||||
);
|
||||
const lessonsArrays = await Promise.all(lessonsPromises);
|
||||
todayLessons = lessonsArrays.flat();
|
||||
|
||||
try {
|
||||
timeSlots = await api.get(`/api/admin/time-slots/effective?date=${todayStr}`);
|
||||
} catch (e) {
|
||||
// Если эндпоинт effective не поддерживается, используем базовые слоты
|
||||
const baseSlots = await api.get('/api/admin/time-slots').catch(() => []);
|
||||
// Отфильтруем базовые слоты тенанта (scopeId = DEFAULT или аналогично)
|
||||
timeSlots = baseSlots.filter(s => s.scopeId === 1 || !s.scopeId);
|
||||
}
|
||||
|
||||
// Сортируем слоты по времени
|
||||
timeSlots.sort((a, b) => (a.orderNumber || 0) - (b.orderNumber || 0));
|
||||
|
||||
// Посчитаем занятость аудиторий сегодня
|
||||
const occupiedClassroomIds = new Set(todayLessons.map(l => l.classroomId).filter(Boolean));
|
||||
const activeClassrooms = classrooms.filter(c => c.isAvailable && c.status !== 'ARCHIVED');
|
||||
const classPercent = activeClassrooms.length
|
||||
? Math.round((occupiedClassroomIds.size / activeClassrooms.length) * 100)
|
||||
: 0;
|
||||
metricClassrooms.textContent = `${classPercent}% (${occupiedClassroomIds.size}/${activeClassrooms.length})`;
|
||||
|
||||
updateRealtimeMonitoring();
|
||||
await checkConflicts();
|
||||
} catch (e) {
|
||||
console.error("Dashboard data load error", e);
|
||||
conflictsContainer.innerHTML = `<div class="form-alert error" style="display:block">Ошибка загрузки панели: ${escapeHtml(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function updateRealtimeMonitoring() {
|
||||
const now = new Date();
|
||||
const currentTimeStr = now.toTimeString().split(' ')[0]; // HH:MM:SS
|
||||
|
||||
// Находим текущий временной слот
|
||||
let currentSlot = null;
|
||||
for (const slot of timeSlots) {
|
||||
if (currentTimeStr >= slot.startTime && currentTimeStr <= slot.endTime) {
|
||||
currentSlot = slot;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (currentSlot) {
|
||||
currentTimeSlot.textContent = `Пара №${currentSlot.orderNumber} (${currentSlot.startTime.substring(0, 5)} – ${currentSlot.endTime.substring(0, 5)})`;
|
||||
renderCurrentLessons(currentSlot.orderNumber);
|
||||
renderFreeClassrooms(currentSlot.orderNumber);
|
||||
} else {
|
||||
currentTimeSlot.textContent = 'Вне сетки пар';
|
||||
currentLessonsTbody.innerHTML = '<tr><td colspan="4" class="loading-row" style="padding: 1.5rem; text-align: center; color: var(--text-secondary);">В данный момент учебные пары не проводятся</td></tr>';
|
||||
|
||||
// Если сейчас нет пары, покажем свободные аудитории на ближайшую следующую пару (или просто все свободные)
|
||||
renderFreeClassrooms(null);
|
||||
}
|
||||
}
|
||||
|
||||
function renderCurrentLessons(slotOrder) {
|
||||
const activeLessons = todayLessons.filter(l => l.timeSlotOrder === slotOrder);
|
||||
if (!activeLessons.length) {
|
||||
currentLessonsTbody.innerHTML = '<tr><td colspan="4" class="loading-row" style="padding: 1.5rem; text-align: center; color: var(--text-secondary);">В текущий слот занятий не запланировано</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
currentLessonsTbody.innerHTML = activeLessons.map(l => `
|
||||
<tr>
|
||||
<td style="padding: 0.75rem;"><strong>${escapeHtml(l.classroomName)}</strong></td>
|
||||
<td style="padding: 0.75rem;">${escapeHtml(l.subjectName)} <span class="badge badge-ef" style="font-size:0.75rem;">${escapeHtml(l.lessonTypeName)}</span></td>
|
||||
<td style="padding: 0.75rem;">${escapeHtml(l.teacherName)}</td>
|
||||
<td style="padding: 0.75rem;"><span class="badge badge-available">${escapeHtml(l.groupNames.join(', '))}</span></td>
|
||||
</tr>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
function renderFreeClassrooms(slotOrder) {
|
||||
const activeClassrooms = classrooms.filter(c => c.isAvailable && c.status !== 'ARCHIVED');
|
||||
let occupiedIds = new Set();
|
||||
if (slotOrder !== null) {
|
||||
occupiedIds = new Set(todayLessons.filter(l => l.timeSlotOrder === slotOrder).map(l => l.classroomId));
|
||||
}
|
||||
|
||||
const free = activeClassrooms.filter(c => !occupiedIds.has(c.id));
|
||||
if (!free.length) {
|
||||
freeClassroomsList.innerHTML = '<span style="color: var(--error); font-size: 0.9rem; font-weight: 500;">Все аудитории заняты</span>';
|
||||
return;
|
||||
}
|
||||
|
||||
freeClassroomsList.innerHTML = free.map(c => `
|
||||
<span class="badge badge-available" style="padding: 0.4rem 0.6rem; font-size: 0.85rem; background: rgba(16, 185, 129, 0.1); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.2);">
|
||||
${escapeHtml(c.name)} (${c.capacity} м.)
|
||||
</span>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
// --- Анализ конфликтов (Red Zone) ---
|
||||
async function checkConflicts() {
|
||||
conflictsContainer.innerHTML = '<div class="loading-row" style="text-align: center; padding: 2rem; color: var(--text-secondary);">Анализ расписания и выявление конфликтов...</div>';
|
||||
|
||||
// Вычисляем даты начала и конца текущей недели
|
||||
const curr = new Date();
|
||||
const day = curr.getDay();
|
||||
const diff = curr.getDate() - day + (day === 0 ? -6 : 1); // Понедельник
|
||||
const monday = new Date(curr.setDate(diff));
|
||||
const sunday = new Date(curr.setDate(diff + 6));
|
||||
|
||||
const mondayStr = monday.toISOString().split('T')[0];
|
||||
const sundayStr = sunday.toISOString().split('T')[0];
|
||||
|
||||
try {
|
||||
// Загружаем расписание на всю неделю по кафедрам
|
||||
const weekLessonsPromises = departments.map(d =>
|
||||
api.get(`/api/schedule/search?departmentId=${d.id}&startDate=${mondayStr}&endDate=${sundayStr}`).catch(() => [])
|
||||
);
|
||||
const weekLessonsArrays = await Promise.all(weekLessonsPromises);
|
||||
const weekLessons = weekLessonsArrays.flat();
|
||||
|
||||
const conflicts = [];
|
||||
|
||||
// Мапы для быстрого поиска характеристик групп и аудиторий
|
||||
const groupSizeMap = new Map(groups.map(g => [g.id, g.groupSize || 0]));
|
||||
const classroomCapacityMap = new Map(classrooms.map(c => [c.id, c.capacity || 0]));
|
||||
|
||||
// 1. Проверка накладок преподавателей
|
||||
// Ключ: date + '_' + timeSlotOrder + '_' + teacherId
|
||||
const teacherSlots = new Map();
|
||||
weekLessons.forEach(l => {
|
||||
if (!l.teacherId) return;
|
||||
const key = `${l.date}_${l.timeSlotOrder}_${l.teacherId}`;
|
||||
if (!teacherSlots.has(key)) {
|
||||
teacherSlots.set(key, []);
|
||||
}
|
||||
teacherSlots.get(key).push(l);
|
||||
});
|
||||
|
||||
teacherSlots.forEach((lessons, key) => {
|
||||
if (lessons.length > 1) {
|
||||
// Проверим, если все занятия в одной аудитории — это потоковая лекция, а не конфликт
|
||||
const classroomIds = new Set(lessons.map(l => l.classroomId));
|
||||
if (classroomIds.size > 1) {
|
||||
const first = lessons[0];
|
||||
const listStr = lessons.map(l => `ауд. ${l.classroomName} (группа ${l.groupNames.join(', ')})`).join(', ');
|
||||
conflicts.push({
|
||||
type: 'TEACHER_COLLISION',
|
||||
title: 'Накладка в расписании преподавателя',
|
||||
description: `Преподаватель <strong>${escapeHtml(first.teacherName)}</strong> назначен одновременно в разные места: ${escapeHtml(listStr)} на <strong>${first.date} (${first.dayName}), пара №${first.timeSlotOrder}</strong>.`,
|
||||
severity: 'error'
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 2. Проверка накладок аудиторий
|
||||
// Ключ: date + '_' + timeSlotOrder + '_' + classroomId
|
||||
const classroomSlots = new Map();
|
||||
weekLessons.forEach(l => {
|
||||
if (!l.classroomId) return;
|
||||
const key = `${l.date}_${l.timeSlotOrder}_${l.classroomId}`;
|
||||
if (!classroomSlots.has(key)) {
|
||||
classroomSlots.set(key, []);
|
||||
}
|
||||
classroomSlots.get(key).push(l);
|
||||
});
|
||||
|
||||
classroomSlots.forEach((lessons, key) => {
|
||||
if (lessons.length > 1) {
|
||||
// Проверим, не является ли это потоковой лекцией (один преподаватель и одна дисциплина)
|
||||
const teacherIds = new Set(lessons.map(l => l.teacherId));
|
||||
const subjectIds = new Set(lessons.map(l => l.subjectId));
|
||||
|
||||
if (teacherIds.size > 1 || subjectIds.size > 1) {
|
||||
const first = lessons[0];
|
||||
const details = lessons.map(l => `препод. ${l.teacherName} (предмет: ${l.subjectName}, группа: ${l.groupNames.join(', ')})`).join(' И ');
|
||||
conflicts.push({
|
||||
type: 'CLASSROOM_COLLISION',
|
||||
title: 'Накладка в аудитории',
|
||||
description: `Аудитория <strong>${escapeHtml(first.classroomName)}</strong> занята одновременно разными занятиями: ${escapeHtml(details)} на <strong>${first.date} (${first.dayName}), пара №${first.timeSlotOrder}</strong>.`,
|
||||
severity: 'error'
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 3. Проверка превышения вместимости аудитории
|
||||
// Считаем сумму студентов для каждого уникального занятия в аудитории
|
||||
classroomSlots.forEach((lessons, key) => {
|
||||
if (!lessons.length) return;
|
||||
const first = lessons[0];
|
||||
const capacity = classroomCapacityMap.get(first.classroomId) || 0;
|
||||
|
||||
// Суммируем численность всех групп, назначенных на этот слот в этой аудитории
|
||||
const groupIds = new Set();
|
||||
lessons.forEach(l => {
|
||||
if (l.groupIds) {
|
||||
l.groupIds.forEach(id => groupIds.add(id));
|
||||
}
|
||||
});
|
||||
|
||||
let totalStudents = 0;
|
||||
groupIds.forEach(id => {
|
||||
totalStudents += groupSizeMap.get(id) || 0;
|
||||
});
|
||||
|
||||
if (totalStudents > capacity) {
|
||||
const groupNamesList = lessons.map(l => l.groupNames.join(', ')).join(', ');
|
||||
conflicts.push({
|
||||
type: 'CAPACITY_OVERFLOW',
|
||||
title: 'Превышение вместимости аудитории',
|
||||
description: `Вместимость аудитории <strong>${escapeHtml(first.classroomName)}</strong> составляет <strong>${capacity} чел.</strong>, однако на занятие назначено <strong>${totalStudents} человек</strong> (группы: ${escapeHtml(groupNamesList)}) на <strong>${first.date} (${first.dayName}), пара №${first.timeSlotOrder}</strong>.`,
|
||||
severity: 'warning'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
renderConflicts(conflicts);
|
||||
} catch (e) {
|
||||
console.error("Conflicts check error", e);
|
||||
conflictsContainer.innerHTML = `<div class="form-alert error" style="display:block">Ошибка при анализе конфликтов: ${escapeHtml(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderConflicts(conflicts) {
|
||||
if (!conflicts.length) {
|
||||
conflictsContainer.innerHTML = `
|
||||
<div style="background: rgba(16, 185, 129, 0.08); border: 1px solid rgba(16, 185, 129, 0.2); border-radius: 8px; padding: 1.25rem; display: flex; align-items: center; gap: 1rem; color: #10b981;">
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
|
||||
<polyline points="22 4 12 14.01 9 11.01" />
|
||||
</svg>
|
||||
<div>
|
||||
<strong style="display: block; font-size: 0.95rem; margin-bottom: 0.15rem;">Конфликты расписания не обнаружены!</strong>
|
||||
<span style="font-size: 0.85rem; opacity: 0.9;">Все правила расписания на текущую неделю согласованы, накладки преподавателей/аудиторий и переполнения отсутствуют.</span>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
conflictsContainer.innerHTML = conflicts.map(c => {
|
||||
const isError = c.severity === 'error';
|
||||
const borderCol = isError ? 'var(--error, #ef4444)' : '#f59e0b';
|
||||
const bgCol = isError ? 'rgba(239, 68, 68, 0.05)' : 'rgba(245, 158, 11, 0.05)';
|
||||
const badgeIcon = isError
|
||||
? `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>`
|
||||
: `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#f59e0b" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>`;
|
||||
|
||||
return `
|
||||
<div style="background: ${bgCol}; border: 1px solid rgba(229, 231, 235, 0.1); border-left: 4px solid ${borderCol}; border-radius: 8px; padding: 1rem; display: flex; gap: 0.75rem; align-items: start;">
|
||||
<div style="margin-top: 0.1rem;">${badgeIcon}</div>
|
||||
<div style="flex: 1;">
|
||||
<h4 style="margin: 0 0 0.25rem 0; font-size: 0.95rem; font-weight: 600; color: ${isError ? 'var(--error, #ef4444)' : '#d97706'};">${escapeHtml(c.title)}</h4>
|
||||
<p style="margin: 0; font-size: 0.85rem; line-height: 1.4; color: var(--text-main);">${c.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
// Загружаем данные при старте
|
||||
await loadData();
|
||||
|
||||
// Запускаем периодическое обновление (каждые 30 секунд для пар в реальном времени)
|
||||
const realtimeTimer = setInterval(() => {
|
||||
if (document.getElementById('current-time-slot')) {
|
||||
updateRealtimeMonitoring();
|
||||
} else {
|
||||
clearInterval(realtimeTimer);
|
||||
}
|
||||
}, 30000);
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
import { api } from '../api.js';
|
||||
import { escapeHtml, showAlert, hideAlert } from '../utils.js';
|
||||
|
||||
export async function initDatabase() {
|
||||
const tenantsTbody = document.getElementById('tenants-tbody');
|
||||
const addTenantForm = document.getElementById('add-tenant-form');
|
||||
const statusInfo = document.getElementById('db-status-info');
|
||||
const btnTest = document.getElementById('btn-test-connection');
|
||||
|
||||
// === Загрузка статуса текущего подключения ===
|
||||
async function loadStatus() {
|
||||
try {
|
||||
const data = await api.get('/api/database/status');
|
||||
const statusBadge = data.connected
|
||||
? '<span class="badge badge-available">Online</span>'
|
||||
: '<span class="badge badge-unavailable">Offline</span>';
|
||||
|
||||
statusInfo.innerHTML = `
|
||||
<div style="display: flex; align-items: center; gap: 1rem; flex-wrap: wrap;">
|
||||
<div>
|
||||
<span style="color: var(--text-secondary); font-size: 0.85rem;">Тенант:</span>
|
||||
<strong>${escapeHtml(data.tenant || '—')}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span style="color: var(--text-secondary); font-size: 0.85rem;">Название:</span>
|
||||
<strong>${escapeHtml(data.name || '—')}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span style="color: var(--text-secondary); font-size: 0.85rem;">Статус:</span>
|
||||
${statusBadge}
|
||||
</div>
|
||||
${data.url ? `<div>
|
||||
<span style="color: var(--text-secondary); font-size: 0.85rem;">URL:</span>
|
||||
<code style="font-size: 0.85rem;">${escapeHtml(data.url)}</code>
|
||||
</div>` : ''}
|
||||
</div>
|
||||
`;
|
||||
} catch (e) {
|
||||
statusInfo.innerHTML = `<div class="form-alert error" style="display:block">Ошибка загрузки статуса: ${e.message}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
// === Загрузка списка тенантов ===
|
||||
async function loadTenants() {
|
||||
try {
|
||||
const tenants = await api.get('/api/database/tenants');
|
||||
renderTenantsTable(tenants);
|
||||
} catch (e) {
|
||||
tenantsTbody.innerHTML = `<tr><td colspan="6" class="loading-row">Ошибка загрузки: ${e.message}</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderTenantsTable(tenants) {
|
||||
if (!tenants || !tenants.length) {
|
||||
tenantsTbody.innerHTML = '<tr><td colspan="6" class="loading-row">Нет подключённых тенантов</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
tenantsTbody.innerHTML = tenants.map(t => {
|
||||
const statusBadge = t.connected
|
||||
? '<span class="badge badge-available">Online</span>'
|
||||
: '<span class="badge badge-unavailable">Offline</span>';
|
||||
|
||||
return `
|
||||
<tr>
|
||||
<td>${escapeHtml(t.name || '—')}</td>
|
||||
<td><code>${escapeHtml(t.domain)}</code></td>
|
||||
<td><code style="font-size: 0.82rem;">${escapeHtml(t.url)}</code></td>
|
||||
<td>${escapeHtml(t.username || '—')}</td>
|
||||
<td>${statusBadge}</td>
|
||||
<td><button class="btn-delete" data-domain="${escapeHtml(t.domain)}">Удалить</button></td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
// === Тест подключения ===
|
||||
btnTest.addEventListener('click', async () => {
|
||||
hideAlert('add-tenant-alert');
|
||||
const url = document.getElementById('tenant-url').value.trim();
|
||||
const username = document.getElementById('tenant-username').value.trim();
|
||||
const password = document.getElementById('tenant-password').value;
|
||||
|
||||
if (!url) {
|
||||
showAlert('add-tenant-alert', 'Введите JDBC URL', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
btnTest.textContent = '...';
|
||||
btnTest.disabled = true;
|
||||
|
||||
try {
|
||||
const result = await api.post('/api/database/test', { url, username, password });
|
||||
if (result.success) {
|
||||
showAlert('add-tenant-alert', '✓ Подключение успешно!', 'success');
|
||||
} else {
|
||||
showAlert('add-tenant-alert', `✗ ${result.message}`, 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
showAlert('add-tenant-alert', `Ошибка: ${e.message}`, 'error');
|
||||
} finally {
|
||||
btnTest.textContent = 'Тест';
|
||||
btnTest.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
// === Добавление тенанта ===
|
||||
addTenantForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
hideAlert('add-tenant-alert');
|
||||
|
||||
const name = document.getElementById('tenant-name').value.trim();
|
||||
const domain = document.getElementById('tenant-domain').value.trim().toLowerCase();
|
||||
const url = document.getElementById('tenant-url').value.trim();
|
||||
const username = document.getElementById('tenant-username').value.trim();
|
||||
const password = document.getElementById('tenant-password').value;
|
||||
|
||||
if (!name || !domain || !url) {
|
||||
showAlert('add-tenant-alert', 'Заполните все обязательные поля', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await api.post('/api/database/tenants', { name, domain, url, username, password });
|
||||
if (result.success) {
|
||||
showAlert('add-tenant-alert', `Тенант "${escapeHtml(domain)}" добавлен!`, 'success');
|
||||
addTenantForm.reset();
|
||||
loadTenants();
|
||||
loadStatus();
|
||||
} else {
|
||||
showAlert('add-tenant-alert', result.message, 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
showAlert('add-tenant-alert', `Ошибка: ${e.message}`, 'error');
|
||||
}
|
||||
});
|
||||
|
||||
// === Удаление тенанта ===
|
||||
tenantsTbody.addEventListener('click', async (e) => {
|
||||
const btn = e.target.closest('.btn-delete');
|
||||
if (!btn) return;
|
||||
|
||||
const domain = btn.dataset.domain;
|
||||
if (!confirm(`Удалить тенант "${domain}"? Пул соединений будет закрыт.`)) return;
|
||||
|
||||
try {
|
||||
await api.delete(`/api/database/tenants/${domain}`);
|
||||
loadTenants();
|
||||
loadStatus();
|
||||
} catch (e) {
|
||||
alert(`Ошибка: ${e.message}`);
|
||||
}
|
||||
});
|
||||
|
||||
// === Init ===
|
||||
loadStatus();
|
||||
loadTenants();
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
import { api } from '../api.js';
|
||||
import { escapeHtml, showAlert, hideAlert } from '../utils.js';
|
||||
|
||||
export let allEducationForms = [];
|
||||
|
||||
export async function fetchEducationForms() {
|
||||
try {
|
||||
allEducationForms = await api.get('/api/education-forms');
|
||||
return allEducationForms;
|
||||
} catch (e) {
|
||||
console.error("Failed to fetch education forms", e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function initEduForms() {
|
||||
const efTbody = document.getElementById('ef-tbody');
|
||||
const createEfForm = document.getElementById('create-ef-form');
|
||||
|
||||
async function loadEF() {
|
||||
try {
|
||||
const forms = await fetchEducationForms();
|
||||
renderEfTable(forms);
|
||||
} catch (e) {
|
||||
efTbody.innerHTML = '<tr><td colspan="3" class="loading-row">Ошибка загрузки</td></tr>';
|
||||
}
|
||||
}
|
||||
|
||||
function renderEfTable(forms) {
|
||||
if (!forms || !forms.length) {
|
||||
efTbody.innerHTML = '<tr><td colspan="3" class="loading-row">Нет форм обучения</td></tr>';
|
||||
return;
|
||||
}
|
||||
efTbody.innerHTML = forms.map(ef => `
|
||||
<tr>
|
||||
<td>${ef.id}</td>
|
||||
<td>${escapeHtml(ef.name)}</td>
|
||||
<td><button class="btn-delete" data-id="${ef.id}">Удалить</button></td>
|
||||
</tr>`).join('');
|
||||
}
|
||||
|
||||
createEfForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
hideAlert('create-ef-alert');
|
||||
const name = document.getElementById('new-ef-name').value.trim();
|
||||
if (!name) { showAlert('create-ef-alert', 'Введите название', 'error'); return; }
|
||||
|
||||
try {
|
||||
const data = await api.post('/api/education-forms', { name });
|
||||
showAlert('create-ef-alert', `Форма "${escapeHtml(data.name)}" создана`, 'success');
|
||||
createEfForm.reset();
|
||||
loadEF();
|
||||
} catch (e) {
|
||||
showAlert('create-ef-alert', e.message || 'Ошибка создания', 'error');
|
||||
}
|
||||
});
|
||||
|
||||
efTbody.addEventListener('click', async (e) => {
|
||||
const btn = e.target.closest('.btn-delete');
|
||||
if (!btn) return;
|
||||
if (!confirm('Удалить форму обучения?')) return;
|
||||
try {
|
||||
await api.delete('/api/education-forms/' + btn.dataset.id);
|
||||
loadEF();
|
||||
} catch (e) {
|
||||
alert(e.message || 'Ошибка удаления');
|
||||
}
|
||||
});
|
||||
|
||||
loadEF();
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
import { api } from '../api.js';
|
||||
import { escapeHtml, showAlert, hideAlert, updateSelectText } from '../utils.js';
|
||||
|
||||
export let allEquipments = [];
|
||||
|
||||
export async function fetchEquipments() {
|
||||
try {
|
||||
allEquipments = await api.get('/api/equipments');
|
||||
return allEquipments;
|
||||
} catch (e) {
|
||||
console.error("Failed to fetch equipments", e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function renderEquipmentCheckboxes(equipments, containerId, textId, checkedIds = []) {
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) return;
|
||||
if (!equipments.length) {
|
||||
container.innerHTML = '<p class="text-muted"><small>Нет доступного оборудования</small></p>';
|
||||
return;
|
||||
}
|
||||
container.innerHTML = equipments.map(eq => {
|
||||
const isChecked = checkedIds.includes(eq.id) ? 'checked' : '';
|
||||
return `
|
||||
<label class="checkbox-item">
|
||||
<input type="checkbox" value="${eq.id}" ${isChecked}>
|
||||
<span class="checkmark"></span>
|
||||
<span class="checkbox-label">${escapeHtml(eq.name)}</span>
|
||||
</label>
|
||||
`}).join('');
|
||||
updateSelectText(containerId, textId);
|
||||
}
|
||||
|
||||
export async function initEquipments() {
|
||||
const equipmentsTbody = document.getElementById('equipments-tbody');
|
||||
const createEquipmentForm = document.getElementById('create-equipment-form');
|
||||
|
||||
async function loadEquipments() {
|
||||
try {
|
||||
const equipments = await fetchEquipments();
|
||||
renderEquipments(equipments);
|
||||
} catch (e) {
|
||||
if (equipmentsTbody) equipmentsTbody.innerHTML = '<tr><td colspan="3" class="loading-row">Ошибка загрузки</td></tr>';
|
||||
}
|
||||
}
|
||||
|
||||
function renderEquipments(equipments) {
|
||||
if (!equipments || !equipments.length) {
|
||||
equipmentsTbody.innerHTML = '<tr><td colspan="3" class="loading-row">Нет оборудования</td></tr>';
|
||||
return;
|
||||
}
|
||||
equipmentsTbody.innerHTML = equipments.map(eq => `
|
||||
<tr>
|
||||
<td>${eq.id}</td>
|
||||
<td>${escapeHtml(eq.name)}</td>
|
||||
<td><button class="btn-delete" data-id="${eq.id}">Удалить</button></td>
|
||||
</tr>`).join('');
|
||||
}
|
||||
|
||||
createEquipmentForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
hideAlert('create-equipment-alert');
|
||||
const name = document.getElementById('new-equipment-name').value.trim();
|
||||
if (!name) { showAlert('create-equipment-alert', 'Введите название', 'error'); return; }
|
||||
|
||||
try {
|
||||
const data = await api.post('/api/equipments', { name });
|
||||
showAlert('create-equipment-alert', `Оборудование "${escapeHtml(data.name)}" добавлено`, 'success');
|
||||
createEquipmentForm.reset();
|
||||
loadEquipments();
|
||||
} catch (e) {
|
||||
showAlert('create-equipment-alert', e.message || 'Ошибка создания', 'error');
|
||||
}
|
||||
});
|
||||
|
||||
equipmentsTbody.addEventListener('click', async (e) => {
|
||||
const btn = e.target.closest('.btn-delete');
|
||||
if (!btn) return;
|
||||
if (!confirm('Удалить оборудование?')) return;
|
||||
try {
|
||||
await api.delete('/api/equipments/' + btn.dataset.id);
|
||||
loadEquipments();
|
||||
} catch (e) {
|
||||
alert(e.message || 'Ошибка удаления');
|
||||
}
|
||||
});
|
||||
|
||||
loadEquipments();
|
||||
}
|
||||
@@ -1,6 +1,14 @@
|
||||
import { api } from '../api.js';
|
||||
import { escapeHtml, showAlert, hideAlert } from '../utils.js';
|
||||
import { fetchEducationForms } from './edu-forms.js';
|
||||
|
||||
async function fetchEducationForms() {
|
||||
try {
|
||||
return await api.get('/api/education-forms');
|
||||
} catch (e) {
|
||||
console.error("Failed to fetch education forms", e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function initGroups() {
|
||||
const groupsTbody = document.getElementById('groups-tbody');
|
||||
@@ -10,6 +18,8 @@ export async function initGroups() {
|
||||
const newGroupSpecialitySelect = document.getElementById('new-group-speciality-code');
|
||||
const newGroupProfileSelect = document.getElementById('new-group-profile');
|
||||
const filterEfSelect = document.getElementById('filter-ef');
|
||||
|
||||
// Модалка группы
|
||||
const modalEditGroup = document.getElementById('modal-edit-group');
|
||||
const modalEditGroupClose = document.getElementById('modal-edit-group-close');
|
||||
const editGroupForm = document.getElementById('edit-group-form');
|
||||
@@ -17,19 +27,30 @@ export async function initGroups() {
|
||||
const editGroupDepartmentSelect = document.getElementById('edit-group-department');
|
||||
const editGroupSpecialitySelect = document.getElementById('edit-group-speciality-code');
|
||||
const editGroupProfileSelect = document.getElementById('edit-group-profile');
|
||||
const calendarForm = document.getElementById('group-calendar-form');
|
||||
const calendarGroupSelect = document.getElementById('calendar-group');
|
||||
const calendarYearSelect = document.getElementById('calendar-year');
|
||||
const calendarSelect = document.getElementById('calendar-id');
|
||||
const calendarAssignmentsTbody = document.getElementById('group-calendar-tbody');
|
||||
const subgroupForm = document.getElementById('subgroup-form');
|
||||
const subgroupIdInput = document.getElementById('subgroup-id');
|
||||
const subgroupGroupSelect = document.getElementById('subgroup-group');
|
||||
const subgroupNameInput = document.getElementById('subgroup-name');
|
||||
const subgroupCapacityInput = document.getElementById('subgroup-capacity');
|
||||
const subgroupSubmitButton = document.getElementById('subgroup-submit');
|
||||
const subgroupResetButton = document.getElementById('subgroup-reset');
|
||||
const subgroupsTbody = document.getElementById('subgroups-tbody');
|
||||
|
||||
// Модалка подгрупп
|
||||
const modalManageSubgroups = document.getElementById('modal-manage-subgroups');
|
||||
const modalManageSubgroupsClose = document.getElementById('modal-manage-subgroups-close');
|
||||
const subgroupsGroupContext = document.getElementById('subgroups-group-context');
|
||||
const subgroupFormTitle = document.getElementById('subgroup-form-title');
|
||||
const manageSubgroupForm = document.getElementById('manage-subgroup-form');
|
||||
const manageSubgroupIdInput = document.getElementById('manage-subgroup-id');
|
||||
const manageSubgroupGroupIdInput = document.getElementById('manage-subgroup-group-id');
|
||||
const manageSubgroupNameInput = document.getElementById('manage-subgroup-name');
|
||||
const manageSubgroupCapacityInput = document.getElementById('manage-subgroup-capacity');
|
||||
const btnSaveSubgroup = document.getElementById('btn-save-subgroup');
|
||||
const btnCancelSubgroupEdit = document.getElementById('btn-cancel-subgroup-edit');
|
||||
const manageSubgroupsTbody = document.getElementById('manage-subgroups-tbody');
|
||||
|
||||
// Модалка календарей
|
||||
const modalManageCalendar = document.getElementById('modal-manage-calendar');
|
||||
const modalManageCalendarClose = document.getElementById('modal-manage-calendar-close');
|
||||
const calendarGroupContext = document.getElementById('calendar-group-context');
|
||||
const manageCalendarForm = document.getElementById('manage-calendar-form');
|
||||
const manageCalendarGroupIdInput = document.getElementById('manage-calendar-group-id');
|
||||
const manageCalendarYearSelect = document.getElementById('manage-calendar-year');
|
||||
const manageCalendarSelect = document.getElementById('manage-calendar-id');
|
||||
const manageCalendarTbody = document.getElementById('manage-calendar-tbody');
|
||||
|
||||
let allGroups = [];
|
||||
let subgroups = [];
|
||||
@@ -48,25 +69,35 @@ export async function initGroups() {
|
||||
filterEfSelect.addEventListener('change', applyGroupFilter);
|
||||
newGroupSpecialitySelect.addEventListener('change', () => populateProfileSelect(newGroupProfileSelect, newGroupSpecialitySelect.value));
|
||||
editGroupSpecialitySelect.addEventListener('change', () => populateProfileSelect(editGroupProfileSelect, editGroupSpecialitySelect.value));
|
||||
calendarGroupSelect.addEventListener('change', () => {
|
||||
populateCalendarSelect();
|
||||
loadAssignments();
|
||||
});
|
||||
calendarYearSelect.addEventListener('change', populateCalendarSelect);
|
||||
|
||||
createGroupForm.addEventListener('submit', createGroup);
|
||||
editGroupForm.addEventListener('submit', updateGroup);
|
||||
calendarForm.addEventListener('submit', saveAssignment);
|
||||
subgroupForm.addEventListener('submit', saveSubgroup);
|
||||
subgroupGroupSelect.addEventListener('change', renderSubgroups);
|
||||
subgroupResetButton.addEventListener('click', resetSubgroupForm);
|
||||
|
||||
// Модалка подгрупп
|
||||
manageSubgroupForm.addEventListener('submit', saveSubgroup);
|
||||
btnCancelSubgroupEdit.addEventListener('click', resetSubgroupForm);
|
||||
manageSubgroupsTbody.addEventListener('click', handleSubgroupTableClick);
|
||||
|
||||
// Модалка календарей
|
||||
manageCalendarForm.addEventListener('submit', saveAssignment);
|
||||
manageCalendarYearSelect.addEventListener('change', populateCalendarSelect);
|
||||
|
||||
groupsTbody.addEventListener('click', handleGroupTableClick);
|
||||
subgroupsTbody.addEventListener('click', handleSubgroupTableClick);
|
||||
calendarAssignmentsTbody.addEventListener('click', handleAssignmentTableClick);
|
||||
|
||||
// Закрытие модалок
|
||||
modalEditGroupClose.addEventListener('click', () => modalEditGroup.classList.remove('open'));
|
||||
modalEditGroup.addEventListener('click', (event) => {
|
||||
if (event.target === modalEditGroup) {
|
||||
modalEditGroup.classList.remove('open');
|
||||
}
|
||||
if (event.target === modalEditGroup) modalEditGroup.classList.remove('open');
|
||||
});
|
||||
|
||||
modalManageSubgroupsClose.addEventListener('click', () => modalManageSubgroups.classList.remove('open'));
|
||||
modalManageSubgroups.addEventListener('click', (event) => {
|
||||
if (event.target === modalManageSubgroups) modalManageSubgroups.classList.remove('open');
|
||||
});
|
||||
|
||||
modalManageCalendarClose.addEventListener('click', () => modalManageCalendar.classList.remove('open'));
|
||||
modalManageCalendar.addEventListener('click', (event) => {
|
||||
if (event.target === modalManageCalendar) modalManageCalendar.classList.remove('open');
|
||||
});
|
||||
}
|
||||
|
||||
@@ -84,12 +115,10 @@ export async function initGroups() {
|
||||
populateDepartmentSelects(departments);
|
||||
populateSpecialitySelects(specialties);
|
||||
populateYearSelect();
|
||||
populateCalendarSelect();
|
||||
await loadGroups();
|
||||
await loadSubgroups();
|
||||
} catch (error) {
|
||||
groupsTbody.innerHTML = `<tr><td colspan="10" class="loading-row">Ошибка загрузки данных: ${escapeHtml(error.message)}</td></tr>`;
|
||||
subgroupsTbody.innerHTML = `<tr><td colspan="4" class="loading-row">Ошибка загрузки данных: ${escapeHtml(error.message)}</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,9 +134,6 @@ export async function initGroups() {
|
||||
try {
|
||||
allGroups = await api.get('/api/groups?includeArchived=true');
|
||||
applyGroupFilter();
|
||||
populateGroupSelect();
|
||||
populateSubgroupGroupSelect();
|
||||
await loadAssignments();
|
||||
} catch (error) {
|
||||
groupsTbody.innerHTML = `<tr><td colspan="10" class="loading-row">Ошибка загрузки: ${escapeHtml(error.message)}</td></tr>`;
|
||||
}
|
||||
@@ -116,9 +142,8 @@ export async function initGroups() {
|
||||
async function loadSubgroups() {
|
||||
try {
|
||||
subgroups = await api.get('/api/subgroups');
|
||||
renderSubgroups();
|
||||
} catch (error) {
|
||||
subgroupsTbody.innerHTML = `<tr><td colspan="4" class="loading-row">Ошибка загрузки: ${escapeHtml(error.message)}</td></tr>`;
|
||||
console.error("Failed to load subgroups", error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,7 +163,7 @@ export async function initGroups() {
|
||||
groupsTbody.innerHTML = groups.map(group => `
|
||||
<tr>
|
||||
<td>${group.id}</td>
|
||||
<td>${escapeHtml(group.name)}</td>
|
||||
<td><strong>${escapeHtml(group.name)}</strong></td>
|
||||
<td>${escapeHtml(String(group.groupSize))}</td>
|
||||
<td><span class="badge badge-ef">${escapeHtml(group.educationFormName)}</span></td>
|
||||
<td>${escapeHtml(departmentLabel(group.departmentId))}</td>
|
||||
@@ -146,11 +171,13 @@ export async function initGroups() {
|
||||
<td>${escapeHtml(specialityLabel(group.specialtyId || group.specialityCode))}</td>
|
||||
<td>${escapeHtml(group.specialtyProfileName || '-')}</td>
|
||||
<td><span class="badge ${statusBadgeClass(group)}">${escapeHtml(statusLabel(group))}</span></td>
|
||||
<td style="text-align: right;">
|
||||
<td style="text-align: right; white-space: nowrap;">
|
||||
<button class="btn-edit-classroom btn-edit-group" data-id="${group.id}">Изменить</button>
|
||||
<button class="btn-primary btn-manage-subgroups" data-id="${group.id}" style="padding: 0.25rem 0.5rem; font-size: 0.85rem;">Подгруппы</button>
|
||||
<button class="btn-primary btn-manage-calendar" data-id="${group.id}" style="padding: 0.25rem 0.5rem; font-size: 0.85rem;">Календарь</button>
|
||||
${group.status === 'ARCHIVED'
|
||||
? `<button class="btn-restore-group" data-id="${group.id}" style="margin-left: 0.5rem;">Восстановить</button>`
|
||||
: `<button class="btn-delete" data-id="${group.id}" style="margin-left: 0.5rem;">Архивировать</button>`}
|
||||
: `<button class="btn-delete" data-id="${group.id}" style="margin-left: 0.5rem;">Архив</button>`}
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
@@ -225,43 +252,18 @@ export async function initGroups() {
|
||||
}
|
||||
|
||||
function populateYearSelect() {
|
||||
calendarYearSelect.innerHTML = '<option value="">Выберите учебный год</option>' +
|
||||
manageCalendarYearSelect.innerHTML = '<option value="">Выберите учебный год</option>' +
|
||||
academicYears.map(year => `<option value="${year.id}">${escapeHtml(year.title)}</option>`).join('');
|
||||
if (!calendarYearSelect.value && academicYears.length) {
|
||||
calendarYearSelect.value = String(academicYears[0].id);
|
||||
if (academicYears.length) {
|
||||
manageCalendarYearSelect.value = String(academicYears[0].id);
|
||||
}
|
||||
syncSelects(calendarYearSelect);
|
||||
}
|
||||
|
||||
function populateGroupSelect() {
|
||||
const current = calendarGroupSelect.value;
|
||||
const availableGroups = allGroups.filter(group => group.active);
|
||||
calendarGroupSelect.innerHTML = '<option value="">Выберите группу</option>' +
|
||||
availableGroups.map(group => `<option value="${group.id}">${escapeHtml(group.name)}</option>`).join('');
|
||||
if (current && availableGroups.some(group => String(group.id) === String(current))) {
|
||||
calendarGroupSelect.value = current;
|
||||
} else if (availableGroups.length) {
|
||||
calendarGroupSelect.value = String(availableGroups[0].id);
|
||||
}
|
||||
syncSelects(calendarGroupSelect);
|
||||
}
|
||||
|
||||
function populateSubgroupGroupSelect() {
|
||||
const current = subgroupGroupSelect.value;
|
||||
const availableGroups = allGroups.filter(group => group.active);
|
||||
subgroupGroupSelect.innerHTML = '<option value="">Выберите группу</option>' +
|
||||
availableGroups.map(group => `<option value="${group.id}">${escapeHtml(group.name)}</option>`).join('');
|
||||
if (current && availableGroups.some(group => String(group.id) === String(current))) {
|
||||
subgroupGroupSelect.value = current;
|
||||
} else if (availableGroups.length) {
|
||||
subgroupGroupSelect.value = String(availableGroups[0].id);
|
||||
}
|
||||
syncSelects(subgroupGroupSelect);
|
||||
syncSelects(manageCalendarYearSelect);
|
||||
}
|
||||
|
||||
function populateCalendarSelect() {
|
||||
const group = selectedCalendarGroup();
|
||||
const yearId = calendarYearSelect.value;
|
||||
const groupId = manageCalendarGroupIdInput.value;
|
||||
const group = allGroups.find(g => g.id == groupId);
|
||||
const yearId = manageCalendarYearSelect.value;
|
||||
const matching = group && yearId
|
||||
? calendars.filter(calendar =>
|
||||
String(calendar.academicYearId) === String(yearId)
|
||||
@@ -270,12 +272,12 @@ export async function initGroups() {
|
||||
&& String(calendar.studyFormId) === String(group.educationFormId)
|
||||
)
|
||||
: [];
|
||||
calendarSelect.innerHTML = matching.length
|
||||
manageCalendarSelect.innerHTML = matching.length
|
||||
? '<option value="">Выберите график</option>' + matching.map(calendar =>
|
||||
`<option value="${calendar.id}">${escapeHtml(calendar.title)}</option>`
|
||||
).join('')
|
||||
: '<option value="">Нет подходящих графиков</option>';
|
||||
syncSelects(calendarSelect);
|
||||
syncSelects(manageCalendarSelect);
|
||||
}
|
||||
|
||||
async function createGroup(event) {
|
||||
@@ -290,7 +292,6 @@ export async function initGroups() {
|
||||
createGroupForm.reset();
|
||||
syncSelects(newGroupEfSelect, newGroupDepartmentSelect, newGroupSpecialitySelect, newGroupProfileSelect);
|
||||
await loadGroups();
|
||||
await loadSubgroups();
|
||||
} catch (error) {
|
||||
showAlert('create-group-alert', error.message || 'Ошибка создания', 'error');
|
||||
}
|
||||
@@ -308,7 +309,6 @@ export async function initGroups() {
|
||||
modalEditGroup.classList.remove('open');
|
||||
showAlert('create-group-alert', `Группа "${escapeHtml(data.name || payload.name)}" обновлена`, 'success');
|
||||
await loadGroups();
|
||||
await loadSubgroups();
|
||||
} catch (error) {
|
||||
showAlert('edit-group-alert', error.message || 'Ошибка обновления', 'error');
|
||||
}
|
||||
@@ -348,13 +348,14 @@ export async function initGroups() {
|
||||
const btnDelete = event.target.closest('.btn-delete');
|
||||
const btnEdit = event.target.closest('.btn-edit-group');
|
||||
const btnRestore = event.target.closest('.btn-restore-group');
|
||||
const btnSubgroups = event.target.closest('.btn-manage-subgroups');
|
||||
const btnCalendar = event.target.closest('.btn-manage-calendar');
|
||||
|
||||
if (btnDelete) {
|
||||
if (!confirm('Архивировать группу? История расписания сохранится.')) return;
|
||||
try {
|
||||
await api.delete('/api/groups/' + btnDelete.dataset.id);
|
||||
await loadGroups();
|
||||
await loadSubgroups();
|
||||
} catch (error) {
|
||||
alert(error.message || 'Ошибка архивирования');
|
||||
}
|
||||
@@ -364,7 +365,6 @@ export async function initGroups() {
|
||||
try {
|
||||
await api.post('/api/groups/' + btnRestore.dataset.id + '/restore', {});
|
||||
await loadGroups();
|
||||
await loadSubgroups();
|
||||
} catch (error) {
|
||||
alert(error.message || 'Ошибка восстановления');
|
||||
}
|
||||
@@ -373,6 +373,18 @@ export async function initGroups() {
|
||||
if (btnEdit) {
|
||||
openEditGroupModal(btnEdit.dataset.id);
|
||||
}
|
||||
|
||||
if (btnSubgroups) {
|
||||
const groupId = btnSubgroups.dataset.id;
|
||||
const group = allGroups.find(g => g.id == groupId);
|
||||
if (group) openSubgroupsModal(group);
|
||||
}
|
||||
|
||||
if (btnCalendar) {
|
||||
const groupId = btnCalendar.dataset.id;
|
||||
const group = allGroups.find(g => g.id == groupId);
|
||||
if (group) openCalendarModal(group);
|
||||
}
|
||||
}
|
||||
|
||||
function openEditGroupModal(id) {
|
||||
@@ -395,21 +407,59 @@ export async function initGroups() {
|
||||
modalEditGroup.classList.add('open');
|
||||
}
|
||||
|
||||
// --- Управление подгруппами ---
|
||||
function openSubgroupsModal(group) {
|
||||
subgroupsGroupContext.textContent = `Группа: ${group.name} (${group.groupSize} чел.)`;
|
||||
manageSubgroupGroupIdInput.value = group.id;
|
||||
resetSubgroupForm();
|
||||
modalManageSubgroups.classList.add('open');
|
||||
renderSubgroupsList(group.id);
|
||||
}
|
||||
|
||||
function renderSubgroupsList(groupId) {
|
||||
const list = subgroups.filter(sub => String(sub.groupId) === String(groupId));
|
||||
if (!list.length) {
|
||||
manageSubgroupsTbody.innerHTML = '<tr><td colspan="3" class="loading-row">Подгруппы не созданы</td></tr>';
|
||||
return;
|
||||
}
|
||||
manageSubgroupsTbody.innerHTML = list.map(sub => `
|
||||
<tr>
|
||||
<td>${escapeHtml(sub.name)}</td>
|
||||
<td>${escapeHtml(String(sub.studentCapacity ?? '-'))} чел.</td>
|
||||
<td>
|
||||
<button class="btn-edit-classroom btn-edit-subgroup" data-id="${sub.id}">Изменить</button>
|
||||
<button class="btn-delete btn-delete-subgroup" data-id="${sub.id}">Удалить</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
function resetSubgroupForm() {
|
||||
manageSubgroupIdInput.value = '';
|
||||
manageSubgroupNameInput.value = '';
|
||||
manageSubgroupCapacityInput.value = '';
|
||||
subgroupFormTitle.textContent = 'Создание подгруппы';
|
||||
btnSaveSubgroup.textContent = 'Создать';
|
||||
btnCancelSubgroupEdit.style.display = 'none';
|
||||
hideAlert('manage-subgroup-alert');
|
||||
}
|
||||
|
||||
async function saveSubgroup(event) {
|
||||
event.preventDefault();
|
||||
hideAlert('subgroup-alert');
|
||||
const groupId = subgroupGroupSelect.value;
|
||||
const name = subgroupNameInput.value.trim();
|
||||
const capacity = subgroupCapacityInput.value;
|
||||
const subgroupId = subgroupIdInput.value;
|
||||
hideAlert('manage-subgroup-alert');
|
||||
const groupId = manageSubgroupGroupIdInput.value;
|
||||
const subgroupId = manageSubgroupIdInput.value;
|
||||
const name = manageSubgroupNameInput.value.trim();
|
||||
const capacity = manageSubgroupCapacityInput.value;
|
||||
|
||||
if (!groupId) { showAlert('subgroup-alert', 'Выберите группу', 'error'); return; }
|
||||
if (!name) { showAlert('subgroup-alert', 'Введите название подгруппы', 'error'); return; }
|
||||
if (capacity && Number(capacity) < 0) { showAlert('subgroup-alert', 'Численность не может быть отрицательной', 'error'); return; }
|
||||
if (!name || !capacity) {
|
||||
showAlert('manage-subgroup-alert', 'Заполните все поля', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
name,
|
||||
studentCapacity: capacity ? Number(capacity) : null
|
||||
studentCapacity: Number(capacity)
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -417,124 +467,74 @@ export async function initGroups() {
|
||||
const saved = subgroupId
|
||||
? await api.put(endpoint, payload)
|
||||
: await api.post(endpoint, payload);
|
||||
showAlert('subgroup-alert', `Подгруппа "${escapeHtml(saved.name)}" сохранена`, 'success');
|
||||
showAlert('manage-subgroup-alert', `Подгруппа "${escapeHtml(saved.name)}" сохранена`, 'success');
|
||||
resetSubgroupForm();
|
||||
await loadSubgroups();
|
||||
renderSubgroupsList(groupId);
|
||||
} catch (error) {
|
||||
showAlert('subgroup-alert', error.message || 'Ошибка сохранения подгруппы', 'error');
|
||||
showAlert('manage-subgroup-alert', error.message || 'Ошибка сохранения подгруппы', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function renderSubgroups() {
|
||||
const groupId = subgroupGroupSelect.value;
|
||||
const visibleSubgroups = groupId
|
||||
? subgroups.filter(subgroup => String(subgroup.groupId) === String(groupId))
|
||||
: subgroups;
|
||||
if (!visibleSubgroups.length) {
|
||||
subgroupsTbody.innerHTML = '<tr><td colspan="4" class="loading-row">Подгруппы не созданы</td></tr>';
|
||||
return;
|
||||
}
|
||||
subgroupsTbody.innerHTML = visibleSubgroups.map(subgroup => `
|
||||
<tr>
|
||||
<td>${escapeHtml(subgroup.groupName || groupName(subgroup.groupId))}</td>
|
||||
<td>${escapeHtml(subgroup.name)}</td>
|
||||
<td>${escapeHtml(String(subgroup.studentCapacity ?? '-'))}</td>
|
||||
<td>
|
||||
<button class="btn-edit-classroom btn-edit-subgroup" data-id="${subgroup.id}">Изменить</button>
|
||||
<button class="btn-delete btn-delete-subgroup" data-id="${subgroup.id}">Удалить</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
async function handleSubgroupTableClick(event) {
|
||||
const editButton = event.target.closest('.btn-edit-subgroup');
|
||||
const deleteButton = event.target.closest('.btn-delete-subgroup');
|
||||
const groupId = manageSubgroupGroupIdInput.value;
|
||||
|
||||
if (editButton) {
|
||||
const subgroup = subgroups.find(item => String(item.id) === String(editButton.dataset.id));
|
||||
const subgroup = subgroups.find(item => item.id == editButton.dataset.id);
|
||||
if (!subgroup) return;
|
||||
subgroupIdInput.value = subgroup.id;
|
||||
subgroupGroupSelect.value = subgroup.groupId;
|
||||
subgroupGroupSelect.disabled = true;
|
||||
subgroupNameInput.value = subgroup.name || '';
|
||||
subgroupCapacityInput.value = subgroup.studentCapacity ?? '';
|
||||
subgroupSubmitButton.textContent = 'Сохранить подгруппу';
|
||||
syncSelects(subgroupGroupSelect);
|
||||
hideAlert('subgroup-alert');
|
||||
|
||||
manageSubgroupIdInput.value = subgroup.id;
|
||||
manageSubgroupNameInput.value = subgroup.name || '';
|
||||
manageSubgroupCapacityInput.value = subgroup.studentCapacity ?? '';
|
||||
subgroupFormTitle.textContent = 'Редактирование подгруппы';
|
||||
btnSaveSubgroup.textContent = 'Сохранить';
|
||||
btnCancelSubgroupEdit.style.display = 'inline-block';
|
||||
hideAlert('manage-subgroup-alert');
|
||||
return;
|
||||
}
|
||||
|
||||
if (deleteButton) {
|
||||
const subgroup = subgroups.find(item => String(item.id) === String(deleteButton.dataset.id));
|
||||
if (!subgroup || !confirm('Удалить подгруппу?')) return;
|
||||
if (!confirm('Удалить подгруппу?')) return;
|
||||
try {
|
||||
await api.delete(`/api/groups/${subgroup.groupId}/subgroups/${subgroup.id}`);
|
||||
showAlert('subgroup-alert', 'Подгруппа удалена', 'success');
|
||||
await api.delete(`/api/groups/${groupId}/subgroups/${deleteButton.dataset.id}`);
|
||||
showAlert('manage-subgroup-alert', 'Подгруппа удалена', 'success');
|
||||
resetSubgroupForm();
|
||||
await loadSubgroups();
|
||||
renderSubgroupsList(groupId);
|
||||
} catch (error) {
|
||||
showAlert('subgroup-alert', error.message || 'Ошибка удаления подгруппы', 'error');
|
||||
showAlert('manage-subgroup-alert', error.message || 'Ошибка удаления подгруппы', 'error');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function resetSubgroupForm() {
|
||||
subgroupIdInput.value = '';
|
||||
subgroupNameInput.value = '';
|
||||
subgroupCapacityInput.value = '';
|
||||
subgroupGroupSelect.disabled = false;
|
||||
subgroupSubmitButton.textContent = 'Создать подгруппу';
|
||||
syncSelects(subgroupGroupSelect);
|
||||
hideAlert('subgroup-alert');
|
||||
// --- Управление календарными графиками ---
|
||||
async function openCalendarModal(group) {
|
||||
calendarGroupContext.textContent = `Группа: ${group.name} (${specialityLabel(group.specialtyId || group.specialityCode)})`;
|
||||
manageCalendarGroupIdInput.value = group.id;
|
||||
hideAlert('manage-calendar-alert');
|
||||
populateCalendarSelect();
|
||||
modalManageCalendar.classList.add('open');
|
||||
await loadAssignmentsList(group.id);
|
||||
}
|
||||
|
||||
async function saveAssignment(event) {
|
||||
event.preventDefault();
|
||||
hideAlert('group-calendar-alert');
|
||||
const groupId = calendarGroupSelect.value;
|
||||
const academicYearId = calendarYearSelect.value;
|
||||
const calendarId = calendarSelect.value;
|
||||
|
||||
if (!groupId || !academicYearId || !calendarId) {
|
||||
showAlert('group-calendar-alert', 'Выберите группу, учебный год и график', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await api.put(`/api/groups/${groupId}/calendar-assignments`, {
|
||||
academicYearId: Number(academicYearId),
|
||||
calendarId: Number(calendarId)
|
||||
});
|
||||
showAlert('group-calendar-alert', 'Календарный график назначен', 'success');
|
||||
await loadAssignments();
|
||||
} catch (error) {
|
||||
showAlert('group-calendar-alert', error.message || 'Ошибка назначения графика', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAssignments() {
|
||||
const groupId = calendarGroupSelect.value;
|
||||
if (!groupId) {
|
||||
currentAssignments = [];
|
||||
calendarAssignmentsTbody.innerHTML = '<tr><td colspan="3" class="loading-row">Выберите группу</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
async function loadAssignmentsList(groupId) {
|
||||
manageCalendarTbody.innerHTML = '<tr><td colspan="3" class="loading-row">Загрузка...</td></tr>';
|
||||
try {
|
||||
currentAssignments = await api.get(`/api/groups/${groupId}/calendar-assignments`);
|
||||
renderAssignments();
|
||||
renderAssignmentsList();
|
||||
} catch (error) {
|
||||
calendarAssignmentsTbody.innerHTML = `<tr><td colspan="3" class="loading-row">Ошибка загрузки: ${escapeHtml(error.message)}</td></tr>`;
|
||||
manageCalendarTbody.innerHTML = `<tr><td colspan="3" class="loading-row">Ошибка: ${escapeHtml(error.message)}</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderAssignments() {
|
||||
function renderAssignmentsList() {
|
||||
if (!currentAssignments.length) {
|
||||
calendarAssignmentsTbody.innerHTML = '<tr><td colspan="3" class="loading-row">Графики не назначены</td></tr>';
|
||||
manageCalendarTbody.innerHTML = '<tr><td colspan="3" class="loading-row">Календарные графики не назначены</td></tr>';
|
||||
return;
|
||||
}
|
||||
calendarAssignmentsTbody.innerHTML = currentAssignments.map(assignment => `
|
||||
manageCalendarTbody.innerHTML = currentAssignments.map(assignment => `
|
||||
<tr>
|
||||
<td>${escapeHtml(assignment.academicYearTitle)}</td>
|
||||
<td>${escapeHtml(assignment.calendarTitle)}</td>
|
||||
@@ -545,35 +545,53 @@ export async function initGroups() {
|
||||
`).join('');
|
||||
}
|
||||
|
||||
async function handleAssignmentTableClick(event) {
|
||||
const deleteButton = event.target.closest('.btn-delete-assignment');
|
||||
if (!deleteButton) return;
|
||||
if (!confirm('Удалить назначение графика?')) return;
|
||||
async function saveAssignment(event) {
|
||||
event.preventDefault();
|
||||
hideAlert('manage-calendar-alert');
|
||||
const groupId = manageCalendarGroupIdInput.value;
|
||||
const academicYearId = manageCalendarYearSelect.value;
|
||||
const calendarId = manageCalendarSelect.value;
|
||||
|
||||
if (!academicYearId || !calendarId) {
|
||||
showAlert('manage-calendar-alert', 'Выберите учебный год и график', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await api.delete(`/api/groups/${calendarGroupSelect.value}/calendar-assignments/${deleteButton.dataset.id}`);
|
||||
showAlert('group-calendar-alert', 'Назначение удалено', 'success');
|
||||
await loadAssignments();
|
||||
await api.put(`/api/groups/${groupId}/calendar-assignments`, {
|
||||
academicYearId: Number(academicYearId),
|
||||
calendarId: Number(calendarId)
|
||||
});
|
||||
showAlert('manage-calendar-alert', 'Календарный график назначен', 'success');
|
||||
await loadAssignmentsList(groupId);
|
||||
} catch (error) {
|
||||
showAlert('group-calendar-alert', error.message || 'Ошибка удаления назначения', 'error');
|
||||
showAlert('manage-calendar-alert', error.message || 'Ошибка назначения графика', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function selectedCalendarGroup() {
|
||||
return allGroups.find(group => String(group.id) === String(calendarGroupSelect.value));
|
||||
}
|
||||
manageCalendarTbody.addEventListener('click', async (event) => {
|
||||
const deleteButton = event.target.closest('.btn-delete-assignment');
|
||||
if (!deleteButton) return;
|
||||
if (!confirm('Удалить назначение графика?')) return;
|
||||
const groupId = manageCalendarGroupIdInput.value;
|
||||
|
||||
try {
|
||||
await api.delete(`/api/groups/${groupId}/calendar-assignments/${deleteButton.dataset.id}`);
|
||||
showAlert('manage-calendar-alert', 'Назначение удалено', 'success');
|
||||
await loadAssignmentsList(groupId);
|
||||
} catch (error) {
|
||||
showAlert('manage-calendar-alert', error.message || 'Ошибка удаления назначения', 'error');
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// --- Вспомогательные функции ---
|
||||
function departmentLabel(departmentId) {
|
||||
const department = departments.find(item => item.id == departmentId);
|
||||
if (!department) return departmentId || '-';
|
||||
return department.departmentName || department.name || departmentId;
|
||||
}
|
||||
|
||||
function groupName(groupId) {
|
||||
const group = allGroups.find(item => String(item.id) === String(groupId));
|
||||
return group ? group.name : groupId || '-';
|
||||
}
|
||||
|
||||
function specialityLabel(specialityId) {
|
||||
const speciality = specialties.find(item => item.id == specialityId);
|
||||
if (!speciality) return specialityId || '-';
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
import { api } from '../api.js';
|
||||
import { escapeHtml, showAlert, hideAlert } from '../utils.js';
|
||||
|
||||
export async function initProfiles() {
|
||||
const createProfileForm = document.getElementById('create-profile-form');
|
||||
const profileSpecialtySelect = document.getElementById('profile-specialty');
|
||||
const profileNameInput = document.getElementById('profile-name');
|
||||
const profileDescriptionInput = document.getElementById('profile-description');
|
||||
const profilesTbody = document.getElementById('profiles-tbody');
|
||||
const profilesContext = document.getElementById('profiles-context');
|
||||
const refreshButton = document.getElementById('profiles-refresh');
|
||||
const editProfileForm = document.getElementById('edit-profile-form');
|
||||
const editProfileModal = document.getElementById('modal-edit-profile');
|
||||
const editProfileClose = document.getElementById('modal-edit-profile-close');
|
||||
|
||||
let specialties = [];
|
||||
let profiles = [];
|
||||
|
||||
await loadSpecialties();
|
||||
|
||||
profileSpecialtySelect.addEventListener('change', loadProfiles);
|
||||
refreshButton.addEventListener('click', loadProfiles);
|
||||
|
||||
createProfileForm.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
hideAlert('create-profile-alert');
|
||||
|
||||
const specialtyId = profileSpecialtySelect.value;
|
||||
const name = profileNameInput.value.trim();
|
||||
const description = profileDescriptionInput.value.trim();
|
||||
|
||||
if (!specialtyId || !name) {
|
||||
showAlert('create-profile-alert', 'Выберите специальность и заполните название профиля', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await api.post(`/api/specialties/${specialtyId}/profiles`, { name, description });
|
||||
showAlert('create-profile-alert', `Профиль "${name}" создан`, 'success');
|
||||
createProfileForm.reset();
|
||||
profileSpecialtySelect.value = specialtyId;
|
||||
syncSelect(profileSpecialtySelect);
|
||||
await loadProfiles();
|
||||
} catch (error) {
|
||||
showAlert('create-profile-alert', error.message || 'Ошибка создания профиля', 'error');
|
||||
}
|
||||
});
|
||||
|
||||
profilesTbody.addEventListener('click', async (event) => {
|
||||
const editButton = event.target.closest('.btn-edit-profile');
|
||||
const deleteButton = event.target.closest('.btn-delete-profile');
|
||||
|
||||
if (editButton) {
|
||||
const profile = profiles.find(item => String(item.id) === String(editButton.dataset.id));
|
||||
if (!profile) return;
|
||||
|
||||
document.getElementById('edit-profile-id').value = profile.id;
|
||||
document.getElementById('edit-profile-name').value = profile.name || '';
|
||||
document.getElementById('edit-profile-description').value = profile.description || '';
|
||||
hideAlert('edit-profile-alert');
|
||||
editProfileModal.classList.add('open');
|
||||
return;
|
||||
}
|
||||
|
||||
if (deleteButton) {
|
||||
if (!confirm('Удалить профиль обучения?')) return;
|
||||
try {
|
||||
await api.delete(`/api/specialties/${profileSpecialtySelect.value}/profiles/${deleteButton.dataset.id}`);
|
||||
showAlert('create-profile-alert', 'Профиль удалён', 'success');
|
||||
await loadProfiles();
|
||||
} catch (error) {
|
||||
showAlert('create-profile-alert', error.message || 'Ошибка удаления профиля', 'error');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
editProfileForm.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
hideAlert('edit-profile-alert');
|
||||
|
||||
const specialtyId = profileSpecialtySelect.value;
|
||||
const id = document.getElementById('edit-profile-id').value;
|
||||
const name = document.getElementById('edit-profile-name').value.trim();
|
||||
const description = document.getElementById('edit-profile-description').value.trim();
|
||||
|
||||
if (!specialtyId || !id || !name) {
|
||||
showAlert('edit-profile-alert', 'Заполните название профиля', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await api.put(`/api/specialties/${specialtyId}/profiles/${id}`, { id: Number(id), name, description });
|
||||
editProfileModal.classList.remove('open');
|
||||
showAlert('create-profile-alert', `Профиль "${name}" обновлён`, 'success');
|
||||
await loadProfiles();
|
||||
} catch (error) {
|
||||
showAlert('edit-profile-alert', error.message || 'Ошибка обновления профиля', 'error');
|
||||
}
|
||||
});
|
||||
|
||||
editProfileClose.addEventListener('click', () => editProfileModal.classList.remove('open'));
|
||||
editProfileModal.addEventListener('click', (event) => {
|
||||
if (event.target === editProfileModal) {
|
||||
editProfileModal.classList.remove('open');
|
||||
}
|
||||
});
|
||||
|
||||
async function loadSpecialties() {
|
||||
profilesTbody.innerHTML = '<tr><td colspan="4" class="loading-row">Загрузка...</td></tr>';
|
||||
try {
|
||||
specialties = await api.get('/api/specialties');
|
||||
renderSpecialtySelect();
|
||||
await loadProfiles();
|
||||
} catch (error) {
|
||||
profileSpecialtySelect.innerHTML = '<option value="">Не удалось загрузить специальности</option>';
|
||||
profilesTbody.innerHTML = `<tr><td colspan="4" class="loading-row">Ошибка загрузки: ${escapeHtml(error.message)}</td></tr>`;
|
||||
syncSelect(profileSpecialtySelect);
|
||||
}
|
||||
}
|
||||
|
||||
function renderSpecialtySelect() {
|
||||
if (!specialties.length) {
|
||||
profileSpecialtySelect.innerHTML = '<option value="">Сначала создайте специальность</option>';
|
||||
syncSelect(profileSpecialtySelect);
|
||||
return;
|
||||
}
|
||||
|
||||
const current = profileSpecialtySelect.value;
|
||||
profileSpecialtySelect.innerHTML = '<option value="">Выберите специальность</option>' +
|
||||
specialties.map(specialty => {
|
||||
const code = specialty.specialityCode || specialty.specialtyCode || specialty.specialty_code || specialty.id;
|
||||
const name = specialty.specialityName || specialty.name || 'Без названия';
|
||||
return `<option value="${specialty.id}">${escapeHtml(code)} — ${escapeHtml(name)}</option>`;
|
||||
}).join('');
|
||||
|
||||
if (current && specialties.some(specialty => String(specialty.id) === String(current))) {
|
||||
profileSpecialtySelect.value = current;
|
||||
} else {
|
||||
profileSpecialtySelect.value = String(specialties[0].id);
|
||||
}
|
||||
syncSelect(profileSpecialtySelect);
|
||||
}
|
||||
|
||||
async function loadProfiles() {
|
||||
const specialtyId = profileSpecialtySelect.value;
|
||||
const specialty = specialties.find(item => String(item.id) === String(specialtyId));
|
||||
profilesContext.textContent = specialty ? specialtyLabel(specialty) : '';
|
||||
|
||||
if (!specialtyId) {
|
||||
profiles = [];
|
||||
profilesTbody.innerHTML = '<tr><td colspan="4" class="loading-row">Выберите специальность</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
profilesTbody.innerHTML = '<tr><td colspan="4" class="loading-row">Загрузка...</td></tr>';
|
||||
try {
|
||||
profiles = await api.get(`/api/specialties/${specialtyId}/profiles`);
|
||||
renderProfiles();
|
||||
} catch (error) {
|
||||
profilesTbody.innerHTML = `<tr><td colspan="4" class="loading-row">Ошибка загрузки: ${escapeHtml(error.message)}</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderProfiles() {
|
||||
if (!profiles.length) {
|
||||
profilesTbody.innerHTML = '<tr><td colspan="4" class="loading-row">Профили не созданы</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
profilesTbody.innerHTML = profiles.map(profile => `
|
||||
<tr>
|
||||
<td>${profile.id}</td>
|
||||
<td>${escapeHtml(profile.name)}</td>
|
||||
<td>${escapeHtml(profile.description || '-')}</td>
|
||||
<td>
|
||||
<button class="btn-edit-classroom btn-edit-profile" data-id="${profile.id}">Изменить</button>
|
||||
<button class="btn-delete btn-delete-profile" data-id="${profile.id}">Удалить</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
function specialtyLabel(specialty) {
|
||||
const code = specialty.specialityCode || specialty.specialtyCode || specialty.specialty_code || specialty.id;
|
||||
const name = specialty.specialityName || specialty.name || 'Без названия';
|
||||
return `${code} · ${name}`;
|
||||
}
|
||||
|
||||
function syncSelect(select) {
|
||||
select.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
}
|
||||
}
|
||||
@@ -451,9 +451,6 @@ export async function initScheduleView() {
|
||||
<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 => `
|
||||
@@ -597,6 +594,40 @@ export async function initScheduleView() {
|
||||
.join(',');
|
||||
}
|
||||
|
||||
function getLessonWeeksText(lesson) {
|
||||
if (!lesson || lesson.weekNumber == null || lesson.lessonTypeAcademicHours == null) {
|
||||
return '';
|
||||
}
|
||||
const totalHours = lesson.lessonTypeAcademicHours;
|
||||
const consumedBefore = lesson.consumedLessonTypeAcademicHoursBeforeLesson || 0;
|
||||
|
||||
// Каждое занятие - это 2 часа
|
||||
const totalLessons = Math.ceil(totalHours / 2);
|
||||
if (totalLessons <= 0) return '';
|
||||
|
||||
const parity = lesson.ruleParity || lesson.parity;
|
||||
let startWeek, endWeek;
|
||||
|
||||
if (parity === 'EVEN' || parity === 'ODD') {
|
||||
// Раз в две недели
|
||||
startWeek = lesson.weekNumber - consumedBefore;
|
||||
endWeek = startWeek + (totalLessons - 1) * 2;
|
||||
} else {
|
||||
// Каждую неделю
|
||||
const steps = Math.floor(consumedBefore / 2);
|
||||
startWeek = lesson.weekNumber - steps;
|
||||
endWeek = startWeek + totalLessons - 1;
|
||||
}
|
||||
|
||||
if (startWeek <= 0) startWeek = 1;
|
||||
if (endWeek < startWeek) endWeek = startWeek;
|
||||
|
||||
if (startWeek === endWeek) {
|
||||
return `${startWeek} нед.`;
|
||||
}
|
||||
return `с ${startWeek} по ${endWeek} нед.`;
|
||||
}
|
||||
|
||||
function renderLessonCard(lesson) {
|
||||
const subgroupText = (lesson.subgroupNames || []).join(', ');
|
||||
const meta = [
|
||||
@@ -605,9 +636,15 @@ export async function initScheduleView() {
|
||||
PARITY_LABELS[lesson.parity] || lesson.parity
|
||||
].filter(Boolean).join(' · ');
|
||||
|
||||
const weeksText = getLessonWeeksText(lesson);
|
||||
const weeksBadge = weeksText ? `<span class="lesson-weeks-badge">${escapeHtml(weeksText)}</span>` : '';
|
||||
|
||||
return `
|
||||
<div class="lesson-card schedule-view-lesson-card">
|
||||
<div class="lesson-subject">${escapeHtml(lesson.subjectName || 'Без дисциплины')}</div>
|
||||
<div class="lesson-subject" style="display: flex; justify-content: space-between; align-items: baseline; gap: 0.5rem;">
|
||||
<span>${escapeHtml(lesson.subjectName || 'Без дисциплины')}</span>
|
||||
${weeksBadge}
|
||||
</div>
|
||||
<div class="lesson-group">${escapeHtml((lesson.groupNames || []).join(', ') || 'Группа не указана')}</div>
|
||||
${subgroupText ? `<div class="lesson-subgroup">${escapeHtml(subgroupText)}</div>` : ''}
|
||||
<div class="lesson-teacher">${escapeHtml(lesson.teacherName || 'Преподаватель не указан')}</div>
|
||||
@@ -895,26 +932,15 @@ function parityForDate(date, lessons) {
|
||||
}
|
||||
|
||||
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('; ');
|
||||
return 'Нечётная и чётная недели';
|
||||
}
|
||||
|
||||
function mobileDayCaption(datesByParity) {
|
||||
return CELL_PARITY_LAYOUT
|
||||
.map(({ parity, label }) => {
|
||||
const date = datesByParity?.[parity];
|
||||
return `${label}: ${date ? formatDate(date) : 'даты нет'}`;
|
||||
})
|
||||
.join(' · ');
|
||||
return 'Нечётная / Чётная';
|
||||
}
|
||||
|
||||
function periodCaption(range) {
|
||||
return `${formatDate(range.startDate)} - ${formatDate(range.endDate)}`;
|
||||
return 'Учебное расписание';
|
||||
}
|
||||
|
||||
function lessonSlotKey(lesson) {
|
||||
|
||||
@@ -4,160 +4,260 @@ import { escapeHtml, showAlert, hideAlert } from '../utils.js';
|
||||
export async function initSubjects() {
|
||||
const subjectsTbody = document.getElementById('subjects-tbody');
|
||||
const createSubjectForm = document.getElementById('create-subject-form');
|
||||
const newSubjectDeptSelect = document.getElementById('new-subject-department');
|
||||
|
||||
const assignTeacherForm = document.getElementById('assign-teacher-form');
|
||||
const assignTeacherSelect = document.getElementById('assign-teacher-select');
|
||||
const assignSubjectSelect = document.getElementById('assign-subject-select');
|
||||
const teacherSubjectsTbody = document.getElementById('teacher-subjects-tbody');
|
||||
// Модалка управления преподавателями
|
||||
const modalManageTeachers = document.getElementById('modal-manage-teachers');
|
||||
const modalManageTeachersClose = document.getElementById('modal-manage-teachers-close');
|
||||
const subjectTeachersContext = document.getElementById('subject-teachers-context');
|
||||
const manageTeacherSubjectForm = document.getElementById('manage-teacher-subject-form');
|
||||
const manageTsSubjectIdInput = document.getElementById('manage-ts-subject-id');
|
||||
const manageTsTeacherSelect = document.getElementById('manage-ts-teacher-select');
|
||||
const manageTsTbody = document.getElementById('manage-ts-tbody');
|
||||
|
||||
let allSubjects = [];
|
||||
let allTeachers = [];
|
||||
let allDepartments = [];
|
||||
let teacherSubjects = [];
|
||||
|
||||
bindEvents();
|
||||
await loadInitialData();
|
||||
|
||||
function bindEvents() {
|
||||
createSubjectForm.addEventListener('submit', createSubject);
|
||||
subjectsTbody.addEventListener('click', handleSubjectsTableClick);
|
||||
|
||||
manageTeacherSubjectForm.addEventListener('submit', saveTeacherAssignment);
|
||||
manageTsTbody.addEventListener('click', handleTeacherAssignmentTableClick);
|
||||
|
||||
modalManageTeachersClose.addEventListener('click', () => modalManageTeachers.classList.remove('open'));
|
||||
modalManageTeachers.addEventListener('click', (e) => {
|
||||
if (e.target === modalManageTeachers) modalManageTeachers.classList.remove('open');
|
||||
});
|
||||
}
|
||||
|
||||
async function loadInitialData() {
|
||||
await Promise.all([loadSubjects(), loadTeachers()]);
|
||||
await loadTeacherSubjects();
|
||||
try {
|
||||
[allTeachers, allDepartments] = await Promise.all([
|
||||
api.get('/api/users/teachers'),
|
||||
api.get('/api/departments')
|
||||
]);
|
||||
populateDepartmentsSelect();
|
||||
await loadSubjects();
|
||||
} catch (e) {
|
||||
subjectsTbody.innerHTML = `<tr><td colspan="6" class="loading-row">Ошибка загрузки справочников: ${escapeHtml(e.message)}</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function populateDepartmentsSelect() {
|
||||
newSubjectDeptSelect.innerHTML = '<option value="">Выберите кафедру</option>' +
|
||||
allDepartments.map(d => {
|
||||
const name = d.departmentName || d.name || 'Без названия';
|
||||
const code = d.departmentCode || d.code || d.id;
|
||||
return `<option value="${d.id}">${escapeHtml(name)} (${escapeHtml(String(code))})</option>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
async function loadSubjects() {
|
||||
subjectsTbody.innerHTML = '<tr><td colspan="6" class="loading-row">Загрузка...</td></tr>';
|
||||
try {
|
||||
allSubjects = await api.get('/api/subjects');
|
||||
renderSubjects(allSubjects);
|
||||
populateSubjectSelect(allSubjects);
|
||||
[allSubjects, teacherSubjects] = await Promise.all([
|
||||
api.get('/api/subjects'),
|
||||
api.get('/api/teacher-subjects')
|
||||
]);
|
||||
renderSubjects();
|
||||
} catch (e) {
|
||||
if (subjectsTbody) subjectsTbody.innerHTML = '<tr><td colspan="5" class="loading-row">Ошибка загрузки</td></tr>';
|
||||
subjectsTbody.innerHTML = `<tr><td colspan="6" class="loading-row">Ошибка загрузки: ${escapeHtml(e.message)}</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderSubjects(subjects) {
|
||||
if (!subjects || !subjects.length) {
|
||||
subjectsTbody.innerHTML = '<tr><td colspan="5" class="loading-row">Нет дисциплин</td></tr>';
|
||||
function renderSubjects() {
|
||||
if (!allSubjects || !allSubjects.length) {
|
||||
subjectsTbody.innerHTML = '<tr><td colspan="6" class="loading-row">Нет дисциплин</td></tr>';
|
||||
return;
|
||||
}
|
||||
subjectsTbody.innerHTML = subjects.map(s => `
|
||||
<tr>
|
||||
<td>${s.id}</td>
|
||||
<td>${escapeHtml(s.name)}</td>
|
||||
<td>${escapeHtml(s.code || '-')}</td>
|
||||
<td>${s.departmentId || '-'}</td>
|
||||
<td><button class="btn-delete" data-id="${s.id}">Удалить</button></td>
|
||||
</tr>`).join('');
|
||||
|
||||
// Группируем преподавателей по дисциплинам
|
||||
const teachersBySubject = new Map();
|
||||
teacherSubjects.forEach(ts => {
|
||||
if (!teachersBySubject.has(ts.subjectId)) {
|
||||
teachersBySubject.set(ts.subjectId, []);
|
||||
}
|
||||
teachersBySubject.get(ts.subjectId).push(ts);
|
||||
});
|
||||
|
||||
subjectsTbody.innerHTML = allSubjects.map(s => {
|
||||
const teachers = teachersBySubject.get(s.id) || [];
|
||||
const teachersHtml = teachers.length
|
||||
? teachers.map(t => `<span class="badge badge-ef" style="margin: 0.1rem;">${escapeHtml(t.fullName || t.username)}</span>`).join('')
|
||||
: '<span class="text-muted"><small>Нет преподавателей</small></span>';
|
||||
|
||||
return `
|
||||
<tr>
|
||||
<td>${s.id}</td>
|
||||
<td><strong>${escapeHtml(s.name)}</strong></td>
|
||||
<td>${escapeHtml(s.code || '-')}</td>
|
||||
<td>${escapeHtml(departmentLabel(s.departmentId))}</td>
|
||||
<td><div style="display: flex; flex-wrap: wrap; gap: 0.25rem;">${teachersHtml}</div></td>
|
||||
<td style="text-align: right; white-space: nowrap;">
|
||||
<button class="btn-primary btn-manage-teachers" data-id="${s.id}" style="padding: 0.25rem 0.5rem; font-size: 0.85rem;">Преподаватели</button>
|
||||
<button class="btn-delete btn-delete-subject" data-id="${s.id}">Удалить</button>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function populateSubjectSelect(subjects) {
|
||||
if (!assignSubjectSelect) return;
|
||||
const currentVal = assignSubjectSelect.value;
|
||||
assignSubjectSelect.innerHTML = '<option value="">Выберите дисциплину</option>' +
|
||||
subjects.map(s => `<option value="${s.id}">${escapeHtml(s.name)}</option>`).join('');
|
||||
if (currentVal && subjects.find(s => s.id == currentVal)) {
|
||||
assignSubjectSelect.value = currentVal;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadTeachers() {
|
||||
try {
|
||||
allTeachers = await api.get('/api/users/teachers');
|
||||
populateTeacherSelect(allTeachers);
|
||||
} catch (e) {
|
||||
if (assignTeacherSelect) assignTeacherSelect.innerHTML = '<option value="">Ошибка загрузки</option>';
|
||||
}
|
||||
}
|
||||
|
||||
function populateTeacherSelect(teachers) {
|
||||
if (!assignTeacherSelect) return;
|
||||
const currentVal = assignTeacherSelect.value;
|
||||
if (!teachers || !teachers.length) {
|
||||
assignTeacherSelect.innerHTML = '<option value="">Нет преподавателей</option>';
|
||||
return;
|
||||
}
|
||||
assignTeacherSelect.innerHTML = '<option value="">Выберите преподавателя</option>' +
|
||||
teachers.map(t => `<option value="${t.id}">${escapeHtml(t.username)}</option>`).join('');
|
||||
if (currentVal && teachers.find(t => t.id == currentVal)) {
|
||||
assignTeacherSelect.value = currentVal;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadTeacherSubjects() {
|
||||
try {
|
||||
const tsData = await api.get('/api/teacher-subjects');
|
||||
renderTeacherSubjects(tsData);
|
||||
} catch (e) {
|
||||
if (teacherSubjectsTbody) teacherSubjectsTbody.innerHTML = '<tr><td colspan="3" class="loading-row">Ошибка загрузки</td></tr>';
|
||||
}
|
||||
}
|
||||
|
||||
function renderTeacherSubjects(tsArray) {
|
||||
if (!tsArray || !tsArray.length) {
|
||||
teacherSubjectsTbody.innerHTML = '<tr><td colspan="3" class="loading-row">Нет привязок</td></tr>';
|
||||
return;
|
||||
}
|
||||
teacherSubjectsTbody.innerHTML = tsArray.map(ts => `
|
||||
<tr>
|
||||
<td>${escapeHtml(ts.username)}</td>
|
||||
<td>${escapeHtml(ts.subjectName)}</td>
|
||||
<td><button class="btn-delete" data-user-id="${ts.userId}" data-subject-id="${ts.subjectId}">Удалить</button></td>
|
||||
</tr>`).join('');
|
||||
}
|
||||
|
||||
createSubjectForm.addEventListener('submit', async (e) => {
|
||||
async function createSubject(e) {
|
||||
e.preventDefault();
|
||||
hideAlert('create-subject-alert');
|
||||
const name = document.getElementById('new-subject-name').value.trim();
|
||||
const code = document.getElementById('new-subject-code').value.trim();
|
||||
const departmentId = document.getElementById('new-subject-department').value;
|
||||
if (!name) { showAlert('create-subject-alert', 'Введите название', 'error'); return; }
|
||||
if (!code) { showAlert('create-subject-alert', 'Введите код предмета', 'error'); return; }
|
||||
if (!departmentId) { showAlert('create-subject-alert', 'Введите идентификатор кафедры', 'error'); return; }
|
||||
const departmentId = newSubjectDeptSelect.value;
|
||||
|
||||
if (!name || !code || !departmentId) {
|
||||
showAlert('create-subject-alert', 'Заполните все поля', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await api.post('/api/subjects', {
|
||||
name,
|
||||
code,
|
||||
departmentId: Number(departmentId)
|
||||
const data = await api.post('/api/subjects', {
|
||||
name,
|
||||
code,
|
||||
departmentId: Number(departmentId)
|
||||
});
|
||||
showAlert('create-subject-alert', `Дисциплина "${escapeHtml(data.name || name)}" добавлена`, 'success');
|
||||
showAlert('create-subject-alert', `Дисциплина "${escapeHtml(data.name || name)}" создана`, 'success');
|
||||
createSubjectForm.reset();
|
||||
loadSubjects();
|
||||
} catch (e) { showAlert('create-subject-alert', e.message || 'Ошибка создания', 'error'); }
|
||||
});
|
||||
await loadSubjects();
|
||||
} catch (error) {
|
||||
showAlert('create-subject-alert', error.message || 'Ошибка создания', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
subjectsTbody.addEventListener('click', async (e) => {
|
||||
const btn = e.target.closest('.btn-delete');
|
||||
if (!btn) return;
|
||||
if (!confirm('Удалить дисциплину?')) return;
|
||||
try {
|
||||
await api.delete('/api/subjects/' + btn.dataset.id);
|
||||
loadSubjects();
|
||||
loadTeacherSubjects(); // May have deleted a subject that was assigned
|
||||
} catch (e) { alert(e.message || 'Ошибка удаления'); }
|
||||
});
|
||||
async function handleSubjectsTableClick(e) {
|
||||
const btnDelete = e.target.closest('.btn-delete-subject');
|
||||
const btnTeachers = e.target.closest('.btn-manage-teachers');
|
||||
|
||||
assignTeacherForm.addEventListener('submit', async (e) => {
|
||||
if (btnDelete) {
|
||||
if (!confirm('Удалить дисциплину? Это удалит её привязки к преподавателям.')) return;
|
||||
try {
|
||||
await api.delete('/api/subjects/' + btnDelete.dataset.id);
|
||||
await loadSubjects();
|
||||
} catch (error) {
|
||||
alert(error.message || 'Ошибка удаления');
|
||||
}
|
||||
}
|
||||
|
||||
if (btnTeachers) {
|
||||
const subjectId = btnTeachers.dataset.id;
|
||||
const subject = allSubjects.find(s => s.id == subjectId);
|
||||
if (subject) openTeachersModal(subject);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Управление привязками преподавателей к дисциплине ---
|
||||
function openTeachersModal(subject) {
|
||||
subjectTeachersContext.textContent = `${subject.code ? `${subject.code} · ` : ''}${subject.name}`;
|
||||
manageTsSubjectIdInput.value = subject.id;
|
||||
hideAlert('manage-ts-alert');
|
||||
modalManageTeachers.classList.add('open');
|
||||
renderSubjectTeachers(subject.id);
|
||||
populateTeachersSelect(subject.id);
|
||||
}
|
||||
|
||||
function renderSubjectTeachers(subjectId) {
|
||||
const list = teacherSubjects.filter(ts => String(ts.subjectId) === String(subjectId));
|
||||
if (!list.length) {
|
||||
manageTsTbody.innerHTML = '<tr><td colspan="2" class="loading-row">Преподаватели не привязаны</td></tr>';
|
||||
return;
|
||||
}
|
||||
manageTsTbody.innerHTML = list.map(ts => `
|
||||
<tr>
|
||||
<td><strong>${escapeHtml(ts.fullName || ts.username)}</strong> <span class="text-muted">(${escapeHtml(ts.username)})</span></td>
|
||||
<td>
|
||||
<button class="btn-delete btn-delete-ts" data-user-id="${ts.userId}" data-subject-id="${ts.subjectId}">Удалить</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
function populateTeachersSelect(subjectId) {
|
||||
// Показываем только тех преподавателей, которые еще не привязаны к этой дисциплине
|
||||
const assignedUserIds = new Set(
|
||||
teacherSubjects
|
||||
.filter(ts => String(ts.subjectId) === String(subjectId))
|
||||
.map(ts => String(ts.userId))
|
||||
);
|
||||
|
||||
const availableTeachers = allTeachers.filter(t => !assignedUserIds.has(String(t.id)));
|
||||
|
||||
if (!availableTeachers.length) {
|
||||
manageTsTeacherSelect.innerHTML = '<option value="">Все преподаватели привязаны</option>';
|
||||
return;
|
||||
}
|
||||
|
||||
manageTsTeacherSelect.innerHTML = '<option value="">Выберите преподавателя</option>' +
|
||||
availableTeachers.map(t => `<option value="${t.id}">${escapeHtml(t.fullName || t.username)} (${escapeHtml(t.username)})</option>`).join('');
|
||||
}
|
||||
|
||||
async function saveTeacherAssignment(e) {
|
||||
e.preventDefault();
|
||||
hideAlert('assign-teacher-alert');
|
||||
const userId = assignTeacherSelect.value;
|
||||
const subjectId = assignSubjectSelect.value;
|
||||
if (!userId) { showAlert('assign-teacher-alert', 'Выберите преподавателя', 'error'); return; }
|
||||
if (!subjectId) { showAlert('assign-teacher-alert', 'Выберите дисциплину', 'error'); return; }
|
||||
hideAlert('manage-ts-alert');
|
||||
const subjectId = manageTsSubjectIdInput.value;
|
||||
const userId = manageTsTeacherSelect.value;
|
||||
|
||||
if (!userId) {
|
||||
showAlert('manage-ts-alert', 'Выберите преподавателя', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await api.post('/api/teacher-subjects', { userId: Number(userId), subjectId: Number(subjectId) });
|
||||
showAlert('assign-teacher-alert', 'Привязка создана', 'success');
|
||||
loadTeacherSubjects();
|
||||
} catch (e) { showAlert('assign-teacher-alert', e.message || 'Ошибка привязки', 'error'); }
|
||||
});
|
||||
await api.post('/api/teacher-subjects', {
|
||||
userId: Number(userId),
|
||||
subjectId: Number(subjectId)
|
||||
});
|
||||
showAlert('manage-ts-alert', 'Преподаватель успешно привязан', 'success');
|
||||
|
||||
// Перезагрузим привязки и обновим интерфейс
|
||||
teacherSubjects = await api.get('/api/teacher-subjects');
|
||||
renderSubjectTeachers(subjectId);
|
||||
populateTeachersSelect(subjectId);
|
||||
|
||||
// Также обновим главную таблицу
|
||||
renderSubjects();
|
||||
} catch (error) {
|
||||
showAlert('manage-ts-alert', error.message || 'Ошибка привязки', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleTeacherAssignmentTableClick(e) {
|
||||
const btnDelete = e.target.closest('.btn-delete-ts');
|
||||
if (!btnDelete) return;
|
||||
if (!confirm('Удалить привязку преподавателя?')) return;
|
||||
const subjectId = manageTsSubjectIdInput.value;
|
||||
|
||||
teacherSubjectsTbody.addEventListener('click', async (e) => {
|
||||
const btn = e.target.closest('.btn-delete');
|
||||
if (!btn) return;
|
||||
if (!confirm('Удалить привязку?')) return;
|
||||
try {
|
||||
await api.delete('/api/teacher-subjects', {
|
||||
userId: Number(btn.dataset.userId),
|
||||
subjectId: Number(btn.dataset.subjectId)
|
||||
userId: Number(btnDelete.dataset.userId),
|
||||
subjectId: Number(btnDelete.dataset.subjectId)
|
||||
});
|
||||
loadTeacherSubjects();
|
||||
} catch (e) { alert(e.message || 'Ошибка удаления'); }
|
||||
});
|
||||
|
||||
// Перезагрузим привязки
|
||||
teacherSubjects = await api.get('/api/teacher-subjects');
|
||||
renderSubjectTeachers(subjectId);
|
||||
populateTeachersSelect(subjectId);
|
||||
|
||||
// Обновим главную таблицу
|
||||
renderSubjects();
|
||||
} catch (error) {
|
||||
alert(error.message || 'Ошибка удаления привязки');
|
||||
}
|
||||
}
|
||||
|
||||
loadInitialData();
|
||||
// --- Вспомогательные функции ---
|
||||
function departmentLabel(departmentId) {
|
||||
const department = allDepartments.find(item => item.id == departmentId);
|
||||
if (!department) return departmentId || '-';
|
||||
return department.departmentName || department.name || departmentId;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { api } from '../api.js';
|
||||
import { escapeHtml, showAlert, hideAlert } from '../utils.js';
|
||||
|
||||
export async function initDepartmentsData() {
|
||||
export async function initUniversityStructure() {
|
||||
const deptTbody = document.getElementById('departments-tbody');
|
||||
const specTbody = document.getElementById('specialties-tbody');
|
||||
|
||||
@@ -14,30 +14,75 @@ export async function initDepartmentsData() {
|
||||
const editDeptClose = document.getElementById('modal-edit-department-close');
|
||||
const editSpecClose = document.getElementById('modal-edit-specialty-close');
|
||||
|
||||
// Элементы вкладок
|
||||
const tabDepartments = document.getElementById('btn-tab-departments');
|
||||
const tabSpecialties = document.getElementById('btn-tab-specialties');
|
||||
const contentDepartments = document.getElementById('tab-content-departments');
|
||||
const contentSpecialties = document.getElementById('tab-content-specialties');
|
||||
|
||||
// Элементы модалки профилей
|
||||
const profilesModal = document.getElementById('modal-manage-profiles');
|
||||
const profilesModalClose = document.getElementById('modal-manage-profiles-close');
|
||||
const profilesSpecContext = document.getElementById('profiles-spec-context');
|
||||
const profileFormTitle = document.getElementById('profile-form-title');
|
||||
const manageProfileForm = document.getElementById('manage-profile-form');
|
||||
const profileIdInput = document.getElementById('manage-profile-id');
|
||||
const profileSpecIdInput = document.getElementById('manage-profile-spec-id');
|
||||
const profileNameInput = document.getElementById('manage-profile-name');
|
||||
const profileDescInput = document.getElementById('manage-profile-description');
|
||||
const btnSaveProfile = document.getElementById('btn-save-profile');
|
||||
const btnCancelProfileEdit = document.getElementById('btn-cancel-profile-edit');
|
||||
const profilesTbody = document.getElementById('manage-profiles-tbody');
|
||||
|
||||
let departments = [];
|
||||
let specialties = [];
|
||||
let currentProfiles = [];
|
||||
|
||||
// --- Логика переключения табов ---
|
||||
tabDepartments.addEventListener('click', () => {
|
||||
tabDepartments.classList.add('active');
|
||||
tabDepartments.style.borderBottomColor = 'var(--primary)';
|
||||
tabDepartments.style.color = 'var(--text-main)';
|
||||
tabSpecialties.classList.remove('active');
|
||||
tabSpecialties.style.borderBottomColor = 'transparent';
|
||||
tabSpecialties.style.color = 'var(--text-secondary)';
|
||||
contentDepartments.style.display = 'block';
|
||||
contentSpecialties.style.display = 'none';
|
||||
});
|
||||
|
||||
tabSpecialties.addEventListener('click', () => {
|
||||
tabSpecialties.classList.add('active');
|
||||
tabSpecialties.style.borderBottomColor = 'var(--primary)';
|
||||
tabSpecialties.style.color = 'var(--text-main)';
|
||||
tabDepartments.classList.remove('active');
|
||||
tabDepartments.style.borderBottomColor = 'transparent';
|
||||
tabDepartments.style.color = 'var(--text-secondary)';
|
||||
contentSpecialties.style.display = 'block';
|
||||
contentDepartments.style.display = 'none';
|
||||
});
|
||||
|
||||
// --- Загрузка данных ---
|
||||
async function loadData() {
|
||||
// Load Departments
|
||||
// Загрузка кафедр
|
||||
try {
|
||||
departments = await api.get('/api/departments');
|
||||
renderDepartments();
|
||||
} catch (e) {
|
||||
deptTbody.innerHTML = '<tr><td colspan="4" class="loading-row">-</td></tr>';
|
||||
deptTbody.innerHTML = '<tr><td colspan="4" class="loading-row">Ошибка загрузки</td></tr>';
|
||||
}
|
||||
|
||||
// Load Specialties
|
||||
// Загрузка специальностей
|
||||
try {
|
||||
specialties = await api.get('/api/specialties');
|
||||
renderSpecialties();
|
||||
} catch (e) {
|
||||
specTbody.innerHTML = '<tr><td colspan="4" 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="4" class="loading-row">-</td></tr>';
|
||||
deptTbody.innerHTML = '<tr><td colspan="4" class="loading-row">Кафедры не созданы</td></tr>';
|
||||
return;
|
||||
}
|
||||
deptTbody.innerHTML = departments.map(d => `
|
||||
@@ -55,7 +100,7 @@ export async function initDepartmentsData() {
|
||||
|
||||
function renderSpecialties() {
|
||||
if (!specialties || !specialties.length) {
|
||||
specTbody.innerHTML = '<tr><td colspan="4" class="loading-row">-</td></tr>';
|
||||
specTbody.innerHTML = '<tr><td colspan="4" class="loading-row">Специальности не созданы</td></tr>';
|
||||
return;
|
||||
}
|
||||
specTbody.innerHTML = specialties.map(s => `
|
||||
@@ -65,12 +110,14 @@ export async function initDepartmentsData() {
|
||||
<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-primary btn-manage-profiles" data-id="${s.id}" style="padding: 0.25rem 0.5rem; font-size: 0.85rem;">Профили</button>
|
||||
<button class="btn-delete btn-delete-specialty" data-id="${s.id}">Удалить</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
// --- Кафедры: CRUD ---
|
||||
createDeptForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
hideAlert('create-dept-alert');
|
||||
@@ -120,6 +167,29 @@ export async function initDepartmentsData() {
|
||||
}
|
||||
});
|
||||
|
||||
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');
|
||||
}
|
||||
});
|
||||
|
||||
// --- Специальности: CRUD ---
|
||||
createSpecForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
hideAlert('create-spec-alert');
|
||||
@@ -144,6 +214,7 @@ export async function initDepartmentsData() {
|
||||
specTbody.addEventListener('click', async (e) => {
|
||||
const editBtn = e.target.closest('.btn-edit-specialty');
|
||||
const deleteBtn = e.target.closest('.btn-delete-specialty');
|
||||
const profilesBtn = e.target.closest('.btn-manage-profiles');
|
||||
|
||||
if (editBtn) {
|
||||
const speciality = specialties.find(item => item.id == editBtn.dataset.id);
|
||||
@@ -167,27 +238,13 @@ export async function initDepartmentsData() {
|
||||
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 (profilesBtn) {
|
||||
const specId = profilesBtn.dataset.id;
|
||||
const speciality = specialties.find(item => item.id == specId);
|
||||
if (!speciality) return;
|
||||
|
||||
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');
|
||||
openProfilesModal(speciality);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -213,14 +270,130 @@ export async function initDepartmentsData() {
|
||||
}
|
||||
});
|
||||
|
||||
// --- Профили обучения: Логика ---
|
||||
async function openProfilesModal(speciality) {
|
||||
profilesSpecContext.textContent = `${speciality.specialityCode || speciality.specialtyCode || speciality.specialty_code} · ${speciality.specialityName || speciality.name}`;
|
||||
profileSpecIdInput.value = speciality.id;
|
||||
resetProfileForm();
|
||||
profilesModal.classList.add('open');
|
||||
await loadProfiles(speciality.id);
|
||||
}
|
||||
|
||||
async function loadProfiles(specId) {
|
||||
profilesTbody.innerHTML = '<tr><td colspan="4" class="loading-row">Загрузка...</td></tr>';
|
||||
try {
|
||||
currentProfiles = await api.get(`/api/specialties/${specId}/profiles`);
|
||||
renderProfilesTable();
|
||||
} catch (e) {
|
||||
profilesTbody.innerHTML = `<tr><td colspan="4" class="loading-row">Ошибка загрузки: ${escapeHtml(e.message)}</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderProfilesTable() {
|
||||
if (!currentProfiles || !currentProfiles.length) {
|
||||
profilesTbody.innerHTML = '<tr><td colspan="4" class="loading-row">Профили не созданы</td></tr>';
|
||||
return;
|
||||
}
|
||||
profilesTbody.innerHTML = currentProfiles.map(p => `
|
||||
<tr>
|
||||
<td>${p.id}</td>
|
||||
<td>${escapeHtml(p.name)}</td>
|
||||
<td>${escapeHtml(p.description || '-')}</td>
|
||||
<td>
|
||||
<button class="btn-edit-classroom btn-edit-profile" data-id="${p.id}">Изменить</button>
|
||||
<button class="btn-delete btn-delete-profile" data-id="${p.id}">Удалить</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
function resetProfileForm() {
|
||||
manageProfileForm.reset();
|
||||
profileIdInput.value = '';
|
||||
profileFormTitle.textContent = 'Создание профиля';
|
||||
btnSaveProfile.textContent = 'Создать';
|
||||
btnCancelProfileEdit.style.display = 'none';
|
||||
hideAlert('manage-profile-alert');
|
||||
}
|
||||
|
||||
manageProfileForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
hideAlert('manage-profile-alert');
|
||||
|
||||
const specId = profileSpecIdInput.value;
|
||||
const profileId = profileIdInput.value;
|
||||
const name = profileNameInput.value.trim();
|
||||
const description = profileDescInput.value.trim();
|
||||
|
||||
if (!name) {
|
||||
showAlert('manage-profile-alert', 'Введите название профиля', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (profileId) {
|
||||
// Обновление
|
||||
await api.put(`/api/specialties/${specId}/profiles/${profileId}`, { id: Number(profileId), name, description });
|
||||
showAlert('manage-profile-alert', `Профиль "${name}" обновлен`, 'success');
|
||||
} else {
|
||||
// Создание
|
||||
await api.post(`/api/specialties/${specId}/profiles`, { name, description });
|
||||
showAlert('manage-profile-alert', `Профиль "${name}" создан`, 'success');
|
||||
}
|
||||
resetProfileForm();
|
||||
await loadProfiles(specId);
|
||||
} catch (error) {
|
||||
showAlert('manage-profile-alert', error.message || 'Ошибка сохранения профиля', 'error');
|
||||
}
|
||||
});
|
||||
|
||||
profilesTbody.addEventListener('click', async (e) => {
|
||||
const editBtn = e.target.closest('.btn-edit-profile');
|
||||
const deleteBtn = e.target.closest('.btn-delete-profile');
|
||||
const specId = profileSpecIdInput.value;
|
||||
|
||||
if (editBtn) {
|
||||
const profile = currentProfiles.find(item => item.id == editBtn.dataset.id);
|
||||
if (!profile) return;
|
||||
|
||||
profileIdInput.value = profile.id;
|
||||
profileNameInput.value = profile.name || '';
|
||||
profileDescInput.value = profile.description || '';
|
||||
profileFormTitle.textContent = 'Редактирование профиля';
|
||||
btnSaveProfile.textContent = 'Сохранить';
|
||||
btnCancelProfileEdit.style.display = 'inline-block';
|
||||
hideAlert('manage-profile-alert');
|
||||
return;
|
||||
}
|
||||
|
||||
if (deleteBtn) {
|
||||
if (!confirm('Удалить профиль обучения?')) return;
|
||||
try {
|
||||
await api.delete(`/api/specialties/${specId}/profiles/${deleteBtn.dataset.id}`);
|
||||
showAlert('manage-profile-alert', 'Профиль удален', 'success');
|
||||
await loadProfiles(specId);
|
||||
} catch (error) {
|
||||
showAlert('manage-profile-alert', error.message || 'Ошибка удаления профиля', 'error');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
btnCancelProfileEdit.addEventListener('click', resetProfileForm);
|
||||
|
||||
// Закрытие модалок
|
||||
editDeptClose.addEventListener('click', () => editDeptModal.classList.remove('open'));
|
||||
editSpecClose.addEventListener('click', () => editSpecModal.classList.remove('open'));
|
||||
profilesModalClose.addEventListener('click', () => profilesModal.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');
|
||||
});
|
||||
profilesModal.addEventListener('click', (e) => {
|
||||
if (e.target === profilesModal) profilesModal.classList.remove('open');
|
||||
});
|
||||
|
||||
await loadData();
|
||||
}
|
||||
Reference in New Issue
Block a user