703 lines
34 KiB
React
703 lines
34 KiB
React
import { useEffect, useRef, useState } from 'react';
|
||
import { CustomSelect } from '../../shared/ui/CustomSelect.jsx';
|
||
import { AsyncCombobox } from '../../shared/ui/AsyncCombobox.jsx';
|
||
import { apiClient } from '../../shared/api-client.js';
|
||
import { toIsoDate } from '../../shared/dates.js';
|
||
import {
|
||
createDirtyScope,
|
||
confirmAbandonDirtyChanges,
|
||
} from '../../../admin/js/dirty-state.js';
|
||
import {
|
||
LOAD_CATEGORIES,
|
||
loadDraft,
|
||
fetchPlanTeachers,
|
||
workloadHours,
|
||
} from '../study-plans-service.js';
|
||
import { fetchDepartments, departmentLabel } from '../subjects-service.js';
|
||
import {
|
||
fetchCalendarLoads,
|
||
calendarMaterialRows,
|
||
saveCalendarLoad,
|
||
assignCalendarTeacher,
|
||
} from '../calendar-loads-service.js';
|
||
import { materialTotals } from '../schedule-materials-service.js';
|
||
const errorText = (error) => error.data?.message || error.message;
|
||
|
||
export function CalendarLoadsWorkspace({ editHours = false }) {
|
||
const [semesters, setSemesters] = useState([]),
|
||
[departments, setDepartments] = useState([]);
|
||
const [semesterId, setSemesterId] = useState(''),
|
||
[details, setDetails] = useState([]);
|
||
const [filters, setFilters] = useState({
|
||
groupId: '',
|
||
departmentId: '',
|
||
query: '',
|
||
unassigned: false,
|
||
});
|
||
const [loading, setLoading] = useState(true),
|
||
[busy, setBusy] = useState(false),
|
||
[alert, setAlert] = useState(null);
|
||
const [reload, setReload] = useState(0),
|
||
[editing, setEditing] = useState(null),
|
||
[draft, setDraft] = useState([]),
|
||
[teacher, setTeacher] = useState(null);
|
||
const [actual, setActual] = useState(null);
|
||
const dirty = useRef(null),
|
||
mounted = useRef(false),
|
||
pending = useRef(false);
|
||
useEffect(() => {
|
||
mounted.current = true;
|
||
dirty.current = createDirtyScope(
|
||
editHours ? 'calendar-group-hours' : 'calendar-materials',
|
||
);
|
||
Promise.all([
|
||
apiClient.get('/api/schedule/semesters'),
|
||
fetchDepartments(),
|
||
])
|
||
.then(([periods, refs]) => {
|
||
if (!mounted.current) return;
|
||
setSemesters(periods);
|
||
setDepartments(refs);
|
||
const today = toIsoDate(new Date());
|
||
const current = periods.find(s => s.startDate <= today && s.endDate >= today) || periods.find(s => s.startDate <= today) || periods[0];
|
||
setSemesterId(String(current?.id || ''));
|
||
if (!periods.length) setLoading(false);
|
||
})
|
||
.catch((error) => {
|
||
if (mounted.current) {
|
||
setAlert({ error: true, text: errorText(error) });
|
||
setLoading(false);
|
||
}
|
||
});
|
||
return () => {
|
||
mounted.current = false;
|
||
dirty.current?.dispose();
|
||
};
|
||
}, []);
|
||
useEffect(() => {
|
||
if (!semesterId) return;
|
||
let active = true;
|
||
setLoading(true);
|
||
setActual(null);
|
||
setDetails([]);
|
||
fetchCalendarLoads(semesterId)
|
||
.then((data) => {
|
||
if (active) setDetails(data);
|
||
})
|
||
.catch((error) => {
|
||
if (active) setAlert({ error: true, text: errorText(error) });
|
||
})
|
||
.finally(() => {
|
||
if (active) setLoading(false);
|
||
});
|
||
return () => {
|
||
active = false;
|
||
};
|
||
}, [semesterId, reload]);
|
||
function close() {
|
||
setEditing(null);
|
||
setTeacher(null);
|
||
setDraft([]);
|
||
dirty.current?.clear();
|
||
}
|
||
async function changeSemester(value) {
|
||
if (!(await confirmAbandonDirtyChanges())) return;
|
||
close();
|
||
setFilters((current) => ({ ...current, groupId: '' }));
|
||
setSemesterId(value);
|
||
setAlert(null);
|
||
}
|
||
async function edit(row) {
|
||
if (!(await confirmAbandonDirtyChanges())) return;
|
||
close();
|
||
setEditing(row);
|
||
const subject = details
|
||
.find((d) => d.context.groupId === row.context.groupId)
|
||
?.subjects.find((s) => s.subjectId === row.subjectId);
|
||
setDraft(loadDraft(subject));
|
||
setTeacher(
|
||
row.teacherId == null
|
||
? null
|
||
: { id: row.teacherId, fullName: row.teacherName },
|
||
);
|
||
}
|
||
function changeLoad(category, hours, split) {
|
||
dirty.current?.mark();
|
||
setDraft((current) =>
|
||
current.map((load) =>
|
||
load.category === category
|
||
? {
|
||
...load,
|
||
academicHours: hours ?? load.academicHours,
|
||
splitSubgroups: Number(hours ?? load.academicHours)
|
||
? (split ?? load.splitSubgroups)
|
||
: false,
|
||
teacherId: Number(hours ?? load.academicHours)
|
||
? load.teacherId
|
||
: null,
|
||
}
|
||
: load,
|
||
),
|
||
);
|
||
}
|
||
async function save(event) {
|
||
event.preventDefault();
|
||
if (pending.current) return;
|
||
pending.current = true;
|
||
setBusy(true);
|
||
setAlert(null);
|
||
try {
|
||
const next = editHours
|
||
? await saveCalendarLoad(
|
||
editing.context,
|
||
editing.subjectId,
|
||
draft,
|
||
)
|
||
: await assignCalendarTeacher(
|
||
editing.context,
|
||
editing,
|
||
teacher?.id ?? null,
|
||
);
|
||
if (!mounted.current) return;
|
||
setDetails((current) =>
|
||
current.map((d) =>
|
||
d.context.groupId === next.context.groupId ? next : d,
|
||
),
|
||
);
|
||
close();
|
||
setAlert({
|
||
text: editHours
|
||
? 'Часы группы сохранены в календарном графике'
|
||
: 'Преподаватель группы назначен. Конструктор использует новое назначение.',
|
||
});
|
||
} catch (error) {
|
||
if (mounted.current)
|
||
setAlert({ error: true, text: errorText(error) });
|
||
} finally {
|
||
pending.current = false;
|
||
if (mounted.current) setBusy(false);
|
||
}
|
||
}
|
||
async function refresh() {
|
||
if (!(await confirmAbandonDirtyChanges())) return;
|
||
close();
|
||
setAlert(null);
|
||
setReload((value) => value + 1);
|
||
}
|
||
async function actualWorkload() {
|
||
const semester = semesters.find((s) => String(s.id) === semesterId);
|
||
if (!semester || pending.current) return;
|
||
pending.current = true;
|
||
setBusy(true);
|
||
try {
|
||
const params = new URLSearchParams({
|
||
startDate: semester.startDate,
|
||
endDate: semester.endDate,
|
||
});
|
||
const [teachers, groups] = await Promise.all([
|
||
apiClient.get(`/api/workload/teachers?${params}`),
|
||
apiClient.get(`/api/workload/groups?${params}`),
|
||
]);
|
||
if (mounted.current) setActual({ teachers, groups });
|
||
} catch (error) {
|
||
if (mounted.current)
|
||
setAlert({ error: true, text: errorText(error) });
|
||
} finally {
|
||
pending.current = false;
|
||
if (mounted.current) setBusy(false);
|
||
}
|
||
}
|
||
const rows = calendarMaterialRows(
|
||
details,
|
||
{ ...filters, includeZero: editHours },
|
||
departments,
|
||
);
|
||
const totals = materialTotals(calendarMaterialRows(details));
|
||
const subjectsSeen = new Set();
|
||
const visibleRows = editHours
|
||
? rows.filter((row) => {
|
||
const key = `${row.context.groupId}:${row.subjectId}`;
|
||
if (subjectsSeen.has(key)) return false;
|
||
subjectsSeen.add(key);
|
||
return true;
|
||
})
|
||
: rows;
|
||
return (
|
||
<section
|
||
className="materials-workspace"
|
||
aria-label={
|
||
editHours
|
||
? 'Часы календарного графика по группам'
|
||
: 'Формирование материалов к расписанию'
|
||
}
|
||
aria-busy={loading || busy}
|
||
>
|
||
{alert && (
|
||
<div
|
||
className={`materials-alert${alert.error ? ' is-error' : ''}`}
|
||
role={alert.error ? 'alert' : 'status'}
|
||
>
|
||
{alert.text}
|
||
</div>
|
||
)}
|
||
<div className="card">
|
||
<h3>
|
||
{editHours
|
||
? 'Часы календарного графика по группам'
|
||
: 'Формирование материалов к расписанию'}
|
||
</h3>
|
||
<p>
|
||
{editHours
|
||
? 'Задайте часы лекций, практик и лабораторных отдельно для каждой группы. Одна пара — 2 академических часа.'
|
||
: 'Часы поступают из календарного графика конкретной группы. Назначение преподавателя здесь не меняет другие группы.'}
|
||
</p>
|
||
<fieldset
|
||
className="study-plan-fieldset materials-filters"
|
||
disabled={busy}
|
||
>
|
||
<label className="form-group">
|
||
Календарный семестр
|
||
<CustomSelect
|
||
value={semesterId}
|
||
onChange={(e) =>
|
||
void changeSemester(e.target.value)
|
||
}
|
||
>
|
||
{!semesters.length && (
|
||
<option value="">Нет семестров</option>
|
||
)}
|
||
{semesters.map((s) => (
|
||
<option key={s.id} value={s.id}>
|
||
{s.academicYearTitle} ·{' '}
|
||
{s.semesterType === 'autumn'
|
||
? 'Осень'
|
||
: 'Весна'}
|
||
</option>
|
||
))}
|
||
</CustomSelect>
|
||
</label>
|
||
<label className="form-group">
|
||
Группа
|
||
<CustomSelect
|
||
value={filters.groupId}
|
||
onChange={(e) =>
|
||
setFilters({
|
||
...filters,
|
||
groupId: e.target.value,
|
||
})
|
||
}
|
||
>
|
||
<option value="">Все группы</option>
|
||
{details.map((d) => (
|
||
<option
|
||
key={d.context.groupId}
|
||
value={d.context.groupId}
|
||
>
|
||
{d.context.groupName}
|
||
</option>
|
||
))}
|
||
</CustomSelect>
|
||
</label>
|
||
<label className="form-group">
|
||
Кафедра дисциплины
|
||
<CustomSelect
|
||
value={filters.departmentId}
|
||
onChange={(e) =>
|
||
setFilters({
|
||
...filters,
|
||
departmentId: e.target.value,
|
||
})
|
||
}
|
||
>
|
||
<option value="">Все кафедры</option>
|
||
{departments.map((d) => (
|
||
<option key={d.id} value={d.id}>
|
||
{departmentLabel(departments, d.id)}
|
||
</option>
|
||
))}
|
||
</CustomSelect>
|
||
</label>
|
||
<label className="form-group">
|
||
Поиск
|
||
<input
|
||
type="search"
|
||
value={filters.query}
|
||
onChange={(e) =>
|
||
setFilters({
|
||
...filters,
|
||
query: e.target.value,
|
||
})
|
||
}
|
||
/>
|
||
</label>
|
||
{!editHours && (
|
||
<label className="checkbox-item">
|
||
<input
|
||
type="checkbox"
|
||
checked={filters.unassigned}
|
||
onChange={(e) =>
|
||
setFilters({
|
||
...filters,
|
||
unassigned: e.target.checked,
|
||
})
|
||
}
|
||
/>
|
||
<span className="checkmark" aria-hidden="true" />
|
||
<span>Только без преподавателя</span>
|
||
</label>
|
||
)}
|
||
<button
|
||
type="button"
|
||
className="btn btn-md btn-secondary"
|
||
onClick={() => void refresh()}
|
||
>
|
||
Обновить
|
||
</button>
|
||
<a
|
||
href={
|
||
editHours
|
||
? '#schedule-materials'
|
||
: '#academic-calendar'
|
||
}
|
||
>
|
||
{editHours
|
||
? 'Распределить преподавателей'
|
||
: 'Редактировать часы в графике'}
|
||
</a>
|
||
</fieldset>
|
||
{!editHours && (
|
||
<div className="materials-totals">
|
||
<div>
|
||
<span>Учебные часы всех групп</span>
|
||
<strong>{totals.academic}</strong>
|
||
</div>
|
||
<div>
|
||
<span>Нагрузка по группам</span>
|
||
<strong>{totals.workload}</strong>
|
||
</div>
|
||
<div>
|
||
<span>Без преподавателя</span>
|
||
<strong>{totals.unassigned}</strong>
|
||
</div>
|
||
</div>
|
||
)}
|
||
{loading ? (
|
||
<p role="status">Загрузка нагрузки групп…</p>
|
||
) : (
|
||
<div className="table-wrap">
|
||
<table className="materials-table">
|
||
<thead>
|
||
<tr>
|
||
<th>Группа / график</th>
|
||
<th>Дисциплина / кафедра</th>
|
||
<th>
|
||
{editHours
|
||
? 'Часы по видам нагрузки'
|
||
: 'Вид нагрузки'}
|
||
</th>
|
||
<th>Учебные часы</th>
|
||
<th>Нагрузка, ч</th>
|
||
{!editHours && <th>Преподаватель</th>}
|
||
<th>Действия</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{visibleRows.map((row) => {
|
||
const subject = details
|
||
.find(
|
||
(d) =>
|
||
d.context.groupId ===
|
||
row.context.groupId,
|
||
)
|
||
?.subjects.find(
|
||
(s) =>
|
||
s.subjectId === row.subjectId,
|
||
);
|
||
return (
|
||
<tr
|
||
key={`${row.context.groupId}-${row.subjectId}-${editHours ? 'hours' : row.category}`}
|
||
>
|
||
<td>
|
||
<strong>
|
||
{row.context.groupName}
|
||
</strong>
|
||
<small>
|
||
{row.context.calendarTitle}{' '}
|
||
·{' '}
|
||
{row.context.semesterNumber}{' '}
|
||
семестр
|
||
</small>
|
||
</td>
|
||
<td>
|
||
<strong>
|
||
{row.subjectName}
|
||
</strong>
|
||
<small>
|
||
{departmentLabel(
|
||
departments,
|
||
row.departmentId,
|
||
)}
|
||
</small>
|
||
</td>
|
||
<td>
|
||
{editHours
|
||
? LOAD_CATEGORIES.map(
|
||
(c) =>
|
||
`${c.label}: ${subject.loads.find((l) => l.category === c.key)?.academicHours || 0}`,
|
||
).join(' / ')
|
||
: LOAD_CATEGORIES.find(
|
||
(c) =>
|
||
c.key ===
|
||
row.category,
|
||
)?.label}
|
||
{!editHours &&
|
||
row.splitSubgroups && (
|
||
<small>
|
||
Две подгруппы
|
||
</small>
|
||
)}
|
||
</td>
|
||
<td>
|
||
{editHours
|
||
? subject.academicHours
|
||
: row.academicHours}
|
||
</td>
|
||
<td>
|
||
{editHours
|
||
? subject.workloadHours
|
||
: row.workloadHours}
|
||
</td>
|
||
{!editHours && (
|
||
<td>
|
||
{row.teacherName ||
|
||
'Не назначен'}
|
||
</td>
|
||
)}
|
||
<td>
|
||
<button
|
||
className="btn btn-sm btn-secondary"
|
||
type="button"
|
||
disabled={busy}
|
||
onClick={() =>
|
||
void edit(row)
|
||
}
|
||
>
|
||
{editHours
|
||
? 'Изменить часы'
|
||
: row.teacherId == null
|
||
? 'Назначить'
|
||
: 'Изменить'}
|
||
</button>
|
||
</td>
|
||
</tr>
|
||
);
|
||
})}
|
||
{!visibleRows.length && (
|
||
<tr>
|
||
<td colSpan={editHours ? 6 : 7}>
|
||
{details.length
|
||
? 'Нет строк по выбранным фильтрам. Часы добавляются в календарном графике группы.'
|
||
: 'Назначьте группам календарный график на выбранный учебный год и добавьте его дисциплины.'}
|
||
</td>
|
||
</tr>
|
||
)}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
)}
|
||
{editing && (
|
||
<form className="materials-editor" onSubmit={save}>
|
||
<fieldset
|
||
className="study-plan-fieldset"
|
||
disabled={busy}
|
||
>
|
||
<h4>
|
||
{editing.context.groupName} ·{' '}
|
||
{editing.subjectName}
|
||
</h4>
|
||
{editHours ? (
|
||
<div className="study-plan-load-grid">
|
||
{LOAD_CATEGORIES.map((c) => {
|
||
const load = draft.find(
|
||
(l) => l.category === c.key,
|
||
);
|
||
return (
|
||
<div
|
||
className="study-plan-load-card"
|
||
key={c.key}
|
||
>
|
||
<h4>{c.label}</h4>
|
||
<label className="form-group">
|
||
Академические часы
|
||
<input
|
||
type="number"
|
||
min="0"
|
||
max="100000"
|
||
step="2"
|
||
required
|
||
value={
|
||
load.academicHours
|
||
}
|
||
onChange={(e) =>
|
||
changeLoad(
|
||
c.key,
|
||
e.target.value,
|
||
)
|
||
}
|
||
/>
|
||
</label>
|
||
{c.key === 'LABORATORY' && (
|
||
<label className="checkbox-item">
|
||
<input
|
||
type="checkbox"
|
||
disabled={
|
||
!Number(
|
||
load.academicHours,
|
||
)
|
||
}
|
||
checked={
|
||
load.splitSubgroups
|
||
}
|
||
onChange={(e) =>
|
||
changeLoad(
|
||
c.key,
|
||
null,
|
||
e.target
|
||
.checked,
|
||
)
|
||
}
|
||
/>
|
||
<span
|
||
className="checkmark"
|
||
aria-hidden="true"
|
||
/>
|
||
<span>
|
||
Делить на две
|
||
подгруппы
|
||
</span>
|
||
</label>
|
||
)}
|
||
<p>
|
||
Нагрузка:{' '}
|
||
<strong>
|
||
{workloadHours(load)} ч
|
||
</strong>
|
||
</p>
|
||
</div>
|
||
);
|
||
})}
|
||
</div>
|
||
) : (
|
||
<>
|
||
<p>
|
||
{
|
||
LOAD_CATEGORIES.find(
|
||
(c) =>
|
||
c.key === editing.category,
|
||
)?.label
|
||
}{' '}
|
||
· {editing.workloadHours} ч
|
||
</p>
|
||
<AsyncCombobox
|
||
key={`${editing.context.groupId}-${editing.subjectId}-${editing.category}`}
|
||
ariaLabel="Преподаватель нагрузки группы"
|
||
load={(query) =>
|
||
fetchPlanTeachers(
|
||
editing.subjectId,
|
||
query,
|
||
)
|
||
}
|
||
selectedValue={teacher?.id || ''}
|
||
selectedLabel={
|
||
teacher?.fullName ||
|
||
teacher?.username ||
|
||
''
|
||
}
|
||
optionLabel={(item) =>
|
||
item.fullName || item.username
|
||
}
|
||
onSelect={(item) => {
|
||
setTeacher(item);
|
||
dirty.current?.mark();
|
||
}}
|
||
/>
|
||
<p>
|
||
Очистите выбор, чтобы снять назначение
|
||
только у этой группы.
|
||
</p>
|
||
</>
|
||
)}
|
||
<div className="materials-actions">
|
||
<button
|
||
className="btn btn-md btn-primary"
|
||
type="submit"
|
||
>
|
||
{editHours
|
||
? 'Сохранить часы группы'
|
||
: 'Сохранить назначение'}
|
||
</button>
|
||
<button
|
||
className="btn btn-md btn-secondary"
|
||
type="button"
|
||
onClick={close}
|
||
>
|
||
Отмена
|
||
</button>
|
||
</div>
|
||
</fieldset>
|
||
</form>
|
||
)}
|
||
</div>
|
||
{!editHours && (
|
||
<div className="card">
|
||
<h3>Фактическая нагрузка по расписанию</h3>
|
||
<p>
|
||
Потоковая лекция учитывается преподавателю один раз, а
|
||
каждой группе — как целая пара. Итоги выше отражают часы
|
||
групп; фактические итоги ниже учитывают общие занятия.
|
||
</p>
|
||
<button
|
||
className="btn btn-md btn-secondary"
|
||
type="button"
|
||
disabled={busy || !semesterId}
|
||
onClick={() => void actualWorkload()}
|
||
>
|
||
Рассчитать по расписанию
|
||
</button>
|
||
{actual && (
|
||
<div className="table-wrap">
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th>Тип</th>
|
||
<th>Преподаватель / группа</th>
|
||
<th>Пар</th>
|
||
<th>Часов</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{[
|
||
['Преподаватель', actual.teachers],
|
||
['Группа', actual.groups],
|
||
].flatMap(([type, items]) =>
|
||
items.map((item) => (
|
||
<tr
|
||
key={`${type}-${item.id}-${item.departmentId}`}
|
||
>
|
||
<td>{type}</td>
|
||
<td>{item.name}</td>
|
||
<td>{item.lessonCount}</td>
|
||
<td>{item.academicHours}</td>
|
||
</tr>
|
||
)),
|
||
)}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
)}
|
||
</div>
|
||
)}
|
||
</section>
|
||
);
|
||
}
|