Merge pull request 'Create-Lesson' (#5) from Create-Lesson into main
Reviewed-on: #5
This commit was merged in pull request #5.
This commit is contained in:
@@ -1 +1 @@
|
|||||||
КОММИТ12
|
тест
|
||||||
@@ -5,6 +5,7 @@ import com.magistr.app.dto.LessonResponse;
|
|||||||
import com.magistr.app.model.*;
|
import com.magistr.app.model.*;
|
||||||
import com.magistr.app.repository.*;
|
import com.magistr.app.repository.*;
|
||||||
import com.magistr.app.utils.DayAndWeekValidator;
|
import com.magistr.app.utils.DayAndWeekValidator;
|
||||||
|
import com.magistr.app.utils.TypeAndFormatLessonValidator;
|
||||||
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.*;
|
||||||
@@ -25,19 +26,22 @@ public class LessonsController {
|
|||||||
private final GroupRepository groupRepository;
|
private final GroupRepository groupRepository;
|
||||||
private final SubjectRepository subjectRepository;
|
private final SubjectRepository subjectRepository;
|
||||||
private final EducationFormRepository educationFormRepository;
|
private final EducationFormRepository educationFormRepository;
|
||||||
|
private final ClassroomRepository classroomRepository;
|
||||||
|
|
||||||
public LessonsController(LessonRepository lessonRepository, UserRepository teacherRepository, GroupRepository groupRepository, SubjectRepository subjectRepository, EducationFormRepository educationForm) {
|
public LessonsController(LessonRepository lessonRepository, UserRepository teacherRepository, GroupRepository groupRepository, SubjectRepository subjectRepository, EducationFormRepository educationForm, ClassroomRepository classroomRepository) {
|
||||||
this.lessonRepository = lessonRepository;
|
this.lessonRepository = lessonRepository;
|
||||||
this.teacherRepository = teacherRepository;
|
this.teacherRepository = teacherRepository;
|
||||||
this.groupRepository = groupRepository;
|
this.groupRepository = groupRepository;
|
||||||
this.subjectRepository = subjectRepository;
|
this.subjectRepository = subjectRepository;
|
||||||
this.educationFormRepository = educationForm;
|
this.educationFormRepository = educationForm;
|
||||||
|
this.classroomRepository = classroomRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//Создание нового занятия
|
||||||
@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={}, subjectId={}, day={}, week={}, time={}",
|
||||||
request.getTeacherId(), request.getGroupId(), request.getSubjectId(), request.getDay(), request.getWeek(), request.getTime());
|
request.getTeacherId(), request.getGroupId(), request.getSubjectId(), request.getDay(), request.getWeek(), request.getTime());
|
||||||
|
|
||||||
//Проверка teacherId
|
//Проверка teacherId
|
||||||
@@ -54,13 +58,42 @@ public class LessonsController {
|
|||||||
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
|
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
|
||||||
}
|
}
|
||||||
|
|
||||||
//Проверка lessonTypeId
|
//Проверка subjectId
|
||||||
if (request.getSubjectId() == null || request.getSubjectId() == 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));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//Проверка lessonFormat
|
||||||
|
if (request.getLessonFormat() == null || request.getLessonFormat().isBlank()) {
|
||||||
|
String errorMessage = "Выбор формата занятия обязателен";
|
||||||
|
logger.info("Ошибка валидации: {}", errorMessage);
|
||||||
|
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
|
||||||
|
} else if(!TypeAndFormatLessonValidator.isValidFormat(request.getLessonFormat())){
|
||||||
|
String errorMessage = "Некорректный формат занятий. " + TypeAndFormatLessonValidator.getValidFormatsMessage();
|
||||||
|
logger.info("Ошибка валидации формата: '{}' - {}", request.getLessonFormat(), errorMessage);
|
||||||
|
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
|
||||||
|
}
|
||||||
|
|
||||||
|
//Проверка typeLesson
|
||||||
|
if (request.getTypeLesson() == null || request.getTypeLesson().isBlank()) {
|
||||||
|
String errorMessage = "Выбор типа занятия обязателен";
|
||||||
|
logger.info("Ошибка валидации: {}", errorMessage);
|
||||||
|
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
|
||||||
|
} else if(!TypeAndFormatLessonValidator.isValidType(request.getTypeLesson())){
|
||||||
|
String errorMessage = "Некорректный тип занятия. " + TypeAndFormatLessonValidator.getValidTypesMessage();
|
||||||
|
logger.info("Ошибка валидации типа: '{}' - {}", request.getTypeLesson(), errorMessage);
|
||||||
|
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
|
||||||
|
}
|
||||||
|
|
||||||
|
//Проверка classroomId
|
||||||
|
if (request.getClassroomId() == null || request.getClassroomId() == 0) {
|
||||||
|
String errorMessage = "ID аудитории обязателен";
|
||||||
|
logger.info("Ошибка валидации: {}", errorMessage);
|
||||||
|
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
|
||||||
|
}
|
||||||
|
|
||||||
//Проверка day
|
//Проверка day
|
||||||
if (request.getDay() == null || request.getDay().isBlank()) {
|
if (request.getDay() == null || request.getDay().isBlank()) {
|
||||||
String errorMessage = "Выбор дня обязателен";
|
String errorMessage = "Выбор дня обязателен";
|
||||||
@@ -96,6 +129,9 @@ public class LessonsController {
|
|||||||
lesson.setTeacherId(request.getTeacherId());
|
lesson.setTeacherId(request.getTeacherId());
|
||||||
lesson.setSubjectId(request.getSubjectId());
|
lesson.setSubjectId(request.getSubjectId());
|
||||||
lesson.setGroupId(request.getGroupId());
|
lesson.setGroupId(request.getGroupId());
|
||||||
|
lesson.setLessonFormat(request.getLessonFormat());
|
||||||
|
lesson.setTypeLesson(request.getTypeLesson());
|
||||||
|
lesson.setClassroomId(request.getClassroomId());
|
||||||
lesson.setDay(request.getDay());
|
lesson.setDay(request.getDay());
|
||||||
lesson.setWeek(request.getWeek());
|
lesson.setWeek(request.getWeek());
|
||||||
lesson.setTime(request.getTime());
|
lesson.setTime(request.getTime());
|
||||||
@@ -107,6 +143,9 @@ public class LessonsController {
|
|||||||
response.put("teacherId", savedLesson.getTeacherId());
|
response.put("teacherId", savedLesson.getTeacherId());
|
||||||
response.put("groupId", savedLesson.getGroupId());
|
response.put("groupId", savedLesson.getGroupId());
|
||||||
response.put("subjectId", savedLesson.getSubjectId());
|
response.put("subjectId", savedLesson.getSubjectId());
|
||||||
|
response.put("formatLesson", savedLesson.getLessonFormat());
|
||||||
|
response.put("typeLesson", savedLesson.getTypeLesson());
|
||||||
|
response.put("classroomId", savedLesson.getClassroomId());
|
||||||
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());
|
||||||
@@ -122,6 +161,7 @@ public class LessonsController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//Запрос для получения всего списка занятий
|
||||||
@GetMapping
|
@GetMapping
|
||||||
public List<LessonResponse> getAllLessons() {
|
public List<LessonResponse> getAllLessons() {
|
||||||
logger.info("Запрос на получение всех занятий");
|
logger.info("Запрос на получение всех занятий");
|
||||||
@@ -152,12 +192,19 @@ public class LessonsController {
|
|||||||
.map(Subject::getName)
|
.map(Subject::getName)
|
||||||
.orElse("Неизвестно");
|
.orElse("Неизвестно");
|
||||||
|
|
||||||
|
String classroomName = classroomRepository.findById(lesson.getClassroomId())
|
||||||
|
.map(Classroom::getName)
|
||||||
|
.orElse("Неизвестно");
|
||||||
|
|
||||||
return new LessonResponse(
|
return new LessonResponse(
|
||||||
lesson.getId(),
|
lesson.getId(),
|
||||||
teacherName,
|
teacherName,
|
||||||
groupName,
|
groupName,
|
||||||
|
classroomName,
|
||||||
educationFormName,
|
educationFormName,
|
||||||
subjectName,
|
subjectName,
|
||||||
|
lesson.getTypeLesson(),
|
||||||
|
lesson.getLessonFormat(),
|
||||||
lesson.getDay(),
|
lesson.getDay(),
|
||||||
lesson.getWeek(),
|
lesson.getWeek(),
|
||||||
lesson.getTime()
|
lesson.getTime()
|
||||||
@@ -173,6 +220,7 @@ public class LessonsController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//Запрос на получение всех занятий для конкретного преподавателя
|
||||||
@GetMapping("/{teacherId}")
|
@GetMapping("/{teacherId}")
|
||||||
public ResponseEntity<?> getLessonsById(@PathVariable Long teacherId) {
|
public ResponseEntity<?> getLessonsById(@PathVariable Long teacherId) {
|
||||||
logger.info("Запрос на получение занятий для преподавателя с ID: {}", teacherId);
|
logger.info("Запрос на получение занятий для преподавателя с ID: {}", teacherId);
|
||||||
@@ -188,17 +236,49 @@ public class LessonsController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
List<LessonResponse> lessonResponses = lessons.stream()
|
List<LessonResponse> lessonResponses = lessons.stream()
|
||||||
.map(l -> new LessonResponse(
|
.map(lesson -> {
|
||||||
l.getId(),
|
String teacherName = teacherRepository.findById(lesson.getTeacherId())
|
||||||
l.getTeacherId(),
|
.map(User::getUsername)
|
||||||
l.getSubjectId(),
|
.orElse("Неизвестно");
|
||||||
l.getGroupId(),
|
|
||||||
l.getDay(),
|
StudentGroup group = groupRepository.findById(lesson.getGroupId()).orElse(null);
|
||||||
l.getWeek(),
|
String groupName = groupRepository.findById(lesson.getGroupId())
|
||||||
l.getTime()
|
.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("Неизвестно");
|
||||||
|
|
||||||
|
String classroomName = classroomRepository.findById(lesson.getClassroomId())
|
||||||
|
.map(Classroom::getName)
|
||||||
|
.orElse("Неизвестно");
|
||||||
|
|
||||||
|
return new LessonResponse(
|
||||||
|
lesson.getId(),
|
||||||
|
teacherName,
|
||||||
|
groupName,
|
||||||
|
classroomName,
|
||||||
|
educationFormName,
|
||||||
|
subjectName,
|
||||||
|
lesson.getTypeLesson(),
|
||||||
|
lesson.getLessonFormat(),
|
||||||
|
lesson.getDay(),
|
||||||
|
lesson.getWeek(),
|
||||||
|
lesson.getTime()
|
||||||
|
);
|
||||||
|
})
|
||||||
.toList();
|
.toList();
|
||||||
logger.info("Найдено {} занянтий для преподавателя с ID: {}", lessonResponses.size(), teacherId);
|
|
||||||
|
logger.info("Найдено {} занятий для преподавателя с ID: {}", lessonResponses.size(), teacherId);
|
||||||
return ResponseEntity.ok(lessonResponses);
|
return ResponseEntity.ok(lessonResponses);
|
||||||
} catch (Exception e ){
|
} catch (Exception e ){
|
||||||
logger.error("Ошибка при получении занятий для преподавателя с ID {}: {}", teacherId, e.getMessage(), e);
|
logger.error("Ошибка при получении занятий для преподавателя с ID {}: {}", teacherId, e.getMessage(), e);
|
||||||
@@ -207,28 +287,6 @@ 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() {
|
||||||
@@ -237,4 +295,213 @@ public class LessonsController {
|
|||||||
logger.debug("Ответ на ping: {}", response);
|
logger.debug("Ответ на ping: {}", response);
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//Удаление занятия по его ID
|
||||||
|
@DeleteMapping("/delete/{lessonId}")
|
||||||
|
public ResponseEntity<?> deleteLessonById(@PathVariable Long lessonId){
|
||||||
|
logger.info("Запрос на удаление занятия по ID: {}", lessonId);
|
||||||
|
if(!lessonRepository.existsById(lessonId)) {
|
||||||
|
return ResponseEntity.badRequest().body(Map.of("message", "Занятие не найдено"));
|
||||||
|
}
|
||||||
|
lessonRepository.deleteById(lessonId);
|
||||||
|
logger.info("Занятие с ID - {} успешно удалено", lessonId);
|
||||||
|
return ResponseEntity.ok(Map.of("message", "Занятие успешно удалено"));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
//Обновление занятия по его ID
|
||||||
|
@PutMapping("/update/{lessonId}")
|
||||||
|
public ResponseEntity<?> updateLessonById(@PathVariable Long lessonId, @RequestBody CreateLessonRequest request) {
|
||||||
|
logger.info("Получен запрос на обновление занятия с ID - {}", lessonId);
|
||||||
|
logger.info("Данные для обновления: teacherId={}, groupId={}, subjectId={}, lessonFormat={}, typeLesson={}, classroomId={}, day={}, week={}, time={}",
|
||||||
|
request.getTeacherId(), request.getGroupId(), request.getSubjectId(), request.getLessonFormat(), request.getTypeLesson(), request.getClassroomId(),
|
||||||
|
request.getDay(), request.getWeek(), request.getTime());
|
||||||
|
|
||||||
|
try {
|
||||||
|
//Проверка на наличие записи
|
||||||
|
Lesson existingLesson = lessonRepository.findById(lessonId).orElse(null);
|
||||||
|
|
||||||
|
if(existingLesson == null) {
|
||||||
|
String errorMessage = "Занятие с ID " + lessonId + " не найдено";
|
||||||
|
logger.info("Ошибка: {}", errorMessage);
|
||||||
|
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("message", errorMessage));
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean hasChanges = false;
|
||||||
|
Map<String, Object> changes = new LinkedHashMap<>();
|
||||||
|
|
||||||
|
//Проверка и обновление teacherId, если он передан и отличается
|
||||||
|
if(request.getTeacherId() != null) {
|
||||||
|
if(!request.getTeacherId().equals(existingLesson.getTeacherId())) {
|
||||||
|
if(request.getTeacherId() == 0) {
|
||||||
|
return ResponseEntity.badRequest()
|
||||||
|
.body(Map.of("message", "ID преподавателя не может быть равен 0"));
|
||||||
|
}
|
||||||
|
existingLesson.setTeacherId(request.getTeacherId());
|
||||||
|
changes.put("teacherId", request.getTeacherId());
|
||||||
|
hasChanges = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Проверка и обновление groupId, если он передан и отличается
|
||||||
|
if(request.getGroupId() != null) {
|
||||||
|
if(!request.getGroupId().equals(existingLesson.getGroupId())) {
|
||||||
|
if(request.getGroupId() == 0) {
|
||||||
|
return ResponseEntity.badRequest()
|
||||||
|
.body(Map.of("message", "ID группы не может быть равен 0"));
|
||||||
|
}
|
||||||
|
existingLesson.setGroupId(request.getGroupId());
|
||||||
|
changes.put("groupId", request.getGroupId());
|
||||||
|
hasChanges = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Проверка и обновление subjectId, если он передан и отличается
|
||||||
|
if(request.getSubjectId() != null) {
|
||||||
|
if(!request.getSubjectId().equals(existingLesson.getSubjectId())) {
|
||||||
|
if(request.getSubjectId() == 0) {
|
||||||
|
return ResponseEntity.badRequest()
|
||||||
|
.body(Map.of("message", "ID дисциплины не может быть равен 0"));
|
||||||
|
}
|
||||||
|
existingLesson.setSubjectId(request.getSubjectId());
|
||||||
|
changes.put("subjectId", request.getSubjectId());
|
||||||
|
hasChanges = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Проверка и обновление lessonFormat, если он передан и отличается
|
||||||
|
if(request.getLessonFormat() != null) {
|
||||||
|
if(!request.getLessonFormat().equals(existingLesson.getLessonFormat())) {
|
||||||
|
if(request.getLessonFormat().isBlank()) {
|
||||||
|
return ResponseEntity.badRequest()
|
||||||
|
.body(Map.of("message", "Формат занятия не может быть пустым"));
|
||||||
|
}
|
||||||
|
if(!TypeAndFormatLessonValidator.isValidFormat(request.getLessonFormat())) {
|
||||||
|
String errorMessage = "Некорректный формат занятий. " + TypeAndFormatLessonValidator.getValidFormatsMessage();
|
||||||
|
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
|
||||||
|
}
|
||||||
|
existingLesson.setLessonFormat(request.getLessonFormat());
|
||||||
|
changes.put("lessonFormat", request.getLessonFormat());
|
||||||
|
hasChanges = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Проверка и обновление typeLesson, если он передан и отличается
|
||||||
|
if(request.getTypeLesson() != null) {
|
||||||
|
if(!request.getTypeLesson().equals(existingLesson.getTypeLesson())) {
|
||||||
|
if(request.getTypeLesson().isBlank()) {
|
||||||
|
return ResponseEntity.badRequest()
|
||||||
|
.body(Map.of("message", "Тип занятия не может быть пустым"));
|
||||||
|
}
|
||||||
|
if(!TypeAndFormatLessonValidator.isValidType(request.getTypeLesson())) {
|
||||||
|
String errorMessage = "Некорректный тип занятий. " + TypeAndFormatLessonValidator.getValidTypesMessage();
|
||||||
|
return ResponseEntity.badRequest().body(Map.of("message", errorMessage));
|
||||||
|
}
|
||||||
|
existingLesson.setLessonFormat(request.getTypeLesson());
|
||||||
|
changes.put("typeLesson", request.getTypeLesson());
|
||||||
|
hasChanges = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Проверка и обновление classroomId, если он передан и отличается
|
||||||
|
if(request.getClassroomId() != null) {
|
||||||
|
if(!request.getClassroomId().equals(existingLesson.getClassroomId())) {
|
||||||
|
if(request.getClassroomId() == 0) {
|
||||||
|
return ResponseEntity.badRequest()
|
||||||
|
.body(Map.of("message", "ID аудитории не можеть быть равен 0"));
|
||||||
|
}
|
||||||
|
existingLesson.setClassroomId(request.getClassroomId());
|
||||||
|
changes.put("classroomId", request.getClassroomId());
|
||||||
|
hasChanges = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Проверка и обновление day, если он передан и отличается
|
||||||
|
if(request.getDay() != null){
|
||||||
|
if(!request.getDay().equals(existingLesson.getDay())) {
|
||||||
|
if(request.getDay().isBlank()) {
|
||||||
|
return ResponseEntity.badRequest()
|
||||||
|
.body(Map.of("message", "Поле \"День\" не может быть пустым"));
|
||||||
|
}
|
||||||
|
if(!DayAndWeekValidator.isValidDay(request.getDay())) {
|
||||||
|
String errorMessage = "Некорректный день. " + DayAndWeekValidator.getValidDaysMessage();
|
||||||
|
return ResponseEntity.badRequest()
|
||||||
|
.body(Map.of("message", errorMessage));
|
||||||
|
}
|
||||||
|
existingLesson.setDay(request.getDay());
|
||||||
|
changes.put("day", request.getDay());
|
||||||
|
hasChanges = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Проверка и обновление week, если он передан и отличается
|
||||||
|
if(request.getWeek() != null) {
|
||||||
|
if(!request.getWeek().equals(existingLesson.getWeek())) {
|
||||||
|
if (request.getWeek().isBlank()) {
|
||||||
|
return ResponseEntity.badRequest()
|
||||||
|
.body(Map.of("message", "Поле \"Неделя\" не может быть пустым"));
|
||||||
|
}
|
||||||
|
if (!DayAndWeekValidator.isValidWeek(request.getWeek())) {
|
||||||
|
String errorMessage = "Некорректная неделя. " + DayAndWeekValidator.getValidWeekMessage();
|
||||||
|
return ResponseEntity.badRequest()
|
||||||
|
.body((Map.of("message", errorMessage)));
|
||||||
|
}
|
||||||
|
existingLesson.setWeek(request.getWeek());
|
||||||
|
changes.put("week", request.getWeek());
|
||||||
|
hasChanges = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Проверка и обновление time, если он передан и отличается
|
||||||
|
if(request.getTime() != null) {
|
||||||
|
if(!request.getTime().equals(existingLesson.getTime())) {
|
||||||
|
if(request.getTime().isBlank()){
|
||||||
|
return ResponseEntity.badRequest()
|
||||||
|
.body(Map.of("message", "Поле \"Время\" не может быть пустым"));
|
||||||
|
}
|
||||||
|
existingLesson.setTime(request.getTime());
|
||||||
|
changes.put("time", request.getTime());
|
||||||
|
hasChanges = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if(!hasChanges) {
|
||||||
|
logger.info("Обновление не требуется - все полня идентичны существующим для занятия с ID: {}", lessonId);
|
||||||
|
|
||||||
|
Map<String, Object> response = buildResponse(existingLesson);
|
||||||
|
response.put("message", "Изменений не обнаружено");
|
||||||
|
return ResponseEntity.ok(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
Lesson updatedLesson = lessonRepository.save(existingLesson);
|
||||||
|
|
||||||
|
Map<String, Object> response = buildResponse(updatedLesson);
|
||||||
|
response.put("updatedFields", changes);
|
||||||
|
response.put("message", "Занятие успешно обновлено");
|
||||||
|
|
||||||
|
logger.info("Занятие с ID - {} успешно обновлено. Изменения: {}", lessonId, changes);
|
||||||
|
|
||||||
|
return ResponseEntity.ok(response);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error("Ошибка при обновлении занятия с ID {}: {}", lessonId, e.getMessage(),e);
|
||||||
|
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||||
|
.body(Map.of("message", "Произошла ошибка при обновлении занятия: " + e.getMessage()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> buildResponse(Lesson lesson) {
|
||||||
|
Map<String, Object> response = new LinkedHashMap<>();
|
||||||
|
response.put("id", lesson.getId());
|
||||||
|
response.put("teacherId", lesson.getTeacherId());
|
||||||
|
response.put("groupId", lesson.getGroupId());
|
||||||
|
response.put("subjectId", lesson.getSubjectId());
|
||||||
|
response.put("LessonFormat", lesson.getLessonFormat());
|
||||||
|
response.put("typeLesson", lesson.getTypeLesson());
|
||||||
|
response.put("classroomId", lesson.getClassroomId());
|
||||||
|
response.put("day", lesson.getDay());
|
||||||
|
response.put("week", lesson.getWeek());
|
||||||
|
response.put("time", lesson.getTime());
|
||||||
|
return response;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,9 @@ public class CreateLessonRequest {
|
|||||||
private Long teacherId;
|
private Long teacherId;
|
||||||
private Long groupId;
|
private Long groupId;
|
||||||
private Long subjectId;
|
private Long subjectId;
|
||||||
|
private String lessonFormat;
|
||||||
|
private String typeLesson;
|
||||||
|
private Long classroomId;
|
||||||
private String day;
|
private String day;
|
||||||
private String week;
|
private String week;
|
||||||
private String time;
|
private String time;
|
||||||
@@ -36,6 +39,30 @@ public class CreateLessonRequest {
|
|||||||
this.subjectId = subjectId;
|
this.subjectId = subjectId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getLessonFormat() {
|
||||||
|
return lessonFormat;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLessonFormat(String lessonFormat) {
|
||||||
|
this.lessonFormat = lessonFormat;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTypeLesson() {
|
||||||
|
return typeLesson;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTypeLesson(String typeLesson) {
|
||||||
|
this.typeLesson = typeLesson;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getClassroomId() {
|
||||||
|
return classroomId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setClassroomId(Long classroomId) {
|
||||||
|
this.classroomId = classroomId;
|
||||||
|
}
|
||||||
|
|
||||||
public String getDay() {
|
public String getDay() {
|
||||||
return day;
|
return day;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,10 @@ public class LessonResponse {
|
|||||||
private String educationFormName;
|
private String educationFormName;
|
||||||
private Long subjectId;
|
private Long subjectId;
|
||||||
private String subjectName;
|
private String subjectName;
|
||||||
|
private String lessonFormat;
|
||||||
|
private String typeLesson;
|
||||||
|
private Long classroomId;
|
||||||
|
private String classroomName;
|
||||||
private String day;
|
private String day;
|
||||||
private String week;
|
private String week;
|
||||||
private String time;
|
private String time;
|
||||||
@@ -31,12 +35,15 @@ public class LessonResponse {
|
|||||||
this.time = time;
|
this.time = time;
|
||||||
}
|
}
|
||||||
|
|
||||||
public LessonResponse(Long id, String teacherName, String groupName, String educationFormName, String subjectName, String day, String week, String time) {
|
public LessonResponse(Long id, String teacherName, String groupName, String classroomName, String educationFormName, String subjectName, String typeLesson, String lessonFormat, String day, String week, String time) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
this.teacherName = teacherName;
|
this.teacherName = teacherName;
|
||||||
this.groupName = groupName;
|
this.groupName = groupName;
|
||||||
|
this.classroomName = classroomName;
|
||||||
this.educationFormName = educationFormName;
|
this.educationFormName = educationFormName;
|
||||||
this.subjectName = subjectName;
|
this.subjectName = subjectName;
|
||||||
|
this.typeLesson = typeLesson;
|
||||||
|
this.lessonFormat = lessonFormat;
|
||||||
this.day = day;
|
this.day = day;
|
||||||
this.week = week;
|
this.week = week;
|
||||||
this.time = time;
|
this.time = time;
|
||||||
@@ -82,6 +89,38 @@ public class LessonResponse {
|
|||||||
this.groupName = groupName;
|
this.groupName = groupName;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getTypeLesson() {
|
||||||
|
return typeLesson;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTypeLesson(String typeLesson) {
|
||||||
|
this.typeLesson = typeLesson;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLessonFormat() {
|
||||||
|
return lessonFormat;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLessonFormat(String lessonFormat) {
|
||||||
|
this.lessonFormat = lessonFormat;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getClassroomId() {
|
||||||
|
return classroomId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setClassroomId(Long classroomId) {
|
||||||
|
this.classroomId = classroomId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getClassroomName() {
|
||||||
|
return classroomName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setClassroomName(String classroomName) {
|
||||||
|
this.classroomName = classroomName;
|
||||||
|
}
|
||||||
|
|
||||||
public String getEducationFormName() {
|
public String getEducationFormName() {
|
||||||
return educationFormName;
|
return educationFormName;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,6 +19,15 @@ public class Lesson {
|
|||||||
@Column(name = "subject_id", nullable = false)
|
@Column(name = "subject_id", nullable = false)
|
||||||
private Long subjectId;
|
private Long subjectId;
|
||||||
|
|
||||||
|
@Column(name = "lesson_format", nullable = false, length = 255)
|
||||||
|
private String lessonFormat;
|
||||||
|
|
||||||
|
@Column(name = "type_lesson", nullable = false, length = 255)
|
||||||
|
private String typeLesson;
|
||||||
|
|
||||||
|
@Column(name = "classroom_id", nullable = false)
|
||||||
|
private Long classroomId;
|
||||||
|
|
||||||
@Column(name = "day", nullable = false, length = 255)
|
@Column(name = "day", nullable = false, length = 255)
|
||||||
private String day;
|
private String day;
|
||||||
|
|
||||||
@@ -63,6 +72,30 @@ public class Lesson {
|
|||||||
this.subjectId = subjectId;
|
this.subjectId = subjectId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getLessonFormat() {
|
||||||
|
return lessonFormat;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLessonFormat(String lessonFormat) {
|
||||||
|
this.lessonFormat = lessonFormat;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTypeLesson() {
|
||||||
|
return typeLesson;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTypeLesson(String typeLesson) {
|
||||||
|
this.typeLesson = typeLesson;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getClassroomId() {
|
||||||
|
return classroomId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setClassroomId(Long classroomId) {
|
||||||
|
this.classroomId = classroomId;
|
||||||
|
}
|
||||||
|
|
||||||
public String getDay() {
|
public String getDay() {
|
||||||
return day;
|
return day;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.magistr.app.utils;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
public class TypeAndFormatLessonValidator {
|
||||||
|
|
||||||
|
private static final Set<String> VALID_TYPES = Set.of(
|
||||||
|
"Лекция", "Лабораторная работа", "Практическая работа"
|
||||||
|
);
|
||||||
|
|
||||||
|
private static final Set<String> VALID_FORMATS = Set.of(
|
||||||
|
"Онлайн", "Очно"
|
||||||
|
);
|
||||||
|
|
||||||
|
public static boolean isValidType(String type) {
|
||||||
|
return type != null && VALID_TYPES.contains(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isValidFormat(String format) {
|
||||||
|
return format != null && VALID_FORMATS.contains(format);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getValidTypesMessage() {
|
||||||
|
return "Допустимые типы: " + String.join(", ", VALID_TYPES);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getValidFormatsMessage() {
|
||||||
|
return "Допустимые форматы: " + String.join(", ", VALID_FORMATS);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,7 +17,8 @@ CREATE TABLE IF NOT EXISTS users (
|
|||||||
|
|
||||||
-- Админ по умолчанию: admin / admin (bcrypt через pgcrypto)
|
-- Админ по умолчанию: admin / admin (bcrypt через pgcrypto)
|
||||||
INSERT INTO users (username, password, role)
|
INSERT INTO users (username, password, role)
|
||||||
VALUES ('admin', crypt('admin', gen_salt('bf', 10)), 'ADMIN')
|
VALUES ('admin', crypt('admin', gen_salt('bf', 10)), 'ADMIN'),
|
||||||
|
('Тестовый преподаватель', '1234567890', 'TEACHER')
|
||||||
ON CONFLICT (username) DO NOTHING;
|
ON CONFLICT (username) DO NOTHING;
|
||||||
|
|
||||||
-- ==========================================
|
-- ==========================================
|
||||||
@@ -186,11 +187,22 @@ CREATE TABLE IF NOT EXISTS lessons (
|
|||||||
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),
|
||||||
subject_id BIGINT NOT NULL REFERENCES subjects(id),
|
subject_id BIGINT NOT NULL REFERENCES subjects(id),
|
||||||
|
lesson_format VARCHAR(255) NOT NULL,
|
||||||
|
type_lesson VARCHAR(255) NOT NULL,
|
||||||
|
classroom_id BIGINT NOT NULL REFERENCES classrooms(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
|
||||||
);
|
);
|
||||||
|
|
||||||
|
INSERT INTO lessons (teacher_id, group_id, subject_id, lesson_format, type_lesson, classroom_id, day, week, time) VALUES
|
||||||
|
(2, 1, 1, 'Очно', 'Лекция', 1, 'Понедельник', 'Верхняя', '11:40 - 13:10'),
|
||||||
|
(1, 1, 2, 'Онлайн', 'Практическая работа', 2, 'Вторник', 'Нижняя', '15:00 - 16:30'),
|
||||||
|
(2, 1, 3, 'Очно', 'Лабораторная работа', 3, 'Среда', 'Верхняя', '8:00 - 9:30'),
|
||||||
|
(1, 1, 4, 'Онлайн', 'Лекция', 1, 'Четверг', 'Нижняя', '11:40 - 13:10'),
|
||||||
|
(2, 1, 5, 'Очно', 'Практическая работа', 2, 'Пятница', 'Верхняя', '15:00 - 16:30'),
|
||||||
|
(1, 1, 3, 'Онлайн', 'Лабораторная работа', 3, 'Суббота', 'Нижняя', '8:00 - 9:30');
|
||||||
|
|
||||||
-- ==========================================
|
-- ==========================================
|
||||||
-- Функция обновления timestamp
|
-- Функция обновления timestamp
|
||||||
-- ==========================================
|
-- ==========================================
|
||||||
|
|||||||
@@ -232,10 +232,16 @@ export async function initSchedule() {
|
|||||||
return (lesson.teacher?.username || lesson.teacherName || '').toLowerCase();
|
return (lesson.teacher?.username || lesson.teacherName || '').toLowerCase();
|
||||||
case 'group':
|
case 'group':
|
||||||
return (lesson.group?.name || lesson.groupName || '').toLowerCase();
|
return (lesson.group?.name || lesson.groupName || '').toLowerCase();
|
||||||
|
case 'classroomName':
|
||||||
|
return (lesson.classroomName?.name || lesson.classroomName || '').toLowerCase();
|
||||||
case 'educationForm':
|
case 'educationForm':
|
||||||
return (lesson.educationForm?.name || lesson.educationFormName || '').toLowerCase();
|
return (lesson.educationForm?.name || lesson.educationFormName || '').toLowerCase();
|
||||||
case 'subject':
|
case 'subject':
|
||||||
return (lesson.subject?.name || lesson.subjectName || '').toLowerCase();
|
return (lesson.subject?.name || lesson.subjectName || '').toLowerCase();
|
||||||
|
case 'lessonFormat':
|
||||||
|
return (lesson.lessonFormat?.name || lesson.lessonFormat || '').toLowerCase();
|
||||||
|
case 'typeLesson':
|
||||||
|
return (lesson.typeLesson?.name || lesson.typeLesson || '').toLowerCase();
|
||||||
case 'day': {
|
case 'day': {
|
||||||
const d = (lesson.day || '').toLowerCase();
|
const d = (lesson.day || '').toLowerCase();
|
||||||
return dayOrder[d] ?? 99;
|
return dayOrder[d] ?? 99;
|
||||||
@@ -335,8 +341,11 @@ export async function initSchedule() {
|
|||||||
tbody.innerHTML = sorted.map(lesson => {
|
tbody.innerHTML = sorted.map(lesson => {
|
||||||
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 classroomName = lesson.classroom?.name || lesson.classroomName || '—';
|
||||||
const educationForm = lesson.educationForm?.name || lesson.educationFormName || '-';
|
const educationForm = lesson.educationForm?.name || lesson.educationFormName || '-';
|
||||||
const subjectName = lesson.subject?.name || lesson.subjectName || '—';
|
const subjectName = lesson.subject?.name || lesson.subjectName || '—';
|
||||||
|
const lessonFormat = lesson.lessonFormat?.name || lesson.lessonFormat || '—';
|
||||||
|
const typeLesson = lesson.typeLesson?.name || lesson.typeLesson || '—';
|
||||||
const day = lesson.day || '—';
|
const day = lesson.day || '—';
|
||||||
const week = lesson.week || '—';
|
const week = lesson.week || '—';
|
||||||
const time = lesson.time || '—';
|
const time = lesson.time || '—';
|
||||||
@@ -345,8 +354,11 @@ 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(classroomName)}</td>
|
||||||
<td>${escapeHtml(educationForm)}</td>
|
<td>${escapeHtml(educationForm)}</td>
|
||||||
<td>${escapeHtml(subjectName)}</td>
|
<td>${escapeHtml(subjectName)}</td>
|
||||||
|
<td>${escapeHtml(lessonFormat)}</td>
|
||||||
|
<td>${escapeHtml(typeLesson)}</td>
|
||||||
<td>${escapeHtml(day)}</td>
|
<td>${escapeHtml(day)}</td>
|
||||||
<td>${escapeHtml(week)}</td>
|
<td>${escapeHtml(week)}</td>
|
||||||
<td>${escapeHtml(time)}</td>
|
<td>${escapeHtml(time)}</td>
|
||||||
|
|||||||
@@ -11,12 +11,21 @@
|
|||||||
<th class="filterable" data-filter-key="group">
|
<th class="filterable" data-filter-key="group">
|
||||||
Группа <span class="filter-icon">▾</span>
|
Группа <span class="filter-icon">▾</span>
|
||||||
</th>
|
</th>
|
||||||
|
<th class="filterable" data-filter-key="classroomName">
|
||||||
|
Аудитория <span class="filter-icon">▾</span>
|
||||||
|
</th>
|
||||||
<th class="filterable" data-filter-key="educationForm">
|
<th class="filterable" data-filter-key="educationForm">
|
||||||
Форма обучения <span class="filter-icon">▾</span>
|
Форма обучения <span class="filter-icon">▾</span>
|
||||||
</th>
|
</th>
|
||||||
<th class="filterable" data-filter-key="subject">
|
<th class="filterable" data-filter-key="subject">
|
||||||
Дисциплина <span class="filter-icon">▾</span>
|
Дисциплина <span class="filter-icon">▾</span>
|
||||||
</th>
|
</th>
|
||||||
|
<th class="filterable" data-filter-key="lessonFormat">
|
||||||
|
Формат занятия <span class="filter-icon">▾</span>
|
||||||
|
</th>
|
||||||
|
<th class="filterable" data-filter-key="typeLesson">
|
||||||
|
Тип занятия <span class="filter-icon">▾</span>
|
||||||
|
</th>
|
||||||
<th class="filterable" data-filter-key="day">
|
<th class="filterable" data-filter-key="day">
|
||||||
День недели <span class="filter-icon">▾</span>
|
День недели <span class="filter-icon">▾</span>
|
||||||
</th>
|
</th>
|
||||||
|
|||||||
Reference in New Issue
Block a user