Compare commits

..

24 Commits

Author SHA1 Message Date
Katerina881
75071fdc1d Принятая лабораторная работа 2023-04-24 16:02:44 +04:00
Nikita Sergeev
b741f13f4d Всё работает 2023-04-23 13:00:59 +04:00
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
95 changed files with 7407 additions and 10 deletions

2
.gitignore vendored
View File

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

View File

@ -12,9 +12,28 @@ repositories {
mavenCentral() mavenCentral()
} }
jar {
enabled = false
}
dependencies { dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web' 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' testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
implementation 'org.webjars:bootstrap:5.1.3'
implementation 'org.webjars:jquery:3.6.0'
implementation 'org.webjars:font-awesome:6.1.0'
} }
tasks.named('test') { 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' rootProject.name = 'labwork'
include 'front'

View File

@ -2,8 +2,6 @@ package ip.labwork;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; 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; import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication @SpringBootApplication
@ -12,8 +10,4 @@ public class LabworkApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(LabworkApplication.class, 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,13 +1,34 @@
package ip.labwork; 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.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 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 @Configuration
class WebConfiguration implements WebMvcConfigurer { public class WebConfiguration implements WebMvcConfigurer {
public static final String REST_API = "/api";
@Override @Override
public void addCorsMappings(CorsRegistry registry){ public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**").allowedMethods("*"); 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,46 @@
package ip.labwork.method.controller;
import ip.labwork.WebConfiguration;
import ip.labwork.method.service.MethodService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/method")
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,49 @@
package ip.labwork.shop.controller;
import ip.labwork.WebConfiguration;
import ip.labwork.shop.service.ComponentService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/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,58 @@
package ip.labwork.shop.controller;
import com.fasterxml.jackson.annotation.JsonProperty;
import ip.labwork.shop.model.Component;
import jakarta.validation.constraints.NotBlank;
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 void setId(long id) {
this.id = id;
}
public String getComponentName() {
return componentName;
}
public void setComponentName(String componentName) {
this.componentName = componentName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}

View File

@ -0,0 +1,55 @@
package ip.labwork.shop.controller;
import ip.labwork.shop.service.ComponentService;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/component")
public class ComponentMvcController {
private final ComponentService componentService;
public ComponentMvcController(ComponentService componentService) {
this.componentService = componentService;
}
@GetMapping
public String getComponents(Model model) {
model.addAttribute("components", componentService.findAllComponent());
return "component";
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editComponent(@PathVariable(required = false) Long id,
Model model) {
if (id == null || id <= 0) {
model.addAttribute("componentDto", new ComponentDTO());
} else {
model.addAttribute("componentId", id);
model.addAttribute("componentDto", new ComponentDTO(componentService.findComponent(id)));
}
return "component-edit";
}
@PostMapping(value = {"/", "/{id}"})
public String saveComponent(@PathVariable(required = false) Long id,
@ModelAttribute @Valid ComponentDTO componentDTO,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "component-edit";
}
if (id == null || id <= 0) {
componentService.create(componentDTO);
} else {
componentService.updateComponent(id, componentDTO);
}
return "redirect:/component";
}
@PostMapping("/delete/{id}")
public String deleteComponent(@PathVariable Long id) {
componentService.deleteComponent(id);
return "redirect:/component";
}
}

View File

@ -0,0 +1,42 @@
package ip.labwork.shop.controller;
import ip.labwork.WebConfiguration;
import ip.labwork.shop.service.OrderService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/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,72 @@
package ip.labwork.shop.controller;
import ip.labwork.shop.model.Order;
import ip.labwork.shop.model.OrderStatus;
import jakarta.validation.constraints.NotBlank;
import java.util.Date;
import java.util.List;
import java.util.Objects;
public class OrderDTO {
private long id;
@NotBlank(message = "Date can't be null or empty")
private Date date = new Date();
@NotBlank(message = "Price can't be null or empty")
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 void setId(long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public OrderStatus getStatus() {
return status;
}
public void setStatus(OrderStatus status) {
this.status = status;
}
public List<ProductDTO> getProductDTOList() {
return productDTOList;
}
public void setProductDTOList(List<ProductDTO> productDTOList) {
this.productDTOList = productDTOList;
}
}

View File

@ -0,0 +1,79 @@
package ip.labwork.shop.controller;
import ip.labwork.shop.model.OrderStatus;
import ip.labwork.shop.service.OrderService;
import ip.labwork.shop.service.ProductService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/order")
public class OrderMvcController {
private final OrderService orderService;
private final ProductService productService;
public OrderMvcController(OrderService orderService, ProductService productService) {
this.orderService = orderService;
this.productService = productService;
}
@GetMapping
public String getOrders(HttpServletRequest request,
Model model) {
Cookie[] cookies = request.getCookies();
List<ProductDTO> productDTOS = new ArrayList<>();
int totalPrice = 0;
if (cookies != null){
for(Cookie cookie : cookies){
if (StringUtils.isNumeric(cookie.getName())){
ProductDTO productDTO = new ProductDTO(productService.findProduct(Long.parseLong(cookie.getName())),Integer.parseInt(cookie.getValue()));
productDTOS.add(productDTO);
totalPrice += productDTO.getPrice() * productDTO.getCount();
}
}
}
model.addAttribute("productDTOS", productDTOS);
model.addAttribute("totalPrice", totalPrice);
return "order";
}
@PostMapping
public String createOrder(HttpServletRequest request,
HttpServletResponse response) {
Cookie[] cookies = request.getCookies();
OrderDTO orderDTO = new OrderDTO();
List<ProductDTO> productDTOS = new ArrayList<>();
int totalPrice = 0;
for(Cookie temp : cookies){
if (StringUtils.isNumeric(temp.getName())){
ProductDTO productDTO = new ProductDTO(productService.findProduct(Long.parseLong(temp.getName())),Integer.parseInt(temp.getValue()));
productDTOS.add(productDTO);
totalPrice += productDTO.getPrice() * productDTO.getCount();
}
}
orderDTO.setPrice(totalPrice);
orderDTO.setProductDTOList(productDTOS);
orderDTO.setStatus(OrderStatus.Готов);
orderService.create(orderDTO);
response.addCookie(new Cookie("delete",""));
return "redirect:/order";
}
@GetMapping(value = {"/all"})
public String getOrders(Model model) {
model.addAttribute("orders", orderService.findAllOrder());
return "orders";
}
@GetMapping(value = {"/view/{id}"})
public String getOrder(@PathVariable(required = false) Long id,
Model model) {
model.addAttribute("orderDto", new OrderDTO(orderService.findOrder(id)));
return "order-view";
}
}

View File

@ -0,0 +1,43 @@
package ip.labwork.shop.controller;
import ip.labwork.WebConfiguration;
import ip.labwork.shop.service.ProductService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/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,100 @@
package ip.labwork.shop.controller;
import ip.labwork.shop.model.Product;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.List;
import java.util.Objects;
public class ProductDTO {
private long id;
@NotBlank(message = "Name can't be null or empty")
private String name;
@NotNull(message = "Price can't be null or empty")
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() == null ? null : 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 void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public List<ComponentDTO> getComponentDTOList() {
return componentDTOList;
}
public void setComponentDTOList(List<ComponentDTO> componentDTOList) {
this.componentDTOList = componentDTOList;
}
public List<OrderDTO> getOrderDTOList() {
return orderDTOList;
}
public void setOrderDTOList(List<OrderDTO> orderDTOList) {
this.orderDTOList = orderDTOList;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}

View File

@ -0,0 +1,83 @@
package ip.labwork.shop.controller;
import ip.labwork.shop.service.ComponentService;
import ip.labwork.shop.service.ProductService;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Base64;
@Controller
@RequestMapping("/product")
public class ProductMvcController {
private final ProductService productService;
private final ComponentService componentService;
public ProductMvcController(ProductService productService, ComponentService componentService) {
this.productService = productService;
this.componentService = componentService;
}
@GetMapping
public String getProducts(Model model) {
model.addAttribute("products", productService.findAllProduct());
return "product";
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editProduct(@PathVariable(required = false) Long id,
Model model) {
if (id == null || id <= 0) {
model.addAttribute("productDto", new ProductDTO());
} else {
model.addAttribute("productId", id);
model.addAttribute("componentDto", new ComponentDTO());
model.addAttribute("productDto", new ProductDTO(productService.findProduct(id)));
}
model.addAttribute("components", componentService.findAllComponent());
return "product-edit";
}
@PostMapping(value = {"/", "/{id}"})
public String saveProduct(@PathVariable(required = false) Long id,
@RequestParam("file") MultipartFile file,
@ModelAttribute @Valid ProductDTO productDTO,
BindingResult bindingResult,
Model model) throws IOException {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "product-edit";
}
productDTO.setImage("data:image/jpeg;base64," + Base64.getEncoder().encodeToString(file.getBytes()));
if (id == null || id <= 0) {
return "redirect:/product/edit/" + productService.create(productDTO).getId();
} else {
productService.updateFields(id, productDTO);
return "redirect:/product/edit/" + id;
}
}
@PostMapping("/delete/{id}")
public String deleteProduct(@PathVariable Long id) {
productService.deleteProduct(id);
return "redirect:/product";
}
@PostMapping("/delete/{id}/{componentid}")
public String deleteComponent(@PathVariable Long id,
@PathVariable Long componentid) {
productService.deleteComponent(id,componentid);
return "redirect:/product/edit/" + id;
}
@PostMapping("/addproduct/{id}")
public String addComponent(@PathVariable Long id,
@ModelAttribute @Valid ComponentDTO componentDTO,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "product-edit";
}
productService.addComponent(id, componentDTO);
return "redirect:/product/edit/" + id;
}
}

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,166 @@
package ip.labwork.shop.service;
import ip.labwork.shop.controller.ComponentDTO;
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);
if(productDTO.getComponentDTOList() != null){
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 updateFields(Long id, ProductDTO product) {
final Product currentProduct = findProduct(id);
currentProduct.setProductName(product.getName());
if (product.getImage().length()>23){
currentProduct.setImage(product.getImage().getBytes());
}
validatorUtil.validate(currentProduct);
productRepository.save(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 ProductDTO addComponent(Long id, ComponentDTO componentDTO) {
if (componentDTO.getCount() <= 0){
return null;
}
final Product currentProduct = findProduct(id);
List<ProductComponents> productComponentsList = productRepository.getProductComponent(id);
if(productComponentsList.stream().filter(x -> x.getId().getComponentId() == componentDTO.getId()).toList().size() != 0) {
final ProductComponents productComponents = productRepository.getProductComponent(id).stream().filter(x -> x.getId().getComponentId().equals(componentDTO.getId())).findFirst().get();
currentProduct.removeComponent(productComponents);
currentProduct.addComponent(new ProductComponents(componentRepository.findById(componentDTO.getId()).orElseThrow(() -> new ComponentNotFoundException(id)), currentProduct, componentDTO.getCount()));
}else{
final ProductComponents productComponents = new ProductComponents(componentRepository.findById(componentDTO.getId()).orElseThrow(() -> new ComponentNotFoundException(id)), currentProduct, componentDTO.getCount());
currentProduct.addComponent(productComponents);
}
productRepository.saveAndFlush(currentProduct);
int price = 0;
for(int i = 0; i < productRepository.getProductComponent(id).size(); i++){
price += productRepository.getProductComponent(id).get(i).getComponent().getPrice() * productRepository.getProductComponent(id).get(i).getCount();
}
currentProduct.setPrice(price);
productRepository.saveAndFlush(currentProduct);
return new ProductDTO(currentProduct);
}
@Transactional
public ProductDTO deleteComponent(Long id, Long componentId) {
Product currentProduct = findProduct(id);
final ProductComponents productComponents = productRepository.getProductComponent(id).stream().filter(x -> x.getId().getComponentId().equals(componentId)).findFirst().get();
currentProduct.removeComponent(productComponents);
Component component = componentRepository.findById(componentId).orElseThrow(() -> new ComponentNotFoundException(componentId));
component.removeProduct(productComponents);
productRepository.save(currentProduct);
currentProduct = findProduct(id);
int price = 0;
for(int i = 0; i < currentProduct.getComponents().size(); i++){
price += currentProduct.getComponents().get(i).getComponent().getPrice() * currentProduct.getComponents().get(i).getCount();
}
currentProduct.setPrice(price);
productRepository.saveAndFlush(currentProduct);
return new ProductDTO(currentProduct);
}
}

View File

@ -0,0 +1,18 @@
package ip.labwork.test.controller;
import ip.labwork.WebConfiguration;
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(WebConfiguration.REST_API + "/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,43 @@
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 org.springframework.web.bind.annotation.RestController;
import java.util.stream.Collectors;
@ControllerAdvice(annotations = RestController.class)
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,86 @@
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;
}
}

View File

@ -0,0 +1,49 @@
<!DOCTYPE html>
<html
lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}"
>
<head> </head>
<body>
<main style="background-color: white" layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form
action="#"
th:action="@{/component/{id}(id=${id})}"
th:object="${componentDto}"
method="post"
>
<div class="mb-3">
<label for="componentName" class="form-label">Название</label>
<input
type="text"
class="form-control"
id="componentName"
th:field="${componentDto.componentName}"
required="true"
/>
</div>
<div class="mb-3">
<label for="price" class="form-label">Цена</label>
<input
type="text"
class="form-control"
id="price"
th:field="${componentDto.price}"
required="true"
/>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span th:if="${id == null}">Добавить</span>
<span th:if="${id != null}">Обновить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/component}">
Назад
</a>
</div>
</form>
</main>
</body>
</html>

View File

@ -0,0 +1,65 @@
<!DOCTYPE html>
<html
lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}"
>
<head> </head>
<body>
<main style="background-color: white" layout:fragment="content">
<div>
<a class="btn btn-success button-fixed" th:href="@{/component/edit}">
<i class="fa-solid fa-plus"></i> Добавить
</a>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Название</th>
<th scope="col">Цена</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr th:each="component, iterator: ${components}">
<th scope="row" th:text="${iterator.index} + 1" />
<td th:text="${component.componentName}" />
<td th:text="${component.price}" style="width: 60%" />
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<a
class="btn btn-warning button-fixed button-sm"
th:href="@{/component/edit/{id}(id=${component.id})}"
>
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a>
<button
type="button"
class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${component.id}').click()|"
>
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
</div>
<form
th:action="@{/component/delete/{id}(id=${component.id})}"
method="post"
>
<button
th:id="'remove-' + ${component.id}"
type="submit"
style="display: none"
>
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</main>
</body>
</html>

View File

@ -0,0 +1,66 @@
<!DOCTYPE html>
<html
lang="ru"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
>
<head>
<meta charset="UTF-8" />
<title>Очень вкусно и запятая</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script
type="text/javascript"
src="/webjars/bootstrap/5.1.3/js/bootstrap.bundle.min.js"
></script>
<link
rel="stylesheet"
href="/webjars/bootstrap/5.1.3/css/bootstrap.min.css"
/>
<link rel="stylesheet" href="/webjars/font-awesome/6.1.0/css/all.min.css" />
<link rel="stylesheet" href="/css/style.css" />
</head>
<body class="d-flex flex-column h-100">
<div id="app">
<nav class="navbar navbar-expand-lg">
<div class="container-fluid">
<a class="navbar-brand" href="/product">
<h1 class="text-black">Очень вкусно и запятая</h1>
</a>
<button
class="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarNav"
aria-controls="navbarNav"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<a class="nav-link fs-4 text-black" href="/component"
>Компоненты</a
>
<a class="nav-link fs-4 text-black" href="/product">Продукты</a>
<a class="nav-link fs-4 text-black" href="/order">Заказы</a>
<a class="nav-link fs-4 text-black" href="/order/all">История заказов</a>
</ul>
</div>
</div>
</nav>
<div class="container-fluid p-0">
<div
class="container container-padding"
layout:fragment="content"
></div>
</div>
<footer
class="footer mt-auto d-flex justify-content-center align-items-center"
>
ООО "Вкусно" © 2022
</footer>
</div>
</body>
<th:block layout:fragment="scripts"> </th:block>
</html>

View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html
lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}"
>
<head> </head>
<body>
<div layout:fragment="content">
<div><span th:text="${error}"></span></div>
<a href="/">На главную</a>
</div>
</body>
</html>

View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html
lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}"
>
<head> </head>
<body>
<div layout:fragment="content">
<div>It's works!</div>
<a href="123">ERROR</a>
</div>
</body>
</html>

View File

@ -0,0 +1,71 @@
<!DOCTYPE html>
<html
lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}"
>
<head>
<script
type="text/javascript"
src="/webjars/jquery/3.6.0/jquery.min.js"
></script>
</head>
<body>
<main style="background-color: white" layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<div class="mb-3">
<label for="name" class="form-label">Дата</label>
<input
type="text"
class="form-control"
id="name"
th:field="${orderDto.date}"
disabled
required="true"
/>
</div>
<div class="mb-3">
<label for="price" class="form-label">Общая стоимость</label>
<input
type="text"
class="form-control"
id="price"
th:value="${orderDto.price}"
disabled
required="true"
/>
</div>
<div class="mb-3">
<label for="image" class="form-label">Статус</label>
<input type="text" class="form-control" disabled id="image" th:value="${orderDto.status}" />
</div>
<div class="mb-3">
<a class="btn btn-secondary button-fixed" th:href="@{/order/all}">
Назад
</a>
</div>
<div class="table-responsive" th:if="${id != null}">
<table class="table">
<thead>
<tr>
<th scope="col">Название</th>
<th scope="col">Количество</th>
</tr>
</thead>
<tbody>
<tr
th:each="product, iterator: ${orderDto.getProductDTOList()}"
>
<th
scope="row"
th:text="${product.getName()}"
style="width: 60%"
/>
<td th:text="${product.getCount()}" />
</tr>
</tbody>
</table>
</div>
</main>
</body>
</html>

View File

@ -0,0 +1,132 @@
<!DOCTYPE html>
<html
lang="en"
layout:decorate="~{default}"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
>
<head> </head>
<body>
<main
class="flex-shrink-0"
style="background-color: white"
layout:fragment="content"
>
<h1 class="my-5 ms-5 fs-1">
<b>Корзина</b>
</h1>
<h2 class="my-5 ms-5 fs-3"></h2>
<div class="ms-5 my-5">Список товаров</div>
<div>
<div style="max-width: 35%">
<table class="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 class="table-group-divider">
<tr th:each="product, iterator: ${productDTOS}">
<th scope="row" th:text="${iterator.index+1}"></th>
<td colspan="2" th:text="${product.name}"></td>
<td th:text="${product.count+'x'+product.price+' руб'}"></td>
<td>
<button th:attr="onclick=|remove(${product.id})|">
Удалить
</button>
</td>
</tr>
</tbody>
</table>
</div>
<h2 class="ms-5 my-5" th:text="${'Итого: ' + totalPrice + ' руб'}"></h2>
<button
class="btn btn-success ms-5 w-25"
type="button"
style="color: black"
th:attr="onclick=|document.getElementById('accept').click()|"
>
Купить
</button>
<form th:action="@{/order}" method="post">
<button th:id="'accept'" type="submit" style="display: none">
Купить
</button>
</form>
</div>
<p></p>
<p></p>
</main>
</body>
<th:block layout:fragment="scripts">
<script>
function deleteAll() {
let l = getCookie();
for (let i = 0; i < l.length; i++) {
if (l[i].id === "delete") {
let cookies = document.cookie.split(";");
for (let j = 0; j < cookies.length; j++) {
let cookie = cookies[j];
let eqPos = cookie.indexOf("=");
let name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie =
name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;";
document.cookie =
name + "=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}
window.location.href = "/order";
}
}
}
deleteAll();
function remove(name) {
let i = getCookie(name);
const d = new Date();
d.setTime(d.getTime() + 24 * 60 * 60 * 1000);
let expires = "expires=" + d.toUTCString();
if (i == "1") {
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;";
document.cookie =
name + "=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;";
} else {
document.cookie =
name + "=" + (Number(i) - Number(1)) + ";" + expires + ";path=/";
}
window.location.href = "/order";
}
function getCookie(name) {
if (name) {
name = name + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(";");
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == " ") {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
} else {
let arrObjects = [];
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split("; ");
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
let cs = c.split("=");
arrObjects[i] = {
id: cs[0],
count: cs[1],
};
}
return arrObjects;
}
}
</script>
</th:block>
</html>

View File

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html
lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}"
>
<head> </head>
<body>
<main style="background-color: white" layout:fragment="content">
<div class="table-responsive">
<table class="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>
<tr th:each="order, iterator: ${orders}">
<th scope="row" th:text="${iterator.index} + 1" />
<td th:text="${order.date}" style="width: 60%"/>
<td th:text="${order.price}" />
<td th:text="${order.status}" />
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<a
class="btn btn-warning button-fixed button-sm"
th:href="@{/order/view/{id}(id=${order.id})}"
>
<i class="fa fa-pencil" aria-hidden="true"></i> Подробнее
</a>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</main>
</body>
</html>

View File

@ -0,0 +1,142 @@
<!DOCTYPE html>
<html
lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}"
>
<head>
<script
type="text/javascript"
src="/webjars/jquery/3.6.0/jquery.min.js"
></script>
</head>
<body>
<main style="background-color: white" layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form
action="#"
th:action="@{/product/{id}(id=${id})}"
th:object="${productDto}"
enctype="multipart/form-data"
method="post"
>
<div class="mb-3">
<label for="name" class="form-label">Название</label>
<input
type="text"
class="form-control"
id="name"
th:field="${productDto.name}"
required="true"
/>
</div>
<div class="mb-3">
<label for="price" class="form-label">Цена</label>
<input
type="text"
class="form-control"
id="price"
th:value="${productDto.price}"
disabled
required="true"
/>
</div>
<div class="mb-3">
<label for="image" class="form-label">Изображение</label>
<input type="file" class="form-control" id="image" th:name="file" />
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span th:if="${id == null}">Добавить</span>
<span th:if="${id != null}">Обновить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/product}">
Назад
</a>
</div>
</form>
<form
th:if="${id != null}"
action="#"
th:action="@{/product/addproduct/{id}(id=${id})}"
th:object="${componentDto}"
method="post"
>
<div class="mb-3">
<label for="lang" class="form-label">Компонент</label>
<select id="lang" class="form-select" th:field="${componentDto.id}">
<option
th:each="value: ${components}"
th:value="${value.getId()}"
th:selected="true"
th:text="${value.getComponentName()}"
></option>
</select>
</div>
<div class="mb-3">
<label for="count" class="form-label">Количество</label>
<input
type="text"
class="form-control"
id="count"
th:field="${componentDto.count}"
required="true"
/>
</div>
<div>
<div>
<button class="btn btn-success button-fixed" type="submit">
Добавить
</button>
</div>
</div>
</form>
<div class="table-responsive" th:if="${id != null}">
<table class="table">
<thead>
<tr>
<th scope="col">Название</th>
<th scope="col">Количество</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr
th:each="component, iterator: ${productDto.getComponentDTOList()}"
>
<th
scope="row"
th:text="${component.getComponentName()}"
style="width: 60%"
/>
<td th:text="${component.getCount()}" />
<td style="width: 10%">
<div class="btn-group" role="group" aria-label="Basic example">
<button
type="button"
class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${component.id}').click()|"
>
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
</div>
<form
th:action="@{/product/delete/{productid}/{id} (id=${component.getId()}, productid=${id})}"
method="post"
>
<button
th:id="'remove-' + ${component.getId()}"
type="submit"
style="display: none"
>
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</main>
</body>
</html>

View File

@ -0,0 +1,108 @@
<!DOCTYPE html>
<html
lang="en"
layout:decorate="~{default}"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
>
<head> </head>
<body>
<main class="flex-shrink-0" layout:fragment="content">
<div class="btn-group mt-2" role="group">
<a
type="button"
class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-2 mb-3"
th:href="@{/product/edit}"
>
Добавить
</a>
</div>
<div class="temp row row-cols-1 row-cols-md-3 g-4" id="tbl-items">
<div
class="col"
th:each="product, iterator: ${products}"
th:key="${product.getId()}"
>
<div class="card">
<div class="container w-100 h-350px">
<img
alt="Бугер"
class="img-fluid rounded mx-auto d-block"
style="width: 100%; height: 350px; objectfit: contain"
th:src="${product.image}"
/>
</div>
<div class="card-body">
<h5
class="card-title text-center fs-1"
th:text="${product.getPrice()}"
></h5>
<a
class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${product.id}').click()|"
>
Удалить
</a>
<a
class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
th:href="@{/product/edit/{id}(id=${product.id})}"
type="button"
>Изменить
</a>
<a
class="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
type="button"
th:attr="onclick=|add(${product.id})|"
>
в корзину
</a>
<form
th:action="@{/product/delete/{id}(id=${product.id})}"
method="post"
>
<button
th:id="'remove-' + ${product.id}"
type="submit"
style="display: none"
>
Удалить
</button>
</form>
</div>
</div>
</div>
</div>
</main>
</body>
<th:block layout:fragment="scripts">
<script>
function add(name) {
let i = getCookie(name);
const d = new Date();
d.setTime(d.getTime() + 24 * 60 * 60 * 1000);
let expires = "expires=" + d.toUTCString();
if (i == "") {
document.cookie = name + "=" + 1 + ";" + expires + ";path=/";
} else {
document.cookie =
name + "=" + (Number(i) + Number(1)) + ";" + expires + ";path=/";
}
}
function getCookie(name) {
name = name + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(";");
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == " ") {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
</script>
</th:block>
</html>

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; package ip.labwork;
import ip.labwork.method.service.MethodService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; 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; import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest @SpringBootTest
class LabworkApplicationTests { class LabworkApplicationTests {
@Autowired
MethodService speakerService;
@Test @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