Изменил метод на получение общего списка занятий. Внёс небольшие правки в 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.CreateLessonRequest;
import com.magistr.app.dto.LessonResponse; import com.magistr.app.dto.LessonResponse;
import com.magistr.app.model.Lesson; import com.magistr.app.model.*;
import com.magistr.app.repository.LessonRepository; import com.magistr.app.repository.*;
import com.magistr.app.utils.DayAndWeekValidator; import com.magistr.app.utils.DayAndWeekValidator;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.Collections; import java.util.*;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
@RestController @RestController
@RequestMapping("/api/users/lessons") @RequestMapping("/api/users/lessons")
public class LessonsController { public class LessonsController {
private final LessonRepository lessonRepository;
private static final Logger logger = LoggerFactory.getLogger(LessonsController.class); 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.lessonRepository = lessonRepository;
this.teacherRepository = teacherRepository;
this.groupRepository = groupRepository;
this.subjectRepository = subjectRepository;
this.educationFormRepository = educationForm;
} }
@PostMapping("/create") @PostMapping("/create")
public ResponseEntity<?> createLesson(@RequestBody CreateLessonRequest request) { public ResponseEntity<?> createLesson(@RequestBody CreateLessonRequest request) {
//Полное логирование входящего запроса //Полное логирование входящего запроса
logger.info("Получен запрос на создание занятия: teacherId={}, groupId={}, lessonTypeId={}, day={}, week={}, time={}", 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 //Проверка teacherId
if (request.getTeacherId() == null || request.getTeacherId() == 0) { if (request.getTeacherId() == null || request.getTeacherId() == 0) {
@@ -49,7 +55,7 @@ public class LessonsController {
} }
//Проверка lessonTypeId //Проверка lessonTypeId
if (request.getLessonTypeId() == null || request.getLessonTypeId() == 0) { if (request.getSubjectId() == null || request.getSubjectId() == 0) {
String errorMessage = "ID предмета обязателен"; String errorMessage = "ID предмета обязателен";
logger.info("Ошибка валидации: {}", errorMessage); logger.info("Ошибка валидации: {}", errorMessage);
return ResponseEntity.badRequest().body(Map.of("message", errorMessage)); return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
@@ -88,7 +94,7 @@ public class LessonsController {
try { try {
Lesson lesson = new Lesson(); Lesson lesson = new Lesson();
lesson.setTeacherId(request.getTeacherId()); lesson.setTeacherId(request.getTeacherId());
lesson.setLessonTypeId(request.getLessonTypeId()); lesson.setSubjectId(request.getSubjectId());
lesson.setGroupId(request.getGroupId()); lesson.setGroupId(request.getGroupId());
lesson.setDay(request.getDay()); lesson.setDay(request.getDay());
lesson.setWeek(request.getWeek()); lesson.setWeek(request.getWeek());
@@ -100,7 +106,7 @@ public class LessonsController {
response.put("id", savedLesson.getId()); response.put("id", savedLesson.getId());
response.put("teacherId", savedLesson.getTeacherId()); response.put("teacherId", savedLesson.getTeacherId());
response.put("groupId", savedLesson.getGroupId()); response.put("groupId", savedLesson.getGroupId());
response.put("lessonTypeId", savedLesson.getLessonTypeId()); response.put("subjectId", savedLesson.getSubjectId());
response.put("day", savedLesson.getDay()); response.put("day", savedLesson.getDay());
response.put("week", savedLesson.getWeek()); response.put("week", savedLesson.getWeek());
response.put("time", savedLesson.getTime()); response.put("time", savedLesson.getTime());
@@ -121,12 +127,46 @@ public class LessonsController {
logger.info("Запрос на получение всех занятий"); logger.info("Запрос на получение всех занятий");
try { try {
List<LessonResponse> lessons = lessonRepository.findAll().stream() List<Lesson> lessons = lessonRepository.findAll();
.map(l -> new LessonResponse(l.getId(), l.getTeacherId(), l.getLessonTypeId(), l.getGroupId(), l.getDay(), l.getWeek(), l.getTime()))
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(); .toList();
logger.info("Получено {} занятий", lessons.size()); logger.info("Получено {} занятий", lessons.size());
return lessons; return response;
} catch (Exception e) { } catch (Exception e) {
logger.error("Ошибка при получении списка всех занятий: {}", e.getMessage(), e); logger.error("Ошибка при получении списка всех занятий: {}", e.getMessage(), e);
throw e; throw e;
@@ -151,7 +191,7 @@ public class LessonsController {
.map(l -> new LessonResponse( .map(l -> new LessonResponse(
l.getId(), l.getId(),
l.getTeacherId(), l.getTeacherId(),
l.getLessonTypeId(), l.getSubjectId(),
l.getGroupId(), l.getGroupId(),
l.getDay(), l.getDay(),
l.getWeek(), 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") @GetMapping("/ping")
public String ping() { public String ping() {

View File

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

View File

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

View File

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

View File

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

View File

@@ -185,7 +185,7 @@ CREATE TABLE IF NOT EXISTS lessons (
id BIGSERIAL PRIMARY KEY, id BIGSERIAL PRIMARY KEY,
teacher_id BIGINT NOT NULL REFERENCES users(id), teacher_id BIGINT NOT NULL REFERENCES users(id),
group_id BIGINT NOT NULL REFERENCES student_groups(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, day VARCHAR(255) NOT NULL,
week VARCHAR(255) NOT NULL, week VARCHAR(255) NOT NULL,
time 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 teacherName = lesson.teacher?.username || lesson.teacherName || '—';
const groupName = lesson.group?.name || lesson.groupName || '—'; const groupName = lesson.group?.name || lesson.groupName || '—';
const educationForm = lesson.educationForm?.name || lesson.educationFormName || '-';
const subjectName = lesson.subject?.name || lesson.subjectName || '—'; const subjectName = lesson.subject?.name || lesson.subjectName || '—';
const day = lesson.day || '—'; const day = lesson.day || '—';
const week = lesson.week || '—'; const week = lesson.week || '—';
@@ -36,6 +37,7 @@ export async function initSchedule() {
<td>${escapeHtml(lesson.id)}</td> <td>${escapeHtml(lesson.id)}</td>
<td>${escapeHtml(teacherName)}</td> <td>${escapeHtml(teacherName)}</td>
<td>${escapeHtml(groupName)}</td> <td>${escapeHtml(groupName)}</td>
<td>${escapeHtml(educationForm)}</td>
<td>${escapeHtml(subjectName)}</td> <td>${escapeHtml(subjectName)}</td>
<td>${escapeHtml(day)}</td> <td>${escapeHtml(day)}</td>
<td>${escapeHtml(week)}</td> <td>${escapeHtml(week)}</td>

View File

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

View File

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