Skip to content

Commit

Permalink
[refactor] 가독성 향상
Browse files Browse the repository at this point in the history
  • Loading branch information
Dr-KoKo committed Aug 17, 2024
1 parent f7662b0 commit 0b8c503
Showing 1 changed file with 37 additions and 10 deletions.
47 changes: 37 additions & 10 deletions src/main/java/camp/woowak/lab/order/domain/PriceChecker.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package camp.woowak.lab.order.domain;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.stereotype.Component;

Expand All @@ -20,19 +25,41 @@ public PriceChecker(MenuRepository menuRepository) {
}

public List<OrderItem> check(List<CartItem> cartItems) {
List<Menu> menus = menuRepository.findAllById(cartItems.stream().map(CartItem::getMenuId).toList());
if (menus.size() != cartItems.size()) {
throw new NotFoundMenuException("등록되지 않은 메뉴를 주문했습니다.");
Set<Long> cartItemMenuIds = extractMenuIds(cartItems);
List<Menu> menus = menuRepository.findAllById(cartItemMenuIds);
Map<Long, Menu> menuMap = listToMap(menus);
Set<Long> missingMenuIds = new HashSet<>();
for (Long menuId : cartItemMenuIds) {
if (!menuMap.containsKey(menuId)) {
missingMenuIds.add(menuId);
}
}
if (!missingMenuIds.isEmpty()) {
String missingIdsString = formatMissingIds(missingMenuIds);
throw new NotFoundMenuException("등록되지 않은 메뉴(id=" + missingIdsString + ")를 주문했습니다.");
}
List<OrderItem> orderItems = new ArrayList<>();
for (Menu menu : menus) {
for (CartItem cartItem : cartItems) {
if (cartItem.getMenuId().equals(menu.getId())) {
OrderItem orderItem = new OrderItem(menu.getId(), menu.getPrice(), cartItem.getAmount());
orderItems.add(orderItem);
}
}
for (CartItem cartItem : cartItems) {
Menu menu = menuMap.get(cartItem.getMenuId());
orderItems.add(new OrderItem(menu.getId(), menu.getPrice(), cartItem.getAmount()));
}
return orderItems;
}

private String formatMissingIds(Set<Long> missingMenuIds) {
return missingMenuIds.stream()
.map(String::valueOf)
.collect(Collectors.joining(", "));
}

private Map<Long, Menu> listToMap(List<Menu> menus) {
return menus.stream()
.collect(Collectors.toMap(Menu::getId, Function.identity()));
}

private Set<Long> extractMenuIds(List<CartItem> cartItems) {
return cartItems.stream()
.map(CartItem::getMenuId)
.collect(Collectors.toSet());
}
}

0 comments on commit 0b8c503

Please sign in to comment.