Фронт халф hp

This commit is contained in:
Nikita Sergeev 2023-03-27 00:59:07 +04:00
parent 08a82d3f06
commit 686c5db7bf
10 changed files with 227 additions and 67 deletions

View File

@ -27,26 +27,30 @@
</ul> </ul>
</div> </div>
</nav> </nav>
<form id="form"> <form id="form" novalidate>
<div class="row mt-3"> <div class="row mt-3">
<div class="col-sm-6"> <div class="col-sm-4">
<label for="componentId" class="form-label">ИД компонента</label>
<input type="text" class="form-control" id="componentId" required>
</div>
<div class="col-sm-4">
<label for="componentName" class="form-label">Название компонента</label> <label for="componentName" class="form-label">Название компонента</label>
<input type="text" class="form-control" id="componentName" required> <input type="text" class="form-control" id="componentName" required>
</div> </div>
<div class="col-sm-6"> <div class="col-sm-4">
<label for="price" class="form-label">Цена</label> <label for="price" class="form-label">Цена</label>
<input type="text" class="form-control" id="price" required> <input type="text" class="form-control" id="price" required>
</div> </div>
</div> </div>
<div class="row mt-3"> <div class="row mt-3">
<div class="d-grid col-sm-4 mx-auto"> <div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Add</button> <button type="submit" class="btn btn-success">Добавить</button>
</div> </div>
<div class="d-grid col-sm-4 mx-auto"> <div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Update</button> <button type="submit" class="btn btn-success" id="btnUpdate" >Обновить</button>
</div> </div>
<div class="d-grid col-sm-4 mx-auto"> <div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Delete</button> <button id="btnRemove" class="btn btn-success">Удалить</button>
</div> </div>
</div> </div>
</form> </form>
@ -54,9 +58,9 @@
<table id="table" class="table mt-3"> <table id="table" class="table mt-3">
<thead> <thead>
<tr> <tr>
<th scope="col">#</th> <th scope="col">ИД</th>
<th scope="col">First name</th> <th scope="col">Название компонента</th>
<th scope="col">Last name</th> <th scope="col">Цена</th>
</tr> </tr>
</thead> </thead>
<tbody id="tbody"> <tbody id="tbody">

View File

@ -27,26 +27,38 @@
</ul> </ul>
</div> </div>
</nav> </nav>
<form id="form"> <form id="form" novalidate>
<div class="row mt-3"> <div class="row mt-3">
<div class="col-sm-6"> <div class="col-sm-4">
<label for="lastName" class="form-label">Last name</label> <label for="productId" class="form-label">ИД продукта</label>
<input type="text" class="form-control" id="lastName" required> <input type="text" class="form-control" id="productId" required>
</div> </div>
<div class="col-sm-6"> <div class="col-sm-4">
<label for="firstName" class="form-label">First name</label> <label for="productName" class="form-label">Название продукта</label>
<input type="text" class="form-control" id="firstName" required> <input type="text" class="form-control" id="productName" required>
</div>
<div class="col-sm-4">
<label for="productPrice" class="form-label">Цена</label>
<input type="text" class="form-control" id="productPrice" required>
</div>
<div class="col-sm-4">
<label for="componentId" class="form-label">ИД компонента</label>
<input type="text" class="form-control" id="componentId" required>
</div>
<div class="col-sm-4">
<label for="componentCount" class="form-label">Количество компонента</label>
<input type="text" class="form-control" id="componentCount" required>
</div> </div>
</div> </div>
<div class="row mt-3"> <div class="row mt-3">
<div class="d-grid col-sm-4 mx-auto"> <div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Add</button> <button type="submit" class="btn btn-success">Добавить</button>
</div> </div>
<div class="d-grid col-sm-4 mx-auto mt-3 mt-sm-0"> <div class="d-grid col-sm-4 mx-auto">
<button id="testError" type="button" class="btn btn-danger">Test</button> <button type="submit" class="btn btn-success" id="btnUpdate" >Обновить</button>
</div> </div>
<div class="d-grid col-sm-4 mx-auto mt-3 mt-sm-0"> <div class="d-grid col-sm-4 mx-auto">
<button id="testNormal" type="button" class="btn btn-secondary">Test</button> <button id="btnRemove" class="btn btn-success">Удалить</button>
</div> </div>
</div> </div>
</form> </form>
@ -54,9 +66,10 @@
<table id="table" class="table mt-3"> <table id="table" class="table mt-3">
<thead> <thead>
<tr> <tr>
<th scope="col">#</th> <th scope="col">ИД</th>
<th scope="col">First name</th> <th scope="col">Название продукта</th>
<th scope="col">Last name</th> <th scope="col">Цена</th>
<th scope="col">Компоненты</th>
</tr> </tr>
</thead> </thead>
<tbody id="tbody"> <tbody id="tbody">

View File

@ -6,7 +6,9 @@ window.addEventListener('DOMContentLoaded', function () {
const form = document.getElementById("form"); const form = document.getElementById("form");
const componentNameInput = document.getElementById("componentName"); const componentNameInput = document.getElementById("componentName");
const priceInput = document.getElementById("price"); const priceInput = document.getElementById("price");
const isEdit = false; const componentIdInput = document.getElementById("componentId");
const buttonRemove = document.getElementById("btnRemove");
const buttonUpdate = document.getElementById("btnUpdate");
const getData = async function () { const getData = async function () {
table.innerHTML = ""; table.innerHTML = "";
const response = await fetch(host + "/component"); const response = await fetch(host + "/component");
@ -15,9 +17,8 @@ window.addEventListener('DOMContentLoaded', function () {
table.innerHTML += table.innerHTML +=
`<tr> `<tr>
<th scope="row" id="componentId">${Component.id}</th> <th scope="row" id="componentId">${Component.id}</th>
<td>${Component.price}</td>
<td>${Component.componentName}</td> <td>${Component.componentName}</td>
<td><button onsubmit="edit">edit</button></td> <td>${Component.price}</td>
</tr>`; </tr>`;
}) })
} }
@ -33,27 +34,59 @@ window.addEventListener('DOMContentLoaded', function () {
return await response.json(); return await response.json();
} }
const test = async function (testObject) { const remove = async function (){
console.info('Try to remove item');
if (itemId.value !== 0) {
if (!confirm('Do you really want to remove this item?')) {
console.info('Canceled');
return;
}
}
const requestParams = { const requestParams = {
method: "POST", method: "DELETE",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, }
body: JSON.stringify(testObject),
}; };
const response = await fetch(host + "/test", requestParams); const response = await fetch(host + `/component/` + itemId.value, requestParams);
if (response.status === 200) { return await response.json();
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(); const update = async function (){
alert(data); console.info('Try to update item');
if (componentIdInput.value === 0 || componentNameInput.value == null || priceInput.value === 0) {
return;
} }
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
} }
function edit(){ };
alert('хуй'); const response = await fetch(host + `/component/${componentIdInput.value}?price=${priceInput.value}&name=${componentNameInput.value}`, requestParams);
return await response.json();
} }
buttonRemove.addEventListener('click', function (event){
event.preventDefault();
remove().then((result) => {
getData()
componentIdInput.value = "";
priceInput.value = "";
componentNameInput.value = "";
});
});
buttonUpdate.addEventListener('click', function (event){
event.preventDefault();
update().then((result) => {
getData()
componentIdInput.value = "";
priceInput.value = "";
componentNameInput.value = "";
});
});
form.addEventListener("submit", function (event) { form.addEventListener("submit", function (event) {
event.preventDefault(); event.preventDefault();
create(priceInput.value, componentNameInput.value).then((result) => { create(priceInput.value, componentNameInput.value).then((result) => {
@ -63,16 +96,5 @@ window.addEventListener('DOMContentLoaded', function () {
alert(`Component[id=${result.id}, price=${result.price}, componentName=${result.componentName}]`); 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(); getData();
}); });

View File

@ -0,0 +1,106 @@
"use strict";
window.addEventListener('DOMContentLoaded', function () {
const host = "http://localhost:8080";
const table = document.getElementById("tbody");
const form = document.getElementById("form");
const productIdInpit = document.getElementById("productId");
const productNameInput = document.getElementById("productName");
const priceInput = document.getElementById("productPrice");
const componentIdInput = document.getElementById("componentId");
const componentCountInput = document.getElementById("componentCount");
const buttonRemove = document.getElementById("btnRemove");
const buttonUpdate = document.getElementById("btnUpdate");
const getData = async function () {
table.innerHTML = "";
const response = await fetch(host + "/product");
const data = await response.json();
data.forEach(Product => {
let temp = "<select>";
Product.componentDTOList.forEach(Component => {
temp += `<option>${Component.componentName + " " + Component.count}</option>>`
})
temp += "</select>"
table.innerHTML +=
`<tr>
<th scope="row">${Product.id}</th>
<td>${Product.productName}</td>
<td>${Product.price}</td>
<td>${temp}</td>
</tr>`;
})
}
const create = async function () {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/product?price=${priceInput.value}&name=${productNameInput.value}&count=${componentCountInput.value}&comp=${componentIdInput.value}`, requestParams);
return await response.json();
}
const remove = async function (){
console.info('Try to remove item');
if (productIdInpit.value !== 0) {
if (!confirm('Do you really want to remove this item?')) {
console.info('Canceled');
return;
}
}
const requestParams = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/product/` + productIdInpit.value, requestParams);
return await response.json();
}
const update = async function (){
console.info('Try to update item');
if (productIdInpit.value === 0 || productNameInput.value == null || priceInput.value === 0 || componentIdInput.value === 0 || componentCountInput.value === 0) {
return;
}
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/product/${productIdInpit.value}?price=${priceInput.value}&name=${productNameInput.value}&count=${componentCountInput.value}&comp=${componentIdInput.value}`, requestParams);
return await response.json();
}
buttonRemove.addEventListener('click', function (event){
event.preventDefault();
remove().then((result) => {
getData()
productIdInpit.value = "";
});
});
buttonUpdate.addEventListener('click', function (event){
event.preventDefault();
update().then((result) => {
getData()
componentIdInput.value = "";
priceInput.value = "";
});
});
form.addEventListener("submit", function (event) {
event.preventDefault();
create().then((result) => {
getData();
priceInput.value = "";
productNameInput.value = "";
alert(`Component[id=${result.id}, price=${result.price}, componentName=${result.productName}]`);
});
});
getData();
});

View File

@ -6,12 +6,18 @@ public class ComponentDTO {
private final long id; private final long id;
private final String componentName; private final String componentName;
private final int price; private final int price;
private int count = 0;
public ComponentDTO(Component component) { public ComponentDTO(Component component) {
this.id = component.getId(); this.id = component.getId();
this.componentName = component.getComponentName(); this.componentName = component.getComponentName();
this.price = component.getPrice(); 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 long getId() { public long getId() {
return id; return id;
@ -21,6 +27,10 @@ public class ComponentDTO {
return componentName; return componentName;
} }
public int getCount() {
return count;
}
public int getPrice() { public int getPrice() {
return price; return price;
} }

View File

@ -25,7 +25,7 @@ public class ProductController {
@RequestParam("comp") Long[] comp){ @RequestParam("comp") Long[] comp){
final Product product = productService.addProduct(name, price); final Product product = productService.addProduct(name, price);
productService.addProductComponents(productService.findProduct(product.getId()), count, componentService.findFiltredComponents(comp)); productService.addProductComponents(productService.findProduct(product.getId()), count, componentService.findFiltredComponents(comp));
return new ProductDTO(product); return new ProductDTO(productService.findProduct(product.getId()));
} }
@PutMapping("/{id}") @PutMapping("/{id}")
public ProductDTO updateProduct(@PathVariable Long id, public ProductDTO updateProduct(@PathVariable Long id,
@ -38,7 +38,9 @@ public class ProductController {
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public ProductDTO removeProduct(@PathVariable Long id){ public ProductDTO removeProduct(@PathVariable Long id){
return new ProductDTO(productService.deleteProduct(id)); ProductDTO temp = new ProductDTO(productService.deleteProduct(id));
productService.test();
return null;
} }
@DeleteMapping @DeleteMapping
public void removeAllProduct(){ public void removeAllProduct(){

View File

@ -1,9 +1,12 @@
package ip.labwork.shop.controller; package ip.labwork.shop.controller;
import ip.labwork.shop.model.Product; import ip.labwork.shop.model.Product;
import ip.labwork.shop.model.ProductComponents;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors;
public class ProductDTO { public class ProductDTO {
private final long id; private final long id;
@ -15,8 +18,11 @@ public class ProductDTO {
this.id = product.getId(); this.id = product.getId();
this.productName = product.getProductName(); this.productName = product.getProductName();
this.price = product.getPrice(); this.price = product.getPrice();
this.componentDTOList = product.getComponents().stream().filter(x -> Objects.equals(x.getId().getProductId(), product.getId())).map(x -> new ComponentDTO(x.getComponent())).toList(); this.componentDTOList = product.getComponents().stream()
this.orderDTOList = product.getOrders().stream().filter(x -> Objects.equals(x.getId().getProductId(), product.getId())).map(x -> new OrderDTO(x.getOrder())).toList(); .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 long getId() { public long getId() {

View File

@ -9,12 +9,12 @@ import jakarta.validation.constraints.NotNull;
@Table(name = "product_component") @Table(name = "product_component")
public class ProductComponents { public class ProductComponents {
@EmbeddedId @EmbeddedId
private ProductComponentsKey id; private ProductComponentsKey id = new ProductComponentsKey();
@ManyToOne(cascade = CascadeType.ALL) @ManyToOne(cascade = CascadeType.MERGE)
@MapsId("componentId") @MapsId("componentId")
@JoinColumn(name = "component_id") @JoinColumn(name = "component_id")
private Component component; private Component component;
@ManyToOne(cascade = CascadeType.ALL) @ManyToOne(cascade = CascadeType.MERGE)
@MapsId("productId") @MapsId("productId")
@JoinColumn(name = "product_id") @JoinColumn(name = "product_id")
@JsonIgnore @JsonIgnore
@ -28,7 +28,6 @@ public class ProductComponents {
public ProductComponents(Component component, Product product, Integer count) { public ProductComponents(Component component, Product product, Integer count) {
this.component = component; this.component = component;
this.id = new ProductComponentsKey(product.getId(), component.getId());
this.id.setComponentId(component.getId()); this.id.setComponentId(component.getId());
this.id.setProductId(product.getId()); this.id.setProductId(product.getId());
this.product = product; this.product = product;

View File

@ -4,14 +4,12 @@ import ip.labwork.shop.model.Component;
import ip.labwork.shop.model.OrderProducts; import ip.labwork.shop.model.OrderProducts;
import ip.labwork.shop.model.Product; import ip.labwork.shop.model.Product;
import ip.labwork.shop.model.ProductComponents; import ip.labwork.shop.model.ProductComponents;
import ip.labwork.shop.repository.ComponentRepository; import ip.labwork.shop.repository.*;
import ip.labwork.shop.repository.OrderProductRepository;
import ip.labwork.shop.repository.ProductComponentRepository;
import ip.labwork.shop.repository.ProductRepository;
import ip.labwork.util.validation.ValidatorUtil; import ip.labwork.util.validation.ValidatorUtil;
import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException; import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext; import jakarta.persistence.PersistenceContext;
import org.h2.mvstore.tx.Transaction;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@ -45,6 +43,7 @@ public class ProductService {
public void addProductComponents(Product product, Integer[] count, List<Component> components){ 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]);
productComponentRepository.saveAndFlush(productComponents);
product.addComponent(productComponents); product.addComponent(productComponents);
components.get(i).addProduct(productComponents); components.get(i).addProduct(productComponents);
productComponentRepository.saveAndFlush(productComponents); productComponentRepository.saveAndFlush(productComponents);

View File

@ -45,7 +45,6 @@ public class JpaStudentTests {
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); final Order order = orderService.addOrder(new Date().toString(), 200);
orderService.addOrderProducts(orderService.findOrder(order.getId()), new Integer[]{ 2 }, productList); orderService.addOrderProducts(orderService.findOrder(order.getId()), new Integer[]{ 2 }, productList);
log.info(order.toString()); log.info(order.toString());