Compare commits
23 Commits
master
...
LabWork06R
Author | SHA1 | Date | |
---|---|---|---|
|
5dd9a0d2e1 | ||
|
52a842d8c9 | ||
|
f89a16bcd1 | ||
|
881dcefe95 | ||
|
26a040743d | ||
|
edfa23dd7b | ||
|
5d790b350c | ||
|
258c8737b8 | ||
|
c57dc591f1 | ||
|
686c5db7bf | ||
|
08a82d3f06 | ||
|
2a876f5516 | ||
|
b56c295266 | ||
|
b2815fd417 | ||
|
8c516e69f1 | ||
|
1b4d36a1e2 | ||
|
70a17c4b7c | ||
|
7ae556be81 | ||
|
a25b5454a7 | ||
|
fd8a8e32c6 | ||
|
ca392cb92b | ||
|
a9e7a9fc6b | ||
|
b77b39e859 |
2
.gitignore
vendored
2
.gitignore
vendored
@ -4,7 +4,7 @@ build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
node_modules
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
|
16
build.gradle
16
build.gradle
@ -12,9 +12,25 @@ repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
jar {
|
||||
enabled = false
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(':front'))
|
||||
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation 'com.h2database:h2:2.1.210'
|
||||
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
|
||||
implementation 'org.hibernate.validator:hibernate-validator'
|
||||
implementation group: 'org.springframework', name: 'spring-tx'
|
||||
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||
implementation 'com.auth0:java-jwt:4.4.0'
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
|
26
front/.gitignore
vendored
Normal file
26
front/.gitignore
vendored
Normal file
@ -0,0 +1,26 @@
|
||||
# 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?
|
||||
|
||||
.parcel-cache
|
58
front/build.gradle
Normal file
58
front/build.gradle
Normal file
@ -0,0 +1,58 @@
|
||||
import com.github.gradle.node.util.PlatformHelper
|
||||
import groovy.text.SimpleTemplateEngine
|
||||
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'com.github.node-gradle.node' version '3.5.1'
|
||||
id "de.undercouch.download" version '5.3.1'
|
||||
}
|
||||
|
||||
node {
|
||||
version = '18.15.0'
|
||||
download = true
|
||||
}
|
||||
|
||||
jar.dependsOn 'npmBuild'
|
||||
|
||||
clean.dependsOn 'npmClean'
|
||||
|
||||
nodeSetup.dependsOn 'downloadNode'
|
||||
|
||||
jar {
|
||||
from 'dist'
|
||||
into 'static'
|
||||
final devHost = 'http://localhost:8080'
|
||||
final prodHost = ''
|
||||
filesMatching('DataService.js') {
|
||||
filter { line -> line.replaceAll(devHost, prodHost) }
|
||||
}
|
||||
}
|
||||
|
||||
task downloadNode(type: Download) {
|
||||
final helper = new PlatformHelper()
|
||||
final templateData = [
|
||||
"url" : node.distBaseUrl.get(),
|
||||
"version": node.version.get(),
|
||||
"os" : helper.osName,
|
||||
"arch" : helper.osArch,
|
||||
"ext" : helper.windows ? 'zip' : 'tar.gz'
|
||||
]
|
||||
final urlTemplate = '${url}/v${version}/node-v${version}-${os}-${arch}.${ext}'
|
||||
final engine = new SimpleTemplateEngine()
|
||||
final url = engine.createTemplate(urlTemplate).make(templateData).toString()
|
||||
final String destDir = '.gradle/'
|
||||
file(destDir).mkdirs()
|
||||
src url
|
||||
dest destDir
|
||||
overwrite false
|
||||
}
|
||||
|
||||
tasks.register('npmBuild', NpmTask) {
|
||||
dependsOn npmInstall
|
||||
args = ['run-script', 'build']
|
||||
}
|
||||
|
||||
tasks.register('npmClean', NpmTask) {
|
||||
dependsOn npmInstall
|
||||
args = ['run-script', 'clean']
|
||||
}
|
31
front/index.html
Normal file
31
front/index.html
Normal file
@ -0,0 +1,31 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||
<script src="/node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
|
||||
<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>Очень вкусно и запятая</title>
|
||||
</head>
|
||||
<body class="d-flex flex-column h-100">
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
</html>
|
3041
front/package-lock.json
generated
Normal file
3041
front/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
29
front/package.json
Normal file
29
front/package.json
Normal file
@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "front",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "vite --port 3000",
|
||||
"build": "vite build",
|
||||
"buildProd": "vite build --mode production",
|
||||
"preview": "vite preview",
|
||||
"clean": "rimraf dist"
|
||||
},
|
||||
"dependencies": {
|
||||
"bootstrap": "^5.2.2",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"axios": "^1.1.3",
|
||||
"react-router-dom": "^6.4.4",
|
||||
"@fortawesome/fontawesome-free": "^6.2.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.0.24",
|
||||
"@types/react-dom": "^18.0.8",
|
||||
"process": "^0.11.10",
|
||||
"rimraf": "4.4.0",
|
||||
"vite": "^3.2.3",
|
||||
"@vitejs/plugin-react": "^2.2.0"
|
||||
}
|
||||
}
|
1
front/public/favicon.svg
Normal file
1
front/public/favicon.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d="M96 0C43 0 0 43 0 96V416c0 53 43 96 96 96H384h32c17.7 0 32-14.3 32-32s-14.3-32-32-32V384c17.7 0 32-14.3 32-32V32c0-17.7-14.3-32-32-32H384 96zm0 384H352v64H96c-17.7 0-32-14.3-32-32s14.3-32 32-32zm32-240c0-8.8 7.2-16 16-16H336c8.8 0 16 7.2 16 16s-7.2 16-16 16H144c-8.8 0-16-7.2-16-16zm16 48H336c8.8 0 16 7.2 16 16s-7.2 16-16 16H144c-8.8 0-16-7.2-16-16s7.2-16 16-16z"/></svg>
|
After Width: | Height: | Size: 611 B |
87
front/src/App.css
Normal file
87
front/src/App.css
Normal file
@ -0,0 +1,87 @@
|
||||
nav {
|
||||
background-color: #c8afaf;
|
||||
}
|
||||
main {
|
||||
background-color: #8c7b7b;
|
||||
min-height: 90vh;
|
||||
}
|
||||
footer {
|
||||
background-color: #c8afaf;
|
||||
color: black;
|
||||
}
|
||||
|
||||
.size {
|
||||
overflow-x: hidden;
|
||||
}
|
||||
.card {
|
||||
background-color: #8c7b7b;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
91
front/src/App.jsx
Normal file
91
front/src/App.jsx
Normal file
@ -0,0 +1,91 @@
|
||||
import "./App.css";
|
||||
import {
|
||||
useRoutes,
|
||||
Outlet,
|
||||
BrowserRouter,
|
||||
Routes,
|
||||
Route,
|
||||
} from "react-router-dom";
|
||||
import Header from "./components/common/Header";
|
||||
import PrivateRoute from "./components/common/PrivateRoute";
|
||||
import Footer from "./components/common/Footer";
|
||||
import CatalogStudents from "./components/catalogs/CatalogStudents";
|
||||
import Menu from "./components/catalogs/Menu";
|
||||
import Basket from "./components/catalogs/Basket";
|
||||
import History from "./components/catalogs/History";
|
||||
import Registration from "./components/catalogs/Registration";
|
||||
import { useState } from "react";
|
||||
import Login from "./components/catalogs/Login";
|
||||
import Users from "./components/catalogs/Users";
|
||||
|
||||
function Router(props) {
|
||||
return useRoutes(props.rootRoute);
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const [product, setProduct] = useState([]);
|
||||
const routes = [
|
||||
{ index: true, element: <CatalogStudents /> },
|
||||
{
|
||||
path: "catalogs/menu",
|
||||
label: "Меню",
|
||||
},
|
||||
{
|
||||
path: "catalogs/component",
|
||||
label: "Компоненты",
|
||||
role: "ADMIN",
|
||||
},
|
||||
{
|
||||
path: "catalogs/basket",
|
||||
label: "Корзина",
|
||||
},
|
||||
{ path: "catalogs/history", label: "История" },
|
||||
{
|
||||
path: "catalogs/users",
|
||||
label: "Пользователи",
|
||||
role: "ADMIN",
|
||||
},
|
||||
{
|
||||
path: "catalogs/registration",
|
||||
label: "Регистрация",
|
||||
},
|
||||
{
|
||||
path: "catalogs/login",
|
||||
label: "Вход в систему",
|
||||
},
|
||||
];
|
||||
const links = routes.filter((route) => route.hasOwnProperty("label"));
|
||||
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Header links={links} />
|
||||
<div className="content-div">
|
||||
<Routes>
|
||||
<Route element={<PrivateRoute role="USER" />}>
|
||||
<Route
|
||||
element={<Menu product={product} setProduct={setProduct} />}
|
||||
path="/catalogs/menu"
|
||||
exact
|
||||
/>
|
||||
<Route
|
||||
element={<Menu product={product} setProduct={setProduct} />}
|
||||
path="*"
|
||||
/>
|
||||
<Route
|
||||
element={<Basket product={product} setProduct={setProduct} />}
|
||||
path="/catalogs/basket"
|
||||
/>
|
||||
<Route element={<History />} path="/catalogs/history" />
|
||||
</Route>
|
||||
<Route element={<PrivateRoute role="ADMIN" />}>
|
||||
<Route element={<CatalogStudents />} path="/catalogs/component" />
|
||||
<Route element={<Users />} path="/catalogs/users" />
|
||||
</Route>
|
||||
<Route element={<Login />} path="/catalogs/login" />
|
||||
<Route element={<Registration />} path="/catalogs/registration" />
|
||||
</Routes>
|
||||
</div>
|
||||
<Footer />
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
15
front/src/components/catalogs/Basket.jsx
Normal file
15
front/src/components/catalogs/Basket.jsx
Normal file
@ -0,0 +1,15 @@
|
||||
import Table from "../common/TableOrder";
|
||||
export default function Basket(props) {
|
||||
return (
|
||||
<main className="flex-shrink-0" style={{ backgroundColor: "white" }}>
|
||||
<h1 className="my-5 ms-5 fs-1">
|
||||
<b>Корзина</b>
|
||||
</h1>
|
||||
<h2 className="my-5 ms-5 fs-3"></h2>
|
||||
<div className="ms-5 my-5">Список товаров</div>
|
||||
<Table product={props.product} setProduct={props.setProduct}></Table>
|
||||
<p> </p>
|
||||
<p> </p>
|
||||
</main>
|
||||
);
|
||||
}
|
113
front/src/components/catalogs/Catalog.jsx
Normal file
113
front/src/components/catalogs/Catalog.jsx
Normal file
@ -0,0 +1,113 @@
|
||||
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 Catalog(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() {
|
||||
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>
|
||||
</>
|
||||
);
|
||||
}
|
66
front/src/components/catalogs/CatalogHistory.jsx
Normal file
66
front/src/components/catalogs/CatalogHistory.jsx
Normal file
@ -0,0 +1,66 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import Table from "../common/Table";
|
||||
import Modal from "../common/Modal";
|
||||
import DataService from '../../services/DataService';
|
||||
|
||||
export default function CatalogHistory(props) {
|
||||
const [items, setItems] = useState([]);
|
||||
const [modalHeader, setModalHeader] = useState('');
|
||||
const [modalConfirm, setModalConfirm] = useState('');
|
||||
const [modalVisible, setModalVisible] = useState(false);
|
||||
const [isEdit, setEdit] = useState(false);
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
loadItems();
|
||||
}, []);
|
||||
|
||||
function loadItems() {
|
||||
DataService.readAllOrders(props.getAllUrl+`/all/${localStorage.getItem("user")}`, props.transformer)
|
||||
.then(data => setItems(data));
|
||||
}
|
||||
|
||||
function saveItem() {
|
||||
if (!isEdit) {
|
||||
DataService.create(props.getAllUrl, props.data).then(() => loadItems());
|
||||
} else {
|
||||
DataService.update(props.url + props.data.id, props.data).then(() => loadItems());
|
||||
}
|
||||
}
|
||||
|
||||
function edit(editedId) {
|
||||
DataService.read(props.url + editedId, props.transformer)
|
||||
.then(data => {
|
||||
setEdit(true);
|
||||
setModalHeader('Редактирование элемента');
|
||||
setModalConfirm('Сохранить');
|
||||
setModalVisible(true);
|
||||
props.onEdit(data);
|
||||
});
|
||||
}
|
||||
|
||||
function handleModalHide() {
|
||||
setModalVisible(false);
|
||||
}
|
||||
|
||||
function handleModalDone() {
|
||||
saveItem();
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Table
|
||||
headers={props.headers}
|
||||
items={items}
|
||||
/>
|
||||
<Modal
|
||||
header={modalHeader}
|
||||
confirm={modalConfirm}
|
||||
visible={modalVisible}
|
||||
onHide={handleModalHide}
|
||||
onDone={handleModalDone}>
|
||||
{props.children}
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
269
front/src/components/catalogs/CatalogProduct.jsx
Normal file
269
front/src/components/catalogs/CatalogProduct.jsx
Normal file
@ -0,0 +1,269 @@
|
||||
import { useState, useEffect, Component } from "react";
|
||||
import Toolbar from "../common/ToolbarProduct";
|
||||
import Card from "../common/Card";
|
||||
import ModalProduct from "../common/ModalProduct";
|
||||
import DataService from "../../services/DataService";
|
||||
import Table from "../common/Table";
|
||||
import ToolbarProduct from "../common/Toolbar";
|
||||
|
||||
export default function CatalogProduct(props) {
|
||||
const [items, setItems] = useState([]);
|
||||
const [modalHeader, setModalHeader] = useState("");
|
||||
const [modalConfirm, setModalConfirm] = useState("");
|
||||
const [modalVisible, setModalVisible] = useState(false);
|
||||
const [isEdit, setEdit] = useState(false);
|
||||
const [componentProduct, setComponentProduct] = 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)
|
||||
);
|
||||
}
|
||||
|
||||
let selectedItems = [];
|
||||
async function saveItem() {
|
||||
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 handleAdd() {
|
||||
setEdit(false);
|
||||
setModalHeader("Добавление элемента");
|
||||
setModalConfirm("Добавить");
|
||||
setModalVisible(true);
|
||||
props.onAdd();
|
||||
}
|
||||
|
||||
function handleEdit(id) {
|
||||
if (selectedItems.length === 0) {
|
||||
return;
|
||||
}
|
||||
setComponentProduct(
|
||||
props.componentProduct.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.componentDTOList.length; i++){
|
||||
props.componentProduct.push(data.componentDTOList[i]);
|
||||
props.setcomponentProduct(props.componentProduct)
|
||||
}
|
||||
setEdit(true);
|
||||
setModalHeader("Редактирование элемента");
|
||||
setModalConfirm("Сохранить");
|
||||
setModalVisible(true);
|
||||
props.onEdit(data);
|
||||
});
|
||||
}
|
||||
|
||||
function handleRemove(id, e) {
|
||||
if (selectedItems.length === 0) {
|
||||
return;
|
||||
}
|
||||
if (confirm("Удалить выбранные элементы?")) {
|
||||
const promises = [];
|
||||
selectedItems.forEach((item) => {
|
||||
props.deleteComponents(item);
|
||||
});
|
||||
selectedItems.length = 0;
|
||||
}
|
||||
}
|
||||
function handleModalHide() {
|
||||
setModalVisible(false);
|
||||
props.setcomponentProduct([]);
|
||||
}
|
||||
|
||||
function handleModalDone() {
|
||||
saveItem();
|
||||
}
|
||||
async function handleAddComponent() {
|
||||
if (
|
||||
props.componentProduct.filter((x) => x.id == componentProduct.id)
|
||||
.length != 0
|
||||
) {
|
||||
await props.updateComponents(componentProduct, isEdit);
|
||||
setComponentProduct({});
|
||||
let count = 0;
|
||||
for (let i = 0; i < props.componentProduct.length; i++) {
|
||||
count +=
|
||||
props.componentProduct[i].price * props.componentProduct[i].count;
|
||||
}
|
||||
props.data.price = count;
|
||||
|
||||
if(isEdit){
|
||||
await props.setprice(count);
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
props.componentProduct.push(componentProduct);
|
||||
await props.setcomponentProduct(props.componentProduct);
|
||||
setComponentProduct({});
|
||||
let count = 0;
|
||||
for (let i = 0; i < props.componentProduct.length; i++) {
|
||||
count +=
|
||||
props.componentProduct[i].price * props.componentProduct[i].count;
|
||||
}
|
||||
props.data.price = count;
|
||||
}
|
||||
function handleRemoveProduct(id) {
|
||||
if (confirm("Удалить выбранные элементы?")) {
|
||||
DataService.delete(props.url + "/" + id).then(() => {
|
||||
loadItems();
|
||||
});
|
||||
}
|
||||
}
|
||||
function handleFormChangeComponent(event) {
|
||||
if (event.target.id === "componentName") {
|
||||
setComponentProduct({
|
||||
...componentProduct,
|
||||
["id"]: event.target.value,
|
||||
["componentName"]: props.component
|
||||
.filter((x) => x.id == event.target.value)
|
||||
.map((x) => x.componentName)[0],
|
||||
["price"]: props.component
|
||||
.filter((x) => x.id == event.target.value)
|
||||
.map((x) => x.price)[0],
|
||||
});
|
||||
return;
|
||||
}
|
||||
setComponentProduct({
|
||||
...componentProduct,
|
||||
[event.target.id]: Number(event.target.value),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const [imageURL, setImageURL] = useState();
|
||||
const fileReader = new FileReader();
|
||||
fileReader.onloadend = () => {
|
||||
const tempval = fileReader.result;
|
||||
setImageURL(tempval);
|
||||
props.setData(tempval);
|
||||
};
|
||||
function handleOnChange(event) {
|
||||
event.preventDefault();
|
||||
const file = event.target.files[0];
|
||||
fileReader.readAsDataURL(file);
|
||||
}
|
||||
function handleTableClick(tableSelectedItems) {
|
||||
selectedItems = tableSelectedItems;
|
||||
}
|
||||
function handleTableDblClick(tableSelectedItem) {
|
||||
setComponentProduct(
|
||||
props.componentProduct.filter((x) => x.id == tableSelectedItem)[0]
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<Toolbar onAdd={handleAdd} />
|
||||
<Card items={items} onEdit={edit} onRemove={handleRemoveProduct} product={props.product} setProduct={props.setProduct}/>
|
||||
<ModalProduct
|
||||
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="name"
|
||||
className="form-control"
|
||||
required
|
||||
value={props.data.name}
|
||||
onChange={props.handleFormChange}
|
||||
/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label htmlFor="price" className="form-label">
|
||||
Цена
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="price"
|
||||
className="form-control"
|
||||
required
|
||||
value={props.data.price}
|
||||
onChange={props.handleFormChange}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-mb-3">
|
||||
<label className="form-label" htmlFor="picture">
|
||||
Изображение
|
||||
</label>
|
||||
<input
|
||||
className="form-control"
|
||||
id="picture"
|
||||
type="file"
|
||||
accept="image/jpeg, image/png, image/jpg"
|
||||
value=""
|
||||
onChange={handleOnChange}
|
||||
/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label htmlFor="groupId" className="form-label">
|
||||
Компонент
|
||||
</label>
|
||||
<select
|
||||
id="componentName"
|
||||
className="form-select"
|
||||
required
|
||||
value={componentProduct.id}
|
||||
onChange={handleFormChangeComponent}
|
||||
>
|
||||
<option disabled value="">
|
||||
Укажите группу
|
||||
</option>
|
||||
{props.component.map((group) => (
|
||||
<option key={group.id} value={group.id}>
|
||||
{group.componentName}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<label htmlFor="count" className="form-label">
|
||||
Количество
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="count"
|
||||
className="form-control"
|
||||
required
|
||||
value={componentProduct.count ?? 0}
|
||||
onChange={handleFormChangeComponent}
|
||||
/>
|
||||
</div>
|
||||
<ToolbarProduct
|
||||
onAdd={handleAddComponent}
|
||||
onEdit={handleEdit}
|
||||
onRemove={handleRemove}
|
||||
/>
|
||||
<Table
|
||||
headers={props.catalogStudHeaders}
|
||||
items={props.componentProduct}
|
||||
allItems={props.component}
|
||||
selectable={true}
|
||||
onClick={handleTableClick}
|
||||
onDblClick={handleTableDblClick}
|
||||
/>
|
||||
</ModalProduct>
|
||||
</>
|
||||
);
|
||||
}
|
52
front/src/components/catalogs/CatalogStudents.jsx
Normal file
52
front/src/components/catalogs/CatalogStudents.jsx
Normal file
@ -0,0 +1,52 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import Catalog from './Catalog';
|
||||
import Component from '../../models/Component';
|
||||
import DataService from '../../services/DataService';
|
||||
|
||||
export default function CatalogStudents(props) {
|
||||
const getAllUrl = '/component';
|
||||
const url = '/component/';
|
||||
const transformer = (data) => new Component(data);
|
||||
const catalogStudHeaders = [
|
||||
{ name: 'componentName', label: 'Название компонента' },
|
||||
{ name: 'price', label: 'Цена' }
|
||||
];
|
||||
|
||||
const [data, setData] = useState(new Component());
|
||||
|
||||
function handleOnAdd() {
|
||||
setData(new Component());
|
||||
}
|
||||
|
||||
function handleOnEdit(data) {
|
||||
setData(new Component(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="componentName" className="form-label">Название компонента</label>
|
||||
<input type="text" id="componentName" className="form-control" required
|
||||
value={data.componentName} onChange={handleFormChange}/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label htmlFor="price" className="form-label">Цена</label>
|
||||
<input type="text" id="price" className="form-control" required
|
||||
value={data.price} onChange={handleFormChange}/>
|
||||
</div>
|
||||
</Catalog>
|
||||
</main>
|
||||
);
|
||||
}
|
54
front/src/components/catalogs/History.jsx
Normal file
54
front/src/components/catalogs/History.jsx
Normal file
@ -0,0 +1,54 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import Catalog from './CatalogHistory';
|
||||
import Component from '../../models/Component';
|
||||
import DataService from '../../services/DataService';
|
||||
import Order from '../../models/Order';
|
||||
|
||||
export default function CatalogStudents(props) {
|
||||
const getAllUrl = '/order';
|
||||
const url = '/order/';
|
||||
const transformer = (data) => new Order(data);
|
||||
const catalogStudHeaders = [
|
||||
{ name: 'date', label: 'Дата оформления' },
|
||||
{ name: 'price', label: 'Общая стоимость' },
|
||||
{ name: 'status', label: 'Статус' }
|
||||
];
|
||||
|
||||
const [data, setData] = useState(new Order());
|
||||
|
||||
function handleOnAdd() {
|
||||
setData(new Order());
|
||||
}
|
||||
|
||||
function handleOnEdit(data) {
|
||||
setData(new Order(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="componentName" className="form-label">Название компонента</label>
|
||||
<input type="text" id="componentName" className="form-control" required
|
||||
value={data.componentName} onChange={handleFormChange}/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label htmlFor="price" className="form-label">Цена</label>
|
||||
<input type="text" id="price" className="form-control" required
|
||||
value={data.price} onChange={handleFormChange}/>
|
||||
</div>
|
||||
</Catalog>
|
||||
</main>
|
||||
);
|
||||
}
|
109
front/src/components/catalogs/Login.jsx
Normal file
109
front/src/components/catalogs/Login.jsx
Normal file
@ -0,0 +1,109 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { useRef } from "react";
|
||||
export default function Login(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("/main");
|
||||
}
|
||||
|
||||
const loginFormOnSubmit = function (event) {
|
||||
event.preventDefault();
|
||||
loginsystem(login, password);
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<main className="flex-shrink-0" style={{ backgroundColor: "white" }}>
|
||||
<h1 className="my-5 ms-5 ">
|
||||
<b>Вход в систему</b>
|
||||
</h1>
|
||||
<form className="row g-3" onSubmit={loginFormOnSubmit}>
|
||||
<div className="mb-3 row ms-5">
|
||||
<label className="col-sm-2 col-form-label" htmlFor="login">
|
||||
Логин
|
||||
</label>
|
||||
<div className="form-outline col-sm-10">
|
||||
<input
|
||||
placeholder="Логин"
|
||||
className="form-control w-50"
|
||||
type="text"
|
||||
id="login"
|
||||
name="login"
|
||||
value={login}
|
||||
onChange={(e) => setLogin(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mb-3 row ms-5">
|
||||
<label className="col-sm-2 col-form-label" htmlFor="password">
|
||||
Пароль
|
||||
</label>
|
||||
<div className="col-sm-10">
|
||||
<input
|
||||
placeholder="Пароль"
|
||||
className="form-control w-50"
|
||||
type="password"
|
||||
id="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<h2>
|
||||
<button className="btn btn-success ms-5" style={{ color: "black" }}>
|
||||
Войти
|
||||
</button>
|
||||
</h2>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
}
|
112
front/src/components/catalogs/Menu.jsx
Normal file
112
front/src/components/catalogs/Menu.jsx
Normal file
@ -0,0 +1,112 @@
|
||||
import { useState, useEffect, Component } from "react";
|
||||
import CatalogProduct from "./CatalogProduct";
|
||||
import Product from "../../models/Product";
|
||||
import Components from "../../models/Component";
|
||||
import DataService from "../../services/DataService";
|
||||
export default function Menu(props) {
|
||||
const url = "/product";
|
||||
const categoryUrl = "/component";
|
||||
const transformer = (data) => new Product(data);
|
||||
const catalogStudHeaders = [
|
||||
{ name: "componentName", label: "Название компонента" },
|
||||
{ name: "count", label: "Количество" },
|
||||
];
|
||||
const [data, setData] = useState(new Product());
|
||||
const [component, setComponent] = useState([]);
|
||||
const [componentProduct, setComponentProduct] = useState([]);
|
||||
useEffect(() => {
|
||||
DataService.readAll(categoryUrl, (data) => new Components(data)).then(
|
||||
(data) => setComponent(data)
|
||||
);
|
||||
}, []);
|
||||
|
||||
function handleOnAdd() {
|
||||
setData(new Product());
|
||||
setComponentProduct([]);
|
||||
}
|
||||
function handleOnEdit(data) {
|
||||
setData(new Product(data));
|
||||
}
|
||||
|
||||
function handleFormChange(event) {
|
||||
setData({ ...data, [event.target.id]: event.target.value });
|
||||
}
|
||||
const [imageURL, setImageURL] = useState();
|
||||
const fileReader = new FileReader();
|
||||
fileReader.onloadend = () => {
|
||||
const tempval = fileReader.result;
|
||||
setImageURL(tempval);
|
||||
setData({ ...data, ["picture"]: tempval });
|
||||
};
|
||||
function handleOnChange(event) {
|
||||
event.preventDefault();
|
||||
const file = event.target.files[0];
|
||||
fileReader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
function handleUpdateComponents(value, bool) {
|
||||
if (bool) {
|
||||
let temp = data.componentDTOList.filter((x) => x.id != value.id);
|
||||
data.componentDTOList = [];
|
||||
for (let i = 0; i < temp.length; i++) {
|
||||
data.componentDTOList.push(temp[i]);
|
||||
}
|
||||
data.componentDTOList.push(value);
|
||||
setData(data);
|
||||
}
|
||||
setComponentProduct(
|
||||
componentProduct.map((obj) => {
|
||||
if (obj.id == value.id) {
|
||||
return { ...obj, count: value.count };
|
||||
} else {
|
||||
return obj;
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
function setDataa(value) {
|
||||
setData({ ...data, ["image"]: value });
|
||||
}
|
||||
function setComponents() {
|
||||
data.componentDTOList = [];
|
||||
for (let i = 0; i < componentProduct.length; i++) {
|
||||
data.componentDTOList.push(componentProduct[i]);
|
||||
}
|
||||
setData(data);
|
||||
}
|
||||
function handleDeleteComponents(value) {
|
||||
setComponentProduct(componentProduct.filter((x) => x.id !== value));
|
||||
}
|
||||
function setprice(value){
|
||||
let count = 0;
|
||||
for (let i = 0; i < data.componentDTOList.length; i++) {
|
||||
count +=
|
||||
data.componentDTOList[i].price * data.componentDTOList[i].count;
|
||||
}
|
||||
data.price = count;
|
||||
}
|
||||
return (
|
||||
<main className="flex-shrink-0">
|
||||
<CatalogProduct
|
||||
url={url}
|
||||
transformer={transformer}
|
||||
data={data}
|
||||
onAdd={handleOnAdd}
|
||||
onEdit={handleOnEdit}
|
||||
handleFormChange={handleFormChange}
|
||||
handleOnChange={handleOnChange}
|
||||
component={component}
|
||||
catalogStudHeaders={catalogStudHeaders}
|
||||
componentProduct={componentProduct}
|
||||
setcomponentProduct={setComponentProduct}
|
||||
updateComponents={handleUpdateComponents}
|
||||
deleteComponents={handleDeleteComponents}
|
||||
setData={setDataa}
|
||||
set={setComponents}
|
||||
setprice={setprice}
|
||||
product={props.product}
|
||||
setProduct={props.setProduct}
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
}
|
115
front/src/components/catalogs/Registration.jsx
Normal file
115
front/src/components/catalogs/Registration.jsx
Normal file
@ -0,0 +1,115 @@
|
||||
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/menu");
|
||||
} 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 ms-5 ">
|
||||
<b>Регистрация</b>
|
||||
</h1>
|
||||
<form className="row g-3" onSubmit={signupFormOnSubmit}>
|
||||
<div className="mb-3 row ms-5">
|
||||
<label className="col-sm-2 col-form-label" htmlFor="login">
|
||||
Логин
|
||||
</label>
|
||||
<div className="form-outline col-sm-10">
|
||||
<input
|
||||
placeholder="Логин"
|
||||
className="form-control w-50"
|
||||
type="text"
|
||||
id="login"
|
||||
name="login"
|
||||
value={login}
|
||||
onChange={(e) => setLogin(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mb-3 row ms-5">
|
||||
<label className="col-sm-2 col-form-label" htmlFor="password">
|
||||
Пароль
|
||||
</label>
|
||||
<div className="col-sm-10">
|
||||
<input
|
||||
placeholder="Пароль"
|
||||
className="form-control w-50"
|
||||
type="password"
|
||||
id="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mb-3 row ms-5">
|
||||
<label className="col-sm-2 col-form-label" htmlFor="passwordConfirm">
|
||||
Пароль
|
||||
</label>
|
||||
<div className="col-sm-10">
|
||||
<input
|
||||
placeholder="Подтверждение пароля"
|
||||
className="form-control w-50"
|
||||
type="password"
|
||||
id="passwordConfirm"
|
||||
value={passwordConfirm}
|
||||
onChange={(e) => setPasswordConfirm(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<h2>
|
||||
<button className="btn btn-success ms-5" style={{ color: "black" }}>
|
||||
Зарегистрироваться
|
||||
</button>
|
||||
</h2>
|
||||
</form>
|
||||
</main>
|
||||
);
|
||||
}
|
76
front/src/components/catalogs/Users.jsx
Normal file
76
front/src/components/catalogs/Users.jsx
Normal file
@ -0,0 +1,76 @@
|
||||
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>
|
||||
<div>
|
||||
<p>Pages:</p>
|
||||
<nav>
|
||||
<ul className="pagination" style={{ backgroundColor: "white" }}>
|
||||
{pageNumbers.map((number, index) => (
|
||||
<li key={index}
|
||||
className={`page-item ${
|
||||
number === pageNumber ? "active" : ""
|
||||
}`}
|
||||
onClick={() => pageButtonOnClick(number)}
|
||||
>
|
||||
<a className="page-link" >
|
||||
{number}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
</div>
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
76
front/src/components/common/Card.jsx
Normal file
76
front/src/components/common/Card.jsx
Normal file
@ -0,0 +1,76 @@
|
||||
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 currentProduct = props.product.filter((x) => x.id == id.id);
|
||||
if (currentProduct.length != 0) {
|
||||
let temp = props.product.filter((x) => x.id != id.id);
|
||||
currentProduct[0].count++;
|
||||
temp.push(currentProduct[0]);
|
||||
await props.setProduct(temp);
|
||||
return;
|
||||
} else {
|
||||
id.count++;
|
||||
props.product.push(id);
|
||||
props.setProduct(props.product);
|
||||
}
|
||||
}
|
||||
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: "350px" }}
|
||||
>
|
||||
<img
|
||||
src={item["image"]}
|
||||
className="img-fluid rounded mx-auto d-block"
|
||||
style={{ width: "100%", height: "350px", objectFit: "contain" }}
|
||||
alt="Бугер"
|
||||
/>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<h5 className="card-title text-center fs-1">{item["price"]}</h5>
|
||||
{localStorage.getItem("role") == "ADMIN" && (
|
||||
<>
|
||||
<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>
|
||||
</>
|
||||
)}
|
||||
<a
|
||||
type="button"
|
||||
className="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
|
||||
onClick={() => mess(item)}
|
||||
>
|
||||
в корзину
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
8
front/src/components/common/Footer.jsx
Normal file
8
front/src/components/common/Footer.jsx
Normal file
@ -0,0 +1,8 @@
|
||||
export default function Footer(props) {
|
||||
return (
|
||||
<footer className="footer mt-auto d-flex justify-content-center align-items-center">
|
||||
ООО "Вкусно" © 2022
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
|
67
front/src/components/common/Header.jsx
Normal file
67
front/src/components/common/Header.jsx
Normal file
@ -0,0 +1,67 @@
|
||||
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("/catalogs/login");
|
||||
localStorage.removeItem("role");
|
||||
localStorage.removeItem("user");
|
||||
localStorage.removeItem("token");
|
||||
}
|
||||
return (
|
||||
<nav className="navbar navbar-expand-lg">
|
||||
<div className="container-fluid">
|
||||
<NavLink className="navbar-brand" to={"/"}>
|
||||
<h1>Очень вкусно и запятая</h1>
|
||||
</NavLink>
|
||||
<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" to={route.path}>
|
||||
{route.label}
|
||||
</NavLink>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
<span className="col text-end">
|
||||
{localStorage.getItem("role") !== null &&
|
||||
<a className="nav-link" onClick={handlelogout}>
|
||||
{"Выход(" + localStorage.getItem("user") + ")"}
|
||||
</a>
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
}
|
46
front/src/components/common/Modal.jsx
Normal file
46
front/src/components/common/Modal.jsx
Normal file
@ -0,0 +1,46 @@
|
||||
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>
|
||||
);
|
||||
}
|
46
front/src/components/common/ModalProduct.jsx
Normal file
46
front/src/components/common/ModalProduct.jsx
Normal file
@ -0,0 +1,46 @@
|
||||
import React from "react";
|
||||
|
||||
export default function ModalProduct(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>
|
||||
);
|
||||
}
|
45
front/src/components/common/PrivateRoute.jsx
Normal file
45
front/src/components/common/PrivateRoute.jsx
Normal file
@ -0,0 +1,45 @@
|
||||
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/main");
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
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 (
|
||||
props.role === userRole || userRole == "ADMIN"
|
||||
) {
|
||||
isAllowed = true;
|
||||
}
|
||||
|
||||
return isAllowed ? <Outlet /> : <Navigate to="/catalogs/login" />;
|
||||
}
|
73
front/src/components/common/Table.jsx
Normal file
73
front/src/components/common/Table.jsx
Normal file
@ -0,0 +1,73 @@
|
||||
import { useState } from 'react';
|
||||
import styles from './Table.module.css';
|
||||
|
||||
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 >
|
||||
);
|
||||
}
|
12
front/src/components/common/Table.module.css
Normal file
12
front/src/components/common/Table.module.css
Normal file
@ -0,0 +1,12 @@
|
||||
.table tbody tr {
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.selectable tbody tr:hover {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.selected {
|
||||
background-color: #0d6efd;
|
||||
opacity: 80%;
|
||||
}
|
92
front/src/components/common/TableOrder.jsx
Normal file
92
front/src/components/common/TableOrder.jsx
Normal file
@ -0,0 +1,92 @@
|
||||
import { useEffect } from "react";
|
||||
import { useState } from "react";
|
||||
import DataService from "../../services/DataService";
|
||||
import Order from "../../models/Order";
|
||||
|
||||
export default function TableOrder(props) {
|
||||
const [order, setOrder] = useState(new Order())
|
||||
const [cost, setCost] = useState(0);
|
||||
const [del, setDel] = useState(false);
|
||||
useEffect(() => {
|
||||
loadItems();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
loadItems();
|
||||
setDel(false);
|
||||
}, [del]);
|
||||
async function loadItems() {
|
||||
await summ(props.product.sort((a, b) => a.name > b.name ? 1 : -1));
|
||||
|
||||
setOrder({...order,["productDTOList"]: props.product, ["price"]:cost});
|
||||
}
|
||||
async function summ(data) {
|
||||
let tem = 0;
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
tem += data[i].count * Number(data[i].price);
|
||||
}
|
||||
setCost(tem);
|
||||
setOrder({...order,["price"]: tem});
|
||||
}
|
||||
async function deleteItem(item) {
|
||||
let currentProduct = props.product.filter((x) => x.id == item.id)[0];
|
||||
let temp = props.product.filter((x) => x.id != item.id);
|
||||
if (currentProduct.count - 1 == 0) {
|
||||
props.setProduct(temp);
|
||||
setDel(true);
|
||||
loadItems();
|
||||
return;
|
||||
} else {
|
||||
currentProduct.count--;
|
||||
temp.push(currentProduct);
|
||||
props.setProduct(temp);
|
||||
setDel(true);
|
||||
loadItems();
|
||||
}
|
||||
}
|
||||
async function acceptOrder(){
|
||||
await DataService.create("/order",{...order, ["price"]:cost, ["status"]: "1", ["user"]:localStorage.getItem("user")} ).then(data => {
|
||||
props.setProduct([]);
|
||||
setCost(0);
|
||||
});
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
<div style={{ maxWidth: "35%" }}>
|
||||
<table className="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">#</th>
|
||||
<th scope="col">Позиция</th>
|
||||
<th scope="col"> </th>
|
||||
<th scope="col">Стоимость</th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="table-group-divider">
|
||||
{props.product.map((item, index) => (
|
||||
<tr key={item.id}>
|
||||
<th scope="row">{index + 1}</th>
|
||||
<td colSpan="2">{item.name}</td>
|
||||
<td>
|
||||
{item.count}x{item.price} руб
|
||||
</td>
|
||||
<td>
|
||||
<button onClick={() => deleteItem(item)}>Удалить</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<h2 className="ms-5 my-5">Итого: {cost} руб</h2>
|
||||
<button
|
||||
className="btn btn-success ms-5 w-25"
|
||||
type="button"
|
||||
style={{ color: "black" }}
|
||||
onClick={acceptOrder}
|
||||
>
|
||||
Купить
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
29
front/src/components/common/Toolbar.jsx
Normal file
29
front/src/components/common/Toolbar.jsx
Normal file
@ -0,0 +1,29 @@
|
||||
import styles from './Toolbar.module.css';
|
||||
|
||||
export default function Toolbar(props) {
|
||||
function add() {
|
||||
props.onAdd();
|
||||
}
|
||||
|
||||
function edit() {
|
||||
props.onEdit();
|
||||
}
|
||||
|
||||
function remove() {
|
||||
props.onRemove();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="btn-group mt-2" role="group">
|
||||
<button type="button" className={`btn btn-outline-dark text-center d-flex justify-content-md-center mx-2 mb-3`} onClick={add}>
|
||||
Добавить
|
||||
</button>
|
||||
<button type="button" className={`btn btn-outline-dark text-center d-flex justify-content-md-center mx-2 mb-3`} onClick={edit} >
|
||||
Изменить
|
||||
</button >
|
||||
<button type="button" className={`btn btn-outline-dark text-center d-flex justify-content-md-center mx-2 mb-3`} onClick={remove}>
|
||||
Удалить
|
||||
</button >
|
||||
</div >
|
||||
);
|
||||
}
|
3
front/src/components/common/Toolbar.module.css
Normal file
3
front/src/components/common/Toolbar.module.css
Normal file
@ -0,0 +1,3 @@
|
||||
.btn {
|
||||
min-width: 140px;
|
||||
}
|
21
front/src/components/common/ToolbarProduct.jsx
Normal file
21
front/src/components/common/ToolbarProduct.jsx
Normal file
@ -0,0 +1,21 @@
|
||||
export default function ToolbarProduct(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
front/src/main.jsx
Normal file
8
front/src/main.jsx
Normal 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 />
|
||||
)
|
7
front/src/models/Component.js
Normal file
7
front/src/models/Component.js
Normal file
@ -0,0 +1,7 @@
|
||||
export default class Component {
|
||||
constructor(data) {
|
||||
this.id = data?.id;
|
||||
this.price = data?.price || "";
|
||||
this.componentName = data?.componentName || "";
|
||||
}
|
||||
}
|
10
front/src/models/Order.js
Normal file
10
front/src/models/Order.js
Normal file
@ -0,0 +1,10 @@
|
||||
export default class Order {
|
||||
constructor(data) {
|
||||
this.id = data?.id;
|
||||
this.date = data?.date || "";
|
||||
this.price = data?.price || 0;
|
||||
this.productDTOList = data?.productDTOList || [];
|
||||
this.status = data?.status || "0";
|
||||
this.user = data?.user || "";
|
||||
}
|
||||
}
|
10
front/src/models/Product.js
Normal file
10
front/src/models/Product.js
Normal file
@ -0,0 +1,10 @@
|
||||
export default class Product {
|
||||
constructor(data) {
|
||||
this.id = data?.id;
|
||||
this.price = data?.price || "";
|
||||
this.name = data?.name || "";
|
||||
this.count = data?.count || 0;
|
||||
this.image = data?.image || "";
|
||||
this.componentDTOList = data?.componentDTOList || [];
|
||||
}
|
||||
}
|
7
front/src/models/User.js
Normal file
7
front/src/models/User.js
Normal file
@ -0,0 +1,7 @@
|
||||
export default class User {
|
||||
constructor(data) {
|
||||
this.id = data?.id;
|
||||
this.login = data?.login || "";
|
||||
this.role = data?.role || "";
|
||||
}
|
||||
}
|
80
front/src/services/DataService.js
Normal file
80
front/src/services/DataService.js
Normal file
@ -0,0 +1,80 @@
|
||||
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();
|
||||
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),
|
||||
};
|
||||
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;
|
||||
}
|
||||
|
||||
static async readUser(url, data) {
|
||||
const response = await axios.get(this.dataUrlPrefix + url + `/${data}`);
|
||||
return response.data;
|
||||
}
|
||||
static async readAllOrders(url, transformer) {
|
||||
const response = await fetch(this.dataUrlPrefix + url, {headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": "Bearer " + localStorage.getItem("token")
|
||||
}});
|
||||
const data = await response.json();
|
||||
return data.map(item => transformer(item));
|
||||
}
|
||||
}
|
0
front/src/style.css
Normal file
0
front/src/style.css
Normal file
7
front/vite.config.js
Normal file
7
front/vite.config.js
Normal file
@ -0,0 +1,7 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()]
|
||||
})
|
@ -1 +1,2 @@
|
||||
rootProject.name = 'labwork'
|
||||
include 'front'
|
@ -2,18 +2,10 @@ package ip.labwork;
|
||||
|
||||
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 LabworkApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(LabworkApplication.class, args);
|
||||
}
|
||||
@GetMapping("/hello")
|
||||
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
|
||||
return String.format("Hello %s!", name);
|
||||
}
|
||||
}
|
||||
|
@ -1,13 +0,0 @@
|
||||
package ip.labwork;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
class WebConfiguration implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry){
|
||||
registry.addMapping("/**").allowedMethods("*");
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package ip.labwork.configuration;
|
||||
|
||||
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 ip.labwork.configuration.jwt.JwtFilter;
|
||||
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")));
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package ip.labwork.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 passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
@ -0,0 +1,92 @@
|
||||
package ip.labwork.configuration;
|
||||
|
||||
import ip.labwork.configuration.jwt.JwtFilter;
|
||||
import ip.labwork.user.controller.UserController;
|
||||
import ip.labwork.user.model.UserRole;
|
||||
import ip.labwork.user.service.UserService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.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.passwordEncoder())
|
||||
.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/**");
|
||||
}
|
||||
}
|
36
src/main/java/ip/labwork/configuration/WebConfiguration.java
Normal file
36
src/main/java/ip/labwork/configuration/WebConfiguration.java
Normal file
@ -0,0 +1,36 @@
|
||||
package ip.labwork.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.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistration;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
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"));
|
||||
};
|
||||
}
|
||||
}
|
11
src/main/java/ip/labwork/configuration/jwt/JwtException.java
Normal file
11
src/main/java/ip/labwork/configuration/jwt/JwtException.java
Normal file
@ -0,0 +1,11 @@
|
||||
package ip.labwork.configuration.jwt;
|
||||
|
||||
public class JwtException extends RuntimeException {
|
||||
public JwtException(Throwable throwable) {
|
||||
super(throwable);
|
||||
}
|
||||
|
||||
public JwtException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
72
src/main/java/ip/labwork/configuration/jwt/JwtFilter.java
Normal file
72
src/main/java/ip/labwork/configuration/jwt/JwtFilter.java
Normal file
@ -0,0 +1,72 @@
|
||||
package ip.labwork.configuration.jwt;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import ip.labwork.user.service.UserService;
|
||||
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);
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package ip.labwork.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;
|
||||
}
|
||||
}
|
107
src/main/java/ip/labwork/configuration/jwt/JwtProvider.java
Normal file
107
src/main/java/ip/labwork/configuration/jwt/JwtProvider.java
Normal file
@ -0,0 +1,107 @@
|
||||
package ip.labwork.configuration.jwt;
|
||||
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import com.auth0.jwt.exceptions.JWTVerificationException;
|
||||
import com.auth0.jwt.interfaces.DecodedJWT;
|
||||
import com.auth0.jwt.interfaces.JWTVerifier;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
public class JwtProvider {
|
||||
private final static Logger LOG = LoggerFactory.getLogger(JwtProvider.class);
|
||||
|
||||
private final static byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
|
||||
private final static String ISSUER = "auth0";
|
||||
|
||||
private final Algorithm algorithm;
|
||||
private final JWTVerifier verifier;
|
||||
|
||||
public JwtProvider(JwtProperties jwtProperties) {
|
||||
if (!jwtProperties.isDev()) {
|
||||
LOG.info("Generate new JWT key for prod");
|
||||
try {
|
||||
final MessageDigest salt = MessageDigest.getInstance("SHA-256");
|
||||
salt.update(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));
|
||||
LOG.info("Use generated JWT key for prod \n{}", bytesToHex(salt.digest()));
|
||||
algorithm = Algorithm.HMAC256(bytesToHex(salt.digest()));
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new JwtException(e);
|
||||
}
|
||||
} else {
|
||||
LOG.info("Use default JWT key for dev \n{}", jwtProperties.getDevToken());
|
||||
algorithm = Algorithm.HMAC256(jwtProperties.getDevToken());
|
||||
}
|
||||
verifier = JWT.require(algorithm)
|
||||
.withIssuer(ISSUER)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static String bytesToHex(byte[] bytes) {
|
||||
byte[] hexChars = new byte[bytes.length * 2];
|
||||
for (int j = 0; j < bytes.length; j++) {
|
||||
int v = bytes[j] & 0xFF;
|
||||
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
|
||||
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
|
||||
}
|
||||
return new String(hexChars, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public String generateToken(String login) {
|
||||
final Date issueDate = Date.from(LocalDate.now()
|
||||
.atStartOfDay(ZoneId.systemDefault())
|
||||
.toInstant());
|
||||
final Date expireDate = Date.from(LocalDate.now()
|
||||
.plusDays(15)
|
||||
.atStartOfDay(ZoneId.systemDefault())
|
||||
.toInstant());
|
||||
return JWT.create()
|
||||
.withIssuer(ISSUER)
|
||||
.withIssuedAt(issueDate)
|
||||
.withExpiresAt(expireDate)
|
||||
.withSubject(login)
|
||||
.sign(algorithm);
|
||||
}
|
||||
|
||||
private DecodedJWT validateToken(String token) {
|
||||
try {
|
||||
return verifier.verify(token);
|
||||
} catch (JWTVerificationException e) {
|
||||
throw new JwtException(String.format("Token verification error: %s", e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isTokenValid(String token) {
|
||||
if (!StringUtils.hasText(token)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
validateToken(token);
|
||||
return true;
|
||||
} catch (JwtException e) {
|
||||
LOG.error(e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<String> getLoginFromToken(String token) {
|
||||
try {
|
||||
return Optional.ofNullable(validateToken(token).getSubject());
|
||||
} catch (JwtException e) {
|
||||
LOG.error(e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
package ip.labwork.method.controller;
|
||||
|
||||
import ip.labwork.method.service.MethodService;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class MethodController {
|
||||
private final MethodService speakerService;
|
||||
|
||||
public MethodController(MethodService speakerService) {
|
||||
this.speakerService = speakerService;
|
||||
}
|
||||
|
||||
@GetMapping("/sum")
|
||||
public String Sum(@RequestParam(value = "first", defaultValue = "1") Object first,
|
||||
@RequestParam(value = "second", defaultValue = "1") Object second,
|
||||
@RequestParam(value = "type", defaultValue = "int") String type) {
|
||||
return speakerService.Sum(first,second,type);
|
||||
}
|
||||
|
||||
@GetMapping("/minus")
|
||||
public String Ras(@RequestParam(value = "first", defaultValue = "1") Object first,
|
||||
@RequestParam(value = "second", defaultValue = "1") Object second,
|
||||
@RequestParam(value = "type", defaultValue = "int") String type) {
|
||||
return speakerService.Ras(first,second,type);
|
||||
}
|
||||
|
||||
@GetMapping("/multi")
|
||||
public String Pros(@RequestParam(value = "first", defaultValue = "1") Object first,
|
||||
@RequestParam(value = "second", defaultValue = "1") Object second,
|
||||
@RequestParam(value = "type", defaultValue = "int") String type) {
|
||||
return speakerService.Pros(first,second,type);
|
||||
}
|
||||
|
||||
@GetMapping("/div")
|
||||
public String Del(@RequestParam(value = "first", defaultValue = "1") Object first,
|
||||
@RequestParam(value = "second", defaultValue = "1") Object second,
|
||||
@RequestParam(value = "type", defaultValue = "int") String type) {
|
||||
return speakerService.Del(first,second,type);
|
||||
}
|
||||
}
|
11
src/main/java/ip/labwork/method/domain/IMethod.java
Normal file
11
src/main/java/ip/labwork/method/domain/IMethod.java
Normal file
@ -0,0 +1,11 @@
|
||||
package ip.labwork.method.domain;
|
||||
|
||||
public interface IMethod<T> {
|
||||
T Sum(T first, T second);
|
||||
|
||||
T Multiply(T first, Integer second);
|
||||
|
||||
T Minus(T first, Integer second);
|
||||
|
||||
T Div(T first, T second);
|
||||
}
|
27
src/main/java/ip/labwork/method/domain/MethodInt.java
Normal file
27
src/main/java/ip/labwork/method/domain/MethodInt.java
Normal file
@ -0,0 +1,27 @@
|
||||
package ip.labwork.method.domain;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component(value="int")
|
||||
public class MethodInt implements IMethod<Integer>{
|
||||
public Integer Sum(Integer first, Integer second) {
|
||||
return Integer.parseInt(first.toString()) + Integer.parseInt(second.toString());
|
||||
}
|
||||
|
||||
public Integer Multiply(Integer first, Integer second) {
|
||||
return Integer.parseInt(first.toString()) * Integer.parseInt(second.toString());
|
||||
}
|
||||
|
||||
public Integer Minus(Integer first, Integer second) {
|
||||
return Integer.parseInt(first.toString()) - Integer.parseInt(second.toString());
|
||||
}
|
||||
|
||||
public Integer Div(Integer first, Integer second) {
|
||||
int num = Integer.parseInt(second.toString());
|
||||
if (num == 0){
|
||||
return null;
|
||||
}else{
|
||||
return Integer.parseInt(first.toString()) / num;
|
||||
}
|
||||
}
|
||||
}
|
44
src/main/java/ip/labwork/method/domain/MethodString.java
Normal file
44
src/main/java/ip/labwork/method/domain/MethodString.java
Normal file
@ -0,0 +1,44 @@
|
||||
package ip.labwork.method.domain;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component(value="string")
|
||||
public class MethodString implements IMethod<String>{
|
||||
@Override
|
||||
public String Sum(String first, String second) {
|
||||
return first.concat(second);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String Multiply(String first, Integer second) {
|
||||
if (second != 0){
|
||||
String temp = "";
|
||||
for (int i = 0; i < second; i++){
|
||||
temp = temp.concat(first);
|
||||
}
|
||||
return temp;
|
||||
}
|
||||
else{
|
||||
return first;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String Minus(String first, Integer second) {
|
||||
String temp = first;
|
||||
if(temp.length() >= second){
|
||||
return temp.substring(0, first.length() - second);
|
||||
}else{
|
||||
return first;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String Div(String first, String second) {
|
||||
if (first.contains(second)){
|
||||
return "true";
|
||||
}else{
|
||||
return "false";
|
||||
}
|
||||
}
|
||||
}
|
51
src/main/java/ip/labwork/method/service/MethodService.java
Normal file
51
src/main/java/ip/labwork/method/service/MethodService.java
Normal file
@ -0,0 +1,51 @@
|
||||
package ip.labwork.method.service;
|
||||
|
||||
import ip.labwork.method.domain.IMethod;
|
||||
import ip.labwork.method.domain.MethodString;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class MethodService {
|
||||
private final ApplicationContext applicationContext;
|
||||
|
||||
public MethodService(ApplicationContext applicationContext) {
|
||||
this.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
public String Sum(Object first, Object second, String type) {
|
||||
final IMethod speaker = (IMethod) applicationContext.getBean(type);
|
||||
if (speaker instanceof MethodString){
|
||||
return String.format("%s", speaker.Sum(first,second));
|
||||
}else{
|
||||
return String.format("%s", speaker.Sum(Integer.parseInt(first.toString()),Integer.parseInt(second.toString())));
|
||||
}
|
||||
}
|
||||
|
||||
public String Ras(Object first, Object second, String type) {
|
||||
final IMethod speaker = (IMethod) applicationContext.getBean(type);
|
||||
if (speaker instanceof MethodString){
|
||||
return String.format("%s", speaker.Minus(first,Integer.parseInt(second.toString())));
|
||||
}else{
|
||||
return String.format("%s", speaker.Minus(Integer.parseInt(first.toString()),Integer.parseInt(second.toString())));
|
||||
}
|
||||
}
|
||||
|
||||
public String Pros(Object first, Object second, String type) {
|
||||
final IMethod speaker = (IMethod) applicationContext.getBean(type);
|
||||
if (speaker instanceof MethodString){
|
||||
return String.format("%s", speaker.Multiply(first,Integer.parseInt(second.toString())));
|
||||
}else{
|
||||
return String.format("%s", speaker.Multiply(Integer.parseInt(first.toString()),Integer.parseInt(second.toString())));
|
||||
}
|
||||
}
|
||||
|
||||
public String Del(Object first, Object second, String type) {
|
||||
final IMethod speaker = (IMethod) applicationContext.getBean(type);
|
||||
if (speaker instanceof MethodString){
|
||||
return String.format("%s", speaker.Div(first,second));
|
||||
}else {
|
||||
return String.format("%s", speaker.Div(Integer.parseInt(first.toString()), Integer.parseInt(second.toString())));
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
package ip.labwork.shop.controller;
|
||||
|
||||
import ip.labwork.shop.service.ComponentService;
|
||||
import ip.labwork.user.model.UserRole;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.security.access.annotation.Secured;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/component")
|
||||
|
||||
public class ComponentController {
|
||||
private final ComponentService componentService;
|
||||
|
||||
public ComponentController(ComponentService componentService) {
|
||||
this.componentService = componentService;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public ComponentDTO createComponent(@RequestBody @Valid ComponentDTO componentDTO) {
|
||||
return componentService.create(componentDTO);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public ComponentDTO updateComponent(@PathVariable Long id, @RequestBody @Valid ComponentDTO componentDTO) {
|
||||
return componentService.updateComponent(id, componentDTO);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public ComponentDTO removeComponent(@PathVariable Long id) {
|
||||
return componentService.deleteComponent(id);
|
||||
}
|
||||
|
||||
@DeleteMapping
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public void removeAllComponent() {
|
||||
componentService.deleteAllComponent();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public ComponentDTO findComponent(@PathVariable Long id) {
|
||||
return new ComponentDTO(componentService.findComponent(id));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public List<ComponentDTO> findAllComponent() {
|
||||
return componentService.findAllComponent();
|
||||
}
|
||||
}
|
40
src/main/java/ip/labwork/shop/controller/ComponentDTO.java
Normal file
40
src/main/java/ip/labwork/shop/controller/ComponentDTO.java
Normal file
@ -0,0 +1,40 @@
|
||||
package ip.labwork.shop.controller;
|
||||
|
||||
import ip.labwork.shop.model.Component;
|
||||
|
||||
public class ComponentDTO {
|
||||
private long id;
|
||||
private String componentName;
|
||||
private int price;
|
||||
private int count = 0;
|
||||
public ComponentDTO(Component component) {
|
||||
this.id = component.getId();
|
||||
this.componentName = component.getComponentName();
|
||||
this.price = component.getPrice();
|
||||
}
|
||||
public ComponentDTO(Component component, int count) {
|
||||
this.id = component.getId();
|
||||
this.componentName = component.getComponentName();
|
||||
this.price = component.getPrice();
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
public ComponentDTO() {
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getComponentName() {
|
||||
return componentName;
|
||||
}
|
||||
|
||||
public int getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
public int getPrice() {
|
||||
return price;
|
||||
}
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
package ip.labwork.shop.controller;
|
||||
|
||||
import ip.labwork.shop.service.OrderService;
|
||||
import ip.labwork.user.model.UserRole;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.security.access.annotation.Secured;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/order")
|
||||
public class OrderController {
|
||||
private final OrderService orderService;
|
||||
|
||||
public OrderController(OrderService orderService) {
|
||||
this.orderService = orderService;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@Secured({UserRole.AsString.USER, UserRole.AsString.ADMIN})
|
||||
public OrderDTO createOrder(@RequestBody @Valid OrderDTO orderDTO) {
|
||||
return orderService.create(orderDTO);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public OrderDTO updateOrder(@PathVariable Long id, @RequestBody @Valid OrderDTO orderDTO) {
|
||||
return orderService.update(id, orderDTO);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public OrderDTO removeOrder(@PathVariable Long id) {
|
||||
return orderService.deleteOrder(id);
|
||||
}
|
||||
|
||||
@DeleteMapping
|
||||
public void removeAllOrder() {
|
||||
orderService.deleteAllOrder();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
@Secured({UserRole.AsString.USER, UserRole.AsString.ADMIN})
|
||||
public OrderDTO findOrder(@PathVariable Long id) {
|
||||
return new OrderDTO(orderService.findOrder(id));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@Secured({UserRole.AsString.USER, UserRole.AsString.ADMIN})
|
||||
public List<OrderDTO> findAllOrder() {
|
||||
return orderService.findAllOrder();
|
||||
}
|
||||
|
||||
@GetMapping("/all/{login}")
|
||||
@Secured({UserRole.AsString.USER, UserRole.AsString.ADMIN})
|
||||
public List<OrderDTO> findFiltredOrder(@PathVariable String login) {
|
||||
return orderService.findFiltredOrder(login);
|
||||
}
|
||||
}
|
81
src/main/java/ip/labwork/shop/controller/OrderDTO.java
Normal file
81
src/main/java/ip/labwork/shop/controller/OrderDTO.java
Normal file
@ -0,0 +1,81 @@
|
||||
package ip.labwork.shop.controller;
|
||||
|
||||
import ip.labwork.shop.model.Order;
|
||||
import ip.labwork.shop.model.OrderStatus;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public class OrderDTO {
|
||||
private long id;
|
||||
private Date date = new Date();
|
||||
private int price;
|
||||
private long user_id;
|
||||
private String user;
|
||||
private OrderStatus status = OrderStatus.Неизвестен;
|
||||
private List<ProductDTO> productDTOList;
|
||||
|
||||
public OrderDTO(Order order) {
|
||||
this.id = order.getId();
|
||||
this.date = order.getDate();
|
||||
this.price = order.getPrice();
|
||||
this.productDTOList = order.getProducts().stream()
|
||||
.filter(x -> Objects.equals(x.getId().getOrderId(), order.getId()))
|
||||
.map(y -> new ProductDTO(y.getProduct(), y.getCount()))
|
||||
.toList();
|
||||
this.status = Objects.equals(order.getStatus().toString(), "") ? OrderStatus.Неизвестен : order.getStatus();
|
||||
this.user_id = order.getUser_id() == null ? -1 : order.getUser_id();
|
||||
}
|
||||
|
||||
public OrderDTO() {
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public int getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(int price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public OrderStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(OrderStatus status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public long getUser_id() {
|
||||
return user_id;
|
||||
}
|
||||
|
||||
public void setUser_id(long user_id) {
|
||||
this.user_id = user_id;
|
||||
}
|
||||
|
||||
public String getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(String user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public List<ProductDTO> getProductDTOList() {
|
||||
return productDTOList;
|
||||
}
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
package ip.labwork.shop.controller;
|
||||
|
||||
import ip.labwork.shop.service.ProductService;
|
||||
import ip.labwork.user.model.UserRole;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.security.access.annotation.Secured;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/product")
|
||||
public class ProductController {
|
||||
private final ProductService productService;
|
||||
|
||||
public ProductController(ProductService productService) {
|
||||
this.productService = productService;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public ProductDTO createProduct(@RequestBody @Valid ProductDTO productDTO) {
|
||||
return productService.create(productDTO);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public ProductDTO updateProduct(@PathVariable Long id, @RequestBody @Valid ProductDTO productDTO) {
|
||||
return productService.updateProduct(id, productDTO);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public ProductDTO removeProduct(@PathVariable Long id) {
|
||||
return productService.deleteProduct(id);
|
||||
}
|
||||
|
||||
@DeleteMapping
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public void removeAllProduct() {
|
||||
productService.deleteAllProduct();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public ProductDTO findProduct(@PathVariable Long id) {
|
||||
return new ProductDTO(productService.findProduct(id));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@Secured({UserRole.AsString.ADMIN})
|
||||
public List<ProductDTO> findAllProduct() {
|
||||
return productService.findAllProduct();
|
||||
}
|
||||
}
|
76
src/main/java/ip/labwork/shop/controller/ProductDTO.java
Normal file
76
src/main/java/ip/labwork/shop/controller/ProductDTO.java
Normal file
@ -0,0 +1,76 @@
|
||||
package ip.labwork.shop.controller;
|
||||
|
||||
import ip.labwork.shop.model.Product;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public class ProductDTO {
|
||||
private long id;
|
||||
private String name;
|
||||
private int price;
|
||||
private List<ComponentDTO> componentDTOList;
|
||||
private List<OrderDTO> orderDTOList;
|
||||
private String image;
|
||||
private int count;
|
||||
public ProductDTO(Product product) {
|
||||
this.id = product.getId();
|
||||
this.name = product.getProductName();
|
||||
this.price = product.getPrice();
|
||||
this.image = product.getImage() == null? "" : new String(product.getImage());
|
||||
this.componentDTOList = product.getComponents().stream()
|
||||
.filter(x -> Objects.equals(x.getId().getProductId(), product.getId()))
|
||||
.map(y -> new ComponentDTO(y.getComponent(), y.getCount()))
|
||||
.toList();
|
||||
this.orderDTOList = product.getOrders() == null ? null : product.getOrders().stream().filter(x -> Objects.equals(x.getId().getProductId(), product.getId())).map(x -> new OrderDTO(x.getOrder())).toList();
|
||||
}
|
||||
public ProductDTO(Product product, int count) {
|
||||
this.id = product.getId();
|
||||
this.name = product.getProductName();
|
||||
this.price = product.getPrice();
|
||||
this.image = product.getImage() == null? "" : new String(product.getImage());
|
||||
this.componentDTOList = product.getComponents().stream()
|
||||
.filter(x -> Objects.equals(x.getId().getProductId(), product.getId()))
|
||||
.map(y -> new ComponentDTO(y.getComponent(), y.getCount()))
|
||||
.toList();
|
||||
this.count = count;
|
||||
}
|
||||
public ProductDTO() {
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public int getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
public void setCount(int count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public List<ComponentDTO> getComponentDTOList() {
|
||||
return componentDTOList;
|
||||
}
|
||||
|
||||
public String getImage() {
|
||||
return image;
|
||||
}
|
||||
|
||||
public void setImage(String image) {
|
||||
this.image = image;
|
||||
}
|
||||
|
||||
public List<OrderDTO> getOrderDTOList() {
|
||||
return orderDTOList;
|
||||
}
|
||||
}
|
102
src/main/java/ip/labwork/shop/model/Component.java
Normal file
102
src/main/java/ip/labwork/shop/model/Component.java
Normal file
@ -0,0 +1,102 @@
|
||||
package ip.labwork.shop.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
@Table(name = "components")
|
||||
public class Component {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
@NotBlank(message = "ComponentName can't be null or empty")
|
||||
@Column(name = "name")
|
||||
private String componentName;
|
||||
@NotNull(message= "Price may not be empty")
|
||||
@Column(name = "price")
|
||||
private Integer price;
|
||||
|
||||
@OneToMany(mappedBy = "component", cascade =
|
||||
{
|
||||
CascadeType.REMOVE,
|
||||
CascadeType.PERSIST
|
||||
}, orphanRemoval = true, fetch = FetchType.EAGER)
|
||||
private List<ProductComponents> products;
|
||||
|
||||
public Component() {
|
||||
}
|
||||
|
||||
public Component(String componentName, Integer price) {
|
||||
this.componentName = componentName;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getComponentName() {
|
||||
return componentName;
|
||||
}
|
||||
|
||||
public void setComponentName(String componentName) {
|
||||
this.componentName = componentName;
|
||||
}
|
||||
|
||||
public Integer getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(Integer price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public List<ProductComponents> getProducts() {
|
||||
return products;
|
||||
}
|
||||
|
||||
public void setProducts(List<ProductComponents> products) {
|
||||
this.products = products;
|
||||
}
|
||||
|
||||
public void addProduct(ProductComponents productComponents) {
|
||||
if (products == null) {
|
||||
products = new ArrayList<>();
|
||||
}
|
||||
if (!products.contains(productComponents))
|
||||
this.products.add(productComponents);
|
||||
}
|
||||
|
||||
public void removeProduct(ProductComponents productComponents) {
|
||||
if (products.contains(productComponents))
|
||||
this.products.remove(productComponents);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Component component = (Component) o;
|
||||
return Objects.equals(id, component.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Component{" +
|
||||
"id=" + id +
|
||||
", componentName='" + componentName + '\'' +
|
||||
", price='" + price + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
111
src/main/java/ip/labwork/shop/model/Order.java
Normal file
111
src/main/java/ip/labwork/shop/model/Order.java
Normal file
@ -0,0 +1,111 @@
|
||||
package ip.labwork.shop.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
@Table(name = "orders")
|
||||
public class Order {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
//@NotNull(message = "Date can't be null or empty")
|
||||
@Column(name = "date")
|
||||
private Date date;
|
||||
@NotNull(message = "Price can't be null or empty")
|
||||
@Column(name = "price")
|
||||
private Integer price;
|
||||
private Long user_id;
|
||||
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
|
||||
private List<OrderProducts> products;
|
||||
private OrderStatus status;
|
||||
|
||||
public Order() {
|
||||
|
||||
}
|
||||
|
||||
public Order(Date date, Integer price, OrderStatus status, Long user_id) {
|
||||
this.date = date;
|
||||
this.price = price;
|
||||
this.user_id = user_id;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public Integer getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(Integer price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public List<OrderProducts> getProducts() {
|
||||
return products;
|
||||
}
|
||||
|
||||
public void setProducts(List<OrderProducts> products) {
|
||||
this.products = products;
|
||||
}
|
||||
|
||||
public void addProduct(OrderProducts orderProducts) {
|
||||
if (products == null) {
|
||||
this.products = new ArrayList<>();
|
||||
}
|
||||
if (!products.contains(orderProducts))
|
||||
this.products.add(orderProducts);
|
||||
}
|
||||
|
||||
public void removeProducts(OrderProducts orderProducts) {
|
||||
if (products.contains(orderProducts))
|
||||
this.products.remove(orderProducts);
|
||||
}
|
||||
|
||||
public OrderStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(OrderStatus status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Long getUser_id() {
|
||||
return user_id;
|
||||
}
|
||||
|
||||
public void setUser_id(Long user_id) {
|
||||
this.user_id = user_id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof Order order)) return false;
|
||||
return Objects.equals(getId(), order.getId()) && Objects.equals(getDate(), order.getDate()) && Objects.equals(getPrice(), order.getPrice()) && Objects.equals(getUser_id(), order.getUser_id()) && Objects.equals(getProducts(), order.getProducts()) && getStatus() == order.getStatus();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(getId(), getDate(), getPrice());
|
||||
}
|
||||
}
|
72
src/main/java/ip/labwork/shop/model/OrderProducts.java
Normal file
72
src/main/java/ip/labwork/shop/model/OrderProducts.java
Normal file
@ -0,0 +1,72 @@
|
||||
package ip.labwork.shop.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
@Entity
|
||||
@Table(name = "order_product")
|
||||
public class OrderProducts {
|
||||
@EmbeddedId
|
||||
private OrderProductsKey id = new OrderProductsKey();
|
||||
@ManyToOne(cascade = CascadeType.MERGE)
|
||||
@MapsId("productId")
|
||||
@JoinColumn(name = "product_id")
|
||||
private Product product;
|
||||
@ManyToOne(cascade = CascadeType.MERGE)
|
||||
@MapsId("orderId")
|
||||
@JoinColumn(name = "order_id")
|
||||
@JsonIgnore
|
||||
private Order order;
|
||||
@NotNull(message = "Count can't be null or empty")
|
||||
@Column(name = "count")
|
||||
private Integer count;
|
||||
|
||||
public OrderProducts() {
|
||||
}
|
||||
|
||||
public OrderProducts(Order order, Product product, Integer count) {
|
||||
this.order = order;
|
||||
this.id.setOrderId(order.getId());
|
||||
this.id.setProductId(product.getId());
|
||||
this.product = product;
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
public OrderProductsKey getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(OrderProductsKey id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Order getOrder() {
|
||||
return order;
|
||||
}
|
||||
|
||||
public void setOrder(Order order) {
|
||||
this.order = order;
|
||||
}
|
||||
|
||||
public Product getProduct() {
|
||||
return product;
|
||||
}
|
||||
|
||||
public void setProduct(Product product) {
|
||||
this.product = product;
|
||||
}
|
||||
|
||||
public Integer getCount() {
|
||||
return count;
|
||||
}
|
||||
public void remove(){
|
||||
order.getProducts().remove(this);
|
||||
order = null;
|
||||
product.getOrders().remove(this);
|
||||
product = null;
|
||||
}
|
||||
public void setCount(Integer count) {
|
||||
this.count = count;
|
||||
}
|
||||
}
|
48
src/main/java/ip/labwork/shop/model/OrderProductsKey.java
Normal file
48
src/main/java/ip/labwork/shop/model/OrderProductsKey.java
Normal file
@ -0,0 +1,48 @@
|
||||
package ip.labwork.shop.model;
|
||||
|
||||
import jakarta.persistence.Embeddable;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
@Embeddable
|
||||
public class OrderProductsKey implements Serializable {
|
||||
private Long productId;
|
||||
private Long orderId;
|
||||
|
||||
public OrderProductsKey() {
|
||||
}
|
||||
|
||||
public OrderProductsKey(Long productId, Long orderId) {
|
||||
this.productId = productId;
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public Long getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
public void setProductId(Long productId) {
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
public Long getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public void setOrderId(Long orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof OrderProductsKey that)) return false;
|
||||
return Objects.equals(getProductId(), that.getProductId()) && Objects.equals(getOrderId(), that.getOrderId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(getProductId(), getOrderId());
|
||||
}
|
||||
}
|
5
src/main/java/ip/labwork/shop/model/OrderStatus.java
Normal file
5
src/main/java/ip/labwork/shop/model/OrderStatus.java
Normal file
@ -0,0 +1,5 @@
|
||||
package ip.labwork.shop.model;
|
||||
|
||||
public enum OrderStatus {
|
||||
Неизвестен, Готов
|
||||
}
|
149
src/main/java/ip/labwork/shop/model/Product.java
Normal file
149
src/main/java/ip/labwork/shop/model/Product.java
Normal file
@ -0,0 +1,149 @@
|
||||
package ip.labwork.shop.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
@Table(name = "products")
|
||||
public class Product {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
@NotBlank(message = "ProductName can't be null or empty")
|
||||
@Column(name = "name")
|
||||
private String productName;
|
||||
@NotNull(message = "Price can't be null or empty")
|
||||
@Column(name = "price")
|
||||
private Integer price;
|
||||
@Lob
|
||||
@Column(name = "image")
|
||||
private byte[] image;
|
||||
@OneToMany(mappedBy = "product", cascade =
|
||||
{
|
||||
CascadeType.REMOVE,
|
||||
CascadeType.MERGE,
|
||||
CascadeType.PERSIST
|
||||
}, orphanRemoval = true, fetch = FetchType.EAGER)
|
||||
private List<ProductComponents> components;
|
||||
|
||||
@OneToMany(mappedBy = "product", cascade =
|
||||
{
|
||||
CascadeType.REMOVE,
|
||||
CascadeType.PERSIST
|
||||
}, orphanRemoval = true, fetch = FetchType.EAGER)
|
||||
private List<OrderProducts> orders;
|
||||
|
||||
|
||||
public Product() {
|
||||
|
||||
}
|
||||
|
||||
public Product(String productName, Integer price, byte[] image) {
|
||||
this.productName = productName;
|
||||
this.price = price;
|
||||
this.image = image;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getProductName() {
|
||||
return productName;
|
||||
}
|
||||
|
||||
public void setProductName(String productName) {
|
||||
this.productName = productName;
|
||||
}
|
||||
|
||||
public Integer getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(Integer price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public List<ProductComponents> getComponents() {
|
||||
return components;
|
||||
}
|
||||
|
||||
public byte[] getImage() {
|
||||
return image;
|
||||
}
|
||||
|
||||
public void setImage(byte[] image) {
|
||||
this.image = image;
|
||||
}
|
||||
|
||||
public void setComponents(List<ProductComponents> components) {
|
||||
this.components = components;
|
||||
}
|
||||
|
||||
public void update(Product product){
|
||||
this.productName = product.productName;
|
||||
this.price = product.price;
|
||||
this.components = product.getComponents();
|
||||
}
|
||||
|
||||
public void addComponent(ProductComponents productComponents){
|
||||
if (components == null){
|
||||
this.components = new ArrayList<>();
|
||||
}
|
||||
if (!components.contains(productComponents))
|
||||
this.components.add(productComponents);
|
||||
}
|
||||
public void removeComponent(ProductComponents productComponents){
|
||||
if (components.contains(productComponents))
|
||||
this.components.remove(productComponents);
|
||||
}
|
||||
|
||||
public List<OrderProducts> getOrders() {
|
||||
return orders;
|
||||
}
|
||||
|
||||
public void setOrders(List<OrderProducts> orders) {
|
||||
this.orders = orders;
|
||||
}
|
||||
public void addOrder(OrderProducts orderProducts){
|
||||
if (orders == null){
|
||||
orders = new ArrayList<>();
|
||||
}
|
||||
if (!orders.contains(orderProducts))
|
||||
this.orders.add(orderProducts);
|
||||
}
|
||||
public void removeOrder(OrderProducts orderProducts){
|
||||
if (orders.contains(orderProducts))
|
||||
this.orders.remove(orderProducts);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Product product = (Product) o;
|
||||
return Objects.equals(id, product.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Product{" +
|
||||
"id=" + id +
|
||||
", productName='" + productName + '\'' +
|
||||
", price='" + price + '\'' +
|
||||
'}';
|
||||
}
|
||||
|
||||
}
|
82
src/main/java/ip/labwork/shop/model/ProductComponents.java
Normal file
82
src/main/java/ip/labwork/shop/model/ProductComponents.java
Normal file
@ -0,0 +1,82 @@
|
||||
package ip.labwork.shop.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
@Entity
|
||||
@Table(name = "product_component")
|
||||
public class ProductComponents {
|
||||
@EmbeddedId
|
||||
private ProductComponentsKey id = new ProductComponentsKey();
|
||||
@ManyToOne(cascade = CascadeType.MERGE)
|
||||
@MapsId("componentId")
|
||||
@JoinColumn(name = "component_id")
|
||||
private Component component;
|
||||
@ManyToOne(cascade = CascadeType.MERGE)
|
||||
@MapsId("productId")
|
||||
@JoinColumn(name = "product_id")
|
||||
@JsonIgnore
|
||||
private Product product;
|
||||
@NotNull(message = "Count can't be null or empty")
|
||||
@Column(name = "count")
|
||||
private Integer count;
|
||||
|
||||
public ProductComponents() {
|
||||
}
|
||||
|
||||
public ProductComponents(Component component, Product product, Integer count) {
|
||||
this.component = component;
|
||||
this.id.setComponentId(component.getId());
|
||||
this.id.setProductId(product.getId());
|
||||
this.product = product;
|
||||
this.count = count;
|
||||
}
|
||||
public ProductComponentsKey getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(ProductComponentsKey id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Component getComponent() {
|
||||
return component;
|
||||
}
|
||||
|
||||
public void setComponent(Component component) {
|
||||
this.component = component;
|
||||
}
|
||||
|
||||
public Product getProduct() {
|
||||
return product;
|
||||
}
|
||||
|
||||
public void setProduct(Product product) {
|
||||
this.product = product;
|
||||
}
|
||||
|
||||
public Integer getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
public void setCount(Integer count) {
|
||||
this.count = count;
|
||||
}
|
||||
public void remove() {
|
||||
product.getComponents().remove(this);
|
||||
product = null;
|
||||
component.getProducts().remove(this);
|
||||
component = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ProductComponents{" +
|
||||
"id=" + id +
|
||||
", component=" + component +
|
||||
", product=" + product +
|
||||
", count=" + count +
|
||||
'}';
|
||||
}
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package ip.labwork.shop.model;
|
||||
|
||||
import jakarta.persistence.Embeddable;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
@Embeddable
|
||||
public class ProductComponentsKey implements Serializable {
|
||||
private Long productId;
|
||||
private Long componentId;
|
||||
|
||||
public ProductComponentsKey() {
|
||||
}
|
||||
|
||||
public ProductComponentsKey(Long productId, Long componentId) {
|
||||
this.productId = productId;
|
||||
this.componentId = componentId;
|
||||
}
|
||||
|
||||
public Long getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
public void setProductId(Long productId) {
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
public Long getComponentId() {
|
||||
return componentId;
|
||||
}
|
||||
|
||||
public void setComponentId(Long componentId) {
|
||||
this.componentId = componentId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof ProductComponentsKey that)) return false;
|
||||
return Objects.equals(getProductId(), that.getProductId()) && Objects.equals(getComponentId(), that.getComponentId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(getProductId(), getComponentId());
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package ip.labwork.shop.repository;
|
||||
|
||||
import ip.labwork.shop.model.Component;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface ComponentRepository extends JpaRepository<Component, Long> {
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package ip.labwork.shop.repository;
|
||||
|
||||
import ip.labwork.shop.model.Order;
|
||||
import ip.labwork.shop.model.OrderProducts;
|
||||
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 OrderRepository extends JpaRepository<Order, Long> {
|
||||
@Query("Select os from OrderProducts os where os.order.id = :orderId")
|
||||
List<OrderProducts> getOrderProduct(@Param("orderId") Long orderId);
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package ip.labwork.shop.repository;
|
||||
|
||||
import ip.labwork.shop.model.Product;
|
||||
import ip.labwork.shop.model.ProductComponents;
|
||||
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 ProductRepository extends JpaRepository<Product, Long> {
|
||||
@Query("Select os from ProductComponents os where os.product.id = :productId")
|
||||
List<ProductComponents> getProductComponent(@Param("productId") Long orderId);
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package ip.labwork.shop.service;
|
||||
|
||||
public class ComponentNotFoundException extends RuntimeException {
|
||||
public ComponentNotFoundException(Long id) {
|
||||
super(String.format("Component with id [%s] is not found", id));
|
||||
}
|
||||
}
|
65
src/main/java/ip/labwork/shop/service/ComponentService.java
Normal file
65
src/main/java/ip/labwork/shop/service/ComponentService.java
Normal file
@ -0,0 +1,65 @@
|
||||
package ip.labwork.shop.service;
|
||||
|
||||
import ip.labwork.shop.controller.ComponentDTO;
|
||||
import ip.labwork.shop.model.Component;
|
||||
import ip.labwork.shop.model.ProductComponents;
|
||||
import ip.labwork.shop.repository.ComponentRepository;
|
||||
import ip.labwork.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 ComponentService {
|
||||
|
||||
private final ComponentRepository componentRepository;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
|
||||
public ComponentService(ComponentRepository componentRepository,
|
||||
ValidatorUtil validatorUtil) {
|
||||
this.componentRepository = componentRepository;
|
||||
this.validatorUtil = validatorUtil;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ComponentDTO create(ComponentDTO componentDTO) {
|
||||
final Component component = new Component(componentDTO.getComponentName(), componentDTO.getPrice());
|
||||
validatorUtil.validate(component);
|
||||
return new ComponentDTO(componentRepository.save(component));
|
||||
}
|
||||
@Transactional(readOnly = true)
|
||||
public Component findComponent(Long id) {
|
||||
final Optional<Component> component = componentRepository.findById(id);
|
||||
return component.orElseThrow(() -> new ComponentNotFoundException(id));
|
||||
}
|
||||
@Transactional(readOnly = true)
|
||||
public List<ComponentDTO> findAllComponent() {
|
||||
return componentRepository.findAll().stream().map(x -> new ComponentDTO(x)).toList();
|
||||
}
|
||||
@Transactional
|
||||
public ComponentDTO updateComponent(Long id, ComponentDTO component) {
|
||||
final Component currentComponent = findComponent(id);
|
||||
currentComponent.setComponentName(component.getComponentName());
|
||||
currentComponent.setPrice(component.getPrice());
|
||||
validatorUtil.validate(currentComponent);
|
||||
return new ComponentDTO(componentRepository.save(currentComponent));
|
||||
}
|
||||
@Transactional
|
||||
public ComponentDTO deleteComponent(Long id) {
|
||||
final Component currentComponent = findComponent(id);
|
||||
int size = currentComponent.getProducts().size();
|
||||
for (int i = 0; i < size; i++) {
|
||||
ProductComponents productComponents = currentComponent.getProducts().get(0);
|
||||
productComponents.getComponent().removeProduct(productComponents);
|
||||
productComponents.getProduct().removeComponent(productComponents);
|
||||
}
|
||||
componentRepository.delete(currentComponent);
|
||||
return new ComponentDTO(currentComponent);
|
||||
}
|
||||
@Transactional
|
||||
public void deleteAllComponent() {
|
||||
componentRepository.deleteAll();
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package ip.labwork.shop.service;
|
||||
|
||||
public class OrderNotFoundException extends RuntimeException {
|
||||
public OrderNotFoundException(Long id) {
|
||||
super(String.format("Order with id [%s] is not found", id));
|
||||
}
|
||||
}
|
116
src/main/java/ip/labwork/shop/service/OrderService.java
Normal file
116
src/main/java/ip/labwork/shop/service/OrderService.java
Normal file
@ -0,0 +1,116 @@
|
||||
package ip.labwork.shop.service;
|
||||
|
||||
import ip.labwork.shop.controller.OrderDTO;
|
||||
import ip.labwork.shop.model.Order;
|
||||
import ip.labwork.shop.model.OrderProducts;
|
||||
import ip.labwork.shop.model.Product;
|
||||
import ip.labwork.shop.repository.OrderRepository;
|
||||
import ip.labwork.shop.repository.ProductRepository;
|
||||
import ip.labwork.user.service.UserService;
|
||||
import ip.labwork.util.validation.ValidatorUtil;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
public class OrderService {
|
||||
private final OrderRepository orderRepository;
|
||||
private final ProductRepository productRepository;
|
||||
private final UserService userService;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
|
||||
public OrderService(OrderRepository orderRepository,
|
||||
ValidatorUtil validatorUtil, ProductRepository productRepository, UserService userService) {
|
||||
this.orderRepository = orderRepository;
|
||||
this.validatorUtil = validatorUtil;
|
||||
this.productRepository = productRepository;
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public OrderDTO create(OrderDTO orderDTO) {
|
||||
int price = 0;
|
||||
for (int i = 0; i < orderDTO.getProductDTOList().size(); i++) {
|
||||
price += orderDTO.getProductDTOList().get(i).getPrice() * orderDTO.getProductDTOList().get(i).getCount();
|
||||
}
|
||||
final Order order = new Order(new Date(), price, orderDTO.getStatus(), userService.findByLogin(orderDTO.getUser()).getId());
|
||||
validatorUtil.validate(order);
|
||||
orderRepository.save(order);
|
||||
for (int i = 0; i < orderDTO.getProductDTOList().size(); i++) {
|
||||
final OrderProducts orderProducts = new OrderProducts(order, productRepository.findById(orderDTO.getProductDTOList().get(i).getId()).orElseThrow(() -> new ProductNotFoundException(1L)), orderDTO.getProductDTOList().get(i).getCount());
|
||||
order.addProduct(orderProducts);
|
||||
}
|
||||
orderRepository.save(order);
|
||||
return new OrderDTO(findOrder(order.getId()));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Order findOrder(Long id) {
|
||||
final Optional<Order> order = orderRepository.findById(id);
|
||||
return order.orElseThrow(() -> new OrderNotFoundException(id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<OrderDTO> findAllOrder() {
|
||||
return orderRepository.findAll().stream().map(x -> new OrderDTO(x)).toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<OrderDTO> findFiltredOrder(String login) {
|
||||
return orderRepository.findAll().stream().filter(x -> Objects.equals(x.getUser_id(), userService.findByLogin(login).getId())).map(x -> new OrderDTO(x)).toList();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public OrderDTO update(Long id, OrderDTO orderDTO) {
|
||||
final Order currentOrder = findOrder(id);
|
||||
currentOrder.setDate(orderDTO.getDate());
|
||||
currentOrder.setPrice(orderDTO.getPrice());
|
||||
validatorUtil.validate(currentOrder);
|
||||
orderRepository.save(currentOrder);
|
||||
List<OrderProducts> orderProductsList = orderRepository.getOrderProduct(id);
|
||||
List<Long> product_id = new ArrayList<>(orderProductsList.stream().map(p -> p.getId().getProductId()).toList());
|
||||
List<Product> newProducts = productRepository.findAllById(orderDTO.getProductDTOList().stream().map(x -> x.getId()).toList());
|
||||
for (int i = 0; i < newProducts.size(); i++) {
|
||||
final Long currentId = newProducts.get(i).getId();
|
||||
if (product_id.contains(currentId)) {
|
||||
final OrderProducts orderProducts = orderProductsList.stream().filter(x -> x.getId().getProductId().equals(currentId)).findFirst().get();
|
||||
orderProductsList.remove(orderProducts);
|
||||
currentOrder.removeProducts(orderProducts);
|
||||
currentOrder.addProduct(new OrderProducts(currentOrder, newProducts.get(i), orderDTO.getProductDTOList().stream().filter(x -> x.getId() == currentId).toList().get(0).getCount()));
|
||||
int finalI = i;
|
||||
product_id = product_id.stream().filter(x -> !Objects.equals(x, newProducts.get(finalI).getId())).toList();
|
||||
orderProducts.setCount(orderDTO.getProductDTOList().stream().filter(x -> x.getId() == currentId).toList().get(0).getCount());
|
||||
orderRepository.saveAndFlush(currentOrder);
|
||||
} else {
|
||||
final OrderProducts orderProducts = new OrderProducts(currentOrder, newProducts.get(i), orderDTO.getProductDTOList().stream().filter(x -> x.getId() == currentId).toList().get(0).getCount());
|
||||
currentOrder.addProduct(orderProducts);
|
||||
orderRepository.saveAndFlush(currentOrder);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < orderProductsList.size(); i++) {
|
||||
orderProductsList.get(i).getProduct().removeOrder(orderProductsList.get(i));
|
||||
orderProductsList.get(i).getOrder().removeProducts(orderProductsList.get(i));
|
||||
}
|
||||
orderRepository.saveAndFlush(currentOrder);
|
||||
return new OrderDTO(currentOrder);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public OrderDTO deleteOrder(Long id) {
|
||||
final Order currentOrder = findOrder(id);
|
||||
int size = currentOrder.getProducts().size();
|
||||
for (int i = 0; i < size; i++) {
|
||||
OrderProducts temp = currentOrder.getProducts().get(0);
|
||||
temp.getProduct().removeOrder(temp);
|
||||
temp.getOrder().removeProducts(temp);
|
||||
}
|
||||
orderRepository.delete(currentOrder);
|
||||
return new OrderDTO(currentOrder);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAllOrder() {
|
||||
orderRepository.deleteAll();
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package ip.labwork.shop.service;
|
||||
|
||||
public class ProductNotFoundException extends RuntimeException {
|
||||
public ProductNotFoundException(Long id) {
|
||||
super(String.format("Product with id [%s] is not found", id));
|
||||
}
|
||||
}
|
115
src/main/java/ip/labwork/shop/service/ProductService.java
Normal file
115
src/main/java/ip/labwork/shop/service/ProductService.java
Normal file
@ -0,0 +1,115 @@
|
||||
package ip.labwork.shop.service;
|
||||
|
||||
import ip.labwork.shop.controller.ProductDTO;
|
||||
import ip.labwork.shop.model.Component;
|
||||
import ip.labwork.shop.model.OrderProducts;
|
||||
import ip.labwork.shop.model.Product;
|
||||
import ip.labwork.shop.model.ProductComponents;
|
||||
import ip.labwork.shop.repository.*;
|
||||
import ip.labwork.util.validation.ValidatorUtil;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
public class ProductService {
|
||||
private final ProductRepository productRepository;
|
||||
private final ComponentRepository componentRepository;
|
||||
private final ValidatorUtil validatorUtil;
|
||||
|
||||
public ProductService(ProductRepository productRepository,
|
||||
ValidatorUtil validatorUtil, ComponentRepository componentRepository) {
|
||||
this.productRepository = productRepository;
|
||||
this.validatorUtil = validatorUtil;
|
||||
this.componentRepository = componentRepository;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ProductDTO create(ProductDTO productDTO) {
|
||||
final Product product = new Product(productDTO.getName(), productDTO.getPrice(),productDTO.getImage().getBytes());
|
||||
validatorUtil.validate(product);
|
||||
productRepository.save(product);
|
||||
for (int i = 0; i < productDTO.getComponentDTOList().size(); i++) {
|
||||
final ProductComponents productComponents = new ProductComponents(componentRepository.findById(productDTO.getComponentDTOList().get(i).getId()).orElseThrow(() -> new ComponentNotFoundException(1L)), product, productDTO.getComponentDTOList().get(i).getCount());
|
||||
product.addComponent(productComponents);
|
||||
}
|
||||
productRepository.save(product);
|
||||
return new ProductDTO(findProduct(product.getId()));
|
||||
}
|
||||
@Transactional(readOnly = true)
|
||||
public Product findProduct(Long id) {
|
||||
final Optional<Product> product = productRepository.findById(id);
|
||||
return product.orElseThrow(() -> new ProductNotFoundException(id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<ProductDTO> findAllProduct() {
|
||||
return productRepository.findAll().stream().map(x -> new ProductDTO(x)).toList();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ProductDTO updateProduct(Long id, ProductDTO product) {
|
||||
final Product currentProduct = findProduct(id);
|
||||
currentProduct.setProductName(product.getName());
|
||||
currentProduct.setPrice(product.getPrice());
|
||||
currentProduct.setImage(product.getImage().getBytes());
|
||||
validatorUtil.validate(currentProduct);
|
||||
productRepository.save(currentProduct);
|
||||
List<ProductComponents> productComponentsList = productRepository.getProductComponent(id);
|
||||
List<Long> component_id = new ArrayList<>(productComponentsList.stream().map(p -> p.getId().getComponentId()).toList());
|
||||
List<Component> newComponents = componentRepository.findAllById(product.getComponentDTOList().stream().map(x -> x.getId()).toList());
|
||||
for (int i = 0; i < newComponents.size(); i++) {
|
||||
final Long currentId = newComponents.get(i).getId();
|
||||
if (component_id.contains(currentId)) {
|
||||
final ProductComponents productComponents = productComponentsList.stream().filter(x -> x.getId().getComponentId().equals(currentId)).findFirst().get();
|
||||
productComponentsList.remove(productComponents);
|
||||
currentProduct.removeComponent(productComponents);
|
||||
currentProduct.addComponent(new ProductComponents(newComponents.get(i) , currentProduct, product.getComponentDTOList().stream().filter(x -> x.getId() == currentId).toList().get(0).getCount()));
|
||||
int finalI = i;
|
||||
component_id = component_id.stream().filter(x -> !Objects.equals(x, newComponents.get(finalI).getId())).toList();
|
||||
productComponents.setCount(product.getComponentDTOList().stream().filter(x -> x.getId() == currentId).toList().get(0).getCount());
|
||||
productRepository.saveAndFlush(currentProduct);
|
||||
}
|
||||
else {
|
||||
final ProductComponents productComponents = new ProductComponents(newComponents.get(i), currentProduct, product.getComponentDTOList().stream().filter(x -> x.getId() == currentId).toList().get(0).getCount());
|
||||
currentProduct.addComponent(productComponents);
|
||||
productRepository.saveAndFlush(currentProduct);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < productComponentsList.size(); i++) {
|
||||
productComponentsList.get(i).getComponent().removeProduct(productComponentsList.get(i));
|
||||
productComponentsList.get(i).getProduct().removeComponent(productComponentsList.get(i));
|
||||
}
|
||||
productRepository.saveAndFlush(currentProduct);
|
||||
return new ProductDTO(currentProduct);
|
||||
}
|
||||
@Transactional
|
||||
public ProductDTO deleteProduct(Long id) {
|
||||
final Product currentProduct = findProduct(id);
|
||||
int size = currentProduct.getComponents().size();
|
||||
for (int i = 0; i < size; i++) {
|
||||
ProductComponents temp = currentProduct.getComponents().get(0);
|
||||
temp.getComponent().removeProduct(temp);
|
||||
temp.getProduct().removeComponent(temp);
|
||||
}
|
||||
int ordSize = currentProduct.getOrders().size();
|
||||
for (int i = 0; i < ordSize; i++){
|
||||
OrderProducts orderProducts = currentProduct.getOrders().get(0);
|
||||
orderProducts.getProduct().removeOrder(orderProducts);
|
||||
orderProducts.getOrder().removeProducts(orderProducts);
|
||||
}
|
||||
productRepository.delete(currentProduct);
|
||||
return new ProductDTO(currentProduct);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAllProduct() {
|
||||
productRepository.deleteAll();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<Product> findFiltredProducts(Long[] arr) {
|
||||
return productRepository.findAllById(Arrays.stream(arr).toList());
|
||||
}
|
||||
}
|
17
src/main/java/ip/labwork/test/controller/TestController.java
Normal file
17
src/main/java/ip/labwork/test/controller/TestController.java
Normal file
@ -0,0 +1,17 @@
|
||||
package ip.labwork.test.controller;
|
||||
|
||||
import ip.labwork.test.model.TestDto;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/test")
|
||||
public class TestController {
|
||||
@PostMapping
|
||||
public TestDto testValidation(@RequestBody @Valid TestDto testDto) {
|
||||
return testDto;
|
||||
}
|
||||
}
|
31
src/main/java/ip/labwork/test/model/TestDto.java
Normal file
31
src/main/java/ip/labwork/test/model/TestDto.java
Normal file
@ -0,0 +1,31 @@
|
||||
package ip.labwork.test.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class TestDto {
|
||||
@NotNull(message = "Id can't be null")
|
||||
private Long id;
|
||||
@NotBlank(message = "Name can't be null or empty")
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public String getData() {
|
||||
return String.format("%s %s", id, name);
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public String getAnotherData() {
|
||||
return "Test";
|
||||
}
|
||||
}
|
64
src/main/java/ip/labwork/user/controller/UserController.java
Normal file
64
src/main/java/ip/labwork/user/controller/UserController.java
Normal file
@ -0,0 +1,64 @@
|
||||
package ip.labwork.user.controller;
|
||||
|
||||
import ip.labwork.user.model.User;
|
||||
import ip.labwork.user.model.UserRole;
|
||||
import ip.labwork.user.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 = "5") 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);
|
||||
}
|
||||
}
|
44
src/main/java/ip/labwork/user/controller/UserDto.java
Normal file
44
src/main/java/ip/labwork/user/controller/UserDto.java
Normal file
@ -0,0 +1,44 @@
|
||||
package ip.labwork.user.controller;
|
||||
|
||||
import ip.labwork.user.model.User;
|
||||
import ip.labwork.user.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 String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public String getPasswordConfirm() {
|
||||
return passwordConfirm;
|
||||
}
|
||||
|
||||
public UserRole getRole() {
|
||||
return role;
|
||||
}
|
||||
}
|
34
src/main/java/ip/labwork/user/controller/UserInfoDto.java
Normal file
34
src/main/java/ip/labwork/user/controller/UserInfoDto.java
Normal file
@ -0,0 +1,34 @@
|
||||
package ip.labwork.user.controller;
|
||||
|
||||
import ip.labwork.user.model.UserRole;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
|
||||
public class UserInfoDto {
|
||||
@NotEmpty
|
||||
private String token;
|
||||
@NotEmpty
|
||||
private String login;
|
||||
@NotEmpty
|
||||
private UserRole role;
|
||||
|
||||
public UserInfoDto(String token, String login, UserRole role) {
|
||||
this.token = token;
|
||||
this.login = login;
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public UserInfoDto() {
|
||||
}
|
||||
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public UserRole getRole() {
|
||||
return role;
|
||||
}
|
||||
}
|
29
src/main/java/ip/labwork/user/controller/UsersPageDTO.java
Normal file
29
src/main/java/ip/labwork/user/controller/UsersPageDTO.java
Normal file
@ -0,0 +1,29 @@
|
||||
package ip.labwork.user.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;
|
||||
}
|
||||
}
|
83
src/main/java/ip/labwork/user/model/User.java
Normal file
83
src/main/java/ip/labwork/user/model/User.java
Normal file
@ -0,0 +1,83 @@
|
||||
package ip.labwork.user.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class User {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
@Column(nullable = false, unique = true, length = 64)
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 64)
|
||||
private String login;
|
||||
@Column(nullable = false, length = 64)
|
||||
@NotBlank
|
||||
@Size(min = 6, max = 64)
|
||||
private String password;
|
||||
private UserRole role;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String login, String password) {
|
||||
this(login, password, UserRole.USER);
|
||||
}
|
||||
|
||||
public User(String login, String password, UserRole role) {
|
||||
this.login = login;
|
||||
this.password = password;
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public UserRole getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
User user = (User) o;
|
||||
return Objects.equals(id, user.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" +
|
||||
"id=" + id +
|
||||
", login='" + login + '\'' +
|
||||
", password='" + password + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
20
src/main/java/ip/labwork/user/model/UserRole.java
Normal file
20
src/main/java/ip/labwork/user/model/UserRole.java
Normal file
@ -0,0 +1,20 @@
|
||||
package ip.labwork.user.model;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
public enum UserRole implements GrantedAuthority {
|
||||
ADMIN,
|
||||
USER;
|
||||
|
||||
private static final String PREFIX = "ROLE_";
|
||||
|
||||
@Override
|
||||
public String getAuthority() {
|
||||
return PREFIX + this.name();
|
||||
}
|
||||
|
||||
public static final class AsString {
|
||||
public static final String ADMIN = PREFIX + "ADMIN";
|
||||
public static final String USER = PREFIX + "USER";
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package ip.labwork.user.repository;
|
||||
|
||||
import ip.labwork.user.model.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
User findOneByLoginIgnoreCase(String login);
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package ip.labwork.user.service;
|
||||
|
||||
public class UserExistsException extends RuntimeException {
|
||||
public UserExistsException(String login) {
|
||||
super(String.format("User '%s' already exists", login));
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package ip.labwork.user.service;
|
||||
|
||||
public class UserNotFoundException extends RuntimeException {
|
||||
public UserNotFoundException(String login) {
|
||||
super(String.format("User not found '%s'", login));
|
||||
}
|
||||
}
|
99
src/main/java/ip/labwork/user/service/UserService.java
Normal file
99
src/main/java/ip/labwork/user/service/UserService.java
Normal file
@ -0,0 +1,99 @@
|
||||
package ip.labwork.user.service;
|
||||
|
||||
import ip.labwork.configuration.jwt.JwtException;
|
||||
import ip.labwork.configuration.jwt.JwtProvider;
|
||||
import ip.labwork.user.controller.UserDto;
|
||||
import ip.labwork.user.controller.UserInfoDto;
|
||||
import ip.labwork.user.model.User;
|
||||
import ip.labwork.user.model.UserRole;
|
||||
import ip.labwork.user.repository.UserRepository;
|
||||
import ip.labwork.util.validation.ValidationException;
|
||||
import ip.labwork.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()));
|
||||
}
|
||||
}
|
42
src/main/java/ip/labwork/util/error/AdviceController.java
Normal file
42
src/main/java/ip/labwork/util/error/AdviceController.java
Normal file
@ -0,0 +1,42 @@
|
||||
package ip.labwork.util.error;
|
||||
|
||||
import ip.labwork.shop.service.ComponentNotFoundException;
|
||||
import ip.labwork.shop.service.OrderNotFoundException;
|
||||
import ip.labwork.shop.service.ProductNotFoundException;
|
||||
import ip.labwork.util.validation.ValidationException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.context.support.DefaultMessageSourceResolvable;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@ControllerAdvice
|
||||
public class AdviceController {
|
||||
@ExceptionHandler({
|
||||
ComponentNotFoundException.class,
|
||||
ProductNotFoundException.class,
|
||||
OrderNotFoundException.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);
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package ip.labwork.util.validation;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public class ValidationException extends RuntimeException {
|
||||
public ValidationException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public ValidationException(Set<String> errors) {
|
||||
super(String.join("\n", errors));
|
||||
}
|
||||
}
|
33
src/main/java/ip/labwork/util/validation/ValidatorUtil.java
Normal file
33
src/main/java/ip/labwork/util/validation/ValidatorUtil.java
Normal file
@ -0,0 +1,33 @@
|
||||
package ip.labwork.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()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1 +1,13 @@
|
||||
|
||||
spring.main.banner-mode=off
|
||||
server.port=8080
|
||||
spring.datasource.url=jdbc:h2:file:./data
|
||||
spring.datasource.driverClassName=org.h2.Driver
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=password
|
||||
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
spring.h2.console.enabled=true
|
||||
spring.h2.console.settings.trace=false
|
||||
spring.h2.console.settings.web-allow-others=false
|
||||
jwt.dev-token=my-secret-jwt
|
||||
jwt.dev=true
|
101
src/test/java/ip/labwork/JpaStudentTests.java
Normal file
101
src/test/java/ip/labwork/JpaStudentTests.java
Normal file
@ -0,0 +1,101 @@
|
||||
package ip.labwork;
|
||||
|
||||
import ip.labwork.shop.model.Component;
|
||||
import ip.labwork.shop.model.Order;
|
||||
import ip.labwork.shop.model.Product;
|
||||
import ip.labwork.shop.service.*;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@SpringBootTest
|
||||
public class JpaStudentTests {
|
||||
private static final Logger log = LoggerFactory.getLogger(JpaStudentTests.class);
|
||||
@Autowired
|
||||
ComponentService componentService;
|
||||
@Autowired
|
||||
ProductService productService;
|
||||
@Autowired
|
||||
OrderService orderService;
|
||||
@Test
|
||||
void test() {
|
||||
// componentService.deleteAllComponent();
|
||||
// productService.deleteAllProduct();
|
||||
// orderService.deleteAllOrder();
|
||||
// //TestCreate
|
||||
// //final Component component = componentService.addComponent("Огурец", 4);
|
||||
// log.info(component.toString());
|
||||
// Assertions.assertNotNull(component.getId());
|
||||
//
|
||||
// List<Component> componentList = new ArrayList<>();
|
||||
// componentList.add(componentService.findComponent(component.getId()));
|
||||
//
|
||||
// final Product product = productService.addProduct("Бургер", 100);
|
||||
// productService.addProductComponents(productService.findProduct(product.getId()), new Integer[]{ 2}, componentList );
|
||||
// log.info(product.toString());
|
||||
// Assertions.assertNotNull(product.getId());
|
||||
//
|
||||
// List<Product> productList = new ArrayList<>();
|
||||
// productList.add(productService.findProduct(product.getId()));
|
||||
// final Order order = orderService.addOrder(new Date().toString(), 200);
|
||||
// orderService.addOrderProducts(orderService.findOrder(order.getId()), new Integer[]{ 2 }, productList);
|
||||
// log.info(order.toString());
|
||||
// Assertions.assertNotNull(order.getId());
|
||||
//
|
||||
// //TestRead
|
||||
// final Component findComponent = componentService.findComponent(component.getId());
|
||||
// log.info(findComponent.toString());
|
||||
// Assertions.assertEquals(component, findComponent);
|
||||
//
|
||||
// final Product findProduct = productService.findProduct(product.getId());
|
||||
// log.info(findProduct.toString());
|
||||
// Assertions.assertEquals(product, findProduct);
|
||||
//
|
||||
// final Order findOrder = orderService.findOrder(order.getId());
|
||||
// log.info(findOrder.toString());
|
||||
// Assertions.assertEquals(order, findOrder);
|
||||
//
|
||||
// //TestReadAll
|
||||
// final List<Component> components = componentService.findAllComponent();
|
||||
// log.info(components.toString());
|
||||
// Assertions.assertEquals(components.size(), 1);
|
||||
//
|
||||
// final List<Product> products = productService.findAllProduct();
|
||||
// log.info(products.toString());
|
||||
// Assertions.assertEquals(products.size(), 1);
|
||||
//
|
||||
// final List<Order> orders = orderService.findAllOrder();
|
||||
// log.info(orders.toString());
|
||||
// Assertions.assertEquals(orders.size(), 1);
|
||||
//
|
||||
// //TestReadNotFound
|
||||
// componentService.deleteAllComponent();
|
||||
// productService.deleteAllProduct();
|
||||
// orderService.deleteAllOrder();
|
||||
// Assertions.assertThrows(ComponentNotFoundException.class, () -> componentService.findComponent(-1L));
|
||||
// Assertions.assertThrows(ProductNotFoundException.class, () -> productService.findProduct(-1L));
|
||||
// Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(-1L));
|
||||
//
|
||||
// //TestReadAllEmpty
|
||||
// final List<Component> newComponents = componentService.findAllComponent();
|
||||
// log.info(newComponents.toString());
|
||||
// productService.test();
|
||||
// Assertions.assertEquals(newComponents.size(), 0);
|
||||
//
|
||||
// final List<Product> newProducts = productService.findAllProduct();
|
||||
// log.info(newProducts.toString());
|
||||
// Assertions.assertEquals(newProducts.size(), 0);
|
||||
//
|
||||
// final List<Order> newOrders = orderService.findAllOrder();
|
||||
// log.info(newOrders.toString());
|
||||
// Assertions.assertEquals(newOrders.size(), 0);
|
||||
}
|
||||
}
|
@ -1,13 +1,62 @@
|
||||
package ip.labwork;
|
||||
|
||||
import ip.labwork.method.service.MethodService;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class LabworkApplicationTests {
|
||||
|
||||
@Autowired
|
||||
MethodService speakerService;
|
||||
@Test
|
||||
void contextLoads() {
|
||||
void testIntSum() {
|
||||
final String res = speakerService.Sum(20,10,"int");
|
||||
Assertions.assertEquals(30, Integer.parseInt(res));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIntMinus() {
|
||||
final String res = speakerService.Ras(20,10,"int");
|
||||
Assertions.assertEquals(10, Integer.parseInt(res));
|
||||
}
|
||||
@Test
|
||||
void testIntMulti() {
|
||||
final String res = speakerService.Pros(20,10,"int");
|
||||
Assertions.assertEquals(200, Integer.parseInt(res));
|
||||
}
|
||||
@Test
|
||||
void testIntDiv() {
|
||||
final String res = speakerService.Del(20,10,"int");
|
||||
Assertions.assertEquals(2, Integer.parseInt(res));
|
||||
}
|
||||
@Test
|
||||
void testStringSum() {
|
||||
final String res = speakerService.Sum("20","10","string");
|
||||
Assertions.assertEquals("2010", res);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStringMinus() {
|
||||
final String res = speakerService.Ras("300",1,"string");
|
||||
Assertions.assertEquals("30", res);
|
||||
}
|
||||
@Test
|
||||
void testStringMulti() {
|
||||
final String res = speakerService.Pros("20",2,"string");
|
||||
Assertions.assertEquals("2020", res);
|
||||
}
|
||||
@Test
|
||||
void testStringDiv() {
|
||||
final String res = speakerService.Del("20","2","string");
|
||||
Assertions.assertEquals("true", res);
|
||||
}
|
||||
@Test
|
||||
void testSpeakerErrorWired() {
|
||||
Assertions.assertThrows(NoSuchBeanDefinitionException.class, () -> speakerService.Sum("10", "20", "double"));
|
||||
}
|
||||
|
||||
}
|
||||
|
6
src/test/resources/application.properties
Normal file
6
src/test/resources/application.properties
Normal file
@ -0,0 +1,6 @@
|
||||
spring.datasource.url=jdbc:h2:mem:testdb
|
||||
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=create-drop
|
Loading…
Reference in New Issue
Block a user