Compare commits

...

21 Commits
main ... Lab_5

Author SHA1 Message Date
a7276a4528 Загрузил(а) файлы в 'Отчеты' 2023-06-15 18:58:21 +04:00
dfb2200a63 Загрузил(а) файлы в 'Отчеты' 2023-06-15 18:25:46 +04:00
464a2848d9 Загрузил(а) файлы в 'Отчеты' 2023-06-15 17:59:13 +04:00
e86e45d2a8 Загрузил(а) файлы в 'Отчеты' 2023-06-15 17:28:35 +04:00
870b50c9be Загрузил(а) файлы в 'Отчеты' 2023-06-15 17:11:38 +04:00
acb61a9a8e lab 5 complete 2023-05-02 13:49:49 +04:00
ec634ba472 Lab 4 - доп.задание 2023-05-01 22:29:41 +04:00
f9c5202f6b Lab 4 - доп.задание 2023-04-17 22:41:54 +04:00
f024215f82 Lab 4 2023-04-17 14:54:26 +04:00
2105cff6f9 Lab 4 2023-04-17 14:30:42 +04:00
9730c77ed5 Lab 4 2023-04-16 01:33:20 +04:00
eb03fcc404 Lab 4 2023-04-03 13:22:51 +04:00
2683ba9907 Lab 3 2023-04-02 17:59:58 +04:00
92e9b29a1e Lab 3 2023-04-02 17:10:24 +04:00
d90389cfbe Lab 3 2023-03-19 22:43:59 +04:00
70ec81dc5c Lab2 2023-03-06 14:51:29 +04:00
eab61da355 Lab2 2023-03-04 12:57:40 +04:00
6dfb0655bb Lab1 2023-02-19 17:07:43 +04:00
f0fec374ff Lab1 2023-02-06 16:52:22 +04:00
a6d16481da Lab1 2023-02-06 16:42:57 +04:00
815967146e Controller(calc) 2023-02-06 14:41:17 +04:00
78 changed files with 34860 additions and 19 deletions

View File

@ -1,10 +1,10 @@
plugins {
id 'java'
id 'org.springframework.boot' version '2.7.8'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
id 'org.springframework.boot' version '3.0.2'
id 'io.spring.dependency-management' version '1.1.0'
}
group = 'ru.ulstu.is'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
@ -14,6 +14,21 @@ repositories {
dependencies {
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'
}

31166
front/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

48
front/package.json Normal file
View File

@ -0,0 +1,48 @@
{
"name": "pages_react",
"version": "0.1.0",
"private": true,
"dependencies": {
"@fortawesome/fontawesome-free": "^6.2.1",
"axios": "^1.1.3",
"bootstrap": "^5.2.3",
"react": "^18.2.0",
"react-bootstrap": "^2.7.2",
"react-dom": "^18.2.0",
"react-router-dom": "^6.6.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"devDependencies": {
"@types/react": "^18.0.24",
"@types/react-dom": "^18.0.8",
"@vitejs/plugin-react": "^2.2.0",
"json-server": "^0.17.1",
"npm-run-all": "^4.1.5",
"vite": "^3.2.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

14
front/public/index.html Normal file
View File

@ -0,0 +1,14 @@
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="/node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/node_modules/@fortawesome/fontawesome-free/css/all.min.css">
<title>Сеть автошкол</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

47
front/src/App.js Normal file
View File

@ -0,0 +1,47 @@
import React from "react";
import { useRoutes, Outlet, BrowserRouter } from 'react-router-dom';
import Students from './components/Students.jsx';
import Header from "./components/commons/Header.jsx"
import 'bootstrap/dist/css/bootstrap.min.css';
import DrivingSchools from './components/DrivingSchools.jsx';
import Categories from './components/Categories.jsx';
import OneDrivingSchool from './components/OneDrivingSchool.jsx';
import CountStudInCategory from './components/CountStudInCategory.jsx';
function Router(props) {
return useRoutes(props.rootRoute);
}
function App() {
const routes = [
{ index: true, element: <DrivingSchools /> },
{ path: '/', element: <DrivingSchools />, label: 'Сеть Автошкол' },
{ path: '/drivingSchools', element: <DrivingSchools />, label: 'Автошколы' },
{ path: '/students', element: <Students />, label: 'Студенты' },
{ path: '/categories', element: <Categories />, label: 'Категории' },
{ path: '/studcategory', element: <CountStudInCategory />, label: 'Количество студентов в категории' },
{ path: '/drivingSchool/:id', element: <OneDrivingSchool />},
];
const links = routes.filter(route => route.hasOwnProperty('label'));
const rootRoute = [
{ path: '/', element: render(links), children: routes }
];
function render(links) {
return (
<div className="App">
<Header links={links} />
<div className="w-100">
<Outlet />
</div>
</div>
);
}
return (
<BrowserRouter>
<Router rootRoute={ rootRoute } />
</BrowserRouter>
);
}
export default App;

View File

@ -0,0 +1,56 @@
import Button from 'react-bootstrap/Button';
import Table from "./commons/Table.jsx";
import { useState} from 'react';
import ModalForm from './commons/ModalForm.jsx';
// это абстрактный компонент для всех справочников
export default function Catalog(props) {
const [show, setShow] = useState(false);
const [modalTitle, setModalTitle] = useState("");
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
function handleAdd() {
setModalTitle("Добавление");
props.onBtnAdd();
handleShow();
}
function handleChoose(itemId) {
setModalTitle("Выбрать");
props.onChoose(itemId);
handleShow();
}
function handleEdit(itemId) {
setModalTitle("Редактирование");
props.onEdit(itemId);
handleShow();
}
function handleRemove(item) {
props.onDelete(item);
}
function changeData(event) {
props.onFormChanged(event);
}
return <>
<div>{props.name}</div>
<Button variant="success" onClick={handleAdd}>Добавить</Button>
<Table
headers={props.headers}
items={props.items}
onChoose={handleChoose}
onEdit={handleEdit}
onDelete={handleRemove}
/>
<ModalForm
show={show}
onClose={handleClose}
modalTitle={modalTitle}
// onSubmit={submitForm}
onChange={changeData}
form={props.form}
/></>
}

View File

@ -0,0 +1,12 @@
import TableForGroup from "./commons/TableForGroup.jsx";
// это абстрактный компонент для всех справочников
export default function CatalogForGroup(props) {
return <>
<div>{props.name}</div>
<TableForGroup
headers={props.headers}
items={props.items}
/></>
}

View File

@ -0,0 +1,49 @@
import Button from 'react-bootstrap/Button';
import TableSC from "./commons/TableSC.jsx";
import { useState} from 'react';
import ModalForm from './commons/ModalForm.jsx';
// это абстрактный компонент для всех справочников
export default function CatalogSC(props) {
const [show, setShow] = useState(false);
const [modalTitle, setModalTitle] = useState("");
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
function handleAdd() {
setModalTitle("Добавление");
props.onBtnAdd();
handleShow();
}
function handleEdit(itemId) {
setModalTitle("Редактирование");
props.onEdit(itemId);
handleShow();
}
function handleRemove(item) {
props.onDelete(item);
}
function changeData(event) {
props.onFormChanged(event);
}
return <>
<div>{props.name}</div>
<Button variant="success" onClick={handleAdd}>Добавить</Button>
<TableSC
headers={props.headers}
items={props.items}
onEdit={handleEdit}
onDelete={handleRemove}
/>
<ModalForm
show={show}
onClose={handleClose}
modalTitle={modalTitle}
// onSubmit={submitForm}
onChange={changeData}
form={props.form}
/></>
}

View File

@ -0,0 +1,108 @@
import Category from "../models/Category";
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import { useState, useEffect } from 'react';
import DataService from '../services/DataService';
import CatalogSC from "./CatalogSC.jsx";
export default function Categories(props) {
const headers = [
{name: 'name', label: "Название"},
];
const nameCatalog = "Категории";
const url = '/category';
const requestParams = '?name=nameData';
const [items, setItems] = useState([]);
const [data, setData] = useState(new Category());
const [isEditing, setEditing] = useState(false);
useEffect(() => {
loadItems();
}, []);
function loadItems() {
DataService.readAll(url, (data) => new Category(data))
.then(data => setItems(data));
}
function handleAdd() {
DataService.create(url +requestParams
.replace("nameData", data.name))
.then(() => loadItems());
}
function handleEdit(editedId) {
DataService.read(url + "/" + editedId, (e) => new Category(e))
.then(data => {
setData(new Category(data));
});
setEditing(true);
}
function handleEditIsDone() {
DataService.update(url + "/" + data.id + requestParams
.replace("nameData", data.name)).then(() => loadItems());
}
function handleDelete(item) {
if (window.confirm('Удалить выбранный элемент?')) {
const promises = [];
promises.push(DataService.delete(url + "/" + item));
Promise.all(promises).then(() => {
loadItems();
});
}
}
// при каждом изменении поля формы происходит вызов этого метода, обновляя данные объекта
function handleFormChange(event) {
setData({ ...data, [event.target.name]: event.target.value });
}
// определяет действия формы по нажатию Отправить
function submitForm() {
if (!isEditing) {
// если добавление элемента
handleAdd();
} else {
// если редактирование элемента;
handleEditIsDone();
setEditing(false);
}
}
// вызывается при закрытии модального окна или по нажатию кнопки Добавить и очищает данные объекта
function reset() {
setData(new Category());
setEditing(false);
}
// для каждого типа сущности своя форма,
// которая передается дальше в абстрактный компонент Catalog в качестве props.form
const form = <Form onSubmit={submitForm}>
<Form.Group className="mb-3" controlId="name">
<Form.Label>Название</Form.Label>
<Form.Control name="name" value={data.name} type="input" placeholder="Enter text" onChange={handleFormChange} required/>
</Form.Group>
<Button variant="primary" type="submit">
Отправить
</Button>
</Form>
return <div className="container-lg pt-5 min-vh-100">
<CatalogSC name={nameCatalog}
headers={headers}
items={items}
onAdd={handleAdd}
onEdit={handleEdit}
onDelete={handleDelete}
onClose={reset}
onBtnAdd={reset}
form={form}>
</CatalogSC>
</div>
}

View File

@ -0,0 +1,37 @@
import { useState, useEffect } from 'react';
import DataService from '../services/DataService';
import CatalogForGroup from "./CatalogForGroup.jsx";
import { useNavigate } from "react-router-dom";
import GroupedStudAndCategoryDto from "../models/GroupedStudAndCategoryDto";
export default function CountStudInCategory(props) {
const headers = [
{name: 'categoryName', label: "Название"},
{name: 'studentsCount', label: "Студенты"},
];
const nameCatalog = "Количество студентов в категории";
const url = '/categoryStudent/groupbycategory';
const [items, setItems] = useState([]);
useEffect(() => {
loadItems();
}, []);
function loadItems() {
DataService.readAll(url, (data) => new GroupedStudAndCategoryDto(data))
.then(data => setItems(data));
}
return <div className="container-lg pt-5 min-vh-100">
<CatalogForGroup name={nameCatalog}
headers={headers}
items={items}>
</CatalogForGroup>
</div>
}

View File

@ -0,0 +1,154 @@
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import { useState, useEffect } from 'react';
import DataService from '../services/DataService';
import Catalog from "./Catalog.jsx";
import DrivingSchool from "../models/DrivingSchool";
import ModalForm from './commons/ModalForm';
import { useNavigate } from "react-router-dom";
export default function DrivingSchools(props) {
const headers = [
{name: 'name', label: "Название"},
{name: 'countStudents', label: "Студенты"},
];
const nameCatalog = "Автошколы";
const url = '/drivingSchool';
const requestParams = '?name=nameData';
const [items, setItems] = useState([]);
const [data, setData] = useState(new DrivingSchool());
const [isEditing, setEditing] = useState(false);
useEffect(() => {
loadItems();
}, []);
const [selectedId, setSelectedId] = useState(null);
function loadItems() {
DataService.readAll(url, (data) => new DrivingSchool(data))
.then(data => setItems(data));
}
function handleAdd() {
DataService.create(url +requestParams
.replace("nameData", data.name))
.then(() => loadItems());
}
function handleEdit(editedId) {
DataService.read(url + "/" + editedId, (e) => new DrivingSchool(e))
.then(data => {
setData(new DrivingSchool(data));
});
setEditing(true);
}
function handleEditIsDone() {
DataService.update(url + "/" + data.id + requestParams
.replace("nameData", data.name))
.then(() => loadItems());
}
function handleDelete(item) {
if (window.confirm('Удалить выбранный элемент?')) {
const promises = [];
promises.push(DataService.delete(url + "/" + item));
Promise.all(promises).then(() => {
loadItems();
});
}
}
// при каждом изменении поля формы происходит вызов этого метода, обновляя данные объекта
function handleFormChange(event) {
setData({ ...data, [event.target.name]: event.target.value });
}
// определяет действия формы по нажатию Отправить
function submitForm() {
if (!isEditing) {
// если добавление элемента
handleAdd();
} else {
// если редактирование элемента;
handleEditIsDone();
setEditing(false);
}
}
// вызывается при закрытии модального окна или по нажатию кнопки Добавить и очищает данные объекта
function reset() {
setData(new DrivingSchool());
setEditing(false);
}
// для каждого типа сущности своя форма,
// которая передается дальше в абстрактный компонент Catalog в качестве props.form
const form = <Form onSubmit={submitForm}>
<Form.Group className="mb-3" controlId="name">
<Form.Label>Название</Form.Label>
<Form.Control name="name" value={data.name} type="input" placeholder="Enter text" onChange={handleFormChange} required/>
</Form.Group>
<Button variant="primary" type="submit">
Отправить
</Button>
</Form>;
const [showModalForm, setShowChoosing] = useState(false);
const formChooseDrivingSchool = <Form onSubmit={redirectToDrivingSchool}>
<Form.Group className="mb-3" controlId="name">
<Form.Label>Автошкола</Form.Label>
<Form.Select name="name_select" type="input" onChange={(e) => {setChosenDrivingSchool(e.target.value)}} required>
<option selected disabled>Выберите автошколу</option>
{
items.map((drivingSchool) => <option key={`drivingSchool_${drivingSchool.id}`} value={`${drivingSchool.id}`}>{`${drivingSchool.name}`}</option>)
}
</Form.Select>
</Form.Group>
<Button variant="primary" type="submit">
Перейти
</Button>
</Form>;
function showModalFormChoosing() {
setShowChoosing(true);
}
function unshowModalFormChoosing() {
setShowChoosing(false);
}
const [chosenDrivingSchool, setChosenDrivingSchool] = useState(0);
const navigate = useNavigate();
function redirectToDrivingSchool(item) {
setSelectedId(item);
navigate(`/drivingSchool/${item}`);
}
return <div className="container-lg pt-5 min-vh-100">
<ModalForm show={showModalForm} onClose={unshowModalFormChoosing} modalTitle={"Выбор автошколы"} form={formChooseDrivingSchool}></ModalForm>
<Catalog name={nameCatalog}
headers={headers}
items={items}
onAdd={handleAdd}
onEdit={handleEdit}
onDelete={handleDelete}
onChoose={redirectToDrivingSchool}
onClose={reset}
onBtnAdd={reset}
form={form}>
</Catalog>
</div>
}

View File

@ -0,0 +1,256 @@
import DrivingSchool from "../models/DrivingSchool";
import { useState, useEffect } from 'react';
import { Link, useParams } from "react-router-dom";
import DataService from '../services/DataService';
import Student from '../models/Student';
import Category from '../models/Category';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import ModalForm from './commons/ModalForm';
import styles from "./OneDrivingSchool.module.css";
export default function OneDrivingSchool(props) {
const { id } = useParams();
const url = '/drivingSchool/id';
const urlDrivingSchoolStud = '/drivingSchool/id/students';
const urlStud = '/student/free';
const urlCat = '/category';
const urlHire = '/drivingSchool/id/hire';
const urlDismiss = '/drivingSchool/id/dismiss';
const urlAddCat = '/student/id/addCat';
const urlDelCat = '/student/id/delCat';
const requestParamsCategory = '?category=catId';
const requestParamsHire = '?studentId=studId';
const [drivingSchool, setDrivingSchool] = useState(new DrivingSchool());
const [itemsStudFree, setItemsStudFree] = useState([]);
const [itemsStudDrivingSchool, setItemsStudDrivingSchool] = useState([]);
const [itemsCat, setItemsCat] = useState([]);
const headersStud = [
{name: 'surname', label: "Фамилия"},
{name: 'name', label: "Имя"},
{name: 'categoriesString', label: 'Категории'},
{name: 'phoneNumber', label: "Номер телефона"}
];
useEffect(() => {
loadDrivingSchool();
}, []);
function loadDrivingSchool() {
DataService.read(url.replace("id", id), (data) => new DrivingSchool(data)).then((data) => setDrivingSchool(new DrivingSchool(data)));
}
function loadItemsStudents() {
DataService.readAll(urlStud, (data) => new Student(data))
.then(data => setItemsStudFree(data));
}
function loadItemsCategories() {
DataService.readAll(urlCat, (data) => new Category(data))
.then(data => setItemsCat(data));
}
function loadItemsStudentsDrivingSchool() {
DataService.readAll(urlDrivingSchoolStud.replace("id", drivingSchool.id), (data) => new Student(data))
.then(data => setItemsStudDrivingSchool(data));
}
// логика для найма или увольнения
const [isShowHire, setShowHire] = useState(false);
function showModalFormHire() {
loadItemsStudents();
setShowHire(true);
}
function unshowModalFormHire() {
setShowHire(false);
}
const [isShowDismiss, setShowDismiss] = useState(false);
function showModalFormDismiss(e) {
loadItemsStudentsDrivingSchool();
setShowDismiss(true);
}
function unshowModalFormDismiss() {
setShowDismiss(false);
}
const [student, setStudent] = useState(new Student());
function studentChosenFree(e) {
setStudent(itemsStudFree.filter((stud) => stud.id == e.target.value)[0]);
}
function studentChosenBusy(e) {
setStudent(Array.from(drivingSchool.students).filter((stud) => stud.id == e.target.value)[0]);
}
function formHireSubmit() {
DataService.update(urlHire.replace("id",drivingSchool.id) + requestParamsHire
.replace("studId", student.id))
.then(() => loadDrivingSchool());
setStudent(new Student());
}
function formDismissSubmit() {
DataService.update(urlDismiss.replace("id",drivingSchool.id) + requestParamsHire
.replace("studId", student.id))
.then(() => loadDrivingSchool());
setStudent(new Student());
}
const [isShowChooseCategory, setShowChooseCategory] = useState(false);
function showModalFormChooseCategory() {
loadItemsCategories();
loadItemsStudentsDrivingSchool();
setShowChooseCategory(true);
}
function unshowModalFormChooseCategory() {
setShowChooseCategory(false);
setCategoryStud([]);
}
const [categoriesChosen, setCategoryStud] = useState([]);
function checkBoxChanged(e) {
// если чекбокс был выбран, то добавляем в массив категорию
if (e.target.checked)
{
categoriesChosen.push(e.target.value);
} // если чекбокс был убран, то исключаем его значение из массива
else
{
let i = categoriesChosen.indexOf(e.target.value);
if(i >= 0) {
categoriesChosen.splice(i,1);
}
}
}
function formChooseCategoriesSubmit() {
for (let i = 0; i < categoriesChosen.length; i++) {
DataService.update(urlAddCat.replace("id",student.id) + requestParamsCategory
.replace("catId", categoriesChosen[i]))
.then(() => loadDrivingSchool());
}
let categoriesStud = student.categories;
for (let i = 0; i < categoriesStud.length; i++) {
if (categoriesChosen.indexOf(''+categoriesStud[i].id) == -1) {
// удаление категории
DataService.update(urlDelCat.replace("id",student.id) + requestParamsCategory
.replace("catId", categoriesStud[i].id))
.then(() => loadDrivingSchool());
}
}
}
const formHire = <Form onSubmit={formHireSubmit}>
<Form.Group className="mb-3" controlId="student">
<Form.Label>Студент</Form.Label>
<Form.Select name="student_select" type="input" onChange={studentChosenFree} required>
<option selected disabled>Выберите студента</option>
{
itemsStudFree.map((e) => <option key={`stud_${e.id}`} value={`${e.id}`}>{`${e.surname} ${e.name}`}</option>)
}
</Form.Select>
</Form.Group>
<Button variant="primary" type="submit">
Отправить
</Button>
</Form>;
const formDismiss = <Form onSubmit={formDismissSubmit}>
<Form.Group className="mb-3" controlId="student">
<Form.Label>Студент</Form.Label>
<Form.Select name="student_select" type="input" onChange={studentChosenBusy} required>
<option selected disabled>Выберите студента</option>
{
itemsStudDrivingSchool.map((e) => <option key={`stud_${e.id}`} value={`${e.id}`}>{`${e.surname} ${e.name}`}</option>)
}
</Form.Select>
</Form.Group>
<Button variant="primary" type="submit">
Отправить
</Button>
</Form>;
const formCheckBoxesCategory = <Form onSubmit={formChooseCategoriesSubmit}>
<Form.Group className="mb-3" controlId="student">
<Form.Label>Студент</Form.Label>
<Form.Select name="student_select" type="input" onChange={studentChosenBusy} required>
<option selected disabled>Выберите студента</option>
{
itemsStudDrivingSchool.map((e) => <option key={`stud_${e.id}`} value={`${e.id}`}>{`${e.surname} ${e.name}`}</option>)
}
</Form.Select>
</Form.Group>
<Form.Group className="mb-3" controlId="category">
<Form.Label>Категории</Form.Label>
<div className={`${styles.prokrutka}`}>
{
itemsCat.map((p) => <div style={{width: `150 px`}}>
<input type="checkbox" key={`${p.id}`} value={`${p.id}`} onChange={checkBoxChanged}/>
{/* {!studentHasCategory(p) && <input type="checkbox" key={`${p.id}`} value={`${p.id}`} onChange={checkBoxChanged}/>}
{studentHasCategory(p) && <input type="checkbox" key={`${p.id}`} value={`${p.id}`} checked onChange={checkBoxChanged}/>} */}
{`${p.name}`}
</div>)
}
</div>
</Form.Group>
<Button variant="primary" type="submit">
Отправить
</Button>
</Form>
if (!drivingSchool) {
return <div><h1>Автошкола не найдена</h1>
<Link to='/drivingSchools'>
<Button variant="info">Назад</Button>
</Link>
</div>
}
return <div className="container-lg pt-5 min-vh-100">
<Link to='/drivingSchools'>
<Button variant="info">Назад</Button>
</Link>
<h1>Название: {drivingSchool.name}</h1>
<h2>Количество студентов: {drivingSchool.countStudents}</h2>
<Button name="Зачисление" onClick={showModalFormHire} variant="btn btn-outline-success">Зачислить студента</Button>
<Button name='Отчисление' onClick={showModalFormDismiss} variant="btn btn-outline-danger">Отчислить студента</Button>
<Button name='Выбор категории' onClick={showModalFormChooseCategory} variant="btn btn-outline-primary">Выбор категории</Button>
<div >
<table className={`table table-hover`}>
<thead>
<tr>
{
headersStud.map((header) => <th key={header.name}>{header.label}</th>)
}
</tr>
</thead>
<tbody>
{
Array.from(drivingSchool.students).map((item, index) => <tr key={item.id}>
{
headersStud.map((header) => <td key={`${header.name}_${item.id}`}>{item[header.name]}</td>)
}
</tr>)
}
</tbody>
</table>
</div>
<ModalForm show={isShowHire} onClose={unshowModalFormHire} modalTitle={"Зачисление"} form={formHire}></ModalForm>
<ModalForm show={isShowDismiss} onClose={unshowModalFormDismiss} modalTitle={"Отчисление"} form={formDismiss}></ModalForm>
<ModalForm show={isShowChooseCategory} onClose={unshowModalFormChooseCategory} modalTitle={"Управление категориями"} form={formCheckBoxesCategory}></ModalForm>
</div>
}

View File

@ -0,0 +1,7 @@
.prokrutka {
background: #fff; /* цвет фона, белый */
border: 1px solid #C1C1C1; /* размер и цвет границы блока */
overflow: auto;
width:200px;
height:100px;
}

View File

@ -0,0 +1,72 @@
import DataService from '../services/DataService';
import Student from '../models/Student';
import Category from '../models/Category';
import { useState, useEffect } from 'react';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import DrivingSchool from '../models/DrivingSchool';
import { Link} from "react-router-dom";
export default function ReportStudentCategory(props) {
const headersEmp = [
{name: 'surname', label: "Фамилия"},
{name: 'name', label: "Имя"},
{name: 'categoriesString', label: 'Категории'},
{name: 'phoneNumber', label: "Номер телефона"},
];
const url = "/student/category?cat=id"
const urlCat = '/category';
const [itemsCat, setItemsCat] = useState([]);
const [itemsStud, setItemsStud] = useState([]);
useEffect(() => {
loadItemsCtegories();
});
function loadItemsCtegories() {
DataService.readAll(urlCat, (data) => new Category(data))
.then(data => setItemsCat(data));
}
function loadItemsStudents(selectedCategory) {
DataService.readAll(url.replace("id", selectedCategory), (data) => new Student(data))
.then(data => setItemsStud(data));
}
return <div className="container-lg pt-5 min-vh-100">
<h1>Отчет</h1>
<Form.Select onChange={(e) => {loadItemsStudents(e.target.value)}} aria-label="Default select example">
<option selected disabled>Выберите категорию</option>
{
itemsCat.map((e) => <option key={`stud_${e.id}`} value={`${e.id}`}>{`${e.name}`}</option>)
}
</Form.Select>
<div >
<table className={`table table-hover`}>
<thead>
<tr>
{
headersStud.map((header) => <th key={header.name}>{header.label}</th>)
}
<th key='company'>Автошкола</th>
</tr>
</thead>
<tbody>
{
itemsStud.map((item) => <tr key={item.id}>
{
headersStud.map((header) => <td key={`${header.name}_${item.id}`}>{item[header.name]}</td>)
}
<td key={`ds_${item.id}`}><Link to={`/drivingSchool/${item['drivingSchool'].id}`}>{item['drivingSchool'].name}</Link></td>
</tr>)
}
</tbody>
</table>
</div>
</div>
}

View File

@ -0,0 +1,115 @@
import Student from "../models/Student";
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import { useState, useEffect } from 'react';
import DataService from '../services/DataService';
import CatalogSC from "./CatalogSC.jsx";
export default function Students(props) {
const headers = [
{name: 'surname', label: "Фамилия"},
{name: 'name', label: "Имя"},
{name: 'phoneNumber', label: "Номер телефона"},
{name: 'categoriesString', label: 'Категории'}
];
const nameCatalog = "Студенты";
const [items, setItems] = useState([]);
const url = '/student';
const requestParams = '?name=nameData&surname=surnameData&phoneNumber=phoneNameData';
const [data, setData] = useState(new Student());
const [isEditing, setEditing] = useState(false);
useEffect(() => {
loadItems();
}, []);
function loadItems() {
DataService.readAll(url, (data) => new Student(data))
.then(data => setItems(data));
}
function handleAdd() {
DataService.create(url +requestParams
.replace("nameData", data.name)
.replace("surnameData", data.surname)
.replace("phoneNameData", data.phoneNumber))
.then(() => loadItems());
}
function handleEdit(editedId) {
DataService.read(url + "/" + editedId, (e) => new Student(e))
.then(data => {
setData(new Student(data));
});
setEditing(true);
}
function handleEditIsDone() {
DataService.update(url + "/" + data.id + requestParams
.replace("nameData", data.name)
.replace("surnameData", data.surname)
.replace("phoneNameData", data.phoneNumber)).then(() => loadItems());
}
function handleDelete(item) {
if (window.confirm('Удалить выбранный элемент?')) {
const promises = [];
promises.push(DataService.delete(url + "/" + item));
Promise.all(promises).then(() => {
loadItems();
});
}
}
// при каждом изменении поля формы происходит вызов этого метода, обновляя данные объекта
function handleFormChange(event) {
setData({ ...data, [event.target.name]: event.target.value });
}
// определяет действия формы по нажатию Отправить
function submitForm() {
if (!isEditing) {
// если добавление элемента
handleAdd();
} else {
// если редактирование элемента;
handleEditIsDone();
setEditing(false);
}
}
// вызывается при закрытии модального окна или по нажатию кнопки Добавить и очищает данные объекта
function reset() {
setData(new Student());
setEditing(false);
}
// для каждого типа сущности своя форма,
// которая передается дальше в абстрактный компонент Catalog в качестве props.form
const form = <Form onSubmit={submitForm}>
<Form.Group className="mb-3" controlId="name">
<Form.Label>Фамилия</Form.Label>
<Form.Control name="surname" value={data.surname} type="input" placeholder="Enter text" onChange={handleFormChange} required/>
<Form.Label>Имя</Form.Label>
<Form.Control name="name" value={data.name} type="input" placeholder="Enter text" onChange={handleFormChange} required/>
<Form.Label>Номер телефона</Form.Label>
<Form.Control name="phoneNumber" value={data.phoneNumber} type="input" placeholder="Enter text" onChange={handleFormChange} required/>
</Form.Group>
<Button variant="primary" type="submit">
Отправить
</Button>
</Form>
return <div className="container-lg pt-5 min-vh-100">
<CatalogSC name={nameCatalog}
headers={headers}
items={items}
onAdd={handleAdd}
onEdit={handleEdit}
onDelete={handleDelete}
onClose={reset}
onBtnAdd={reset}
form={form}>
</CatalogSC>
</div>
}

View File

@ -0,0 +1,25 @@
import { NavLink } from 'react-router-dom';
import Container from 'react-bootstrap/Container';
import Nav from 'react-bootstrap/Nav';
import Navbar from 'react-bootstrap/Navbar';
export default function Header(props) {
return (
<Navbar collapseOnSelect expand="lg" bg="primary" variant="primary">
<Container className='lg justify-content-center'>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="me-auto">
{
props.links.map(route =>
<NavLink key={route.path} className="nav-link" to={route.path}>
<div>{route.label}</div>
</NavLink>
)
}
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
);
}

View File

@ -0,0 +1,22 @@
import Button from 'react-bootstrap/Button';
export default function ItemTable(props) {
function edit() {
props.onEdit(props.item.id);
}
function remove() {
props.onDelete(props.item.id);
}
function chooseDrivingSchool() {
props.onChoose(props.item.id);
}
return <tr key={props.item.id}>
{
props.headers.map((header) => <td key={`${header.name}_${props.item.id}`}>{props.item[header.name]}</td>)
}
{props.isOnlyView || <td key={`controls_${props.item.id}`}>
<Button variant="btn btn-outline-warning" onClick={chooseDrivingSchool}>Выбрать</Button>
<Button variant="btn btn-outline-primary" onClick={edit}>Редактировать</Button>
<Button variant="btn btn-outline-danger" onClick={remove}>Удалить</Button></td>}
</tr>
}

View File

@ -0,0 +1,8 @@
export default function ItemTableForGroup(props) {
return <tr key={props.item.id}>
{
props.headers.map((header) => <td key={`${header.name}_${props.item.id}`}>{props.item[header.name]}</td>)
}
</tr>
}

View File

@ -0,0 +1,18 @@
import Button from 'react-bootstrap/Button';
export default function ItemTableSC(props) {
function edit() {
props.onEdit(props.item.id);
}
function remove() {
props.onDelete(props.item.id);
}
return <tr key={props.item.id}>
{
props.headers.map((header) => <td key={`${header.name}_${props.item.id}`}>{props.item[header.name]}</td>)
}
{props.isOnlyView || <td key={`controls_${props.item.id}`}>
<Button variant="btn btn-outline-primary" onClick={edit}>Редактировать</Button>
<Button variant="btn btn-outline-danger" onClick={remove}>Удалить</Button></td>}
</tr>
}

View File

@ -0,0 +1,14 @@
import Form from 'react-bootstrap/Form';
import Modal from 'react-bootstrap/Modal';
import Button from 'react-bootstrap/Button';
import { React} from 'react';
export default function ModalForm(props) {
return <Modal show={props.show} onHide={props.onClose}>
<Modal.Header closeButton>
<Modal.Title>{props.modalTitle}</Modal.Title>
</Modal.Header>
<Modal.Body>
{props.form}
</Modal.Body>
</Modal>
}

View File

@ -0,0 +1,39 @@
import ItemTable from './ItemTable';
export default function Table(props) {
function edit(itemId) {
props.onEdit(itemId)
}
function remove(itemId) {
props.onDelete(itemId);
}
function chooseDrivingSchool(itemId) {
props.onChoose(itemId);
}
return <div >
<table className={`table table-hover`}>
<thead>
<tr>
{
props.headers.map((header) => <th key={header.name}>{header.label}</th>)
}
{props.isOnlyView || <th key='controls'>Элементы управления</th>}
</tr>
</thead>
<tbody>
{
props.items.map((item, index) =>
<ItemTable
key={index}
headers={props.headers}
item={item}
onDelete={remove}
onEdit={edit}
onChoose={chooseDrivingSchool}
isOnlyView={props.isOnlyView}/>)
}
</tbody>
</table>
</div>
}

View File

@ -0,0 +1,26 @@
import ItemTableForGroup from './ItemTableForGroup';
export default function TableForGroup(props) {
return <div >
<table className={`table table-hover`}>
<thead>
<tr>
{
props.headers.map((header) => <th key={header.name}>{header.label}</th>)
}
</tr>
</thead>
<tbody>
{
props.items.map((item, index) =>
<ItemTableForGroup
key={index}
headers={props.headers}
item={item}
isOnlyView={props.isOnlyView}/>)
}
</tbody>
</table>
</div>
}

View File

@ -0,0 +1,35 @@
import ItemTableSC from './ItemTableSC';
export default function TableSC(props) {
function edit(itemId) {
props.onEdit(itemId)
}
function remove(itemId) {
props.onDelete(itemId);
}
return <div >
<table className={`table table-hover`}>
<thead>
<tr>
{
props.headers.map((header) => <th key={header.name}>{header.label}</th>)
}
{props.isOnlyView || <th key='controls'>Элементы управления</th>}
</tr>
</thead>
<tbody>
{
props.items.map((item, index) =>
<ItemTableSC
key={index}
headers={props.headers}
item={item}
onDelete={remove}
onEdit={edit}
isOnlyView={props.isOnlyView}/>)
}
</tbody>
</table>
</div>
}

8
front/src/index.js Normal file
View File

@ -0,0 +1,8 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);

View File

@ -0,0 +1,6 @@
export default class Category {
constructor(data) {
this.id = data?.id;
this.name = data?.name || '';
}
}

View File

@ -0,0 +1,13 @@
import Student from "./Student";
export default class DrivingSchool {
constructor(data) {
this.id = data?.id;
this.name = data?.name || '';
this.students = data?.students.map((e) => new Student(e)) || '';
this.countStudents = '';
if (this.students !== '') {
this.countStudents = this.students.length;
}
}
}

View File

@ -0,0 +1,7 @@
export default class GroupedStudAndCategoryDto {
constructor(data) {
this.Id = data?.Id;
this.categoryName = data?.categoryName;
this.studentsCount = data?.studentsCount;
}
}

View File

@ -0,0 +1,25 @@
import Category from "./Category";
export default class Student {
constructor(data) {
this.id = data?.id;
this.surname = data?.surname || '';
this.name = data?.name || '';
this.phoneNumber = data?.phoneNumber || '';
this.categories = data?.categories.map((p) => new Category(p)) || '';
this.categoriesString = '';
if (this.categories !== '') {
this.categories.forEach((p) => {this.categoriesString += p.name + " "});
}
this.drivingSchool = data?.drivingSchool || '';
}
}
Student.prototype.equals = function (obj){
if(typeof obj != typeof this)
return false;
if (this.id === obj.id) {
return true;
}
return false;
}

View File

@ -0,0 +1,42 @@
import axios from 'axios';
function toJSON(data) {
const jsonObj = {};
const fields = Object.getOwnPropertyNames(data);
for (const field of fields) {
if (data[field] === undefined) {
continue;
}
jsonObj[field] = data[field];
}
return jsonObj;
}
export default class DataService {
static dataUrlPrefix = 'http://localhost:8080/api';
static async readAll(url, transformer) {
const response = await axios.get(this.dataUrlPrefix + url);
return response.data.map(item => transformer(item));
}
static async read(url, transformer) {
const response = await axios.get(this.dataUrlPrefix + url);
return transformer(response.data);
}
static async create(url, data) {
const response = await axios.post(this.dataUrlPrefix + url);
return true;
}
static async update(url, data) {
const response = await axios.put(this.dataUrlPrefix + url);
return true;
}
static async delete(url) {
const response = await axios.delete(this.dataUrlPrefix + url);
return response.data.id;
}
}

View File

@ -5,9 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CbappApplication {
public static void main(String[] args) {
SpringApplication.run(CbappApplication.class, args);
}
}

View File

@ -0,0 +1,15 @@
package ru.ulstu.is.cbapp;
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 {
public static final String REST_API = "/api";
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}

View File

@ -0,0 +1,47 @@
package ru.ulstu.is.cbapp.controller;
import jakarta.validation.Valid;
import ru.ulstu.is.cbapp.WebConfiguration;
import ru.ulstu.is.cbapp.dto.CategoryDto;
import ru.ulstu.is.cbapp.service.CategoryService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/category")
public class CategoryController {
private final CategoryService categoryService;
public CategoryController(CategoryService categoryService) {
this.categoryService = categoryService;
}
@GetMapping("/{id}")
public CategoryDto getDrivingSchool(@PathVariable long id) {
return new CategoryDto(categoryService.findCategory(id));
}
@GetMapping
public List<CategoryDto> getAllDrivingSchools() {
return categoryService.findAllCategories().stream()
.map(CategoryDto::new)
.toList();
}
@PostMapping
public CategoryDto create(@RequestBody @Valid CategoryDto categoryDto) {
return new CategoryDto(categoryService.addCategory(categoryDto.getName()));
}
@PutMapping("/{id}")
public CategoryDto update(@PathVariable Long id,
@RequestBody @Valid CategoryDto categoryDto) {
return new CategoryDto(categoryService.updateCategory(id, categoryDto.getName()));
}
@DeleteMapping("/{id}")
public CategoryDto delete(@PathVariable Long id) {
return new CategoryDto(categoryService.deleteCategory(id));
}
}

View File

@ -0,0 +1,27 @@
package ru.ulstu.is.cbapp.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.is.cbapp.WebConfiguration;
import ru.ulstu.is.cbapp.dto.GroupedStudAndCategoryDto;
import ru.ulstu.is.cbapp.service.CategoryService;
import ru.ulstu.is.cbapp.service.CategoryStudentService;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API+"/categoryStudent")
public class CategoryStudentController {
private CategoryStudentService categoryStudentService;
public CategoryStudentController(CategoryStudentService categoryStudentService) {
this.categoryStudentService = categoryStudentService;
}
@GetMapping("/groupbycategory")
public List<GroupedStudAndCategoryDto> getGroupedStudAndCategory(){
return categoryStudentService.getGroupedStudAndCategory();
}
}

View File

@ -0,0 +1,70 @@
package ru.ulstu.is.cbapp.controller;
import jakarta.validation.Valid;
import ru.ulstu.is.cbapp.WebConfiguration;
import ru.ulstu.is.cbapp.dto.DrivingSchoolDto;
import ru.ulstu.is.cbapp.dto.StudentDto;
import ru.ulstu.is.cbapp.models.Student;
import ru.ulstu.is.cbapp.service.DrivingSchoolService;
import ru.ulstu.is.cbapp.service.StudentService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/drivingSchool")
public class DrivingSchoolController {
private final DrivingSchoolService drivingSchoolService;
private final StudentService studentService;
public DrivingSchoolController(DrivingSchoolService drivingSchoolService, StudentService studentService) {
this.drivingSchoolService = drivingSchoolService;
this.studentService = studentService;
}
@GetMapping("/{id}")
public DrivingSchoolDto getDrivingSchool(@PathVariable long id) {
return new DrivingSchoolDto(drivingSchoolService.findDrivingSchool(id));
}
@GetMapping("/{id}/students")
public List<StudentDto> getDrivingSchoolStudents(@PathVariable long id) {
return drivingSchoolService.findDrivingSchool(id).getStudents().stream().map(StudentDto::new).toList();
}
@GetMapping
public List<DrivingSchoolDto> getAllDrivingSchools() {
return drivingSchoolService.findAllDrivingSchools().stream()
.map(DrivingSchoolDto::new)
.toList();
}
@PostMapping
public DrivingSchoolDto create(@RequestBody @Valid DrivingSchoolDto drivingSchoolDto) {
return new DrivingSchoolDto(drivingSchoolService.addDrivingSchool(drivingSchoolDto.getName()));
}
@PutMapping("/{id}")
public DrivingSchoolDto update(@PathVariable Long id,
@RequestBody @Valid DrivingSchoolDto drivingSchoolDto) {
return new DrivingSchoolDto(drivingSchoolService.updateDrivingSchool(id, drivingSchoolDto.getName()));
}
@DeleteMapping("/{id}")
public DrivingSchoolDto delete(@PathVariable Long id) {
return new DrivingSchoolDto(drivingSchoolService.deleteDrivingSchool(id));
}
@PutMapping("/{id}/hire")
public StudentDto hire(@PathVariable Long id, @RequestParam Long studentId) {
Student e = studentService.findStudent(studentId);
return new StudentDto(drivingSchoolService.addNewStudent(id, e));
}
@PutMapping("/{id}/dismiss")
public void dismiss(@PathVariable Long id, @RequestParam Long studentId) {
Student e = studentService.findStudent(studentId);
drivingSchoolService.deleteStudent(id, e);
}
}

View File

@ -0,0 +1,90 @@
package ru.ulstu.is.cbapp.controller;
import jakarta.validation.Valid;
import ru.ulstu.is.cbapp.WebConfiguration;
import ru.ulstu.is.cbapp.dto.StudentDto;
import ru.ulstu.is.cbapp.models.Category;
import ru.ulstu.is.cbapp.service.StudentService;
import ru.ulstu.is.cbapp.service.CategoryService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/student")
public class StudentController {
private final StudentService studentService;
private final CategoryService categoryService;
public StudentController(StudentService studentService, CategoryService categoryService) {
this.studentService = studentService;
this.categoryService = categoryService;
}
@GetMapping("/{id}")
public StudentDto getStudent(@PathVariable long id) {
return new StudentDto(studentService.findStudent(id));
}
@GetMapping
public List<StudentDto> getAllStudents() {
return studentService.findAllStudents().stream()
.map(StudentDto::new)
.toList();
}
@PostMapping
public StudentDto createStudent(@RequestBody @Valid StudentDto studentDto) {
return new StudentDto(studentService.addStudent(
studentDto.getSurname(),
studentDto.getName(),
studentDto.getPhoneNumber()));
}
@PutMapping("/{id}")
public StudentDto updateStudent(@PathVariable Long id,
@RequestBody @Valid StudentDto studentDto) {
return new StudentDto(studentService.updateStudent(id, studentDto.getSurname(), studentDto.getName(), studentDto.getPhoneNumber()));
}
@DeleteMapping("/{id}")
public StudentDto deleteStudent(@PathVariable Long id) {
return new StudentDto(studentService.deleteStudent(id));
}
@PutMapping("/{id}/addCat")
public StudentDto addCategory(@PathVariable Long id,
@RequestParam("category") Long category) {
Category p = categoryService.findCategory(category);
if (p == null)
return null;
return new StudentDto(studentService.addCategory(id, p));
}
@PutMapping("/{id}/delCat")
public StudentDto delCategory(@PathVariable Long id,
@RequestParam("category") Long category) {
Category p = categoryService.findCategory(category);
if (p == null)
return null;
return new StudentDto(studentService.deleteCategory(id, p));
}
@GetMapping("/free")
public List<StudentDto> getAllFreeStudents() {
return studentService.findAllFreeStudents().stream()
.map(StudentDto::new)
.toList();
}
@GetMapping("/category")
public List<StudentDto> getStudentsByCategory(@RequestParam Long cat) {
Category p = categoryService.findCategory(cat);
if (p == null) {
return null;
}
return studentService.getStudentsByCategory(p).stream()
.map(StudentDto::new)
.toList();
}
}

View File

@ -0,0 +1,13 @@
package ru.ulstu.is.cbapp.dao;
import org.springframework.data.jpa.repository.Query;
import ru.ulstu.is.cbapp.dto.GroupedStudAndCategoryDto;
import ru.ulstu.is.cbapp.models.Category;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface CategoryRepository extends JpaRepository<Category, Long> {
Optional<Category> findById(Long id);
}

View File

@ -0,0 +1,10 @@
package ru.ulstu.is.cbapp.dao;
import ru.ulstu.is.cbapp.models.DrivingSchool;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface DrivingSchoolRepository extends JpaRepository<DrivingSchool, Long> {
Optional<DrivingSchool> findById(Long id);
}

View File

@ -0,0 +1,19 @@
package ru.ulstu.is.cbapp.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import ru.ulstu.is.cbapp.dto.GroupedStudAndCategoryDto;
import ru.ulstu.is.cbapp.models.StudentCategories;
import java.util.List;
import java.util.Optional;
public interface StudentCategoriesRepository extends JpaRepository<StudentCategories, Long> {
Optional<StudentCategories> findById(Long id);
@Query("SELECT new ru.ulstu.is.cbapp.dto.GroupedStudAndCategoryDto(cs.category.name,COUNT(cs.student.id))"+
"FROM StudentCategories cs "+
"group by cs.category.name")
List<GroupedStudAndCategoryDto> getGroupedStudAndCategory();
}

View File

@ -0,0 +1,13 @@
package ru.ulstu.is.cbapp.dao;
import ru.ulstu.is.cbapp.models.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface StudentRepository extends JpaRepository<Student, Long> {
Optional<Student> findById(Long id);
List<Student> findByCategories_Id(Long p_id);
List<Student> findByDrivingSchoolIsNull();
}

View File

@ -0,0 +1,28 @@
package ru.ulstu.is.cbapp.dto;
import ru.ulstu.is.cbapp.models.Category;
public class CategoryDto {
private Long Id;
private String name;
public CategoryDto(Category category) {
Id = category.getId();
this.name = category.getName();
}
public CategoryDto() {
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return Id;
}
public String getName() {
return name;
}
}

View File

@ -0,0 +1,35 @@
package ru.ulstu.is.cbapp.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import ru.ulstu.is.cbapp.models.DrivingSchool;
import java.util.List;
public class DrivingSchoolDto {
private Long Id;
private String name;
private List<StudentDto> students;
public DrivingSchoolDto(DrivingSchool drivingSchool) {
Id = drivingSchool.getId();
this.name = drivingSchool.getName();
this.students = drivingSchool.getStudents().stream().map(StudentDto::new).toList();
}
public DrivingSchoolDto() {
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() {
return Id;
}
public String getName() {
return name;
}
public List<StudentDto> getStudents() {
return students;
}
}

View File

@ -0,0 +1,21 @@
package ru.ulstu.is.cbapp.dto;
import ru.ulstu.is.cbapp.models.DrivingSchool;
public class DrivingSchoolWithoutStudDto {
private final Long Id;
private final String name;
public DrivingSchoolWithoutStudDto(DrivingSchool drivingSchool) {
this.Id = drivingSchool.getId();
this.name = drivingSchool.getName();
}
public Long getId() {
return Id;
}
public String getName() {
return name;
}
}

View File

@ -0,0 +1,27 @@
package ru.ulstu.is.cbapp.dto;
public class GroupedStudAndCategoryDto {
private String categoryName;
private Long StudentsCount;
public GroupedStudAndCategoryDto(String categoryName, Long StudentsCount){
this.categoryName=categoryName;
this.StudentsCount=StudentsCount;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryId(String categoryName) {
this.categoryName = categoryName;
}
public Long getStudentsCount() {
return StudentsCount;
}
public void setStudentsCount(Long studentsCount) {
StudentsCount = studentsCount;
}
}

View File

@ -0,0 +1,63 @@
package ru.ulstu.is.cbapp.dto;
import ru.ulstu.is.cbapp.models.Student;
import java.util.List;
public class StudentDto {
private Long Id;
private String name;
private String phoneNumber;
private String surname;
private List<CategoryDto> categories;
private DrivingSchoolWithoutStudDto drivingSchool;
public StudentDto(Student student) {
Id = student.getId();
this.name = student.getName();
this.phoneNumber = student.getPhoneNumber();
this.surname = student.getSurname();
this.categories = student.getCategories().stream().map(CategoryDto::new).toList();
this.drivingSchool = student.getDrivingSchool() != null ? new DrivingSchoolWithoutStudDto(student.getDrivingSchool()) : null;
}
public StudentDto() {
}
public Long getId() {
return Id;
}
public void setName(String name) {
this.name = name;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getSurname() {
return surname;
}
public List<CategoryDto> getCategories() {
return categories;
}
public DrivingSchoolWithoutStudDto getDrivingSchool() {
return drivingSchool;
}
}

View File

@ -0,0 +1,71 @@
package ru.ulstu.is.cbapp.models;
import jakarta.persistence.*;
import java.util.*;
@Entity
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long Id;
private String name;
//mappedBy - атрибут, указывающий, что классом-владельцем отношений является другой класс
@ManyToMany(mappedBy = "categories", cascade = {CascadeType.REMOVE}, fetch = FetchType.EAGER)
private Set<Student> students = new HashSet<>();
public Category() {
}
public Category(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return Id;
}
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
public void addNewStudent(Student e) {
students.add(e);
if (!e.getCategories().contains(this)) {
e.addNewCategory(this);
}
}
public void deleteStudent(Student e) {
students.remove(e);
if (e.getCategories().contains(this)) {
e.removeCategory(this);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Category student = (Category) o;
return Objects.equals(Id, student.Id);
}
@Override
public int hashCode() {
return Objects.hash(Id);
}
}

View File

@ -0,0 +1,79 @@
package ru.ulstu.is.cbapp.models;
import jakarta.persistence.*;
import java.util.*;
@Entity
public class DrivingSchool {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long Id;
@Column(unique = true)
private String name;
@OneToMany(mappedBy = "drivingSchool", cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private Set<Student> students = new HashSet<>();
public DrivingSchool(String name, Set<Student> students) {
this.name = name;
this.students = students;
}
public DrivingSchool(String name) {
this.name = name;
}
public DrivingSchool() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addNewStudent(Student student) {
students.add(student);
student.setDrivingSchool(this);
}
public void deleteStudent(Student student) {
students.remove(student);
student.deleteDrivingSchool();
}
public Long getId() {
return Id;
}
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DrivingSchool drivingSchool = (DrivingSchool) o;
return Objects.equals(Id, drivingSchool.Id);
}
@Override
public int hashCode() {
return Objects.hash(Id);
}
@Override
public String toString() {
return "DrivingSchool{" +
"Id=" + Id +
", name='" + name + '\'' +
", students=" + students +
'}';
}
}

View File

@ -0,0 +1,113 @@
package ru.ulstu.is.cbapp.models;
import jakarta.persistence.*;
import java.util.*;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String phoneNumber;
private String name;
private String surname;
@ManyToOne(fetch = FetchType.EAGER)
private DrivingSchool drivingSchool;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
//@JoinTable(name="CATEGORY_STUDENT",
//joinColumns = {@JoinColumn(name="student_id")},
//inverseJoinColumns = {@JoinColumn(name="category_id")})
private Set<Category> categories = new HashSet<>();
public Student(String surname, String name, String phoneNumber) {
this.phoneNumber = phoneNumber;
this.name = name;
this.surname = surname;
}
public Student() {
}
public Long getId() {
return id;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public List<Category> getCategories() {
return categories.stream().toList();
}
public DrivingSchool getDrivingSchool() {
return drivingSchool;
}
public void setDrivingSchool(DrivingSchool drivingSchool) {
this.drivingSchool = drivingSchool;
if (!drivingSchool.getStudents().contains(this)) {
drivingSchool.addNewStudent(this);
}
}
public void deleteDrivingSchool() {
if (drivingSchool.getStudents().contains(this)) {
drivingSchool.deleteStudent(this);
}
this.drivingSchool = null;
this.categories.clear();
}
public void addNewCategory(Category p) {
categories.add(p);
if (!p.getStudents().contains(this)) {
p.addNewStudent(this);
}
}
public void removeCategory(Category p) {
categories.remove(p);
if (p.getStudents().contains(this)) {
p.deleteStudent(this);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student e = (Student) o;
return Objects.equals(id, e.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}

View File

@ -0,0 +1,36 @@
package ru.ulstu.is.cbapp.models;
import jakarta.persistence.*;
@Entity
@Table(name="student_categories")
@IdClass(StudentCategoriesId.class)
public class StudentCategories {
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
@Id
@ManyToOne
@JoinColumn(name="students_id")
private Student student;
@Id
@ManyToOne
@JoinColumn(name="categories_id")
private Category category;
}

View File

@ -0,0 +1,24 @@
package ru.ulstu.is.cbapp.models;
import java.io.Serializable;
public class StudentCategoriesId implements Serializable {
private Long student;
private Long category;
public Long getStudent() {
return student;
}
public void setStudent(Long student) {
this.student = student;
}
public Long getCategory() {
return category;
}
public void setCategory(Long category) {
this.category = category;
}
}

View File

@ -0,0 +1,64 @@
package ru.ulstu.is.cbapp.mvc;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.cbapp.dto.CategoryDto;
import ru.ulstu.is.cbapp.service.CategoryService;
@Controller
@RequestMapping("/category")
public class CategoryMvcController {
private final CategoryService categoryService;
public CategoryMvcController(CategoryService categoryService) {
this.categoryService = categoryService;
}
@GetMapping
public String getCategories(Model model) {
model.addAttribute("categories",
categoryService.findAllCategories().stream()
.map(CategoryDto::new)
.toList());
return "category";
}
@GetMapping(value = {"/edit/", "/edit/{id}"})
public String editCategory(@PathVariable(required = false) Long id,
Model model) {
if (id == null || id <= 0) {
model.addAttribute("categoryDto", new CategoryDto());
} else {
model.addAttribute("categoryId", id);
model.addAttribute("categoryDto", new CategoryDto(categoryService.findCategory(id)));
}
return "category-edit";
}
@PostMapping(value = {"/", "/{id}"})
public String saveCategory(@PathVariable(required = false) Long id,
@ModelAttribute @Valid CategoryDto categoryDto,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "category-edit";
}
if (id == null || id <= 0) {
categoryService.addCategory(categoryDto.getName());
} else {
categoryService.updateCategory(id, categoryDto.getName());
}
return "redirect:/category";
}
@PostMapping("/delete/{id}")
public String deleteStudent(@PathVariable Long id) {
categoryService.deleteCategory(id);
return "redirect:/category";
}
}

View File

@ -0,0 +1,27 @@
package ru.ulstu.is.cbapp.mvc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.ulstu.is.cbapp.dto.GroupedStudAndCategoryDto;
import ru.ulstu.is.cbapp.service.CategoryStudentService;
import org.springframework.ui.Model;
import java.util.List;
@Controller
@RequestMapping("/categoryStudent")
public class CategoryStudentMvcController {
private final CategoryStudentService categoryStudentService;
public CategoryStudentMvcController(CategoryStudentService categoryStudentService) {
this.categoryStudentService = categoryStudentService;
}
@GetMapping("/groupbycategory")
public String getGroupedStudAndCategory(Model model) {
List<GroupedStudAndCategoryDto> GroupedStudAndCategoryDtos = categoryStudentService.getGroupedStudAndCategory();
model.addAttribute("GroupedStudAndCategoryDtos", GroupedStudAndCategoryDtos);
return "groupbycategory";
}
}

View File

@ -0,0 +1,85 @@
package ru.ulstu.is.cbapp.mvc;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.cbapp.dto.CategoryDto;
import ru.ulstu.is.cbapp.dto.DrivingSchoolDto;
import ru.ulstu.is.cbapp.dto.StudentDto;
import ru.ulstu.is.cbapp.service.CategoryService;
import ru.ulstu.is.cbapp.service.DrivingSchoolService;
import ru.ulstu.is.cbapp.service.StudentService;
@Controller
@RequestMapping("/drivingSchool")
public class DrivingSchoolMvcController {
private final DrivingSchoolService drivingSchoolService;
private final StudentService studentService;
private final CategoryService categoryService;
public DrivingSchoolMvcController(DrivingSchoolService drivingSchoolService, StudentService studentService, CategoryService categoryService) {
this.drivingSchoolService = drivingSchoolService;
this.studentService = studentService;
this.categoryService = categoryService;
}
@GetMapping
public String getDrivingSchools(Model model) {
model.addAttribute("drivingSchools",
drivingSchoolService.findAllDrivingSchools().stream()
.map(DrivingSchoolDto::new)
.toList());
return "drivingSchool";
}
@GetMapping("/one/{id}")
public String getDrivingSchool(@PathVariable(required = false) Long id, Model model) {
model.addAttribute("drivingSchool",
new DrivingSchoolDto(drivingSchoolService.findDrivingSchool(id)));
model.addAttribute("freeStudents", studentService.findAllFreeStudents().stream().map(StudentDto::new).toList());
model.addAttribute("categories", categoryService.findAllCategories().stream().map(CategoryDto::new).toList());
return "drivingSchool-one";
}
@PostMapping(value = "/redirect")
public String redirectToDrivingSchoolPage(@RequestParam("drivingSchoolId") Long drivingSchoolId) {
return "redirect:/drivingSchool/one/" + drivingSchoolId;
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editDrivingSchool(@PathVariable(required = false) Long id,
Model model) {
if (id == null || id <= 0) {
model.addAttribute("drivingSchoolDto", new DrivingSchoolDto());
} else {
model.addAttribute("drivingSchoolId", id);
model.addAttribute("drivingSchoolDto", new DrivingSchoolDto(drivingSchoolService.findDrivingSchool(id)));
}
return "drivingSchool-edit";
}
@PostMapping(value = {"/", "/{id}"})
public String saveDrivingSchool(@PathVariable(required = false) Long id,
@ModelAttribute @Valid DrivingSchoolDto drivingSchoolDto,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "drivingSchool-edit";
}
if (id == null || id <= 0) {
drivingSchoolService.addDrivingSchool(drivingSchoolDto.getName());
} else {
drivingSchoolService.updateDrivingSchool(id, drivingSchoolDto.getName());
}
return "redirect:/drivingSchool";
}
@PostMapping("/delete/{id}")
public String deleteDrivingSchool(@PathVariable Long id) {
drivingSchoolService.deleteDrivingSchool(id);
return "redirect:/drivingSchool";
}
}

View File

@ -0,0 +1,16 @@
package ru.ulstu.is.cbapp.mvc;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
@Controller
public class HomeController {
@ModelAttribute("requestURI")
public String requestURI(final HttpServletRequest request) {
return request.getRequestURI();
}
}

View File

@ -0,0 +1,69 @@
package ru.ulstu.is.cbapp.mvc;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.cbapp.dto.CategoryDto;
import ru.ulstu.is.cbapp.dto.StudentDto;
import ru.ulstu.is.cbapp.service.CategoryService;
import ru.ulstu.is.cbapp.service.StudentService;
@Controller
@RequestMapping("/student")
public class StudentMvcController {
private final StudentService studentService;
private final CategoryService categoryService;
public StudentMvcController(StudentService studentService, CategoryService categoryService) {
this.studentService = studentService;
this.categoryService = categoryService;
}
@GetMapping
public String getStudents(Model model) {
model.addAttribute("students",
studentService.findAllStudents().stream()
.map(StudentDto::new)
.toList());
return "student";
}
@GetMapping(value = {"/edit/", "/edit/{id}"})
public String editDrivingSchool(@PathVariable(required = false) Long id,
Model model) {
if (id == null || id <= 0) {
model.addAttribute("studentDto", new StudentDto());
} else {
model.addAttribute("studentId", id);
model.addAttribute("studentDto", new StudentDto(studentService.findStudent(id)));
}
return "student-edit";
}
@PostMapping(value = {"/", "/{id}"})
public String saveDrivingSchool(@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.getSurname(), studentDto.getName(), studentDto.getPhoneNumber());
} else {
studentService.updateStudent(id, studentDto.getSurname(), studentDto.getName(), studentDto.getPhoneNumber());
}
return "redirect:/student";
}
@PostMapping("/delete/{id}")
public String deleteStudent(@PathVariable Long id) {
studentService.deleteStudent(id);
return "redirect:/student";
}
}

View File

@ -0,0 +1,69 @@
package ru.ulstu.is.cbapp.service;
import ru.ulstu.is.cbapp.dao.CategoryRepository;
import ru.ulstu.is.cbapp.dto.GroupedStudAndCategoryDto;
import ru.ulstu.is.cbapp.models.Category;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
@Service
public class CategoryService {
private CategoryRepository categoryRepository;
public CategoryService(CategoryRepository categoryRepository) {
this.categoryRepository = categoryRepository;
}
@Transactional
public Category addCategory(String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Student's data is null or empty");
}
final Category category = new Category(name);
categoryRepository.save(category);
return category;
}
@Transactional
public Category findCategory(Long id) {
final Category category = categoryRepository.findById(id).orElse(null);
if (category == null) {
throw new EntityNotFoundException(String.format("Category with id [%s] is not found", id));
}
return category;
}
@Transactional(readOnly = true)
public List<Category> findAllCategories() {
return categoryRepository.findAll();
}
@Transactional
public Category updateCategory(Long id, String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Student's data is null or empty");
}
final Category currentCategory = findCategory(id);
currentCategory.setName(name);
return categoryRepository.save(currentCategory);
}
@Transactional
public Category deleteCategory(Long id) {
final Category p = findCategory(id);
categoryRepository.delete(p);
return p;
}
@Transactional
public void deleteAllCategories() {
categoryRepository.deleteAll();
}
}

View File

@ -0,0 +1,23 @@
package ru.ulstu.is.cbapp.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.is.cbapp.dao.StudentCategoriesRepository;
import ru.ulstu.is.cbapp.dto.GroupedStudAndCategoryDto;
import java.util.List;
@Service
public class CategoryStudentService {
private StudentCategoriesRepository studentCategoriesRepository;
public CategoryStudentService(StudentCategoriesRepository studentCategoriesRepository) {
this.studentCategoriesRepository = studentCategoriesRepository;
}
@Transactional(readOnly = true)
public List<GroupedStudAndCategoryDto> getGroupedStudAndCategory() {
return studentCategoriesRepository.getGroupedStudAndCategory();
}
}

View File

@ -0,0 +1,84 @@
package ru.ulstu.is.cbapp.service;
import ru.ulstu.is.cbapp.dao.DrivingSchoolRepository;
import ru.ulstu.is.cbapp.models.DrivingSchool;
import ru.ulstu.is.cbapp.models.Student;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
@Service
public class DrivingSchoolService {
private DrivingSchoolRepository drivingSchoolRepository;
private StudentService studentService;
public DrivingSchoolService(DrivingSchoolRepository drivingSchoolRepository, StudentService studentService) {
this.drivingSchoolRepository = drivingSchoolRepository;
this.studentService = studentService;
}
@Transactional
public DrivingSchool addDrivingSchool(String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Student name is null or empty");
}
final DrivingSchool drivingSchool = new DrivingSchool(name);
drivingSchoolRepository.save(drivingSchool);
return drivingSchool;
}
@Transactional(readOnly = true)
public DrivingSchool findDrivingSchool(Long id) {
final DrivingSchool drivingSchool = drivingSchoolRepository.findById(id).orElse(null);
if (drivingSchool == null) {
throw new EntityNotFoundException(String.format("DrivingSchool with id [%s] is not found", id));
}
return drivingSchool;
}
@Transactional(readOnly = true)
public List<DrivingSchool> findAllDrivingSchools() {
return drivingSchoolRepository.findAll();
}
@Transactional
public DrivingSchool updateDrivingSchool(Long id, String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("DrivingSchool name is null or empty");
}
final DrivingSchool currentDrivingSchool = findDrivingSchool(id);
currentDrivingSchool.setName(name);
return drivingSchoolRepository.save(currentDrivingSchool);
}
@Transactional
public DrivingSchool deleteDrivingSchool(Long id) {
final DrivingSchool currentDrivingSchool = findDrivingSchool(id);
drivingSchoolRepository.delete(currentDrivingSchool);
return currentDrivingSchool;
}
@Transactional
public void deleteAllDrivingSchools() {
drivingSchoolRepository.deleteAll();
}
@Transactional
public Student addNewStudent(Long id, Student student) {
DrivingSchool currentDrivingSchool = findDrivingSchool(id);
currentDrivingSchool.addNewStudent(student);
drivingSchoolRepository.save(currentDrivingSchool);
return student;
}
@Transactional
public void deleteStudent(Long id, Student student) {
DrivingSchool currentDrivingSchool = findDrivingSchool(id);
currentDrivingSchool.deleteStudent(student);
}
}

View File

@ -0,0 +1,111 @@
package ru.ulstu.is.cbapp.service;
import ru.ulstu.is.cbapp.dao.StudentRepository;
import ru.ulstu.is.cbapp.models.Category;
import ru.ulstu.is.cbapp.models.DrivingSchool;
import ru.ulstu.is.cbapp.models.Student;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
@Service
public class StudentService {
private StudentRepository studentRepository;
public StudentService(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
@Transactional
public Student addStudent(String surname, String name, String phoneNumber) {
if (!StringUtils.hasText(name) ||!StringUtils.hasText(surname) || !StringUtils.hasText(phoneNumber)) {
throw new IllegalArgumentException("Student's data is null or empty");
}
final Student student = new Student(surname, name, phoneNumber);
studentRepository.save(student);
return student;
}
@Transactional
public Student findStudent(Long id) {
final Student student = studentRepository.findById(id).orElse(null);
if (student == null) {
throw new EntityNotFoundException(String.format("Student with id [%s] is not found", id));
}
return student;
}
@Transactional(readOnly = true)
public List<Student> findAllStudents() {
return studentRepository.findAll();
}
@Transactional(readOnly = true)
public List<Student> findAllFreeStudents() {
return studentRepository.findByDrivingSchoolIsNull();
}
@Transactional
public Student updateStudent(Long id, String surname, String name, String phoneNumber) {
if (!StringUtils.hasText(name) ||!StringUtils.hasText(surname) || !StringUtils.hasText(phoneNumber)) {
throw new IllegalArgumentException("Student's data is null or empty");
}
final Student currentStudent = findStudent(id);
currentStudent.setName(name);
currentStudent.setSurname(surname);
currentStudent.setPhoneNumber(phoneNumber);
return studentRepository.save(currentStudent);
}
@Transactional
public Student deleteStudent(Long id) {
final Student student = findStudent(id);
studentRepository.delete(student);
return student;
}
@Transactional
public void deleteAllStudents() {
studentRepository.deleteAll();
}
@Transactional
public void addDrivingSchool(Long id, DrivingSchool c) {
final Student student = findStudent(id);
student.setDrivingSchool(c);
studentRepository.save(student);
}
@Transactional
public void deleteDrivingSchool(Long id) {
final Student student = findStudent(id);
student.deleteDrivingSchool();
studentRepository.save(student);
}
@Transactional
public Student addCategory(Long id, Category p) {
Student e = findStudent(id);
e.addNewCategory(p);
System.out.println(e.getCategories().size());
return studentRepository.save(e);
}
@Transactional
public Student deleteCategory(Long id, Category p) {
Student e = findStudent(id);
e.removeCategory(p);
return studentRepository.save(e);
}
@Transactional
public List<Student> getStudentsByCategory(Category p) {
List<Student> students = studentRepository.findByCategories_Id(p.getId());
return students;
}
}

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,9 @@
.prokrutka {
background: #fff; /* цвет фона, белый */
border: 1px solid #C1C1C1; /* размер и цвет границы блока */
overflow: auto;
width:230px;
height:100px;
display: flex;
flex-direction: column;
}

View File

@ -0,0 +1,115 @@
<!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>Категории</div>
<div>
<a class="btn btn-success button-fixed"
onsubmit="openModalEdit()" data-bs-target="#categoryEditModal" data-bs-toggle="modal">
<i class="fa-solid fa-plus"></i> Добавить
</a>
</div>
<div>
<table class="table table-hover">
<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="category, iterator: ${categories}">
<th scope="row" th:text="${iterator.index} + 1"/>
<td th:text="${category.id}"/>
<td th:text="${category.name}" style="width: 60%"/>
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<a class="btn btn-info button-fixed button-sm" th:data-category="${category.id}"
data-bs-target="#categoryEditModal" data-bs-toggle="modal"
th:onclick="openModalEdit(this.getAttribute('data-category'))">Изменить</a>
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${category.id}').click()|">
Удалить
</button>
</div>
<form th:action="@{/category/delete/{id}(id=${category.id})}" method="post">
<button th:id="'remove-' + ${category.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
<div class="modal" id="categoryEditModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<form id="form-edit-category">
<input type="hidden" id="categoryId" name="id"/>
<div class="mb-3">
<label for="name" class="form-label">Название</label>
<input type="text" class="form-control" id="name" required="true">
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span th:if="${id == null}">Добавить</span>
<span th:if="${id != null}">Обновить</span>
</button>
<a class="btn btn-secondary button-fixed" data-bs-dismiss="modal">
Назад
</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
<th:block layout:fragment="scripts">
<script th:inline="javascript">
function openModalEdit(id) {
var categories = [[${categories}]];
var category = categories.find(x => x.id + '' === id);
if (category !== 'undefined') {
$('#categoryId').val(id);
$('#name').val(category.name);
}
}
$(document).on('submit', '#form-edit-category', function (e) {
e.preventDefault();
var categoryName = document.getElementById('name');
var idInput = document.getElementById('categoryId');
var urlCategory = 'http://localhost:8080/api/category';
let category = {name: categoryName.value};
var method = 'POST';
if (idInput.value !== '') {
method = 'PUT';
urlCategory = urlCategory + '/' + idInput.value;
}
$.ajax({
url: urlCategory,
method: method,
data: JSON.stringify(category),
contentType: "application/json;"
})
.done(function() {
location.reload();
})
.fail((err) => {
alert(err);
});
});
</script>
</th:block>
</html>

View File

@ -0,0 +1,46 @@
<!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>Автошколы, студенты и категории</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"/>
<script type="text/javascript" src="/webjars/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<div class="lg justify-content-center container">
<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" th:with="activeLink=${requestURI}">
<a class="nav-link" href="/drivingSchool"
th:classappend="${#strings.equals(activeLink, '/')} ? 'active' : ''">Главная страница</a>
<a class="nav-link" href="/student"
th:classappend="${#strings.equals(activeLink, '/student')} ? 'active' : ''">Студенты</a>
<a class="nav-link" href="/drivingSchool"
th:classappend="${#strings.equals(activeLink, '/drivingSchool')} ? 'active' : ''">Автошколы</a>
<a class="nav-link" href="/category"
th:classappend="${#strings.equals(activeLink, '/category')} ? 'active' : ''">Категории</a>
<a class="nav-link" href="/categoryStudent/groupbycategory"
th:classappend="${#strings.equals(activeLink, '/categoryStudent/groupbycategory')} ? 'active' : ''">Количество студентов в категории</a>
</ul>
</div>
</div>
</nav>
<div class="container-lg pt-5 min-vh-100">
<div class="container container-padding" layout:fragment="content">
</div>
</div>
</body>
<th:block layout:fragment="scripts">
</th:block>
</html>

View File

@ -0,0 +1,255 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<body>
<head>
<link th:href="@{/styles/drivingSchool.css}" rel="stylesheet" />
</head>
<div layout:fragment="content">
<h1>Название: <span th:text="${drivingSchool.name}"></span></h1>
<h2>Количество студентов: <span th:text="${#arrays.length(drivingSchool.students.toArray())}"></span></h2>
<div>
<a class="btn btn-success button-fixed"
data-bs-target="#hireModal" data-bs-toggle="modal">
Зачислить студента
</a>
</div>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">ID</th>
<th scope="col">Фамилия</th>
<th scope="col">Имя</th>
<th scope="col">Номер телефона</th>
<th scope="col">Категории</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr th:each="student, iterator: ${drivingSchool.students}">
<th scope="row" th:text="${iterator.index} + 1"/>
<td th:text="${student.id}"/>
<td th:text="${student.surname}" />
<td th:text="${student.name}" />
<td th:text="${student.phoneNumber}" />
<td th:text="${#strings.listJoin(student.categories.![name],',')}"></td>
<th style="width: 20%">
<a class="btn btn-danger button-fixed button-sm" th:data-student="${student.id}"
data-bs-target="#dismissModal" data-bs-toggle="modal"
th:onclick="openModalDismiss(this.getAttribute('data-student'))">Отчислить</a>
<a class="btn btn-info button-fixed button-sm" th:data-student="${student.id}"
data-bs-target="#manageCategoryModal" data-bs-toggle="modal"
th:onclick="openModalManageCategory(this.getAttribute('data-student'))">Категории</a>
</th>
</tr>
</tbody>
</table>
<!-- Modal -->
<div class="modal" id="dismissModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Отчисление</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="form-dismiss">
<div class="mb-3">
<label class="form-label" for="studentSelect">Студент</label>
<select class="form-select" id="studentSelect" name="studentId" required>
<option th:each="student, iterator: ${drivingSchool.students}" th:value="${student.id}"
th:text="${student.surname} + ' ' + ${student.name}">
</option>
</select>
</div>
<button class="btn btn-danger" type="submit">Отчислить</button>
<a class="btn btn-secondary button-fixed" data-bs-dismiss="modal">
Назад
</a>
</form>
</div>
</div>
</div>
</div>
<div class="modal" id="hireModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="hireModalLabel">Зачислить</h5>
<button type="button" class="close" data-bs-dismiss="modal">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<form id="form-hire">
<div class="mb-3">
<label class="form-label" for="studentHireSelect">Студент</label>
<select class="form-select" id="studentHireSelect" name="studentId" required>
<option selected disabled>Выберите студента</option>
<option th:each="student, iterator: ${freeStudents}" th:value="${student.id}"
th:text="${student.surname} + ' ' + ${student.name}">
</option>
</select>
</div>
<button class="btn btn-info" type="submit">Зачислить</button>
<a class="btn btn-secondary button-fixed" data-bs-dismiss="modal">
Назад
</a>
</form>
</div>
</div>
</div>
</div>
<div class="modal" id="manageCategoryModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="manageCategoryModalLabel">Назначение категории</h5>
<button type="button" class="close" data-bs-dismiss="modal">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<form id="form-categories">
<div class="mb-3">
<label class="form-label" for="studentCatSelect">Студент</label>
<select class="form-select" id="studentCatSelect" name="studentId" required>
<option value="0" selected disabled>Выберите студента</option>
<option th:each="student, iterator: ${drivingSchool.students}" th:value="${student.id}"
th:text="${student.surname} + ' ' + ${student.name}">
</option>
</select>
</div>
<div class="mb-3">
<label class="form-label" for="studentSelect">Категории</label>
<div class="prokrutka">
<div style="200px;" th:each="category, iterator: ${categories}">
<input type="checkbox" th:value="${category.id}"
th:text="${category.name}">
</div>
</div>
</div>
<button class="btn btn-info" type="submit">Зачислить</button>
<a class="btn btn-secondary button-fixed" data-bs-dismiss="modal">
Назад
</a>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
<th:block layout:fragment="scripts">
<script th:inline="javascript">
$(document).on('submit', '#form-dismiss', function (e) {
e.preventDefault();
var drivingSchool = [[${drivingSchool}]];
var url = 'http://localhost:8080/api/drivingSchool/id/dismiss?studentId=studId';
url = url.replace("id", drivingSchool.id).replace("studId", $("#studentSelect").val())
alert(url);
$.ajax({
url: url,
method: 'PUT',
contentType: "application/json;"
})
.done(function() {
location.reload();
})
.fail((err) => {
alert(err);
});
});
$(document).on('submit', '#form-hire', function (e) {
e.preventDefault();
var drivingSchool = [[${drivingSchool}]];
var url = 'http://localhost:8080/api/drivingSchool/id/hire?studentId=studId';
url = url.replace("id", drivingSchool.id).replace("studId", $("#studentHireSelect").val())
alert(url);
$.ajax({
url: url,
method: 'PUT',
contentType: "application/json;"
})
.done(function() {
location.reload();
})
.fail((err) => {
alert(err);
});
});
$(document).on('submit', '#form-categories', function (e) {
e.preventDefault();
var drivingSchool = [[${drivingSchool}]];
var studentId = $("#studentCatSelect").val();
var student = drivingSchool.students.find(x => x.id + '' === studentId);
var categories = student.categories.map(x => x.id + '');
var urlAdd = 'http://localhost:8080/api/student/id/addCat?category=catId';
var urlDel = 'http://localhost:8080/api/student/id/delCat?category=catId';
$('input[type=checkbox]').each(function(){
if(categories.indexOf($(this).val()) !== -1 && $(this).is(":checked") === false){
$.ajax({
url: urlDel.replace("id", student.id).replace("catId", $(this).val()),
method: 'PUT',
contentType: "application/json;"
})
.done(function() {
location.reload();
})
.fail((err) => {
alert(err);
});
} else if (categories.indexOf($(this).val()) == -1 && $(this).is(":checked")){
$.ajax({
url: urlAdd.replace("id", student.id).replace("catId", $(this).val()),
method: 'PUT',
contentType: "application/json;"
})
.done(function() {
location.reload();
})
.fail((err) => {
alert(err);
});
}
});
});
$(document).ready(function(){
$('#studentCatSelect').change(function(){
var selectedStudent = $(this).val();
var drivingSchool = [[${drivingSchool}]];
var student = drivingSchool.students.find(x => x.id + '' === selectedStudent);
var categories = student.categories.map(x => x.id + '');
$('input[type=checkbox]').prop('checked', false);
$('input[type=checkbox]').each(function(){
if(categories.indexOf($(this).val()) !== -1){
$(this).prop('checked', true);
}
});
});
});
function openModalDismiss(id) {
$('#studentSelect').val(id);
$( "#studentSelect" ).prop( "disabled", true );
}
function openModalManageCategory(id) {
$('#studentCatSelect').val(id);
$( "#studentCatSelect" ).prop( "disabled", true );
var drivingSchool = [[${drivingSchool}]];
var student = drivingSchool.students.find(x => x.id + '' === id);
var categories = student.categories.map(x => x.id + '');
$('input[type=checkbox]').prop('checked', false);
$('input[type=checkbox]').each(function(){
if(categories.indexOf($(this).val()) !== -1){
$(this).prop('checked', true);
}
});
}
</script>
</th:block>
</html>

View File

@ -0,0 +1,148 @@
<!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>Автошколы</div>
<div>
<a class="btn btn-success button-fixed"
onsubmit="openModalEdit()" data-bs-target="#drivingSchoolEditModal" data-bs-toggle="modal">
<i class="fa-solid fa-plus"></i> Добавить
</a>
<!-- <a class="btn btn-info button-fixed" data-bs-toggle="modal" data-bs-target="#drivingSchoolModal">-->
<!-- Перейти к компании-->
<!-- </a>-->
</div>
<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>
<th scope="col">Элементы управления</th>
</tr>
</thead>
<tbody>
<tr th:each="drivingSchool, iterator: ${drivingSchools}">
<th scope="row" th:text="${iterator.index} + 1"/>
<td th:text="${drivingSchool.id}"/>
<td style="width: 60%"><a th:href="@{/drivingSchool/one/{id}(id=${drivingSchool.id})}" th:text="${drivingSchool.name}"></a></td>
<td th:text="${#arrays.length(drivingSchool.students.toArray())}" style="width: 60%"/>
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<a class="btn btn-info button-fixed button-sm" th:data-drivingSchool="${drivingSchool.id}"
data-bs-target="#drivingSchoolEditModal" data-bs-toggle="modal"
th:onclick="openModalEdit(this.getAttribute('data-drivingSchool'))">Изменить</a>
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${drivingSchool.id}').click()|">
Удалить
</button>
</div>
<form th:action="@{/drivingSchool/delete/{id}(id=${drivingSchool.id})}" method="post">
<button th:id="'remove-' + ${drivingSchool.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Modal -->
<div class="modal" id="drivingSchoolModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Выбор автошколы</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form action="/drivingSchool/redirect" method="post">
<div class="mb-3">
<label class="form-label" for="drivingSchoolSelect">Автошкола</label>
<select class="form-select" id="drivingSchoolSelect" name="drivingSchoolId" required>
<option selected disabled>Выберите автошколу</option>
<option th:each="drivingSchool, iterator: ${drivingSchools}" th:value="${drivingSchool.id}" th:text="${drivingSchool.name}">
</option>
</select>
</div>
<button class="btn btn-primary" type="submit">Перейти</button>
<a class="btn btn-secondary button-fixed" data-bs-dismiss="modal">
Назад
</a>
</form>
</div>
</div>
</div>
</div>
<div class="modal" id="drivingSchoolEditModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<form id="form-edit-drivingSchool">
<input type="hidden" id="drivingSchoolId" name="id"/>
<div class="mb-3">
<label for="name" class="form-label">Название</label>
<input type="text" class="form-control" id="name" required="true">
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span th:if="${id == null}">Добавить</span>
<span th:if="${id != null}">Обновить</span>
</button>
<a class="btn btn-secondary button-fixed" data-bs-dismiss="modal">
Назад
</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
<th:block layout:fragment="scripts">
<script th:inline="javascript">
function openModalEdit(id) {
var drivingSchools = [[${drivingSchools}]];
var drivingSchool = drivingSchools.find(x => x.id + '' === id);
if (drivingSchool !== 'undefined') {
$('#drivingSchoolId').val(id);
$('#name').val(drivingSchool.name);
}
}
$(document).on('submit', '#form-edit-drivingSchool', function (e) {
e.preventDefault();
var drivingSchoolName = document.getElementById('name');
var idInput = document.getElementById('drivingSchoolId');
var urlDrivingSchool = 'http://localhost:8080/api/drivingSchool';
let drivingSchool = {name: drivingSchoolName.value};
var method = 'POST';
if (idInput.value !== '') {
method = 'PUT';
urlDrivingSchool = urlDrivingSchool + '/' + idInput.value;
}
$.ajax({
url: urlDrivingSchool,
method: method,
data: JSON.stringify(drivingSchool),
contentType: "application/json;"
})
.done(function() {
location.reload();
})
.fail((err) => {
alert(err);
});
});
</script>
</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}">
<head>
</head>
<body>
<div layout:fragment="content">
<div><span th:text="${error}"></span></div>
<a href="/">На главную</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">
<h1>Отчет (количество студентов в категории)</h1>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Название категории</th>
<th scope="col">Количество студентов</th>
</tr>
</thead>
<tbody>
<tr th:each="GroupedStudAndCategoryDto : ${GroupedStudAndCategoryDtos}">
<td th:text="${GroupedStudAndCategoryDto.categoryName}"></td>
<td th:text="${GroupedStudAndCategoryDto.studentsCount}"></td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,13 @@
<!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>Вроде работает</div>
<a href="123">Ошибка :(</a>
</div>
</body>
</html>

View File

@ -0,0 +1,133 @@
<!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>Студенты</div>
<div>
<a class="btn btn-success button-fixed"
onsubmit="openModalEdit()" data-bs-target="#studentEditModal" data-bs-toggle="modal">
<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">ID</th>
<th scope="col">Фамилия</th>
<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}">
<th scope="row" th:text="${iterator.index} + 1"/>
<td th:text="${student.id}"/>
<td th:text="${student.surname}" />
<td th:text="${student.name}" />
<td th:text="${student.phoneNumber}" />
<td th:text="${#strings.listJoin(student.categories.![name],',')}"></td>
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<a class="btn btn-info button-fixed button-sm" th:data-student="${student.id}"
data-bs-target="#studentEditModal" data-bs-toggle="modal"
th:onclick="openModalEdit(this.getAttribute('data-student'))">
Изменить
</a>
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${student.id}').click()|">
Удалить
</button>
</div>
<form th:action="@{/student/delete/{id}(id=${student.id})}" method="post">
<button th:id="'remove-' + ${student.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
<div class="modal" id="studentEditModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<form id="form-edit-student">
<input type="hidden" id="studentId" name="id"/>
<div class="mb-3">
<label for="surname" class="form-label">Фамилия</label>
<input type="text" class="form-control" id="surname" required="true">
</div>
<div class="mb-3">
<label for="name" class="form-label">Имя</label>
<input type="text" class="form-control" id="name" required="true">
</div>
<div class="mb-3">
<label for="phoneNumber" class="form-label">Номер телефона</label>
<input type="text" class="form-control" id="phoneNumber" required="true">
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span th:if="${id == null}">Добавить</span>
<span th:if="${id != null}">Обновить</span>
</button>
<a class="btn btn-secondary button-fixed" data-bs-dismiss="modal">
Назад
</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
<th:block layout:fragment="scripts">
<script th:inline="javascript">
function openModalEdit(id) {
var students = [[${students}]];
var student = students.find(x => x.id + '' === id);
if (student !== 'undefined') {
$('#studentId').val(id);
$('#surname').val(student.surname);
$('#name').val(student.name);
$('#phoneNumber').val(student.phoneNumber);
}
}
$(document).on('submit', '#form-edit-student', function (e) {
e.preventDefault();
var idInput = document.getElementById('studentId');
var urlStudent = 'http://localhost:8080/api/student';
let student = {surname: $('#surname').val(),
name: $('#name').val(),
phoneNumber: $('#phoneNumber').val()};
var method = 'POST';
if (idInput.value !== '') {
method = 'PUT';
urlStudent = urlStudent + '/' + idInput.value;
}
$.ajax({
url: urlStudent,
method: method,
data: JSON.stringify(student),
contentType: "application/json;"
})
.done(function() {
location.reload();
})
.fail((err) => {
alert(err);
});
});
</script>
</th:block>
</html>

View File

@ -0,0 +1,55 @@
package ru.ulstu.is.cbapp;
import ru.ulstu.is.cbapp.models.Category;
import ru.ulstu.is.cbapp.models.Student;
import ru.ulstu.is.cbapp.service.StudentService;
import ru.ulstu.is.cbapp.service.CategoryService;
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;
@SpringBootTest
public class CategoryServiceTests {
@Autowired
private CategoryService categoryService;
@Autowired
private StudentService studentService;
@Test
public void testAddStudent() {
studentService.deleteAllStudents();
categoryService.deleteAllCategories();
Category p = categoryService.addCategory("Category");
Student e = studentService.addStudent("1", "2", "33");
studentService.addCategory(e.getId(), p);
Assertions.assertTrue(studentService.findStudent(e.getId()).getCategories().contains(p));
Assertions.assertTrue(categoryService.findCategory(p.getId()).getStudents().contains(e));
studentService.deleteAllStudents();
categoryService.deleteAllCategories();
}
@Test
public void testDeleteStudent() {
studentService.deleteAllStudents();
categoryService.deleteAllCategories();
Category p = categoryService.addCategory("Category");
Student e = studentService.addStudent("1", "2", "33");
studentService.addCategory(e.getId(), p);
studentService.deleteCategory(e.getId(), p);
Assertions.assertFalse(studentService.findStudent(e.getId()).getCategories().contains(p));
Assertions.assertFalse(categoryService.findCategory(p.getId()).getStudents().contains(e));
studentService.deleteAllStudents();
categoryService.deleteAllCategories();
}
}

View File

@ -1,13 +0,0 @@
package ru.ulstu.is.cbapp;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class CbappApplicationTests {
@Test
void contextLoads() {
}
}

View File

@ -0,0 +1,116 @@
package ru.ulstu.is.cbapp;
import ru.ulstu.is.cbapp.models.DrivingSchool;
import ru.ulstu.is.cbapp.models.Student;
import ru.ulstu.is.cbapp.service.DrivingSchoolService;
import ru.ulstu.is.cbapp.service.StudentService;
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;
@SpringBootTest
public class DrivingSchoolServiceTests {
@Autowired
private DrivingSchoolService drivingSchoolService;
@Autowired
private StudentService studentService;
@Test
public void testDeleteAllDrivingSchools() {
drivingSchoolService.deleteAllDrivingSchools();
int n = 3;
for (int i = 0; i < n; i++) {
String name = "DrivingSchool" + i;
drivingSchoolService.addDrivingSchool(name);
}
drivingSchoolService.deleteAllDrivingSchools();
Assertions.assertEquals(drivingSchoolService.findAllDrivingSchools().size(), 0);
}
@Test
public void testDeleteDrivingSchool() {
drivingSchoolService.deleteAllDrivingSchools();
String name = "DrivingSchool1";
DrivingSchool c = drivingSchoolService.addDrivingSchool(name);
drivingSchoolService.deleteDrivingSchool(c.getId());
Assertions.assertThrows(EntityNotFoundException.class, () -> {
drivingSchoolService.findDrivingSchool(c.getId());});
}
@Test
public void testAddDrivingSchool() {
drivingSchoolService.deleteAllDrivingSchools();
String name = "DrivingSchool1";
DrivingSchool c = drivingSchoolService.addDrivingSchool(name);
Assertions.assertNotNull(drivingSchoolService.findDrivingSchool(c.getId()));
drivingSchoolService.deleteAllDrivingSchools();
}
@Test
public void testUpdateDrivingSchool() {
drivingSchoolService.deleteAllDrivingSchools();
String name = "DrivingSchool1";
DrivingSchool c = drivingSchoolService.addDrivingSchool(name);
String name2 = "DrivingSchool2";
drivingSchoolService.updateDrivingSchool(c.getId(), name2);
Assertions.assertNotNull(drivingSchoolService.findDrivingSchool(c.getId()));
drivingSchoolService.deleteAllDrivingSchools();
}
@Test
public void testFindAllDrivingSchools() {
drivingSchoolService.deleteAllDrivingSchools();
int n = 3;
for (int i = 0; i < n; i++) {
String name = "DrivingSchool" + i;
drivingSchoolService.addDrivingSchool(name);
}
Assertions.assertEquals(drivingSchoolService.findAllDrivingSchools().size(), n);
drivingSchoolService.deleteAllDrivingSchools();
}
@Test
public void testAddStudent() {
studentService.deleteAllStudents();
drivingSchoolService.deleteAllDrivingSchools();
final String name = "DrivingSchool";
DrivingSchool c = drivingSchoolService.addDrivingSchool(name);
Student newStudent = studentService.addStudent("cha", "chacha", "111");
drivingSchoolService.addNewStudent(c.getId(), newStudent);
Assertions.assertTrue(drivingSchoolService.findDrivingSchool(c.getId()).getStudents().contains(newStudent));
studentService.deleteAllStudents();
drivingSchoolService.deleteAllDrivingSchools();
}
@Test
public void testDeleteStudent() {
studentService.deleteAllStudents();
drivingSchoolService.deleteAllDrivingSchools();
final String name = "DrivingSchool";
DrivingSchool c = drivingSchoolService.addDrivingSchool(name);
Student newStudent = studentService.addStudent("cha", "chacha", "111");
drivingSchoolService.addNewStudent(c.getId(), newStudent);
Assertions.assertTrue(drivingSchoolService.findDrivingSchool(c.getId()).getStudents().contains(newStudent));
drivingSchoolService.deleteStudent(c.getId(), newStudent);
Assertions.assertFalse(drivingSchoolService.findDrivingSchool(c.getId()).getStudents().contains(newStudent));
studentService.deleteAllStudents();
drivingSchoolService.deleteAllDrivingSchools();
}
}

View File

@ -0,0 +1,123 @@
package ru.ulstu.is.cbapp;
import ru.ulstu.is.cbapp.models.Category;
import ru.ulstu.is.cbapp.models.DrivingSchool;
import ru.ulstu.is.cbapp.models.Student;
import ru.ulstu.is.cbapp.service.DrivingSchoolService;
import ru.ulstu.is.cbapp.service.StudentService;
import ru.ulstu.is.cbapp.service.CategoryService;
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;
@SpringBootTest
public class StudentServiceTests {
@Autowired
private StudentService studentService;
@Autowired
private DrivingSchoolService drivingSchoolService;
@Autowired
private CategoryService categoryService;
@Test
public void testAddStudent() {
studentService.deleteAllStudents();
studentService.addStudent("name", "surname", "111");
Assertions.assertEquals(1, studentService.findAllStudents().size());
studentService.deleteAllStudents();
}
@Test
public void testUpdateStudent() {
studentService.deleteAllStudents();
final String newName = "name";
Student e = studentService.addStudent("surname", "name", "111");
studentService.updateStudent(e.getId(),e.getSurname(), newName, e.getPhoneNumber());
Assertions.assertEquals(newName, studentService.findStudent(e.getId()).getName());
studentService.deleteAllStudents();
}
@Test
public void testDeleteStudent() {
studentService.deleteAllStudents();
Student e = studentService.addStudent("name", "surname", "111");
studentService.deleteStudent(e.getId());
Assertions.assertEquals(0, studentService.findAllStudents().size());
studentService.deleteAllStudents();
}
@Test
public void testFindAllStudent() {
studentService.deleteAllStudents();
int n = 3;
for (int i = 0; i < n; i++) {
studentService.addStudent("name", "surname", "111");
}
Assertions.assertEquals(n, studentService.findAllStudents().size());
studentService.deleteAllStudents();
}
@Test
public void testAddDrivingSchool() {
studentService.deleteAllStudents();
drivingSchoolService.deleteAllDrivingSchools();
Student e = studentService.addStudent("name", "surname", "111");
DrivingSchool c = drivingSchoolService.addDrivingSchool("Comp");
drivingSchoolService.addNewStudent(c.getId(), e);
Assertions.assertEquals(c, studentService.findStudent(e.getId()).getDrivingSchool());
studentService.deleteAllStudents();
drivingSchoolService.deleteAllDrivingSchools();
}
@Test
public void testDeleteFromDrivingSchool() {
studentService.deleteAllStudents();
drivingSchoolService.deleteAllDrivingSchools();
Student e = studentService.addStudent("name", "surname", "111");
DrivingSchool c = drivingSchoolService.addDrivingSchool("Comp");
studentService.addDrivingSchool(e.getId(), c);
Assertions.assertEquals(c, studentService.findStudent(e.getId()).getDrivingSchool());
studentService.deleteDrivingSchool(e.getId());
Assertions.assertNull(studentService.findStudent(e.getId()).getDrivingSchool());
studentService.deleteAllStudents();
drivingSchoolService.deleteAllDrivingSchools();
}
@Test
public void testGetByCategory() {
studentService.deleteAllStudents();
categoryService.deleteAllCategories();
Category p = categoryService.addCategory("Category 1");
Category p2 = categoryService.addCategory("Category 2");
final int n = 10;
for (int i = 0; i < n; i++) {
Student e = studentService.addStudent("1111", "name" + i, "surname");
if (i % 2 == 0) {
studentService.addCategory(e.getId(), p);
}
else {
studentService.addCategory(e.getId(), p2);
}
}
Assertions.assertEquals(n / 2, studentService.getStudentsByCategory(p).size());
Assertions.assertEquals(n / 2, studentService.getStudentsByCategory(p2).size());
studentService.deleteAllStudents();
categoryService.deleteAllCategories();
}
}