Compare commits

..

34 Commits

Author SHA1 Message Date
ArtemEmelyanov
009a006ea8 MVC сделано 2023-05-24 23:02:28 +04:00
ArtemEmelyanov
69d0346b24 Начата 6 лаба MVC 2023-05-23 21:42:43 +04:00
ArtemEmelyanov
3e575845d6 Ого, вау еще и 5 сдал 2023-05-16 20:21:44 +04:00
ArtemEmelyanov
d427d1eaa3 Ого, вау еще и 5 сдал 2023-05-16 20:20:57 +04:00
ArtemEmelyanov
b489ac9547 Ого, вау еще и 5 сделал 2023-05-15 21:57:44 +04:00
ArtemEmelyanov
f2a3f2164c Merge branch 'LabWork_04' into LabWork_05
# Conflicts:
#	data.mv.db
#	src/main/java/ru/IP_LabWorks/IP/University/Contoller/REST/StudentController.java
2023-05-15 20:13:58 +04:00
ArtemEmelyanov
a47d810d48 Ого, вау сделал отчет 2023-05-15 20:09:55 +04:00
ArtemEmelyanov
58280603ce Ого, вау, переделал всю структуру, мне это очень понравилось 2023-05-15 19:04:10 +04:00
ArtemEmelyanov
02e24932d4 Хоть мне это не нравилось, но я сделал 2023-05-14 16:12:14 +04:00
ArtemEmelyanov
1b1d31e033 Мне это не нравится 2023-05-13 23:25:24 +04:00
ArtemEmelyanov
969527b864 Мне это не нравится 2023-05-13 23:25:12 +04:00
ArtemEmelyanov
2139fe0e18 Боль 2023-05-13 20:36:21 +04:00
ArtemEmelyanov
6a334b2d25 Вроде все сделал 2023-05-13 15:30:22 +04:00
ArtemEmelyanov
18c774db30 Вроде все сделал 2023-05-13 15:01:01 +04:00
ArtemEmelyanov
e54c2dc46e Добавлены связь - многие ко многим, есть баг с галочками)) 2023-05-12 21:23:55 +04:00
ArtemEmelyanov
66052b7078 Добавлен просмотр студентов через группы 2023-05-12 15:41:21 +04:00
ArtemEmelyanov
6159f006a7 Поправил студента 2023-05-12 15:04:39 +04:00
ArtemEmelyanov
51f3480755 Добавлены студенты и добавление их в группу, осталось добавить добавление предметов 2023-05-11 21:01:05 +04:00
ArtemEmelyanov
db321f5899 Потихоньку добавлю фронт 2023-05-10 10:57:22 +04:00
ArtemEmelyanov
b25ef9f3eb Потихоньку добавлю фронт 2023-04-21 16:12:26 +04:00
ArtemEmelyanov
08fe574653 Сервисы переписаны на репозитории, не до конца, осталось дописать методы взаимодействия между сущностями 2023-04-21 14:53:50 +04:00
ArtemEmelyanov
67b9d4fabf Добавлены репозитории 2023-04-21 14:30:13 +04:00
ArtemEmelyanov
591f84718a Добавлены контроллеры и DTO 2023-04-21 14:22:01 +04:00
ArtemEmelyanov
83e27918ee Начало 4 лабы 2023-04-21 13:41:52 +04:00
ArtemEmelyanov
7de8e172de Сданная лаба 2023-04-21 13:38:51 +04:00
ArtemEmelyanov
71a1250ae1 Чуток тесты не проходят 2023-04-15 17:40:26 +04:00
ArtemEmelyanov
3ecb50cec8 Все дописано, осталось наладить связи 2023-04-15 17:09:21 +04:00
ArtemEmelyanov
97d5ae0cf4 Осталось добавить взаимодействие между сущностями 2023-04-15 15:42:27 +04:00
ArtemEmelyanov
8595331a1d ок 2023-04-14 22:00:27 +04:00
ArtemEmelyanov
4f9bba63ee Для данила 2023-03-26 12:53:15 +04:00
ArtemEmelyanov
4b71c89826 Добавлены сущности, не полностью 2023-03-20 16:04:15 +04:00
ArtemEmelyanov
63c115f8be LabWork_02 добвлен еще один тип, лаба сдана 2023-03-20 14:52:50 +04:00
ArtemEmelyanov
d80f64a86e LabWork_02 done 2023-03-11 20:38:01 +04:00
ArtemEmelyanov
035fadd9dc add frontend 2023-02-19 15:53:42 +04:00
89 changed files with 18147 additions and 2 deletions

1
.gitignore vendored
View File

@ -16,6 +16,7 @@ build/
bin/ bin/
!**/src/main/**/bin/ !**/src/main/**/bin/
!**/src/test/**/bin/ !**/src/test/**/bin/
node_modules/
### IntelliJ IDEA ### ### IntelliJ IDEA ###
.idea .idea

View File

@ -14,7 +14,27 @@ repositories {
dependencies { dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
implementation 'org.webjars:bootstrap:5.1.3'
implementation 'org.webjars:jquery:3.6.0'
implementation 'org.webjars:font-awesome:6.1.0'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210'
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'com.auth0:java-jwt:4.4.0'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
} }
tasks.named('test') { tasks.named('test') {

BIN
data.mv.db Normal file

Binary file not shown.

12684
data.trace.db Normal file

File diff suppressed because it is too large Load Diff

6
frontend/package-lock.json generated Normal file
View File

@ -0,0 +1,6 @@
{
"name": "frontend",
"lockfileVersion": 2,
"requires": true,
"packages": {}
}

28
frontend/vue-project/.gitignore vendored Normal file
View File

@ -0,0 +1,28 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.DS_Store
dist
dist-ssr
coverage
*.local
/cypress/videos/
/cypress/screenshots/
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@ -0,0 +1,29 @@
# vue-project
This template should help get you started developing with Vue 3 in Vite.
## Recommended IDE Setup
[VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur) + [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin).
## Customize configuration
See [Vite Configuration Reference](https://vitejs.dev/config/).
## Project Setup
```sh
npm install
```
### Compile and Hot-Reload for Development
```sh
npm run dev
```
### Compile and Minify for Production
```sh
npm run build
```

View File

@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<link rel="stylesheet" href="./src/style.css">
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Vue</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

1288
frontend/vue-project/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,19 @@
{
"name": "vue-project",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.4.0",
"vue": "^3.2.47",
"vue-router": "^4.1.6"
},
"devDependencies": {
"@vitejs/plugin-vue": "^4.0.0",
"vite": "^4.1.4"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@ -0,0 +1,16 @@
<script>
import Header from "./components/Header.vue"
export default {
components:{Header}
}
</script>
<template>
<Header></Header>
<div class="container-fluid">
<router-view></router-view>
</div>
</template>
<style>
</style>

View File

@ -0,0 +1,74 @@
/* color palette from <https://github.com/vuejs/theme> */
:root {
--vt-c-white: #ffffff;
--vt-c-white-soft: #f8f8f8;
--vt-c-white-mute: #f2f2f2;
--vt-c-black: #181818;
--vt-c-black-soft: #222222;
--vt-c-black-mute: #282828;
--vt-c-indigo: #2c3e50;
--vt-c-divider-light-1: rgba(60, 60, 60, 0.29);
--vt-c-divider-light-2: rgba(60, 60, 60, 0.12);
--vt-c-divider-dark-1: rgba(84, 84, 84, 0.65);
--vt-c-divider-dark-2: rgba(84, 84, 84, 0.48);
--vt-c-text-light-1: var(--vt-c-indigo);
--vt-c-text-light-2: rgba(60, 60, 60, 0.66);
--vt-c-text-dark-1: var(--vt-c-white);
--vt-c-text-dark-2: rgba(235, 235, 235, 0.64);
}
/* semantic color variables for this project */
:root {
--color-background: var(--vt-c-white);
--color-background-soft: var(--vt-c-white-soft);
--color-background-mute: var(--vt-c-white-mute);
--color-border: var(--vt-c-divider-light-2);
--color-border-hover: var(--vt-c-divider-light-1);
--color-heading: var(--vt-c-text-light-1);
--color-text: var(--vt-c-text-light-1);
--section-gap: 160px;
}
@media (prefers-color-scheme: dark) {
:root {
--color-background: var(--vt-c-black);
--color-background-soft: var(--vt-c-black-soft);
--color-background-mute: var(--vt-c-black-mute);
--color-border: var(--vt-c-divider-dark-2);
--color-border-hover: var(--vt-c-divider-dark-1);
--color-heading: var(--vt-c-text-dark-1);
--color-text: var(--vt-c-text-dark-2);
}
}
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
position: relative;
font-weight: normal;
}
body {
min-height: 100vh;
color: var(--color-text);
background: var(--color-background);
transition: color 0.5s, background-color 0.5s;
line-height: 1.6;
font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
font-size: 15px;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 261.76 226.69"><path d="M161.096.001l-30.225 52.351L100.647.001H-.005l130.877 226.688L261.749.001z" fill="#41b883"/><path d="M161.096.001l-30.225 52.351L100.647.001H52.346l78.526 136.01L209.398.001z" fill="#34495e"/></svg>

After

Width:  |  Height:  |  Size: 276 B

View File

@ -0,0 +1,47 @@
<template>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav justify-content-center">
<li class="nav-item">
<router-link to="/students" class="nav-link">Студенты</router-link>
</li>
<li class="nav-item">
<router-link to="/groups" class="nav-link">Группы</router-link>
</li>
<li class="nav-item">
<router-link to="/subjects" class="nav-link">Предметы</router-link>
</li>
</ul>
</div>
</div>
</nav>
</template>
<style>
.navbar-brand {
font-size: 2rem;
font-weight: bold;
}
.nav-link {
color: black;
font-weight: bold;
text-transform: uppercase;
transition: color 0.3s ease-in-out;
}
.nav-link:hover {
color: #dc3545;
}
</style>
<script>
export default {
}
</script>

View File

@ -0,0 +1,10 @@
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')

View File

@ -0,0 +1,7 @@
export default class Group{
constructor(data) {
this.id = data?.id;
this.name = data?.name;
this.subjectIds = data?.subjectIds;
}
}

View File

@ -0,0 +1,8 @@
export default class Student{
constructor(data) {
this.id = data?.id;
this.name = data?.name;
this.birthDate = data?.birthDate;
this.group = data?.group;
}
}

View File

@ -0,0 +1,7 @@
export default class Subject{
constructor(data) {
this.id = data?.id;
this.name = data?.name;
this.groupIds = data?.groupIds;
}
}

View File

@ -0,0 +1,450 @@
<template>
<div class="container mt-4">
<h1 class="text-center mb-4">Group Table</h1>
<button class="btn btn-primary mr-2" @click="openModal('create')">Добавить</button>
<button class="btn btn-primary mr-2" @click="openReport()">Отчет</button>
<table class="table table-striped">
<thead>
<tr>
<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>
<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="openReport">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Отчет</h5>
</div>
<div class="modal-body">
<form>
<table class="table table-striped">
<thead>
<tr>
<th>Группа</th>
<th>Студенты</th>
</tr>
</thead>
<tbody>
<tr v-for="[key, value] in Object.entries(getAllInfo)" :key="key">
<td>{{ key }}</td>
<td>
<ul>
<li v-for="book in value" :key="book">{{ book }}</li>
</ul>
</td>
</tr>
</tbody>
</table>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeReport()">Закрыть</button>
</div>
</div>
</div>
</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">
<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>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModal()">Закрыть</button>
<button type="button" class="btn btn-primary" v-if="group.status === 'create'" @click="addGroup(group)">Создать</button>
<button type="button" class="btn btn-primary" v-else @click="editGroup(group)">Сохранить</button>
</div>
</div>
</div>
</div>
<!-- Модальное окно для просмотра студентов в группе-->
<div class="modal" tabindex="-1" id="ModelForStudents">
<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">
<table class="table table-striped">
<thead>
<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>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="ModelForStudents" @click="closeModelForStudents()">Закрыть</button>
</div>
</div>
</div>
</div>
<!-- Модальное окно для просмотра предметов в группе-->
<div class="modal" tabindex="-1" id="ModelForSubjects">
<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">
<table class="table table-striped">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
<tr v-for="sbjct in subjectsInGroup" :key="sbjct.id">
<td>{{ sbjct.name }}</td>
</tr>
</tbody>
</table>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="ModelForSubjects" @click="closeModelForSubjects()">Закрыть</button>
</div>
</div>
</div>
</div>
</template>
<script>
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();
this.getAll();
},
data() {
return{
groups: [],
URL: "http://localhost:8080/",
group: new Group(),
students: [],
subjects: [],
selectedStudents: [],
open: [],
groupId: undefined,
selectedSubjects: [],
subjectsInGroup: [],
getAllInfo: new Object() ,
}
},
methods: {
getAll(){
axios.get(this.URL + "group/getAll")
.then(response => {
this.getAllInfo = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
getSubjectsInGroup(id){
axios.get(this.URL + `group/${id}/getAllSubjects`)
.then(response => {
this.subjectsInGroup = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
getGroups(){
axios.get(this.URL + "group")
.then(response => {
this.groups = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
addGroup(group){
console.log(this.group);
axios.post(this.URL + "group", group)
.then(() => {
this.getGroups();
this.closeModal();
})
.catch(error => {
console.log(error);
});
},
deleteGroup(id){
axios.delete(this.URL + `group/${id}`)
.then(() =>{
this.getGroups();
})
},
editGroup(group){
axios.put(this.URL + `group/${group.id}`, group)
.then(() =>{
const index = this.groups.findIndex((s) => s.id === group.id);
if (index !== -1) {
this.groups[index] = { ...group };
}
this.closeModal();
this.getGroups();
})
this.closeModal();
},
openModal(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";
}
document.getElementById("editModal").style.display = "block";
},
closeModal() {
document.getElementById("editModal").style.display = "none";
},
getStudentsFromGroup(groupId){
this.selectedStudents = [];
axios.get(this.URL + `group/${groupId}/students`)
.then(response => {
this.students = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
OpenModelForStudents() {
document.getElementById("ModelForStudents").style.display = "block";
},
closeModelForStudents() {
document.getElementById("ModelForStudents").style.display = "none";
},
OpenModelForSubjects() {
document.getElementById("ModelForSubjects").style.display = "block";
},
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";
},
openReport() {
document.getElementById("openReport").style.display = "block";
},
closeReport() {
document.getElementById("openReport").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>
<style>
</style>

View File

@ -0,0 +1,156 @@
<template>
<div class="container mt-4">
<h1 class="text-center mb-4">Student Table</h1>
<button class="btn btn-primary mr-2" @click="openModal('create')">Добавить</button>
<table class="table table-striped">
<thead>
<tr>
<th>Имя</th>
<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>{{stud.groupName || 'No Group'}}</td>
<td>
<td>
<button class="btn btn-primary mr-2" @click="openModal('edit', stud)">Изменить</button>
</td>
<td>
<button class="btn btn-danger" @click="deleteStudent(stud.id)">Удалить</button>
</td>
</td>
</tr>
</tbody>
</table>
</div>
<div class="modal" tabindex="-1" id="editModal">
<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="editedStudent.name">
</div>
<div class="form-group">
<label for="birthdate">Дата рождения:</label>
<input type="date" class="form-control" id="birthdate" name="birthdate" v-model="editedStudent.birthDate">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModal()">Закрыть</button>
<button type="button" class="btn btn-primary" v-if="editedStudent.status === 'create'" @click="addStudent(editedStudent)">Создать</button>
<button type="button" class="btn btn-primary" v-else @click="editStudent(editedStudent)">Сохранить</button>
</div>
</div>
</div>
</div>
</template>
<script>
import 'axios';
import axios from "axios";
import Student from "@/models/Student";
export default {
created() {
this.getStudents();
this.getGroups();
},
mounted() {
const addModal = document.getElementById('editModal');
addModal.addEventListener('shown.bs.modal', function () {
})
},
data() {
return{
students: [],
groups: [],
URL: "http://localhost:8080/",
student: new Student(),
editedStudent: new Student(),
}
},
methods: {
getStudents(){
axios.get(this.URL + "student")
.then(response => {
this.students = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
getGroups() {
axios.get(this.URL + "student/groups")
.then(response => {
this.groups = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
addStudent(student) {
console.log(student);
student.group = null;
console.log(student);
axios
.post(this.URL + "student", student)
.then(() => {
this.getStudents();
this.closeModal();
})
.catch((error) => {
console.log(error);
});
},
deleteStudent(id){
axios.delete(this.URL + `student/${id}`)
.then(() =>{
this.getStudents();
})
},
openModal(status, student = null) {
if (status === "create") {
this.editedStudent = new Student();
this.editedStudent.status = "create";
} else if (status === "edit" && student) {
this.editedStudent = { ...student };
this.editedStudent.status = "edit";
}
document.getElementById("editModal").style.display = "block";
},
closeModal() {
document.getElementById("editModal").style.display = "none";
},
editStudent(student) {
axios.put(this.URL + `student/${student.id}`, student)
.then(() => {
const index = this.students.findIndex((s) => s.id === student.id);
if (index !== -1) {
this.students[index] = { ...student };
}
this.closeModal();
this.getStudents();
})
.catch((error) => {
console.log(error);
});
},
}
}
</script>
<style>
</style>

View File

@ -0,0 +1,124 @@
<template>
<div class="container mt-4">
<h1 class="text-center mb-4">Subject Table</h1>
<button class="btn btn-primary mr-2" @click="openModal('create')">Добавить</button>
<table class="table table-striped">
<thead>
<tr>
<th>Имя</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="sbjct in subjects" :key="sbjct.id">
<td>{{ sbjct.name }}</td>
<td>
<td>
<button class="btn btn-primary mr-2" @click="openModal('edit', sbjct)">Изменить</button>
</td>
<td>
<button class="btn btn-danger" @click="deleteSubject(sbjct.id)">Удалить</button>
</td>
</td>
</tr>
</tbody>
</table>
</div>
<!--Форма для создания и добавления предметов-->
<div class="modal" tabindex="-1" id="editModal">
<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="subject.name">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModal()">Закрыть</button>
<button type="button" class="btn btn-primary" v-if="subject.status === 'create'" @click="addSubject(subject)">Создать</button>
<button type="button" class="btn btn-primary" v-else @click="editSubject(subject)">Сохранить</button>
</div>
</div>
</div>
</div>
</template>
<script>
import 'axios';
import axios from "axios";
import Subject from "@/models/Subject";
import Group from "@/models/Group";
export default {
created() {
this.getSubjects();
},
data() {
return{
subjects: [],
URL: "http://localhost:8080/",
subject: new Subject(),
}
},
methods: {
getSubjects(){
axios.get(this.URL + "subject")
.then(response => {
this.subjects = response.data;
})
.catch(error => {
console.log(error);
});
},
addSubject(subject){
console.log(subject);
axios.post(this.URL + "subject", subject)
.then(() => {
this.getSubjects();
this.closeModal();
})
.catch(error => {
console.log(error);
});
},
deleteSubject(id){
axios.delete(this.URL + `subject/${id}`)
.then(() =>{
this.getSubjects();
})
},
editSubject(subject){
axios.put(this.URL + `subject/${subject.id}`, subject)
.then(() =>{
const index = this.subjects.findIndex((s) => s.id === subject.id);
if (index !== -1) {
this.subjects[index] = { ...subject };
}
this.closeModal();
this.getSubjects();
})
this.closeModal();
},
openModal(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";
}
document.getElementById("editModal").style.display = "block";
},
closeModal() {
document.getElementById("editModal").style.display = "none";
},
}
}
</script>
<style>
</style>

View File

@ -0,0 +1,19 @@
import students from "../pages/students.vue"
import groups from "../pages/groups.vue"
import subjects from "../pages/subjects.vue"
import {createRouter, createWebHistory} from "vue-router"
const routes = [
{path: '/students', component: students},
{path: '/groups', component: groups},
{path: '/subjects', component: subjects},
]
const router = createRouter({
history: createWebHistory(),
linkActiveClass: 'active',
routes
})
export default router;

View File

@ -0,0 +1,15 @@
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>
<style>
@media (min-width: 1024px) {
.about {
min-height: 100vh;
display: flex;
align-items: center;
}
}
</style>

View File

@ -0,0 +1,9 @@
<script setup>
import TheWelcome from '../components/TheWelcome.vue'
</script>
<template>
<main>
<TheWelcome />
</main>
</template>

View File

@ -0,0 +1,14 @@
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
})

6
package-lock.json generated Normal file
View File

@ -0,0 +1,6 @@
{
"name": "IP",
"lockfileVersion": 2,
"requires": true,
"packages": {}
}

View File

@ -2,12 +2,15 @@ package ru.IP_LabWorks.IP;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication @SpringBootApplication
public class IpApplication { public class IpApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(IpApplication.class, args); SpringApplication.run(IpApplication.class, args);
} }
} }

View File

@ -0,0 +1,31 @@
package ru.IP_LabWorks.IP.TypeCalculator.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ru.IP_LabWorks.IP.TypeCalculator.domain.TypeInt;
import ru.IP_LabWorks.IP.TypeCalculator.domain.TypeArray;
import ru.IP_LabWorks.IP.TypeCalculator.domain.TypeDouble;
import ru.IP_LabWorks.IP.TypeCalculator.domain.TypeString;
@Configuration
public class TypeConfiguration {
@Bean(value = "int")
public TypeInt createIntType(){
return new TypeInt();
}
@Bean(value = "str")
public TypeString createStrType(){
return new TypeString();
}
@Bean(value = "double")
public TypeDouble createDoubleType(){
return new TypeDouble();
}
@Bean(value = "array")
public TypeArray createArrayType(){
return new TypeArray();
}
}

View File

@ -0,0 +1,43 @@
package ru.IP_LabWorks.IP.TypeCalculator.controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ru.IP_LabWorks.IP.TypeCalculator.service.TypeService;
@RestController
public class MainController {
private final TypeService Service;
public MainController(TypeService service) {
Service = service;
}
@GetMapping("/Method1")
public Object Method1(@RequestParam(value = "Type") String Type,
@RequestParam(value = "value1") Object value1,
@RequestParam(value = "value2") Object value2){
return Service.Method1(value1,value2,Type);
}
@GetMapping("/Method2")
public Object Method2(@RequestParam(value = "Type") String Type,
@RequestParam(value = "value1") Object value1,
@RequestParam(value = "value2") Object value2){
return Service.Method2(value1,value2,Type);
}
@GetMapping("/Method3")
public Object Method3(@RequestParam(value = "Type") String Type,
@RequestParam(value = "value1") Object value1,
@RequestParam(value = "value2") Object value2){
return Service.Method3(value1,value2,Type);
}
@GetMapping("/Method4")
public Object Method4(@RequestParam(value = "Type") String Type,
@RequestParam(value = "value1") Object value1,
@RequestParam(value = "value2") Object value2){
return Service.Method4(value1,value2,Type);
}
}

View File

@ -0,0 +1,8 @@
package ru.IP_LabWorks.IP.TypeCalculator.domain;
public interface ITypeInterface<T> {
T Method1(T value1, T value2);
T Method2(T value1, T value2);
T Method3(T value1, T value2);
T Method4(T value1, T value2);
}

View File

@ -0,0 +1,42 @@
package ru.IP_LabWorks.IP.TypeCalculator.domain;
import java.util.ArrayList;
public class TypeArray implements ITypeInterface<ArrayList<Integer>> {
@Override
public ArrayList<Integer> Method1(ArrayList<Integer> value1, ArrayList<Integer> value2) {
ArrayList<Integer> result = new ArrayList<>();
for (int i = 0; i < Math.min(value1.size(), value2.size()); ++i){
result.add(value1.get(i) + value2.get(i));
}
return result;
}
@Override
public ArrayList<Integer> Method2(ArrayList<Integer> value1, ArrayList<Integer> value2) {
ArrayList<Integer> result = new ArrayList<>();
for (int i = 0; i < Math.min(value1.size(), value2.size()); ++i){
result.add(value1.get(i) - value2.get(i));
}
return result;
}
@Override
public ArrayList<Integer> Method3(ArrayList<Integer> value1, ArrayList<Integer> value2) {
ArrayList<Integer> result = new ArrayList<>();
for (int i = 0; i < Math.min(value1.size(), value2.size()); ++i){
result.add(value1.get(i) * value2.get(i));
}
return result;
}
@Override
public ArrayList<Integer> Method4(ArrayList<Integer> value1, ArrayList<Integer> value2) {
ArrayList<Integer> result = new ArrayList<>();
for (int i = 0; i < Math.min(value1.size(), value2.size()); ++i){
result.add(value1.get(i) / value2.get(i));
}
return result;
}
}

View File

@ -0,0 +1,24 @@
package ru.IP_LabWorks.IP.TypeCalculator.domain;
public class TypeDouble implements ITypeInterface<Double> {
@Override
public Double Method1(Double value1, Double value2) {
return value1 + value2;
}
@Override
public Double Method2(Double value1, Double value2) {
return value1 - value2;
}
@Override
public Double Method3(Double value1, Double value2) {
return value1 * value2;
}
@Override
public Double Method4(Double value1, Double value2) {
return value1 / value2;
}
}

View File

@ -0,0 +1,24 @@
package ru.IP_LabWorks.IP.TypeCalculator.domain;
public class TypeInt implements ITypeInterface<Integer> {
@Override
public Integer Method1(Integer value1, Integer value2) {
return value1 + value2;
}
@Override
public Integer Method2(Integer value1, Integer value2) {
return value1 - value2;
}
@Override
public Integer Method3(Integer value1, Integer value2) {
return value1 * value2;
}
@Override
public Integer Method4(Integer value1, Integer value2) {
return value1 / value2;
}
}

View File

@ -0,0 +1,24 @@
package ru.IP_LabWorks.IP.TypeCalculator.domain;
public class TypeString implements ITypeInterface<String> {
@Override
public String Method1(String value1, String value2) {
return value1 + value2;
}
@Override
public String Method2(String value1, String value2) {
return value1.toUpperCase() + value2.toUpperCase();
}
@Override
public String Method3(String value1, String value2) {
return value1.toLowerCase() + value2.toLowerCase();
}
@Override
public String Method4(String value1, String value2) {
return value1.toLowerCase() + value2.toUpperCase();
}
}

View File

@ -0,0 +1,78 @@
package ru.IP_LabWorks.IP.TypeCalculator.service;
import ru.IP_LabWorks.IP.TypeCalculator.domain.ITypeInterface;
import org.springframework.stereotype.Service;
import org.springframework.context.ApplicationContext;
import java.util.Arrays;
import java.util.stream.Collectors;
@Service
public class TypeService {
private final ApplicationContext applicationContext;
private ITypeInterface _type;
private Object _value1;
private Object _value2;
public TypeService(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
private void ValidateParams(Object value1, Object value2, String type){
_type = (ITypeInterface)applicationContext.getBean(type);
switch (type) {
case "int" -> {
try {
_value1 = Integer.valueOf(value1.toString());
_value2 = Integer.valueOf(value2.toString());
}catch (Exception ex){
_value1 = 0;
_value2 = 0;
}
}
case "double" -> {
try {
_value1 = Double.valueOf(value1.toString());
_value2 = Double.valueOf(value2.toString());
}catch (Exception ex){
_value1 = 0.0;
_value2 = 0.0;
}
}
case "str" -> {
_value1 = value1;
_value2 = value2;
}
case "array" -> {
_value1 = Arrays.stream(value1.toString().split(","))
.map(Integer::parseInt)
.collect(Collectors.toList());
_value2 = Arrays.stream(value2.toString().split(","))
.map(Integer::parseInt)
.collect(Collectors.toList());
}
}
}
public Object Method1(Object value1, Object value2, String type){
ValidateParams(value1,value2,type);
return String.format("%s", _type.Method1(_value1,_value2));
}
public Object Method2(Object value1, Object value2, String type){
ValidateParams(value1,value2,type);
return String.format("%s", _type.Method2(_value1,_value2));
}
public Object Method3(Object value1, Object value2, String type){
ValidateParams(value1,value2,type);
return String.format("%s", _type.Method3(_value1,_value2));
}
public Object Method4(Object value1, Object value2, String type){
ValidateParams(value1,value2,type);
return String.format("%s", _type.Method4(_value1,_value2));
}
}

View File

@ -0,0 +1,14 @@
package ru.IP_LabWorks.IP.University.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class PasswordEncoderConfiguration {
@Bean
public PasswordEncoder createPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,68 @@
package ru.IP_LabWorks.IP.University.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.web.SecurityFilterChain;
import ru.IP_LabWorks.IP.University.Contoller.MVC.UserSignUpMvcController;
import ru.IP_LabWorks.IP.University.Model.UserRole;
import ru.IP_LabWorks.IP.University.Service.UserService;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(
securedEnabled = true
)
public class SecurityConfiguration {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
private static final String LOGIN_URL = "/login";
private final UserService userService;
public SecurityConfiguration(UserService userService) {
this.userService = userService;
createAdminOnStartup();
}
private void createAdminOnStartup() {
final String admin = "admin";
if (userService.findByLogin(admin) == null) {
log.info("Admin user successfully created");
userService.createUser(admin, admin, admin, UserRole.ADMIN);
}
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.headers().frameOptions().sameOrigin().and()
.cors().and()
.csrf().disable()
.authorizeHttpRequests()
.requestMatchers(UserSignUpMvcController.SIGNUP_URL).permitAll()
.requestMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage(LOGIN_URL).permitAll()
.defaultSuccessUrl("/student", true)
.and()
.logout().permitAll();
return http.userDetailsService(userService).build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.requestMatchers("/css/**")
.requestMatchers("/js/**")
.requestMatchers("/templates/**")
.requestMatchers("/webjars/**");
}
}

View File

@ -0,0 +1,20 @@
package ru.IP_LabWorks.IP.University.Configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
public static final String REST_API = "/api";
@Override
public void addViewControllers(ViewControllerRegistry registry) {
WebMvcConfigurer.super.addViewControllers(registry);
registry.addViewController("login");
}
}

View File

@ -0,0 +1,41 @@
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(){
return id;
}
public String getName(){
return name;
}
public void setId(long id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public List<Long> getSubjectIds(){
return subjectIds;
}
}

View File

@ -0,0 +1,62 @@
package ru.IP_LabWorks.IP.University.Contoller.DTO;
import ru.IP_LabWorks.IP.University.Model.Group;
import ru.IP_LabWorks.IP.University.Model.Student;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class StudentDTO {
private long id;
private String name;
private LocalDate birthDate;
private long groupId;
private String groupName;
public StudentDTO() {
}
public StudentDTO(Student student) {
this.id = student.getId();
this.name = student.getName();
this.birthDate = student.getBirthDate();
if(student.getGroup() != null){
this.groupName = student.getGroup().getName();
}
}
public String getGroupName() {
return groupName;
}
public Long getId(){
return id;
}
public String getName(){
return name;
}
public LocalDate getBirthDate(){
return birthDate;
}
public Long getGroupId(){
return groupId;
}
public void setGroupId(long id){
this.groupId = id;
}
public void setId(long id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public void setBirthDate(LocalDate birthDate){
this.birthDate = birthDate;
}
}

View File

@ -0,0 +1,36 @@
package ru.IP_LabWorks.IP.University.Contoller.DTO;
import ru.IP_LabWorks.IP.University.Model.Subject;
import java.util.List;
import java.util.stream.Collectors;
public class SubjectDTO {
private long id;
private String name;
private List<Long> groupIds;
public SubjectDTO(){
}
public SubjectDTO(Subject subject){
this.id = subject.getId();
this.name = subject.getName();
this.groupIds = subject.getGroupIds();
}
public Long getId(){
return id;
}
public String getName(){
return name;
}
public List<Long> getGroupIds(){
return groupIds;
}
public void setName(String name){
this.name = name;
}
}

View File

@ -0,0 +1,28 @@
package ru.IP_LabWorks.IP.University.Contoller.DTO;
import ru.IP_LabWorks.IP.University.Model.User;
import ru.IP_LabWorks.IP.University.Model.UserRole;
public class UserDTO {
private final long id;
private final String login;
private final UserRole role;
public UserDTO(User user) {
this.id = user.getId();
this.login = user.getLogin();
this.role = user.getRole();
}
public long getId() {
return id;
}
public String getLogin() {
return login;
}
public UserRole getRole() {
return role;
}
}

View File

@ -0,0 +1,40 @@
package ru.IP_LabWorks.IP.University.Contoller.DTO;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserSignUpDTO {
@NotBlank
@Size(min = 3, max = 64)
private String login;
@NotBlank
@Size(min = 6, max = 64)
private String password;
@NotBlank
@Size(min = 6, max = 64)
private String passwordConfirm;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
}

View File

@ -0,0 +1,163 @@
package ru.IP_LabWorks.IP.University.Contoller.MVC;
import jakarta.validation.Valid;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.IP_LabWorks.IP.University.Contoller.DTO.GroupDTO;
import ru.IP_LabWorks.IP.University.Model.Student;
import ru.IP_LabWorks.IP.University.Model.Subject;
import ru.IP_LabWorks.IP.University.Service.GroupService;
import ru.IP_LabWorks.IP.University.Service.SubjectService;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Controller
@RequestMapping("/group")
public class GroupMvcController {
private final GroupService groupService;
private final SubjectService subjectService;
public GroupMvcController(GroupService groupService, SubjectService subjectService)
{
this.groupService = groupService;
this.subjectService = subjectService;
}
@GetMapping
public String getGroups(Model model, Authentication authentication) {
model.addAttribute("groups",
groupService.findAllGroups().stream()
.map(GroupDTO::new)
.toList());
boolean isAdmin = authentication.getAuthorities().stream()
.anyMatch(authority -> authority.getAuthority().equals("ROLE_ADMIN"));
model.addAttribute("isAdmin", isAdmin);
return "group";
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editGroup(@PathVariable(required = false) Long id,
Model model, Authentication authentication) {
if (id == null || id <= 0) {
model.addAttribute("groupDTO", new GroupDTO());
boolean isAdmin = authentication.getAuthorities().stream()
.anyMatch(authority -> authority.getAuthority().equals("ROLE_ADMIN"));
model.addAttribute("isAdmin", isAdmin);
} else {
model.addAttribute("groupId", id);
model.addAttribute("groupDTO", new GroupDTO(groupService.findGroup(id)));
}
return "group-edit";
}
@PostMapping(value = {"/", "/{id}"})
public String saveGroup(@PathVariable(required = false) Long id,
@ModelAttribute @Valid GroupDTO groupDTO,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "group-edit";
}
if (id == null || id <= 0) {
groupService.addGroup(groupDTO.getName());
} else {
groupService.updateGroup(id, groupDTO.getName());
}
return "redirect:/group";
}
@PostMapping("/delete/{id}")
public String deleteGroup(@PathVariable Long id) {
groupService.deleteGroup(id);
return "redirect:/group";
}
@GetMapping("/students/{id}")
public String getStudentsFromGroup(@PathVariable Long id, Model model) {
List<Student> students = groupService.getStudentFromGroup(id);
model.addAttribute("students", students);
return "view-students";
}
@GetMapping("/subjects/{id}")
public String getSubjectsFromGroup(@PathVariable Long id, Model model) {
List<Subject> subjects = groupService.getSubjectInGroup(id);
model.addAttribute("subjects", subjects);
return "view-subjects";
}
@GetMapping("/getStudentsUndefined/{id}")
public String getStudentsFromUndefinedGroup(@PathVariable Long id, Model model){
List<Student> students = groupService.getStudentsUndefined();
model.addAttribute("undefinedStudents", students);
model.addAttribute("groupId", id);
model.addAttribute("groupDTO", new GroupDTO(groupService.findGroup(id)));
return "add-students-to-group";
}
@PostMapping("/addStudents/{id}")
public String addStudentToGroup(@PathVariable Long id,
@RequestParam("studentId") List<String> studentsIds){
List<Long> studentIdsAsLong = studentsIds.stream()
.map(Long::parseLong)
.collect(Collectors.toList());
groupService.addStudentToGroup(id, studentIdsAsLong);
return "redirect:/group";
}
@PostMapping("/deleteStudentFromGroup/{id}")
public String deleteStudentFromGroup(@PathVariable Long id) {
groupService.deleteStudentFromGroup(id);
return "redirect:/group";
}
@GetMapping("/getSubjectsUndefined/{id}")
public String getSubjectsFromUndefinedGroup(@PathVariable Long id, Model model){
List<Subject> subjects = groupService.getSubjectsUndefined(id);
model.addAttribute("undefinedSubjects", subjects);
model.addAttribute("groupId", id);
model.addAttribute("groupDTO", new GroupDTO(groupService.findGroup(id)));
return "add-subject-to-group";
}
@PostMapping("/addSubjects/{id}")
public String addSubjectToGroup(@PathVariable Long id,
@RequestParam("subjectId") List<String> subjectIds){
List<Long> subjectIdsAsLong = subjectIds.stream()
.map(Long::parseLong)
.collect(Collectors.toList());
groupService.addSubjectToGroup(id, subjectIdsAsLong);
return "redirect:/group";
}
@GetMapping("/getAll")
public String getAll(Model model){
Map<String, List<String>> report = groupService.getAll();
model.addAttribute("report", report);
return "report";
}
/* @GetMapping("/addSubjectToGroup/{id}")
public String addSubjectToGroupForm(@PathVariable Long id, Model model) {
model.addAttribute("groupDTO", new GroupDTO(groupService.findGroup(id)));
model.addAttribute("groupId", id);
model.addAttribute("subjects", subjectService.findAllSubjects());
return "add-subject-to-group";
}
@PostMapping("/addSubjectToGroup/{id}")
public String addSubjectToGroup(@PathVariable Long id,
@RequestParam("subjectId") List<Long> subjectIds) {
groupService.addSubjectToGroup(id, subjectIds);
return "redirect:/group";
}*/
}

View File

@ -0,0 +1,79 @@
package ru.IP_LabWorks.IP.University.Contoller.MVC;
import jakarta.validation.Valid;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
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;
@Controller
@RequestMapping("/student")
public class StudentMvcController {
private final StudentService studentService;
private final GroupService groupService;
public StudentMvcController(StudentService studentService, GroupService groupService)
{
this.studentService = studentService;
this.groupService = groupService;
}
@GetMapping
public String getStudents(Model model, Authentication authentication) {
model.addAttribute("students",
studentService.findAllStudents().stream()
.map(StudentDTO::new)
.toList());
boolean isAdmin = authentication.getAuthorities().stream()
.anyMatch(authority -> authority.getAuthority().equals("ROLE_ADMIN"));
model.addAttribute("isAdmin", isAdmin);
return "student";
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editStudent(@PathVariable(required = false) Long id,
Model model, Authentication authentication) {
model.addAttribute("Groups", groupService.findAllGroups());
if (id == null || id <= 0) {
model.addAttribute("studentDTO", new StudentDTO());
boolean isAdmin = authentication.getAuthorities().stream()
.anyMatch(authority -> authority.getAuthority().equals("ROLE_ADMIN"));
model.addAttribute("isAdmin", isAdmin);
} else {
model.addAttribute("studentId", id);
model.addAttribute("studentDTO", new StudentDTO(studentService.findStudent(id)));
}
return "student-edit";
}
@PostMapping(value = {"", "/{id}"})
public String saveStudent(@PathVariable(required = false) Long id,
@ModelAttribute @Valid StudentDTO studentDTO,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "student-edit";
}
if (id == null || id <= 0) {
studentService.addStudent(studentDTO.getName(), studentDTO.getBirthDate());
} else {
studentService.updateStudent(id, studentDTO.getName(), studentDTO.getBirthDate());
}
return "redirect:/student";
}
@PostMapping("/delete/{id}")
public String deleteStudent(@PathVariable Long id) {
studentService.deleteStudent(id);
return "redirect:/student";
}
}

View File

@ -0,0 +1,92 @@
package ru.IP_LabWorks.IP.University.Contoller.MVC;
import jakarta.validation.Valid;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.IP_LabWorks.IP.University.Contoller.DTO.SubjectDTO;
import ru.IP_LabWorks.IP.University.Service.GroupService;
import ru.IP_LabWorks.IP.University.Service.SubjectService;
import java.util.List;
@Controller
@RequestMapping("/subject")
public class SubjectMvcController {
private final SubjectService subjectService;
private final GroupService groupService;
public SubjectMvcController(SubjectService subjectService, GroupService groupService)
{
this.subjectService = subjectService;
this.groupService = groupService;
}
@GetMapping
public String getSubjects(Model model, Authentication authentication) {
model.addAttribute("subjects",
subjectService.findAllSubjects().stream()
.map(SubjectDTO::new)
.toList());
boolean isAdmin = authentication.getAuthorities().stream()
.anyMatch(authority -> authority.getAuthority().equals("ROLE_ADMIN"));
model.addAttribute("isAdmin", isAdmin);
return "subject";
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editSubject(@PathVariable(required = false) Long id,
Model model, Authentication authentication) {
if (id == null || id <= 0) {
model.addAttribute("subjectDTO", new SubjectDTO());
boolean isAdmin = authentication.getAuthorities().stream()
.anyMatch(authority -> authority.getAuthority().equals("ROLE_ADMIN"));
model.addAttribute("isAdmin", isAdmin);
} else {
model.addAttribute("subjectId", id);
model.addAttribute("subjectDTO", new SubjectDTO(subjectService.findSubject(id)));
}
return "subject-edit";
}
@PostMapping(value = {"/", "/{id}"})
public String saveSubject(@PathVariable(required = false) Long id,
@ModelAttribute @Valid SubjectDTO subjectDTO,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "subject-edit";
}
if (id == null || id <= 0) {
subjectService.addSubject(subjectDTO.getName());
} else {
subjectService.updateSubject(id, subjectDTO.getName());
}
return "redirect:/subject";
}
@PostMapping("/delete/{id}")
public String deleteSubject(@PathVariable Long id) {
subjectService.deleteSubject(id);
return "redirect:/subject";
}
@GetMapping("/addSubjectToGroup/{id}")
public String addSubjectToGroupForm(@PathVariable Long id, Model model) {
model.addAttribute("subjectDTO", new SubjectDTO(subjectService.findSubject(id)));
model.addAttribute("subjectId", id);
model.addAttribute("groups", groupService.findAllGroups());
return "add-subject-to-group";
}
@PostMapping("/addSubjectToGroup/{id}")
public String addSubjectToGroup(@PathVariable Long id,
@RequestParam("groupId") List<Long> groupIds) {
subjectService.addSubjectToGroup(id, groupIds);
return "redirect:/subject";
}
}

View File

@ -0,0 +1,42 @@
package ru.IP_LabWorks.IP.University.Contoller.MVC;
import org.springframework.data.domain.Page;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import ru.IP_LabWorks.IP.University.Contoller.DTO.UserDTO;
import ru.IP_LabWorks.IP.University.Model.UserRole;
import ru.IP_LabWorks.IP.University.Service.UserService;
import java.util.List;
import java.util.stream.IntStream;
@Controller
@RequestMapping("/users")
public class UserMvcController {
private final UserService userService;
public UserMvcController(UserService userService) {
this.userService = userService;
}
@GetMapping
@Secured({UserRole.AsString.ADMIN})
public String getUsers(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "5") int size,
Model model) {
final Page<UserDTO> users = userService.findAllPages(page, size)
.map(UserDTO::new);
model.addAttribute("users", users);
final int totalPages = users.getTotalPages();
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
.boxed()
.toList();
model.addAttribute("pages", pageNumbers);
model.addAttribute("totalPages", totalPages);
return "users";
}
}

View File

@ -0,0 +1,48 @@
package ru.IP_LabWorks.IP.University.Contoller.MVC;
import jakarta.validation.Valid;
import jakarta.validation.ValidationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.IP_LabWorks.IP.University.Contoller.DTO.UserSignUpDTO;
import ru.IP_LabWorks.IP.University.Model.User;
import ru.IP_LabWorks.IP.University.Service.UserService;
@Controller
@RequestMapping(UserSignUpMvcController.SIGNUP_URL)
public class UserSignUpMvcController {
public static final String SIGNUP_URL = "/signup";
private final UserService userService;
public UserSignUpMvcController(UserService userService) {
this.userService = userService;
}
@GetMapping
public String showSignupForm(Model model) {
model.addAttribute("UserDTO", new UserSignUpDTO());
return "signup";
}
@PostMapping
public String signup(@ModelAttribute("UserDTO") @Valid UserSignUpDTO userSignupDto,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "signup";
}
try {
final User user = userService.createUser(userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm());
return "redirect:/login?created=" + user.getLogin();
} catch (ValidationException e) {
model.addAttribute("errors", e.getMessage());
return "signup";
}
}
}

View File

@ -0,0 +1,87 @@
package ru.IP_LabWorks.IP.University.Contoller.REST;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ru.IP_LabWorks.IP.University.Contoller.DTO.GroupDTO;
import ru.IP_LabWorks.IP.University.Model.Student;
import ru.IP_LabWorks.IP.University.Model.Subject;
import ru.IP_LabWorks.IP.University.Service.GroupService;
import ru.IP_LabWorks.IP.University.Configuration.WebConfiguration;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/group")
public class GroupController {
private final GroupService groupService;
public GroupController(GroupService groupService) {
this.groupService = groupService;
}
@GetMapping("/{id}")
public GroupDTO getGroup(@PathVariable Long id){
return new GroupDTO(groupService.findGroup(id));
}
@GetMapping
public List<GroupDTO> getGroups(){
return groupService.findAllGroups().stream()
.map(GroupDTO::new)
.toList();
}
@PostMapping
public GroupDTO createGroup(@RequestBody @Valid GroupDTO groupDTO){
return new GroupDTO(groupService.addGroup(groupDTO.getName()));
}
@PutMapping("/{id}")
public GroupDTO updateGroup(@PathVariable Long id, @RequestBody @Valid GroupDTO groupDTO){
return new GroupDTO(groupService.updateGroup(id, groupDTO.getName()));
}
@DeleteMapping("/{id}")
public GroupDTO deleteGroup(@PathVariable Long id){
return new GroupDTO(groupService.deleteGroup(id));
}
@GetMapping("/{groupId}/students")
public ResponseEntity<List<Student>> getStudentsFromGroup(@PathVariable Long groupId) {
List<Student> students = groupService.getStudentFromGroup(groupId);
return ResponseEntity.ok(students);
}
@GetMapping("/{groupId}/getAllSubjects")
public ResponseEntity<List<Subject>> getSubjectInGroup(@PathVariable Long groupId){
List<Subject> subjects = groupService.getSubjectInGroup(groupId);
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);
}
@GetMapping("/getAll")
public Map<String, List<String>> getAll(){
return groupService.getAll();
}
}

View File

@ -0,0 +1,59 @@
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 ru.IP_LabWorks.IP.University.Configuration.WebConfiguration;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/student")
public class StudentController {
private final StudentService studentService;
private final GroupService groupService;
public StudentController(StudentService studentService, GroupService groupService) {
this.studentService = studentService;
this.groupService = groupService;
}
@GetMapping("/{id}")
public StudentDTO getStudent(@PathVariable Long id){
return new StudentDTO(studentService.findStudent(id));
}
@GetMapping
public List<StudentDTO> getStudents(){
return studentService.findAllStudents().stream()
.map(StudentDTO::new)
.toList();
}
@PostMapping
public StudentDTO createStudent(@RequestBody @Valid StudentDTO studentDTO){
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()));
}
@DeleteMapping("/{id}")
public StudentDTO deleteStudent(@PathVariable Long id){
return new StudentDTO(studentService.deleteStudent(id));
}
@GetMapping("/groups")
public List<GroupDTO> getGroups() {
return groupService.findAllGroups().stream()
.map(GroupDTO::new)
.toList();
}
}

View File

@ -0,0 +1,56 @@
package ru.IP_LabWorks.IP.University.Contoller.REST;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import ru.IP_LabWorks.IP.University.Contoller.DTO.SubjectDTO;
import ru.IP_LabWorks.IP.University.Service.SubjectService;
import ru.IP_LabWorks.IP.University.Configuration.WebConfiguration;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/subject")
public class SubjectController {
private final SubjectService subjectService;
public SubjectController(SubjectService subjectService) {
this.subjectService = subjectService;
}
@GetMapping("/{id}")
public SubjectDTO getSubject(@PathVariable Long id){
return new SubjectDTO(subjectService.findSubject(id));
}
@GetMapping
public List<SubjectDTO> getSubject(){
return subjectService.findAllSubjects().stream()
.map(SubjectDTO::new)
.toList();
}
@PostMapping
public SubjectDTO createSubject(@RequestBody @Valid SubjectDTO subjectDTO){
return new SubjectDTO(subjectService.addSubject(subjectDTO.getName()));
}
@PutMapping("/{id}")
public SubjectDTO updateSubject(@PathVariable Long id, @RequestBody @Valid SubjectDTO subjectDTO){
return new SubjectDTO(subjectService.updateSubject(id,subjectDTO.getName()));
}
@DeleteMapping("/{id}")
public SubjectDTO deleteSubject(@PathVariable Long id){
return new SubjectDTO(subjectService.deleteSubject(id));
}
@GetMapping("/getAllSubjectGroup")
public List<Object[]> getAllSubjectGroup(){
return subjectService.getAllSubjectGroup();
}
@PostMapping("/{id}/addSubjectToGroup")
public void addSubjectToGroup(@PathVariable Long id, @RequestBody @Valid List<Long> groupsIds){
subjectService.addSubjectToGroup(id, groupsIds);
}
}

View File

@ -0,0 +1,116 @@
package ru.IP_LabWorks.IP.University.Model;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "groups")
public class Group {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@JsonManagedReference
@OneToMany(fetch = FetchType.EAGER, mappedBy = "group")
private List<Student> students;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "subject_group",
joinColumns = {@JoinColumn(name = "group_id")},
inverseJoinColumns = {@JoinColumn(name = "subject_id")})
private List<Subject> subjects;
@ManyToOne
@JoinColumn(name= "user_id", nullable = false)
private User user;
public Group() {
this.students = new ArrayList<>();
}
public Group(String name) {
this.name = name;
this.students = new ArrayList<>();
}
public Long getId() { return id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Group group = (Group) o;
return Objects.equals(id, group.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Group{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public void setStudent(Student student){
this.students.add(student);
if(student.getGroup() != this){
student.setGroup(this);
}
}
public List<Student> getStudents(){
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
public List<Subject> getSubjects(){
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
public void addSubject(Subject subject) {
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;
}
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}

View File

@ -0,0 +1,95 @@
package ru.IP_LabWorks.IP.University.Model;
import com.fasterxml.jackson.annotation.JsonBackReference;
import jakarta.persistence.*;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import java.time.LocalDate;
import java.time.Period;
import java.util.Objects;
@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private LocalDate birthDate;
@JsonBackReference
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "group_id", nullable = true)
private Group group;
@ManyToOne
@JoinColumn(name= "user_id", nullable = false)
private User user;
public Student() {
}
public Student(String name, LocalDate birthDate) {
this.name = name;
this.birthDate = birthDate;
}
public Long getId() { return id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public LocalDate getBirthDate() { return birthDate;}
public void setBirthDate(LocalDate birthDate) { this.birthDate = birthDate; }
public Integer getAge() {
if (birthDate == null) {
return 0;
}
return Period.between(birthDate, LocalDate.now()).getYears();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(id, student.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
String groupStr = (group != null) ? group.getName() : "No Group";
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", birthDate='" + birthDate + '\'' +
", age='" + getAge() + '\'' +
", group='" + groupStr + '\'' +
'}';
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
if (this.group != group) {
if (this.group != null) {
this.group.getStudents().remove(this);
}
this.group = group;
if (group != null && !group.getStudents().contains(this)) {
group.getStudents().add(this);
}
}
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}

View File

@ -0,0 +1,92 @@
package ru.IP_LabWorks.IP.University.Model;
import com.fasterxml.jackson.annotation.JsonBackReference;
import jakarta.persistence.*;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "subjects")
public class Subject {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@JsonBackReference
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)
@JoinTable(name = "subject_group",
joinColumns = {@JoinColumn(name = "subject_id")},
inverseJoinColumns = {@JoinColumn(name = "group_id")})
private List<Group> groups = new ArrayList<>();
@ManyToOne
@JoinColumn(name= "user_id", nullable = false)
private User user;
public Subject() {
}
public Subject(String name) {
this.name = name;
}
public Long getId() { return id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Subject subject = (Subject) o;
return Objects.equals(id, subject.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Subject{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public List<Group> getGroups(){
return groups;
}
public void setGroups(List<Group> groups) {
this.groups = groups;
}
public List<Long> getGroupIds() {
if (groups.isEmpty()) {
return Collections.emptyList();
} else {
List<Long> groupIds = new ArrayList<>();
for (Group group : groups) {
if (!groupIds.contains(group.getId())) {
groupIds.add(group.getId());
}
}
return groupIds;
}
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}

View File

@ -0,0 +1,83 @@
package ru.IP_LabWorks.IP.University.Model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.util.Objects;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true, length = 64)
@NotBlank
@Size(min = 3, max = 64)
private String login;
@Column(nullable = false, length = 64)
@NotBlank
@Size(min = 6, max = 64)
private String password;
private UserRole role;
public User() {
}
public User(String login, String password) {
this(login, password, UserRole.USER);
}
public User(String login, String password, UserRole role) {
this.login = login;
this.password = password;
this.role = role;
}
public Long getId() {
return id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserRole getRole() {
return role;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id) && Objects.equals(login, user.login);
}
@Override
public int hashCode() {
return Objects.hash(id, login);
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", login='" + login + '\'' +
", password='" + password + '\'' +
", role='" + role + '\'' +
'}';
}
}

View File

@ -0,0 +1,20 @@
package ru.IP_LabWorks.IP.University.Model;
import org.springframework.security.core.GrantedAuthority;
public enum UserRole implements GrantedAuthority {
ADMIN,
USER;
private static final String PREFIX = "ROLE_";
@Override
public String getAuthority() {
return PREFIX + this.name();
}
public static final class AsString {
public static final String ADMIN = PREFIX + "ADMIN";
public static final String USER = PREFIX + "USER";
}
}

View File

@ -0,0 +1,15 @@
package ru.IP_LabWorks.IP.University.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import ru.IP_LabWorks.IP.University.Model.Group;
import java.util.List;
public interface GroupRepository extends JpaRepository<Group, Long> {
@Query("select g.name as group, s.name as students " +
"from Group g " +
"join g.students s " +
"group by g.id, g.name, s.name")
List<Object[]> getAll();
}

View File

@ -0,0 +1,7 @@
package ru.IP_LabWorks.IP.University.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.IP_LabWorks.IP.University.Model.Student;
public interface StudentRepository extends JpaRepository<Student, Long> {
}

View File

@ -0,0 +1,12 @@
package ru.IP_LabWorks.IP.University.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import ru.IP_LabWorks.IP.University.Model.Subject;
import java.util.List;
public interface SubjectRepository extends JpaRepository<Subject, Long> {
@Query(value = "SELECT * FROM subject_group", nativeQuery = true)
List<Object[]> getAllSubjectGroup();
}

View File

@ -0,0 +1,9 @@
package ru.IP_LabWorks.IP.University.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.IP_LabWorks.IP.University.Model.Student;
import ru.IP_LabWorks.IP.University.Model.User;
public interface UserRepository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login);
}

View File

@ -0,0 +1,167 @@
package ru.IP_LabWorks.IP.University.Service;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import ru.IP_LabWorks.IP.University.Model.*;
import ru.IP_LabWorks.IP.University.Repository.GroupRepository;
import ru.IP_LabWorks.IP.University.Service.NotFoundException.GroupNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class GroupService {
private final GroupRepository groupRepository;
private final StudentService studentService;
private final SubjectService subjectService;
private final UserService userService;
public GroupService(GroupRepository groupRepository, StudentService studentService, @Lazy SubjectService subjectService, UserService userService) {
this.groupRepository = groupRepository;
this.studentService = studentService;
this.subjectService = subjectService;
this.userService = userService;
}
@Transactional
public Group addGroup(String name){
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Group name is null or empty");
}
final Group group = new Group(name);
Object currentUser = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if(currentUser instanceof UserDetails){
String username = ((UserDetails)currentUser).getUsername();
User user = userService.findByLogin(username);
if(user.getRole() == UserRole.ADMIN){
group.setUser(user);
}
}
return groupRepository.save(group);
}
@Transactional(readOnly = true)
public Group findGroup(Long id){
final Optional<Group> group = groupRepository.findById(id);
return group.orElseThrow(() -> new GroupNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Group> findAllGroups() {
return groupRepository.findAll();
}
@Transactional
public Group updateGroup(Long id, String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Group name is null or empty");
}
final Group currentGroup = findGroup(id);
currentGroup.setName(name);
return groupRepository.save(currentGroup);
}
@Transactional
public Group deleteGroup(Long id) {
final Group currentGroup = findGroup(id);
groupRepository.delete(currentGroup);
return currentGroup;
}
@Transactional
public void deleteAllGroups() {
groupRepository.deleteAll();
}
@Transactional
public List<Student> getStudentFromGroup(Long groupId){
Optional<Group> groupOptional = groupRepository.findById(groupId);
if (groupOptional.isPresent()) {
Group group = groupOptional.get();
return group.getStudents();
} else {
throw new IllegalArgumentException("Group not found with id: " + groupId);
}
}
@Transactional
public List<Subject> getSubjectInGroup(Long groupId){
Optional<Group> groupOptional = groupRepository.findById(groupId);
if (groupOptional.isPresent()) {
Group group = groupOptional.get();
return group.getSubjects();
} else {
throw new IllegalArgumentException("Group not found with id: " + groupId);
}
}
@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 List<Subject> getSubjectsUndefined(Long groupId){
List<Subject> subjects = new ArrayList<>();
for(Subject subject : subjectService.findAllSubjects()){
if(!subject.getGroupIds().contains(groupId)){
subjects.add(subject);
}
}
return subjects;
}
@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 deleteSubjectFromGroup(Long id){
subjectService.findSubject(id);
}
@Transactional
public void addSubjectToGroup(Long groupId, List<Long> subjectIds){
final Group currentGroup = findGroup(groupId);
for(Long subjectId : subjectIds) {
currentGroup.getSubjects().add(subjectService.findSubject(subjectId));
}
groupRepository.save(currentGroup);
}
@Transactional
public Map<String, List<String>> getAll(){
return groupRepository.getAll().stream()
.collect(
Collectors.groupingBy(
o -> (String) o[0],
Collectors.mapping( o -> (String) o[1], Collectors.toList() )
)
);
}
}

View File

@ -0,0 +1,7 @@
package ru.IP_LabWorks.IP.University.Service.NotFoundException;
public class GroupNotFoundException extends RuntimeException {
public GroupNotFoundException(Long id) {
super(String.format("Group with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,7 @@
package ru.IP_LabWorks.IP.University.Service.NotFoundException;
public class StudentNotFoundException extends RuntimeException {
public StudentNotFoundException(Long id) {
super(String.format("Student with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,7 @@
package ru.IP_LabWorks.IP.University.Service.NotFoundException;
public class SubjectNotFoundException extends RuntimeException {
public SubjectNotFoundException(Long id) {
super(String.format("Subject with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,92 @@
package ru.IP_LabWorks.IP.University.Service;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import ru.IP_LabWorks.IP.University.Model.Student;
import ru.IP_LabWorks.IP.University.Model.User;
import ru.IP_LabWorks.IP.University.Model.UserRole;
import ru.IP_LabWorks.IP.University.Repository.StudentRepository;
import ru.IP_LabWorks.IP.University.Service.NotFoundException.StudentNotFoundException;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
@Service
public class StudentService {
private final StudentRepository studentRepository;
private final GroupService groupService;
private final UserService userService;
public StudentService(StudentRepository studentRepository, @Lazy GroupService groupService, UserService userService) {
this.studentRepository = studentRepository;
this.groupService = groupService;
this.userService = userService;
}
@Transactional
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");
}
final Student student = new Student(name, birthDate);
Object currentUser = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if(currentUser instanceof UserDetails){
String username = ((UserDetails)currentUser).getUsername();
User user = userService.findByLogin(username);
if(user.getRole() == UserRole.ADMIN){
student.setUser(user);
}
}
return studentRepository.save(student);
}
@Transactional(readOnly = true)
public Student findStudent(Long id) {
final Optional<Student> student = studentRepository.findById(id);
return student.orElseThrow(() -> new StudentNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Student> findAllStudents() {
return studentRepository.findAll();
}
@Transactional
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);
return studentRepository.save(currentStudent);
}
@Transactional
public Student deleteStudent(Long id) {
final Student currentStudent = findStudent(id);
studentRepository.delete(currentStudent);
return currentStudent;
}
@Transactional
public void deleteAllStudent() {
studentRepository.deleteAll();
}
// @Transactional
// public void AddStudentToGroup(Long idStudent, Long idGroup){
// Student student = findStudent(idStudent);
// Group group = em.find(Group.class, idGroup);
// if (group == null || student == null) {
// throw new EntityNotFoundException("Group or Student not found");
// }
// student.setGroup(group);
// em.merge(student);
// }
}

View File

@ -0,0 +1,129 @@
package ru.IP_LabWorks.IP.University.Service;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.IP_LabWorks.IP.University.Model.Subject;
import ru.IP_LabWorks.IP.University.Model.User;
import ru.IP_LabWorks.IP.University.Model.UserRole;
import ru.IP_LabWorks.IP.University.Repository.SubjectRepository;
import ru.IP_LabWorks.IP.University.Service.NotFoundException.SubjectNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class SubjectService {
private final SubjectRepository subjectRepository;
private final GroupService groupService;
private final UserService userService;
public SubjectService(SubjectRepository subjectRepository, GroupService groupService, UserService userService) {
this.subjectRepository = subjectRepository;
this.groupService = groupService;
this.userService = userService;
}
@Transactional
public Subject addSubject(String name){
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Subject name is null or empty");
}
final Subject subject = new Subject(name);
Object currentUser = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if(currentUser instanceof UserDetails){
String username = ((UserDetails)currentUser).getUsername();
User user = userService.findByLogin(username);
if(user.getRole() == UserRole.ADMIN){
subject.setUser(user);
}
}
return subjectRepository.save(subject);
}
@Transactional(readOnly = true)
public Subject findSubject(Long id){
final Optional<Subject> subject = subjectRepository.findById(id);
return subject.orElseThrow(() -> new SubjectNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Subject> findAllSubjects() {
return subjectRepository.findAll();
}
@Transactional
public Subject updateSubject(Long id, String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Subject name is null or empty");
}
final Subject currentSubject = findSubject(id);
currentSubject.setName(name);
return subjectRepository.save(currentSubject);
}
@Transactional
public Subject deleteSubject(Long id) {
final Subject currentSubject = findSubject(id);
currentSubject.getGroups().clear(); // Удаляем все связи с группами
subjectRepository.delete(currentSubject);
return currentSubject;
}
@Transactional
public void deleteAllSubjects() {
subjectRepository.deleteAll();
}
@Transactional
public List<Object[]> getAllSubjectGroup(){
return subjectRepository.getAllSubjectGroup();
}
@Transactional
public void addSubjectToGroup(Long subjectId, List<Long> groupIds){
final Subject currentSubject = findSubject(subjectId);
currentSubject.setGroups(new ArrayList<>());
for(Long groupId : groupIds) {
currentSubject.getGroups().add(groupService.findGroup(groupId));
}
subjectRepository.save(currentSubject);
}
// @Transactional
// public void addSubjectToGroup(List<Long> groupsId, Subject subject) {
// List<Group> groups = groupRepository.findAllById(groupsId);
// for (Group group : groups) {
// group.addSubject(subject);
// }
// groupRepository.saveAll(groups);
// }
// @Transactional
// public void addGroupToSubject(Long subjectId, Long groupId) {
// Subject subject = findSubject(subjectId);
// Group group = em.find(Group.class, groupId);
// subject.getGroups().add(group);
// em.merge(subject);
// em.merge(group);
// }
//
// @Transactional
// public void removeGroupFromSubject(Long subjectId, Long groupId) {
// Subject subject = findSubject(subjectId);
// Group group = em.find(Group.class, groupId);
// subject.getGroups().remove(group);
// em.merge(subject);
// em.merge(group);
// }
//
// @Transactional(readOnly = true)
// public List<Group> findGroupsBySubject(Long subjectId) {
// Subject subject = findSubject(subjectId);
// return subject.getGroups();
// }
}

View File

@ -0,0 +1,59 @@
package ru.IP_LabWorks.IP.University.Service;
import jakarta.validation.ValidationException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import ru.IP_LabWorks.IP.University.Model.User;
import ru.IP_LabWorks.IP.University.Model.UserRole;
import ru.IP_LabWorks.IP.University.Repository.UserRepository;
import java.util.Collections;
import java.util.Objects;
@Service
public class UserService implements UserDetailsService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
public Page<User> findAllPages(int page, int size) {
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
}
public User findByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login);
}
public User createUser(String login, String password, String passwordConfirm) {
return createUser(login, password, passwordConfirm, UserRole.USER);
}
public User createUser(String login, String password, String passwordConfirm, UserRole role) {
if (findByLogin(login) != null) {
throw new ValidationException(String.format("User '%s' already exists", login));
}
final User user = new User(login, passwordEncoder.encode(password), role);
if (!Objects.equals(password, passwordConfirm)) {
throw new ValidationException("Passwords not equals");
}
return userRepository.save(user);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final User userEntity = findByLogin(username);
if (userEntity == null) {
throw new UsernameNotFoundException(username);
}
return new org.springframework.security.core.userdetails.User(
userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
}
}

View File

@ -1 +1,11 @@
spring.main.banner-mode=off
server.port=8080
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false

View File

@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/group/addStudents/{id}(id=${groupId})}" method="post">
<div class="mb-3">
<label for="name" class="form-label">Название</label>
<input type="text" class="form-control" id="name" th:field="${groupDTO.name}" readonly>
</div>
<div class="form-group">
<label for="name">Выберите студентов:</label>
<ul class="list-group">
<li class="list-group-item" th:each="student, iterator: ${undefinedStudents}">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="studentId" th:value="${student.id}">
<label class="form-check-label" th:text="${student.name}"></label>
</div>
</li>
</ul>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span>Добавить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/group}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/group/addSubjects/{id}(id=${groupId})}" method="post">
<div class="mb-3">
<label for="name" class="form-label">Название</label>
<input type="text" class="form-control" id="name" th:field="${groupDTO.name}" readonly>
</div>
<div class="form-group">
<label for="name">Выберите предметы для добавления:</label>
<ul class="list-group">
<li class="list-group-item" th:each="subject, iterator: ${undefinedSubjects}">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="subjectId" th:value="${subject.id}">
<label class="form-check-label" th:text="${subject.name}"></label>
</div>
</li>
</ul>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span>Добавить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/group}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -0,0 +1,41 @@
<!DOCTYPE html>
<html lang="ru"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title>University</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="icon" href="/favicon.svg">
<script type="text/javascript" src="/webjars/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="/webjars/bootstrap/5.1.3/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/webjars/font-awesome/6.1.0/css/all.min.css"/>
<link rel="stylesheet" href="/css/style.css"/>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<button class="navbar-toggler" type="button"
data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<a class="nav-link" href="/student" th:classappend="${#strings.equals(activeLink, '/student')} ? 'active' : ''">Студенты</a>
<a class="nav-link" href="/group" th:classappend="${#strings.equals(activeLink, '/group')} ? 'active' : ''">Группы</a>
<a class="nav-link" href="/subject" th:classappend="${#strings.equals(activeLink, '/subject')} ? 'active' : ''">Предметы</a>
<a class="nav-link" href="/users" th:classappend="${#strings.equals(activeLink, '/users')} ? 'active' : ''">Пользователи</a>
<a class="nav-link" href="/logout" th:classappend="${#strings.equals(activeLink, '/login')} ? 'active' : ''">Выход</a>
</ul>
</div>
</div>
</nav>
<div class="container-fluid">
<div class="container container-padding" layout:fragment="content">
</div>
</div>
</body>
<th:block layout:fragment="scripts">
</th:block>
</html>

View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div class="alert alert-danger">
<span th:text="${error}"></span>
</div>
<a href="/student">На главную</a>
</div>
</body>
</html>

View File

@ -0,0 +1,27 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/group/{id}(id=${id})}" th:object="${groupDTO}" method="post">
<div class="mb-3">
<label for="name" class="form-label">Название</label>
<input type="text" class="form-control" id="name" th:field="${groupDTO.name}" required="true">
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span th:if="${groupId == null}">Добавить</span>
<span th:if="${groupId != null}">Обновить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/group}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -0,0 +1,60 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div layout:fragment="content">
<h1 class="text-center mb-4">Group Table</h1>
<div>
<a class="btn btn-success button-fixed"
th:href="@{/group/edit}" th:if="${isAdmin}">
<i class="fa-solid fa-plus"></i> Добавить
</a>
<a class="btn btn-success button-fixed"
th:href="@{/group/getAll}">
<i class="fa-solid fa-plus"></i> Отчет
</a>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Название</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr th:each="group, iterator: ${groups}">
<td th:text="${group.name}"></td>
<td>
<div class="btn-group" role="group" aria-label="Basic example">
<a class="btn btn-warning button-fixed button-sm"
th:href="@{/group/edit/{id}(id=${group.id})}" th:if="${isAdmin}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a>
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${group.id}').click()|" th:if="${isAdmin}">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
<a class="btn btn-primary button-fixed button-sm"
th:href="@{/group/students/{id}(id=${group.id})}">Посмотреть студентов</a>
<a class="btn btn-primary button-fixed button-sm"
th:href="@{/group/getStudentsUndefined/{id}(id=${group.id})}">Добавить студентов</a>
<a class="btn btn-primary button-fixed button-sm"
th:href="@{/group/getSubjectsUndefined/{id}(id=${group.id})}"> Добавить предметы</a>
<a class="btn btn-primary button-fixed button-sm"
th:href="@{/group/subjects/{id}(id=${group.id})}">Посмотреть предметы</a>
</div>
<form th:action="@{/group/delete/{id}(id=${group.id})}" method="post" th:if="${isAdmin}">
<button th:id="'remove-' + ${group.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,42 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.w3.org/1999/xhtml"
layout:decorate="~{default}">
<body>
<div layout:fragment="content">
<div th:if="${param.error}" class="alert alert-danger margin-bottom">
User not found
</div>
<div th:if="${param.logout}" class="alert alert-success margin-bottom">
Logout success
</div>
<div th:if="${param.created}" class="alert alert-success margin-bottom">
User '<span th:text="${param.created}"></span>' was successfully created
</div>
<form th:action="@{/login}" method="post">
<div class="mb-3">
<p class="mb-1">Login</p>
<input name="username" id="username" class="form-control"
type="text" required autofocus />
</div>
<div class="mb-3">
<p class="mb-1">Password</p>
<input name="password" id="password" class="form-control"
type="password" required />
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success">
Sign in
</button>
</div>
<div>
<p>
<span>Not a member yet?</span>
<a href="/signup">Sign Up here</a>
</p>
</div>
</form>
</div>
</body>
</html>

View File

@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div layout:fragment="content">
<h1 class="text-center mb-4">Report</h1>
<div>
<a class="btn btn-secondary button-fixed" th:href="@{/group}">
Назад
</a>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Группа</th>
<th scope="col">Студенты</th>
</tr>
</thead>
<tbody>
<tr th:each="report, iterator: ${report}">
<td th:text="${report.key}"/>
<td>
<ul>
<li th:each="value : ${report.value}">
<span style="text-decoration: none" th:text="${value}"></span>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,29 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org"
layout:decorate="~{default}">
<body>
<div class="container container-padding mt-3" layout:fragment="content">
<div th:if="${errors}" th:text="${errors}" class="margin-bottom alert alert-danger"></div>
<form action="#" th:action="@{/signup}" th:object="${UserDTO}" method="post">
<div class="mb-3">
<input type="text" class="form-control" th:field="${UserDTO.login}"
placeholder="Логин" required="true" autofocus="true" maxlength="64"/>
</div>
<div class="mb-3">
<input type="password" class="form-control" th:field="${UserDTO.password}"
placeholder="Пароль" required="true" minlength="6" maxlength="64"/>
</div>
<div class="mb-3">
<input type="password" class="form-control" th:field="${UserDTO.passwordConfirm}"
placeholder="Пароль (подтверждение)" required="true" minlength="6" maxlength="64"/>
</div>
<div class="mx-4">
<button type="submit" class="btn btn-success button-fixed">Создать</button>
<a class="btn btn-primary button-fixed" href="/login">Назад</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -0,0 +1,31 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/student}" th:object="${studentDTO}" method="post">
<div class="mb-3">
<label for="name" class="form-label">ФИО</label>
<input type="text" class="form-control" id="name" th:field="${studentDTO.name}" required="true">
</div>
<div class="mb-3">
<label for="birthDate" class="form-label">Дата рождения</label>
<input type="date" class="form-control" id="birthDate" th:field="${studentDTO.birthDate}" required="true">
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span th:if="${studentId == null}">Добавить</span>
<span th:if="${studentId != null}">Обновить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/student}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -0,0 +1,54 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<h1 class="text-center mb-4">Student Table</h1>
<div>
<a class="btn btn-success button-fixed"
th:href="@{/student/edit}" th:if="${isAdmin}">
<i class="fa-solid fa-plus"></i> Добавить
</a>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">ФИО</th>
<th scope="col">Дата рождения</th>
<th scope="col">Группа</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr th:each="student, iterator: ${students}">
<td th:text="${student.name}"></td>
<td th:text="${student.birthDate}"></td>
<td th:text="${student.groupName}"></td>
<td>
<div class="btn-group" role="group" aria-label="Basic example">
<a class="btn btn-warning button-fixed button-sm"
th:href="@{/student/edit/{id}(id=${student.id})}" th:if="${isAdmin}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a>
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${student.id}').click()|" th:if="${isAdmin}">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
</div>
<form th:action="@{/student/delete/{id}(id=${student.id})}" method="post" th:if="${isAdmin}">
<button th:id="'remove-' + ${student.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,27 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/subject/{id}(id=${id})}" th:object="${subjectDTO}" method="post">
<div class="mb-3">
<label for="name" class="form-label">Название</label>
<input type="text" class="form-control" id="name" th:field="${subjectDTO.name}" required="true">
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span th:if="${subjectId == null}">Добавить</span>
<span th:if="${subjectId != null}">Обновить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/subject}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@ -0,0 +1,48 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<div layout:fragment="content">
<h1 class="text-center mb-4">Subject Table</h1>
<div>
<a class="btn btn-success button-fixed"
th:href="@{/subject/edit}" th:if="${isAdmin}">
<i class="fa-solid fa-plus"></i> Добавить
</a>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Название</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr th:each="subject, iterator: ${subjects}">
<td th:text="${subject.name}"></td>
<td>
<div class="btn-group" role="group" aria-label="Basic example">
<a class="btn btn-warning button-fixed button-sm"
th:href="@{/subject/edit/{id}(id=${subject.id})}" th:if="${isAdmin}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a>
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${subject.id}').click()|" th:if="${isAdmin}">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
</div>
<form th:action="@{/subject/delete/{id}(id=${subject.id})}" method="post" th:if="${isAdmin}">
<button th:id="'remove-' + ${subject.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,38 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org"
layout:decorate="~{default}">
<body>
<div class="container" layout:fragment="content">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">ID</th>
<th scope="col">Логин</th>
<th scope="col">Роль</th>
</tr>
</thead>
<tbody>
<tr th:each="user, iterator: ${users}">
<th scope="row" th:text="${iterator.index} + 1"></th>
<td th:text="${user.id}"></td>
<td th:text="${user.login}" style="width: 60%"></td>
<td th:text="${user.role}" style="width: 20%"></td>
</tr>
</tbody>
</table>
</div>
<div th:if="${totalPages > 0}" class="pagination">
<span style="float: left; padding: 5px 5px;">Страницы:</span>
<a th:each="page : ${pages}"
th:href="@{/users(page=${page}, size=${users.size})}"
th:text="${page}"
th:class="${page == users.number + 1} ? active">
</a>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,36 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">ФИО</th>
<th scope="col">Дата рождения</th>
<th></th>
</tr>
</thead>
<tbody>
<tr th:each="student, iterator: ${students}">
<td th:text="${student.name}"></td>
<td th:text="${student.birthDate}"></td>
<td>
<form method="post" th:action="@{/group/deleteStudentFromGroup/{id}(id=${student.id})}">
<button type="submit" class="btn btn-danger button-fixed button-sm">Удалить</button>
</form>
</td>
</tr>
</tbody>
<a class="btn btn-secondary button-fixed" th:href="@{/group}">
Назад
</a>
</table>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,28 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Название</th>
</tr>
</thead>
<tbody>
<tr th:each="subject, iterator: ${subjects}">
<td th:text="${subject.name}"></td>
</tr>
</tbody>
<a class="btn btn-secondary button-fixed" th:href="@{/group}">
Назад
</a>
</table>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,78 @@
package ru.IP_LabWorks.IP;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.IP_LabWorks.IP.University.Model.Group;
import ru.IP_LabWorks.IP.University.Model.Student;
import ru.IP_LabWorks.IP.University.Service.GroupService;
import ru.IP_LabWorks.IP.University.Service.StudentService;
import java.time.LocalDate;
import java.util.List;
@SpringBootTest
public class GroupServiceTests {
@Autowired
private GroupService groupService;
@Autowired
private StudentService studentService;
@Test
void TestAddGroup(){
groupService.deleteAllGroups();
final Group group = groupService.addGroup("ПИбд-21");
Assertions.assertNotNull(group.getId());
}
@Test
void TestFindGroup(){
groupService.deleteAllGroups();
final Group group = groupService.addGroup("ПИбд-21");
final Group findGroup = groupService.findGroup(group.getId());
Assertions.assertEquals(group, findGroup);
}
@Test
void TestFindAllGroup(){
groupService.deleteAllGroups();
final Group group1 = groupService.addGroup("ПИбд-21");
final Group group2 = groupService.addGroup("ПИбд-22");
final List<Group> groups = groupService.findAllGroups();
Assertions.assertEquals(groups.size(), 2);
}
@Test
void TestUpdateGroup(){
groupService.deleteAllGroups();
Group group = groupService.addGroup("ПИбд-21");
group = groupService.updateGroup(group.getId(), "ПИбд-22");
Assertions.assertEquals(group.getName(), "ПИбд-22");
}
@Test
void TestDeleteGroup(){
groupService.deleteAllGroups();
Group group = groupService.addGroup("ПИбд-21");
groupService.deleteGroup(group.getId());
Assertions.assertThrows(EntityNotFoundException.class, () -> {
groupService.findGroup(group.getId());
});
}
@Test
void TestFindStudentsInGroup(){
studentService.deleteAllStudent();
groupService.deleteAllGroups();
Student student1 = studentService.addStudent("Марков Данил Павлович", LocalDate.of(2003,8,19));
Student student2 = studentService.addStudent("Емельянов Артём Сергеевич", LocalDate.of(2003,7,26));
Group group = groupService.addGroup("ПИбд-21");
groupService.addStudentToGroup(group.getId(), student1.getId());
groupService.addStudentToGroup(group.getId(), student2.getId());
final List<Student> students = groupService.findStudentsInGroup(group.getId());
Assertions.assertEquals(students.size(), 2);
}
}

View File

@ -1,13 +1,113 @@
package ru.IP_LabWorks.IP; package ru.IP_LabWorks.IP;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import ru.IP_LabWorks.IP.TypeCalculator.service.TypeService;
@SpringBootTest @SpringBootTest
class IpApplicationTests { class IpApplicationTests {
@Autowired
TypeService Service;
@Test @Test
void contextLoads() { void contextLoads() {
} }
@Test
void testIntPlus() {
final String res = (String) Service.Method1( "100", "10", "int");
Assertions.assertEquals("110", res);
}
@Test
void testIntMinus() {
final String res = (String)Service.Method2( "100", "10", "int");
Assertions.assertEquals("90", res);
}
@Test
void testIntMultiply() {
final String res = (String)Service.Method3( "100", "10", "int");
Assertions.assertEquals("1000", res);
}
@Test
void testIntDivision() {
final String res = (String)Service.Method4( "100", "10", "int");
Assertions.assertEquals("10", res);
}
@Test
void testStringPlus() {
final String res = (String)Service.Method1( "abc", "dfe", "str");
Assertions.assertEquals("abcdfe", res);
}
@Test
void testStringtoUpper() {
final String res = (String)Service.Method2( "abc", "dfe", "str");
Assertions.assertEquals("ABCDFE", res);
}
@Test
void testStringtoLower() {
final String res = (String)Service.Method3( "abc", "dfe", "str");
Assertions.assertEquals("abcdfe", res);
}
@Test
void testStringStrange() {
final String res = (String)Service.Method4( "abc", "dfe", "str");
Assertions.assertEquals("abcDFE", res);
}
@Test
void testDoublePlus() {
final String res = (String)Service.Method1( "1.01", "2.76", "double");
Assertions.assertEquals("3.7699999999999996", res);
}
@Test
void testDoubleMinus() {
final String res = (String)Service.Method2( "1.01", "2.76", "double");
Assertions.assertEquals("-1.7499999999999998", res);
}
@Test
void testDoubleMyltiply() {
final String res = (String)Service.Method3( "1.01", "2.76", "double");
Assertions.assertEquals("2.7876", res);
}
@Test
void testDoubleDivision() {
final String res = (String)Service.Method4( "1.01", "2.76", "double");
Assertions.assertEquals("0.36594202898550726", res);
}
@Test
void testArrayPlus(){
final String res = (String)Service.Method1( "1,2,3", "1,2,3", "array");
Assertions.assertEquals("[2, 4, 6]", res);
}
@Test
void testArrayMinus(){
final String res = (String)Service.Method2( "1,2,3", "1,2,3", "array");
Assertions.assertEquals("[0, 0, 0]", res);
}
@Test
void testArrayMult(){
final String res = (String)Service.Method3( "1,2,3", "1,2,3", "array");
Assertions.assertEquals("[1, 4, 9]", res);
}
@Test
void testArrayDiv(){
final String res = (String)Service.Method4( "1,2,3", "1,2,3", "array");
Assertions.assertEquals("[1, 1, 1]", res);
}
} }

View File

@ -0,0 +1,79 @@
package ru.IP_LabWorks.IP;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.IP_LabWorks.IP.University.Model.Group;
import ru.IP_LabWorks.IP.University.Model.Student;
import ru.IP_LabWorks.IP.University.Service.GroupService;
import ru.IP_LabWorks.IP.University.Service.StudentService;
import java.time.LocalDate;
import java.util.List;
@SpringBootTest
public class StudentServiceTests {
@Autowired
private StudentService studentService;
@Autowired
private GroupService groupService;
@Test
void TestAddStudent(){
studentService.deleteAllStudent();
final Student student = studentService.addStudent("Марков Данил Павлович", LocalDate.of(2003,8,19));
Assertions.assertNotNull(student.getId());
}
@Test
void TestFindStudent(){
studentService.deleteAllStudent();
final Student student = studentService.addStudent("Марков Данил Павлович", LocalDate.of(2003,8,19));
final Student findStudent = studentService.findStudent(student.getId());
Assertions.assertEquals(student, findStudent);
}
@Test
void TestFindAllStudent(){
studentService.deleteAllStudent();
final Student student1 = studentService.addStudent("Марков Данил Павлович", LocalDate.of(2003,8,19));
final Student student2 = studentService.addStudent("Емельянов Артём Сергеевич", LocalDate.of(2003,7,26));
final List<Student> students = studentService.findAllStudents();
Assertions.assertEquals(students.size(), 2);
}
@Test
void TestUpdateStudent(){
studentService.deleteAllStudent();
Student student = studentService.addStudent("Марков Данил Павлович", LocalDate.of(2003,8,19));
student = studentService.updateStudent(student.getId(), "Емельянов Артём Сергеевич", LocalDate.of(2003,7,26));
Assertions.assertEquals(student.getName(), "Емельянов Артём Сергеевич");
}
@Test
void TestDeleteStudent(){
studentService.deleteAllStudent();
Student student = studentService.addStudent("Марков Данил Павлович", LocalDate.of(2003,8,19));
studentService.deleteStudent(student.getId());
Assertions.assertThrows(EntityNotFoundException.class, () -> {
studentService.findStudent(student.getId());
});
}
@Test
void TestAddStudentToGroup(){
studentService.deleteAllStudent();
groupService.deleteAllGroups();
Student student = studentService.addStudent("Марков Данил Павлович", LocalDate.of(2003,8,19));
Group group = groupService.addGroup("ПИбд-21");
studentService.AddStudentToGroup(student.getId(), group.getId());
Assertions.assertEquals(group,studentService.findStudent(student.getId()).getGroup());
}
}

View File

@ -0,0 +1,107 @@
package ru.IP_LabWorks.IP;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.IP_LabWorks.IP.University.Model.Group;
import ru.IP_LabWorks.IP.University.Model.Subject;
import ru.IP_LabWorks.IP.University.Service.GroupService;
import ru.IP_LabWorks.IP.University.Service.SubjectService;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@SpringBootTest
public class SubjectServiceTests {
@Autowired
private SubjectService subjectService;
@Autowired
private GroupService groupService;
@Test
void TestAddSubject(){
subjectService.deleteAllSubjects();
final Subject subject = subjectService.addSubject("Философия");
Assertions.assertNotNull(subject.getId());
}
@Test
void TestFindSubject(){
subjectService.deleteAllSubjects();
final Subject subject = subjectService.addSubject("Философия");
final Subject findSubject = subjectService.findSubject(subject.getId());
assertEquals(subject, findSubject);
}
@Test
void TestFindAllSubject(){
subjectService.deleteAllSubjects();
final Subject subject1 = subjectService.addSubject("Философия");
final Subject subject2 = subjectService.addSubject("Математика");
final List<Subject> subjects = subjectService.findAllSubjects();
assertEquals(subjects.size(), 2);
}
@Test
void TestUpdateSubject(){
subjectService.deleteAllSubjects();
Subject subject = subjectService.addSubject("Философия");
subject = subjectService.updateSubject(subject.getId(), "Математика");
assertEquals(subject.getName(), "Математика");
}
@Test
void TestDeleteSubject(){
subjectService.deleteAllSubjects();
Subject subject = subjectService.addSubject("Математика");
subjectService.deleteSubject(subject.getId());
Assertions.assertThrows(EntityNotFoundException.class, () -> {
subjectService.findSubject(subject.getId());
});
}
@Test
void testAddAndFindGroupsInSubject() {
subjectService.deleteAllSubjects();
groupService.deleteAllGroups();
Subject subject = subjectService.addSubject("Math");
Group group1 = groupService.addGroup("PIBD-21");
Group group2 = groupService.addGroup("PIBD-22");
subjectService.addGroupToSubject(subject.getId(), group1.getId());
subjectService.addGroupToSubject(subject.getId(), group2.getId());
List<Group> groups = subjectService.findGroupsBySubject(subject.getId());
System.out.println(groups);
assertEquals(2, groups.size());
}
@Test
void testRemoveGroupFromSubject() {
subjectService.deleteAllSubjects();
groupService.deleteAllGroups();
Subject subject = subjectService.addSubject("Math");
Group group1 = groupService.addGroup("PIBD-21");
Group group2 = groupService.addGroup("PIBD-22");
subjectService.addGroupToSubject(subject.getId(), group1.getId());
subjectService.addGroupToSubject(subject.getId(), group2.getId());
List<Group> groupsBeforeRemove = subjectService.findGroupsBySubject(subject.getId());
assertEquals(2, groupsBeforeRemove.size());
subjectService.removeGroupFromSubject(subject.getId(), group1.getId());
List<Group> groupsAfterRemove = subjectService.findGroupsBySubject(subject.getId());
assertEquals(1, groupsAfterRemove.size());
assertTrue(groupsAfterRemove.contains(group2));
}
}