Compare commits

...

26 Commits
main ... Lab07

Author SHA1 Message Date
195330c1e2 Отчет 2023-06-15 22:02:46 +04:00
1186635546 Любовь, ненависть, боль, наслаждение, жизнь, смерть. Здесь есть всё... Вот что значит — быть человеком. 2023-05-15 15:37:31 +04:00
0c672ab5e9 Мы все находимся в руках великого течения, которое называют судьбой. 2023-05-15 12:27:56 +04:00
dbe46aa061 Даже без великой мечты человек способен жить дальше. 2023-05-15 11:47:15 +04:00
d2682bd470 Что вершит судьбу человечества в этом мире? Некое незримое существо или закон, подобно Длани Господней парящей над миром? По крайне мере истинно то, что человек не властен даже над своей волей. 2023-05-15 01:45:45 +04:00
adf7148a18 Commit message2. 2023-05-15 01:29:26 +04:00
0bcf6791d3 Commit message. 2023-05-15 01:25:15 +04:00
f6d23f860d Чиним чиним 2023-05-14 20:39:33 +04:00
b9ce279df5 Вот теперь доделал MVC (я умру с реактом) 2023-05-14 19:33:35 +04:00
10bc9bdb69 Доделал дезигн 2023-05-14 19:16:12 +04:00
9afbf32743 Почему то не отправляетсчя build.gradle 2023-05-14 17:49:13 +04:00
b9f3c91d08 Перенес все на новую версию, + сделал MVC 2023-05-14 17:45:44 +04:00
d97e9324a7 Фух, надеюсь, как у *Кое-кого* не попросит доп.задание... 2023-05-02 13:57:02 +04:00
eeaea74c2f Абалдеть, я сдал.... 2023-05-02 10:16:22 +04:00
ff2d56d0a6 Удаление не нужного 2023-05-01 23:06:43 +04:00
4a9ed45050 Вроде бы сделал... 2023-05-01 22:54:14 +04:00
2d6c7a0029 Лаб4 показана 2023-04-17 22:54:30 +04:00
e9d10a9578 Вроде бы сделал лаб 4 2023-04-16 21:10:13 +04:00
bbeb090ec4 Абалдеть, я сдал... 2023-04-04 12:30:07 +04:00
478aea525a 3 Лабораторная с доп заданием 2 2023-04-03 20:35:36 +04:00
c8a4f68073 3 Лабораторная с доп заданием 2023-04-02 23:12:42 +04:00
d65fd982d0 Шаг 1. Сданная лабораторная работа 2023-03-06 16:10:25 +04:00
d39b23c64d Шаг 1. Лабораторная работа 2023-03-05 16:53:50 +04:00
362b892de6 Отчёт 2023-02-19 14:24:20 +04:00
1b59c23805 front 2023-02-06 16:55:23 +04:00
504c935b72 Add spring 2023-02-06 16:43:26 +04:00
90 changed files with 9641 additions and 31 deletions

Binary file not shown.

View File

@ -1,10 +1,10 @@
plugins {
id 'java'
id 'org.springframework.boot' version '2.7.8'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
id 'org.springframework.boot' version '3.0.6'
id 'io.spring.dependency-management' version '1.1.0'
}
group = 'ru.ulstu.is'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
@ -13,9 +13,16 @@ repositories {
}
dependencies {
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'com.h2database:h2:2.1.210'
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.4'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'com.auth0:java-jwt:4.4.0'
testImplementation 'org.springframework.boot:spring-boot-starter-test'}
tasks.named('test') {
useJUnitPlatform()

BIN
data.mv.db Normal file

Binary file not shown.

24
frontend/.gitignore vendored Normal file
View File

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

19
frontend/data.json Normal file
View File

@ -0,0 +1,19 @@
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
],
"profile": {
"name": "typicode"
}
}

32
frontend/index.html Normal file
View File

@ -0,0 +1,32 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="/node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"
integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3"
crossorigin="anonymous"
></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.min.js"
integrity="sha384-IDwe1+LCz02ROU9k972gdyvl+AESN10+x7tBKgc9I5HFtuNz0wWnPclzo6p9vxnk"
crossorigin="anonymous"
></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>Кашин Максим ПИбд-22</title>
</head>
<body class="d-flex flex-column h-100">
<div id="app"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

5764
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

29
frontend/package.json Normal file
View File

@ -0,0 +1,29 @@
{
"name": "spa-react",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"fake-server": "json-server --watch data.json -p 8081",
"start": "npm-run-all --parallel dev fake-server",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.4",
"axios": "^1.1.3",
"bootstrap": "^5.2.2",
"@fortawesome/fontawesome-free": "^6.2.1"
},
"devDependencies": {
"@types/react": "^18.0.24",
"@types/react-dom": "^18.0.8",
"vite": "^3.2.3",
"@vitejs/plugin-react": "^2.2.0",
"npm-run-all": "^4.1.5",
"json-server": "^0.17.1"
}
}

93
frontend/src/App.css Normal file
View File

@ -0,0 +1,93 @@
nav {
background-color: #708090;
}
main {
background-color: #ffffff;
/* min-height: 90vh; */
}
footer {
background-color: #708090;
color: black;
position: absolute;
bottom: 0;
width: 100vw;
}
.size {
overflow-x: hidden;
}
.card {
background-color: #bdb1b1;
border-color: #8c7b7b;
}
.card-body {
background-color: #8c7b7b;
}
h1 {
word-wrap: break-word;
}
#banner {
margin: 0px 15px 15px 15px;
padding-top: 15px;
display: flex;
align-items: center;
flex-direction: column;
}
#banner img {
border-radius: 5px;
}
#banner img.show {
width: 100%;
opacity: 1;
transition: opacity 1s, visibility 0s;
}
#banner img.hide {
height: 0;
width: 0;
opacity: 0;
visibility: hidden;
transition: opacity 1s, visibility 0s 1s;
}
@media (max-width: 767px) {
.btn {
padding: 1px 5px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.btn {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.btn {
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
border-radius: 4px;
}
}
@media (min-width: 1200px) {
.btn {
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333;
border-radius: 6px;
}
}
@media (max-width: 600px) {
.tem {
padding-right: 50px;
}
}
.vl {
border-left: 5px solid;
height: 100vh;
}

61
frontend/src/App.jsx Normal file
View File

@ -0,0 +1,61 @@
import './App.css';
import { useRoutes,
Outlet,
BrowserRouter,
Routes,
Route, } from 'react-router-dom';
import Header from './components/common/Header';
import Footer from "./components/common/Footer";
import CatalogBuyers from './components/catalogs/CatalogBuyers';
import { useState } from 'react';
import CarInfo from './components/catalogs/CarInfo';
import CatalogStores from './components/catalogs/CatalogStores';
import Find from './components/catalogs/Find';
import SignUpPage from './components/catalogs/SignUpPage';
import LoginPage from './components/catalogs/LoginPage';
import PrivateRoutes from './services/PrivateRoutes';
import Users from "./components/catalogs/CatalogUsers";
import Ucant from './components/catalogs/Ucant';
function Router(props) {
return useRoutes(props.rootRoute);
}
export default function App() {
const [car,setCar] = useState([]);
const routes = [
{ index: true, element: <CatalogBuyers /> },
{ path: "catalogs/store" , label: "Магазины", },
{ path: "catalogs/buyer", label: "Покупатели", },
{ path: "catalogs/car", label: "Машины", },
{ path: "catalog/users", label: "Пользователи",},
{ path: "catalogs/find", label: "Отчет", },
{ path: '/login', label: "Авторизация",},
];
const links = routes.filter(route => route.hasOwnProperty('label'));
return (
<>
<BrowserRouter>
<Header links={links}/>
<div className="content-div">
<Routes>
<Route element={<PrivateRoutes role="USER"/>}>
<Route element={<Find/>} path="catalogs/find"/>
</Route>
<Route element={<PrivateRoutes role="ADMIN"/>}>
<Route element={<Users/>} path="catalog/users"/>
<Route element={<CatalogStores />} path="catalogs/store"/>
<Route element={<CatalogBuyers/>} path="catalogs/buyer"/>
<Route element={<CarInfo/>} path="catalogs/car"/>
</Route>
<Route element={<LoginPage/>} path="/login"/>
<Route element={<SignUpPage/>} path="catalog/signup"/>
<Route element={<Ucant/>} path="/err"/>
</Routes>
</div>
<Footer/>
</BrowserRouter>
</>
);
}

View File

@ -0,0 +1,135 @@
import { useState, useEffect, Component } from "react";
import CatalogCar from "./CatalogCars.jsx";
import Store from "../../models/Store";
import Buyer from "../../models/Buyer";
import Car from "../../models/Car";
import DataService from "../../services/DataService";
export default function Menustores(props) {
const url = "/car";
const prodUrl = "/store";
const workUrl = "/buyer"
const transformer = (data) => new Car(data);
const catalogProdHeaders = [
{ name: "storeName", label: "Название магазина" },
];
const catalogWorkHeaders = [
{ name: "buyerFirstName", label: "Имя" },
{ name: "buyerSecondName", label: "Фамилия" },
];
const [data, setData] = useState(new Car());
const [store, setStore] = useState([]);
const [workStore, setWorkStore] = useState([]);
const [buyer, setBuyer] = useState([]);
const [workBuyer, setWorkBuyer] = useState([]);
useEffect(() => {
DataService.readAll(prodUrl, (data) => new Store(data)).then(
(data) => setStore(data)
);
DataService.readAll(workUrl, (data) => new Buyer(data)).then(
(data) => setBuyer(data)
);
}, []);
function handleOnAdd() {
setData(new Car());
setWorkStore([]);
setWorkBuyer([]);
}
function handleOnEdit(data) {
setData(new Car(data));
}
function handleFormChange(event) {
setData({ ...data, [event.target.id]: event.target.value });
}
function handleUpdateStores(value) {
let temp = data.storeDTOList.filter((x) => x.id != value.id);
data.storeDTOList = [];
for (let i = 0; i < temp.length; i++) {
data.storeDTOList.push(temp[i]);
}
data.storeDTOList.push(value);
setData(data);
console.log(data);
setWorkStore();
}
function setCar() {
data.storeDTOList = [];
for (let i = 0; i < workStore.length; i++) {
data.storeDTOList.push(workStore[i]);
}
data.buyerDTOList = [];
for (let i = 0; i < workBuyer.length; i++) {
data.buyerDTOList.push(workBuyer[i]);
}
setData(data);
}
function handleDeleteStores(value) {
let temp = data.storeDTOList.filter((x) => x.id != value);
data.storeDTOList = [];
for (let i = 0; i < temp.length; i++) {
data.storeDTOList.push(temp[i]);
}
console.log(data);
setData(data);
setWorkStore(workStore.filter((x) => x.id !== value));
console.log(workStore);
}
function handleUpdateBuyers(value){
let temp = data.buyerDTOList.filter((x) => x.id != value.id);
data.buyerDTOList = [];
for (let i = 0; i < temp.length; i++) {
data.buyerDTOList.push(temp[i]);
}
data.buyerDTOList.push(value);
setData(data);
console.log(data);
setWorkBuyer(data.buyerDTOList);
console.log(workBuyer);
}
function handleDeleteBuyers(value) {
let temp = data.buyerDTOList.filter((x) => x.id != value);
data.buyerDTOList = [];
for (let i = 0; i < temp.length; i++) {
data.buyerDTOList.push(temp[i]);
}
console.log(data);
setData(data);
setWorkBuyer(workBuyer.filter((x) => x.id !== value));
console.log(workBuyer);
}
return (
<main className="flex-shrink-0">
<CatalogCar
url={url}
transformer={transformer}
data={data}
onAdd={handleOnAdd}
onEdit={handleOnEdit}
handleFormChange={handleFormChange}
set={setCar}
car={props.car}
setCar={props.setCar}
store={store}
catalogProdHeaders={catalogProdHeaders}
workStore={workStore}
setWorkStore={setWorkStore}
updateStores={handleUpdateStores}
deleteStores={handleDeleteStores}
buyer={buyer}
catalogWorkHeaders={catalogWorkHeaders}
workBuyer={workBuyer}
setWorkBuyer={setWorkBuyer}
updateBuyers={handleUpdateBuyers}
deleteBuyers={handleDeleteBuyers}
/>
</main>
);
}

View File

@ -0,0 +1,114 @@
import { useState, useEffect } from "react";
import Toolbar from "../common/Toolbar";
import Table from "../common/Table";
import Modal from "../common/Modal";
import DataService from '../../services/DataService';
export default function CatalogW(props) {
const [items, setItems] = useState([]);
const [modalHeader, setModalHeader] = useState('');
const [modalConfirm, setModalConfirm] = useState('');
const [modalVisible, setModalVisible] = useState(false);
const [isEdit, setEdit] = useState(false);
let selectedItems = [];
useEffect(() => {
loadItems();
}, []);
function loadItems() {
DataService.readAll(props.getAllUrl, props.transformer)
.then(data => setItems(data));
}
function saveItem() {
console.log(props.data);
if (!isEdit) {
DataService.create(props.getAllUrl, props.data).then(() => loadItems());
} else {
DataService.update(props.url + props.data.id, props.data).then(() => loadItems());
}
}
function handleAdd() {
setEdit(false);
setModalHeader('Добавление элемента');
setModalConfirm('Добавить');
setModalVisible(true);
props.onAdd();
}
function handleEdit() {
if (selectedItems.length === 0) {
return;
}
edit(selectedItems[0]);
}
function edit(editedId) {
DataService.read(props.url + editedId, props.transformer)
.then(data => {
setEdit(true);
setModalHeader('Редактирование элемента');
setModalConfirm('Сохранить');
setModalVisible(true);
props.onEdit(data);
});
}
function handleRemove() {
if (selectedItems.length === 0) {
return;
}
if (confirm('Удалить выбранные элементы?')) {
const promises = [];
selectedItems.forEach(item => {
promises.push(DataService.delete(props.url + item));
});
Promise.all(promises).then((results) => {
selectedItems.length = 0;
loadItems();
});
}
}
function handleTableClick(tableSelectedItems) {
selectedItems = tableSelectedItems;
}
function handleTableDblClick(tableSelectedItem) {
edit(tableSelectedItem);
}
function handleModalHide() {
setModalVisible(false);
}
function handleModalDone() {
saveItem();
}
return (
<>
<Toolbar
onAdd={handleAdd}
onEdit={handleEdit}
onRemove={handleRemove}/>
<Table
headers={props.headers}
items={items}
selectable={true}
onClick={handleTableClick}
onDblClick={handleTableDblClick}/>
<Modal
header={modalHeader}
confirm={modalConfirm}
visible={modalVisible}
onHide={handleModalHide}
onDone={handleModalDone}>
{props.children}
</Modal>
</>
);
}

View File

@ -0,0 +1,54 @@
import { useState, useEffect } from 'react';
import Catalog from './Catalog';
import Buyer from '../../models/Buyer';
import DataService from '../../services/DataService';
export default function CatalogBuyers(props) {
const getAllUrl = '/buyer';
const url = '/buyer/';
const transformer = (data) => new Buyer(data);
const catalogBuyerHeaders = [
{ name:"id", label:"ID"},
{ name: 'buyerFirstName', label: 'Имя' },
{ name: 'buyerSecondName', label: 'Фамилия' },
];
const [data, setData] = useState(new Buyer());
function handleOnAdd() {
console.log("create buyer: " + data.buyerFirstName + "|" + data.buyerSecondName);
setData(new Buyer());
}
function handleOnEdit(data) {
setData(new Buyer(data));
}
function handleFormChange(event) {
setData({ ...data, [event.target.id]: event.target.value })
}
return (
<main className="flex-shrink-0" style={{ backgroundColor: "white" }}>
<Catalog
headers={catalogBuyerHeaders}
getAllUrl={getAllUrl}
url={url}
transformer={transformer}
data={data}
onAdd={handleOnAdd}
onEdit={handleOnEdit}>
<div className="mb-3">
<label htmlFor="buyerFirstName" className="form-label">Имя покупателя</label>
<input type="text" id="buyerFirstName" className="form-control" required
value={data.buyerFirstName} onChange={handleFormChange}/>
</div>
<div className="mb-3">
<label htmlFor="buyerSecondName" className="form-label">Фамилия покупателя</label>
<input type="text" id="buyerSecondName" className="form-control" required
value={data.buyerSecondName} onChange={handleFormChange}/>
</div>
</Catalog>
</main>
);
}

View File

@ -0,0 +1,313 @@
import { useState, useEffect, Component } from "react";
import ToolbarStore from "../common/ToolbarStore";
import Card from "../common/Card";
import Modal from "../common/Modal";
import DataService from "../../services/DataService";
import Table from "../common/Table";
import Toolbar from "../common/Toolbar";
export default function catalogP(props) {
const [items, setItems] = useState([]);
const [modalHeader, setModalHeader] = useState("");
const [modalConfirm, setModalConfirm] = useState("");
const [modalVisible, setModalVisible] = useState(false);
const [isEdit, setEdit] = useState(false);
const [StoreL, setStoreL] = useState({});
const [BuyerL, setBuyerL] = useState({});
useEffect(() => {
loadItems();
}, []);
function loadItems() {
DataService.readAll(props.url, props.transformer).then((data) =>{
setItems(data);
});
DataService.readAll(props.url, props.transformer).then((data) =>
setItems(data));
}
const catalogCarHeaders = [
{ name: 'carName', label: 'Название' },
// { name: 'storeDTOList.length', label: 'Количество магазинов'}
];
let selectedItems = [];
async function saveItem() {
console.log(props.data);
if (!isEdit) {
await props.set();
DataService.create(props.url, props.data).then(() => loadItems());
} else {
await props.set();
DataService.update(props.url + "/" + props.data.id, props.data).then(() =>
loadItems()
);
}
}
function handleRemoveCard(id) {
if (confirm("Удалить выбранные элементы?")) {
DataService.delete(props.url + "/" + id).then(() => {
loadItems();
});
}
}
function handleRemove() {
if (selectedItems.length === 0) {
return;
}
if (confirm('Удалить выбранные элементы?')) {
const promises = [];
selectedItems.forEach(item => {
promises.push(DataService.delete(props.url + "/" + item));
});
Promise.all(promises).then((results) => {
selectedItems.length = 0;
loadItems();
});
}
}
function handleAdd() {
setEdit(false);
setModalHeader("Добавление элемента");
setModalConfirm("Добавить");
setModalVisible(true);
props.onAdd();
}
function handleEdit(id) {
if (selectedItems.length === 0) {
return;
}
setStoreL(
props.workStore.filter((x) => x.id == selectedItems[0])[0]
);
}
function edit(editedId) {
DataService.read(props.url+ "/" + editedId, props.transformer).then((data) => {
for(let i = 0; i < data.storeDTOList.length; i++){
props.workStore.push(data.storeDTOList[i]);
props.setWorkStore(props.workStore)
}
for(let i = 0; i < data.buyerDTOList.length; i++){
props.workBuyer.push(data.buyerDTOList[i]);
//props.setworkBuyer(props.workBuyer)
}
setEdit(true);
setModalHeader("Редактирование элемента");
setModalConfirm("Сохранить");
setModalVisible(true);
props.onEdit(data);
});
}
function handleModalDone() {
saveItem();
}
function handleModalHide() {
setModalVisible(false);
props.setWorkStore([]);
props.setWorkBuyer([]);
}
function handleRemoveStore(id, e) {
if (selectedItems.length === 0) {
return;
}
if (confirm("Удалить выбранные элементы?")) {
const promises = [];
selectedItems.forEach((item) => {
props.deleteStores(item);
});
selectedItems.length = 0;
}
}
function handleRemoveBuyer(id, e) {
if (selectedItems.length === 0) {
return;
}
if (confirm("Удалить выбранные элементы?")) {
const promises = [];
selectedItems.forEach((item) => {
props.deleteBuyers(item);
});
selectedItems.length = 0;
}
}
async function handleAddStore() {
if (props.workStore.filter((x) => x.id == StoreL.id).length == 0)
{
await props.updateStores(StoreL);
setStoreL({});
props.workStore.push(StoreL);
await props.setWorkStore(props.workStore);
setStoreL({});
return;
}
}
async function handleAddBuyer() {
if (props.workBuyer.filter((x) => x.id == BuyerL.id).length == 0)
{
await props.updateBuyers(BuyerL);
setBuyerL({});
props.workBuyer.push(BuyerL);
await props.setWorkBuyer(props.workBuyer);
setBuyerL({});
return;
}
}
function handleFormChangeStore(event) {
if (event.target.id === "storeName") {
setStoreL({
...StoreL,
["id"]: event.target.value,
["storeName"]: props.store
.filter((x) => x.id == event.target.value)
.map((x) => x.storeName)[0],
});
return;
}
setStoreL({
...StoreL,
[event.target.id]: Number(event.target.value),
});
return;
}
function handleFormChangeBuyer(event) {
if (event.target.id === "buyerSecondName") {
setBuyerL({
...BuyerL,
["id"]: event.target.value,
["buyerFirstName"]: props.buyer
.filter((x) => x.id == event.target.value)
.map((x) => x.buyerFirstName)[0],
["buyerSecondName"]: props.buyer
.filter((x) => x.id == event.target.value)
.map((x) => x.buyerSecondName)[0],
});
return;
}
setBuyerL({
...BuyerL,
[event.target.id]: Number(event.target.value),
});
return;
}
function handleTableClick(tableSelectedItems) {
selectedItems = tableSelectedItems;
}
function handleTableDblClickModalProd(tableSelectedItem) {
setStoreL(
props.workStore.filter((x) => x.id == tableSelectedItem)[0]
);
}
function handleTableDblClick(tableSelectedItem) {
edit(tableSelectedItem);
}
return (
<>
{/* <ToolbarStore onAdd={handleAdd} />
<Card items={items} onEdit={edit} onRemove={handleRemoveCard} car={props.car} setCar={props.setCar}/> */}
<Modal
header={modalHeader}
confirm={modalConfirm}
visible={modalVisible}
onHide={handleModalHide}
onDone={handleModalDone}
>
<div className="mb-3">
<label htmlFor="name" className="form-label">
Название машины
</label>
<input
type="text"
id="carName"
className="form-control"
required
value={props.data.carName}
onChange={props.handleFormChange}
/>
</div>
<div className="mb-3">
<label htmlFor="groupId" className="form-label">
Магазин
</label>
<select
id="storeName"
className="form-select"
required
value={StoreL.id}
onChange={handleFormChangeStore}
>
<option disabled value="">
Укажите магазин
</option>
{props.store.map((group) => (
<option key={group.id} value={group.id}>
{group.storeName}
</option>
))}
</select>
</div>
<Toolbar
onAdd={handleAddStore}
onEdit={handleEdit}
onRemove={handleRemoveStore}
/>
<Table
headers={props.catalogProdHeaders}
items={props.workStore}
allItems={props.store}
selectable={true}
onClick={handleTableClick}
onDblClick={handleTableDblClickModalProd}
/>
<div className="mb-3">
<label htmlFor="groupId" className="form-label">
Покупатель
</label>
<select
id="buyerSecondName"
className="form-select"
required
value={BuyerL.id}
onChange={handleFormChangeBuyer}
>
<option disabled value="">
Укажите рабочего
</option>
{props.buyer.map((group) => (
<option key={group.id} value={group.id}>
{group.buyerFirstName} {group.buyerSecondName}
</option>
))}
</select>
</div>
<Toolbar
onAdd={handleAddBuyer}
onEdit={handleEdit}
onRemove={handleRemoveBuyer}
/>
<Table
headers={props.catalogWorkHeaders}
items={props.workBuyer}
allItems={props.buyer}
selectable={true}
onClick={handleTableClick}
onDblClick={handleTableDblClickModalProd}
/>
</Modal>
<Toolbar
onAdd={handleAdd}
onEdit={handleEdit}
onRemove={handleRemove}
/>
<Table
headers={catalogCarHeaders}
items={items}
selectable={true}
onClick={handleTableClick}
onDblClick={handleTableDblClick}
/>
</>
);
}

View File

@ -0,0 +1,48 @@
import { useState, useEffect } from 'react';
import Catalog from './Catalog';
import Store from '../../models/Store';
import DataService from '../../services/DataService';
export default function CatalogStores(props) {
const getAllUrl = '/store';
const url = '/store/';
const transformer = (data) => new Store(data);
const catalogStudHeaders = [
{ name:"id", label:"ID"},
{ name: 'storeName', label: 'Название' }
];
const [data, setData] = useState(new Store());
function handleOnAdd() {
setData(new Store());
console.log("create store: " + data.storeName);
}
function handleOnEdit(data) {
setData(new Store(data));
}
function handleFormChange(event) {
setData({ ...data, [event.target.id]: event.target.value })
}
return (
<main className="flex-shrink-0" style={{ backgroundColor: "white" }}>
<Catalog
headers={catalogStudHeaders}
getAllUrl={getAllUrl}
url={url}
transformer={transformer}
data={data}
onAdd={handleOnAdd}
onEdit={handleOnEdit}>
<div className="mb-3">
<label htmlFor="storeName" className="form-label">Название</label>
<input type="text" id="storeName" className="form-control" required
value={data.storeName} onChange={handleFormChange}/>
</div>
</Catalog>
</main>
);
}

View File

@ -0,0 +1,74 @@
import { useState } from "react";
import { useEffect } from "react";
import DataService from "../../services/DataService";
export default function Users(props) {
const [users, setUsers] = useState([]);
const [pageNumbers, setPageNumbers] = useState([]);
const [pageNumber, setPageNumber] = useState();
const usersUrl = "/users";
const host = "http://localhost:8080";
useEffect(() => {
DataService.readUsersPage(host, usersUrl, 1).then((data) => {
setUsers(data.users.content);
setPageNumbers(data.pageNumbers);
setPageNumber(1);
});
}, []);
const pageButtonOnClick = function (page) {
DataService.readUsersPage(host, usersUrl, page).then((data) => {
setUsers(data.users.content);
setPageNumber(page);
});
};
return (
<main className="flex-shrink-0" style={{ backgroundColor: "white" }}>
<div className="table-shell mb-3">
<table className="table">
<thead>
<tr>
<th style={{ width: "15%"}} scope="col">
ID
</th>
<th style={{ width: "30%" }} scope="col">
Логин
</th>
<th style={{ width: "15%" }} scope="col">
Роль
</th>
</tr>
</thead>
<tbody>
{users.map((user, index) => (
<tr key={index}>
<td style={{ width: "15%" }}>{user.id}</td>
<td style={{ width: "30%" }}>{user.login}</td>
<td style={{ width: "15%" }}>{user.role}</td>
</tr>
))}
</tbody>
</table>
<div className="form-group d-flex align-items-center" style={{marginTop: "20px"}}>
<p style={{marginRight: "10px", marginBottom: "0"}}>Странички:</p>
<nav>
<ul className="pagination" style={{ backgroundColor: "white", marginBottom: "0" }}>
{pageNumbers.map((number, index) => (
<li key={index}
className={`page-item ${
number === pageNumber ? "active" : ""
}`}
onClick={() => pageButtonOnClick(number)}
>
<a className="btn btn-outline-dark" >
{number}
</a>
</li>
))}
</ul>
</nav>
</div>
</div>
</main>
);
}

View File

@ -0,0 +1,88 @@
import DataService from "../../services/DataService";
import Buyer from "../../models/Buyer";
import Store from "../../models/Store";
import Table from "../common/Table";
import { useState, useEffect, Component } from "react";
import '../../App.css';
export default function Find(props) {
const prodUrl = "/store";
const storeURL ='/store/buyer/';
const [itemsP, setItemsP] = useState([]);
const [StoreL, setStoreL] = useState({});
const [store, setStore] = useState([]);
const catalogBuyerHeaders = [
{ name: 'buyerFirstName', label: 'Имя' },
{ name: 'buyerSecondName', label: 'Фамилия' },
];
const transformer = (data) => new Buyer(data);
function loadItems() {
DataService.readAll(storeURL + StoreL.id, transformer)
.then(data => setItemsP(data));
}
useEffect(() => {
DataService.readAll(prodUrl, (data) => new Store(data)).then(
(data) => setStore(data)
);
}, []);
let selectedItems = [];
function handleTableClick(tableSelectedItems) {
selectedItems = tableSelectedItems;
}
function handleTableDblClick(tableSelectedItem) {
confirm(tableSelectedItem);
}
function handleFormChangeStore(event) {
if (event.target.id === "storeName") {
setStoreL({
...StoreL,
["id"]: event.target.value,
["storeName"]: store
.filter((x) => x.id == event.target.value)
.map((x) => x.storeName)[0],
});
return;
}
setStoreL({
...StoreL,
[event.target.id]: Number(event.target.value),
});
return;
}
return(
<main className="form-group" style={{ backgroundColor: "white" }}>
<select
id="storeName"
className="form-select"
value={StoreL.id}
onChange={handleFormChangeStore}
>
<option disabled selected value="">
Укажите магазин
</option>
{store.map((group) => (
<option key={group.id} value={group.id}>
{group.storeName}
</option>
))}
</select>
<a
class="btn btn-light d-flex justify-content-center align-items-center"
href="#"
type="button"
onClick={(e) => loadItems()}
>
Покупатели, которые пользуются выбранным магазином
</a>
<div className="d-flex ">
<Table className="table"
headers={catalogBuyerHeaders}
items={itemsP}
selectable={false}
onClick={handleTableClick}
onDblClick={handleTableDblClick}/>
</div>
</main>
);
}

View File

@ -0,0 +1,97 @@
import { useState, useEffect } from "react";
import { NavLink, useNavigate } from 'react-router-dom';import { useRef } from "react";
export default function LoginPage(props) {
const [login, setLogin] = useState("");
const [password, setPassword] = useState("");
const navigate = useNavigate();
useEffect(() => {
}, []);
const loginsystem = async function (login, password) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({login: login, password: password}),
};
const response = await fetch("http://localhost:8080/jwt/login", requestParams);
const result = await response.text();
if (response.status === 200) {
localStorage.setItem("token", result);
localStorage.setItem("user", login);
getRole(result);
} else {
localStorage.removeItem("token");
localStorage.removeItem("user");
localStorage.removeItem("role");
}
}
const getRole = async function (token) {
const requestParams = {
method: "GET",
headers: {
"Content-Type": "application/json"
}
};
const requestUrl = `http://localhost:8080/user?token=${token}`;
const response = await fetch(requestUrl, requestParams);
const result = await response.text();
localStorage.setItem("role", result);
window.dispatchEvent(new Event("storage"));
navigate("/catalogs/find");
}
const loginFormOnSubmit = function (event) {
event.preventDefault();
loginsystem(login, password);
};
return (
<main className="flex-shrink-0" style={{ backgroundColor: "white" }}>
<div className="text-center">
<h1 className="my-5 ms-5">
<b>Вход в систему</b>
</h1>
<form className="row g-3 text-center justify-content-center align-items-center" onSubmit={loginFormOnSubmit}>
<div className="mb-3 row text">
<div className="form-outline">
<input
placeholder="Логин"
className="form-control"
type="text"
id="login"
name="login"
value={login}
onChange={(e) => setLogin(e.target.value)}
/>
</div>
</div>
<div className="mb-3 row">
<div className="col">
<input
placeholder="Пароль"
className="form-control"
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
</div>
<div className="form-group ">
<div className="d-flex">
<button className="btn btn-light" style={{ color: "black" }}>
Войти
</button>
<NavLink className="navbar-brand" style={{marginLeft: "5vw", paddingTop:"1.5vh"}} to={"/catalog/signup"}>
<h5>Регистрация</h5>
</NavLink>
</div>
</div>
</form>
</div>
</main>
);
}

View File

@ -0,0 +1,106 @@
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useEffect } from "react";
import { Link } from 'react-router-dom';
import { useRef } from "react";
export default function Registration(props) {
const [login, setLogin] = useState("");
const [password, setPassword] = useState("");
const [passwordConfirm, setPasswordConfirm] = useState("");
const navigate = useNavigate();
useEffect(() => {}, []);
async function signup() {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
login: login,
password: password,
passwordConfirm: passwordConfirm,
}),
};
const response = await fetch(
"http://localhost:8080/jwt/signup",
requestParams
);
const result = await response.json();
if (response.status === 200) {
localStorage.setItem("token", result.token);
localStorage.setItem("user", result.login);
localStorage.setItem("role", result.role);
window.dispatchEvent(new Event("storage"));
navigate("/catalogs/find");
} else {
localStorage.removeItem("token");
localStorage.removeItem("user");
localStorage.removeItem("role");
alert(result);
}
}
const signupFormOnSubmit = function (event) {
event.preventDefault();
signup({
login: login,
password: password,
passwordConfirm: passwordConfirm
});
};
return (
<main className="flex-shrink-0" style={{ backgroundColor: "white" }}>
<h1 className="my-5 row g-3 text-center justify-content-center align-items-center ">
<b>Регистрация</b>
</h1>
<form className="row g-3 text-center justify-content-center align-items-center" onSubmit={signupFormOnSubmit}>
<div className="mb-3 row ms-5">
<div className="form-outline col-sm-11">
<input
placeholder="Логин"
className="form-control ms-5"
type="text"
id="login"
name="login"
value={login}
onChange={(e) => setLogin(e.target.value)}
/>
</div>
</div>
<div className="mb-3 row ms-5">
<div className="col-sm-11">
<input
placeholder="Пароль"
className="form-control ms-5"
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
</div>
<div className="mb-3 row ms-5">
<div className="col-sm-11">
<input
placeholder="Подтверждение пароля"
className="form-control ms-5"
type="password"
id="passwordConfirm"
value={passwordConfirm}
onChange={(e) => setPasswordConfirm(e.target.value)}
/>
</div>
</div>
<h2>
<button className="btn btn-light" style={{ color: "black" }}>
Зарегистрироваться
</button>
</h2>
</form>
</main>
);
}

View File

@ -0,0 +1,8 @@
import React from 'react';
export default function Ucant(props) {
return(
<main>
<label class="form-check-label" for="exampleCheck1">Зачем я сюда зашел</label>
</main>
);
}

View File

@ -0,0 +1,60 @@
import DataService from "../../services/DataService";
export default function Card(props) {
function edit(id) {
props.onEdit(id);
}
function remove(id) {
props.onRemove(id);
}
async function mess(id){
let currentStore = props.store.filter(x => x.id == id.id);
if (currentStore.length != 0){
let temp = props.store.filter(x => x.id != id.id);
currentStore[0].count++;
temp.push(currentStore[0]);
await props.setStore(temp);
return;
}else{
id.count++;
props.store.push(id);
props.setStore(props.store);
}
}
return (
<div className="temp row row-cols-1 row-cols-md-3 g-4" id="tbl-items">
{props.items.map((item) => (
<div className="col" key={item.id}>
<div className="card">
<div
className="container"
style={{ width: "100%", height: "100px", alignItems: "center" }}
>
<p>{item["carName"]}</p>
</div>
<div className="card-body">
<a
href="#"
className="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
onClick={(e) => remove(item.id, e)}
>
Удалить
</a>
<a
href="#"
type="button"
className="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
data-bs-toggle="modal"
data-bs-target="#staticBackdrop"
onClick={(e) => edit(item.id, e)}
>
Изменить
</a>
</div>
</div>
</div>
))}
</div>
);
}

View File

@ -0,0 +1,8 @@
export default function Footer(props) {
return (
<footer class="text-center p-4 p-3 mb-2 bg-light text-dark">
Кашин Максим ПИбд-22
</footer>
);
}

View File

@ -0,0 +1,65 @@
import { NavLink, useNavigate } from "react-router-dom";
import {useEffect, useState} from "react";
export default function Header(props) {
const [userRole, setUserRole] = useState("");
const navigate = useNavigate();
useEffect(() => {
window.addEventListener("storage", () => {
getUserRole();
});
getUserRole();
}, []);
const getUserRole = function () {
const role = localStorage.getItem("role") || "NONE";
setUserRole(role);
};
const handlelogout = function () {
window.location.reload();
navigate("/login");
localStorage.removeItem("role");
localStorage.removeItem("user");
localStorage.removeItem("token");
}
return (
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<div className="container-fluid">
<button
className="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav me-auto mb-2 mb-lg-0">
{props.links.map((route) => {
if(route.role == userRole || route.role == undefined){
return(
<li key={route.path} className="nav-item">
<NavLink className="nav-link fs-5" to={route.path}>
{route.label}
</NavLink>
</li>
);
}
})}
</ul>
</div>
<span className="nav-item">
{localStorage.getItem("role") !== null &&
<a className="nav-link fs-5" onClick={handlelogout}>
{"Выход(" + localStorage.getItem("user") + ")"}
</a>
}
</span >
</div>
</nav>
);
}

View File

@ -0,0 +1,48 @@
import React from "react";
export default function Modal(props) {
const formRef = React.createRef();
function hide() {
props.onHide();
}
function done(e) {
e.preventDefault();
if (formRef.current.checkValidity()) {
props.onDone();
hide();
} else {
formRef.current.reportValidity();
}
}
return (
<div className="modal fade show" tabIndex="-1" aria-hidden="true"
style={{ display: props.visible ? 'block' : 'none' }}>
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h1 className="modal-title fs-5" id="exampleModalLabel">{props.header}</h1>
<button className="btn-close" type="button" aria-label="Close"
onClick={hide}></button>
</div>
<div className="modal-body">
<form ref={formRef} onSubmit={done}>
{props.children}
</form>
</div>
<div className="modal-footer">
<button className="btn btn-secondary" type="button" onClick={hide}>Отменить</button>
<button className="btn btn-primary" type="button" onClick={done}>
{props.confirm}
</button>
</div>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,75 @@
import { useState } from 'react';
import styles from './Table.module.css';
import Toolbar from './Toolbar.jsx'
export default function Table(props) {
const [tableUpdate, setTableUpdate] = useState(false);
const [selectedItems, setSelectedItems] = useState([]);
function isSelected(id) {
if (!props.selectable) {
return false;
}
return selectedItems.includes(id);
}
function click(id) {
if (!props.selectable) {
return;
}
if (isSelected(id)) {
var index = selectedItems.indexOf(id);
if (index !== -1) {
selectedItems.splice(index, 1);
setSelectedItems(selectedItems);
setTableUpdate(!tableUpdate);
}
} else {
selectedItems.push(id);
setSelectedItems(selectedItems);
setTableUpdate(!tableUpdate);
}
props.onClick(selectedItems);
}
function dblClick(id) {
if (!props.selectable) {
return;
}
props.onDblClick(id);
}
return (
<table className={`table table-hover ${styles.table} ${props.selectable ? styles.selectable : ''}`}>
<thead>
<tr>
<th scope="col">#</th>
{
props.headers.map(header =>
<th key={header.name} scope="col">
{header.label}
</th>
)
}
</tr>
</thead>
<tbody>
{
props.items?.map((item, index) =>
<tr key={item.id}
className={isSelected(item.id) ? styles.selected : ''}
onClick={(e) => click(item.id, e)} onDoubleClick={(e) => dblClick(item.id, e)}>
<th scope="row">{index + 1}</th>
{
props.headers.map(header =>
<td key={item.id + header.name}>{item[header.name]}</td>
)
}
</tr>
)
}
</tbody >
</table >
);
}

View File

@ -0,0 +1,12 @@
.table tbody tr {
user-select: none;
}
.selectable tbody tr:hover {
cursor: pointer;
}
.selected {
background-color: #0d6efd;
opacity: 80%;
}

View File

@ -0,0 +1,40 @@
import styles from './Toolbar.module.css';
export default function Toolbar(props) {
function add() {
props.onAdd();
}
function edit() {
props.onEdit();
}
function remove() {
props.onRemove();
}
return (
<main className="form-group" style={{ backgroundColor: "white" }}>
{localStorage.getItem("role") == "ADMIN" && (
<a type="button" className="btn btn-light d-flex justify-content-center align-items-center" onClick={add}>
Добавить
</a>
)}
{(
<a type="button" className="btn btn-light d-flex justify-content-center align-items-center" onClick={add}>
Добавить
</a>
)}
{localStorage.getItem("role") == "ADMIN" && (
<a type="button" className="btn btn-light d-flex justify-content-center align-items-center" onClick={edit}>
Изменить
</a>
)}
{localStorage.getItem("role") == "ADMIN" && (
<a type="button" className="btn btn-light d-flex justify-content-center align-items-center" onClick={remove}>
Удалить
</a>
)}
</main>
);
}

View File

@ -0,0 +1,3 @@
.btn {
min-width: 140px;
}

View File

@ -0,0 +1,19 @@
export default function ToolbarStore(props) {
function add() {
props.onAdd();
}
return (
<div className="btn-group mt-2" role="group">
{localStorage.getItem("role") == "ADMIN" &&
<button
type="button"
className={`btn btn-outline-dark text-center d-flex justify-content-md-center mx-5 mb-3`}
onClick={add}
>
Добавить
</button>
}
</div>
);
}

8
frontend/src/main.jsx Normal file
View File

@ -0,0 +1,8 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './style.css'
ReactDOM.createRoot(document.getElementById('app')).render(
<App />
)

View File

@ -0,0 +1,8 @@
export default class Buyer {
constructor(data) {
this.id = data?.id;
this.buyerFirstName = data?.buyerFirstName || "";
this.buyerSecondName = data?.buyerSecondName || "";
//this.car = data?.car || null;
}
}

View File

@ -0,0 +1,8 @@
export default class Car {
constructor(data) {
this.id = data?.id;
this.carName = data?.carName || "";
this.storeDTOList = data?.storeDTOList || [];
this.buyerDTOList = data?.buyerDTOList || [];
}
}

View File

@ -0,0 +1,7 @@
export default class Store {
constructor(data) {
this.id = data?.id;
this.storeName = data?.storeName || "";
this.carDTOList = data?.carDTOList || [];
}
}

View File

@ -0,0 +1,7 @@
export default class UserLogin{
constructor(data){
this.login = data?.login;
this.password = data?.password;
this.role = data?.role || "";
}
}

View File

@ -0,0 +1,7 @@
export default class UserSignUp {
constructor(data) {
this.login = data?.login;
this.password = data?.password;
this.passwordConfirm = data?.passwordConfirm;
}
}

View File

@ -0,0 +1,32 @@
import axios from "axios";
import UserSignUpDto from "../models/UserSignUp";
import UserLoginDto from "../models/UserLogin";
const API_URL = "http://localhost:8080";
const register = (username, password, passwordConfirm) => {
return axios.post(API_URL + "/signup", new UserSignUpDto({login: username,
password: password,
passwordConfirm: passwordConfirm}));
};
const login = (username, password) => {
return axios
.post(API_URL + "/jwt/login", new UserLoginDto({login: username, password: password}))
.then((response) => {
if(response.status === 200){
localStorage.setItem("token", response.data)
}
});
};
const logout = () => {
localStorage.removeItem("token");
};
const AuthService = {
register,
login,
logout,
};
export default AuthService;

View File

@ -0,0 +1,68 @@
import axios from 'axios';
export default class DataService {
static dataUrlPrefix = 'http://localhost:8080';
static async readAll(url, transformer) {
const response = await fetch(this.dataUrlPrefix + url, {headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + localStorage.getItem("token")
}});
const data = await response.json();
console.log(data);
return data.map(item => transformer(item));
}
static async readUsersPage(dataUrlPrefix, url, page) {
const response = await axios.get(dataUrlPrefix + url + `?page=${page}`,{
headers:{
"Authorization": "Bearer " + localStorage.getItem("token")
}
});
return response.data;
}
static async readUser(dataUrlPrefix, url, login){
const response = await axios.get(dataUrlPrefix + url + `/${login}`);
return response.data;
}
static async read(url, transformer) {
const response = await axios.get(this.dataUrlPrefix + url,{headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + localStorage.getItem("token")
}});
return transformer(response.data);
}
static async create(url, data) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
};
console.log(JSON.stringify(data) + " " + this.dataUrlPrefix + " " + url);
const response = await fetch(this.dataUrlPrefix + url, requestParams);
}
static async update(url, data) {
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + localStorage.getItem("token")
},
body: JSON.stringify(data),
};
const response = await fetch(this.dataUrlPrefix + url, requestParams);
return true;
}
static async delete(url) {
const response = await axios.delete(this.dataUrlPrefix + url,{headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + localStorage.getItem("token")
}});
return response.data.id;
}
}

View File

@ -0,0 +1,48 @@
import { Outlet, Navigate, useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";
export default function PrivateRoute(props) {
const navigate = useNavigate();
useEffect(() => {
window.addEventListener("storage", () => {
let token = localStorage.getItem("token");
if (token) {
getRole(token).then((role) => {
if (localStorage.getItem("role") != role) {
localStorage.removeItem("token");
localStorage.removeItem("user");
localStorage.removeItem("role");
window.dispatchEvent(new Event("storage"));
navigate("/catalog/store");
}
});
}
});
}, []);
const getRole = async function (token) {
const requestParams = {
method: "GET",
headers: {
"Content-Type": "application/json",
},
};
const requestUrl = `http://localhost:8080/user?token=${token}`;
const response = await fetch(requestUrl, requestParams);
const result = await response.text();
return result;
};
let isAllowed = false;
let userRole = localStorage.getItem("role");
if(userRole != "ADMIN" && userRole != "USER"){
return <Navigate to="/login"/>
}
if (
props.role === userRole || userRole == "ADMIN"
) {
isAllowed = true;
}
return isAllowed ? <Outlet /> : <Navigate to="/err" />;
}

0
frontend/src/style.css Normal file
View File

7
frontend/vite.config.js Normal file
View File

@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()]
})

View File

@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@ -1 +1 @@
rootProject.name = 'lab1'
rootProject.name = 'maxim'

View File

@ -0,0 +1,28 @@
package com.example.maxim.Configuration;
import com.example.maxim.Configuration.jwt.JwtFilter;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenAPI30Configuration {
public static final String API_PREFIX = "/api/1.0";
@Bean
public OpenAPI customizeOpenAPI() {
final String securitySchemeName = JwtFilter.TOKEN_BEGIN_STR;
return new OpenAPI()
.addSecurityItem(new SecurityRequirement()
.addList(securitySchemeName))
.components(new Components()
.addSecuritySchemes(securitySchemeName, new SecurityScheme()
.name(securitySchemeName)
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")));
}
}

View File

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

View File

@ -0,0 +1,92 @@
package com.example.maxim.Configuration;
import com.example.maxim.Configuration.jwt.JwtFilter;
import com.example.maxim.lab3.controller.UserController;
import com.example.maxim.lab3.model.UserRole;
import com.example.maxim.lab3.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.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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
public class SecurityConfiguration {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
public static final String SPA_URL_MASK = "/{path:[^\\.]*}";
private final UserService userService;
private final JwtFilter jwtFilter;
public SecurityConfiguration(UserService userService) {
this.userService = userService;
this.jwtFilter = new JwtFilter(userService);
createAdminOnStartup();
}
private void createAdminOnStartup() {
final String admin = "admin";
if (userService.findByLogin(admin) == null) {
log.info("Admin user successfully created");
userService.createUser(admin, admin, admin, UserRole.ADMIN);
}
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
log.info("Creating security configuration");
http.cors()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests()
.requestMatchers("/", SPA_URL_MASK).permitAll()
.requestMatchers(HttpMethod.POST, UserController.URL_SIGNUP).permitAll()
.requestMatchers(HttpMethod.POST, UserController.URL_LOGIN).permitAll()
.requestMatchers(HttpMethod.GET, "/users/*").permitAll()
.requestMatchers(HttpMethod.GET, "/h2-console").permitAll()
.anyRequest()
.authenticated()
.and()
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.anonymous();
return http.build();
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http, PasswordEncoderConfiguration bCryptPasswordEncoder)
throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.userDetailsService(userService)
.passwordEncoder(bCryptPasswordEncoder.createPasswordEncoder())
.and()
.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.requestMatchers(HttpMethod.OPTIONS, "/**")
.requestMatchers("/*.js")
.requestMatchers("/*.png")
.requestMatchers("/*.jpg")
.requestMatchers("/*.html")
.requestMatchers("/*.css")
.requestMatchers("/assets/**")
.requestMatchers("/favicon.ico")
.requestMatchers("/.js", "/.css")
.requestMatchers("/swagger-ui/index.html")
.requestMatchers("/webjars/**")
.requestMatchers("/swagger-resources/**")
.requestMatchers("/v3/api-docs/**");
}
}

View File

@ -0,0 +1,46 @@
package com.example.maxim.Configuration;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**").allowedMethods("*");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController(SecurityConfiguration.SPA_URL_MASK).setViewName("forward:/");
registry.addViewController("/notFound").setViewName("forward:/");
ViewControllerRegistration registration = registry.addViewController("/notFound");
registration.setViewName("forward:/index.html");
registration.setStatusCode(HttpStatus.OK);
}
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
return container -> {
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
};
}
@Override
public void addResourceHandlers(
ResourceHandlerRegistry registry) {
registry.addResourceHandler("/public/**")
.addResourceLocations("/WEB-INF/view/react/build/public/");
registry.addResourceHandler("/*.js")
.addResourceLocations("/WEB-INF/view/react/build/");
registry.addResourceHandler("/*.json")
.addResourceLocations("/WEB-INF/view/react/build/");
registry.addResourceHandler("/*.ico")
.addResourceLocations("/WEB-INF/view/react/build/");
}
}

View File

@ -0,0 +1,11 @@
package com.example.maxim.Configuration.jwt;
public class JwtException extends RuntimeException {
public JwtException(Throwable throwable) {
super(throwable);
}
public JwtException(String message) {
super(message);
}
}

View File

@ -0,0 +1,71 @@
package com.example.maxim.Configuration.jwt;
import com.example.maxim.lab3.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.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
import java.io.IOException;
public class JwtFilter extends GenericFilterBean {
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;
}
}
}
chain.doFilter(request, response);
}
}

View File

@ -0,0 +1,27 @@
package com.example.maxim.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;
}
}

View File

@ -0,0 +1,107 @@
package com.example.maxim.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();
}
}
}

View File

@ -0,0 +1,13 @@
package com.example.maxim;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MaximApplication {
public static void main(String[] args) {
SpringApplication.run(MaximApplication.class, args);
}
}

View File

@ -0,0 +1,11 @@
package com.example.maxim.lab3.Respository;
import com.example.maxim.lab3.model.Buyer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface IBuyerRespository extends JpaRepository<Buyer, Long> {
}

View File

@ -0,0 +1,7 @@
package com.example.maxim.lab3.Respository;
import com.example.maxim.lab3.model.Car;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ICarRespository extends JpaRepository<Car, Long> {
}

View File

@ -0,0 +1,14 @@
package com.example.maxim.lab3.Respository;
import com.example.maxim.lab3.model.Store;
import com.example.maxim.lab3.model.Buyer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface IStoreRespository extends JpaRepository<Store, Long> {
@Query("SELECT DISTINCT p.buyers FROM Car p where :store MEMBER OF p.stores")
List<Buyer> getBuyers(@Param("store") Store store);
}

View File

@ -0,0 +1,8 @@
package com.example.maxim.lab3.Respository;
import com.example.maxim.lab3.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login);
}

View File

@ -0,0 +1,52 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.lab3.model.UserRole;
import com.example.maxim.lab3.service.BuyerService;
import jakarta.validation.Valid;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/buyer")
public class BuyerController {
private final BuyerService buyerService;
public BuyerController(BuyerService buyerService){
this.buyerService = buyerService;
}
@PostMapping
@Secured({UserRole.AsString.ADMIN})
public BuyerDTO addBuyer(@RequestBody BuyerDTO buyerDTO) {
return new BuyerDTO(buyerService.addBuyer(buyerDTO));
}
@PutMapping("/{id}")
@Secured({UserRole.AsString.ADMIN})
public BuyerDTO updateBuyer(@PathVariable Long id,@RequestBody @Valid BuyerDTO buyerDTO) {
return new BuyerDTO(buyerService.updateBuyer(id,buyerDTO));
}
@DeleteMapping("/{id}")
@Secured({UserRole.AsString.ADMIN})
public BuyerDTO removeBuyer(@PathVariable Long id) {
return new BuyerDTO(buyerService.deleteBuyer(id));
}
@DeleteMapping
@Secured({UserRole.AsString.ADMIN})
public void removeAllBuyers() {
buyerService.deleteAllBuyers();
}
@GetMapping("/{id}")
public BuyerDTO findBuyer(@PathVariable Long id) {
return new BuyerDTO(buyerService.findBuyer(id));
}
@GetMapping
public List<BuyerDTO> findAllBuyer() {
return buyerService.findAllBuyers()
.stream()
.map(x-> new BuyerDTO(x))
.toList();
}
}

View File

@ -0,0 +1,35 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.lab3.model.Buyer;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
public class BuyerDTO {
private long id;
@NotBlank(message = "FirstName can't be null or empty")
private String buyerFirstName;
@NotBlank(message = "SecondName can't be null or empty")
private String buyerSecondName;
public BuyerDTO(Buyer buyer){
this.id =buyer.getId();
this.buyerFirstName = buyer.getBuyerFirstName();
this.buyerSecondName = buyer.getBuyerSecondName();
}
public BuyerDTO(){
}
public long getId() {
return id;
}
public String getBuyerFirstName(){
return buyerFirstName;
}
public void setBuyerFirstName(String buyerFirstName){
this.buyerFirstName = buyerFirstName;
}
public String getBuyerSecondName(){
return buyerSecondName;
}
public void setBuyerSecondName(String buyerSecondName){
this.buyerSecondName = buyerSecondName;
}
}

View File

@ -0,0 +1,57 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.lab3.service.BuyerService;
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("/buyer2")
public class BuyerMVCController {
private final BuyerService buyerService;
public BuyerMVCController(BuyerService buyerService){
this.buyerService = buyerService;
}
@GetMapping
public String getBuyers(Model model){
model.addAttribute("buyers",
buyerService.findAllBuyers().stream()
.map(BuyerDTO::new)
.toList());
return "buyer";
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editBuyer(@PathVariable(required = false) Long id,
Model model) {
if (id == null || id <= 0) {
model.addAttribute("BuyerDTO", new BuyerDTO());
} else {
model.addAttribute("buyerId", id);
model.addAttribute("BuyerDTO", new BuyerDTO(buyerService.findBuyer(id)));
}
return "buyer-edit";
}
@PostMapping(value = {"", "/{id}"})
public String saveBuyer(@PathVariable(required = false) Long id,
@ModelAttribute @Valid BuyerDTO buyerDTO,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "buyer-edit";
}
if (id == null || id <= 0) {
buyerService.addBuyer(buyerDTO);
} else {
buyerService.updateBuyer(id, buyerDTO);
}
return "redirect:/buyer";
}
@PostMapping("/delete/{id}")
public String deleteBuyer(@PathVariable Long id) {
buyerService.deleteBuyer(id);
return "redirect:/buyer";
}
}

View File

@ -0,0 +1,48 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.lab3.model.UserRole;
import com.example.maxim.lab3.service.CarService;
import jakarta.validation.Valid;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/car")
public class CarController {
private final CarService carService;
public CarController(CarService carService){
this.carService = carService;
}
@PostMapping
@Secured({UserRole.AsString.ADMIN})
public CarDTO addCar(@RequestBody @Valid CarDTO carDTO){
return new CarDTO(carService.addCar(carDTO));
}
@PutMapping("/{id}")
@Secured({UserRole.AsString.ADMIN})
public CarDTO updateCar(@PathVariable Long id, @RequestBody CarDTO carDTO){
return new CarDTO(carService.updateCar(id, carDTO));
}
@DeleteMapping("/{id}")
@Secured({UserRole.AsString.ADMIN})
public CarDTO removeCar(@PathVariable Long id){
return new CarDTO(carService.deleteCar(id));
}
@DeleteMapping
@Secured({UserRole.AsString.ADMIN})
public void removeAllCars(){
carService.deleteAllCars();
}
@GetMapping("/{id}")
public CarDTO findCar(@PathVariable Long id){
return new CarDTO(carService.findCar(id));
}
@GetMapping
public List<CarDTO> findAllCars(){
return carService.findAllCars()
.stream()
.map(x -> new CarDTO(x))
.toList();
}
}

View File

@ -0,0 +1,51 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.lab3.model.Car;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import java.util.List;
public class CarDTO {
private long id;
@NotBlank(message = "CarName can't be null or empty")
private String carName;
private List<BuyerDTO> buyerDTOList;
private List<StoreDTO> storeDTOList;
public CarDTO(Car car){
this.id = car.getId();
this.carName = car.getCarName();
this.storeDTOList = car.getStores() == null ? null : car.getStores()
.stream()
.filter(x -> x.getCar().contains(car))
.map(StoreDTO::new)
.toList();
this.buyerDTOList = car.getBuyers() == null ? null : car.getBuyers()
.stream()
.map(BuyerDTO::new)
.toList();
}
public CarDTO(){}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public long getId() {
return id;
}
public String getCarName(){
return carName;
}
public void setCarName(String carName){
this.carName = carName;
}
public List<BuyerDTO> getBuyerDTOList(){
return buyerDTOList;
}
public void setBuyerDTOList(List<BuyerDTO> buyers){
this.buyerDTOList = buyers;
}
public List<StoreDTO> getStoreDTOList(){
return storeDTOList;
}
public void setStoreDTOList(List<StoreDTO> stores){
this.storeDTOList = stores;
}
}

View File

@ -0,0 +1,118 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.lab3.service.StoreService;
import com.example.maxim.lab3.service.BuyerService;
import com.example.maxim.lab3.service.CarService;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/car2")
public class CarMVCController {
private final CarService carService;
private final BuyerService buyerService;
private final StoreService storeService;
public CarMVCController(CarService carService, BuyerService buyerService, StoreService storeService){
this.carService = carService;
this.buyerService = buyerService;
this.storeService = storeService;
}
@GetMapping
public String getCars(Model model){
model.addAttribute("cars",
carService.findAllCars().stream()
.map(CarDTO::new)
.toList());
return "car";
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editCar(@PathVariable(required = false) Long id,
Model model) {
if (id == null || id <= 0) {
List<BuyerDTO> buyers = buyerService.findAllBuyers().stream()
.map(BuyerDTO::new).toList();
List<StoreDTO> stores = storeService.findAllStores().stream()
.map(StoreDTO::new).toList();
model.addAttribute("CarDTO", new CarDTO());
model.addAttribute("buyers", buyers);
model.addAttribute("stores", stores);
return "car-create";
} else {
String name = carService.findCar(id).getCarName();
List<BuyerDTO> buyers = buyerService.findAllBuyers().stream()
.map(BuyerDTO::new).toList();
List<BuyerDTO> carBuyers = carService
.findCar(id)
.getBuyers()
.stream()
.map(BuyerDTO::new)
.toList();
List<StoreDTO> stores = storeService.findAllStores().stream()
.map(StoreDTO::new).toList();
List<StoreDTO> carStores = carService
.findCar(id)
.getStores()
.stream()
.map(StoreDTO::new)
.toList();
model.addAttribute("name", name);
model.addAttribute("carId", id);
model.addAttribute("carBuyers", carBuyers);
model.addAttribute("buyers", buyers);
model.addAttribute("carStores", carStores);
model.addAttribute("stores", stores);
model.addAttribute("CarDTO", new CarDTO(carService.findCar(id)));
}
return "car-set";
}
@PostMapping(value = {"/"})
public String saveCar(@ModelAttribute @Valid CarDTO carDTO,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "car-create";
}
carService.addCar(carDTO);
// } else {
// carService.updateCar(id, carDTO);
// }
return "redirect:/car";
}
@PostMapping(value = {"/{id}"})
public String editCar(@PathVariable Long id,
@RequestParam("PW") String PW,
@RequestParam("wpName") String name,
@RequestParam(value="idPW", required = false) Long idPW,
@RequestParam(value = "delete", required = false) boolean del,
Model model) {
if(PW.equals("N")){
carService.findCar(id).setCarName(name);
carService.updateCar(id, new CarDTO(carService.findCar(id)));
}
if (PW.equals("W")){
if (del == true) {
carService.deleteBuyer(id, idPW);
} else {
carService.addBuyer(id, idPW);
}
}
else if(PW.equals("P")){
if (del == true) {
carService.deleteStore(id, idPW);
} else {
carService.addStore(id, idPW);
}
}
return "redirect:/car/edit/" + id;
}
@PostMapping("/delete/{id}")
public String deleteCar(@PathVariable Long id) {
carService.deleteCar(id);
return "redirect:/car";
}
}

View File

@ -0,0 +1,60 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.lab3.model.UserRole;
import com.example.maxim.lab3.service.StoreService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import org.springframework.security.access.annotation.Secured;
@RestController
@RequestMapping("/store")
public class StoreController {
private final StoreService storeService;
public StoreController(StoreService storeService){
this.storeService = storeService;
}
@PostMapping
@Secured({UserRole.AsString.ADMIN})
public StoreDTO addStore(@RequestBody @Valid StoreDTO storeDTO) {
return new StoreDTO(storeService.addStore(storeDTO));
}
@PutMapping("/{id}")
@Secured({UserRole.AsString.ADMIN})
public StoreDTO updateStore(@PathVariable Long id, @RequestBody @Valid StoreDTO storeDTO) {
return new StoreDTO(storeService.updateStore(id, storeDTO));
}
@DeleteMapping("/{id}")
@Secured({UserRole.AsString.ADMIN})
public StoreDTO removeStore(@PathVariable Long id) {
return new StoreDTO(storeService.deleteStore(id));
}
@DeleteMapping
@Secured({UserRole.AsString.ADMIN})
public void removeAllStores() {
storeService.deleteAllStores();
}
@GetMapping("/{id}")
public StoreDTO findStore(@PathVariable Long id) {
return new StoreDTO(storeService.findStore(id));
}
@GetMapping("/buyer/{id}")
public List<BuyerDTO> findBuyersOnCar(@PathVariable Long id){
return storeService.findAllBuyersProducedStore(id)
.stream()
.map(BuyerDTO::new)
.toList();
}
@GetMapping
public List<StoreDTO> findAllStore() {
return storeService.findAllStores()
.stream()
.map(StoreDTO::new)
.toList();
}
}

View File

@ -0,0 +1,39 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.lab3.model.Store;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.List;
public class StoreDTO {
private long id;
@NotBlank(message = "StoreName can't be null or empty")
private String storeName;
private List<CarDTO> carDTOList;
public StoreDTO(Store store){
this.id = store.getId();
this.storeName = store.getStoreName();
this.carDTOList = store.getCar() == null ? null : store.getCar()
.stream()
.filter(x -> x.getStores().contains(store.getId()))
.map(y -> new CarDTO(y))
.toList();
}
public StoreDTO() {
}
public long getId() {
return id;
}
public String getStoreName() {
return storeName;
}
public void setStoreName(String storeName){
this.storeName = storeName;
}
public List<CarDTO> getCarDTOList(){
return carDTOList;
}
}

View File

@ -0,0 +1,67 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.lab3.service.StoreService;
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("/store2123")
public class StoreMVCController {
private final StoreService storeService;
public StoreMVCController(StoreService storeService){
this.storeService = storeService;
}
@GetMapping
public String getStores(Model model){
model.addAttribute("stores",
storeService.findAllStores().stream()
.map(StoreDTO::new)
.toList());
return "store";
}
@GetMapping("/info/{id}")
public String findBuyersOnCar(@PathVariable(required = false) Long id, Model model){
model.addAttribute("cathegory", "Кто производит " + storeService.findStore(id).getStoreName());
model.addAttribute("buyers", storeService.findAllBuyersProducedStore(id)
.stream()
.map(BuyerDTO::new)
.toList());
model.addAttribute("page", "store");
return "buyer-info";
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editStore(@PathVariable(required = false) Long id,
Model model) {
if (id == null || id <= 0) {
model.addAttribute("StoreDTO", new StoreDTO());
} else {
model.addAttribute("storeId", id);
model.addAttribute("StoreDTO", new StoreDTO(storeService.findStore(id)));
}
return "store-edit";
}
@PostMapping(value = {"", "/{id}"})
public String saveStore(@PathVariable(required = false) Long id,
@ModelAttribute @Valid StoreDTO storeDTO,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "store-edit";
}
if (id == null || id <= 0) {
storeService.addStore(storeDTO);
} else {
storeService.updateStore(id, storeDTO);
}
return "redirect:/store";
}
@PostMapping("/delete/{id}")
public String deleteStore(@PathVariable Long id) {
storeService.deleteStore(id);
return "redirect:/store";
}
}

View File

@ -0,0 +1,64 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.lab3.model.User;
import com.example.maxim.lab3.model.UserRole;
import com.example.maxim.lab3.service.UserService;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.IntStream;
@RestController
public class UserController {
public static final String URL_LOGIN = "/jwt/login";
public static final String URL_SIGNUP = "/jwt/signup";
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);
}
@PostMapping(URL_SIGNUP)
public UserInfoDTO signup(@RequestBody @Valid UserDTO userDto) {
return userService.signupAndGetToken(userDto);
}
@GetMapping("/users/{login}")
public UserDetails getCurrentUser(@PathVariable String login) {
try {
return userService.loadUserByUsername(login);
} catch (Exception e) {
return null;
}
}
@GetMapping("/user")
public String findUser(@RequestParam("token") String token) {
UserDetails userDetails = userService.loadUserByToken(token);
User user = userService.findByLogin(userDetails.getUsername());
return user.getRole().toString();
}
@GetMapping("/users")
@Secured({UserRole.AsString.ADMIN})
public UsersPageDTO getUsers(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "2") int size) {
final Page<UserDTO> users = userService.findAllPages(page, size)
.map(UserDTO::new);
final int totalPages = users.getTotalPages();
final List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
.boxed()
.toList();
return new UsersPageDTO(users, pageNumbers, totalPages);
}
}

View File

@ -0,0 +1,43 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.lab3.model.User;
import com.example.maxim.lab3.model.UserRole;
import jakarta.validation.constraints.NotEmpty;
public class UserDTO {
private long id;
@NotEmpty
private String login;
@NotEmpty
private String password;
private String passwordConfirm;
private UserRole role;
public UserDTO() {
}
public UserDTO(User user) {
this.id = user.getId();
this.login = user.getLogin();
this.role = user.getRole();
}
public long getId() {
return id;
}
public String getLogin() {
return login;
}
public UserRole getRole() {
return role;
}
public String getPassword() {
return password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
}

View File

@ -0,0 +1,26 @@
package com.example.maxim.lab3.controller;
import com.example.maxim.lab3.model.UserRole;
public class UserInfoDTO {
private final String token;
private String login;
private final UserRole role;
public UserInfoDTO(String token, String login, UserRole role) {
this.token = token;
this.login = login;
this.role = role;
}
public String getToken() {
return token;
}
public UserRole getRole() {
return role;
}
public String getLogin() {
return login;
}
}

View File

@ -0,0 +1,25 @@
package com.example.maxim.lab3.controller;
import jakarta.validation.constraints.NotBlank;
public class UserLoginDTO {
@NotBlank
private String login;
@NotBlank
private String password;
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;
}
}

View File

@ -0,0 +1,40 @@
package com.example.maxim.lab3.controller;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserSignUpDTO {
@NotBlank
@Size(min = 3, max = 64)
private String login;
@NotBlank
@Size(min = 6, max = 64)
private String password;
@NotBlank
@Size(min = 6, max = 64)
private String passwordConfirm;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
}

View File

@ -0,0 +1,29 @@
package com.example.maxim.lab3.controller;
import org.springframework.data.domain.Page;
import java.util.List;
public class UsersPageDTO {
private Page<UserDTO> users;
private List<Integer> pageNumbers;
private int totalPages;
public UsersPageDTO(Page<UserDTO> users, List<Integer> pageNumbers, int totalPages) {
this.users = users;
this.pageNumbers = pageNumbers;
this.totalPages = totalPages;
}
public Page<UserDTO> getUsers() {
return users;
}
public List<Integer> getPageNumbers() {
return pageNumbers;
}
public int getTotalPages() {
return totalPages;
}
}

View File

@ -0,0 +1,60 @@
package com.example.maxim.lab3.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import java.util.Objects;
@Entity
@Table(name = "buyer")
public class Buyer {
@Id
@GeneratedValue
private long id;
@NotNull(message = "First name can't be empty")
@Column(name = "first_name")
private String buyerFirstName;
@NotNull(message = "Second name can't be empty")
@Column(name = "second_name")
private String buyerSecondName;
public Buyer(){
}
public Buyer(String buyerFirstName, String buyerSecondName){
this.buyerFirstName = buyerFirstName;
this.buyerSecondName = buyerSecondName;
}
public Long getId(){return id;}
public String getBuyerFirstName(){
return buyerFirstName;
}
public String getBuyerSecondName(){
return buyerSecondName;
}
public void setBuyerFirstName(String buyerFirstName) {
this.buyerFirstName = buyerFirstName;
}
public void setBuyerSecondName(String buyerSecondName) {
this.buyerSecondName = buyerSecondName;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Buyer buyer = (Buyer) o;
return Objects.equals(id, buyer.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Buyer{" +
"id=" + id +
", buyerFirstName='" + buyerFirstName + '\'' +
", buyerSecondName='" + buyerSecondName + '\'' +
'}';
}
}

View File

@ -0,0 +1,106 @@
package com.example.maxim.lab3.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "car")
public class Car {
@Id
@GeneratedValue
private long id;
@NotNull(message = "Name can't be empty")
@Column(name = "name")
private String carName;
@OneToMany(cascade = {CascadeType.MERGE})
@JoinColumn(name = "buyers", nullable = true)
private List<Buyer> buyers;
@ManyToMany(cascade = { CascadeType.MERGE }, fetch = FetchType.EAGER)
@JoinTable(name = "cars_stores",
joinColumns = @JoinColumn(name = "car_fk"),
inverseJoinColumns = @JoinColumn(name = "store_fk"))
private List<Store> stores;
public Car(){
}
public Car(String carName, List<Store> stores, List<Buyer> buyers){
this.carName = carName;
this.stores = stores;
this.buyers = buyers;
}
public Long getId() {
return id;
}
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public List<Store> getStores() {
return stores;
}
public List<Buyer> getBuyers(){return buyers;}
public void setStores(List<Store> stores) {
this.stores = stores;
}
public void setBuyers(List<Buyer> buyers) {
this.buyers = buyers;
}
public void update(Car car){
this.carName = car.carName;
this.stores = car.getStores();
}
public void addStore(Store store){
if (stores == null){
this.stores = new ArrayList<>();
}
if (!stores.contains(store)) {
this.stores.add(store);
store.addCar(this);
}
}
public void removeStore(Store store){
if (stores.contains(store)) {
this.stores.remove(store);
store.removeCar(this);
}
}
public void addBuyer(Buyer buyer){
if (buyers == null){
this.buyers = new ArrayList<>();
}
if (!buyers.contains(buyer)) {
this.buyers.add(buyer);
}
}
public void removeBuyer(Buyer buyer){
if (buyers.contains(buyer)) {
this.buyers.remove(buyer);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Car car = (Car) o;
return Objects.equals(id, car.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Car{" +
"id=" + id +
", carName='" + carName + '\'' + +
'}';
}
}

View File

@ -0,0 +1,79 @@
package com.example.maxim.lab3.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
public class Store {
@Id
@GeneratedValue
private Long id;
@NotNull(message = "Name can't be empty")
@Column(name = "storeName")
private String storeName;
@NotNull(message = "Price can't be null or empty")
@ManyToMany(mappedBy = "stores",cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
private List<Car> car;
public Store() {
}
public Store(String storeName) {
this.storeName = storeName;
}
public Long getId() {
return id;
}
public String getStoreName() {
return storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
public List<Car> getCar() {
return car;
}
public void setCar(List<Car> car) {
this.car = car;
}
public void addCar(Car car) {
if (this.car == null) {
this.car = new ArrayList<>();
}
if (!this.car.contains(car))
this.car.add(car);
}
public void removeCar(Car car) {
if (this.car.contains(car))
this.car.remove(car);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Store store = (Store) o;
return Objects.equals(id, store.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Store{" +
"id=" + id +
", storeName='" + storeName + '\'' +
'}';
}
}

View File

@ -0,0 +1,84 @@
package com.example.maxim.lab3.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);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", login='" + login + '\'' +
", password='" + password + '\'' +
'}';
}
}

View File

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

View File

@ -0,0 +1,7 @@
package com.example.maxim.lab3.service;
public class BuyerNotFoundException extends RuntimeException {
public BuyerNotFoundException(Long id){
super(String.format("Buyer with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,74 @@
package com.example.maxim.lab3.service;
import com.example.maxim.lab3.Respository.IBuyerRespository;
import com.example.maxim.lab3.controller.BuyerDTO;
import com.example.maxim.lab3.controller.CarDTO;
import com.example.maxim.lab3.model.Buyer;
import com.example.maxim.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Service
public class BuyerService {
private final IBuyerRespository buyerRespository;
private final ValidatorUtil validatorUtil;
public BuyerService(IBuyerRespository buyerRespositroy, ValidatorUtil validatorUtil){
this.buyerRespository = buyerRespositroy;
this.validatorUtil = validatorUtil;
}
@Transactional
public Buyer addBuyer(BuyerDTO buyerDTO) {
final Buyer buyer = new Buyer(buyerDTO.getBuyerFirstName(), buyerDTO.getBuyerSecondName());
//validatorUtil.validate(buyer);
buyerRespository.save(buyer);
return buyer;
}
@Transactional(readOnly = true)
public Buyer findBuyer(Long id) {
final Optional<Buyer> buyer = buyerRespository.findById(id);
return buyer.orElseThrow(()->new BuyerNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Buyer> findAllBuyerByid(CarDTO carDTO) {
if(carDTO.getBuyerDTOList() == null){
return null;
}
return buyerRespository
.findAllById(carDTO
.getBuyerDTOList()
.stream()
.map(x->x.getId())
.toList());
}
@Transactional(readOnly = true)
public List<Buyer> findAllBuyers() {
return buyerRespository
.findAll();
}
@Transactional
public Buyer updateBuyer(Long id, BuyerDTO buyer) {
final Buyer currentBuyer = findBuyer(id);
currentBuyer.setBuyerFirstName(buyer.getBuyerFirstName());
currentBuyer.setBuyerSecondName(buyer.getBuyerSecondName());
validatorUtil.validate(currentBuyer);
buyerRespository.save(currentBuyer);
return currentBuyer;
}
@Transactional
public Buyer deleteBuyer(Long id) {
final Buyer currentBuyer= findBuyer(id);
buyerRespository.delete(currentBuyer);
return currentBuyer;
}
@Transactional
public void deleteAllBuyers() {
buyerRespository.deleteAll();
}
}

View File

@ -0,0 +1,7 @@
package com.example.maxim.lab3.service;
public class CarNotFoundException extends RuntimeException{
public CarNotFoundException(Long id){
super(String.format("Car with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,94 @@
package com.example.maxim.lab3.service;
import com.example.maxim.lab3.Respository.ICarRespository;
import com.example.maxim.lab3.controller.CarDTO;
import com.example.maxim.lab3.model.Store;
import com.example.maxim.lab3.model.Buyer;
import com.example.maxim.lab3.model.Car;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Service
public class CarService {
private final ICarRespository carRespository;
private final StoreService storeService;
private final BuyerService buyerService;
public CarService(ICarRespository carRespository,
StoreService storeService,
BuyerService buyerService
){
this.carRespository = carRespository;
this.storeService = storeService;
this.buyerService = buyerService;
}
@Transactional
public Car addCar(CarDTO carDTO) {
List<Store> stores = storeService.findAllStoresById(carDTO);
List<Buyer> buyers = buyerService.findAllBuyerByid(carDTO);
final Car car = new Car(
carDTO.getCarName(), stores, buyers);
carRespository.save(car);
return car;
}
@Transactional
public Car addBuyer(Long id, Long idW){
final Car currentCar = findCar(id);
currentCar.addBuyer(buyerService.findBuyer(idW));
return currentCar;
}
@Transactional
public Car deleteBuyer(Long id, Long idW){
final Car currentCar = findCar(id);
currentCar.removeBuyer(buyerService.findBuyer(idW));
return currentCar;
}
@Transactional
public Car addStore(Long id, Long idP){
final Car currentCar = findCar(id);
currentCar.addStore(storeService.findStore(idP));
return currentCar;
}
@Transactional
public Car deleteStore(Long id, Long idP){
final Car currentCar = findCar(id);
currentCar.removeStore(storeService.findStore(idP));
return currentCar;
}
@Transactional(readOnly = true)
public Car findCar(Long id) {
final Optional<Car> car = carRespository.findById(id);
return car.orElseThrow(() -> new CarNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Car> findAllCars() {
return carRespository.findAll();
}
@Transactional
public Car updateCar(Long id, CarDTO carDTO) {
final Car currentCar = findCar(id);
currentCar.setCarName(carDTO.getCarName());
List<Store> newStores = storeService.findAllStoresById(carDTO);
List<Buyer> newBuyers = buyerService.findAllBuyerByid(carDTO);
currentCar.setStores(newStores);
currentCar.setBuyers(newBuyers);
carRespository.save(currentCar);
return currentCar;
}
@Transactional
public Car deleteCar(Long id) {
final Car currentCar = findCar(id);
carRespository.delete(currentCar);
return currentCar;
}
@Transactional
public void deleteAllCars() {
carRespository.deleteAll();
}
}

View File

@ -0,0 +1,7 @@
package com.example.maxim.lab3.service;
public class StoreNotFoundException extends RuntimeException{
public StoreNotFoundException(Long id){
super(String.format("Store with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,83 @@
package com.example.maxim.lab3.service;
import com.example.maxim.lab3.Respository.IStoreRespository;
import com.example.maxim.lab3.controller.StoreDTO;
import com.example.maxim.lab3.controller.CarDTO;
import com.example.maxim.lab3.model.Store;
import com.example.maxim.lab3.model.Buyer;
import com.example.maxim.lab3.model.Car;
import com.example.maxim.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Service
public class StoreService {
private final IStoreRespository storeRespository;
private final ValidatorUtil validatorUtil;
public StoreService(IStoreRespository storeRespository,
ValidatorUtil validatorUtil){
this.storeRespository = storeRespository;
this.validatorUtil = validatorUtil;
}
@Transactional
public Store addStore(StoreDTO storeDTO) {
final Store store = new Store(storeDTO.getStoreName());
validatorUtil.validate(store);
storeRespository.save(store);
return store;
}
@Transactional(readOnly = true)
public Store findStore(Long id) {
final Optional<Store> store = storeRespository.findById(id);
return store.orElseThrow(()->new StoreNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Store> findAllStores() {
return storeRespository.findAll();
}
@Transactional(readOnly = true)
public List<Store> findAllStoresById(CarDTO carDTO) {
if(carDTO.getStoreDTOList() == null){
return null;
}
return storeRespository
.findAllById(carDTO
.getStoreDTOList()
.stream()
.map(x -> x.getId())
.toList());
}
@Transactional
public Store updateStore(Long id, StoreDTO storeDTO) {
final Store currentStore = findStore(id);
currentStore.setStoreName(storeDTO.getStoreName());
storeRespository.save(currentStore);
return currentStore;
}
@Transactional
public Store deleteStore(Long id) {
final Store currentStore = findStore(id);
int size = currentStore.getCar().size();
for (int i = 0; i < size; i++) {
Car temp = currentStore.getCar().get(i);
temp.removeStore(currentStore);
currentStore.removeCar(temp);
}
storeRespository.delete(currentStore);
return currentStore;
}
@Transactional
public List<Buyer> findAllBuyersProducedStore(Long id){
return storeRespository.getBuyers(findStore(id));
}
@Transactional
public void deleteAllStores() {
storeRespository.deleteAll();
}
}

View File

@ -0,0 +1,7 @@
package com.example.maxim.lab3.service;
public class UserExistsException extends RuntimeException {
public UserExistsException(String login) {
super(String.format("User '%s' already exists", login));
}
}

View File

@ -0,0 +1,7 @@
package com.example.maxim.lab3.service;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String login) {
super(String.format("User not found '%s'", login));
}
}

View File

@ -0,0 +1,99 @@
package com.example.maxim.lab3.service;
import com.example.maxim.Configuration.jwt.JwtException;
import com.example.maxim.Configuration.jwt.JwtProvider;
import com.example.maxim.lab3.Respository.UserRepository;
import com.example.maxim.lab3.controller.UserDTO;
import com.example.maxim.lab3.controller.UserInfoDTO;
import com.example.maxim.lab3.model.User;
import com.example.maxim.lab3.model.UserRole;
import com.example.maxim.util.validation.ValidationException;
import com.example.maxim.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 JwtProvider jwtProvider;
public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder,
ValidatorUtil validatorUtil,
JwtProvider 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 UserExistsException(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());
}
public UserInfoDTO signupAndGetToken(UserDTO userDto) {
final User user = createUser(userDto.getLogin(), userDto.getPassword(), userDto.getPasswordConfirm(), UserRole.USER);
return new UserInfoDTO(jwtProvider.generateToken(user.getLogin()), user.getLogin(), UserRole.USER);
}
public UserDetails loadUserByToken(String token) throws UsernameNotFoundException {
if (!jwtProvider.isTokenValid(token)) {
throw new JwtException("Bad token");
}
final String userLogin = jwtProvider.getLoginFromToken(token)
.orElseThrow(() -> 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()));
}
}

View File

@ -0,0 +1,43 @@
package com.example.maxim.util.error;
import com.example.maxim.lab3.service.StoreNotFoundException;
import com.example.maxim.lab3.service.BuyerNotFoundException;
import com.example.maxim.lab3.service.CarNotFoundException;
import com.example.maxim.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.util.stream.Collectors;
@ControllerAdvice(annotations = RestController.class)
public class AdviceController {
@ExceptionHandler({
BuyerNotFoundException.class,
StoreNotFoundException.class,
CarNotFoundException.class,
ValidationException.class
})
public ResponseEntity<Object> handleException(Throwable e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
@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);
}
}

View File

@ -0,0 +1,12 @@
package com.example.maxim.util.validation;
import java.util.Set;
public class ValidationException extends RuntimeException {
public <T> ValidationException(Set<String> errors) {
super(String.join("\n", errors));
}
public ValidationException(String message) {
super(message);
}
}

View File

@ -0,0 +1,30 @@
package com.example.maxim.util.validation;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.springframework.stereotype.Component;
import java.util.Set;
import java.util.stream.Collectors;
@Component
public class ValidatorUtil {
private final Validator validator;
public ValidatorUtil() {
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
this.validator = factory.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()));
}
}
}

View File

@ -1,21 +0,0 @@
package ru.ulstu.is.lab1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class Lab1Application {
public static void main(String[] args) {
SpringApplication.run(Lab1Application.class, args);
}
@GetMapping("/name")
public String hello(@RequestParam(value = "n", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}

View File

@ -1 +1,14 @@
spring.main.banner-mode=off
server.port=8080
server.tomcat.relaxed-query-chars=|,{,},[,]
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

View File

@ -1,10 +1,10 @@
package ru.ulstu.is.lab1;
package com.example.maxim;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Lab1ApplicationTests {
class MaximApplicationTests {
@Test
void contextLoads() {