Compare commits
No commits in common. "master" and "lab6" have entirely different histories.
79
.gitignore
vendored
79
.gitignore
vendored
@ -1,79 +0,0 @@
|
|||||||
# ---> JetBrains
|
|
||||||
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
|
|
||||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
|
||||||
|
|
||||||
# User-specific stuff
|
|
||||||
.idea/**/workspace.xml
|
|
||||||
.idea/**/tasks.xml
|
|
||||||
.idea/**/usage.statistics.xml
|
|
||||||
.idea/**/dictionaries
|
|
||||||
.idea/**/shelf
|
|
||||||
|
|
||||||
# AWS User-specific
|
|
||||||
.idea/**/aws.xml
|
|
||||||
|
|
||||||
# Generated files
|
|
||||||
.idea/**/contentModel.xml
|
|
||||||
|
|
||||||
# Sensitive or high-churn files
|
|
||||||
.idea/**/dataSources/
|
|
||||||
.idea/**/dataSources.ids
|
|
||||||
.idea/**/dataSources.local.xml
|
|
||||||
.idea/**/sqlDataSources.xml
|
|
||||||
.idea/**/dynamic.xml
|
|
||||||
.idea/**/uiDesigner.xml
|
|
||||||
.idea/**/dbnavigator.xml
|
|
||||||
|
|
||||||
# Gradle
|
|
||||||
.idea/**/gradle.xml
|
|
||||||
.idea/**/libraries
|
|
||||||
|
|
||||||
# Gradle and Maven with auto-import
|
|
||||||
# When using Gradle or Maven with auto-import, you should exclude module files,
|
|
||||||
# since they will be recreated, and may cause churn. Uncomment if using
|
|
||||||
# auto-import.
|
|
||||||
# .idea/artifacts
|
|
||||||
# .idea/compiler.xml
|
|
||||||
# .idea/jarRepositories.xml
|
|
||||||
# .idea/modules.xml
|
|
||||||
# .idea/*.iml
|
|
||||||
# .idea/modules
|
|
||||||
# *.iml
|
|
||||||
# *.ipr
|
|
||||||
|
|
||||||
# CMake
|
|
||||||
cmake-build-*/
|
|
||||||
|
|
||||||
# Mongo Explorer plugin
|
|
||||||
.idea/**/mongoSettings.xml
|
|
||||||
|
|
||||||
# File-based project format
|
|
||||||
*.iws
|
|
||||||
|
|
||||||
# IntelliJ
|
|
||||||
out/
|
|
||||||
|
|
||||||
# mpeltonen/sbt-idea plugin
|
|
||||||
.idea_modules/
|
|
||||||
|
|
||||||
# JIRA plugin
|
|
||||||
atlassian-ide-plugin.xml
|
|
||||||
|
|
||||||
# Cursive Clojure plugin
|
|
||||||
.idea/replstate.xml
|
|
||||||
|
|
||||||
# SonarLint plugin
|
|
||||||
.idea/sonarlint/
|
|
||||||
|
|
||||||
# Crashlytics plugin (for Android Studio and IntelliJ)
|
|
||||||
com_crashlytics_export_strings.xml
|
|
||||||
crashlytics.properties
|
|
||||||
crashlytics-build.properties
|
|
||||||
fabric.properties
|
|
||||||
|
|
||||||
# Editor-based Rest Client
|
|
||||||
.idea/httpRequests
|
|
||||||
|
|
||||||
# Android studio 3.1+ serialized cache file
|
|
||||||
.idea/caches/build_file_checksums.ser
|
|
||||||
|
|
43
build.gradle
Normal file
43
build.gradle
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
plugins {
|
||||||
|
id 'java'
|
||||||
|
id 'org.springframework.boot' version '3.0.2'
|
||||||
|
id 'io.spring.dependency-management' version '1.1.0'
|
||||||
|
}
|
||||||
|
|
||||||
|
group = 'com.example'
|
||||||
|
version = '0.0.1-SNAPSHOT'
|
||||||
|
sourceCompatibility = '17'
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
|
||||||
|
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.springframework.boot:spring-boot-starter-security'
|
||||||
|
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
|
||||||
|
implementation 'com.auth0:java-jwt:4.4.0'
|
||||||
|
implementation group: 'io.jsonwebtoken', name: 'jjwt', version: '0.9.1'
|
||||||
|
implementation 'javax.xml.bind:jaxb-api:2.3.1'
|
||||||
|
|
||||||
|
implementation 'org.hibernate.validator:hibernate-validator'
|
||||||
|
|
||||||
|
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
|
||||||
|
|
||||||
|
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.named('test') {
|
||||||
|
useJUnitPlatform()
|
||||||
|
}
|
31206
front/package-lock.json
generated
Normal file
31206
front/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
49
front/package.json
Normal file
49
front/package.json
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
{
|
||||||
|
"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": "^6.10.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
14
front/public/index.html
Normal 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>
|
69
front/src/App.js
Normal file
69
front/src/App.js
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
import Main from './components/Main.jsx';
|
||||||
|
import React from "react";
|
||||||
|
import { useRoutes, Outlet, BrowserRouter } from 'react-router-dom';
|
||||||
|
import Employees from './components/Employees.jsx';
|
||||||
|
import Header from "./components/commons/Header.jsx"
|
||||||
|
import 'bootstrap/dist/css/bootstrap.min.css';
|
||||||
|
import Companies from './components/Companies.jsx';
|
||||||
|
import Positions from './components/Positions.jsx';
|
||||||
|
import OneCompany from './components/OneCompany.jsx';
|
||||||
|
import ReportEmployeePosition from './components/ReportEmployeePosition.jsx';
|
||||||
|
import Login from './components/Login.jsx';
|
||||||
|
import Logout from './components/Logout.jsx';
|
||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
function Router(props) {
|
||||||
|
return useRoutes(props.rootRoute);
|
||||||
|
}
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
const routes = [
|
||||||
|
{ index: true, element: <Companies /> },
|
||||||
|
{ path: '/', element: <Companies />, label: 'ГЛАВНОЕ' },
|
||||||
|
{ path: '/employees', element: <Employees />, label: 'Сотрудники' },
|
||||||
|
{ path: '/companies', element: <Companies />, label: 'Компании' },
|
||||||
|
{ path: '/positions', element: <Positions />, label: 'Должности' },
|
||||||
|
{ path: '/report', element: <ReportEmployeePosition />, label: 'Сотрудники по должностям' },
|
||||||
|
{ path: '/company/:id', element: <OneCompany />},
|
||||||
|
{ path: '/login', element: <Login />},
|
||||||
|
{ path: '/logout', element: <Logout />},
|
||||||
|
];
|
||||||
|
const links = routes.filter(route => route.hasOwnProperty('label'));
|
||||||
|
const [token, setToken] = useState(localStorage.getItem('token'));
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
|
||||||
|
function handleStorageChange() {
|
||||||
|
setToken(localStorage.getItem('token'));
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('storage', handleStorageChange);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('storage', handleStorageChange);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const rootRoute = [
|
||||||
|
{ path: '/', element: render(links), children: routes }
|
||||||
|
];
|
||||||
|
|
||||||
|
function render(links) {
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="App">
|
||||||
|
<Header token={token} links={links} />
|
||||||
|
<div className="w-100">
|
||||||
|
<Outlet />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<BrowserRouter>
|
||||||
|
<Router rootRoute={ rootRoute } />
|
||||||
|
</BrowserRouter>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default App;
|
50
front/src/components/Catalog.jsx
Normal file
50
front/src/components/Catalog.jsx
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
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 handleEdit(itemId) {
|
||||||
|
setModalTitle("Редактирование");
|
||||||
|
props.onEdit(itemId);
|
||||||
|
handleShow();
|
||||||
|
}
|
||||||
|
function handleRemove(item) {
|
||||||
|
props.onDelete(item);
|
||||||
|
}
|
||||||
|
function changeData(event) {
|
||||||
|
props.onFormChanged(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
return <>
|
||||||
|
<div>{props.name}</div>
|
||||||
|
{localStorage.getItem("role") === "ADMIN" && <Button variant="success" onClick={handleAdd}>Добавить</Button>}
|
||||||
|
<Table
|
||||||
|
headers={props.headers}
|
||||||
|
items={props.items}
|
||||||
|
onEdit={handleEdit}
|
||||||
|
onDelete={handleRemove}
|
||||||
|
/>
|
||||||
|
<ModalForm
|
||||||
|
show={show}
|
||||||
|
onClose={handleClose}
|
||||||
|
modalTitle={modalTitle}
|
||||||
|
// onSubmit={submitForm}
|
||||||
|
onChange={changeData}
|
||||||
|
form={props.form}
|
||||||
|
/></>
|
||||||
|
|
||||||
|
}
|
155
front/src/components/Companies.jsx
Normal file
155
front/src/components/Companies.jsx
Normal file
@ -0,0 +1,155 @@
|
|||||||
|
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 Company from "../models/Company";
|
||||||
|
import ModalForm from './commons/ModalForm';
|
||||||
|
import Employee from '../models/Employee';
|
||||||
|
import Position from '../models/Position';
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import withAuth from './withAuth';
|
||||||
|
|
||||||
|
function Companies(props) {
|
||||||
|
const headers = [
|
||||||
|
{name: 'name', label: "Название"},
|
||||||
|
{name: 'countEmployees', label: "Сотрудники"},
|
||||||
|
];
|
||||||
|
const nameCatalog = "Компании";
|
||||||
|
|
||||||
|
const url = '/company';
|
||||||
|
const requestParams = '?name=nameData';
|
||||||
|
|
||||||
|
const [items, setItems] = useState([]);
|
||||||
|
|
||||||
|
|
||||||
|
const [data, setData] = useState(new Company());
|
||||||
|
const [isEditing, setEditing] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
loadItems();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
function loadItems() {
|
||||||
|
DataService.readAll(url, (data) => new Company(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 Company(e))
|
||||||
|
.then(data => {
|
||||||
|
setData(new Company(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 Company());
|
||||||
|
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 formChooseCompany = <Form onSubmit={redirectToCompany}>
|
||||||
|
<Form.Group className="mb-3" controlId="name">
|
||||||
|
<Form.Label>Компания</Form.Label>
|
||||||
|
<Form.Select name="name_select" type="input" onChange={(e) => {setChosenCompany(e.target.value)}} required>
|
||||||
|
<option selected disabled>Выберите компанию</option>
|
||||||
|
{
|
||||||
|
items.map((company) => <option key={`company_${company.id}`} value={`${company.id}`}>{`${company.name}`}</option>)
|
||||||
|
}
|
||||||
|
</Form.Select>
|
||||||
|
</Form.Group>
|
||||||
|
<Button variant="primary" type="submit">
|
||||||
|
Перейти
|
||||||
|
</Button>
|
||||||
|
</Form>;
|
||||||
|
|
||||||
|
function showModalFormChoosing() {
|
||||||
|
setShowChoosing(true);
|
||||||
|
}
|
||||||
|
function unshowModalFormChoosing() {
|
||||||
|
setShowChoosing(false);
|
||||||
|
}
|
||||||
|
const [chosenCompany, setChosenCompany] = useState(0);
|
||||||
|
const navigate = useNavigate();
|
||||||
|
function redirectToCompany() {
|
||||||
|
|
||||||
|
if (chosenCompany !== 0) {
|
||||||
|
navigate(`/company/${chosenCompany}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return <div className="container-lg pt-5 min-vh-100">
|
||||||
|
<Button onClick={showModalFormChoosing} variant="info">Перейти к компании</Button>
|
||||||
|
<ModalForm show={showModalForm} onClose={unshowModalFormChoosing} modalTitle={"Выбор компаниии"} form={formChooseCompany}></ModalForm>
|
||||||
|
<Catalog name={nameCatalog}
|
||||||
|
headers={headers}
|
||||||
|
items={items}
|
||||||
|
onAdd={handleAdd}
|
||||||
|
onEdit={handleEdit}
|
||||||
|
onDelete={handleDelete}
|
||||||
|
onClose={reset}
|
||||||
|
onBtnAdd={reset}
|
||||||
|
form={form}>
|
||||||
|
</Catalog>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default withAuth(Companies);
|
119
front/src/components/Employees.jsx
Normal file
119
front/src/components/Employees.jsx
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
import Employee from "../models/Employee";
|
||||||
|
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 withAuth from './withAuth';
|
||||||
|
|
||||||
|
function Employees(props) {
|
||||||
|
const headers = [
|
||||||
|
{name: 'surname', label: "Фамилия"},
|
||||||
|
{name: 'name', label: "Имя"},
|
||||||
|
{name: 'phoneNumber', label: "Номер телефона"},
|
||||||
|
{name: 'positionsString', label: 'Должности'}
|
||||||
|
];
|
||||||
|
const nameCatalog = "Сотрудники";
|
||||||
|
const [items, setItems] = useState([]);
|
||||||
|
const url = '/employee';
|
||||||
|
const requestParams = '?name=nameData&surname=surnameData&phoneNumber=phoneNameData';
|
||||||
|
const [data, setData] = useState(new Employee());
|
||||||
|
const [isEditing, setEditing] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
loadItems();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
|
||||||
|
function loadItems() {
|
||||||
|
DataService.readAll(url, (data) => new Employee(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 Employee(e))
|
||||||
|
.then(data => {
|
||||||
|
setData(new Employee(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 Employee());
|
||||||
|
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">
|
||||||
|
<Catalog name={nameCatalog}
|
||||||
|
headers={headers}
|
||||||
|
items={items}
|
||||||
|
onAdd={handleAdd}
|
||||||
|
onEdit={handleEdit}
|
||||||
|
onDelete={handleDelete}
|
||||||
|
onClose={reset}
|
||||||
|
onBtnAdd={reset}
|
||||||
|
form={form}>
|
||||||
|
</Catalog>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default withAuth(Employees);
|
21
front/src/components/Login.css
Normal file
21
front/src/components/Login.css
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
body {
|
||||||
|
background-color: #f8f9fa;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-title {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
background-color: #007bff;
|
||||||
|
border-color: #007bff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover {
|
||||||
|
background-color: #0069d9;
|
||||||
|
border-color: #0062cc;
|
||||||
|
}
|
70
front/src/components/Login.jsx
Normal file
70
front/src/components/Login.jsx
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import './Login.css';
|
||||||
|
import 'bootstrap/dist/css/bootstrap.min.css';
|
||||||
|
import { useNavigate} from "react-router-dom";
|
||||||
|
|
||||||
|
export default function Login(props) {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const [loginData, setLoginData] = useState({ login: '', password: '' });
|
||||||
|
const hostURL = 'http://localhost:8080';
|
||||||
|
const handleLoginSubmit = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
login(loginData.login, loginData.password);
|
||||||
|
};
|
||||||
|
|
||||||
|
const login = async function (login, password) {
|
||||||
|
const requestParams = {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({login: login, password: password}),
|
||||||
|
};
|
||||||
|
const response = await fetch(hostURL + "/jwt/login", requestParams);
|
||||||
|
const result = await response.text();
|
||||||
|
if (response.status === 200) {
|
||||||
|
localStorage.setItem("token", result);
|
||||||
|
localStorage.setItem("user", login);
|
||||||
|
let jwtData = result.split('.')[1]
|
||||||
|
let decodedJwtJsonData = window.atob(jwtData);
|
||||||
|
let decodedJwtData = JSON.parse(decodedJwtJsonData);
|
||||||
|
|
||||||
|
let role = decodedJwtData.role;
|
||||||
|
localStorage.setItem("role", role.toUpperCase());
|
||||||
|
window.dispatchEvent(new Event("storage"));
|
||||||
|
navigate("/");
|
||||||
|
} else {
|
||||||
|
localStorage.removeItem("token");
|
||||||
|
localStorage.removeItem("user");
|
||||||
|
localStorage.removeItem("role");
|
||||||
|
alert(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="container-fluid">
|
||||||
|
<div className="row justify-content-center align-items-center vh-100">
|
||||||
|
<div className="col-sm-6 col-md-4">
|
||||||
|
<div className="card">
|
||||||
|
<div className="card-body">
|
||||||
|
<h5 className="card-title">Авторизация</h5>
|
||||||
|
<form onSubmit={handleLoginSubmit}>
|
||||||
|
<div className="form-group mb-3">
|
||||||
|
<label htmlFor="login">Логин</label>
|
||||||
|
<input type="text" className="form-control" id="login" value={loginData.login} onChange={(e) => setLoginData({ ...loginData, login: e.target.value })} />
|
||||||
|
</div>
|
||||||
|
<div className="form-group mb-3">
|
||||||
|
<label htmlFor="loginPassword">Пароль</label>
|
||||||
|
<input type="password" className="form-control" id="loginPassword" value={loginData.password} onChange={(e) => setLoginData({ ...loginData, password: e.target.value })} />
|
||||||
|
</div>
|
||||||
|
<button type="submit" className="btn btn-primary">Вход</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
20
front/src/components/Logout.jsx
Normal file
20
front/src/components/Logout.jsx
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
import { useEffect } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
|
||||||
|
function Logout() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Удаление токена из localStorage или другого места
|
||||||
|
localStorage.removeItem('token');
|
||||||
|
localStorage.removeItem("user");
|
||||||
|
localStorage.removeItem("role");
|
||||||
|
window.dispatchEvent(new Event("storage"));
|
||||||
|
// Перенаправление пользователя на страницу входа или другую страницу
|
||||||
|
navigate('/login');
|
||||||
|
}, [navigate]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Logout;
|
76
front/src/components/Main.jsx
Normal file
76
front/src/components/Main.jsx
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
import { Button } from "bootstrap";
|
||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import DataService from '../services/DataService';
|
||||||
|
|
||||||
|
export default function Main(props) {
|
||||||
|
const url = 'http://localhost:8080';
|
||||||
|
const urlRandomNumber = '/getRandomNumber';
|
||||||
|
const urlCalc = '/sum?val1=num1&val2=num2';
|
||||||
|
const urlLength = '/length?name=strName';
|
||||||
|
const urlUpperCase = '/upperCase?word=strWord';
|
||||||
|
|
||||||
|
function get(url2) {
|
||||||
|
fetch(
|
||||||
|
url + url2,
|
||||||
|
{
|
||||||
|
method: 'GET',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
}
|
||||||
|
).then(resp => resp.text()).then(alert);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getRandomNumber() {
|
||||||
|
get(urlRandomNumber);
|
||||||
|
|
||||||
|
}
|
||||||
|
function req_calc() {
|
||||||
|
get(urlCalc.replace("num1", num1).replace("num2", num2));
|
||||||
|
}
|
||||||
|
const [num1, setnum1] = useState('');
|
||||||
|
const [num2, setnum2] = useState('');
|
||||||
|
function valueChanged1(event) {
|
||||||
|
console.log(event.target);
|
||||||
|
setnum1(event.target.value);
|
||||||
|
}
|
||||||
|
function valueChanged2(event) {
|
||||||
|
setnum2(event.target.value);
|
||||||
|
}
|
||||||
|
function req_length() {
|
||||||
|
get(urlLength.replace("strName", strName));
|
||||||
|
|
||||||
|
}
|
||||||
|
const [strName, setName] = useState('');
|
||||||
|
function valueChangedName(event) {
|
||||||
|
setName(event.target.value);
|
||||||
|
}
|
||||||
|
function req_upperCase() {
|
||||||
|
get(urlUpperCase.replace("strWord", strWord));
|
||||||
|
}
|
||||||
|
const [strWord, setWord] = useState('');
|
||||||
|
function valueChangedWord(event) {
|
||||||
|
setWord(event.target.value);
|
||||||
|
}
|
||||||
|
return <div>
|
||||||
|
<h1>Сайт...</h1>
|
||||||
|
<div className="row">
|
||||||
|
<h1>Рандомное число</h1>
|
||||||
|
<button className="btn primary" onClick={getRandomNumber}>Get Random Number</button>
|
||||||
|
</div>
|
||||||
|
<div className="row">
|
||||||
|
<h1>Калькулятор</h1>
|
||||||
|
<input type="text" onChange={valueChanged1}></input>
|
||||||
|
<input type="text" onChange={valueChanged2}></input>
|
||||||
|
<button onClick={req_calc}>Press</button>
|
||||||
|
</div>
|
||||||
|
<div className="row">
|
||||||
|
<h1>Посчитать длину строки</h1>
|
||||||
|
<input type="text" onChange={valueChangedName}></input>
|
||||||
|
<button onClick={req_length}>Press</button>
|
||||||
|
</div>
|
||||||
|
<div className="row">
|
||||||
|
<h1>Перевести слово в верхний регистр</h1>
|
||||||
|
<input type="text" onChange={valueChangedWord}></input>
|
||||||
|
<button onClick={req_upperCase}>Press</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
258
front/src/components/OneCompany.jsx
Normal file
258
front/src/components/OneCompany.jsx
Normal file
@ -0,0 +1,258 @@
|
|||||||
|
import Company from "../models/Company";
|
||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { Link, useParams } from "react-router-dom";
|
||||||
|
import DataService from '../services/DataService';
|
||||||
|
import Employee from '../models/Employee';
|
||||||
|
import Position from '../models/Position';
|
||||||
|
import Form from 'react-bootstrap/Form';
|
||||||
|
import Button from 'react-bootstrap/Button';
|
||||||
|
import ModalForm from './commons/ModalForm';
|
||||||
|
import styles from "./OneCompany.module.css";
|
||||||
|
import withAuth from './withAuth';
|
||||||
|
|
||||||
|
function OneCompany(props) {
|
||||||
|
const { id } = useParams();
|
||||||
|
|
||||||
|
const url = '/company/id';
|
||||||
|
const urlCompanyEmp = '/company/id/employees';
|
||||||
|
const urlEmp = '/employee/free';
|
||||||
|
const urlPos = '/position';
|
||||||
|
const urlHire = '/company/id/hire';
|
||||||
|
const urlDismiss = '/company/id/dismiss';
|
||||||
|
const urlAddPos = '/employee/id/addPos';
|
||||||
|
const urlDelPos = '/employee/id/delPos';
|
||||||
|
const requestParamsPosition = '?position=posId';
|
||||||
|
const requestParamsHire = '?employeeId=empId';
|
||||||
|
|
||||||
|
const [company, setCompany] = useState(new Company());
|
||||||
|
const [itemsEmpFree, setItemsEmpFree] = useState([]);
|
||||||
|
const [itemsEmpCompany, setItemsEmpCompany] = useState([]);
|
||||||
|
const [itemsPos, setItemsPos] = useState([]);
|
||||||
|
|
||||||
|
const headersEmp = [
|
||||||
|
{name: 'surname', label: "Фамилия"},
|
||||||
|
{name: 'name', label: "Имя"},
|
||||||
|
{name: 'positionsString', label: 'Должности'},
|
||||||
|
{name: 'phoneNumber', label: "Номер телефона"}
|
||||||
|
];
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadCompany();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
function loadCompany() {
|
||||||
|
DataService.read(url.replace("id", id), (data) => new Company(data)).then((data) => setCompany(new Company(data)));
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadItemsEmployees() {
|
||||||
|
DataService.readAll(urlEmp, (data) => new Employee(data))
|
||||||
|
.then(data => setItemsEmpFree(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadItemsPositions() {
|
||||||
|
DataService.readAll(urlPos, (data) => new Position(data))
|
||||||
|
.then(data => setItemsPos(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadItemsEmployeesCompany() {
|
||||||
|
DataService.readAll(urlCompanyEmp.replace("id", company.id), (data) => new Employee(data))
|
||||||
|
.then(data => setItemsEmpCompany(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// логика для найма или увольнения
|
||||||
|
const [isShowHire, setShowHire] = useState(false);
|
||||||
|
|
||||||
|
function showModalFormHire() {
|
||||||
|
loadItemsEmployees();
|
||||||
|
setShowHire(true);
|
||||||
|
}
|
||||||
|
function unshowModalFormHire() {
|
||||||
|
setShowHire(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
const [isShowDismiss, setShowDismiss] = useState(false);
|
||||||
|
|
||||||
|
function showModalFormDismiss(e) {
|
||||||
|
loadItemsEmployeesCompany();
|
||||||
|
setShowDismiss(true);
|
||||||
|
}
|
||||||
|
function unshowModalFormDismiss() {
|
||||||
|
setShowDismiss(false);
|
||||||
|
}
|
||||||
|
const [employee, setEmployee] = useState(new Employee());
|
||||||
|
|
||||||
|
function employeeChosenFree(e) {
|
||||||
|
setEmployee(itemsEmpFree.filter((emp) => emp.id == e.target.value)[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function employeeChosenBusy(e) {
|
||||||
|
setEmployee(Array.from(company.employees).filter((emp) => emp.id == e.target.value)[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formHireSubmit() {
|
||||||
|
DataService.update(urlHire.replace("id",company.id) + requestParamsHire
|
||||||
|
.replace("empId", employee.id))
|
||||||
|
.then(() => loadCompany());
|
||||||
|
|
||||||
|
|
||||||
|
setEmployee(new Employee());
|
||||||
|
}
|
||||||
|
|
||||||
|
function formDismissSubmit() {
|
||||||
|
DataService.update(urlDismiss.replace("id",company.id) + requestParamsHire
|
||||||
|
.replace("empId", employee.id))
|
||||||
|
.then(() => loadCompany());
|
||||||
|
|
||||||
|
setEmployee(new Employee());
|
||||||
|
}
|
||||||
|
|
||||||
|
const [isShowChoosePosition, setShowChoosePosition] = useState(false);
|
||||||
|
|
||||||
|
function showModalFormChoosePosition() {
|
||||||
|
loadItemsPositions();
|
||||||
|
loadItemsEmployeesCompany();
|
||||||
|
setShowChoosePosition(true);
|
||||||
|
}
|
||||||
|
function unshowModalFormChoosePosition() {
|
||||||
|
setShowChoosePosition(false);
|
||||||
|
setPositionEmp([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const [positionsChosen, setPositionEmp] = useState([]);
|
||||||
|
function checkBoxChanged(e) {
|
||||||
|
// если чекбокс был выбран, то дабавляем в массив должность
|
||||||
|
if (e.target.checked)
|
||||||
|
{
|
||||||
|
positionsChosen.push(e.target.value);
|
||||||
|
} // если чекбокс был убран, то исключаем его значение из массива
|
||||||
|
else
|
||||||
|
{
|
||||||
|
let i = positionsChosen.indexOf(e.target.value);
|
||||||
|
if(i >= 0) {
|
||||||
|
positionsChosen.splice(i,1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formChoosePositionsSubmit() {
|
||||||
|
for (let i = 0; i < positionsChosen.length; i++) {
|
||||||
|
DataService.update(urlAddPos.replace("id",employee.id) + requestParamsPosition
|
||||||
|
.replace("posId", positionsChosen[i]))
|
||||||
|
.then(() => loadCompany());
|
||||||
|
}
|
||||||
|
|
||||||
|
let positionsEmp = employee.positions;
|
||||||
|
|
||||||
|
for (let i = 0; i < positionsEmp.length; i++) {
|
||||||
|
if (positionsChosen.indexOf(''+positionsEmp[i].id) == -1) {
|
||||||
|
// удаление должности
|
||||||
|
DataService.update(urlDelPos.replace("id",employee.id) + requestParamsPosition
|
||||||
|
.replace("posId", positionsEmp[i].id))
|
||||||
|
.then(() => loadCompany());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const formHire = <Form onSubmit={formHireSubmit}>
|
||||||
|
<Form.Group className="mb-3" controlId="employee">
|
||||||
|
<Form.Label>Сотрудник</Form.Label>
|
||||||
|
<Form.Select name="employee_select" type="input" onChange={employeeChosenFree} required>
|
||||||
|
<option selected disabled>Выберите сотрудника</option>
|
||||||
|
{
|
||||||
|
itemsEmpFree.map((e) => <option key={`emp_${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="employee">
|
||||||
|
<Form.Label>Сотрудник</Form.Label>
|
||||||
|
<Form.Select name="employee_select" type="input" onChange={employeeChosenBusy} required>
|
||||||
|
<option selected disabled>Выберите сотрудника</option>
|
||||||
|
{
|
||||||
|
itemsEmpCompany.map((e) => <option key={`emp_${e.id}`} value={`${e.id}`}>{`${e.surname} ${e.name}`}</option>)
|
||||||
|
}
|
||||||
|
</Form.Select>
|
||||||
|
</Form.Group>
|
||||||
|
<Button variant="primary" type="submit">
|
||||||
|
Отправить
|
||||||
|
</Button>
|
||||||
|
</Form>;
|
||||||
|
|
||||||
|
const formCheckBoxesPosition = <Form onSubmit={formChoosePositionsSubmit}>
|
||||||
|
<Form.Group className="mb-3" controlId="employee">
|
||||||
|
<Form.Label>Сотрудник</Form.Label>
|
||||||
|
<Form.Select name="employee_select" type="input" onChange={employeeChosenBusy} required>
|
||||||
|
<option selected disabled>Выберите сотрудника</option>
|
||||||
|
{
|
||||||
|
itemsEmpCompany.map((e) => <option key={`emp_${e.id}`} value={`${e.id}`}>{`${e.surname} ${e.name}`}</option>)
|
||||||
|
}
|
||||||
|
</Form.Select>
|
||||||
|
</Form.Group>
|
||||||
|
<Form.Group className="mb-3" controlId="position">
|
||||||
|
<Form.Label>Должности</Form.Label>
|
||||||
|
<div className={`${styles.prokrutka}`}>
|
||||||
|
{
|
||||||
|
itemsPos.map((p) => <div style={{width: `150 px`}}>
|
||||||
|
<input type="checkbox" key={`${p.id}`} value={`${p.id}`} onChange={checkBoxChanged}/>
|
||||||
|
{/* {!employeeHasPosition(p) && <input type="checkbox" key={`${p.id}`} value={`${p.id}`} onChange={checkBoxChanged}/>}
|
||||||
|
{employeeHasPosition(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 (!company) {
|
||||||
|
return <div><h1>Компания не найдена</h1>
|
||||||
|
<Link to='/companies'>
|
||||||
|
<Button variant="info">Назад</Button>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
return <div className="container-lg pt-5 min-vh-100">
|
||||||
|
<Link to='/companies'>
|
||||||
|
<Button variant="info">Назад</Button>
|
||||||
|
</Link>
|
||||||
|
<h1>Название: {company.name}</h1>
|
||||||
|
<h2>Количество сотрудников: {company.countEmployees}</h2>
|
||||||
|
{localStorage.getItem("role") === "ADMIN" && <Button name="Найм" onClick={showModalFormHire} variant="success">Нанять сотрудника</Button>}
|
||||||
|
{localStorage.getItem("role") === "ADMIN" && <Button name='Увольнение' onClick={showModalFormDismiss} variant="danger">Уволить сотрудника</Button>}
|
||||||
|
{localStorage.getItem("role") === "ADMIN" && <Button name='Назначение должности' onClick={showModalFormChoosePosition} variant="info">Назначение должности</Button>}
|
||||||
|
<div >
|
||||||
|
<table className={`table table-hover`}>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
{
|
||||||
|
headersEmp.map((header) => <th key={header.name}>{header.label}</th>)
|
||||||
|
}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{
|
||||||
|
Array.from(company.employees).map((item, index) => <tr key={item.id}>
|
||||||
|
{
|
||||||
|
headersEmp.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={isShowChoosePosition} onClose={unshowModalFormChoosePosition} modalTitle={"Управление должностями"} form={formCheckBoxesPosition}></ModalForm>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default withAuth(OneCompany);
|
7
front/src/components/OneCompany.module.css
Normal file
7
front/src/components/OneCompany.module.css
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
.prokrutka {
|
||||||
|
background: #fff; /* цвет фона, белый */
|
||||||
|
border: 1px solid #C1C1C1; /* размер и цвет границы блока */
|
||||||
|
overflow: auto;
|
||||||
|
width:200px;
|
||||||
|
height:100px;
|
||||||
|
}
|
111
front/src/components/Positions.jsx
Normal file
111
front/src/components/Positions.jsx
Normal file
@ -0,0 +1,111 @@
|
|||||||
|
import Position from "../models/Position";
|
||||||
|
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 withAuth from './withAuth';
|
||||||
|
|
||||||
|
function Positions(props) {
|
||||||
|
const headers = [
|
||||||
|
{name: 'name', label: "Название"},
|
||||||
|
];
|
||||||
|
|
||||||
|
const nameCatalog = "Должности";
|
||||||
|
const url = '/position';
|
||||||
|
const requestParams = '?name=nameData';
|
||||||
|
|
||||||
|
const [items, setItems] = useState([]);
|
||||||
|
const [data, setData] = useState(new Position());
|
||||||
|
|
||||||
|
const [isEditing, setEditing] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
loadItems();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
|
||||||
|
function loadItems() {
|
||||||
|
DataService.readAll(url, (data) => new Position(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 Position(e))
|
||||||
|
.then(data => {
|
||||||
|
setData(new Position(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 Position());
|
||||||
|
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">
|
||||||
|
<Catalog name={nameCatalog}
|
||||||
|
headers={headers}
|
||||||
|
items={items}
|
||||||
|
onAdd={handleAdd}
|
||||||
|
onEdit={handleEdit}
|
||||||
|
onDelete={handleDelete}
|
||||||
|
onClose={reset}
|
||||||
|
onBtnAdd={reset}
|
||||||
|
form={form}
|
||||||
|
role={props.role}>
|
||||||
|
</Catalog>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default withAuth(Positions);
|
75
front/src/components/ReportEmployeePosition.jsx
Normal file
75
front/src/components/ReportEmployeePosition.jsx
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
import DataService from '../services/DataService';
|
||||||
|
import Employee from '../models/Employee';
|
||||||
|
import Position from '../models/Position';
|
||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import Form from 'react-bootstrap/Form';
|
||||||
|
import Button from 'react-bootstrap/Button';
|
||||||
|
import Company from '../models/Company';
|
||||||
|
import { Link} from "react-router-dom";
|
||||||
|
import withAuth from './withAuth';
|
||||||
|
function ReportEmployeePosition(props) {
|
||||||
|
const headersEmp = [
|
||||||
|
{name: 'surname', label: "Фамилия"},
|
||||||
|
{name: 'name', label: "Имя"},
|
||||||
|
{name: 'positionsString', label: 'Должности'},
|
||||||
|
{name: 'phoneNumber', label: "Номер телефона"},
|
||||||
|
];
|
||||||
|
|
||||||
|
|
||||||
|
const url = "/employee/position?pos=id"
|
||||||
|
const urlPos = '/position';
|
||||||
|
|
||||||
|
const [itemsPos, setItemsPos] = useState([]);
|
||||||
|
|
||||||
|
const [itemsEmp, setItemsEmp] = useState([]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadItemsPositions();
|
||||||
|
});
|
||||||
|
|
||||||
|
function loadItemsPositions() {
|
||||||
|
DataService.readAll(urlPos, (data) => new Position(data))
|
||||||
|
.then(data => setItemsPos(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadItemsEmployees(selectedPosition) {
|
||||||
|
DataService.readAll(url.replace("id", selectedPosition), (data) => new Employee(data))
|
||||||
|
.then(data => setItemsEmp(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
return <div className="container-lg pt-5 min-vh-100">
|
||||||
|
<h1>Отчет</h1>
|
||||||
|
|
||||||
|
<Form.Select onChange={(e) => {loadItemsEmployees(e.target.value)}} aria-label="Default select example">
|
||||||
|
<option selected disabled>Выберите должность</option>
|
||||||
|
{
|
||||||
|
itemsPos.map((e) => <option key={`emp_${e.id}`} value={`${e.id}`}>{`${e.name}`}</option>)
|
||||||
|
}
|
||||||
|
</Form.Select>
|
||||||
|
|
||||||
|
<div >
|
||||||
|
<table className={`table table-hover`}>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
{
|
||||||
|
headersEmp.map((header) => <th key={header.name}>{header.label}</th>)
|
||||||
|
}
|
||||||
|
<th key='company'>Компания</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{
|
||||||
|
itemsEmp.map((item) => <tr key={item.id}>
|
||||||
|
{
|
||||||
|
headersEmp.map((header) => <td key={`${header.name}_${item.id}`}>{item[header.name]}</td>)
|
||||||
|
}
|
||||||
|
<td key={`comp_${item.id}`}><Link to={`/company/${item['company'].id}`}>{item['company'].name}</Link></td>
|
||||||
|
</tr>)
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
export default withAuth(ReportEmployeePosition);
|
37
front/src/components/commons/Header.jsx
Normal file
37
front/src/components/commons/Header.jsx
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
import { NavLink } from 'react-router-dom';
|
||||||
|
import Container from 'react-bootstrap/Container';
|
||||||
|
import Nav from 'react-bootstrap/Nav';
|
||||||
|
import Navbar from 'react-bootstrap/Navbar';
|
||||||
|
import styles from "./Header.module.css";
|
||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
|
||||||
|
export default function Header(props) {
|
||||||
|
return (
|
||||||
|
<Navbar collapseOnSelect expand="lg" bg="dark" variant="dark">
|
||||||
|
<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>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
{props.token && props.token !== 'undefined' ?
|
||||||
|
<NavLink className="nav-link" to="/logout">
|
||||||
|
<div>Выйти</div>
|
||||||
|
</NavLink>
|
||||||
|
:
|
||||||
|
<NavLink className="nav-link" to="/login">
|
||||||
|
<div>Войти</div>
|
||||||
|
</NavLink>
|
||||||
|
}
|
||||||
|
</Nav>
|
||||||
|
</Navbar.Collapse>
|
||||||
|
</Container>
|
||||||
|
</Navbar>
|
||||||
|
);
|
||||||
|
}
|
20
front/src/components/commons/ItemTable.jsx
Normal file
20
front/src/components/commons/ItemTable.jsx
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
return <tr key={props.item.id}>
|
||||||
|
{
|
||||||
|
props.headers.map((header) => <td key={`${header.name}_${props.item.id}`}>{props.item[header.name]}</td>)
|
||||||
|
}
|
||||||
|
{localStorage.getItem("role") !== "ADMIN" ||props.isOnlyView || <td key={`controls_${props.item.id}`}>
|
||||||
|
|
||||||
|
{localStorage.getItem("role") === "ADMIN" && <Button variant="info" onClick={edit}>Редактировать</Button>}
|
||||||
|
{localStorage.getItem("role") === "ADMIN" && <Button variant="danger" onClick={remove}>Удалить</Button>}
|
||||||
|
</td>}
|
||||||
|
</tr>
|
||||||
|
}
|
14
front/src/components/commons/ModalForm.jsx
Normal file
14
front/src/components/commons/ModalForm.jsx
Normal 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>
|
||||||
|
}
|
34
front/src/components/commons/Table.jsx
Normal file
34
front/src/components/commons/Table.jsx
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
import ItemTable from './ItemTable';
|
||||||
|
export default function Table(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>)
|
||||||
|
}
|
||||||
|
{localStorage.getItem("role") !== "ADMIN" || 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}
|
||||||
|
isOnlyView={props.isOnlyView}/>)
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
}
|
24
front/src/components/withAuth.js
Normal file
24
front/src/components/withAuth.js
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
import React from 'react'
|
||||||
|
import { useNavigate} from "react-router-dom";
|
||||||
|
import { useEffect } from 'react';
|
||||||
|
|
||||||
|
const withAuth = (Component) => {
|
||||||
|
const AuthenticatedComponent = (props) => {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!token || token === 'undefined') {
|
||||||
|
navigate('/login');
|
||||||
|
}
|
||||||
|
}, [navigate, token]);
|
||||||
|
|
||||||
|
if (token && token !== 'undefined') {
|
||||||
|
return <Component {...props} />
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return AuthenticatedComponent;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default withAuth;
|
8
front/src/index.js
Normal file
8
front/src/index.js
Normal 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 />
|
||||||
|
);
|
13
front/src/models/Company.js
Normal file
13
front/src/models/Company.js
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import Employee from "./Employee";
|
||||||
|
|
||||||
|
export default class Company {
|
||||||
|
constructor(data) {
|
||||||
|
this.id = data?.id;
|
||||||
|
this.name = data?.name || '';
|
||||||
|
this.employees = data?.employees.map((e) => new Employee(e)) || '';
|
||||||
|
this.countEmployees = '';
|
||||||
|
if (this.employees !== '') {
|
||||||
|
this.countEmployees = this.employees.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
25
front/src/models/Employee.js
Normal file
25
front/src/models/Employee.js
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
import Position from "./Position";
|
||||||
|
|
||||||
|
export default class Employee {
|
||||||
|
constructor(data) {
|
||||||
|
this.id = data?.id;
|
||||||
|
this.surname = data?.surname || '';
|
||||||
|
this.name = data?.name || '';
|
||||||
|
this.phoneNumber = data?.phoneNumber || '';
|
||||||
|
this.positions = data?.positions.map((p) => new Position(p)) || '';
|
||||||
|
this.positionsString = '';
|
||||||
|
if (this.positions !== '') {
|
||||||
|
this.positions.forEach((p) => {this.positionsString += p.name + " "});
|
||||||
|
}
|
||||||
|
this.company = data?.company || '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Employee.prototype.equals = function (obj){
|
||||||
|
if(typeof obj != typeof this)
|
||||||
|
return false;
|
||||||
|
if (this.id === obj.id) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
6
front/src/models/Position.js
Normal file
6
front/src/models/Position.js
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
export default class Position {
|
||||||
|
constructor(data) {
|
||||||
|
this.id = data?.id;
|
||||||
|
this.name = data?.name || '';
|
||||||
|
}
|
||||||
|
}
|
55
front/src/services/DataService.js
Normal file
55
front/src/services/DataService.js
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
|
const getTokenForHeader = function () {
|
||||||
|
return "Bearer " + localStorage.getItem("token");
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class DataService {
|
||||||
|
static dataUrlPrefix = 'http://localhost:8080/api';
|
||||||
|
|
||||||
|
static async readAll(url, transformer) {
|
||||||
|
const response = await axios.get(this.dataUrlPrefix + url, {headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
|
}});
|
||||||
|
return response.data.map(item => transformer(item));
|
||||||
|
}
|
||||||
|
|
||||||
|
static async read(url, transformer) {
|
||||||
|
const response = await axios.get(this.dataUrlPrefix + url, {headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
|
}});
|
||||||
|
return transformer(response.data);
|
||||||
|
}
|
||||||
|
|
||||||
|
static async create(url, data) {
|
||||||
|
const response = await axios.post(this.dataUrlPrefix + url, {headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
|
}});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static async update(url, data) {
|
||||||
|
const response = await axios.put(this.dataUrlPrefix + url, {headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
|
}});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static async delete(url) {
|
||||||
|
const response = await axios.delete(this.dataUrlPrefix + url, {headers: {
|
||||||
|
"Authorization": getTokenForHeader(),
|
||||||
|
}});
|
||||||
|
return response.data.id;
|
||||||
|
}
|
||||||
|
}
|
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
5
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
5
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
240
gradlew
vendored
Normal file
240
gradlew
vendored
Normal file
@ -0,0 +1,240 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copyright © 2015-2021 the original authors.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
#
|
||||||
|
# Gradle start up script for POSIX generated by Gradle.
|
||||||
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh Gradle
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
|
# Resolve links: $0 may be a link
|
||||||
|
app_path=$0
|
||||||
|
|
||||||
|
# Need this for daisy-chained symlinks.
|
||||||
|
while
|
||||||
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
|
[ -h "$app_path" ]
|
||||||
|
do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||||
|
|
||||||
|
APP_NAME="Gradle"
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
|
||||||
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
|
MAX_FD=maximum
|
||||||
|
|
||||||
|
warn () {
|
||||||
|
echo "$*"
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
die () {
|
||||||
|
echo
|
||||||
|
echo "$*"
|
||||||
|
echo
|
||||||
|
exit 1
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
# OS specific support (must be 'true' or 'false').
|
||||||
|
cygwin=false
|
||||||
|
msys=false
|
||||||
|
darwin=false
|
||||||
|
nonstop=false
|
||||||
|
case "$( uname )" in #(
|
||||||
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
|
Darwin* ) darwin=true ;; #(
|
||||||
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
|
NONSTOP* ) nonstop=true ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||||
|
|
||||||
|
|
||||||
|
# Determine the Java command to use to start the JVM.
|
||||||
|
if [ -n "$JAVA_HOME" ] ; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||||
|
else
|
||||||
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
|
fi
|
||||||
|
if [ ! -x "$JAVACMD" ] ; then
|
||||||
|
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
JAVACMD=java
|
||||||
|
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Increase the maximum file descriptors if we can.
|
||||||
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
|
case $MAX_FD in #(
|
||||||
|
max*)
|
||||||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
|
warn "Could not query maximum file descriptor limit"
|
||||||
|
esac
|
||||||
|
case $MAX_FD in #(
|
||||||
|
'' | soft) :;; #(
|
||||||
|
*)
|
||||||
|
ulimit -n "$MAX_FD" ||
|
||||||
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
|
# * args from the command line
|
||||||
|
# * the main class name
|
||||||
|
# * -classpath
|
||||||
|
# * -D...appname settings
|
||||||
|
# * --module-path (only if needed)
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
|
if "$cygwin" || "$msys" ; then
|
||||||
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
|
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||||
|
|
||||||
|
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||||
|
|
||||||
|
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||||
|
for arg do
|
||||||
|
if
|
||||||
|
case $arg in #(
|
||||||
|
-*) false ;; # don't mess with options #(
|
||||||
|
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||||
|
[ -e "$t" ] ;; #(
|
||||||
|
*) false ;;
|
||||||
|
esac
|
||||||
|
then
|
||||||
|
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||||
|
fi
|
||||||
|
# Roll the args list around exactly as many times as the number of
|
||||||
|
# args, so each arg winds up back in the position where it started, but
|
||||||
|
# possibly modified.
|
||||||
|
#
|
||||||
|
# NB: a `for` loop captures its iteration list before it begins, so
|
||||||
|
# changing the positional parameters here affects neither the number of
|
||||||
|
# iterations, nor the values presented in `arg`.
|
||||||
|
shift # remove old arg
|
||||||
|
set -- "$@" "$arg" # push replacement arg
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command;
|
||||||
|
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||||
|
# shell script including quotes and variable substitutions, so put them in
|
||||||
|
# double quotes to make sure that they get re-expanded; and
|
||||||
|
# * put everything else in single quotes, so that it's not re-expanded.
|
||||||
|
|
||||||
|
set -- \
|
||||||
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
-classpath "$CLASSPATH" \
|
||||||
|
org.gradle.wrapper.GradleWrapperMain \
|
||||||
|
"$@"
|
||||||
|
|
||||||
|
# Stop when "xargs" is not available.
|
||||||
|
if ! command -v xargs >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "xargs is not available"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use "xargs" to parse quoted args.
|
||||||
|
#
|
||||||
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
|
#
|
||||||
|
# In Bash we could simply go:
|
||||||
|
#
|
||||||
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
|
# set -- "${ARGS[@]}" "$@"
|
||||||
|
#
|
||||||
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
|
# the whole thing up as a single "set" statement.
|
||||||
|
#
|
||||||
|
# This will of course break if any of these variables contains a newline or
|
||||||
|
# an unmatched quote.
|
||||||
|
#
|
||||||
|
|
||||||
|
eval "set -- $(
|
||||||
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
|
xargs -n1 |
|
||||||
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
|
tr '\n' ' '
|
||||||
|
)" '"$@"'
|
||||||
|
|
||||||
|
exec "$JAVACMD" "$@"
|
91
gradlew.bat
vendored
Normal file
91
gradlew.bat
vendored
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
@rem
|
||||||
|
@rem Copyright 2015 the original author or authors.
|
||||||
|
@rem
|
||||||
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
@rem you may not use this file except in compliance with the License.
|
||||||
|
@rem You may obtain a copy of the License at
|
||||||
|
@rem
|
||||||
|
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@rem
|
||||||
|
@rem Unless required by applicable law or agreed to in writing, software
|
||||||
|
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
@rem See the License for the specific language governing permissions and
|
||||||
|
@rem limitations under the License.
|
||||||
|
@rem
|
||||||
|
|
||||||
|
@if "%DEBUG%"=="" @echo off
|
||||||
|
@rem ##########################################################################
|
||||||
|
@rem
|
||||||
|
@rem Gradle startup script for Windows
|
||||||
|
@rem
|
||||||
|
@rem ##########################################################################
|
||||||
|
|
||||||
|
@rem Set local scope for the variables with windows NT shell
|
||||||
|
if "%OS%"=="Windows_NT" setlocal
|
||||||
|
|
||||||
|
set DIRNAME=%~dp0
|
||||||
|
if "%DIRNAME%"=="" set DIRNAME=.
|
||||||
|
set APP_BASE_NAME=%~n0
|
||||||
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
|
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||||
|
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||||
|
|
||||||
|
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||||
|
|
||||||
|
@rem Find java.exe
|
||||||
|
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||||
|
|
||||||
|
set JAVA_EXE=java.exe
|
||||||
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
|
if %ERRORLEVEL% equ 0 goto execute
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
echo.
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
echo location of your Java installation.
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:findJavaFromJavaHome
|
||||||
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||||
|
echo.
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
echo location of your Java installation.
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:execute
|
||||||
|
@rem Setup the command line
|
||||||
|
|
||||||
|
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||||
|
|
||||||
|
|
||||||
|
@rem Execute Gradle
|
||||||
|
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||||
|
|
||||||
|
:end
|
||||||
|
@rem End local scope for the variables with windows NT shell
|
||||||
|
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||||
|
|
||||||
|
:fail
|
||||||
|
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||||
|
rem the _cmd.exe /c_ return code!
|
||||||
|
set EXIT_CODE=%ERRORLEVEL%
|
||||||
|
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||||
|
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||||
|
exit /b %EXIT_CODE%
|
||||||
|
|
||||||
|
:mainEnd
|
||||||
|
if "%OS%"=="Windows_NT" endlocal
|
||||||
|
|
||||||
|
:omega
|
1
settings.gradle
Normal file
1
settings.gradle
Normal file
@ -0,0 +1 @@
|
|||||||
|
rootProject.name = 'springip'
|
13
src/main/java/com/example/springip/SpringipApplication.java
Normal file
13
src/main/java/com/example/springip/SpringipApplication.java
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
package com.example.springip;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class SpringipApplication {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SpringApplication.run(SpringipApplication.class, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
21
src/main/java/com/example/springip/WebConfiguration.java
Normal file
21
src/main/java/com/example/springip/WebConfiguration.java
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
package com.example.springip;
|
||||||
|
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 addViewControllers(ViewControllerRegistry registry) {
|
||||||
|
WebMvcConfigurer.super.addViewControllers(registry);
|
||||||
|
registry.addViewController("login");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addCorsMappings(CorsRegistry registry) {
|
||||||
|
registry.addMapping("/**").allowedMethods("*");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,35 @@
|
|||||||
|
package com.example.springip.lab1.controllers;
|
||||||
|
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
public class TestController {
|
||||||
|
@GetMapping("/getRandomNumber")
|
||||||
|
public String getRandom() {
|
||||||
|
Random random = new Random();
|
||||||
|
|
||||||
|
return "Your number = " + random.nextInt(0,100);
|
||||||
|
}
|
||||||
|
|
||||||
|
// @GetMapping("/sum")
|
||||||
|
// public String getSum(@RequestParam(name = "val1", defaultValue = "1") int val1,
|
||||||
|
// @RequestParam(name="val2",defaultValue = "2") int val2) {
|
||||||
|
// return "Your summa = " + (val1 + val2);
|
||||||
|
// }
|
||||||
|
|
||||||
|
@GetMapping("/upperCase")
|
||||||
|
public String toUpperCase(String word) {
|
||||||
|
if (word != null)
|
||||||
|
return word.toUpperCase();
|
||||||
|
return "Incorrect word";
|
||||||
|
}
|
||||||
|
|
||||||
|
// @GetMapping("/length")
|
||||||
|
// public String length(String name) {
|
||||||
|
// return "Length = " + name.length();
|
||||||
|
// }
|
||||||
|
}
|
@ -0,0 +1,42 @@
|
|||||||
|
package com.example.springip.lab2.controllers;
|
||||||
|
|
||||||
|
import com.example.springip.lab2.service.OperationService;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
public class OperationController {
|
||||||
|
private final OperationService operationService;
|
||||||
|
|
||||||
|
public OperationController( OperationService operationService) {
|
||||||
|
this.operationService = operationService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/sum")
|
||||||
|
public Object sum(@RequestParam String val1, @RequestParam String val2, @RequestParam String type) {
|
||||||
|
|
||||||
|
return (Object) operationService.sum(val1, val2, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/mul")
|
||||||
|
public Object mul(@RequestParam String val1, @RequestParam Integer val2, @RequestParam String type) {
|
||||||
|
|
||||||
|
return (Object) operationService.mul(val1, val2, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/length")
|
||||||
|
public Object length(@RequestParam String val1, @RequestParam String type) {
|
||||||
|
|
||||||
|
return (Object) operationService.length(val1, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/startsWith")
|
||||||
|
public Object startsWith(@RequestParam String val1, @RequestParam String val2, @RequestParam String type) {
|
||||||
|
|
||||||
|
return (Object) operationService.startsWith(val1, val2, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,8 @@
|
|||||||
|
package com.example.springip.lab2.domains;
|
||||||
|
|
||||||
|
public interface OperationInterface<T> {
|
||||||
|
T sum(T o,T o2);
|
||||||
|
T mul(T o, int num);
|
||||||
|
int length(T o);
|
||||||
|
boolean startsWith(T o, T symb);
|
||||||
|
}
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.example.springip.lab2.domains;
|
||||||
|
|
||||||
|
import com.example.springip.lab2.domains.OperationInterface;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component(value = "num")
|
||||||
|
public class OperationNumImpl implements OperationInterface<Integer> {
|
||||||
|
@Override
|
||||||
|
public Integer sum(Integer o, Integer o2) {
|
||||||
|
return o + o2;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Integer mul(Integer o, int num) {
|
||||||
|
return o * num;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int length(Integer o) {
|
||||||
|
int n = o;
|
||||||
|
int k = 0;
|
||||||
|
while (n % 10 != 0) {
|
||||||
|
n /= 10;
|
||||||
|
k++;
|
||||||
|
}
|
||||||
|
return k;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean startsWith(Integer o, Integer symb) {
|
||||||
|
return o % (Math.pow(10,length(symb))) == symb;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,31 @@
|
|||||||
|
package com.example.springip.lab2.domains;
|
||||||
|
|
||||||
|
import com.example.springip.lab2.domains.OperationInterface;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component(value = "str")
|
||||||
|
public class OperationStringImpl implements OperationInterface<String> {
|
||||||
|
@Override
|
||||||
|
public String sum(String o, String o2) {
|
||||||
|
return o+o2;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String mul(String o, int num) {
|
||||||
|
StringBuilder res = new StringBuilder();
|
||||||
|
for (int i = 0; i < num; i++) {
|
||||||
|
res.append(o);
|
||||||
|
}
|
||||||
|
return res.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int length(String o) {
|
||||||
|
return o.length();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean startsWith(String o, String symb) {
|
||||||
|
return o.startsWith(symb);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,48 @@
|
|||||||
|
package com.example.springip.lab2.service;
|
||||||
|
|
||||||
|
import com.example.springip.lab2.domains.OperationInterface;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class OperationService {
|
||||||
|
private final ApplicationContext applicationContext;
|
||||||
|
|
||||||
|
public OperationService(ApplicationContext applicationContext) {
|
||||||
|
this.applicationContext = applicationContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object sum(Object o, Object o2, String type){
|
||||||
|
|
||||||
|
OperationInterface operationInterface = (OperationInterface) applicationContext.getBean(type);
|
||||||
|
if (type.equals("num"))
|
||||||
|
return operationInterface.sum(Integer.parseInt(o.toString()),Integer.parseInt(o2.toString()));
|
||||||
|
return operationInterface.sum(o, o2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object mul(Object o, Object o2, String type){
|
||||||
|
|
||||||
|
OperationInterface operationInterface = (OperationInterface) applicationContext.getBean(type);
|
||||||
|
if (type.equals("num"))
|
||||||
|
return operationInterface.mul(Integer.parseInt(o.toString()), Integer.parseInt(o2.toString()));
|
||||||
|
return operationInterface.mul(o, Integer.parseInt(o2.toString()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object length(Object o, String type){
|
||||||
|
|
||||||
|
OperationInterface operationInterface = (OperationInterface) applicationContext.getBean(type);
|
||||||
|
if (type.equals("num"))
|
||||||
|
return operationInterface.length(Integer.parseInt(o.toString()));
|
||||||
|
return operationInterface.length(o);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object startsWith(Object o, Object o2, String type){
|
||||||
|
|
||||||
|
OperationInterface operationInterface = (OperationInterface) applicationContext.getBean(type);
|
||||||
|
if (type.equals("num"))
|
||||||
|
return operationInterface.startsWith(Integer.parseInt(o.toString()), Integer.parseInt(o2.toString()));
|
||||||
|
return operationInterface.startsWith(o,o2);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.example.springip.lab3.configuration;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class PasswordEncoderConfiguration {
|
||||||
|
@Bean
|
||||||
|
public PasswordEncoder createPasswordEncoder() {
|
||||||
|
return new BCryptPasswordEncoder();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,87 @@
|
|||||||
|
package com.example.springip.lab3.configuration;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.configuration.jwt.JwtFilter;
|
||||||
|
import com.example.springip.lab3.user.controller.UserController;
|
||||||
|
import com.example.springip.lab3.user.controller.UserSignupMvcController;
|
||||||
|
import com.example.springip.lab3.user.model.UserRole;
|
||||||
|
import com.example.springip.lab3.user.service.UserService;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.core.annotation.Order;
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
|
||||||
|
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||||
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||||
|
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableWebSecurity
|
||||||
|
@EnableMethodSecurity(securedEnabled = true)
|
||||||
|
public class SecurityConfiguration {
|
||||||
|
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
|
||||||
|
private static final String LOGIN_URL = "/login";
|
||||||
|
public static final String SPA_URL_MASK = "/{path:[^\\.]*}";
|
||||||
|
private UserService userService;
|
||||||
|
private JwtFilter jwtFilter;
|
||||||
|
|
||||||
|
public SecurityConfiguration(UserService userService) {
|
||||||
|
this.userService = userService;
|
||||||
|
this.jwtFilter = new JwtFilter(userService);
|
||||||
|
createAdminOnStartup();
|
||||||
|
createTestUsersOnStartup();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createAdminOnStartup() {
|
||||||
|
final String admin = "admin";
|
||||||
|
if (userService.findByLogin(admin) == null) {
|
||||||
|
log.info("Admin user successfully created");
|
||||||
|
userService.createUser(admin, admin, admin, UserRole.ADMIN);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createTestUsersOnStartup() {
|
||||||
|
final String[] userNames = {"user1", "user2", "user3"};
|
||||||
|
for (String user : userNames) {
|
||||||
|
if (userService.findByLogin(user) == null) {
|
||||||
|
log.info("User %s successfully created".formatted(user));
|
||||||
|
userService.createUser(user, user, user, UserRole.USER);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
|
||||||
|
http.cors()
|
||||||
|
.and()
|
||||||
|
.csrf().disable()
|
||||||
|
.authorizeHttpRequests((a) -> a
|
||||||
|
.requestMatchers(HttpMethod.DELETE, "/api/**").hasRole("ADMIN")
|
||||||
|
.requestMatchers(HttpMethod.PUT, "/api/**").hasRole("ADMIN")
|
||||||
|
.requestMatchers(HttpMethod.POST, "/api/**").hasRole("ADMIN")
|
||||||
|
.requestMatchers("/api/**").authenticated()
|
||||||
|
.requestMatchers(HttpMethod.POST, UserController.URL_LOGIN).permitAll())
|
||||||
|
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||||
|
.anonymous().and().authorizeHttpRequests((a) ->
|
||||||
|
a.requestMatchers(LOGIN_URL, UserSignupMvcController.SIGNUP_URL, "/h2-console/**")
|
||||||
|
.permitAll().requestMatchers("/users").hasRole("ADMIN").anyRequest().authenticated())
|
||||||
|
.formLogin()
|
||||||
|
.loginPage(LOGIN_URL).permitAll()
|
||||||
|
.and()
|
||||||
|
.logout().permitAll()
|
||||||
|
.logoutSuccessUrl("/login")
|
||||||
|
.and()
|
||||||
|
.userDetailsService(userService);
|
||||||
|
return http.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public WebSecurityCustomizer webSecurityCustomizer() {
|
||||||
|
return (web) -> web.ignoring().requestMatchers("/css/**", "/js/**", "/templates/**", "/webjars/**", "/styles/**");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,11 @@
|
|||||||
|
package com.example.springip.lab3.configuration.jwt;
|
||||||
|
|
||||||
|
public class JwtException extends RuntimeException {
|
||||||
|
public JwtException(Throwable throwable) {
|
||||||
|
super(throwable);
|
||||||
|
}
|
||||||
|
|
||||||
|
public JwtException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,93 @@
|
|||||||
|
package com.example.springip.lab3.configuration.jwt;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.user.service.UserService;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.ServletRequest;
|
||||||
|
import jakarta.servlet.ServletResponse;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||||
|
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.filter.GenericFilterBean;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class JwtFilter extends AbstractPreAuthenticatedProcessingFilter {
|
||||||
|
private static final String AUTHORIZATION = "Authorization";
|
||||||
|
public static final String TOKEN_BEGIN_STR = "Bearer ";
|
||||||
|
|
||||||
|
private final UserService userService;
|
||||||
|
|
||||||
|
public JwtFilter(UserService userService) {
|
||||||
|
this.userService = userService;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getTokenFromRequest(HttpServletRequest request) {
|
||||||
|
String bearer = request.getHeader(AUTHORIZATION);
|
||||||
|
if (StringUtils.hasText(bearer) && bearer.startsWith(TOKEN_BEGIN_STR)) {
|
||||||
|
return bearer.substring(TOKEN_BEGIN_STR.length());
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void raiseException(ServletResponse response, int status, String message) throws IOException {
|
||||||
|
if (response instanceof final HttpServletResponse httpResponse) {
|
||||||
|
httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||||
|
httpResponse.setStatus(status);
|
||||||
|
final byte[] body = new ObjectMapper().writeValueAsBytes(message);
|
||||||
|
response.getOutputStream().write(body);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void doFilter(ServletRequest request,
|
||||||
|
ServletResponse response,
|
||||||
|
FilterChain chain) throws IOException, ServletException {
|
||||||
|
if (request instanceof final HttpServletRequest httpRequest) {
|
||||||
|
final String token = getTokenFromRequest(httpRequest);
|
||||||
|
if (StringUtils.hasText(token)) {
|
||||||
|
try {
|
||||||
|
final UserDetails user = userService.loadUserByToken(token);
|
||||||
|
final UsernamePasswordAuthenticationToken auth =
|
||||||
|
new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
|
||||||
|
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||||
|
} catch (JwtException e) {
|
||||||
|
raiseException(response, HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
|
||||||
|
return;
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
raiseException(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
|
||||||
|
String.format("Internal error: %s", e.getMessage()));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
HttpServletRequest httpRequest = (HttpServletRequest) request;
|
||||||
|
if (httpRequest.getRequestURI().startsWith("/api/")) {
|
||||||
|
// Для URL, начинающихся с /api/, выполняем проверку наличия токена
|
||||||
|
super.doFilter(request, response, chain);
|
||||||
|
} else {
|
||||||
|
// Для остальных URL выполняем авторизацию
|
||||||
|
chain.doFilter(request, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
|
||||||
|
String token = getTokenFromRequest(request);
|
||||||
|
// Возвращаем токен как принципала
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
|
||||||
|
return new WebAuthenticationDetailsSource().buildDetails(request);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,27 @@
|
|||||||
|
package com.example.springip.lab3.configuration.jwt;
|
||||||
|
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@ConfigurationProperties(prefix = "jwt", ignoreInvalidFields = true)
|
||||||
|
public class JwtProperties {
|
||||||
|
private String devToken = "";
|
||||||
|
private Boolean isDev = true;
|
||||||
|
|
||||||
|
public String getDevToken() {
|
||||||
|
return devToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDevToken(String devToken) {
|
||||||
|
this.devToken = devToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean isDev() {
|
||||||
|
return isDev;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDev(Boolean dev) {
|
||||||
|
isDev = dev;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,107 @@
|
|||||||
|
package com.example.springip.lab3.configuration.jwt;
|
||||||
|
|
||||||
|
import com.auth0.jwt.JWT;
|
||||||
|
import com.auth0.jwt.algorithms.Algorithm;
|
||||||
|
import com.auth0.jwt.exceptions.JWTVerificationException;
|
||||||
|
import com.auth0.jwt.interfaces.DecodedJWT;
|
||||||
|
import com.auth0.jwt.interfaces.JWTVerifier;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
//
|
||||||
|
//@Component
|
||||||
|
//public class JwtProvider {
|
||||||
|
// private final static Logger LOG = LoggerFactory.getLogger(JwtProvider.class);
|
||||||
|
//
|
||||||
|
// private final static byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
|
||||||
|
// private final static String ISSUER = "auth0";
|
||||||
|
//
|
||||||
|
// private final Algorithm algorithm;
|
||||||
|
// private final JWTVerifier verifier;
|
||||||
|
//
|
||||||
|
// public JwtProvider(JwtProperties jwtProperties) {
|
||||||
|
// if (!jwtProperties.isDev()) {
|
||||||
|
// LOG.info("Generate new JWT key for prod");
|
||||||
|
// try {
|
||||||
|
// final MessageDigest salt = MessageDigest.getInstance("SHA-256");
|
||||||
|
// salt.update(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));
|
||||||
|
// LOG.info("Use generated JWT key for prod \n{}", bytesToHex(salt.digest()));
|
||||||
|
// algorithm = Algorithm.HMAC256(bytesToHex(salt.digest()));
|
||||||
|
// } catch (NoSuchAlgorithmException e) {
|
||||||
|
// throw new JwtException(e);
|
||||||
|
// }
|
||||||
|
// } else {
|
||||||
|
// LOG.info("Use default JWT key for dev \n{}", jwtProperties.getDevToken());
|
||||||
|
// algorithm = Algorithm.HMAC256(jwtProperties.getDevToken());
|
||||||
|
// }
|
||||||
|
// verifier = JWT.require(algorithm)
|
||||||
|
// .withIssuer(ISSUER)
|
||||||
|
// .build();
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// private static String bytesToHex(byte[] bytes) {
|
||||||
|
// byte[] hexChars = new byte[bytes.length * 2];
|
||||||
|
// for (int j = 0; j < bytes.length; j++) {
|
||||||
|
// int v = bytes[j] & 0xFF;
|
||||||
|
// hexChars[j * 2] = HEX_ARRAY[v >>> 4];
|
||||||
|
// hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
|
||||||
|
// }
|
||||||
|
// return new String(hexChars, StandardCharsets.UTF_8);
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// public String generateToken(String login) {
|
||||||
|
// final Date issueDate = Date.from(LocalDate.now()
|
||||||
|
// .atStartOfDay(ZoneId.systemDefault())
|
||||||
|
// .toInstant());
|
||||||
|
// final Date expireDate = Date.from(LocalDate.now()
|
||||||
|
// .plusDays(15)
|
||||||
|
// .atStartOfDay(ZoneId.systemDefault())
|
||||||
|
// .toInstant());
|
||||||
|
// return JWT.create()
|
||||||
|
// .withIssuer(ISSUER)
|
||||||
|
// .withIssuedAt(issueDate)
|
||||||
|
// .withExpiresAt(expireDate)
|
||||||
|
// .withSubject(login)
|
||||||
|
// .sign(algorithm);
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// private DecodedJWT validateToken(String token) {
|
||||||
|
// try {
|
||||||
|
// return verifier.verify(token);
|
||||||
|
// } catch (JWTVerificationException e) {
|
||||||
|
// throw new JwtException(String.format("Token verification error: %s", e.getMessage()));
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// public boolean isTokenValid(String token) {
|
||||||
|
// if (!StringUtils.hasText(token)) {
|
||||||
|
// return false;
|
||||||
|
// }
|
||||||
|
// try {
|
||||||
|
// validateToken(token);
|
||||||
|
// return true;
|
||||||
|
// } catch (JwtException e) {
|
||||||
|
// LOG.error(e.getMessage());
|
||||||
|
// return false;
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// public Optional<String> getLoginFromToken(String token) {
|
||||||
|
// try {
|
||||||
|
// return Optional.ofNullable(validateToken(token).getSubject());
|
||||||
|
// } catch (JwtException e) {
|
||||||
|
// LOG.error(e.getMessage());
|
||||||
|
// return Optional.empty();
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//}
|
@ -0,0 +1,50 @@
|
|||||||
|
package com.example.springip.lab3.configuration.jwt;
|
||||||
|
import io.jsonwebtoken.Claims;
|
||||||
|
import io.jsonwebtoken.JwtBuilder;
|
||||||
|
import io.jsonwebtoken.Jwts;
|
||||||
|
import io.jsonwebtoken.SignatureAlgorithm;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.util.Calendar;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.TimeZone;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class JwtsProvider {
|
||||||
|
|
||||||
|
@Value("jwt.secret")
|
||||||
|
private String secret;
|
||||||
|
|
||||||
|
public String generateToken(String login, String role) {
|
||||||
|
Date date = Date.from(LocalDate.now().plusDays(15).atStartOfDay(ZoneId.systemDefault()).toInstant());
|
||||||
|
|
||||||
|
JwtBuilder builder = Jwts.builder()
|
||||||
|
.setSubject(login)
|
||||||
|
.setExpiration(date)
|
||||||
|
.signWith(SignatureAlgorithm.HS512, secret);
|
||||||
|
Claims claims = Jwts.claims();
|
||||||
|
claims.put("role", role);
|
||||||
|
builder.addClaims(claims);
|
||||||
|
return builder.compact();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean validateToken(String token) {
|
||||||
|
try {
|
||||||
|
Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
|
||||||
|
return true;
|
||||||
|
} catch (Exception e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLogin(String token) {
|
||||||
|
return Jwts.parser()
|
||||||
|
.setSigningKey(secret)
|
||||||
|
.parseClaimsJws(token)
|
||||||
|
.getBody()
|
||||||
|
.getSubject();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,71 @@
|
|||||||
|
package com.example.springip.lab3.controller;
|
||||||
|
|
||||||
|
import com.example.springip.WebConfiguration;
|
||||||
|
import com.example.springip.lab3.dto.CompanyDto;
|
||||||
|
import com.example.springip.lab3.dto.EmployeeDto;
|
||||||
|
import com.example.springip.lab3.models.Employee;
|
||||||
|
import com.example.springip.lab3.service.CompanyService;
|
||||||
|
import com.example.springip.lab3.service.EmployeeService;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import org.springframework.validation.annotation.Validated;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping(WebConfiguration.REST_API + "/company")
|
||||||
|
public class CompanyController {
|
||||||
|
private final CompanyService companyService;
|
||||||
|
private final EmployeeService employeeService;
|
||||||
|
|
||||||
|
public CompanyController(CompanyService companyService, EmployeeService employeeService) {
|
||||||
|
this.companyService = companyService;
|
||||||
|
this.employeeService = employeeService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public CompanyDto getCompany(@PathVariable long id) {
|
||||||
|
return new CompanyDto(companyService.findCompany(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}/employees")
|
||||||
|
public List<EmployeeDto> getCompanyEmployees(@PathVariable long id) {
|
||||||
|
return companyService.findCompany(id).getEmployees().stream().map(EmployeeDto::new).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public List<CompanyDto> getAllCompanies() {
|
||||||
|
return companyService.findAllCompanies().stream()
|
||||||
|
.map(CompanyDto::new)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public CompanyDto create(@RequestBody @Valid CompanyDto companyDto) {
|
||||||
|
return new CompanyDto(companyService.addCompany(companyDto.getName()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
public CompanyDto update(@PathVariable Long id,
|
||||||
|
@RequestBody @Valid CompanyDto companyDto) {
|
||||||
|
return new CompanyDto(companyService.updateCompany(id, companyDto.getName()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public CompanyDto delete(@PathVariable Long id) {
|
||||||
|
return new CompanyDto(companyService.deleteCompany(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{id}/hire")
|
||||||
|
public EmployeeDto hire(@PathVariable Long id, @RequestParam Long employeeId) {
|
||||||
|
Employee e = employeeService.findEmployee(employeeId);
|
||||||
|
return new EmployeeDto(companyService.addNewEmployee(id, e));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{id}/dismiss")
|
||||||
|
public EmployeeDto dismiss(@PathVariable Long id, @RequestParam Long employeeId) {
|
||||||
|
Employee e = employeeService.findEmployee(employeeId);
|
||||||
|
return new EmployeeDto(companyService.deleteEmployee(id, e));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,94 @@
|
|||||||
|
package com.example.springip.lab3.controller;
|
||||||
|
|
||||||
|
import com.example.springip.WebConfiguration;
|
||||||
|
import com.example.springip.lab3.dto.CompanyDto;
|
||||||
|
import com.example.springip.lab3.dto.EmployeeDto;
|
||||||
|
import com.example.springip.lab3.dto.PositionDto;
|
||||||
|
import com.example.springip.lab3.models.Employee;
|
||||||
|
import com.example.springip.lab3.models.Position;
|
||||||
|
import com.example.springip.lab3.service.EmployeeService;
|
||||||
|
import com.example.springip.lab3.service.PositionService;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping(WebConfiguration.REST_API + "/employee")
|
||||||
|
public class EmployeeController {
|
||||||
|
private final EmployeeService employeeService;
|
||||||
|
private final PositionService positionService;
|
||||||
|
|
||||||
|
public EmployeeController(EmployeeService employeeService, PositionService positionService) {
|
||||||
|
this.employeeService = employeeService;
|
||||||
|
this.positionService = positionService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public EmployeeDto getEmployee(@PathVariable long id) {
|
||||||
|
return new EmployeeDto(employeeService.findEmployee(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public List<EmployeeDto> getAllEmployees() {
|
||||||
|
return employeeService.findAllEmployees().stream()
|
||||||
|
.map(EmployeeDto::new)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public EmployeeDto createEmployee( @RequestBody @Valid EmployeeDto employeeDto) {
|
||||||
|
return new EmployeeDto(employeeService.addEmployee(
|
||||||
|
employeeDto.getSurname(),
|
||||||
|
employeeDto.getName(),
|
||||||
|
employeeDto.getPhoneNumber()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
public EmployeeDto updateEmployee(@PathVariable Long id,
|
||||||
|
@RequestBody @Valid EmployeeDto employeeDto) {
|
||||||
|
return new EmployeeDto(employeeService.updateEmployee(id, employeeDto.getSurname(),
|
||||||
|
employeeDto.getName(), employeeDto.getPhoneNumber()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public EmployeeDto deleteEmployee(@PathVariable Long id) {
|
||||||
|
return new EmployeeDto(employeeService.deleteEmployee(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{id}/addPos")
|
||||||
|
public EmployeeDto addPosition(@PathVariable Long id,
|
||||||
|
@RequestParam("position") Long position) {
|
||||||
|
Position p = positionService.findPosition(position);
|
||||||
|
if (p == null)
|
||||||
|
return null;
|
||||||
|
return new EmployeeDto(employeeService.addPosition(id, p));
|
||||||
|
}
|
||||||
|
@PutMapping("/{id}/delPos")
|
||||||
|
public EmployeeDto delPosition(@PathVariable Long id,
|
||||||
|
@RequestParam("position") Long position) {
|
||||||
|
Position p = positionService.findPosition(position);
|
||||||
|
if (p == null)
|
||||||
|
return null;
|
||||||
|
return new EmployeeDto(employeeService.deletePosition(id, p));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/free")
|
||||||
|
public List<EmployeeDto> getAllFreeEmployees() {
|
||||||
|
return employeeService.findAllFreeEmployees().stream()
|
||||||
|
.map(EmployeeDto::new)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/position")
|
||||||
|
public List<EmployeeDto> getEmployeesByPosition(@RequestParam Long pos) {
|
||||||
|
Position p = positionService.findPosition(pos);
|
||||||
|
if (p == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return employeeService.getEmployeesByPosition(p).stream()
|
||||||
|
.map(EmployeeDto::new)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,48 @@
|
|||||||
|
package com.example.springip.lab3.controller;
|
||||||
|
|
||||||
|
import com.example.springip.WebConfiguration;
|
||||||
|
import com.example.springip.lab3.dto.CompanyDto;
|
||||||
|
import com.example.springip.lab3.dto.PositionDto;
|
||||||
|
import com.example.springip.lab3.service.PositionService;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping(WebConfiguration.REST_API + "/position")
|
||||||
|
public class PositionController {
|
||||||
|
private final PositionService positionService;
|
||||||
|
|
||||||
|
public PositionController(PositionService positionService) {
|
||||||
|
this.positionService = positionService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public PositionDto getCompany(@PathVariable long id) {
|
||||||
|
return new PositionDto(positionService.findPosition(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public List<PositionDto> getAllCompanies() {
|
||||||
|
return positionService.findAllPositions().stream()
|
||||||
|
.map(PositionDto::new)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public PositionDto create(@RequestBody @Valid PositionDto positionDto) {
|
||||||
|
return new PositionDto(positionService.addPosition(positionDto.getName()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
public PositionDto update(@PathVariable Long id,
|
||||||
|
@RequestBody @Valid PositionDto positionDto) {
|
||||||
|
return new PositionDto(positionService.updatePosition(id, positionDto.getName()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public PositionDto delete(@PathVariable Long id) {
|
||||||
|
return new PositionDto(positionService.deletePosition(id));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.example.springip.lab3.dao;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.models.Company;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public interface CompanyRepository extends JpaRepository<Company, Long> {
|
||||||
|
Optional<Company> findById(Long id);
|
||||||
|
}
|
@ -0,0 +1,15 @@
|
|||||||
|
package com.example.springip.lab3.dao;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.models.Employee;
|
||||||
|
import com.example.springip.lab3.models.Position;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
|
||||||
|
Optional<Employee> findById(Long id);
|
||||||
|
List<Employee> findByPositions_Id(Long p_id);
|
||||||
|
List<Employee> findByCompanyIsNull();
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.example.springip.lab3.dao;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.models.Position;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public interface PositionRepository extends JpaRepository<Position, Long> {
|
||||||
|
Optional<Position> findById(Long id);
|
||||||
|
}
|
43
src/main/java/com/example/springip/lab3/dto/CompanyDto.java
Normal file
43
src/main/java/com/example/springip/lab3/dto/CompanyDto.java
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
package com.example.springip.lab3.dto;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.models.Company;
|
||||||
|
import com.example.springip.lab3.models.Employee;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class CompanyDto {
|
||||||
|
private Long Id;
|
||||||
|
private String name;
|
||||||
|
private List<EmployeeDto> employees;
|
||||||
|
|
||||||
|
public CompanyDto(Company company) {
|
||||||
|
Id = company.getId();
|
||||||
|
this.name = company.getName();
|
||||||
|
this.employees = company.getEmployees().stream().map(EmployeeDto::new).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompanyDto() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||||
|
public Long getId() {
|
||||||
|
return Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<EmployeeDto> getEmployees() {
|
||||||
|
return employees;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.example.springip.lab3.dto;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.models.Company;
|
||||||
|
|
||||||
|
public class CompanyWithoutEmpDto {
|
||||||
|
private final Long Id;
|
||||||
|
private final String name;
|
||||||
|
|
||||||
|
public CompanyWithoutEmpDto(Company company) {
|
||||||
|
this.Id = company.getId();
|
||||||
|
this.name = company.getName();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
}
|
66
src/main/java/com/example/springip/lab3/dto/EmployeeDto.java
Normal file
66
src/main/java/com/example/springip/lab3/dto/EmployeeDto.java
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
package com.example.springip.lab3.dto;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.models.Company;
|
||||||
|
import com.example.springip.lab3.models.Employee;
|
||||||
|
import com.example.springip.lab3.models.Position;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
public class EmployeeDto {
|
||||||
|
private Long Id;
|
||||||
|
private String name;
|
||||||
|
private String phoneNumber;
|
||||||
|
private String surname;
|
||||||
|
private List<PositionDto> positions;
|
||||||
|
|
||||||
|
private CompanyWithoutEmpDto company;
|
||||||
|
|
||||||
|
public EmployeeDto(Employee employee) {
|
||||||
|
Id = employee.getId();
|
||||||
|
this.name = employee.getName();
|
||||||
|
this.phoneNumber = employee.getPhoneNumber();
|
||||||
|
this.surname = employee.getSurname();
|
||||||
|
this.positions = employee.getPositions().stream().map(PositionDto::new).toList();
|
||||||
|
this.company = employee.getCompany() != null ? new CompanyWithoutEmpDto(employee.getCompany()) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public EmployeeDto() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPhoneNumber() {
|
||||||
|
return phoneNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getSurname() {
|
||||||
|
return surname;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<PositionDto> getPositions() {
|
||||||
|
return positions;
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompanyWithoutEmpDto getCompany() {
|
||||||
|
return company;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPhoneNumber(String phoneNumber) {
|
||||||
|
this.phoneNumber = phoneNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSurname(String surname) {
|
||||||
|
this.surname = surname;
|
||||||
|
}
|
||||||
|
}
|
28
src/main/java/com/example/springip/lab3/dto/PositionDto.java
Normal file
28
src/main/java/com/example/springip/lab3/dto/PositionDto.java
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
package com.example.springip.lab3.dto;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.models.Position;
|
||||||
|
|
||||||
|
public class PositionDto {
|
||||||
|
private Long Id;
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
public PositionDto(Position position) {
|
||||||
|
Id = position.getId();
|
||||||
|
this.name = position.getName();
|
||||||
|
}
|
||||||
|
|
||||||
|
public PositionDto() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
}
|
82
src/main/java/com/example/springip/lab3/models/Company.java
Normal file
82
src/main/java/com/example/springip/lab3/models/Company.java
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
package com.example.springip.lab3.models;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonRootName;
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class Company {
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||||
|
private Long Id;
|
||||||
|
@Column(unique = true)
|
||||||
|
private String name;
|
||||||
|
@OneToMany(mappedBy = "company", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
|
||||||
|
private Set<Employee> employees = new HashSet<>();
|
||||||
|
|
||||||
|
public Company(String name, Set<Employee> employees) {
|
||||||
|
this.name = name;
|
||||||
|
this.employees = employees;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Company(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Company() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addNewEmployee(Employee employee) {
|
||||||
|
employees.add(employee);
|
||||||
|
employee.setCompany(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void deleteEmployee(Employee employee) {
|
||||||
|
employees.remove(employee);
|
||||||
|
employee.deleteCompany();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set<Employee> getEmployees() {
|
||||||
|
return employees;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmployees(Set<Employee> employees) {
|
||||||
|
this.employees = employees;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) return true;
|
||||||
|
if (o == null || getClass() != o.getClass()) return false;
|
||||||
|
Company company = (Company) o;
|
||||||
|
return Objects.equals(Id, company.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Company{" +
|
||||||
|
"Id=" + Id +
|
||||||
|
", name='" + name + '\'' +
|
||||||
|
", employees=" + employees +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
|
}
|
111
src/main/java/com/example/springip/lab3/models/Employee.java
Normal file
111
src/main/java/com/example/springip/lab3/models/Employee.java
Normal file
@ -0,0 +1,111 @@
|
|||||||
|
package com.example.springip.lab3.models;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class Employee {
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
private String phoneNumber;
|
||||||
|
private String name;
|
||||||
|
private String surname;
|
||||||
|
|
||||||
|
@ManyToOne(fetch = FetchType.EAGER)
|
||||||
|
private Company company;
|
||||||
|
|
||||||
|
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
|
||||||
|
private Set<Position> positions = new HashSet<>();
|
||||||
|
|
||||||
|
|
||||||
|
public Employee(String surname, String name, String phoneNumber) {
|
||||||
|
this.phoneNumber = phoneNumber;
|
||||||
|
this.name = name;
|
||||||
|
this.surname = surname;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Employee() {
|
||||||
|
}
|
||||||
|
|
||||||
|
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<Position> getPositions() {
|
||||||
|
return positions.stream().toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Company getCompany() {
|
||||||
|
return company;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCompany(Company company) {
|
||||||
|
this.company = company;
|
||||||
|
if (!company.getEmployees().contains(this)) {
|
||||||
|
company.addNewEmployee(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void deleteCompany() {
|
||||||
|
if (company.getEmployees().contains(this)) {
|
||||||
|
company.deleteEmployee(this);
|
||||||
|
}
|
||||||
|
this.company = null;
|
||||||
|
this.positions.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addNewPosition(Position p) {
|
||||||
|
positions.add(p);
|
||||||
|
if (!p.getEmployees().contains(this)) {
|
||||||
|
p.addNewEmployee(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public void removePosition(Position p) {
|
||||||
|
positions.remove(p);
|
||||||
|
if (p.getEmployees().contains(this)) {
|
||||||
|
p.deleteEmployee(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) return true;
|
||||||
|
if (o == null || getClass() != o.getClass()) return false;
|
||||||
|
Employee e = (Employee) o;
|
||||||
|
return Objects.equals(id, e.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(id);
|
||||||
|
}
|
||||||
|
}
|
73
src/main/java/com/example/springip/lab3/models/Position.java
Normal file
73
src/main/java/com/example/springip/lab3/models/Position.java
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
package com.example.springip.lab3.models;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class Position {
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||||
|
private Long Id;
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
//mappedBy - атрибут, указывающий, что классом-владельцем отношений является другой класс
|
||||||
|
@ManyToMany(mappedBy = "positions", cascade = {CascadeType.REMOVE}, fetch = FetchType.EAGER)
|
||||||
|
private List<Employee> employees = new ArrayList<>();
|
||||||
|
|
||||||
|
public Position() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Position(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Employee> getEmployees() {
|
||||||
|
return employees;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmployees(List<Employee> employees) {
|
||||||
|
this.employees = employees;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addNewEmployee(Employee e) {
|
||||||
|
employees.add(e);
|
||||||
|
if (!e.getPositions().contains(this)) {
|
||||||
|
e.addNewPosition(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public void deleteEmployee(Employee e) {
|
||||||
|
employees.remove(e);
|
||||||
|
if (e.getPositions().contains(this)) {
|
||||||
|
e.removePosition(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) return true;
|
||||||
|
if (o == null || getClass() != o.getClass()) return false;
|
||||||
|
Position student = (Position) o;
|
||||||
|
return Objects.equals(Id, student.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(Id);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,88 @@
|
|||||||
|
package com.example.springip.lab3.mvc;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.dto.CompanyDto;
|
||||||
|
import com.example.springip.lab3.dto.EmployeeDto;
|
||||||
|
import com.example.springip.lab3.dto.PositionDto;
|
||||||
|
import com.example.springip.lab3.service.CompanyService;
|
||||||
|
import com.example.springip.lab3.service.EmployeeService;
|
||||||
|
import com.example.springip.lab3.service.PositionService;
|
||||||
|
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.*;
|
||||||
|
|
||||||
|
@Controller
|
||||||
|
@RequestMapping("/company")
|
||||||
|
public class CompanyMvcController {
|
||||||
|
private final CompanyService companyService;
|
||||||
|
private final EmployeeService employeeService;
|
||||||
|
private final PositionService positionService;
|
||||||
|
|
||||||
|
public CompanyMvcController(CompanyService companyService, EmployeeService employeeService, PositionService positionService) {
|
||||||
|
this.companyService = companyService;
|
||||||
|
this.employeeService = employeeService;
|
||||||
|
this.positionService = positionService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public String getCompanies(Model model) {
|
||||||
|
model.addAttribute("companies",
|
||||||
|
companyService.findAllCompanies().stream()
|
||||||
|
.map(CompanyDto::new)
|
||||||
|
.toList());
|
||||||
|
return "company";
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/one/{id}")
|
||||||
|
public String getCompany(@PathVariable(required = false) Long id, Model model) {
|
||||||
|
model.addAttribute("company",
|
||||||
|
new CompanyDto(companyService.findCompany(id)));
|
||||||
|
model.addAttribute("freeEmployees", employeeService.findAllFreeEmployees().stream().map(EmployeeDto::new).toList());
|
||||||
|
model.addAttribute("positions", positionService.findAllPositions().stream().map(PositionDto::new).toList());
|
||||||
|
return "company-one";
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping(value = "/redirect")
|
||||||
|
public String redirectToCompanyPage(@RequestParam("companyId") Long companyId) {
|
||||||
|
return "redirect:/company/one/" + companyId;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping(value = {"/edit", "/edit/{id}"})
|
||||||
|
public String editCompany(@PathVariable(required = false) Long id,
|
||||||
|
Model model) {
|
||||||
|
if (id == null || id <= 0) {
|
||||||
|
model.addAttribute("companyDto", new CompanyDto());
|
||||||
|
} else {
|
||||||
|
model.addAttribute("companyId", id);
|
||||||
|
model.addAttribute("companyDto", new CompanyDto(companyService.findCompany(id)));
|
||||||
|
}
|
||||||
|
return "company-edit";
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping(value = {"/", "/{id}"})
|
||||||
|
public String saveCompany(@PathVariable(required = false) Long id,
|
||||||
|
@ModelAttribute @Valid CompanyDto companyDto,
|
||||||
|
BindingResult bindingResult,
|
||||||
|
Model model) {
|
||||||
|
if (bindingResult.hasErrors()) {
|
||||||
|
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||||
|
return "company-edit";
|
||||||
|
}
|
||||||
|
if (id == null || id <= 0) {
|
||||||
|
companyService.addCompany(companyDto.getName());
|
||||||
|
} else {
|
||||||
|
companyService.updateCompany(id, companyDto.getName());
|
||||||
|
}
|
||||||
|
return "redirect:/company";
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@PostMapping("/delete/{id}")
|
||||||
|
public String deleteCompany(@PathVariable Long id) {
|
||||||
|
companyService.deleteCompany(id);
|
||||||
|
return "redirect:/company";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,79 @@
|
|||||||
|
package com.example.springip.lab3.mvc;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.dto.CompanyDto;
|
||||||
|
import com.example.springip.lab3.dto.EmployeeDto;
|
||||||
|
import com.example.springip.lab3.dto.PositionDto;
|
||||||
|
import com.example.springip.lab3.service.CompanyService;
|
||||||
|
import com.example.springip.lab3.service.EmployeeService;
|
||||||
|
import com.example.springip.lab3.service.PositionService;
|
||||||
|
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.*;
|
||||||
|
|
||||||
|
@Controller
|
||||||
|
@RequestMapping("/employee")
|
||||||
|
public class EmployeeMvcController {
|
||||||
|
private final EmployeeService employeeService;
|
||||||
|
private final PositionService positionService;
|
||||||
|
|
||||||
|
public EmployeeMvcController(EmployeeService employeeService, PositionService positionService) {
|
||||||
|
this.employeeService = employeeService;
|
||||||
|
this.positionService = positionService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public String getEmployees(Model model) {
|
||||||
|
model.addAttribute("employees",
|
||||||
|
employeeService.findAllEmployees().stream()
|
||||||
|
.map(EmployeeDto::new)
|
||||||
|
.toList());
|
||||||
|
return "employee";
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping(value = {"/edit/", "/edit/{id}"})
|
||||||
|
public String editCompany(@PathVariable(required = false) Long id,
|
||||||
|
Model model) {
|
||||||
|
if (id == null || id <= 0) {
|
||||||
|
model.addAttribute("employeeDto", new EmployeeDto());
|
||||||
|
} else {
|
||||||
|
model.addAttribute("employeeId", id);
|
||||||
|
model.addAttribute("employeeDto", new EmployeeDto(employeeService.findEmployee(id)));
|
||||||
|
}
|
||||||
|
return "employee-edit";
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping(value = {"/", "/{id}"})
|
||||||
|
public String saveCompany(@PathVariable(required = false) Long id,
|
||||||
|
@ModelAttribute @Valid EmployeeDto employeeDto,
|
||||||
|
BindingResult bindingResult,
|
||||||
|
Model model) {
|
||||||
|
if (bindingResult.hasErrors()) {
|
||||||
|
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||||
|
return "employee-edit";
|
||||||
|
}
|
||||||
|
if (id == null || id <= 0) {
|
||||||
|
employeeService.addEmployee(employeeDto.getSurname(), employeeDto.getName(), employeeDto.getPhoneNumber());
|
||||||
|
} else {
|
||||||
|
employeeService.updateEmployee(id, employeeDto.getSurname(), employeeDto.getName(), employeeDto.getPhoneNumber());
|
||||||
|
}
|
||||||
|
return "redirect:/employee";
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@PostMapping("/delete/{id}")
|
||||||
|
public String deleteEmployee(@PathVariable Long id) {
|
||||||
|
employeeService.deleteEmployee(id);
|
||||||
|
return "redirect:/employee";
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/report")
|
||||||
|
public String getReport(Model model) {
|
||||||
|
model.addAttribute("positions",
|
||||||
|
positionService.findAllPositions().stream()
|
||||||
|
.map(PositionDto::new)
|
||||||
|
.toList());
|
||||||
|
return "report";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.example.springip.lab3.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();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,67 @@
|
|||||||
|
package com.example.springip.lab3.mvc;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.dto.EmployeeDto;
|
||||||
|
import com.example.springip.lab3.dto.PositionDto;
|
||||||
|
import com.example.springip.lab3.service.EmployeeService;
|
||||||
|
import com.example.springip.lab3.service.PositionService;
|
||||||
|
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.*;
|
||||||
|
|
||||||
|
@Controller
|
||||||
|
@RequestMapping("/position")
|
||||||
|
public class PositionMvcController {
|
||||||
|
private final PositionService positionService;
|
||||||
|
|
||||||
|
public PositionMvcController(PositionService positionService) {
|
||||||
|
this.positionService = positionService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public String getPositions(Model model) {
|
||||||
|
model.addAttribute("positions",
|
||||||
|
positionService.findAllPositions().stream()
|
||||||
|
.map(PositionDto::new)
|
||||||
|
.toList());
|
||||||
|
return "position";
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping(value = {"/edit/", "/edit/{id}"})
|
||||||
|
public String editPosition(@PathVariable(required = false) Long id,
|
||||||
|
Model model) {
|
||||||
|
if (id == null || id <= 0) {
|
||||||
|
model.addAttribute("positionDto", new PositionDto());
|
||||||
|
} else {
|
||||||
|
model.addAttribute("positionId", id);
|
||||||
|
model.addAttribute("positionDto", new PositionDto(positionService.findPosition(id)));
|
||||||
|
}
|
||||||
|
return "position-edit";
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping(value = {"/", "/{id}"})
|
||||||
|
public String savePosition(@PathVariable(required = false) Long id,
|
||||||
|
@ModelAttribute @Valid PositionDto positionDto,
|
||||||
|
BindingResult bindingResult,
|
||||||
|
Model model) {
|
||||||
|
if (bindingResult.hasErrors()) {
|
||||||
|
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||||
|
return "position-edit";
|
||||||
|
}
|
||||||
|
if (id == null || id <= 0) {
|
||||||
|
positionService.addPosition(positionDto.getName());
|
||||||
|
} else {
|
||||||
|
positionService.updatePosition(id, positionDto.getName());
|
||||||
|
}
|
||||||
|
return "redirect:/position";
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@PostMapping("/delete/{id}")
|
||||||
|
public String deleteEmployee(@PathVariable Long id) {
|
||||||
|
positionService.deletePosition(id);
|
||||||
|
return "redirect:/position";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,86 @@
|
|||||||
|
package com.example.springip.lab3.service;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.dao.CompanyRepository;
|
||||||
|
import com.example.springip.lab3.dao.EmployeeRepository;
|
||||||
|
import com.example.springip.lab3.models.Company;
|
||||||
|
import com.example.springip.lab3.models.Employee;
|
||||||
|
import jakarta.persistence.EntityManager;
|
||||||
|
import jakarta.persistence.EntityNotFoundException;
|
||||||
|
import jakarta.persistence.PersistenceContext;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class CompanyService {
|
||||||
|
private CompanyRepository companyRepository;
|
||||||
|
private EmployeeRepository employeeRepository;
|
||||||
|
public CompanyService(CompanyRepository companyRepository, EmployeeRepository employeeRepository) {
|
||||||
|
this.companyRepository = companyRepository;
|
||||||
|
this.employeeRepository = employeeRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Company addCompany(String name) {
|
||||||
|
if (!StringUtils.hasText(name)) {
|
||||||
|
throw new IllegalArgumentException("Student name is null or empty");
|
||||||
|
}
|
||||||
|
final Company company = new Company(name);
|
||||||
|
companyRepository.save(company);
|
||||||
|
return company;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public Company findCompany(Long id) {
|
||||||
|
final Company company = companyRepository.findById(id).orElse(null);
|
||||||
|
if (company == null) {
|
||||||
|
throw new EntityNotFoundException(String.format("Company with id [%s] is not found", id));
|
||||||
|
}
|
||||||
|
return company;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public List<Company> findAllCompanies() {
|
||||||
|
return companyRepository.findAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Company updateCompany(Long id, String name) {
|
||||||
|
if (!StringUtils.hasText(name)) {
|
||||||
|
throw new IllegalArgumentException("Company name is null or empty");
|
||||||
|
}
|
||||||
|
final Company currentCompany = findCompany(id);
|
||||||
|
currentCompany.setName(name);
|
||||||
|
|
||||||
|
return companyRepository.save(currentCompany);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Company deleteCompany(Long id) {
|
||||||
|
final Company currentCompany = findCompany(id);
|
||||||
|
companyRepository.delete(currentCompany);
|
||||||
|
return currentCompany;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void deleteAllCompanies() {
|
||||||
|
companyRepository.deleteAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Employee addNewEmployee(Long id, Employee employee) {
|
||||||
|
Company currentCompany = findCompany(id);
|
||||||
|
currentCompany.addNewEmployee(employee);
|
||||||
|
companyRepository.save(currentCompany);
|
||||||
|
return employee;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Employee deleteEmployee(Long id, Employee employee) {
|
||||||
|
Company currentCompany = findCompany(id);
|
||||||
|
currentCompany.deleteEmployee(employee);
|
||||||
|
return employeeRepository.save(employee);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,112 @@
|
|||||||
|
package com.example.springip.lab3.service;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.dao.EmployeeRepository;
|
||||||
|
import com.example.springip.lab3.models.Company;
|
||||||
|
import com.example.springip.lab3.models.Employee;
|
||||||
|
import com.example.springip.lab3.models.Position;
|
||||||
|
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 EmployeeService {
|
||||||
|
private EmployeeRepository employeeRepository;
|
||||||
|
public EmployeeService(EmployeeRepository employeeRepository) {
|
||||||
|
this.employeeRepository = employeeRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Employee addEmployee(String surname, String name, String phoneNumber) {
|
||||||
|
if (!StringUtils.hasText(name) ||!StringUtils.hasText(surname) || !StringUtils.hasText(phoneNumber)) {
|
||||||
|
throw new IllegalArgumentException("Employee's data is null or empty");
|
||||||
|
}
|
||||||
|
final Employee employee = new Employee(surname, name, phoneNumber);
|
||||||
|
employeeRepository.save(employee);
|
||||||
|
return employee;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Employee findEmployee(Long id) {
|
||||||
|
final Employee employee = employeeRepository.findById(id).orElse(null);
|
||||||
|
if (employee == null) {
|
||||||
|
throw new EntityNotFoundException(String.format("Employee with id [%s] is not found", id));
|
||||||
|
}
|
||||||
|
return employee;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public List<Employee> findAllEmployees() {
|
||||||
|
return employeeRepository.findAll();
|
||||||
|
}
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public List<Employee> findAllFreeEmployees() {
|
||||||
|
return employeeRepository.findByCompanyIsNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Employee updateEmployee(Long id, String surname, String name, String phoneNumber) {
|
||||||
|
if (!StringUtils.hasText(name) ||!StringUtils.hasText(surname) || !StringUtils.hasText(phoneNumber)) {
|
||||||
|
throw new IllegalArgumentException("Employee's data is null or empty");
|
||||||
|
}
|
||||||
|
final Employee currentEmployee = findEmployee(id);
|
||||||
|
currentEmployee.setName(name);
|
||||||
|
currentEmployee.setSurname(surname);
|
||||||
|
currentEmployee.setPhoneNumber(phoneNumber);
|
||||||
|
|
||||||
|
return employeeRepository.save(currentEmployee);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Employee deleteEmployee(Long id) {
|
||||||
|
final Employee employee = findEmployee(id);
|
||||||
|
employeeRepository.delete(employee);
|
||||||
|
return employee;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void deleteAllEmployees() {
|
||||||
|
employeeRepository.deleteAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void addCompany(Long id, Company c) {
|
||||||
|
final Employee employee = findEmployee(id);
|
||||||
|
employee.setCompany(c);
|
||||||
|
employeeRepository.save(employee);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void deleteCompany(Long id) {
|
||||||
|
final Employee employee = findEmployee(id);
|
||||||
|
employee.deleteCompany();
|
||||||
|
employeeRepository.save(employee);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Employee addPosition(Long id, Position p) {
|
||||||
|
Employee e = findEmployee(id);
|
||||||
|
e.addNewPosition(p);
|
||||||
|
System.out.println(e.getPositions().size());
|
||||||
|
return employeeRepository.save(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Employee deletePosition(Long id, Position p) {
|
||||||
|
Employee e = findEmployee(id);
|
||||||
|
e.removePosition(p);
|
||||||
|
return employeeRepository.save(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public List<Employee> getEmployeesByPosition(Position p) {
|
||||||
|
// List<Employee> employees = em.createQuery("select e from Employee e INNER JOIN e.positions p WHERE p.id=:posit",
|
||||||
|
// Employee.class)
|
||||||
|
// .setParameter("posit", p.getId())
|
||||||
|
// .getResultList();
|
||||||
|
List<Employee> employees = employeeRepository.findByPositions_Id(p.getId());
|
||||||
|
return employees;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,73 @@
|
|||||||
|
package com.example.springip.lab3.service;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.dao.PositionRepository;
|
||||||
|
import com.example.springip.lab3.models.Company;
|
||||||
|
import com.example.springip.lab3.models.Employee;
|
||||||
|
import com.example.springip.lab3.models.Position;
|
||||||
|
import jakarta.persistence.EntityManager;
|
||||||
|
import jakarta.persistence.EntityNotFoundException;
|
||||||
|
import jakarta.persistence.PersistenceContext;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class PositionService {
|
||||||
|
|
||||||
|
private PositionRepository positionRepository;
|
||||||
|
|
||||||
|
public PositionService(PositionRepository positionRepository) {
|
||||||
|
this.positionRepository = positionRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Position addPosition(String name) {
|
||||||
|
if (!StringUtils.hasText(name)) {
|
||||||
|
throw new IllegalArgumentException("Employee's data is null or empty");
|
||||||
|
}
|
||||||
|
final Position position = new Position(name);
|
||||||
|
positionRepository.save(position);
|
||||||
|
return position;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Position findPosition(Long id) {
|
||||||
|
final Position position = positionRepository.findById(id).orElse(null);
|
||||||
|
if (position == null) {
|
||||||
|
throw new EntityNotFoundException(String.format("Position with id [%s] is not found", id));
|
||||||
|
}
|
||||||
|
return position;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public List<Position> findAllPositions() {
|
||||||
|
return positionRepository.findAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Position updatePosition(Long id, String name) {
|
||||||
|
if (!StringUtils.hasText(name)) {
|
||||||
|
throw new IllegalArgumentException("Employee's data is null or empty");
|
||||||
|
}
|
||||||
|
final Position currentPosition = findPosition(id);
|
||||||
|
currentPosition.setName(name);
|
||||||
|
|
||||||
|
return positionRepository.save(currentPosition);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public Position deletePosition(Long id) {
|
||||||
|
final Position p = findPosition(id);
|
||||||
|
positionRepository.delete(p);
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void deleteAllPositions() {
|
||||||
|
positionRepository.deleteAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.example.springip.lab3.user.controller;
|
||||||
|
|
||||||
|
import com.example.springip.WebConfiguration;
|
||||||
|
import com.example.springip.lab3.user.model.UserDto;
|
||||||
|
import com.example.springip.lab3.user.service.UserService;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
|
||||||
|
@RestController()
|
||||||
|
public class UserController {
|
||||||
|
public static final String URL_LOGIN = "/jwt/login";
|
||||||
|
|
||||||
|
private final UserService userService;
|
||||||
|
|
||||||
|
public UserController(UserService userService) {
|
||||||
|
this.userService = userService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping(URL_LOGIN)
|
||||||
|
public String login(@RequestBody @Valid UserDto userDto) {
|
||||||
|
return userService.loginAndGetToken(userDto);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,44 @@
|
|||||||
|
package com.example.springip.lab3.user.controller;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.user.model.User;
|
||||||
|
import com.example.springip.lab3.user.model.UserDto;
|
||||||
|
import com.example.springip.lab3.user.model.UserRole;
|
||||||
|
import com.example.springip.lab3.user.service.UserService;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.security.access.annotation.Secured;
|
||||||
|
import org.springframework.stereotype.Controller;
|
||||||
|
import org.springframework.ui.Model;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
@Controller
|
||||||
|
@RequestMapping("/users")
|
||||||
|
public class UserMvcController {
|
||||||
|
private final UserService userService;
|
||||||
|
|
||||||
|
public UserMvcController(UserService userService) {
|
||||||
|
this.userService = userService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
@Secured({UserRole.AsString.ADMIN})
|
||||||
|
public String getUsers(@RequestParam(defaultValue = "1") int page,
|
||||||
|
@RequestParam(defaultValue = "5") int size,
|
||||||
|
Model model) {
|
||||||
|
final Page<UserDto> users = userService.findAllPages(page, size)
|
||||||
|
.map(UserDto::new);
|
||||||
|
model.addAttribute("users", users);
|
||||||
|
final int totalPages = users.getTotalPages();
|
||||||
|
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
|
||||||
|
.boxed()
|
||||||
|
.toList();
|
||||||
|
model.addAttribute("pages", pageNumbers);
|
||||||
|
model.addAttribute("totalPages", totalPages);
|
||||||
|
return "users";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,50 @@
|
|||||||
|
package com.example.springip.lab3.user.controller;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.user.model.User;
|
||||||
|
import com.example.springip.lab3.user.model.UserSignupDto;
|
||||||
|
import com.example.springip.lab3.user.service.UserService;
|
||||||
|
import com.example.springip.lab3.util.validation.ValidationException;
|
||||||
|
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.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
|
||||||
|
@Controller
|
||||||
|
@RequestMapping(UserSignupMvcController.SIGNUP_URL)
|
||||||
|
public class UserSignupMvcController {
|
||||||
|
public static final String SIGNUP_URL = "/signup";
|
||||||
|
|
||||||
|
private final UserService userService;
|
||||||
|
|
||||||
|
public UserSignupMvcController(UserService userService) {
|
||||||
|
this.userService = userService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
public String showSignupForm(Model model) {
|
||||||
|
model.addAttribute("userDto", new UserSignupDto());
|
||||||
|
return "signup";
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
public String signup(@ModelAttribute("userDto") @Valid UserSignupDto userSignupDto,
|
||||||
|
BindingResult bindingResult,
|
||||||
|
Model model) {
|
||||||
|
if (bindingResult.hasErrors()) {
|
||||||
|
model.addAttribute("errors", bindingResult.getAllErrors());
|
||||||
|
return "signup";
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final User user = userService.createUser(
|
||||||
|
userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm());
|
||||||
|
return "redirect:/login?created=" + user.getLogin();
|
||||||
|
} catch (ValidationException e) {
|
||||||
|
model.addAttribute("errors", e.getMessage());
|
||||||
|
return "signup";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
75
src/main/java/com/example/springip/lab3/user/model/User.java
Normal file
75
src/main/java/com/example/springip/lab3/user/model/User.java
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
package com.example.springip.lab3.user.model;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "users")
|
||||||
|
public class User {
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
@Column(nullable = false, unique = true, length = 64)
|
||||||
|
@NotBlank
|
||||||
|
@Size(min = 3, max = 64)
|
||||||
|
private String login;
|
||||||
|
@Column(nullable = false, length = 64)
|
||||||
|
@NotBlank
|
||||||
|
@Size(min = 6, max = 64)
|
||||||
|
private String password;
|
||||||
|
private UserRole role;
|
||||||
|
|
||||||
|
public User() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public User(String login, String password) {
|
||||||
|
this(login, password, UserRole.USER);
|
||||||
|
}
|
||||||
|
|
||||||
|
public User(String login, String password, UserRole role) {
|
||||||
|
this.login = login;
|
||||||
|
this.password = password;
|
||||||
|
this.role = role;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLogin() {
|
||||||
|
return login;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLogin(String login) {
|
||||||
|
this.login = login;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPassword() {
|
||||||
|
return password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPassword(String password) {
|
||||||
|
this.password = password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public UserRole getRole() {
|
||||||
|
return role;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) return true;
|
||||||
|
if (o == null || getClass() != o.getClass()) return false;
|
||||||
|
User user = (User) o;
|
||||||
|
return Objects.equals(id, user.id) && Objects.equals(login, user.login);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(id, login);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,46 @@
|
|||||||
|
package com.example.springip.lab3.user.model;
|
||||||
|
|
||||||
|
public class UserDto {
|
||||||
|
private long id;
|
||||||
|
private String login;
|
||||||
|
private UserRole role;
|
||||||
|
private String password;
|
||||||
|
|
||||||
|
public UserDto(User user) {
|
||||||
|
this.id = user.getId();
|
||||||
|
this.login = user.getLogin();
|
||||||
|
this.role = user.getRole();
|
||||||
|
this.password = user.getPassword();
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLogin() {
|
||||||
|
return login;
|
||||||
|
}
|
||||||
|
|
||||||
|
public UserRole getRole() {
|
||||||
|
return role;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPassword() {
|
||||||
|
return password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public UserDto() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLogin(String login) {
|
||||||
|
this.login = login;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRole(UserRole role) {
|
||||||
|
this.role = role;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPassword(String password) {
|
||||||
|
this.password = password;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,20 @@
|
|||||||
|
package com.example.springip.lab3.user.model;
|
||||||
|
|
||||||
|
import org.springframework.security.core.GrantedAuthority;
|
||||||
|
|
||||||
|
public enum UserRole implements GrantedAuthority {
|
||||||
|
ADMIN,
|
||||||
|
USER;
|
||||||
|
|
||||||
|
private static final String PREFIX = "ROLE_";
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getAuthority() {
|
||||||
|
return PREFIX + this.name();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static final class AsString {
|
||||||
|
public static final String ADMIN = PREFIX + "ADMIN";
|
||||||
|
public static final String USER = PREFIX + "USER";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,41 @@
|
|||||||
|
package com.example.springip.lab3.user.model;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
|
||||||
|
|
||||||
|
public class UserSignupDto {
|
||||||
|
@NotBlank
|
||||||
|
@Size(min = 3, max = 64)
|
||||||
|
private String login;
|
||||||
|
@NotBlank
|
||||||
|
@Size(min = 6, max = 64)
|
||||||
|
private String password;
|
||||||
|
@NotBlank
|
||||||
|
@Size(min = 6, max = 64)
|
||||||
|
private String passwordConfirm;
|
||||||
|
|
||||||
|
public String getLogin() {
|
||||||
|
return login;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLogin(String login) {
|
||||||
|
this.login = login;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPassword() {
|
||||||
|
return password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPassword(String password) {
|
||||||
|
this.password = password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPasswordConfirm() {
|
||||||
|
return passwordConfirm;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPasswordConfirm(String passwordConfirm) {
|
||||||
|
this.passwordConfirm = passwordConfirm;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,8 @@
|
|||||||
|
package com.example.springip.lab3.user.repository;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.user.model.User;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
public interface UserRepository extends JpaRepository<User, Long> {
|
||||||
|
User findOneByLoginIgnoreCase(String login);
|
||||||
|
}
|
@ -0,0 +1,7 @@
|
|||||||
|
package com.example.springip.lab3.user.service;
|
||||||
|
|
||||||
|
public class UserNotFoundException extends RuntimeException {
|
||||||
|
public UserNotFoundException(String login) {
|
||||||
|
super(String.format("User not found '%s'", login));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,98 @@
|
|||||||
|
package com.example.springip.lab3.user.service;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.configuration.jwt.JwtException;
|
||||||
|
import com.example.springip.lab3.configuration.jwt.JwtsProvider;
|
||||||
|
import com.example.springip.lab3.user.model.User;
|
||||||
|
import com.example.springip.lab3.user.model.UserDto;
|
||||||
|
import com.example.springip.lab3.user.model.UserRole;
|
||||||
|
import com.example.springip.lab3.user.repository.UserRepository;
|
||||||
|
import com.example.springip.lab3.util.validation.ValidationException;
|
||||||
|
import com.example.springip.lab3.util.validation.ValidatorUtil;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.data.domain.Sort;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||||
|
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class UserService implements UserDetailsService {
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
private final ValidatorUtil validatorUtil;
|
||||||
|
private final JwtsProvider jwtProvider;
|
||||||
|
|
||||||
|
public UserService(UserRepository userRepository,
|
||||||
|
PasswordEncoder passwordEncoder,
|
||||||
|
ValidatorUtil validatorUtil,
|
||||||
|
JwtsProvider jwtProvider) {
|
||||||
|
this.userRepository = userRepository;
|
||||||
|
this.passwordEncoder = passwordEncoder;
|
||||||
|
this.validatorUtil = validatorUtil;
|
||||||
|
this.jwtProvider = jwtProvider;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Page<User> findAllPages(int page, int size) {
|
||||||
|
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public User findByLogin(String login) {
|
||||||
|
return userRepository.findOneByLoginIgnoreCase(login);
|
||||||
|
}
|
||||||
|
|
||||||
|
public User createUser(String login, String password, String passwordConfirm) {
|
||||||
|
return createUser(login, password, passwordConfirm, UserRole.USER);
|
||||||
|
}
|
||||||
|
|
||||||
|
public User createUser(String login, String password, String passwordConfirm, UserRole role) {
|
||||||
|
if (findByLogin(login) != null) {
|
||||||
|
throw new ValidationException(String.format("User '%s' already exists", login));
|
||||||
|
}
|
||||||
|
final User user = new User(login, passwordEncoder.encode(password), role);
|
||||||
|
validatorUtil.validate(user);
|
||||||
|
if (!Objects.equals(password, passwordConfirm)) {
|
||||||
|
throw new ValidationException("Passwords not equals");
|
||||||
|
}
|
||||||
|
return userRepository.save(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public String loginAndGetToken(UserDto userDto) {
|
||||||
|
final User user = findByLogin(userDto.getLogin());
|
||||||
|
if (user == null) {
|
||||||
|
throw new UserNotFoundException(userDto.getLogin());
|
||||||
|
}
|
||||||
|
if (!passwordEncoder.matches(userDto.getPassword(), user.getPassword())) {
|
||||||
|
throw new UserNotFoundException(user.getLogin());
|
||||||
|
}
|
||||||
|
return jwtProvider.generateToken(user.getLogin(), user.getRole().name());
|
||||||
|
}
|
||||||
|
|
||||||
|
public UserDetails loadUserByToken(String token) throws UsernameNotFoundException {
|
||||||
|
if (!jwtProvider.validateToken(token)) {
|
||||||
|
throw new JwtException("Bad token");
|
||||||
|
}
|
||||||
|
final String userLogin = jwtProvider.getLogin(token);
|
||||||
|
if (userLogin.isEmpty()) {
|
||||||
|
throw new JwtException("Token is not contain Login");
|
||||||
|
}
|
||||||
|
return loadUserByUsername(userLogin);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||||
|
final User userEntity = findByLogin(username);
|
||||||
|
if (userEntity == null) {
|
||||||
|
throw new UsernameNotFoundException(username);
|
||||||
|
}
|
||||||
|
return new org.springframework.security.core.userdetails.User(
|
||||||
|
userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,46 @@
|
|||||||
|
package com.example.springip.lab3.util.error;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.util.validation.ValidationException;
|
||||||
|
import org.springframework.context.support.DefaultMessageSourceResolvable;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||||
|
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||||
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
|
||||||
|
import java.nio.file.AccessDeniedException;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@ControllerAdvice(annotations = RestController.class)
|
||||||
|
public class AdviceController {
|
||||||
|
@ExceptionHandler({
|
||||||
|
ValidationException.class
|
||||||
|
})
|
||||||
|
public ResponseEntity<Object> handleException(Throwable e) {
|
||||||
|
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler({
|
||||||
|
AccessDeniedException.class
|
||||||
|
})
|
||||||
|
public ResponseEntity<Object> handleAccessDeniedException(Throwable e) {
|
||||||
|
return new ResponseEntity<>(e.getMessage(), HttpStatus.FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||||
|
public ResponseEntity<Object> handleBindException(MethodArgumentNotValidException e) {
|
||||||
|
final ValidationException validationException = new ValidationException(
|
||||||
|
e.getBindingResult().getAllErrors().stream()
|
||||||
|
.map(DefaultMessageSourceResolvable::getDefaultMessage)
|
||||||
|
.collect(Collectors.toSet()));
|
||||||
|
return handleException(validationException);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(Exception.class)
|
||||||
|
public ResponseEntity<Object> handleUnknownException(Throwable e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.example.springip.lab3.util.validation;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
public class ValidationException extends RuntimeException {
|
||||||
|
public <T> ValidationException(Set<String> errors) {
|
||||||
|
super(String.join("\n", errors));
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> ValidationException(String error) {
|
||||||
|
super(error);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,27 @@
|
|||||||
|
package com.example.springip.lab3.util.validation;
|
||||||
|
|
||||||
|
import jakarta.validation.ConstraintViolation;
|
||||||
|
import jakarta.validation.Validation;
|
||||||
|
import jakarta.validation.Validator;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class ValidatorUtil {
|
||||||
|
private final Validator validator;
|
||||||
|
|
||||||
|
public ValidatorUtil() {
|
||||||
|
this.validator = Validation.buildDefaultValidatorFactory().getValidator();
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> void validate(T object) {
|
||||||
|
final Set<ConstraintViolation<T>> errors = validator.validate(object);
|
||||||
|
if (!errors.isEmpty()) {
|
||||||
|
throw new ValidationException(errors.stream()
|
||||||
|
.map(ConstraintViolation::getMessage)
|
||||||
|
.collect(Collectors.toSet()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
14
src/main/resources/application.properties
Normal file
14
src/main/resources/application.properties
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
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
|
||||||
|
jwt.dev-token=my-secret-jwt
|
||||||
|
jwt.dev=true
|
||||||
|
jwt.secret = my-secret-jwt
|
9
src/main/resources/static/styles/company.css
Normal file
9
src/main/resources/static/styles/company.css
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
.prokrutka {
|
||||||
|
background: #fff; /* цвет фона, белый */
|
||||||
|
border: 1px solid #C1C1C1; /* размер и цвет границы блока */
|
||||||
|
overflow: auto;
|
||||||
|
width:230px;
|
||||||
|
height:100px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
21
src/main/resources/static/styles/login.css
Normal file
21
src/main/resources/static/styles/login.css
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
body {
|
||||||
|
background-color: #f8f9fa;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-title {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
background-color: #007bff;
|
||||||
|
border-color: #007bff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover {
|
||||||
|
background-color: #0069d9;
|
||||||
|
border-color: #0062cc;
|
||||||
|
}
|
255
src/main/resources/templates/company-one.html
Normal file
255
src/main/resources/templates/company-one.html
Normal file
@ -0,0 +1,255 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en"
|
||||||
|
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||||
|
layout:decorate="~{default}">
|
||||||
|
<head>
|
||||||
|
<link th:href="@{/styles/company.css}" rel="stylesheet" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div layout:fragment="content">
|
||||||
|
<h1>Название: <span th:text="${company.name}"></span></h1>
|
||||||
|
<h2>Количество сотрудников: <span th:text="${#arrays.length(company.employees.toArray())}"></span></h2>
|
||||||
|
<div sec:authorize="hasRole('ROLE_ADMIN')">
|
||||||
|
<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 sec:authorize="hasRole('ROLE_ADMIN')" scope="col"></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr th:each="employee, iterator: ${company.employees}">
|
||||||
|
<th scope="row" th:text="${iterator.index} + 1"/>
|
||||||
|
<td th:text="${employee.id}"/>
|
||||||
|
<td th:text="${employee.surname}" />
|
||||||
|
<td th:text="${employee.name}" />
|
||||||
|
<td th:text="${employee.phoneNumber}" />
|
||||||
|
<td th:text="${#strings.listJoin(employee.positions.![name],',')}"></td>
|
||||||
|
<th sec:authorize="hasRole('ROLE_ADMIN')" style="width: 20%">
|
||||||
|
<a class="btn btn-danger button-fixed button-sm" th:data-employee="${employee.id}"
|
||||||
|
data-bs-target="#dismissModal" data-bs-toggle="modal"
|
||||||
|
th:onclick="openModalDismiss(this.getAttribute('data-employee'))">Уволить</a>
|
||||||
|
<a class="btn btn-info button-fixed button-sm" th:data-employee="${employee.id}"
|
||||||
|
data-bs-target="#managePositionModal" data-bs-toggle="modal"
|
||||||
|
th:onclick="openModalManagePosition(this.getAttribute('data-employee'))">Должности</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="employeeSelect">Сотрудник</label>
|
||||||
|
<select class="form-select" id="employeeSelect" name="employeeId" required>
|
||||||
|
<option th:each="employee, iterator: ${company.employees}" th:value="${employee.id}"
|
||||||
|
th:text="${employee.surname} + ' ' + ${employee.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">×</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="modal-body">
|
||||||
|
<form id="form-hire">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label" for="employeeHireSelect">Сотрудник</label>
|
||||||
|
<select class="form-select" id="employeeHireSelect" name="employeeId" required>
|
||||||
|
<option selected disabled>Выберите сотрудника</option>
|
||||||
|
<option th:each="employee, iterator: ${freeEmployees}" th:value="${employee.id}"
|
||||||
|
th:text="${employee.surname} + ' ' + ${employee.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="managePositionModal">
|
||||||
|
<div class="modal-dialog">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h5 class="modal-title" id="managePositionModalLabel">Назначение должности</h5>
|
||||||
|
<button type="button" class="close" data-bs-dismiss="modal">
|
||||||
|
<span aria-hidden="true">×</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="modal-body">
|
||||||
|
<form id="form-positions">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label" for="employeePosSelect">Сотрудник</label>
|
||||||
|
<select class="form-select" id="employeePosSelect" name="employeeId" required>
|
||||||
|
<option value="0" selected disabled>Выберите сотрудника</option>
|
||||||
|
<option th:each="employee, iterator: ${company.employees}" th:value="${employee.id}"
|
||||||
|
th:text="${employee.surname} + ' ' + ${employee.name}">
|
||||||
|
</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label" for="employeeSelect">Должности</label>
|
||||||
|
<div class="prokrutka">
|
||||||
|
<div style="200px;" th:each="position, iterator: ${positions}">
|
||||||
|
<input type="checkbox" th:value="${position.id}"
|
||||||
|
th:text="${position.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 company = [[${company}]];
|
||||||
|
var url = 'http://localhost:8080/api/company/id/dismiss?employeeId=empId';
|
||||||
|
url = url.replace("id", company.id).replace("empId", $("#employeeSelect").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 company = [[${company}]];
|
||||||
|
var url = 'http://localhost:8080/api/company/id/hire?employeeId=empId';
|
||||||
|
url = url.replace("id", company.id).replace("empId", $("#employeeHireSelect").val())
|
||||||
|
alert(url);
|
||||||
|
$.ajax({
|
||||||
|
url: url,
|
||||||
|
method: 'PUT',
|
||||||
|
contentType: "application/json;"
|
||||||
|
})
|
||||||
|
.done(function() {
|
||||||
|
location.reload();
|
||||||
|
})
|
||||||
|
.fail((err) => {
|
||||||
|
alert(err);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
$(document).on('submit', '#form-positions', function (e) {
|
||||||
|
e.preventDefault();
|
||||||
|
var company = [[${company}]];
|
||||||
|
var employeeId = $("#employeePosSelect").val();
|
||||||
|
var employee = company.employees.find(x => x.id + '' === employeeId);
|
||||||
|
var positions = employee.positions.map(x => x.id + '');
|
||||||
|
var urlAdd = 'http://localhost:8080/api/employee/id/addPos?position=posId';
|
||||||
|
var urlDel = 'http://localhost:8080/api/employee/id/delPos?position=posId';
|
||||||
|
$('input[type=checkbox]').each(function(){
|
||||||
|
if(positions.indexOf($(this).val()) !== -1 && $(this).is(":checked") === false){
|
||||||
|
$.ajax({
|
||||||
|
url: urlDel.replace("id", employee.id).replace("posId", $(this).val()),
|
||||||
|
method: 'PUT',
|
||||||
|
contentType: "application/json;"
|
||||||
|
})
|
||||||
|
.done(function() {
|
||||||
|
location.reload();
|
||||||
|
})
|
||||||
|
.fail((err) => {
|
||||||
|
alert(err);
|
||||||
|
});
|
||||||
|
|
||||||
|
} else if (positions.indexOf($(this).val()) == -1 && $(this).is(":checked")){
|
||||||
|
$.ajax({
|
||||||
|
url: urlAdd.replace("id", employee.id).replace("posId", $(this).val()),
|
||||||
|
method: 'PUT',
|
||||||
|
contentType: "application/json;"
|
||||||
|
})
|
||||||
|
.done(function() {
|
||||||
|
location.reload();
|
||||||
|
})
|
||||||
|
.fail((err) => {
|
||||||
|
alert(err);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
$(document).ready(function(){
|
||||||
|
$('#employeePosSelect').change(function(){
|
||||||
|
var selectedEmployee = $(this).val();
|
||||||
|
var company = [[${company}]];
|
||||||
|
var employee = company.employees.find(x => x.id + '' === selectedEmployee);
|
||||||
|
var positions = employee.positions.map(x => x.id + '');
|
||||||
|
$('input[type=checkbox]').prop('checked', false);
|
||||||
|
$('input[type=checkbox]').each(function(){
|
||||||
|
if(positions.indexOf($(this).val()) !== -1){
|
||||||
|
$(this).prop('checked', true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function openModalDismiss(id) {
|
||||||
|
$('#employeeSelect').val(id);
|
||||||
|
$( "#employeeSelect" ).prop( "disabled", true );
|
||||||
|
}
|
||||||
|
function openModalManagePosition(id) {
|
||||||
|
$('#employeePosSelect').val(id);
|
||||||
|
$( "#employeePosSelect" ).prop( "disabled", true );
|
||||||
|
var company = [[${company}]];
|
||||||
|
var employee = company.employees.find(x => x.id + '' === id);
|
||||||
|
var positions = employee.positions.map(x => x.id + '');
|
||||||
|
$('input[type=checkbox]').prop('checked', false);
|
||||||
|
$('input[type=checkbox]').each(function(){
|
||||||
|
if(positions.indexOf($(this).val()) !== -1){
|
||||||
|
$(this).prop('checked', true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</th:block>
|
||||||
|
</html>
|
145
src/main/resources/templates/company.html
Normal file
145
src/main/resources/templates/company.html
Normal file
@ -0,0 +1,145 @@
|
|||||||
|
<!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 sec:authorize="hasRole('ROLE_ADMIN')">
|
||||||
|
<a class="btn btn-success button-fixed"
|
||||||
|
onsubmit="openModalEdit()" data-bs-target="#companyEditModal" 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 sec:authorize="hasRole('ROLE_ADMIN')" scope="col">Элементы управления</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr th:each="company, iterator: ${companies}">
|
||||||
|
<th scope="row" th:text="${iterator.index} + 1"/>
|
||||||
|
<td th:text="${company.id}"/>
|
||||||
|
<td style="width: 60%"><a th:href="@{/company/one/{id}(id=${company.id})}" th:text="${company.name}"></a></td>
|
||||||
|
<td th:text="${#arrays.length(company.employees.toArray())}" style="width: 60%"/>
|
||||||
|
<td sec:authorize="hasRole('ROLE_ADMIN')" style="width: 10%">
|
||||||
|
<div class="btn-group" role="group" aria-label="Basic example">
|
||||||
|
<a class="btn btn-info button-fixed button-sm" th:data-company="${company.id}"
|
||||||
|
data-bs-target="#companyEditModal" data-bs-toggle="modal"
|
||||||
|
th:onclick="openModalEdit(this.getAttribute('data-company'))">Изменить</a>
|
||||||
|
<button type="button" class="btn btn-danger button-fixed button-sm"
|
||||||
|
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${company.id}').click()|">
|
||||||
|
Удалить
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<form th:action="@{/company/delete/{id}(id=${company.id})}" method="post">
|
||||||
|
<button th:id="'remove-' + ${company.id}" type="submit" style="display: none">
|
||||||
|
Удалить
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<!-- Modal -->
|
||||||
|
<div class="modal" id="companyModal">
|
||||||
|
<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="/company/redirect" method="post">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label class="form-label" for="companySelect">Компания</label>
|
||||||
|
<select class="form-select" id="companySelect" name="companyId" required>
|
||||||
|
<option selected disabled>Выберите компанию</option>
|
||||||
|
<option th:each="company, iterator: ${companies}" th:value="${company.id}" th:text="${company.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="companyEditModal">
|
||||||
|
<div class="modal-dialog">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-body">
|
||||||
|
<form id="form-edit-company">
|
||||||
|
<input type="hidden" id="companyId" 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 companies = [[${companies}]];
|
||||||
|
var company = companies.find(x => x.id + '' === id);
|
||||||
|
if (company !== 'undefined') {
|
||||||
|
$('#companyId').val(id);
|
||||||
|
$('#name').val(company.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$(document).on('submit', '#form-edit-company', function (e) {
|
||||||
|
e.preventDefault();
|
||||||
|
var companyName = document.getElementById('name');
|
||||||
|
var idInput = document.getElementById('companyId');
|
||||||
|
var urlCompany = 'http://localhost:8080/api/company';
|
||||||
|
let company = {name: companyName.value};
|
||||||
|
var method = 'POST';
|
||||||
|
if (idInput.value !== '') {
|
||||||
|
method = 'PUT';
|
||||||
|
urlCompany = urlCompany + '/' + idInput.value;
|
||||||
|
}
|
||||||
|
$.ajax({
|
||||||
|
url: urlCompany,
|
||||||
|
method: method,
|
||||||
|
data: JSON.stringify(company),
|
||||||
|
contentType: "application/json;"
|
||||||
|
})
|
||||||
|
.done(function() {
|
||||||
|
location.reload();
|
||||||
|
})
|
||||||
|
.fail((err) => {
|
||||||
|
alert(err);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</th:block>
|
||||||
|
</html>
|
49
src/main/resources/templates/default.html
Normal file
49
src/main/resources/templates/default.html
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
<!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-dark">
|
||||||
|
<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="/company"
|
||||||
|
th:classappend="${#strings.equals(activeLink, '/')} ? 'active' : ''">ГЛАВНОЕ</a>
|
||||||
|
<a class="nav-link" href="/employee"
|
||||||
|
th:classappend="${#strings.equals(activeLink, '/employee')} ? 'active' : ''">Сотрудники</a>
|
||||||
|
<a class="nav-link" href="/company"
|
||||||
|
th:classappend="${#strings.equals(activeLink, '/company')} ? 'active' : ''">Компании</a>
|
||||||
|
<a class="nav-link" href="/position"
|
||||||
|
th:classappend="${#strings.equals(activeLink, '/position')} ? 'active' : ''">Должности</a>
|
||||||
|
<a class="nav-link" href="/employee/report"
|
||||||
|
th:classappend="${#strings.equals(activeLink, '/employee/report')} ? 'active' : ''">Сотрудники по должностям</a>
|
||||||
|
<a class="nav-link" href="/h2-console/" target="_blank">Консоль H2</a>
|
||||||
|
<a sec:authorize="!isAuthenticated()" class="nav-link" href="/login">Войти</a>
|
||||||
|
<a sec:authorize="isAuthenticated()" class="nav-link" href="/logout">Выйти</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>
|
133
src/main/resources/templates/employee.html
Normal file
133
src/main/resources/templates/employee.html
Normal 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 sec:authorize="hasRole('ROLE_ADMIN')">
|
||||||
|
<a class="btn btn-success button-fixed"
|
||||||
|
onsubmit="openModalEdit()" data-bs-target="#employeeEditModal" 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 sec:authorize="hasRole('ROLE_ADMIN')" scope="col">Элементы управления</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr th:each="employee, iterator: ${employees}">
|
||||||
|
<th scope="row" th:text="${iterator.index} + 1"/>
|
||||||
|
<td th:text="${employee.id}"/>
|
||||||
|
<td th:text="${employee.surname}" />
|
||||||
|
<td th:text="${employee.name}" />
|
||||||
|
<td th:text="${employee.phoneNumber}" />
|
||||||
|
<td th:text="${#strings.listJoin(employee.positions.![name],',')}"></td>
|
||||||
|
<td sec:authorize="hasRole('ROLE_ADMIN')" style="width: 10%">
|
||||||
|
<div class="btn-group" role="group" aria-label="Basic example">
|
||||||
|
<a class="btn btn-info button-fixed button-sm" th:data-employee="${employee.id}"
|
||||||
|
data-bs-target="#employeeEditModal" data-bs-toggle="modal"
|
||||||
|
th:onclick="openModalEdit(this.getAttribute('data-employee'))">
|
||||||
|
Изменить
|
||||||
|
</a>
|
||||||
|
<button type="button" class="btn btn-danger button-fixed button-sm"
|
||||||
|
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${employee.id}').click()|">
|
||||||
|
Удалить
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<form th:action="@{/employee/delete/{id}(id=${employee.id})}" method="post">
|
||||||
|
<button th:id="'remove-' + ${employee.id}" type="submit" style="display: none">
|
||||||
|
Удалить
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div class="modal" id="employeeEditModal">
|
||||||
|
<div class="modal-dialog">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-body">
|
||||||
|
<form id="form-edit-employee">
|
||||||
|
<input type="hidden" id="employeeId" 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 employees = [[${employees}]];
|
||||||
|
var employee = employees.find(x => x.id + '' === id);
|
||||||
|
if (employee !== 'undefined') {
|
||||||
|
$('#employeeId').val(id);
|
||||||
|
$('#surname').val(employee.surname);
|
||||||
|
$('#name').val(employee.name);
|
||||||
|
$('#phoneNumber').val(employee.phoneNumber);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$(document).on('submit', '#form-edit-employee', function (e) {
|
||||||
|
e.preventDefault();
|
||||||
|
var idInput = document.getElementById('employeeId');
|
||||||
|
var urlEmployee = 'http://localhost:8080/api/employee';
|
||||||
|
let employee = {surname: $('#surname').val(),
|
||||||
|
name: $('#name').val(),
|
||||||
|
phoneNumber: $('#phoneNumber').val()};
|
||||||
|
var method = 'POST';
|
||||||
|
if (idInput.value !== '') {
|
||||||
|
method = 'PUT';
|
||||||
|
urlEmployee = urlEmployee + '/' + idInput.value;
|
||||||
|
}
|
||||||
|
$.ajax({
|
||||||
|
url: urlEmployee,
|
||||||
|
method: method,
|
||||||
|
data: JSON.stringify(employee),
|
||||||
|
contentType: "application/json;"
|
||||||
|
})
|
||||||
|
.done(function() {
|
||||||
|
location.reload();
|
||||||
|
})
|
||||||
|
.fail((err) => {
|
||||||
|
alert(err);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</th:block>
|
||||||
|
</html>
|
13
src/main/resources/templates/error.html
Normal file
13
src/main/resources/templates/error.html
Normal 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>
|
13
src/main/resources/templates/index.html
Normal file
13
src/main/resources/templates/index.html
Normal 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>It's works!</div>
|
||||||
|
<a href="123">ERROR</a>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
44
src/main/resources/templates/login.html
Normal file
44
src/main/resources/templates/login.html
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en"
|
||||||
|
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||||
|
layout:decorate="~{default}">
|
||||||
|
<head>
|
||||||
|
<link th:href="@{/styles/login.css}" rel="stylesheet" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container-fluid" layout:fragment="content">
|
||||||
|
<div th:if="${param.error}" class="alert alert-danger margin-bottom">
|
||||||
|
Пользователь не найден или пароль указан не верно
|
||||||
|
</div>
|
||||||
|
<div th:if="${param.logout}" class="alert alert-success margin-bottom">
|
||||||
|
Выход успешно произведен
|
||||||
|
</div>
|
||||||
|
<div th:if="${param.created}" class="alert alert-success margin-bottom">
|
||||||
|
Пользователь '<span th:text="${param.created}"></span>' успешно создан
|
||||||
|
</div>
|
||||||
|
<div class="row justify-content-center align-items-center vh-100">
|
||||||
|
<div class="col-sm-6 col-md-4">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-body">
|
||||||
|
<h5 class="card-title">Авторизация</h5>
|
||||||
|
<form th:action="@{/login}" method="post">
|
||||||
|
<div class="mb-3">
|
||||||
|
<label htmlFor="login">Логин</label>
|
||||||
|
<input type="text" name="username" id="username" class="form-control"
|
||||||
|
placeholder="Логин" required="true" autofocus="true"/>
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<label htmlFor="login">Пароль</label>
|
||||||
|
<input type="password" name="password" id="password" class="form-control"
|
||||||
|
placeholder="Пароль" required="true"/>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn btn-primary button-fixed">Войти</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
115
src/main/resources/templates/position.html
Normal file
115
src/main/resources/templates/position.html
Normal 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 sec:authorize="hasRole('ROLE_ADMIN')">
|
||||||
|
<a class="btn btn-success button-fixed"
|
||||||
|
onsubmit="openModalEdit()" data-bs-target="#positionEditModal" 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 sec:authorize="hasRole('ROLE_ADMIN')" scope="col">Элементы управления</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr th:each="position, iterator: ${positions}">
|
||||||
|
<th scope="row" th:text="${iterator.index} + 1"/>
|
||||||
|
<td th:text="${position.id}"/>
|
||||||
|
<td th:text="${position.name}" style="width: 60%"/>
|
||||||
|
<td sec:authorize="hasRole('ROLE_ADMIN')" style="width: 10%">
|
||||||
|
<div class="btn-group" role="group" aria-label="Basic example">
|
||||||
|
<a class="btn btn-info button-fixed button-sm" th:data-position="${position.id}"
|
||||||
|
data-bs-target="#positionEditModal" data-bs-toggle="modal"
|
||||||
|
th:onclick="openModalEdit(this.getAttribute('data-position'))">Изменить</a>
|
||||||
|
<button type="button" class="btn btn-danger button-fixed button-sm"
|
||||||
|
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${position.id}').click()|">
|
||||||
|
Удалить
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<form th:action="@{/position/delete/{id}(id=${position.id})}" method="post">
|
||||||
|
<button th:id="'remove-' + ${position.id}" type="submit" style="display: none">
|
||||||
|
Удалить
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div class="modal" id="positionEditModal">
|
||||||
|
<div class="modal-dialog">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-body">
|
||||||
|
<form id="form-edit-position">
|
||||||
|
<input type="hidden" id="positionId" 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 positions = [[${positions}]];
|
||||||
|
var position = positions.find(x => x.id + '' === id);
|
||||||
|
if (position !== 'undefined') {
|
||||||
|
$('#positionId').val(id);
|
||||||
|
$('#name').val(position.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$(document).on('submit', '#form-edit-position', function (e) {
|
||||||
|
e.preventDefault();
|
||||||
|
var positionName = document.getElementById('name');
|
||||||
|
var idInput = document.getElementById('positionId');
|
||||||
|
var urlPosition = 'http://localhost:8080/api/position';
|
||||||
|
let position = {name: positionName.value};
|
||||||
|
var method = 'POST';
|
||||||
|
if (idInput.value !== '') {
|
||||||
|
method = 'PUT';
|
||||||
|
urlPosition = urlPosition + '/' + idInput.value;
|
||||||
|
}
|
||||||
|
$.ajax({
|
||||||
|
url: urlPosition,
|
||||||
|
method: method,
|
||||||
|
data: JSON.stringify(position),
|
||||||
|
contentType: "application/json;"
|
||||||
|
})
|
||||||
|
.done(function() {
|
||||||
|
location.reload();
|
||||||
|
})
|
||||||
|
.fail((err) => {
|
||||||
|
alert(err);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</th:block>
|
||||||
|
</html>
|
67
src/main/resources/templates/report.html
Normal file
67
src/main/resources/templates/report.html
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
<!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>
|
||||||
|
<select id="positionSelect" name="positionId" class="form-select" required>
|
||||||
|
<option selected disabled>Выберите должность</option>
|
||||||
|
<option th:each="position, iterator: ${positions}" th:value="${position.id}" th:text="${position.name}">
|
||||||
|
</option>
|
||||||
|
</select>
|
||||||
|
<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 id="employees">
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
<th:block layout:fragment="scripts">
|
||||||
|
<script th:inline="javascript">
|
||||||
|
$(document).on('change', '#positionSelect', function (e) {
|
||||||
|
var url = 'http://localhost:8080/api/employee/position?pos=id';
|
||||||
|
$("#employees > tr").remove();
|
||||||
|
$.ajax({
|
||||||
|
url: url.replace("id", $("#positionSelect").val()),
|
||||||
|
method: 'GET'
|
||||||
|
}).then(function (data) {
|
||||||
|
$.each(data, function (index, value) {
|
||||||
|
const row = $("<tr>");
|
||||||
|
const number = $("<th>")
|
||||||
|
.attr("scope", "row")
|
||||||
|
.text(index + 1);
|
||||||
|
const id = $("<td>").text(value.id);
|
||||||
|
const surname = $("<td>").text(value.surname);
|
||||||
|
const name = $("<td>").text(value.name);
|
||||||
|
const positions = $("<td>").text(value.positions.map(x => x.name).join(", "));
|
||||||
|
const phoneNumber = $("<td>").text(value.phoneNumber);
|
||||||
|
|
||||||
|
const company = $("<td>").html(`<a href="/company/one/${value.company.id}">${value.company.name}</a>`);
|
||||||
|
row.append(number);
|
||||||
|
row.append(id);
|
||||||
|
row.append(surname);
|
||||||
|
row.append(name);
|
||||||
|
row.append(positions);
|
||||||
|
row.append(phoneNumber);
|
||||||
|
row.append(company);
|
||||||
|
$("#employees").append(row);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</th:block>
|
||||||
|
</html>
|
28
src/main/resources/templates/signup.html
Normal file
28
src/main/resources/templates/signup.html
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en"
|
||||||
|
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||||
|
layout:decorate="~{default}">
|
||||||
|
<body>
|
||||||
|
<div class="container container-padding" layout:fragment="content">
|
||||||
|
<div th:if="${errors}" th:text="${errors}" class="margin-bottom alert alert-danger"></div>
|
||||||
|
<form action="#" th:action="@{/signup}" th:object="${userDto}" method="post">
|
||||||
|
<div class="mb-3">
|
||||||
|
<input type="text" class="form-control" th:field="${userDto.login}"
|
||||||
|
placeholder="Логин" required="true" autofocus="true" maxlength="64"/>
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<input type="password" class="form-control" th:field="${userDto.password}"
|
||||||
|
placeholder="Пароль" required="true" minlength="6" maxlength="64"/>
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<input type="password" class="form-control" th:field="${userDto.passwordConfirm}"
|
||||||
|
placeholder="Пароль (подтверждение)" required="true" minlength="6" maxlength="64"/>
|
||||||
|
</div>
|
||||||
|
<div class="mb-3">
|
||||||
|
<button type="submit" class="btn btn-success button-fixed">Создать</button>
|
||||||
|
<a class="btn btn-primary button-fixed" href="/login">Назад</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
37
src/main/resources/templates/users.html
Normal file
37
src/main/resources/templates/users.html
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en"
|
||||||
|
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||||
|
layout:decorate="~{default}">
|
||||||
|
<body>
|
||||||
|
<div class="container" layout:fragment="content">
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th scope="col">#</th>
|
||||||
|
<th scope="col">ID</th>
|
||||||
|
<th scope="col">Логин</th>
|
||||||
|
<th scope="col">Роль</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr th:each="user, iterator: ${users}">
|
||||||
|
<th scope="row" th:text="${iterator.index} + 1"></th>
|
||||||
|
<td th:text="${user.id}"></td>
|
||||||
|
<td th:text="${user.login}" style="width: 60%"></td>
|
||||||
|
<td th:text="${user.role}" style="width: 20%"></td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div th:if="${totalPages > 0}" class="pagination">
|
||||||
|
<span style="float: left; padding: 5px 5px;">Страницы:</span>
|
||||||
|
<a th:each="page : ${pages}"
|
||||||
|
th:href="@{/users(page=${page}, size=${users.size})}"
|
||||||
|
th:text="${page}"
|
||||||
|
th:class="${page == users.number + 1} ? active">
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
118
src/test/java/com/example/springip/CompanyServiceTests.java
Normal file
118
src/test/java/com/example/springip/CompanyServiceTests.java
Normal file
@ -0,0 +1,118 @@
|
|||||||
|
package com.example.springip;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.models.Company;
|
||||||
|
import com.example.springip.lab3.models.Employee;
|
||||||
|
import com.example.springip.lab3.service.CompanyService;
|
||||||
|
import com.example.springip.lab3.service.EmployeeService;
|
||||||
|
import jakarta.persistence.EntityNotFoundException;
|
||||||
|
import org.junit.jupiter.api.Assertions;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
|
||||||
|
import java.util.NoSuchElementException;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
public class CompanyServiceTests {
|
||||||
|
@Autowired
|
||||||
|
private CompanyService companyService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private EmployeeService employeeService;
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testDeleteAllCompanies() {
|
||||||
|
companyService.deleteAllCompanies();
|
||||||
|
int n = 3;
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
String name = "Company" + i;
|
||||||
|
companyService.addCompany(name);
|
||||||
|
}
|
||||||
|
companyService.deleteAllCompanies();
|
||||||
|
Assertions.assertEquals(companyService.findAllCompanies().size(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testDeleteCompany() {
|
||||||
|
companyService.deleteAllCompanies();
|
||||||
|
String name = "Company1";
|
||||||
|
Company c = companyService.addCompany(name);
|
||||||
|
companyService.deleteCompany(c.getId());
|
||||||
|
Assertions.assertThrows(EntityNotFoundException.class, () -> {companyService.findCompany(c.getId());});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testAddCompany() {
|
||||||
|
companyService.deleteAllCompanies();
|
||||||
|
String name = "Company1";
|
||||||
|
Company c = companyService.addCompany(name);
|
||||||
|
Assertions.assertNotNull(companyService.findCompany(c.getId()));
|
||||||
|
companyService.deleteAllCompanies();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testUpdateCompany() {
|
||||||
|
companyService.deleteAllCompanies();
|
||||||
|
String name = "Company1";
|
||||||
|
Company c = companyService.addCompany(name);
|
||||||
|
String name2 = "Company2";
|
||||||
|
companyService.updateCompany(c.getId(), name2);
|
||||||
|
Assertions.assertNotNull(companyService.findCompany(c.getId()));
|
||||||
|
companyService.deleteAllCompanies();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testFindAllCompanies() {
|
||||||
|
companyService.deleteAllCompanies();
|
||||||
|
int n = 3;
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
String name = "Company" + i;
|
||||||
|
companyService.addCompany(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assertions.assertEquals(companyService.findAllCompanies().size(), n);
|
||||||
|
companyService.deleteAllCompanies();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testAddEmployee() {
|
||||||
|
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
companyService.deleteAllCompanies();
|
||||||
|
|
||||||
|
|
||||||
|
final String name = "Company";
|
||||||
|
Company c = companyService.addCompany(name);
|
||||||
|
Employee newEmployee = employeeService.addEmployee("cha", "chacha", "111");
|
||||||
|
companyService.addNewEmployee(c.getId(), newEmployee);
|
||||||
|
|
||||||
|
Assertions.assertTrue(companyService.findCompany(c.getId()).getEmployees().contains(newEmployee));
|
||||||
|
|
||||||
|
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
companyService.deleteAllCompanies();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testDeleteEmployee() {
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
companyService.deleteAllCompanies();
|
||||||
|
|
||||||
|
|
||||||
|
final String name = "Company";
|
||||||
|
Company c = companyService.addCompany(name);
|
||||||
|
Employee newEmployee = employeeService.addEmployee("cha", "chacha", "111");
|
||||||
|
|
||||||
|
companyService.addNewEmployee(c.getId(), newEmployee);
|
||||||
|
Assertions.assertTrue(companyService.findCompany(c.getId()).getEmployees().contains(newEmployee));
|
||||||
|
|
||||||
|
companyService.deleteEmployee(c.getId(), newEmployee);
|
||||||
|
Assertions.assertFalse(companyService.findCompany(c.getId()).getEmployees().contains(newEmployee));
|
||||||
|
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
companyService.deleteAllCompanies();
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
123
src/test/java/com/example/springip/EmployeeServiceTests.java
Normal file
123
src/test/java/com/example/springip/EmployeeServiceTests.java
Normal file
@ -0,0 +1,123 @@
|
|||||||
|
package com.example.springip;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.models.Company;
|
||||||
|
import com.example.springip.lab3.models.Employee;
|
||||||
|
import com.example.springip.lab3.models.Position;
|
||||||
|
import com.example.springip.lab3.service.CompanyService;
|
||||||
|
import com.example.springip.lab3.service.EmployeeService;
|
||||||
|
import com.example.springip.lab3.service.PositionService;
|
||||||
|
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 EmployeeServiceTests {
|
||||||
|
@Autowired
|
||||||
|
private EmployeeService employeeService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CompanyService companyService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private PositionService positionService;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testAddEmployee() {
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
|
||||||
|
employeeService.addEmployee("name", "surname", "111");
|
||||||
|
Assertions.assertEquals(1, employeeService.findAllEmployees().size());
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testUpdateEmployee() {
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
final String newName = "name";
|
||||||
|
|
||||||
|
Employee e = employeeService.addEmployee("surname", "name", "111");
|
||||||
|
employeeService.updateEmployee(e.getId(),e.getSurname(), newName, e.getPhoneNumber());
|
||||||
|
Assertions.assertEquals(newName, employeeService.findEmployee(e.getId()).getName());
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testDeleteEmployee() {
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
|
||||||
|
Employee e = employeeService.addEmployee("name", "surname", "111");
|
||||||
|
employeeService.deleteEmployee(e.getId());
|
||||||
|
Assertions.assertEquals(0, employeeService.findAllEmployees().size());
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testFindAllEmployee() {
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
int n = 3;
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
employeeService.addEmployee("name", "surname", "111");
|
||||||
|
}
|
||||||
|
Assertions.assertEquals(n, employeeService.findAllEmployees().size());
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testAddCompany() {
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
companyService.deleteAllCompanies();
|
||||||
|
|
||||||
|
Employee e = employeeService.addEmployee("name", "surname", "111");
|
||||||
|
Company c = companyService.addCompany("Comp");
|
||||||
|
companyService.addNewEmployee(c.getId(), e);
|
||||||
|
Assertions.assertEquals(c, employeeService.findEmployee(e.getId()).getCompany());
|
||||||
|
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
companyService.deleteAllCompanies();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testDeleteFromCompany() {
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
companyService.deleteAllCompanies();
|
||||||
|
|
||||||
|
Employee e = employeeService.addEmployee("name", "surname", "111");
|
||||||
|
Company c = companyService.addCompany("Comp");
|
||||||
|
|
||||||
|
employeeService.addCompany(e.getId(), c);
|
||||||
|
Assertions.assertEquals(c, employeeService.findEmployee(e.getId()).getCompany());
|
||||||
|
|
||||||
|
employeeService.deleteCompany(e.getId());
|
||||||
|
Assertions.assertNull(employeeService.findEmployee(e.getId()).getCompany());
|
||||||
|
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
companyService.deleteAllCompanies();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetByPosition() {
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
positionService.deleteAllPositions();
|
||||||
|
|
||||||
|
Position p = positionService.addPosition("Position 1");
|
||||||
|
Position p2 = positionService.addPosition("Position 2");
|
||||||
|
|
||||||
|
final int n = 10;
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
Employee e = employeeService.addEmployee("1111", "name" + i, "surname");
|
||||||
|
if (i % 2 == 0) {
|
||||||
|
employeeService.addPosition(e.getId(), p);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
employeeService.addPosition(e.getId(), p2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Assertions.assertEquals(n / 2, employeeService.getEmployeesByPosition(p).size());
|
||||||
|
Assertions.assertEquals(n / 2, employeeService.getEmployeesByPosition(p2).size());
|
||||||
|
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
positionService.deleteAllPositions();
|
||||||
|
}
|
||||||
|
}
|
56
src/test/java/com/example/springip/PositionServiceTests.java
Normal file
56
src/test/java/com/example/springip/PositionServiceTests.java
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
package com.example.springip;
|
||||||
|
|
||||||
|
import com.example.springip.lab3.models.Employee;
|
||||||
|
import com.example.springip.lab3.models.Position;
|
||||||
|
import com.example.springip.lab3.service.EmployeeService;
|
||||||
|
import com.example.springip.lab3.service.PositionService;
|
||||||
|
import org.junit.jupiter.api.Assertions;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
public class PositionServiceTests {
|
||||||
|
@Autowired
|
||||||
|
private PositionService positionService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private EmployeeService employeeService;
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testAddEmployee() {
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
positionService.deleteAllPositions();
|
||||||
|
|
||||||
|
Position p = positionService.addPosition("Position");
|
||||||
|
Employee e = employeeService.addEmployee("1", "2", "33");
|
||||||
|
|
||||||
|
employeeService.addPosition(e.getId(), p);
|
||||||
|
Assertions.assertTrue(employeeService.findEmployee(e.getId()).getPositions().contains(p));
|
||||||
|
Assertions.assertTrue(positionService.findPosition(p.getId()).getEmployees().contains(e));
|
||||||
|
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
positionService.deleteAllPositions();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testDeleteEmployee() {
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
positionService.deleteAllPositions();
|
||||||
|
|
||||||
|
Position p = positionService.addPosition("Position");
|
||||||
|
Employee e = employeeService.addEmployee("1", "2", "33");
|
||||||
|
|
||||||
|
employeeService.addPosition(e.getId(), p);
|
||||||
|
employeeService.deletePosition(e.getId(), p);
|
||||||
|
Assertions.assertFalse(employeeService.findEmployee(e.getId()).getPositions().contains(p));
|
||||||
|
Assertions.assertFalse(positionService.findPosition(p.getId()).getEmployees().contains(e));
|
||||||
|
|
||||||
|
employeeService.deleteAllEmployees();
|
||||||
|
positionService.deleteAllPositions();
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,61 @@
|
|||||||
|
package com.example.springip;
|
||||||
|
|
||||||
|
import com.example.springip.lab2.service.OperationService;
|
||||||
|
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
|
||||||
|
class SpringipApplicationTests {
|
||||||
|
@Autowired
|
||||||
|
OperationService operationService;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSumString() {
|
||||||
|
final String res = (String) operationService.sum("Привет ", "Мир!", "str");
|
||||||
|
Assertions.assertEquals("Привет Мир!", res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSumNum() {
|
||||||
|
final Integer res = (Integer) operationService.sum(1, 2, "num");
|
||||||
|
Assertions.assertEquals(3, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testMulString() {
|
||||||
|
final String res = (String) operationService.mul("A", 4, "str");
|
||||||
|
Assertions.assertEquals("AAAA", res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testMulNum() {
|
||||||
|
final Integer res = (Integer) operationService.mul(2, 4, "num");
|
||||||
|
Assertions.assertEquals(8, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testLengthString() {
|
||||||
|
final Integer res = (Integer) operationService.length("Hello", "str");
|
||||||
|
Assertions.assertEquals(5, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testLengthNum() {
|
||||||
|
final Integer res = (Integer) operationService.length(777,"num");
|
||||||
|
Assertions.assertEquals(3, res);
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void testStWString() {
|
||||||
|
final boolean res = (boolean) operationService.startsWith("Orange","Or", "str");
|
||||||
|
Assertions.assertEquals(true, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testStWNum() {
|
||||||
|
final boolean res = (boolean) operationService.startsWith(777, 77, "num");
|
||||||
|
Assertions.assertEquals(true, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
BIN
отчеты/Отчёт 1.docx
Normal file
BIN
отчеты/Отчёт 1.docx
Normal file
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user