Изменил метод на получение общего списка занятий. Внёс небольшие правки в FE для странички с расписанием

This commit is contained in:
ProstoDenya01
2026-03-03 17:28:20 +03:00
parent 88f1abfe25
commit 47039ee878
9 changed files with 148 additions and 41 deletions

View File

@@ -2,37 +2,43 @@ package com.magistr.app.controller;
import com.magistr.app.dto.CreateLessonRequest;
import com.magistr.app.dto.LessonResponse;
import com.magistr.app.model.Lesson;
import com.magistr.app.repository.LessonRepository;
import com.magistr.app.model.*;
import com.magistr.app.repository.*;
import com.magistr.app.utils.DayAndWeekValidator;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
@RestController
@RequestMapping("/api/users/lessons")
public class LessonsController {
private final LessonRepository lessonRepository;
private static final Logger logger = LoggerFactory.getLogger(LessonsController.class);
public LessonsController(LessonRepository lessonRepository) {
private final LessonRepository lessonRepository;
private final UserRepository teacherRepository;
private final GroupRepository groupRepository;
private final SubjectRepository subjectRepository;
private final EducationFormRepository educationFormRepository;
public LessonsController(LessonRepository lessonRepository, UserRepository teacherRepository, GroupRepository groupRepository, SubjectRepository subjectRepository, EducationFormRepository educationForm) {
this.lessonRepository = lessonRepository;
this.teacherRepository = teacherRepository;
this.groupRepository = groupRepository;
this.subjectRepository = subjectRepository;
this.educationFormRepository = educationForm;
}
@PostMapping("/create")
public ResponseEntity<?> createLesson(@RequestBody CreateLessonRequest request) {
//Полное логирование входящего запроса
logger.info("Получен запрос на создание занятия: teacherId={}, groupId={}, lessonTypeId={}, day={}, week={}, time={}",
request.getTeacherId(), request.getGroupId(), request.getLessonTypeId(), request.getDay(), request.getWeek(), request.getTime());
request.getTeacherId(), request.getGroupId(), request.getSubjectId(), request.getDay(), request.getWeek(), request.getTime());
//Проверка teacherId
if (request.getTeacherId() == null || request.getTeacherId() == 0) {
@@ -49,7 +55,7 @@ public class LessonsController {
}
//Проверка lessonTypeId
if (request.getLessonTypeId() == null || request.getLessonTypeId() == 0) {
if (request.getSubjectId() == null || request.getSubjectId() == 0) {
String errorMessage = "ID предмета обязателен";
logger.info("Ошибка валидации: {}", errorMessage);
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
@@ -88,7 +94,7 @@ public class LessonsController {
try {
Lesson lesson = new Lesson();
lesson.setTeacherId(request.getTeacherId());
lesson.setLessonTypeId(request.getLessonTypeId());
lesson.setSubjectId(request.getSubjectId());
lesson.setGroupId(request.getGroupId());
lesson.setDay(request.getDay());
lesson.setWeek(request.getWeek());
@@ -100,7 +106,7 @@ public class LessonsController {
response.put("id", savedLesson.getId());
response.put("teacherId", savedLesson.getTeacherId());
response.put("groupId", savedLesson.getGroupId());
response.put("lessonTypeId", savedLesson.getLessonTypeId());
response.put("subjectId", savedLesson.getSubjectId());
response.put("day", savedLesson.getDay());
response.put("week", savedLesson.getWeek());
response.put("time", savedLesson.getTime());
@@ -121,12 +127,46 @@ public class LessonsController {
logger.info("Запрос на получение всех занятий");
try {
List<LessonResponse> lessons = lessonRepository.findAll().stream()
.map(l -> new LessonResponse(l.getId(), l.getTeacherId(), l.getLessonTypeId(), l.getGroupId(), l.getDay(), l.getWeek(), l.getTime()))
List<Lesson> lessons = lessonRepository.findAll();
List<LessonResponse> response = lessons.stream()
.map(lesson -> {
String teacherName = teacherRepository.findById(lesson.getTeacherId())
.map(User::getUsername)
.orElse("Неизвестно");
StudentGroup group = groupRepository.findById(lesson.getGroupId()).orElse(null);
String groupName = groupRepository.findById(lesson.getGroupId())
.map(StudentGroup::getName)
.orElse("Неизвестно");
String educationFormName = "Неизвестно";
if(group != null && group.getEducationForm() != null) {
Long educationFormId = group.getEducationForm().getId();
educationFormName = educationFormRepository.findById(educationFormId)
.map(EducationForm::getName)
.orElse("Неизвестно");
}
String subjectName = subjectRepository.findById(lesson.getSubjectId())
.map(Subject::getName)
.orElse("Неизвестно");
return new LessonResponse(
lesson.getId(),
teacherName,
groupName,
educationFormName,
subjectName,
lesson.getDay(),
lesson.getWeek(),
lesson.getTime()
);
})
.toList();
logger.info("Получено {} занятий", lessons.size());
return lessons;
return response;
} catch (Exception e) {
logger.error("Ошибка при получении списка всех занятий: {}", e.getMessage(), e);
throw e;
@@ -151,7 +191,7 @@ public class LessonsController {
.map(l -> new LessonResponse(
l.getId(),
l.getTeacherId(),
l.getLessonTypeId(),
l.getSubjectId(),
l.getGroupId(),
l.getDay(),
l.getWeek(),
@@ -167,6 +207,28 @@ public class LessonsController {
}
}
@GetMapping("/debug/subjects")
public ResponseEntity<?> debugSubjects() {
Map<String, Object> result = new HashMap<>();
// Через JPA репозиторий
List<Subject> allSubjects = subjectRepository.findAll();
result.put("jpa_count", allSubjects.size());
result.put("jpa_subjects", allSubjects.stream()
.map(s -> Map.of("id", s.getId(), "name", s.getName()))
.toList());
// Проверка конкретных ID
Map<Long, Boolean> existenceCheck = new HashMap<>();
for (long id = 1; id <= 6; id++) {
boolean exists = subjectRepository.existsById(id);
existenceCheck.put(id, exists);
}
result.put("existence_check", existenceCheck);
return ResponseEntity.ok(result);
}
//Тестовый запрос на проверку доступности контроллера
@GetMapping("/ping")
public String ping() {

View File

@@ -4,7 +4,7 @@ public class CreateLessonRequest {
private Long teacherId;
private Long groupId;
private Long lessonTypeId;
private Long subjectId;
private String day;
private String week;
private String time;
@@ -28,12 +28,12 @@ public class CreateLessonRequest {
this.groupId = groupId;
}
public Long getLessonTypeId() {
return lessonTypeId;
public Long getSubjectId() {
return subjectId;
}
public void setLessonTypeId(Long lessonTypeId) {
this.lessonTypeId= lessonTypeId;
public void setSubjectId(Long subjectId) {
this.subjectId = subjectId;
}
public String getDay() {

View File

@@ -1,11 +1,19 @@
package com.magistr.app.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class LessonResponse {
private Long id;
private Long teacherId;
private String teacherName;
private Long groupId;
private Long lessonTypeId;
private String groupName;
private String educationFormName;
private Long subjectId;
private String subjectName;
private String day;
private String week;
private String time;
@@ -13,20 +21,22 @@ public class LessonResponse {
public LessonResponse() {
}
public LessonResponse(Long id, Long teacherId, Long groupId, Long lessonTypeId, String day, String week, String time) {
public LessonResponse(Long id, Long teacherId, Long groupId, Long subjectId, String day, String week, String time) {
this.id = id;
this.teacherId = teacherId;
this.groupId = groupId;
this.lessonTypeId = lessonTypeId;
this.subjectId = subjectId;
this.day = day;
this.week = week;
this.time = time;
}
public LessonResponse(Long id, Long teacherId, Long lessonTypeId, String day, String week, String time) {
public LessonResponse(Long id, String teacherName, String groupName, String educationFormName, String subjectName, String day, String week, String time) {
this.id = id;
this.teacherId = teacherId;
this.lessonTypeId = lessonTypeId;
this.teacherName = teacherName;
this.groupName = groupName;
this.educationFormName = educationFormName;
this.subjectName = subjectName;
this.day = day;
this.week = week;
this.time = time;
@@ -48,6 +58,14 @@ public class LessonResponse {
this.teacherId = teacherId;
}
public String getTeacherName() {
return teacherName;
}
public void setTeacherName(String teacherName) {
this.teacherName = teacherName;
}
public Long getGroupId() {
return groupId;
}
@@ -56,12 +74,36 @@ public class LessonResponse {
this.groupId = groupId;
}
public Long getLessonTypeId() {
return lessonTypeId;
public String getGroupName() {
return groupName;
}
public void setLessonTypeId(Long lessonTypeId) {
this.lessonTypeId = lessonTypeId;
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getEducationFormName() {
return educationFormName;
}
public void setEducationFormName(String educationFormName) {
this.educationFormName = educationFormName;
}
public Long getSubjectId() {
return subjectId;
}
public void setSubjectId(Long subjectId) {
this.subjectId = subjectId;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public String getDay() {

View File

@@ -16,8 +16,8 @@ public class Lesson {
@Column(name = "group_id", nullable = false)
private Long groupId;
@Column(name = "lesson_type_id", nullable = false)
private Long lessonTypeId;
@Column(name = "subject_id", nullable = false)
private Long subjectId;
@Column(name = "day", nullable = false, length = 255)
private String day;
@@ -55,12 +55,12 @@ public class Lesson {
this.groupId = groupId;
}
public Long getLessonTypeId() {
return lessonTypeId;
public Long getSubjectId() {
return subjectId;
}
public void setLessonTypeId(Long lessonTypeId) {
this.lessonTypeId = lessonTypeId;
public void setSubjectId(Long subjectId) {
this.subjectId = subjectId;
}
public String getDay() {

View File

@@ -8,7 +8,7 @@ import java.util.Optional;
public interface LessonRepository extends JpaRepository<Lesson, Long> {
Optional<Lesson> findByLessonTypeId(Long lessonTypeId);
Optional<Lesson> findBySubjectId(Long subjectId);
List<Lesson> findByTeacherId(Long teacherId);
}

View File

@@ -185,7 +185,7 @@ CREATE TABLE IF NOT EXISTS lessons (
id BIGSERIAL PRIMARY KEY,
teacher_id BIGINT NOT NULL REFERENCES users(id),
group_id BIGINT NOT NULL REFERENCES student_groups(id),
lesson_type_id BIGINT NOT NULL REFERENCES lesson_types(id),
subject_id BIGINT NOT NULL REFERENCES subjects(id),
day VARCHAR(255) NOT NULL,
week VARCHAR(255) NOT NULL,
time VARCHAR(255) NOT NULL

View File

@@ -27,6 +27,7 @@ export async function initSchedule() {
// Извлекаем имена из вложенных объектов или используем запасные поля
const teacherName = lesson.teacher?.username || lesson.teacherName || '—';
const groupName = lesson.group?.name || lesson.groupName || '—';
const educationForm = lesson.educationForm?.name || lesson.educationFormName || '-';
const subjectName = lesson.subject?.name || lesson.subjectName || '—';
const day = lesson.day || '—';
const week = lesson.week || '—';
@@ -36,6 +37,7 @@ export async function initSchedule() {
<td>${escapeHtml(lesson.id)}</td>
<td>${escapeHtml(teacherName)}</td>
<td>${escapeHtml(groupName)}</td>
<td>${escapeHtml(educationForm)}</td>
<td>${escapeHtml(subjectName)}</td>
<td>${escapeHtml(day)}</td>
<td>${escapeHtml(week)}</td>

View File

@@ -185,7 +185,7 @@ export async function initUsers() {
const response = await api.post('/api/users/lessons/create', {
teacherId: parseInt(userId),
groupId: parseInt(groupId),
lessonTypeId: parseInt(subjectId),
subjectId: parseInt(subjectId),
day: dayOfWeek,
week: weekType,
time: timeSlot // передаём время

View File

@@ -7,6 +7,7 @@
<th>ID</th>
<th>Преподаватель</th>
<th>Группа</th>
<th>Форма обучения</th>
<th>Дисциплина</th>
<th>День недели</th>
<th>Неделя</th>