в чём сила, брат?

This commit is contained in:
Вячеслав Иванов 2024-05-03 01:59:36 +04:00
parent 19fad7ac71
commit 19620712d4
10 changed files with 113 additions and 214 deletions

View File

@ -41,7 +41,3 @@ dependencies {
tasks.named('test') {
useJUnitPlatform()
}
bootRun {
args = ['--populate']
}

View File

@ -1,7 +1,6 @@
package com.example.demo;
import java.util.Arrays;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -9,6 +8,7 @@ import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.demo.orders.api.OrderProductDto;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService;
import com.example.demo.product.model.ProductEntity;
@ -40,7 +40,7 @@ public class DemoApplication implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
if (args.length > 0 && Arrays.asList(args).contains("--populate")) {
// if (args.length > 0 && Arrays.asList(args).contains("--populate")) {
log.info("Create default types values");
final var type1 = typeService.create(new TypeEntity("Мясная"));
final var type2 = typeService.create(new TypeEntity("Пепперони"));
@ -59,20 +59,22 @@ public class DemoApplication implements CommandLineRunner {
final var user2 = userService.create(new UserEntity("vihoof", "Фёдор", "Лопатин", "test1@test.ru", "22-12-2023", "+79875433210", "qwerty321"));
final var user3 = userService.create(new UserEntity("fragreg", "Семён", "Кукушкин", "test2@test.ru", "03-02-2023", "+74567433210", "qwerty451"));
log.info("Create default order values");
final var order1 = orderService.create(user1.getId(), new OrderEntity("ул. Северный венец, 32"));
final var order2 = orderService.create(user2.getId(), new OrderEntity("ул. Северный венец, 32"));
final var order3 = orderService.create(user3.getId(), new OrderEntity("ул. Северный венец, 32"));
orderService.addOrderProducts(user1.getId(), order1.getId(),
Map.of(product1.getId(), 3,
product2.getId(), 1,
product3.getId(), 2));
orderService.addOrderProducts(user2.getId(), order2.getId(),
Map.of(product4.getId(), 5));
orderService.addOrderProducts(user3.getId(), order3.getId(),
Map.of(product5.getId(), 1,
product6.getId(), 1));
}
log.info("Create default orders values");
orderService.create(user1.getId(), new OrderEntity("test"), Arrays.asList(
new OrderProductDto(product1.getId(), 3),
new OrderProductDto(product2.getId(), 1),
new OrderProductDto(product3.getId(), 2)
));
orderService.create(user2.getId(), new OrderEntity("test1"), Arrays.asList(
new OrderProductDto(product4.getId(), 5)
));
orderService.create(user3.getId(), new OrderEntity("test2"), Arrays.asList(
new OrderProductDto(product5.getId(), 1),
new OrderProductDto(product6.getId(), 1)
));
}
}

View File

@ -3,8 +3,8 @@ package com.example.demo.orders.api;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import org.hibernate.Hibernate;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
@ -38,6 +38,7 @@ public class OrderController {
}
private OrderDto toDto(OrderEntity entity) {
Hibernate.initialize(entity.getOrderProducts());
final OrderDto dto = modelMapper.map(entity, OrderDto.class);
dto.setSum(orderService.getSum(entity.getUser().getId(), entity.getId()));
dto.setCount(orderService.getFullCount(entity.getUser().getId(), entity.getId()));
@ -48,7 +49,7 @@ public class OrderController {
return modelMapper.map(entity, ProductDto.class);
}
private OrderEntity toEntity(OrderDto dto) throws ParseException {
private OrderEntity toEntity(OrderDto dto) {
final OrderEntity entity = modelMapper.map(dto, OrderEntity.class);
return entity;
}
@ -72,7 +73,7 @@ public class OrderController {
public OrderDto create(
@PathVariable(name = "user") Long userId,
@RequestBody @Valid OrderDto dto) throws ParseException {
return toDto(orderService.create(userId, toEntity(dto)));
return toDto(orderService.create(userId, toEntity(dto), dto.getOrderProducts()));
}
@PutMapping("/{id}")
@ -80,7 +81,7 @@ public class OrderController {
@PathVariable(name = "user") Long userId,
@PathVariable(name = "id") Long id,
@RequestBody @Valid OrderDto dto) throws ParseException {
return toDto(orderService.update(userId, id, toEntity(dto)));
return toDto(orderService.update(userId, id, toEntity(dto), dto.getOrderProducts()));
}
@DeleteMapping("/{id}")
@ -96,35 +97,4 @@ public class OrderController {
@PathVariable(name = "id") Long id) {
return orderService.getOrderProducts(userId, id).stream().map(this::toProductDto).toList();
}
@PostMapping("/{id}/product")
public List<ProductDto> addProducts(
@PathVariable(name = "user") Long userId,
@PathVariable(name = "id") Long id,
@RequestBody Map<Long, Integer> productsIdsCount) {
return orderService.addOrderProducts(userId, id, productsIdsCount).stream().map(this::toProductDto).toList();
}
@PutMapping("/{id}/product")
public List<ProductDto> changeProductsCount(
@PathVariable(name = "user") Long userId,
@PathVariable(name = "id") Long id,
@RequestBody Map<Long, Integer> productsIdsCount) {
return orderService.changeProductsCount(userId, id, productsIdsCount).stream().map(this::toProductDto).toList();
}
@DeleteMapping("/{id}/product")
public List<ProductDto> deleteOrderProducts(
@PathVariable(name = "user") Long userId,
@PathVariable(name = "id") Long id,
@RequestParam(name = "products", defaultValue = "") List<Long> productsIds) {
return orderService.deleteOrderProducts(userId, id, productsIds).stream().map(this::toProductDto).toList();
}
@DeleteMapping("/{id}/product/all")
public List<ProductDto> deleteAllOrderProducts(
@PathVariable(name = "user") Long userId,
@PathVariable(name = "id") Long id) {
return orderService.deleteAllOrderProducts(userId, id).stream().map(this::toProductDto).toList();
}
}

View File

@ -1,5 +1,7 @@
package com.example.demo.orders.api;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
@ -14,6 +16,17 @@ public class OrderDto {
@NotBlank
private String shippingAddress;
private List<OrderProductDto> orderProducts;
public List<OrderProductDto> getOrderProducts() {
return orderProducts;
}
public void setOrderProducts(List<OrderProductDto> orderProducts) {
this.orderProducts = orderProducts;
}
public Long getId() {
return id;
}

View File

@ -0,0 +1,32 @@
package com.example.demo.orders.api;
import jakarta.validation.constraints.NotNull;
public class OrderProductDto {
private Long productId;
@NotNull
private Integer count;
public OrderProductDto(Long productId, Integer count) {
this.productId = productId;
this.count = count;
}
public OrderProductDto() {
}
public Long getProductId() {
return productId;
}
public void setProductId(Long id) {
this.productId = id;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}

View File

@ -11,6 +11,7 @@ import com.example.demo.ordersproducts.model.OrderProductEntity;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
@ -25,8 +26,9 @@ public class OrderEntity extends BaseEntity {
private UserEntity user;
@Column(nullable = false)
private String shippingAddress;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true )
@OrderBy("id ASC")
private Set<OrderProductEntity> orderProducts = new HashSet<>();
public OrderEntity() {
@ -59,6 +61,10 @@ public class OrderEntity extends BaseEntity {
return orderProducts;
}
public void setOrdersProducts(Set<OrderProductEntity> set) {
this.orderProducts = set;
}
public void addProduct(OrderProductEntity orderProduct) {
if (orderProduct.getOrder() != this) {
orderProduct.setOrder(this);

View File

@ -1,8 +1,7 @@
package com.example.demo.orders.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
@ -11,6 +10,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.orders.api.OrderProductDto;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.repository.OrderRepository;
import com.example.demo.product.model.ProductEntity;
@ -52,20 +52,36 @@ public class OrderService {
}
@Transactional
public OrderEntity create(long userId, OrderEntity entity) {
public OrderEntity create(long userId, OrderEntity entity, List<OrderProductDto> orderProductList) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
final UserEntity existsUser = userService.get(userId);
entity.setUser(existsUser);
entity = repository.save(entity);
List<OrderProductEntity> orderProductListEntities = new ArrayList<OrderProductEntity>();
for (OrderProductDto element : orderProductList) {
OrderProductEntity orderProductEntity = new OrderProductEntity(entity, productService.get(element.getProductId()), element.getCount());
orderProductEntity.setOrder(entity);
orderProductListEntities.add(orderProductEntity);
entity.addProduct(orderProductEntity);
}
return repository.save(entity);
}
@Transactional
public OrderEntity update(long userId, long id, OrderEntity entity) {
public OrderEntity update(long userId, long id, OrderEntity entity, List<OrderProductDto> orderProductList) {
userService.get(userId);
final OrderEntity existsEntity = get(userId, id);
existsEntity.setShippingAddress(entity.getShippingAddress());
existsEntity.getOrderProducts().clear();
for (OrderProductDto dto : orderProductList) {
OrderProductEntity orderProductEntity = new OrderProductEntity(existsEntity, productService.get(dto.getProductId()), dto.getCount());
existsEntity.addProduct(orderProductEntity);
}
return repository.save(existsEntity);
}
@ -100,75 +116,4 @@ public class OrderService {
.mapToInt(OrderProductEntity::getCount)
.sum();
}
@Transactional
public List<ProductEntity> addOrderProducts(
long userId,
long id,
Map<Long, Integer> productsIdsCount) {
userService.get(userId);
final OrderEntity existsOrder = get(userId, id);
List<ProductEntity> result = productService.getAll(0L).stream()
.filter(product -> productsIdsCount.containsKey(product.getId()))
.toList();
result.forEach(product -> {
final OrderProductEntity orderProduct = new OrderProductEntity(existsOrder, product, productsIdsCount.get(product.getId()));
orderProduct.setOrder(existsOrder);
// orderProduct.setProduct(product);
});
repository.save(existsOrder);
return result;
}
@Transactional
public List<ProductEntity> changeProductsCount(
long userId,
long id,
Map<Long, Integer> productsIdsCount) {
userService.get(userId);
final OrderEntity existsOrder = get(userId, id);
List<ProductEntity> result = existsOrder.getOrderProducts().stream()
.filter(product -> Objects.nonNull(product.getProduct()))
.filter(product -> productsIdsCount.containsKey(product.getProduct().getId()))
.map(product -> {
Integer newCount = productsIdsCount.getOrDefault(product.getProduct().getId(), product.getCount());
product.setCount(newCount);
return product.getProduct();
})
.toList();
repository.save(existsOrder);
return result;
}
@Transactional
public List<ProductEntity> deleteOrderProducts(
long userId,
long id,
List<Long> productsIds) {
userService.get(userId);
final OrderEntity existsOrder = get(userId, id);
final List<OrderProductEntity> products = existsOrder.getOrderProducts().stream()
.filter(product -> Objects.nonNull(product.getProduct()))
.filter(product -> productsIds.contains(product.getProduct().getId()))
.toList();
products.forEach(existsOrder::deleteProduct);
repository.save(existsOrder);
return products.stream()
.map(OrderProductEntity::getProduct)
.toList();
}
@Transactional
public List<ProductEntity> deleteAllOrderProducts(long userId, long id) {
userService.get(userId);
final OrderEntity existsOrder = get(userId, id);
final List<OrderProductEntity> products = existsOrder.getOrderProducts().stream()
.filter(product -> Objects.nonNull(product.getProduct()))
.toList();
products.forEach(existsOrder::deleteProduct);
repository.save(existsOrder);
return products.stream()
.map(OrderProductEntity::getProduct)
.toList();
}
}

View File

@ -2,28 +2,23 @@ package com.example.demo.ordersproducts.model;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.product.model.ProductEntity;
import jakarta.persistence.Column;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.MapsId;
import jakarta.persistence.Table;
@Entity
@Table(name = "orders_products")
public class OrderProductEntity {
@EmbeddedId
private OrderProductId id = new OrderProductId();
public class OrderProductEntity extends BaseEntity {
@ManyToOne
@MapsId("orderId")
@JoinColumn(name = "order_id")
private OrderEntity order;
@ManyToOne
@MapsId("productId")
@JoinColumn(name = "product_id")
private ProductEntity product;
@Column(nullable = false)
@ -38,14 +33,6 @@ public class OrderProductEntity {
this.count = count;
}
public OrderProductId getId() {
return id;
}
public void setId(OrderProductId id) {
this.id = id;
}
public OrderEntity getOrder() {
return order;
}

View File

@ -1,17 +1,12 @@
package com.example.demo.product.model;
// import java.util.HashSet;
import java.util.Objects;
// import java.util.Set;
import com.example.demo.types.model.TypeEntity;
// import com.example.demo.ordersproducts.model.OrderProductEntity;
import com.example.demo.core.model.BaseEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
// import jakarta.persistence.OneToMany;
// import jakarta.persistence.OrderBy;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@ -27,10 +22,6 @@ public class ProductEntity extends BaseEntity {
@Column(nullable = false)
private Double price;
// @OneToMany(mappedBy = "product")
// @OrderBy("id ASC")
// private Set<OrderProductEntity> orderProducts = new HashSet<>();
public ProductEntity() {
}
@ -64,17 +55,6 @@ public class ProductEntity extends BaseEntity {
this.price = price;
}
// public Set<OrderProductEntity> getOrderProducts() {
// return orderProducts;
// }
// public void addOrder(OrderProductEntity orderProduct) {
// if (orderProduct.getProduct() != this) {
// orderProduct.setProduct(this);
// }
// orderProducts.add(orderProduct);
// }
@Override
public int hashCode() {
return Objects.hash(id, name, type, price/* , orderProducts*/);
@ -91,6 +71,5 @@ public class ProductEntity extends BaseEntity {
&& Objects.equals(other.getName(), name)
&& Objects.equals(other.getType(), type)
&& Objects.equals(other.getPrice(), price);
// && Objects.equals(other.getOrderProducts(), orderProducts);
}
}

View File

@ -1,7 +1,6 @@
package com.example.demo;
import java.util.Map;
import java.util.List;
import java.util.Arrays;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
@ -12,6 +11,7 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.orders.api.OrderProductDto;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService;
import com.example.demo.product.model.ProductEntity;
@ -53,14 +53,15 @@ public class OrderServiceTests {
product2 = productService.create(new ProductEntity("test2", type, 499.00));
product3 = productService.create(new ProductEntity("test3", type, 450.50));
user = userService.create(new UserEntity("kruviii", "Павел", "Крылов", "test@test.ru", "11-11-2023", "+79876543210", "qwerty123"));
order = orderService.create(user.getId(), new OrderEntity("ул. Северный венец, 32"));
orderService.create(user.getId(), new OrderEntity("ул. Северный венец, 32"));
orderService.create(user.getId(), new OrderEntity("ул. Северный венец, 32"));
orderService.addOrderProducts(user.getId(), order.getId(),
Map.of(product1.getId(), 3,
product2.getId(), 1,
product3.getId(), 2));
order = orderService.create(user.getId(), new OrderEntity("ул. Северный венец, 32"), Arrays.asList(
new OrderProductDto(product1.getId(), 3),
new OrderProductDto(product2.getId(), 1),
new OrderProductDto(product3.getId(), 2)));
orderService.create(user.getId(), new OrderEntity("ул. Северный венец, 32"), Arrays.asList(
new OrderProductDto(product1.getId(), 5)));
orderService.create(user.getId(), new OrderEntity("ул. Северный венец, 32"), Arrays.asList(
new OrderProductDto(product2.getId(), 1),
new OrderProductDto(product3.getId(), 1)));
}
@AfterEach
@ -85,7 +86,8 @@ public class OrderServiceTests {
@Transactional
@Test
void updateTest() {
final OrderEntity newEntity = orderService.update(user.getId(), order.getId(), new OrderEntity("ул. Северный венец, 32"));
final OrderEntity newEntity = orderService.update(user.getId(), order.getId(), new OrderEntity("ул. Северный венец, 32"), Arrays.asList(
new OrderProductDto(product1.getId(), 5)));
Assertions.assertEquals(3, orderService.getAll(user.getId()).size());
Assertions.assertEquals(newEntity, orderService.get(user.getId(), order.getId()));
}
@ -95,7 +97,8 @@ public class OrderServiceTests {
orderService.delete(user.getId(), order.getId());
Assertions.assertEquals(2, orderService.getAll(user.getId()).size());
final OrderEntity newEntity = orderService.create(user.getId(), new OrderEntity("ул. Северный венец, 32"));
final OrderEntity newEntity = orderService.create(user.getId(), new OrderEntity("ул. Северный венец, 32"), Arrays.asList(
new OrderProductDto(product1.getId(), 5)));
Assertions.assertEquals(3, orderService.getAll(user.getId()).size());
Assertions.assertNotEquals(order.getId(), newEntity.getId());
}
@ -111,38 +114,4 @@ public class OrderServiceTests {
Integer count = orderService.getFullCount(user.getId(), order.getId());
Assertions.assertEquals(6, count);
}
@Transactional
@Test
void AddOrderProductsTest() {
final var type = typeService.create(new TypeEntity("3 сыра"));
final var product = productService.create(new ProductEntity("test1", type, 100.00));
Assertions.assertEquals(3, orderService.getOrderProducts(user.getId(), order.getId()).size());
orderService.addOrderProducts(user.getId(), order.getId(), Map.of(product.getId(), 5));
Assertions.assertEquals(4, orderService.getOrderProducts(user.getId(), order.getId()).size());
}
@Transactional
@Test
void changeProductsCountTest() {
Assertions.assertEquals(6, orderService.getFullCount(user.getId(), order.getId()));
orderService.changeProductsCount(user.getId(), order.getId(), Map.of(product2.getId(), 4, product3.getId(), 1));
Assertions.assertEquals(8, orderService.getFullCount(user.getId(), order.getId()));
}
@Transactional
@Test
void deleteOrderProductsTest() {
Assertions.assertEquals(3, orderService.getOrderProducts(user.getId(), order.getId()).size());
orderService.deleteOrderProducts(user.getId(), order.getId(), List.of(product1.getId(), product3.getId()));
Assertions.assertEquals(1, orderService.getOrderProducts(user.getId(), order.getId()).size());
}
@Transactional
@Test
void deleteAllOrderProductsTest() {
Assertions.assertEquals(3, orderService.getOrderProducts(user.getId(), order.getId()).size());
orderService.deleteAllOrderProducts(user.getId(), order.getId());
Assertions.assertEquals(0, orderService.getOrderProducts(user.getId(), order.getId()).size());
}
}