Compare commits

..

22 Commits

Author SHA1 Message Date
Nikita Sergeev
52a842d8c9 Merge remote-tracking branch 'origin/LabWork04' into LabWork04
# Conflicts:
#	src/main/java/ip/labwork/shop/service/OrderService.java
2023-04-21 14:29:20 +04:00
Nikita Sergeev
f89a16bcd1 Так правильнее 2023-04-21 14:23:06 +04:00
Katerina881
881dcefe95 lab4 final edition 2023-04-10 17:26:35 +04:00
Nikita Sergeev
26a040743d работает на одном порту 2023-04-09 15:40:39 +04:00
Nikita Sergeev
edfa23dd7b frontend lab4 2023-04-09 14:32:21 +04:00
Nikita Sergeev
5d790b350c Merge remote-tracking branch 'origin/LabWork04' into LabWork04
# Conflicts:
#	src/main/java/ip/labwork/shop/controller/OrderController.java
#	src/main/java/ip/labwork/shop/controller/OrderDTO.java
#	src/main/java/ip/labwork/shop/controller/ProductController.java
#	src/main/java/ip/labwork/shop/controller/ProductDTO.java
#	src/main/java/ip/labwork/shop/service/OrderService.java
#	src/main/java/ip/labwork/shop/service/ProductService.java
2023-04-09 14:06:36 +04:00
Nikita Sergeev
258c8737b8 backend lab4 2023-04-09 14:04:16 +04:00
Katerina881
c57dc591f1 Надеюсь работает 2023-03-27 17:33:09 +04:00
Nikita Sergeev
686c5db7bf Фронт халф hp 2023-03-27 00:59:07 +04:00
Nikita Sergeev
08a82d3f06 Тесты и круды работают. А что ещё нужно для счастья? 2023-03-26 17:38:41 +04:00
Nikita Sergeev
2a876f5516 Сохранение перед добавлением фронта 2023-03-25 22:57:08 +04:00
Nikita Sergeev
b56c295266 Раскомментировал строчки теста 2023-03-17 19:56:14 +04:00
Nikita Sergeev
b2815fd417 Удаление работает 2023-03-17 19:34:38 +04:00
Nikita Sergeev
8c516e69f1 Странно работает удаление 2023-03-17 18:57:11 +04:00
Nikita Sergeev
1b4d36a1e2 Всё работает, но надо сделать ☆☆refactoring☆☆ 2023-03-17 00:15:17 +04:00
Nikita Sergeev
70a17c4b7c Работает всё, кроме обновления 2023-03-16 22:58:22 +04:00
Nikita Sergeev
7ae556be81 Все операции над компонентом работают 2023-03-16 17:23:50 +04:00
Katerina881
a25b5454a7 Одобренный вариант, но он мне не нравится 2023-03-13 18:01:25 +04:00
Katerina881
fd8a8e32c6 Lab3 2023-03-13 16:55:16 +04:00
Katerina881
ca392cb92b Сделанная вторая лаба 2023-02-27 17:00:41 +04:00
Katerina881
a9e7a9fc6b Рефакторинг 2023-02-13 17:45:53 +04:00
Katerina881
b77b39e859 Первая лаба 2023-02-13 17:27:49 +04:00
81 changed files with 6279 additions and 9 deletions

2
.gitignore vendored
View File

@ -4,7 +4,7 @@ build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
node_modules
### STS ###
.apt_generated
.classpath

View File

@ -12,9 +12,21 @@ repositories {
mavenCentral()
}
jar {
enabled = false
}
dependencies {
implementation(project(':front'))
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'
}
tasks.named('test') {

26
front/.gitignore vendored Normal file
View 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
View 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']
}

32
front/index.html Normal file
View File

@ -0,0 +1,32 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="/node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"
integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3"
crossorigin="anonymous"
></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.min.js"
integrity="sha384-IDwe1+LCz02ROU9k972gdyvl+AESN10+x7tBKgc9I5HFtuNz0wWnPclzo6p9vxnk"
crossorigin="anonymous"
></script>
<link
rel="stylesheet"
href="/node_modules/bootstrap/dist/css/bootstrap.min.css"
/>
<link
rel="stylesheet"
href="/node_modules/@fortawesome/fontawesome-free/css/all.min.css"
/>
<title>Очень вкусно и запятая</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

File diff suppressed because it is too large Load Diff

29
front/package.json Normal file
View 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
View 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
View 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;
}
}

46
front/src/App.jsx Normal file
View File

@ -0,0 +1,46 @@
import './App.css';
import { useRoutes, Outlet, BrowserRouter } from 'react-router-dom';
import Header from './components/common/Header';
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 { useState } from 'react';
function Router(props) {
return useRoutes(props.rootRoute);
}
export default function App() {
const [product,setProduct] = useState([]);
const routes = [
{ index: true, element: <CatalogStudents /> },
{ path: "catalogs/menu", element: <Menu product={product} setProduct={setProduct}/>, label: "Меню" },
{ path: "catalogs/component", element: <CatalogStudents />, label: "Компоненты" },
{ path: "catalogs/basket", element: <Basket product={product} setProduct={setProduct}/>, label: "Корзина" },
{ path: "catalogs/history", element: <History />, label: "История" }
];
const links = routes.filter(route => route.hasOwnProperty('label'));
const rootRoute = [
{ path: '/', element: render(links), children: routes }
];
function render(links) {
return (
<>
<Header links={links} />
<div className="container-fluid p-0">
<Outlet />
</div>
<Footer></Footer>
</>
);
}
return (
<BrowserRouter>
<Router rootRoute={ rootRoute } />
</BrowserRouter>
);
}

View 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>
);
}

View 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>
</>
);
}

View 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.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 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>
</>
);
}

View 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>
</>
);
}

View 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>
);
}

View 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>
);
}

View 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>
);
}

View File

@ -0,0 +1,73 @@
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>
<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>
);
}

View 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>
);
}

View File

@ -0,0 +1,35 @@
import { NavLink } from "react-router-dom";
export default function Header(props) {
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) => (
<li key={route.path} className="nav-item">
<NavLink className="nav-link fs-4" to={route.path}>
{route.label}
</NavLink>
</li>
))}
</ul>
</div>
</div>
</nav>
);
}

View 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>
);
}

View 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>
);
}

View 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 >
);
}

View File

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

View File

@ -0,0 +1,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"} ).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>
);
}

View 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 >
);
}

View File

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

View File

@ -0,0 +1,17 @@
export default function ToolbarProduct(props) {
function add() {
props.onAdd();
}
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-5 mb-3`}
onClick={add}
>
Добавить
</button>
</div>
);
}

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

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

View File

@ -0,0 +1,7 @@
export default class Component {
constructor(data) {
this.id = data?.id;
this.price = data?.price || "";
this.componentName = data?.componentName || "";
}
}

View File

@ -0,0 +1,9 @@
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";
}
}

View 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 || [];
}
}

View File

@ -0,0 +1,44 @@
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);
const data = await response.json();
return data.map(item => transformer(item));
}
static async read(url, transformer) {
const response = await axios.get(this.dataUrlPrefix + url);
return transformer(response.data);
}
static async create(url, data) {
const 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",
},
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);
return response.data.id;
}
}

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

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

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

View File

@ -1 +1,2 @@
rootProject.name = 'labwork'
include 'front'

View File

@ -2,8 +2,6 @@ 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
@ -12,8 +10,4 @@ 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);
}
}

View File

@ -1,8 +1,15 @@
package ip.labwork;
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.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.http.HttpStatus;
@Configuration
class WebConfiguration implements WebMvcConfigurer {
@ -10,4 +17,17 @@ class WebConfiguration implements WebMvcConfigurer {
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**").allowedMethods("*");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
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"));
};
}
}

View File

@ -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);
}
}

View 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);
}

View 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;
}
}
}

View 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";
}
}
}

View 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())));
}
}
}

View File

@ -0,0 +1,48 @@
package ip.labwork.shop.controller;
import ip.labwork.shop.service.ComponentService;
import jakarta.validation.Valid;
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
public ComponentDTO createComponent(@RequestBody @Valid ComponentDTO componentDTO) {
return componentService.create(componentDTO);
}
@PutMapping("/{id}")
public ComponentDTO updateComponent(@PathVariable Long id,@RequestBody @Valid ComponentDTO componentDTO) {
return componentService.updateComponent(id,componentDTO);
}
@DeleteMapping("/{id}")
public ComponentDTO removeComponent(@PathVariable Long id) {
return componentService.deleteComponent(id);
}
@DeleteMapping
public void removeAllComponent() {
componentService.deleteAllComponent();
}
@GetMapping("/{id}")
public ComponentDTO findComponent(@PathVariable Long id) {
return new ComponentDTO(componentService.findComponent(id));
}
@GetMapping
public List<ComponentDTO> findAllComponent() {
return componentService.findAllComponent();
}
}

View 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;
}
}

View File

@ -0,0 +1,41 @@
package ip.labwork.shop.controller;
import ip.labwork.shop.service.OrderService;
import jakarta.validation.Valid;
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
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}")
public OrderDTO findOrder(@PathVariable Long id){
return new OrderDTO(orderService.findOrder(id));
}
@GetMapping
public List<OrderDTO> findAllOrder(){
return orderService.findAllOrder();
}
}

View File

@ -0,0 +1,61 @@
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 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();
}
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 List<ProductDTO> getProductDTOList() {
return productDTOList;
}
}

View File

@ -0,0 +1,42 @@
package ip.labwork.shop.controller;
import ip.labwork.shop.service.ProductService;
import jakarta.validation.Valid;
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
public ProductDTO createProduct(@RequestBody @Valid ProductDTO productDTO){
return productService.create(productDTO);
}
@PutMapping("/{id}")
public ProductDTO updateProduct(@PathVariable Long id,@RequestBody @Valid ProductDTO productDTO){
return productService.updateProduct(id, productDTO);
}
@DeleteMapping("/{id}")
public ProductDTO removeProduct(@PathVariable Long id){
return productService.deleteProduct(id);
}
@DeleteMapping
public void removeAllProduct(){
productService.deleteAllProduct();
}
@GetMapping("/{id}")
public ProductDTO findProduct(@PathVariable Long id){
return new ProductDTO(productService.findProduct(id));
}
@GetMapping
public List<ProductDTO> findAllProduct(){
return productService.findAllProduct();
}
}

View 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;
}
}

View 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 + '\'' +
'}';
}
}

View File

@ -0,0 +1,98 @@
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;
@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) {
this.date = date;
this.price = price;
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;
}
@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());
}
@Override
public int hashCode() {
return Objects.hash(getId(), getDate(), getPrice());
}
}

View 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;
}
}

View 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());
}
}

View File

@ -0,0 +1,5 @@
package ip.labwork.shop.model;
public enum OrderStatus {
Неизвестен, Готов
}

View 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 + '\'' +
'}';
}
}

View 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 +
'}';
}
}

View 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 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());
}
}

View File

@ -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> {
}

View File

@ -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);
}

View File

@ -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);
}

View File

@ -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));
}
}

View 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();
}
}

View File

@ -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));
}
}

View File

@ -0,0 +1,101 @@
package ip.labwork.shop.service;
import ip.labwork.shop.controller.OrderDTO;
import ip.labwork.shop.model.*;
import ip.labwork.shop.repository.OrderRepository;
import ip.labwork.shop.repository.ProductRepository;
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 ValidatorUtil validatorUtil;
public OrderService(OrderRepository orderRepository,
ValidatorUtil validatorUtil, ProductRepository productRepository) {
this.orderRepository = orderRepository;
this.validatorUtil = validatorUtil;
this.productRepository = productRepository;
}
@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());
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
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();
}
}

View File

@ -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));
}
}

View 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());
}
}

View 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;
}
}

View 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";
}
}

View 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);
}
}

View File

@ -0,0 +1,9 @@
package ip.labwork.util.validation;
import java.util.Set;
public class ValidationException extends RuntimeException {
public ValidationException(Set<String> errors) {
super(String.join("\n", errors));
}
}

View 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()));
}
}
}

View File

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

View File

@ -0,0 +1,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);
}
}

View File

@ -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"));
}
}

View 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