Skip to content

Commit

Permalink
applied suggested changes
Browse files Browse the repository at this point in the history
  • Loading branch information
TarasYashchuk committed Jul 25, 2024
1 parent d4de0e6 commit f781d08
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
1 change: 0 additions & 1 deletion src/main/java/mate/academy/model/OrderItem.java
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
18 changes: 12 additions & 6 deletions src/main/java/mate/academy/service/impl/OrderServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand All @@ -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<OrderItem> orderItems) {
BigDecimal total = BigDecimal.ZERO;
for (OrderItem item : orderItems) {
total = total.add(item.getPrice());
}
return total;
}
Expand Down

0 comments on commit f781d08

Please sign in to comment.