Ого, вау, переделал всю структуру, мне это очень понравилось

This commit is contained in:
ArtemEmelyanov 2023-05-15 19:04:10 +04:00
parent 6a334b2d25
commit 58280603ce
13 changed files with 305 additions and 164 deletions

Binary file not shown.

View File

@ -2,5 +2,6 @@ export default class Group{
constructor(data) {
this.id = data?.id;
this.name = data?.name;
this.subjectIds = data?.subjectIds;
}
}

View File

@ -6,30 +6,102 @@
<thead>
<tr>
<th>Имя</th>
<th></th>
<th>Действия</th>
<th>Работа с группой</th>
<th>Работа с предметами</th>
</tr>
</thead>
<tbody>
<tr v-for="grp in groups" :key="grp.id">
<td>{{ grp.name }}</td>
<td>
<td>
<button class="btn btn-primary mr-2" @click="openModal('edit', grp)">Изменить</button>
</td>
<td>
<button class="btn btn-danger" @click="deleteGroup(grp.id)">Удалить</button>
</td>
<td>
<button class="btn btn-primary mr-2" @click="OpenModelForStudents();getStudentsFromGroup(grp.id)">Просмотр студентов</button>
</td>
<td>
<button class="btn btn-primary mr-2" @click="OpenModelForSubjects();getSubjects(grp.id)">Просмотр предметов</button>
</td>
<div class="d-flex flex-column">
<button class="btn btn-primary mb-2" @click="openModal('edit', grp)">Изменить</button>
<button class="btn btn-danger mb-2" @click="deleteGroup(grp.id)">Удалить</button>
</div>
</td>
<td>
<div class="d-flex flex-column">
<button class="btn btn-primary mb-2" @click="OpenModelForStudents(); getStudentsFromGroup(grp.id)">Просмотр студентов</button>
<button class="btn btn-primary mb-2" @click="OpenModelForAddStudents(grp); getStudentsFromUndefinedGroup()">Добавление студентов в группу</button>
</div>
</td>
<td>
<div class="d-flex flex-column">
<button class="btn btn-primary mb-2" @click="OpenModelForSubjects(); getSubjectsInGroup(grp.id)">Просмотр предметов</button>
<button class="btn btn-primary mb-2" @click="OpenModelForAddSubjects('edit', grp);">Добавление предметов в группу</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!--Форма для привязки предмета и групп -->
<div class="modal" tabindex="-1" id="openModalForAddSubjects">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Добавление предметов</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="name">Имя:</label>
<input readonly type="text" class="form-control" id="name" name="name" v-model="group.name">
</div>
<div class="form-group">
<label for="name">Выберите предметы для добавления:</label>
<ul class="list-group">
<li class="list-group-item" v-for="subject in subjects" :key="subject.id">
<div class="form-check">
<input class="form-check-input" type="checkbox" v-model="selectedSubjects" :value="subject.id" v-bind:checked="open.includes(subject.id)" id="groupCheck{{ subject.id }}">
<label class="form-check-label" for="groupCheck{{ subject.id }}">{{ subject.name }}</label>
</div>
</li>
</ul>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModalForAddSubjects()">Закрыть</button>
<button type="button" class="btn btn-primary" @click="addSubjectToGroup(group.id, selectedSubjects)">Добавить</button>
</div>
</div>
</div>
</div>
<!-- Модальное окно для добавления студентов в группу-->
<div class="modal" tabindex="-1" id="ModalForAddStudents">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Добавление студентов в группу</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="name">Имя:</label>
<input type="text" class="form-control" id="name" name="name" v-model="group.name">
</div>
<div class="form-group">
<label for="name">Выберите студентов для добавления:</label>
<ul class="list-group">
<li class="list-group-item" v-for="student in students" :key="student.id">
<div class="form-check">
<input class="form-check-input" type="checkbox" :id="'studentCheck' + student.id" :value="student.id" v-model="selectedStudents">
<label class="form-check-label" :for="'studentCheck' + student.id">{{ student.name }}</label>
</div>
</li>
</ul>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="CloseModalForAddStudents()">Закрыть</button>
<button type="button" class="btn btn-primary" @click="saveStudents(group.id)">Сохранить</button>
</div>
</div>
</div>
</div>
<!-- Модальное окно для добавления и изменения-->
<div class="modal" tabindex="-1" id="editModal">
<div class="modal-dialog">
@ -68,12 +140,18 @@
<tr>
<th>Имя</th>
<th>Дата рождения</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="stud in students" :key="stud.id">
<td>{{ stud.name }}</td>
<td>{{ stud.birthDate }}</td>
<td>
<td>
<button class="btn btn-danger mr-2" @click="deleteStudentFromGroup(stud.id)">Удалить</button>
</td>
</td>
</tr>
</tbody>
</table>
@ -103,7 +181,7 @@
</tr>
</thead>
<tbody>
<tr v-for="sbjct in subjects" :key="sbjct.id">
<tr v-for="sbjct in subjectsInGroup" :key="sbjct.id">
<td>{{ sbjct.name }}</td>
</tr>
</tbody>
@ -123,9 +201,11 @@ import 'axios';
import axios from "axios";
import Group from "@/models/Group";
import Student from "@/models/Student";
import Subject from "@/models/Subject";
export default {
created() {
this.getGroups();
this.getSubjects();
},
data() {
return{
@ -134,13 +214,18 @@ export default {
group: new Group(),
students: [],
subjects: [],
selectedStudents: [],
open: [],
groupId: undefined,
selectedSubjects: [],
subjectsInGroup: [],
}
},
methods: {
getSubjects(id){
getSubjectsInGroup(id){
axios.get(this.URL + `group/${id}/getAllSubjects`)
.then(response => {
this.subjects = response.data;
this.subjectsInGroup = response.data;
console.log(response.data);
})
.catch(error => {
@ -200,6 +285,7 @@ export default {
document.getElementById("editModal").style.display = "none";
},
getStudentsFromGroup(groupId){
this.selectedStudents = [];
axios.get(this.URL + `group/${groupId}/students`)
.then(response => {
this.students = response.data;
@ -221,6 +307,87 @@ export default {
closeModelForSubjects() {
document.getElementById("ModelForSubjects").style.display = "none";
},
OpenModelForAddStudents(group) {
this.group = { ...group };
document.getElementById("ModalForAddStudents").style.display = "block";
},
CloseModalForAddStudents() {
document.getElementById("ModalForAddStudents").style.display = "none";
},
saveStudents(id) {
axios.post(this.URL + `group/${id}/addStudents`, this.selectedStudents)
.then(() => {
this.getStudentsFromGroup(id);
this.CloseModalForAddStudents();
console.log(this.students);
})
.catch(error => {
console.log(error);
});
},
getStudentsFromUndefinedGroup(){
axios.get(this.URL + `group/getStudentsUndefined`)
.then(response => {
this.students = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
deleteStudentFromGroup(id){
axios.delete(this.URL + `group/deleteStudentFromGroup/${id}`)
.then(() =>{
this.getStudentsFromGroup();
})
.catch(error => {
console.log(error);
});
},
OpenModelForAddSubjects(status, group = null) {
if (status === "create") {
this.group = new Group();
this.group.status = "create";
} else if (status === "edit" && group) {
this.group = { ...group };
this.group.status = "edit";
}
this.open = this.group.subjectIds ? [...this.group.subjectIds] : []; // Создаём новый массив, чтобы избежать проблем с ссылками
this.loadSelectedSubjects(); // Загрузка выбранных групп при открытии модального окна
document.getElementById("openModalForAddSubjects").style.display = "block";
},
closeModalForAddSubjects() {
document.getElementById("openModalForAddSubjects").style.display = "none";
this.open = [...this.selectedSubjects]; // Обновление массива open значениями из selectedGroups
this.selectedSubjects = []; // Сброс выбранных групп
this.group = new Group(); // Сброс текущего предмета при закрытии модального окна
},
loadSelectedSubjects() {
// Загрузка выбранных групп из массива open
this.selectedSubjects = [...this.open];
},
addSubjectToGroup(id, list) {
axios
.post(this.URL + `group/${id}/addSubjectToGroup`, list)
.then(() => {
this.closeModalForAddSubjects();
this.getGroups(); // Обновляем список предметов после успешного добавления
this.open = [...this.selectedSubjects]; // Обновляем массив выбранных групп
})
.catch((error) => {
console.log(error);
});
},
getSubjects(){
axios.get(this.URL + "subject")
.then(response => {
this.subjects = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
}
}
</script>

View File

@ -15,7 +15,7 @@
<tr v-for="stud in students" :key="stud.id">
<td>{{ stud.name }}</td>
<td>{{ stud.birthDate }}</td>
<td>{{ stud.groupName }}</td>
<td>{{stud.groupName || 'No Group'}}</td>
<td>
<td>
<button class="btn btn-primary mr-2" @click="openModal('edit', stud)">Изменить</button>
@ -44,14 +44,6 @@
<label for="birthdate">Дата рождения:</label>
<input type="date" class="form-control" id="birthdate" name="birthdate" v-model="editedStudent.birthDate">
</div>
<div class="form-group">
<label for="group">Группа:</label>
<select v-model="editedStudent.groupId" class="form-control">
<option v-for="(group, index) in groups" :key="index" :value="group.id">
{{ group.name }}
</option>
</select>
</div>
</form>
</div>
<div class="modal-footer">
@ -98,8 +90,8 @@ export default {
console.log(error);
});
},
getGroups(){
axios.get(this.URL + "group")
getGroups() {
axios.get(this.URL + "student/groups")
.then(response => {
this.groups = response.data;
console.log(response.data);
@ -109,6 +101,8 @@ export default {
});
},
addStudent(student) {
console.log(student);
student.group = null;
console.log(student);
axios
.post(this.URL + "student", student)

View File

@ -19,9 +19,6 @@
<td>
<button class="btn btn-danger" @click="deleteSubject(sbjct.id)">Удалить</button>
</td>
<td>
<button class="btn btn-primary mr-2" @click="openModalForAdd('edit', sbjct);">Добавить предметы в группы</button>
</td>
</td>
</tr>
</tbody>
@ -50,39 +47,6 @@
</div>
</div>
</div>
<!--Форма для привязки предмета и групп -->
<div class="modal" tabindex="-1" id="openModalForAdd">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Добавление групп</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="name">Имя:</label>
<input readonly type="text" class="form-control" id="name" name="name" v-model="subject.name">
</div>
<div class="form-group">
<label for="name">Выберите группы для добавления:</label>
<ul class="list-group">
<li class="list-group-item" v-for="group in groups" :key="group.id">
<div class="form-check">
<input class="form-check-input" type="checkbox" v-model="selectedGroups" :value="group.id" v-bind:checked="open.includes(group.id)" id="groupCheck{{ group.id }}">
<label class="form-check-label" for="groupCheck{{ group.id }}">{{ group.name }}</label>
</div>
</li>
</ul>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModalForAdd()">Закрыть</button>
<button type="button" class="btn btn-primary" @click="addSubjectToGroup(subject.id, selectedGroups)">Добавить</button>
</div>
</div>
</div>
</div>
</template>
<script>
import 'axios';
@ -92,40 +56,15 @@ import Group from "@/models/Group";
export default {
created() {
this.getSubjects();
this.getGroups();
this.getAllSubjectGroup();
},
mounted() {
const addModal = document.getElementById('editModal');
addModal.addEventListener('shown.bs.modal', function () {
})
const openModalForAdd = document.getElementById('openModalForAdd');
openModalForAdd.addEventListener('shown.bs.modal', function () {
})
},
data() {
return{
subjects: [],
URL: "http://localhost:8080/",
subject: new Subject(),
groups: [],
selectedGroups: [],
AllSubjectGroup: [],
open: [],
}
},
methods: {
getAllSubjectGroup(){
axios.get(this.URL + "subject/getAllSubjectGroup")
.then(response => {
this.AllSubjectGroup = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
getSubjects(){
axios.get(this.URL + "subject")
.then(response => {
@ -164,27 +103,6 @@ export default {
})
this.closeModal();
},
openModalForAdd(status, subject = null) {
if (status === "create") {
this.subject = new Subject();
this.subject.status = "create";
} else if (status === "edit" && subject) {
this.subject = { ...subject };
this.subject.status = "edit";
}
this.open = this.subject.groupIds ? [...this.subject.groupIds] : []; // Создаём новый массив, чтобы избежать проблем с ссылками
this.loadSelectedGroups(); // Загрузка выбранных групп при открытии модального окна
document.getElementById("openModalForAdd").style.display = "block";
},
closeModalForAdd() {
document.getElementById("openModalForAdd").style.display = "none";
this.open = [...this.selectedGroups]; // Обновление массива open значениями из selectedGroups
this.selectedGroups = []; // Сброс выбранных групп
this.subject = new Subject(); // Сброс текущего предмета при закрытии модального окна
},
openModal(status, subject = null) {
if (status === "create") {
this.subject = new Subject();
@ -198,38 +116,6 @@ export default {
closeModal() {
document.getElementById("editModal").style.display = "none";
},
getGroups(){
axios.get(this.URL + "group")
.then(response => {
this.groups = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
saveSelectedGroups() {
// Сохранение выбранных групп в массив open
this.open = [...this.selectedGroups];
},
loadSelectedGroups() {
// Загрузка выбранных групп из массива open
this.selectedGroups = [...this.open];
},
addSubjectToGroup(id, list) {
axios
.post(this.URL + `subject/${id}/addSubjectToGroup`, list)
.then(() => {
this.closeModalForAdd();
this.getSubjects(); // Обновляем список предметов после успешного добавления
this.open = [...this.selectedGroups]; // Обновляем массив выбранных групп
})
.catch((error) => {
console.log(error);
});
},
}
}
</script>

View File

@ -2,16 +2,21 @@ package ru.IP_LabWorks.IP.University.Contoller.DTO;
import ru.IP_LabWorks.IP.University.Model.Group;
import java.util.List;
public class GroupDTO {
private long id;
private String name;
private List<Long> subjectIds;
public GroupDTO(){
}
public GroupDTO(Group group){
this.id = group.getId();
this.name = group.getName();
this.subjectIds = group.getSubjectIds();
}
public Long getId(){
@ -29,4 +34,8 @@ public class GroupDTO {
public void setName(String name){
this.name = name;
}
public List<Long> getSubjectIds(){
return subjectIds;
}
}

View File

@ -20,8 +20,9 @@ public class StudentDTO {
this.id = student.getId();
this.name = student.getName();
this.birthDate = student.getBirthDate();
this.groupName = student.getGroup().getName();
this.groupId = student.getGroup().getId();
if(student.getGroup() != null){
this.groupName = student.getGroup().getName();
}
}
public String getGroupName() {

View File

@ -59,6 +59,28 @@ public class GroupController {
return ResponseEntity.ok(subjects);
}
@GetMapping("/getStudentsUndefined")
public ResponseEntity<List<Student>> getStudentsFromUndefinedGroup(){
List<Student> students = groupService.getStudentsUndefined();
return ResponseEntity.ok(students);
}
@PostMapping("/{id}/addStudents")
public void addStudentToGroup(@PathVariable Long id, @RequestBody @Valid List<Long> studentsIds){
groupService.addStudentToGroup(id, studentsIds);
}
@DeleteMapping("deleteStudentFromGroup/{id}")
public void deleteStudentFromGroup(@PathVariable Long id){
groupService.deleteStudentFromGroup(id);
}
@PostMapping("/{id}/addSubjectToGroup")
public void addSubjectToGroup(@PathVariable Long id, @RequestBody @Valid List<Long> subjectIds){
groupService.addSubjectToGroup(id, subjectIds);
}
// @PostMapping("/{id}/student")
// public StudentDTO setStudentToGroup(@PathVariable Long id,
// @RequestParam("studentId") Long studentId) {

View File

@ -1,20 +1,24 @@
package ru.IP_LabWorks.IP.University.Contoller.REST;
import org.springframework.web.bind.annotation.*;
import ru.IP_LabWorks.IP.University.Contoller.DTO.GroupDTO;
import ru.IP_LabWorks.IP.University.Contoller.DTO.StudentDTO;
import ru.IP_LabWorks.IP.University.Service.GroupService;
import ru.IP_LabWorks.IP.University.Service.StudentService;
import jakarta.validation.Valid;
import java.time.LocalDate;
import java.util.List;
@RestController
@RequestMapping("/student")
public class StudentController {
private final StudentService studentService;
private final GroupService groupService;
public StudentController(StudentService studentService) {
public StudentController(StudentService studentService, GroupService groupService) {
this.studentService = studentService;
this.groupService = groupService;
}
@GetMapping("/{id}")
@ -31,12 +35,12 @@ public class StudentController {
@PostMapping
public StudentDTO createStudent(@RequestBody @Valid StudentDTO studentDTO){
return new StudentDTO(studentService.addStudent(studentDTO.getName(), studentDTO.getBirthDate(), studentDTO.getGroupId()));
return new StudentDTO(studentService.addStudent(studentDTO.getName(), studentDTO.getBirthDate()));
}
@PutMapping("/{id}")
public StudentDTO updateStudent(@PathVariable Long id, @RequestBody @Valid StudentDTO studentDTO) {
return new StudentDTO(studentService.updateStudent(id, studentDTO.getName(), studentDTO.getBirthDate(), studentDTO.getGroupId()));
return new StudentDTO(studentService.updateStudent(id, studentDTO.getName(), studentDTO.getBirthDate()));
}
@DeleteMapping("/{id}")
@ -44,4 +48,11 @@ public class StudentController {
return new StudentDTO(studentService.deleteStudent(id));
}
@GetMapping("/groups")
public List<GroupDTO> getGroups() {
return groupService.findAllGroups().stream()
.map(GroupDTO::new)
.toList();
}
}

View File

@ -8,6 +8,7 @@ import org.hibernate.annotations.OnDeleteAction;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
@ -89,4 +90,18 @@ public class Group {
subjects.add(subject);
subject.getGroups().add(this);
}
public List<Long> getSubjectIds() {
if (subjects.isEmpty()) {
return Collections.emptyList();
} else {
List<Long> subjectIds = new ArrayList<>();
for (Subject subject : subjects) {
if (!subjectIds.contains(subject.getId())) {
subjectIds.add(subject.getId());
}
}
return subjectIds;
}
}
}

View File

@ -25,10 +25,9 @@ public class Student {
public Student() {
}
public Student(String name, LocalDate birthDate, Group group) {
public Student(String name, LocalDate birthDate) {
this.name = name;
this.birthDate = birthDate;
this.group = group;
}
public Long getId() { return id; }
@ -59,11 +58,13 @@ public class Student {
@Override
public String toString() {
String groupStr = (group != null) ? group.getName() : "No Group";
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", birthDate='" + birthDate + '\'' +
", age='" + getAge() + '\'' +
", group='" + groupStr + '\'' +
'}';
}

View File

@ -1,6 +1,6 @@
package ru.IP_LabWorks.IP.University.Service;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@ -8,10 +8,9 @@ import ru.IP_LabWorks.IP.University.Model.Group;
import ru.IP_LabWorks.IP.University.Model.Student;
import ru.IP_LabWorks.IP.University.Model.Subject;
import ru.IP_LabWorks.IP.University.Repository.GroupRepository;
import ru.IP_LabWorks.IP.University.Repository.StudentRepository;
import ru.IP_LabWorks.IP.University.Service.NotFoundException.GroupNotFoundException;
import java.awt.desktop.OpenFilesEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@ -19,8 +18,13 @@ import java.util.Optional;
public class GroupService {
private final GroupRepository groupRepository;
public GroupService(GroupRepository groupRepository) {
private final StudentService studentService;
private final SubjectService subjectService;
public GroupService(GroupRepository groupRepository, StudentService studentService, @Lazy SubjectService subjectService) {
this.groupRepository = groupRepository;
this.studentService = studentService;
this.subjectService = subjectService;
}
@Transactional
@ -87,6 +91,41 @@ public class GroupService {
}
}
@Transactional
public List<Student> getStudentsUndefined(){
List<Student> students = new ArrayList<>();
for(Student student : studentService.findAllStudents()){
if(student.getGroup() == null){
students.add(student);
}
}
return students;
}
@Transactional
public void addStudentToGroup(Long groupId, List<Long> studentIds){
final Group currentGroup = findGroup(groupId);
for(Long studentId : studentIds) {
studentService.findStudent(studentId).setGroup(currentGroup);
}
groupRepository.save(currentGroup);
}
@Transactional
public void deleteStudentFromGroup(Long id){
studentService.findStudent(id).setGroup(null);
}
@Transactional
public void addSubjectToGroup(Long groupId, List<Long> subjectIds){
final Group currentGroup = findGroup(groupId);
currentGroup.setSubjects(new ArrayList<>());
for(Long subjectId : subjectIds) {
currentGroup.getSubjects().add(subjectService.findSubject(subjectId));
}
groupRepository.save(currentGroup);
}
/* @Transactional
public Group addStudentToGroup(Long groupId, Long studentId) {
Group group = findGroup(groupId);

View File

@ -1,5 +1,7 @@
package ru.IP_LabWorks.IP.University.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@ -17,23 +19,17 @@ public class StudentService {
private final StudentRepository studentRepository;
private final GroupService groupService;
public StudentService(StudentRepository studentRepository, GroupService groupService) {
public StudentService(StudentRepository studentRepository,@Lazy GroupService groupService) {
this.studentRepository = studentRepository;
this.groupService = groupService;
}
@Transactional
public Student addStudent(String name, LocalDate birthDate, Long groupId){
public Student addStudent(String name, LocalDate birthDate){
if (!StringUtils.hasText(name) || !StringUtils.hasText(String.valueOf(birthDate))) {
throw new IllegalArgumentException("Student name or date is null or empty");
}
Group group = null;
try{
group = groupService.findGroup(groupId);
}catch (Exception ex){
group = null;
}
final Student student = new Student(name, birthDate,group);
final Student student = new Student(name, birthDate);
return studentRepository.save(student);
}
@ -49,14 +45,13 @@ public class StudentService {
}
@Transactional
public Student updateStudent(Long id, String name, LocalDate date, Long groupId) {
public Student updateStudent(Long id, String name, LocalDate date) {
if (!StringUtils.hasText(name) || !StringUtils.hasText(String.valueOf(date))) {
throw new IllegalArgumentException("Student name or date is null or empty");
}
final Student currentStudent = findStudent(id);
currentStudent.setName(name);
currentStudent.setBirthDate(date);
currentStudent.setGroup(groupService.findGroup(groupId));
return studentRepository.save(currentStudent);
}