Тесты и круды работают. А что ещё нужно для счастья?

This commit is contained in:
Nikita Sergeev 2023-03-26 17:38:41 +04:00
parent 2a876f5516
commit 08a82d3f06
26 changed files with 576 additions and 2151 deletions

View File

@ -1,152 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="../node_modules/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet"/>
<title>Rest CLient</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-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">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<form id="formComponent">
<div class="row mt-3">
<div class="col-sm-6">
<label for="lastName" class="form-label">Last name</label>
<input type="text" class="form-control" id="lastName" required>
</div>
<div class="col-sm-6">
<label for="firstName" class="form-label">First name</label>
<input type="text" class="form-control" id="firstName" required>
</div>
</div>
<div class="row mt-3">
<div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Add</button>
</div>
<div class="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button id="testError" type="button" class="btn btn-danger">Test</button>
</div>
<div class="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button id="testNormal" type="button" class="btn btn-secondary">Test</button>
</div>
</div>
</form>
<div class="row table-responsive">
<table class="table mt-3">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First name</th>
<th scope="col">Last name</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</div>
<div class="container">
<form id="form">
<div class="row mt-3">
<div class="col-sm-6">
<label for="lastName" class="form-label">Last name</label>
<input type="text" class="form-control" id="lastName" required>
</div>
<div class="col-sm-6">
<label for="firstName" class="form-label">First name</label>
<input type="text" class="form-control" id="firstName" required>
</div>
</div>
<div class="row mt-3">
<div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Add</button>
</div>
<div class="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button id="testError" type="button" class="btn btn-danger">Test</button>
</div>
<div class="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button id="testNormal" type="button" class="btn btn-secondary">Test</button>
</div>
</div>
</form>
<div class="row table-responsive">
<table class="table mt-3">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First name</th>
<th scope="col">Last name</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</div>
<div class="container">
<form id="form">
<div class="row mt-3">
<div class="col-sm-6">
<label for="lastName" class="form-label">Last name</label>
<input type="text" class="form-control" id="lastName" required>
</div>
<div class="col-sm-6">
<label for="firstName" class="form-label">First name</label>
<input type="text" class="form-control" id="firstName" required>
</div>
</div>
<div class="row mt-3">
<div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Add</button>
</div>
<div class="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button id="testError" type="button" class="btn btn-danger">Test</button>
</div>
<div class="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button id="testNormal" type="button" class="btn btn-secondary">Test</button>
</div>
</div>
</form>
<div class="row table-responsive">
<table class="table mt-3">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First name</th>
<th scope="col">Last name</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</div>
<script src="/script.js"></script>
</body>
</html>

View File

@ -1,51 +0,0 @@
let calculateButton = document.getElementById("calculate");
let numberOneInput = document.getElementById("first");
let numberTwoInput = document.getElementById("second");
let resultInput = document.getElementById("res");
let typeInput = document.getElementById("type");
buttonPlus.onclick = function(event) {
event.preventDefault();
let num_1 = numberOneInput.value;
let num_2 = numberTwoInput.value;
let type = typeInput.value;
fetch(`http://localhost:8080/sum?first=${num_1}&second=${num_2}&type=${type}`)
.then(response => response.text())
.then(res => {
resultInput.value = res;
});
}
buttonMinus.onclick = function(event) {
event.preventDefault();
let num_1 = numberOneInput.value;
let num_2 = numberTwoInput.value;
let type = typeInput.value;
fetch(`http://localhost:8080/minus?first=${num_1}&second=${num_2}&type=${type}`)
.then(response => response.text())
.then(res => {
resultInput.value = res;
});
}
buttonMulti.onclick = function(event) {
event.preventDefault();
let num_1 = numberOneInput.value;
let num_2 = numberTwoInput.value;
let type = typeInput.value;
fetch(`http://localhost:8080/multi?first=${num_1}&second=${num_2}&type=${type}`)
.then(response => response.text())
.then(res => {
resultInput.value = res;
});
}
buttonDiv.onclick = function(event) {
event.preventDefault();
let num_1 = numberOneInput.value;
let num_2 = numberTwoInput.value;
let type = typeInput.value;
fetch(`http://localhost:8080/div?first=${num_1}&second=${num_2}&type=${type}`)
.then(response => response.text())
.then(res =>
{
resultInput.value = res;
});
}

View File

@ -17,7 +17,7 @@ jar {
} }
dependencies { dependencies {
implementation(project(':Front')) implementation(project(':front'))
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 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210' implementation 'com.h2database:h2:2.1.210'

File diff suppressed because it is too large Load Diff

View File

@ -1,14 +1,14 @@
{ {
"name": "int-prog", "name": "front",
"version": "1.0.0", "version": "1.0.0",
"main": "src/index.html", "source": "src/index.html",
"scripts": { "scripts": {
"start": "parcel --port 3000", "start": "parcel --port 3000",
"build": "npm run clean && parcel build", "build": "npm run clean && parcel build",
"clean": "rimraf dist" "clean": "rimraf dist"
}, },
"dependencies": { "dependencies": {
"bootstrap": "5.2.1" "bootstrap": "5.2.3"
}, },
"devDependencies": { "devDependencies": {
"parcel": "2.8.3", "parcel": "2.8.3",

69
front/src/components.html Normal file
View File

@ -0,0 +1,69 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Компоненты</title>
<script type="module" src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<div class="container">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="index.html">Заказы</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-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">
<li class="nav-item">
<a class="nav-link" href="components.html">Компоненты</a>
</li>
<li class="nav-item">
<a class="nav-link" href="products.html">Продукты</a>
</li>
</ul>
</div>
</nav>
<form id="form">
<div class="row mt-3">
<div class="col-sm-6">
<label for="componentName" class="form-label">Название компонента</label>
<input type="text" class="form-control" id="componentName" required>
</div>
<div class="col-sm-6">
<label for="price" class="form-label">Цена</label>
<input type="text" class="form-control" id="price" required>
</div>
</div>
<div class="row mt-3">
<div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Add</button>
</div>
<div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Update</button>
</div>
<div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Delete</button>
</div>
</div>
</form>
<div class="row table-responsive">
<table id="table" class="table mt-3">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First name</th>
<th scope="col">Last name</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</div>
</body>
<script src="scriptComponent.js"></script>
</html>

69
front/src/index.html Normal file
View File

@ -0,0 +1,69 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Заказы</title>
<script type="module" src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<div class="container">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="index.html">Заказы</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-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">
<li class="nav-item">
<a class="nav-link" href="components.html">Компоненты</a>
</li>
<li class="nav-item">
<a class="nav-link" href="products.html">Продукты</a>
</li>
</ul>
</div>
</nav>
<form id="form">
<div class="row mt-3">
<div class="col-sm-6">
<label for="componentName" class="form-label">Название компонента</label>
<input type="text" class="form-control" id="componentName" required>
</div>
<div class="col-sm-6">
<label for="firstName" class="form-label">First name</label>
<input type="text" class="form-control" id="firstName" required>
</div>
</div>
<div class="row mt-3">
<div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Add</button>
</div>
<div class="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button id="testError" type="button" class="btn btn-danger">Test</button>
</div>
<div class="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button id="testNormal" type="button" class="btn btn-secondary">Test</button>
</div>
</div>
</form>
<div class="row table-responsive">
<table class="table mt-3">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First name</th>
<th scope="col">Last name</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</div>
</body>
<script src="scriptOrder.js"/>
</html>

69
front/src/products.html Normal file
View File

@ -0,0 +1,69 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Продукты</title>
<script type="module" src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<div class="container">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="index.html">Заказы</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-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">
<li class="nav-item">
<a class="nav-link" href="components.html">Компоненты</a>
</li>
<li class="nav-item">
<a class="nav-link" href="products.html">Продукты</a>
</li>
</ul>
</div>
</nav>
<form id="form">
<div class="row mt-3">
<div class="col-sm-6">
<label for="lastName" class="form-label">Last name</label>
<input type="text" class="form-control" id="lastName" required>
</div>
<div class="col-sm-6">
<label for="firstName" class="form-label">First name</label>
<input type="text" class="form-control" id="firstName" required>
</div>
</div>
<div class="row mt-3">
<div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Add</button>
</div>
<div class="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button id="testError" type="button" class="btn btn-danger">Test</button>
</div>
<div class="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button id="testNormal" type="button" class="btn btn-secondary">Test</button>
</div>
</div>
</form>
<div class="row table-responsive">
<table id="table" class="table mt-3">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First name</th>
<th scope="col">Last name</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</div>
</body>
<script src="scriptProduct.js"/>
</html>

View File

@ -0,0 +1,78 @@
"use strict";
window.addEventListener('DOMContentLoaded', function () {
const host = "http://localhost:8080";
const table = document.getElementById("tbody");
const form = document.getElementById("form");
const componentNameInput = document.getElementById("componentName");
const priceInput = document.getElementById("price");
const isEdit = false;
const getData = async function () {
table.innerHTML = "";
const response = await fetch(host + "/component");
const data = await response.json();
data.forEach(Component => {
table.innerHTML +=
`<tr>
<th scope="row" id="componentId">${Component.id}</th>
<td>${Component.price}</td>
<td>${Component.componentName}</td>
<td><button onsubmit="edit">edit</button></td>
</tr>`;
})
}
const create = async function (price, componentName) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/component?price=${price}&name=${componentName}`, requestParams);
return await response.json();
}
const test = async function (testObject) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(testObject),
};
const response = await fetch(host + "/test", requestParams);
if (response.status === 200) {
const data = await response.json();
alert(`TestDto=[id=${data.id}, name=${data.name}, data=${data.data}]`);
}
if (response.status === 400) {
const data = await response.text();
alert(data);
}
}
function edit(){
alert('хуй');
}
form.addEventListener("submit", function (event) {
event.preventDefault();
create(priceInput.value, componentNameInput.value).then((result) => {
getData();
priceInput.value = "";
componentNameInput.value = "";
alert(`Component[id=${result.id}, price=${result.price}, componentName=${result.componentName}]`);
});
});
table.addEventListener("edit", function (event) {
event.preventDefault();
alert('хуй');
create(priceInput.value, componentNameInput.value).then((result) => {
getData();
priceInput.value = "";
componentNameInput.value = "";
alert(`Component[id=${result.id}, price=${result.price}, componentName=${result.componentName}]`);
});
});
getData();
});

75
front/src/scriptOrder.js Normal file
View File

@ -0,0 +1,75 @@
"use strict";
window.addEventListener('DOMContentLoaded', function () {
const host = "http://localhost:8080";
const table = document.getElementById("tbody");
const form = document.getElementById("form");
const lastNameInput = document.getElementById("componentName");
const firstNameInput = document.getElementById("firstName");
const testErrorBtn = document.getElementById("testError");
const testNormalBtn = document.getElementById("testNormal");
const getData = async function () {
table.innerHTML = "";
const response = await fetch(host + "/student");
const data = await response.json();
data.forEach(student => {
table.innerHTML +=
`<tr>
<th scope="row">${student.id}</th>
<td>${student.firstName}</td>
<td>${student.lastName}</td>
</tr>`;
})
}
const create = async function (firstName, lastName) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/student?firstName=${firstName}&lastName=${lastName}`, requestParams);
return await response.json();
}
const test = async function (testObject) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(testObject),
};
const response = await fetch(host + "/test", requestParams);
if (response.status === 200) {
const data = await response.json();
alert(`TestDto=[id=${data.id}, name=${data.name}, data=${data.data}]`);
}
if (response.status === 400) {
const data = await response.text();
alert(data);
}
}
form.addEventListener("submit", function (event) {
event.preventDefault();
create(firstNameInput.value, lastNameInput.value).then((result) => {
getData();
firstNameInput.value = "";
lastNameInput.value = "";
alert(`Student[id=${result.id}, firstName=${result.firstName}, lastName=${result.lastName}]`);
});
});
testErrorBtn.addEventListener("click", function () {
test({});
});
testNormalBtn.addEventListener("click", function () {
test({id: 10, name: "test"});
});
getData();
});

View File

View File

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

View File

@ -22,7 +22,9 @@ public class OrderController {
@RequestParam("price") Integer price, @RequestParam("price") Integer price,
@RequestParam("count") Integer[] count, @RequestParam("count") Integer[] count,
@RequestParam("prod") Long[] prod){ @RequestParam("prod") Long[] prod){
return new OrderDTO(orderService.addOrder(date, price, count, productService.findFiltredProducts(prod))); final Order order = orderService.addOrder(date, price);
orderService.addOrderProducts(orderService.findOrder(order.getId()), count, productService.findFiltredProducts(prod));
return new OrderDTO(order);
} }
@PutMapping("/{id}") @PutMapping("/{id}")
public OrderDTO updateOrder(@PathVariable Long id, public OrderDTO updateOrder(@PathVariable Long id,
@ -30,7 +32,8 @@ public class OrderController {
@RequestParam("price") Integer price, @RequestParam("price") Integer price,
@RequestParam("count") Integer[] count, @RequestParam("count") Integer[] count,
@RequestParam("prod") Long[] prod){ @RequestParam("prod") Long[] prod){
return new OrderDTO(orderService.updateOrder(id, date, price, count, productService.findFiltredProducts(prod))); orderService.updateOrder(id, date, price, count, productService.findFiltredProducts(prod));
return new OrderDTO(orderService.update(orderService.findOrder(id),orderService.getOrderProducts(orderService.findOrder(id)), orderService.getOrderProducts(orderService.findOrder(id)).stream().map(p -> p.getId().getProductId()).toList(), count, productService.findFiltredProducts(prod)));
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public OrderDTO removeOrder(@PathVariable Long id){ public OrderDTO removeOrder(@PathVariable Long id){

View File

@ -23,7 +23,9 @@ public class ProductController {
@RequestParam("price") Integer price, @RequestParam("price") Integer price,
@RequestParam("count") Integer[] count, @RequestParam("count") Integer[] count,
@RequestParam("comp") Long[] comp){ @RequestParam("comp") Long[] comp){
return new ProductDTO(productService.addProduct(name, price, count, componentService.findFiltredComponents(comp))); final Product product = productService.addProduct(name, price);
productService.addProductComponents(productService.findProduct(product.getId()), count, componentService.findFiltredComponents(comp));
return new ProductDTO(product);
} }
@PutMapping("/{id}") @PutMapping("/{id}")
public ProductDTO updateProduct(@PathVariable Long id, public ProductDTO updateProduct(@PathVariable Long id,
@ -31,7 +33,8 @@ public class ProductController {
@RequestParam("price") Integer price, @RequestParam("price") Integer price,
@RequestParam("count") Integer[] count, @RequestParam("count") Integer[] count,
@RequestParam("comp") Long[] comp){ @RequestParam("comp") Long[] comp){
return new ProductDTO(productService.updateProduct(id, name, price, count, componentService.findFiltredComponents(comp))); productService.updateProduct(id, name, price, count, componentService.findFiltredComponents(comp));
return new ProductDTO(productService.update(productService.findProduct(id),productService.getProductComponents(productService.findProduct(id)), productService.getProductComponents(productService.findProduct(id)).stream().map(p -> p.getId().getComponentId()).toList(), count, componentService.findFiltredComponents(comp)));
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public ProductDTO removeProduct(@PathVariable Long id){ public ProductDTO removeProduct(@PathVariable Long id){

View File

@ -3,6 +3,7 @@ package ip.labwork.shop.model;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*; import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -17,7 +18,7 @@ public class Component {
@NotBlank(message = "ComponentName can't be null or empty") @NotBlank(message = "ComponentName can't be null or empty")
@Column(name = "name") @Column(name = "name")
private String componentName; private String componentName;
@NotBlank(message = "Price can't be null or empty") @NotNull(message= "Price may not be empty")
@Column(name = "price") @Column(name = "price")
private Integer price; private Integer price;

View File

@ -2,6 +2,7 @@ package ip.labwork.shop.model;
import jakarta.persistence.*; import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
@ -14,10 +15,10 @@ public class Order {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@NotBlank(message = "Date can't be null or empty") @NotNull(message = "Date can't be null or empty")
@Column(name = "date") @Column(name = "date")
private Date date; private Date date;
@NotBlank(message = "Price can't be null or empty") @NotNull(message = "Price can't be null or empty")
@Column(name = "price") @Column(name = "price")
private Integer price; private Integer price;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, fetch = FetchType.EAGER) @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, fetch = FetchType.EAGER)

View File

@ -3,6 +3,7 @@ package ip.labwork.shop.model;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*; import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
@Entity @Entity
@Table(name = "order_product") @Table(name = "order_product")
@ -18,7 +19,7 @@ public class OrderProducts {
@JoinColumn(name = "order_id") @JoinColumn(name = "order_id")
@JsonIgnore @JsonIgnore
private Order order; private Order order;
@NotBlank(message = "Count can't be null or empty") @NotNull(message = "Count can't be null or empty")
@Column(name = "count") @Column(name = "count")
private Integer count; private Integer count;
@ -61,7 +62,12 @@ public class OrderProducts {
public Integer getCount() { public Integer getCount() {
return count; return count;
} }
public void remove(){
order.getProducts().remove(this);
order = null;
product.getOrders().remove(this);
product = null;
}
public void setCount(Integer count) { public void setCount(Integer count) {
this.count = count; this.count = count;
} }

View File

@ -3,6 +3,7 @@ package ip.labwork.shop.model;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*; import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -17,7 +18,7 @@ public class Product {
@NotBlank(message = "ProductName can't be null or empty") @NotBlank(message = "ProductName can't be null or empty")
@Column(name = "name") @Column(name = "name")
private String productName; private String productName;
@NotBlank(message = "Price can't be null or empty") @NotNull(message = "Price can't be null or empty")
@Column(name = "price") @Column(name = "price")
private Integer price; private Integer price;

View File

@ -3,22 +3,23 @@ package ip.labwork.shop.model;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*; import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
@Entity @Entity
@Table(name = "product_component") @Table(name = "product_component")
public class ProductComponents { public class ProductComponents {
@EmbeddedId @EmbeddedId
private ProductComponentsKey id; private ProductComponentsKey id;
@ManyToOne @ManyToOne(cascade = CascadeType.ALL)
@MapsId("componentId") @MapsId("componentId")
@JoinColumn(name = "component_id") @JoinColumn(name = "component_id")
private Component component; private Component component;
@ManyToOne @ManyToOne(cascade = CascadeType.ALL)
@MapsId("productId") @MapsId("productId")
@JoinColumn(name = "product_id") @JoinColumn(name = "product_id")
@JsonIgnore @JsonIgnore
private Product product; private Product product;
@NotBlank(message = "Count can't be null or empty") @NotNull(message = "Count can't be null or empty")
@Column(name = "count") @Column(name = "count")
private Integer count; private Integer count;
@ -33,7 +34,6 @@ public class ProductComponents {
this.product = product; this.product = product;
this.count = count; this.count = count;
} }
public ProductComponentsKey getId() { public ProductComponentsKey getId() {
return id; return id;
} }
@ -65,4 +65,20 @@ public class ProductComponents {
public void setCount(Integer count) { public void setCount(Integer count) {
this.count = 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

@ -3,6 +3,7 @@ package ip.labwork.shop.repository;
import ip.labwork.shop.model.ProductComponents; import ip.labwork.shop.model.ProductComponents;
import ip.labwork.shop.model.ProductComponentsKey; import ip.labwork.shop.model.ProductComponentsKey;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List; import java.util.List;

View File

@ -8,6 +8,7 @@ import ip.labwork.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@ -73,7 +74,12 @@ public class ComponentService {
} }
@Transactional @Transactional
public void deleteAllComponent() { public void deleteAllComponent() {
productComponentRepository.findAll().forEach(ProductComponents::remove);
productComponentRepository.deleteAll(); productComponentRepository.deleteAll();
componentRepository.deleteAll(); componentRepository.deleteAll();
} }
public void test() {
int s =5;
}
} }

View File

@ -23,20 +23,22 @@ public class OrderService {
this.orderProductRepository = orderProductRepository; this.orderProductRepository = orderProductRepository;
} }
@Transactional @Transactional
public Order addOrder(String date, Integer price, Integer[] count, List<Product> products) { public Order addOrder(String date, Integer price) {
Date correctDate = getDate(date); Date correctDate = getDate(date);
final Order order = new Order(correctDate, price); final Order order = new Order(correctDate, price);
validatorUtil.validate(order); validatorUtil.validate(order);
orderRepository.save(order); orderRepository.save(order);
return order;
}
@Transactional
public void addOrderProducts(Order order, Integer[] count, List<Product> products){
for (int i = 0; i < products.size(); i++) { for (int i = 0; i < products.size(); i++) {
final OrderProducts orderProducts = new OrderProducts(order, products.get(i), count[i]); final OrderProducts orderProducts = new OrderProducts(order, products.get(i), count[i]);
order.addProduct(orderProducts); order.addProduct(orderProducts);
products.get(i).addOrder(orderProducts); products.get(i).addOrder(orderProducts);
orderProductRepository.save(orderProducts); orderProductRepository.save(orderProducts);
} }
return order;
} }
public Date getDate(String date) { public Date getDate(String date) {
SimpleDateFormat format = new SimpleDateFormat(); SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("dd.MM.yyyy"); format.applyPattern("dd.MM.yyyy");
@ -60,7 +62,7 @@ public class OrderService {
return orderRepository.findAll(); return orderRepository.findAll();
} }
@Transactional /*@Transactional
public Order updateOrder(Long id, String date, Integer price, Integer[] count, List<Product> products) { public Order updateOrder(Long id, String date, Integer price, Integer[] count, List<Product> products) {
final Order currentOrder = findOrder(id); final Order currentOrder = findOrder(id);
currentOrder.setDate(getDate(date)); currentOrder.setDate(getDate(date));
@ -90,8 +92,54 @@ public class OrderService {
orderProductRepository.delete(orderProductsList.get(i)); orderProductRepository.delete(orderProductsList.get(i));
} }
return currentOrder; return currentOrder;
} }*/
@Transactional
public Order updateOrder(Long id, String date, Integer price, Integer[] count, List<Product> products) {
final Order currentOrder = findOrder(id);
currentOrder.setDate(getDate(date));
currentOrder.setPrice(price);
validatorUtil.validate(currentOrder);
orderRepository.save(currentOrder);
List<OrderProducts> orderProductsList = orderProductRepository.getOrderProductsByOrderId(id);
List<Long> product_id = new ArrayList<>(orderProductsList.stream().map(p -> p.getId().getProductId()).toList());
for (int i = 0; i < products.size(); i++) {
final Long currentId = products.get(i).getId();
if (product_id.contains(currentId)) {
final OrderProducts orderProducts = orderProductsList.stream().filter(x -> Objects.equals(x.getId().getProductId(), currentId)).toList().get(0);
orderProductsList.remove(orderProducts);
product_id.remove(products.get(i).getId());
orderProducts.setCount(count[i]);
orderProductRepository.save(orderProducts);
}
}
for (int i = 0; i < orderProductsList.size(); i++) {
orderProductsList.get(i).getProduct().removeOrder(orderProductsList.get(i));
orderProductsList.get(i).getOrder().removeProducts(orderProductsList.get(i));
orderProductRepository.delete(orderProductsList.get(i));
}
return currentOrder;
}
@Transactional
public Order update(Order currentOrder, List<OrderProducts> orderProductsList, List<Long> product_id, Integer[] count, List<Product> products) {
for (int i = 0; i < products.size(); i++) {
final Long currentId = products.get(i).getId();
if (product_id.contains(currentId)) {
orderProductsList.remove(orderProductsList.stream().filter(x -> Objects.equals(x.getId().getProductId(), currentId)).toList().get(0));
product_id.remove(products.get(i).getId());
}
else {
final OrderProducts orderProducts = new OrderProducts(currentOrder, products.get(i), count[i]);
currentOrder.addProduct(orderProducts);
products.get(i).addOrder(orderProducts);
orderProductRepository.save(orderProducts);
}
}
return currentOrder;
}
public List<OrderProducts> getOrderProducts(Order currentOrder){
return orderProductRepository.getOrderProductsByOrderId(currentOrder.getId());
}
@Transactional @Transactional
public Order deleteOrder(Long id) { public Order deleteOrder(Long id) {
final Order currentOrder = findOrder(id); final Order currentOrder = findOrder(id);
@ -107,6 +155,7 @@ public class OrderService {
} }
@Transactional @Transactional
public void deleteAllOrder() { public void deleteAllOrder() {
orderProductRepository.findAll().forEach(OrderProducts::remove);
orderProductRepository.deleteAll(); orderProductRepository.deleteAll();
orderRepository.deleteAll(); orderRepository.deleteAll();
} }

View File

@ -23,29 +23,33 @@ public class ProductService {
private final ProductRepository productRepository; private final ProductRepository productRepository;
private final ProductComponentRepository productComponentRepository; private final ProductComponentRepository productComponentRepository;
private final OrderProductRepository orderProductRepository; private final OrderProductRepository orderProductRepository;
private final ComponentRepository componentRepository;
private final ValidatorUtil validatorUtil; private final ValidatorUtil validatorUtil;
public ProductService(ProductRepository productRepository, public ProductService(ProductRepository productRepository,
ValidatorUtil validatorUtil, ProductComponentRepository productComponentRepository, OrderProductRepository orderProductRepository) { ValidatorUtil validatorUtil, ProductComponentRepository productComponentRepository, OrderProductRepository orderProductRepository, ComponentRepository componentRepository) {
this.productRepository = productRepository; this.productRepository = productRepository;
this.validatorUtil = validatorUtil; this.validatorUtil = validatorUtil;
this.productComponentRepository = productComponentRepository; this.productComponentRepository = productComponentRepository;
this.orderProductRepository = orderProductRepository; this.orderProductRepository = orderProductRepository;
this.componentRepository = componentRepository;
} }
@Transactional @Transactional
public Product addProduct(String productName, Integer price, Integer[] count, List<Component> components) { public Product addProduct(String productName, Integer price) {
final Product product = new Product(productName, price); final Product product = new Product(productName, price);
validatorUtil.validate(product); validatorUtil.validate(product);
productRepository.save(product); productRepository.save(product);
return product;
}
@Transactional
public void addProductComponents(Product product, Integer[] count, List<Component> components){
for (int i = 0; i < components.size(); i++) { for (int i = 0; i < components.size(); i++) {
final ProductComponents productComponents = new ProductComponents(components.get(i), product, count[i]); final ProductComponents productComponents = new ProductComponents(components.get(i), product, count[i]);
product.addComponent(productComponents); product.addComponent(productComponents);
components.get(i).addProduct(productComponents); components.get(i).addProduct(productComponents);
productComponentRepository.save(productComponents); productComponentRepository.saveAndFlush(productComponents);
} }
return product;
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public Product findProduct(Long id) { public Product findProduct(Long id) {
final Optional<Product> product = productRepository.findById(id); final Optional<Product> product = productRepository.findById(id);
@ -57,6 +61,38 @@ public class ProductService {
return productRepository.findAll(); return productRepository.findAll();
} }
/*@Transactional
public Product updateProduct(Long id, String productName, Integer price, Integer[] count, List<Component> components) {
final Product currentProduct = findProduct(id);
currentProduct.setProductName(productName);
currentProduct.setPrice(price);
validatorUtil.validate(currentProduct);
productRepository.save(currentProduct);
List<ProductComponents> productComponentsList = productComponentRepository.getProductComponentsByProductId(id);
List<Long> component_id = new ArrayList<>(productComponentsList.stream().map(p -> p.getId().getComponentId()).toList());
for (int i = 0; i < components.size(); i++) {
final Long currentId = components.get(i).getId();
if (component_id.contains(currentId)) {
final ProductComponents productComponents = productComponentsList.stream().filter(x -> Objects.equals(x.getId().getComponentId(), currentId)).toList().get(0);
productComponentsList.remove(productComponents);
component_id.remove(components.get(i).getId());
productComponents.setCount(count[i]);
productComponentRepository.saveAndFlush(productComponents);
}
else {
final ProductComponents productComponents = new ProductComponents(components.get(i), currentProduct, count[i]);
currentProduct.addComponent(productComponents);
components.get(i).addProduct(productComponents);
productComponentRepository.save(productComponents);
}
}
for (int i = 0; i < productComponentsList.size(); i++) {
productComponentsList.get(i).getComponent().removeProduct(productComponentsList.get(i));
productComponentsList.get(i).getProduct().removeComponent(productComponentsList.get(i));
productComponentRepository.delete(productComponentsList.get(i));
}
return currentProduct;
}*/
@Transactional @Transactional
public Product updateProduct(Long id, String productName, Integer price, Integer[] count, List<Component> components) { public Product updateProduct(Long id, String productName, Integer price, Integer[] count, List<Component> components) {
final Product currentProduct = findProduct(id); final Product currentProduct = findProduct(id);
@ -73,12 +109,7 @@ public class ProductService {
productComponentsList.remove(productComponents); productComponentsList.remove(productComponents);
component_id.remove(components.get(i).getId()); component_id.remove(components.get(i).getId());
productComponents.setCount(count[i]); productComponents.setCount(count[i]);
productComponentRepository.save(productComponents); productComponentRepository.saveAndFlush(productComponents);
} else {
final ProductComponents productComponents = new ProductComponents(components.get(i), currentProduct, count[i]);
currentProduct.addComponent(productComponents);
components.get(i).addProduct(productComponents);
productComponentRepository.save(productComponents);
} }
} }
for (int i = 0; i < productComponentsList.size(); i++) { for (int i = 0; i < productComponentsList.size(); i++) {
@ -88,7 +119,29 @@ public class ProductService {
} }
return currentProduct; return currentProduct;
} }
@Transactional
public Product update(Product currentProduct, List<ProductComponents> productComponentsList, List<Long> component_id, Integer[] count, List<Component> components) {
for (int i = 0; i < components.size(); i++) {
final Long currentId = components.get(i).getId();
if (component_id.contains(currentId)) {
productComponentsList.remove(productComponentsList.stream().filter(x -> Objects.equals(x.getId().getComponentId(), currentId)).toList().get(0));
component_id.remove(components.get(i).getId());
}
else {
final ProductComponents productComponents = new ProductComponents(components.get(i), currentProduct, count[i]);
currentProduct.addComponent(productComponents);
components.get(i).addProduct(productComponents);
productComponentRepository.save(productComponents);
}
}
return currentProduct;
}
public List<ProductComponents> getProductComponents(Product currentProduct){
return productComponentRepository.getProductComponentsByProductId(currentProduct.getId());
}
public void test(){
int s =5;
}
@Transactional @Transactional
public Product deleteProduct(Long id) { public Product deleteProduct(Long id) {
final Product currentProduct = findProduct(id); final Product currentProduct = findProduct(id);
@ -112,6 +165,8 @@ public class ProductService {
@Transactional @Transactional
public void deleteAllProduct() { public void deleteAllProduct() {
orderProductRepository.findAll().forEach(OrderProducts::remove);
productComponentRepository.findAll().forEach(ProductComponents::remove);
productComponentRepository.deleteAll(); productComponentRepository.deleteAll();
orderProductRepository.deleteAll(); orderProductRepository.deleteAll();
productRepository.deleteAll(); productRepository.deleteAll();

View File

@ -3,9 +3,7 @@ package ip.labwork;
import ip.labwork.shop.model.Component; import ip.labwork.shop.model.Component;
import ip.labwork.shop.model.Order; import ip.labwork.shop.model.Order;
import ip.labwork.shop.model.Product; import ip.labwork.shop.model.Product;
import ip.labwork.shop.service.ComponentService; import ip.labwork.shop.service.*;
import ip.labwork.shop.service.OrderService;
import ip.labwork.shop.service.ProductService;
import jakarta.persistence.EntityNotFoundException; import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -39,13 +37,17 @@ public class JpaStudentTests {
List<Component> componentList = new ArrayList<>(); List<Component> componentList = new ArrayList<>();
componentList.add(componentService.findComponent(component.getId())); componentList.add(componentService.findComponent(component.getId()));
final Product product = productService.addProduct("Бургер", 100, new Integer[]{ 2 }, componentList);
final Product product = productService.addProduct("Бургер", 100);
productService.addProductComponents(productService.findProduct(product.getId()), new Integer[]{ 2}, componentList );
log.info(product.toString()); log.info(product.toString());
Assertions.assertNotNull(product.getId()); Assertions.assertNotNull(product.getId());
List<Product> productList = new ArrayList<>(); List<Product> productList = new ArrayList<>();
productList.add(productService.findProduct(product.getId())); productList.add(productService.findProduct(product.getId()));
final Order order = orderService.addOrder(new Date().toString(), 200, new Integer[]{ 3 }, productList);
final Order order = orderService.addOrder(new Date().toString(), 200);
orderService.addOrderProducts(orderService.findOrder(order.getId()), new Integer[]{ 2 }, productList);
log.info(order.toString()); log.info(order.toString());
Assertions.assertNotNull(order.getId()); Assertions.assertNotNull(order.getId());
@ -75,19 +77,18 @@ public class JpaStudentTests {
log.info(orders.toString()); log.info(orders.toString());
Assertions.assertEquals(orders.size(), 1); Assertions.assertEquals(orders.size(), 1);
//TestReadNotFound //TestReadNotFound
componentService.deleteAllComponent(); componentService.deleteAllComponent();
productService.deleteAllProduct(); productService.deleteAllProduct();
orderService.deleteAllOrder(); orderService.deleteAllOrder();
Assertions.assertThrows(ComponentNotFoundException.class, () -> componentService.findComponent(-1L));
Assertions.assertThrows(EntityNotFoundException.class, () -> componentService.findComponent(-1L)); Assertions.assertThrows(ProductNotFoundException.class, () -> productService.findProduct(-1L));
Assertions.assertThrows(EntityNotFoundException.class, () -> productService.findProduct(-1L)); Assertions.assertThrows(OrderNotFoundException.class, () -> orderService.findOrder(-1L));
Assertions.assertThrows(EntityNotFoundException.class, () -> orderService.findOrder(-1L));
//TestReadAllEmpty //TestReadAllEmpty
final List<Component> newComponents = componentService.findAllComponent(); final List<Component> newComponents = componentService.findAllComponent();
log.info(newComponents.toString()); log.info(newComponents.toString());
productService.test();
Assertions.assertEquals(newComponents.size(), 0); Assertions.assertEquals(newComponents.size(), 0);
final List<Product> newProducts = productService.findAllProduct(); final List<Product> newProducts = productService.findAllProduct();