code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,40 @@
+package store.util.parse;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import store.entity.DateProvider;
+import store.entity.Product;
+import store.entity.Promotion;
+import store.entity.RealDateProvider;
+
+public class ProductParser {
+ private static final DateProvider dateProvider = new RealDateProvider();
+
+ public static List<Product> parse(List<String> products, Map<String, Promotion> promotions) {
+ List<Product> stockProduct = new ArrayList<>();
+ for (int i = 1; i < products.size(); i++) { // ํค๋ ๋ถ๋ถ ์ ์ธ
+ String[] fields = products.get(i).split(",");
+ int price = Integer.parseInt(fields[1]);
+ int quantity = Integer.parseInt(fields[2]);
+ Promotion promotion = promotions.get(fields[3]);
+ addOrUpdateProduct(stockProduct, fields[0], price, quantity, promotion);
+ }
+ return stockProduct;
+ }
+
+ private static void addOrUpdateProduct(List<Product> products, String name, int price, int quantity,
+ Promotion promotion) {
+ findProduct(products, name).ifPresentOrElse(
+ existingProduct -> existingProduct.addQuantity(quantity, promotion),
+ () -> products.add(new Product(name, price, quantity, promotion, dateProvider))
+ );
+ }
+
+ private static Optional<Product> findProduct(List<Product> products, String name) {
+ return products.stream()
+ .filter(p -> p.getName().equals(name))
+ .findFirst();
+ }
+} | Java | ๋ณดํต ์ปฌ๋ ์
์ด๋ ๋ฐฐ์ด์ ์ํํ ๋ ์ธ๋ฑ์ค๊ฐ 0๋ถํฐ ์์ํ๋ ๊ฑธ๋ก ์๊ณ ์์ต๋๋ค.
์์์ธ๋ฑ์ค๊ฐ ์ 1์ธ์ง ์์๋ก ํํํด์ฃผ์๋ฉด ์ข์ ๊ฒ ๊ฐ๋จ ์๊ฐ์ด ๋ญ๋๋ค! |
@@ -0,0 +1,30 @@
+package store.util.parse;
+
+import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import store.entity.Promotion;
+
+public class PromotionParser {
+ private static final String SEPARATOR = ",";
+ private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
+
+ public static Map<String, Promotion> parse(List<String> promotions) {
+ return promotions.stream()
+ .skip(1) // ์ฒซ ๋ฒ์งธ ํค๋ ๋ถ๋ถ ์ ์ธ
+ .map(PromotionParser::parsePromotionLine)
+ .collect(Collectors.toMap(Promotion::getName, promotion -> promotion));
+ }
+
+ private static Promotion parsePromotionLine(String promotion) {
+ String[] fields = promotion.split(SEPARATOR);
+ String name = fields[0];
+ int buy = Integer.parseInt(fields[1]);
+ int get = Integer.parseInt(fields[2]);
+ LocalDate startDate = LocalDate.parse(fields[3], dateTimeFormatter);
+ LocalDate endDate = LocalDate.parse(fields[4], dateTimeFormatter);
+ return new Promotion(name, buy, get, startDate, endDate);
+ }
+} | Java | ์ฒซ ๋ฒ์งธ ํค๋๋ฅผ ์ ์ธํ๋ค๋ ์ฃผ์ ๋์ 1์ด ๊ฐ์ง๋ ์๋ฏธ๋ฅผ ์์๋ก ์ ์ํด์ฃผ์
๋ ๊ด์ฐฎ์์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,7 @@
+package store.entity;
+
+import java.time.LocalDate;
+
+public interface DateProvider {
+ LocalDate now();
+} | Java | ํ
์คํธ ํ ๋ ํด๋น ํด๋์ค๋ฅผ ๊ทธ๋๋ก ์ฌ์ฉํ๋ฉด ์ค๋ ๋ ์ง๋ก ํ
์คํธ๊ฐ ๋๊ธฐ ๋๋ฌธ์
๋๋ค! |
@@ -0,0 +1,57 @@
+package store.entity;
+
+import java.time.LocalDate;
+import java.util.Objects;
+
+public class Promotion {
+ private final String name;
+ private final int buy;
+ private final int get;
+ private final LocalDate startDate;
+ private final LocalDate endDate;
+
+ public Promotion(String name, int buy, int get, LocalDate startDate, LocalDate endDate) {
+ this.name = name;
+ this.buy = buy;
+ this.get = get;
+ this.startDate = startDate;
+ this.endDate = endDate;
+ }
+
+ public boolean isPromotionValid(LocalDate currentDate) {
+ return !currentDate.isBefore(startDate) && !currentDate.isAfter(endDate);
+ }
+
+ public boolean isInsufficientPromotion(Integer value) {
+ return value % (buy + get) >= buy;
+ }
+
+ public Integer getInsufficientPromotionQuantity(Integer value) {
+ return (buy + get) - value % (buy + get);
+ }
+
+ public Integer getCycle() {
+ return buy + get;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Promotion promotion = (Promotion) o;
+ return buy == promotion.buy &&
+ get == promotion.get &&
+ Objects.equals(name, promotion.name) &&
+ Objects.equals(startDate, promotion.startDate) &&
+ Objects.equals(endDate, promotion.endDate);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, buy, get, startDate, endDate);
+ }
+} | Java | ๊ทธ๋ ๋ค์! ์ข์ ์๊ฒฌ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,61 @@
+package store.entity;
+
+import static store.constant.Constant.ERROR_PREFIX;
+
+import java.util.List;
+import java.util.Map;
+
+public class Stock {
+ private static final String NON_EXIST_PRODUCT_MESSAGE = ERROR_PREFIX + "์กด์ฌํ์ง ์๋ ์ํ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final String STOCK_EXCEED_MESSAGE = ERROR_PREFIX + "์ฌ๊ณ ์๋์ ์ด๊ณผํ์ฌ ๊ตฌ๋งคํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.";
+
+ private final List<Product> stock;
+
+ public Stock(List<Product> stock) {
+ this.stock = stock;
+ }
+
+ public Product findByName(String name) {
+ return stock.stream()
+ .filter(product -> product.getName().equals(name))
+ .findFirst()
+ .orElseThrow(() -> new IllegalArgumentException(NON_EXIST_PRODUCT_MESSAGE));
+ }
+
+ public void validateAll(Map<String, Integer> items) {
+ items.forEach(this::validate);
+ }
+
+ public void update(Map<Product, Integer> cartItem) {
+ cartItem.forEach((product, quantity) -> {
+ Product stockProduct = findByName(product.getName());
+ if (product.isPromotionEligible()) {
+ stockProduct.reducePromotionQuantity(quantity);
+ } else {
+ stockProduct.reduceQuantity(quantity);
+ }
+ });
+ }
+
+ private void validate(String productName, Integer quantity) {
+ if (!isValidName(productName)) {
+ throw new IllegalArgumentException(NON_EXIST_PRODUCT_MESSAGE);
+ }
+ if (!isStockAvailable(productName, quantity)) {
+ throw new IllegalArgumentException(STOCK_EXCEED_MESSAGE);
+ }
+ }
+
+ private boolean isValidName(String name) {
+ return stock.stream().anyMatch(product -> product.getName().equals(name));
+ }
+
+ private boolean isStockAvailable(String productName, Integer quantity) {
+ Product product = findByName(productName);
+ return product.isStockAvailable(quantity);
+ }
+
+ public List<Product> getStock() {
+ return stock.stream().toList();
+ }
+} | Java | ํ๊ฑฑ.. ์ด๊ฑธ ๋ชป๋ดค๋ค์.. |
@@ -0,0 +1,40 @@
+package store.util.parse;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import store.entity.DateProvider;
+import store.entity.Product;
+import store.entity.Promotion;
+import store.entity.RealDateProvider;
+
+public class ProductParser {
+ private static final DateProvider dateProvider = new RealDateProvider();
+
+ public static List<Product> parse(List<String> products, Map<String, Promotion> promotions) {
+ List<Product> stockProduct = new ArrayList<>();
+ for (int i = 1; i < products.size(); i++) { // ํค๋ ๋ถ๋ถ ์ ์ธ
+ String[] fields = products.get(i).split(",");
+ int price = Integer.parseInt(fields[1]);
+ int quantity = Integer.parseInt(fields[2]);
+ Promotion promotion = promotions.get(fields[3]);
+ addOrUpdateProduct(stockProduct, fields[0], price, quantity, promotion);
+ }
+ return stockProduct;
+ }
+
+ private static void addOrUpdateProduct(List<Product> products, String name, int price, int quantity,
+ Promotion promotion) {
+ findProduct(products, name).ifPresentOrElse(
+ existingProduct -> existingProduct.addQuantity(quantity, promotion),
+ () -> products.add(new Product(name, price, quantity, promotion, dateProvider))
+ );
+ }
+
+ private static Optional<Product> findProduct(List<Product> products, String name) {
+ return products.stream()
+ .filter(p -> p.getName().equals(name))
+ .findFirst();
+ }
+} | Java | ์ข์ ์๊ฒฌ ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,7 @@
+package store.entity;
+
+import java.time.LocalDate;
+
+public interface DateProvider {
+ LocalDate now();
+} | Java | > ํ
์คํธ ํ ๋ ํด๋น ํด๋์ค๋ฅผ ๊ทธ๋๋ก ์ฌ์ฉํ๋ฉด ์ค๋ ๋ ์ง๋ก ํ
์คํธ๊ฐ ๋๊ธฐ ๋๋ฌธ์
๋๋ค!
์ด ๋ถ๋ถ์ ๋ํด ์ ๊ฐ ์ ์ดํด๋ฅผ ํ์ง ๋ชปํ์๋๋ฐ, ๊ฐ๋จํ ์์๋ฅผ ๋ง์ํด์ฃผ์ค ์ ์์๊น์?? |
@@ -1,7 +1,65 @@
package store;
+import static store.constant.Constant.ERROR_PREFIX;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import java.util.Map;
+import store.constant.YesOrNo;
+import store.controller.PurchaseController;
+import store.dto.StockResponse;
+import store.entity.Product;
+import store.entity.Promotion;
+import store.entity.Stock;
+import store.service.CartService;
+import store.service.StockService;
+import store.util.parse.PromotionParser;
+import store.util.parse.ProductParser;
+import store.view.InputView;
+import store.view.OutputView;
+
public class Application {
+ private static final String PRODUCT_FILE_PATH = "src/main/resources/products.md";
+ private static final String PROMOTION_FILE_PATH = "src/main/resources/promotions.md";
+ private static final String FILE_ERROR_MESSAGE = ERROR_PREFIX + "ํ์ผ์ ์ฝ๋๋ฐ ์คํจํ์ต๋๋ค.";
+
public static void main(String[] args) {
- // TODO: ํ๋ก๊ทธ๋จ ๊ตฌํ
+ List<Product> items = getInitProducts();
+ Stock stock = new Stock(items);
+ StockService stockService = new StockService(stock);
+ initializeApplication(stock, stockService);
+ }
+
+ private static void initializeApplication(Stock stock, StockService stockService) {
+ YesOrNo continueShopping = YesOrNo.YES;
+ while (continueShopping == YesOrNo.YES) {
+ CartService cartService = new CartService(stock);
+ PurchaseController purchaseController = new PurchaseController(cartService, stockService);
+ List<StockResponse> stockResult = purchaseController.getStock();
+ OutputView.printStartMessage(stockResult);
+ purchaseController.purchase();
+ continueShopping = InputView.askForAdditionalPurchase();
+ }
+ }
+
+ private static List<Product> getInitProducts() {
+ List<String> products = readFile(PRODUCT_FILE_PATH);
+ List<String> promotions = readFile(PROMOTION_FILE_PATH);
+ Map<String, Promotion> parsePromotions = PromotionParser.parse(promotions);
+ List<Product> items = ProductParser.parse(products, parsePromotions);
+ return items;
+ }
+
+ private static List<String> readFile(String filePath) {
+ try {
+ Path path = Paths.get(filePath);
+ return Files.readAllLines(path);
+ } catch (IOException e) {
+ throw new UncheckedIOException(FILE_ERROR_MESSAGE, e);
+ }
}
} | Java | ์ ๋ ๋์ํฉ๋๋ค! ์ ์ ํฉํ ๋ฆฌ ๋ฉ์๋ ์ด์ฉํด๋ณด๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,65 @@
+package store.controller;
+
+import java.util.List;
+import java.util.Map;
+import store.dto.ProductItem;
+import store.dto.StockResponse;
+import store.service.CartService;
+import store.service.StockService;
+import store.util.RetryHandler;
+import store.util.parse.PurchaseItemParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class PurchaseController {
+ private final CartService cartService;
+ private final StockService stockService;
+
+ public PurchaseController(CartService cartService, StockService stockService) {
+ this.cartService = cartService;
+ this.stockService = stockService;
+ }
+
+ public List<StockResponse> getStock() {
+ return stockService.getStock();
+ }
+
+ public void purchase() {
+ inputPurchaseItem();
+ inputAdditionalPromotionItem();
+ inputPromotionStock();
+ OutputView.printReceipt(cartService.pay(inputMembership()));
+ }
+
+ private void inputPromotionStock() {
+ RetryHandler.handleWithRetry(() -> {
+ List<ProductItem> nonPromotionItems = cartService.getNonPromotion();
+ if (!nonPromotionItems.isEmpty()) {
+ List<ProductItem> removeNonPromotionItems = InputView.askForNonPromotionItems(nonPromotionItems);
+ cartService.removeNonPromotionItems(removeNonPromotionItems);
+ }
+ });
+ }
+
+ private void inputPurchaseItem() {
+ RetryHandler.handleWithRetry(() -> {
+ String items = InputView.readItem();
+ Map<String, Integer> parseItems = PurchaseItemParser.parse(items);
+ cartService.purchase(parseItems);
+ });
+ }
+
+ private void inputAdditionalPromotionItem() {
+ RetryHandler.handleWithRetry(() -> {
+ List<ProductItem> additionalItems = cartService.getPromotionAdditionalItems();
+ if (!additionalItems.isEmpty()) {
+ List<ProductItem> items = InputView.askForPromotionItems(additionalItems);
+ cartService.addPromotionItems(items);
+ }
+ });
+ }
+
+ private boolean inputMembership() {
+ return RetryHandler.handleWithRetry(() -> InputView.askForMembership());
+ }
+} | Java | ์ ์ฒด์ ์ผ๋ก ์ฝ๋์ indent๊ฐ ๊น๋ค๋ ์๊ฐ์ด ๋ค์ด์! ๋ฏธ์
์๊ตฌ์ฌํญ์๋ indent๋ฅผ 2๊น์ง ํ์ฉํ๋ค๊ณ ๋ดค๋๋ฐ ์ด์ ๋ํด ์ด๋ป๊ฒ ์๊ฐํ์๋์? |
@@ -0,0 +1,4 @@
+package store.dto;
+
+public record ProductItem(String productName, int quantity) {
+} | Java | ๋ ์ฝ๋ ํ์ฉ๐ |
@@ -0,0 +1,24 @@
+package store.dto;
+
+import store.entity.Product;
+
+public record StockResponse(String name, int price, String quantity, String promotionQuantity, String promotionName) {
+ private static final String NONE_STOCK = "์ฌ๊ณ ์์";
+ private static final String QUANTITY_UNIT = "๊ฐ";
+
+ public static StockResponse from(Product product) {
+ String promotionName = "";
+ if (product.getPromotion() != null) {
+ promotionName = product.getPromotion().getName();
+ }
+ return new StockResponse(product.getName(), product.getPrice(), formatQuantity(product.getQuantity()),
+ formatQuantity(product.getPromotionQuantity()), promotionName);
+ }
+
+ private static String formatQuantity(int quantity) {
+ if (quantity == 0) {
+ return NONE_STOCK;
+ }
+ return quantity + QUANTITY_UNIT;
+ }
+} | Java | ๋น ๋ฌธ์์ด๋ก ์ด๊ธฐํํ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,117 @@
+package store.entity;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import store.dto.FinalPaymentProduct;
+import store.dto.ProductItem;
+import store.dto.ProductItemWithPrice;
+
+public class Cart {
+ private final Map<Product, Integer> cartItem;
+
+ public Cart() {
+ this.cartItem = new LinkedHashMap<>();
+ }
+
+ public void addProduct(Product product, int quantity) {
+ cartItem.put(product, cartItem.getOrDefault(product, 0) + quantity);
+ }
+
+ public void addPromotionItems(Product product, int additionalQuantity) {
+ cartItem.put(product, cartItem.get(product) + additionalQuantity);
+ }
+
+ public void removeNonPromotionItems(Product product, int quantity) {
+ cartItem.put(product, cartItem.get(product) - quantity);
+ }
+
+ public List<ProductItem> getInsufficientPromotionItems() {
+ List<ProductItem> insufficientPromotionItems = new ArrayList<>();
+ for (Map.Entry<Product, Integer> cart : getPromotionItems().entrySet()) {
+ Product product = cart.getKey();
+ if (product.isInsufficientPromotion(cart.getValue())) {
+ int insufficientQuantity = product.getInsufficientPromotionQuantity(cart.getValue());
+ insufficientPromotionItems.add(new ProductItem(product.getName(), insufficientQuantity));
+ }
+ }
+ return insufficientPromotionItems;
+ }
+
+ public List<ProductItem> getNonPromotionItems() {
+ List<ProductItem> nonPromotionItems = new ArrayList<>();
+ for (Map.Entry<Product, Integer> cart : getPromotionItems().entrySet()) {
+ Product product = cart.getKey();
+ if (product.isInSufficientPromotionStock(cart.getValue())) {
+ int nonPromotionQuantity = product.getNonEligiblePromotionQuantity(cart.getValue());
+ nonPromotionItems.add(new ProductItem(product.getName(), nonPromotionQuantity));
+ }
+ }
+ return nonPromotionItems;
+ }
+
+ public Map<Product, Integer> getPromotionItems() {
+ Map<Product, Integer> promotionItems = new LinkedHashMap<>();
+ for (Map.Entry<Product, Integer> entry : cartItem.entrySet()) {
+ Product product = entry.getKey();
+ if (product.isPromotionEligible()) {
+ promotionItems.put(product, entry.getValue());
+ }
+ }
+ return promotionItems;
+ }
+
+ public FinalPaymentProduct getFinalPaymentItems() {
+ Cart discountedCart = new Cart();
+ Cart nonDiscountedCart = new Cart();
+ for (Map.Entry<Product, Integer> entry : cartItem.entrySet()) {
+ if (isEligibleForPromotion(entry.getKey())) {
+ processPromotionProduct(entry.getKey(), entry.getValue(), discountedCart, nonDiscountedCart);
+ } else {
+ nonDiscountedCart.addProduct(entry.getKey(), entry.getValue());
+ }
+ }
+ return new FinalPaymentProduct(discountedCart, nonDiscountedCart);
+ }
+
+ public int getTotalPrice() {
+ return cartItem.entrySet().stream()
+ .mapToInt(entry -> entry.getKey().getPrice() * entry.getValue())
+ .sum();
+ }
+
+ public List<ProductItemWithPrice> getCartItemsWithPrice() {
+ return cartItem.entrySet().stream()
+ .map(entry -> new ProductItemWithPrice(entry.getKey().getName(), entry.getValue(),
+ entry.getKey().getPrice()))
+ .toList();
+ }
+
+ public List<ProductItem> getCartItems() {
+ return cartItem.entrySet().stream()
+ .map(entry -> new ProductItem(entry.getKey().getName(), entry.getValue()))
+ .toList();
+ }
+
+ private boolean isEligibleForPromotion(Product product) {
+ return product.getPromotion() != null && product.isPromotionEligible();
+ }
+
+ private void processPromotionProduct(Product product, Integer orderedQuantity, Cart discountedCart,
+ Cart nonDiscountedCart) {
+ int nonPromotionQuantity = product.getNonEligiblePromotionQuantity(orderedQuantity);
+ int promotionCount = orderedQuantity - nonPromotionQuantity;
+ int promotableQuantity = product.calculateEligiblePromotionQuantity(promotionCount);
+ if (promotableQuantity > 0) {
+ discountedCart.addProduct(product, promotableQuantity);
+ }
+ if (nonPromotionQuantity > 0) {
+ nonDiscountedCart.addProduct(product, nonPromotionQuantity);
+ }
+ }
+
+ public Map<Product, Integer> getCartItem() {
+ return cartItem;
+ }
+} | Java | Cart ํด๋์ค์์ ์์ฑ์ ์์กด์ฑ ์ฃผ์
์ ์ฌ์ฉํ๊ฒ ๋ ๊ณ๊ธฐ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,61 @@
+package store.entity;
+
+import static store.constant.Constant.ERROR_PREFIX;
+
+import java.util.List;
+import java.util.Map;
+
+public class Stock {
+ private static final String NON_EXIST_PRODUCT_MESSAGE = ERROR_PREFIX + "์กด์ฌํ์ง ์๋ ์ํ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final String STOCK_EXCEED_MESSAGE = ERROR_PREFIX + "์ฌ๊ณ ์๋์ ์ด๊ณผํ์ฌ ๊ตฌ๋งคํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.";
+
+ private final List<Product> stock;
+
+ public Stock(List<Product> stock) {
+ this.stock = stock;
+ }
+
+ public Product findByName(String name) {
+ return stock.stream()
+ .filter(product -> product.getName().equals(name))
+ .findFirst()
+ .orElseThrow(() -> new IllegalArgumentException(NON_EXIST_PRODUCT_MESSAGE));
+ }
+
+ public void validateAll(Map<String, Integer> items) {
+ items.forEach(this::validate);
+ }
+
+ public void update(Map<Product, Integer> cartItem) {
+ cartItem.forEach((product, quantity) -> {
+ Product stockProduct = findByName(product.getName());
+ if (product.isPromotionEligible()) {
+ stockProduct.reducePromotionQuantity(quantity);
+ } else {
+ stockProduct.reduceQuantity(quantity);
+ }
+ });
+ }
+
+ private void validate(String productName, Integer quantity) {
+ if (!isValidName(productName)) {
+ throw new IllegalArgumentException(NON_EXIST_PRODUCT_MESSAGE);
+ }
+ if (!isStockAvailable(productName, quantity)) {
+ throw new IllegalArgumentException(STOCK_EXCEED_MESSAGE);
+ }
+ }
+
+ private boolean isValidName(String name) {
+ return stock.stream().anyMatch(product -> product.getName().equals(name));
+ }
+
+ private boolean isStockAvailable(String productName, Integer quantity) {
+ Product product = findByName(productName);
+ return product.isStockAvailable(quantity);
+ }
+
+ public List<Product> getStock() {
+ return stock.stream().toList();
+ }
+} | Java | ์์ธ๋ฅผ `isValidName`๋ฉ์๋์ `isStockAvailable`๋ฉ์๋์์ ๋์ง๋๊ฒ ์ด๋จ๊น์? |
@@ -0,0 +1,93 @@
+package store.view;
+
+import java.util.List;
+import store.dto.ProductItem;
+import store.dto.ProductItemWithPrice;
+import store.dto.Receipt;
+import store.dto.StockResponse;
+
+public class OutputView {
+ private static final String START_MESSAGE = "์๋
ํ์ธ์. Wํธ์์ ์
๋๋ค.\nํ์ฌ ๋ณด์ ํ๊ณ ์๋ ์ํ์
๋๋ค.\n";
+ private static final String PROMOTION_IN_STOCK_FORMAT = "- %s %,d์ %s %s";
+ private static final String REGULAR_IN_STOCK_FORMAT = "- %s %,d์ %s";
+ private static final String RECEIPT_HEADER = "==============W ํธ์์ ================";
+ private static final String RECEIPT_ITEM_HEADER = String.format("%-17s %-9s %-1s", "์ํ๋ช
", "์๋", "๊ธ์ก");
+ private static final String NAME_QUANTITY_PRICE = "%-17s %-9d %,d";
+ private static final String RECEIPT_PROMOTION_HEADER = "=============์ฆ ์ ===============";
+ private static final String NAME_QUANTITY_ONLY = "%-17s %d";
+ private static final String RECEIPT_FOOTER = "====================================";
+ private static final String NAME_AMOUNT_ONLY = "%-27s -%,d";
+ private static final String NAME_AMOUNT_FINAL_AMOUNT = "%-27s %,d";
+ private static final String TOTAL_AMOUNT_LABEL = "์ด๊ตฌ๋งค์ก";
+ private static final String EVENT_DISCOUNT_LABEL = "ํ์ฌํ ์ธ";
+ private static final String MEMBERSHIP_DISCOUNT_LABEL = "๋ฉค๋ฒ์ญํ ์ธ";
+ private static final String FINAL_PAYMENT_LABEL = "๋ด์ค๋";
+
+ public static void printStartMessage(List<StockResponse> stock) {
+ System.out.println(START_MESSAGE);
+ for (StockResponse stockResponse : stock) {
+ if (!stockResponse.promotionName().isBlank()) {
+ printStockWithPromotion(stockResponse);
+ continue;
+ }
+ printStockWithoutPromotion(stockResponse);
+ }
+ System.out.println();
+ }
+
+ public static void printErrorMessage(String errorMessage) {
+ System.out.println(errorMessage);
+ }
+
+ private static void printStockWithPromotion(StockResponse stockResponse) {
+ System.out.println(
+ String.format(PROMOTION_IN_STOCK_FORMAT, stockResponse.name(), stockResponse.price(),
+ stockResponse.promotionQuantity(),
+ stockResponse.promotionName()));
+ System.out.println(String.format(REGULAR_IN_STOCK_FORMAT, stockResponse.name(), stockResponse.price(),
+ stockResponse.quantity()));
+ }
+
+ private static void printStockWithoutPromotion(StockResponse stockResponse) {
+ System.out.println(String.format(REGULAR_IN_STOCK_FORMAT, stockResponse.name(), stockResponse.price(),
+ stockResponse.quantity()));
+ }
+
+ public static void printReceipt(Receipt receipt) {
+ System.out.println(RECEIPT_HEADER);
+ printPurchaseProduct(receipt);
+ printPresent(receipt);
+ printAmount(receipt);
+ }
+
+ private static void printPurchaseProduct(Receipt receipt) {
+ System.out.println(RECEIPT_ITEM_HEADER);
+ for (ProductItemWithPrice productItem: receipt.purchaseProducts()) {
+ System.out.println(String.format(NAME_QUANTITY_PRICE,
+ productItem.productName(),
+ productItem.quantity(),
+ productItem.quantity() * productItem.price()
+ ));
+ }
+ }
+
+ private static void printPresent(Receipt receipt) {
+ List<ProductItem> discountedItems = receipt.promotionDiscountedItems();
+ if (!discountedItems.isEmpty()) {
+ System.out.println(RECEIPT_PROMOTION_HEADER);
+ discountedItems.forEach(
+ item -> System.out.println(String.format(NAME_QUANTITY_ONLY, item.productName(), item.quantity())));
+ }
+ System.out.println(RECEIPT_FOOTER);
+ }
+
+ private static void printAmount(Receipt receipt) {
+ System.out.printf(NAME_QUANTITY_PRICE + "\n", TOTAL_AMOUNT_LABEL,
+ receipt.purchaseProducts().stream().mapToInt(productItem -> productItem.quantity()).sum(),
+ receipt.amount().totalAmount());
+ System.out.printf(NAME_AMOUNT_ONLY + "\n", EVENT_DISCOUNT_LABEL, receipt.amount().promotionDiscountAmount());
+ System.out.printf(NAME_AMOUNT_ONLY + "\n", MEMBERSHIP_DISCOUNT_LABEL,
+ receipt.amount().membershipDiscountAmount());
+ System.out.printf(NAME_AMOUNT_FINAL_AMOUNT + "\n", FINAL_PAYMENT_LABEL, receipt.amount().finalAmount());
+ }
+} | Java | DTO์ ์ปฌ๋ ์
์ฌ์ฉํด์ ์ถ๋ ฅ์ ๊น๋ํ๊ฒ ํ์
จ๋ค์! ๋ฐฐ์ฐ๊ณ ๊ฐ๋๋ค!! |
@@ -0,0 +1,65 @@
+package store.controller;
+
+import java.util.List;
+import java.util.Map;
+import store.dto.ProductItem;
+import store.dto.StockResponse;
+import store.service.CartService;
+import store.service.StockService;
+import store.util.RetryHandler;
+import store.util.parse.PurchaseItemParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class PurchaseController {
+ private final CartService cartService;
+ private final StockService stockService;
+
+ public PurchaseController(CartService cartService, StockService stockService) {
+ this.cartService = cartService;
+ this.stockService = stockService;
+ }
+
+ public List<StockResponse> getStock() {
+ return stockService.getStock();
+ }
+
+ public void purchase() {
+ inputPurchaseItem();
+ inputAdditionalPromotionItem();
+ inputPromotionStock();
+ OutputView.printReceipt(cartService.pay(inputMembership()));
+ }
+
+ private void inputPromotionStock() {
+ RetryHandler.handleWithRetry(() -> {
+ List<ProductItem> nonPromotionItems = cartService.getNonPromotion();
+ if (!nonPromotionItems.isEmpty()) {
+ List<ProductItem> removeNonPromotionItems = InputView.askForNonPromotionItems(nonPromotionItems);
+ cartService.removeNonPromotionItems(removeNonPromotionItems);
+ }
+ });
+ }
+
+ private void inputPurchaseItem() {
+ RetryHandler.handleWithRetry(() -> {
+ String items = InputView.readItem();
+ Map<String, Integer> parseItems = PurchaseItemParser.parse(items);
+ cartService.purchase(parseItems);
+ });
+ }
+
+ private void inputAdditionalPromotionItem() {
+ RetryHandler.handleWithRetry(() -> {
+ List<ProductItem> additionalItems = cartService.getPromotionAdditionalItems();
+ if (!additionalItems.isEmpty()) {
+ List<ProductItem> items = InputView.askForPromotionItems(additionalItems);
+ cartService.addPromotionItems(items);
+ }
+ });
+ }
+
+ private boolean inputMembership() {
+ return RetryHandler.handleWithRetry(() -> InputView.askForMembership());
+ }
+} | Java | ์ ์ฝ๋๋ indent๊ฐ 2 ์๋๊ฐ์?! |
@@ -0,0 +1,24 @@
+package store.dto;
+
+import store.entity.Product;
+
+public record StockResponse(String name, int price, String quantity, String promotionQuantity, String promotionName) {
+ private static final String NONE_STOCK = "์ฌ๊ณ ์์";
+ private static final String QUANTITY_UNIT = "๊ฐ";
+
+ public static StockResponse from(Product product) {
+ String promotionName = "";
+ if (product.getPromotion() != null) {
+ promotionName = product.getPromotion().getName();
+ }
+ return new StockResponse(product.getName(), product.getPrice(), formatQuantity(product.getQuantity()),
+ formatQuantity(product.getPromotionQuantity()), promotionName);
+ }
+
+ private static String formatQuantity(int quantity) {
+ if (quantity == 0) {
+ return NONE_STOCK;
+ }
+ return quantity + QUANTITY_UNIT;
+ }
+} | Java | OutputView ์์ ํด๋น promotionName์ ์ํ์ ๋ฐ๋ผ ๋ค๋ฅธ ํฌ๋งท์ ์ ์ฉ์ํค๋ ค๊ณ ํ์ต๋๋ค! |
@@ -0,0 +1,117 @@
+package store.entity;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import store.dto.FinalPaymentProduct;
+import store.dto.ProductItem;
+import store.dto.ProductItemWithPrice;
+
+public class Cart {
+ private final Map<Product, Integer> cartItem;
+
+ public Cart() {
+ this.cartItem = new LinkedHashMap<>();
+ }
+
+ public void addProduct(Product product, int quantity) {
+ cartItem.put(product, cartItem.getOrDefault(product, 0) + quantity);
+ }
+
+ public void addPromotionItems(Product product, int additionalQuantity) {
+ cartItem.put(product, cartItem.get(product) + additionalQuantity);
+ }
+
+ public void removeNonPromotionItems(Product product, int quantity) {
+ cartItem.put(product, cartItem.get(product) - quantity);
+ }
+
+ public List<ProductItem> getInsufficientPromotionItems() {
+ List<ProductItem> insufficientPromotionItems = new ArrayList<>();
+ for (Map.Entry<Product, Integer> cart : getPromotionItems().entrySet()) {
+ Product product = cart.getKey();
+ if (product.isInsufficientPromotion(cart.getValue())) {
+ int insufficientQuantity = product.getInsufficientPromotionQuantity(cart.getValue());
+ insufficientPromotionItems.add(new ProductItem(product.getName(), insufficientQuantity));
+ }
+ }
+ return insufficientPromotionItems;
+ }
+
+ public List<ProductItem> getNonPromotionItems() {
+ List<ProductItem> nonPromotionItems = new ArrayList<>();
+ for (Map.Entry<Product, Integer> cart : getPromotionItems().entrySet()) {
+ Product product = cart.getKey();
+ if (product.isInSufficientPromotionStock(cart.getValue())) {
+ int nonPromotionQuantity = product.getNonEligiblePromotionQuantity(cart.getValue());
+ nonPromotionItems.add(new ProductItem(product.getName(), nonPromotionQuantity));
+ }
+ }
+ return nonPromotionItems;
+ }
+
+ public Map<Product, Integer> getPromotionItems() {
+ Map<Product, Integer> promotionItems = new LinkedHashMap<>();
+ for (Map.Entry<Product, Integer> entry : cartItem.entrySet()) {
+ Product product = entry.getKey();
+ if (product.isPromotionEligible()) {
+ promotionItems.put(product, entry.getValue());
+ }
+ }
+ return promotionItems;
+ }
+
+ public FinalPaymentProduct getFinalPaymentItems() {
+ Cart discountedCart = new Cart();
+ Cart nonDiscountedCart = new Cart();
+ for (Map.Entry<Product, Integer> entry : cartItem.entrySet()) {
+ if (isEligibleForPromotion(entry.getKey())) {
+ processPromotionProduct(entry.getKey(), entry.getValue(), discountedCart, nonDiscountedCart);
+ } else {
+ nonDiscountedCart.addProduct(entry.getKey(), entry.getValue());
+ }
+ }
+ return new FinalPaymentProduct(discountedCart, nonDiscountedCart);
+ }
+
+ public int getTotalPrice() {
+ return cartItem.entrySet().stream()
+ .mapToInt(entry -> entry.getKey().getPrice() * entry.getValue())
+ .sum();
+ }
+
+ public List<ProductItemWithPrice> getCartItemsWithPrice() {
+ return cartItem.entrySet().stream()
+ .map(entry -> new ProductItemWithPrice(entry.getKey().getName(), entry.getValue(),
+ entry.getKey().getPrice()))
+ .toList();
+ }
+
+ public List<ProductItem> getCartItems() {
+ return cartItem.entrySet().stream()
+ .map(entry -> new ProductItem(entry.getKey().getName(), entry.getValue()))
+ .toList();
+ }
+
+ private boolean isEligibleForPromotion(Product product) {
+ return product.getPromotion() != null && product.isPromotionEligible();
+ }
+
+ private void processPromotionProduct(Product product, Integer orderedQuantity, Cart discountedCart,
+ Cart nonDiscountedCart) {
+ int nonPromotionQuantity = product.getNonEligiblePromotionQuantity(orderedQuantity);
+ int promotionCount = orderedQuantity - nonPromotionQuantity;
+ int promotableQuantity = product.calculateEligiblePromotionQuantity(promotionCount);
+ if (promotableQuantity > 0) {
+ discountedCart.addProduct(product, promotableQuantity);
+ }
+ if (nonPromotionQuantity > 0) {
+ nonDiscountedCart.addProduct(product, nonPromotionQuantity);
+ }
+ }
+
+ public Map<Product, Integer> getCartItem() {
+ return cartItem;
+ }
+} | Java | ์์ฑ์์ ์๋ฌด๊ฒ๋ ๋ฐ์ง ์์์ ์์กด์ฑ ์ฃผ์
์ ์๋์ง ์๋์?! |
@@ -0,0 +1,7 @@
+package store.entity;
+
+import java.time.LocalDate;
+
+public interface DateProvider {
+ LocalDate now();
+} | Java | ํ
์คํธ ์ฝ๋์์ ์ค์ ์ค๋๋ ์ง๋ฅผ ๋ฐํํ๋ now()๋ฅผ ์ฌ์ฉํ๊ฒ๋๋ฉด ํ
์คํธ์ฝ๋๊ฐ ํด๋น ๋ ์ง์ ์์กดํ์ง ์์๊น์?? |
@@ -0,0 +1,61 @@
+package store.entity;
+
+import static store.constant.Constant.ERROR_PREFIX;
+
+import java.util.List;
+import java.util.Map;
+
+public class Stock {
+ private static final String NON_EXIST_PRODUCT_MESSAGE = ERROR_PREFIX + "์กด์ฌํ์ง ์๋ ์ํ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final String STOCK_EXCEED_MESSAGE = ERROR_PREFIX + "์ฌ๊ณ ์๋์ ์ด๊ณผํ์ฌ ๊ตฌ๋งคํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.";
+
+ private final List<Product> stock;
+
+ public Stock(List<Product> stock) {
+ this.stock = stock;
+ }
+
+ public Product findByName(String name) {
+ return stock.stream()
+ .filter(product -> product.getName().equals(name))
+ .findFirst()
+ .orElseThrow(() -> new IllegalArgumentException(NON_EXIST_PRODUCT_MESSAGE));
+ }
+
+ public void validateAll(Map<String, Integer> items) {
+ items.forEach(this::validate);
+ }
+
+ public void update(Map<Product, Integer> cartItem) {
+ cartItem.forEach((product, quantity) -> {
+ Product stockProduct = findByName(product.getName());
+ if (product.isPromotionEligible()) {
+ stockProduct.reducePromotionQuantity(quantity);
+ } else {
+ stockProduct.reduceQuantity(quantity);
+ }
+ });
+ }
+
+ private void validate(String productName, Integer quantity) {
+ if (!isValidName(productName)) {
+ throw new IllegalArgumentException(NON_EXIST_PRODUCT_MESSAGE);
+ }
+ if (!isStockAvailable(productName, quantity)) {
+ throw new IllegalArgumentException(STOCK_EXCEED_MESSAGE);
+ }
+ }
+
+ private boolean isValidName(String name) {
+ return stock.stream().anyMatch(product -> product.getName().equals(name));
+ }
+
+ private boolean isStockAvailable(String productName, Integer quantity) {
+ Product product = findByName(productName);
+ return product.isStockAvailable(quantity);
+ }
+
+ public List<Product> getStock() {
+ return stock.stream().toList();
+ }
+} | Java | ๊ทธ๋๋ ๋ ๊ฒ๊ฐ๋ค์! |
@@ -1,7 +1,65 @@
package store;
+import static store.constant.Constant.ERROR_PREFIX;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import java.util.Map;
+import store.constant.YesOrNo;
+import store.controller.PurchaseController;
+import store.dto.StockResponse;
+import store.entity.Product;
+import store.entity.Promotion;
+import store.entity.Stock;
+import store.service.CartService;
+import store.service.StockService;
+import store.util.parse.PromotionParser;
+import store.util.parse.ProductParser;
+import store.view.InputView;
+import store.view.OutputView;
+
public class Application {
+ private static final String PRODUCT_FILE_PATH = "src/main/resources/products.md";
+ private static final String PROMOTION_FILE_PATH = "src/main/resources/promotions.md";
+ private static final String FILE_ERROR_MESSAGE = ERROR_PREFIX + "ํ์ผ์ ์ฝ๋๋ฐ ์คํจํ์ต๋๋ค.";
+
public static void main(String[] args) {
- // TODO: ํ๋ก๊ทธ๋จ ๊ตฌํ
+ List<Product> items = getInitProducts();
+ Stock stock = new Stock(items);
+ StockService stockService = new StockService(stock);
+ initializeApplication(stock, stockService);
+ }
+
+ private static void initializeApplication(Stock stock, StockService stockService) {
+ YesOrNo continueShopping = YesOrNo.YES;
+ while (continueShopping == YesOrNo.YES) {
+ CartService cartService = new CartService(stock);
+ PurchaseController purchaseController = new PurchaseController(cartService, stockService);
+ List<StockResponse> stockResult = purchaseController.getStock();
+ OutputView.printStartMessage(stockResult);
+ purchaseController.purchase();
+ continueShopping = InputView.askForAdditionalPurchase();
+ }
+ }
+
+ private static List<Product> getInitProducts() {
+ List<String> products = readFile(PRODUCT_FILE_PATH);
+ List<String> promotions = readFile(PROMOTION_FILE_PATH);
+ Map<String, Promotion> parsePromotions = PromotionParser.parse(promotions);
+ List<Product> items = ProductParser.parse(products, parsePromotions);
+ return items;
+ }
+
+ private static List<String> readFile(String filePath) {
+ try {
+ Path path = Paths.get(filePath);
+ return Files.readAllLines(path);
+ } catch (IOException e) {
+ throw new UncheckedIOException(FILE_ERROR_MESSAGE, e);
+ }
}
} | Java | ์ข์ ์๊ฒฌ ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,100 @@
+package store;
+
+import java.util.Map;
+import store.model.order.Payment;
+import store.model.order.PurchaseOrder;
+import store.model.store.StoreRoom;
+import store.util.parser.ClosedQuestionsParser;
+import store.util.parser.PurchaseParser;
+import store.util.reader.RepeatableReader;
+import store.view.ErrorView;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreApplication {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final ErrorView errorView;
+ private final StoreRoom storeRoom;
+
+ public StoreApplication(InputView inputView, OutputView outputView, ErrorView errorView, StoreRoom storeRoom) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.errorView = errorView;
+ this.storeRoom = storeRoom;
+ }
+
+ public void run() {
+ while (true) {
+ outputView.printProducts(storeRoom);
+ processPurchase();
+ boolean buyMore = RepeatableReader.handle(inputView::askAdditionalPurchase,
+ ClosedQuestionsParser::parseAnswer, errorView::errorPage);
+ if (!buyMore) {
+ return;
+ }
+ }
+ }
+
+ private void processPurchase() {
+ PurchaseOrder purchaseOrder = createPurchaseOrder(storeRoom);
+ purchaseOrder = adjustOrderWithPromotions(purchaseOrder, storeRoom);
+ if (purchaseOrder.getTotalBuyAmount() <= 0) {
+ return;
+ }
+ boolean hasMembership = RepeatableReader.handle(inputView::askMembership, ClosedQuestionsParser::parseAnswer,
+ errorView::errorPage);
+ Payment payment = Payment.from(purchaseOrder, storeRoom, hasMembership);
+ outputView.printReceipt(payment);
+ storeRoom.arrange(payment.getPurchaseOrder().getPurchaseOrder());
+ }
+
+ private PurchaseOrder createPurchaseOrder(StoreRoom storeRoom) {
+ return RepeatableReader.handle(inputView::readItem, (userInput) -> {
+ Map<String, Integer> items = PurchaseParser.parseInputItems(userInput);
+ return PurchaseOrder.from(items, storeRoom);
+ }, errorView::errorPage);
+ }
+
+ private PurchaseOrder adjustOrderWithPromotions(PurchaseOrder purchaseOrder, StoreRoom storeRoom) {
+ PurchaseOrder result = purchaseOrder;
+ for (Map.Entry<String, Integer> entry : purchaseOrder.getPurchaseOrder().entrySet()) {
+ result = applyPromotionToProduct(result, storeRoom, entry.getKey(), entry.getValue());
+ }
+ return result;
+ }
+
+ private PurchaseOrder applyPromotionToProduct(PurchaseOrder purchaseOrder,
+ StoreRoom storeRoom,
+ String productName,
+ int buyAmount) {
+ int fullPriceAmount = storeRoom.getNonPromotionalQuantity(productName, buyAmount);
+ if (fullPriceAmount > 0) {
+ purchaseOrder = purchaseOrder
+ .decreaseBuyAmount(productName, getDecreaseAmount(productName, fullPriceAmount));
+ }
+ if (storeRoom.canGetOneMore(productName, buyAmount)) {
+ purchaseOrder = purchaseOrder.increaseBuyAmount(productName, getIncreaseAmount(productName));
+ }
+ return purchaseOrder;
+ }
+
+ private int getDecreaseAmount(String productName, int fullPriceAmount) {
+ boolean isAgree = RepeatableReader.handle(() ->
+ inputView.askFullPrice(productName, fullPriceAmount), ClosedQuestionsParser::parseAnswer,
+ errorView::errorPage);
+ if (!isAgree) {
+ return fullPriceAmount;
+ }
+ return 0;
+ }
+
+ private int getIncreaseAmount(String productName) {
+ boolean isAgree = RepeatableReader.handle(() ->
+ inputView.askAddOne(productName), ClosedQuestionsParser::parseAnswer, errorView::errorPage);
+ if (isAgree) {
+ return 1;
+ }
+ return 0;
+ }
+} | Java | ๋ฉค๋ฒ์ญ์ ์ ์ฉํ๋ค๋ ๊ด์ ์ด ์๋๋ผ, has ํค์๋๋ฅผ ์ฌ์ฉํด์ ๋ฉค๋ฒ์ญ์ด ์๋ค๋ฉด ๋ฐ๋์ ์ ์ฉํ๋ค๋ ๊ด์ ์ด ์๋นํ ์ง๊ด์ ์ด๊ณ ์ดํด๊ฐ ์ ๋๋ค์.
๊ทธ๋ ์ง๋ง ์ถ๋ ฅ๋๋ ๋ฌธ์ฅ์ด `๋ฉค๋ฒ์ญ ํ ์ธ์ ๋ฐ์ผ์๊ฒ ์ต๋๊น? (Y/N)`์ธ๋ฐ ์ถ์ํํด์ ํํํด๋ ๋๋ ๊ฑธ๊น์? |
@@ -0,0 +1,29 @@
+package store.exception.store;
+
+public enum StoreErrorStatus {
+
+ INSUFFICIENT_STOCK("์ฌ๊ณ ์๋์ ์ด๊ณผํ์ฌ ๊ตฌ๋งคํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
+ NON_EXIST_PRODUCT("์กด์ฌํ์ง ์๋ ์ํ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
+ DUPLICATE_GENERAL_PRODUCT("์ํ์ด ์ค๋ณต๋์์ต๋๋ค."),
+ DUPLICATE_PROMOTION_PRODUCT("ํ๋์ ์ํ์ ๋๊ฐ์ ํ๋ก๋ชจ์
์ด ์ ์ฉ๋ ์ ์์ต๋๋ค."),
+
+ INVALID_PROMOTION_BUY_AMOUNT("๊ตฌ๋งค ๊ฐ์๋ 0 ์ดํ๊ฐ ๋ ์ ์์ต๋๋ค."),
+ INVALID_PROMOTION_GIVE_AMOUNT("์ถ๊ฐ ์ฆ์ ์ ํ๋๋ง ๊ฐ๋ฅํฉ๋๋ค."),
+ NON_EXIST_PROMOTION("์กด์ฌํ์ง ์๋ ํ๋ก๋ชจ์
์ด ์์ต๋๋ค."),
+ DUPLICATE_PROMOTION_NAME("ํ๋ก๋ชจ์
์ ์ด๋ฆ์ ์ค๋ณต๋ ์ ์์ต๋๋ค."),
+
+ INVALID_PRODUCT_PRICE("๊ฐ๊ฒฉ์ 0 ์ดํ๊ฐ ๋ ์ ์์ต๋๋ค."),
+ INVALID_PRODUCT_STOCK("์ฌ๊ณ ๋ ์์๊ฐ ๋ ์ ์์ต๋๋ค."),
+
+ PRODUCT_PRICE_INCONSISTENT("์ผ๋ฐ ์ํ๊ณผ ํ๋ก๋ชจ์
์ํ์ ๊ฐ๊ฒฉ์ ๋์ผํด์ผํฉ๋๋ค.");
+
+ private final String message;
+
+ StoreErrorStatus(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+} | Java | ๋ฐ์ฑํ๊ฒ ๋ง๋๋ ์์ธ ๋ฆฌ์คํธ๋ค์... ๋๋จํ์ญ๋๋ค. |
@@ -0,0 +1,92 @@
+package store.model.order;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.util.Map;
+import java.util.stream.Collectors;
+import store.model.store.StoreRoom;
+import store.model.store.product.Product;
+
+public class Payment {
+ private final PurchaseOrder purchaseOrder;
+ private final StoreRoom storeRoom;
+ private final boolean hasMembership;
+
+ private Payment(PurchaseOrder purchaseOrder, StoreRoom storeRoom, boolean hasMembership) {
+ this.purchaseOrder = purchaseOrder;
+ this.storeRoom = storeRoom;
+ this.hasMembership = hasMembership;
+ }
+
+ public static Payment from(PurchaseOrder purchaseOrder, StoreRoom storeRoom, boolean hasMembership) {
+ return new Payment(purchaseOrder, storeRoom, hasMembership);
+ }
+
+ public long calculateActualPrice() {
+ long promotionalDiscount = calculatePromotionalDiscount();
+ long membershipDiscount = calculateMembershipDiscount();
+ long totalPrice = calculateTotalPrice();
+ return totalPrice - (promotionalDiscount + membershipDiscount);
+ }
+
+ public long calculatePromotionalDiscount() {
+ return extractPromotionalProducts().entrySet().stream()
+ .mapToLong(entry -> (long) storeRoom.getProductPrice(entry.getKey()) * entry.getValue())
+ .sum();
+ }
+
+ public long calculateMembershipDiscount() {
+ if (!hasMembership) {
+ return 0;
+ }
+ long promotionAppliedPrice = extractPromotionalProducts().entrySet().stream()
+ .mapToLong(entry -> {
+ Product product = storeRoom.getPromotionProducts().findNullableProductByName(entry.getKey());
+ return (long) product.getPrice() * entry.getValue() * product.getPromotionUnit();
+ }).sum();
+ long membershipDiscount = (long) ((calculateTotalPrice() - promotionAppliedPrice) * 0.3);
+ return Math.min(8000L, membershipDiscount);
+ }
+
+ public long calculateTotalPrice() {
+ return purchaseOrder.getPurchaseOrder().entrySet().stream()
+ .mapToLong(entry -> (long) storeRoom.getProductPrice(entry.getKey()) * entry.getValue())
+ .sum();
+ }
+
+ public long calculateProductPrice(String productName) {
+ int buyAmount = purchaseOrder.getPurchaseOrder().get(productName);
+ int productPrice = storeRoom.getProductPrice(productName);
+ return (long) buyAmount * productPrice;
+ }
+
+ public long calculateTotalBuyAmount() {
+ return purchaseOrder.getPurchaseOrder().values().stream()
+ .mapToLong(Long::valueOf)
+ .sum();
+ }
+
+ private int calculateGiveawayAmount(String productName, int quantity) {
+ Product product = storeRoom.getPromotionProducts().findNullableProductByName(productName);
+ if (product != null
+ && product.isPromotionPeriod(DateTimes.now())
+ && product.getStock() >= product.getPromotionUnit()) {
+ int promotionalQuantity = quantity - storeRoom.getNonPromotionalQuantity(productName, quantity);
+ return promotionalQuantity / product.getPromotionUnit();
+ }
+ return 0;
+ }
+
+ public Map<String, Integer> extractPromotionalProducts() {
+ return purchaseOrder.getPurchaseOrder().entrySet().stream()
+ .map(entry -> Map.entry(
+ entry.getKey(),
+ calculateGiveawayAmount(entry.getKey(), entry.getValue())
+ ))
+ .filter(entry -> entry.getValue() > 0)
+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+ }
+
+ public PurchaseOrder getPurchaseOrder() {
+ return purchaseOrder;
+ }
+} | Java | ํ๋ผ๋ฏธํฐ๊ฐ 2๊ฐ ์ด์์ด๋ผ๋ฉด of ๋ฅผ ์ฌ์ฉํ์ง ์๋์? ๊ตณ์ด ์ ๊ฒฝ์ฐ์ง ์๋ ๋ถ๋ถ์ด์ค๊น์? |
@@ -0,0 +1,94 @@
+package store.model.store.product;
+
+import static store.exception.store.StoreErrorStatus.INVALID_PRODUCT_PRICE;
+import static store.exception.store.StoreErrorStatus.INVALID_PRODUCT_STOCK;
+
+import java.time.LocalDateTime;
+import store.exception.store.StoreException;
+import store.model.store.promotion.Promotion;
+
+public class Product {
+ private final String name;
+ private final int price;
+ private int stock;
+ private final Promotion promotion;
+
+ private Product(String name, int price, int stock, Promotion promotion) {
+ validatePrice(price);
+ validateStock(stock);
+ this.name = name;
+ this.price = price;
+ this.stock = stock;
+ this.promotion = promotion;
+ }
+
+ public static Product of(String name, int price, int stock, Promotion promotion) {
+ return new Product(name, price, stock, promotion);
+ }
+
+ public static Product createEmptyGeneralProduct(Product product) {
+ return new Product(product.name, product.price, 0, null);
+ }
+
+ public void decreaseStock(int amount) {
+ stock -= amount;
+ }
+
+ public boolean isNameEquals(Product product) {
+ return this.name.equals(product.name);
+ }
+
+ public boolean isNameEquals(String name) {
+ return this.name.equals(name);
+ }
+
+ public boolean isPromotionPeriod(LocalDateTime now) {
+ if (this.promotion == null) {
+ return false;
+ }
+ return promotion.isPeriod(now);
+ }
+
+ public boolean isGeneralProduct() {
+ return promotion == null;
+ }
+
+ public boolean isPromotionProduct() {
+ return promotion != null;
+ }
+
+ private void validatePrice(int price) {
+ if (price <= 0) {
+ throw new StoreException(INVALID_PRODUCT_PRICE);
+ }
+ }
+
+ private void validateStock(int stock) {
+ if (stock < 0) {
+ throw new StoreException(INVALID_PRODUCT_STOCK);
+ }
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public int getStock() {
+ return stock;
+ }
+
+ public String getPromotionName() {
+ if (promotion == null) {
+ return "";
+ }
+ return promotion.getName();
+ }
+
+ public int getPromotionUnit() {
+ return promotion.getUnit();
+ }
+} | Java | ์ด ๋ถ๋ถ์ด ์ ๋ ๋ค๋ฅด๋ค์! ์ ๋ Product์ ์ฌ๊ณ ๋ฅผ ํฌํจ์ํค์ง ์๊ณ ์ฌ๊ณ ๋ repository์์ ๊ฐ์ ธ์ค๋๋ก ํ์ต๋๋ค.
product๊ฐ ์ฌ๊ณ ์๋์ ๊ฐ์ ธ๋ ๊ด์ฐฎ์์ง ์ฌ์ญค๋ณด๊ณ ์ถ์ต๋๋ค~ |
@@ -0,0 +1,61 @@
+package store.model.store.promotion;
+
+import static store.exception.store.StoreErrorStatus.INVALID_PROMOTION_BUY_AMOUNT;
+import static store.exception.store.StoreErrorStatus.INVALID_PROMOTION_GIVE_AMOUNT;
+
+import java.time.LocalDateTime;
+import store.exception.store.StoreException;
+
+public class Promotion {
+ private final String name;
+ private final int buyAmount;
+ private final int giveAmount;
+ private final LocalDateTime startAt;
+ private final LocalDateTime endAt;
+
+ private Promotion(String name, int buyAmount, int giveAmount, LocalDateTime startAt, LocalDateTime endAt) {
+ validateBuyAmount(buyAmount);
+ validateGiveAmount(giveAmount);
+ this.name = name;
+ this.buyAmount = buyAmount;
+ this.giveAmount = giveAmount;
+ this.startAt = startAt;
+ this.endAt = endAt;
+ }
+
+ public static Promotion of(String name,
+ int buyAmount,
+ int giveAmount,
+ LocalDateTime startAt,
+ LocalDateTime endAt) {
+ return new Promotion(name, buyAmount, giveAmount, startAt, endAt);
+ }
+
+ public boolean isNameEquals(String name) {
+ return this.name.equals(name);
+ }
+
+ public boolean isPeriod(LocalDateTime now) {
+ return startAt.isBefore(now) && endAt.isAfter(now);
+ }
+
+ private void validateBuyAmount(int buyAmount) {
+ if (buyAmount < 1) {
+ throw new StoreException(INVALID_PROMOTION_BUY_AMOUNT);
+ }
+ }
+
+ private void validateGiveAmount(int giveAmount) {
+ if (giveAmount != 1) {
+ throw new StoreException(INVALID_PROMOTION_GIVE_AMOUNT);
+ }
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getUnit() {
+ return buyAmount + giveAmount;
+ }
+} | Java | LocalDate๊ฐ ์๋ LocalDateTime์ ์ฌ์ฉํ์ ์ด์ ๊ฐ ์๋์? |
@@ -0,0 +1,20 @@
+package store.util.reader;
+
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+public class RepeatableReader {
+ public static <T> T handle(Supplier<String> viewMethod,
+ Function<String, T> converter,
+ Consumer<String> errorHandler) {
+ while (true) {
+ try {
+ String userInput = viewMethod.get();
+ return converter.apply(userInput);
+ } catch (IllegalArgumentException e) {
+ errorHandler.accept(e.getMessage());
+ }
+ }
+ }
+} | Java | ํจ์ํ ํ๋ก๊ทธ๋๋ฐ์ ๋๊ฒ ์ํ์๋ค์. |
@@ -0,0 +1,10 @@
+package store.view;
+
+public class ErrorView {
+
+ private static final String ERROR_PREFIX = "[ERROR] ";
+
+ public void errorPage(String message) {
+ System.out.println(ERROR_PREFIX + message);
+ }
+} | Java | ErrorView๋ ์ฒ์ ๋ณด๋๋ฐ, ์ ๋ง๋์ ๊ฑฐ ๊ฐ์์! |
@@ -0,0 +1,44 @@
+package store.util.reader;
+
+import static store.exception.reader.FileReadErrorStatus.INVALID_FILE_PATH;
+import static store.exception.reader.FileReadErrorStatus.UNEXPECTED_IO_ERROR;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import store.exception.reader.FileReadException;
+
+public class StoreFileReader {
+ private static final String DELIMITER = ",";
+
+ public static List<List<String>> readFile(String fileName) {
+ validateFileReadable(fileName);
+ Path path = Paths.get(fileName);
+ try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
+ return reader.lines().skip(1)
+ .filter(line -> line != null && !line.trim().isEmpty())
+ .map(StoreFileReader::parseLine)
+ .toList();
+ } catch (IOException e) {
+ throw new FileReadException(UNEXPECTED_IO_ERROR);
+ }
+ }
+
+ private static List<String> parseLine(String line) {
+ return List.of(line.split(DELIMITER));
+ }
+
+ public static void validateFileReadable(String fileName) {
+ if (fileName == null || fileName.trim().isEmpty()) {
+ throw new FileReadException(INVALID_FILE_PATH);
+ }
+ Path path = Paths.get(fileName);
+ if (!(Files.exists(path) && Files.isReadable(path))) {
+ throw new FileReadException(INVALID_FILE_PATH);
+ }
+ }
+} | Java | `String.isBlank`๋ฉ์๋๋ ์ฌ์ฉํด๋ณด์๋ฉด ์ข์ ๊ฑฐ ๊ฐ์์! |
@@ -0,0 +1,130 @@
+package store.view.formatter;
+
+import store.model.order.Payment;
+import store.model.store.StoreRoom;
+import store.model.store.product.Product;
+import store.model.store.product.Products;
+
+public class OutputFormatter {
+ private static final String WELCOME_MESSAGE = "์๋
ํ์ธ์. Wํธ์์ ์
๋๋ค.\nํ์ฌ ๋ณด์ ํ๊ณ ์๋ ์ํ์
๋๋ค.";
+ private static final String PRODUCT_PREFIX = "- ";
+ private static final String SOLD_OUT = "์ฌ๊ณ ์์";
+ private static final String RECEIPT_START_MESSAGE = "==============W ํธ์์ ================";
+ private static final String RECEIPT_COLUMN_MESSAGE = "์ํ๋ช
\t\t์๋\t๊ธ์ก";
+ private static final String RECEIPT_PURCHASE_MESSAGE_FORMAT = "%s\t\t%,d \t%,d";
+ private static final String RECEIPT_GIVEAWAY_MESSAGE = "=============์ฆ\t์ ===============";
+ private static final String RECEIPT_GIVEAWAY_PRODUCT_MESSAGE_FORMAT = "%s\t\t%,d";
+ private static final String RECEIPT_LINE_SEPARATOR = "====================================";
+ private static final String RECEIPT_TOTAL_PRICE_MESSAGE_FORMAT = "์ด๊ตฌ๋งค์ก\t\t%,d\t%,d";
+ private static final String RECEIPT_PROMOTION_DISCOUNT_MESSAGE_FORMAT = "ํ์ฌํ ์ธ\t\t\t-%,d";
+ private static final String RECEIPT_MEMBERSHIP_DISCOUNT_MESSAGE_FORMAT = "๋ฉค๋ฒ์ญํ ์ธ\t\t\t-%,d";
+ private static final String RECEIPT_ACTUAL_PRICE_MESSAGE_FORMAT = "๋ด์ค๋\t\t\t%,d";
+ private static final String SYSTEM_LINE_SEPARATOR = System.lineSeparator();
+
+ private OutputFormatter() {
+ }
+
+ public static String buildStoreStock(StoreRoom storeRoom) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(WELCOME_MESSAGE).append(SYSTEM_LINE_SEPARATOR).append(SYSTEM_LINE_SEPARATOR);
+
+ String menus = buildProducts(storeRoom.getGeneralProducts(), storeRoom.getPromotionProducts());
+ sb.append(menus);
+ return sb.toString();
+ }
+
+ public static String buildReceipt(Payment payment) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(buildReceiptHeader())
+ .append(buildPurchaseItems(payment))
+ .append(buildGiveawayIems(payment))
+ .append(buildReceiptSummary(payment));
+ return sb.toString();
+ }
+
+ private static String buildProducts(Products generalProducts, Products promotionProducts) {
+ StringBuilder sb = new StringBuilder();
+ for (Product product : generalProducts.getProducts()) {
+ if (promotionProducts.contains(product.getName())) {
+ sb.append(buildProductMessage(promotionProducts.findNullableProductByName(product.getName())));
+ }
+ sb.append(buildProductMessage(product));
+ }
+ return sb.toString();
+ }
+
+ private static String buildProductMessage(Product product) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(PRODUCT_PREFIX)
+ .append(product.getName()).append(" ")
+ .append(String.format("%,d์", product.getPrice())).append(" ")
+ .append(buildProductStock(product.getStock())).append(" ")
+ .append(product.getPromotionName()).append(SYSTEM_LINE_SEPARATOR);
+ return sb.toString();
+ }
+
+ private static String buildProductStock(int stock) {
+ if (stock == 0) {
+ return SOLD_OUT;
+ }
+ return String.format("%,d๊ฐ", stock);
+ }
+
+ private static String buildReceiptHeader() {
+ StringBuilder sb = new StringBuilder();
+ sb.append(RECEIPT_START_MESSAGE).append(SYSTEM_LINE_SEPARATOR)
+ .append(RECEIPT_COLUMN_MESSAGE).append(SYSTEM_LINE_SEPARATOR);
+ return sb.toString();
+ }
+
+ private static String buildPurchaseItems(Payment payment) {
+ StringBuilder sb = new StringBuilder();
+ payment.getPurchaseOrder().getPurchaseOrder().forEach((name, quantity) ->
+ sb.append(String.format(RECEIPT_PURCHASE_MESSAGE_FORMAT,
+ name, quantity, payment.calculateProductPrice(name)))
+ .append(SYSTEM_LINE_SEPARATOR)
+ );
+ return sb.toString();
+ }
+
+ private static String buildGiveawayIems(Payment payment) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(RECEIPT_GIVEAWAY_MESSAGE).append(SYSTEM_LINE_SEPARATOR);
+
+ payment.extractPromotionalProducts().forEach((name, quantity) ->
+ sb.append(String.format(RECEIPT_GIVEAWAY_PRODUCT_MESSAGE_FORMAT, name, quantity))
+ .append(SYSTEM_LINE_SEPARATOR)
+ );
+ return sb.toString();
+ }
+
+ private static String buildReceiptSummary(Payment payment) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(RECEIPT_LINE_SEPARATOR).append(SYSTEM_LINE_SEPARATOR)
+ .append(buildTotalPrice(payment))
+ .append(buildDiscounts(payment))
+ .append(buildFinalPrice(payment));
+ return sb.toString();
+ }
+
+ private static String buildTotalPrice(Payment payment) {
+ return String.format(RECEIPT_TOTAL_PRICE_MESSAGE_FORMAT,
+ payment.calculateTotalBuyAmount(), payment.calculateTotalPrice())
+ + SYSTEM_LINE_SEPARATOR;
+ }
+
+ private static String buildDiscounts(Payment payment) {
+ return String.format(RECEIPT_PROMOTION_DISCOUNT_MESSAGE_FORMAT,
+ payment.calculatePromotionalDiscount())
+ + SYSTEM_LINE_SEPARATOR
+ + String.format(RECEIPT_MEMBERSHIP_DISCOUNT_MESSAGE_FORMAT,
+ payment.calculateMembershipDiscount())
+ + SYSTEM_LINE_SEPARATOR;
+ }
+
+ private static String buildFinalPrice(Payment payment) {
+ return String.format(RECEIPT_ACTUAL_PRICE_MESSAGE_FORMAT,
+ payment.calculateActualPrice())
+ + SYSTEM_LINE_SEPARATOR;
+ }
+} | Java | ,๋ฅผ ์ด๋ ๊ฒ๋ ๋ฃ์ ์ ์๊ตฐ์!
์ข์ ๋ฐฉ๋ฒ์ด๋ค์! |
@@ -0,0 +1,20 @@
+package store.util.reader;
+
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+public class RepeatableReader {
+ public static <T> T handle(Supplier<String> viewMethod,
+ Function<String, T> converter,
+ Consumer<String> errorHandler) {
+ while (true) {
+ try {
+ String userInput = viewMethod.get();
+ return converter.apply(userInput);
+ } catch (IllegalArgumentException e) {
+ errorHandler.accept(e.getMessage());
+ }
+ }
+ }
+} | Java | ํจ์ํ ์ธํฐํ์ด์ค๋ฅผ ๋๋ฌด ์ ์ฌ์ฉํ์ ๊ฑฐ ๊ฐ์์! |
@@ -0,0 +1,100 @@
+package store;
+
+import java.util.Map;
+import store.model.order.Payment;
+import store.model.order.PurchaseOrder;
+import store.model.store.StoreRoom;
+import store.util.parser.ClosedQuestionsParser;
+import store.util.parser.PurchaseParser;
+import store.util.reader.RepeatableReader;
+import store.view.ErrorView;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreApplication {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final ErrorView errorView;
+ private final StoreRoom storeRoom;
+
+ public StoreApplication(InputView inputView, OutputView outputView, ErrorView errorView, StoreRoom storeRoom) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.errorView = errorView;
+ this.storeRoom = storeRoom;
+ }
+
+ public void run() {
+ while (true) {
+ outputView.printProducts(storeRoom);
+ processPurchase();
+ boolean buyMore = RepeatableReader.handle(inputView::askAdditionalPurchase,
+ ClosedQuestionsParser::parseAnswer, errorView::errorPage);
+ if (!buyMore) {
+ return;
+ }
+ }
+ }
+
+ private void processPurchase() {
+ PurchaseOrder purchaseOrder = createPurchaseOrder(storeRoom);
+ purchaseOrder = adjustOrderWithPromotions(purchaseOrder, storeRoom);
+ if (purchaseOrder.getTotalBuyAmount() <= 0) {
+ return;
+ }
+ boolean hasMembership = RepeatableReader.handle(inputView::askMembership, ClosedQuestionsParser::parseAnswer,
+ errorView::errorPage);
+ Payment payment = Payment.from(purchaseOrder, storeRoom, hasMembership);
+ outputView.printReceipt(payment);
+ storeRoom.arrange(payment.getPurchaseOrder().getPurchaseOrder());
+ }
+
+ private PurchaseOrder createPurchaseOrder(StoreRoom storeRoom) {
+ return RepeatableReader.handle(inputView::readItem, (userInput) -> {
+ Map<String, Integer> items = PurchaseParser.parseInputItems(userInput);
+ return PurchaseOrder.from(items, storeRoom);
+ }, errorView::errorPage);
+ }
+
+ private PurchaseOrder adjustOrderWithPromotions(PurchaseOrder purchaseOrder, StoreRoom storeRoom) {
+ PurchaseOrder result = purchaseOrder;
+ for (Map.Entry<String, Integer> entry : purchaseOrder.getPurchaseOrder().entrySet()) {
+ result = applyPromotionToProduct(result, storeRoom, entry.getKey(), entry.getValue());
+ }
+ return result;
+ }
+
+ private PurchaseOrder applyPromotionToProduct(PurchaseOrder purchaseOrder,
+ StoreRoom storeRoom,
+ String productName,
+ int buyAmount) {
+ int fullPriceAmount = storeRoom.getNonPromotionalQuantity(productName, buyAmount);
+ if (fullPriceAmount > 0) {
+ purchaseOrder = purchaseOrder
+ .decreaseBuyAmount(productName, getDecreaseAmount(productName, fullPriceAmount));
+ }
+ if (storeRoom.canGetOneMore(productName, buyAmount)) {
+ purchaseOrder = purchaseOrder.increaseBuyAmount(productName, getIncreaseAmount(productName));
+ }
+ return purchaseOrder;
+ }
+
+ private int getDecreaseAmount(String productName, int fullPriceAmount) {
+ boolean isAgree = RepeatableReader.handle(() ->
+ inputView.askFullPrice(productName, fullPriceAmount), ClosedQuestionsParser::parseAnswer,
+ errorView::errorPage);
+ if (!isAgree) {
+ return fullPriceAmount;
+ }
+ return 0;
+ }
+
+ private int getIncreaseAmount(String productName) {
+ boolean isAgree = RepeatableReader.handle(() ->
+ inputView.askAddOne(productName), ClosedQuestionsParser::parseAnswer, errorView::errorPage);
+ if (isAgree) {
+ return 1;
+ }
+ return 0;
+ }
+} | Java | do-while๋ ์ฌ์ฉํด๋ณด์๋ฉด ๋ ๊ฐ๋
์ฑ์ด ์ข์์ง ๊ฑฐ ๊ฐ์์! |
@@ -0,0 +1,10 @@
+package store.view;
+
+public class ErrorView {
+
+ private static final String ERROR_PREFIX = "[ERROR] ";
+
+ public void errorPage(String message) {
+ System.out.println(ERROR_PREFIX + message);
+ }
+} | Java | ๊ฐ์ฌํฉ๋๋ค ๐ |
@@ -0,0 +1,44 @@
+package store.util.reader;
+
+import static store.exception.reader.FileReadErrorStatus.INVALID_FILE_PATH;
+import static store.exception.reader.FileReadErrorStatus.UNEXPECTED_IO_ERROR;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import store.exception.reader.FileReadException;
+
+public class StoreFileReader {
+ private static final String DELIMITER = ",";
+
+ public static List<List<String>> readFile(String fileName) {
+ validateFileReadable(fileName);
+ Path path = Paths.get(fileName);
+ try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
+ return reader.lines().skip(1)
+ .filter(line -> line != null && !line.trim().isEmpty())
+ .map(StoreFileReader::parseLine)
+ .toList();
+ } catch (IOException e) {
+ throw new FileReadException(UNEXPECTED_IO_ERROR);
+ }
+ }
+
+ private static List<String> parseLine(String line) {
+ return List.of(line.split(DELIMITER));
+ }
+
+ public static void validateFileReadable(String fileName) {
+ if (fileName == null || fileName.trim().isEmpty()) {
+ throw new FileReadException(INVALID_FILE_PATH);
+ }
+ Path path = Paths.get(fileName);
+ if (!(Files.exists(path) && Files.isReadable(path))) {
+ throw new FileReadException(INVALID_FILE_PATH);
+ }
+ }
+} | Java | ์ข์ ์๊ฒฌ ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,20 @@
+package store.util.reader;
+
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+public class RepeatableReader {
+ public static <T> T handle(Supplier<String> viewMethod,
+ Function<String, T> converter,
+ Consumer<String> errorHandler) {
+ while (true) {
+ try {
+ String userInput = viewMethod.get();
+ return converter.apply(userInput);
+ } catch (IllegalArgumentException e) {
+ errorHandler.accept(e.getMessage());
+ }
+ }
+ }
+} | Java | ์ ๋ ์ ๋ฒ ๋ฏธ์
์ฝ๋๋ฆฌ๋ทฐ ๋ค๋๋ฉด์ ๋ดค๋๋ฐ ์ข๋ค๊ณ ์๊ฐํด์ ์ด๋ฒ ๋ฏธ์
์ ์ ์ฉํด๋ณด์์ด์! |
@@ -0,0 +1,100 @@
+package store;
+
+import java.util.Map;
+import store.model.order.Payment;
+import store.model.order.PurchaseOrder;
+import store.model.store.StoreRoom;
+import store.util.parser.ClosedQuestionsParser;
+import store.util.parser.PurchaseParser;
+import store.util.reader.RepeatableReader;
+import store.view.ErrorView;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreApplication {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final ErrorView errorView;
+ private final StoreRoom storeRoom;
+
+ public StoreApplication(InputView inputView, OutputView outputView, ErrorView errorView, StoreRoom storeRoom) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.errorView = errorView;
+ this.storeRoom = storeRoom;
+ }
+
+ public void run() {
+ while (true) {
+ outputView.printProducts(storeRoom);
+ processPurchase();
+ boolean buyMore = RepeatableReader.handle(inputView::askAdditionalPurchase,
+ ClosedQuestionsParser::parseAnswer, errorView::errorPage);
+ if (!buyMore) {
+ return;
+ }
+ }
+ }
+
+ private void processPurchase() {
+ PurchaseOrder purchaseOrder = createPurchaseOrder(storeRoom);
+ purchaseOrder = adjustOrderWithPromotions(purchaseOrder, storeRoom);
+ if (purchaseOrder.getTotalBuyAmount() <= 0) {
+ return;
+ }
+ boolean hasMembership = RepeatableReader.handle(inputView::askMembership, ClosedQuestionsParser::parseAnswer,
+ errorView::errorPage);
+ Payment payment = Payment.from(purchaseOrder, storeRoom, hasMembership);
+ outputView.printReceipt(payment);
+ storeRoom.arrange(payment.getPurchaseOrder().getPurchaseOrder());
+ }
+
+ private PurchaseOrder createPurchaseOrder(StoreRoom storeRoom) {
+ return RepeatableReader.handle(inputView::readItem, (userInput) -> {
+ Map<String, Integer> items = PurchaseParser.parseInputItems(userInput);
+ return PurchaseOrder.from(items, storeRoom);
+ }, errorView::errorPage);
+ }
+
+ private PurchaseOrder adjustOrderWithPromotions(PurchaseOrder purchaseOrder, StoreRoom storeRoom) {
+ PurchaseOrder result = purchaseOrder;
+ for (Map.Entry<String, Integer> entry : purchaseOrder.getPurchaseOrder().entrySet()) {
+ result = applyPromotionToProduct(result, storeRoom, entry.getKey(), entry.getValue());
+ }
+ return result;
+ }
+
+ private PurchaseOrder applyPromotionToProduct(PurchaseOrder purchaseOrder,
+ StoreRoom storeRoom,
+ String productName,
+ int buyAmount) {
+ int fullPriceAmount = storeRoom.getNonPromotionalQuantity(productName, buyAmount);
+ if (fullPriceAmount > 0) {
+ purchaseOrder = purchaseOrder
+ .decreaseBuyAmount(productName, getDecreaseAmount(productName, fullPriceAmount));
+ }
+ if (storeRoom.canGetOneMore(productName, buyAmount)) {
+ purchaseOrder = purchaseOrder.increaseBuyAmount(productName, getIncreaseAmount(productName));
+ }
+ return purchaseOrder;
+ }
+
+ private int getDecreaseAmount(String productName, int fullPriceAmount) {
+ boolean isAgree = RepeatableReader.handle(() ->
+ inputView.askFullPrice(productName, fullPriceAmount), ClosedQuestionsParser::parseAnswer,
+ errorView::errorPage);
+ if (!isAgree) {
+ return fullPriceAmount;
+ }
+ return 0;
+ }
+
+ private int getIncreaseAmount(String productName) {
+ boolean isAgree = RepeatableReader.handle(() ->
+ inputView.askAddOne(productName), ClosedQuestionsParser::parseAnswer, errorView::errorPage);
+ if (isAgree) {
+ return 1;
+ }
+ return 0;
+ }
+} | Java | ์ข์ ์๊ฒฌ ๊ฐ์ฌํฉ๋๋ค ๐ |
@@ -0,0 +1,100 @@
+package store;
+
+import java.util.Map;
+import store.model.order.Payment;
+import store.model.order.PurchaseOrder;
+import store.model.store.StoreRoom;
+import store.util.parser.ClosedQuestionsParser;
+import store.util.parser.PurchaseParser;
+import store.util.reader.RepeatableReader;
+import store.view.ErrorView;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreApplication {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final ErrorView errorView;
+ private final StoreRoom storeRoom;
+
+ public StoreApplication(InputView inputView, OutputView outputView, ErrorView errorView, StoreRoom storeRoom) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.errorView = errorView;
+ this.storeRoom = storeRoom;
+ }
+
+ public void run() {
+ while (true) {
+ outputView.printProducts(storeRoom);
+ processPurchase();
+ boolean buyMore = RepeatableReader.handle(inputView::askAdditionalPurchase,
+ ClosedQuestionsParser::parseAnswer, errorView::errorPage);
+ if (!buyMore) {
+ return;
+ }
+ }
+ }
+
+ private void processPurchase() {
+ PurchaseOrder purchaseOrder = createPurchaseOrder(storeRoom);
+ purchaseOrder = adjustOrderWithPromotions(purchaseOrder, storeRoom);
+ if (purchaseOrder.getTotalBuyAmount() <= 0) {
+ return;
+ }
+ boolean hasMembership = RepeatableReader.handle(inputView::askMembership, ClosedQuestionsParser::parseAnswer,
+ errorView::errorPage);
+ Payment payment = Payment.from(purchaseOrder, storeRoom, hasMembership);
+ outputView.printReceipt(payment);
+ storeRoom.arrange(payment.getPurchaseOrder().getPurchaseOrder());
+ }
+
+ private PurchaseOrder createPurchaseOrder(StoreRoom storeRoom) {
+ return RepeatableReader.handle(inputView::readItem, (userInput) -> {
+ Map<String, Integer> items = PurchaseParser.parseInputItems(userInput);
+ return PurchaseOrder.from(items, storeRoom);
+ }, errorView::errorPage);
+ }
+
+ private PurchaseOrder adjustOrderWithPromotions(PurchaseOrder purchaseOrder, StoreRoom storeRoom) {
+ PurchaseOrder result = purchaseOrder;
+ for (Map.Entry<String, Integer> entry : purchaseOrder.getPurchaseOrder().entrySet()) {
+ result = applyPromotionToProduct(result, storeRoom, entry.getKey(), entry.getValue());
+ }
+ return result;
+ }
+
+ private PurchaseOrder applyPromotionToProduct(PurchaseOrder purchaseOrder,
+ StoreRoom storeRoom,
+ String productName,
+ int buyAmount) {
+ int fullPriceAmount = storeRoom.getNonPromotionalQuantity(productName, buyAmount);
+ if (fullPriceAmount > 0) {
+ purchaseOrder = purchaseOrder
+ .decreaseBuyAmount(productName, getDecreaseAmount(productName, fullPriceAmount));
+ }
+ if (storeRoom.canGetOneMore(productName, buyAmount)) {
+ purchaseOrder = purchaseOrder.increaseBuyAmount(productName, getIncreaseAmount(productName));
+ }
+ return purchaseOrder;
+ }
+
+ private int getDecreaseAmount(String productName, int fullPriceAmount) {
+ boolean isAgree = RepeatableReader.handle(() ->
+ inputView.askFullPrice(productName, fullPriceAmount), ClosedQuestionsParser::parseAnswer,
+ errorView::errorPage);
+ if (!isAgree) {
+ return fullPriceAmount;
+ }
+ return 0;
+ }
+
+ private int getIncreaseAmount(String productName) {
+ boolean isAgree = RepeatableReader.handle(() ->
+ inputView.askAddOne(productName), ClosedQuestionsParser::parseAnswer, errorView::errorPage);
+ if (isAgree) {
+ return 1;
+ }
+ return 0;
+ }
+} | Java | ์ฌ์ญค๋ณด์ ๊ฒ ์๋ฒฝํ ์ดํด๋ฅผ ๋ชปํ์ง๋ง ๋ต๋ณ ๋๋ฆฌ๋ฉด `๋ฉค๋ฒ์ญ ํ ์ธ์ ๋ฐ์ผ์๊ฒ ์ต๋๊น? (Y/N)`๋ฅผ ๋ฌผ์ด๋ณด๋ ๋ฉ์๋๋ `askMembership`์ด๋ผ๊ณ ์ง๊ด์ ์ผ๋ก ์์ฑํ์๊ณ , ๊ทธ๋ฅผ ๋ด๋ ๋ณ์๋ ๋ฉค๋ฒ์ญ ํ ์ธ ์ ๋ฌด์ด๊ธฐ ๋๋ฌธ์ has๋ผ๋ ํค์๋๋ฅผ ์ด์ฉํ์ต๋๋ค! |
@@ -0,0 +1,29 @@
+package store.exception.store;
+
+public enum StoreErrorStatus {
+
+ INSUFFICIENT_STOCK("์ฌ๊ณ ์๋์ ์ด๊ณผํ์ฌ ๊ตฌ๋งคํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
+ NON_EXIST_PRODUCT("์กด์ฌํ์ง ์๋ ์ํ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
+ DUPLICATE_GENERAL_PRODUCT("์ํ์ด ์ค๋ณต๋์์ต๋๋ค."),
+ DUPLICATE_PROMOTION_PRODUCT("ํ๋์ ์ํ์ ๋๊ฐ์ ํ๋ก๋ชจ์
์ด ์ ์ฉ๋ ์ ์์ต๋๋ค."),
+
+ INVALID_PROMOTION_BUY_AMOUNT("๊ตฌ๋งค ๊ฐ์๋ 0 ์ดํ๊ฐ ๋ ์ ์์ต๋๋ค."),
+ INVALID_PROMOTION_GIVE_AMOUNT("์ถ๊ฐ ์ฆ์ ์ ํ๋๋ง ๊ฐ๋ฅํฉ๋๋ค."),
+ NON_EXIST_PROMOTION("์กด์ฌํ์ง ์๋ ํ๋ก๋ชจ์
์ด ์์ต๋๋ค."),
+ DUPLICATE_PROMOTION_NAME("ํ๋ก๋ชจ์
์ ์ด๋ฆ์ ์ค๋ณต๋ ์ ์์ต๋๋ค."),
+
+ INVALID_PRODUCT_PRICE("๊ฐ๊ฒฉ์ 0 ์ดํ๊ฐ ๋ ์ ์์ต๋๋ค."),
+ INVALID_PRODUCT_STOCK("์ฌ๊ณ ๋ ์์๊ฐ ๋ ์ ์์ต๋๋ค."),
+
+ PRODUCT_PRICE_INCONSISTENT("์ผ๋ฐ ์ํ๊ณผ ํ๋ก๋ชจ์
์ํ์ ๊ฐ๊ฒฉ์ ๋์ผํด์ผํฉ๋๋ค.");
+
+ private final String message;
+
+ StoreErrorStatus(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+} | Java | ๊ฐ์ฌํฉ๋๋ค ๐ |
@@ -0,0 +1,92 @@
+package store.model.order;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.util.Map;
+import java.util.stream.Collectors;
+import store.model.store.StoreRoom;
+import store.model.store.product.Product;
+
+public class Payment {
+ private final PurchaseOrder purchaseOrder;
+ private final StoreRoom storeRoom;
+ private final boolean hasMembership;
+
+ private Payment(PurchaseOrder purchaseOrder, StoreRoom storeRoom, boolean hasMembership) {
+ this.purchaseOrder = purchaseOrder;
+ this.storeRoom = storeRoom;
+ this.hasMembership = hasMembership;
+ }
+
+ public static Payment from(PurchaseOrder purchaseOrder, StoreRoom storeRoom, boolean hasMembership) {
+ return new Payment(purchaseOrder, storeRoom, hasMembership);
+ }
+
+ public long calculateActualPrice() {
+ long promotionalDiscount = calculatePromotionalDiscount();
+ long membershipDiscount = calculateMembershipDiscount();
+ long totalPrice = calculateTotalPrice();
+ return totalPrice - (promotionalDiscount + membershipDiscount);
+ }
+
+ public long calculatePromotionalDiscount() {
+ return extractPromotionalProducts().entrySet().stream()
+ .mapToLong(entry -> (long) storeRoom.getProductPrice(entry.getKey()) * entry.getValue())
+ .sum();
+ }
+
+ public long calculateMembershipDiscount() {
+ if (!hasMembership) {
+ return 0;
+ }
+ long promotionAppliedPrice = extractPromotionalProducts().entrySet().stream()
+ .mapToLong(entry -> {
+ Product product = storeRoom.getPromotionProducts().findNullableProductByName(entry.getKey());
+ return (long) product.getPrice() * entry.getValue() * product.getPromotionUnit();
+ }).sum();
+ long membershipDiscount = (long) ((calculateTotalPrice() - promotionAppliedPrice) * 0.3);
+ return Math.min(8000L, membershipDiscount);
+ }
+
+ public long calculateTotalPrice() {
+ return purchaseOrder.getPurchaseOrder().entrySet().stream()
+ .mapToLong(entry -> (long) storeRoom.getProductPrice(entry.getKey()) * entry.getValue())
+ .sum();
+ }
+
+ public long calculateProductPrice(String productName) {
+ int buyAmount = purchaseOrder.getPurchaseOrder().get(productName);
+ int productPrice = storeRoom.getProductPrice(productName);
+ return (long) buyAmount * productPrice;
+ }
+
+ public long calculateTotalBuyAmount() {
+ return purchaseOrder.getPurchaseOrder().values().stream()
+ .mapToLong(Long::valueOf)
+ .sum();
+ }
+
+ private int calculateGiveawayAmount(String productName, int quantity) {
+ Product product = storeRoom.getPromotionProducts().findNullableProductByName(productName);
+ if (product != null
+ && product.isPromotionPeriod(DateTimes.now())
+ && product.getStock() >= product.getPromotionUnit()) {
+ int promotionalQuantity = quantity - storeRoom.getNonPromotionalQuantity(productName, quantity);
+ return promotionalQuantity / product.getPromotionUnit();
+ }
+ return 0;
+ }
+
+ public Map<String, Integer> extractPromotionalProducts() {
+ return purchaseOrder.getPurchaseOrder().entrySet().stream()
+ .map(entry -> Map.entry(
+ entry.getKey(),
+ calculateGiveawayAmount(entry.getKey(), entry.getValue())
+ ))
+ .filter(entry -> entry.getValue() > 0)
+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+ }
+
+ public PurchaseOrder getPurchaseOrder() {
+ return purchaseOrder;
+ }
+} | Java | ์ ๋ `of`, `from`๋ฉ์๋ ๋ค์ด๋ฐ์ ๋ํด์ ๊ณ ๋ฏผ์ ๋ง์ดํ๋๋ฐ ์ด๋ค ๋ธ๋ก๊ทธ์๋ ํ๋ผ๋ฏธํฐ๊ฐ 2๊ฐ ์ด์์ด๋ฉด `of` ํ๋๋ฉด `from`์ผ๋ก ํ๋ค๋ ๊ธ์ ๋ดค์ต๋๋ค.
๋ค๋ฅธ ๊ธ์์๋ ์ ๋ณด๋ฅผ ์กฐํฉํด์ ๊ฐ์ฒด๋ฅผ ๋ง๋๋ ๊ฒฝ์ฐ๋ `of`๋ผ ํ๊ณ ํ๋ผ๋ฏธํฐ๋ก ๋ค์ด์ค๋ ์ ๋ณด๋ฅผ ์ด์ฉํด์ ๊ฐ์ฒด๋ฅผ ๋ง๋๋ ๊ฒฝ์ฐ๋ `from`์ด๋ผ๊ณ ๋ค์ด๋ฐํ๋ค๋ ๊ธ๋ ์์๋๋ฐ ์ ๋ ์ด ๊ธ์ ๋ ๊ณต๊ฐ์ ๋๊ปด์ ์ ๊ฒฝ์ฐ๋ `from`์ด๋ผ๋ ๋ฉ์๋ ๋ค์์ด ์ ๋ง๋ค๋ ์๊ฐ์ ํ์ต๋๋ค. |
@@ -0,0 +1,94 @@
+package store.model.store.product;
+
+import static store.exception.store.StoreErrorStatus.INVALID_PRODUCT_PRICE;
+import static store.exception.store.StoreErrorStatus.INVALID_PRODUCT_STOCK;
+
+import java.time.LocalDateTime;
+import store.exception.store.StoreException;
+import store.model.store.promotion.Promotion;
+
+public class Product {
+ private final String name;
+ private final int price;
+ private int stock;
+ private final Promotion promotion;
+
+ private Product(String name, int price, int stock, Promotion promotion) {
+ validatePrice(price);
+ validateStock(stock);
+ this.name = name;
+ this.price = price;
+ this.stock = stock;
+ this.promotion = promotion;
+ }
+
+ public static Product of(String name, int price, int stock, Promotion promotion) {
+ return new Product(name, price, stock, promotion);
+ }
+
+ public static Product createEmptyGeneralProduct(Product product) {
+ return new Product(product.name, product.price, 0, null);
+ }
+
+ public void decreaseStock(int amount) {
+ stock -= amount;
+ }
+
+ public boolean isNameEquals(Product product) {
+ return this.name.equals(product.name);
+ }
+
+ public boolean isNameEquals(String name) {
+ return this.name.equals(name);
+ }
+
+ public boolean isPromotionPeriod(LocalDateTime now) {
+ if (this.promotion == null) {
+ return false;
+ }
+ return promotion.isPeriod(now);
+ }
+
+ public boolean isGeneralProduct() {
+ return promotion == null;
+ }
+
+ public boolean isPromotionProduct() {
+ return promotion != null;
+ }
+
+ private void validatePrice(int price) {
+ if (price <= 0) {
+ throw new StoreException(INVALID_PRODUCT_PRICE);
+ }
+ }
+
+ private void validateStock(int stock) {
+ if (stock < 0) {
+ throw new StoreException(INVALID_PRODUCT_STOCK);
+ }
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public int getStock() {
+ return stock;
+ }
+
+ public String getPromotionName() {
+ if (promotion == null) {
+ return "";
+ }
+ return promotion.getName();
+ }
+
+ public int getPromotionUnit() {
+ return promotion.getUnit();
+ }
+} | Java | Product๊ฐ ์ด๋ฆ๊ณผ ๊ฐ๊ฒฉ๋ง์ ๊ฐ์ง๊ณ , Stock์ด๋ผ๋ ๋ชจ๋ธ์ ๋ง๋ค์ด `Product product`, `int stock` ์ ๊ฐ์ง๊ฒ ํ ๊น ์๊ฐํ์ง๋ง, ์ผ๋จ ๋น ๋ฅด๊ฒ ๊ตฌํํ๋๊ฒ ๋ชฉํ๊ธฐ๋ ํ๊ณ ํฐ ๋ฌธ์ ๊ฐ ์์ ๊ฒ ๊ฐ์์ ์์ ๊ฐ์ด ์ค๊ณํ์ต๋๋ค.
Service ๋ ์ด์ด์ Repository ๋ ์ด์ด๋ฅผ ๋์
์์ด MVC ํจํด๋ง์ผ๋ก ์ค๊ณํด์ ๋ชจ๋ธ์ด ์ฌ๊ณ ์๋์ ๋ค๊ณ ์๋ ๊ฒ์ ๋ฌธ์ ๋ ์๋ค๊ณ ์๊ฐํฉ๋๋ค. |
@@ -0,0 +1,61 @@
+package store.model.store.promotion;
+
+import static store.exception.store.StoreErrorStatus.INVALID_PROMOTION_BUY_AMOUNT;
+import static store.exception.store.StoreErrorStatus.INVALID_PROMOTION_GIVE_AMOUNT;
+
+import java.time.LocalDateTime;
+import store.exception.store.StoreException;
+
+public class Promotion {
+ private final String name;
+ private final int buyAmount;
+ private final int giveAmount;
+ private final LocalDateTime startAt;
+ private final LocalDateTime endAt;
+
+ private Promotion(String name, int buyAmount, int giveAmount, LocalDateTime startAt, LocalDateTime endAt) {
+ validateBuyAmount(buyAmount);
+ validateGiveAmount(giveAmount);
+ this.name = name;
+ this.buyAmount = buyAmount;
+ this.giveAmount = giveAmount;
+ this.startAt = startAt;
+ this.endAt = endAt;
+ }
+
+ public static Promotion of(String name,
+ int buyAmount,
+ int giveAmount,
+ LocalDateTime startAt,
+ LocalDateTime endAt) {
+ return new Promotion(name, buyAmount, giveAmount, startAt, endAt);
+ }
+
+ public boolean isNameEquals(String name) {
+ return this.name.equals(name);
+ }
+
+ public boolean isPeriod(LocalDateTime now) {
+ return startAt.isBefore(now) && endAt.isAfter(now);
+ }
+
+ private void validateBuyAmount(int buyAmount) {
+ if (buyAmount < 1) {
+ throw new StoreException(INVALID_PROMOTION_BUY_AMOUNT);
+ }
+ }
+
+ private void validateGiveAmount(int giveAmount) {
+ if (giveAmount != 1) {
+ throw new StoreException(INVALID_PROMOTION_GIVE_AMOUNT);
+ }
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getUnit() {
+ return buyAmount + giveAmount;
+ }
+} | Java | ์ฐํ
์ฝ์์ ์ ๊ณตํ๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ `DateTimes` ํด๋์ค์ `now()` ๋ฉ์๋์ ๋ฐํ๊ฐ์ด LocalDateTime์ด์ฌ์ LocalDate๋ก ๋ณํํ์ง ์๊ณ ๋ฐ๋ก ๋น๊ตํ ์ ์๊ฒ ์์ ๊ฐ์ด ์ฌ์ฉํ์ต๋๋ค. |
@@ -0,0 +1,20 @@
+package store.util.reader;
+
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+public class RepeatableReader {
+ public static <T> T handle(Supplier<String> viewMethod,
+ Function<String, T> converter,
+ Consumer<String> errorHandler) {
+ while (true) {
+ try {
+ String userInput = viewMethod.get();
+ return converter.apply(userInput);
+ } catch (IllegalArgumentException e) {
+ errorHandler.accept(e.getMessage());
+ }
+ }
+ }
+} | Java | ๊ฐ์ฌํฉ๋๋ค ๐ |
@@ -0,0 +1,100 @@
+package store;
+
+import java.util.Map;
+import store.model.order.Payment;
+import store.model.order.PurchaseOrder;
+import store.model.store.StoreRoom;
+import store.util.parser.ClosedQuestionsParser;
+import store.util.parser.PurchaseParser;
+import store.util.reader.RepeatableReader;
+import store.view.ErrorView;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreApplication {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final ErrorView errorView;
+ private final StoreRoom storeRoom;
+
+ public StoreApplication(InputView inputView, OutputView outputView, ErrorView errorView, StoreRoom storeRoom) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.errorView = errorView;
+ this.storeRoom = storeRoom;
+ }
+
+ public void run() {
+ while (true) {
+ outputView.printProducts(storeRoom);
+ processPurchase();
+ boolean buyMore = RepeatableReader.handle(inputView::askAdditionalPurchase,
+ ClosedQuestionsParser::parseAnswer, errorView::errorPage);
+ if (!buyMore) {
+ return;
+ }
+ }
+ }
+
+ private void processPurchase() {
+ PurchaseOrder purchaseOrder = createPurchaseOrder(storeRoom);
+ purchaseOrder = adjustOrderWithPromotions(purchaseOrder, storeRoom);
+ if (purchaseOrder.getTotalBuyAmount() <= 0) {
+ return;
+ }
+ boolean hasMembership = RepeatableReader.handle(inputView::askMembership, ClosedQuestionsParser::parseAnswer,
+ errorView::errorPage);
+ Payment payment = Payment.from(purchaseOrder, storeRoom, hasMembership);
+ outputView.printReceipt(payment);
+ storeRoom.arrange(payment.getPurchaseOrder().getPurchaseOrder());
+ }
+
+ private PurchaseOrder createPurchaseOrder(StoreRoom storeRoom) {
+ return RepeatableReader.handle(inputView::readItem, (userInput) -> {
+ Map<String, Integer> items = PurchaseParser.parseInputItems(userInput);
+ return PurchaseOrder.from(items, storeRoom);
+ }, errorView::errorPage);
+ }
+
+ private PurchaseOrder adjustOrderWithPromotions(PurchaseOrder purchaseOrder, StoreRoom storeRoom) {
+ PurchaseOrder result = purchaseOrder;
+ for (Map.Entry<String, Integer> entry : purchaseOrder.getPurchaseOrder().entrySet()) {
+ result = applyPromotionToProduct(result, storeRoom, entry.getKey(), entry.getValue());
+ }
+ return result;
+ }
+
+ private PurchaseOrder applyPromotionToProduct(PurchaseOrder purchaseOrder,
+ StoreRoom storeRoom,
+ String productName,
+ int buyAmount) {
+ int fullPriceAmount = storeRoom.getNonPromotionalQuantity(productName, buyAmount);
+ if (fullPriceAmount > 0) {
+ purchaseOrder = purchaseOrder
+ .decreaseBuyAmount(productName, getDecreaseAmount(productName, fullPriceAmount));
+ }
+ if (storeRoom.canGetOneMore(productName, buyAmount)) {
+ purchaseOrder = purchaseOrder.increaseBuyAmount(productName, getIncreaseAmount(productName));
+ }
+ return purchaseOrder;
+ }
+
+ private int getDecreaseAmount(String productName, int fullPriceAmount) {
+ boolean isAgree = RepeatableReader.handle(() ->
+ inputView.askFullPrice(productName, fullPriceAmount), ClosedQuestionsParser::parseAnswer,
+ errorView::errorPage);
+ if (!isAgree) {
+ return fullPriceAmount;
+ }
+ return 0;
+ }
+
+ private int getIncreaseAmount(String productName) {
+ boolean isAgree = RepeatableReader.handle(() ->
+ inputView.askAddOne(productName), ClosedQuestionsParser::parseAnswer, errorView::errorPage);
+ if (isAgree) {
+ return 1;
+ }
+ return 0;
+ }
+} | Java | ์กฐ๊ธ ๋ ํ์ด์ ๋ง์๋๋ฆฌ๋ฉด
`boolean ๋ฉค๋ฒ์ฝํ ์ธ์๋ฐ๊ธฐ๋กํ๋๊ฐ` ๊ฐ ์๋,
`boolean ๋ฉค๋ฒ์ฝ์๊ฐ์ก๋๊ฐ` ๋ก ๋ช
๋ช
๋์ด์ ์ฌ์ญค๋ดค์ต๋๋ค. |
@@ -0,0 +1,94 @@
+package store.model.store.product;
+
+import static store.exception.store.StoreErrorStatus.INVALID_PRODUCT_PRICE;
+import static store.exception.store.StoreErrorStatus.INVALID_PRODUCT_STOCK;
+
+import java.time.LocalDateTime;
+import store.exception.store.StoreException;
+import store.model.store.promotion.Promotion;
+
+public class Product {
+ private final String name;
+ private final int price;
+ private int stock;
+ private final Promotion promotion;
+
+ private Product(String name, int price, int stock, Promotion promotion) {
+ validatePrice(price);
+ validateStock(stock);
+ this.name = name;
+ this.price = price;
+ this.stock = stock;
+ this.promotion = promotion;
+ }
+
+ public static Product of(String name, int price, int stock, Promotion promotion) {
+ return new Product(name, price, stock, promotion);
+ }
+
+ public static Product createEmptyGeneralProduct(Product product) {
+ return new Product(product.name, product.price, 0, null);
+ }
+
+ public void decreaseStock(int amount) {
+ stock -= amount;
+ }
+
+ public boolean isNameEquals(Product product) {
+ return this.name.equals(product.name);
+ }
+
+ public boolean isNameEquals(String name) {
+ return this.name.equals(name);
+ }
+
+ public boolean isPromotionPeriod(LocalDateTime now) {
+ if (this.promotion == null) {
+ return false;
+ }
+ return promotion.isPeriod(now);
+ }
+
+ public boolean isGeneralProduct() {
+ return promotion == null;
+ }
+
+ public boolean isPromotionProduct() {
+ return promotion != null;
+ }
+
+ private void validatePrice(int price) {
+ if (price <= 0) {
+ throw new StoreException(INVALID_PRODUCT_PRICE);
+ }
+ }
+
+ private void validateStock(int stock) {
+ if (stock < 0) {
+ throw new StoreException(INVALID_PRODUCT_STOCK);
+ }
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public int getStock() {
+ return stock;
+ }
+
+ public String getPromotionName() {
+ if (promotion == null) {
+ return "";
+ }
+ return promotion.getName();
+ }
+
+ public int getPromotionUnit() {
+ return promotion.getUnit();
+ }
+} | Java | ๋ง์ต๋๋ค. ์ฝ๋๋ฅผ ๋ณด๋ฉด์ ๋ถํธํจ์ด ์ ํ ์์์ต๋๋ค! |
@@ -0,0 +1,92 @@
+package store.model.order;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.util.Map;
+import java.util.stream.Collectors;
+import store.model.store.StoreRoom;
+import store.model.store.product.Product;
+
+public class Payment {
+ private final PurchaseOrder purchaseOrder;
+ private final StoreRoom storeRoom;
+ private final boolean hasMembership;
+
+ private Payment(PurchaseOrder purchaseOrder, StoreRoom storeRoom, boolean hasMembership) {
+ this.purchaseOrder = purchaseOrder;
+ this.storeRoom = storeRoom;
+ this.hasMembership = hasMembership;
+ }
+
+ public static Payment from(PurchaseOrder purchaseOrder, StoreRoom storeRoom, boolean hasMembership) {
+ return new Payment(purchaseOrder, storeRoom, hasMembership);
+ }
+
+ public long calculateActualPrice() {
+ long promotionalDiscount = calculatePromotionalDiscount();
+ long membershipDiscount = calculateMembershipDiscount();
+ long totalPrice = calculateTotalPrice();
+ return totalPrice - (promotionalDiscount + membershipDiscount);
+ }
+
+ public long calculatePromotionalDiscount() {
+ return extractPromotionalProducts().entrySet().stream()
+ .mapToLong(entry -> (long) storeRoom.getProductPrice(entry.getKey()) * entry.getValue())
+ .sum();
+ }
+
+ public long calculateMembershipDiscount() {
+ if (!hasMembership) {
+ return 0;
+ }
+ long promotionAppliedPrice = extractPromotionalProducts().entrySet().stream()
+ .mapToLong(entry -> {
+ Product product = storeRoom.getPromotionProducts().findNullableProductByName(entry.getKey());
+ return (long) product.getPrice() * entry.getValue() * product.getPromotionUnit();
+ }).sum();
+ long membershipDiscount = (long) ((calculateTotalPrice() - promotionAppliedPrice) * 0.3);
+ return Math.min(8000L, membershipDiscount);
+ }
+
+ public long calculateTotalPrice() {
+ return purchaseOrder.getPurchaseOrder().entrySet().stream()
+ .mapToLong(entry -> (long) storeRoom.getProductPrice(entry.getKey()) * entry.getValue())
+ .sum();
+ }
+
+ public long calculateProductPrice(String productName) {
+ int buyAmount = purchaseOrder.getPurchaseOrder().get(productName);
+ int productPrice = storeRoom.getProductPrice(productName);
+ return (long) buyAmount * productPrice;
+ }
+
+ public long calculateTotalBuyAmount() {
+ return purchaseOrder.getPurchaseOrder().values().stream()
+ .mapToLong(Long::valueOf)
+ .sum();
+ }
+
+ private int calculateGiveawayAmount(String productName, int quantity) {
+ Product product = storeRoom.getPromotionProducts().findNullableProductByName(productName);
+ if (product != null
+ && product.isPromotionPeriod(DateTimes.now())
+ && product.getStock() >= product.getPromotionUnit()) {
+ int promotionalQuantity = quantity - storeRoom.getNonPromotionalQuantity(productName, quantity);
+ return promotionalQuantity / product.getPromotionUnit();
+ }
+ return 0;
+ }
+
+ public Map<String, Integer> extractPromotionalProducts() {
+ return purchaseOrder.getPurchaseOrder().entrySet().stream()
+ .map(entry -> Map.entry(
+ entry.getKey(),
+ calculateGiveawayAmount(entry.getKey(), entry.getValue())
+ ))
+ .filter(entry -> entry.getValue() > 0)
+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+ }
+
+ public PurchaseOrder getPurchaseOrder() {
+ return purchaseOrder;
+ }
+} | Java | ๊ฐ์ฌํฉ๋๋ค! ์ฐธ๊ณ ํ๊ฒ ์ต๋๋ค. |
@@ -0,0 +1,100 @@
+package store;
+
+import java.util.Map;
+import store.model.order.Payment;
+import store.model.order.PurchaseOrder;
+import store.model.store.StoreRoom;
+import store.util.parser.ClosedQuestionsParser;
+import store.util.parser.PurchaseParser;
+import store.util.reader.RepeatableReader;
+import store.view.ErrorView;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreApplication {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final ErrorView errorView;
+ private final StoreRoom storeRoom;
+
+ public StoreApplication(InputView inputView, OutputView outputView, ErrorView errorView, StoreRoom storeRoom) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.errorView = errorView;
+ this.storeRoom = storeRoom;
+ }
+
+ public void run() {
+ while (true) {
+ outputView.printProducts(storeRoom);
+ processPurchase();
+ boolean buyMore = RepeatableReader.handle(inputView::askAdditionalPurchase,
+ ClosedQuestionsParser::parseAnswer, errorView::errorPage);
+ if (!buyMore) {
+ return;
+ }
+ }
+ }
+
+ private void processPurchase() {
+ PurchaseOrder purchaseOrder = createPurchaseOrder(storeRoom);
+ purchaseOrder = adjustOrderWithPromotions(purchaseOrder, storeRoom);
+ if (purchaseOrder.getTotalBuyAmount() <= 0) {
+ return;
+ }
+ boolean hasMembership = RepeatableReader.handle(inputView::askMembership, ClosedQuestionsParser::parseAnswer,
+ errorView::errorPage);
+ Payment payment = Payment.from(purchaseOrder, storeRoom, hasMembership);
+ outputView.printReceipt(payment);
+ storeRoom.arrange(payment.getPurchaseOrder().getPurchaseOrder());
+ }
+
+ private PurchaseOrder createPurchaseOrder(StoreRoom storeRoom) {
+ return RepeatableReader.handle(inputView::readItem, (userInput) -> {
+ Map<String, Integer> items = PurchaseParser.parseInputItems(userInput);
+ return PurchaseOrder.from(items, storeRoom);
+ }, errorView::errorPage);
+ }
+
+ private PurchaseOrder adjustOrderWithPromotions(PurchaseOrder purchaseOrder, StoreRoom storeRoom) {
+ PurchaseOrder result = purchaseOrder;
+ for (Map.Entry<String, Integer> entry : purchaseOrder.getPurchaseOrder().entrySet()) {
+ result = applyPromotionToProduct(result, storeRoom, entry.getKey(), entry.getValue());
+ }
+ return result;
+ }
+
+ private PurchaseOrder applyPromotionToProduct(PurchaseOrder purchaseOrder,
+ StoreRoom storeRoom,
+ String productName,
+ int buyAmount) {
+ int fullPriceAmount = storeRoom.getNonPromotionalQuantity(productName, buyAmount);
+ if (fullPriceAmount > 0) {
+ purchaseOrder = purchaseOrder
+ .decreaseBuyAmount(productName, getDecreaseAmount(productName, fullPriceAmount));
+ }
+ if (storeRoom.canGetOneMore(productName, buyAmount)) {
+ purchaseOrder = purchaseOrder.increaseBuyAmount(productName, getIncreaseAmount(productName));
+ }
+ return purchaseOrder;
+ }
+
+ private int getDecreaseAmount(String productName, int fullPriceAmount) {
+ boolean isAgree = RepeatableReader.handle(() ->
+ inputView.askFullPrice(productName, fullPriceAmount), ClosedQuestionsParser::parseAnswer,
+ errorView::errorPage);
+ if (!isAgree) {
+ return fullPriceAmount;
+ }
+ return 0;
+ }
+
+ private int getIncreaseAmount(String productName) {
+ boolean isAgree = RepeatableReader.handle(() ->
+ inputView.askAddOne(productName), ClosedQuestionsParser::parseAnswer, errorView::errorPage);
+ if (isAgree) {
+ return 1;
+ }
+ return 0;
+ }
+} | Java | ์ํ ๊ทธ ๋ป์ด์๊ตฐ์.
์ ๋ ๋ฉค๋ฒ์ญ ์ ๋ฌด์๋ง ์ ๊ฒฝ์จ์ ์ ๋ ๊ฒ ๋ค์ด๋ฐ์ ํ๋๋ฐ ๋ง์์ ๋ฃ๊ณ ๋ณด๋ ์๋๊ฐ ๋ค ๋ณ์์ ๋ด๊ธฐ์ง ์์ ๋ฏ ๋ณด์ด๋ค์. |
@@ -0,0 +1,94 @@
+package store.model.store.product;
+
+import static store.exception.store.StoreErrorStatus.INVALID_PRODUCT_PRICE;
+import static store.exception.store.StoreErrorStatus.INVALID_PRODUCT_STOCK;
+
+import java.time.LocalDateTime;
+import store.exception.store.StoreException;
+import store.model.store.promotion.Promotion;
+
+public class Product {
+ private final String name;
+ private final int price;
+ private int stock;
+ private final Promotion promotion;
+
+ private Product(String name, int price, int stock, Promotion promotion) {
+ validatePrice(price);
+ validateStock(stock);
+ this.name = name;
+ this.price = price;
+ this.stock = stock;
+ this.promotion = promotion;
+ }
+
+ public static Product of(String name, int price, int stock, Promotion promotion) {
+ return new Product(name, price, stock, promotion);
+ }
+
+ public static Product createEmptyGeneralProduct(Product product) {
+ return new Product(product.name, product.price, 0, null);
+ }
+
+ public void decreaseStock(int amount) {
+ stock -= amount;
+ }
+
+ public boolean isNameEquals(Product product) {
+ return this.name.equals(product.name);
+ }
+
+ public boolean isNameEquals(String name) {
+ return this.name.equals(name);
+ }
+
+ public boolean isPromotionPeriod(LocalDateTime now) {
+ if (this.promotion == null) {
+ return false;
+ }
+ return promotion.isPeriod(now);
+ }
+
+ public boolean isGeneralProduct() {
+ return promotion == null;
+ }
+
+ public boolean isPromotionProduct() {
+ return promotion != null;
+ }
+
+ private void validatePrice(int price) {
+ if (price <= 0) {
+ throw new StoreException(INVALID_PRODUCT_PRICE);
+ }
+ }
+
+ private void validateStock(int stock) {
+ if (stock < 0) {
+ throw new StoreException(INVALID_PRODUCT_STOCK);
+ }
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public int getStock() {
+ return stock;
+ }
+
+ public String getPromotionName() {
+ if (promotion == null) {
+ return "";
+ }
+ return promotion.getName();
+ }
+
+ public int getPromotionUnit() {
+ return promotion.getUnit();
+ }
+} | Java | ๊ทธ๋ ๊ฒ ๋ง์ํด์ฃผ์๋ ๊ฐ์ฌํฉ๋๋ค ๐ |
@@ -0,0 +1,100 @@
+package store;
+
+import java.util.Map;
+import store.model.order.Payment;
+import store.model.order.PurchaseOrder;
+import store.model.store.StoreRoom;
+import store.util.parser.ClosedQuestionsParser;
+import store.util.parser.PurchaseParser;
+import store.util.reader.RepeatableReader;
+import store.view.ErrorView;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreApplication {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final ErrorView errorView;
+ private final StoreRoom storeRoom;
+
+ public StoreApplication(InputView inputView, OutputView outputView, ErrorView errorView, StoreRoom storeRoom) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.errorView = errorView;
+ this.storeRoom = storeRoom;
+ }
+
+ public void run() {
+ while (true) {
+ outputView.printProducts(storeRoom);
+ processPurchase();
+ boolean buyMore = RepeatableReader.handle(inputView::askAdditionalPurchase,
+ ClosedQuestionsParser::parseAnswer, errorView::errorPage);
+ if (!buyMore) {
+ return;
+ }
+ }
+ }
+
+ private void processPurchase() {
+ PurchaseOrder purchaseOrder = createPurchaseOrder(storeRoom);
+ purchaseOrder = adjustOrderWithPromotions(purchaseOrder, storeRoom);
+ if (purchaseOrder.getTotalBuyAmount() <= 0) {
+ return;
+ }
+ boolean hasMembership = RepeatableReader.handle(inputView::askMembership, ClosedQuestionsParser::parseAnswer,
+ errorView::errorPage);
+ Payment payment = Payment.from(purchaseOrder, storeRoom, hasMembership);
+ outputView.printReceipt(payment);
+ storeRoom.arrange(payment.getPurchaseOrder().getPurchaseOrder());
+ }
+
+ private PurchaseOrder createPurchaseOrder(StoreRoom storeRoom) {
+ return RepeatableReader.handle(inputView::readItem, (userInput) -> {
+ Map<String, Integer> items = PurchaseParser.parseInputItems(userInput);
+ return PurchaseOrder.from(items, storeRoom);
+ }, errorView::errorPage);
+ }
+
+ private PurchaseOrder adjustOrderWithPromotions(PurchaseOrder purchaseOrder, StoreRoom storeRoom) {
+ PurchaseOrder result = purchaseOrder;
+ for (Map.Entry<String, Integer> entry : purchaseOrder.getPurchaseOrder().entrySet()) {
+ result = applyPromotionToProduct(result, storeRoom, entry.getKey(), entry.getValue());
+ }
+ return result;
+ }
+
+ private PurchaseOrder applyPromotionToProduct(PurchaseOrder purchaseOrder,
+ StoreRoom storeRoom,
+ String productName,
+ int buyAmount) {
+ int fullPriceAmount = storeRoom.getNonPromotionalQuantity(productName, buyAmount);
+ if (fullPriceAmount > 0) {
+ purchaseOrder = purchaseOrder
+ .decreaseBuyAmount(productName, getDecreaseAmount(productName, fullPriceAmount));
+ }
+ if (storeRoom.canGetOneMore(productName, buyAmount)) {
+ purchaseOrder = purchaseOrder.increaseBuyAmount(productName, getIncreaseAmount(productName));
+ }
+ return purchaseOrder;
+ }
+
+ private int getDecreaseAmount(String productName, int fullPriceAmount) {
+ boolean isAgree = RepeatableReader.handle(() ->
+ inputView.askFullPrice(productName, fullPriceAmount), ClosedQuestionsParser::parseAnswer,
+ errorView::errorPage);
+ if (!isAgree) {
+ return fullPriceAmount;
+ }
+ return 0;
+ }
+
+ private int getIncreaseAmount(String productName) {
+ boolean isAgree = RepeatableReader.handle(() ->
+ inputView.askAddOne(productName), ClosedQuestionsParser::parseAnswer, errorView::errorPage);
+ if (isAgree) {
+ return 1;
+ }
+ return 0;
+ }
+} | Java | ์๋จ ์ ๊ฐ ์กฐ๊ธ ์ต์ง๋ก ์ฌ์ญค๋ณธ ๊ฒ๋ ์์ด์. ํน๋ณํ ์๋๊ฐ ์๋ค๋ฉด ๋ฐฐ์ฐ๊ณ ์ถ์์ต๋๋ค ใ
ใ
|
@@ -0,0 +1,16 @@
+package store.view;
+
+import store.model.order.Payment;
+import store.model.store.StoreRoom;
+import store.view.formatter.OutputFormatter;
+
+public class OutputView {
+
+ public void printProducts(StoreRoom storeRoom) {
+ System.out.println(OutputFormatter.buildStoreStock(storeRoom));
+ }
+
+ public void printReceipt(Payment payment) {
+ System.out.println(OutputFormatter.buildReceipt(payment));
+ }
+} | Java | `MVC` ๊ด์ ์์ ๋ทฐ๊ฐ ๋ชจ๋ธ์ ์ฐธ์กฐํ๋ ๊ฒ์ด ์๋๋ ๊ฒ์ ์๋์ง๋ง `๋ทฐ๋ ๋ชจ๋ธ๊ณผ ์ปจํธ๋กค๋ฌ๋ฅผ ์ ํ์๊ฐ ์๋ค`๋ผ๋ ๋ง์ด ์๋ ๊ฑฐ์ฒ๋ผ ๋๋๋ก ๋ชจ๋ฅด๋ ๊ฒ์ด ์ข์ ๊ฒ์ผ๋ก ์๊ณ ์์ต๋๋ค!
๊ทธ๋ฐ ์ธก๋ฉด์์ `StoreRoom`์ ์ธ์๋ก ๋ฐ์์ ์ฒ๋ฆฌํ๋ ๊ฒ ๋ณด๋ค ๋ฉ์ธ์ง ํฌ๋งท์ ์ํ ๋ฐ์ดํฐ๋ง ๋ฐ์์ ์ฒ๋ฆฌํ๋ ๋ฐฉ์์ ์ด๋จ๊น์? |
@@ -0,0 +1,130 @@
+package store.view.formatter;
+
+import store.model.order.Payment;
+import store.model.store.StoreRoom;
+import store.model.store.product.Product;
+import store.model.store.product.Products;
+
+public class OutputFormatter {
+ private static final String WELCOME_MESSAGE = "์๋
ํ์ธ์. Wํธ์์ ์
๋๋ค.\nํ์ฌ ๋ณด์ ํ๊ณ ์๋ ์ํ์
๋๋ค.";
+ private static final String PRODUCT_PREFIX = "- ";
+ private static final String SOLD_OUT = "์ฌ๊ณ ์์";
+ private static final String RECEIPT_START_MESSAGE = "==============W ํธ์์ ================";
+ private static final String RECEIPT_COLUMN_MESSAGE = "์ํ๋ช
\t\t์๋\t๊ธ์ก";
+ private static final String RECEIPT_PURCHASE_MESSAGE_FORMAT = "%s\t\t%,d \t%,d";
+ private static final String RECEIPT_GIVEAWAY_MESSAGE = "=============์ฆ\t์ ===============";
+ private static final String RECEIPT_GIVEAWAY_PRODUCT_MESSAGE_FORMAT = "%s\t\t%,d";
+ private static final String RECEIPT_LINE_SEPARATOR = "====================================";
+ private static final String RECEIPT_TOTAL_PRICE_MESSAGE_FORMAT = "์ด๊ตฌ๋งค์ก\t\t%,d\t%,d";
+ private static final String RECEIPT_PROMOTION_DISCOUNT_MESSAGE_FORMAT = "ํ์ฌํ ์ธ\t\t\t-%,d";
+ private static final String RECEIPT_MEMBERSHIP_DISCOUNT_MESSAGE_FORMAT = "๋ฉค๋ฒ์ญํ ์ธ\t\t\t-%,d";
+ private static final String RECEIPT_ACTUAL_PRICE_MESSAGE_FORMAT = "๋ด์ค๋\t\t\t%,d";
+ private static final String SYSTEM_LINE_SEPARATOR = System.lineSeparator();
+
+ private OutputFormatter() {
+ }
+
+ public static String buildStoreStock(StoreRoom storeRoom) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(WELCOME_MESSAGE).append(SYSTEM_LINE_SEPARATOR).append(SYSTEM_LINE_SEPARATOR);
+
+ String menus = buildProducts(storeRoom.getGeneralProducts(), storeRoom.getPromotionProducts());
+ sb.append(menus);
+ return sb.toString();
+ }
+
+ public static String buildReceipt(Payment payment) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(buildReceiptHeader())
+ .append(buildPurchaseItems(payment))
+ .append(buildGiveawayIems(payment))
+ .append(buildReceiptSummary(payment));
+ return sb.toString();
+ }
+
+ private static String buildProducts(Products generalProducts, Products promotionProducts) {
+ StringBuilder sb = new StringBuilder();
+ for (Product product : generalProducts.getProducts()) {
+ if (promotionProducts.contains(product.getName())) {
+ sb.append(buildProductMessage(promotionProducts.findNullableProductByName(product.getName())));
+ }
+ sb.append(buildProductMessage(product));
+ }
+ return sb.toString();
+ }
+
+ private static String buildProductMessage(Product product) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(PRODUCT_PREFIX)
+ .append(product.getName()).append(" ")
+ .append(String.format("%,d์", product.getPrice())).append(" ")
+ .append(buildProductStock(product.getStock())).append(" ")
+ .append(product.getPromotionName()).append(SYSTEM_LINE_SEPARATOR);
+ return sb.toString();
+ }
+
+ private static String buildProductStock(int stock) {
+ if (stock == 0) {
+ return SOLD_OUT;
+ }
+ return String.format("%,d๊ฐ", stock);
+ }
+
+ private static String buildReceiptHeader() {
+ StringBuilder sb = new StringBuilder();
+ sb.append(RECEIPT_START_MESSAGE).append(SYSTEM_LINE_SEPARATOR)
+ .append(RECEIPT_COLUMN_MESSAGE).append(SYSTEM_LINE_SEPARATOR);
+ return sb.toString();
+ }
+
+ private static String buildPurchaseItems(Payment payment) {
+ StringBuilder sb = new StringBuilder();
+ payment.getPurchaseOrder().getPurchaseOrder().forEach((name, quantity) ->
+ sb.append(String.format(RECEIPT_PURCHASE_MESSAGE_FORMAT,
+ name, quantity, payment.calculateProductPrice(name)))
+ .append(SYSTEM_LINE_SEPARATOR)
+ );
+ return sb.toString();
+ }
+
+ private static String buildGiveawayIems(Payment payment) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(RECEIPT_GIVEAWAY_MESSAGE).append(SYSTEM_LINE_SEPARATOR);
+
+ payment.extractPromotionalProducts().forEach((name, quantity) ->
+ sb.append(String.format(RECEIPT_GIVEAWAY_PRODUCT_MESSAGE_FORMAT, name, quantity))
+ .append(SYSTEM_LINE_SEPARATOR)
+ );
+ return sb.toString();
+ }
+
+ private static String buildReceiptSummary(Payment payment) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(RECEIPT_LINE_SEPARATOR).append(SYSTEM_LINE_SEPARATOR)
+ .append(buildTotalPrice(payment))
+ .append(buildDiscounts(payment))
+ .append(buildFinalPrice(payment));
+ return sb.toString();
+ }
+
+ private static String buildTotalPrice(Payment payment) {
+ return String.format(RECEIPT_TOTAL_PRICE_MESSAGE_FORMAT,
+ payment.calculateTotalBuyAmount(), payment.calculateTotalPrice())
+ + SYSTEM_LINE_SEPARATOR;
+ }
+
+ private static String buildDiscounts(Payment payment) {
+ return String.format(RECEIPT_PROMOTION_DISCOUNT_MESSAGE_FORMAT,
+ payment.calculatePromotionalDiscount())
+ + SYSTEM_LINE_SEPARATOR
+ + String.format(RECEIPT_MEMBERSHIP_DISCOUNT_MESSAGE_FORMAT,
+ payment.calculateMembershipDiscount())
+ + SYSTEM_LINE_SEPARATOR;
+ }
+
+ private static String buildFinalPrice(Payment payment) {
+ return String.format(RECEIPT_ACTUAL_PRICE_MESSAGE_FORMAT,
+ payment.calculateActualPrice())
+ + SYSTEM_LINE_SEPARATOR;
+ }
+} | Java | `getPurchaseOrder`๋ผ๋ ๋ฉ์๋๊ฐ ๋ ๋ฒ ์ฐ์๋์ด ๋ชจํธํ ๊ฐ์ด ์๋ ๊ฒ ๊ฐ์ต๋๋ค!
๋ ๋ฉ์๋์ ๋ค์ด๋ฐ์ ๋ฌ๋ฆฌ ํ๋ฉด ์ข์ ๊ฒ ๊ฐ์์!
์ถ๊ฐ์ ์ผ๋ก ์ฒซ `getPurchaseOrder` ์์๋ `PurchaseOrder` ๊ฐ์ฒด๊ฐ ๋ฐํ๋๊ณ ๋ ๋ฒ์งธ์์๋ ์์ดํ
์ ๋ณด๋ค์ด ๋ด๊ธด `Map`์ด ๋ฐํ๋๋ ๊ฒ ๊ฐ์ต๋๋ค! ์ด๋ `๋๋ฏธํฐ์ ๋ฒ์น`์ ์๋ฐฐ๋๋ ๊ฒ์ผ๋ก ๋ณด์ด๋๋ฐ์! ์ฐํ
์ฝ์์ ์ ์ํ๋ ํด๋ฆฐ์ฝ๋ ์ฌํญ์ `๋๋ฏธํฐ ๋ฒ์น`์ด ํฌํจ๋ ๋งํผ ์ฐ์์ ์ผ๋ก ์ฌ์ฉํ๋ ๊ฒ์ ์ง์ํ๋ ๊ฒ๋ ์ข์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,130 @@
+package store.view.formatter;
+
+import store.model.order.Payment;
+import store.model.store.StoreRoom;
+import store.model.store.product.Product;
+import store.model.store.product.Products;
+
+public class OutputFormatter {
+ private static final String WELCOME_MESSAGE = "์๋
ํ์ธ์. Wํธ์์ ์
๋๋ค.\nํ์ฌ ๋ณด์ ํ๊ณ ์๋ ์ํ์
๋๋ค.";
+ private static final String PRODUCT_PREFIX = "- ";
+ private static final String SOLD_OUT = "์ฌ๊ณ ์์";
+ private static final String RECEIPT_START_MESSAGE = "==============W ํธ์์ ================";
+ private static final String RECEIPT_COLUMN_MESSAGE = "์ํ๋ช
\t\t์๋\t๊ธ์ก";
+ private static final String RECEIPT_PURCHASE_MESSAGE_FORMAT = "%s\t\t%,d \t%,d";
+ private static final String RECEIPT_GIVEAWAY_MESSAGE = "=============์ฆ\t์ ===============";
+ private static final String RECEIPT_GIVEAWAY_PRODUCT_MESSAGE_FORMAT = "%s\t\t%,d";
+ private static final String RECEIPT_LINE_SEPARATOR = "====================================";
+ private static final String RECEIPT_TOTAL_PRICE_MESSAGE_FORMAT = "์ด๊ตฌ๋งค์ก\t\t%,d\t%,d";
+ private static final String RECEIPT_PROMOTION_DISCOUNT_MESSAGE_FORMAT = "ํ์ฌํ ์ธ\t\t\t-%,d";
+ private static final String RECEIPT_MEMBERSHIP_DISCOUNT_MESSAGE_FORMAT = "๋ฉค๋ฒ์ญํ ์ธ\t\t\t-%,d";
+ private static final String RECEIPT_ACTUAL_PRICE_MESSAGE_FORMAT = "๋ด์ค๋\t\t\t%,d";
+ private static final String SYSTEM_LINE_SEPARATOR = System.lineSeparator();
+
+ private OutputFormatter() {
+ }
+
+ public static String buildStoreStock(StoreRoom storeRoom) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(WELCOME_MESSAGE).append(SYSTEM_LINE_SEPARATOR).append(SYSTEM_LINE_SEPARATOR);
+
+ String menus = buildProducts(storeRoom.getGeneralProducts(), storeRoom.getPromotionProducts());
+ sb.append(menus);
+ return sb.toString();
+ }
+
+ public static String buildReceipt(Payment payment) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(buildReceiptHeader())
+ .append(buildPurchaseItems(payment))
+ .append(buildGiveawayIems(payment))
+ .append(buildReceiptSummary(payment));
+ return sb.toString();
+ }
+
+ private static String buildProducts(Products generalProducts, Products promotionProducts) {
+ StringBuilder sb = new StringBuilder();
+ for (Product product : generalProducts.getProducts()) {
+ if (promotionProducts.contains(product.getName())) {
+ sb.append(buildProductMessage(promotionProducts.findNullableProductByName(product.getName())));
+ }
+ sb.append(buildProductMessage(product));
+ }
+ return sb.toString();
+ }
+
+ private static String buildProductMessage(Product product) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(PRODUCT_PREFIX)
+ .append(product.getName()).append(" ")
+ .append(String.format("%,d์", product.getPrice())).append(" ")
+ .append(buildProductStock(product.getStock())).append(" ")
+ .append(product.getPromotionName()).append(SYSTEM_LINE_SEPARATOR);
+ return sb.toString();
+ }
+
+ private static String buildProductStock(int stock) {
+ if (stock == 0) {
+ return SOLD_OUT;
+ }
+ return String.format("%,d๊ฐ", stock);
+ }
+
+ private static String buildReceiptHeader() {
+ StringBuilder sb = new StringBuilder();
+ sb.append(RECEIPT_START_MESSAGE).append(SYSTEM_LINE_SEPARATOR)
+ .append(RECEIPT_COLUMN_MESSAGE).append(SYSTEM_LINE_SEPARATOR);
+ return sb.toString();
+ }
+
+ private static String buildPurchaseItems(Payment payment) {
+ StringBuilder sb = new StringBuilder();
+ payment.getPurchaseOrder().getPurchaseOrder().forEach((name, quantity) ->
+ sb.append(String.format(RECEIPT_PURCHASE_MESSAGE_FORMAT,
+ name, quantity, payment.calculateProductPrice(name)))
+ .append(SYSTEM_LINE_SEPARATOR)
+ );
+ return sb.toString();
+ }
+
+ private static String buildGiveawayIems(Payment payment) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(RECEIPT_GIVEAWAY_MESSAGE).append(SYSTEM_LINE_SEPARATOR);
+
+ payment.extractPromotionalProducts().forEach((name, quantity) ->
+ sb.append(String.format(RECEIPT_GIVEAWAY_PRODUCT_MESSAGE_FORMAT, name, quantity))
+ .append(SYSTEM_LINE_SEPARATOR)
+ );
+ return sb.toString();
+ }
+
+ private static String buildReceiptSummary(Payment payment) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(RECEIPT_LINE_SEPARATOR).append(SYSTEM_LINE_SEPARATOR)
+ .append(buildTotalPrice(payment))
+ .append(buildDiscounts(payment))
+ .append(buildFinalPrice(payment));
+ return sb.toString();
+ }
+
+ private static String buildTotalPrice(Payment payment) {
+ return String.format(RECEIPT_TOTAL_PRICE_MESSAGE_FORMAT,
+ payment.calculateTotalBuyAmount(), payment.calculateTotalPrice())
+ + SYSTEM_LINE_SEPARATOR;
+ }
+
+ private static String buildDiscounts(Payment payment) {
+ return String.format(RECEIPT_PROMOTION_DISCOUNT_MESSAGE_FORMAT,
+ payment.calculatePromotionalDiscount())
+ + SYSTEM_LINE_SEPARATOR
+ + String.format(RECEIPT_MEMBERSHIP_DISCOUNT_MESSAGE_FORMAT,
+ payment.calculateMembershipDiscount())
+ + SYSTEM_LINE_SEPARATOR;
+ }
+
+ private static String buildFinalPrice(Payment payment) {
+ return String.format(RECEIPT_ACTUAL_PRICE_MESSAGE_FORMAT,
+ payment.calculateActualPrice())
+ + SYSTEM_LINE_SEPARATOR;
+ }
+} | Java | `OutputFrmatter`๊ฐ ๋ค์ ๋ฌด๊ฑฐ์ด ๊ฐ์ฒด๋ผ๋ ๋๋์ด ๋ญ๋๋ค!
ํฌ๋งคํฐ์์ ๋ง์ ๋ก์ง์ ๋ด๋นํ๊ณ ์๋ ๊ฒ์ผ๋ก ์๊ฐ ๋๋๋ฐ์ ํนํ `payment.calculateActualPrice()` ๋ฑ ๋ชจ๋ธ ๊ฐ์ฒด๋ค์ ๋ด๋ถ ๊ธฐ๋ฅ๋ค์ ํ์ฉํด์ ๋ฐ์ดํฐ๋ค์ ๊ฐ์ ธ์ค๋ ๋ฐฉ์์ผ๋ก ๋ณด์
๋๋ค!
๋ค์ํ ๋ชจ๋ธ๋ค์ ๊ธฐ๋ฅ์ ํฌ๋งคํฐ ๋ด๋ถ์ ์ผ๋ก ๋ง์ด ์ฌ์ฉํด์ ๋ทฐ ๊ฐ์ฒด ๋ณด๋ค๋ ์๋น์ค์ ๊ฐ๊น์ง ์์๊น๋ผ๋ ์๊ฐ์ด ๋๋๋ฐ์ ์ด ๋ถ๋ถ์ ๋ํด์ ์ด๋ป๊ฒ ์๊ฐํ์๋์??
ํฌ๋งคํฐ๊ฐ ๋ชจ๋ธ ๊ฐ์ฒด๋ค์ ๋ฐ๋ ๊ฒ์ด ์๋ ์ด๋ฏธ ๊ณ์ฐ๋ ๋ฐ์ดํฐ๋ฅผ ๋ฐ๋ ๊ฒ์ผ๋ก ํ๋ฉด ๋ทฐ ๊ฐ์ฒด๋ก์ ๋ทฐ์ ํฌ๋งคํฐ ์ญํ ์ ๋ ์ง์ค๋ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค!
์ถ๊ฐ์ ์ผ๋ก ๋ชจ๋ธ ๊ฐ์ฒด๋ค์ ๋ํ ์์กด์ฑ๋ ์ค์ผ ์ ์๋ ์ด์ ์ด ์์ ๊ฒ ๊ฐ๋ค์! |
@@ -0,0 +1,35 @@
+package calculator.controller.validation
+
+class UserInputValidator {
+ fun validateUserInput(numbers: List<String>): List<Int> {
+ val newNumbers = checkIsEmpty(numbers)
+ checkIsInteger(newNumbers)
+ val allNumbers = changeInteger(newNumbers)
+ changeNegativeNumber(allNumbers)
+ return allNumbers
+ }
+
+ private fun checkIsEmpty(numbers: List<String>): List<String> {
+ return numbers.map { it.ifEmpty { "0" } }
+ }
+
+ private fun checkIsInteger(newNumbers: List<String>) {
+ newNumbers.map {
+ if (it.toIntOrNull() == null) {
+ throw IllegalArgumentException(UserInputErrorType.NOT_INTEGER.errorMessage)
+ }
+ }
+ }
+
+ private fun changeInteger(newNumbers: List<String>): List<Int> {
+ return newNumbers.map { it.toInt() }
+ }
+
+ private fun changeNegativeNumber(allNumbers: List<Int>) {
+ allNumbers.forEach {
+ if (it < 0) {
+ throw IllegalArgumentException(UserInputErrorType.NEGATIVE_NUMBER.errorMessage)
+ }
+ }
+ }
+}
\ No newline at end of file | Kotlin | ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ํ๋ ํจ์์ธ์ง๋ผ chane๋ผ๋ ๋ค์ด๋ฐ์ ์กฐ๊ธ ์ด์ํ๊ฒ ๊ฐ์์ ! ใ
ใ
any๋ฅผ ์ฌ์ฉํ๋ฉด ํจ์๋ฅผ ์กฐ๊ธ ๋ ์ค์ผ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค !
```
private fun changeNegativeNumber(allNumbers: List<Int>) {
if (allNumbers.any { it < 0 }) {
throw IllegalArgumentException(UserInputErrorType.NEGATIVE_NUMBER.errorMessage)
}
}
``` |
@@ -0,0 +1,45 @@
+package calculator.controller.domain
+
+import calculator.constants.Delimiter.CLONE
+import calculator.constants.Delimiter.COMMA
+import calculator.constants.Delimiter.CUSTOM_DELIMITER_PREFIX
+import calculator.constants.Delimiter.CUSTOM_DELIMITER_SUFFIX
+
+class DelimiterController(
+ private val input: String
+) {
+ fun checkDelimiter(): List<String> {
+ if (hasCustomDelimiter()) {
+ val customDelimiter = getCustomDelimiter()
+ val noCustomDelimiter = deleteCustomDelimiter()
+ val numbers = splitCustomDelimiter(noCustomDelimiter, customDelimiter)
+ return numbers
+ }
+ val numbers = splitDelimiter()
+ return numbers
+ }
+
+ private fun hasCustomDelimiter(): Boolean {
+ return input.startsWith(CUSTOM_DELIMITER_PREFIX.value) && input.indexOf(CUSTOM_DELIMITER_SUFFIX.value) == 3
+ }
+
+ private fun getCustomDelimiter(): String {
+ val customDelimiter = input.substring(2, 3)
+ return customDelimiter
+ }
+
+ private fun deleteCustomDelimiter(): String {
+ val noCustomDelimiter = input.substring(5)
+ return noCustomDelimiter
+ }
+
+ private fun splitDelimiter(): List<String> {
+ val numbers = input.split(COMMA.value, CLONE.value)
+ return numbers
+ }
+
+ private fun splitCustomDelimiter(noCustomDelimiter: String, customDelimiter: String): List<String> {
+ val numbers = noCustomDelimiter.split(COMMA.value, CLONE.value, customDelimiter)
+ return numbers
+ }
+}
\ No newline at end of file | Kotlin | ์ฑ์ฑ๋! ์ ๋ ์ฒซ ์ฃผ์ฐจ ๋ ์ปค์คํ
๊ตฌ๋ถ์๋ฅผ ์๋ฐ์์ผ๋ก ์ถ์ถํ์๋๋ฐ์
๋ค๋ฅธ ๋ถ๋ค ๊ตฌํํ๊ฑธ ๋ณด๋๊น ๋ ๊ธ์ ์ด์์ผ ๋ ๋ ๊ตฌ๋ถ์๋ก ์ฌ์ฉํ ์ ์๋๋ก ๋ง๋์
จ๋๋ผ๊ตฌ์
๊ทธ๋์ ์ด๋ ๊ฒ ํ๋ฉด ์ปค์คํ
๊ตฌ๋ถ์๊ฐ 2๊ธ์ ์ด์์ผ ๊ฒฝ์ฐ ์์๊ณผ๋ ๋ค๋ฅธ ์ค๋ฅ๋ฅผ ๋ณด์ฌ์ฃผ๋ ๊ฒ ๊ฐ์์
๋ฌผ๋ก ! ๋ฌธ์ ์๊ตฌ ์ฌํญ์ ์์๊ธฐ ๋๋ฌธ์ ๋ฐฐ์ ํ๊ณ ๊ตฌํํด๋ ์ ํ ๋ฌธ์ ์์ง๋ง ์ ๋
์ด๋ฐ ๋ถ๋ถ์ ์ฒซ ์ฃผ์ฐจ ๋ ๋์ณ์ ์ด๋ฒ ๋ฆฌํฉํ ๋ง์์ ์ ์ฉํด๋ดค๋๋ฐ ํน์ ์ผ๋ถ๋ฌ ๊ตฌํ์ ์ํ์ ๊ฑด์ง ๊ถ๊ธํฉ๋๋ค ใ
ใ
<img width="926" alt="image" src="https://github.com/user-attachments/assets/ec40ef9b-ae02-4dc5-8dac-6420d69ea0c5"> |
@@ -0,0 +1,45 @@
+package calculator.controller.domain
+
+import calculator.constants.Delimiter.CLONE
+import calculator.constants.Delimiter.COMMA
+import calculator.constants.Delimiter.CUSTOM_DELIMITER_PREFIX
+import calculator.constants.Delimiter.CUSTOM_DELIMITER_SUFFIX
+
+class DelimiterController(
+ private val input: String
+) {
+ fun checkDelimiter(): List<String> {
+ if (hasCustomDelimiter()) {
+ val customDelimiter = getCustomDelimiter()
+ val noCustomDelimiter = deleteCustomDelimiter()
+ val numbers = splitCustomDelimiter(noCustomDelimiter, customDelimiter)
+ return numbers
+ }
+ val numbers = splitDelimiter()
+ return numbers
+ }
+
+ private fun hasCustomDelimiter(): Boolean {
+ return input.startsWith(CUSTOM_DELIMITER_PREFIX.value) && input.indexOf(CUSTOM_DELIMITER_SUFFIX.value) == 3
+ }
+
+ private fun getCustomDelimiter(): String {
+ val customDelimiter = input.substring(2, 3)
+ return customDelimiter
+ }
+
+ private fun deleteCustomDelimiter(): String {
+ val noCustomDelimiter = input.substring(5)
+ return noCustomDelimiter
+ }
+
+ private fun splitDelimiter(): List<String> {
+ val numbers = input.split(COMMA.value, CLONE.value)
+ return numbers
+ }
+
+ private fun splitCustomDelimiter(noCustomDelimiter: String, customDelimiter: String): List<String> {
+ val numbers = noCustomDelimiter.split(COMMA.value, CLONE.value, customDelimiter)
+ return numbers
+ }
+}
\ No newline at end of file | Kotlin | ์ 5๋ผ๋ ์์๋ ์ด๋ฆ์ ๋ถํ์ฃผ๋๊ฑด ์ด๋จ๊น์ ? |
@@ -0,0 +1,45 @@
+package calculator.controller.domain
+
+import calculator.constants.Delimiter.CLONE
+import calculator.constants.Delimiter.COMMA
+import calculator.constants.Delimiter.CUSTOM_DELIMITER_PREFIX
+import calculator.constants.Delimiter.CUSTOM_DELIMITER_SUFFIX
+
+class DelimiterController(
+ private val input: String
+) {
+ fun checkDelimiter(): List<String> {
+ if (hasCustomDelimiter()) {
+ val customDelimiter = getCustomDelimiter()
+ val noCustomDelimiter = deleteCustomDelimiter()
+ val numbers = splitCustomDelimiter(noCustomDelimiter, customDelimiter)
+ return numbers
+ }
+ val numbers = splitDelimiter()
+ return numbers
+ }
+
+ private fun hasCustomDelimiter(): Boolean {
+ return input.startsWith(CUSTOM_DELIMITER_PREFIX.value) && input.indexOf(CUSTOM_DELIMITER_SUFFIX.value) == 3
+ }
+
+ private fun getCustomDelimiter(): String {
+ val customDelimiter = input.substring(2, 3)
+ return customDelimiter
+ }
+
+ private fun deleteCustomDelimiter(): String {
+ val noCustomDelimiter = input.substring(5)
+ return noCustomDelimiter
+ }
+
+ private fun splitDelimiter(): List<String> {
+ val numbers = input.split(COMMA.value, CLONE.value)
+ return numbers
+ }
+
+ private fun splitCustomDelimiter(noCustomDelimiter: String, customDelimiter: String): List<String> {
+ val numbers = noCustomDelimiter.split(COMMA.value, CLONE.value, customDelimiter)
+ return numbers
+ }
+}
\ No newline at end of file | Kotlin | ํน์ ์ฌ๊ธฐ์ 3์ด ์๋ฏธํ๋๊ฒ ๋ญ์ง ๊ถ๊ธํ๋ค์..! |
@@ -0,0 +1,35 @@
+package calculator.controller.validation
+
+class UserInputValidator {
+ fun validateUserInput(numbers: List<String>): List<Int> {
+ val newNumbers = checkIsEmpty(numbers)
+ checkIsInteger(newNumbers)
+ val allNumbers = changeInteger(newNumbers)
+ changeNegativeNumber(allNumbers)
+ return allNumbers
+ }
+
+ private fun checkIsEmpty(numbers: List<String>): List<String> {
+ return numbers.map { it.ifEmpty { "0" } }
+ }
+
+ private fun checkIsInteger(newNumbers: List<String>) {
+ newNumbers.map {
+ if (it.toIntOrNull() == null) {
+ throw IllegalArgumentException(UserInputErrorType.NOT_INTEGER.errorMessage)
+ }
+ }
+ }
+
+ private fun changeInteger(newNumbers: List<String>): List<Int> {
+ return newNumbers.map { it.toInt() }
+ }
+
+ private fun changeNegativeNumber(allNumbers: List<Int>) {
+ allNumbers.forEach {
+ if (it < 0) {
+ throw IllegalArgumentException(UserInputErrorType.NEGATIVE_NUMBER.errorMessage)
+ }
+ }
+ }
+}
\ No newline at end of file | Kotlin | check๋ฅผ ํ๊ณ ์๋ก์ด ์ซ์๋ค์ ๋ฐํํด๋ณผ ์๊ฐ์ ๋ชปํ๋๋ฐ, ์ ๋ ์จ๋ด์ผ๊ฒ ์ต๋๋คใ
ใ
๊ทธ๋ฐ๋ฐ ์๋ก์ด ์ซ์๋ค์ ๋ฐํํ๋ค๋ฉด ๋ฐ ํจ์์ฒ๋ผ ์ด๋ฆ์ change๋ก ํด๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋น |
@@ -0,0 +1,45 @@
+package calculator.controller.domain
+
+import calculator.constants.Delimiter.CLONE
+import calculator.constants.Delimiter.COMMA
+import calculator.constants.Delimiter.CUSTOM_DELIMITER_PREFIX
+import calculator.constants.Delimiter.CUSTOM_DELIMITER_SUFFIX
+
+class DelimiterController(
+ private val input: String
+) {
+ fun checkDelimiter(): List<String> {
+ if (hasCustomDelimiter()) {
+ val customDelimiter = getCustomDelimiter()
+ val noCustomDelimiter = deleteCustomDelimiter()
+ val numbers = splitCustomDelimiter(noCustomDelimiter, customDelimiter)
+ return numbers
+ }
+ val numbers = splitDelimiter()
+ return numbers
+ }
+
+ private fun hasCustomDelimiter(): Boolean {
+ return input.startsWith(CUSTOM_DELIMITER_PREFIX.value) && input.indexOf(CUSTOM_DELIMITER_SUFFIX.value) == 3
+ }
+
+ private fun getCustomDelimiter(): String {
+ val customDelimiter = input.substring(2, 3)
+ return customDelimiter
+ }
+
+ private fun deleteCustomDelimiter(): String {
+ val noCustomDelimiter = input.substring(5)
+ return noCustomDelimiter
+ }
+
+ private fun splitDelimiter(): List<String> {
+ val numbers = input.split(COMMA.value, CLONE.value)
+ return numbers
+ }
+
+ private fun splitCustomDelimiter(noCustomDelimiter: String, customDelimiter: String): List<String> {
+ val numbers = noCustomDelimiter.split(COMMA.value, CLONE.value, customDelimiter)
+ return numbers
+ }
+}
\ No newline at end of file | Kotlin | ์ค ์๋์ง ์๋์ง ํ์ธํ๊ณ , ๊ฒฐ๊ณผ๋ number๋ก ํต์ผํ๋ ๋ฐฉ๋ฒ ๋ฐฐ์๊ฐ๋๋ค! |
@@ -0,0 +1,35 @@
+package calculator.controller.validation
+
+class UserInputValidator {
+ fun validateUserInput(numbers: List<String>): List<Int> {
+ val newNumbers = checkIsEmpty(numbers)
+ checkIsInteger(newNumbers)
+ val allNumbers = changeInteger(newNumbers)
+ changeNegativeNumber(allNumbers)
+ return allNumbers
+ }
+
+ private fun checkIsEmpty(numbers: List<String>): List<String> {
+ return numbers.map { it.ifEmpty { "0" } }
+ }
+
+ private fun checkIsInteger(newNumbers: List<String>) {
+ newNumbers.map {
+ if (it.toIntOrNull() == null) {
+ throw IllegalArgumentException(UserInputErrorType.NOT_INTEGER.errorMessage)
+ }
+ }
+ }
+
+ private fun changeInteger(newNumbers: List<String>): List<Int> {
+ return newNumbers.map { it.toInt() }
+ }
+
+ private fun changeNegativeNumber(allNumbers: List<Int>) {
+ allNumbers.forEach {
+ if (it < 0) {
+ throw IllegalArgumentException(UserInputErrorType.NEGATIVE_NUMBER.errorMessage)
+ }
+ }
+ }
+}
\ No newline at end of file | Kotlin | ์...! any!! ์ข์ ํจ์ ์๋ ค์ค์ ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,45 @@
+package calculator.controller.domain
+
+import calculator.constants.Delimiter.CLONE
+import calculator.constants.Delimiter.COMMA
+import calculator.constants.Delimiter.CUSTOM_DELIMITER_PREFIX
+import calculator.constants.Delimiter.CUSTOM_DELIMITER_SUFFIX
+
+class DelimiterController(
+ private val input: String
+) {
+ fun checkDelimiter(): List<String> {
+ if (hasCustomDelimiter()) {
+ val customDelimiter = getCustomDelimiter()
+ val noCustomDelimiter = deleteCustomDelimiter()
+ val numbers = splitCustomDelimiter(noCustomDelimiter, customDelimiter)
+ return numbers
+ }
+ val numbers = splitDelimiter()
+ return numbers
+ }
+
+ private fun hasCustomDelimiter(): Boolean {
+ return input.startsWith(CUSTOM_DELIMITER_PREFIX.value) && input.indexOf(CUSTOM_DELIMITER_SUFFIX.value) == 3
+ }
+
+ private fun getCustomDelimiter(): String {
+ val customDelimiter = input.substring(2, 3)
+ return customDelimiter
+ }
+
+ private fun deleteCustomDelimiter(): String {
+ val noCustomDelimiter = input.substring(5)
+ return noCustomDelimiter
+ }
+
+ private fun splitDelimiter(): List<String> {
+ val numbers = input.split(COMMA.value, CLONE.value)
+ return numbers
+ }
+
+ private fun splitCustomDelimiter(noCustomDelimiter: String, customDelimiter: String): List<String> {
+ val numbers = noCustomDelimiter.split(COMMA.value, CLONE.value, customDelimiter)
+ return numbers
+ }
+}
\ No newline at end of file | Kotlin | ์ ๋ต์
๋๋ค. ์ผ๋ถ๋ฌ ๊ตฌํ ์ํ์ต๋๋ค! ์ ๋ ๋ฌธ์ ํด์ํ๋ฉด์ ๊ตฌ๋ถ์๋ ํ๊ธ์๋ง ์์ผํ๋ค๋ผ๊ณ ์๊ฐ์ ํด์ ์์ ๊ฐ์ด ์
๋ ฅํ๋ฉด ์๋ฌ๋ผ๊ณ ํ๋จํ์ต๋๋ค! ๋ฌธ์ ํด์์ด ์ ์ผ ์ด๋ ค์ด ๊ฑฐ ๊ฐ์์ ใ
ใ
|
@@ -0,0 +1,45 @@
+package calculator.controller.domain
+
+import calculator.constants.Delimiter.CLONE
+import calculator.constants.Delimiter.COMMA
+import calculator.constants.Delimiter.CUSTOM_DELIMITER_PREFIX
+import calculator.constants.Delimiter.CUSTOM_DELIMITER_SUFFIX
+
+class DelimiterController(
+ private val input: String
+) {
+ fun checkDelimiter(): List<String> {
+ if (hasCustomDelimiter()) {
+ val customDelimiter = getCustomDelimiter()
+ val noCustomDelimiter = deleteCustomDelimiter()
+ val numbers = splitCustomDelimiter(noCustomDelimiter, customDelimiter)
+ return numbers
+ }
+ val numbers = splitDelimiter()
+ return numbers
+ }
+
+ private fun hasCustomDelimiter(): Boolean {
+ return input.startsWith(CUSTOM_DELIMITER_PREFIX.value) && input.indexOf(CUSTOM_DELIMITER_SUFFIX.value) == 3
+ }
+
+ private fun getCustomDelimiter(): String {
+ val customDelimiter = input.substring(2, 3)
+ return customDelimiter
+ }
+
+ private fun deleteCustomDelimiter(): String {
+ val noCustomDelimiter = input.substring(5)
+ return noCustomDelimiter
+ }
+
+ private fun splitDelimiter(): List<String> {
+ val numbers = input.split(COMMA.value, CLONE.value)
+ return numbers
+ }
+
+ private fun splitCustomDelimiter(noCustomDelimiter: String, customDelimiter: String): List<String> {
+ val numbers = noCustomDelimiter.split(COMMA.value, CLONE.value, customDelimiter)
+ return numbers
+ }
+}
\ No newline at end of file | Kotlin | CUSTOM_DELIMITER_SUFFIX์ index๊ฐ 3์ด๋ฉด CUSTOM_DELIMITER_PREFIX์ CUSTOM_DELIMITER_SUFFIX ์ฌ์ด์ ์ปค์คํ
๊ตฌ๋ถ์๋ฅผ ์
๋ ฅ์ ํ๋ค๊ณ ํ๋จ์ ํ์ต๋๋ค! |
@@ -0,0 +1,35 @@
+package calculator.controller.validation
+
+class UserInputValidator {
+ fun validateUserInput(numbers: List<String>): List<Int> {
+ val newNumbers = checkIsEmpty(numbers)
+ checkIsInteger(newNumbers)
+ val allNumbers = changeInteger(newNumbers)
+ changeNegativeNumber(allNumbers)
+ return allNumbers
+ }
+
+ private fun checkIsEmpty(numbers: List<String>): List<String> {
+ return numbers.map { it.ifEmpty { "0" } }
+ }
+
+ private fun checkIsInteger(newNumbers: List<String>) {
+ newNumbers.map {
+ if (it.toIntOrNull() == null) {
+ throw IllegalArgumentException(UserInputErrorType.NOT_INTEGER.errorMessage)
+ }
+ }
+ }
+
+ private fun changeInteger(newNumbers: List<String>): List<Int> {
+ return newNumbers.map { it.toInt() }
+ }
+
+ private fun changeNegativeNumber(allNumbers: List<Int>) {
+ allNumbers.forEach {
+ if (it < 0) {
+ throw IllegalArgumentException(UserInputErrorType.NEGATIVE_NUMBER.errorMessage)
+ }
+ }
+ }
+}
\ No newline at end of file | Kotlin | ์ ๋ง๋ค์! ๊ทธ๋ผ ํจ์๋ช
์ด ๋ ํต์ผ์ฑ์ด ์์ด์ ์ข์๊ฑฐ ๊ฐ์์! ์ข์ ์๊ฒฌ ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,108 @@
+package store.contoller;
+
+import store.Utils;
+import store.model.*;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.time.LocalDate;
+import java.util.*;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+
+public class StoreController {
+ private static final Map<String, Product> productMap = new LinkedHashMap<>();
+ private static final StockManager stockManager = new StockManager();
+ private static final MembershipDiscount membershipDiscount = new MembershipDiscount();
+ private static final LocalDate today = LocalDate.from(DateTimes.now());
+
+ public StoreController() {
+ ProductLoader.initProducts(productMap);
+ }
+
+ public void run() {
+ while (true) {
+ try {
+ handleCustomerInteraction();
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ continue;
+ }
+ if (!InputView.askRetry()) {
+ break;
+ }
+ }
+ }
+
+ private void handleCustomerInteraction() {
+ OutputView.welcomeStore();
+ printProducts();
+ Receipt receipt = purchaseItems();
+ receipt.print();
+ }
+
+ public void printProducts() {
+ productMap.values().forEach(System.out::println);
+ }
+
+ public static Receipt purchaseItems() {
+ String item = readItemInput();
+ List<PurchaseItem> purchaseItems = processItemInput(item);
+ return processItems(purchaseItems);
+ }
+
+ private static String readItemInput() {
+ return InputView.readItem();
+ }
+
+ private static List<PurchaseItem> processItemInput(String item) {
+ String cleanedItem = Utils.removeBrackets(item);
+ return Utils.parseItems(cleanedItem);
+ }
+
+ public static Receipt processItems(List<PurchaseItem> purchaseItems) {
+ Map<String, PurchaseItem> purchase = new LinkedHashMap<>();
+ Map<String, PurchaseItem> freeItems = new LinkedHashMap<>();
+ int totalPrice = 0;
+ int nonPromotionTotalPrice = 0;
+
+ for (PurchaseItem purchaseItem : purchaseItems) {
+ Product product = productMap.get(purchaseItem.getName());
+ stockManager.validateStock(purchaseItem, product);
+ int purchaseTotalPrice = processItem(purchaseItem, product, freeItems);
+ nonPromotionTotalPrice += getNonPromotionTotalPrice(product, purchaseTotalPrice);
+ totalPrice += purchaseTotalPrice;
+ purchase.put(purchaseItem.getName(), new PurchaseItem(purchaseItem.getName(), purchaseItem.getQuantity(), purchaseTotalPrice));
+ }
+
+ int membershipDiscountPrice = membershipDiscount.applyMembershipDiscount(nonPromotionTotalPrice);
+ return new Receipt(purchase, freeItems, membershipDiscountPrice, totalPrice);
+ }
+
+ private static int processItem(PurchaseItem purchaseItem, Product product, Map<String, PurchaseItem> freeItems) {
+ int purchaseTotalPrice;
+ Promotion promotion = product.getPromotion();
+
+ if (isPromotionAvailable(promotion, product)) {
+ PromotionHandler promotionHandler = new PromotionHandler(product, purchaseItem);
+ purchaseTotalPrice = promotionHandler.applyPromotion();
+ freeItems.putAll(promotionHandler.getFreeItems());
+ return purchaseTotalPrice;
+ }
+
+ NonPromotionHandler nonPromotionHandler = new NonPromotionHandler(product, purchaseItem);
+ purchaseTotalPrice = nonPromotionHandler.handleNonPromotion();
+ return purchaseTotalPrice;
+ }
+
+ private static boolean isPromotionAvailable(Promotion promotion, Product product) {
+ return promotion != Promotion.NULL && promotion.isAvailable(today) && product.getPromotionQuantity() > 0;
+ }
+
+ private static int getNonPromotionTotalPrice(Product product, int purchaseTotalPrice) {
+ if (isPromotionAvailable(product.getPromotion(), product)) {
+ return 0;
+ }
+ return purchaseTotalPrice;
+ }
+} | Java | ์ํ๋ค์ ์ถ๋ ฅํ๋ ๋ก์ง์ OutputView ์์ ํ์ผ๋ฉด ์ด๋จ๊น ์ถ์ด์!!! |
@@ -0,0 +1,17 @@
+package store.model;
+
+import store.view.InputView;
+
+public class MembershipDiscount {
+ public int applyMembershipDiscount(int totalNonPromotionPrice) {
+ if (InputView.askMemberShip()) {
+ return calculateMembershipDiscount(totalNonPromotionPrice);
+ }
+ return 0;
+ }
+
+ public int calculateMembershipDiscount(int totalAmount) {
+ int membershipDiscount = (int) (totalAmount * 0.3);
+ return Math.min(membershipDiscount, 8000);
+ }
+}
\ No newline at end of file | Java | ๋ฉค๋ฒ์ญ ํ ์ธ ๋น์จ์ ์์๋ก ๋ฝ์ผ๋ฉด ์ด๋จ๊น ์ถ์ต๋๋ค!!! |
@@ -0,0 +1,17 @@
+package store.model;
+
+import store.view.InputView;
+
+public class MembershipDiscount {
+ public int applyMembershipDiscount(int totalNonPromotionPrice) {
+ if (InputView.askMemberShip()) {
+ return calculateMembershipDiscount(totalNonPromotionPrice);
+ }
+ return 0;
+ }
+
+ public int calculateMembershipDiscount(int totalAmount) {
+ int membershipDiscount = (int) (totalAmount * 0.3);
+ return Math.min(membershipDiscount, 8000);
+ }
+}
\ No newline at end of file | Java | ์ ๋ ์ด๋ ๊ฒ ํ ๊ฑธ ๊ทธ๋ฌ์ต๋๋ค!! ์ ๋ฐฐ์ฐ๊ณ ๊ฐ๋๋ค!!!! |
@@ -0,0 +1,81 @@
+package store.model;
+
+import store.message.ViewMessage;
+
+import java.text.NumberFormat;
+import java.util.Locale;
+
+public class Product {
+ private final String name;
+ private final int price;
+ private int quantity;
+ private int promotionQuantity;
+ private final Promotion promotion;
+
+ public Product(String name, int price, int quantity, String promotion) {
+ this.name = name;
+ this.price = price;
+ this.quantity = quantity;
+ this.promotion = Promotion.fromString(promotion);
+ }
+
+ // getter ๋ฐ setter
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public Promotion getPromotion() {
+ return promotion;
+ }
+
+ public int getPromotionQuantity() {
+ return promotionQuantity;
+ }
+
+ public int getTotalQuantity() {
+ return quantity + promotionQuantity;
+ }
+
+ public void setQuantity(int quantity) {
+ this.quantity = quantity;
+ }
+
+ public void setPromotionQuantity(int promotionQuantity) {
+ this.promotionQuantity = promotionQuantity;
+ }
+
+
+ public String formatPrice() {
+ NumberFormat currencyFormat = NumberFormat.getInstance(Locale.KOREA);
+ return currencyFormat.format(price);
+ }
+
+ @Override
+ public String toString() {
+ if (quantity > 0 && promotion != Promotion.NULL) {
+ return ViewMessage.PROMOTION_WITH_STOCK
+ .format(name, formatPrice(), promotionQuantity, promotion.getName(),
+ name, formatPrice(), quantity, Promotion.NULL.getName());
+ }
+ if (promotion == Promotion.NULL) {
+ return ViewMessage.NO_PROMOTION
+ .format(name, formatPrice(), quantity, Promotion.NULL.getName());
+ }
+ if (quantity == 0 && promotionQuantity == 0) {
+ return ViewMessage.OUT_OF_STOCK_WITH_PROMOTION
+ .format(name, formatPrice(), promotion.getName(),
+ name, formatPrice(), Promotion.NULL.getName());
+ }
+ return ViewMessage.PROMOTION_ONLY_OUT_OF_STOCK
+ .format(name, formatPrice(), promotionQuantity, promotion.getName(),
+ name, formatPrice(), Promotion.NULL.getName());
+ }
+} | Java | ์ฌ๊ณ ์๋์ ๋ณ๋์ setter ๋์ ์๋ ์ฆ๊ฐ์ `increaseQuantity()` ์ฌ๊ณ ๊ฐ์์ 'decreaseQuantiy()` ์ด๋ฐ์์ผ๋ก ์๋ฏธ๋ฅผ ๋ถ์ฌํ๋ ๋ฉ์๋๋ฅผ ๋ง๋ค๋ฉด ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค!!! |
@@ -0,0 +1,69 @@
+package store.model;
+
+import store.message.ReceiptMessage;
+import store.view.OutputView;
+
+import java.text.NumberFormat;
+import java.util.Locale;
+import java.util.Map;
+
+public class Receipt {
+ private final Map<String, PurchaseItem> purchase;
+ private final Map<String, PurchaseItem> freeItems;
+ private final int membershipDiscountPrice;
+ private int totalAmount;
+ private int totalPromotionDiscount;
+ private int totalPurchasePrice;
+
+ public Receipt(Map<String, PurchaseItem> purchase, Map<String, PurchaseItem> freeItems,
+ int membershipDiscountPrice, int totalAmount) {
+ this.purchase = purchase;
+ this.freeItems = freeItems;
+ this.membershipDiscountPrice = membershipDiscountPrice;
+ this.totalAmount = totalAmount;
+ this.totalPromotionDiscount = 0;
+ this.totalPurchasePrice = 0;
+
+ }
+
+ public void print() {
+ NumberFormat currencyFormat = NumberFormat.getInstance(Locale.KOREA);
+
+ OutputView.printStore();
+
+ totalPurchasePrice = purchaseItems(currencyFormat, totalPurchasePrice);
+ totalPromotionDiscount = freeItems(totalPromotionDiscount);
+
+ OutputView.printLine();
+
+ printPriceDetails(currencyFormat);
+ }
+
+ private int purchaseItems(NumberFormat currencyFormat, int totalPurchasePrice) {
+ for (PurchaseItem purchaseItem : purchase.values()) {
+ totalPurchasePrice += purchaseItem.getPrice();
+ OutputView.printProductFormat(purchaseItem, currencyFormat);
+ }
+ return totalPurchasePrice;
+ }
+
+ private int freeItems(int totalPromotionDiscount) {
+ OutputView.printFreeItem();
+ for (PurchaseItem freeItem : freeItems.values()) {
+ totalPromotionDiscount += freeItem.getQuantity() * freeItem.getPrice();
+ if (freeItem.getQuantity() > 0) {
+ OutputView.printFreeProductFormat(freeItem);
+ }
+ }
+ return totalPromotionDiscount;
+ }
+
+ private void printPriceDetails(NumberFormat currencyFormat) {
+ totalAmount -= totalPromotionDiscount;
+ totalAmount -= membershipDiscountPrice;
+ OutputView.printTotalAmount(totalPurchasePrice,currencyFormat);
+ OutputView.printPromotionDiscount(totalPromotionDiscount,currencyFormat);
+ OutputView.printMembershipDiscount(membershipDiscountPrice,currencyFormat);
+ OutputView.printFinalAmount(totalAmount,currencyFormat);
+ }
+} | Java | MVC ํจํด์ ๋ํ ๋ด์ฉ์ ์ดํด๋ณด๋ฉด ๋ชจ๋ธ์ ๋ทฐ๋ ์ปจํธ๋กค๋ฌ๋ฅผ ์์กดํ๋ฉด ์๋๋ค๊ณ ๋์ด ์๋ ๊ธ์ ๋ณด์์ต๋๋ค!! Recipt ์ ๋ํ ์ ๋ณด๋ฅผ DTO ๋ก ๋ง๋ ๋ค ์ปจํธ๋กค๋ฌ์ ๋๊ฒจ ์ปจํธ๋กค๋ฌ๊ฐ OutputView๋ก ์์์ฆ์ ๋ํ ๋ด์ฉ์ ๋๊ฒผ์ผ๋ฉด ์ด๋จ๊น ์ถ์ต๋๋ค!! |
@@ -0,0 +1,34 @@
+package store.model;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+class MembershipTest {
+ private MembershipDiscount membershipDiscount;
+
+ @BeforeEach
+ void setUp() {
+ membershipDiscount = new MembershipDiscount();
+ }
+
+ @Test
+ void applyMembershipDiscount_WithMembership_ReturnsDiscountedAmount() {
+ int totalNonPromotionPrice = 20000;
+ int expectedDiscount = 6000;
+
+ int result = membershipDiscount.calculateMembershipDiscount(totalNonPromotionPrice);
+
+ assertEquals(expectedDiscount, result);
+ }
+
+ @Test
+ void applyMembershipDiscount_WithMembership_CapsAt8000() {
+ int totalNonPromotionPrice = 50000;
+ int expectedDiscount = 8000;
+
+ int result = membershipDiscount.calculateMembershipDiscount(totalNonPromotionPrice);
+
+ assertEquals(expectedDiscount, result);
+ }
+} | Java | ํ
์คํธ ์ฝ๋์ ๋ํ ๋ง์ ๊ณ ๋ฏผ์ด ๋ณด์ด๋ ๊ฒ ๊ฐ์ต๋๋ค!!! ์ ๋ง ๊ณ ์ํ์
จ์ต๋๋ค!!!! |
@@ -0,0 +1,61 @@
+name: Solution-friend Dev CI/CD
+
+on:
+ pull_request:
+ types: [ closed ]
+ workflow_dispatch: # (2).์๋ ์คํ๋ ๊ฐ๋ฅํ๋๋ก
+
+jobs:
+ build:
+ runs-on: ubuntu-latest # (3).OSํ๊ฒฝ
+ if: github.event.pull_request.merged == true && github.event.pull_request.base.ref == 'develop'
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v2 # (4).์ฝ๋ check out
+
+ - name: Set up JDK 11
+ uses: actions/setup-java@v3
+ with:
+ java-version: 11 # (5).์๋ฐ ์ค์น
+ distribution: 'adopt'
+
+ - name: Grant execute permission for gradlew
+ run: chmod +x ./gradlew
+ shell: bash # (6).๊ถํ ๋ถ์ฌ
+
+ - name: Build with Gradle
+ run: ./gradlew clean build -x test
+ shell: bash # (7).build์์
+
+ - name: Get current time
+ uses: 1466587594/get-current-time@v2
+ id: current-time
+ with:
+ format: YYYY-MM-DDTHH-mm-ss
+ utcOffset: "+09:00" # (8).build์์ ์ ์๊ฐํ๋ณด
+
+ - name: Show Current Time
+ run: echo "CurrentTime=$"
+ shell: bash # (9).ํ๋ณดํ ์๊ฐ ๋ณด์ฌ์ฃผ๊ธฐ
+
+ - name: Generate deployment package
+ run: |
+ mkdir -p deploy
+ cp build/libs/*.jar deploy/application.jar
+ cp Procfile deploy/Procfile
+ cp -r .ebextensions-dev deploy/.ebextensions
+ cp -r .platform deploy/.platform
+ cd deploy && zip -r deploy.zip .
+
+ - name: Beanstalk Deploy
+ uses: einaregilsson/beanstalk-deploy@v20
+ with:
+ aws_access_key: ${{ secrets.AWS_ACTION_ACCESS_KEY_ID }}
+ aws_secret_key: ${{ secrets.AWS_ACTION_SECRET_ACCESS_KEY }}
+ application_name: solution-friend-dev
+ environment_name: Solution-friend-dev-env-1
+ version_label: github-action-${{ steps.current-time.outputs.formattedTime }}
+ region: ap-northeast-2
+ deployment_package: deploy/deploy.zip
+ wait_for_deployment: false | Unknown | PR์ด ๊ธฐ๊ฐ๋์ด๋ ํด๋น Action์ด ์ํ๋ ๊ฒ ๊ฐ๋ค์. |
@@ -0,0 +1,62 @@
+plugins {
+ id 'java'
+ id 'org.springframework.boot' version '2.7.17'
+ id 'io.spring.dependency-management' version '1.0.15.RELEASE'
+}
+
+group = 'friend'
+version = '0.0.1-SNAPSHOT'
+
+java {
+ sourceCompatibility = '11'
+}
+
+configurations {
+ compileOnly {
+ extendsFrom annotationProcessor
+ }
+}
+
+repositories {
+ mavenCentral()
+}
+
+dependencies {
+ implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
+ implementation 'org.springframework.boot:spring-boot-starter-web'
+ compileOnly 'org.projectlombok:lombok'
+ runtimeOnly 'com.mysql:mysql-connector-j'
+ annotationProcessor 'org.projectlombok:lombok'
+ implementation 'org.springframework.boot:spring-boot-starter-validation'
+ testImplementation 'org.springframework.boot:spring-boot-starter-test'
+ implementation 'org.springdoc:springdoc-openapi-ui:1.6.15'
+ implementation 'io.springfox:springfox-swagger2:2.9.2'
+ implementation 'io.springfox:springfox-swagger-ui:2.9.2'
+
+ //user
+ implementation 'com.google.code.findbugs:jsr305:3.0.2'
+ //mail
+ implementation group: 'com.sun.mail', name: 'javax.mail', version: '1.6.2'
+ //jwt
+ implementation 'org.springframework.boot:spring-boot-starter-security'
+ implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.4'
+ runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.4'
+ runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.4'
+// redis
+ implementation 'org.springframework.boot:spring-boot-starter-data-redis'
+ //kakao
+// implementation 'org.springframework.boot:spring-boot-starter-webflux'
+ // S3
+ implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'
+ implementation platform('software.amazon.awssdk:bom:2.20.56')
+ implementation 'software.amazon.awssdk:s3'
+
+}
+
+tasks.named('test') {
+ useJUnitPlatform()
+}
+
+jar {
+ enabled = false
+} | Unknown | gradle ํ์์ ํต์ผํด ์ฃผ์ธ์.
`com.sun.mail:javax.mail:1.6.2`
๋ํ, sun ์์กด์ฑ์ ๋งค์ฐ ์๋ ์์กด์ฑ์ ๊ฐ๋ฅ์ฑ์ด ๋์ต๋๋ค. ํ์ธ์ด ํ์ํฉ๋๋ค. |
@@ -0,0 +1,27 @@
+package friend.spring;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
+import org.springframework.scheduling.annotation.EnableScheduling;
+
+import javax.annotation.PostConstruct;
+import java.time.LocalDateTime;
+import java.util.TimeZone;
+
+@SpringBootApplication
+@EnableJpaAuditing
+@EnableScheduling
+public class Application {
+
+ @PostConstruct
+ public void started() {
+ TimeZone.setDefault(TimeZone.getTimeZone("Asia/Seoul"));
+ }
+
+ public static void main(String[] args) {
+ SpringApplication.run(Application.class, args);
+ System.out.println("ํ์ฌ์๊ฐ " + LocalDateTime.now());
+ }
+
+} | Java | System out ๋ณด๋ค๋ log ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ก ์ถ๋ ฅํ๋๋ก ์ค์ ํด ์ฃผ์ธ์. |
@@ -0,0 +1,15 @@
+package friend.spring.OAuth;
+
+import lombok.Data;
+
+@Data
+public class OAuthToken {
+
+ private String access_token;
+ private String token_type;
+ private String refresh_token;
+ private String id_token;
+ private int expires_in;
+ private String scope;
+ private int refresh_token_expires_in;
+} | Java | `@Data` ๋ ์ต๋ํ ์ฌ์ฉํ์ง ๋ง์ธ์.
์๋ํ์ง ์์ ๊ฒฐ๊ณผ๊ฐ ๋์ฌ ์ ์์ต๋๋ค.
ํ์ํ ํ๋์ ๋ฐ๋ผ ์ ์ ํ๊ฒ ํ์ํ ์ด๋
ธํ
์ด์
๋ง ์ฌ์ฉํ๋๋ก ํด ์ฃผ์ธ์. |
@@ -0,0 +1,15 @@
+package friend.spring.OAuth;
+
+import lombok.Data;
+
+@Data
+public class OAuthToken {
+
+ private String access_token;
+ private String token_type;
+ private String refresh_token;
+ private String id_token;
+ private int expires_in;
+ private String scope;
+ private int refresh_token_expires_in;
+} | Java | Java์์๋ ๊ฐ๋ฅํ๋ฉด underscore๋ฅผ ์ฌ์ฉํ์ง ์๋๋ก ํด ์ฃผ์ธ์. (์บ๋ฉ ์ผ์ด์ค ๊ถ์ฅ)
- ์ฐธ๊ณ : https://google.github.io/styleguide/javaguide.html
- ์ฐธ๊ณ 2: https://naver.github.io/hackday-conventions-java/
+ ๊ฐ๋ฅํ๋ฉด checkstyle ๋ฑ์ ๋๊ตฌ๋ฅผ ์ฌ์ฉํด์ ์ฝ๋ ์คํ์ผ์ ์ ์ํ๊ณ , ํด๋น ์คํ์ผ์ ๋ง์ถ๊ฒ ์ฝ๋ ํํ๋ฅผ ๊ฐ์ ํ๋ ๊ฒ ์ข์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,104 @@
+package friend.spring.OAuth.provider;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import friend.spring.apiPayload.GeneralException;
+import friend.spring.apiPayload.code.status.ErrorStatus;
+import friend.spring.OAuth.KakaoProfile;
+import friend.spring.OAuth.OAuthToken;
+import friend.spring.security.PrincipalDetailService;
+import org.springframework.beans.factory.annotation.Value;
+import friend.spring.repository.UserRepository;
+import friend.spring.security.JwtTokenProvider;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Component;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
+import org.springframework.web.client.RestTemplate;
+
+@Component
+@RequiredArgsConstructor
+public class KakaoAuthProvider {
+
+ private final PrincipalDetailService principalDetailService;
+ private final UserRepository userRepository;
+ private final JwtTokenProvider jwtTokenProvider;
+
+ @Value("${kakao.auth.client}")
+ private String client;
+
+ @Value("${kakao.auth.redirect_uri}")
+ private String redirect;
+
+ @Value("${kakao.auth.secret_key}")
+ private String secretKey;
+
+ // code๋ก access ํ ํฐ ์์ฒญํ๊ธฐ
+ public OAuthToken requestToken(String code) {
+ RestTemplate restTemplate = new RestTemplate();
+ HttpHeaders headers = new HttpHeaders();
+
+ headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
+
+ MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
+ params.add("grant_type", "authorization_code");
+ params.add("client_id", client);
+ params.add("redirect_uri", redirect);
+ params.add("secret_key", secretKey);
+ params.add("code", code);
+
+ HttpEntity<MultiValueMap<String, String>> kakaoTokenRequest =
+ new HttpEntity<>(params, headers);
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(
+ "https://kauth.kakao.com/oauth/token",
+ HttpMethod.POST,
+ kakaoTokenRequest,
+ String.class);
+
+ ObjectMapper objectMapper = new ObjectMapper();
+
+ OAuthToken oAuthToken = null;
+
+ try {
+ oAuthToken = objectMapper.readValue(response.getBody(), OAuthToken.class);
+ } catch (JsonProcessingException e) {
+ throw new GeneralException(ErrorStatus.INVALID_REQUEST_INFO);
+ }
+
+ return oAuthToken;
+ }
+
+ // Token์ผ๋ก ์ ๋ณด ์์ฒญํ๊ธฐ
+ public KakaoProfile requestKakaoProfile(String token) {
+ RestTemplate restTemplate = new RestTemplate();
+ HttpHeaders headers = new HttpHeaders();
+ headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
+ headers.add("Authorization", "Bearer " + token);
+
+ HttpEntity<MultiValueMap<String, String>> kakaoProfileRequest = new HttpEntity<>(headers);
+
+ ResponseEntity<String> response =
+ restTemplate.exchange(
+ "https://kapi.kakao.com/v2/user/me",
+ HttpMethod.POST,
+ kakaoProfileRequest,
+ String.class);
+
+ ObjectMapper objectMapper = new ObjectMapper();
+ KakaoProfile kakaoProfile = null;
+
+ try {
+ kakaoProfile = objectMapper.readValue(response.getBody(), KakaoProfile.class);
+ } catch (JsonProcessingException e) {
+ throw new GeneralException(ErrorStatus.INVALID_REQUEST_INFO);
+ }
+
+ return kakaoProfile;
+ }
+} | Java | ์ด์ฐจํผ ํ ๋ฒ ๋ง๋ค๋ฉด ์ฌ์ฌ์ฉ์ด ๊ฐ๋ฅํ๋๊น...
- Spring์ ๊ธฐ๋ณธ์ผ๋ก ๋ฑ๋ก๋ ObjectMapper Bean์ ์ฌ์ฉํ๊ฑฐ๋ (private final ํ๋)
- ํด๋์ค ์๋จ๋ถ์ new ๋ก ํ๋ ๋ง๋ค์ด ์ฃผ์ธ์. |
@@ -0,0 +1,120 @@
+package friend.spring.apiPayload;
+
+import friend.spring.apiPayload.code.ErrorReasonDTO;
+import friend.spring.apiPayload.code.status.ErrorStatus;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseStatus;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+import org.springframework.web.context.request.ServletWebRequest;
+import org.springframework.web.context.request.WebRequest;
+import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.validation.ConstraintViolationException;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Optional;
+
+@Slf4j
+@RestControllerAdvice(annotations = {RestController.class})
+public class ExceptionAdvice extends ResponseEntityExceptionHandler {
+
+
+ @org.springframework.web.bind.annotation.ExceptionHandler
+ public ResponseEntity<Object> validation(ConstraintViolationException e, WebRequest request) {
+ String errorMessage = e.getConstraintViolations().stream()
+ .map(constraintViolation -> constraintViolation.getMessage())
+ .findFirst()
+ .orElseThrow(() -> new RuntimeException("ConstraintViolationException ์ถ์ถ ๋์ค ์๋ฌ ๋ฐ์"));
+
+ return handleExceptionInternalConstraint(e, ErrorStatus.valueOf(errorMessage), HttpHeaders.EMPTY, request);
+ }
+
+
+ @Override
+ public ResponseEntity<Object> handleMethodArgumentNotValid(
+ MethodArgumentNotValidException e, HttpHeaders headers, HttpStatus status, WebRequest request) {
+
+ Map<String, String> errors = new LinkedHashMap<>();
+
+ e.getBindingResult().getFieldErrors().stream()
+ .forEach(fieldError -> {
+ String fieldName = fieldError.getField();
+ String errorMessage = Optional.ofNullable(fieldError.getDefaultMessage()).orElse("");
+ errors.merge(fieldName, errorMessage, (existingErrorMessage, newErrorMessage) -> existingErrorMessage + ", " + newErrorMessage);
+ });
+
+ return handleExceptionInternalArgs(e, HttpHeaders.EMPTY, ErrorStatus.valueOf("_BAD_REQUEST"), request, errors);
+ }
+
+ @org.springframework.web.bind.annotation.ExceptionHandler
+ public ResponseEntity<Object> exception(Exception e, WebRequest request) {
+ e.printStackTrace();
+
+ return handleExceptionInternalFalse(e, ErrorStatus._INTERNAL_SERVER_ERROR, HttpHeaders.EMPTY, ErrorStatus._INTERNAL_SERVER_ERROR.getHttpStatus(), request, e.getMessage());
+ }
+
+ @ExceptionHandler(value = GeneralException.class)
+ public ResponseEntity onThrowException(GeneralException generalException, HttpServletRequest request) {
+ ErrorReasonDTO errorReasonHttpStatus = generalException.getErrorReasonHttpStatus();
+ return handleExceptionInternal(generalException, errorReasonHttpStatus, null, request);
+ }
+
+ private ResponseEntity<Object> handleExceptionInternal(Exception e, ErrorReasonDTO reason,
+ HttpHeaders headers, HttpServletRequest request) {
+
+ ApiResponse<Object> body = ApiResponse.onFailure(reason.getCode(), reason.getMessage(), null);
+// e.printStackTrace();
+
+ WebRequest webRequest = new ServletWebRequest(request);
+ return super.handleExceptionInternal(
+ e,
+ body,
+ headers,
+ reason.getHttpStatus(),
+ webRequest
+ );
+ }
+
+ private ResponseEntity<Object> handleExceptionInternalFalse(Exception e, ErrorStatus errorCommonStatus,
+ HttpHeaders headers, HttpStatus status, WebRequest request, String errorPoint) {
+ ApiResponse<Object> body = ApiResponse.onFailure(errorCommonStatus.getCode(), errorCommonStatus.getMessage(), errorPoint);
+ return super.handleExceptionInternal(
+ e,
+ body,
+ headers,
+ status,
+ request
+ );
+ }
+
+ private ResponseEntity<Object> handleExceptionInternalArgs(Exception e, HttpHeaders headers, ErrorStatus errorCommonStatus,
+ WebRequest request, Map<String, String> errorArgs) {
+ ApiResponse<Object> body = ApiResponse.onFailure(errorCommonStatus.getCode(), errorCommonStatus.getMessage(), errorArgs);
+ return super.handleExceptionInternal(
+ e,
+ body,
+ headers,
+ errorCommonStatus.getHttpStatus(),
+ request
+ );
+ }
+
+ private ResponseEntity<Object> handleExceptionInternalConstraint(Exception e, ErrorStatus errorCommonStatus,
+ HttpHeaders headers, WebRequest request) {
+ ApiResponse<Object> body = ApiResponse.onFailure(errorCommonStatus.getCode(), errorCommonStatus.getMessage(), null);
+ return super.handleExceptionInternal(
+ e,
+ body,
+ headers,
+ errorCommonStatus.getHttpStatus(),
+ request
+ );
+ }
+}
\ No newline at end of file | Java | - ๋ฉ์์ง ์ ๊ฑฐ (์ฌ์ : ์ด์ฐจํผ trace ์ฐ์ผ๋ฉด ์ด๋์ ํฐ์ก๋์ง ๋ค ๋์ต๋๋ค.)
- ๊ฐ๋ฅํ๋ฉด RuntimeException ๋ณด๋ค๋ ์ข ๋ ๊ตฌ์ฒดํ ๋ ์์ธ๋ฅผ ์ฌ์ฉํ๋ฉด ์ข๊ฒ ์ต๋๋ค. |
@@ -0,0 +1,109 @@
+package friend.spring.apiPayload.code.status;
+
+import friend.spring.apiPayload.code.BaseErrorCode;
+import friend.spring.apiPayload.code.ErrorReasonDTO;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import org.springframework.http.HttpStatus;
+
+@Getter
+@AllArgsConstructor
+public enum ErrorStatus implements BaseErrorCode {
+
+ // ๊ฐ์ฅ ์ผ๋ฐ์ ์ธ ์๋ต
+ _INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "COMMON5000", "์๋ฒ ์๋ฌ, ๊ด๋ฆฌ์์๊ฒ ๋ฌธ์ ๋ฐ๋๋๋ค."),
+ _BAD_REQUEST(HttpStatus.BAD_REQUEST, "COMMON4000", "์๋ชป๋ ์์ฒญ์
๋๋ค."),
+ _UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "COMMON4001", "์ธ์ฆ์ด ํ์ํฉ๋๋ค."),
+ _FORBIDDEN(HttpStatus.FORBIDDEN, "COMMON4003", "๊ธ์ง๋ ์์ฒญ์
๋๋ค."),
+
+ // ๋ฉค๋ฒ ๊ด๋ จ ์๋ต
+ USER_NOT_FOUND(HttpStatus.NOT_FOUND, "USER4001", "ํ์์ ๋ณด๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค."),
+ USERS_NOT_FOUND_EMAIL(HttpStatus.NOT_FOUND, "USER4010", "๊ฐ์
๊ฐ๋ฅํ ์ด๋ฉ์ผ์
๋๋ค."),
+ USER_EXISTS_EMAIL(HttpStatus.NOT_ACCEPTABLE, "USER4002", "์ด๋ฏธ ์กด์ฌํ๋ ๋ฉ์ผ ์ฃผ์์
๋๋ค"),
+ UNABLE_TO_SEND_EMAIL(HttpStatus.BAD_REQUEST, "USER4003", "์ด๋ฉ์ผ์ ๋ฐ์กํ์ง ๋ชปํ์ต๋๋ค."),
+ ERR_MAKE_CODE(HttpStatus.BAD_REQUEST, "USER4004", "์ธ์ฆ ์ฝ๋ ์์ฑ์ ์ค๋ฅ๊ฐ ์์ต๋๋ค."),
+ INCORRECT_CODE(HttpStatus.UNAUTHORIZED, "USER4005", "์ธ์ฆ ์ฝ๋๊ฐ ์ผ์นํ์ง ์์ต๋๋ค."),
+ EMPTY_JWT(HttpStatus.BAD_REQUEST, "USER4006", "JWT๋ฅผ ์
๋ ฅํด์ฃผ์ธ์."),
+ INVALID_JWT(HttpStatus.UNAUTHORIZED, "USER4007", "์ ํจํ์ง ์์ JWT์
๋๋ค."),
+ INVALID_PASSWORD_FORMAT(HttpStatus.NOT_ACCEPTABLE, "USER4077", "๋น๋ฐ๋ฒํธ ํ์์ ๋ง์ง ์์ต๋๋ค."),
+ PASSWORD_INCORRECT(HttpStatus.NOT_FOUND, "USER4008", "๋น๋ฐ๋ฒํธ๊ฐ ํ๋ ธ์ต๋๋ค."),
+ PASSWORD_CHECK_INCORRECT(HttpStatus.NOT_FOUND, "USER4009", "ํ์ธ ๋น๋ฐ๋ฒํธ๊ฐ ์ผ์นํ์ง ์์ต๋๋ค."),
+ RTK_INCORREXT(HttpStatus.UNAUTHORIZED, "USER4100", "RefreshToken๊ฐ์ ํ์ธํด์ฃผ์ธ์."),
+ NOT_ADMIN(HttpStatus.BAD_REQUEST, "USER4101", "๊ด๋ฆฌ์๊ฐ ์๋๋๋ค."),
+
+ // Auth ๊ด๋ จ
+ AUTH_EXPIRED_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_4101", "ํ ํฐ์ด ๋ง๋ฃ๋์์ต๋๋ค."),
+ AUTH_INVALID_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_4102", "ํ ํฐ์ด ์ ํจํ์ง ์์ต๋๋ค."),
+ INVALID_LOGIN_REQUEST(HttpStatus.UNAUTHORIZED, "AUTH_4103", "์ฌ๋ฐ๋ฅธ ์ด๋ฉ์ผ์ด๋ ํจ์ค์๋๊ฐ ์๋๋๋ค."),
+ INVALID_REQUEST_INFO(HttpStatus.UNAUTHORIZED, "AUTH_4106", "์นด์นด์ค ์ ๋ณด ๋ถ๋ฌ์ค๊ธฐ์ ์คํจํ์์ต๋๋ค."),
+ NOT_EQUAL_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_4107", "๋ฆฌํ๋ ์ ํ ํฐ์ด ๋ค๋ฆ
๋๋ค."),
+ NOT_CONTAIN_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_4108", "ํด๋นํ๋ ํ ํฐ์ด ์ ์ฅ๋์ด์์ง ์์ต๋๋ค."),
+
+ // ๊ธ ๊ด๋ จ ์๋ต
+ POST_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4001", "๊ธ์ ์ฐพ์ ์ ์์ต๋๋ค."),
+ POST_NOT_CORRECT_USER(HttpStatus.BAD_REQUEST, "POST4002", "์ฌ๋ฐ๋ฅธ ์ฌ์ฉ์(๊ธ ์์ฑ์)๊ฐ ์๋๋๋ค."),
+ POST_LIKE_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4003", "๊ธ์ ๋ํ ์ข์์ ๋ฐ์ดํฐ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."),
+ POST_CATGORY_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4004", "์นดํ
๊ณ ๋ฆฌ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."),
+ POST_SAVED_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4005", "์ ์ฅํ ๊ธ์ด ์์ต๋๋ค."),
+ POST_SCRAP_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4004", "๊ธ์ ๋ํ ์คํฌ๋ฉ ๋ฐ์ดํฐ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."),
+ POST_GENERAL_POLL_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4005", "๊ธ์ ๋ํ ์ผ๋ฐ ํฌํ ๋ฐ์ดํฐ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."),
+ POST_CARD_POLL_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4006", "๊ธ์ ๋ํ ์นด๋ ํฌํ ๋ฐ์ดํฐ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."),
+ TITLE_TEXT_LIMIT(HttpStatus.BAD_REQUEST, "POST4007", "์ต์ 5์ ์ด์, 30์ ๋ฏธ๋ง ์
๋ ฅํด ์ฃผ์ธ์"),
+ CONTENT_TEXT_LIMIT(HttpStatus.BAD_REQUEST, "POST4008", "์ต์ 5์ ์ด์, 1000์ ๋ฏธ๋ง ์
๋ ฅํด ์ฃผ์ธ์"),
+ CANDIDATE_TEXT_LIMIT(HttpStatus.BAD_REQUEST, "POST4009", "์ต์ 1์ ์ด์, 30์ ๋ฏธ๋ง ์
๋ ฅํด ์ฃผ์ธ์"),
+ DEADLINE_LIMIT(HttpStatus.BAD_REQUEST, "POST4010", "์ต์ 1๋ถ~์ต๋30์ผ๋ก ์
๋ ฅํด ์ฃผ์ธ์"),
+ CANDIDATE_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4011", "ํ๋ณด๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค"),
+ TOO_MUCH_FIXED(HttpStatus.NOT_FOUND, "POST4012", "์ด๋ฏธ 2ํ ์ด์ ์์ ํ์ต๋๋ค"),
+ NOT_ENOUGH_POINT(HttpStatus.BAD_REQUEST, "POST4013", "ํด๋น ์ ์ ์ ํฌ์ธํธ๊ฐ ๋ถ์กฑ ํฉ๋๋ค"),
+ POST_LIKE_DUPLICATE(HttpStatus.BAD_REQUEST, "POST4014", "๊ธ์ ๋ํ ์ข์์ ๋ฐ์ดํฐ๊ฐ ์ด๋ฏธ ์กด์ฌํฉ๋๋ค."),
+ POST_SCRAP_DUPLICATE(HttpStatus.BAD_REQUEST, "POST4015", "๊ธ์ ๋ํ ์คํฌ๋ฉ ๋ฐ์ดํฐ๊ฐ ์ด๋ฏธ ์กด์ฌํฉ๋๋ค."),
+ DEADLINE_OVER(HttpStatus.BAD_REQUEST, "POST4016", "ํฌํ ๋ง๊ฐ ์๊ฐ์ด ์ง๋ฌ์ต๋๋ค"),
+ ALREADY_VOTE(HttpStatus.BAD_REQUEST, "POST4017", "์ด๋ฏธ ํฌํ ํ์
จ์ต๋๋ค."),
+// USER_VOTE(HttpStatus.BAD_REQUEST,"POST4017","์์ฑ์๋ ํฌํ๊ฐ ๋ถ๊ฐ๋ฅ ํฉ๋๋ค ํ์
จ์ต๋๋ค."), // ์ด๊ฑฐ ํ์์์ผ๋ฉด ์ง์์ผ ํ ๊ฒ ๊ฐ์ต๋๋ค!
+
+ POST_REPORT_DUPLICATE(HttpStatus.BAD_REQUEST, "POST4018", "์ด ์ ์ ๊ฐ ํด๋น ๊ธ์ ์ ๊ณ ํ ์ ๊ณ ๋ด์ญ ๋ฐ์ดํฐ๊ฐ ์ด๋ฏธ ์กด์ฌํฉ๋๋ค."),
+
+ // ๋๊ธ ๊ด๋ จ ์๋ต
+ COMMENT_NOT_FOUND(HttpStatus.NOT_FOUND, "COMMENT4001", "๋๊ธ์ ์ฐพ์ ์ ์์ต๋๋ค."),
+ COMMENT_LIKE_NOT_FOUND(HttpStatus.NOT_FOUND, "COMMENT4002", "๋๊ธ์ ๋ํ ์ข์์ ๋ฐ์ดํฐ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."),
+ COMMENT_CHOICE_OVER_ONE(HttpStatus.BAD_REQUEST, "COMMENT4003", "๋๊ธ ์ฑํ์ 1๊ฐ ๋๊ธ์ ๋ํด์๋ง ๊ฐ๋ฅํฉ๋๋ค."),
+ COMMENT_SELECT_MYSELF(HttpStatus.BAD_REQUEST, "COMMENT4004", "์๊ธฐ ์์ ์ ์ฑํํ ์ ์์ต๋๋ค."),
+ COMMENT_NOT_CORRECT_USER(HttpStatus.BAD_REQUEST, "COMMENT4005", "์ฌ๋ฐ๋ฅธ ์ฌ์ฉ์(๋๊ธ ์์ฑ์)๊ฐ ์๋๋๋ค."),
+ COMMENT_POST_NOT_MATCH(HttpStatus.BAD_REQUEST, "COMMENT4006", "ํด๋น ๊ธ์ ์์ฑ๋ ๋๊ธ์ด ์๋๋๋ค."),
+ COMMENT_LIKE_DUPLICATE(HttpStatus.BAD_REQUEST, "COMMENT4007", "๋๊ธ์ ๋ํ ์ข์์ ๋ฐ์ดํฐ๊ฐ ์ด๋ฏธ ์กด์ฌํฉ๋๋ค."),
+ COMMENT_REPORT_DUPLICATE(HttpStatus.BAD_REQUEST, "COMMENT4008", "์ด ์ ์ ๊ฐ ํด๋น ๋๊ธ์ ์ ๊ณ ํ ์ ๊ณ ๋ด์ญ ๋ฐ์ดํฐ๊ฐ ์ด๋ฏธ ์กด์ฌํฉ๋๋ค."),
+
+ // ์๋ฆผ ๊ด๋ จ ์๋ต
+ ALARM_NOT_FOUND(HttpStatus.NOT_FOUND, "ALARM4001", "์๋ฆผ์ด ์์ต๋๋ค"),
+
+
+ // ๊ณต์ง์ฌํญ ๊ด๋ จ ์๋ต
+ NOTICE_NOT_FOUND(HttpStatus.NOT_FOUND, "NOTICE4001", "๊ณต์ง์ฌํญ์ด ์์ต๋๋ค.");
+
+ private final HttpStatus httpStatus;
+ private final String code;
+ private final String message;
+
+ @Override
+ public ErrorReasonDTO getReason() {
+ return ErrorReasonDTO.builder()
+ .message(message)
+ .code(code)
+ .isSuccess(false)
+ .build();
+ }
+
+ @Override
+ public ErrorReasonDTO getReasonHttpStatus() {
+ return ErrorReasonDTO.builder()
+ .message(message)
+ .code(code)
+ .isSuccess(false)
+ .httpStatus(httpStatus)
+ .build()
+ ;
+
+
+ }
+}
+ | Java | ์๋ฒ์๋ฌ์ธ๊ฒ ๊ฐ์๋ฐ, 500์ด ๋ซ์ง ์์๊น์? |
@@ -0,0 +1,109 @@
+package friend.spring.apiPayload.code.status;
+
+import friend.spring.apiPayload.code.BaseErrorCode;
+import friend.spring.apiPayload.code.ErrorReasonDTO;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import org.springframework.http.HttpStatus;
+
+@Getter
+@AllArgsConstructor
+public enum ErrorStatus implements BaseErrorCode {
+
+ // ๊ฐ์ฅ ์ผ๋ฐ์ ์ธ ์๋ต
+ _INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "COMMON5000", "์๋ฒ ์๋ฌ, ๊ด๋ฆฌ์์๊ฒ ๋ฌธ์ ๋ฐ๋๋๋ค."),
+ _BAD_REQUEST(HttpStatus.BAD_REQUEST, "COMMON4000", "์๋ชป๋ ์์ฒญ์
๋๋ค."),
+ _UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "COMMON4001", "์ธ์ฆ์ด ํ์ํฉ๋๋ค."),
+ _FORBIDDEN(HttpStatus.FORBIDDEN, "COMMON4003", "๊ธ์ง๋ ์์ฒญ์
๋๋ค."),
+
+ // ๋ฉค๋ฒ ๊ด๋ จ ์๋ต
+ USER_NOT_FOUND(HttpStatus.NOT_FOUND, "USER4001", "ํ์์ ๋ณด๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค."),
+ USERS_NOT_FOUND_EMAIL(HttpStatus.NOT_FOUND, "USER4010", "๊ฐ์
๊ฐ๋ฅํ ์ด๋ฉ์ผ์
๋๋ค."),
+ USER_EXISTS_EMAIL(HttpStatus.NOT_ACCEPTABLE, "USER4002", "์ด๋ฏธ ์กด์ฌํ๋ ๋ฉ์ผ ์ฃผ์์
๋๋ค"),
+ UNABLE_TO_SEND_EMAIL(HttpStatus.BAD_REQUEST, "USER4003", "์ด๋ฉ์ผ์ ๋ฐ์กํ์ง ๋ชปํ์ต๋๋ค."),
+ ERR_MAKE_CODE(HttpStatus.BAD_REQUEST, "USER4004", "์ธ์ฆ ์ฝ๋ ์์ฑ์ ์ค๋ฅ๊ฐ ์์ต๋๋ค."),
+ INCORRECT_CODE(HttpStatus.UNAUTHORIZED, "USER4005", "์ธ์ฆ ์ฝ๋๊ฐ ์ผ์นํ์ง ์์ต๋๋ค."),
+ EMPTY_JWT(HttpStatus.BAD_REQUEST, "USER4006", "JWT๋ฅผ ์
๋ ฅํด์ฃผ์ธ์."),
+ INVALID_JWT(HttpStatus.UNAUTHORIZED, "USER4007", "์ ํจํ์ง ์์ JWT์
๋๋ค."),
+ INVALID_PASSWORD_FORMAT(HttpStatus.NOT_ACCEPTABLE, "USER4077", "๋น๋ฐ๋ฒํธ ํ์์ ๋ง์ง ์์ต๋๋ค."),
+ PASSWORD_INCORRECT(HttpStatus.NOT_FOUND, "USER4008", "๋น๋ฐ๋ฒํธ๊ฐ ํ๋ ธ์ต๋๋ค."),
+ PASSWORD_CHECK_INCORRECT(HttpStatus.NOT_FOUND, "USER4009", "ํ์ธ ๋น๋ฐ๋ฒํธ๊ฐ ์ผ์นํ์ง ์์ต๋๋ค."),
+ RTK_INCORREXT(HttpStatus.UNAUTHORIZED, "USER4100", "RefreshToken๊ฐ์ ํ์ธํด์ฃผ์ธ์."),
+ NOT_ADMIN(HttpStatus.BAD_REQUEST, "USER4101", "๊ด๋ฆฌ์๊ฐ ์๋๋๋ค."),
+
+ // Auth ๊ด๋ จ
+ AUTH_EXPIRED_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_4101", "ํ ํฐ์ด ๋ง๋ฃ๋์์ต๋๋ค."),
+ AUTH_INVALID_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_4102", "ํ ํฐ์ด ์ ํจํ์ง ์์ต๋๋ค."),
+ INVALID_LOGIN_REQUEST(HttpStatus.UNAUTHORIZED, "AUTH_4103", "์ฌ๋ฐ๋ฅธ ์ด๋ฉ์ผ์ด๋ ํจ์ค์๋๊ฐ ์๋๋๋ค."),
+ INVALID_REQUEST_INFO(HttpStatus.UNAUTHORIZED, "AUTH_4106", "์นด์นด์ค ์ ๋ณด ๋ถ๋ฌ์ค๊ธฐ์ ์คํจํ์์ต๋๋ค."),
+ NOT_EQUAL_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_4107", "๋ฆฌํ๋ ์ ํ ํฐ์ด ๋ค๋ฆ
๋๋ค."),
+ NOT_CONTAIN_TOKEN(HttpStatus.UNAUTHORIZED, "AUTH_4108", "ํด๋นํ๋ ํ ํฐ์ด ์ ์ฅ๋์ด์์ง ์์ต๋๋ค."),
+
+ // ๊ธ ๊ด๋ จ ์๋ต
+ POST_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4001", "๊ธ์ ์ฐพ์ ์ ์์ต๋๋ค."),
+ POST_NOT_CORRECT_USER(HttpStatus.BAD_REQUEST, "POST4002", "์ฌ๋ฐ๋ฅธ ์ฌ์ฉ์(๊ธ ์์ฑ์)๊ฐ ์๋๋๋ค."),
+ POST_LIKE_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4003", "๊ธ์ ๋ํ ์ข์์ ๋ฐ์ดํฐ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."),
+ POST_CATGORY_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4004", "์นดํ
๊ณ ๋ฆฌ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."),
+ POST_SAVED_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4005", "์ ์ฅํ ๊ธ์ด ์์ต๋๋ค."),
+ POST_SCRAP_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4004", "๊ธ์ ๋ํ ์คํฌ๋ฉ ๋ฐ์ดํฐ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."),
+ POST_GENERAL_POLL_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4005", "๊ธ์ ๋ํ ์ผ๋ฐ ํฌํ ๋ฐ์ดํฐ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."),
+ POST_CARD_POLL_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4006", "๊ธ์ ๋ํ ์นด๋ ํฌํ ๋ฐ์ดํฐ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."),
+ TITLE_TEXT_LIMIT(HttpStatus.BAD_REQUEST, "POST4007", "์ต์ 5์ ์ด์, 30์ ๋ฏธ๋ง ์
๋ ฅํด ์ฃผ์ธ์"),
+ CONTENT_TEXT_LIMIT(HttpStatus.BAD_REQUEST, "POST4008", "์ต์ 5์ ์ด์, 1000์ ๋ฏธ๋ง ์
๋ ฅํด ์ฃผ์ธ์"),
+ CANDIDATE_TEXT_LIMIT(HttpStatus.BAD_REQUEST, "POST4009", "์ต์ 1์ ์ด์, 30์ ๋ฏธ๋ง ์
๋ ฅํด ์ฃผ์ธ์"),
+ DEADLINE_LIMIT(HttpStatus.BAD_REQUEST, "POST4010", "์ต์ 1๋ถ~์ต๋30์ผ๋ก ์
๋ ฅํด ์ฃผ์ธ์"),
+ CANDIDATE_NOT_FOUND(HttpStatus.NOT_FOUND, "POST4011", "ํ๋ณด๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค"),
+ TOO_MUCH_FIXED(HttpStatus.NOT_FOUND, "POST4012", "์ด๋ฏธ 2ํ ์ด์ ์์ ํ์ต๋๋ค"),
+ NOT_ENOUGH_POINT(HttpStatus.BAD_REQUEST, "POST4013", "ํด๋น ์ ์ ์ ํฌ์ธํธ๊ฐ ๋ถ์กฑ ํฉ๋๋ค"),
+ POST_LIKE_DUPLICATE(HttpStatus.BAD_REQUEST, "POST4014", "๊ธ์ ๋ํ ์ข์์ ๋ฐ์ดํฐ๊ฐ ์ด๋ฏธ ์กด์ฌํฉ๋๋ค."),
+ POST_SCRAP_DUPLICATE(HttpStatus.BAD_REQUEST, "POST4015", "๊ธ์ ๋ํ ์คํฌ๋ฉ ๋ฐ์ดํฐ๊ฐ ์ด๋ฏธ ์กด์ฌํฉ๋๋ค."),
+ DEADLINE_OVER(HttpStatus.BAD_REQUEST, "POST4016", "ํฌํ ๋ง๊ฐ ์๊ฐ์ด ์ง๋ฌ์ต๋๋ค"),
+ ALREADY_VOTE(HttpStatus.BAD_REQUEST, "POST4017", "์ด๋ฏธ ํฌํ ํ์
จ์ต๋๋ค."),
+// USER_VOTE(HttpStatus.BAD_REQUEST,"POST4017","์์ฑ์๋ ํฌํ๊ฐ ๋ถ๊ฐ๋ฅ ํฉ๋๋ค ํ์
จ์ต๋๋ค."), // ์ด๊ฑฐ ํ์์์ผ๋ฉด ์ง์์ผ ํ ๊ฒ ๊ฐ์ต๋๋ค!
+
+ POST_REPORT_DUPLICATE(HttpStatus.BAD_REQUEST, "POST4018", "์ด ์ ์ ๊ฐ ํด๋น ๊ธ์ ์ ๊ณ ํ ์ ๊ณ ๋ด์ญ ๋ฐ์ดํฐ๊ฐ ์ด๋ฏธ ์กด์ฌํฉ๋๋ค."),
+
+ // ๋๊ธ ๊ด๋ จ ์๋ต
+ COMMENT_NOT_FOUND(HttpStatus.NOT_FOUND, "COMMENT4001", "๋๊ธ์ ์ฐพ์ ์ ์์ต๋๋ค."),
+ COMMENT_LIKE_NOT_FOUND(HttpStatus.NOT_FOUND, "COMMENT4002", "๋๊ธ์ ๋ํ ์ข์์ ๋ฐ์ดํฐ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."),
+ COMMENT_CHOICE_OVER_ONE(HttpStatus.BAD_REQUEST, "COMMENT4003", "๋๊ธ ์ฑํ์ 1๊ฐ ๋๊ธ์ ๋ํด์๋ง ๊ฐ๋ฅํฉ๋๋ค."),
+ COMMENT_SELECT_MYSELF(HttpStatus.BAD_REQUEST, "COMMENT4004", "์๊ธฐ ์์ ์ ์ฑํํ ์ ์์ต๋๋ค."),
+ COMMENT_NOT_CORRECT_USER(HttpStatus.BAD_REQUEST, "COMMENT4005", "์ฌ๋ฐ๋ฅธ ์ฌ์ฉ์(๋๊ธ ์์ฑ์)๊ฐ ์๋๋๋ค."),
+ COMMENT_POST_NOT_MATCH(HttpStatus.BAD_REQUEST, "COMMENT4006", "ํด๋น ๊ธ์ ์์ฑ๋ ๋๊ธ์ด ์๋๋๋ค."),
+ COMMENT_LIKE_DUPLICATE(HttpStatus.BAD_REQUEST, "COMMENT4007", "๋๊ธ์ ๋ํ ์ข์์ ๋ฐ์ดํฐ๊ฐ ์ด๋ฏธ ์กด์ฌํฉ๋๋ค."),
+ COMMENT_REPORT_DUPLICATE(HttpStatus.BAD_REQUEST, "COMMENT4008", "์ด ์ ์ ๊ฐ ํด๋น ๋๊ธ์ ์ ๊ณ ํ ์ ๊ณ ๋ด์ญ ๋ฐ์ดํฐ๊ฐ ์ด๋ฏธ ์กด์ฌํฉ๋๋ค."),
+
+ // ์๋ฆผ ๊ด๋ จ ์๋ต
+ ALARM_NOT_FOUND(HttpStatus.NOT_FOUND, "ALARM4001", "์๋ฆผ์ด ์์ต๋๋ค"),
+
+
+ // ๊ณต์ง์ฌํญ ๊ด๋ จ ์๋ต
+ NOTICE_NOT_FOUND(HttpStatus.NOT_FOUND, "NOTICE4001", "๊ณต์ง์ฌํญ์ด ์์ต๋๋ค.");
+
+ private final HttpStatus httpStatus;
+ private final String code;
+ private final String message;
+
+ @Override
+ public ErrorReasonDTO getReason() {
+ return ErrorReasonDTO.builder()
+ .message(message)
+ .code(code)
+ .isSuccess(false)
+ .build();
+ }
+
+ @Override
+ public ErrorReasonDTO getReasonHttpStatus() {
+ return ErrorReasonDTO.builder()
+ .message(message)
+ .code(code)
+ .isSuccess(false)
+ .httpStatus(httpStatus)
+ .build()
+ ;
+
+
+ }
+}
+ | Java | FORBIDDEN์ด ๋์ ๊ฒ ๊ฐ์์. |
@@ -1,83 +1,25 @@
"use client";
import { useRouter } from "next/navigation";
-import { useState, useEffect } from "react";
+import CardWishlist from "./CardWishlist";
import Content from "./Content";
import StatusBadge from "./StatusBadge";
-import Bookmark from "@/assets/images/icons/bookmark.svg";
-import BookmarkActive from "@/assets/images/icons/bookmark_active.svg";
-import SolidButton from "@/components/common/buttons/SolidButton";
-import useChangeWishlist from "@/hooks/useChangeWishlist";
-import useUserStore from "@/store/auth/useUserStore";
-import useUserWishlist from "@/store/wishlist/useUserWishlist";
+import CardReview from "@/components/common/card/CardReview";
import { type CardInfo } from "@/types/card";
-export default function Card({ card }: CardInfo) {
- const { user } = useUserStore();
+const Card = ({ card }: CardInfo) => {
const router = useRouter();
- const { userAllWishlist } = useUserWishlist();
- const [wishlist, setWishlist] = useState<number[]>([]);
- const { loggedInWishlist, nonLoggedInWishlist } = useChangeWishlist();
- const [isComplete, setIsComplete] = useState(true);
-
- const contentData = {
- title: card.title,
- location: card.location,
- participants: card.participants,
- recruitmentStartDate: card.recruitmentStartDate,
- recruitmentEndDate: card.recruitmentEndDate,
- meetingStartDate: card.meetingStartDate,
- meetingEndDate: card.meetingEndDate,
- thumbnail: card.thumbnail,
- };
-
- const handleClickWishlist = (e: React.MouseEvent) => {
- // ๋ถ๋ชจ๋ก ์ด๋ฒคํธ ์ ๋ฌ ๋ง๊ธฐ
- e.stopPropagation();
-
- // ์ด๋ฏธ ์์ฒญ ์ค์ด๋ผ๋ฉด ํจ์ ์ข
๋ฃ
- if (!isComplete) return;
-
- // ๋ก๋ฉ ์ํ๋ก ์ ํ
- setIsComplete(false);
-
- if (user != null) {
- // ๋ก๊ทธ์ธ ์ํ ์ฒ๋ฆฌ
- loggedInWishlist(card.meetupId, card.meetupStatus);
- } else {
- // ๋น๋ก๊ทธ์ธ ์ํ ์ฒ๋ฆฌ
- nonLoggedInWishlist(card.meetupId, card.meetupStatus, setWishlist);
- }
-
- setIsComplete(true);
- };
const handleClickDetail = (type: string, id: number): void => {
const lowerCase = type.toLowerCase();
router.push(`/${lowerCase}/${id}`);
};
- const handleClickReview = (e: React.MouseEvent, meetUpId: number) => {
- e.stopPropagation();
-
- router.push(`/user/create_review?meetupId=${meetUpId}`);
- };
-
- useEffect(() => {
- if (user === null) {
- // user๊ฐ null์ผ ๊ฒฝ์ฐ, localStorage์์ wishlist๋ฅผ ๊ฐ์ ธ์์ ์ํ๋ฅผ ์ค์
- const myWishlist = JSON.parse(localStorage.getItem("wishlist") || "[]");
- setWishlist(myWishlist);
- } else {
- // user๊ฐ ์์ ๊ฒฝ์ฐ, ์ ์ญ ์ํ๊ด๋ฆฌ์ ์ ์ฅ๋ userWishlist ์ํ๋ฅผ ๊ทธ๋๋ก ์ฌ์ฉ
- setWishlist(userAllWishlist);
- }
- }, [user, userAllWishlist]);
-
return (
<div
className='flex cursor-pointer flex-col rounded-[16px] bg-gray-950 p-3'
onClick={() => handleClickDetail(card.meetingType, card.meetupId)}
+ aria-label={`๋ชจ์${card.meetupId} ์ด๋`}
>
<div className='flex justify-between'>
<div className='flex gap-1.5'>
@@ -91,38 +33,34 @@ export default function Card({ card }: CardInfo) {
/>
</div>
- {!card.isMypage && (
- <button onClick={(e) => handleClickWishlist(e)}>
- {card.meetupStatus === "RECRUITING" ? (
- user != null ? (
- userAllWishlist.includes(card.meetupId) ? (
- <BookmarkActive className='size-6 text-orange-200' />
- ) : (
- <Bookmark className='size-6' />
- )
- ) : wishlist.includes(card.meetupId) ? (
- <BookmarkActive className='size-6 text-orange-200' />
- ) : (
- <Bookmark className='size-6' />
- )
- ) : (
- <Bookmark className='size-6' />
- )}
- </button>
- )}
+ <CardWishlist
+ wishlistInfo={{
+ meetupId: card.meetupId,
+ meetupStatus: card.meetupStatus,
+ isMypage: card.isMypage,
+ }}
+ />
</div>
- <Content content={contentData} />
+ <Content
+ content={{
+ title: card.title,
+ location: card.location,
+ participants: card.participants,
+ recruitmentStartDate: card.recruitmentStartDate,
+ recruitmentEndDate: card.recruitmentEndDate,
+ meetingStartDate: card.meetingStartDate,
+ meetingEndDate: card.meetingEndDate,
+ thumbnail: card.thumbnail,
+ }}
+ />
{/* ๋ฒํผ ์ปดํฌ๋ํธ ๋จธ์ง ํ ์ถ๊ฐ ์์
ํ์ */}
{card.isMypage && card.isReview && card.meetupStatus === "COMPLETED" && (
- <SolidButton
- className='mt-6'
- onClick={(e) => handleClickReview(e, card.meetupId as number)}
- >
- ๋ฆฌ๋ทฐ ์์ฑ
- </SolidButton>
+ <CardReview meetupId={card.meetupId} />
)}
</div>
);
-}
+};
+
+export default Card; | Unknown | ์ ๊ฐ ๋ฆฌ๋ทฐ ์์ฑ ์์
๋ ๊ตฌํํ๋ ๋ถ๋ถ์ด ๋ฐ์์ด ์๋์ด์๋ ๊ฒ ๊ฐ์ต๋๋ค๐ฅน
(์ ๋ ์ต๊ทผ pr๊น์ง ๋ฐ์๋ ์ํ์
๋๋ค!)
ํด๋น ๋ถ๋ถ ๋ฐ์ํด์ฃผ์ค ์ ์์ผ์ค๊น์ ..?
- [๊ด๋ จ commit](https://github.com/Stilllee/mogua-fe/commit/90c016aa0cdf5244f96ac5221a635ae9cbbe8d96)
- [๊ด๋ จ PR](https://github.com/mogua-station/FE/pull/147/files#diff-833efd5f77902c17828e34065e9320e385ac78b7f146499b369d5e4be8fa2284) |
@@ -0,0 +1,21 @@
+import { useRouter } from "next/navigation";
+import SolidButton from "@/components/common/buttons/SolidButton";
+
+export default function CardReview({ meetupId }: { meetupId: number }) {
+ const router = useRouter();
+
+ const handleClickReview = (e: React.MouseEvent, meetUpId: number) => {
+ e.stopPropagation();
+
+ router.push(`/user/create_review?meetupId=${meetUpId}`);
+ };
+
+ return (
+ <SolidButton
+ className='mt-6'
+ onClick={(e) => handleClickReview(e, meetupId as number)}
+ >
+ ๋ฆฌ๋ทฐ ์์ฑ
+ </SolidButton>
+ );
+} | Unknown | ์์์ ์ธ๊ธํ ๋ถ๋ถ์
๋๋ค~ |
@@ -1,83 +1,25 @@
"use client";
import { useRouter } from "next/navigation";
-import { useState, useEffect } from "react";
+import CardWishlist from "./CardWishlist";
import Content from "./Content";
import StatusBadge from "./StatusBadge";
-import Bookmark from "@/assets/images/icons/bookmark.svg";
-import BookmarkActive from "@/assets/images/icons/bookmark_active.svg";
-import SolidButton from "@/components/common/buttons/SolidButton";
-import useChangeWishlist from "@/hooks/useChangeWishlist";
-import useUserStore from "@/store/auth/useUserStore";
-import useUserWishlist from "@/store/wishlist/useUserWishlist";
+import CardReview from "@/components/common/card/CardReview";
import { type CardInfo } from "@/types/card";
-export default function Card({ card }: CardInfo) {
- const { user } = useUserStore();
+const Card = ({ card }: CardInfo) => {
const router = useRouter();
- const { userAllWishlist } = useUserWishlist();
- const [wishlist, setWishlist] = useState<number[]>([]);
- const { loggedInWishlist, nonLoggedInWishlist } = useChangeWishlist();
- const [isComplete, setIsComplete] = useState(true);
-
- const contentData = {
- title: card.title,
- location: card.location,
- participants: card.participants,
- recruitmentStartDate: card.recruitmentStartDate,
- recruitmentEndDate: card.recruitmentEndDate,
- meetingStartDate: card.meetingStartDate,
- meetingEndDate: card.meetingEndDate,
- thumbnail: card.thumbnail,
- };
-
- const handleClickWishlist = (e: React.MouseEvent) => {
- // ๋ถ๋ชจ๋ก ์ด๋ฒคํธ ์ ๋ฌ ๋ง๊ธฐ
- e.stopPropagation();
-
- // ์ด๋ฏธ ์์ฒญ ์ค์ด๋ผ๋ฉด ํจ์ ์ข
๋ฃ
- if (!isComplete) return;
-
- // ๋ก๋ฉ ์ํ๋ก ์ ํ
- setIsComplete(false);
-
- if (user != null) {
- // ๋ก๊ทธ์ธ ์ํ ์ฒ๋ฆฌ
- loggedInWishlist(card.meetupId, card.meetupStatus);
- } else {
- // ๋น๋ก๊ทธ์ธ ์ํ ์ฒ๋ฆฌ
- nonLoggedInWishlist(card.meetupId, card.meetupStatus, setWishlist);
- }
-
- setIsComplete(true);
- };
const handleClickDetail = (type: string, id: number): void => {
const lowerCase = type.toLowerCase();
router.push(`/${lowerCase}/${id}`);
};
- const handleClickReview = (e: React.MouseEvent, meetUpId: number) => {
- e.stopPropagation();
-
- router.push(`/user/create_review?meetupId=${meetUpId}`);
- };
-
- useEffect(() => {
- if (user === null) {
- // user๊ฐ null์ผ ๊ฒฝ์ฐ, localStorage์์ wishlist๋ฅผ ๊ฐ์ ธ์์ ์ํ๋ฅผ ์ค์
- const myWishlist = JSON.parse(localStorage.getItem("wishlist") || "[]");
- setWishlist(myWishlist);
- } else {
- // user๊ฐ ์์ ๊ฒฝ์ฐ, ์ ์ญ ์ํ๊ด๋ฆฌ์ ์ ์ฅ๋ userWishlist ์ํ๋ฅผ ๊ทธ๋๋ก ์ฌ์ฉ
- setWishlist(userAllWishlist);
- }
- }, [user, userAllWishlist]);
-
return (
<div
className='flex cursor-pointer flex-col rounded-[16px] bg-gray-950 p-3'
onClick={() => handleClickDetail(card.meetingType, card.meetupId)}
+ aria-label={`๋ชจ์${card.meetupId} ์ด๋`}
>
<div className='flex justify-between'>
<div className='flex gap-1.5'>
@@ -91,38 +33,34 @@ export default function Card({ card }: CardInfo) {
/>
</div>
- {!card.isMypage && (
- <button onClick={(e) => handleClickWishlist(e)}>
- {card.meetupStatus === "RECRUITING" ? (
- user != null ? (
- userAllWishlist.includes(card.meetupId) ? (
- <BookmarkActive className='size-6 text-orange-200' />
- ) : (
- <Bookmark className='size-6' />
- )
- ) : wishlist.includes(card.meetupId) ? (
- <BookmarkActive className='size-6 text-orange-200' />
- ) : (
- <Bookmark className='size-6' />
- )
- ) : (
- <Bookmark className='size-6' />
- )}
- </button>
- )}
+ <CardWishlist
+ wishlistInfo={{
+ meetupId: card.meetupId,
+ meetupStatus: card.meetupStatus,
+ isMypage: card.isMypage,
+ }}
+ />
</div>
- <Content content={contentData} />
+ <Content
+ content={{
+ title: card.title,
+ location: card.location,
+ participants: card.participants,
+ recruitmentStartDate: card.recruitmentStartDate,
+ recruitmentEndDate: card.recruitmentEndDate,
+ meetingStartDate: card.meetingStartDate,
+ meetingEndDate: card.meetingEndDate,
+ thumbnail: card.thumbnail,
+ }}
+ />
{/* ๋ฒํผ ์ปดํฌ๋ํธ ๋จธ์ง ํ ์ถ๊ฐ ์์
ํ์ */}
{card.isMypage && card.isReview && card.meetupStatus === "COMPLETED" && (
- <SolidButton
- className='mt-6'
- onClick={(e) => handleClickReview(e, card.meetupId as number)}
- >
- ๋ฆฌ๋ทฐ ์์ฑ
- </SolidButton>
+ <CardReview meetupId={card.meetupId} />
)}
</div>
);
-}
+};
+
+export default Card; | Unknown | ์ ์๊ฒ ์ต๋๋ค! Develop์ ๋จธ์ง ๋์ด์๋๊ฑด๊ฐ์? |
@@ -1,83 +1,25 @@
"use client";
import { useRouter } from "next/navigation";
-import { useState, useEffect } from "react";
+import CardWishlist from "./CardWishlist";
import Content from "./Content";
import StatusBadge from "./StatusBadge";
-import Bookmark from "@/assets/images/icons/bookmark.svg";
-import BookmarkActive from "@/assets/images/icons/bookmark_active.svg";
-import SolidButton from "@/components/common/buttons/SolidButton";
-import useChangeWishlist from "@/hooks/useChangeWishlist";
-import useUserStore from "@/store/auth/useUserStore";
-import useUserWishlist from "@/store/wishlist/useUserWishlist";
+import CardReview from "@/components/common/card/CardReview";
import { type CardInfo } from "@/types/card";
-export default function Card({ card }: CardInfo) {
- const { user } = useUserStore();
+const Card = ({ card }: CardInfo) => {
const router = useRouter();
- const { userAllWishlist } = useUserWishlist();
- const [wishlist, setWishlist] = useState<number[]>([]);
- const { loggedInWishlist, nonLoggedInWishlist } = useChangeWishlist();
- const [isComplete, setIsComplete] = useState(true);
-
- const contentData = {
- title: card.title,
- location: card.location,
- participants: card.participants,
- recruitmentStartDate: card.recruitmentStartDate,
- recruitmentEndDate: card.recruitmentEndDate,
- meetingStartDate: card.meetingStartDate,
- meetingEndDate: card.meetingEndDate,
- thumbnail: card.thumbnail,
- };
-
- const handleClickWishlist = (e: React.MouseEvent) => {
- // ๋ถ๋ชจ๋ก ์ด๋ฒคํธ ์ ๋ฌ ๋ง๊ธฐ
- e.stopPropagation();
-
- // ์ด๋ฏธ ์์ฒญ ์ค์ด๋ผ๋ฉด ํจ์ ์ข
๋ฃ
- if (!isComplete) return;
-
- // ๋ก๋ฉ ์ํ๋ก ์ ํ
- setIsComplete(false);
-
- if (user != null) {
- // ๋ก๊ทธ์ธ ์ํ ์ฒ๋ฆฌ
- loggedInWishlist(card.meetupId, card.meetupStatus);
- } else {
- // ๋น๋ก๊ทธ์ธ ์ํ ์ฒ๋ฆฌ
- nonLoggedInWishlist(card.meetupId, card.meetupStatus, setWishlist);
- }
-
- setIsComplete(true);
- };
const handleClickDetail = (type: string, id: number): void => {
const lowerCase = type.toLowerCase();
router.push(`/${lowerCase}/${id}`);
};
- const handleClickReview = (e: React.MouseEvent, meetUpId: number) => {
- e.stopPropagation();
-
- router.push(`/user/create_review?meetupId=${meetUpId}`);
- };
-
- useEffect(() => {
- if (user === null) {
- // user๊ฐ null์ผ ๊ฒฝ์ฐ, localStorage์์ wishlist๋ฅผ ๊ฐ์ ธ์์ ์ํ๋ฅผ ์ค์
- const myWishlist = JSON.parse(localStorage.getItem("wishlist") || "[]");
- setWishlist(myWishlist);
- } else {
- // user๊ฐ ์์ ๊ฒฝ์ฐ, ์ ์ญ ์ํ๊ด๋ฆฌ์ ์ ์ฅ๋ userWishlist ์ํ๋ฅผ ๊ทธ๋๋ก ์ฌ์ฉ
- setWishlist(userAllWishlist);
- }
- }, [user, userAllWishlist]);
-
return (
<div
className='flex cursor-pointer flex-col rounded-[16px] bg-gray-950 p-3'
onClick={() => handleClickDetail(card.meetingType, card.meetupId)}
+ aria-label={`๋ชจ์${card.meetupId} ์ด๋`}
>
<div className='flex justify-between'>
<div className='flex gap-1.5'>
@@ -91,38 +33,34 @@ export default function Card({ card }: CardInfo) {
/>
</div>
- {!card.isMypage && (
- <button onClick={(e) => handleClickWishlist(e)}>
- {card.meetupStatus === "RECRUITING" ? (
- user != null ? (
- userAllWishlist.includes(card.meetupId) ? (
- <BookmarkActive className='size-6 text-orange-200' />
- ) : (
- <Bookmark className='size-6' />
- )
- ) : wishlist.includes(card.meetupId) ? (
- <BookmarkActive className='size-6 text-orange-200' />
- ) : (
- <Bookmark className='size-6' />
- )
- ) : (
- <Bookmark className='size-6' />
- )}
- </button>
- )}
+ <CardWishlist
+ wishlistInfo={{
+ meetupId: card.meetupId,
+ meetupStatus: card.meetupStatus,
+ isMypage: card.isMypage,
+ }}
+ />
</div>
- <Content content={contentData} />
+ <Content
+ content={{
+ title: card.title,
+ location: card.location,
+ participants: card.participants,
+ recruitmentStartDate: card.recruitmentStartDate,
+ recruitmentEndDate: card.recruitmentEndDate,
+ meetingStartDate: card.meetingStartDate,
+ meetingEndDate: card.meetingEndDate,
+ thumbnail: card.thumbnail,
+ }}
+ />
{/* ๋ฒํผ ์ปดํฌ๋ํธ ๋จธ์ง ํ ์ถ๊ฐ ์์
ํ์ */}
{card.isMypage && card.isReview && card.meetupStatus === "COMPLETED" && (
- <SolidButton
- className='mt-6'
- onClick={(e) => handleClickReview(e, card.meetupId as number)}
- >
- ๋ฆฌ๋ทฐ ์์ฑ
- </SolidButton>
+ <CardReview meetupId={card.meetupId} />
)}
</div>
);
-}
+};
+
+export default Card; | Unknown | 
๋ค๋ต ๋จธ์ง ๋์ด์๋ ๋ถ๋ถ์
๋๋น |
@@ -1,7 +1,17 @@
package store;
+import store.controller.StoreController;
+import store.global.util.FileUtil;
+import store.view.InputView;
+import store.view.OutputView;
+
public class Application {
public static void main(String[] args) {
- // TODO: ํ๋ก๊ทธ๋จ ๊ตฌํ
+ FileUtil fileInputView = new FileUtil();
+ StoreController storeController = new StoreController(
+ new OutputView(),
+ new InputView(fileInputView)
+ );
+ storeController.run();
}
} | Java | FileUtil ์ด๋ผ๋ ์๋ช
์ด ์ง๊ด์ ์ด์ด์ ์ข๋ค์! ์ ๋ StoreInitializer๋ก ํ๋๋ฐ ๋ญ๊ฐ ์ ์๋ฟ์์ ์์ฌ์ ์ด์ |
@@ -1 +1,325 @@
-# java-convenience-store-precourse
+# ํธ์์ ๐ช
+
+## ๊ธฐ๋ฅ ๊ตฌํ ๋ชฉ๋ก
+
+### โ
ํ์ผ ์ฝ๊ธฐ ๊ธฐ๋ฅ
+- [x] ํ์ผ ๋ด์ฉ์ ์
๋ ฅ ๋ฐ์ ๋ฆฌ์คํธ๋ก ๋ฐํํ๋ค
+ - `products.md`, `promotions.md` ํ์ผ ์
๋ ฅ
+ - ๋ด์ฉ `(,)` ์ผํ๋ก ๊ตฌ๋ถ
+ - ์ ์ฒด ๋ด์ฉ ๋ถ๋ฆฌ ํ ๋ฆฌ์คํธ๋ก ๋ฐํ
+- [x] `์์ธ์ฒ๋ฆฌ` ์ผ์นํ๋ ํ์ผ๋ช
์ด ์์ ๊ฒฝ์ฐ ์์ธ๊ฐ ๋ฐ์ํ๋ค
+- [x] `์์ธ์ฒ๋ฆฌ` ํ์ผ์์ ๋ด์ฉ์ด ์์ ๊ฒฝ์ฐ ์์ธ๊ฐ ๋ฐ์ํ๋ค
+- [x] `์์ธ์ฒ๋ฆฌ` ๋ถ๋ฆฌํ ๋ฐฐ์ด ์์๊ฐ ๊ณต๋ฐฑ์ผ ๊ฒฝ์ฐ ์์ธ๊ฐ ๋ฐ์ํ๋ค
+
+---
+### โ
์ํ ๋ฑ๋ก ๊ธฐ๋ฅ
+- [x] ์ํ ์ ๋ณด ๋ฆฌ์คํธ๋ก ์ํ์ ๋ฑ๋กํ๋ค
+- [x] ์ ์ฒด ์ํ ์ ๋ณด ๋ฆฌ์คํธ๋ก ์ฌ๋ฌ ์ํ์ ๋ฑ๋กํ๋ค
+- [x] ํ๋ก๋ชจ์
์ด ์กด์ฌํ ๊ฒฝ์ฐ ๊ธฐ๋ณธ ์ํ๋ ๋ฑ๋ก๋๋ค
+- [x] ํ๋ก๋ชจ์
null ์ผ ๋ ๋น๊ฐ์ ๋ฑ๋กํ๋ค
+- [x] `์์ธ์ฒ๋ฆฌ` ์ํ ์ ๋ณด ๋ฆฌ์คํธ ํฌ๊ธฐ๊ฐ 4๊ฐ ์๋ ๊ฒฝ์ฐ ์์ธ๊ฐ ๋ฐ์ํ๋ค
+- [x] `์์ธ์ฒ๋ฆฌ` ๋ฑ๋ก ๊ฐ๊ฒฉ์ด ์ซ์๊ฐ ์๋ ๊ฒฝ์ฐ ์์ธ๊ฐ ๋ฐ์ํ๋ค
+- [x] `์์ธ์ฒ๋ฆฌ` ๋ฑ๋ก ๊ฐ๊ฒฉ์ด ์ต์๋ณด๋ค ์์ ๊ฒฝ์ฐ ์์ธ๊ฐ ๋ฐ์ํ๋ค `์ต์ : 0`
+- [x] `์์ธ์ฒ๋ฆฌ` ๋ฑ๋ก ๊ฐ๊ฒฉ์ด ์ต๋๋ณด๋ค ํด ๊ฒฝ์ฐ ์์ธ๊ฐ ๋ฐ์ํ๋ค `์ต๋ : 1,000,000`
+- [x] `์์ธ์ฒ๋ฆฌ` ๋ฑ๋ก ์๋์ด ์ซ์๊ฐ ์๋ ๊ฒฝ์ฐ ์์ธ๊ฐ ๋ฐ์ํ๋ค
+- [x] `์์ธ์ฒ๋ฆฌ` ๋ฑ๋ก ์๋์ด ์ต์๋ณด๋ค ์์ ๊ฒฝ์ฐ ์์ธ๊ฐ ๋ฐ์ํ๋ค `์ต์ : 1`
+- [x] `์์ธ์ฒ๋ฆฌ` ๋ฑ๋ก ์๋์ด ์ต๋๋ณด๋ค ํด ๊ฒฝ์ฐ ์์ธ๊ฐ ๋ฐ์ํ๋ค `์ต๋ : 1,000,000`
+
+---
+### โ
์ํ ๋ชฉ๋ก ์ถ๋ ฅ ๊ธฐ๋ฅ
+- [x] ์ด๋ฆ ๊ฐ์ฒด์ ์ ๋ณด๋ฅผ ๋ฐํํ๋ค `ex) ์ฝ๋ผ`
+- [x] ๊ฐ๊ฒฉ ๊ฐ์ฒด์ ์ ๋ณด๋ฅผ ๋ฐํํ๋ค `ex) 1,000์`
+- [x] ์๋ ๊ฐ์ฒด์ ์ ๋ณด๋ฅผ ๋ฐํํ๋ค `ex) 1๊ฐ, 1,000๊ฐ, ์ฌ๊ณ ์์`
+ - [x] ์๋์ด 0๊ฐ์ผ ๊ฒฝ์ฐ `์ฌ๊ณ ์์`์ ๋ฐํํ๋ค
+- [x] ํ๋ก๋ชจ์
๊ฐ์ฒด์ ์ ๋ณด๋ฅผ ๋ฐํํ๋ค `ex) MD์ถ์ฒ์ํ`
+- [x] ๋จ์ผ ์ํ์ ์ ๋ณด๋ฅผ ๋ฐํํ๋ค `ex) ์ฝ๋ผ, 1,000์, 1๊ฐ, MD์ถ์ฒ์ํ`
+- [x] ์ ์ฒด ์ํ์ ์ ๋ณด๋ฅผ ๋ฐํํ๋ค `ex) [์ฝ๋ผ, 1,000์ ...] [์ฌ์ด๋ค, 1,200์ ...]`
+- [x] ์ ์ฒด ์ํ์ ์ ๋ณด๋ฅผ ์ถ๋ ฅํ๋ค `ex) - ์ฝ๋ผ 1,000์ 10๊ฐ ํ์ฐ2+1`
+
+---
+### โ
๋ฌผํ ์ฐพ๊ธฐ ๊ธฐ๋ฅ
+- [x] ์ด๋ฆ์ด ๊ฐ์ ๊ฒฝ์ฐ ์ํ์ ๋ฐํํ๋ค
+- [x] ๋ชฉ๋ก์ ์ด๋ฆ์ด ๊ฐ์ ์ํ์ ์ฐพ๋๋ค
+- [x] ๊ตฌ๋งคํ ์ํ์ ์ด๋ฆ๊ณผ ์๋์ ๊ตฌ๋ถํ๋ค `ex) [์ฌ์ด๋ค-2],[๊ฐ์์นฉ-1]`
+ - ์๋ `(-)` ํ์ดํ ๊ตฌ๋ถ
+ - ์ํ์ `([])` ๋๊ดํธ๋ก ๋ฌถ์ธ `(,)` ๊ตฌ๋ถ
+- [x] ๊ตฌ๋งคํ ์ํ์ด ์ค๋ณต๋ ์ ์๋์ ํฉ์ฐํ๋ค `ex) [์ฌ์ด๋ค-2],[์ฌ์ด๋ค-1]`
+- [x] ๊ตฌ๋งคํ ์ํ์ ๋์ผํ ๋ชจ๋ ์ํ์ ์ฐพ๋๋ค
+- [x] `์์ธ์ฒ๋ฆฌ` ์ํ์ด ์กด์ฌํ์ง ์์ ๊ฒฝ์ฐ ์์ธ๊ฐ ๋ฐ์ํ๋ค
+- [x] `์์ธ์ฒ๋ฆฌ` ๊ตฌ๋งคํ ์ํ์ ํ์์ด ์ฌ๋ฐ๋ฅด์ง ์์ ๊ฒฝ์ฐ ์์ธ๊ฐ ๋ฐ์ํ๋ค `ex) [์ฌ์ด๋ค-ํ๊ฐ] [์ฌ์ด๋ค-2 ์ด 15๊ฐ์ง ์ผ์ด์ค`
+- [x] `์์ธ์ฒ๋ฆฌ` ๊ตฌ๋งคํ ์ํ์ ์๋์ด ๋ฒ์์ ๋ฒ์ด๋ ๊ฒฝ์ฐ ์์ธ๊ฐ ๋ฐ์ํ๋ค `์ต์ : 1`, `์ต๋ : 1,000,000`
+
+---
+### โ
๊ณ์ฐ ๊ธฐ๋ฅ
+- [x] ์ํ๋ณ ๊ฐ๊ฒฉ๊ณผ ์๋ ๊ณฑ์ผ๋ก ์ด๊ตฌ๋งค์ก ๊ณ์ฐ
+- [x] ํ๋ก๋ชจ์
ํ ์ธ ์ ์ฑ
๊ณ์ฐ
+- [x] ๋ฉค๋ฒ์ญ ํ ์ธ ์ ์ฑ
๊ณ์ฐ
+
+---
+### โ
์ฌ๊ณ ๊ด๋ฆฌ ๊ธฐ๋ฅ
+- [x] ์ฌ๊ณ ์๋ ํ์ธ ํ, ๊ฒฐ์ ๊ฐ๋ฅ ์ฌ๋ถ
+- [x] ์ํ ๊ตฌ๋งค ์ ์ฌ๊ณ ์ฐจ๊ฐ
+- [x] `์์ธ์ฒ๋ฆฌ` ๊ตฌ๋งคํ ์ํ๊ณผ ์๋ ํ์์ด ์ฌ๋ฐ๋ฅด์ง ์์ ๊ฒฝ์ฐ `[ERROR] ์ฌ๋ฐ๋ฅด์ง ์์ ํ์์ผ๋ก ์
๋ ฅํ์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.`
+- [x] `์์ธ์ฒ๋ฆฌ` ์กด์ฌํ์ง ์๋ ์ํ์ ์
๋ ฅํ ๊ฒฝ์ฐ `[ERROR] ์กด์ฌํ์ง ์๋ ์ํ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.`
+- [x] `์์ธ์ฒ๋ฆฌ` ๊ตฌ๋งค ์๋์ด ์ฌ๊ณ ์๋์ ์ด๊ณผํ ๊ฒฝ์ฐ `[ERROR] ์ฌ๊ณ ์๋์ ์ด๊ณผํ์ฌ ๊ตฌ๋งคํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.`
+
+---
+### โ
ํ๋ก๋ชจ์
ํ ์ธ ๊ธฐ๋ฅ
+- [x] ํ๋ก๋ชจ์
๊ธฐ๊ฐ ๋ด์ ํฌํจ๋ ๊ฒฝ์ฐ๋ง ํ ์ธ ์ ์ฉ
+- [x] ํ๋ก๋ชจ์
์ ์ง์ ๋ ์ํ์๋ง ์ ์ฉ
+- [x] ๋์ผ ์ํ์ ์ฌ๋ฌ ํ๋ก๋ชจ์
์ ์ฉ X
+- [x] ํํ์ ํ๋ก๋ชจ์
์ํ ์ฌ๊ณ ๋ง ์ ์ฉ
+- [x] ํ๋ก๋ชจ์
์ฌ๊ณ ๋ถ์กฑ ์, ๋์ผ ์ํ์ ์ผ๋ฐ ์ฌ๊ณ ์ฌ์ฉ
+- [x] ํ๋ก๋ชจ์
์๋๋ณด๋ค ์ ๊ฒ ๊ฐ์ ธ์ฌ ๋, ์ถ๊ฐ ๊ตฌ๋งค ์ ํํ ์๋ด
+- [x] ํ๋ก๋ชจ์
์๋๋ณด๋ค ๋ง๊ฒ ๊ฐ์ ธ์ฌ ๋, ์ ๊ฐ ๊ฒฐ์ ์ฃผ์ ์๋ด
+
+---
+### โ
๋ฉค๋ฒ์ญ ํ ์ธ ๊ธฐ๋ฅ
+- [x] ๋ฉค๋ฒ์ญ ํ์์ ํ๋ก๋ชจ์
๋ฏธ์ ์ฉ ์ํ์ `30%` ํ ์ธ
+- [x] ํ๋ก๋ชจ์
์ ์ฉ ํ, ๋จ์ ๊ธ์ก์ ๋ํ ๋ฉค๋ฒ์ญ ํ ์ธ
+- [x] ํ ์ธ ์ต๋ ํ๋ `8,000`์
+- [x] `์์ธ์ฒ๋ฆฌ` ํ ์ธ ์ ์ฉ ํ `๋ด์ค๋` ๊ธ์ก์ด ์์๋ฉด 0์ ๋ฐํํ๋ค.
+
+---
+### โ
์์์ฆ ์ถ๋ ฅ ๊ธฐ๋ฅ
+- [x] ๊ตฌ๋งค ๋ด์ญ๊ณผ ํ ์ธ์ ์ถ๋ ฅ
+ - ๊ตฌ๋งค ๋ด์ญ : ์ํ๋ช
, ์๋, ๊ฐ๊ฒฉ
+ - ์ฆ์ ์ํ ๋ด์ญ : ํ๋ก๋ชจ์
์ฆ์ ์ํ
+ - ๊ธ์ก ์ ๋ณด
+ - ์ด๊ตฌ๋งค์ก : ์ํ์ ์ด ์๋๊ณผ ๊ธ์ก
+ - ํ์ฌํ ์ธ : ํ๋ก๋ชจ์
์ผ๋ก ํ ์ธ๋ ๊ธ์ก
+ - ๋ฉค๋ฒ์ญํ ์ธ : ๋ฉค๋ฒ์ญ์ผ๋ก ํ ์ธ๋ ๊ธ์ก
+ - ๋ด์ค๋ : ์ต์ข
๊ฒฐ์ ๊ธ์ก
+- [x] ์์์ฆ ๊ตฌ์ฑ ์์ ์ ๋ ฌ
+```
+ex)
+==============W ํธ์์ ================
+์ํ๋ช
์๋ ๊ธ์ก
+์ฝ๋ผ 10 10,000
+=============์ฆ ์ ===============
+์ฝ๋ผ 2
+====================================
+์ด๊ตฌ๋งค์ก 10 10,000
+ํ์ฌํ ์ธ -2,000
+๋ฉค๋ฒ์ญํ ์ธ -0
+๋ด์ค๋ 8,000
+```
+
+---
+### โ
๊ทธ ์ธ ๊ธฐ๋ฅ
+- [x] ์์์ฆ ์ถ๋ ฅ ํ ์ฌ์์ ์ฌ๋ถ ํ์ธ
+
+---
+### โ
์๋ฌ ์ฒ๋ฆฌ
+- [x] ์๋ชป๋ ๊ฐ ์
๋ ฅ ์ `[ERROR] ` ์๋ฌ ๋ฉ์์ง ์ถ๋ ฅ ํ, ๋ค์ ์
๋ ฅ
+- [x] `Exception`์ด ์๋, `IllegalArgumentException`์ `IllegalStateException` ๋ช
ํํ ์ ํ์ผ๋ก ์ฒ๋ฆฌ
+
+---
+### โ
์
๋ ฅ
+- [x] ๊ตฌ๋งค ์ํ๊ณผ ์๋
+```
+ex)
+๊ตฌ๋งคํ์ค ์ํ๋ช
๊ณผ ์๋์ ์
๋ ฅํด ์ฃผ์ธ์. (์: [์ฌ์ด๋ค-2],[๊ฐ์์นฉ-1])
+[์ฝ๋ผ-10],[์ฌ์ด๋ค-3]
+```
+
+- [x] ํ๋ก๋ชจ์
์ ์ฉ ๊ฐ๋ฅํ ์ถ๊ฐ ์๋ ์ฌ๋ถ
+```
+ex)
+ํ์ฌ ์ค๋ ์ง์ฃผ์ค์(๋) 1๊ฐ๋ฅผ ๋ฌด๋ฃ๋ก ๋ ๋ฐ์ ์ ์์ต๋๋ค. ์ถ๊ฐํ์๊ฒ ์ต๋๊น? (Y/N)
+Y
+```
+- [x] ํ๋ก๋ชจ์
์ ์ฉ ๋ถ๊ฐ๋ฅํ ์๋์ ์ ๊ฐ ๊ฒฐ์ ์ฌ๋ถ
+```
+ํ์ฌ ์ฝ๋ผ 4๊ฐ๋ ํ๋ก๋ชจ์
ํ ์ธ์ด ์ ์ฉ๋์ง ์์ต๋๋ค. ๊ทธ๋๋ ๊ตฌ๋งคํ์๊ฒ ์ต๋๊น? (Y/N)
+Y
+```
+- [x] ๋ฉค๋ฒ์ญ ํ ์ธ ์ ์ฉ ์ฌ๋ถ
+```
+๋ฉค๋ฒ์ญ ํ ์ธ์ ๋ฐ์ผ์๊ฒ ์ต๋๊น? (Y/N)
+Y
+```
+- [x] ์ถ๊ฐ ๊ตฌ๋งค ์ฌ๋ถ
+```
+๊ฐ์ฌํฉ๋๋ค. ๊ตฌ๋งคํ๊ณ ์ถ์ ๋ค๋ฅธ ์ํ์ด ์๋์? (Y/N)
+N
+```
+- `์์ธ์ฒ๋ฆฌ` ์๋ชป๋ ์
๋ ฅ์ ๊ฒฝ์ฐ `[ERROR] ์๋ชป๋ ์
๋ ฅ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.`
+
+---
+### โ
์ถ๋ ฅ
+- [x] ํ์ ์ธ์ฌ ์ถ๋ ฅ `ex) ์๋
ํ์ธ์. Wํธ์์ ์
๋๋ค.`
+- [x] ๋ณด์ ๋ฌผํ ์๋ด ์ถ๋ ฅ `ex) ํ์ฌ ๋ณด์ ํ๊ณ ์๋ ์ํ์
๋๋ค.`
+- [x] ๋ณด์ ๋ฌผํ ์ถ๋ ฅ
+```
+ex)
+- ์ฝ๋ผ 1,000์ 10๊ฐ ํ์ฐ2+1
+- ์ฝ๋ผ 1,000์ 10๊ฐ
+- ์ฌ์ด๋ค 1,000์ 8๊ฐ ํ์ฐ2+1
+- ์ฌ์ด๋ค 1,000์ 7๊ฐ
+- ์ค๋ ์ง์ฃผ์ค 1,800์ 9๊ฐ MD์ถ์ฒ์ํ
+- ์ค๋ ์ง์ฃผ์ค 1,800์ ์ฌ๊ณ ์์
+- ํ์ฐ์ 1,200์ 5๊ฐ ํ์ฐ2+1
+- ํ์ฐ์ 1,200์ ์ฌ๊ณ ์์
+- ๋ฌผ 500์ 10๊ฐ
+- ๋นํ๋ฏผ์ํฐ 1,500์ 6๊ฐ
+- ๊ฐ์์นฉ 1,500์ 5๊ฐ ๋ฐ์งํ ์ธ
+- ๊ฐ์์นฉ 1,500์ 5๊ฐ
+- ์ด์ฝ๋ฐ 1,200์ 5๊ฐ MD์ถ์ฒ์ํ
+- ์ด์ฝ๋ฐ 1,200์ 5๊ฐ
+- ์๋์ง๋ฐ 2,000์ 5๊ฐ
+- ์ ์๋์๋ฝ 6,400์ 8๊ฐ
+- ์ปต๋ผ๋ฉด 1,700์ 1๊ฐ MD์ถ์ฒ์ํ
+- ์ปต๋ผ๋ฉด 1,700์ 10๊ฐ
+```
+- [x] ๊ตฌ๋งค, ์ฆ์ ์ํ ๋ด์ญ - ๊ธ์ก ์ ๋ณด ์ถ๋ ฅ
+```
+==============W ํธ์์ ================
+์ํ๋ช
์๋ ๊ธ์ก
+์ฝ๋ผ 3 3,000
+์๋์ง๋ฐ 5 10,000
+=============์ฆ ์ ===============
+์ฝ๋ผ 1
+====================================
+์ด๊ตฌ๋งค์ก 8 13,000
+ํ์ฌํ ์ธ -1,000
+๋ฉค๋ฒ์ญํ ์ธ -3,000
+๋ด์ค๋ 9,000
+```
+
+---
+### โ
์คํ ๊ฒฐ๊ณผ
+```
+์๋
ํ์ธ์. Wํธ์์ ์
๋๋ค.
+ํ์ฌ ๋ณด์ ํ๊ณ ์๋ ์ํ์
๋๋ค.
+
+- ์ฝ๋ผ 1,000์ 10๊ฐ ํ์ฐ2+1
+- ์ฝ๋ผ 1,000์ 10๊ฐ
+- ์ฌ์ด๋ค 1,000์ 8๊ฐ ํ์ฐ2+1
+- ์ฌ์ด๋ค 1,000์ 7๊ฐ
+- ์ค๋ ์ง์ฃผ์ค 1,800์ 9๊ฐ MD์ถ์ฒ์ํ
+- ์ค๋ ์ง์ฃผ์ค 1,800์ ์ฌ๊ณ ์์
+- ํ์ฐ์ 1,200์ 5๊ฐ ํ์ฐ2+1
+- ํ์ฐ์ 1,200์ ์ฌ๊ณ ์์
+- ๋ฌผ 500์ 10๊ฐ
+- ๋นํ๋ฏผ์ํฐ 1,500์ 6๊ฐ
+- ๊ฐ์์นฉ 1,500์ 5๊ฐ ๋ฐ์งํ ์ธ
+- ๊ฐ์์นฉ 1,500์ 5๊ฐ
+- ์ด์ฝ๋ฐ 1,200์ 5๊ฐ MD์ถ์ฒ์ํ
+- ์ด์ฝ๋ฐ 1,200์ 5๊ฐ
+- ์๋์ง๋ฐ 2,000์ 5๊ฐ
+- ์ ์๋์๋ฝ 6,400์ 8๊ฐ
+- ์ปต๋ผ๋ฉด 1,700์ 1๊ฐ MD์ถ์ฒ์ํ
+- ์ปต๋ผ๋ฉด 1,700์ 10๊ฐ
+
+๊ตฌ๋งคํ์ค ์ํ๋ช
๊ณผ ์๋์ ์
๋ ฅํด ์ฃผ์ธ์. (์: [์ฌ์ด๋ค-2],[๊ฐ์์นฉ-1])
+[์ฝ๋ผ-3],[์๋์ง๋ฐ-5]
+
+๋ฉค๋ฒ์ญ ํ ์ธ์ ๋ฐ์ผ์๊ฒ ์ต๋๊น? (Y/N)
+Y
+
+==============W ํธ์์ ================
+์ํ๋ช
์๋ ๊ธ์ก
+์ฝ๋ผ 3 3,000
+์๋์ง๋ฐ 5 10,000
+=============์ฆ ์ ===============
+์ฝ๋ผ 1
+====================================
+์ด๊ตฌ๋งค์ก 8 13,000
+ํ์ฌํ ์ธ -1,000
+๋ฉค๋ฒ์ญํ ์ธ -3,000
+๋ด์ค๋ 9,000
+
+๊ฐ์ฌํฉ๋๋ค. ๊ตฌ๋งคํ๊ณ ์ถ์ ๋ค๋ฅธ ์ํ์ด ์๋์? (Y/N)
+Y
+
+์๋
ํ์ธ์. Wํธ์์ ์
๋๋ค.
+ํ์ฌ ๋ณด์ ํ๊ณ ์๋ ์ํ์
๋๋ค.
+
+- ์ฝ๋ผ 1,000์ 7๊ฐ ํ์ฐ2+1
+- ์ฝ๋ผ 1,000์ 10๊ฐ
+- ์ฌ์ด๋ค 1,000์ 8๊ฐ ํ์ฐ2+1
+- ์ฌ์ด๋ค 1,000์ 7๊ฐ
+- ์ค๋ ์ง์ฃผ์ค 1,800์ 9๊ฐ MD์ถ์ฒ์ํ
+- ์ค๋ ์ง์ฃผ์ค 1,800์ ์ฌ๊ณ ์์
+- ํ์ฐ์ 1,200์ 5๊ฐ ํ์ฐ2+1
+- ํ์ฐ์ 1,200์ ์ฌ๊ณ ์์
+- ๋ฌผ 500์ 10๊ฐ
+- ๋นํ๋ฏผ์ํฐ 1,500์ 6๊ฐ
+- ๊ฐ์์นฉ 1,500์ 5๊ฐ ๋ฐ์งํ ์ธ
+- ๊ฐ์์นฉ 1,500์ 5๊ฐ
+- ์ด์ฝ๋ฐ 1,200์ 5๊ฐ MD์ถ์ฒ์ํ
+- ์ด์ฝ๋ฐ 1,200์ 5๊ฐ
+- ์๋์ง๋ฐ 2,000์ ์ฌ๊ณ ์์
+- ์ ์๋์๋ฝ 6,400์ 8๊ฐ
+- ์ปต๋ผ๋ฉด 1,700์ 1๊ฐ MD์ถ์ฒ์ํ
+- ์ปต๋ผ๋ฉด 1,700์ 10๊ฐ
+
+๊ตฌ๋งคํ์ค ์ํ๋ช
๊ณผ ์๋์ ์
๋ ฅํด ์ฃผ์ธ์. (์: [์ฌ์ด๋ค-2],[๊ฐ์์นฉ-1])
+[์ฝ๋ผ-10]
+
+ํ์ฌ ์ฝ๋ผ 4๊ฐ๋ ํ๋ก๋ชจ์
ํ ์ธ์ด ์ ์ฉ๋์ง ์์ต๋๋ค. ๊ทธ๋๋ ๊ตฌ๋งคํ์๊ฒ ์ต๋๊น? (Y/N)
+Y
+
+๋ฉค๋ฒ์ญ ํ ์ธ์ ๋ฐ์ผ์๊ฒ ์ต๋๊น? (Y/N)
+N
+
+==============W ํธ์์ ================
+์ํ๋ช
์๋ ๊ธ์ก
+์ฝ๋ผ 10 10,000
+=============์ฆ ์ ===============
+์ฝ๋ผ 2
+====================================
+์ด๊ตฌ๋งค์ก 10 10,000
+ํ์ฌํ ์ธ -2,000
+๋ฉค๋ฒ์ญํ ์ธ -0
+๋ด์ค๋ 8,000
+
+๊ฐ์ฌํฉ๋๋ค. ๊ตฌ๋งคํ๊ณ ์ถ์ ๋ค๋ฅธ ์ํ์ด ์๋์? (Y/N)
+Y
+
+์๋
ํ์ธ์. Wํธ์์ ์
๋๋ค.
+ํ์ฌ ๋ณด์ ํ๊ณ ์๋ ์ํ์
๋๋ค.
+
+- ์ฝ๋ผ 1,000์ ์ฌ๊ณ ์์ ํ์ฐ2+1
+- ์ฝ๋ผ 1,000์ 7๊ฐ
+- ์ฌ์ด๋ค 1,000์ 8๊ฐ ํ์ฐ2+1
+- ์ฌ์ด๋ค 1,000์ 7๊ฐ
+- ์ค๋ ์ง์ฃผ์ค 1,800์ 9๊ฐ MD์ถ์ฒ์ํ
+- ์ค๋ ์ง์ฃผ์ค 1,800์ ์ฌ๊ณ ์์
+- ํ์ฐ์ 1,200์ 5๊ฐ ํ์ฐ2+1
+- ํ์ฐ์ 1,200์ ์ฌ๊ณ ์์
+- ๋ฌผ 500์ 10๊ฐ
+- ๋นํ๋ฏผ์ํฐ 1,500์ 6๊ฐ
+- ๊ฐ์์นฉ 1,500์ 5๊ฐ ๋ฐ์งํ ์ธ
+- ๊ฐ์์นฉ 1,500์ 5๊ฐ
+- ์ด์ฝ๋ฐ 1,200์ 5๊ฐ MD์ถ์ฒ์ํ
+- ์ด์ฝ๋ฐ 1,200์ 5๊ฐ
+- ์๋์ง๋ฐ 2,000์ ์ฌ๊ณ ์์
+- ์ ์๋์๋ฝ 6,400์ 8๊ฐ
+- ์ปต๋ผ๋ฉด 1,700์ 1๊ฐ MD์ถ์ฒ์ํ
+- ์ปต๋ผ๋ฉด 1,700์ 10๊ฐ
+
+๊ตฌ๋งคํ์ค ์ํ๋ช
๊ณผ ์๋์ ์
๋ ฅํด ์ฃผ์ธ์. (์: [์ฌ์ด๋ค-2],[๊ฐ์์นฉ-1])
+[์ค๋ ์ง์ฃผ์ค-1]
+
+ํ์ฌ ์ค๋ ์ง์ฃผ์ค์(๋) 1๊ฐ๋ฅผ ๋ฌด๋ฃ๋ก ๋ ๋ฐ์ ์ ์์ต๋๋ค. ์ถ๊ฐํ์๊ฒ ์ต๋๊น? (Y/N)
+Y
+
+๋ฉค๋ฒ์ญ ํ ์ธ์ ๋ฐ์ผ์๊ฒ ์ต๋๊น? (Y/N)
+Y
+
+==============W ํธ์์ ================
+์ํ๋ช
์๋ ๊ธ์ก
+์ค๋ ์ง์ฃผ์ค 2 3,600
+=============์ฆ ์ ===============
+์ค๋ ์ง์ฃผ์ค 1
+====================================
+์ด๊ตฌ๋งค์ก 2 3,600
+ํ์ฌํ ์ธ -1,800
+๋ฉค๋ฒ์ญํ ์ธ -0
+๋ด์ค๋ 1,800
+
+๊ฐ์ฌํฉ๋๋ค. ๊ตฌ๋งคํ๊ณ ์ถ์ ๋ค๋ฅธ ์ํ์ด ์๋์? (Y/N)
+N
+```
\ No newline at end of file | Unknown | ์๊ฐํ๊ธฐ ์ฝ์ง ์์ ์ ์๋ ์ฃ์ง ์ผ์ด์ค์์ํ
๋ฐ ์ ์ง์ผ์
จ๋ค์! |
@@ -0,0 +1,223 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import store.domain.PaymentProductList;
+import store.domain.Product;
+import store.domain.Products;
+import store.domain.Promotions;
+import store.domain.PromotionsList;
+import store.domain.PurchaseProduct;
+import store.global.util.ProductParser;
+import store.global.util.PromotionParser;
+import store.global.util.PurchaseParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final OutputView outputView;
+ private final InputView inputView;
+
+ public StoreController(OutputView outputView, InputView inputView) {
+ this.outputView = outputView;
+ this.inputView = inputView;
+ }
+
+ public void run() {
+ Products products = loadStoreFiles();
+
+ do {
+ displayWelcome(products);
+ List<PurchaseProduct> purchases = handlePurchases(products);
+ PaymentProductList paymentProductList = processPurchases(purchases);
+
+ displayPaymentInfo(paymentProductList);
+ } while (readAdditionalPurchaseConfirmationWithRetry());
+ }
+
+ private void displayWelcome(Products products) {
+ displayWelcomeMessage();
+ displayProductsInfo(products);
+ }
+
+ private Products loadStoreFiles() {
+ PromotionsList promotionsList = loadPromotions();
+ return loadProducts(promotionsList);
+ }
+
+ private PaymentProductList processPurchases(List<PurchaseProduct> purchases) {
+ PaymentProductList paymentProductList = new PaymentProductList();
+ LocalDateTime now = DateTimes.now();
+
+ for (PurchaseProduct purchase : purchases) {
+ processSinglePurchase(paymentProductList, purchase, now);
+ }
+
+ decreaseProductStock(purchases, paymentProductList);
+ applyMembershipDiscountIfConfirmed(paymentProductList);
+ return paymentProductList;
+ }
+
+ private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) {
+ List<Integer> quantities = paymentProductList.getAllProductQuantities();
+ for (int i = 0; i < purchases.size(); i++) {
+ purchases.get(i).reduceProductStock(quantities.get(i));
+ }
+ }
+
+ private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ LocalDateTime now) {
+ if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) {
+ handlePromotionProduct(paymentProductList, purchase);
+ return;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0));
+ }
+
+
+ private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ int remainingStock = purchase.getRemainingStock();
+ if (remainingStock > 0) {
+ handleRemainingStock(paymentProductList, purchase, remainingStock);
+ return;
+ }
+ if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) {
+ handleNonZeroRemainingStock(paymentProductList, purchase);
+ return;
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ int remainingStock) {
+ int quantity = calculateQuantity(purchase, remainingStock);
+
+ if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) {
+ purchase.decrease(quantity);
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1));
+ }
+
+ private int calculateQuantity(PurchaseProduct purchase, int remainingStock) {
+ int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock));
+ return remainingStock + promotionRate;
+ }
+
+ private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ boolean answer = confirmPromotionAddition(purchase.getProductName());
+ int promotionUnits = purchase.getPromotionUnits();
+ if (answer) {
+ purchase.increaseQuantityForPromotion();
+ promotionUnits += 1;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void displayPaymentInfo(PaymentProductList paymentProductList) {
+ List<String> productInfos = paymentProductList.infoProduct();
+ List<String> promotionInfos = paymentProductList.infoPromotion();
+ List<String> finalResults = paymentProductList.finalResult();
+
+ outputView.printPaymentInfoResult(productInfos);
+ outputView.printPromotionInfoResult(promotionInfos);
+ outputView.printFinalResult(finalResults);
+ }
+
+ private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) {
+ if (readMembershipConfirmationWithRetry()) {
+ paymentProductList.applyMembershipDiscount();
+ }
+ }
+
+ private void displayWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ private PromotionsList loadPromotions() {
+ List<List<String>> inputPromotions = inputView.readPromotionsData();
+ List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions);
+ return new PromotionsList(promotionsList1);
+ }
+
+ private Products loadProducts(PromotionsList promotionsList) {
+ List<List<String>> inputProducts = inputView.readProductsData();
+ List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList);
+ return new Products(productList);
+ }
+
+ private void displayProductsInfo(Products products) {
+ outputView.printProductsInfo(products.getAllProductsInfo());
+ }
+
+ private List<PurchaseProduct> handlePurchases(Products products) {
+ while (true) {
+ try {
+ Map<String, Integer> purchases = readAndParsePurchaseInput();
+ return processPurchases(products, purchases);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private Map<String, Integer> readAndParsePurchaseInput() {
+ String input = inputView.readPurchaseInput();
+ return PurchaseParser.parseInputProduct(input);
+ }
+
+ private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) {
+ List<PurchaseProduct> purchaseProducts = new ArrayList<>();
+ for (Map.Entry<String, Integer> entry : purchases.entrySet()) {
+ List<Product> foundProducts = products.findProductByName(entry.getKey());
+ purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue()));
+ }
+ return purchaseProducts;
+ }
+
+ private boolean confirmPromotionNotApplied(String productName, int quantity) {
+ while (true) {
+ try {
+ outputView.printPromotionNotApplied(productName, quantity);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean confirmPromotionAddition(String productName) {
+ while (true) {
+ try {
+ outputView.printPromotionAddition(productName);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readMembershipConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readMembershipConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readAdditionalPurchaseConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readAdditionalPurchaseConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+} | Java | do {} while์ด ์์ฃผ ์ ์ฐ์ด๋ ๊ตฌ๋ฌธ์ด๋ผ์ ์ฌ์ฉ ํ ์๊ฐ์ ํ๋๊ฒ์ด ์ฝ์ง ์์ผ์
จ์ํ
๋ฐ ์ด๊ฒ๋ ์ ํ์
จ๋ค์! |
@@ -0,0 +1,223 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import store.domain.PaymentProductList;
+import store.domain.Product;
+import store.domain.Products;
+import store.domain.Promotions;
+import store.domain.PromotionsList;
+import store.domain.PurchaseProduct;
+import store.global.util.ProductParser;
+import store.global.util.PromotionParser;
+import store.global.util.PurchaseParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final OutputView outputView;
+ private final InputView inputView;
+
+ public StoreController(OutputView outputView, InputView inputView) {
+ this.outputView = outputView;
+ this.inputView = inputView;
+ }
+
+ public void run() {
+ Products products = loadStoreFiles();
+
+ do {
+ displayWelcome(products);
+ List<PurchaseProduct> purchases = handlePurchases(products);
+ PaymentProductList paymentProductList = processPurchases(purchases);
+
+ displayPaymentInfo(paymentProductList);
+ } while (readAdditionalPurchaseConfirmationWithRetry());
+ }
+
+ private void displayWelcome(Products products) {
+ displayWelcomeMessage();
+ displayProductsInfo(products);
+ }
+
+ private Products loadStoreFiles() {
+ PromotionsList promotionsList = loadPromotions();
+ return loadProducts(promotionsList);
+ }
+
+ private PaymentProductList processPurchases(List<PurchaseProduct> purchases) {
+ PaymentProductList paymentProductList = new PaymentProductList();
+ LocalDateTime now = DateTimes.now();
+
+ for (PurchaseProduct purchase : purchases) {
+ processSinglePurchase(paymentProductList, purchase, now);
+ }
+
+ decreaseProductStock(purchases, paymentProductList);
+ applyMembershipDiscountIfConfirmed(paymentProductList);
+ return paymentProductList;
+ }
+
+ private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) {
+ List<Integer> quantities = paymentProductList.getAllProductQuantities();
+ for (int i = 0; i < purchases.size(); i++) {
+ purchases.get(i).reduceProductStock(quantities.get(i));
+ }
+ }
+
+ private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ LocalDateTime now) {
+ if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) {
+ handlePromotionProduct(paymentProductList, purchase);
+ return;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0));
+ }
+
+
+ private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ int remainingStock = purchase.getRemainingStock();
+ if (remainingStock > 0) {
+ handleRemainingStock(paymentProductList, purchase, remainingStock);
+ return;
+ }
+ if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) {
+ handleNonZeroRemainingStock(paymentProductList, purchase);
+ return;
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ int remainingStock) {
+ int quantity = calculateQuantity(purchase, remainingStock);
+
+ if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) {
+ purchase.decrease(quantity);
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1));
+ }
+
+ private int calculateQuantity(PurchaseProduct purchase, int remainingStock) {
+ int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock));
+ return remainingStock + promotionRate;
+ }
+
+ private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ boolean answer = confirmPromotionAddition(purchase.getProductName());
+ int promotionUnits = purchase.getPromotionUnits();
+ if (answer) {
+ purchase.increaseQuantityForPromotion();
+ promotionUnits += 1;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void displayPaymentInfo(PaymentProductList paymentProductList) {
+ List<String> productInfos = paymentProductList.infoProduct();
+ List<String> promotionInfos = paymentProductList.infoPromotion();
+ List<String> finalResults = paymentProductList.finalResult();
+
+ outputView.printPaymentInfoResult(productInfos);
+ outputView.printPromotionInfoResult(promotionInfos);
+ outputView.printFinalResult(finalResults);
+ }
+
+ private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) {
+ if (readMembershipConfirmationWithRetry()) {
+ paymentProductList.applyMembershipDiscount();
+ }
+ }
+
+ private void displayWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ private PromotionsList loadPromotions() {
+ List<List<String>> inputPromotions = inputView.readPromotionsData();
+ List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions);
+ return new PromotionsList(promotionsList1);
+ }
+
+ private Products loadProducts(PromotionsList promotionsList) {
+ List<List<String>> inputProducts = inputView.readProductsData();
+ List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList);
+ return new Products(productList);
+ }
+
+ private void displayProductsInfo(Products products) {
+ outputView.printProductsInfo(products.getAllProductsInfo());
+ }
+
+ private List<PurchaseProduct> handlePurchases(Products products) {
+ while (true) {
+ try {
+ Map<String, Integer> purchases = readAndParsePurchaseInput();
+ return processPurchases(products, purchases);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private Map<String, Integer> readAndParsePurchaseInput() {
+ String input = inputView.readPurchaseInput();
+ return PurchaseParser.parseInputProduct(input);
+ }
+
+ private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) {
+ List<PurchaseProduct> purchaseProducts = new ArrayList<>();
+ for (Map.Entry<String, Integer> entry : purchases.entrySet()) {
+ List<Product> foundProducts = products.findProductByName(entry.getKey());
+ purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue()));
+ }
+ return purchaseProducts;
+ }
+
+ private boolean confirmPromotionNotApplied(String productName, int quantity) {
+ while (true) {
+ try {
+ outputView.printPromotionNotApplied(productName, quantity);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean confirmPromotionAddition(String productName) {
+ while (true) {
+ try {
+ outputView.printPromotionAddition(productName);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readMembershipConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readMembershipConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readAdditionalPurchaseConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readAdditionalPurchaseConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+} | Java | ```java
private <T> T process(Supplier<T> supplier) {
while (true) {
try {
return supplier.get();
} catch (IllegalArgumentException e) {
outputView.printErrorMessage(e.getMessage());
}
}
}
process(inputView::read~~); //ํธ์ถ
```
ํจ์ํ ์ธํฐํ์ด์ค์ ์ ๋ค๋ฆญ์ ํ์ฉํ๋ฉด ์ค๋ณต์ ์ค์ผ ์ ์์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,223 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import store.domain.PaymentProductList;
+import store.domain.Product;
+import store.domain.Products;
+import store.domain.Promotions;
+import store.domain.PromotionsList;
+import store.domain.PurchaseProduct;
+import store.global.util.ProductParser;
+import store.global.util.PromotionParser;
+import store.global.util.PurchaseParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final OutputView outputView;
+ private final InputView inputView;
+
+ public StoreController(OutputView outputView, InputView inputView) {
+ this.outputView = outputView;
+ this.inputView = inputView;
+ }
+
+ public void run() {
+ Products products = loadStoreFiles();
+
+ do {
+ displayWelcome(products);
+ List<PurchaseProduct> purchases = handlePurchases(products);
+ PaymentProductList paymentProductList = processPurchases(purchases);
+
+ displayPaymentInfo(paymentProductList);
+ } while (readAdditionalPurchaseConfirmationWithRetry());
+ }
+
+ private void displayWelcome(Products products) {
+ displayWelcomeMessage();
+ displayProductsInfo(products);
+ }
+
+ private Products loadStoreFiles() {
+ PromotionsList promotionsList = loadPromotions();
+ return loadProducts(promotionsList);
+ }
+
+ private PaymentProductList processPurchases(List<PurchaseProduct> purchases) {
+ PaymentProductList paymentProductList = new PaymentProductList();
+ LocalDateTime now = DateTimes.now();
+
+ for (PurchaseProduct purchase : purchases) {
+ processSinglePurchase(paymentProductList, purchase, now);
+ }
+
+ decreaseProductStock(purchases, paymentProductList);
+ applyMembershipDiscountIfConfirmed(paymentProductList);
+ return paymentProductList;
+ }
+
+ private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) {
+ List<Integer> quantities = paymentProductList.getAllProductQuantities();
+ for (int i = 0; i < purchases.size(); i++) {
+ purchases.get(i).reduceProductStock(quantities.get(i));
+ }
+ }
+
+ private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ LocalDateTime now) {
+ if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) {
+ handlePromotionProduct(paymentProductList, purchase);
+ return;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0));
+ }
+
+
+ private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ int remainingStock = purchase.getRemainingStock();
+ if (remainingStock > 0) {
+ handleRemainingStock(paymentProductList, purchase, remainingStock);
+ return;
+ }
+ if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) {
+ handleNonZeroRemainingStock(paymentProductList, purchase);
+ return;
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ int remainingStock) {
+ int quantity = calculateQuantity(purchase, remainingStock);
+
+ if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) {
+ purchase.decrease(quantity);
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1));
+ }
+
+ private int calculateQuantity(PurchaseProduct purchase, int remainingStock) {
+ int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock));
+ return remainingStock + promotionRate;
+ }
+
+ private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ boolean answer = confirmPromotionAddition(purchase.getProductName());
+ int promotionUnits = purchase.getPromotionUnits();
+ if (answer) {
+ purchase.increaseQuantityForPromotion();
+ promotionUnits += 1;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void displayPaymentInfo(PaymentProductList paymentProductList) {
+ List<String> productInfos = paymentProductList.infoProduct();
+ List<String> promotionInfos = paymentProductList.infoPromotion();
+ List<String> finalResults = paymentProductList.finalResult();
+
+ outputView.printPaymentInfoResult(productInfos);
+ outputView.printPromotionInfoResult(promotionInfos);
+ outputView.printFinalResult(finalResults);
+ }
+
+ private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) {
+ if (readMembershipConfirmationWithRetry()) {
+ paymentProductList.applyMembershipDiscount();
+ }
+ }
+
+ private void displayWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ private PromotionsList loadPromotions() {
+ List<List<String>> inputPromotions = inputView.readPromotionsData();
+ List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions);
+ return new PromotionsList(promotionsList1);
+ }
+
+ private Products loadProducts(PromotionsList promotionsList) {
+ List<List<String>> inputProducts = inputView.readProductsData();
+ List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList);
+ return new Products(productList);
+ }
+
+ private void displayProductsInfo(Products products) {
+ outputView.printProductsInfo(products.getAllProductsInfo());
+ }
+
+ private List<PurchaseProduct> handlePurchases(Products products) {
+ while (true) {
+ try {
+ Map<String, Integer> purchases = readAndParsePurchaseInput();
+ return processPurchases(products, purchases);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private Map<String, Integer> readAndParsePurchaseInput() {
+ String input = inputView.readPurchaseInput();
+ return PurchaseParser.parseInputProduct(input);
+ }
+
+ private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) {
+ List<PurchaseProduct> purchaseProducts = new ArrayList<>();
+ for (Map.Entry<String, Integer> entry : purchases.entrySet()) {
+ List<Product> foundProducts = products.findProductByName(entry.getKey());
+ purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue()));
+ }
+ return purchaseProducts;
+ }
+
+ private boolean confirmPromotionNotApplied(String productName, int quantity) {
+ while (true) {
+ try {
+ outputView.printPromotionNotApplied(productName, quantity);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean confirmPromotionAddition(String productName) {
+ while (true) {
+ try {
+ outputView.printPromotionAddition(productName);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readMembershipConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readMembershipConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readAdditionalPurchaseConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readAdditionalPurchaseConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+} | Java | ์ด ๋๊ฐ์ ๋ฉ์๋๋ฅผ, purchase.canApplyPromotion() ์ผ๋ก ๋ฌถ๋ ๊ฒ๋ ๊ฐ๋
์ฑ์ ๋์ด๋๋ฐ์ ์ข์ ๋ณด์
๋๋ค. |
@@ -0,0 +1,223 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import store.domain.PaymentProductList;
+import store.domain.Product;
+import store.domain.Products;
+import store.domain.Promotions;
+import store.domain.PromotionsList;
+import store.domain.PurchaseProduct;
+import store.global.util.ProductParser;
+import store.global.util.PromotionParser;
+import store.global.util.PurchaseParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final OutputView outputView;
+ private final InputView inputView;
+
+ public StoreController(OutputView outputView, InputView inputView) {
+ this.outputView = outputView;
+ this.inputView = inputView;
+ }
+
+ public void run() {
+ Products products = loadStoreFiles();
+
+ do {
+ displayWelcome(products);
+ List<PurchaseProduct> purchases = handlePurchases(products);
+ PaymentProductList paymentProductList = processPurchases(purchases);
+
+ displayPaymentInfo(paymentProductList);
+ } while (readAdditionalPurchaseConfirmationWithRetry());
+ }
+
+ private void displayWelcome(Products products) {
+ displayWelcomeMessage();
+ displayProductsInfo(products);
+ }
+
+ private Products loadStoreFiles() {
+ PromotionsList promotionsList = loadPromotions();
+ return loadProducts(promotionsList);
+ }
+
+ private PaymentProductList processPurchases(List<PurchaseProduct> purchases) {
+ PaymentProductList paymentProductList = new PaymentProductList();
+ LocalDateTime now = DateTimes.now();
+
+ for (PurchaseProduct purchase : purchases) {
+ processSinglePurchase(paymentProductList, purchase, now);
+ }
+
+ decreaseProductStock(purchases, paymentProductList);
+ applyMembershipDiscountIfConfirmed(paymentProductList);
+ return paymentProductList;
+ }
+
+ private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) {
+ List<Integer> quantities = paymentProductList.getAllProductQuantities();
+ for (int i = 0; i < purchases.size(); i++) {
+ purchases.get(i).reduceProductStock(quantities.get(i));
+ }
+ }
+
+ private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ LocalDateTime now) {
+ if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) {
+ handlePromotionProduct(paymentProductList, purchase);
+ return;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0));
+ }
+
+
+ private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ int remainingStock = purchase.getRemainingStock();
+ if (remainingStock > 0) {
+ handleRemainingStock(paymentProductList, purchase, remainingStock);
+ return;
+ }
+ if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) {
+ handleNonZeroRemainingStock(paymentProductList, purchase);
+ return;
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ int remainingStock) {
+ int quantity = calculateQuantity(purchase, remainingStock);
+
+ if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) {
+ purchase.decrease(quantity);
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1));
+ }
+
+ private int calculateQuantity(PurchaseProduct purchase, int remainingStock) {
+ int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock));
+ return remainingStock + promotionRate;
+ }
+
+ private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ boolean answer = confirmPromotionAddition(purchase.getProductName());
+ int promotionUnits = purchase.getPromotionUnits();
+ if (answer) {
+ purchase.increaseQuantityForPromotion();
+ promotionUnits += 1;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void displayPaymentInfo(PaymentProductList paymentProductList) {
+ List<String> productInfos = paymentProductList.infoProduct();
+ List<String> promotionInfos = paymentProductList.infoPromotion();
+ List<String> finalResults = paymentProductList.finalResult();
+
+ outputView.printPaymentInfoResult(productInfos);
+ outputView.printPromotionInfoResult(promotionInfos);
+ outputView.printFinalResult(finalResults);
+ }
+
+ private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) {
+ if (readMembershipConfirmationWithRetry()) {
+ paymentProductList.applyMembershipDiscount();
+ }
+ }
+
+ private void displayWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ private PromotionsList loadPromotions() {
+ List<List<String>> inputPromotions = inputView.readPromotionsData();
+ List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions);
+ return new PromotionsList(promotionsList1);
+ }
+
+ private Products loadProducts(PromotionsList promotionsList) {
+ List<List<String>> inputProducts = inputView.readProductsData();
+ List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList);
+ return new Products(productList);
+ }
+
+ private void displayProductsInfo(Products products) {
+ outputView.printProductsInfo(products.getAllProductsInfo());
+ }
+
+ private List<PurchaseProduct> handlePurchases(Products products) {
+ while (true) {
+ try {
+ Map<String, Integer> purchases = readAndParsePurchaseInput();
+ return processPurchases(products, purchases);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private Map<String, Integer> readAndParsePurchaseInput() {
+ String input = inputView.readPurchaseInput();
+ return PurchaseParser.parseInputProduct(input);
+ }
+
+ private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) {
+ List<PurchaseProduct> purchaseProducts = new ArrayList<>();
+ for (Map.Entry<String, Integer> entry : purchases.entrySet()) {
+ List<Product> foundProducts = products.findProductByName(entry.getKey());
+ purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue()));
+ }
+ return purchaseProducts;
+ }
+
+ private boolean confirmPromotionNotApplied(String productName, int quantity) {
+ while (true) {
+ try {
+ outputView.printPromotionNotApplied(productName, quantity);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean confirmPromotionAddition(String productName) {
+ while (true) {
+ try {
+ outputView.printPromotionAddition(productName);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readMembershipConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readMembershipConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readAdditionalPurchaseConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readAdditionalPurchaseConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+} | Java | StoreController์ ์ญ ์ฝ์ผ๋ฉฐ ๋ ์๊ฐ์ด, ๋ฌผ๋ก ์๊ฐ์ด ์ด๋ฐํ๊ณ ์ด์ฉ ์ ์์์ง๋ง ์ปจํธ๋กค๋ฌ์ ๋๋ฌด ๋ง์ ์ฑ
์๊ณผ ๊ตฌํ์ด ์ง์ค๋์ด ์๋ ๊ฒ ๊ฐ์ต๋๋ค. ์ปจํธ๋กค๋ฌ๋ ์ ๋ง ๋จ์ํ ์ ์ด ์ญํ ์ ํ๊ณ , ๋น์ฆ๋์ค๊ฐ ํฌํจ๋ ๊ตฌํ ๋ถ๋ถ์ Service ๋ ์ด์ด๋ก ๋ฐ๋ก ๋นผ๋ ๋ฐฉ๋ฒ์ ์ด๋จ๊น์? |
@@ -0,0 +1,223 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import store.domain.PaymentProductList;
+import store.domain.Product;
+import store.domain.Products;
+import store.domain.Promotions;
+import store.domain.PromotionsList;
+import store.domain.PurchaseProduct;
+import store.global.util.ProductParser;
+import store.global.util.PromotionParser;
+import store.global.util.PurchaseParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final OutputView outputView;
+ private final InputView inputView;
+
+ public StoreController(OutputView outputView, InputView inputView) {
+ this.outputView = outputView;
+ this.inputView = inputView;
+ }
+
+ public void run() {
+ Products products = loadStoreFiles();
+
+ do {
+ displayWelcome(products);
+ List<PurchaseProduct> purchases = handlePurchases(products);
+ PaymentProductList paymentProductList = processPurchases(purchases);
+
+ displayPaymentInfo(paymentProductList);
+ } while (readAdditionalPurchaseConfirmationWithRetry());
+ }
+
+ private void displayWelcome(Products products) {
+ displayWelcomeMessage();
+ displayProductsInfo(products);
+ }
+
+ private Products loadStoreFiles() {
+ PromotionsList promotionsList = loadPromotions();
+ return loadProducts(promotionsList);
+ }
+
+ private PaymentProductList processPurchases(List<PurchaseProduct> purchases) {
+ PaymentProductList paymentProductList = new PaymentProductList();
+ LocalDateTime now = DateTimes.now();
+
+ for (PurchaseProduct purchase : purchases) {
+ processSinglePurchase(paymentProductList, purchase, now);
+ }
+
+ decreaseProductStock(purchases, paymentProductList);
+ applyMembershipDiscountIfConfirmed(paymentProductList);
+ return paymentProductList;
+ }
+
+ private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) {
+ List<Integer> quantities = paymentProductList.getAllProductQuantities();
+ for (int i = 0; i < purchases.size(); i++) {
+ purchases.get(i).reduceProductStock(quantities.get(i));
+ }
+ }
+
+ private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ LocalDateTime now) {
+ if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) {
+ handlePromotionProduct(paymentProductList, purchase);
+ return;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0));
+ }
+
+
+ private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ int remainingStock = purchase.getRemainingStock();
+ if (remainingStock > 0) {
+ handleRemainingStock(paymentProductList, purchase, remainingStock);
+ return;
+ }
+ if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) {
+ handleNonZeroRemainingStock(paymentProductList, purchase);
+ return;
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ int remainingStock) {
+ int quantity = calculateQuantity(purchase, remainingStock);
+
+ if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) {
+ purchase.decrease(quantity);
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1));
+ }
+
+ private int calculateQuantity(PurchaseProduct purchase, int remainingStock) {
+ int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock));
+ return remainingStock + promotionRate;
+ }
+
+ private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ boolean answer = confirmPromotionAddition(purchase.getProductName());
+ int promotionUnits = purchase.getPromotionUnits();
+ if (answer) {
+ purchase.increaseQuantityForPromotion();
+ promotionUnits += 1;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void displayPaymentInfo(PaymentProductList paymentProductList) {
+ List<String> productInfos = paymentProductList.infoProduct();
+ List<String> promotionInfos = paymentProductList.infoPromotion();
+ List<String> finalResults = paymentProductList.finalResult();
+
+ outputView.printPaymentInfoResult(productInfos);
+ outputView.printPromotionInfoResult(promotionInfos);
+ outputView.printFinalResult(finalResults);
+ }
+
+ private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) {
+ if (readMembershipConfirmationWithRetry()) {
+ paymentProductList.applyMembershipDiscount();
+ }
+ }
+
+ private void displayWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ private PromotionsList loadPromotions() {
+ List<List<String>> inputPromotions = inputView.readPromotionsData();
+ List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions);
+ return new PromotionsList(promotionsList1);
+ }
+
+ private Products loadProducts(PromotionsList promotionsList) {
+ List<List<String>> inputProducts = inputView.readProductsData();
+ List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList);
+ return new Products(productList);
+ }
+
+ private void displayProductsInfo(Products products) {
+ outputView.printProductsInfo(products.getAllProductsInfo());
+ }
+
+ private List<PurchaseProduct> handlePurchases(Products products) {
+ while (true) {
+ try {
+ Map<String, Integer> purchases = readAndParsePurchaseInput();
+ return processPurchases(products, purchases);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private Map<String, Integer> readAndParsePurchaseInput() {
+ String input = inputView.readPurchaseInput();
+ return PurchaseParser.parseInputProduct(input);
+ }
+
+ private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) {
+ List<PurchaseProduct> purchaseProducts = new ArrayList<>();
+ for (Map.Entry<String, Integer> entry : purchases.entrySet()) {
+ List<Product> foundProducts = products.findProductByName(entry.getKey());
+ purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue()));
+ }
+ return purchaseProducts;
+ }
+
+ private boolean confirmPromotionNotApplied(String productName, int quantity) {
+ while (true) {
+ try {
+ outputView.printPromotionNotApplied(productName, quantity);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean confirmPromotionAddition(String productName) {
+ while (true) {
+ try {
+ outputView.printPromotionAddition(productName);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readMembershipConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readMembershipConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readAdditionalPurchaseConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readAdditionalPurchaseConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+} | Java | ๋น์ฆ๋์ค ๋ก์ง์ด ์ปจํธ๋กค๋ฌ์ ํฌํจ๋์ด ์๋ ๊ฒ์ ์ด์ํ ๊ฒ ๊ฐ์ต๋๋ค! ์ปจํธ๋กค๋ฌ์ ์๋น์ค๋ฅผ ๋ถ๋ฆฌํ๋ค๋ฉด ๋ ๋์ ์ฝ๋๊ฐ ๋์์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,223 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import store.domain.PaymentProductList;
+import store.domain.Product;
+import store.domain.Products;
+import store.domain.Promotions;
+import store.domain.PromotionsList;
+import store.domain.PurchaseProduct;
+import store.global.util.ProductParser;
+import store.global.util.PromotionParser;
+import store.global.util.PurchaseParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final OutputView outputView;
+ private final InputView inputView;
+
+ public StoreController(OutputView outputView, InputView inputView) {
+ this.outputView = outputView;
+ this.inputView = inputView;
+ }
+
+ public void run() {
+ Products products = loadStoreFiles();
+
+ do {
+ displayWelcome(products);
+ List<PurchaseProduct> purchases = handlePurchases(products);
+ PaymentProductList paymentProductList = processPurchases(purchases);
+
+ displayPaymentInfo(paymentProductList);
+ } while (readAdditionalPurchaseConfirmationWithRetry());
+ }
+
+ private void displayWelcome(Products products) {
+ displayWelcomeMessage();
+ displayProductsInfo(products);
+ }
+
+ private Products loadStoreFiles() {
+ PromotionsList promotionsList = loadPromotions();
+ return loadProducts(promotionsList);
+ }
+
+ private PaymentProductList processPurchases(List<PurchaseProduct> purchases) {
+ PaymentProductList paymentProductList = new PaymentProductList();
+ LocalDateTime now = DateTimes.now();
+
+ for (PurchaseProduct purchase : purchases) {
+ processSinglePurchase(paymentProductList, purchase, now);
+ }
+
+ decreaseProductStock(purchases, paymentProductList);
+ applyMembershipDiscountIfConfirmed(paymentProductList);
+ return paymentProductList;
+ }
+
+ private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) {
+ List<Integer> quantities = paymentProductList.getAllProductQuantities();
+ for (int i = 0; i < purchases.size(); i++) {
+ purchases.get(i).reduceProductStock(quantities.get(i));
+ }
+ }
+
+ private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ LocalDateTime now) {
+ if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) {
+ handlePromotionProduct(paymentProductList, purchase);
+ return;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0));
+ }
+
+
+ private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ int remainingStock = purchase.getRemainingStock();
+ if (remainingStock > 0) {
+ handleRemainingStock(paymentProductList, purchase, remainingStock);
+ return;
+ }
+ if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) {
+ handleNonZeroRemainingStock(paymentProductList, purchase);
+ return;
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ int remainingStock) {
+ int quantity = calculateQuantity(purchase, remainingStock);
+
+ if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) {
+ purchase.decrease(quantity);
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1));
+ }
+
+ private int calculateQuantity(PurchaseProduct purchase, int remainingStock) {
+ int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock));
+ return remainingStock + promotionRate;
+ }
+
+ private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ boolean answer = confirmPromotionAddition(purchase.getProductName());
+ int promotionUnits = purchase.getPromotionUnits();
+ if (answer) {
+ purchase.increaseQuantityForPromotion();
+ promotionUnits += 1;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void displayPaymentInfo(PaymentProductList paymentProductList) {
+ List<String> productInfos = paymentProductList.infoProduct();
+ List<String> promotionInfos = paymentProductList.infoPromotion();
+ List<String> finalResults = paymentProductList.finalResult();
+
+ outputView.printPaymentInfoResult(productInfos);
+ outputView.printPromotionInfoResult(promotionInfos);
+ outputView.printFinalResult(finalResults);
+ }
+
+ private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) {
+ if (readMembershipConfirmationWithRetry()) {
+ paymentProductList.applyMembershipDiscount();
+ }
+ }
+
+ private void displayWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ private PromotionsList loadPromotions() {
+ List<List<String>> inputPromotions = inputView.readPromotionsData();
+ List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions);
+ return new PromotionsList(promotionsList1);
+ }
+
+ private Products loadProducts(PromotionsList promotionsList) {
+ List<List<String>> inputProducts = inputView.readProductsData();
+ List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList);
+ return new Products(productList);
+ }
+
+ private void displayProductsInfo(Products products) {
+ outputView.printProductsInfo(products.getAllProductsInfo());
+ }
+
+ private List<PurchaseProduct> handlePurchases(Products products) {
+ while (true) {
+ try {
+ Map<String, Integer> purchases = readAndParsePurchaseInput();
+ return processPurchases(products, purchases);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private Map<String, Integer> readAndParsePurchaseInput() {
+ String input = inputView.readPurchaseInput();
+ return PurchaseParser.parseInputProduct(input);
+ }
+
+ private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) {
+ List<PurchaseProduct> purchaseProducts = new ArrayList<>();
+ for (Map.Entry<String, Integer> entry : purchases.entrySet()) {
+ List<Product> foundProducts = products.findProductByName(entry.getKey());
+ purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue()));
+ }
+ return purchaseProducts;
+ }
+
+ private boolean confirmPromotionNotApplied(String productName, int quantity) {
+ while (true) {
+ try {
+ outputView.printPromotionNotApplied(productName, quantity);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean confirmPromotionAddition(String productName) {
+ while (true) {
+ try {
+ outputView.printPromotionAddition(productName);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readMembershipConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readMembershipConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readAdditionalPurchaseConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readAdditionalPurchaseConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+} | Java | ์ด๋ฐ ๋ถ๋ถ๋ remainingStock์ด๋ผ๋ ๋ก์ปฌ ๋ณ์๊ฐ ์ฌ์ค purchase์ ํ๋๋๊น if๋ฌธ์ &&๋ฅผ ์์ ๊ณ purchase์ ํ๋์ ๋ฉ์์ง๋ฅผ ๋ณด๋ด๋ ์ชฝ์ผ๋ก ๊ตฌํํ๋ค๋ฉด ๊ฐ๋
์ฑ์ด ํจ์ฌ ์ข์์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,39 @@
+package store.domain.product;
+
+import static store.global.constant.ErrorMessage.INVALID_PRICE_NUMERIC;
+import static store.global.constant.ErrorMessage.INVALID_PRICE_OUT_OF_RANGE;
+import static store.global.validation.CommonValidator.validateNotNumeric;
+
+import java.text.DecimalFormat;
+
+public class Price {
+
+ private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("###,###");
+ private static final int MINIMUM_PRICE = 1;
+ private static final int MAXIMUM_PRICE = 1_000_000;
+ private static final String UNIT = "์";
+
+ private final int price;
+
+ public Price(final String inputPrice) {
+ validateNotNumeric(inputPrice, INVALID_PRICE_NUMERIC);
+ int price = Integer.parseInt(inputPrice);
+ validateRange(price);
+ this.price = price;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ @Override
+ public String toString() {
+ return DECIMAL_FORMAT.format(price) + UNIT;
+ }
+
+ private void validateRange(final int price) {
+ if (price < MINIMUM_PRICE || price > MAXIMUM_PRICE) {
+ throw new IllegalArgumentException(INVALID_PRICE_OUT_OF_RANGE.getMessage());
+ }
+ }
+} | Java | Price๊ฐ์ฒด์ ํ์๊ฐ ๋ฐ๋ก ์๋ ๊ฒ ๊ฐ์ ๋ณด์ด๋๋ฐ, ๋จ์ํ "๊ฐ๊ฒฉ"์ด๋ผ๋ ๋๋ฉ์ธ ์ ์ฝ ๊ฒ์ฆ๊ณผ, ๊ด๋ จ๋ ์์๋ค์ ๋ฌถ์ด๋๊ธฐ ์ํด ์ฌ์ฉํ์ ๊ฑด๊ฐ์? |
@@ -0,0 +1,77 @@
+package store.global.util;
+
+import static store.global.constant.ErrorMessage.INVALID_INPUT_PURCHASE;
+import static store.global.validation.CommonValidator.validateBlank;
+import static store.global.validation.CommonValidator.validateNotNumeric;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class PurchaseParser {
+
+ private static final Pattern PRODUCT_PATTERN = Pattern.compile("^\\[(.*?)-(\\d+)]$");
+ private static final Pattern INVALID_NAME_PATTERN = Pattern.compile(".*[-\\[\\]].*");
+
+ public static Map<String, Integer> parseInputProduct(String input) {
+ validateInput(input);
+
+ String[] splitProducts = splitInput(input);
+ LinkedHashMap<String, Integer> product = new LinkedHashMap<>();
+
+ for (String productString : splitProducts) {
+ processProductString(productString, product);
+ }
+ return product;
+ }
+
+ private static String[] splitInput(String input) {
+ return input.split(",");
+ }
+
+ private static void processProductString(String productString, Map<String, Integer> product) {
+ String name = extractProductName(productString);
+ String quantity = extractProductQuantity(productString);
+ addProductToMap(name, quantity, product);
+ }
+
+ private static String extractProductName(String productString) {
+ Matcher matcher = matchProductPattern(productString);
+ String name = matcher.group(1);
+ validateName(name);
+ return name;
+ }
+
+ private static String extractProductQuantity(String productString) {
+ Matcher matcher = matchProductPattern(productString);
+ String quantity = matcher.group(2);
+ validateNotNumeric(quantity, INVALID_INPUT_PURCHASE);
+ return quantity;
+ }
+
+ private static Matcher matchProductPattern(String productString) {
+ Matcher matcher = PRODUCT_PATTERN.matcher(productString);
+ if (!matcher.find()) {
+ throw new IllegalArgumentException(INVALID_INPUT_PURCHASE.getMessage());
+ }
+ return matcher;
+ }
+
+ private static void addProductToMap(String name, String quantity, Map<String, Integer> product) {
+ product.merge(name, Integer.parseInt(quantity), Integer::sum);
+ }
+
+ private static void validateName(String name) {
+ validateBlank(name, INVALID_INPUT_PURCHASE);
+ if (INVALID_NAME_PATTERN.matcher(name).matches()) {
+ throw new IllegalArgumentException(INVALID_INPUT_PURCHASE.getMessage());
+ }
+ }
+
+ private static void validateInput(String input) {
+ if (!input.matches("^\\[.*]$")) {
+ throw new IllegalArgumentException(INVALID_INPUT_PURCHASE.getMessage());
+ }
+ }
+} | Java | ๊ณตํต ํผ๋๋ฐฑ์์ ๋ณ์ ์ด๋ฆ์ ์๋ฃํ์ ๋ฃ์ง ๋ง๋ผ๊ณ ํ๋๋ผ๊ตฌ์! |
@@ -0,0 +1,15 @@
+package store.domain.product;
+
+public class Name {
+
+ private final String name;
+
+ public Name(final String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+} | Java | Nameํด๋์ค์ ์ฉ๋๊ฐ ๊ถ๊ธํด์! |
@@ -0,0 +1,223 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import store.domain.PaymentProductList;
+import store.domain.Product;
+import store.domain.Products;
+import store.domain.Promotions;
+import store.domain.PromotionsList;
+import store.domain.PurchaseProduct;
+import store.global.util.ProductParser;
+import store.global.util.PromotionParser;
+import store.global.util.PurchaseParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final OutputView outputView;
+ private final InputView inputView;
+
+ public StoreController(OutputView outputView, InputView inputView) {
+ this.outputView = outputView;
+ this.inputView = inputView;
+ }
+
+ public void run() {
+ Products products = loadStoreFiles();
+
+ do {
+ displayWelcome(products);
+ List<PurchaseProduct> purchases = handlePurchases(products);
+ PaymentProductList paymentProductList = processPurchases(purchases);
+
+ displayPaymentInfo(paymentProductList);
+ } while (readAdditionalPurchaseConfirmationWithRetry());
+ }
+
+ private void displayWelcome(Products products) {
+ displayWelcomeMessage();
+ displayProductsInfo(products);
+ }
+
+ private Products loadStoreFiles() {
+ PromotionsList promotionsList = loadPromotions();
+ return loadProducts(promotionsList);
+ }
+
+ private PaymentProductList processPurchases(List<PurchaseProduct> purchases) {
+ PaymentProductList paymentProductList = new PaymentProductList();
+ LocalDateTime now = DateTimes.now();
+
+ for (PurchaseProduct purchase : purchases) {
+ processSinglePurchase(paymentProductList, purchase, now);
+ }
+
+ decreaseProductStock(purchases, paymentProductList);
+ applyMembershipDiscountIfConfirmed(paymentProductList);
+ return paymentProductList;
+ }
+
+ private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) {
+ List<Integer> quantities = paymentProductList.getAllProductQuantities();
+ for (int i = 0; i < purchases.size(); i++) {
+ purchases.get(i).reduceProductStock(quantities.get(i));
+ }
+ }
+
+ private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ LocalDateTime now) {
+ if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) {
+ handlePromotionProduct(paymentProductList, purchase);
+ return;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0));
+ }
+
+
+ private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ int remainingStock = purchase.getRemainingStock();
+ if (remainingStock > 0) {
+ handleRemainingStock(paymentProductList, purchase, remainingStock);
+ return;
+ }
+ if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) {
+ handleNonZeroRemainingStock(paymentProductList, purchase);
+ return;
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ int remainingStock) {
+ int quantity = calculateQuantity(purchase, remainingStock);
+
+ if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) {
+ purchase.decrease(quantity);
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1));
+ }
+
+ private int calculateQuantity(PurchaseProduct purchase, int remainingStock) {
+ int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock));
+ return remainingStock + promotionRate;
+ }
+
+ private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ boolean answer = confirmPromotionAddition(purchase.getProductName());
+ int promotionUnits = purchase.getPromotionUnits();
+ if (answer) {
+ purchase.increaseQuantityForPromotion();
+ promotionUnits += 1;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void displayPaymentInfo(PaymentProductList paymentProductList) {
+ List<String> productInfos = paymentProductList.infoProduct();
+ List<String> promotionInfos = paymentProductList.infoPromotion();
+ List<String> finalResults = paymentProductList.finalResult();
+
+ outputView.printPaymentInfoResult(productInfos);
+ outputView.printPromotionInfoResult(promotionInfos);
+ outputView.printFinalResult(finalResults);
+ }
+
+ private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) {
+ if (readMembershipConfirmationWithRetry()) {
+ paymentProductList.applyMembershipDiscount();
+ }
+ }
+
+ private void displayWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ private PromotionsList loadPromotions() {
+ List<List<String>> inputPromotions = inputView.readPromotionsData();
+ List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions);
+ return new PromotionsList(promotionsList1);
+ }
+
+ private Products loadProducts(PromotionsList promotionsList) {
+ List<List<String>> inputProducts = inputView.readProductsData();
+ List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList);
+ return new Products(productList);
+ }
+
+ private void displayProductsInfo(Products products) {
+ outputView.printProductsInfo(products.getAllProductsInfo());
+ }
+
+ private List<PurchaseProduct> handlePurchases(Products products) {
+ while (true) {
+ try {
+ Map<String, Integer> purchases = readAndParsePurchaseInput();
+ return processPurchases(products, purchases);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private Map<String, Integer> readAndParsePurchaseInput() {
+ String input = inputView.readPurchaseInput();
+ return PurchaseParser.parseInputProduct(input);
+ }
+
+ private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) {
+ List<PurchaseProduct> purchaseProducts = new ArrayList<>();
+ for (Map.Entry<String, Integer> entry : purchases.entrySet()) {
+ List<Product> foundProducts = products.findProductByName(entry.getKey());
+ purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue()));
+ }
+ return purchaseProducts;
+ }
+
+ private boolean confirmPromotionNotApplied(String productName, int quantity) {
+ while (true) {
+ try {
+ outputView.printPromotionNotApplied(productName, quantity);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean confirmPromotionAddition(String productName) {
+ while (true) {
+ try {
+ outputView.printPromotionAddition(productName);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readMembershipConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readMembershipConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readAdditionalPurchaseConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readAdditionalPurchaseConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+} | Java | ๊ฐ์ธ์ ์ผ๋ก๋ ์ปจํธ๋กค๋ฌ๊ฐ ๋ถ๋ด์ด ์กฐ๊ธ ํฐ ๊ฒ ๊ฐ์์!
๋น์ฆ๋์ค ๋ก์ง์ ์์ํ์ง์๊ณ ์ผ๋ถ๋ฅผ ๋ด๋นํ๊ณ ์๋ค๋ ๋๋์ด ๋ค์ด์. ์ด๋ป๊ฒ ์๊ฐํ์๋์?! |
@@ -0,0 +1,89 @@
+package store.domain;
+
+import static store.global.constant.MessageConstant.FORMAT;
+
+import java.text.DecimalFormat;
+import java.util.ArrayList;
+import java.util.List;
+
+public class PaymentProductList {
+
+ private static final DecimalFormat PRICE_FORMAT = new DecimalFormat("###,###");
+
+ private List<PaymentProduct> paymentProducts;
+ private int totalPrice = 0;
+ private int totalPromotion = 0;
+ private int membershipPrice = 0;
+
+ public PaymentProductList() {
+ this.paymentProducts = new ArrayList<>();
+ }
+
+ public void addPaymentProduct(PaymentProduct product) {
+ paymentProducts.add(product);
+ }
+
+ public List<Integer> getAllProductQuantities() {
+ return paymentProducts.stream()
+ .map(PaymentProduct::getQuantity)
+ .toList();
+ }
+
+ public List<String> infoProduct() {
+ return paymentProducts.stream()
+ .map(PaymentProduct::toString)
+ .toList();
+ }
+
+ public List<String> infoPromotion() {
+ return paymentProducts.stream()
+ .filter(PaymentProduct::isPromotion)
+ .map(PaymentProduct::buildPromotion)
+ .toList();
+ }
+
+ public List<String> finalResult() {
+ List<String> result = new ArrayList<>();
+ result.add(String.format(FORMAT.getMessage(), "์ด๊ตฌ๋งค์ก", totalQuantity(), totalPrice()));
+ result.add(String.format(FORMAT.getMessage(), "ํ์ฌํ ์ธ", "", totalPromotionPrice()));
+ result.add(String.format(FORMAT.getMessage(), "๋ฉค๋ฒ์ญํ ์ธ", "", "-" + PRICE_FORMAT.format(membershipPrice)));
+ result.add(String.format(FORMAT.getMessage(), "๋ด์ค๋", "",
+ PRICE_FORMAT.format(totalPrice - totalPromotion - membershipPrice)));
+
+ return result;
+ }
+
+ private int totalQuantity() {
+ return paymentProducts.stream()
+ .mapToInt(PaymentProduct::getQuantity)
+ .sum();
+ }
+
+ private String totalPrice() {
+ this.totalPrice = paymentProducts.stream()
+ .mapToInt(PaymentProduct::getTotalPrice)
+ .sum();
+ return PRICE_FORMAT.format(totalPrice);
+ }
+
+ private String totalPromotionPrice() {
+ this.totalPromotion = paymentProducts.stream()
+ .filter(PaymentProduct::isPromotion)
+ .mapToInt(PaymentProduct::getPromotionPrice)
+ .sum();
+ return "-" + PRICE_FORMAT.format(totalPromotion);
+ }
+
+ public void applyMembershipDiscount() {
+ int price = (int) (paymentProducts.stream()
+ .filter(product -> !product.isPromotion())
+ .mapToInt(PaymentProduct::getTotalPrice)
+ .sum() * 0.3);
+
+ if (price > 8000) {
+ price = 8000;
+ }
+
+ this.membershipPrice = price;
+ }
+} | Java | ์ต๋ ํ ์ธ ๊ธ์ก์ด ๋์ด์ฐ๋์ง ํ์ธํ๋ ๋ฉ์๋๋ก ๋ฐ๋ก ๋ถ๋ฆฌ๋ฅผ ํ์ผ๋ฉด ๋ ์ข์์ ๊ฒ ๊ฐ๋ค๋ ์๊ฐ์ด ๋ค์์ด์! |
@@ -0,0 +1,46 @@
+package store.domain;
+
+import java.time.LocalDate;
+
+public class Promotions {
+
+ private final String name;
+ private final int buy;
+ private final int get;
+ private final LocalDate startDate;
+ private final LocalDate endDate;
+
+ public Promotions(String name, String buy, String get, String startDate, String endDate) {
+ this.name = name;
+ this.buy = Integer.parseInt(buy);
+ this.get = Integer.parseInt(get);
+ this.startDate = LocalDate.parse(startDate);
+ this.endDate = LocalDate.parse(endDate);
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+
+ public boolean hasName(String name) {
+ return this.name.equals(name);
+ }
+
+ public boolean isPromotionApplicable(int quantity) {
+ return calculateRemainingItems(quantity) >= get;
+ }
+
+ public int calculateRemainingItems(int quantity) {
+ return quantity % (buy + get);
+ }
+
+ public int calculatePromotionUnits(int quantity) {
+ return quantity / (buy + get);
+ }
+
+ public boolean isWithinPromotionPeriod(LocalDate date) {
+ return (date.isEqual(startDate) || date.isAfter(startDate)) &&
+ (date.isEqual(endDate) || date.isBefore(endDate));
+ }
+} | Java | ํน์, Name ํ์
์ผ๋ก ํ์ง ์์ผ์ ์ด์ ๊ฐ ์๋์ฉ?? |
@@ -0,0 +1,223 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import store.domain.PaymentProductList;
+import store.domain.Product;
+import store.domain.Products;
+import store.domain.Promotions;
+import store.domain.PromotionsList;
+import store.domain.PurchaseProduct;
+import store.global.util.ProductParser;
+import store.global.util.PromotionParser;
+import store.global.util.PurchaseParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final OutputView outputView;
+ private final InputView inputView;
+
+ public StoreController(OutputView outputView, InputView inputView) {
+ this.outputView = outputView;
+ this.inputView = inputView;
+ }
+
+ public void run() {
+ Products products = loadStoreFiles();
+
+ do {
+ displayWelcome(products);
+ List<PurchaseProduct> purchases = handlePurchases(products);
+ PaymentProductList paymentProductList = processPurchases(purchases);
+
+ displayPaymentInfo(paymentProductList);
+ } while (readAdditionalPurchaseConfirmationWithRetry());
+ }
+
+ private void displayWelcome(Products products) {
+ displayWelcomeMessage();
+ displayProductsInfo(products);
+ }
+
+ private Products loadStoreFiles() {
+ PromotionsList promotionsList = loadPromotions();
+ return loadProducts(promotionsList);
+ }
+
+ private PaymentProductList processPurchases(List<PurchaseProduct> purchases) {
+ PaymentProductList paymentProductList = new PaymentProductList();
+ LocalDateTime now = DateTimes.now();
+
+ for (PurchaseProduct purchase : purchases) {
+ processSinglePurchase(paymentProductList, purchase, now);
+ }
+
+ decreaseProductStock(purchases, paymentProductList);
+ applyMembershipDiscountIfConfirmed(paymentProductList);
+ return paymentProductList;
+ }
+
+ private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) {
+ List<Integer> quantities = paymentProductList.getAllProductQuantities();
+ for (int i = 0; i < purchases.size(); i++) {
+ purchases.get(i).reduceProductStock(quantities.get(i));
+ }
+ }
+
+ private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ LocalDateTime now) {
+ if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) {
+ handlePromotionProduct(paymentProductList, purchase);
+ return;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0));
+ }
+
+
+ private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ int remainingStock = purchase.getRemainingStock();
+ if (remainingStock > 0) {
+ handleRemainingStock(paymentProductList, purchase, remainingStock);
+ return;
+ }
+ if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) {
+ handleNonZeroRemainingStock(paymentProductList, purchase);
+ return;
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ int remainingStock) {
+ int quantity = calculateQuantity(purchase, remainingStock);
+
+ if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) {
+ purchase.decrease(quantity);
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1));
+ }
+
+ private int calculateQuantity(PurchaseProduct purchase, int remainingStock) {
+ int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock));
+ return remainingStock + promotionRate;
+ }
+
+ private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ boolean answer = confirmPromotionAddition(purchase.getProductName());
+ int promotionUnits = purchase.getPromotionUnits();
+ if (answer) {
+ purchase.increaseQuantityForPromotion();
+ promotionUnits += 1;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void displayPaymentInfo(PaymentProductList paymentProductList) {
+ List<String> productInfos = paymentProductList.infoProduct();
+ List<String> promotionInfos = paymentProductList.infoPromotion();
+ List<String> finalResults = paymentProductList.finalResult();
+
+ outputView.printPaymentInfoResult(productInfos);
+ outputView.printPromotionInfoResult(promotionInfos);
+ outputView.printFinalResult(finalResults);
+ }
+
+ private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) {
+ if (readMembershipConfirmationWithRetry()) {
+ paymentProductList.applyMembershipDiscount();
+ }
+ }
+
+ private void displayWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ private PromotionsList loadPromotions() {
+ List<List<String>> inputPromotions = inputView.readPromotionsData();
+ List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions);
+ return new PromotionsList(promotionsList1);
+ }
+
+ private Products loadProducts(PromotionsList promotionsList) {
+ List<List<String>> inputProducts = inputView.readProductsData();
+ List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList);
+ return new Products(productList);
+ }
+
+ private void displayProductsInfo(Products products) {
+ outputView.printProductsInfo(products.getAllProductsInfo());
+ }
+
+ private List<PurchaseProduct> handlePurchases(Products products) {
+ while (true) {
+ try {
+ Map<String, Integer> purchases = readAndParsePurchaseInput();
+ return processPurchases(products, purchases);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private Map<String, Integer> readAndParsePurchaseInput() {
+ String input = inputView.readPurchaseInput();
+ return PurchaseParser.parseInputProduct(input);
+ }
+
+ private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) {
+ List<PurchaseProduct> purchaseProducts = new ArrayList<>();
+ for (Map.Entry<String, Integer> entry : purchases.entrySet()) {
+ List<Product> foundProducts = products.findProductByName(entry.getKey());
+ purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue()));
+ }
+ return purchaseProducts;
+ }
+
+ private boolean confirmPromotionNotApplied(String productName, int quantity) {
+ while (true) {
+ try {
+ outputView.printPromotionNotApplied(productName, quantity);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean confirmPromotionAddition(String productName) {
+ while (true) {
+ try {
+ outputView.printPromotionAddition(productName);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readMembershipConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readMembershipConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readAdditionalPurchaseConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readAdditionalPurchaseConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+} | Java | ์๋
ํ์ธ์!
๊ฐ์ฒด๋ฅผ ๊ฐ์ฒด๋ต๊ฒ ํ์ฉํ๊ธฐ ์ํด, ๋ฉ์์ง๋ฅผ ์ ๋ฌํด ๊ฐ์ฒด๊ฐ ์ค์ค๋ก ์์
์ ์ํํ๋๋ก ํ๋ ๊ฒ์ด ์ข๋ค๋ ๊ณตํต ํผ๋๋ฐฑ์ ํ์ธํ์ต๋๋ค.
ํ์ฌ ๋ฉ์๋๋ ์๋(quantity)์ 1์ฉ ์ฆ๊ฐ์ํค๋ ๋จ์ํ ๋ก์ง์ ๊ฐ์ง๊ณ ์๋๋ฐ์,
์ด ๊ฒฝ์ฐ ๋งค๋ฒ ํธ์ถํ ๋๋ง๋ค ์๋์ 1์ฉ ์ฆ๊ฐ์ํค๋ ๋์ , ํ๋ผ๋ฏธํฐ๋ก ์ฆ๊ฐํ ์๋์ ์ ๋ฌํ๊ณ ์ด๋ฅผ ๋ฐ์ํ๋ ๋ฐฉ๋ฒ๋ ๊ณ ๋ คํด๋ณผ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค.
```
public void increaseQuantity(int number) {
this.quantity += number;
}
```
ํ์ง๋ง ์ด์ ๋์์ ๋๋ฌด ๋จ์ํ ๋ก์ง์๋ ๋ฉ์์ง๋ฅผ ํตํด ์์
์ ์ํํด์ผ ํ๋์ง ๊ณ ๋ฏผ์ด ๋๋ค์..
ํน์ ์ด๋ป๊ฒ ์๊ฐํ์๋์ง ๊ถ๊ธํฉ๋๋ค. |
@@ -0,0 +1,39 @@
+package store.domain.product;
+
+import static store.global.constant.ErrorMessage.INVALID_PRICE_NUMERIC;
+import static store.global.constant.ErrorMessage.INVALID_PRICE_OUT_OF_RANGE;
+import static store.global.validation.CommonValidator.validateNotNumeric;
+
+import java.text.DecimalFormat;
+
+public class Price {
+
+ private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("###,###");
+ private static final int MINIMUM_PRICE = 1;
+ private static final int MAXIMUM_PRICE = 1_000_000;
+ private static final String UNIT = "์";
+
+ private final int price;
+
+ public Price(final String inputPrice) {
+ validateNotNumeric(inputPrice, INVALID_PRICE_NUMERIC);
+ int price = Integer.parseInt(inputPrice);
+ validateRange(price);
+ this.price = price;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ @Override
+ public String toString() {
+ return DECIMAL_FORMAT.format(price) + UNIT;
+ }
+
+ private void validateRange(final int price) {
+ if (price < MINIMUM_PRICE || price > MAXIMUM_PRICE) {
+ throw new IllegalArgumentException(INVALID_PRICE_OUT_OF_RANGE.getMessage());
+ }
+ }
+} | Java | ๋์ผํ ํ์์ ์์๋ฅผ Quantity์์๋ ๋ณด์์ด์!
ํน์, ๊ณตํต์ ์ผ๋ก ์ฌ์ฉํ๋ ์์๋ ๋ฐ๋ก ๋ถ๋ฆฌ๋ฅผ ํ์๋ ๊ฒ์ ์ด๋ป๊ฒ ์๊ฐํ์๋์? |
@@ -0,0 +1,58 @@
+package store.view;
+
+import static store.global.constant.MessageConstant.FORMAT;
+import static store.global.constant.MessageConstant.NEW_LINE;
+import static store.global.constant.MessageConstant.OUTPUT_HEADER_PROMOTION;
+import static store.global.constant.MessageConstant.OUTPUT_HEADER_SEPARATOR;
+import static store.global.constant.MessageConstant.OUTPUT_HEADER_STORE;
+import static store.global.constant.MessageConstant.OUTPUT_PRODUCT_INFO;
+import static store.global.constant.MessageConstant.OUTPUT_PRODUCT_PREFIX;
+import static store.global.constant.MessageConstant.OUTPUT_PROMOTION_ADD;
+import static store.global.constant.MessageConstant.OUTPUT_PROMOTION_NOT_APPLIED;
+import static store.global.constant.MessageConstant.OUTPUT_WELCOME;
+
+import java.util.List;
+
+public class OutputView {
+
+ public void printWelcomeMessage() {
+ System.out.println(OUTPUT_WELCOME.getMessage());
+ System.out.println(OUTPUT_PRODUCT_INFO.getMessage() + NEW_LINE.getMessage());
+ }
+
+ public void printProductsInfo(List<String> products) {
+ products.forEach(product ->
+ System.out.println(OUTPUT_PRODUCT_PREFIX.getMessage() + product)
+ );
+ }
+
+ public void printPromotionNotApplied(String name, int quantity) {
+ System.out.printf(NEW_LINE.getMessage() + OUTPUT_PROMOTION_NOT_APPLIED.getMessage() + NEW_LINE.getMessage(),
+ name, quantity);
+ }
+
+ public void printPromotionAddition(String name) {
+ System.out.printf(NEW_LINE.getMessage() + OUTPUT_PROMOTION_ADD.getMessage() + NEW_LINE.getMessage(), name);
+ }
+
+ public void printPaymentInfoResult(List<String> infos) {
+ System.out.printf(NEW_LINE.getMessage());
+ System.out.println(OUTPUT_HEADER_STORE.getMessage());
+ System.out.printf(FORMAT.getMessage() + NEW_LINE.getMessage(), "์ํ๋ช
", "์๋", "๊ธ์ก");
+ infos.forEach(System.out::println);
+ }
+
+ public void printPromotionInfoResult(List<String> strings) {
+ System.out.println(OUTPUT_HEADER_PROMOTION.getMessage());
+ strings.forEach(System.out::println);
+ }
+
+ public void printFinalResult(List<String> result) {
+ System.out.println(OUTPUT_HEADER_SEPARATOR.getMessage());
+ result.forEach(System.out::println);
+ }
+
+ public void printErrorMessage(String message) {
+ System.out.println(message);
+ }
+} | Java | ์๋
ํ์ธ์!
ํน์ ์๋์ ๊ฐ์ด ํฌ๋งท์ ์ค์ ํ์
จ์ ๋, ๋์ด์ฐ๊ธฐ ๋๋ฌธ์ ์ถ๋ ฅ์ด ์ฌ๋ฐ๋ฅด๊ฒ ์ ๋ ฌ์ด ๊ฐ๋ฅํ์
จ๋์?
4์ฃผ ์ฐจ ์งํํ๋ฉด์ ์์์ฆ ์ถ๋ ฅ ๋ถ๋ถ์ ๋ณด๊ธฐ ์ข๊ฒ ์ ๋ฆฌํ๋ ๊ฒ์ด ์๊ตฌ์ฌํญ์ด์์ด์ ๋ง์ด ์ฐพ์๋ดค์ต๋๋ค!
๊ทธ ๊ณผ์ ์์ ์๊ฒ ๋ ์ ์, ํ๊ตญ์ด๋ 2๊ธ์๋ก ์ทจ๊ธ๋์ง๋ง, ๋์ด์ฐ๊ธฐ์ ์์ด๋ 1๊ธ์๋ก ์ทจ๊ธ๋๋ค๋ ๊ฒ์
๋๋ค. ๊ทธ๋์ ๋์ด์ฐ๊ธฐ๋ฅผ ํ๊ธ์ฒ๋ผ 2๊ธ์ ์ญํ ์ ํ ์ ์๋ ๋ฐฉ๋ฒ์ด ์์๊น ๊ณ ๋ฏผํ๋ค๊ฐ, \u3000 (์ ๋์ฝ๋ ๊ณต๋ฐฑ)์ ์๊ฒ ๋์์ต๋๋ค!
์๋ฅผ ๋ค์ด, ์๋์ ๊ฐ์ด ์ฌ์ฉํ ์ ์์ต๋๋ค:
`String name = String.format("%-14s", "์ด๊ตฌ๋งค์ก").replace(" ", "\u3000");`
์ด ๋ฐฉ๋ฒ์ ์ฌ์ฉํ๋ฉด ํ๊ธ์ฒ๋ผ ๋์ด์ฐ๊ธฐ๋ฅผ 2๊ธ์ ์ทจ๊ธํ ์ ์์ด์ ์ ๋ ฌ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์ต๋๋ค! ๐ |
@@ -0,0 +1,89 @@
+package store.domain;
+
+import static store.global.constant.MessageConstant.FORMAT;
+
+import java.text.DecimalFormat;
+import java.util.ArrayList;
+import java.util.List;
+
+public class PaymentProductList {
+
+ private static final DecimalFormat PRICE_FORMAT = new DecimalFormat("###,###");
+
+ private List<PaymentProduct> paymentProducts;
+ private int totalPrice = 0;
+ private int totalPromotion = 0;
+ private int membershipPrice = 0;
+
+ public PaymentProductList() {
+ this.paymentProducts = new ArrayList<>();
+ }
+
+ public void addPaymentProduct(PaymentProduct product) {
+ paymentProducts.add(product);
+ }
+
+ public List<Integer> getAllProductQuantities() {
+ return paymentProducts.stream()
+ .map(PaymentProduct::getQuantity)
+ .toList();
+ }
+
+ public List<String> infoProduct() {
+ return paymentProducts.stream()
+ .map(PaymentProduct::toString)
+ .toList();
+ }
+
+ public List<String> infoPromotion() {
+ return paymentProducts.stream()
+ .filter(PaymentProduct::isPromotion)
+ .map(PaymentProduct::buildPromotion)
+ .toList();
+ }
+
+ public List<String> finalResult() {
+ List<String> result = new ArrayList<>();
+ result.add(String.format(FORMAT.getMessage(), "์ด๊ตฌ๋งค์ก", totalQuantity(), totalPrice()));
+ result.add(String.format(FORMAT.getMessage(), "ํ์ฌํ ์ธ", "", totalPromotionPrice()));
+ result.add(String.format(FORMAT.getMessage(), "๋ฉค๋ฒ์ญํ ์ธ", "", "-" + PRICE_FORMAT.format(membershipPrice)));
+ result.add(String.format(FORMAT.getMessage(), "๋ด์ค๋", "",
+ PRICE_FORMAT.format(totalPrice - totalPromotion - membershipPrice)));
+
+ return result;
+ }
+
+ private int totalQuantity() {
+ return paymentProducts.stream()
+ .mapToInt(PaymentProduct::getQuantity)
+ .sum();
+ }
+
+ private String totalPrice() {
+ this.totalPrice = paymentProducts.stream()
+ .mapToInt(PaymentProduct::getTotalPrice)
+ .sum();
+ return PRICE_FORMAT.format(totalPrice);
+ }
+
+ private String totalPromotionPrice() {
+ this.totalPromotion = paymentProducts.stream()
+ .filter(PaymentProduct::isPromotion)
+ .mapToInt(PaymentProduct::getPromotionPrice)
+ .sum();
+ return "-" + PRICE_FORMAT.format(totalPromotion);
+ }
+
+ public void applyMembershipDiscount() {
+ int price = (int) (paymentProducts.stream()
+ .filter(product -> !product.isPromotion())
+ .mapToInt(PaymentProduct::getTotalPrice)
+ .sum() * 0.3);
+
+ if (price > 8000) {
+ price = 8000;
+ }
+
+ this.membershipPrice = price;
+ }
+} | Java | ์๋
ํ์ธ์!
์ ๋ ๊ณตํต ํผ๋๋ฐฑ์์ ๋๋ฉ์ธ ๊ฐ์ฒด๋ ์ถ๋ ฅ๊ณผ ๊ด๋ จ๋ ๋ก์ง์ ์ต๋ํ ๋ฐฐ์ ํ๊ณ ,
ํ์ํ ๊ฒฝ์ฐ toString์ ์ค๋ฒ๋ผ์ด๋ํ๋ ์ ๋๋ก ์ ํํ๋ ๊ฒ์ด ์ข๋ค๊ณ ๋ณธ ๊ฒ ๊ฐ์ต๋๋ค.
ํ์ฌ ํด๋น ๋ถ๋ถ์ ๋๋ฉ์ธ์์ ์ถ๋ ฅ ๋ก์ง์ ์ฒ๋ฆฌํ๊ณ ์๋ ๊ฒ์ผ๋ก ๋ณด์ฌ์!
view์์ ์ฒ๋ฆฌํ๋ ๋ฐฉ์์ด ๋ ์ข์ ๊ฒ ๊ฐ์๋ฐ ์ด๋ป๊ฒ ์๊ฐํ์๋์? |
@@ -0,0 +1,223 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import store.domain.PaymentProductList;
+import store.domain.Product;
+import store.domain.Products;
+import store.domain.Promotions;
+import store.domain.PromotionsList;
+import store.domain.PurchaseProduct;
+import store.global.util.ProductParser;
+import store.global.util.PromotionParser;
+import store.global.util.PurchaseParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreController {
+ private final OutputView outputView;
+ private final InputView inputView;
+
+ public StoreController(OutputView outputView, InputView inputView) {
+ this.outputView = outputView;
+ this.inputView = inputView;
+ }
+
+ public void run() {
+ Products products = loadStoreFiles();
+
+ do {
+ displayWelcome(products);
+ List<PurchaseProduct> purchases = handlePurchases(products);
+ PaymentProductList paymentProductList = processPurchases(purchases);
+
+ displayPaymentInfo(paymentProductList);
+ } while (readAdditionalPurchaseConfirmationWithRetry());
+ }
+
+ private void displayWelcome(Products products) {
+ displayWelcomeMessage();
+ displayProductsInfo(products);
+ }
+
+ private Products loadStoreFiles() {
+ PromotionsList promotionsList = loadPromotions();
+ return loadProducts(promotionsList);
+ }
+
+ private PaymentProductList processPurchases(List<PurchaseProduct> purchases) {
+ PaymentProductList paymentProductList = new PaymentProductList();
+ LocalDateTime now = DateTimes.now();
+
+ for (PurchaseProduct purchase : purchases) {
+ processSinglePurchase(paymentProductList, purchase, now);
+ }
+
+ decreaseProductStock(purchases, paymentProductList);
+ applyMembershipDiscountIfConfirmed(paymentProductList);
+ return paymentProductList;
+ }
+
+ private void decreaseProductStock(List<PurchaseProduct> purchases, PaymentProductList paymentProductList) {
+ List<Integer> quantities = paymentProductList.getAllProductQuantities();
+ for (int i = 0; i < purchases.size(); i++) {
+ purchases.get(i).reduceProductStock(quantities.get(i));
+ }
+ }
+
+ private void processSinglePurchase(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ LocalDateTime now) {
+ if (purchase.hasPromotionProduct() && purchase.isWithinPromotionPeriod(now)) {
+ handlePromotionProduct(paymentProductList, purchase);
+ return;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(0));
+ }
+
+
+ private void handlePromotionProduct(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ int remainingStock = purchase.getRemainingStock();
+ if (remainingStock > 0) {
+ handleRemainingStock(paymentProductList, purchase, remainingStock);
+ return;
+ }
+ if (remainingStock < 0 && purchase.isPromotionAdditionalProduct()) {
+ handleNonZeroRemainingStock(paymentProductList, purchase);
+ return;
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void handleRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase,
+ int remainingStock) {
+ int quantity = calculateQuantity(purchase, remainingStock);
+
+ if (!confirmPromotionNotApplied(purchase.getProductName(), quantity)) {
+ purchase.decrease(quantity);
+ }
+ int promotionUnits = purchase.getPromotionUnits();
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits - 1));
+ }
+
+ private int calculateQuantity(PurchaseProduct purchase, int remainingStock) {
+ int promotionRate = purchase.getPromotionRate(Math.abs(remainingStock));
+ return remainingStock + promotionRate;
+ }
+
+ private void handleNonZeroRemainingStock(PaymentProductList paymentProductList, PurchaseProduct purchase) {
+ boolean answer = confirmPromotionAddition(purchase.getProductName());
+ int promotionUnits = purchase.getPromotionUnits();
+ if (answer) {
+ purchase.increaseQuantityForPromotion();
+ promotionUnits += 1;
+ }
+ paymentProductList.addPaymentProduct(purchase.createPaymentProduct(promotionUnits));
+ }
+
+ private void displayPaymentInfo(PaymentProductList paymentProductList) {
+ List<String> productInfos = paymentProductList.infoProduct();
+ List<String> promotionInfos = paymentProductList.infoPromotion();
+ List<String> finalResults = paymentProductList.finalResult();
+
+ outputView.printPaymentInfoResult(productInfos);
+ outputView.printPromotionInfoResult(promotionInfos);
+ outputView.printFinalResult(finalResults);
+ }
+
+ private void applyMembershipDiscountIfConfirmed(PaymentProductList paymentProductList) {
+ if (readMembershipConfirmationWithRetry()) {
+ paymentProductList.applyMembershipDiscount();
+ }
+ }
+
+ private void displayWelcomeMessage() {
+ outputView.printWelcomeMessage();
+ }
+
+ private PromotionsList loadPromotions() {
+ List<List<String>> inputPromotions = inputView.readPromotionsData();
+ List<Promotions> promotionsList1 = PromotionParser.parseToPromotions(inputPromotions);
+ return new PromotionsList(promotionsList1);
+ }
+
+ private Products loadProducts(PromotionsList promotionsList) {
+ List<List<String>> inputProducts = inputView.readProductsData();
+ List<Product> productList = ProductParser.parseToProducts(inputProducts, promotionsList);
+ return new Products(productList);
+ }
+
+ private void displayProductsInfo(Products products) {
+ outputView.printProductsInfo(products.getAllProductsInfo());
+ }
+
+ private List<PurchaseProduct> handlePurchases(Products products) {
+ while (true) {
+ try {
+ Map<String, Integer> purchases = readAndParsePurchaseInput();
+ return processPurchases(products, purchases);
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private Map<String, Integer> readAndParsePurchaseInput() {
+ String input = inputView.readPurchaseInput();
+ return PurchaseParser.parseInputProduct(input);
+ }
+
+ private List<PurchaseProduct> processPurchases(Products products, Map<String, Integer> purchases) {
+ List<PurchaseProduct> purchaseProducts = new ArrayList<>();
+ for (Map.Entry<String, Integer> entry : purchases.entrySet()) {
+ List<Product> foundProducts = products.findProductByName(entry.getKey());
+ purchaseProducts.add(new PurchaseProduct(foundProducts, entry.getValue()));
+ }
+ return purchaseProducts;
+ }
+
+ private boolean confirmPromotionNotApplied(String productName, int quantity) {
+ while (true) {
+ try {
+ outputView.printPromotionNotApplied(productName, quantity);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean confirmPromotionAddition(String productName) {
+ while (true) {
+ try {
+ outputView.printPromotionAddition(productName);
+ return inputView.readYesOrNoInput();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readMembershipConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readMembershipConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+
+ private boolean readAdditionalPurchaseConfirmationWithRetry() {
+ while (true) {
+ try {
+ return inputView.readAdditionalPurchaseConfirmation();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+} | Java | ์ ๋ ์๊ฐ์ด ์กฐ๊ธ ๋ค๋ฅธ ๊ฒ, ์ ๋ ๊ฒ ์ซ์๋ฅผ ํตํด ๊ฐ์ ์กฐ์ํ ์ ์๊ฒ ํ๋ฉด ๋จ์ํ +1 ํ๋ ๊ฒ๋ณด๋ค ์กฐ๊ธ ๋ ์ฑ
์์ ์ ๊ฐํ๋ ๊ฒ์ด๋ผ๊ณ ํด์ํ ์๋ ์์ง ์๋์? |
@@ -0,0 +1,58 @@
+package store.view;
+
+import static store.global.constant.MessageConstant.FORMAT;
+import static store.global.constant.MessageConstant.NEW_LINE;
+import static store.global.constant.MessageConstant.OUTPUT_HEADER_PROMOTION;
+import static store.global.constant.MessageConstant.OUTPUT_HEADER_SEPARATOR;
+import static store.global.constant.MessageConstant.OUTPUT_HEADER_STORE;
+import static store.global.constant.MessageConstant.OUTPUT_PRODUCT_INFO;
+import static store.global.constant.MessageConstant.OUTPUT_PRODUCT_PREFIX;
+import static store.global.constant.MessageConstant.OUTPUT_PROMOTION_ADD;
+import static store.global.constant.MessageConstant.OUTPUT_PROMOTION_NOT_APPLIED;
+import static store.global.constant.MessageConstant.OUTPUT_WELCOME;
+
+import java.util.List;
+
+public class OutputView {
+
+ public void printWelcomeMessage() {
+ System.out.println(OUTPUT_WELCOME.getMessage());
+ System.out.println(OUTPUT_PRODUCT_INFO.getMessage() + NEW_LINE.getMessage());
+ }
+
+ public void printProductsInfo(List<String> products) {
+ products.forEach(product ->
+ System.out.println(OUTPUT_PRODUCT_PREFIX.getMessage() + product)
+ );
+ }
+
+ public void printPromotionNotApplied(String name, int quantity) {
+ System.out.printf(NEW_LINE.getMessage() + OUTPUT_PROMOTION_NOT_APPLIED.getMessage() + NEW_LINE.getMessage(),
+ name, quantity);
+ }
+
+ public void printPromotionAddition(String name) {
+ System.out.printf(NEW_LINE.getMessage() + OUTPUT_PROMOTION_ADD.getMessage() + NEW_LINE.getMessage(), name);
+ }
+
+ public void printPaymentInfoResult(List<String> infos) {
+ System.out.printf(NEW_LINE.getMessage());
+ System.out.println(OUTPUT_HEADER_STORE.getMessage());
+ System.out.printf(FORMAT.getMessage() + NEW_LINE.getMessage(), "์ํ๋ช
", "์๋", "๊ธ์ก");
+ infos.forEach(System.out::println);
+ }
+
+ public void printPromotionInfoResult(List<String> strings) {
+ System.out.println(OUTPUT_HEADER_PROMOTION.getMessage());
+ strings.forEach(System.out::println);
+ }
+
+ public void printFinalResult(List<String> result) {
+ System.out.println(OUTPUT_HEADER_SEPARATOR.getMessage());
+ result.forEach(System.out::println);
+ }
+
+ public void printErrorMessage(String message) {
+ System.out.println(message);
+ }
+} | Java | ํ .. ! ๋๋ฌด๋๋ ์ข์ ๊ฟํ ๊ฐ์ฌ๋๋ฆฝ๋๋ค. |
@@ -0,0 +1,48 @@
+package store.domain;
+
+import static store.global.constant.MessageConstant.FORMAT;
+
+import java.text.DecimalFormat;
+
+public class PaymentProduct {
+
+ private static final DecimalFormat PRICE_FORMAT = new DecimalFormat("###,###");
+
+ private final String name;
+ private final int quantity;
+ private final int price;
+ private final int promotion;
+
+ public PaymentProduct(String name, int quantity, int price, int promotion) {
+ this.name = name;
+ this.quantity = quantity;
+ this.price = price;
+ this.promotion = promotion;
+ }
+
+ @Override
+ public String toString() {
+ String formattedPrice = PRICE_FORMAT.format(quantity * price);
+ return String.format(FORMAT.getMessage(), name, quantity, formattedPrice);
+ }
+
+ public boolean isPromotion() {
+ return promotion != 0;
+ }
+
+ public String buildPromotion() {
+ return String.format(FORMAT.getMessage(), name, promotion, "");
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public int getTotalPrice() {
+ return quantity * price;
+ }
+
+ public int getPromotionPrice() {
+ return promotion * price;
+ }
+} | Java | DecimalFormat์ด๋ผ๋ ํด๋์ค๋ ์ฒ์ ๋ณด๋ค์ ! ๋ฐฐ์๊ฐ๋๋ค |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.