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

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 {
implementation(project(':Front'))
implementation(project(':front'))
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210'

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",
"main": "src/index.html",
"source": "src/index.html",
"scripts": {
"start": "parcel --port 3000",
"build": "npm run clean && parcel build",
"clean": "rimraf dist"
},
"dependencies": {
"bootstrap": "5.2.1"
"bootstrap": "5.2.3"
},
"devDependencies": {
"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'
include 'Front'
include 'front'

View File

@ -22,7 +22,9 @@ public class OrderController {
@RequestParam("price") Integer price,
@RequestParam("count") Integer[] count,
@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}")
public OrderDTO updateOrder(@PathVariable Long id,
@ -30,7 +32,8 @@ public class OrderController {
@RequestParam("price") Integer price,
@RequestParam("count") Integer[] count,
@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}")
public OrderDTO removeOrder(@PathVariable Long id){

View File

@ -23,7 +23,9 @@ public class ProductController {
@RequestParam("price") Integer price,
@RequestParam("count") Integer[] count,
@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}")
public ProductDTO updateProduct(@PathVariable Long id,
@ -31,7 +33,8 @@ public class ProductController {
@RequestParam("price") Integer price,
@RequestParam("count") Integer[] count,
@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}")
public ProductDTO removeProduct(@PathVariable Long id){

View File

@ -3,6 +3,7 @@ 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;
@ -17,7 +18,7 @@ public class Component {
@NotBlank(message = "ComponentName can't be null or empty")
@Column(name = "name")
private String componentName;
@NotBlank(message = "Price can't be null or empty")
@NotNull(message= "Price may not be empty")
@Column(name = "price")
private Integer price;

View File

@ -2,6 +2,7 @@ package ip.labwork.shop.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
@ -14,10 +15,10 @@ public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotBlank(message = "Date can't be null or empty")
@NotNull(message = "Date can't be null or empty")
@Column(name = "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")
private Integer price;
@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 jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
@Entity
@Table(name = "order_product")
@ -18,7 +19,7 @@ public class OrderProducts {
@JoinColumn(name = "order_id")
@JsonIgnore
private Order order;
@NotBlank(message = "Count can't be null or empty")
@NotNull(message = "Count can't be null or empty")
@Column(name = "count")
private Integer count;
@ -61,7 +62,12 @@ public class OrderProducts {
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

@ -3,6 +3,7 @@ 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;
@ -17,7 +18,7 @@ public class Product {
@NotBlank(message = "ProductName can't be null or empty")
@Column(name = "name")
private String productName;
@NotBlank(message = "Price can't be null or empty")
@NotNull(message = "Price can't be null or empty")
@Column(name = "price")
private Integer price;

View File

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

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

View File

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

View File

@ -23,20 +23,22 @@ public class OrderService {
this.orderProductRepository = orderProductRepository;
}
@Transactional
public Order addOrder(String date, Integer price, Integer[] count, List<Product> products) {
public Order addOrder(String date, Integer price) {
Date correctDate = getDate(date);
final Order order = new Order(correctDate, price);
validatorUtil.validate(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++) {
final OrderProducts orderProducts = new OrderProducts(order, products.get(i), count[i]);
order.addProduct(orderProducts);
products.get(i).addOrder(orderProducts);
orderProductRepository.save(orderProducts);
}
return order;
}
public Date getDate(String date) {
SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("dd.MM.yyyy");
@ -60,7 +62,7 @@ public class OrderService {
return orderRepository.findAll();
}
@Transactional
/*@Transactional
public Order updateOrder(Long id, String date, Integer price, Integer[] count, List<Product> products) {
final Order currentOrder = findOrder(id);
currentOrder.setDate(getDate(date));
@ -90,8 +92,54 @@ public class OrderService {
orderProductRepository.delete(orderProductsList.get(i));
}
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
public Order deleteOrder(Long id) {
final Order currentOrder = findOrder(id);
@ -107,6 +155,7 @@ public class OrderService {
}
@Transactional
public void deleteAllOrder() {
orderProductRepository.findAll().forEach(OrderProducts::remove);
orderProductRepository.deleteAll();
orderRepository.deleteAll();
}

View File

@ -23,29 +23,33 @@ public class ProductService {
private final ProductRepository productRepository;
private final ProductComponentRepository productComponentRepository;
private final OrderProductRepository orderProductRepository;
private final ComponentRepository componentRepository;
private final ValidatorUtil validatorUtil;
public ProductService(ProductRepository productRepository,
ValidatorUtil validatorUtil, ProductComponentRepository productComponentRepository, OrderProductRepository orderProductRepository) {
ValidatorUtil validatorUtil, ProductComponentRepository productComponentRepository, OrderProductRepository orderProductRepository, ComponentRepository componentRepository) {
this.productRepository = productRepository;
this.validatorUtil = validatorUtil;
this.productComponentRepository = productComponentRepository;
this.orderProductRepository = orderProductRepository;
this.componentRepository = componentRepository;
}
@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);
validatorUtil.validate(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++) {
final ProductComponents productComponents = new ProductComponents(components.get(i), product, count[i]);
product.addComponent(productComponents);
components.get(i).addProduct(productComponents);
productComponentRepository.save(productComponents);
productComponentRepository.saveAndFlush(productComponents);
}
return product;
}
@Transactional(readOnly = true)
public Product findProduct(Long id) {
final Optional<Product> product = productRepository.findById(id);
@ -57,6 +61,38 @@ public class ProductService {
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
public Product updateProduct(Long id, String productName, Integer price, Integer[] count, List<Component> components) {
final Product currentProduct = findProduct(id);
@ -73,12 +109,7 @@ public class ProductService {
productComponentsList.remove(productComponents);
component_id.remove(components.get(i).getId());
productComponents.setCount(count[i]);
productComponentRepository.save(productComponents);
} else {
final ProductComponents productComponents = new ProductComponents(components.get(i), currentProduct, count[i]);
currentProduct.addComponent(productComponents);
components.get(i).addProduct(productComponents);
productComponentRepository.save(productComponents);
productComponentRepository.saveAndFlush(productComponents);
}
}
for (int i = 0; i < productComponentsList.size(); i++) {
@ -88,7 +119,29 @@ public class ProductService {
}
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
public Product deleteProduct(Long id) {
final Product currentProduct = findProduct(id);
@ -112,6 +165,8 @@ public class ProductService {
@Transactional
public void deleteAllProduct() {
orderProductRepository.findAll().forEach(OrderProducts::remove);
productComponentRepository.findAll().forEach(ProductComponents::remove);
productComponentRepository.deleteAll();
orderProductRepository.deleteAll();
productRepository.deleteAll();

View File

@ -3,9 +3,7 @@ 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.ComponentService;
import ip.labwork.shop.service.OrderService;
import ip.labwork.shop.service.ProductService;
import ip.labwork.shop.service.*;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -39,13 +37,17 @@ public class JpaStudentTests {
List<Component> componentList = new ArrayList<>();
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());
Assertions.assertNotNull(product.getId());
List<Product> productList = new ArrayList<>();
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());
Assertions.assertNotNull(order.getId());
@ -75,19 +77,18 @@ public class JpaStudentTests {
log.info(orders.toString());
Assertions.assertEquals(orders.size(), 1);
//TestReadNotFound
componentService.deleteAllComponent();
productService.deleteAllProduct();
orderService.deleteAllOrder();
Assertions.assertThrows(EntityNotFoundException.class, () -> componentService.findComponent(-1L));
Assertions.assertThrows(EntityNotFoundException.class, () -> productService.findProduct(-1L));
Assertions.assertThrows(EntityNotFoundException.class, () -> orderService.findOrder(-1L));
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();