Надеюсь работает

This commit is contained in:
Katerina881 2023-03-27 17:33:09 +04:00
parent 686c5db7bf
commit c57dc591f1
11 changed files with 169 additions and 110 deletions

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="componentName" class="form-label">Название компонента</label> <label for="orderId" class="form-label">ИД Заказа</label>
<input type="text" class="form-control" id="componentName" required> <input type="text" class="form-control" id="orderId" required>
</div> </div>
<div class="col-sm-6"> <div class="col-sm-4">
<label for="firstName" class="form-label">First name</label> <label for="orderDate" class="form-label">Время оформления</label>
<input type="text" class="form-control" id="firstName" required> <input type="text" class="form-control" id="orderDate" required>
</div>
<div class="col-sm-4">
<label for="orderPrice" class="form-label">Цена</label>
<input type="text" class="form-control" id="orderPrice" required>
</div>
<div class="col-sm-4">
<label for="productId" class="form-label">ИД продукта</label>
<input type="text" class="form-control" id="productId" required>
</div>
<div class="col-sm-4">
<label for="productCount" class="form-label">Количество продукта</label>
<input type="text" class="form-control" id="productCount" 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 class="table mt-3"> <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

@ -36,7 +36,7 @@ window.addEventListener('DOMContentLoaded', function () {
const remove = async function (){ const remove = async function (){
console.info('Try to remove item'); console.info('Try to remove item');
if (itemId.value !== 0) { if (componentIdInput.value !== 0) {
if (!confirm('Do you really want to remove this item?')) { if (!confirm('Do you really want to remove this item?')) {
console.info('Canceled'); console.info('Canceled');
return; return;
@ -48,7 +48,7 @@ window.addEventListener('DOMContentLoaded', function () {
"Content-Type": "application/json", "Content-Type": "application/json",
} }
}; };
const response = await fetch(host + `/component/` + itemId.value, requestParams); const response = await fetch(host + `/component/` + componentIdInput.value, requestParams);
return await response.json(); return await response.json();
} }

View File

@ -4,72 +4,110 @@ window.addEventListener('DOMContentLoaded', function () {
const host = "http://localhost:8080"; const host = "http://localhost:8080";
const table = document.getElementById("tbody"); const table = document.getElementById("tbody");
const form = document.getElementById("form"); const form = document.getElementById("form");
const lastNameInput = document.getElementById("componentName"); const orderIdInput = document.getElementById("orderId");
const firstNameInput = document.getElementById("firstName"); const orderDate = document.getElementById("orderDate");
const testErrorBtn = document.getElementById("testError"); const priceInput = document.getElementById("orderPrice");
const testNormalBtn = document.getElementById("testNormal"); const productIdInput = document.getElementById("productId");
const productCountInput = document.getElementById("productCount");
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 + "/student"); const response = await fetch(host + "/order");
const data = await response.json(); const data = await response.json();
data.forEach(student => { data.forEach(Order => {
let temp = "<select>";
Order.productDTOList.forEach(Product => {
temp += `<option>${Product.productName + " " + Product.count}</option>>`
})
temp += "</select>"
table.innerHTML += table.innerHTML +=
`<tr> `<tr>
<th scope="row">${student.id}</th> <th scope="row">${Order.id}</th>
<td>${student.firstName}</td> <td>${Order.date}</td>
<td>${student.lastName}</td> <td>${Order.price}</td>
<td>${temp}</td>
</tr>`; </tr>`;
}) })
} }
const create = async function (firstName, lastName) { const create = async function () {
const requestParams = { const requestParams = {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
} }
}; };
const response = await fetch(host + `/student?firstName=${firstName}&lastName=${lastName}`, requestParams); let temp = Date.now();
let time = new Date(temp);
let tru = time.toString();
const response = await fetch(host + `/order?price=${priceInput.value}&date=${tru}&count=${productCountInput.value}&prod=${productIdInput.value}`, requestParams);
return await response.json(); return await response.json();
} }
const test = async function (testObject) { const remove = async function (){
console.info('Try to remove item');
if (orderIdInput.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 + `/order/` + orderIdInput.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 (orderIdInput.value === 0 || orderDate.value == null || orderPrice.value === 0 || productIdInput.value === 0 || productCountInput.value === 0) {
return;
} }
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
} }
};
let temp = Date.now();
let time = new Date(temp);
let tru = time.toString();
const response = await fetch(host + `/order/${orderIdInput.value}?price=${priceInput.value}&date=${tru}&count=${productCountInput.value}&prod=${productIdInput.value}`, requestParams);
return await response.json();
}
buttonRemove.addEventListener('click', function (event){
event.preventDefault();
remove().then((result) => {
getData()
orderIdInput.value = "";
});
});
buttonUpdate.addEventListener('click', function (event){
event.preventDefault();
update().then((result) => {
getData()
orderIdInput.value = "";
priceInput.value = "";
});
});
form.addEventListener("submit", function (event) { form.addEventListener("submit", function (event) {
event.preventDefault(); event.preventDefault();
create(firstNameInput.value, lastNameInput.value).then((result) => { create().then((result) => {
getData(); getData();
firstNameInput.value = ""; priceInput.value = "";
lastNameInput.value = ""; orderIdInput.value = "";
alert(`Student[id=${result.id}, firstName=${result.firstName}, lastName=${result.lastName}]`); alert(`Component[id=${result.id}, price=${result.price}, componentName=${result.date}]`);
}); });
}); });
testErrorBtn.addEventListener("click", function () {
test({});
});
testNormalBtn.addEventListener("click", function () {
test({id: 10, name: "test"});
});
getData(); getData();
}); });

View File

@ -18,13 +18,13 @@ public class OrderController {
} }
@PostMapping @PostMapping
public OrderDTO createOrder(@RequestParam("date") String date, public Order createOrder(@RequestParam("date") String date,
@RequestParam("price") Integer price, @RequestParam("price") Integer price,
@RequestParam("count") Integer[] count, @RequestParam("count") Integer[] count,
@RequestParam("prod") Long[] prod){ @RequestParam("prod") Long[] prod){
final Order order = orderService.addOrder(date, price); final Order order = orderService.addOrder(date, price);
orderService.addOrderProducts(orderService.findOrder(order.getId()), count, productService.findFiltredProducts(prod)); orderService.addOrderProducts(orderService.findOrder(order.getId()), count, productService.findFiltredProducts(prod));
return new OrderDTO(order); return order;
} }
@PutMapping("/{id}") @PutMapping("/{id}")
public OrderDTO updateOrder(@PathVariable Long id, public OrderDTO updateOrder(@PathVariable Long id,
@ -32,8 +32,7 @@ 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){
orderService.updateOrder(id, date, price, count, productService.findFiltredProducts(prod)); return new OrderDTO(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

@ -15,7 +15,10 @@ public class OrderDTO {
this.id = order.getId(); this.id = order.getId();
this.date = order.getDate(); this.date = order.getDate();
this.price = order.getPrice(); this.price = order.getPrice();
this.productDTOList = order.getProducts().stream().filter(x -> Objects.equals(x.getId().getOrderId(), order.getId())).map(x -> new ProductDTO(x.getProduct())).toList(); this.productDTOList = order.getProducts().stream()
.filter(x -> Objects.equals(x.getId().getOrderId(), order.getId()))
.map(y -> new ProductDTO(y.getProduct(), y.getCount()))
.toList();
} }
public long getId() { public long getId() {

View File

@ -23,9 +23,7 @@ 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){
final Product product = productService.addProduct(name, price); return new ProductDTO(productService.addProduct(name, price, count, componentService.findFiltredComponents(comp)));
productService.addProductComponents(productService.findProduct(product.getId()), count, componentService.findFiltredComponents(comp));
return new ProductDTO(productService.findProduct(product.getId()));
} }
@PutMapping("/{id}") @PutMapping("/{id}")
public ProductDTO updateProduct(@PathVariable Long id, public ProductDTO updateProduct(@PathVariable Long id,
@ -33,8 +31,7 @@ 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){
productService.updateProduct(id, name, price, count, componentService.findFiltredComponents(comp)); return new ProductDTO(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

@ -1,5 +1,6 @@
package ip.labwork.shop.controller; package ip.labwork.shop.controller;
import ip.labwork.shop.model.Component;
import ip.labwork.shop.model.Product; import ip.labwork.shop.model.Product;
import ip.labwork.shop.model.ProductComponents; import ip.labwork.shop.model.ProductComponents;
@ -12,8 +13,8 @@ public class ProductDTO {
private final long id; private final long id;
private final String productName; private final String productName;
private final int price; private final int price;
private int count = 0;
private final List<ComponentDTO> componentDTOList; private final List<ComponentDTO> componentDTOList;
private final List<OrderDTO> orderDTOList;
public ProductDTO(Product product) { public ProductDTO(Product product) {
this.id = product.getId(); this.id = product.getId();
this.productName = product.getProductName(); this.productName = product.getProductName();
@ -22,9 +23,17 @@ public class ProductDTO {
.filter(x -> Objects.equals(x.getId().getProductId(), product.getId())) .filter(x -> Objects.equals(x.getId().getProductId(), product.getId()))
.map(y -> new ComponentDTO(y.getComponent(), y.getCount())) .map(y -> new ComponentDTO(y.getComponent(), y.getCount()))
.toList(); .toList();
this.orderDTOList = product.getOrders() == null ? null : product.getOrders().stream().filter(x -> Objects.equals(x.getId().getProductId(), product.getId())).map(x -> new OrderDTO(x.getOrder())).toList();
} }
public ProductDTO(Product product, int count) {
this.id = product.getId();
this.productName = product.getProductName();
this.price = product.getPrice();
this.componentDTOList = product.getComponents().stream()
.filter(x -> Objects.equals(x.getId().getProductId(), product.getId()))
.map(y -> new ComponentDTO(y.getComponent(), y.getCount()))
.toList();
this.count = count;
}
public long getId() { public long getId() {
return id; return id;
} }
@ -41,7 +50,8 @@ public class ProductDTO {
return componentDTOList; return componentDTOList;
} }
public List<OrderDTO> getOrderDTOList() {
return orderDTOList; public int getCount() {
return count;
} }
} }

View File

@ -15,7 +15,7 @@ public class Order {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
private Long id; private Long id;
@NotNull(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;
@NotNull(message = "Price can't be null or empty") @NotNull(message = "Price can't be null or empty")

View File

@ -9,12 +9,12 @@ import jakarta.validation.constraints.NotNull;
@Table(name = "order_product") @Table(name = "order_product")
public class OrderProducts { public class OrderProducts {
@EmbeddedId @EmbeddedId
private OrderProductsKey id; private OrderProductsKey id = new OrderProductsKey();
@ManyToOne @ManyToOne(cascade = CascadeType.MERGE)
@MapsId("productId") @MapsId("productId")
@JoinColumn(name = "product_id") @JoinColumn(name = "product_id")
private Product product; private Product product;
@ManyToOne @ManyToOne(cascade = CascadeType.MERGE)
@MapsId("orderId") @MapsId("orderId")
@JoinColumn(name = "order_id") @JoinColumn(name = "order_id")
@JsonIgnore @JsonIgnore
@ -28,7 +28,6 @@ public class OrderProducts {
public OrderProducts(Order order, Product product, Integer count) { public OrderProducts(Order order, Product product, Integer count) {
this.order = order; this.order = order;
this.id = new OrderProductsKey(product.getId(), order.getId());
this.id.setOrderId(order.getId()); this.id.setOrderId(order.getId());
this.id.setProductId(product.getId()); this.id.setProductId(product.getId());
this.product = product; this.product = product;

View File

@ -34,6 +34,7 @@ public class OrderService {
public void addOrderProducts(Order order, Integer[] count, List<Product> products){ 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]);
orderProductRepository.saveAndFlush(orderProducts);
order.addProduct(orderProducts); order.addProduct(orderProducts);
products.get(i).addOrder(orderProducts); products.get(i).addOrder(orderProducts);
orderProductRepository.save(orderProducts); orderProductRepository.save(orderProducts);
@ -62,7 +63,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));
@ -81,6 +82,7 @@ public class OrderService {
orderProductRepository.save(orderProducts); orderProductRepository.save(orderProducts);
} else { } else {
final OrderProducts orderProducts = new OrderProducts(currentOrder, products.get(i), count[i]); final OrderProducts orderProducts = new OrderProducts(currentOrder, products.get(i), count[i]);
orderProductRepository.saveAndFlush(orderProducts);
currentOrder.addProduct(orderProducts); currentOrder.addProduct(orderProducts);
products.get(i).addOrder(orderProducts); products.get(i).addOrder(orderProducts);
orderProductRepository.save(orderProducts); orderProductRepository.save(orderProducts);
@ -92,9 +94,9 @@ public class OrderService {
orderProductRepository.delete(orderProductsList.get(i)); orderProductRepository.delete(orderProductsList.get(i));
} }
return currentOrder; return currentOrder;
}*/ }
@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));
@ -136,7 +138,7 @@ public class OrderService {
} }
} }
return currentOrder; return currentOrder;
} }*/
public List<OrderProducts> getOrderProducts(Order currentOrder){ public List<OrderProducts> getOrderProducts(Order currentOrder){
return orderProductRepository.getOrderProductsByOrderId(currentOrder.getId()); return orderProductRepository.getOrderProductsByOrderId(currentOrder.getId());
} }

View File

@ -33,14 +33,10 @@ public class ProductService {
this.componentRepository = componentRepository; this.componentRepository = componentRepository;
} }
@Transactional @Transactional
public Product addProduct(String productName, Integer price) { public Product addProduct(String productName, Integer price, Integer[] count, List<Component> components) {
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]);
productComponentRepository.saveAndFlush(productComponents); productComponentRepository.saveAndFlush(productComponents);
@ -48,6 +44,7 @@ public class ProductService {
components.get(i).addProduct(productComponents); components.get(i).addProduct(productComponents);
productComponentRepository.saveAndFlush(productComponents); productComponentRepository.saveAndFlush(productComponents);
} }
return product;
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public Product findProduct(Long id) { public Product findProduct(Long id) {
@ -60,7 +57,7 @@ public class ProductService {
return productRepository.findAll(); return productRepository.findAll();
} }
/*@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);
currentProduct.setProductName(productName); currentProduct.setProductName(productName);
@ -80,6 +77,7 @@ public class ProductService {
} }
else { else {
final ProductComponents productComponents = new ProductComponents(components.get(i), currentProduct, count[i]); final ProductComponents productComponents = new ProductComponents(components.get(i), currentProduct, count[i]);
productComponentRepository.saveAndFlush(productComponents);
currentProduct.addComponent(productComponents); currentProduct.addComponent(productComponents);
components.get(i).addProduct(productComponents); components.get(i).addProduct(productComponents);
productComponentRepository.save(productComponents); productComponentRepository.save(productComponents);
@ -91,8 +89,8 @@ public class ProductService {
productComponentRepository.delete(productComponentsList.get(i)); productComponentRepository.delete(productComponentsList.get(i));
} }
return currentProduct; 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);
currentProduct.setProductName(productName); currentProduct.setProductName(productName);
@ -124,7 +122,7 @@ public class ProductService {
final Long currentId = components.get(i).getId(); final Long currentId = components.get(i).getId();
if (component_id.contains(currentId)) { if (component_id.contains(currentId)) {
productComponentsList.remove(productComponentsList.stream().filter(x -> Objects.equals(x.getId().getComponentId(), currentId)).toList().get(0)); productComponentsList.remove(productComponentsList.stream().filter(x -> Objects.equals(x.getId().getComponentId(), currentId)).toList().get(0));
component_id.remove(components.get(i).getId()); component_id.remove(currentId);
} }
else { else {
final ProductComponents productComponents = new ProductComponents(components.get(i), currentProduct, count[i]); final ProductComponents productComponents = new ProductComponents(components.get(i), currentProduct, count[i]);
@ -134,7 +132,7 @@ public class ProductService {
} }
} }
return currentProduct; return currentProduct;
} }*/
public List<ProductComponents> getProductComponents(Product currentProduct){ public List<ProductComponents> getProductComponents(Product currentProduct){
return productComponentRepository.getProductComponentsByProductId(currentProduct.getId()); return productComponentRepository.getProductComponentsByProductId(currentProduct.getId());
} }