diff --git a/src/main/java/mate/academy/model/OrderItem.java b/src/main/java/mate/academy/model/OrderItem.java index d219b8a..9ae8a26 100644 --- a/src/main/java/mate/academy/model/OrderItem.java +++ b/src/main/java/mate/academy/model/OrderItem.java @@ -33,7 +33,6 @@ public class OrderItem { @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "book_id", nullable = false) private Book book; - @Column(nullable = false) private int quantity; @Column(nullable = false) diff --git a/src/main/java/mate/academy/service/impl/OrderServiceImpl.java b/src/main/java/mate/academy/service/impl/OrderServiceImpl.java index 839ff84..6469e4f 100644 --- a/src/main/java/mate/academy/service/impl/OrderServiceImpl.java +++ b/src/main/java/mate/academy/service/impl/OrderServiceImpl.java @@ -3,6 +3,8 @@ import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.List; +import java.util.Set; + import lombok.RequiredArgsConstructor; import mate.academy.dto.order.OrderDto; import mate.academy.dto.order.OrderItemDto; @@ -40,7 +42,8 @@ public OrderDto createOrder(Long userId, String shippingAddress) { User user = getUser(userId); Order order = makeOrder(shippingAddress, user); - BigDecimal total = calculateTotalAndAddOrderItems(shoppingCart, order); + addOrderItemsFromCart(shoppingCart, order); + BigDecimal total = calculateTotal(order.getOrderItems()); order.setTotal(total); saveOrderAndOrderItems(order); @@ -83,7 +86,7 @@ public void updateOrderStatus(Long orderId, Order.Status status) { orderRepository.save(order); } - private static Order makeOrder(String shippingAddress, User user) { + private Order makeOrder(String shippingAddress, User user) { Order order = new Order(); order.setUser(user); order.setStatus(Order.Status.PENDING); @@ -106,9 +109,7 @@ private User getUser(Long userId) { .orElseThrow(() -> new EntityNotFoundException("User not found")); } - private BigDecimal calculateTotalAndAddOrderItems(ShoppingCart shoppingCart, Order order) { - BigDecimal total = BigDecimal.ZERO; - + private void addOrderItemsFromCart(ShoppingCart shoppingCart, Order order) { for (CartItem cartItem : shoppingCart.getCartItems()) { OrderItem orderItem = new OrderItem(); orderItem.setOrder(order); @@ -118,8 +119,13 @@ private BigDecimal calculateTotalAndAddOrderItems(ShoppingCart shoppingCart, Ord .multiply(BigDecimal.valueOf(cartItem.getQuantity()))); orderItem.setDeleted(false); order.getOrderItems().add(orderItem); + } + } - total = total.add(orderItem.getPrice()); + private BigDecimal calculateTotal(Set orderItems) { + BigDecimal total = BigDecimal.ZERO; + for (OrderItem item : orderItems) { + total = total.add(item.getPrice()); } return total; }