code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,135 @@ +package store.domain; + +import camp.nextstep.edu.missionutils.DateTimes; + +public class CartItem { + private static final int DEFAULT_FREE_QUANTITY = 0; + private static final int MINIMUM_VALID_QUANTITY = 0; + + private final Product product; + private final int quantity; + + public CartItem(Product product, int quantity) { + this.product = product; + this.quantity = quantity; + } + + public Money calculateTotalPrice() { + return product.calculateTotalPrice(quantity); + } + + public int calculatePromotionDiscount() { + if (!product.isPromotionValid()) { + return 0; + } + Money totalAmount = calculateTotalPrice(); + Money amountWithoutPromotion = getTotalAmountWithoutPromotion(); + return totalAmount.subtract(amountWithoutPromotion).getAmount(); + } + + public int calculateTotalIfNoPromotion() { + if (!product.isPromotionValid()) { + return calculateTotalPrice().getAmount(); + } + return 0; + } + + public Money getTotalAmountWithoutPromotion() { + return product.calculatePrice(getEffectivePaidQuantity()); + } + + public int getEffectivePaidQuantity() { + Promotion promotion = product.getPromotion(); + if (!isPromotionValid(promotion)) { + return quantity; + } + return calculateQuotient(promotion); + } + + private int calculateQuotient(Promotion promotion) { + int totalRequired = promotion.getBuyQuantity() + promotion.getFreeQuantity(); + return quantity - Math.min(quantity / totalRequired, product.getStock() / totalRequired); + } + + public boolean isPromotionValid() { + Promotion promotion = product.getPromotion(); + return isPromotionValid(promotion); + } + + private boolean isPromotionValid(Promotion promotion) { + return promotion != null && promotion.isValid(DateTimes.now().toLocalDate()); + } + + public boolean checkPromotionStock() { + Promotion promotion = product.getPromotion(); + if (!isPromotionValid(promotion)) { + return false; + } + return isStockAvailable(promotion); + } + + private boolean isStockAvailable(Promotion promotion) { + int totalRequired = promotion.getBuyQuantity() + promotion.getFreeQuantity(); + int promoAvailableQuantity = (product.getStock() / totalRequired) * totalRequired; + return (quantity - promoAvailableQuantity) > MINIMUM_VALID_QUANTITY; + } + + public int getFreeQuantity() { + Promotion promotion = product.getPromotion(); + if (promotion == null) { + return DEFAULT_FREE_QUANTITY; + } + return promotion.calculateFreeItems(quantity, product.getStock()); + } + + public int calculateRemainingQuantity() { + Promotion promotion = product.getPromotion(); + if (!isPromotionValid(promotion)) { + return quantity; + } + return calculateRemainingQuantityForValidPromotion(promotion); + } + + private int calculateRemainingQuantityForValidPromotion(Promotion promotion) { + int totalRequired = promotion.getBuyQuantity() + promotion.getFreeQuantity(); + int promoAvailableQuantity = (product.getStock() / totalRequired) * totalRequired; + return Math.max(MINIMUM_VALID_QUANTITY, quantity - promoAvailableQuantity); + } + + public int calculateAdditionalQuantityNeeded() { + Promotion promotion = product.getPromotion(); + if (!isPromotionValid(promotion)) { + return DEFAULT_FREE_QUANTITY; + } + return calculateAdditionalQuantity(promotion); + } + + private int calculateAdditionalQuantity(Promotion promotion) { + int totalRequired = promotion.getBuyQuantity() + promotion.getFreeQuantity(); + int remainder = quantity % totalRequired; + if (remainder == promotion.getBuyQuantity()) { + return totalRequired - remainder; + } + return DEFAULT_FREE_QUANTITY; + } + + public CartItem withUpdatedQuantityForFullPrice(int newQuantity) { + return new CartItem(this.product, newQuantity); + } + + public CartItem withAdditionalQuantity(int additionalQuantity) { + return new CartItem(this.product, this.quantity + additionalQuantity); + } + + public String getProductName() { + return product.getName(); + } + + public Product getProduct() { + return product; + } + + public int getQuantity() { + return quantity; + } +}
Java
์•„์˜ˆ ๋‚ด๋ถ€๋ฅผ ์ˆ˜์ •ํ•˜๊ฒŒ ์—†๊ฒŒ๋” ์ƒˆ๋กœ์šด ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋„ค์š”! ์ €๋Š” ๋†“์ณค๋˜ ๋ถ€๋ถ„์ธ๋ฐ ์—„์ฒญ ๊ผผ๊ผผํ•˜์‹ญ๋‹ˆ๋‹ค ๐Ÿ‘
@@ -0,0 +1,238 @@ +package store.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import store.common.ErrorMessages; +import store.io.output.StoreOutput; + +public class Inventory { + private static final String PROMOTIONS_FILE_PATH = "src/main/resources/promotions.md"; + private static final String PRODUCTS_FILE_PATH = "src/main/resources/products.md"; + public static final String MD_FILE_DELIMITER = ","; + + private static final int NAME_INDEX = 0; + private static final int BUY_QUANTITY_INDEX = 1; + private static final int FREE_QUANTITY_INDEX = 2; + private static final int START_DATE_INDEX = 3; + private static final int END_DATE_INDEX = 4; + private static final int PRICE_INDEX = 1; + private static final int STOCK_INDEX = 2; + private static final int PROMOTION_NAME_INDEX = 3; + + private static final int DEFAULT_STOCK = 0; + private static final int EMPTY_PROMOTION = 0; + + private final List<Product> products = new ArrayList<>(); + private final Map<String, Promotion> promotions = new HashMap<>(); + + public Inventory() { + loadPromotions(); + loadProducts(); + } + + private void loadPromotions() { + LocalDate currentDate = DateTimes.now().toLocalDate(); + try (BufferedReader reader = new BufferedReader(new FileReader(PROMOTIONS_FILE_PATH))) { + reader.readLine(); + String line; + while ((line = reader.readLine()) != null) { + Promotion promotion = parsePromotion(line); + addPromotionToMap(promotion, currentDate); + } + } catch (IOException e) { + System.out.println(ErrorMessages.ERROR_LOADING_PROMOTIONS_FILE); + } + } + + private Promotion parsePromotion(String line) { + String[] fields = line.split(MD_FILE_DELIMITER); + String name = fields[NAME_INDEX]; + int buyQuantity = Integer.parseInt(fields[BUY_QUANTITY_INDEX]); + int freeQuantity = Integer.parseInt(fields[FREE_QUANTITY_INDEX]); + LocalDate startDate = LocalDate.parse(fields[START_DATE_INDEX]); + LocalDate endDate = LocalDate.parse(fields[END_DATE_INDEX]); + return new Promotion(name, buyQuantity, freeQuantity, startDate, endDate); + } + + private void addPromotionToMap(Promotion promotion, LocalDate currentDate) { + if (!promotion.isValid(currentDate)) { + promotions.put(promotion.getName(), null); + return; + } + promotions.put(promotion.getName(), promotion); + } + + private void loadProducts() { + try (BufferedReader reader = new BufferedReader(new FileReader(PRODUCTS_FILE_PATH))) { + reader.readLine(); + String line; + while ((line = reader.readLine()) != null) { + Product product = parseProduct(line); + addProductToInventory(product); + } + } catch (IOException e) { + System.out.println(ErrorMessages.ERROR_LOADING_PRODUCTS_FILE); + } + } + + private Product parseProduct(String line) { + String[] fields = line.split(MD_FILE_DELIMITER); + String name = fields[NAME_INDEX]; + int price = Integer.parseInt(fields[PRICE_INDEX]); + int stock = Integer.parseInt(fields[STOCK_INDEX]); + + String promotionName = null; + if (fields.length > PROMOTION_NAME_INDEX) { + promotionName = fields[PROMOTION_NAME_INDEX]; + } + + Promotion promotion = promotions.get(promotionName); + return new Product(name, price, stock, promotion); + } + + private void addProductToInventory(Product product) { + Optional<Product> existingProduct = findProductByNameAndPromotion(product.getName(), product.getPromotion()); + if (existingProduct.isEmpty()) { + products.add(product); + return; + } + existingProduct.get().addStock(product.getStock()); + } + + private Optional<Product> findProductByNameAndPromotion(String name, Promotion promotion) { + return products.stream() + .filter(product -> isMatchingProduct(product, name, promotion)) + .findFirst(); + } + + private boolean isMatchingProduct(Product product, String name, Promotion promotion) { + if (!product.getName().equals(name)) { + return false; + } + return isMatchingPromotion(product, promotion); + } + + private boolean isMatchingPromotion(Product product, Promotion promotion) { + if (product.getPromotion() == null && promotion == null) { + return true; + } + if (product.getPromotion() != null) { + return product.getPromotion().equals(promotion); + } + return false; + } + + public Optional<Product> getProductByNameAndPromotion(String productName, boolean hasPromotion) { + return products.stream() + .filter(product -> isMatchingProductByNameAndPromotion(product, productName, hasPromotion)) + .findFirst(); + } + + private boolean isMatchingProductByNameAndPromotion(Product product, String productName, boolean hasPromotion) { + if (!product.getName().equalsIgnoreCase(productName)) { + return false; + } + if (hasPromotion) { + return product.getPromotion() != null; + } + return product.getPromotion() == null; + } + + public void updateInventory(Cart cart) { + validateStock(cart); + reduceStock(cart); + } + + private void validateStock(Cart cart) { + for (CartItem item : cart.getItems()) { + Product product = item.getProduct(); + int requiredQuantity = item.getQuantity(); + int totalAvailableStock = getTotalAvailableStock(product); + + if (requiredQuantity > totalAvailableStock) { + throw new IllegalStateException(ErrorMessages.EXCEED_STOCK); + } + } + } + + private int getTotalAvailableStock(Product product) { + int availablePromoStock = getAvailablePromoStock(product); + int availableRegularStock = getAvailableRegularStock(product); + return availablePromoStock + availableRegularStock; + } + + private int getAvailablePromoStock(Product product) { + Optional<Product> promoProduct = getProductByNameAndPromotion(product.getName(), true); + if (promoProduct.isPresent()) { + return promoProduct.get().getStock(); + } + return DEFAULT_STOCK; + } + + private int getAvailableRegularStock(Product product) { + Optional<Product> regularProduct = getProductByNameAndPromotion(product.getName(), false); + if (regularProduct.isPresent()) { + return regularProduct.get().getStock(); + } + return DEFAULT_STOCK; + } + + private void reduceStock(Cart cart) { + for (CartItem item : cart.getItems()) { + Product product = item.getProduct(); + int requiredQuantity = item.getQuantity(); + + int promoQuantity = calculatePromoQuantity(product, requiredQuantity); + int regularQuantity = requiredQuantity - promoQuantity; + + reduceStock(product.getName(), promoQuantity, regularQuantity); + } + } + + private int calculatePromoQuantity(Product product, int requiredQuantity) { + if (product.getPromotion() == null) { + return EMPTY_PROMOTION; + } + if (!product.getPromotion().isValid(DateTimes.now().toLocalDate())) { + return EMPTY_PROMOTION; + } + return Math.min(requiredQuantity, product.getStock()); + } + + private void reduceStock(String productName, int promoQuantity, int regularQuantity) { + reducePromotionStock(productName, promoQuantity); + reduceRegularStock(productName, regularQuantity); + } + + private void reducePromotionStock(String productName, int promoQuantity) { + if (promoQuantity <= DEFAULT_STOCK) { + return; + } + Optional<Product> promoProduct = getProductByNameAndPromotion(productName, true); + if (promoProduct.isPresent()) { + promoProduct.get().reducePromotionStock(promoQuantity); + } + } + + private void reduceRegularStock(String productName, int regularQuantity) { + if (regularQuantity <= DEFAULT_STOCK) { + return; + } + Optional<Product> regularProduct = getProductByNameAndPromotion(productName, false); + if (regularProduct.isPresent()) { + regularProduct.get().reduceRegularStock(regularQuantity); + } + } + + public void printProductList(StoreOutput storeOutput) { + storeOutput.printProductList(products); + } +}
Java
์ŠคํŠธ๋ฆผ์˜ skip์„ ํ†ตํ•ด ๋” ๊ฐ„๋žตํ•˜๊ฒŒ ์ฝ”๋“œ๋ฅผ ๊ตฌ์„ฑํ•  ์ˆ˜ ์žˆ์„๊ฑฐ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,238 @@ +package store.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import store.common.ErrorMessages; +import store.io.output.StoreOutput; + +public class Inventory { + private static final String PROMOTIONS_FILE_PATH = "src/main/resources/promotions.md"; + private static final String PRODUCTS_FILE_PATH = "src/main/resources/products.md"; + public static final String MD_FILE_DELIMITER = ","; + + private static final int NAME_INDEX = 0; + private static final int BUY_QUANTITY_INDEX = 1; + private static final int FREE_QUANTITY_INDEX = 2; + private static final int START_DATE_INDEX = 3; + private static final int END_DATE_INDEX = 4; + private static final int PRICE_INDEX = 1; + private static final int STOCK_INDEX = 2; + private static final int PROMOTION_NAME_INDEX = 3; + + private static final int DEFAULT_STOCK = 0; + private static final int EMPTY_PROMOTION = 0; + + private final List<Product> products = new ArrayList<>(); + private final Map<String, Promotion> promotions = new HashMap<>(); + + public Inventory() { + loadPromotions(); + loadProducts(); + } + + private void loadPromotions() { + LocalDate currentDate = DateTimes.now().toLocalDate(); + try (BufferedReader reader = new BufferedReader(new FileReader(PROMOTIONS_FILE_PATH))) { + reader.readLine(); + String line; + while ((line = reader.readLine()) != null) { + Promotion promotion = parsePromotion(line); + addPromotionToMap(promotion, currentDate); + } + } catch (IOException e) { + System.out.println(ErrorMessages.ERROR_LOADING_PROMOTIONS_FILE); + } + } + + private Promotion parsePromotion(String line) { + String[] fields = line.split(MD_FILE_DELIMITER); + String name = fields[NAME_INDEX]; + int buyQuantity = Integer.parseInt(fields[BUY_QUANTITY_INDEX]); + int freeQuantity = Integer.parseInt(fields[FREE_QUANTITY_INDEX]); + LocalDate startDate = LocalDate.parse(fields[START_DATE_INDEX]); + LocalDate endDate = LocalDate.parse(fields[END_DATE_INDEX]); + return new Promotion(name, buyQuantity, freeQuantity, startDate, endDate); + } + + private void addPromotionToMap(Promotion promotion, LocalDate currentDate) { + if (!promotion.isValid(currentDate)) { + promotions.put(promotion.getName(), null); + return; + } + promotions.put(promotion.getName(), promotion); + } + + private void loadProducts() { + try (BufferedReader reader = new BufferedReader(new FileReader(PRODUCTS_FILE_PATH))) { + reader.readLine(); + String line; + while ((line = reader.readLine()) != null) { + Product product = parseProduct(line); + addProductToInventory(product); + } + } catch (IOException e) { + System.out.println(ErrorMessages.ERROR_LOADING_PRODUCTS_FILE); + } + } + + private Product parseProduct(String line) { + String[] fields = line.split(MD_FILE_DELIMITER); + String name = fields[NAME_INDEX]; + int price = Integer.parseInt(fields[PRICE_INDEX]); + int stock = Integer.parseInt(fields[STOCK_INDEX]); + + String promotionName = null; + if (fields.length > PROMOTION_NAME_INDEX) { + promotionName = fields[PROMOTION_NAME_INDEX]; + } + + Promotion promotion = promotions.get(promotionName); + return new Product(name, price, stock, promotion); + } + + private void addProductToInventory(Product product) { + Optional<Product> existingProduct = findProductByNameAndPromotion(product.getName(), product.getPromotion()); + if (existingProduct.isEmpty()) { + products.add(product); + return; + } + existingProduct.get().addStock(product.getStock()); + } + + private Optional<Product> findProductByNameAndPromotion(String name, Promotion promotion) { + return products.stream() + .filter(product -> isMatchingProduct(product, name, promotion)) + .findFirst(); + } + + private boolean isMatchingProduct(Product product, String name, Promotion promotion) { + if (!product.getName().equals(name)) { + return false; + } + return isMatchingPromotion(product, promotion); + } + + private boolean isMatchingPromotion(Product product, Promotion promotion) { + if (product.getPromotion() == null && promotion == null) { + return true; + } + if (product.getPromotion() != null) { + return product.getPromotion().equals(promotion); + } + return false; + } + + public Optional<Product> getProductByNameAndPromotion(String productName, boolean hasPromotion) { + return products.stream() + .filter(product -> isMatchingProductByNameAndPromotion(product, productName, hasPromotion)) + .findFirst(); + } + + private boolean isMatchingProductByNameAndPromotion(Product product, String productName, boolean hasPromotion) { + if (!product.getName().equalsIgnoreCase(productName)) { + return false; + } + if (hasPromotion) { + return product.getPromotion() != null; + } + return product.getPromotion() == null; + } + + public void updateInventory(Cart cart) { + validateStock(cart); + reduceStock(cart); + } + + private void validateStock(Cart cart) { + for (CartItem item : cart.getItems()) { + Product product = item.getProduct(); + int requiredQuantity = item.getQuantity(); + int totalAvailableStock = getTotalAvailableStock(product); + + if (requiredQuantity > totalAvailableStock) { + throw new IllegalStateException(ErrorMessages.EXCEED_STOCK); + } + } + } + + private int getTotalAvailableStock(Product product) { + int availablePromoStock = getAvailablePromoStock(product); + int availableRegularStock = getAvailableRegularStock(product); + return availablePromoStock + availableRegularStock; + } + + private int getAvailablePromoStock(Product product) { + Optional<Product> promoProduct = getProductByNameAndPromotion(product.getName(), true); + if (promoProduct.isPresent()) { + return promoProduct.get().getStock(); + } + return DEFAULT_STOCK; + } + + private int getAvailableRegularStock(Product product) { + Optional<Product> regularProduct = getProductByNameAndPromotion(product.getName(), false); + if (regularProduct.isPresent()) { + return regularProduct.get().getStock(); + } + return DEFAULT_STOCK; + } + + private void reduceStock(Cart cart) { + for (CartItem item : cart.getItems()) { + Product product = item.getProduct(); + int requiredQuantity = item.getQuantity(); + + int promoQuantity = calculatePromoQuantity(product, requiredQuantity); + int regularQuantity = requiredQuantity - promoQuantity; + + reduceStock(product.getName(), promoQuantity, regularQuantity); + } + } + + private int calculatePromoQuantity(Product product, int requiredQuantity) { + if (product.getPromotion() == null) { + return EMPTY_PROMOTION; + } + if (!product.getPromotion().isValid(DateTimes.now().toLocalDate())) { + return EMPTY_PROMOTION; + } + return Math.min(requiredQuantity, product.getStock()); + } + + private void reduceStock(String productName, int promoQuantity, int regularQuantity) { + reducePromotionStock(productName, promoQuantity); + reduceRegularStock(productName, regularQuantity); + } + + private void reducePromotionStock(String productName, int promoQuantity) { + if (promoQuantity <= DEFAULT_STOCK) { + return; + } + Optional<Product> promoProduct = getProductByNameAndPromotion(productName, true); + if (promoProduct.isPresent()) { + promoProduct.get().reducePromotionStock(promoQuantity); + } + } + + private void reduceRegularStock(String productName, int regularQuantity) { + if (regularQuantity <= DEFAULT_STOCK) { + return; + } + Optional<Product> regularProduct = getProductByNameAndPromotion(productName, false); + if (regularProduct.isPresent()) { + regularProduct.get().reduceRegularStock(regularQuantity); + } + } + + public void printProductList(StoreOutput storeOutput) { + storeOutput.printProductList(products); + } +}
Java
์ธ๋ฑ์Šค๊นŒ์ง€ ์ƒ์ˆ˜ํ™”ํ•˜๋Š”๊ฑฐ ์ข‹์€๊ฑฐ๊ฐ™์•„์š”! ๊ฐ ํ•ด๋‹น ์ธ๋ฑ์Šค๊ฐ€ ๋ญ˜ ์˜๋ฏธํ•˜๋Š”์ง€ ํŒŒ์•…ํ•˜๊ธฐ ์‰ฝ๋„ค์š”! ํ•˜๋‚˜ ์•Œ์•„๊ฐ‘๋‹ˆ๋‹ค ๐Ÿ˜Š
@@ -0,0 +1,73 @@ +package store.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import store.common.ErrorMessages; + +public class Product { + private static final String NO_PROMOTION_DESCRIPTION = ""; + + private final String name; + private final Money price; + private int stock; + private final Promotion promotion; + + public Product(String name, int price, int stock, Promotion promotion) { + this.name = name; + this.price = new Money(price); + this.stock = stock; + this.promotion = promotion; + } + + public Money calculatePrice(int quantity) { + return price.multiply(quantity); + } + + public boolean isPromotionValid() { + return promotion != null && promotion.isValid(DateTimes.now().toLocalDate()); + } + + public void reduceRegularStock(int quantity) { + if (quantity > stock) { + throw new IllegalStateException(ErrorMessages.EXCEED_STOCK); + } + stock -= quantity; + } + + public void reducePromotionStock(int promoQuantity) { + if (promoQuantity > stock) { + throw new IllegalStateException(ErrorMessages.EXCEED_STOCK); + } + stock -= promoQuantity; + } + + public String getPromotionDescription() { + if (promotion != null) { + return promotion.getName(); + } + return NO_PROMOTION_DESCRIPTION; + } + + public void addStock(int additionalStock) { + this.stock += additionalStock; + } + + public Money calculateTotalPrice(int quantity) { + return price.multiply(quantity); + } + + public Money getPrice() { + return price; + } + + public int getStock() { + return stock; + } + + public String getName() { + return name; + } + + public Promotion getPromotion() { + return promotion; + } +}
Java
ํ”„๋กœ๋ชจ์…˜์„ ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜ํ•˜๋Š”๊ฑฐ๋ณด๋‹ค ํ”„๋กœ๋ชจ์…˜์ด ์žˆ๋Š”์ง€๋งŒ ํ™•์ธํ•˜๋Š” ๋ฉ”์†Œ๋“œ๋ฅผ ๊ตฌํ˜„ํ•˜๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”??
@@ -0,0 +1,17 @@ +package store.io.output; + +import java.util.List; +import store.domain.Cart; +import store.domain.Membership; +import store.domain.Product; +import store.domain.Receipt; + +public interface StoreOutput { + void printProductList(List<Product> products); + + void printReceipt(Receipt receipt, Cart cart, Membership membership); + + void printError(String message); + + void close(); +}
Java
์ธํ„ฐํŽ˜์ด์Šค ๋Œ์ž… ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,134 @@ +package store.io.output.impl; + +import camp.nextstep.edu.missionutils.Console; +import java.util.List; +import java.util.Optional; +import store.common.ConsoleMessages; +import store.common.ErrorMessages; +import store.domain.Cart; +import store.domain.CartItem; +import store.domain.Membership; +import store.domain.Product; +import store.domain.Receipt; +import store.io.output.StoreOutput; + +public class OutputConsole implements StoreOutput { + + @Override + public void printProductList(List<Product> products) { + printHeader(); + printProducts(products); + } + + private void printHeader() { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.println(ConsoleMessages.WELCOME_MESSAGE); + System.out.println(ConsoleMessages.PRODUCT_LIST_HEADER); + System.out.print(ConsoleMessages.LINE_SEPARATOR); + } + + private void printProducts(List<Product> products) { + for (Product product : products) { + printProductInfo(product); + printRegularProductInfoIfMissing(products, product); + } + } + + private void printProductInfo(Product product) { + String stockInfo = getStockInfo(product); + String promoInfo = product.getPromotionDescription(); + String formattedPrice = getFormattedPrice(product); + System.out.printf("- %s %s์› %s %s%n", product.getName(), formattedPrice, stockInfo, promoInfo); + } + + private void printRegularProductInfoIfMissing(List<Product> products, Product product) { + if (product.getPromotion() == null) { + return; + } + Optional<Product> regularProduct = findRegularProduct(products, product); + if (regularProduct.isEmpty()) { + String formattedPrice = getFormattedPrice(product); + System.out.printf("- %s %s์› ์žฌ๊ณ  ์—†์Œ%n", product.getName(), formattedPrice); + } + } + + private String getStockInfo(Product product) { + return product.getStock() > 0 ? product.getStock() + "๊ฐœ" : "์žฌ๊ณ  ์—†์Œ"; + } + + private String getFormattedPrice(Product product) { + return String.format("%,d", product.getPrice().getAmount()); + } + + private Optional<Product> findRegularProduct(List<Product> products, Product product) { + return products.stream() + .filter(p -> p.getName().equals(product.getName()) && p.getPromotion() == null) + .findFirst(); + } + + @Override + public void printReceipt(Receipt receipt, Cart cart, Membership membership) { + printReceiptHeader(); + printPurchasedItems(receipt); + printFreeItems(receipt); + printReceiptSummary(receipt, cart, membership); + } + + private void printReceiptHeader() { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.printf("==============%-3s%s================%n", "W", "ํŽธ์˜์ "); + System.out.printf("%-10s %10s %8s%n", "์ƒํ’ˆ๋ช…", "์ˆ˜๋Ÿ‰", "๊ธˆ์•ก"); + } + + private void printPurchasedItems(Receipt receipt) { + for (CartItem item : receipt.getPurchasedItems()) { + printPurchasedItem(item); + } + } + + private void printPurchasedItem(CartItem item) { + String productName = item.getProduct().getName(); + int quantity = item.getQuantity(); + String totalPrice = String.format("%,d", item.calculateTotalPrice().getAmount()); + + if (productName.length() < 3) { + System.out.printf("%-10s %10d %13s%n", productName, quantity, totalPrice); + return; + } + System.out.printf("%-10s %9d %14s%n", productName, quantity, totalPrice); + } + + private void printFreeItems(Receipt receipt) { + System.out.printf("=============%-7s%s===============%n", "์ฆ", "์ •"); + for (CartItem item : receipt.getFreeItems()) { + printFreeItem(item); + } + } + + private void printFreeItem(CartItem item) { + String productName = item.getProduct().getName(); + int quantity = item.getFreeQuantity(); + System.out.printf("%-10s %9d%n", productName, quantity); + } + + private void printReceiptSummary(Receipt receipt, Cart cart, Membership membership) { + System.out.println("===================================="); + System.out.printf("%-10s %8d %13s%n", "์ด๊ตฌ๋งค์•ก", receipt.getTotalQuantity(), + String.format("%,d", receipt.getTotalPrice())); + System.out.printf("%-10s %22s%n", "ํ–‰์‚ฌํ• ์ธ", + String.format("-%s", String.format("%,d", receipt.getPromotionDiscount(cart)))); + System.out.printf("%-10s %30s%n", "๋ฉค๋ฒ„์‹ญํ• ์ธ", + String.format("-%s", String.format("%,d", receipt.getMembershipDiscount(cart, membership)))); + System.out.printf("%-10s %23s%n", "๋‚ด์‹ค๋ˆ", String.format("%,d", receipt.getFinalPrice(cart, membership))); + } + + @Override + public void printError(String message) { + System.out.println(ErrorMessages.ERROR_MESSAGE + message); + } + + @Override + public void close() { + Console.close(); + } +}
Java
์—ฌ๊ธฐ๋Š” ํ•˜๋“œ์ฝ”๋”ฉ๋œ ์ƒํƒœ๋กœ ๋†”๋‘์…จ๋„ค์š”? ์‹ค์ œ ๊ตฌํ˜„์ฒด๋ผ์„œ ๊ทธ๋Ÿฐ๊ฑด๊ฐ€์š”?? ๊ธฐ์ค€์ด ์–ด๋–ค๊ฑด์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,101 @@ +package store.domain; + +import static org.assertj.core.api.Assertions.assertThat; + +import camp.nextstep.edu.missionutils.DateTimes; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +public class CartItemTest { + private Product product; + private Promotion promotion; + private CartItem cartItem; + + @BeforeEach + void setup() { + promotion = new Promotion("Buy 2 Get 1 Free", 2, 1, DateTimes.now().toLocalDate().minusDays(1), + DateTimes.now().toLocalDate().plusDays(1)); + product = new Product("Sample Product", 1000, 10, promotion); + cartItem = new CartItem(product, 5); + } + + @Test + void ์ด๊ฐ€๊ฒฉ_๊ณ„์‚ฐ_์„ฑ๊ณต() { + Money totalPrice = cartItem.calculateTotalPrice(); + assertThat(totalPrice.getAmount()).isEqualTo(5000); + } + + @ParameterizedTest + @CsvSource({"5, 1000", "7, 2000", "15, 3000"}) + void ํ”„๋กœ๋ชจ์…˜ํ• ์ธ_๊ณ„์‚ฐ_์„ฑ๊ณต(int quantity, int expectedDiscount) { + CartItem cartItem = new CartItem(product, quantity); + int discount = cartItem.calculatePromotionDiscount(); + assertThat(discount).isEqualTo(expectedDiscount); + } + + @Test + void ํ”„๋กœ๋ชจ์…˜ํ• ์ธ_์—†๋Š”๊ฒฝ์šฐ_๊ณ„์‚ฐ_์„ฑ๊ณต() { + Product noPromoProduct = new Product("No Promo Product", 1000, 10, null); + CartItem cartItem = new CartItem(noPromoProduct, 5); + int discount = cartItem.calculatePromotionDiscount(); + assertThat(discount).isEqualTo(0); + } + + @Test + void ์œ ํšจํ•˜์ง€์•Š์€_ํ”„๋กœ๋ชจ์…˜_์ ์šฉ_์˜ˆ์™ธ() { + Promotion expiredPromotion = new Promotion("Expired Promo", 2, 1, DateTimes.now().toLocalDate().minusDays(10), + DateTimes.now().toLocalDate().minusDays(1)); + Product expiredProduct = new Product("Expired Product", 1000, 10, expiredPromotion); + CartItem cartItem = new CartItem(expiredProduct, 5); + + boolean isValid = cartItem.isPromotionValid(); + assertThat(isValid).isFalse(); + } + + @Test + void ํ”„๋กœ๋ชจ์…˜_์žฌ๊ณ ๋ถ€์กฑ_์˜ˆ์™ธ() { + Product lowStockProduct = new Product("Low Stock Product", 1000, 1, promotion); + CartItem cartItem = new CartItem(lowStockProduct, 6); + + boolean stockAvailable = cartItem.checkPromotionStock(); + assertThat(stockAvailable).isTrue(); + } + + @Test + void ์œ ํšจํ•œ_ํ”„๋กœ๋ชจ์…˜_์žฌ๊ณ _ํ™•์ธ() { + boolean stockAvailable = cartItem.checkPromotionStock(); + assertThat(stockAvailable).isFalse(); + } + + @Test + void ๋ฌด๋ฃŒ์ˆ˜๋Ÿ‰_๊ณ„์‚ฐ_์„ฑ๊ณต() { + int freeQuantity = cartItem.getFreeQuantity(); + assertThat(freeQuantity).isEqualTo(1); + } + + @Test + void ๋‚จ์€์ˆ˜๋Ÿ‰_๊ณ„์‚ฐ_์„ฑ๊ณต() { + int remainingQuantity = cartItem.calculateRemainingQuantity(); + assertThat(remainingQuantity).isEqualTo(0); + } + + @Test + void ์ถ”๊ฐ€_ํ•„์š”ํ•œ_์ˆ˜๋Ÿ‰_๊ณ„์‚ฐ_์„ฑ๊ณต() { + int additionalQuantity = cartItem.calculateAdditionalQuantityNeeded(); + assertThat(additionalQuantity).isEqualTo(1); + } + + @Test + void ์ˆ˜๋Ÿ‰_์—…๋ฐ์ดํŠธ_ํ›„_์•„์ดํ…œ_์ƒ์„ฑ_์„ฑ๊ณต() { + CartItem updatedItem = cartItem.withUpdatedQuantityForFullPrice(10); + assertThat(updatedItem.getQuantity()).isEqualTo(10); + } + + @Test + void ์ถ”๊ฐ€_์ˆ˜๋Ÿ‰_์ ์šฉ_ํ›„_์•„์ดํ…œ_์ƒ์„ฑ_์„ฑ๊ณต() { + CartItem updatedItem = cartItem.withAdditionalQuantity(3); + assertThat(updatedItem.getQuantity()).isEqualTo(8); + } +}
Java
๋ฉ”์„œ๋“œ ๋ช…์œผ๋กœ ํ…Œ์ŠคํŠธ๋ฅผ ํ™•์‹คํ•˜๊ฒŒ ์•Œ ์ˆ˜ ์žˆ๋„ค์š”! ๋‹ค์Œ์—๋Š” display ์• ๋…ธํ…Œ์ด์…˜๋„ ํ™œ์šฉํ•ด๋ณด๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”?ใ…Žใ…Ž
@@ -0,0 +1,64 @@ +package store.io.input.impl; + +import camp.nextstep.edu.missionutils.Console; +import store.common.ConsoleMessages; +import store.common.ErrorMessages; +import store.io.input.StoreInput; + + +public class InputConsole implements StoreInput { + + @Override + public String getPurchaseItemsInput() { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.println(ConsoleMessages.PURCHASE_ITEMS_PROMPT); + return Console.readLine(); + } + + @Override + public boolean askForAdditionalPromo(String itemName, int additionalCount) { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.printf(ConsoleMessages.ADDITIONAL_PROMO_PROMPT + ConsoleMessages.LINE_SEPARATOR, itemName, + additionalCount); + return getYesNoResponse(); + } + + @Override + public boolean askForFullPricePurchase(String itemName, int shortageCount) { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.printf(ConsoleMessages.FULL_PRICE_PURCHASE_PROMPT + ConsoleMessages.LINE_SEPARATOR, itemName, + shortageCount); + return getYesNoResponse(); + } + + @Override + public boolean askForMembershipDiscount() { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.println(ConsoleMessages.MEMBERSHIP_DISCOUNT_PROMPT); + return getYesNoResponse(); + } + + @Override + public boolean askForAdditionalPurchase() { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.println(ConsoleMessages.ADDITIONAL_PURCHASE_PROMPT); + return getYesNoResponse(); + } + + private boolean getYesNoResponse() { + while (true) { + try { + String input = Console.readLine(); + if ("Y".equals(input)) { + return true; + } + if ("N".equals(input)) { + return false; + } + throw new IllegalArgumentException(ErrorMessages.INVALID_INPUT_MESSAGE); + } catch (IllegalArgumentException e) { + System.out.println(ErrorMessages.ERROR_MESSAGE + e.getMessage()); + } + } + } +}
Java
4์ฃผ์ฐจ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์š”๊ตฌ์‚ฌํ•ญ ์ค‘ view๋ฅผ ๊ตฌํ˜„ํ•˜๋ผ๋Š” ๋‚ด์šฉ์ด ์žˆ์—ˆ๋˜ ๊ฒƒ์œผ๋กœ ๊ธฐ์–ตํ•ฉ๋‹ˆ๋‹ค! ๊ผญ view๋ผ๋Š” ํด๋ž˜์Šค ์ด๋ฆ„์„ ์‚ฌ์šฉํ•ด์•ผํ•˜๋Š”๊ฑด ์•„๋‹ˆ๊ฒ ์ง€๋งŒ InputConsole๋กœ ๋„ค์ด๋ฐํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,48 @@ +package store.domain; + +import java.util.ArrayList; +import java.util.List; + +public class Cart { + private final List<CartItem> items; + + public Cart() { + this.items = new ArrayList<>(); + } + + public void addItem(CartItem item) { + this.items.add(item); + } + + public void replaceItem(int index, CartItem newItem) { + this.items.set(index, newItem); + } + + public Money getTotalPrice() { + Money totalPrice = new Money(0); + for (CartItem item : items) { + totalPrice = totalPrice.add(item.calculateTotalPrice()); + } + return totalPrice; + } + + public int getTotalPromotionDiscount() { + int totalDiscount = 0; + for (CartItem item : items) { + totalDiscount += item.calculatePromotionDiscount(); + } + return totalDiscount; + } + + public int getTotalNonPromoAmount() { + int total = 0; + for (CartItem item : items) { + total += item.calculateTotalIfNoPromotion(); + } + return total; + } + + public List<CartItem> getItems() { + return List.copyOf(items); + } +}
Java
stream์„ ์‚ฌ์šฉํ•˜์‹œ๋ฉด ์–ด๋–จ๊นŒ์š”?! ```suggestion return items.stream() .mapToInt(CartItem::calculatePromotionDiscount) .sum(); ```
@@ -0,0 +1,238 @@ +package store.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import store.common.ErrorMessages; +import store.io.output.StoreOutput; + +public class Inventory { + private static final String PROMOTIONS_FILE_PATH = "src/main/resources/promotions.md"; + private static final String PRODUCTS_FILE_PATH = "src/main/resources/products.md"; + public static final String MD_FILE_DELIMITER = ","; + + private static final int NAME_INDEX = 0; + private static final int BUY_QUANTITY_INDEX = 1; + private static final int FREE_QUANTITY_INDEX = 2; + private static final int START_DATE_INDEX = 3; + private static final int END_DATE_INDEX = 4; + private static final int PRICE_INDEX = 1; + private static final int STOCK_INDEX = 2; + private static final int PROMOTION_NAME_INDEX = 3; + + private static final int DEFAULT_STOCK = 0; + private static final int EMPTY_PROMOTION = 0; + + private final List<Product> products = new ArrayList<>(); + private final Map<String, Promotion> promotions = new HashMap<>(); + + public Inventory() { + loadPromotions(); + loadProducts(); + } + + private void loadPromotions() { + LocalDate currentDate = DateTimes.now().toLocalDate(); + try (BufferedReader reader = new BufferedReader(new FileReader(PROMOTIONS_FILE_PATH))) { + reader.readLine(); + String line; + while ((line = reader.readLine()) != null) { + Promotion promotion = parsePromotion(line); + addPromotionToMap(promotion, currentDate); + } + } catch (IOException e) { + System.out.println(ErrorMessages.ERROR_LOADING_PROMOTIONS_FILE); + } + } + + private Promotion parsePromotion(String line) { + String[] fields = line.split(MD_FILE_DELIMITER); + String name = fields[NAME_INDEX]; + int buyQuantity = Integer.parseInt(fields[BUY_QUANTITY_INDEX]); + int freeQuantity = Integer.parseInt(fields[FREE_QUANTITY_INDEX]); + LocalDate startDate = LocalDate.parse(fields[START_DATE_INDEX]); + LocalDate endDate = LocalDate.parse(fields[END_DATE_INDEX]); + return new Promotion(name, buyQuantity, freeQuantity, startDate, endDate); + } + + private void addPromotionToMap(Promotion promotion, LocalDate currentDate) { + if (!promotion.isValid(currentDate)) { + promotions.put(promotion.getName(), null); + return; + } + promotions.put(promotion.getName(), promotion); + } + + private void loadProducts() { + try (BufferedReader reader = new BufferedReader(new FileReader(PRODUCTS_FILE_PATH))) { + reader.readLine(); + String line; + while ((line = reader.readLine()) != null) { + Product product = parseProduct(line); + addProductToInventory(product); + } + } catch (IOException e) { + System.out.println(ErrorMessages.ERROR_LOADING_PRODUCTS_FILE); + } + } + + private Product parseProduct(String line) { + String[] fields = line.split(MD_FILE_DELIMITER); + String name = fields[NAME_INDEX]; + int price = Integer.parseInt(fields[PRICE_INDEX]); + int stock = Integer.parseInt(fields[STOCK_INDEX]); + + String promotionName = null; + if (fields.length > PROMOTION_NAME_INDEX) { + promotionName = fields[PROMOTION_NAME_INDEX]; + } + + Promotion promotion = promotions.get(promotionName); + return new Product(name, price, stock, promotion); + } + + private void addProductToInventory(Product product) { + Optional<Product> existingProduct = findProductByNameAndPromotion(product.getName(), product.getPromotion()); + if (existingProduct.isEmpty()) { + products.add(product); + return; + } + existingProduct.get().addStock(product.getStock()); + } + + private Optional<Product> findProductByNameAndPromotion(String name, Promotion promotion) { + return products.stream() + .filter(product -> isMatchingProduct(product, name, promotion)) + .findFirst(); + } + + private boolean isMatchingProduct(Product product, String name, Promotion promotion) { + if (!product.getName().equals(name)) { + return false; + } + return isMatchingPromotion(product, promotion); + } + + private boolean isMatchingPromotion(Product product, Promotion promotion) { + if (product.getPromotion() == null && promotion == null) { + return true; + } + if (product.getPromotion() != null) { + return product.getPromotion().equals(promotion); + } + return false; + } + + public Optional<Product> getProductByNameAndPromotion(String productName, boolean hasPromotion) { + return products.stream() + .filter(product -> isMatchingProductByNameAndPromotion(product, productName, hasPromotion)) + .findFirst(); + } + + private boolean isMatchingProductByNameAndPromotion(Product product, String productName, boolean hasPromotion) { + if (!product.getName().equalsIgnoreCase(productName)) { + return false; + } + if (hasPromotion) { + return product.getPromotion() != null; + } + return product.getPromotion() == null; + } + + public void updateInventory(Cart cart) { + validateStock(cart); + reduceStock(cart); + } + + private void validateStock(Cart cart) { + for (CartItem item : cart.getItems()) { + Product product = item.getProduct(); + int requiredQuantity = item.getQuantity(); + int totalAvailableStock = getTotalAvailableStock(product); + + if (requiredQuantity > totalAvailableStock) { + throw new IllegalStateException(ErrorMessages.EXCEED_STOCK); + } + } + } + + private int getTotalAvailableStock(Product product) { + int availablePromoStock = getAvailablePromoStock(product); + int availableRegularStock = getAvailableRegularStock(product); + return availablePromoStock + availableRegularStock; + } + + private int getAvailablePromoStock(Product product) { + Optional<Product> promoProduct = getProductByNameAndPromotion(product.getName(), true); + if (promoProduct.isPresent()) { + return promoProduct.get().getStock(); + } + return DEFAULT_STOCK; + } + + private int getAvailableRegularStock(Product product) { + Optional<Product> regularProduct = getProductByNameAndPromotion(product.getName(), false); + if (regularProduct.isPresent()) { + return regularProduct.get().getStock(); + } + return DEFAULT_STOCK; + } + + private void reduceStock(Cart cart) { + for (CartItem item : cart.getItems()) { + Product product = item.getProduct(); + int requiredQuantity = item.getQuantity(); + + int promoQuantity = calculatePromoQuantity(product, requiredQuantity); + int regularQuantity = requiredQuantity - promoQuantity; + + reduceStock(product.getName(), promoQuantity, regularQuantity); + } + } + + private int calculatePromoQuantity(Product product, int requiredQuantity) { + if (product.getPromotion() == null) { + return EMPTY_PROMOTION; + } + if (!product.getPromotion().isValid(DateTimes.now().toLocalDate())) { + return EMPTY_PROMOTION; + } + return Math.min(requiredQuantity, product.getStock()); + } + + private void reduceStock(String productName, int promoQuantity, int regularQuantity) { + reducePromotionStock(productName, promoQuantity); + reduceRegularStock(productName, regularQuantity); + } + + private void reducePromotionStock(String productName, int promoQuantity) { + if (promoQuantity <= DEFAULT_STOCK) { + return; + } + Optional<Product> promoProduct = getProductByNameAndPromotion(productName, true); + if (promoProduct.isPresent()) { + promoProduct.get().reducePromotionStock(promoQuantity); + } + } + + private void reduceRegularStock(String productName, int regularQuantity) { + if (regularQuantity <= DEFAULT_STOCK) { + return; + } + Optional<Product> regularProduct = getProductByNameAndPromotion(productName, false); + if (regularProduct.isPresent()) { + regularProduct.get().reduceRegularStock(regularQuantity); + } + } + + public void printProductList(StoreOutput storeOutput) { + storeOutput.printProductList(products); + } +}
Java
Inventory ์ƒ์ˆ˜๋ฅผ ์œ„ํ•œ ํด๋ž˜์Šค๋ฅผ ๋”ฐ๋กœ ๊ตฌํ˜„ํ•˜์‹œ๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”??
@@ -0,0 +1,66 @@ +package store.domain; + +import java.util.ArrayList; +import java.util.List; + +public class Receipt { + private static final int NO_QUANTITY = 0; + + private final List<CartItem> purchasedItems; + private final List<CartItem> freeItems; + private final Money totalPrice; + + public Receipt(Cart cart) { + this.purchasedItems = cart.getItems(); + this.freeItems = calculateFreeItems(cart); + this.totalPrice = cart.getTotalPrice(); + } + + private List<CartItem> calculateFreeItems(Cart cart) { + List<CartItem> items = cart.getItems(); + return getFreeItemsFromCart(items); + } + + private List<CartItem> getFreeItemsFromCart(List<CartItem> items) { + List<CartItem> freeItems = new ArrayList<>(); + for (CartItem item : items) { + addFreeItems(freeItems, item); + } + return freeItems; + } + + private void addFreeItems(List<CartItem> freeItems, CartItem item) { + int freeQuantity = item.getFreeQuantity(); + if (freeQuantity > NO_QUANTITY) { + freeItems.add(item); + } + } + + public int getTotalQuantity() { + return purchasedItems.size(); + } + + public int getTotalPrice() { + return totalPrice.getAmount(); + } + + public int getPromotionDiscount(Cart cart) { + return cart.getTotalPromotionDiscount(); + } + + public int getMembershipDiscount(Cart cart, Membership membership) { + return membership.calculateDiscount(cart.getTotalNonPromoAmount()); + } + + public int getFinalPrice(Cart cart, Membership membership) { + return totalPrice.getAmount() - getPromotionDiscount(cart) - getMembershipDiscount(cart, membership); + } + + public List<CartItem> getPurchasedItems() { + return purchasedItems; + } + + public List<CartItem> getFreeItems() { + return freeItems; + } +}
Java
์ด ๋ถ€๋ถ„๋„ stream ์‚ฌ์šฉํ•˜์‹œ๋ฉด ๊ฐ€๋…์„ฑ ์ธก๋ฉด์—์„œ ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ```suggestion return items.stream() .filter(item -> isFreeItem(item)) .collect(Collectors.toList()); ```
@@ -0,0 +1,101 @@ +package store.domain; + +import static org.assertj.core.api.Assertions.assertThat; + +import camp.nextstep.edu.missionutils.DateTimes; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +public class CartItemTest { + private Product product; + private Promotion promotion; + private CartItem cartItem; + + @BeforeEach + void setup() { + promotion = new Promotion("Buy 2 Get 1 Free", 2, 1, DateTimes.now().toLocalDate().minusDays(1), + DateTimes.now().toLocalDate().plusDays(1)); + product = new Product("Sample Product", 1000, 10, promotion); + cartItem = new CartItem(product, 5); + } + + @Test + void ์ด๊ฐ€๊ฒฉ_๊ณ„์‚ฐ_์„ฑ๊ณต() { + Money totalPrice = cartItem.calculateTotalPrice(); + assertThat(totalPrice.getAmount()).isEqualTo(5000); + } + + @ParameterizedTest + @CsvSource({"5, 1000", "7, 2000", "15, 3000"}) + void ํ”„๋กœ๋ชจ์…˜ํ• ์ธ_๊ณ„์‚ฐ_์„ฑ๊ณต(int quantity, int expectedDiscount) { + CartItem cartItem = new CartItem(product, quantity); + int discount = cartItem.calculatePromotionDiscount(); + assertThat(discount).isEqualTo(expectedDiscount); + } + + @Test + void ํ”„๋กœ๋ชจ์…˜ํ• ์ธ_์—†๋Š”๊ฒฝ์šฐ_๊ณ„์‚ฐ_์„ฑ๊ณต() { + Product noPromoProduct = new Product("No Promo Product", 1000, 10, null); + CartItem cartItem = new CartItem(noPromoProduct, 5); + int discount = cartItem.calculatePromotionDiscount(); + assertThat(discount).isEqualTo(0); + } + + @Test + void ์œ ํšจํ•˜์ง€์•Š์€_ํ”„๋กœ๋ชจ์…˜_์ ์šฉ_์˜ˆ์™ธ() { + Promotion expiredPromotion = new Promotion("Expired Promo", 2, 1, DateTimes.now().toLocalDate().minusDays(10), + DateTimes.now().toLocalDate().minusDays(1)); + Product expiredProduct = new Product("Expired Product", 1000, 10, expiredPromotion); + CartItem cartItem = new CartItem(expiredProduct, 5); + + boolean isValid = cartItem.isPromotionValid(); + assertThat(isValid).isFalse(); + } + + @Test + void ํ”„๋กœ๋ชจ์…˜_์žฌ๊ณ ๋ถ€์กฑ_์˜ˆ์™ธ() { + Product lowStockProduct = new Product("Low Stock Product", 1000, 1, promotion); + CartItem cartItem = new CartItem(lowStockProduct, 6); + + boolean stockAvailable = cartItem.checkPromotionStock(); + assertThat(stockAvailable).isTrue(); + } + + @Test + void ์œ ํšจํ•œ_ํ”„๋กœ๋ชจ์…˜_์žฌ๊ณ _ํ™•์ธ() { + boolean stockAvailable = cartItem.checkPromotionStock(); + assertThat(stockAvailable).isFalse(); + } + + @Test + void ๋ฌด๋ฃŒ์ˆ˜๋Ÿ‰_๊ณ„์‚ฐ_์„ฑ๊ณต() { + int freeQuantity = cartItem.getFreeQuantity(); + assertThat(freeQuantity).isEqualTo(1); + } + + @Test + void ๋‚จ์€์ˆ˜๋Ÿ‰_๊ณ„์‚ฐ_์„ฑ๊ณต() { + int remainingQuantity = cartItem.calculateRemainingQuantity(); + assertThat(remainingQuantity).isEqualTo(0); + } + + @Test + void ์ถ”๊ฐ€_ํ•„์š”ํ•œ_์ˆ˜๋Ÿ‰_๊ณ„์‚ฐ_์„ฑ๊ณต() { + int additionalQuantity = cartItem.calculateAdditionalQuantityNeeded(); + assertThat(additionalQuantity).isEqualTo(1); + } + + @Test + void ์ˆ˜๋Ÿ‰_์—…๋ฐ์ดํŠธ_ํ›„_์•„์ดํ…œ_์ƒ์„ฑ_์„ฑ๊ณต() { + CartItem updatedItem = cartItem.withUpdatedQuantityForFullPrice(10); + assertThat(updatedItem.getQuantity()).isEqualTo(10); + } + + @Test + void ์ถ”๊ฐ€_์ˆ˜๋Ÿ‰_์ ์šฉ_ํ›„_์•„์ดํ…œ_์ƒ์„ฑ_์„ฑ๊ณต() { + CartItem updatedItem = cartItem.withAdditionalQuantity(3); + assertThat(updatedItem.getQuantity()).isEqualTo(8); + } +}
Java
ํ…Œ์ŠคํŠธ์ฝ”๋“œ๋ฅผ ๊ต‰์žฅํžˆ ๊ผผ๊ผผํ•˜๊ฒŒ ๊ตฌํ˜„ํ•˜์…จ๋„ค์š” ์ข‹์€ ๊ฒƒ ๊ฐ™์•„์š”๐Ÿ‘
@@ -0,0 +1,90 @@ +package store.controller; + +import java.util.List; +import store.domain.Cart; +import store.domain.Membership; +import store.domain.ParsedItem; +import store.domain.Receipt; +import store.io.input.StoreInput; +import store.io.output.StoreOutput; +import store.service.ConvenienceStoreService; + +public class ConvenienceStoreController { + private final StoreInput storeInput; + private final StoreOutput storeOutput; + private final ConvenienceStoreService convenienceStoreService; + + public ConvenienceStoreController(StoreInput storeInput, StoreOutput storeOutput, + ConvenienceStoreService convenienceStoreService) { + this.storeInput = storeInput; + this.storeOutput = storeOutput; + this.convenienceStoreService = convenienceStoreService; + } + + public void start() { + boolean continueShopping; + try { + do { + executeShoppingCycle(); + continueShopping = getValidAdditionalPurchaseResponse(); + } while (continueShopping); + } finally { + storeOutput.close(); + } + } + + private void executeShoppingCycle() { + convenienceStoreService.printInventoryProductList(storeOutput); + + List<ParsedItem> parsedItems = getValidParsedItems(); + Cart cart = convenienceStoreService.createCart(parsedItems); + + convenienceStoreService.applyPromotionToCartItems(cart, storeInput); + + Membership membership = getValidMembershipResponse(); + + Receipt receipt = convenienceStoreService.createReceipt(cart); + storeOutput.printReceipt(receipt, cart, membership); + + updateInventory(cart); + } + + private List<ParsedItem> getValidParsedItems() { + while (true) { + try { + String input = storeInput.getPurchaseItemsInput(); + return convenienceStoreService.parseItems(input); + } catch (IllegalArgumentException | IllegalStateException e) { + storeOutput.printError(e.getMessage()); + } + } + } + + private Membership getValidMembershipResponse() { + while (true) { + try { + return convenienceStoreService.determineMembership(storeInput); + } catch (IllegalArgumentException e) { + storeOutput.printError(e.getMessage()); + } + } + } + + private void updateInventory(Cart cart) { + try { + convenienceStoreService.updateInventory(cart); + } catch (IllegalStateException e) { + storeOutput.printError(e.getMessage()); + } + } + + private boolean getValidAdditionalPurchaseResponse() { + while (true) { + try { + return storeInput.askForAdditionalPurchase(); + } catch (IllegalArgumentException e) { + storeOutput.printError(e.getMessage()); + } + } + } +}
Java
do-while๋ฌธ์€ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๊ฒŒ ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,238 @@ +package store.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import store.common.ErrorMessages; +import store.io.output.StoreOutput; + +public class Inventory { + private static final String PROMOTIONS_FILE_PATH = "src/main/resources/promotions.md"; + private static final String PRODUCTS_FILE_PATH = "src/main/resources/products.md"; + public static final String MD_FILE_DELIMITER = ","; + + private static final int NAME_INDEX = 0; + private static final int BUY_QUANTITY_INDEX = 1; + private static final int FREE_QUANTITY_INDEX = 2; + private static final int START_DATE_INDEX = 3; + private static final int END_DATE_INDEX = 4; + private static final int PRICE_INDEX = 1; + private static final int STOCK_INDEX = 2; + private static final int PROMOTION_NAME_INDEX = 3; + + private static final int DEFAULT_STOCK = 0; + private static final int EMPTY_PROMOTION = 0; + + private final List<Product> products = new ArrayList<>(); + private final Map<String, Promotion> promotions = new HashMap<>(); + + public Inventory() { + loadPromotions(); + loadProducts(); + } + + private void loadPromotions() { + LocalDate currentDate = DateTimes.now().toLocalDate(); + try (BufferedReader reader = new BufferedReader(new FileReader(PROMOTIONS_FILE_PATH))) { + reader.readLine(); + String line; + while ((line = reader.readLine()) != null) { + Promotion promotion = parsePromotion(line); + addPromotionToMap(promotion, currentDate); + } + } catch (IOException e) { + System.out.println(ErrorMessages.ERROR_LOADING_PROMOTIONS_FILE); + } + } + + private Promotion parsePromotion(String line) { + String[] fields = line.split(MD_FILE_DELIMITER); + String name = fields[NAME_INDEX]; + int buyQuantity = Integer.parseInt(fields[BUY_QUANTITY_INDEX]); + int freeQuantity = Integer.parseInt(fields[FREE_QUANTITY_INDEX]); + LocalDate startDate = LocalDate.parse(fields[START_DATE_INDEX]); + LocalDate endDate = LocalDate.parse(fields[END_DATE_INDEX]); + return new Promotion(name, buyQuantity, freeQuantity, startDate, endDate); + } + + private void addPromotionToMap(Promotion promotion, LocalDate currentDate) { + if (!promotion.isValid(currentDate)) { + promotions.put(promotion.getName(), null); + return; + } + promotions.put(promotion.getName(), promotion); + } + + private void loadProducts() { + try (BufferedReader reader = new BufferedReader(new FileReader(PRODUCTS_FILE_PATH))) { + reader.readLine(); + String line; + while ((line = reader.readLine()) != null) { + Product product = parseProduct(line); + addProductToInventory(product); + } + } catch (IOException e) { + System.out.println(ErrorMessages.ERROR_LOADING_PRODUCTS_FILE); + } + } + + private Product parseProduct(String line) { + String[] fields = line.split(MD_FILE_DELIMITER); + String name = fields[NAME_INDEX]; + int price = Integer.parseInt(fields[PRICE_INDEX]); + int stock = Integer.parseInt(fields[STOCK_INDEX]); + + String promotionName = null; + if (fields.length > PROMOTION_NAME_INDEX) { + promotionName = fields[PROMOTION_NAME_INDEX]; + } + + Promotion promotion = promotions.get(promotionName); + return new Product(name, price, stock, promotion); + } + + private void addProductToInventory(Product product) { + Optional<Product> existingProduct = findProductByNameAndPromotion(product.getName(), product.getPromotion()); + if (existingProduct.isEmpty()) { + products.add(product); + return; + } + existingProduct.get().addStock(product.getStock()); + } + + private Optional<Product> findProductByNameAndPromotion(String name, Promotion promotion) { + return products.stream() + .filter(product -> isMatchingProduct(product, name, promotion)) + .findFirst(); + } + + private boolean isMatchingProduct(Product product, String name, Promotion promotion) { + if (!product.getName().equals(name)) { + return false; + } + return isMatchingPromotion(product, promotion); + } + + private boolean isMatchingPromotion(Product product, Promotion promotion) { + if (product.getPromotion() == null && promotion == null) { + return true; + } + if (product.getPromotion() != null) { + return product.getPromotion().equals(promotion); + } + return false; + } + + public Optional<Product> getProductByNameAndPromotion(String productName, boolean hasPromotion) { + return products.stream() + .filter(product -> isMatchingProductByNameAndPromotion(product, productName, hasPromotion)) + .findFirst(); + } + + private boolean isMatchingProductByNameAndPromotion(Product product, String productName, boolean hasPromotion) { + if (!product.getName().equalsIgnoreCase(productName)) { + return false; + } + if (hasPromotion) { + return product.getPromotion() != null; + } + return product.getPromotion() == null; + } + + public void updateInventory(Cart cart) { + validateStock(cart); + reduceStock(cart); + } + + private void validateStock(Cart cart) { + for (CartItem item : cart.getItems()) { + Product product = item.getProduct(); + int requiredQuantity = item.getQuantity(); + int totalAvailableStock = getTotalAvailableStock(product); + + if (requiredQuantity > totalAvailableStock) { + throw new IllegalStateException(ErrorMessages.EXCEED_STOCK); + } + } + } + + private int getTotalAvailableStock(Product product) { + int availablePromoStock = getAvailablePromoStock(product); + int availableRegularStock = getAvailableRegularStock(product); + return availablePromoStock + availableRegularStock; + } + + private int getAvailablePromoStock(Product product) { + Optional<Product> promoProduct = getProductByNameAndPromotion(product.getName(), true); + if (promoProduct.isPresent()) { + return promoProduct.get().getStock(); + } + return DEFAULT_STOCK; + } + + private int getAvailableRegularStock(Product product) { + Optional<Product> regularProduct = getProductByNameAndPromotion(product.getName(), false); + if (regularProduct.isPresent()) { + return regularProduct.get().getStock(); + } + return DEFAULT_STOCK; + } + + private void reduceStock(Cart cart) { + for (CartItem item : cart.getItems()) { + Product product = item.getProduct(); + int requiredQuantity = item.getQuantity(); + + int promoQuantity = calculatePromoQuantity(product, requiredQuantity); + int regularQuantity = requiredQuantity - promoQuantity; + + reduceStock(product.getName(), promoQuantity, regularQuantity); + } + } + + private int calculatePromoQuantity(Product product, int requiredQuantity) { + if (product.getPromotion() == null) { + return EMPTY_PROMOTION; + } + if (!product.getPromotion().isValid(DateTimes.now().toLocalDate())) { + return EMPTY_PROMOTION; + } + return Math.min(requiredQuantity, product.getStock()); + } + + private void reduceStock(String productName, int promoQuantity, int regularQuantity) { + reducePromotionStock(productName, promoQuantity); + reduceRegularStock(productName, regularQuantity); + } + + private void reducePromotionStock(String productName, int promoQuantity) { + if (promoQuantity <= DEFAULT_STOCK) { + return; + } + Optional<Product> promoProduct = getProductByNameAndPromotion(productName, true); + if (promoProduct.isPresent()) { + promoProduct.get().reducePromotionStock(promoQuantity); + } + } + + private void reduceRegularStock(String productName, int regularQuantity) { + if (regularQuantity <= DEFAULT_STOCK) { + return; + } + Optional<Product> regularProduct = getProductByNameAndPromotion(productName, false); + if (regularProduct.isPresent()) { + regularProduct.get().reduceRegularStock(regularQuantity); + } + } + + public void printProductList(StoreOutput storeOutput) { + storeOutput.printProductList(products); + } +}
Java
์ด๋ถ€๋ถ„์„ ๋ถ„๋ฆฌ ์‹œํ‚ค๋ฉด ์ธ๋ดํŠธ๋„ ์ค„์ผ ์ˆ˜ ์žˆ๊ณ  ๋ฉ”์„œ๋“œ ๊ธธ์ด๋„ ์ค„์ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,238 @@ +package store.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import store.common.ErrorMessages; +import store.io.output.StoreOutput; + +public class Inventory { + private static final String PROMOTIONS_FILE_PATH = "src/main/resources/promotions.md"; + private static final String PRODUCTS_FILE_PATH = "src/main/resources/products.md"; + public static final String MD_FILE_DELIMITER = ","; + + private static final int NAME_INDEX = 0; + private static final int BUY_QUANTITY_INDEX = 1; + private static final int FREE_QUANTITY_INDEX = 2; + private static final int START_DATE_INDEX = 3; + private static final int END_DATE_INDEX = 4; + private static final int PRICE_INDEX = 1; + private static final int STOCK_INDEX = 2; + private static final int PROMOTION_NAME_INDEX = 3; + + private static final int DEFAULT_STOCK = 0; + private static final int EMPTY_PROMOTION = 0; + + private final List<Product> products = new ArrayList<>(); + private final Map<String, Promotion> promotions = new HashMap<>(); + + public Inventory() { + loadPromotions(); + loadProducts(); + } + + private void loadPromotions() { + LocalDate currentDate = DateTimes.now().toLocalDate(); + try (BufferedReader reader = new BufferedReader(new FileReader(PROMOTIONS_FILE_PATH))) { + reader.readLine(); + String line; + while ((line = reader.readLine()) != null) { + Promotion promotion = parsePromotion(line); + addPromotionToMap(promotion, currentDate); + } + } catch (IOException e) { + System.out.println(ErrorMessages.ERROR_LOADING_PROMOTIONS_FILE); + } + } + + private Promotion parsePromotion(String line) { + String[] fields = line.split(MD_FILE_DELIMITER); + String name = fields[NAME_INDEX]; + int buyQuantity = Integer.parseInt(fields[BUY_QUANTITY_INDEX]); + int freeQuantity = Integer.parseInt(fields[FREE_QUANTITY_INDEX]); + LocalDate startDate = LocalDate.parse(fields[START_DATE_INDEX]); + LocalDate endDate = LocalDate.parse(fields[END_DATE_INDEX]); + return new Promotion(name, buyQuantity, freeQuantity, startDate, endDate); + } + + private void addPromotionToMap(Promotion promotion, LocalDate currentDate) { + if (!promotion.isValid(currentDate)) { + promotions.put(promotion.getName(), null); + return; + } + promotions.put(promotion.getName(), promotion); + } + + private void loadProducts() { + try (BufferedReader reader = new BufferedReader(new FileReader(PRODUCTS_FILE_PATH))) { + reader.readLine(); + String line; + while ((line = reader.readLine()) != null) { + Product product = parseProduct(line); + addProductToInventory(product); + } + } catch (IOException e) { + System.out.println(ErrorMessages.ERROR_LOADING_PRODUCTS_FILE); + } + } + + private Product parseProduct(String line) { + String[] fields = line.split(MD_FILE_DELIMITER); + String name = fields[NAME_INDEX]; + int price = Integer.parseInt(fields[PRICE_INDEX]); + int stock = Integer.parseInt(fields[STOCK_INDEX]); + + String promotionName = null; + if (fields.length > PROMOTION_NAME_INDEX) { + promotionName = fields[PROMOTION_NAME_INDEX]; + } + + Promotion promotion = promotions.get(promotionName); + return new Product(name, price, stock, promotion); + } + + private void addProductToInventory(Product product) { + Optional<Product> existingProduct = findProductByNameAndPromotion(product.getName(), product.getPromotion()); + if (existingProduct.isEmpty()) { + products.add(product); + return; + } + existingProduct.get().addStock(product.getStock()); + } + + private Optional<Product> findProductByNameAndPromotion(String name, Promotion promotion) { + return products.stream() + .filter(product -> isMatchingProduct(product, name, promotion)) + .findFirst(); + } + + private boolean isMatchingProduct(Product product, String name, Promotion promotion) { + if (!product.getName().equals(name)) { + return false; + } + return isMatchingPromotion(product, promotion); + } + + private boolean isMatchingPromotion(Product product, Promotion promotion) { + if (product.getPromotion() == null && promotion == null) { + return true; + } + if (product.getPromotion() != null) { + return product.getPromotion().equals(promotion); + } + return false; + } + + public Optional<Product> getProductByNameAndPromotion(String productName, boolean hasPromotion) { + return products.stream() + .filter(product -> isMatchingProductByNameAndPromotion(product, productName, hasPromotion)) + .findFirst(); + } + + private boolean isMatchingProductByNameAndPromotion(Product product, String productName, boolean hasPromotion) { + if (!product.getName().equalsIgnoreCase(productName)) { + return false; + } + if (hasPromotion) { + return product.getPromotion() != null; + } + return product.getPromotion() == null; + } + + public void updateInventory(Cart cart) { + validateStock(cart); + reduceStock(cart); + } + + private void validateStock(Cart cart) { + for (CartItem item : cart.getItems()) { + Product product = item.getProduct(); + int requiredQuantity = item.getQuantity(); + int totalAvailableStock = getTotalAvailableStock(product); + + if (requiredQuantity > totalAvailableStock) { + throw new IllegalStateException(ErrorMessages.EXCEED_STOCK); + } + } + } + + private int getTotalAvailableStock(Product product) { + int availablePromoStock = getAvailablePromoStock(product); + int availableRegularStock = getAvailableRegularStock(product); + return availablePromoStock + availableRegularStock; + } + + private int getAvailablePromoStock(Product product) { + Optional<Product> promoProduct = getProductByNameAndPromotion(product.getName(), true); + if (promoProduct.isPresent()) { + return promoProduct.get().getStock(); + } + return DEFAULT_STOCK; + } + + private int getAvailableRegularStock(Product product) { + Optional<Product> regularProduct = getProductByNameAndPromotion(product.getName(), false); + if (regularProduct.isPresent()) { + return regularProduct.get().getStock(); + } + return DEFAULT_STOCK; + } + + private void reduceStock(Cart cart) { + for (CartItem item : cart.getItems()) { + Product product = item.getProduct(); + int requiredQuantity = item.getQuantity(); + + int promoQuantity = calculatePromoQuantity(product, requiredQuantity); + int regularQuantity = requiredQuantity - promoQuantity; + + reduceStock(product.getName(), promoQuantity, regularQuantity); + } + } + + private int calculatePromoQuantity(Product product, int requiredQuantity) { + if (product.getPromotion() == null) { + return EMPTY_PROMOTION; + } + if (!product.getPromotion().isValid(DateTimes.now().toLocalDate())) { + return EMPTY_PROMOTION; + } + return Math.min(requiredQuantity, product.getStock()); + } + + private void reduceStock(String productName, int promoQuantity, int regularQuantity) { + reducePromotionStock(productName, promoQuantity); + reduceRegularStock(productName, regularQuantity); + } + + private void reducePromotionStock(String productName, int promoQuantity) { + if (promoQuantity <= DEFAULT_STOCK) { + return; + } + Optional<Product> promoProduct = getProductByNameAndPromotion(productName, true); + if (promoProduct.isPresent()) { + promoProduct.get().reducePromotionStock(promoQuantity); + } + } + + private void reduceRegularStock(String productName, int regularQuantity) { + if (regularQuantity <= DEFAULT_STOCK) { + return; + } + Optional<Product> regularProduct = getProductByNameAndPromotion(productName, false); + if (regularProduct.isPresent()) { + regularProduct.get().reduceRegularStock(regularQuantity); + } + } + + public void printProductList(StoreOutput storeOutput) { + storeOutput.printProductList(products); + } +}
Java
์ด๋ถ€๋ถ„์€ ์ธ๋ผ์ธ ์ฒ˜๋ฆฌํ•ด๋„ ๊ดœ์ฐฎ์ง€ ์•Š์„๊นŒ์š”?
@@ -0,0 +1,134 @@ +package store.io.output.impl; + +import camp.nextstep.edu.missionutils.Console; +import java.util.List; +import java.util.Optional; +import store.common.ConsoleMessages; +import store.common.ErrorMessages; +import store.domain.Cart; +import store.domain.CartItem; +import store.domain.Membership; +import store.domain.Product; +import store.domain.Receipt; +import store.io.output.StoreOutput; + +public class OutputConsole implements StoreOutput { + + @Override + public void printProductList(List<Product> products) { + printHeader(); + printProducts(products); + } + + private void printHeader() { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.println(ConsoleMessages.WELCOME_MESSAGE); + System.out.println(ConsoleMessages.PRODUCT_LIST_HEADER); + System.out.print(ConsoleMessages.LINE_SEPARATOR); + } + + private void printProducts(List<Product> products) { + for (Product product : products) { + printProductInfo(product); + printRegularProductInfoIfMissing(products, product); + } + } + + private void printProductInfo(Product product) { + String stockInfo = getStockInfo(product); + String promoInfo = product.getPromotionDescription(); + String formattedPrice = getFormattedPrice(product); + System.out.printf("- %s %s์› %s %s%n", product.getName(), formattedPrice, stockInfo, promoInfo); + } + + private void printRegularProductInfoIfMissing(List<Product> products, Product product) { + if (product.getPromotion() == null) { + return; + } + Optional<Product> regularProduct = findRegularProduct(products, product); + if (regularProduct.isEmpty()) { + String formattedPrice = getFormattedPrice(product); + System.out.printf("- %s %s์› ์žฌ๊ณ  ์—†์Œ%n", product.getName(), formattedPrice); + } + } + + private String getStockInfo(Product product) { + return product.getStock() > 0 ? product.getStock() + "๊ฐœ" : "์žฌ๊ณ  ์—†์Œ"; + } + + private String getFormattedPrice(Product product) { + return String.format("%,d", product.getPrice().getAmount()); + } + + private Optional<Product> findRegularProduct(List<Product> products, Product product) { + return products.stream() + .filter(p -> p.getName().equals(product.getName()) && p.getPromotion() == null) + .findFirst(); + } + + @Override + public void printReceipt(Receipt receipt, Cart cart, Membership membership) { + printReceiptHeader(); + printPurchasedItems(receipt); + printFreeItems(receipt); + printReceiptSummary(receipt, cart, membership); + } + + private void printReceiptHeader() { + System.out.print(ConsoleMessages.LINE_SEPARATOR); + System.out.printf("==============%-3s%s================%n", "W", "ํŽธ์˜์ "); + System.out.printf("%-10s %10s %8s%n", "์ƒํ’ˆ๋ช…", "์ˆ˜๋Ÿ‰", "๊ธˆ์•ก"); + } + + private void printPurchasedItems(Receipt receipt) { + for (CartItem item : receipt.getPurchasedItems()) { + printPurchasedItem(item); + } + } + + private void printPurchasedItem(CartItem item) { + String productName = item.getProduct().getName(); + int quantity = item.getQuantity(); + String totalPrice = String.format("%,d", item.calculateTotalPrice().getAmount()); + + if (productName.length() < 3) { + System.out.printf("%-10s %10d %13s%n", productName, quantity, totalPrice); + return; + } + System.out.printf("%-10s %9d %14s%n", productName, quantity, totalPrice); + } + + private void printFreeItems(Receipt receipt) { + System.out.printf("=============%-7s%s===============%n", "์ฆ", "์ •"); + for (CartItem item : receipt.getFreeItems()) { + printFreeItem(item); + } + } + + private void printFreeItem(CartItem item) { + String productName = item.getProduct().getName(); + int quantity = item.getFreeQuantity(); + System.out.printf("%-10s %9d%n", productName, quantity); + } + + private void printReceiptSummary(Receipt receipt, Cart cart, Membership membership) { + System.out.println("===================================="); + System.out.printf("%-10s %8d %13s%n", "์ด๊ตฌ๋งค์•ก", receipt.getTotalQuantity(), + String.format("%,d", receipt.getTotalPrice())); + System.out.printf("%-10s %22s%n", "ํ–‰์‚ฌํ• ์ธ", + String.format("-%s", String.format("%,d", receipt.getPromotionDiscount(cart)))); + System.out.printf("%-10s %30s%n", "๋ฉค๋ฒ„์‹ญํ• ์ธ", + String.format("-%s", String.format("%,d", receipt.getMembershipDiscount(cart, membership)))); + System.out.printf("%-10s %23s%n", "๋‚ด์‹ค๋ˆ", String.format("%,d", receipt.getFinalPrice(cart, membership))); + } + + @Override + public void printError(String message) { + System.out.println(ErrorMessages.ERROR_MESSAGE + message); + } + + @Override + public void close() { + Console.close(); + } +}
Java
๋„๋ฉ”์ธ์„ ์ง์ ‘ ๋ทฐ์—์„œ ์ฐธ์กฐํ•˜๋Š” ๊ฒƒ ๋ณด๋‹ค๋Š” ๋‹ค๋ฅธ ๊ฐ์ฒด์—์„œ ๋ฌธ์ž์—ด์„ ์กฐํ•ฉํ•˜์—ฌ ๊ฑด๋‚ด์ฃผ๋Š” ๊ฒƒ์ด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,124 @@ +package store.controller; + +import java.util.ArrayList; +import java.util.List; +import store.domain.Product; +import store.domain.Promotion; +import store.domain.Store; +import store.dto.PromotionApplyResult; +import store.dto.ReceiptInfo; +import store.dto.TotalProductStock; +import store.enumerate.Membership; +import store.service.MembershipService; +import store.service.ProductService; +import store.service.PromotionService; +import store.service.StoreService; +import store.validator.InputValidator; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + + private final InputView inputView; + private final OutputView outputView; + private final ProductService productService; + private final StoreService storeService; + private final InputValidator inputValidator; + private final MembershipService membershipService; + private final PromotionService promotionService; + + public StoreController(InputView inputView, OutputView outputView, ProductService productService, + StoreService storeService, InputValidator inputValidator, + MembershipService membershipService, PromotionService promotionService) { + this.inputView = inputView; + this.outputView = outputView; + this.productService = productService; + this.storeService = storeService; + this.inputValidator = inputValidator; + this.membershipService = membershipService; + this.promotionService = promotionService; + } + + public void startProcess() { + do { + promotionService.getAllPromotions(); + List<Product> stockProducts = displayStockList(); + List<Product> purchaseProducts = getPurchaseProducts(stockProducts); + List<Product> purchaseProductsForReceipt = productService.cloneProductList(purchaseProducts); + List<PromotionApplyResult> productPromotionApplyResults = getPurchaseResults(purchaseProducts, purchaseProductsForReceipt); + + ReceiptInfo receiptInfo = calculateReceiptInfoAndApplyMembership(purchaseProductsForReceipt, stockProducts, productPromotionApplyResults); + outputView.printReceipt(stockProducts, purchaseProductsForReceipt, productPromotionApplyResults, receiptInfo); + } while (isNo()); + } + + private List<Product> getPurchaseProducts(List<Product> stockProducts) { + while(true) { + try { + return getProducts(stockProducts); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private List<Product> getProducts(List<Product> stockProducts) { + String buyProductAmountInput = inputView.getBuyProductAmount(); + inputValidator.purchaseProductInputPatternValidate(buyProductAmountInput); + + List<Product> purchaseProducts = productService.parsePurchaseProductFromInput(buyProductAmountInput); + List<TotalProductStock> totalProductStocks = storeService.getTotalProductStocks(purchaseProducts); + inputValidator.purchaseProductValidate(stockProducts, purchaseProducts, totalProductStocks); + return purchaseProducts; + } + + private List<PromotionApplyResult> getPurchaseResults(List<Product> purchaseProducts, + List<Product> purchaseProductsForReceipt) { + List<Store> productPromotionStore = storeService.connectProductsPromotions(purchaseProducts); + List<PromotionApplyResult> productPromotionApplyResults = new ArrayList<>(); + for (Store productPromotion : productPromotionStore) { + storeService.purchaseProducts(productPromotion, purchaseProductsForReceipt, productPromotionApplyResults); + } + return productPromotionApplyResults; + } + + private List<Product> displayStockList() { + List<Product> productList = productService.getAllProducts(); + outputView.printWelcomeAndStockList(productList); + return productList; + } + + private static int getTotalPromotedPrice(List<PromotionApplyResult> productPromotionApplyResults) { + int totalPromotedPrice = 0; + for (PromotionApplyResult promotionApplyResult : productPromotionApplyResults) { + int promotedPrice = promotionApplyResult.getTotalPromotedPrice(); + totalPromotedPrice += promotedPrice; + } + return totalPromotedPrice; + } + + private boolean isNo() { + while(true) { + try { + String checkAdditionalPurchase = inputView.checkAdditionalPurchase(); + inputValidator.validateYesOrNoType(checkAdditionalPurchase); + return !checkAdditionalPurchase.equals("N"); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private ReceiptInfo calculateReceiptInfoAndApplyMembership(List<Product> purchaseProductsForReceipt, List<Product> stockProducts, List<PromotionApplyResult> productPromotionApplyResults) { + int totalProductPrice = productService.getTotalProductPrice(purchaseProductsForReceipt, stockProducts); //์ƒํ’ˆ ์ด์•ก + int totalPromotedPrice = getTotalPromotedPrice(productPromotionApplyResults); //ํ”„๋กœ๋ชจ์…˜์œผ๋กœ ํ• ์ธ๋œ ๊ฐ€๊ฒฉ + + int membershipDiscountAmount = 0; + if(totalProductPrice != 0 && totalProductPrice - totalPromotedPrice > 0){ + Membership membership = membershipService.checkMembership(); + membershipDiscountAmount = membershipService.applyMembership(totalProductPrice - totalPromotedPrice, membership); + } + return new ReceiptInfo(totalProductPrice, totalPromotedPrice, membershipDiscountAmount); + } + +}
Java
์˜ค๋ฅ˜ ์ถœ๋ ฅ๋„ View ํด๋ž˜์Šค์—์„œ ํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,147 @@ +package store.service; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import store.constant.ExceptionMessage; +import store.domain.Product; +import store.dto.TotalProductStock; +import store.repository.ProductRepository; +import store.view.InputView; + +public class ProductService { + + private final ProductRepository productRepository; + + public ProductService(ProductRepository productRepository) { + this.productRepository = productRepository; + } + + public List<Product> getAllProducts() { + if(productRepository.getAllProducts().isEmpty()) { + parseProducts("src/main/resources/products.md"); + } + return productRepository.getAllProducts(); + } + + public List<Product> parsePurchaseProductFromInput(String buyProductAmountsInput) { + String[] buyProductAmounts = buyProductAmountsInput.split(","); + + replaceSquareBracketsToBlank(buyProductAmounts); + + return setupBuyProducts(buyProductAmounts); + } + + public Product getPromotionProductByName(String name) { + productRepository.getPromotionProducts(); + return productRepository.getPromotionProductByName(name); + } + + public Product getRegularProductByName(String name) { + productRepository.getRegularProducts(); + return productRepository.getRegularProductByName(name); + } + + public List<Product> cloneProductList(List<Product> purchaseProducts) { + return purchaseProducts.stream() + .map(Product::clone) + .collect(Collectors.toList()); + } + + public int getTotalProductPrice(List<Product> purchaseProducts, List<Product> stockProducts) { + int totalProductPrice = 0; + for (Product buyProduct : purchaseProducts) { + int price = getProductPrice(buyProduct.getName(), stockProducts) * buyProduct.getQuantity(); + totalProductPrice += price; + } + return totalProductPrice; + } + + public int getProductPrice(String name, List<Product> stockProducts) { + for(Product product : stockProducts) { + if(product.getName().equals(name)) { + return product.getPrice(); + } + } + return 0; + } + + public void increaseTotalPurchaseAmount(String name, List<Product> purchaseProductsForReceipt, int increaseAmount) { + for (Product product : purchaseProductsForReceipt) { + if(product.getName().equals(name)) { + product.increaseQuantity(increaseAmount); + } + } + } + + public void decreaseTotalPurchaseAmount(String name, List<Product> purchaseProductsForReceipt, int decreaseAmount) { + for (Product product : purchaseProductsForReceipt) { + if(product.getName().equals(name)) { + product.decreaseQuantity(decreaseAmount); + } + } + } + + private static List<Product> setupBuyProducts(String[] buyProductAmounts) { + List<Product> buyProducts = new ArrayList<>(); + for (String buyProductAmount : buyProductAmounts) { + String[] splitProductAmount = buyProductAmount.split("-"); + Product buyProduct = new Product(splitProductAmount[0].trim(), Integer.parseInt(splitProductAmount[1].trim())); + addBuyProduct(buyProducts, buyProduct); + } + return buyProducts; + } + + private static void addBuyProduct(List<Product> buyProducts, Product buyProduct) { + boolean productExists = false; + productExists = addBuyProductAmountIfExist(buyProducts, buyProduct, productExists); + if (!productExists) { + buyProducts.add(buyProduct); + } + } + + private static boolean addBuyProductAmountIfExist(List<Product> buyProducts, Product buyProduct, boolean productExists) { + for (Product product : buyProducts) { + if (product.getName().equals(buyProduct.getName())) { + product.increaseQuantity(buyProduct.getQuantity()); + productExists = true; + break; + } + } + return productExists; + } + + private static void replaceSquareBracketsToBlank(String[] buyProductAmounts) { + for (int i = 0; i < buyProductAmounts.length; i++) { + buyProductAmounts[i] = buyProductAmounts[i].replaceAll("[\\[\\]]", "").trim(); + } + } + + private void parseProducts(String filePath) { + try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { + reader.readLine(); + parseProduct(reader); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } + } + + private void parseProduct(BufferedReader reader) throws IOException { + String line; + while((line = reader.readLine()) != null) { + String[] fields = line.split(","); + String name = fields[0]; + int price = Integer.parseInt(fields[1]); + int quantity = Integer.parseInt(fields[2]); + String promotion = fields.length > 3 ? fields[3] : null; // ์ˆ˜์ •ํ•˜๊ธฐ + productRepository.addProduct(new Product(name, price, quantity, promotion)); + } + } + + +}
Java
๊ณตํ†ต ํ”ผ๋“œ๋ฐฑ ๋‚ด์šฉ ์ค‘์— ๋ฐฐ์—ด๋ณด๋‹ค๋Š” ์ปฌ๋ ‰์…˜์„ ์ง€ํ–ฅํ•˜๋ผ๋Š” ๊ธ€์ด ์žˆ์—ˆ๋Š”๋ฐ, splitํ•ด์„œ ์ƒ๊ธด ๋ฐฐ์—ด์„ ๋ฐ”๋กœ List๋กœ ๋งŒ๋“ค๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,147 @@ +package store.service; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import store.constant.ExceptionMessage; +import store.domain.Product; +import store.dto.TotalProductStock; +import store.repository.ProductRepository; +import store.view.InputView; + +public class ProductService { + + private final ProductRepository productRepository; + + public ProductService(ProductRepository productRepository) { + this.productRepository = productRepository; + } + + public List<Product> getAllProducts() { + if(productRepository.getAllProducts().isEmpty()) { + parseProducts("src/main/resources/products.md"); + } + return productRepository.getAllProducts(); + } + + public List<Product> parsePurchaseProductFromInput(String buyProductAmountsInput) { + String[] buyProductAmounts = buyProductAmountsInput.split(","); + + replaceSquareBracketsToBlank(buyProductAmounts); + + return setupBuyProducts(buyProductAmounts); + } + + public Product getPromotionProductByName(String name) { + productRepository.getPromotionProducts(); + return productRepository.getPromotionProductByName(name); + } + + public Product getRegularProductByName(String name) { + productRepository.getRegularProducts(); + return productRepository.getRegularProductByName(name); + } + + public List<Product> cloneProductList(List<Product> purchaseProducts) { + return purchaseProducts.stream() + .map(Product::clone) + .collect(Collectors.toList()); + } + + public int getTotalProductPrice(List<Product> purchaseProducts, List<Product> stockProducts) { + int totalProductPrice = 0; + for (Product buyProduct : purchaseProducts) { + int price = getProductPrice(buyProduct.getName(), stockProducts) * buyProduct.getQuantity(); + totalProductPrice += price; + } + return totalProductPrice; + } + + public int getProductPrice(String name, List<Product> stockProducts) { + for(Product product : stockProducts) { + if(product.getName().equals(name)) { + return product.getPrice(); + } + } + return 0; + } + + public void increaseTotalPurchaseAmount(String name, List<Product> purchaseProductsForReceipt, int increaseAmount) { + for (Product product : purchaseProductsForReceipt) { + if(product.getName().equals(name)) { + product.increaseQuantity(increaseAmount); + } + } + } + + public void decreaseTotalPurchaseAmount(String name, List<Product> purchaseProductsForReceipt, int decreaseAmount) { + for (Product product : purchaseProductsForReceipt) { + if(product.getName().equals(name)) { + product.decreaseQuantity(decreaseAmount); + } + } + } + + private static List<Product> setupBuyProducts(String[] buyProductAmounts) { + List<Product> buyProducts = new ArrayList<>(); + for (String buyProductAmount : buyProductAmounts) { + String[] splitProductAmount = buyProductAmount.split("-"); + Product buyProduct = new Product(splitProductAmount[0].trim(), Integer.parseInt(splitProductAmount[1].trim())); + addBuyProduct(buyProducts, buyProduct); + } + return buyProducts; + } + + private static void addBuyProduct(List<Product> buyProducts, Product buyProduct) { + boolean productExists = false; + productExists = addBuyProductAmountIfExist(buyProducts, buyProduct, productExists); + if (!productExists) { + buyProducts.add(buyProduct); + } + } + + private static boolean addBuyProductAmountIfExist(List<Product> buyProducts, Product buyProduct, boolean productExists) { + for (Product product : buyProducts) { + if (product.getName().equals(buyProduct.getName())) { + product.increaseQuantity(buyProduct.getQuantity()); + productExists = true; + break; + } + } + return productExists; + } + + private static void replaceSquareBracketsToBlank(String[] buyProductAmounts) { + for (int i = 0; i < buyProductAmounts.length; i++) { + buyProductAmounts[i] = buyProductAmounts[i].replaceAll("[\\[\\]]", "").trim(); + } + } + + private void parseProducts(String filePath) { + try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { + reader.readLine(); + parseProduct(reader); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } + } + + private void parseProduct(BufferedReader reader) throws IOException { + String line; + while((line = reader.readLine()) != null) { + String[] fields = line.split(","); + String name = fields[0]; + int price = Integer.parseInt(fields[1]); + int quantity = Integer.parseInt(fields[2]); + String promotion = fields.length > 3 ? fields[3] : null; // ์ˆ˜์ •ํ•˜๊ธฐ + productRepository.addProduct(new Product(name, price, quantity, promotion)); + } + } + + +}
Java
ํ˜น์‹œ PRoduct md ํŒŒ์ผ์—์„œ ํ”„๋กœ๋ชจ์…˜๋งŒ ์ ํ˜€์žˆ๋Š” ์ œํ’ˆ์€ ์žฌ๊ณ ๊ฐ€ ์—†๋Š” ์ผ๋ฐ˜ ์ƒํ’ˆ๋„ ๋งŒ๋“ค์–ด์ค˜์•ผํ•˜๋Š”๋ฐ, ๊ทธ ๋กœ์ง์„ ๋ชป์ฐพ์•˜์Šต๋‹ˆ๋‹ค. ์–ด๋””์— ๋ช…์‹œ๋˜์–ด ์žˆ๋Š”์ง€ ์•Œ ์ˆ˜ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,147 @@ +package store.service; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import store.constant.ExceptionMessage; +import store.domain.Product; +import store.dto.TotalProductStock; +import store.repository.ProductRepository; +import store.view.InputView; + +public class ProductService { + + private final ProductRepository productRepository; + + public ProductService(ProductRepository productRepository) { + this.productRepository = productRepository; + } + + public List<Product> getAllProducts() { + if(productRepository.getAllProducts().isEmpty()) { + parseProducts("src/main/resources/products.md"); + } + return productRepository.getAllProducts(); + } + + public List<Product> parsePurchaseProductFromInput(String buyProductAmountsInput) { + String[] buyProductAmounts = buyProductAmountsInput.split(","); + + replaceSquareBracketsToBlank(buyProductAmounts); + + return setupBuyProducts(buyProductAmounts); + } + + public Product getPromotionProductByName(String name) { + productRepository.getPromotionProducts(); + return productRepository.getPromotionProductByName(name); + } + + public Product getRegularProductByName(String name) { + productRepository.getRegularProducts(); + return productRepository.getRegularProductByName(name); + } + + public List<Product> cloneProductList(List<Product> purchaseProducts) { + return purchaseProducts.stream() + .map(Product::clone) + .collect(Collectors.toList()); + } + + public int getTotalProductPrice(List<Product> purchaseProducts, List<Product> stockProducts) { + int totalProductPrice = 0; + for (Product buyProduct : purchaseProducts) { + int price = getProductPrice(buyProduct.getName(), stockProducts) * buyProduct.getQuantity(); + totalProductPrice += price; + } + return totalProductPrice; + } + + public int getProductPrice(String name, List<Product> stockProducts) { + for(Product product : stockProducts) { + if(product.getName().equals(name)) { + return product.getPrice(); + } + } + return 0; + } + + public void increaseTotalPurchaseAmount(String name, List<Product> purchaseProductsForReceipt, int increaseAmount) { + for (Product product : purchaseProductsForReceipt) { + if(product.getName().equals(name)) { + product.increaseQuantity(increaseAmount); + } + } + } + + public void decreaseTotalPurchaseAmount(String name, List<Product> purchaseProductsForReceipt, int decreaseAmount) { + for (Product product : purchaseProductsForReceipt) { + if(product.getName().equals(name)) { + product.decreaseQuantity(decreaseAmount); + } + } + } + + private static List<Product> setupBuyProducts(String[] buyProductAmounts) { + List<Product> buyProducts = new ArrayList<>(); + for (String buyProductAmount : buyProductAmounts) { + String[] splitProductAmount = buyProductAmount.split("-"); + Product buyProduct = new Product(splitProductAmount[0].trim(), Integer.parseInt(splitProductAmount[1].trim())); + addBuyProduct(buyProducts, buyProduct); + } + return buyProducts; + } + + private static void addBuyProduct(List<Product> buyProducts, Product buyProduct) { + boolean productExists = false; + productExists = addBuyProductAmountIfExist(buyProducts, buyProduct, productExists); + if (!productExists) { + buyProducts.add(buyProduct); + } + } + + private static boolean addBuyProductAmountIfExist(List<Product> buyProducts, Product buyProduct, boolean productExists) { + for (Product product : buyProducts) { + if (product.getName().equals(buyProduct.getName())) { + product.increaseQuantity(buyProduct.getQuantity()); + productExists = true; + break; + } + } + return productExists; + } + + private static void replaceSquareBracketsToBlank(String[] buyProductAmounts) { + for (int i = 0; i < buyProductAmounts.length; i++) { + buyProductAmounts[i] = buyProductAmounts[i].replaceAll("[\\[\\]]", "").trim(); + } + } + + private void parseProducts(String filePath) { + try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { + reader.readLine(); + parseProduct(reader); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } + } + + private void parseProduct(BufferedReader reader) throws IOException { + String line; + while((line = reader.readLine()) != null) { + String[] fields = line.split(","); + String name = fields[0]; + int price = Integer.parseInt(fields[1]); + int quantity = Integer.parseInt(fields[2]); + String promotion = fields.length > 3 ? fields[3] : null; // ์ˆ˜์ •ํ•˜๊ธฐ + productRepository.addProduct(new Product(name, price, quantity, promotion)); + } + } + + +}
Java
addBuyProductAmountIfExist๋ผ๋Š” ๋ฉ”์„œ๋“œ๊ฐ€ ์กด์žฌ ์—ฌ๋ถ€๋„ ํ™•์ธํ•˜๊ณ , ๊ตฌ๋งค๊นŒ์ง€ ํ•ด์ฃผ๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ, ์ด ๋‘˜์„ ๋ถ„๋ฆฌํ•˜๋Š” ๊ฒƒ์— ๋Œ€ํ•ด์„œ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,147 @@ +package store.service; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import store.constant.ExceptionMessage; +import store.domain.Product; +import store.dto.TotalProductStock; +import store.repository.ProductRepository; +import store.view.InputView; + +public class ProductService { + + private final ProductRepository productRepository; + + public ProductService(ProductRepository productRepository) { + this.productRepository = productRepository; + } + + public List<Product> getAllProducts() { + if(productRepository.getAllProducts().isEmpty()) { + parseProducts("src/main/resources/products.md"); + } + return productRepository.getAllProducts(); + } + + public List<Product> parsePurchaseProductFromInput(String buyProductAmountsInput) { + String[] buyProductAmounts = buyProductAmountsInput.split(","); + + replaceSquareBracketsToBlank(buyProductAmounts); + + return setupBuyProducts(buyProductAmounts); + } + + public Product getPromotionProductByName(String name) { + productRepository.getPromotionProducts(); + return productRepository.getPromotionProductByName(name); + } + + public Product getRegularProductByName(String name) { + productRepository.getRegularProducts(); + return productRepository.getRegularProductByName(name); + } + + public List<Product> cloneProductList(List<Product> purchaseProducts) { + return purchaseProducts.stream() + .map(Product::clone) + .collect(Collectors.toList()); + } + + public int getTotalProductPrice(List<Product> purchaseProducts, List<Product> stockProducts) { + int totalProductPrice = 0; + for (Product buyProduct : purchaseProducts) { + int price = getProductPrice(buyProduct.getName(), stockProducts) * buyProduct.getQuantity(); + totalProductPrice += price; + } + return totalProductPrice; + } + + public int getProductPrice(String name, List<Product> stockProducts) { + for(Product product : stockProducts) { + if(product.getName().equals(name)) { + return product.getPrice(); + } + } + return 0; + } + + public void increaseTotalPurchaseAmount(String name, List<Product> purchaseProductsForReceipt, int increaseAmount) { + for (Product product : purchaseProductsForReceipt) { + if(product.getName().equals(name)) { + product.increaseQuantity(increaseAmount); + } + } + } + + public void decreaseTotalPurchaseAmount(String name, List<Product> purchaseProductsForReceipt, int decreaseAmount) { + for (Product product : purchaseProductsForReceipt) { + if(product.getName().equals(name)) { + product.decreaseQuantity(decreaseAmount); + } + } + } + + private static List<Product> setupBuyProducts(String[] buyProductAmounts) { + List<Product> buyProducts = new ArrayList<>(); + for (String buyProductAmount : buyProductAmounts) { + String[] splitProductAmount = buyProductAmount.split("-"); + Product buyProduct = new Product(splitProductAmount[0].trim(), Integer.parseInt(splitProductAmount[1].trim())); + addBuyProduct(buyProducts, buyProduct); + } + return buyProducts; + } + + private static void addBuyProduct(List<Product> buyProducts, Product buyProduct) { + boolean productExists = false; + productExists = addBuyProductAmountIfExist(buyProducts, buyProduct, productExists); + if (!productExists) { + buyProducts.add(buyProduct); + } + } + + private static boolean addBuyProductAmountIfExist(List<Product> buyProducts, Product buyProduct, boolean productExists) { + for (Product product : buyProducts) { + if (product.getName().equals(buyProduct.getName())) { + product.increaseQuantity(buyProduct.getQuantity()); + productExists = true; + break; + } + } + return productExists; + } + + private static void replaceSquareBracketsToBlank(String[] buyProductAmounts) { + for (int i = 0; i < buyProductAmounts.length; i++) { + buyProductAmounts[i] = buyProductAmounts[i].replaceAll("[\\[\\]]", "").trim(); + } + } + + private void parseProducts(String filePath) { + try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { + reader.readLine(); + parseProduct(reader); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } + } + + private void parseProduct(BufferedReader reader) throws IOException { + String line; + while((line = reader.readLine()) != null) { + String[] fields = line.split(","); + String name = fields[0]; + int price = Integer.parseInt(fields[1]); + int quantity = Integer.parseInt(fields[2]); + String promotion = fields.length > 3 ? fields[3] : null; // ์ˆ˜์ •ํ•˜๊ธฐ + productRepository.addProduct(new Product(name, price, quantity, promotion)); + } + } + + +}
Java
break๋ง๊ณ  return true๋กœ ํ•œ๋‹ค๋ฉด ๊ตณ์ด productExists๋ฅผ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์•ˆ๋„˜๊ฒจ๋„ ๋  ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,156 @@ +package store.service; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import store.domain.Product; +import store.domain.Promotion; +import store.domain.Store; +import store.dto.PromotionApplyResult; +import store.dto.PromotionInfo; +import store.dto.TotalProductStock; + +public class StoreService { + + private final ProductService productService; + private final PromotionService promotionService; + + public StoreService(ProductService productService, PromotionService promotionService) { + this.productService = productService; + this.promotionService = promotionService; + } + + public List<TotalProductStock> getTotalProductStocks(List<Product> buyProducts) { + return getTotalProductStock(buyProducts) + .collect(Collectors.toList()); + } + + public List<Store> connectProductsPromotions(List<Product> buyProducts) { + List<Store> applyResults = new ArrayList<>(); + Map<String, Promotion> activePromotions = promotionService.findActivePromotions(buyProducts); + purchaseProductStart(buyProducts, activePromotions, applyResults); + return applyResults; + } + + public void purchaseProducts(Store productPromotion, List<Product> buyProductsForReceipt, List<PromotionApplyResult> productPromotionApplyResults) { + Product purchaseProduct = productPromotion.getProduct(); + Promotion appliedPromotion = productPromotion.getPromotion(); + if(appliedPromotion == null) { + purchaseRegularProduct(purchaseProduct, productService.getRegularProductByName(purchaseProduct.getName())); + return; + } + PromotionApplyResult promotionApplyResult = purchasePromotionProduct(purchaseProduct, appliedPromotion, buyProductsForReceipt); + productPromotionApplyResults.add(promotionApplyResult); + } + + public PromotionApplyResult purchasePromotionProduct(Product buyProduct, Promotion promotion, List<Product> purchaseProductsForReceipt) { + PromotionInfo promotionInfo = setupPromotionInfo(promotion); + Product promotionProduct = productService.getPromotionProductByName(buyProduct.getName()); + PromotionApplyResult promotionApplyResult = new PromotionApplyResult(buyProduct, 0, 0, 0); + + purchaseProcess(buyProduct, promotion, purchaseProductsForReceipt, promotionInfo, promotionProduct, + promotionApplyResult); + return promotionApplyResult; + } + + public void purchaseRegularProduct(Product purchaseProduct, Product stock) { + if(purchaseProduct.getQuantity() > 0) { + if(!stock.getPromotion().isBlank()) purchaseProductFromPromotionStock(purchaseProduct, stock); + purchaseProductFromRegularStock(purchaseProduct); + } + } + + private void purchaseProcess(Product buyProduct, Promotion promotion, List<Product> purchaseProductsForReceipt, + PromotionInfo promotionInfo, Product promotionProduct, + PromotionApplyResult promotionApplyResult) { + boolean isExtraPromotionProductApproved = applyPromotionProcess(buyProduct, purchaseProductsForReceipt, + promotionInfo, promotionProduct, promotionApplyResult); + if(isExtraPromotionProductApproved && buyProduct.getQuantity() > 0 && !promotion.getName().isBlank()) { + promotionService.checkPurchaseWithoutPromotion(buyProduct, purchaseProductsForReceipt); + } + purchaseRegularProduct(buyProduct, promotionProduct); + } + + private static void purchaseProductStart(List<Product> buyProducts, Map<String, Promotion> activePromotions, + List<Store> applyResults) { + for (Product buyProduct : buyProducts) { + Promotion promotion = activePromotions.get(buyProduct.getName()); + if(promotion != null) { + applyResults.add(new Store(buyProduct, promotion)); + continue; + } + applyResults.add(new Store(buyProduct, null)); + } + } + + private PromotionInfo setupPromotionInfo(Promotion promotion) { + return new PromotionInfo(promotion.getBuyAmount(), promotion.getGetAmount()); + } + + private boolean applyPromotionProcess(Product buyProduct, List<Product> purchaseProductsForReceipt, PromotionInfo promotionInfo, Product promotionProduct, PromotionApplyResult promotionApplyResult) { + boolean isExtraPromotionProductApproved = true; + while (buyProduct.getQuantity() >= promotionInfo.getPromotionBuyAmount() && promotionProduct.getQuantity() >= promotionInfo.getPromotionTotalAmount()) { + if (!promotionService.applyExtraForPromo(buyProduct, purchaseProductsForReceipt, promotionInfo)) { + isExtraPromotionProductApproved = false; + break; + } + calculatePromotionTotals(buyProduct, promotionProduct, promotionInfo, promotionApplyResult); + } + return isExtraPromotionProductApproved; + } + + private void calculatePromotionTotals(Product buyProduct, Product promotionProduct, PromotionInfo promotionInfo, PromotionApplyResult promotionApplyResult) { + promotionApplyResult.addTotalGetAmount(promotionInfo.getPromotionGetAmount()); + promotionApplyResult.addTotalPromotedPrice(promotionInfo.getPromotionTotalAmount() * promotionProduct.getPrice()); + promotionApplyResult.addTotalPromotedSalePrice(promotionInfo.getPromotionGetAmount() * promotionProduct.getPrice()); + buyProduct.decreaseQuantity(promotionInfo.getPromotionTotalAmount()); + promotionProduct.decreaseQuantity(promotionInfo.getPromotionTotalAmount()); + } + + private void purchaseProductFromRegularStock(Product purchaseProduct) { + int remainPurchaseProductQuantity = purchaseProduct.getQuantity(); + if(remainPurchaseProductQuantity > 0) { + Product regularProduct = productService.getRegularProductByName(purchaseProduct.getName()); + regularProduct.decreaseQuantity(remainPurchaseProductQuantity); + purchaseProduct.decreaseQuantity(remainPurchaseProductQuantity); + } + } + + private static void purchaseProductFromPromotionStock(Product purchaseProduct, Product stock) { + int promotionProductQuantity = stock.getQuantity(); + if(promotionProductQuantity > 0) { //ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๋ถ€ํ„ฐ ์†Œ์ง„ ์‹œํ‚ค๊ธฐ + int purchaseQuantity = purchaseProduct.getQuantity(); + if(purchaseQuantity > promotionProductQuantity) purchaseQuantity = promotionProductQuantity; + stock.decreaseQuantity(purchaseQuantity); + purchaseProduct.decreaseQuantity(purchaseQuantity); + } + } + + private Stream<TotalProductStock> getTotalProductStock(List<Product> buyProducts) { + return buyProducts.stream().map(buyProduct -> { + String name = buyProduct.getName(); + Product promotionProduct = productService.getPromotionProductByName(name); + int promotionQuantity = getPromotionStockQuantity(promotionProduct); + + int regularQuantity = getRegularStockQuantity(name); + + return new TotalProductStock(name, promotionQuantity + regularQuantity); + }); + } + + private int getRegularStockQuantity(String name) { + int regularQuantity = Optional.ofNullable(productService.getRegularProductByName(name)) + .map(Product::getQuantity).orElse(0); + return regularQuantity; + } + + private int getPromotionStockQuantity(Product promotionProduct) { + int promotionQuantity = Optional.ofNullable(promotionProduct) + .filter(prod -> promotionService.isPromotionActive(promotionService.getPromotionByName(prod.getPromotion()))) + .map(Product::getQuantity).orElse(0); + return promotionQuantity; + } +}
Java
ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ€ ๋„ˆ๋ฌด ๋งŽ์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ค„์ด๋Š” ๋ฐฉํ–ฅ์œผ๋กœ ๋ฉ”์„œ๋“œ๋ฅผ ๋งŒ๋“ค๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,147 @@ +package store.service; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import store.constant.ExceptionMessage; +import store.domain.Product; +import store.dto.TotalProductStock; +import store.repository.ProductRepository; +import store.view.InputView; + +public class ProductService { + + private final ProductRepository productRepository; + + public ProductService(ProductRepository productRepository) { + this.productRepository = productRepository; + } + + public List<Product> getAllProducts() { + if(productRepository.getAllProducts().isEmpty()) { + parseProducts("src/main/resources/products.md"); + } + return productRepository.getAllProducts(); + } + + public List<Product> parsePurchaseProductFromInput(String buyProductAmountsInput) { + String[] buyProductAmounts = buyProductAmountsInput.split(","); + + replaceSquareBracketsToBlank(buyProductAmounts); + + return setupBuyProducts(buyProductAmounts); + } + + public Product getPromotionProductByName(String name) { + productRepository.getPromotionProducts(); + return productRepository.getPromotionProductByName(name); + } + + public Product getRegularProductByName(String name) { + productRepository.getRegularProducts(); + return productRepository.getRegularProductByName(name); + } + + public List<Product> cloneProductList(List<Product> purchaseProducts) { + return purchaseProducts.stream() + .map(Product::clone) + .collect(Collectors.toList()); + } + + public int getTotalProductPrice(List<Product> purchaseProducts, List<Product> stockProducts) { + int totalProductPrice = 0; + for (Product buyProduct : purchaseProducts) { + int price = getProductPrice(buyProduct.getName(), stockProducts) * buyProduct.getQuantity(); + totalProductPrice += price; + } + return totalProductPrice; + } + + public int getProductPrice(String name, List<Product> stockProducts) { + for(Product product : stockProducts) { + if(product.getName().equals(name)) { + return product.getPrice(); + } + } + return 0; + } + + public void increaseTotalPurchaseAmount(String name, List<Product> purchaseProductsForReceipt, int increaseAmount) { + for (Product product : purchaseProductsForReceipt) { + if(product.getName().equals(name)) { + product.increaseQuantity(increaseAmount); + } + } + } + + public void decreaseTotalPurchaseAmount(String name, List<Product> purchaseProductsForReceipt, int decreaseAmount) { + for (Product product : purchaseProductsForReceipt) { + if(product.getName().equals(name)) { + product.decreaseQuantity(decreaseAmount); + } + } + } + + private static List<Product> setupBuyProducts(String[] buyProductAmounts) { + List<Product> buyProducts = new ArrayList<>(); + for (String buyProductAmount : buyProductAmounts) { + String[] splitProductAmount = buyProductAmount.split("-"); + Product buyProduct = new Product(splitProductAmount[0].trim(), Integer.parseInt(splitProductAmount[1].trim())); + addBuyProduct(buyProducts, buyProduct); + } + return buyProducts; + } + + private static void addBuyProduct(List<Product> buyProducts, Product buyProduct) { + boolean productExists = false; + productExists = addBuyProductAmountIfExist(buyProducts, buyProduct, productExists); + if (!productExists) { + buyProducts.add(buyProduct); + } + } + + private static boolean addBuyProductAmountIfExist(List<Product> buyProducts, Product buyProduct, boolean productExists) { + for (Product product : buyProducts) { + if (product.getName().equals(buyProduct.getName())) { + product.increaseQuantity(buyProduct.getQuantity()); + productExists = true; + break; + } + } + return productExists; + } + + private static void replaceSquareBracketsToBlank(String[] buyProductAmounts) { + for (int i = 0; i < buyProductAmounts.length; i++) { + buyProductAmounts[i] = buyProductAmounts[i].replaceAll("[\\[\\]]", "").trim(); + } + } + + private void parseProducts(String filePath) { + try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { + reader.readLine(); + parseProduct(reader); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } + } + + private void parseProduct(BufferedReader reader) throws IOException { + String line; + while((line = reader.readLine()) != null) { + String[] fields = line.split(","); + String name = fields[0]; + int price = Integer.parseInt(fields[1]); + int quantity = Integer.parseInt(fields[2]); + String promotion = fields.length > 3 ? fields[3] : null; // ์ˆ˜์ •ํ•˜๊ธฐ + productRepository.addProduct(new Product(name, price, quantity, promotion)); + } + } + + +}
Java
indent depth๋„ ์ค„์–ด๋“ค๊ณ  ์ฑ…์ž„๋„ ํ•˜๋‚˜๋งŒ ๊ฐ€์ง€๊ณ  ๊ทธ๊ฒŒ ์ข‹์„๊ฑฐ ๊ฐ™๋„ค์š”! ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,147 @@ +package store.service; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import store.constant.ExceptionMessage; +import store.domain.Product; +import store.dto.TotalProductStock; +import store.repository.ProductRepository; +import store.view.InputView; + +public class ProductService { + + private final ProductRepository productRepository; + + public ProductService(ProductRepository productRepository) { + this.productRepository = productRepository; + } + + public List<Product> getAllProducts() { + if(productRepository.getAllProducts().isEmpty()) { + parseProducts("src/main/resources/products.md"); + } + return productRepository.getAllProducts(); + } + + public List<Product> parsePurchaseProductFromInput(String buyProductAmountsInput) { + String[] buyProductAmounts = buyProductAmountsInput.split(","); + + replaceSquareBracketsToBlank(buyProductAmounts); + + return setupBuyProducts(buyProductAmounts); + } + + public Product getPromotionProductByName(String name) { + productRepository.getPromotionProducts(); + return productRepository.getPromotionProductByName(name); + } + + public Product getRegularProductByName(String name) { + productRepository.getRegularProducts(); + return productRepository.getRegularProductByName(name); + } + + public List<Product> cloneProductList(List<Product> purchaseProducts) { + return purchaseProducts.stream() + .map(Product::clone) + .collect(Collectors.toList()); + } + + public int getTotalProductPrice(List<Product> purchaseProducts, List<Product> stockProducts) { + int totalProductPrice = 0; + for (Product buyProduct : purchaseProducts) { + int price = getProductPrice(buyProduct.getName(), stockProducts) * buyProduct.getQuantity(); + totalProductPrice += price; + } + return totalProductPrice; + } + + public int getProductPrice(String name, List<Product> stockProducts) { + for(Product product : stockProducts) { + if(product.getName().equals(name)) { + return product.getPrice(); + } + } + return 0; + } + + public void increaseTotalPurchaseAmount(String name, List<Product> purchaseProductsForReceipt, int increaseAmount) { + for (Product product : purchaseProductsForReceipt) { + if(product.getName().equals(name)) { + product.increaseQuantity(increaseAmount); + } + } + } + + public void decreaseTotalPurchaseAmount(String name, List<Product> purchaseProductsForReceipt, int decreaseAmount) { + for (Product product : purchaseProductsForReceipt) { + if(product.getName().equals(name)) { + product.decreaseQuantity(decreaseAmount); + } + } + } + + private static List<Product> setupBuyProducts(String[] buyProductAmounts) { + List<Product> buyProducts = new ArrayList<>(); + for (String buyProductAmount : buyProductAmounts) { + String[] splitProductAmount = buyProductAmount.split("-"); + Product buyProduct = new Product(splitProductAmount[0].trim(), Integer.parseInt(splitProductAmount[1].trim())); + addBuyProduct(buyProducts, buyProduct); + } + return buyProducts; + } + + private static void addBuyProduct(List<Product> buyProducts, Product buyProduct) { + boolean productExists = false; + productExists = addBuyProductAmountIfExist(buyProducts, buyProduct, productExists); + if (!productExists) { + buyProducts.add(buyProduct); + } + } + + private static boolean addBuyProductAmountIfExist(List<Product> buyProducts, Product buyProduct, boolean productExists) { + for (Product product : buyProducts) { + if (product.getName().equals(buyProduct.getName())) { + product.increaseQuantity(buyProduct.getQuantity()); + productExists = true; + break; + } + } + return productExists; + } + + private static void replaceSquareBracketsToBlank(String[] buyProductAmounts) { + for (int i = 0; i < buyProductAmounts.length; i++) { + buyProductAmounts[i] = buyProductAmounts[i].replaceAll("[\\[\\]]", "").trim(); + } + } + + private void parseProducts(String filePath) { + try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { + reader.readLine(); + parseProduct(reader); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } + } + + private void parseProduct(BufferedReader reader) throws IOException { + String line; + while((line = reader.readLine()) != null) { + String[] fields = line.split(","); + String name = fields[0]; + int price = Integer.parseInt(fields[1]); + int quantity = Integer.parseInt(fields[2]); + String promotion = fields.length > 3 ? fields[3] : null; // ์ˆ˜์ •ํ•˜๊ธฐ + productRepository.addProduct(new Product(name, price, quantity, promotion)); + } + } + + +}
Java
๊ทธ๊ฑธ ๋ชปํ•ด์„œ 3/4์ž…๋‹ˆ๋‹ค,,
@@ -0,0 +1,124 @@ +package store.controller; + +import java.io.IOException; +import java.util.List; +import store.constant.ConstantBox; +import store.dto.PurchaseResponse; +import store.dto.ReceiptInformation; +import store.exception.InputException; +import store.model.domain.PurchaseResponseCode; +import store.model.domain.StockManager; +import store.model.domain.input.CustomerRespond; +import store.model.domain.input.ProductsInput; +import store.model.domain.product.ProductsDisplayData; +import store.view.inputview.InputView; +import store.view.inputview.InputViewType; +import store.view.outputview.OutputView; +import store.view.outputview.OutputViewFactory; + +public class StoreController { + + private InputView inputView; + private OutputView outputView; + private StockManager stockManager; + + public StoreController(InputView inputView, StockManager stockManager) { + this.inputView = inputView; + this.stockManager = stockManager; + } + + public void run() throws IOException { + while (true) { + displayStore(); + List<String> requestProducts = getRequestProducts(); + handlePurchase(requestProducts); + ReceiptInformation receiptInformation = getReceiptInformation(); + displayReceipt(receiptInformation); + CustomerRespond continueShopping = getContinueRespond(); + if (!continueShopping.doesCustomerAgree()) { + break; + } + } + } + + private CustomerRespond getContinueRespond() { + inputView.showRequestMessageOf(InputViewType.CONTINUE_SHOPPING); + return getCustomerRespond(); + } + + private void handlePurchase(List<String> requestProducts) { + for (String requestProduct : requestProducts) { + PurchaseResponse purchaseResponse = getPurchaseResponse(requestProduct); + PurchaseResponseCode purchaseResponseCode = purchaseResponse.getPurchaseResponseCode(); + CustomerRespond customerRespond = announceAndGetRespond(purchaseResponseCode, purchaseResponse); + stockManager.updateReceipt(customerRespond, purchaseResponse); + } + } + + private CustomerRespond announceAndGetRespond(PurchaseResponseCode purchaseResponseCode, + PurchaseResponse purchaseResponse) { + if (purchaseResponseCode.equals(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE)) { + inputView.showRequestMessageOf(InputViewType.PROMOTION_PARTIAL_UNAVAILABLE, purchaseResponse); + return getCustomerRespond(); + } + if (purchaseResponseCode.equals(PurchaseResponseCode.FREE_PRODUCT_REMIND)) { + inputView.showRequestMessageOf(InputViewType.FREE_PRODUCT_REMIND, purchaseResponse); + return getCustomerRespond(); + } + return null; + } + + private PurchaseResponse getPurchaseResponse(String requestProduct) { + String requestProductName = requestProduct.split(ConstantBox.INPUT_SEPARATOR)[0]; + int requestQuantity = Integer.parseInt(requestProduct.split(ConstantBox.INPUT_SEPARATOR)[1]); + return stockManager.getPurchaseResponseFrom(requestProductName, requestQuantity); + } + + private void displayReceipt(ReceiptInformation receiptInformation) { + outputView = OutputViewFactory.createReceiptDisplayView(receiptInformation); + outputView.display(); + } + + private ReceiptInformation getReceiptInformation() { + inputView.showRequestMessageOf(InputViewType.MEMBERSHIP); + CustomerRespond membershipRespond = getCustomerRespond(); + return stockManager.getReceiptInformation(membershipRespond); + } + + private List<String> getRequestProducts() { + inputView.showRequestMessageOf(InputViewType.PRODUCTS_NAME_AMOUNT); + while (true) { + try { + ProductsInput productsInput = new ProductsInput(inputView.getInput()); + List<String> requestProducts = productsInput.getRequestProducts(); + for (String requestProduct : requestProducts) { + String requestProductName = requestProduct.split(ConstantBox.INPUT_SEPARATOR)[0]; + int requestQuantity = Integer.parseInt(requestProduct.split(ConstantBox.INPUT_SEPARATOR)[1]); + stockManager.checkNotExistProductException(requestProductName); + stockManager.checkOverStockAmountException(requestProductName, requestQuantity); + } + return requestProducts; + } catch (InputException e) { + System.out.println(e.getMessage()); + } + } + } + + private CustomerRespond getCustomerRespond() { + CustomerRespond customerRespond; + while (true) { + try { + return new CustomerRespond(inputView.getInput()); + } catch (InputException e) { + System.out.println(e.getMessage()); + } + } + } + + private void displayStore() { + List<ProductsDisplayData> displayDatas = stockManager.getDisplayDatas(); + outputView = OutputViewFactory.createProductDisplayView(displayDatas); + outputView.display(); + } +} +
Java
ํ•ด๋‹น ๋ถ€๋ถ„์— ๋Œ€ํ•ด์„œ ๋ฉ”์„œ๋“œ ๋ถ„๋ฆฌ๋ฅผ ํ•˜๋ฉด ์ถ”์ƒํ™” ์ธก๋ฉด์ด๋‚˜ ๊ฐ€๋…์„ฑ ์ธก๋ฉด์—์„œ ๋” ์ข‹์€ ์ฝ”๋“œ๊ฐ€ ๋  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,31 @@ +package store.dto; + +import java.util.List; +import java.util.Map; + +public class ReceiptInformation { + + private Map<String, List> salesDatas; + private List<Integer> amountInformation; + + public ReceiptInformation(Map<String, List> salesDatas, List<Integer> amountInformation) { + this.salesDatas = salesDatas; + this.amountInformation = amountInformation; + } + + public Map<String, List> getSalesDatas() { + return salesDatas; + } + + public void setSalesDatas(Map<String, List> salesDatas) { + this.salesDatas = salesDatas; + } + + public List<Integer> getAmountInformation() { + return amountInformation; + } + + public void setAmountInformation(List<Integer> amountInformation) { + this.amountInformation = amountInformation; + } +}
Java
`XXXInformation`๊ณผ ๊ฐ™์€ ๋„ค์ด๋ฐ๋ณด๋‹ค๋Š” ์–ด๋–ค ์ •๋ณด๊ฐ€ ๋‹ด๊ฒจ์žˆ๋Š”์ง€ ํ‘œํ˜„ํ•˜์‹œ๋ฉด ๋” ์ดํ•ดํ•˜๊ธฐ ์‰ฌ์šด ์ฝ”๋“œ๊ฐ€ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,80 @@ +package store.model.domain; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import store.dto.ReceiptInformation; +import store.dto.SalesData; +import store.model.domain.input.CustomerRespond; + +public class Receipt { + + private static final int ZERO = 0; + public static final int MAX_MEMBERSHIP_DISCOUNT = 8000; + public static final int MIN_MEMBERSHIP_DISCOUNT = 1000; + + private final List<String> names = new ArrayList<>(); + private final List<Integer> quantities = new ArrayList<>(); + private final List<Integer> prices = new ArrayList<>(); + private final List<Integer> promotionCounts = new ArrayList<>(); + + public void addSalesData(SalesData salesData) { + names.add(salesData.getName()); + quantities.add(salesData.getQuantity()); + prices.add(salesData.getPrice()); + promotionCounts.add(salesData.getPromotionCount()); + } + + public ReceiptInformation getReceiptInformation(CustomerRespond membershipRespond) { + int totalPurchased = ZERO; + int promotionDiscount = ZERO; + int totalQuantity = ZERO; + List<Integer> amountInformation = generateAmountInformation(membershipRespond, totalPurchased, + promotionDiscount, totalQuantity); + Map<String, List> salesDatas = generateSalesDatas(); + return new ReceiptInformation(salesDatas, amountInformation); + } + + private List<Integer> generateAmountInformation(CustomerRespond membershipRespond, int totalPurchased, + int promotionDiscount, + int totalQuantity) { + for (int productKindIndex = ZERO; productKindIndex < names.size(); productKindIndex++) { + totalPurchased += quantities.get(productKindIndex) * prices.get(productKindIndex); + promotionDiscount += promotionCounts.get(productKindIndex) * prices.get(productKindIndex); + totalQuantity += quantities.get(productKindIndex); + } + int memberShipDiscount = getMembershipDiscount(membershipRespond, totalPurchased, promotionDiscount); + int pay = totalPurchased - promotionDiscount - memberShipDiscount; + return List.of(totalQuantity, totalPurchased, promotionDiscount, memberShipDiscount, pay); + } + + private int getMembershipDiscount(CustomerRespond membershipRespond, int totalPurchasedAmount, + int promotionDiscountAmount) { + if (!membershipRespond.doesCustomerAgree()) { + return ZERO; + } + return calculateMembershipDiscount(totalPurchasedAmount, promotionDiscountAmount); + } + + private static int calculateMembershipDiscount(int totalPurchasedAmount, int promotionDiscountAmount) { + double discount = (totalPurchasedAmount - promotionDiscountAmount) * 0.3; + int memberShipDiscountAmount = ((int) discount / 1000) * 1000; + if (memberShipDiscountAmount < MIN_MEMBERSHIP_DISCOUNT) { + return ZERO; + } + if (memberShipDiscountAmount > MAX_MEMBERSHIP_DISCOUNT) { + return MAX_MEMBERSHIP_DISCOUNT; + } + return memberShipDiscountAmount; + } + + private Map<String, List> generateSalesDatas() { + return Map.of( + "names", Collections.unmodifiableList(names), + "quantities", Collections.unmodifiableList(quantities), + "prices", Collections.unmodifiableList(prices), + "promotionCounts", Collections.unmodifiableList(promotionCounts) + ); + } +}
Java
0์ด๋ผ๋Š” ์ˆ˜๋ฅผ ์ƒ์ˆ˜ํ™”ํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,22 @@ +package store.model.domain.product; + +import java.util.List; +import java.util.Map; +import store.model.domain.Promotion; + +public class ProductFactory { + + private ProductFactory() { + } + + public static Product createProductFrom(List<String> productData, Map<String, Promotion> promotions) { + String name = productData.get(0); + int price = Integer.parseInt(productData.get(1)); + int quantity = Integer.parseInt(productData.get(2)); + String promotion_name = productData.get(3); + if (promotion_name.equals("null")) { + return new NormalProduct(name, price, quantity); + } + return new PromotionProduct(name, price, quantity, promotions.get(promotion_name)); + } +}
Java
๋ฌผํ’ˆ์„ ์ผ๋ฐ˜ ๋ฌผํ’ˆ๊ณผ ํ”„๋กœ๋ชจ์…˜ ๋ฌผํ’ˆ์œผ๋กœ ๋‚˜๋ˆ„์–ด ํŒฉํ† ๋ฆฌ ํŒจํ„ด์„ ์‚ฌ์šฉํ•˜์‹  ๋ถ€๋ถ„์ด ์ข‹์•„๋ณด์ด๋„ค์š” ๐Ÿ‘
@@ -0,0 +1,28 @@ +package store.model.domain.product; + +public class ProductsDisplayData { + + private String promotionProductData; + private String normalProductData; + + public ProductsDisplayData(String promotionProductData, String normalProductData) { + this.promotionProductData = promotionProductData; + this.normalProductData = normalProductData; + } + + public String getPromotionProductData() { + return promotionProductData; + } + + public void setPromotionProductData(String promotionProductData) { + this.promotionProductData = promotionProductData; + } + + public String getNormalProductData() { + return normalProductData; + } + + public void setNormalProductData(String normalProductData) { + this.normalProductData = normalProductData; + } +}
Java
ํ•ด๋‹น ๋ถ€๋ถ„์€ OutputView์—์„œ ์ถœ๋ ฅํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉํ•˜์‹œ๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ ๊ทธ๊ฒŒ ๋งž๋‹ค๋ฉด DTO๋กœ ๋ถ„๋ฅ˜ํ•˜์…”๋„ ๊ดœ์ฐฎ์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,9 @@ +package store.constant; + +public class ConstantBox { + public static final String SEPARATOR = ","; + public static final String NO_QUANTITY = "0"; + public static final String INPUT_SEPARATOR = "-"; + public static final String CUSTOMER_RESPOND_Y = "Y"; + public static final String CUSTOMER_RESPOND_N = "N"; +}
Java
์—ฌ๋Ÿฌ ๋Œ€์•ˆ์ด ์žˆ์—ˆ์„ ๊ฒƒ ๊ฐ™์€๋ฐ, ํ•ด๋‹น ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ด์š”! (์‚ฌ์šฉํ•˜๋Š” ํด๋ž˜์Šค ๋‚ด๋ถ€ ์ƒ์ˆ˜์ฒ˜๋ฆฌ ๋ผ๋˜์ง€, enum ์ด๋ผ๋˜์ง€...)
@@ -0,0 +1,124 @@ +package store.controller; + +import java.io.IOException; +import java.util.List; +import store.constant.ConstantBox; +import store.dto.PurchaseResponse; +import store.dto.ReceiptInformation; +import store.exception.InputException; +import store.model.domain.PurchaseResponseCode; +import store.model.domain.StockManager; +import store.model.domain.input.CustomerRespond; +import store.model.domain.input.ProductsInput; +import store.model.domain.product.ProductsDisplayData; +import store.view.inputview.InputView; +import store.view.inputview.InputViewType; +import store.view.outputview.OutputView; +import store.view.outputview.OutputViewFactory; + +public class StoreController { + + private InputView inputView; + private OutputView outputView; + private StockManager stockManager; + + public StoreController(InputView inputView, StockManager stockManager) { + this.inputView = inputView; + this.stockManager = stockManager; + } + + public void run() throws IOException { + while (true) { + displayStore(); + List<String> requestProducts = getRequestProducts(); + handlePurchase(requestProducts); + ReceiptInformation receiptInformation = getReceiptInformation(); + displayReceipt(receiptInformation); + CustomerRespond continueShopping = getContinueRespond(); + if (!continueShopping.doesCustomerAgree()) { + break; + } + } + } + + private CustomerRespond getContinueRespond() { + inputView.showRequestMessageOf(InputViewType.CONTINUE_SHOPPING); + return getCustomerRespond(); + } + + private void handlePurchase(List<String> requestProducts) { + for (String requestProduct : requestProducts) { + PurchaseResponse purchaseResponse = getPurchaseResponse(requestProduct); + PurchaseResponseCode purchaseResponseCode = purchaseResponse.getPurchaseResponseCode(); + CustomerRespond customerRespond = announceAndGetRespond(purchaseResponseCode, purchaseResponse); + stockManager.updateReceipt(customerRespond, purchaseResponse); + } + } + + private CustomerRespond announceAndGetRespond(PurchaseResponseCode purchaseResponseCode, + PurchaseResponse purchaseResponse) { + if (purchaseResponseCode.equals(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE)) { + inputView.showRequestMessageOf(InputViewType.PROMOTION_PARTIAL_UNAVAILABLE, purchaseResponse); + return getCustomerRespond(); + } + if (purchaseResponseCode.equals(PurchaseResponseCode.FREE_PRODUCT_REMIND)) { + inputView.showRequestMessageOf(InputViewType.FREE_PRODUCT_REMIND, purchaseResponse); + return getCustomerRespond(); + } + return null; + } + + private PurchaseResponse getPurchaseResponse(String requestProduct) { + String requestProductName = requestProduct.split(ConstantBox.INPUT_SEPARATOR)[0]; + int requestQuantity = Integer.parseInt(requestProduct.split(ConstantBox.INPUT_SEPARATOR)[1]); + return stockManager.getPurchaseResponseFrom(requestProductName, requestQuantity); + } + + private void displayReceipt(ReceiptInformation receiptInformation) { + outputView = OutputViewFactory.createReceiptDisplayView(receiptInformation); + outputView.display(); + } + + private ReceiptInformation getReceiptInformation() { + inputView.showRequestMessageOf(InputViewType.MEMBERSHIP); + CustomerRespond membershipRespond = getCustomerRespond(); + return stockManager.getReceiptInformation(membershipRespond); + } + + private List<String> getRequestProducts() { + inputView.showRequestMessageOf(InputViewType.PRODUCTS_NAME_AMOUNT); + while (true) { + try { + ProductsInput productsInput = new ProductsInput(inputView.getInput()); + List<String> requestProducts = productsInput.getRequestProducts(); + for (String requestProduct : requestProducts) { + String requestProductName = requestProduct.split(ConstantBox.INPUT_SEPARATOR)[0]; + int requestQuantity = Integer.parseInt(requestProduct.split(ConstantBox.INPUT_SEPARATOR)[1]); + stockManager.checkNotExistProductException(requestProductName); + stockManager.checkOverStockAmountException(requestProductName, requestQuantity); + } + return requestProducts; + } catch (InputException e) { + System.out.println(e.getMessage()); + } + } + } + + private CustomerRespond getCustomerRespond() { + CustomerRespond customerRespond; + while (true) { + try { + return new CustomerRespond(inputView.getInput()); + } catch (InputException e) { + System.out.println(e.getMessage()); + } + } + } + + private void displayStore() { + List<ProductsDisplayData> displayDatas = stockManager.getDisplayDatas(); + outputView = OutputViewFactory.createProductDisplayView(displayDatas); + outputView.display(); + } +} +
Java
final ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์œผ์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ด์š”
@@ -0,0 +1,49 @@ +package store.dto; + +import store.model.domain.PurchaseResponseCode; + +public class PurchaseResponse { + + private String name; + private PurchaseResponseCode purchaseResponseCode; + private int promotionCount; + private int restCount; + + public PurchaseResponse(PurchaseResponseCode purchaseResponseCode, int promotionCount, int restCount) { + this.purchaseResponseCode = purchaseResponseCode; + this.promotionCount = promotionCount; + this.restCount = restCount; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public PurchaseResponseCode getPurchaseResponseCode() { + return purchaseResponseCode; + } + + public void setPurchaseResponseCode(PurchaseResponseCode purchaseResponseCode) { + this.purchaseResponseCode = purchaseResponseCode; + } + + public int getPromotionCount() { + return promotionCount; + } + + public void setPromotionCount(int promotionCount) { + this.promotionCount = promotionCount; + } + + public int getRestCount() { + return restCount; + } + + public void setRestCount(int restCount) { + this.restCount = restCount; + } +}
Java
ํ•ด๋‹น ๋ฉ”์„œ๋“œ๋Š” ์–ด๋–ค ์—ญํ• ์„ ํ•˜๋Š” ์ง€ ์ข€ ๋” ๋ช…ํ™•ํ•œ ๋„ค์ด๋ฐ์„ ์“ฐ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! (set... ๋„ค์ด๋ฐ๋ณด๋‹ค๋Š”)
@@ -0,0 +1,107 @@ +package store.model.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import store.dto.PurchaseResponse; + +public class Promotion { + + private static final String DATE_FORMAT = "yyyy-MM-dd"; + public static final int NO_PARTIAL = 0; + + private final int buy; + private final int get; + private final List<String> promotionInformation; + + public Promotion(List<String> promotionInformation) { + this.promotionInformation = promotionInformation; + this.buy = Integer.parseInt(promotionInformation.get(1)); + this.get = Integer.parseInt(promotionInformation.get(2)); + } + + public boolean isOnPromotion() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT); + String startDateInformation = promotionInformation.get(3); + LocalDateTime startDate = LocalDate.parse(startDateInformation, formatter).atStartOfDay(); + String endDateInformation = promotionInformation.get(4); + LocalDateTime endDate = LocalDate.parse(endDateInformation, formatter).atStartOfDay(); + LocalDateTime today = DateTimes.now(); + return (today.isAfter(startDate) && today.isBefore(endDate)); + } + + public PurchaseResponse discount(int requestQuantity, int stockQuantity) { + int promotionCount = requestQuantity / (buy + get); + int restCount = requestQuantity % (buy + get); + return getResponse(requestQuantity, stockQuantity, promotionCount, restCount); + } + + private PurchaseResponse getResponse(int requestQuantity, int stockQuantity, int promotionCount, int restCount) { + if (isInsufficientStock(requestQuantity, stockQuantity)) { + return responseInsufficientStock(requestQuantity, stockQuantity); + } + if (isSuccessPromotionPurchase(restCount)) { + return responseSuccessPromotionPurchase(promotionCount, restCount); + } + if (isNeedFreeRemind(restCount)) { + return responseInsufficientFreeStockOrFreeRemind(requestQuantity, stockQuantity, promotionCount, restCount); + } + return responsePartialAvailable(promotionCount, restCount); + } + + private PurchaseResponse responsePartialAvailable(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private boolean isInsufficientStock(int requestQuantity, int stockQuantity) { + return requestQuantity > stockQuantity; + } + + private PurchaseResponse responseInsufficientStock(int requestQuantity, int stockQuantity) { + int promotionCount = stockQuantity / (buy + get); + int restCount = stockQuantity % (buy + get) + (requestQuantity - stockQuantity); + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private boolean isSuccessPromotionPurchase(int restCount) { + return restCount == NO_PARTIAL; + } + + private PurchaseResponse responseSuccessPromotionPurchase(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PURCHASE_SUCCESS, promotionCount, restCount); + } + + private boolean isNeedFreeRemind(int restCount) { + return restCount == buy; + } + + private boolean isInsufficientFreeStock(int requestQuantity, int stockQuantity) { + return requestQuantity == stockQuantity; + } + + private PurchaseResponse responseInsufficientFreeStockOrFreeRemind(int requestQuantity, int stockQuantity, + int promotionCount, int restCount) { + if (isInsufficientFreeStock(requestQuantity, stockQuantity)) { + return responseInsufficientFreeStock(promotionCount, restCount); + } + return responseFreeRemind(promotionCount, restCount); + } + + private PurchaseResponse responseInsufficientFreeStock(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private PurchaseResponse responseFreeRemind(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.FREE_PRODUCT_REMIND, promotionCount, restCount); + } + + public String getPromotionName() { + return promotionInformation.getFirst(); + } + + public int getAppliedQuantity() { + return buy + get; + } +}
Java
Integer.parseInt ์™€ ๊ฐ™์€ ํŒŒ์‹ฑ์€ ํ•ด๋‹น ์ƒ์„ฑ์ž๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ์ชฝ์—์„œ ํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”? ํ•ด๋‹น ๋ฐฉ์‹์€ ํ…Œ์ŠคํŠธ ์ฝ”๋“œ ์ž‘์„ฑ, ์šด์˜ ์ฝ”๋“œ์—์„œ์˜ ํ™•์žฅ ๋ฉด์—์„œ ์•„์‰ฌ์›€์ด ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,107 @@ +package store.model.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import store.dto.PurchaseResponse; + +public class Promotion { + + private static final String DATE_FORMAT = "yyyy-MM-dd"; + public static final int NO_PARTIAL = 0; + + private final int buy; + private final int get; + private final List<String> promotionInformation; + + public Promotion(List<String> promotionInformation) { + this.promotionInformation = promotionInformation; + this.buy = Integer.parseInt(promotionInformation.get(1)); + this.get = Integer.parseInt(promotionInformation.get(2)); + } + + public boolean isOnPromotion() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT); + String startDateInformation = promotionInformation.get(3); + LocalDateTime startDate = LocalDate.parse(startDateInformation, formatter).atStartOfDay(); + String endDateInformation = promotionInformation.get(4); + LocalDateTime endDate = LocalDate.parse(endDateInformation, formatter).atStartOfDay(); + LocalDateTime today = DateTimes.now(); + return (today.isAfter(startDate) && today.isBefore(endDate)); + } + + public PurchaseResponse discount(int requestQuantity, int stockQuantity) { + int promotionCount = requestQuantity / (buy + get); + int restCount = requestQuantity % (buy + get); + return getResponse(requestQuantity, stockQuantity, promotionCount, restCount); + } + + private PurchaseResponse getResponse(int requestQuantity, int stockQuantity, int promotionCount, int restCount) { + if (isInsufficientStock(requestQuantity, stockQuantity)) { + return responseInsufficientStock(requestQuantity, stockQuantity); + } + if (isSuccessPromotionPurchase(restCount)) { + return responseSuccessPromotionPurchase(promotionCount, restCount); + } + if (isNeedFreeRemind(restCount)) { + return responseInsufficientFreeStockOrFreeRemind(requestQuantity, stockQuantity, promotionCount, restCount); + } + return responsePartialAvailable(promotionCount, restCount); + } + + private PurchaseResponse responsePartialAvailable(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private boolean isInsufficientStock(int requestQuantity, int stockQuantity) { + return requestQuantity > stockQuantity; + } + + private PurchaseResponse responseInsufficientStock(int requestQuantity, int stockQuantity) { + int promotionCount = stockQuantity / (buy + get); + int restCount = stockQuantity % (buy + get) + (requestQuantity - stockQuantity); + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private boolean isSuccessPromotionPurchase(int restCount) { + return restCount == NO_PARTIAL; + } + + private PurchaseResponse responseSuccessPromotionPurchase(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PURCHASE_SUCCESS, promotionCount, restCount); + } + + private boolean isNeedFreeRemind(int restCount) { + return restCount == buy; + } + + private boolean isInsufficientFreeStock(int requestQuantity, int stockQuantity) { + return requestQuantity == stockQuantity; + } + + private PurchaseResponse responseInsufficientFreeStockOrFreeRemind(int requestQuantity, int stockQuantity, + int promotionCount, int restCount) { + if (isInsufficientFreeStock(requestQuantity, stockQuantity)) { + return responseInsufficientFreeStock(promotionCount, restCount); + } + return responseFreeRemind(promotionCount, restCount); + } + + private PurchaseResponse responseInsufficientFreeStock(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private PurchaseResponse responseFreeRemind(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.FREE_PRODUCT_REMIND, promotionCount, restCount); + } + + public String getPromotionName() { + return promotionInformation.getFirst(); + } + + public int getAppliedQuantity() { + return buy + get; + } +}
Java
PurchaseResponse ๋ผ๊ณ  ํ•˜๋Š” Data Object ๊ฐ€ ๋„๋ฉ”์ธ์—์„œ ์กฐ๋ฆฝ๋˜์–ด ๋ฆฌํ„ด๋˜๊ณ  ์žˆ๋Š”๋ฐ์š”! ํ•ด๋‹น ๋ฐฉ์‹์€ ๋” ์ค‘์š”ํ•œ ๋„๋ฉ”์ธ์ด ๋œ ์ค‘์š”ํ•œ Data Object์—๊ฒŒ ์˜ํ–ฅ์„ ๋ฐ›๊ฒŒ ๋˜๋Š” ๋ฌธ์ œ๊ฐ€ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ์˜ˆ๋ฅผ ๋“ค์–ด PurchaseResponse ์—์„œ ๋ฆฌํ„ด๋˜์–ด์•ผ ํ•˜๋Š” ํ•ญ๋ชฉ์ด ๋” ๋งŽ์•„์ง€๊ฑฐ๋‚˜, ์ ์–ด์ง„๋‹ค๋ฉด ํ•ด๋‹น ๋ณ€๊ฒฝ ์‚ฌํ•ญ์ด ๋„๋ฉ”์ธ์— ์˜ํ–ฅ์„ ๋ฏธ์น  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,80 @@ +package store.model.domain; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import store.dto.ReceiptInformation; +import store.dto.SalesData; +import store.model.domain.input.CustomerRespond; + +public class Receipt { + + private static final int ZERO = 0; + public static final int MAX_MEMBERSHIP_DISCOUNT = 8000; + public static final int MIN_MEMBERSHIP_DISCOUNT = 1000; + + private final List<String> names = new ArrayList<>(); + private final List<Integer> quantities = new ArrayList<>(); + private final List<Integer> prices = new ArrayList<>(); + private final List<Integer> promotionCounts = new ArrayList<>(); + + public void addSalesData(SalesData salesData) { + names.add(salesData.getName()); + quantities.add(salesData.getQuantity()); + prices.add(salesData.getPrice()); + promotionCounts.add(salesData.getPromotionCount()); + } + + public ReceiptInformation getReceiptInformation(CustomerRespond membershipRespond) { + int totalPurchased = ZERO; + int promotionDiscount = ZERO; + int totalQuantity = ZERO; + List<Integer> amountInformation = generateAmountInformation(membershipRespond, totalPurchased, + promotionDiscount, totalQuantity); + Map<String, List> salesDatas = generateSalesDatas(); + return new ReceiptInformation(salesDatas, amountInformation); + } + + private List<Integer> generateAmountInformation(CustomerRespond membershipRespond, int totalPurchased, + int promotionDiscount, + int totalQuantity) { + for (int productKindIndex = ZERO; productKindIndex < names.size(); productKindIndex++) { + totalPurchased += quantities.get(productKindIndex) * prices.get(productKindIndex); + promotionDiscount += promotionCounts.get(productKindIndex) * prices.get(productKindIndex); + totalQuantity += quantities.get(productKindIndex); + } + int memberShipDiscount = getMembershipDiscount(membershipRespond, totalPurchased, promotionDiscount); + int pay = totalPurchased - promotionDiscount - memberShipDiscount; + return List.of(totalQuantity, totalPurchased, promotionDiscount, memberShipDiscount, pay); + } + + private int getMembershipDiscount(CustomerRespond membershipRespond, int totalPurchasedAmount, + int promotionDiscountAmount) { + if (!membershipRespond.doesCustomerAgree()) { + return ZERO; + } + return calculateMembershipDiscount(totalPurchasedAmount, promotionDiscountAmount); + } + + private static int calculateMembershipDiscount(int totalPurchasedAmount, int promotionDiscountAmount) { + double discount = (totalPurchasedAmount - promotionDiscountAmount) * 0.3; + int memberShipDiscountAmount = ((int) discount / 1000) * 1000; + if (memberShipDiscountAmount < MIN_MEMBERSHIP_DISCOUNT) { + return ZERO; + } + if (memberShipDiscountAmount > MAX_MEMBERSHIP_DISCOUNT) { + return MAX_MEMBERSHIP_DISCOUNT; + } + return memberShipDiscountAmount; + } + + private Map<String, List> generateSalesDatas() { + return Map.of( + "names", Collections.unmodifiableList(names), + "quantities", Collections.unmodifiableList(quantities), + "prices", Collections.unmodifiableList(prices), + "promotionCounts", Collections.unmodifiableList(promotionCounts) + ); + } +}
Java
Dto, VO ๋“ฑ์„ ๊ต‰์žฅํžˆ ์ ๊ทน์ ์œผ๋กœ ์‚ฌ์šฉํ•˜์‹  ๊ฒƒ์œผ๋กœ ๋ณด์ด๋Š”๋ฐ์š”, ํ•ด๋‹น ๋ถ€๋ถ„์—๋Š” ์‚ฌ์šฉํ•˜์ง€ ์•Š์œผ์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,136 @@ +package store.model.domain; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import store.constant.ConstantBox; +import store.dto.PurchaseResponse; +import store.dto.ReceiptInformation; +import store.dto.SalesData; +import store.exception.ExceptionType; +import store.exception.InputException; +import store.model.domain.input.CustomerRespond; +import store.model.domain.product.Product; +import store.model.domain.product.ProductFactory; +import store.model.domain.product.Products; +import store.model.domain.product.ProductsDisplayData; + +public class StockManager { + + public static final String PRODUCTS_FILE_PATH = "src/main/resources/products.md"; + public static final String PROMOTIONS_FILE_PATH = "src/main/resources/promotions.md"; + + private Map<String, Products> stock; + private Map<String, Promotion> promotions; + private Receipt receipt; + + public StockManager() throws IOException { + readPromotionsFrom(); + readProductsFrom(); + receipt = new Receipt(); + } + + public void readProductsFrom() throws IOException { + List<String> productsData = Files.readAllLines(Path.of(PRODUCTS_FILE_PATH)); + productsData.removeFirst(); // ์ฒซ ๋ผ์ธ(ํ—ค๋”) ์ œ๊ฑฐ + this.stock = organizeStock(productsData); + } + + private Map<String, Products> organizeStock(List<String> productsData) { + Map<String, Products> stock = new LinkedHashMap<>(); + productsData.forEach(productData -> putStock(stock, productData)); + return Collections.unmodifiableMap(stock); + } + + private void putStock(Map<String, Products> stock, String productData) { + List<String> productInformation = List.of(productData.split(ConstantBox.SEPARATOR)); + Product product = ProductFactory.createProductFrom(productInformation, promotions); + String name = productInformation.getFirst(); + addProduct(stock, name, product); + } + + private void addProduct(Map<String, Products> stock, String name, Product product) { + if (!stock.containsKey(name)) { + stock.put(name, new Products(product)); + return; + } + if (stock.containsKey(name)) { + stock.get(name).add(product); + } + } + + private void readPromotionsFrom() throws IOException { + List<String> promotionsData = Files.readAllLines(Path.of(PROMOTIONS_FILE_PATH)); + promotionsData.removeFirst(); // ์ฒซ ๋ผ์ธ(ํ—ค๋”) ์ œ๊ฑฐ + promotions = organizePromotions(promotionsData); + } + + private Map<String, Promotion> organizePromotions(List<String> promotionsData) { + Map<String, Promotion> promotions = new HashMap<>(); + promotionsData.forEach(promotionData -> putPromotion(promotions, promotionData)); + return Collections.unmodifiableMap(promotions); + } + + private void putPromotion(Map<String, Promotion> promotions, String promotionData) { + List<String> promotionInformation = List.of(promotionData.split(ConstantBox.SEPARATOR)); + String name = promotionInformation.getFirst(); + promotions.put(name, new Promotion(promotionInformation)); + } + + public PurchaseResponse getPurchaseResponseFrom(String requestProductName, int requestQuantity) { + Products products = stock.get(requestProductName); + checkNotExistProductException(requestProductName); + PurchaseResponse purchaseResponse = products.checkQuantity(requestQuantity); + checkOverStockAmountException(requestProductName, requestQuantity); + purchaseResponse.setName(requestProductName); + return purchaseResponse; + } + + public void checkNotExistProductException(String requestProductName) { + Products products = stock.get(requestProductName); + boolean isNotExistProduct = (products == null); + if (isNotExistProduct) { + throw new InputException(ExceptionType.NOT_EXIST_PRODUCT); + } + } + + public void checkOverStockAmountException(String requestProductName, int requestQuantity) { + Products products = stock.get(requestProductName); + PurchaseResponse purchaseResponse = products.checkQuantity(requestQuantity); + boolean isOverStock = purchaseResponse.getPurchaseResponseCode().equals(PurchaseResponseCode.OUT_OF_STOCK); + if (isOverStock) { + throw new InputException(ExceptionType.OVER_STOCK_AMOUNT); + } + } + + public List<ProductsDisplayData> getDisplayDatas() { + List<ProductsDisplayData> displayDatas = new ArrayList<>(); + for (Products products : stock.values()) { + displayDatas.add(products.getProductsData()); + } + return displayDatas; + } + + public void updateReceipt(CustomerRespond customerRespond, PurchaseResponse purchaseResponse) { + String productName = purchaseResponse.getName(); + PurchaseResponseCode purchaseResponseCode = purchaseResponse.getPurchaseResponseCode(); + int promotionCount = purchaseResponse.getPromotionCount(); + int restCount = purchaseResponse.getRestCount(); + Products products = stock.get(productName); + SalesData salesData = products.getSalesDataByEachCase(customerRespond, purchaseResponseCode, restCount, + promotionCount); + receipt.addSalesData(salesData); + } + + public ReceiptInformation getReceiptInformation(CustomerRespond membershipRespond) { + ReceiptInformation receiptInformation = receipt.getReceiptInformation(membershipRespond); + receipt = new Receipt(); + return receiptInformation; + } +}
Java
From์ด๋ผ๋Š” ๋„ค์ด๋ฐ ํ›„์— ํŒจ๋Ÿฌ๋ฏธํ„ฐ๊ฐ€ ๋น„์–ด์žˆ์–ด์„œ "์–ด๋””์„œ" ์ฝ์–ด์˜ค๋Š” ์ง€ ๋ชจํ˜ธํ•ด์ง€๋Š” ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,9 @@ +package store.constant; + +public class ConstantBox { + public static final String SEPARATOR = ","; + public static final String NO_QUANTITY = "0"; + public static final String INPUT_SEPARATOR = "-"; + public static final String CUSTOMER_RESPOND_Y = "Y"; + public static final String CUSTOMER_RESPOND_N = "N"; +}
Java
์—ฌ๋Ÿฌ ํด๋ž˜์Šค์—์„œ ์‚ฌ์šฉ๋˜๋Š” ๋™์ผํ•œ ๋‹จ์ˆœ ๊ฐ’๋“ค์„ ํ•œ ํด๋ž˜์Šค์—์„œ ๋ชจ์•„ ๊ด€๋ฆฌํ•˜๊ณ ์ž ์ƒ์ˆ˜ ์ „์šฉ ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค! ์˜ˆ์ „์— ์—๋Ÿฌ ๋ฉ”์„ธ์ง€๋“ค์„ enum์œผ๋กœ ๊ด€๋ฆฌ ํ–ˆ์—ˆ๋Š”๋ฐ์š”! ๋‹จ์ˆœ Strimg ๋ฉ”์„ธ์ง€๋“ค๋งŒ ๋“ค์–ด์žˆ๋Š”๋ฐ ์ถ”๊ฐ€์ ์œผ๋กœ getter๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๊ฐ’์„ ๊ฐ€์ ธ์˜ค๋‹ค ๋ณด๋‹ˆ ๊ฐ€๋…์„ฑ์ด ๋–จ์–ด์ง€๊ณ  enum์˜ ์ง„์ •ํ•œ ์“ฐ์ž„์ด๋ผ๊ณ  ๋ณด๊ธฐ ํž˜๋“ค ๊ฒƒ ๊ฐ™๋‹ค๋Š” ๋ฆฌ๋ทฐ๋ฅผ ์ ‘ํ•œ ์ ์ด ์žˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ๋‹จ์ˆœ ๊ฐ’๋“ค์ด ์—ฌ๋Ÿฌ ํด๋ž˜์Šค์—์„œ ์‚ฌ์šฉ๋  ๋•Œ๋Š” ์ƒ์ˆ˜๋“ค์„ ๋ชจ์•„ ๋†“์€ ํด๋ž˜์Šค๋ฅผ ํ†ตํ•ด ๊ณต์œ ํ•ด์„œ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹๊ฒ ๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์–ด ์ด๋ ‡๊ฒŒ ๊ด€๋ฆฌํ•˜๊ฒŒ ๋œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,124 @@ +package store.controller; + +import java.io.IOException; +import java.util.List; +import store.constant.ConstantBox; +import store.dto.PurchaseResponse; +import store.dto.ReceiptInformation; +import store.exception.InputException; +import store.model.domain.PurchaseResponseCode; +import store.model.domain.StockManager; +import store.model.domain.input.CustomerRespond; +import store.model.domain.input.ProductsInput; +import store.model.domain.product.ProductsDisplayData; +import store.view.inputview.InputView; +import store.view.inputview.InputViewType; +import store.view.outputview.OutputView; +import store.view.outputview.OutputViewFactory; + +public class StoreController { + + private InputView inputView; + private OutputView outputView; + private StockManager stockManager; + + public StoreController(InputView inputView, StockManager stockManager) { + this.inputView = inputView; + this.stockManager = stockManager; + } + + public void run() throws IOException { + while (true) { + displayStore(); + List<String> requestProducts = getRequestProducts(); + handlePurchase(requestProducts); + ReceiptInformation receiptInformation = getReceiptInformation(); + displayReceipt(receiptInformation); + CustomerRespond continueShopping = getContinueRespond(); + if (!continueShopping.doesCustomerAgree()) { + break; + } + } + } + + private CustomerRespond getContinueRespond() { + inputView.showRequestMessageOf(InputViewType.CONTINUE_SHOPPING); + return getCustomerRespond(); + } + + private void handlePurchase(List<String> requestProducts) { + for (String requestProduct : requestProducts) { + PurchaseResponse purchaseResponse = getPurchaseResponse(requestProduct); + PurchaseResponseCode purchaseResponseCode = purchaseResponse.getPurchaseResponseCode(); + CustomerRespond customerRespond = announceAndGetRespond(purchaseResponseCode, purchaseResponse); + stockManager.updateReceipt(customerRespond, purchaseResponse); + } + } + + private CustomerRespond announceAndGetRespond(PurchaseResponseCode purchaseResponseCode, + PurchaseResponse purchaseResponse) { + if (purchaseResponseCode.equals(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE)) { + inputView.showRequestMessageOf(InputViewType.PROMOTION_PARTIAL_UNAVAILABLE, purchaseResponse); + return getCustomerRespond(); + } + if (purchaseResponseCode.equals(PurchaseResponseCode.FREE_PRODUCT_REMIND)) { + inputView.showRequestMessageOf(InputViewType.FREE_PRODUCT_REMIND, purchaseResponse); + return getCustomerRespond(); + } + return null; + } + + private PurchaseResponse getPurchaseResponse(String requestProduct) { + String requestProductName = requestProduct.split(ConstantBox.INPUT_SEPARATOR)[0]; + int requestQuantity = Integer.parseInt(requestProduct.split(ConstantBox.INPUT_SEPARATOR)[1]); + return stockManager.getPurchaseResponseFrom(requestProductName, requestQuantity); + } + + private void displayReceipt(ReceiptInformation receiptInformation) { + outputView = OutputViewFactory.createReceiptDisplayView(receiptInformation); + outputView.display(); + } + + private ReceiptInformation getReceiptInformation() { + inputView.showRequestMessageOf(InputViewType.MEMBERSHIP); + CustomerRespond membershipRespond = getCustomerRespond(); + return stockManager.getReceiptInformation(membershipRespond); + } + + private List<String> getRequestProducts() { + inputView.showRequestMessageOf(InputViewType.PRODUCTS_NAME_AMOUNT); + while (true) { + try { + ProductsInput productsInput = new ProductsInput(inputView.getInput()); + List<String> requestProducts = productsInput.getRequestProducts(); + for (String requestProduct : requestProducts) { + String requestProductName = requestProduct.split(ConstantBox.INPUT_SEPARATOR)[0]; + int requestQuantity = Integer.parseInt(requestProduct.split(ConstantBox.INPUT_SEPARATOR)[1]); + stockManager.checkNotExistProductException(requestProductName); + stockManager.checkOverStockAmountException(requestProductName, requestQuantity); + } + return requestProducts; + } catch (InputException e) { + System.out.println(e.getMessage()); + } + } + } + + private CustomerRespond getCustomerRespond() { + CustomerRespond customerRespond; + while (true) { + try { + return new CustomerRespond(inputView.getInput()); + } catch (InputException e) { + System.out.println(e.getMessage()); + } + } + } + + private void displayStore() { + List<ProductsDisplayData> displayDatas = stockManager.getDisplayDatas(); + outputView = OutputViewFactory.createProductDisplayView(displayDatas); + outputView.display(); + } +} +
Java
๋งˆ์ง€๋ง‰์— ์‚ฌ์‹ค,, ์ง€์› ์‚ฌ์ดํŠธ์—์„œ ์˜ˆ๊ธฐ์น˜ ์•Š์€ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒ์ด ๋– ์„œ ๋‹นํ™ฉํ•œ ๋งˆ์Œ์— git push๋ฌธ์ œ์ผ๊นŒ ํ•ด์„œ ์ •์‹ ์—†์ด ์ด๋ฆฌ์ €๋ฆฌ ๋ฐ”๊ฟ”๋ณด๊ณ  ์ปค๋ฐ‹์„ ํ‘ธ์‹œ ํ•˜๋‹ค๊ฐ€ ๋นผ๊ฒŒ ๋œ ๊ฒƒ ๊ฐ™์•„์š”.. final์„ ์“ฐ๋Š” ๊ฒƒ์ด ๋” ๋งž์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ์ข‹์€ ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌ๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,107 @@ +package store.model.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import store.dto.PurchaseResponse; + +public class Promotion { + + private static final String DATE_FORMAT = "yyyy-MM-dd"; + public static final int NO_PARTIAL = 0; + + private final int buy; + private final int get; + private final List<String> promotionInformation; + + public Promotion(List<String> promotionInformation) { + this.promotionInformation = promotionInformation; + this.buy = Integer.parseInt(promotionInformation.get(1)); + this.get = Integer.parseInt(promotionInformation.get(2)); + } + + public boolean isOnPromotion() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT); + String startDateInformation = promotionInformation.get(3); + LocalDateTime startDate = LocalDate.parse(startDateInformation, formatter).atStartOfDay(); + String endDateInformation = promotionInformation.get(4); + LocalDateTime endDate = LocalDate.parse(endDateInformation, formatter).atStartOfDay(); + LocalDateTime today = DateTimes.now(); + return (today.isAfter(startDate) && today.isBefore(endDate)); + } + + public PurchaseResponse discount(int requestQuantity, int stockQuantity) { + int promotionCount = requestQuantity / (buy + get); + int restCount = requestQuantity % (buy + get); + return getResponse(requestQuantity, stockQuantity, promotionCount, restCount); + } + + private PurchaseResponse getResponse(int requestQuantity, int stockQuantity, int promotionCount, int restCount) { + if (isInsufficientStock(requestQuantity, stockQuantity)) { + return responseInsufficientStock(requestQuantity, stockQuantity); + } + if (isSuccessPromotionPurchase(restCount)) { + return responseSuccessPromotionPurchase(promotionCount, restCount); + } + if (isNeedFreeRemind(restCount)) { + return responseInsufficientFreeStockOrFreeRemind(requestQuantity, stockQuantity, promotionCount, restCount); + } + return responsePartialAvailable(promotionCount, restCount); + } + + private PurchaseResponse responsePartialAvailable(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private boolean isInsufficientStock(int requestQuantity, int stockQuantity) { + return requestQuantity > stockQuantity; + } + + private PurchaseResponse responseInsufficientStock(int requestQuantity, int stockQuantity) { + int promotionCount = stockQuantity / (buy + get); + int restCount = stockQuantity % (buy + get) + (requestQuantity - stockQuantity); + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private boolean isSuccessPromotionPurchase(int restCount) { + return restCount == NO_PARTIAL; + } + + private PurchaseResponse responseSuccessPromotionPurchase(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PURCHASE_SUCCESS, promotionCount, restCount); + } + + private boolean isNeedFreeRemind(int restCount) { + return restCount == buy; + } + + private boolean isInsufficientFreeStock(int requestQuantity, int stockQuantity) { + return requestQuantity == stockQuantity; + } + + private PurchaseResponse responseInsufficientFreeStockOrFreeRemind(int requestQuantity, int stockQuantity, + int promotionCount, int restCount) { + if (isInsufficientFreeStock(requestQuantity, stockQuantity)) { + return responseInsufficientFreeStock(promotionCount, restCount); + } + return responseFreeRemind(promotionCount, restCount); + } + + private PurchaseResponse responseInsufficientFreeStock(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private PurchaseResponse responseFreeRemind(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.FREE_PRODUCT_REMIND, promotionCount, restCount); + } + + public String getPromotionName() { + return promotionInformation.getFirst(); + } + + public int getAppliedQuantity() { + return buy + get; + } +}
Java
์ƒ์„ฑ์ž๋ฅผ ํ˜ธ์ถœํ•  ๋•Œ ํŒŒ์‹ฑ์„ํ•˜๊ณ  ๋„˜๊ฒจ์ฃผ๋Š” ์ชฝ์œผ๋กœ ํ•˜๋Š” ๊ฒƒ์ด ์–ด๋–จ์ง€๋กœ ํ”ผ๋“œ๋ฐฑ ์ฃผ์‹  ๊ฒŒ ๋งž์„๊นŒ์š”? ์ œ๊ฐ€ ์ดํ•ดํ•œ ๋ฐฉํ–ฅ์ด ๋งž๋‹ค๋ฉด ๊ทธ์— ๋Œ€ํ•œ ๋‹ต๋ณ€์œผ๋กœ๋Š” promotionInformation์„ ๋ฐ–์—์„œ ํŒŒ์‹ฑ ํ•˜๊ณ  ๋„ฃ์–ด์ฃผ๋‹ค ๋ณด๋‹ˆ ์ƒ์„ฑ์ž ํ˜ธ์ถœ ์‹œ ๋„˜๊ฒจ์ค˜์•ผ ํ•  ์ธ์ž๊ฐ€ ๋„ˆ๋ฌด ๋งŽ์•„ ๋ฆฌ์ŠคํŠธ๋กœ ๋ฐ›๋„๋ก ํ•˜๊ณ  ๋‚ด๋ถ€์—์„œ ํ•„์š”ํ•œ ๊ฐ’์„ ๊บผ๋‚ด ์“ฐ๋„๋ก ํ–ˆ์—ˆ๋Š”๋ฐ์š”! ๋ง์”€ ์ฃผ์‹  ํ”ผ๋“œ๋ฐฑ์„ ๋ฐ˜์˜ํ•ด๋ณด๋ ค๋ฉด ์–ด๋–ค ๋ฐฉ๋ฒ•์ด ์ข‹์„๊นŒ์š”? ์กฐ์–ธ์„ ๊ตฌํ•˜๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค! ์šด์˜ ์ฝ”๋“œ์—์„œ์˜ ํ™•์ • ์ธก๋ฉด ์ด๋ผ๋Š” ํ‚ค์›Œ๋“œ๋„ ํ•œ๋ฒˆ ๊ณต๋ถ€ํ•ด๋ด์•ผ๊ฒ ๋„ค์š”! ์ข‹์€ ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌ๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,107 @@ +package store.model.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import store.dto.PurchaseResponse; + +public class Promotion { + + private static final String DATE_FORMAT = "yyyy-MM-dd"; + public static final int NO_PARTIAL = 0; + + private final int buy; + private final int get; + private final List<String> promotionInformation; + + public Promotion(List<String> promotionInformation) { + this.promotionInformation = promotionInformation; + this.buy = Integer.parseInt(promotionInformation.get(1)); + this.get = Integer.parseInt(promotionInformation.get(2)); + } + + public boolean isOnPromotion() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT); + String startDateInformation = promotionInformation.get(3); + LocalDateTime startDate = LocalDate.parse(startDateInformation, formatter).atStartOfDay(); + String endDateInformation = promotionInformation.get(4); + LocalDateTime endDate = LocalDate.parse(endDateInformation, formatter).atStartOfDay(); + LocalDateTime today = DateTimes.now(); + return (today.isAfter(startDate) && today.isBefore(endDate)); + } + + public PurchaseResponse discount(int requestQuantity, int stockQuantity) { + int promotionCount = requestQuantity / (buy + get); + int restCount = requestQuantity % (buy + get); + return getResponse(requestQuantity, stockQuantity, promotionCount, restCount); + } + + private PurchaseResponse getResponse(int requestQuantity, int stockQuantity, int promotionCount, int restCount) { + if (isInsufficientStock(requestQuantity, stockQuantity)) { + return responseInsufficientStock(requestQuantity, stockQuantity); + } + if (isSuccessPromotionPurchase(restCount)) { + return responseSuccessPromotionPurchase(promotionCount, restCount); + } + if (isNeedFreeRemind(restCount)) { + return responseInsufficientFreeStockOrFreeRemind(requestQuantity, stockQuantity, promotionCount, restCount); + } + return responsePartialAvailable(promotionCount, restCount); + } + + private PurchaseResponse responsePartialAvailable(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private boolean isInsufficientStock(int requestQuantity, int stockQuantity) { + return requestQuantity > stockQuantity; + } + + private PurchaseResponse responseInsufficientStock(int requestQuantity, int stockQuantity) { + int promotionCount = stockQuantity / (buy + get); + int restCount = stockQuantity % (buy + get) + (requestQuantity - stockQuantity); + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private boolean isSuccessPromotionPurchase(int restCount) { + return restCount == NO_PARTIAL; + } + + private PurchaseResponse responseSuccessPromotionPurchase(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PURCHASE_SUCCESS, promotionCount, restCount); + } + + private boolean isNeedFreeRemind(int restCount) { + return restCount == buy; + } + + private boolean isInsufficientFreeStock(int requestQuantity, int stockQuantity) { + return requestQuantity == stockQuantity; + } + + private PurchaseResponse responseInsufficientFreeStockOrFreeRemind(int requestQuantity, int stockQuantity, + int promotionCount, int restCount) { + if (isInsufficientFreeStock(requestQuantity, stockQuantity)) { + return responseInsufficientFreeStock(promotionCount, restCount); + } + return responseFreeRemind(promotionCount, restCount); + } + + private PurchaseResponse responseInsufficientFreeStock(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private PurchaseResponse responseFreeRemind(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.FREE_PRODUCT_REMIND, promotionCount, restCount); + } + + public String getPromotionName() { + return promotionInformation.getFirst(); + } + + public int getAppliedQuantity() { + return buy + get; + } +}
Java
์•„ํ•˜ ๊ทธ๋ ‡๊ฒŒ ๋ณผ ์ˆ˜ ์žˆ๊ตฐ์š”.. ์•„์ง ๊ฐœ๋…์ด ํ™•์‹ค์น˜ ๋ชปํ•˜๋‹ค ๋ณด๋‹ˆ ์กฐ๋ฆฝํ•˜๋Š” ๋ฐฉ์‹ ๋ฐ–์— ์ƒ๊ฐ์„ ๋ชปํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ๊ทธ๋ ‡๋‹ค๋ฉด ์ œ๊ฐ€ ์ดํ•ดํ•˜๊ธฐ๋กœ๋Š” ๋ง์”€ํ•ด์ฃผ์‹  ํ”ผ๋“œ๋ฐฑ์„ ์ ์šฉํ•ด๋ณด์ž๋ฉด DataObject๊ฐ€ ํ•˜๋‚˜ํ•˜๋‚˜ ๋ฐ›์•„์„œ ๋งŒ๋“ค์–ด์ง€๊ธฐ ๋ณด๋‹ค List๋ผ๋˜์ง€ ์ •๋ณด ์„ธํŠธ?๋ฅผ ํ•˜๋‚˜ ๋ฐ›์•„์„œ ๋‚ด๋ถ€์ ์œผ๋กœ ์กฐ๋ฆฝ๋˜๋„๋ก ํ•˜๋Š” ๊ฒƒ์ด ๋ฐ”๋žŒ์งํ•  ๊ฒƒ ๊ฐ™๋‹ค๋Š” ๋ง์”€์ด ๋งž์œผ์‹ค๊นŒ์š”?
@@ -0,0 +1,80 @@ +package store.model.domain; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import store.dto.ReceiptInformation; +import store.dto.SalesData; +import store.model.domain.input.CustomerRespond; + +public class Receipt { + + private static final int ZERO = 0; + public static final int MAX_MEMBERSHIP_DISCOUNT = 8000; + public static final int MIN_MEMBERSHIP_DISCOUNT = 1000; + + private final List<String> names = new ArrayList<>(); + private final List<Integer> quantities = new ArrayList<>(); + private final List<Integer> prices = new ArrayList<>(); + private final List<Integer> promotionCounts = new ArrayList<>(); + + public void addSalesData(SalesData salesData) { + names.add(salesData.getName()); + quantities.add(salesData.getQuantity()); + prices.add(salesData.getPrice()); + promotionCounts.add(salesData.getPromotionCount()); + } + + public ReceiptInformation getReceiptInformation(CustomerRespond membershipRespond) { + int totalPurchased = ZERO; + int promotionDiscount = ZERO; + int totalQuantity = ZERO; + List<Integer> amountInformation = generateAmountInformation(membershipRespond, totalPurchased, + promotionDiscount, totalQuantity); + Map<String, List> salesDatas = generateSalesDatas(); + return new ReceiptInformation(salesDatas, amountInformation); + } + + private List<Integer> generateAmountInformation(CustomerRespond membershipRespond, int totalPurchased, + int promotionDiscount, + int totalQuantity) { + for (int productKindIndex = ZERO; productKindIndex < names.size(); productKindIndex++) { + totalPurchased += quantities.get(productKindIndex) * prices.get(productKindIndex); + promotionDiscount += promotionCounts.get(productKindIndex) * prices.get(productKindIndex); + totalQuantity += quantities.get(productKindIndex); + } + int memberShipDiscount = getMembershipDiscount(membershipRespond, totalPurchased, promotionDiscount); + int pay = totalPurchased - promotionDiscount - memberShipDiscount; + return List.of(totalQuantity, totalPurchased, promotionDiscount, memberShipDiscount, pay); + } + + private int getMembershipDiscount(CustomerRespond membershipRespond, int totalPurchasedAmount, + int promotionDiscountAmount) { + if (!membershipRespond.doesCustomerAgree()) { + return ZERO; + } + return calculateMembershipDiscount(totalPurchasedAmount, promotionDiscountAmount); + } + + private static int calculateMembershipDiscount(int totalPurchasedAmount, int promotionDiscountAmount) { + double discount = (totalPurchasedAmount - promotionDiscountAmount) * 0.3; + int memberShipDiscountAmount = ((int) discount / 1000) * 1000; + if (memberShipDiscountAmount < MIN_MEMBERSHIP_DISCOUNT) { + return ZERO; + } + if (memberShipDiscountAmount > MAX_MEMBERSHIP_DISCOUNT) { + return MAX_MEMBERSHIP_DISCOUNT; + } + return memberShipDiscountAmount; + } + + private Map<String, List> generateSalesDatas() { + return Map.of( + "names", Collections.unmodifiableList(names), + "quantities", Collections.unmodifiableList(quantities), + "prices", Collections.unmodifiableList(prices), + "promotionCounts", Collections.unmodifiableList(promotionCounts) + ); + } +}
Java
์ œ๊ฐ€ ์•„์ง ๊ฐœ๋…์ด ํ™•์‹ค์น˜ ์•Š์•„์„œ ํ‹€๋ฆด ์ˆ˜ ์žˆ์ง€๋งŒ.. ์ฒ˜์Œ์— ๋งŒ๋“ค ๋•Œ SalesData ๊ฐ์ฒด๊ฐ€ DTO์ด๊ณ  Receipt๋Š” ๋„๋ฉ”์ธ ๊ฐ์ฒด๋กœ ์„ค์ •ํ•˜์˜€์Šต๋‹ˆ๋‹ค! ๊ทธ ์ด์œ ๋Š” ์ œ๊ฐ€ ์•Œ๊ธฐ๋กœ DTO๋Š” ๋‚ด๋ถ€์— ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์„ ๊ฐ€์ง€๊ณ  ์žˆ์ง€ ์•Š์•„์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์œผ๋กœ ์•Œ๊ณ  ์žˆ์–ด์„œ Reciept๋Š” SalesData๋ผ๋Š” Dto๋ฅผ ๋ฐ›์•„ ์˜์ˆ˜์ฆ ์ •๋ณด๋ฅผ ๋งŒ๋“œ๋Š” ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์„ ๊ฐ–๊ณ  ReceiptInformation์ด๋ผ๋Š” DTO๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋„๋ก ์„ค๊ณ„ํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,136 @@ +package store.model.domain; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import store.constant.ConstantBox; +import store.dto.PurchaseResponse; +import store.dto.ReceiptInformation; +import store.dto.SalesData; +import store.exception.ExceptionType; +import store.exception.InputException; +import store.model.domain.input.CustomerRespond; +import store.model.domain.product.Product; +import store.model.domain.product.ProductFactory; +import store.model.domain.product.Products; +import store.model.domain.product.ProductsDisplayData; + +public class StockManager { + + public static final String PRODUCTS_FILE_PATH = "src/main/resources/products.md"; + public static final String PROMOTIONS_FILE_PATH = "src/main/resources/promotions.md"; + + private Map<String, Products> stock; + private Map<String, Promotion> promotions; + private Receipt receipt; + + public StockManager() throws IOException { + readPromotionsFrom(); + readProductsFrom(); + receipt = new Receipt(); + } + + public void readProductsFrom() throws IOException { + List<String> productsData = Files.readAllLines(Path.of(PRODUCTS_FILE_PATH)); + productsData.removeFirst(); // ์ฒซ ๋ผ์ธ(ํ—ค๋”) ์ œ๊ฑฐ + this.stock = organizeStock(productsData); + } + + private Map<String, Products> organizeStock(List<String> productsData) { + Map<String, Products> stock = new LinkedHashMap<>(); + productsData.forEach(productData -> putStock(stock, productData)); + return Collections.unmodifiableMap(stock); + } + + private void putStock(Map<String, Products> stock, String productData) { + List<String> productInformation = List.of(productData.split(ConstantBox.SEPARATOR)); + Product product = ProductFactory.createProductFrom(productInformation, promotions); + String name = productInformation.getFirst(); + addProduct(stock, name, product); + } + + private void addProduct(Map<String, Products> stock, String name, Product product) { + if (!stock.containsKey(name)) { + stock.put(name, new Products(product)); + return; + } + if (stock.containsKey(name)) { + stock.get(name).add(product); + } + } + + private void readPromotionsFrom() throws IOException { + List<String> promotionsData = Files.readAllLines(Path.of(PROMOTIONS_FILE_PATH)); + promotionsData.removeFirst(); // ์ฒซ ๋ผ์ธ(ํ—ค๋”) ์ œ๊ฑฐ + promotions = organizePromotions(promotionsData); + } + + private Map<String, Promotion> organizePromotions(List<String> promotionsData) { + Map<String, Promotion> promotions = new HashMap<>(); + promotionsData.forEach(promotionData -> putPromotion(promotions, promotionData)); + return Collections.unmodifiableMap(promotions); + } + + private void putPromotion(Map<String, Promotion> promotions, String promotionData) { + List<String> promotionInformation = List.of(promotionData.split(ConstantBox.SEPARATOR)); + String name = promotionInformation.getFirst(); + promotions.put(name, new Promotion(promotionInformation)); + } + + public PurchaseResponse getPurchaseResponseFrom(String requestProductName, int requestQuantity) { + Products products = stock.get(requestProductName); + checkNotExistProductException(requestProductName); + PurchaseResponse purchaseResponse = products.checkQuantity(requestQuantity); + checkOverStockAmountException(requestProductName, requestQuantity); + purchaseResponse.setName(requestProductName); + return purchaseResponse; + } + + public void checkNotExistProductException(String requestProductName) { + Products products = stock.get(requestProductName); + boolean isNotExistProduct = (products == null); + if (isNotExistProduct) { + throw new InputException(ExceptionType.NOT_EXIST_PRODUCT); + } + } + + public void checkOverStockAmountException(String requestProductName, int requestQuantity) { + Products products = stock.get(requestProductName); + PurchaseResponse purchaseResponse = products.checkQuantity(requestQuantity); + boolean isOverStock = purchaseResponse.getPurchaseResponseCode().equals(PurchaseResponseCode.OUT_OF_STOCK); + if (isOverStock) { + throw new InputException(ExceptionType.OVER_STOCK_AMOUNT); + } + } + + public List<ProductsDisplayData> getDisplayDatas() { + List<ProductsDisplayData> displayDatas = new ArrayList<>(); + for (Products products : stock.values()) { + displayDatas.add(products.getProductsData()); + } + return displayDatas; + } + + public void updateReceipt(CustomerRespond customerRespond, PurchaseResponse purchaseResponse) { + String productName = purchaseResponse.getName(); + PurchaseResponseCode purchaseResponseCode = purchaseResponse.getPurchaseResponseCode(); + int promotionCount = purchaseResponse.getPromotionCount(); + int restCount = purchaseResponse.getRestCount(); + Products products = stock.get(productName); + SalesData salesData = products.getSalesDataByEachCase(customerRespond, purchaseResponseCode, restCount, + promotionCount); + receipt.addSalesData(salesData); + } + + public ReceiptInformation getReceiptInformation(CustomerRespond membershipRespond) { + ReceiptInformation receiptInformation = receipt.getReceiptInformation(membershipRespond); + receipt = new Receipt(); + return receiptInformation; + } +}
Java
๋งž์Šต๋‹ˆ๋‹ค ๊ธฐ์กด์—๋Š” filePath๋ฅผ ๋ฐ›์•˜์–ด์„œ ๊ทธ๋ ‡๊ฒŒ ์ง€์—ˆ์—ˆ๊ณ  ๋งˆ์ง€๋ง‰์— ๊ณ ์น˜๋ ค ํ•œ ๋ฆฌํŒฉํ† ๋ง ๋ฆฌ์ŠคํŠธ ์ค‘ ํ•˜๋‚˜ ์˜€๋Š”๋ฐ ๋งˆ์ง€๋ง‰์— ์ œ์ถœ ๋•Œ ์ด์Šˆ๊ฐ€ ์ข€ ์žˆ์–ด์„œ ๋ฐ”๊พธ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค ใ…  ๊ผผ๊ผผํ•œ ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,124 @@ +package store.controller; + +import java.io.IOException; +import java.util.List; +import store.constant.ConstantBox; +import store.dto.PurchaseResponse; +import store.dto.ReceiptInformation; +import store.exception.InputException; +import store.model.domain.PurchaseResponseCode; +import store.model.domain.StockManager; +import store.model.domain.input.CustomerRespond; +import store.model.domain.input.ProductsInput; +import store.model.domain.product.ProductsDisplayData; +import store.view.inputview.InputView; +import store.view.inputview.InputViewType; +import store.view.outputview.OutputView; +import store.view.outputview.OutputViewFactory; + +public class StoreController { + + private InputView inputView; + private OutputView outputView; + private StockManager stockManager; + + public StoreController(InputView inputView, StockManager stockManager) { + this.inputView = inputView; + this.stockManager = stockManager; + } + + public void run() throws IOException { + while (true) { + displayStore(); + List<String> requestProducts = getRequestProducts(); + handlePurchase(requestProducts); + ReceiptInformation receiptInformation = getReceiptInformation(); + displayReceipt(receiptInformation); + CustomerRespond continueShopping = getContinueRespond(); + if (!continueShopping.doesCustomerAgree()) { + break; + } + } + } + + private CustomerRespond getContinueRespond() { + inputView.showRequestMessageOf(InputViewType.CONTINUE_SHOPPING); + return getCustomerRespond(); + } + + private void handlePurchase(List<String> requestProducts) { + for (String requestProduct : requestProducts) { + PurchaseResponse purchaseResponse = getPurchaseResponse(requestProduct); + PurchaseResponseCode purchaseResponseCode = purchaseResponse.getPurchaseResponseCode(); + CustomerRespond customerRespond = announceAndGetRespond(purchaseResponseCode, purchaseResponse); + stockManager.updateReceipt(customerRespond, purchaseResponse); + } + } + + private CustomerRespond announceAndGetRespond(PurchaseResponseCode purchaseResponseCode, + PurchaseResponse purchaseResponse) { + if (purchaseResponseCode.equals(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE)) { + inputView.showRequestMessageOf(InputViewType.PROMOTION_PARTIAL_UNAVAILABLE, purchaseResponse); + return getCustomerRespond(); + } + if (purchaseResponseCode.equals(PurchaseResponseCode.FREE_PRODUCT_REMIND)) { + inputView.showRequestMessageOf(InputViewType.FREE_PRODUCT_REMIND, purchaseResponse); + return getCustomerRespond(); + } + return null; + } + + private PurchaseResponse getPurchaseResponse(String requestProduct) { + String requestProductName = requestProduct.split(ConstantBox.INPUT_SEPARATOR)[0]; + int requestQuantity = Integer.parseInt(requestProduct.split(ConstantBox.INPUT_SEPARATOR)[1]); + return stockManager.getPurchaseResponseFrom(requestProductName, requestQuantity); + } + + private void displayReceipt(ReceiptInformation receiptInformation) { + outputView = OutputViewFactory.createReceiptDisplayView(receiptInformation); + outputView.display(); + } + + private ReceiptInformation getReceiptInformation() { + inputView.showRequestMessageOf(InputViewType.MEMBERSHIP); + CustomerRespond membershipRespond = getCustomerRespond(); + return stockManager.getReceiptInformation(membershipRespond); + } + + private List<String> getRequestProducts() { + inputView.showRequestMessageOf(InputViewType.PRODUCTS_NAME_AMOUNT); + while (true) { + try { + ProductsInput productsInput = new ProductsInput(inputView.getInput()); + List<String> requestProducts = productsInput.getRequestProducts(); + for (String requestProduct : requestProducts) { + String requestProductName = requestProduct.split(ConstantBox.INPUT_SEPARATOR)[0]; + int requestQuantity = Integer.parseInt(requestProduct.split(ConstantBox.INPUT_SEPARATOR)[1]); + stockManager.checkNotExistProductException(requestProductName); + stockManager.checkOverStockAmountException(requestProductName, requestQuantity); + } + return requestProducts; + } catch (InputException e) { + System.out.println(e.getMessage()); + } + } + } + + private CustomerRespond getCustomerRespond() { + CustomerRespond customerRespond; + while (true) { + try { + return new CustomerRespond(inputView.getInput()); + } catch (InputException e) { + System.out.println(e.getMessage()); + } + } + } + + private void displayStore() { + List<ProductsDisplayData> displayDatas = stockManager.getDisplayDatas(); + outputView = OutputViewFactory.createProductDisplayView(displayDatas); + outputView.display(); + } +} +
Java
์ข‹์€ ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! ๋งˆ์ง€๋ง‰์— ๊ธ‰ํ•˜๊ฒŒ ์ œ์ถœํ•˜๋‹ค ๋ณด๋‹ˆ ๋น ํŠธ๋ฆฌ๊ฒŒ ๋˜์—ˆ๋„ค์š” ๐Ÿ˜ญ ๊ผผ๊ผผํžˆ ๋ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,28 @@ +package store.model.domain.product; + +public class ProductsDisplayData { + + private String promotionProductData; + private String normalProductData; + + public ProductsDisplayData(String promotionProductData, String normalProductData) { + this.promotionProductData = promotionProductData; + this.normalProductData = normalProductData; + } + + public String getPromotionProductData() { + return promotionProductData; + } + + public void setPromotionProductData(String promotionProductData) { + this.promotionProductData = promotionProductData; + } + + public String getNormalProductData() { + return normalProductData; + } + + public void setNormalProductData(String normalProductData) { + this.normalProductData = normalProductData; + } +}
Java
์˜ค ๋งž์Šต๋‹ˆ๋‹ค! ์ด ๋ถ€๋ถ„๋„ ๋งˆ์ง€๋ง‰ ์ œ์ถœ์ด ๊ธ‰ํ•ด์„œ ๋น ํŠธ๋ฆฌ๊ฒŒ ๋˜์—ˆ๋„ค์š”,, ์ข‹์€ ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,107 @@ +package store.model.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import store.dto.PurchaseResponse; + +public class Promotion { + + private static final String DATE_FORMAT = "yyyy-MM-dd"; + public static final int NO_PARTIAL = 0; + + private final int buy; + private final int get; + private final List<String> promotionInformation; + + public Promotion(List<String> promotionInformation) { + this.promotionInformation = promotionInformation; + this.buy = Integer.parseInt(promotionInformation.get(1)); + this.get = Integer.parseInt(promotionInformation.get(2)); + } + + public boolean isOnPromotion() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT); + String startDateInformation = promotionInformation.get(3); + LocalDateTime startDate = LocalDate.parse(startDateInformation, formatter).atStartOfDay(); + String endDateInformation = promotionInformation.get(4); + LocalDateTime endDate = LocalDate.parse(endDateInformation, formatter).atStartOfDay(); + LocalDateTime today = DateTimes.now(); + return (today.isAfter(startDate) && today.isBefore(endDate)); + } + + public PurchaseResponse discount(int requestQuantity, int stockQuantity) { + int promotionCount = requestQuantity / (buy + get); + int restCount = requestQuantity % (buy + get); + return getResponse(requestQuantity, stockQuantity, promotionCount, restCount); + } + + private PurchaseResponse getResponse(int requestQuantity, int stockQuantity, int promotionCount, int restCount) { + if (isInsufficientStock(requestQuantity, stockQuantity)) { + return responseInsufficientStock(requestQuantity, stockQuantity); + } + if (isSuccessPromotionPurchase(restCount)) { + return responseSuccessPromotionPurchase(promotionCount, restCount); + } + if (isNeedFreeRemind(restCount)) { + return responseInsufficientFreeStockOrFreeRemind(requestQuantity, stockQuantity, promotionCount, restCount); + } + return responsePartialAvailable(promotionCount, restCount); + } + + private PurchaseResponse responsePartialAvailable(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private boolean isInsufficientStock(int requestQuantity, int stockQuantity) { + return requestQuantity > stockQuantity; + } + + private PurchaseResponse responseInsufficientStock(int requestQuantity, int stockQuantity) { + int promotionCount = stockQuantity / (buy + get); + int restCount = stockQuantity % (buy + get) + (requestQuantity - stockQuantity); + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private boolean isSuccessPromotionPurchase(int restCount) { + return restCount == NO_PARTIAL; + } + + private PurchaseResponse responseSuccessPromotionPurchase(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PURCHASE_SUCCESS, promotionCount, restCount); + } + + private boolean isNeedFreeRemind(int restCount) { + return restCount == buy; + } + + private boolean isInsufficientFreeStock(int requestQuantity, int stockQuantity) { + return requestQuantity == stockQuantity; + } + + private PurchaseResponse responseInsufficientFreeStockOrFreeRemind(int requestQuantity, int stockQuantity, + int promotionCount, int restCount) { + if (isInsufficientFreeStock(requestQuantity, stockQuantity)) { + return responseInsufficientFreeStock(promotionCount, restCount); + } + return responseFreeRemind(promotionCount, restCount); + } + + private PurchaseResponse responseInsufficientFreeStock(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private PurchaseResponse responseFreeRemind(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.FREE_PRODUCT_REMIND, promotionCount, restCount); + } + + public String getPromotionName() { + return promotionInformation.getFirst(); + } + + public int getAppliedQuantity() { + return buy + get; + } +}
Java
> ์ƒ์„ฑ์ž๋ฅผ ํ˜ธ์ถœํ•  ๋•Œ ํŒŒ์‹ฑ์„ํ•˜๊ณ  ๋„˜๊ฒจ์ฃผ๋Š” ์ชฝ ์ด ๋งž์Šต๋‹ˆ๋‹ค ๐Ÿ˜„ ์ œ๊ฐ€ ํ‘œํ˜„์ด ๋ชจํ˜ธํ–ˆ๋„ค์š” ์˜ˆ๋ฅผ ๋“ค์–ด Promotion ์„ ์ดˆ๊ธฐํ™”ํ•˜๋Š”, ์ฆ‰ ์ƒ์„ฑํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ํ˜„์žฌ๋Š” List<String> ์„ ํ†ตํ•ด์„œ ์ƒ์„ฑํ•˜๋Š” ํ•œ ๊ฐ€์ง€ ๋ฐฉ๋ฒ•๋งŒ์ด ์žˆ์ง€๋งŒ, ์ถ”๊ฐ€ ์š”๊ตฌ ์‚ฌํ•ญ์ด(๊ธฐ๋Šฅ์˜ ์ถ”๊ฐ€, ์ˆ˜์ • ์‚ญ์ œ) ์ƒ๊ฒจ์„œ Promotion ์„ ๋‹ค๋ฅด๊ฒŒ ์ดˆ๊ธฐํ™” ํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ ๋˜ ๋‹ค๋ฅธ ์ƒ์„ฑ์ž๊ฐ€ ์ •์˜๋˜์–ด์•ผ ํ•  ๊ฒƒ ๊ฐ™์•„์š”! ์ด ๋•Œ ํ”„๋กœ๊ทธ๋ž˜๋จธ๋Š” ์„ ํƒ์„ ํ•ด์•ผ ํ•˜๋Š”๋ฐ 1. private ์ƒ์„ฑ์ž๋ฅผ ์ •์˜ํ•˜๊ณ , public static ๋ฉ”์„œ๋“œ๋ฅผ(์ •์  ํŒฉํ† ๋ฆฌ) ํ†ตํ•ด ์ƒ์„ฑํ•˜๋„๋ก ํ•œ๋‹ค. 2. public ์ƒ์„ฑ์ž๋ฅผ ๋‘๊ณ , ํ˜ธ์ถœํ•˜๋Š” ์ธก์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€๊ณต(parse)ํ•œ ํ›„ ์ƒ์„ฑ์ž๋ฅผ ํ˜ธ์ถœํ•˜๊ฒŒ ํ•œ๋‹ค ๋‘ ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์ด ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”. 1,2๋ฒˆ ๋ชจ๋‘ ์ƒํ™ฉ์— ๋”ฐ๋ผ ์–ด๋А ์ชฝ์„ ์„ ํ˜ธ ํ•ด์•ผ ํ•  ์ง€๊ฐ€ ๋‹ค๋ฅด๊ฒ ์ง€๋งŒ, ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์— ์ถ”๊ฐ€ ์š”๊ตฌ์‚ฌํ•ญ์ด ์ƒ๊ธฐ๊ณ , ๊ทธ์— ๋”ฐ๋ผ ๊ธฐ๋Šฅ์„ ํ™•์žฅ/์ˆ˜์ •/์‚ญ์ œ ํ•ด์•ผ ํ•˜๋Š” ์ƒํ™ฉ์ด ์ƒ๊ธฐ๋Š”(์ด ๋ถ€๋ถ„์ด ์ œ๊ฐ€ ๋ง์”€๋“œ๋ฆฐ "์šด์˜์ฝ”๋“œ์—์„œ์˜ ํ™•์žฅ" ์ž…๋‹ˆ๋‹ค) ๊ฒƒ์„ ๊ณ ๋ ค ํ–ˆ์„ ๋•Œ ์ €๋Š” ๊ฐ€๋Šฅํ•œ Promotion ํด๋ž˜์Šค์˜ ํ•„์ˆ˜ ํ•„๋“œ(final field)๋ฅผ ์ƒ์„ฑ์ž๋กœ ๋‘๋Š” ๊ฒƒ์„ ์„ ํ˜ธํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ํ…Œ์ŠคํŠธ ์ฝ”๋“œ์˜ ๊ฒฝ์šฐ์—๋„, ํ…Œ์ŠคํŠธ์—์„œ ์ด ๊ฐ’, ์ € ๊ฐ’ ๋„ฃ์–ด๋ณด๋ฉฐ ํ…Œ์ŠคํŠธํ•˜๊ธฐ๊ฐ€ ์ข€ ๋” ํŽธํ•˜๊ณ , ์ง๊ด€์ ์ด๋ผ๊ณ  ์ƒ๊ฐํ•ด์š” ๐Ÿ˜„ ๋”๋ถˆ์–ด 1๋ฒˆ ์ •์  ํŒฉํ† ๋ฆฌ ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ "์ด ๋ฐ์ดํ„ฐ๋Š” ์ด ๋ฐฉ์‹์œผ๋กœ ์ดˆ๊ธฐํ™”๋˜์–ด์•ผ ํ•ด" ๋ฅผ ๋ช…์‹œํ•˜๋Š” ํšจ๊ณผ๊ฐ€ ์žˆ๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ, ํ•ด๋‹น ๋ถ€๋ถ„์—์„œ Promotion ๋„๋ฉ”์ธ์ด์ด ์ธํ”„๋ผ์ ์ธ ์š”๊ตฌ์‚ฌํ•ญ (๋งˆํฌ๋‹ค์šด ํŒŒ์ผ์„ List<String> ๋ฐ์ดํ„ฐ๋ฅผ ์ด์šฉํ•˜๋ผ๋Š” ์š”๊ตฌ์‚ฌํ•ญ)์— ์˜ํ•ด์„œ๋งŒ ์ดˆ๊ธฐํ™” ๋˜๋Š” ์‚ฌ์‹ค์„ ๋„๋ฉ”์ธ์ด ์•Œ๊ณ  ์žˆ๋Š” ํ˜•ํƒœ, ์ฆ‰ ์˜์กดํ•˜๊ณ  ์žˆ๋Š” ํ˜•ํƒœ๊ฐ€ ๋˜๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋ฌผ๋ก , ์ด ๋ฐฉ๋ฒ•์ด ํ•ญ์ƒ ๋‚˜์œ ๊ฒƒ์€ ์•„๋‹ˆ๋ฉฐ ํŽธ์˜์— ์˜ํ•ด์„œ ์–ผ๋งˆ๋“ ์ง€ ์‚ฌ์šฉ๋˜์–ด๋„ ์ข‹๋‹ค๊ณ  ์ƒ๊ฐ์€ ํ•ฉ๋‹ˆ๋‹ค๋งŒ! ๋” ์ค‘์š”ํ•œ ๋ชจ๋“ˆ(๋„๋ฉ”์ธ) ์ด ๋œ ์ค‘์š”ํ•œ ๋ชจ๋“ˆ(์ธํ”„๋ผ)์— ์˜์กดํ•˜์ง€ ์•Š๊ฒŒ ๋งŒ๋“ค๋ฉด ์ข€ ๋” ์œ ์—ฐํ•œ ํ™•์žฅ์ด ๊ฐ€๋Šฅ ํ•  ๊ฒƒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,107 @@ +package store.model.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import store.dto.PurchaseResponse; + +public class Promotion { + + private static final String DATE_FORMAT = "yyyy-MM-dd"; + public static final int NO_PARTIAL = 0; + + private final int buy; + private final int get; + private final List<String> promotionInformation; + + public Promotion(List<String> promotionInformation) { + this.promotionInformation = promotionInformation; + this.buy = Integer.parseInt(promotionInformation.get(1)); + this.get = Integer.parseInt(promotionInformation.get(2)); + } + + public boolean isOnPromotion() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT); + String startDateInformation = promotionInformation.get(3); + LocalDateTime startDate = LocalDate.parse(startDateInformation, formatter).atStartOfDay(); + String endDateInformation = promotionInformation.get(4); + LocalDateTime endDate = LocalDate.parse(endDateInformation, formatter).atStartOfDay(); + LocalDateTime today = DateTimes.now(); + return (today.isAfter(startDate) && today.isBefore(endDate)); + } + + public PurchaseResponse discount(int requestQuantity, int stockQuantity) { + int promotionCount = requestQuantity / (buy + get); + int restCount = requestQuantity % (buy + get); + return getResponse(requestQuantity, stockQuantity, promotionCount, restCount); + } + + private PurchaseResponse getResponse(int requestQuantity, int stockQuantity, int promotionCount, int restCount) { + if (isInsufficientStock(requestQuantity, stockQuantity)) { + return responseInsufficientStock(requestQuantity, stockQuantity); + } + if (isSuccessPromotionPurchase(restCount)) { + return responseSuccessPromotionPurchase(promotionCount, restCount); + } + if (isNeedFreeRemind(restCount)) { + return responseInsufficientFreeStockOrFreeRemind(requestQuantity, stockQuantity, promotionCount, restCount); + } + return responsePartialAvailable(promotionCount, restCount); + } + + private PurchaseResponse responsePartialAvailable(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private boolean isInsufficientStock(int requestQuantity, int stockQuantity) { + return requestQuantity > stockQuantity; + } + + private PurchaseResponse responseInsufficientStock(int requestQuantity, int stockQuantity) { + int promotionCount = stockQuantity / (buy + get); + int restCount = stockQuantity % (buy + get) + (requestQuantity - stockQuantity); + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private boolean isSuccessPromotionPurchase(int restCount) { + return restCount == NO_PARTIAL; + } + + private PurchaseResponse responseSuccessPromotionPurchase(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PURCHASE_SUCCESS, promotionCount, restCount); + } + + private boolean isNeedFreeRemind(int restCount) { + return restCount == buy; + } + + private boolean isInsufficientFreeStock(int requestQuantity, int stockQuantity) { + return requestQuantity == stockQuantity; + } + + private PurchaseResponse responseInsufficientFreeStockOrFreeRemind(int requestQuantity, int stockQuantity, + int promotionCount, int restCount) { + if (isInsufficientFreeStock(requestQuantity, stockQuantity)) { + return responseInsufficientFreeStock(promotionCount, restCount); + } + return responseFreeRemind(promotionCount, restCount); + } + + private PurchaseResponse responseInsufficientFreeStock(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private PurchaseResponse responseFreeRemind(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.FREE_PRODUCT_REMIND, promotionCount, restCount); + } + + public String getPromotionName() { + return promotionInformation.getFirst(); + } + + public int getAppliedQuantity() { + return buy + get; + } +}
Java
์‚ฌ์‹ค, ์œ„์˜ '์ธํ”„๋ผ'์™€ '๋„๋ฉ”์ธ' ์ค‘ ๋” ์ค‘์š”ํ•œ ๊ฒƒ์ด ๋œ ์ค‘์š”ํ•œ ๊ฒƒ์„ ์˜์กดํ•˜์ง€ ์•Š๊ฒŒ ํ•˜์ž! ๋Š” ๋ง๊ณผ๋„ ๊ฐ™์€ ๋งฅ๋ฝ์ธ๋ฐ์š”! ํ•ด๋‹น Dto ๋Š” ๋„๋ฉ”์ธ๋ณด๋‹ค ๋œ ์ค‘์š”ํ•˜๋‹ˆ, Dto ์˜ ๋ณ€๊ฒฝ์ด ๋„๋ฉ”์ธ์— ์˜ํ–ฅ์„ ๋ฏธ์น˜๊ฒŒ ํ•˜๋ฉด ์–ด๋–จ๊นŒ? ํ•˜๋Š” ์ด์•ผ๊ธฐ์˜€๋‹ต๋‹ˆ๋‹ค. ์‚ฌ์‹ค ์ž‘์„ฑ ํ•ด ์ฃผ์‹  ๋ฐฉ์‹์€ ์•„์ฃผ ๊น”๋”ํ•˜๊ฒŒ ์ž˜ ์„ค๊ณ„๋˜์–ด ์žˆ์ง€๋งŒ, ํ•ด๋‹น ๋ฐฉ์‹(DTO๋ฅผ ๋งŒ๋“ค์–ด์„œ ๋ฆฌํ„ดํ•˜๋Š”)์€ service์—์„œ ํ•˜๋Š” ์ผ์— ๊ฐ€๊น์ง€ ์•Š๋‚˜? ์‹ถ์€ ์˜๋ฌธ๋„ ์žˆ์Šต๋‹ˆ๋‹ค. ๋„๋ฉ”์ธ์€ ๋” ์ž‘๊ณ , ์ค‘์š”ํ•œ ๋ฐ์ดํ„ฐ ์กฐ์ž‘๊ณผ ๊ด€๋ฆฌ๋ฅผ ํ•˜๊ณ  ์„œ๋น„์Šค์—์„œ ํ•ด๋‹น ๋ฐ์ดํ„ฐ๋“ค์„ ๋ชจ์•„์„œ ๋ฆฌํ„ดํ•˜๋ฉด ์–ด๋–จ๊นŒ ํ•ด์š”. ๋„๋ฉ”์ธ์˜ ๋ฉ”์„œ๋“œ ํ•˜๋‚˜๊ฐ€ ํ•˜๋‚˜์˜ ๋ฐ์ดํ„ฐ๋งŒ ์กฐ์ž‘ํ•˜๊ณ , ๋ฆฌํ„ดํ•˜๊ณ , ํ•ด๋‹น ๋ฉ”์„œ๋“œ๋“ค์„ public ์œผ๋กœ ๋งŒ๋“ค์–ด์„œ ์™ธ๋ถ€์™€ ์ƒํ˜ธ์ž‘์šฉํ•˜๊ฒŒ ๋งŒ๋“œ๋Š” ๊ฒƒ์ด์ฃ . ์™ธ๋ถ€(์•„๋งˆ๋„ ์„œ๋น„์Šค)์—์„œ๋Š” ์ด public ๋ฉ”์„œ๋“œ๋ฅผ ์กฐํ•ฉํ•ด์„œ ์ปค๋‹ค๋ž€ ๋ฐ์ดํ„ฐ ๋ฉ์–ด๋ฆฌ(DTO๋ผ๊ณ  ๋ถ€๋ฅด๋Š”)๋ฅผ ๋งŒ๋“ค๊ณ , ์ด๋ฅผ ์ปจํŠธ๋กค๋Ÿฌ ์ธก์— ๋„˜๊ฒจ์„œ ์ตœ์ข…์ ์œผ๋กœ๋Š” view ์— ๋ฟŒ๋ ค์ฃผ๋Š” ์‹์€ ์–ด๋–จ๊นŒ์š”? ๐Ÿ˜„
@@ -0,0 +1,80 @@ +package store.model.domain; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import store.dto.ReceiptInformation; +import store.dto.SalesData; +import store.model.domain.input.CustomerRespond; + +public class Receipt { + + private static final int ZERO = 0; + public static final int MAX_MEMBERSHIP_DISCOUNT = 8000; + public static final int MIN_MEMBERSHIP_DISCOUNT = 1000; + + private final List<String> names = new ArrayList<>(); + private final List<Integer> quantities = new ArrayList<>(); + private final List<Integer> prices = new ArrayList<>(); + private final List<Integer> promotionCounts = new ArrayList<>(); + + public void addSalesData(SalesData salesData) { + names.add(salesData.getName()); + quantities.add(salesData.getQuantity()); + prices.add(salesData.getPrice()); + promotionCounts.add(salesData.getPromotionCount()); + } + + public ReceiptInformation getReceiptInformation(CustomerRespond membershipRespond) { + int totalPurchased = ZERO; + int promotionDiscount = ZERO; + int totalQuantity = ZERO; + List<Integer> amountInformation = generateAmountInformation(membershipRespond, totalPurchased, + promotionDiscount, totalQuantity); + Map<String, List> salesDatas = generateSalesDatas(); + return new ReceiptInformation(salesDatas, amountInformation); + } + + private List<Integer> generateAmountInformation(CustomerRespond membershipRespond, int totalPurchased, + int promotionDiscount, + int totalQuantity) { + for (int productKindIndex = ZERO; productKindIndex < names.size(); productKindIndex++) { + totalPurchased += quantities.get(productKindIndex) * prices.get(productKindIndex); + promotionDiscount += promotionCounts.get(productKindIndex) * prices.get(productKindIndex); + totalQuantity += quantities.get(productKindIndex); + } + int memberShipDiscount = getMembershipDiscount(membershipRespond, totalPurchased, promotionDiscount); + int pay = totalPurchased - promotionDiscount - memberShipDiscount; + return List.of(totalQuantity, totalPurchased, promotionDiscount, memberShipDiscount, pay); + } + + private int getMembershipDiscount(CustomerRespond membershipRespond, int totalPurchasedAmount, + int promotionDiscountAmount) { + if (!membershipRespond.doesCustomerAgree()) { + return ZERO; + } + return calculateMembershipDiscount(totalPurchasedAmount, promotionDiscountAmount); + } + + private static int calculateMembershipDiscount(int totalPurchasedAmount, int promotionDiscountAmount) { + double discount = (totalPurchasedAmount - promotionDiscountAmount) * 0.3; + int memberShipDiscountAmount = ((int) discount / 1000) * 1000; + if (memberShipDiscountAmount < MIN_MEMBERSHIP_DISCOUNT) { + return ZERO; + } + if (memberShipDiscountAmount > MAX_MEMBERSHIP_DISCOUNT) { + return MAX_MEMBERSHIP_DISCOUNT; + } + return memberShipDiscountAmount; + } + + private Map<String, List> generateSalesDatas() { + return Map.of( + "names", Collections.unmodifiableList(names), + "quantities", Collections.unmodifiableList(quantities), + "prices", Collections.unmodifiableList(prices), + "promotionCounts", Collections.unmodifiableList(promotionCounts) + ); + } +}
Java
์šฐํ…Œ์ฝ” ํ”ผ๋“œ๋ฐฑ ์‚ฌํ•ญ์„ ์ƒ๊ฐํ•˜๋‹ค ๋ณด๋‹ˆ ๊ธฐ๊ณ„์ ์œผ๋กœ ์ƒ์ˆ˜ํ™”๋ฅผ ์ง„ํ–‰ํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ํ•  ๋•Œ ๋‹น์‹œ์—๋Š” ํฐ ์ด์œ ๋Š” ์—†์—ˆ์ง€๋งŒ ๊ทธ๋ž˜๋„ 0์ด๋ผ๋Š” ์ˆซ์ž๋ณด๋‹ค๋Š” ZERO๋ผ๋Š” ์ƒ์ˆ˜๋กœ ํ‘œํ˜„ํ•˜๋Š” ๊ฒƒ์ด ์ข€ ๋” ์ง๊ด€์ ์ด์ง€ ์•Š์„๊นŒ,, ์ƒ๊ฐ๋„ ๋“œ๋„ค์š”,, ๊ทผ๋ฐ 0๋„ ์ถฉ๋ถ„ํžˆ ์ง๊ด€์ ์ด๋ผ ๋งค์šฐ ์˜๋ฏธ ์žˆ์–ด ๋ณด์ด์ง„ ์•Š๋Š” ๊ฒƒ ๊ฐ™๋„ค์š” ๐Ÿ˜ญ
@@ -0,0 +1,107 @@ +package store.model.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import store.dto.PurchaseResponse; + +public class Promotion { + + private static final String DATE_FORMAT = "yyyy-MM-dd"; + public static final int NO_PARTIAL = 0; + + private final int buy; + private final int get; + private final List<String> promotionInformation; + + public Promotion(List<String> promotionInformation) { + this.promotionInformation = promotionInformation; + this.buy = Integer.parseInt(promotionInformation.get(1)); + this.get = Integer.parseInt(promotionInformation.get(2)); + } + + public boolean isOnPromotion() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT); + String startDateInformation = promotionInformation.get(3); + LocalDateTime startDate = LocalDate.parse(startDateInformation, formatter).atStartOfDay(); + String endDateInformation = promotionInformation.get(4); + LocalDateTime endDate = LocalDate.parse(endDateInformation, formatter).atStartOfDay(); + LocalDateTime today = DateTimes.now(); + return (today.isAfter(startDate) && today.isBefore(endDate)); + } + + public PurchaseResponse discount(int requestQuantity, int stockQuantity) { + int promotionCount = requestQuantity / (buy + get); + int restCount = requestQuantity % (buy + get); + return getResponse(requestQuantity, stockQuantity, promotionCount, restCount); + } + + private PurchaseResponse getResponse(int requestQuantity, int stockQuantity, int promotionCount, int restCount) { + if (isInsufficientStock(requestQuantity, stockQuantity)) { + return responseInsufficientStock(requestQuantity, stockQuantity); + } + if (isSuccessPromotionPurchase(restCount)) { + return responseSuccessPromotionPurchase(promotionCount, restCount); + } + if (isNeedFreeRemind(restCount)) { + return responseInsufficientFreeStockOrFreeRemind(requestQuantity, stockQuantity, promotionCount, restCount); + } + return responsePartialAvailable(promotionCount, restCount); + } + + private PurchaseResponse responsePartialAvailable(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private boolean isInsufficientStock(int requestQuantity, int stockQuantity) { + return requestQuantity > stockQuantity; + } + + private PurchaseResponse responseInsufficientStock(int requestQuantity, int stockQuantity) { + int promotionCount = stockQuantity / (buy + get); + int restCount = stockQuantity % (buy + get) + (requestQuantity - stockQuantity); + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private boolean isSuccessPromotionPurchase(int restCount) { + return restCount == NO_PARTIAL; + } + + private PurchaseResponse responseSuccessPromotionPurchase(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PURCHASE_SUCCESS, promotionCount, restCount); + } + + private boolean isNeedFreeRemind(int restCount) { + return restCount == buy; + } + + private boolean isInsufficientFreeStock(int requestQuantity, int stockQuantity) { + return requestQuantity == stockQuantity; + } + + private PurchaseResponse responseInsufficientFreeStockOrFreeRemind(int requestQuantity, int stockQuantity, + int promotionCount, int restCount) { + if (isInsufficientFreeStock(requestQuantity, stockQuantity)) { + return responseInsufficientFreeStock(promotionCount, restCount); + } + return responseFreeRemind(promotionCount, restCount); + } + + private PurchaseResponse responseInsufficientFreeStock(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private PurchaseResponse responseFreeRemind(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.FREE_PRODUCT_REMIND, promotionCount, restCount); + } + + public String getPromotionName() { + return promotionInformation.getFirst(); + } + + public int getAppliedQuantity() { + return buy + get; + } +}
Java
์ธํ”„๋ผ์— ์˜์กด, ์šด์˜์ฝ”๋“œ์—์„œ์˜ ํ™•์žฅ ์ธก๋ฉด ๋“ฑ ๋‹ค์–‘ํ•˜๊ฒŒ ์ œ๊ฐ€ ์ƒ๊ฐํ•ด๋ณด์ง€ ์•Š์€ ์˜์—ญ๋“ค์„ ์•Œ๋ ค์ฃผ์‹  ๊ฒƒ ๊ฐ™์•„ ์ œ ์ƒ๊ฐ์ด ํ™•์žฅ๋˜๋Š” ๋А๋‚Œ์ด๋„ค์š”! ์ž์„ธํ•œ ๋‹ต๋ณ€ ๊ฐ์‚ฌ๋“œ๋ฆฝ๋‹ˆ๋‹ค! ๐Ÿ‘
@@ -0,0 +1,107 @@ +package store.model.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import store.dto.PurchaseResponse; + +public class Promotion { + + private static final String DATE_FORMAT = "yyyy-MM-dd"; + public static final int NO_PARTIAL = 0; + + private final int buy; + private final int get; + private final List<String> promotionInformation; + + public Promotion(List<String> promotionInformation) { + this.promotionInformation = promotionInformation; + this.buy = Integer.parseInt(promotionInformation.get(1)); + this.get = Integer.parseInt(promotionInformation.get(2)); + } + + public boolean isOnPromotion() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT); + String startDateInformation = promotionInformation.get(3); + LocalDateTime startDate = LocalDate.parse(startDateInformation, formatter).atStartOfDay(); + String endDateInformation = promotionInformation.get(4); + LocalDateTime endDate = LocalDate.parse(endDateInformation, formatter).atStartOfDay(); + LocalDateTime today = DateTimes.now(); + return (today.isAfter(startDate) && today.isBefore(endDate)); + } + + public PurchaseResponse discount(int requestQuantity, int stockQuantity) { + int promotionCount = requestQuantity / (buy + get); + int restCount = requestQuantity % (buy + get); + return getResponse(requestQuantity, stockQuantity, promotionCount, restCount); + } + + private PurchaseResponse getResponse(int requestQuantity, int stockQuantity, int promotionCount, int restCount) { + if (isInsufficientStock(requestQuantity, stockQuantity)) { + return responseInsufficientStock(requestQuantity, stockQuantity); + } + if (isSuccessPromotionPurchase(restCount)) { + return responseSuccessPromotionPurchase(promotionCount, restCount); + } + if (isNeedFreeRemind(restCount)) { + return responseInsufficientFreeStockOrFreeRemind(requestQuantity, stockQuantity, promotionCount, restCount); + } + return responsePartialAvailable(promotionCount, restCount); + } + + private PurchaseResponse responsePartialAvailable(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private boolean isInsufficientStock(int requestQuantity, int stockQuantity) { + return requestQuantity > stockQuantity; + } + + private PurchaseResponse responseInsufficientStock(int requestQuantity, int stockQuantity) { + int promotionCount = stockQuantity / (buy + get); + int restCount = stockQuantity % (buy + get) + (requestQuantity - stockQuantity); + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private boolean isSuccessPromotionPurchase(int restCount) { + return restCount == NO_PARTIAL; + } + + private PurchaseResponse responseSuccessPromotionPurchase(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PURCHASE_SUCCESS, promotionCount, restCount); + } + + private boolean isNeedFreeRemind(int restCount) { + return restCount == buy; + } + + private boolean isInsufficientFreeStock(int requestQuantity, int stockQuantity) { + return requestQuantity == stockQuantity; + } + + private PurchaseResponse responseInsufficientFreeStockOrFreeRemind(int requestQuantity, int stockQuantity, + int promotionCount, int restCount) { + if (isInsufficientFreeStock(requestQuantity, stockQuantity)) { + return responseInsufficientFreeStock(promotionCount, restCount); + } + return responseFreeRemind(promotionCount, restCount); + } + + private PurchaseResponse responseInsufficientFreeStock(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.PROMOTION_PARTIAL_UNAVAILABLE, promotionCount, restCount); + } + + private PurchaseResponse responseFreeRemind(int promotionCount, int restCount) { + return new PurchaseResponse(PurchaseResponseCode.FREE_PRODUCT_REMIND, promotionCount, restCount); + } + + public String getPromotionName() { + return promotionInformation.getFirst(); + } + + public int getAppliedQuantity() { + return buy + get; + } +}
Java
์˜ค ๋ง์”€ํ•ด์ฃผ์‹  ๊ฒƒ์ด ์ œ๊ฐ€ ํ•ด๋ณด๊ณ ์ž ํ•œ ๋ฐฉํ–ฅ์ด์—ˆ๋˜ ๊ฒƒ ๊ฐ™์•„์š”! ๋„๋ฉ”์ธ์€ ํ•˜๋‚˜์˜ ๋ฐ์ดํ„ฐ๋งŒ ๋ฉ”์„ธ์ง€๋ฅผ ๋ฐ›์•„ ์กฐ์ž‘,๋ฆฌํ„ด ํ•ด๋‹น ๋ฉ”์„œ๋“œ๋“ค์„ ํ†ตํ•ด ์„œ๋น„์Šค์—์„œ DTO๋ฅผ ์กฐ๋ฆฝ,, ๋จธ๋ฆฌ ์†์—์„œ๋งŒ ์• ๋งคํ•˜๊ฒŒ ์žˆ์–ด ๋‹ค์†Œ ๋†“์นœ ๋ถ€๋ถ„๋“ค ๋•Œ๋ฌธ์— ์ด๋ฒˆ์— ์งฌ๋ฝ•์ด ๋œ ๋А๋‚Œ์ธ๋ฐ ๋‹ต๊ธ€์„ ๋ณด๊ณ  ๊ฐœ๋…์ ์œผ๋กœ ์ข€ ๋” ํด๋ฆฌ์–ดํ•ด์ง„ ๊ฒƒ ๊ฐ™๋„ค์š”.. ์ •๋ง ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! ๐Ÿ‘
@@ -0,0 +1,92 @@ +package store.controller; + +import store.model.Product; +import store.model.Receipt; +import store.model.Store; +import store.view.InputView; +import store.view.OutputView; + +import java.util.Map; + +public class BuyController { + private final Store store; + + public BuyController(Store store) { + this.store = store; + } + + public void buyProduct() { + boolean continueShopping = true; + while (continueShopping) { + Receipt receipt = new Receipt(); + try { + Map<String, Integer> purchasedItems = InputView.purchasedItems(); + processPurchasedItems(receipt, purchasedItems); + applyMembershipDiscount(receipt); + receipt.print(); + OutputView.askForAdditionalPurchase(); + continueShopping = InputView.yOrN(); + if (continueShopping) OutputView.printInventoryInformation(store); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private void processPurchasedItems(Receipt receipt, Map<String, Integer> purchasedItems) { + for (String key : purchasedItems.keySet()) { + int number = purchasedItems.get(key); + Product product = checkInventory(key, number); + if (product.isPromotion()) { + processPromotionalItem(receipt, product, number, purchasedItems, key); + } else { + addItemToReceipt(receipt, product, number, 0); + } + } + } + + private void processPromotionalItem(Receipt receipt, Product product, int number, Map<String, Integer> purchasedItems, String key) { + int eventProduct = product.addPromotions(number); + if (eventProduct != 0) { + if (product.getQuantity() >= eventProduct + number) { + OutputView.printAddEventProduct(eventProduct, product.getName()); + if (InputView.yOrN()) { + number += eventProduct; + purchasedItems.put(key, number); + } + } + if (product.getQuantity() < eventProduct + number) { + OutputView.PromotionNotApplied(product); + if (!InputView.yOrN()) { + number -= product.getPromotionBuy(); + purchasedItems.put(key, number); + } + } + } + store.deductInventory(product.getName(), number); + addItemToReceipt(receipt, product, number, product.applyPromotions(number)); + } + + private void addItemToReceipt(Receipt receipt, Product product, int quantity, int promotionAppliedQuantity) { + receipt.addItem(product, quantity, promotionAppliedQuantity); + } + + private void applyMembershipDiscount(Receipt receipt) { + OutputView.printMemberShipDiscount(); + if (InputView.yOrN()) { + receipt.applyMembershipDiscount(); + } + } + + private Product checkInventory(String productName, int quantity) { + if (productName == null || quantity <= 0) { + throw new IllegalArgumentException("[ERROR] ์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + Product product = store.findProductByName(productName) + .orElseThrow(() -> new IllegalArgumentException("[ERROR] ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.")); + if (product.getQuantity() < quantity) { + throw new IllegalArgumentException("[ERROR] ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + return product; + } +}
Java
depth๊ฐ€ 3์ด๋„ค์š”! ๋ฉ”์„œ๋“œ๋ฅผ ๋ถ„๋ฆฌํ–ˆ๋‹ค๋ฉด ๋” ์ข‹์•˜์„ ๊ฒƒ ๊ฐ™์•„์š”!:)
@@ -0,0 +1,92 @@ +package store.controller; + +import store.model.Product; +import store.model.Receipt; +import store.model.Store; +import store.view.InputView; +import store.view.OutputView; + +import java.util.Map; + +public class BuyController { + private final Store store; + + public BuyController(Store store) { + this.store = store; + } + + public void buyProduct() { + boolean continueShopping = true; + while (continueShopping) { + Receipt receipt = new Receipt(); + try { + Map<String, Integer> purchasedItems = InputView.purchasedItems(); + processPurchasedItems(receipt, purchasedItems); + applyMembershipDiscount(receipt); + receipt.print(); + OutputView.askForAdditionalPurchase(); + continueShopping = InputView.yOrN(); + if (continueShopping) OutputView.printInventoryInformation(store); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private void processPurchasedItems(Receipt receipt, Map<String, Integer> purchasedItems) { + for (String key : purchasedItems.keySet()) { + int number = purchasedItems.get(key); + Product product = checkInventory(key, number); + if (product.isPromotion()) { + processPromotionalItem(receipt, product, number, purchasedItems, key); + } else { + addItemToReceipt(receipt, product, number, 0); + } + } + } + + private void processPromotionalItem(Receipt receipt, Product product, int number, Map<String, Integer> purchasedItems, String key) { + int eventProduct = product.addPromotions(number); + if (eventProduct != 0) { + if (product.getQuantity() >= eventProduct + number) { + OutputView.printAddEventProduct(eventProduct, product.getName()); + if (InputView.yOrN()) { + number += eventProduct; + purchasedItems.put(key, number); + } + } + if (product.getQuantity() < eventProduct + number) { + OutputView.PromotionNotApplied(product); + if (!InputView.yOrN()) { + number -= product.getPromotionBuy(); + purchasedItems.put(key, number); + } + } + } + store.deductInventory(product.getName(), number); + addItemToReceipt(receipt, product, number, product.applyPromotions(number)); + } + + private void addItemToReceipt(Receipt receipt, Product product, int quantity, int promotionAppliedQuantity) { + receipt.addItem(product, quantity, promotionAppliedQuantity); + } + + private void applyMembershipDiscount(Receipt receipt) { + OutputView.printMemberShipDiscount(); + if (InputView.yOrN()) { + receipt.applyMembershipDiscount(); + } + } + + private Product checkInventory(String productName, int quantity) { + if (productName == null || quantity <= 0) { + throw new IllegalArgumentException("[ERROR] ์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + Product product = store.findProductByName(productName) + .orElseThrow(() -> new IllegalArgumentException("[ERROR] ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.")); + if (product.getQuantity() < quantity) { + throw new IllegalArgumentException("[ERROR] ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + return product; + } +}
Java
์•„๋ž˜์ฒ˜๋Ÿผ ๋ฉ”์„œ๋“œ๋กœ ๋ถ„๋ฆฌํ•˜๋ฉด buyProduct() ๋ฉ”์„œ๋“œ ๋‚ด๋ถ€ ํ๋ฆ„์ด ๋” ๋ช…ํ™•ํžˆ ๋ณด์ผ ๊ฒƒ ๊ฐ™์•„์š”! ```suggestion askAdditionalPurchase(); ```
@@ -0,0 +1,92 @@ +package store.controller; + +import store.model.Product; +import store.model.Receipt; +import store.model.Store; +import store.view.InputView; +import store.view.OutputView; + +import java.util.Map; + +public class BuyController { + private final Store store; + + public BuyController(Store store) { + this.store = store; + } + + public void buyProduct() { + boolean continueShopping = true; + while (continueShopping) { + Receipt receipt = new Receipt(); + try { + Map<String, Integer> purchasedItems = InputView.purchasedItems(); + processPurchasedItems(receipt, purchasedItems); + applyMembershipDiscount(receipt); + receipt.print(); + OutputView.askForAdditionalPurchase(); + continueShopping = InputView.yOrN(); + if (continueShopping) OutputView.printInventoryInformation(store); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private void processPurchasedItems(Receipt receipt, Map<String, Integer> purchasedItems) { + for (String key : purchasedItems.keySet()) { + int number = purchasedItems.get(key); + Product product = checkInventory(key, number); + if (product.isPromotion()) { + processPromotionalItem(receipt, product, number, purchasedItems, key); + } else { + addItemToReceipt(receipt, product, number, 0); + } + } + } + + private void processPromotionalItem(Receipt receipt, Product product, int number, Map<String, Integer> purchasedItems, String key) { + int eventProduct = product.addPromotions(number); + if (eventProduct != 0) { + if (product.getQuantity() >= eventProduct + number) { + OutputView.printAddEventProduct(eventProduct, product.getName()); + if (InputView.yOrN()) { + number += eventProduct; + purchasedItems.put(key, number); + } + } + if (product.getQuantity() < eventProduct + number) { + OutputView.PromotionNotApplied(product); + if (!InputView.yOrN()) { + number -= product.getPromotionBuy(); + purchasedItems.put(key, number); + } + } + } + store.deductInventory(product.getName(), number); + addItemToReceipt(receipt, product, number, product.applyPromotions(number)); + } + + private void addItemToReceipt(Receipt receipt, Product product, int quantity, int promotionAppliedQuantity) { + receipt.addItem(product, quantity, promotionAppliedQuantity); + } + + private void applyMembershipDiscount(Receipt receipt) { + OutputView.printMemberShipDiscount(); + if (InputView.yOrN()) { + receipt.applyMembershipDiscount(); + } + } + + private Product checkInventory(String productName, int quantity) { + if (productName == null || quantity <= 0) { + throw new IllegalArgumentException("[ERROR] ์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + Product product = store.findProductByName(productName) + .orElseThrow(() -> new IllegalArgumentException("[ERROR] ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.")); + if (product.getQuantity() < quantity) { + throw new IllegalArgumentException("[ERROR] ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + return product; + } +}
Java
์—๋Ÿฌ๋ฉ”์‹œ์ง€๋Š” enum ํด๋ž˜์Šค๋กœ ๋ถ„๋ฆฌํ•ด์ฃผ์‹œ๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™๋„ค์š”:)
@@ -0,0 +1,76 @@ +package store.model; + +import camp.nextstep.edu.missionutils.DateTimes; + +import java.text.NumberFormat; +import java.time.LocalDateTime; + +public class Product { + private final String name; + private int price; + private int quantity; + private Promotion promotion; + + public Product(String name, int price, int quantity, Promotion promotion) { + this.name = name; + this.price = price; + this.quantity = quantity; + this.promotion = promotion; + } + + public String getName() { + return name; + } + + public int getQuantity() { + return quantity; + } + + public int getPrice() { + return price; + } + + public int addPromotions(int number) { + int buy = promotion.getBuy(); + int get = promotion.getGet(); + if (number % (buy + get) >= buy) { + return get - (number % (buy + get) - buy); + } + return 0; + } + + public int applyPromotions(int number) { + int buy = promotion.getBuy(); + int get = promotion.getGet(); + return (number / (get + buy)) * get; + } + + public boolean isPromotion() { + if (promotion == null) { + return false; + } + LocalDateTime time = DateTimes.now(); + if (time.isBefore(promotion.getStartDate()) || time.isAfter(promotion.getEndDate())) { + return false; + } + return true; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public int getPromotionBuy() { + return promotion.getBuy(); + } + + @Override + public String toString() { + NumberFormat formatter = NumberFormat.getInstance(); + StringBuilder result = new StringBuilder("- " + name + " " + formatter.format(price) + "์›"); + if (quantity > 0) result.append(" ").append(quantity).append("๊ฐœ"); + if (quantity == 0) result.append(" ์žฌ๊ณ  ์—†์Œ"); + if (promotion != null) result.append(" ").append(promotion.getName()); + return result.toString(); + } +}
Java
์•„๋ž˜์ฒ˜๋Ÿผ ์ถ•์•ฝํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”? ํ  ๋„ˆ๋ฌด ๊ธด๊ฐ€์š”?!๐Ÿค” ```suggestion return !time.isBefore(promotion.getStartDate()) && !time.isAfter(promotion.getEndDate()); ```
@@ -0,0 +1,81 @@ +package store.model; + +import java.util.ArrayList; +import java.util.List; + +public class Receipt { + private final List<ReceiptItem> items = new ArrayList<>(); + private int totalAmount = 0; + private int eventDiscount = 0; + private int membershipDiscount = 0; + + public void addItem(Product product, int quantity, int promotionAppliedQuantity) { + int itemTotal = product.getPrice() * quantity; + items.add(new ReceiptItem(product.getName(), product.getPrice(), quantity, promotionAppliedQuantity, itemTotal)); + totalAmount += itemTotal; + if (promotionAppliedQuantity > 0) { + eventDiscount += product.getPrice() * promotionAppliedQuantity; + } + } + + public void applyMembershipDiscount() { + int discountedTotal = totalAmount - eventDiscount; + membershipDiscount = (int) (discountedTotal * 0.3); + } + + public void print() { + System.out.println("============= W ํŽธ์˜์  =============="); + System.out.printf("%-12s %-8s %-10s\n", "์ƒํ’ˆ๋ช…", "์ˆ˜๋Ÿ‰", "๊ธˆ์•ก"); + for (ReceiptItem item : items) { + System.out.printf("%-12s %-8d %-10s\n", + item.getName(), + item.getQuantity(), + String.format("%,d", item.getItemTotal())); + } + for (ReceiptItem item : items) { + if (item.getPromotionAppliedQuantity() > 0) { + System.out.println("============= ์ฆ ์ • ==============="); + System.out.printf("%-12s %-8d\n", item.getName(), item.getPromotionAppliedQuantity()); + } + } + System.out.println("===================================="); + System.out.printf("%-12s %-8s %-10s\n", "์ด๊ตฌ๋งค์•ก", "", String.format("%,d", totalAmount)); + System.out.printf("%-12s %-8s %-10s\n", "ํ–‰์‚ฌํ• ์ธ", "", "-" + String.format("%,d", eventDiscount)); + System.out.printf("%-12s %-8s %-10s\n", "๋ฉค๋ฒ„์‹ญํ• ์ธ", "", "-" + String.format("%,d", membershipDiscount)); + int finalAmount = totalAmount - eventDiscount - membershipDiscount; + System.out.printf("%-12s %-8s %-10s\n", "๋‚ด์‹ค๋ˆ", "", String.format("%,d", finalAmount)); + System.out.println("===================================="); + } + + private static class ReceiptItem { + private final String name; + private final int price; + private final int quantity; + private final int promotionAppliedQuantity; + private final int itemTotal; + + public ReceiptItem(String name, int price, int quantity, int promotionAppliedQuantity, int itemTotal) { + this.name = name; + this.price = price; + this.quantity = quantity; + this.promotionAppliedQuantity = promotionAppliedQuantity; + this.itemTotal = itemTotal; + } + + public String getName() { + return name; + } + + public int getQuantity() { + return quantity; + } + + public int getPromotionAppliedQuantity() { + return promotionAppliedQuantity; + } + + public int getItemTotal() { + return itemTotal; + } + } +}
Java
Receipt ํด๋ž˜์Šค ๋‚ด์—์„œ ์ถœ๋ ฅ๋ฌธ์„ ์ž‘์„ฑํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”??
@@ -0,0 +1,77 @@ +package store.controller; + +import store.model.Product; +import store.model.Promotion; +import store.model.Store; +import store.view.OutputView; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.stream.Collectors; + +public class StoreController { + + public void run() { + Store store = new Store(); + BuyController buyController = new BuyController(store); + promotionListUp(store); + productListUp(store); + OutputView.printInventoryInformation(store); + buyController.buyProduct(); + } + + private void promotionListUp(Store store) { + String productsContent = readMarkdownFile("promotions.md"); + String[] lines = productsContent.split("\n"); + Arrays.stream(lines) + .map(this::parsePromotion) + .filter(Objects::nonNull) + .forEach(store::addPromotion); + } + + private Promotion parsePromotion(String line) { + String[] parts = line.split(","); + String name = parts[0]; + if (name.equals("name")) return null; + int buy = Integer.parseInt(parts[1]); + int get = Integer.parseInt(parts[2]); + String startDate = parts[3]; + String endDate = parts[4]; + return new Promotion(name, buy, get, startDate, endDate); + } + + private void productListUp(Store store) { + String productsContent = readMarkdownFile("products.md"); + String[] lines = productsContent.split("\n"); + Arrays.stream(lines) + .map(line -> parseProduct(line, store)) + .filter(Objects::nonNull) + .forEach(store::addProduct); + } + + private Product parseProduct(String line, Store store) { + String[] parts = line.split(","); + String name = parts[0]; + if (name.equals("name")) return null; + int price = Integer.parseInt(parts[1]); + int quantity = Integer.parseInt(parts[2]); + Promotion promotion = store.findPromotionByName(parts[3]); + return new Product(name, price, quantity, promotion); + } + + private String readMarkdownFile(String fileName) { + InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName); + if (inputStream == null) { + throw new IllegalArgumentException("[ERROR] ์žฌ๊ณ  ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { + return reader.lines().collect(Collectors.joining("\n")); + } catch (Exception e) { + return null; + } + } +}
Java
parse์— ๊ด€๋ จ๋œ ๊ธฐ๋Šฅ์„ controller ๋‚ด๋ถ€์—์„œ ๊ตฌํ˜„ํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ด์š”! controller์˜ ์—ญํ• ๋กœ์จ ์ ์ ˆํ•œ ๋ฐฉํ–ฅ์ผ๊นŒ์š”?!๐Ÿค”
@@ -0,0 +1,46 @@ +package store.model; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class Store { + private final List<Product> productList = new ArrayList<>(); + private final List<Promotion> promotionList = new ArrayList<>(); + + public void addProduct(Product product) { + productList.add(product); + } + + public List<Product> getProductList() { + return productList; + } + + public void addPromotion(Promotion promotion) { + promotionList.add(promotion); + } + + public List<Promotion> getPromotionList() { + return promotionList; + } + + public Promotion findPromotionByName(String name) { + return promotionList.stream() + .filter(promo -> promo.getName().equals(name)) + .findFirst() + .orElse(null); + } + + public void deductInventory(String productName, int quantity) { + productList.stream() + .filter(product -> product.getName().equals(productName)) + .findFirst() + .ifPresent(product -> product.setQuantity(product.getQuantity() - quantity)); + } + + public Optional<Product> findProductByName(String productName) { + return productList.stream() + .filter(product -> product.getName().equals(productName)) + .findFirst(); + } +}
Java
ํ•ด๋‹น ์ฝ”๋“œ ์ง๊ด€์ ์ด์–ด์„œ ๊ต‰์žฅํžˆ ์ข‹์€ ๊ฒƒ ๊ฐ™์•„์š”! ๋˜ํ•œ ifPresent()๋ฅผ ์‚ฌ์šฉํ•ด ๋‚ด๋ถ€์— ๊ฐ’์ด ์žˆ์„ ๋•Œ๋งŒ ๋™์ž‘ํ•ด NPE ๋ฐœ์ƒ์„ ์˜ˆ๋ฐฉํ•  ์ˆ˜ ์žˆ๊ฒ ๋„ค์š”:)
@@ -0,0 +1,77 @@ +package store.controller; + +import store.model.Product; +import store.model.Promotion; +import store.model.Store; +import store.view.OutputView; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.stream.Collectors; + +public class StoreController { + + public void run() { + Store store = new Store(); + BuyController buyController = new BuyController(store); + promotionListUp(store); + productListUp(store); + OutputView.printInventoryInformation(store); + buyController.buyProduct(); + } + + private void promotionListUp(Store store) { + String productsContent = readMarkdownFile("promotions.md"); + String[] lines = productsContent.split("\n"); + Arrays.stream(lines) + .map(this::parsePromotion) + .filter(Objects::nonNull) + .forEach(store::addPromotion); + } + + private Promotion parsePromotion(String line) { + String[] parts = line.split(","); + String name = parts[0]; + if (name.equals("name")) return null; + int buy = Integer.parseInt(parts[1]); + int get = Integer.parseInt(parts[2]); + String startDate = parts[3]; + String endDate = parts[4]; + return new Promotion(name, buy, get, startDate, endDate); + } + + private void productListUp(Store store) { + String productsContent = readMarkdownFile("products.md"); + String[] lines = productsContent.split("\n"); + Arrays.stream(lines) + .map(line -> parseProduct(line, store)) + .filter(Objects::nonNull) + .forEach(store::addProduct); + } + + private Product parseProduct(String line, Store store) { + String[] parts = line.split(","); + String name = parts[0]; + if (name.equals("name")) return null; + int price = Integer.parseInt(parts[1]); + int quantity = Integer.parseInt(parts[2]); + Promotion promotion = store.findPromotionByName(parts[3]); + return new Product(name, price, quantity, promotion); + } + + private String readMarkdownFile(String fileName) { + InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName); + if (inputStream == null) { + throw new IllegalArgumentException("[ERROR] ์žฌ๊ณ  ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { + return reader.lines().collect(Collectors.joining("\n")); + } catch (Exception e) { + return null; + } + } +}
Java
์ „์ฒด์ ์œผ๋กœ ๋ฆฌํŒฉํ† ๋ง์ด ๋ถ€์กฑํ•ด์„œ ์—ญํ•  ๋ถ„๋ฆฌ๊ฐ€ ์•ˆ๋œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ๐Ÿ˜ข ์ข‹์€ ์ง€์  ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,92 @@ +package store.controller; + +import store.model.Product; +import store.model.Receipt; +import store.model.Store; +import store.view.InputView; +import store.view.OutputView; + +import java.util.Map; + +public class BuyController { + private final Store store; + + public BuyController(Store store) { + this.store = store; + } + + public void buyProduct() { + boolean continueShopping = true; + while (continueShopping) { + Receipt receipt = new Receipt(); + try { + Map<String, Integer> purchasedItems = InputView.purchasedItems(); + processPurchasedItems(receipt, purchasedItems); + applyMembershipDiscount(receipt); + receipt.print(); + OutputView.askForAdditionalPurchase(); + continueShopping = InputView.yOrN(); + if (continueShopping) OutputView.printInventoryInformation(store); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private void processPurchasedItems(Receipt receipt, Map<String, Integer> purchasedItems) { + for (String key : purchasedItems.keySet()) { + int number = purchasedItems.get(key); + Product product = checkInventory(key, number); + if (product.isPromotion()) { + processPromotionalItem(receipt, product, number, purchasedItems, key); + } else { + addItemToReceipt(receipt, product, number, 0); + } + } + } + + private void processPromotionalItem(Receipt receipt, Product product, int number, Map<String, Integer> purchasedItems, String key) { + int eventProduct = product.addPromotions(number); + if (eventProduct != 0) { + if (product.getQuantity() >= eventProduct + number) { + OutputView.printAddEventProduct(eventProduct, product.getName()); + if (InputView.yOrN()) { + number += eventProduct; + purchasedItems.put(key, number); + } + } + if (product.getQuantity() < eventProduct + number) { + OutputView.PromotionNotApplied(product); + if (!InputView.yOrN()) { + number -= product.getPromotionBuy(); + purchasedItems.put(key, number); + } + } + } + store.deductInventory(product.getName(), number); + addItemToReceipt(receipt, product, number, product.applyPromotions(number)); + } + + private void addItemToReceipt(Receipt receipt, Product product, int quantity, int promotionAppliedQuantity) { + receipt.addItem(product, quantity, promotionAppliedQuantity); + } + + private void applyMembershipDiscount(Receipt receipt) { + OutputView.printMemberShipDiscount(); + if (InputView.yOrN()) { + receipt.applyMembershipDiscount(); + } + } + + private Product checkInventory(String productName, int quantity) { + if (productName == null || quantity <= 0) { + throw new IllegalArgumentException("[ERROR] ์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + Product product = store.findProductByName(productName) + .orElseThrow(() -> new IllegalArgumentException("[ERROR] ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.")); + if (product.getQuantity() < quantity) { + throw new IllegalArgumentException("[ERROR] ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + return product; + } +}
Java
controller์—์„œ view์™€ ๋„๋ฉ”์ธ ๊ฐ์ฒด์— ์ง์ ‘ ์ ‘๊ทผํ•˜์—ฌ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์„ ์ˆ˜ํ–‰ํ•˜๋‹ˆ view์™€ model ์‚ฌ์ด์˜ ๊ฒฐํ•ฉ๋„๊ฐ€ ์กฐ๊ธˆ ๋†’์€ ๊ฒƒ ๊ฐ™์•„์š”! service๋ฅผ ๋ถ„๋ฆฌํ•˜๊ฑฐ๋‚˜ model์—๊ฒŒ ๋” ๊ฐ•ํ•œ ์ฑ…์ž„์„ ๋ถ€์—ฌํ•˜๋Š” ๋ฐฉํ–ฅ์€ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋Š”์ง€ ๊ถ๊ธˆํ•ด์š”!
@@ -0,0 +1,77 @@ +package store.controller; + +import store.model.Product; +import store.model.Promotion; +import store.model.Store; +import store.view.OutputView; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.stream.Collectors; + +public class StoreController { + + public void run() { + Store store = new Store(); + BuyController buyController = new BuyController(store); + promotionListUp(store); + productListUp(store); + OutputView.printInventoryInformation(store); + buyController.buyProduct(); + } + + private void promotionListUp(Store store) { + String productsContent = readMarkdownFile("promotions.md"); + String[] lines = productsContent.split("\n"); + Arrays.stream(lines) + .map(this::parsePromotion) + .filter(Objects::nonNull) + .forEach(store::addPromotion); + } + + private Promotion parsePromotion(String line) { + String[] parts = line.split(","); + String name = parts[0]; + if (name.equals("name")) return null; + int buy = Integer.parseInt(parts[1]); + int get = Integer.parseInt(parts[2]); + String startDate = parts[3]; + String endDate = parts[4]; + return new Promotion(name, buy, get, startDate, endDate); + } + + private void productListUp(Store store) { + String productsContent = readMarkdownFile("products.md"); + String[] lines = productsContent.split("\n"); + Arrays.stream(lines) + .map(line -> parseProduct(line, store)) + .filter(Objects::nonNull) + .forEach(store::addProduct); + } + + private Product parseProduct(String line, Store store) { + String[] parts = line.split(","); + String name = parts[0]; + if (name.equals("name")) return null; + int price = Integer.parseInt(parts[1]); + int quantity = Integer.parseInt(parts[2]); + Promotion promotion = store.findPromotionByName(parts[3]); + return new Product(name, price, quantity, promotion); + } + + private String readMarkdownFile(String fileName) { + InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName); + if (inputStream == null) { + throw new IllegalArgumentException("[ERROR] ์žฌ๊ณ  ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { + return reader.lines().collect(Collectors.joining("\n")); + } catch (Exception e) { + return null; + } + } +}
Java
๋งค์ง ๋„˜๋ฒ„๋“ค์€ ์ƒ์ˆ˜ํ™”ํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,42 @@ +package store.model; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +public class Promotion { + private final String name; + private final int buy; + private final int get; + private final LocalDateTime startDate; + private final LocalDateTime endDate; + + private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm"); + + public Promotion(String name, int buy, int get, String startDate, String endDate) { + this.name = name; + this.buy = buy; + this.get = get; + this.startDate = LocalDateTime.parse(startDate + "T00:00", formatter); + this.endDate = LocalDateTime.parse(endDate + "T23:59", formatter); + } + + public String getName() { + return name; + } + + public int getBuy() { + return buy; + } + + public int getGet() { + return get; + } + + public LocalDateTime getStartDate() { + return startDate; + } + + public LocalDateTime getEndDate() { + return endDate; + } +}
Java
๋‚ ์งœ ํ˜•์‹ ์ƒ์ˆ˜ํ™” ์ข‹๋„ค์š”! ๐Ÿ‘
@@ -0,0 +1,42 @@ +package store.model; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +public class Promotion { + private final String name; + private final int buy; + private final int get; + private final LocalDateTime startDate; + private final LocalDateTime endDate; + + private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm"); + + public Promotion(String name, int buy, int get, String startDate, String endDate) { + this.name = name; + this.buy = buy; + this.get = get; + this.startDate = LocalDateTime.parse(startDate + "T00:00", formatter); + this.endDate = LocalDateTime.parse(endDate + "T23:59", formatter); + } + + public String getName() { + return name; + } + + public int getBuy() { + return buy; + } + + public int getGet() { + return get; + } + + public LocalDateTime getStartDate() { + return startDate; + } + + public LocalDateTime getEndDate() { + return endDate; + } +}
Java
์ƒ์ˆ˜ํ™” ๋“ฑ์„ ํ†ตํ•ด ์กฐ๊ธˆ ๋” ์ง๊ด€์ ์œผ๋กœ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,81 @@ +package store.model; + +import java.util.ArrayList; +import java.util.List; + +public class Receipt { + private final List<ReceiptItem> items = new ArrayList<>(); + private int totalAmount = 0; + private int eventDiscount = 0; + private int membershipDiscount = 0; + + public void addItem(Product product, int quantity, int promotionAppliedQuantity) { + int itemTotal = product.getPrice() * quantity; + items.add(new ReceiptItem(product.getName(), product.getPrice(), quantity, promotionAppliedQuantity, itemTotal)); + totalAmount += itemTotal; + if (promotionAppliedQuantity > 0) { + eventDiscount += product.getPrice() * promotionAppliedQuantity; + } + } + + public void applyMembershipDiscount() { + int discountedTotal = totalAmount - eventDiscount; + membershipDiscount = (int) (discountedTotal * 0.3); + } + + public void print() { + System.out.println("============= W ํŽธ์˜์  =============="); + System.out.printf("%-12s %-8s %-10s\n", "์ƒํ’ˆ๋ช…", "์ˆ˜๋Ÿ‰", "๊ธˆ์•ก"); + for (ReceiptItem item : items) { + System.out.printf("%-12s %-8d %-10s\n", + item.getName(), + item.getQuantity(), + String.format("%,d", item.getItemTotal())); + } + for (ReceiptItem item : items) { + if (item.getPromotionAppliedQuantity() > 0) { + System.out.println("============= ์ฆ ์ • ==============="); + System.out.printf("%-12s %-8d\n", item.getName(), item.getPromotionAppliedQuantity()); + } + } + System.out.println("===================================="); + System.out.printf("%-12s %-8s %-10s\n", "์ด๊ตฌ๋งค์•ก", "", String.format("%,d", totalAmount)); + System.out.printf("%-12s %-8s %-10s\n", "ํ–‰์‚ฌํ• ์ธ", "", "-" + String.format("%,d", eventDiscount)); + System.out.printf("%-12s %-8s %-10s\n", "๋ฉค๋ฒ„์‹ญํ• ์ธ", "", "-" + String.format("%,d", membershipDiscount)); + int finalAmount = totalAmount - eventDiscount - membershipDiscount; + System.out.printf("%-12s %-8s %-10s\n", "๋‚ด์‹ค๋ˆ", "", String.format("%,d", finalAmount)); + System.out.println("===================================="); + } + + private static class ReceiptItem { + private final String name; + private final int price; + private final int quantity; + private final int promotionAppliedQuantity; + private final int itemTotal; + + public ReceiptItem(String name, int price, int quantity, int promotionAppliedQuantity, int itemTotal) { + this.name = name; + this.price = price; + this.quantity = quantity; + this.promotionAppliedQuantity = promotionAppliedQuantity; + this.itemTotal = itemTotal; + } + + public String getName() { + return name; + } + + public int getQuantity() { + return quantity; + } + + public int getPromotionAppliedQuantity() { + return promotionAppliedQuantity; + } + + public int getItemTotal() { + return itemTotal; + } + } +}
Java
0.3์ด ์–ด๋–ค ์˜๋ฏธ์ธ๊ฐ€์š”?!
@@ -0,0 +1,81 @@ +package store.model; + +import java.util.ArrayList; +import java.util.List; + +public class Receipt { + private final List<ReceiptItem> items = new ArrayList<>(); + private int totalAmount = 0; + private int eventDiscount = 0; + private int membershipDiscount = 0; + + public void addItem(Product product, int quantity, int promotionAppliedQuantity) { + int itemTotal = product.getPrice() * quantity; + items.add(new ReceiptItem(product.getName(), product.getPrice(), quantity, promotionAppliedQuantity, itemTotal)); + totalAmount += itemTotal; + if (promotionAppliedQuantity > 0) { + eventDiscount += product.getPrice() * promotionAppliedQuantity; + } + } + + public void applyMembershipDiscount() { + int discountedTotal = totalAmount - eventDiscount; + membershipDiscount = (int) (discountedTotal * 0.3); + } + + public void print() { + System.out.println("============= W ํŽธ์˜์  =============="); + System.out.printf("%-12s %-8s %-10s\n", "์ƒํ’ˆ๋ช…", "์ˆ˜๋Ÿ‰", "๊ธˆ์•ก"); + for (ReceiptItem item : items) { + System.out.printf("%-12s %-8d %-10s\n", + item.getName(), + item.getQuantity(), + String.format("%,d", item.getItemTotal())); + } + for (ReceiptItem item : items) { + if (item.getPromotionAppliedQuantity() > 0) { + System.out.println("============= ์ฆ ์ • ==============="); + System.out.printf("%-12s %-8d\n", item.getName(), item.getPromotionAppliedQuantity()); + } + } + System.out.println("===================================="); + System.out.printf("%-12s %-8s %-10s\n", "์ด๊ตฌ๋งค์•ก", "", String.format("%,d", totalAmount)); + System.out.printf("%-12s %-8s %-10s\n", "ํ–‰์‚ฌํ• ์ธ", "", "-" + String.format("%,d", eventDiscount)); + System.out.printf("%-12s %-8s %-10s\n", "๋ฉค๋ฒ„์‹ญํ• ์ธ", "", "-" + String.format("%,d", membershipDiscount)); + int finalAmount = totalAmount - eventDiscount - membershipDiscount; + System.out.printf("%-12s %-8s %-10s\n", "๋‚ด์‹ค๋ˆ", "", String.format("%,d", finalAmount)); + System.out.println("===================================="); + } + + private static class ReceiptItem { + private final String name; + private final int price; + private final int quantity; + private final int promotionAppliedQuantity; + private final int itemTotal; + + public ReceiptItem(String name, int price, int quantity, int promotionAppliedQuantity, int itemTotal) { + this.name = name; + this.price = price; + this.quantity = quantity; + this.promotionAppliedQuantity = promotionAppliedQuantity; + this.itemTotal = itemTotal; + } + + public String getName() { + return name; + } + + public int getQuantity() { + return quantity; + } + + public int getPromotionAppliedQuantity() { + return promotionAppliedQuantity; + } + + public int getItemTotal() { + return itemTotal; + } + } +}
Java
์ €๋„ ๊ถ๊ธˆํ•ด์š”!
@@ -0,0 +1,46 @@ +package store.model; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class Store { + private final List<Product> productList = new ArrayList<>(); + private final List<Promotion> promotionList = new ArrayList<>(); + + public void addProduct(Product product) { + productList.add(product); + } + + public List<Product> getProductList() { + return productList; + } + + public void addPromotion(Promotion promotion) { + promotionList.add(promotion); + } + + public List<Promotion> getPromotionList() { + return promotionList; + } + + public Promotion findPromotionByName(String name) { + return promotionList.stream() + .filter(promo -> promo.getName().equals(name)) + .findFirst() + .orElse(null); + } + + public void deductInventory(String productName, int quantity) { + productList.stream() + .filter(product -> product.getName().equals(productName)) + .findFirst() + .ifPresent(product -> product.setQuantity(product.getQuantity() - quantity)); + } + + public Optional<Product> findProductByName(String productName) { + return productList.stream() + .filter(product -> product.getName().equals(productName)) + .findFirst(); + } +}
Java
stream์„ ์ž˜ ํ™œ์šฉํ•˜์‹œ๋Š” ๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ‘
@@ -0,0 +1,27 @@ +package store.view; + +import camp.nextstep.edu.missionutils.Console; + +import java.util.Map; + +public class InputView { + public static Map<String, Integer> purchasedItems() { + while (true) { + try { + String input = Console.readLine(); + InputParser.validateInputFormat(input); + return InputParser.parseItems(input); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + public static boolean yOrN() { + String input = Console.readLine(); + if (input.equals("Y")) return true; + if (input.equals("N")) return false; + System.out.println("[ERROR] ์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + return yOrN(); + } +}
Java
์กฐ๊ฑด๋ฌธ์€ ์ค‘๊ด„ํ˜ธ๋กœ ๊ฐ์‹ธ์ฃผ์„ธ์š”!
@@ -0,0 +1,34 @@ +package store.view; + +import store.model.Product; +import store.model.Store; + +import java.util.List; + +public class OutputView { + public static void printInventoryInformation(Store store) { + System.out.println("์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค."); + System.out.println("ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."); + System.out.println(); + List<Product> productList = store.getProductList(); + productList.forEach(System.out::println); + System.out.println(); + System.out.println("๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1]"); + } + + public static void printAddEventProduct(int number, String productName) { + System.out.println("ํ˜„์žฌ " + productName + "์€(๋Š”) " + number + "๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"); + } + + public static void printMemberShipDiscount() { + System.out.println("๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"); + } + + public static void askForAdditionalPurchase() { + System.out.println("๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"); + } + + public static void PromotionNotApplied(Product product) { + System.out.println("ํ˜„์žฌ " + product.getName() + " " + product.getPromotionBuy() + "๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?"); + } +}
Java
์—ฌ๊ธฐ์„œ๋Š” String.format์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์€ ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ ๊ฐ€์š”??
@@ -0,0 +1,34 @@ +package store.view; + +import store.model.Product; +import store.model.Store; + +import java.util.List; + +public class OutputView { + public static void printInventoryInformation(Store store) { + System.out.println("์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค."); + System.out.println("ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."); + System.out.println(); + List<Product> productList = store.getProductList(); + productList.forEach(System.out::println); + System.out.println(); + System.out.println("๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1]"); + } + + public static void printAddEventProduct(int number, String productName) { + System.out.println("ํ˜„์žฌ " + productName + "์€(๋Š”) " + number + "๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"); + } + + public static void printMemberShipDiscount() { + System.out.println("๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"); + } + + public static void askForAdditionalPurchase() { + System.out.println("๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"); + } + + public static void PromotionNotApplied(Product product) { + System.out.println("ํ˜„์žฌ " + product.getName() + " " + product.getPromotionBuy() + "๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?"); + } +}
Java
์—†์Šต๋‹ˆ๋‹ค... ๊ณ ๋ฏผ์„ ๋งŽ์ด ํ•˜์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ๐Ÿ˜ข
@@ -0,0 +1,92 @@ +package store.controller; + +import store.model.Product; +import store.model.Receipt; +import store.model.Store; +import store.view.InputView; +import store.view.OutputView; + +import java.util.Map; + +public class BuyController { + private final Store store; + + public BuyController(Store store) { + this.store = store; + } + + public void buyProduct() { + boolean continueShopping = true; + while (continueShopping) { + Receipt receipt = new Receipt(); + try { + Map<String, Integer> purchasedItems = InputView.purchasedItems(); + processPurchasedItems(receipt, purchasedItems); + applyMembershipDiscount(receipt); + receipt.print(); + OutputView.askForAdditionalPurchase(); + continueShopping = InputView.yOrN(); + if (continueShopping) OutputView.printInventoryInformation(store); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private void processPurchasedItems(Receipt receipt, Map<String, Integer> purchasedItems) { + for (String key : purchasedItems.keySet()) { + int number = purchasedItems.get(key); + Product product = checkInventory(key, number); + if (product.isPromotion()) { + processPromotionalItem(receipt, product, number, purchasedItems, key); + } else { + addItemToReceipt(receipt, product, number, 0); + } + } + } + + private void processPromotionalItem(Receipt receipt, Product product, int number, Map<String, Integer> purchasedItems, String key) { + int eventProduct = product.addPromotions(number); + if (eventProduct != 0) { + if (product.getQuantity() >= eventProduct + number) { + OutputView.printAddEventProduct(eventProduct, product.getName()); + if (InputView.yOrN()) { + number += eventProduct; + purchasedItems.put(key, number); + } + } + if (product.getQuantity() < eventProduct + number) { + OutputView.PromotionNotApplied(product); + if (!InputView.yOrN()) { + number -= product.getPromotionBuy(); + purchasedItems.put(key, number); + } + } + } + store.deductInventory(product.getName(), number); + addItemToReceipt(receipt, product, number, product.applyPromotions(number)); + } + + private void addItemToReceipt(Receipt receipt, Product product, int quantity, int promotionAppliedQuantity) { + receipt.addItem(product, quantity, promotionAppliedQuantity); + } + + private void applyMembershipDiscount(Receipt receipt) { + OutputView.printMemberShipDiscount(); + if (InputView.yOrN()) { + receipt.applyMembershipDiscount(); + } + } + + private Product checkInventory(String productName, int quantity) { + if (productName == null || quantity <= 0) { + throw new IllegalArgumentException("[ERROR] ์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + Product product = store.findProductByName(productName) + .orElseThrow(() -> new IllegalArgumentException("[ERROR] ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.")); + if (product.getQuantity() < quantity) { + throw new IllegalArgumentException("[ERROR] ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + return product; + } +}
Java
model ์—๊ฒŒ ๊ฐ•ํ•œ ์ฑ…์ž„์„ ๋ถ€์—ฌํ•˜๋Š” ๋ฐฉํ–ฅ์„ ์ง€ํ–ฅํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋ฒˆ ์ฝ”๋“œ๋Š” ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ€ ๋Š˜์–ด๋‚˜๋Š”๊ฒŒ ๋„ˆ๋ฌด ๋ถ€๋‹ด์Šค๋Ÿฌ์›Œ์„œ ๋ฆฌํŒฉํ† ๋ง์ด ๋งŽ์ด ๋ถ€์กฑํ–ˆ๋˜ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ๐Ÿ˜ข
@@ -0,0 +1,77 @@ +package store.controller; + +import store.model.Product; +import store.model.Promotion; +import store.model.Store; +import store.view.OutputView; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.stream.Collectors; + +public class StoreController { + + public void run() { + Store store = new Store(); + BuyController buyController = new BuyController(store); + promotionListUp(store); + productListUp(store); + OutputView.printInventoryInformation(store); + buyController.buyProduct(); + } + + private void promotionListUp(Store store) { + String productsContent = readMarkdownFile("promotions.md"); + String[] lines = productsContent.split("\n"); + Arrays.stream(lines) + .map(this::parsePromotion) + .filter(Objects::nonNull) + .forEach(store::addPromotion); + } + + private Promotion parsePromotion(String line) { + String[] parts = line.split(","); + String name = parts[0]; + if (name.equals("name")) return null; + int buy = Integer.parseInt(parts[1]); + int get = Integer.parseInt(parts[2]); + String startDate = parts[3]; + String endDate = parts[4]; + return new Promotion(name, buy, get, startDate, endDate); + } + + private void productListUp(Store store) { + String productsContent = readMarkdownFile("products.md"); + String[] lines = productsContent.split("\n"); + Arrays.stream(lines) + .map(line -> parseProduct(line, store)) + .filter(Objects::nonNull) + .forEach(store::addProduct); + } + + private Product parseProduct(String line, Store store) { + String[] parts = line.split(","); + String name = parts[0]; + if (name.equals("name")) return null; + int price = Integer.parseInt(parts[1]); + int quantity = Integer.parseInt(parts[2]); + Promotion promotion = store.findPromotionByName(parts[3]); + return new Product(name, price, quantity, promotion); + } + + private String readMarkdownFile(String fileName) { + InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName); + if (inputStream == null) { + throw new IllegalArgumentException("[ERROR] ์žฌ๊ณ  ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { + return reader.lines().collect(Collectors.joining("\n")); + } catch (Exception e) { + return null; + } + } +}
Java
if๋ฌธ์„ ์ค‘๊ฐ€๋กœ ์—†์ด ๋ฐ”๋กœ return ํ•˜์…จ๋Š”๋ฐ ์ด๊ฒŒ ๊ฐ€๋…์„ฑ์ด ๋” ์ข‹์•„์„œ ์ด๋ ‡๊ฒŒ ํ•˜์‹ ๊ฑด๊ฐ€์š”?
@@ -0,0 +1,77 @@ +package store.controller; + +import store.model.Product; +import store.model.Promotion; +import store.model.Store; +import store.view.OutputView; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.stream.Collectors; + +public class StoreController { + + public void run() { + Store store = new Store(); + BuyController buyController = new BuyController(store); + promotionListUp(store); + productListUp(store); + OutputView.printInventoryInformation(store); + buyController.buyProduct(); + } + + private void promotionListUp(Store store) { + String productsContent = readMarkdownFile("promotions.md"); + String[] lines = productsContent.split("\n"); + Arrays.stream(lines) + .map(this::parsePromotion) + .filter(Objects::nonNull) + .forEach(store::addPromotion); + } + + private Promotion parsePromotion(String line) { + String[] parts = line.split(","); + String name = parts[0]; + if (name.equals("name")) return null; + int buy = Integer.parseInt(parts[1]); + int get = Integer.parseInt(parts[2]); + String startDate = parts[3]; + String endDate = parts[4]; + return new Promotion(name, buy, get, startDate, endDate); + } + + private void productListUp(Store store) { + String productsContent = readMarkdownFile("products.md"); + String[] lines = productsContent.split("\n"); + Arrays.stream(lines) + .map(line -> parseProduct(line, store)) + .filter(Objects::nonNull) + .forEach(store::addProduct); + } + + private Product parseProduct(String line, Store store) { + String[] parts = line.split(","); + String name = parts[0]; + if (name.equals("name")) return null; + int price = Integer.parseInt(parts[1]); + int quantity = Integer.parseInt(parts[2]); + Promotion promotion = store.findPromotionByName(parts[3]); + return new Product(name, price, quantity, promotion); + } + + private String readMarkdownFile(String fileName) { + InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName); + if (inputStream == null) { + throw new IllegalArgumentException("[ERROR] ์žฌ๊ณ  ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { + return reader.lines().collect(Collectors.joining("\n")); + } catch (Exception e) { + return null; + } + } +}
Java
๊ฐ€๋กœ ์•ˆ์— ๊ฐ€๋กœ ์•ˆ์— ๊ฐ€๋กœ ๊ฐ€ ์žˆ๋Š”๊ฒŒ ๊ฐ€๋…์„ฑ์ด ๋–จ์–ด์ง€๋Š”๊ฑฐ ๊ฐ™์•„์š” ๋‚˜์ค‘์— ์ด ๋ถ€๋ถ„๋„ ๋ฆฌํŒฉํ„ฐ๋ง ํ•˜๋ฉด ์ข‹์„๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,46 @@ +package store.model; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class Store { + private final List<Product> productList = new ArrayList<>(); + private final List<Promotion> promotionList = new ArrayList<>(); + + public void addProduct(Product product) { + productList.add(product); + } + + public List<Product> getProductList() { + return productList; + } + + public void addPromotion(Promotion promotion) { + promotionList.add(promotion); + } + + public List<Promotion> getPromotionList() { + return promotionList; + } + + public Promotion findPromotionByName(String name) { + return promotionList.stream() + .filter(promo -> promo.getName().equals(name)) + .findFirst() + .orElse(null); + } + + public void deductInventory(String productName, int quantity) { + productList.stream() + .filter(product -> product.getName().equals(productName)) + .findFirst() + .ifPresent(product -> product.setQuantity(product.getQuantity() - quantity)); + } + + public Optional<Product> findProductByName(String productName) { + return productList.stream() + .filter(product -> product.getName().equals(productName)) + .findFirst(); + } +}
Java
getPromotionLsit()๋Š” ์‚ฌ์šฉ๋˜์ง€ ์•Š๋Š” ๊ฑธ๋กœ ๋ณด์—ฌ์š”! ๋ฆฌํŒฉํ„ฐ๋ง ์‹œ๊ฐ„์ด ๋ถ€์กฑํ•˜์…”์„œ ๋‚จ๊ฒจ๋‘์‹ ๊ฑฐ ๊ฐ™์€๋ฐ ํ˜น์‹œ ์ด ๋ฉ”์„œ๋“œ๋ฅผ ๋‚จ๊ฒจ๋‘์‹  ๋‹ค๋ฅธ ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,81 @@ +package store.model; + +import java.util.ArrayList; +import java.util.List; + +public class Receipt { + private final List<ReceiptItem> items = new ArrayList<>(); + private int totalAmount = 0; + private int eventDiscount = 0; + private int membershipDiscount = 0; + + public void addItem(Product product, int quantity, int promotionAppliedQuantity) { + int itemTotal = product.getPrice() * quantity; + items.add(new ReceiptItem(product.getName(), product.getPrice(), quantity, promotionAppliedQuantity, itemTotal)); + totalAmount += itemTotal; + if (promotionAppliedQuantity > 0) { + eventDiscount += product.getPrice() * promotionAppliedQuantity; + } + } + + public void applyMembershipDiscount() { + int discountedTotal = totalAmount - eventDiscount; + membershipDiscount = (int) (discountedTotal * 0.3); + } + + public void print() { + System.out.println("============= W ํŽธ์˜์  =============="); + System.out.printf("%-12s %-8s %-10s\n", "์ƒํ’ˆ๋ช…", "์ˆ˜๋Ÿ‰", "๊ธˆ์•ก"); + for (ReceiptItem item : items) { + System.out.printf("%-12s %-8d %-10s\n", + item.getName(), + item.getQuantity(), + String.format("%,d", item.getItemTotal())); + } + for (ReceiptItem item : items) { + if (item.getPromotionAppliedQuantity() > 0) { + System.out.println("============= ์ฆ ์ • ==============="); + System.out.printf("%-12s %-8d\n", item.getName(), item.getPromotionAppliedQuantity()); + } + } + System.out.println("===================================="); + System.out.printf("%-12s %-8s %-10s\n", "์ด๊ตฌ๋งค์•ก", "", String.format("%,d", totalAmount)); + System.out.printf("%-12s %-8s %-10s\n", "ํ–‰์‚ฌํ• ์ธ", "", "-" + String.format("%,d", eventDiscount)); + System.out.printf("%-12s %-8s %-10s\n", "๋ฉค๋ฒ„์‹ญํ• ์ธ", "", "-" + String.format("%,d", membershipDiscount)); + int finalAmount = totalAmount - eventDiscount - membershipDiscount; + System.out.printf("%-12s %-8s %-10s\n", "๋‚ด์‹ค๋ˆ", "", String.format("%,d", finalAmount)); + System.out.println("===================================="); + } + + private static class ReceiptItem { + private final String name; + private final int price; + private final int quantity; + private final int promotionAppliedQuantity; + private final int itemTotal; + + public ReceiptItem(String name, int price, int quantity, int promotionAppliedQuantity, int itemTotal) { + this.name = name; + this.price = price; + this.quantity = quantity; + this.promotionAppliedQuantity = promotionAppliedQuantity; + this.itemTotal = itemTotal; + } + + public String getName() { + return name; + } + + public int getQuantity() { + return quantity; + } + + public int getPromotionAppliedQuantity() { + return promotionAppliedQuantity; + } + + public int getItemTotal() { + return itemTotal; + } + } +}
Java
ReceipItem ํด๋ž˜์Šค์— ๋‚ด๋ถ€ ํ•„๋“œ ์ค‘ price๋Š” ์‚ฌ์šฉ๋˜์ง€์•Š๋Š” ๊ฑธ๋กœ ๋ณด์ด๋Š”๋ฐ ํ˜น์‹œ ์–ด๋–ค ์˜๋„๊ฐ€ ์žˆ๋‚˜์š”?
@@ -0,0 +1,76 @@ +package store.model; + +import camp.nextstep.edu.missionutils.DateTimes; + +import java.text.NumberFormat; +import java.time.LocalDateTime; + +public class Product { + private final String name; + private int price; + private int quantity; + private Promotion promotion; + + public Product(String name, int price, int quantity, Promotion promotion) { + this.name = name; + this.price = price; + this.quantity = quantity; + this.promotion = promotion; + } + + public String getName() { + return name; + } + + public int getQuantity() { + return quantity; + } + + public int getPrice() { + return price; + } + + public int addPromotions(int number) { + int buy = promotion.getBuy(); + int get = promotion.getGet(); + if (number % (buy + get) >= buy) { + return get - (number % (buy + get) - buy); + } + return 0; + } + + public int applyPromotions(int number) { + int buy = promotion.getBuy(); + int get = promotion.getGet(); + return (number / (get + buy)) * get; + } + + public boolean isPromotion() { + if (promotion == null) { + return false; + } + LocalDateTime time = DateTimes.now(); + if (time.isBefore(promotion.getStartDate()) || time.isAfter(promotion.getEndDate())) { + return false; + } + return true; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public int getPromotionBuy() { + return promotion.getBuy(); + } + + @Override + public String toString() { + NumberFormat formatter = NumberFormat.getInstance(); + StringBuilder result = new StringBuilder("- " + name + " " + formatter.format(price) + "์›"); + if (quantity > 0) result.append(" ").append(quantity).append("๊ฐœ"); + if (quantity == 0) result.append(" ์žฌ๊ณ  ์—†์Œ"); + if (promotion != null) result.append(" ").append(promotion.getName()); + return result.toString(); + } +}
Java
ํ•„๋“œ ๊ฐ’ ์ค‘ quantitiy๋Š” ์•„๋ž˜ set๋ฉ”์„œ๋“œ๊ฐ€ ์žˆ์–ด์„œ ๊ฐ€๋ณ€์œผ๋กœ ํ•˜๋Š”๊ฑด ์ดํ•ดํ•˜๊ฒ ๋Š”๋ฐ price, promotion์€ final๋กœ ๋ถˆ๋ณ€์œผ๋กœ ๋งŒ๋“œ๋Š”๊ฒŒ ์ข‹์€๊ฑฐ ๊ฐ™๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ญ๋‹ˆ๋‹ค. ํ˜น์‹œ ๊ฐ€๋ณ€์œผ๋กœ ํ•˜์‹  ์–ด๋–ค ์˜๋„๊ฐ€ ์žˆ์œผ์‹ ๊ฐ€์š”?
@@ -0,0 +1,77 @@ +package store.controller; + +import store.model.Product; +import store.model.Promotion; +import store.model.Store; +import store.view.OutputView; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.stream.Collectors; + +public class StoreController { + + public void run() { + Store store = new Store(); + BuyController buyController = new BuyController(store); + promotionListUp(store); + productListUp(store); + OutputView.printInventoryInformation(store); + buyController.buyProduct(); + } + + private void promotionListUp(Store store) { + String productsContent = readMarkdownFile("promotions.md"); + String[] lines = productsContent.split("\n"); + Arrays.stream(lines) + .map(this::parsePromotion) + .filter(Objects::nonNull) + .forEach(store::addPromotion); + } + + private Promotion parsePromotion(String line) { + String[] parts = line.split(","); + String name = parts[0]; + if (name.equals("name")) return null; + int buy = Integer.parseInt(parts[1]); + int get = Integer.parseInt(parts[2]); + String startDate = parts[3]; + String endDate = parts[4]; + return new Promotion(name, buy, get, startDate, endDate); + } + + private void productListUp(Store store) { + String productsContent = readMarkdownFile("products.md"); + String[] lines = productsContent.split("\n"); + Arrays.stream(lines) + .map(line -> parseProduct(line, store)) + .filter(Objects::nonNull) + .forEach(store::addProduct); + } + + private Product parseProduct(String line, Store store) { + String[] parts = line.split(","); + String name = parts[0]; + if (name.equals("name")) return null; + int price = Integer.parseInt(parts[1]); + int quantity = Integer.parseInt(parts[2]); + Promotion promotion = store.findPromotionByName(parts[3]); + return new Product(name, price, quantity, promotion); + } + + private String readMarkdownFile(String fileName) { + InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName); + if (inputStream == null) { + throw new IllegalArgumentException("[ERROR] ์žฌ๊ณ  ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { + return reader.lines().collect(Collectors.joining("\n")); + } catch (Exception e) { + return null; + } + } +}
Java
์ฝ”๋“œ ์ž‘์„ฑํ•  ๋•Œ๋Š” ๊ฐ„๊ฒฐํ•ด ๋ณด์˜€๋Š”๋ฐ ๋ง‰์ƒ ๋ฆฌ๋ทฐ ๋ฐ›์œผ๋‹ˆ๊นŒ ์ค‘๊ด„ํ˜ธ์ž‘์„ฑํ•  ๋•Œ๋Š” ๊ฐ„๊ฒฐํ•ด ๋ณด์˜€๋Š”๋ฐ ๋ง‰์ƒ ๋ฆฌ๋ทฐ ๋ฐ›์œผ๋‹ˆ๊นŒ ์ค‘๊ด„ํ˜ธ๋ฅผ ๋„ฃ๋Š”๊ฒŒ ๋” ์ข‹์•„๋ณด์ด๋„ค์š” ๐Ÿ˜ข
@@ -0,0 +1,46 @@ +package store.model; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class Store { + private final List<Product> productList = new ArrayList<>(); + private final List<Promotion> promotionList = new ArrayList<>(); + + public void addProduct(Product product) { + productList.add(product); + } + + public List<Product> getProductList() { + return productList; + } + + public void addPromotion(Promotion promotion) { + promotionList.add(promotion); + } + + public List<Promotion> getPromotionList() { + return promotionList; + } + + public Promotion findPromotionByName(String name) { + return promotionList.stream() + .filter(promo -> promo.getName().equals(name)) + .findFirst() + .orElse(null); + } + + public void deductInventory(String productName, int quantity) { + productList.stream() + .filter(product -> product.getName().equals(productName)) + .findFirst() + .ifPresent(product -> product.setQuantity(product.getQuantity() - quantity)); + } + + public Optional<Product> findProductByName(String productName) { + return productList.stream() + .filter(product -> product.getName().equals(productName)) + .findFirst(); + } +}
Java
๋ฆฌํŒฉํ† ๋ง์ด ๋ถ€์กฑํ–ˆ๋˜ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ฐœ์ธ์ ์œผ๋กœ ๊ธฐ๋ณธ์ ์ธ ๊ฒŒํ„ฐ๋Š” ๋‚จ๊ฒจ๋‘ฌ๋„ ํฌ๊ฒŒ ์ƒ๊ด€ ์—†๋‹ค๊ณ  ์ƒ๊ฐ์€ ํ•ฉ๋‹ˆ๋‹ค ๐Ÿค”
@@ -0,0 +1,76 @@ +package store.model; + +import camp.nextstep.edu.missionutils.DateTimes; + +import java.text.NumberFormat; +import java.time.LocalDateTime; + +public class Product { + private final String name; + private int price; + private int quantity; + private Promotion promotion; + + public Product(String name, int price, int quantity, Promotion promotion) { + this.name = name; + this.price = price; + this.quantity = quantity; + this.promotion = promotion; + } + + public String getName() { + return name; + } + + public int getQuantity() { + return quantity; + } + + public int getPrice() { + return price; + } + + public int addPromotions(int number) { + int buy = promotion.getBuy(); + int get = promotion.getGet(); + if (number % (buy + get) >= buy) { + return get - (number % (buy + get) - buy); + } + return 0; + } + + public int applyPromotions(int number) { + int buy = promotion.getBuy(); + int get = promotion.getGet(); + return (number / (get + buy)) * get; + } + + public boolean isPromotion() { + if (promotion == null) { + return false; + } + LocalDateTime time = DateTimes.now(); + if (time.isBefore(promotion.getStartDate()) || time.isAfter(promotion.getEndDate())) { + return false; + } + return true; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public int getPromotionBuy() { + return promotion.getBuy(); + } + + @Override + public String toString() { + NumberFormat formatter = NumberFormat.getInstance(); + StringBuilder result = new StringBuilder("- " + name + " " + formatter.format(price) + "์›"); + if (quantity > 0) result.append(" ").append(quantity).append("๊ฐœ"); + if (quantity == 0) result.append(" ์žฌ๊ณ  ์—†์Œ"); + if (promotion != null) result.append(" ").append(promotion.getName()); + return result.toString(); + } +}
Java
์ƒํ’ˆ์„ ๊ตฌ๋ถ„ํ•˜๋Š” ์œ ์ผํ•œ ๋ฐฉ๋ฒ•์ด ์ƒํ’ˆ์ด๋ฆ„์ด์—ฌ์„œ name ๋นผ๊ณ ๋Š” ๋ฐ”๋€” ์ˆ˜๋„ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์—ˆ์Šต๋‹ˆ๋‹ค. ํ˜„์žฌ ์ฝ”๋“œ๋ฅผ ๊ธฐ์ค€์œผ๋กœ๋Š” quantitiy ๋นผ๊ณ ๋Š” final ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ค˜๋„ ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,81 @@ +package store.model; + +import java.util.ArrayList; +import java.util.List; + +public class Receipt { + private final List<ReceiptItem> items = new ArrayList<>(); + private int totalAmount = 0; + private int eventDiscount = 0; + private int membershipDiscount = 0; + + public void addItem(Product product, int quantity, int promotionAppliedQuantity) { + int itemTotal = product.getPrice() * quantity; + items.add(new ReceiptItem(product.getName(), product.getPrice(), quantity, promotionAppliedQuantity, itemTotal)); + totalAmount += itemTotal; + if (promotionAppliedQuantity > 0) { + eventDiscount += product.getPrice() * promotionAppliedQuantity; + } + } + + public void applyMembershipDiscount() { + int discountedTotal = totalAmount - eventDiscount; + membershipDiscount = (int) (discountedTotal * 0.3); + } + + public void print() { + System.out.println("============= W ํŽธ์˜์  =============="); + System.out.printf("%-12s %-8s %-10s\n", "์ƒํ’ˆ๋ช…", "์ˆ˜๋Ÿ‰", "๊ธˆ์•ก"); + for (ReceiptItem item : items) { + System.out.printf("%-12s %-8d %-10s\n", + item.getName(), + item.getQuantity(), + String.format("%,d", item.getItemTotal())); + } + for (ReceiptItem item : items) { + if (item.getPromotionAppliedQuantity() > 0) { + System.out.println("============= ์ฆ ์ • ==============="); + System.out.printf("%-12s %-8d\n", item.getName(), item.getPromotionAppliedQuantity()); + } + } + System.out.println("===================================="); + System.out.printf("%-12s %-8s %-10s\n", "์ด๊ตฌ๋งค์•ก", "", String.format("%,d", totalAmount)); + System.out.printf("%-12s %-8s %-10s\n", "ํ–‰์‚ฌํ• ์ธ", "", "-" + String.format("%,d", eventDiscount)); + System.out.printf("%-12s %-8s %-10s\n", "๋ฉค๋ฒ„์‹ญํ• ์ธ", "", "-" + String.format("%,d", membershipDiscount)); + int finalAmount = totalAmount - eventDiscount - membershipDiscount; + System.out.printf("%-12s %-8s %-10s\n", "๋‚ด์‹ค๋ˆ", "", String.format("%,d", finalAmount)); + System.out.println("===================================="); + } + + private static class ReceiptItem { + private final String name; + private final int price; + private final int quantity; + private final int promotionAppliedQuantity; + private final int itemTotal; + + public ReceiptItem(String name, int price, int quantity, int promotionAppliedQuantity, int itemTotal) { + this.name = name; + this.price = price; + this.quantity = quantity; + this.promotionAppliedQuantity = promotionAppliedQuantity; + this.itemTotal = itemTotal; + } + + public String getName() { + return name; + } + + public int getQuantity() { + return quantity; + } + + public int getPromotionAppliedQuantity() { + return promotionAppliedQuantity; + } + + public int getItemTotal() { + return itemTotal; + } + } +}
Java
์ƒํ’ˆํ•˜๋ฉด ๋‹น์—ฐํ•˜๊ฒŒ price๋ฅผ ๊ตฌํ˜„ํ•ด์•ผ ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค. ๊ฐœ์ธ์ ์œผ๋กœ ๋ฆฌํŒฉํ† ๋งํ•œ๋‹ค๋ฉด itemTotal์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  quantity๋ž‘ price๋กœ ๊ณ„์‚ฐ์„ ํ•˜๋Š”๊ฒŒ ์˜ฌ๋ฐ”๋ฅธ ๋ฐฉ๋ฒ•์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,116 @@ +package store; + +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import store.domain.Stock; +import store.domain.order.OrderItem; +import store.domain.order.OrderItems; +import store.domain.order.OrderStatus; +import store.domain.order.service.OrderService; +import store.domain.receipt.Receipt; +import store.messages.ErrorMessage; +import store.view.View; + +public class StoreService { + private static final String ORDER_ITEM_PATTERN_REGEX = "\\[(.+)-(\\d+)]"; + private static final int FREE_PROMOTION_ITEM_COUNT = 1; + + private final OrderService orderService; + + public StoreService(OrderService orderService) { + this.orderService = orderService; + } + + public OrderItems getOrderItems(String input) { + return makeOrderItems(getSeparatedInput(input)); + } + + public Receipt proceedPurchase(Stock stock, OrderItems orderItems) { + Receipt receipt = new Receipt(); + orderItems.getOrderItems().forEach(orderItem -> proceedOrder(stock, orderItem, receipt)); + checkApplyMembership(receipt); + + return receipt; + } + + private void proceedOrder(Stock stock, OrderItem orderItem, Receipt receipt) { + OrderStatus orderStatus = stock.getOrderStatus(orderItem); + checkOutOfStock(orderStatus); + confirmOrder(orderStatus, orderItem); + orderService.order(orderStatus, orderItem, receipt); + } + + private void checkOutOfStock(OrderStatus orderStatus) { + if (!orderStatus.isProductFound()) { + throw new NoSuchElementException(ErrorMessage.INVALID_PRODUCT_NAME.getMessage()); + } + if (!orderStatus.isInStock()) { + throw new IllegalStateException(ErrorMessage.OVER_STOCK.getMessage()); + } + } + + private void confirmOrder(OrderStatus orderStatus, OrderItem orderItem) { + addCanGetFreeItem(orderStatus, orderItem); + checkNotAppliedPromotionItem(orderStatus, orderItem); + } + + private void addCanGetFreeItem(OrderStatus orderStatus, OrderItem orderItem) { + if (orderStatus.isCanGetFreeItem()) { + boolean addFreeItem = View.getInstance() + .promptFreePromotion(orderItem.getItemName(), FREE_PROMOTION_ITEM_COUNT); + if (addFreeItem) { + orderItem.addQuantity(FREE_PROMOTION_ITEM_COUNT); + } + } + } + + private void checkNotAppliedPromotionItem(OrderStatus orderStatus, OrderItem orderItem) { + if (!(orderStatus.isMultipleStock() && orderStatus.hasPromotionProduct())) { + return; + } + + int notAppliedItemCount = orderStatus.getNotAppliedItemCount(orderItem.getQuantity()); + // ์ •๊ฐ€๋กœ ๊ฒฐ์ œํ•ด์•ผ ํ•˜๋Š” ์ˆ˜๋Ÿ‰์„ ์ œ์™ธํ•˜๋Š” ์˜ต์…˜์„ ์„ ํƒํ–ˆ๋‹ค๋ฉด, ๋น„ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์„ ํŒ๋งค ๋Œ€์ƒ์—์„œ ์‚ญ์ œํ•˜๊ณ  ์ฃผ๋ฌธ ๊ฐœ์ˆ˜๋ฅผ ๊ฐ์†Œ์‹œํ‚ด. + if (!askProceedWithNotPromotionItems(orderItem, notAppliedItemCount)) { + orderItem.subQuantity(notAppliedItemCount); + orderStatus.removeNormalProduct(); + } + } + + private boolean askProceedWithNotPromotionItems(OrderItem orderItem, int notAppliedItemCount) { + return View.getInstance() + .promptInsufficientPromotion(orderItem.getItemName(), notAppliedItemCount); + } + + private void checkApplyMembership(Receipt receipt) { + if (View.getInstance().promptMembershipDiscount()) { + receipt.applyMembershipDiscount(); + } + } + + private OrderItems makeOrderItems(List<String> separatedInputs) { + List<OrderItem> orderItems = new ArrayList<>(); + Pattern pattern = Pattern.compile(ORDER_ITEM_PATTERN_REGEX); + + for (String input : separatedInputs) { + Matcher matcher = pattern.matcher(input); + if (matcher.matches()) { + orderItems.add(makeOrderItem(matcher)); + } + } + return new OrderItems(orderItems); + } + + private OrderItem makeOrderItem(Matcher matcher) { + String name = matcher.group(1); + int quantity = Integer.parseInt(matcher.group(2)); + return new OrderItem(name, quantity); + } + + private List<String> getSeparatedInput(String input) { + return List.of(input.split(",")); + } +}
Java
Pattern ๊ฐ์ฒด๊ฐ€ ๋ฉ”์„œ๋“œ๊ฐ€ ์‹คํ–‰๋  ๋•Œ๋งˆ๋‹ค ๋ฐ˜๋ณต์ ์œผ๋กœ ์ƒ์„ฑ๋˜์–ด ์„ฑ๋Šฅ์— ์ข‹์ง€ ์•Š์•„์š” ๐Ÿ˜Š ์ •๊ทœ์‹ ํŒจํ„ด์€ ํ•œ ๋ฒˆ๋งŒ ์ปดํŒŒ์ผํ•˜๋ฉด ๊ณ„์† ์žฌ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, Pattern ๊ฐ์ฒด๋ฅผ ํ•„๋“œ์— ์ €์žฅํ•˜์—ฌ ์—ฌ๋Ÿฌ ๋ฒˆ ์‚ฌ์šฉํ•˜๋„๋ก ํ•˜๋Š” ๊ฒƒ์ด ๋‚˜์„ ๊ฒƒ ๊ฐ™์•„์š” ! ```java private static final Pattern ORDER_ITEM_PATTERN = Pattern.compile(ORDER_ITEM_PATTERN_REGEX); public OrderItems makeOrderItems(List<String> separatedInputs) { List<OrderItem> orderItems = new ArrayList<>(); for (String input : separatedInputs) { Matcher matcher = ORDER_ITEM_PATTERN.matcher(input); if (matcher.matches()) { orderItems.add(makeOrderItem(matcher)); } } return new OrderItems(orderItems); } ```
@@ -0,0 +1,116 @@ +package store; + +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import store.domain.Stock; +import store.domain.order.OrderItem; +import store.domain.order.OrderItems; +import store.domain.order.OrderStatus; +import store.domain.order.service.OrderService; +import store.domain.receipt.Receipt; +import store.messages.ErrorMessage; +import store.view.View; + +public class StoreService { + private static final String ORDER_ITEM_PATTERN_REGEX = "\\[(.+)-(\\d+)]"; + private static final int FREE_PROMOTION_ITEM_COUNT = 1; + + private final OrderService orderService; + + public StoreService(OrderService orderService) { + this.orderService = orderService; + } + + public OrderItems getOrderItems(String input) { + return makeOrderItems(getSeparatedInput(input)); + } + + public Receipt proceedPurchase(Stock stock, OrderItems orderItems) { + Receipt receipt = new Receipt(); + orderItems.getOrderItems().forEach(orderItem -> proceedOrder(stock, orderItem, receipt)); + checkApplyMembership(receipt); + + return receipt; + } + + private void proceedOrder(Stock stock, OrderItem orderItem, Receipt receipt) { + OrderStatus orderStatus = stock.getOrderStatus(orderItem); + checkOutOfStock(orderStatus); + confirmOrder(orderStatus, orderItem); + orderService.order(orderStatus, orderItem, receipt); + } + + private void checkOutOfStock(OrderStatus orderStatus) { + if (!orderStatus.isProductFound()) { + throw new NoSuchElementException(ErrorMessage.INVALID_PRODUCT_NAME.getMessage()); + } + if (!orderStatus.isInStock()) { + throw new IllegalStateException(ErrorMessage.OVER_STOCK.getMessage()); + } + } + + private void confirmOrder(OrderStatus orderStatus, OrderItem orderItem) { + addCanGetFreeItem(orderStatus, orderItem); + checkNotAppliedPromotionItem(orderStatus, orderItem); + } + + private void addCanGetFreeItem(OrderStatus orderStatus, OrderItem orderItem) { + if (orderStatus.isCanGetFreeItem()) { + boolean addFreeItem = View.getInstance() + .promptFreePromotion(orderItem.getItemName(), FREE_PROMOTION_ITEM_COUNT); + if (addFreeItem) { + orderItem.addQuantity(FREE_PROMOTION_ITEM_COUNT); + } + } + } + + private void checkNotAppliedPromotionItem(OrderStatus orderStatus, OrderItem orderItem) { + if (!(orderStatus.isMultipleStock() && orderStatus.hasPromotionProduct())) { + return; + } + + int notAppliedItemCount = orderStatus.getNotAppliedItemCount(orderItem.getQuantity()); + // ์ •๊ฐ€๋กœ ๊ฒฐ์ œํ•ด์•ผ ํ•˜๋Š” ์ˆ˜๋Ÿ‰์„ ์ œ์™ธํ•˜๋Š” ์˜ต์…˜์„ ์„ ํƒํ–ˆ๋‹ค๋ฉด, ๋น„ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์„ ํŒ๋งค ๋Œ€์ƒ์—์„œ ์‚ญ์ œํ•˜๊ณ  ์ฃผ๋ฌธ ๊ฐœ์ˆ˜๋ฅผ ๊ฐ์†Œ์‹œํ‚ด. + if (!askProceedWithNotPromotionItems(orderItem, notAppliedItemCount)) { + orderItem.subQuantity(notAppliedItemCount); + orderStatus.removeNormalProduct(); + } + } + + private boolean askProceedWithNotPromotionItems(OrderItem orderItem, int notAppliedItemCount) { + return View.getInstance() + .promptInsufficientPromotion(orderItem.getItemName(), notAppliedItemCount); + } + + private void checkApplyMembership(Receipt receipt) { + if (View.getInstance().promptMembershipDiscount()) { + receipt.applyMembershipDiscount(); + } + } + + private OrderItems makeOrderItems(List<String> separatedInputs) { + List<OrderItem> orderItems = new ArrayList<>(); + Pattern pattern = Pattern.compile(ORDER_ITEM_PATTERN_REGEX); + + for (String input : separatedInputs) { + Matcher matcher = pattern.matcher(input); + if (matcher.matches()) { + orderItems.add(makeOrderItem(matcher)); + } + } + return new OrderItems(orderItems); + } + + private OrderItem makeOrderItem(Matcher matcher) { + String name = matcher.group(1); + int quantity = Integer.parseInt(matcher.group(2)); + return new OrderItem(name, quantity); + } + + private List<String> getSeparatedInput(String input) { + return List.of(input.split(",")); + } +}
Java
`,` ๋„ ์ƒ์ˆ˜ํ™” ํ•˜์—ฌ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ๋‚˜์•„๋ณด์—ฌ์š” ๐Ÿ˜Š
@@ -0,0 +1,158 @@ +package store.domain; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; +import store.domain.order.OrderItem; +import store.domain.order.OrderStatus; +import store.domain.product.Product; +import store.domain.product.ProductParameter; +import store.messages.ErrorMessage; + + +/** + * Stock ํด๋ž˜์Šค๋Š” ํŽธ์˜์ ์˜ ์ƒํ’ˆ ๋ชฉ๋ก(์žฌ๊ณ )์„ ํ•„๋“œ๋กœ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. + * OrderItem(์ฃผ๋ฌธ ๋‚ด์—ญ)์ด ๋“ค์–ด์™”์„ ๋•Œ ์žฌ๊ณ  ํ˜„ํ™ฉ์„ ํŒŒ์•…ํ•˜์—ฌ OrderStatus ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด ์ฑ…์ž„์ž…๋‹ˆ๋‹ค. + * + * @see OrderItem + * @see OrderStatus + */ +public class Stock { + private final List<Product> stock; + + public Stock(List<Product> stock) { + this.stock = stock; + } + + public List<Product> getProducts() { + return stock; + } + + /* generateNormalProductFromOnlyPromotionProduct() ๋ฉ”์„œ๋“œ์˜ ์กด์žฌ ์ด์œ  + * ์šฐ์•„ํ•œํ…Œํฌ์ฝ”์Šค์˜ ์‹คํ–‰ ๊ฒฐ๊ณผ ์˜ˆ์‹œ์— ๋”ฐ๋ฅด๋ฉด ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋œ ๋ชจ๋“  ์ƒํ’ˆ์€, ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋˜์ง€ ์•Š์€ ๋ฒ„์ „์˜ ์ƒํ’ˆ ์ •๋ณด๋„ ํ‘œ์‹œํ•ด์•ผ ํ•จ. + * ๋”ฐ๋ผ์„œ, ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋œ ์ƒํ’ˆ์— ๋Œ€ํ•ด์„œ ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋˜์ง€ ์•Š์€ ์ผ๋ฐ˜ ์ƒํ’ˆ์ด ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด ์ผ๋ฐ˜ ์ƒํ’ˆ์„ ์ƒ์„ฑํ•จ. + */ + public void generateNormalProductFromOnlyPromotionProduct() { + List<Product> onlyPromotionProducts = findOnlyPromotionProducts(stock); + for (Product product : onlyPromotionProducts) { + ProductParameter productParameter = new ProductParameter( + List.of(product.getName(), String.valueOf(product.getPrice()), "0", "null")); + insertProduct(new Product(productParameter, null)); + } + } + + public OrderStatus getOrderStatus(OrderItem orderItem) { + List<Product> foundProducts = findProductsByName(orderItem.getItemName()); + if (foundProducts.isEmpty()) { + return OrderStatus.outOfStock(foundProducts); + } + + return checkOrderAvailability(orderItem, findAvailableProductsByName(orderItem.getItemName())); + } + + private OrderStatus checkOrderAvailability(OrderItem orderItem, List<Product> foundAvailableProducts) { + if (foundAvailableProducts.isEmpty()) { + return OrderStatus.outOfStock(findProductsByName(orderItem.getItemName())); + } + if (foundAvailableProducts.size() == 1) { + return getOrderStatusWithSingleProduct(orderItem, foundAvailableProducts.getFirst()); + } + if (foundAvailableProducts.size() == 2) { + return getOrderStatusWithMultipleProducts(orderItem, foundAvailableProducts); + } + + throw new IllegalArgumentException(ErrorMessage.INVALID_PRODUCT_PROMOTIONS.getMessage()); + } + + private static OrderStatus getOrderStatusWithSingleProduct(OrderItem orderItem, Product product) { + if (!product.isStockAvailable(orderItem.getQuantity())) { + return OrderStatus.outOfStock(List.of(product)); + } + if (product.isPromotedProduct()) { + boolean canGetFreeItem = product.isCanGetFreeProduct(orderItem.getQuantity()); + int maxPromotionCanAppliedCount = product.getMaxAvailablePromotionQuantity(); + return OrderStatus.inOnlyPromotionStock(product, canGetFreeItem, maxPromotionCanAppliedCount); + } + + return OrderStatus.inOnlyNormalStock(product); + } + + private OrderStatus getOrderStatusWithMultipleProducts(OrderItem orderItem, List<Product> foundProducts) { + if (getAllQuantity(foundProducts) < orderItem.getQuantity()) { + return OrderStatus.outOfStock(foundProducts); + } + + if (hasPromotedProduct(foundProducts)) { + return checkMixedProductsSituation(orderItem, foundProducts); + } + + // ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋˜์ง€ ์•Š์€ ์ƒํ’ˆ๋งŒ 2๊ฐœ๋ผ๋ฉด + return OrderStatus.inMultipleNormalProductStock(foundProducts); + } + + private OrderStatus checkMixedProductsSituation(OrderItem orderItem, List<Product> foundProducts) { + Product promotedProduct = getPromotedProduct(foundProducts).get(); + if (promotedProduct.isStockAvailable(orderItem.getQuantity())) { // ํ”„๋กœ๋ชจ์…˜ ์ œํ’ˆ ์žฌ๊ณ ๋งŒ์œผ๋กœ ์ฒ˜๋ฆฌ ๊ฐ€๋Šฅํ•˜๋ฉด + boolean canGetFreeItem = promotedProduct.isCanGetFreeProduct(orderItem.getQuantity()); + int maxPromotionCanAppliedCount = promotedProduct.getMaxAvailablePromotionQuantity(); + return OrderStatus.inOnlyPromotionStock(promotedProduct, canGetFreeItem, maxPromotionCanAppliedCount); + } + + // ํ”„๋กœ๋ชจ์…˜ ์ œํ’ˆ์˜ ์žฌ๊ณ ๋งŒ์œผ๋กœ ์ฒ˜๋ฆฌ๊ฐ€ ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค๋ฉด, ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๋Š” ์ผ๋‹จ ๋‹ค ์“ฐ๊ณ , ๋‚˜๋จธ์ง€ ์–‘์€ ๋น„ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๋กœ ์ฒ˜๋ฆฌ + int maxPromotionCanAppliedCount = promotedProduct.getMaxAvailablePromotionQuantity(); + return new OrderStatus(foundProducts, true, false, maxPromotionCanAppliedCount); + } + + private boolean hasPromotedProduct(List<Product> products) { + return products.stream().anyMatch(Product::isPromotedProduct); + } + + private Optional<Product> getPromotedProduct(List<Product> products) { + return products.stream().filter(Product::isPromotedProduct).findFirst(); + } + + private int getAllQuantity(List<Product> products) { + return products.getFirst().getQuantity() + products.getLast().getQuantity(); + } + + private List<Product> findProductsByName(String productName) { + return stock.stream().filter(product -> Objects.equals(product.getName(), productName)).toList(); + } + + private List<Product> findAvailableProductsByName(String productName) { + return stock.stream().filter(product -> Objects.equals(product.getName(), productName)) + .filter(product -> product.getQuantity() > 0).toList(); + } + + private int findProductIndexByName(String productName) { + for (int i = 0; i < stock.size(); i++) { + if (stock.get(i).getName().equals(productName)) { + return i; + } + } + return -1; + } + + private void insertProduct(Product product) { + int index = findProductIndexByName(product.getName()); + if (index != -1) { + stock.add(index + 1, product); + return; + } + stock.add(product); + } + + private List<Product> findOnlyPromotionProducts(List<Product> products) { + Map<String, List<Product>> productByName = products.stream() + .collect(Collectors.groupingBy(Product::getName)); + + return productByName.values().stream() + .filter(productList -> productList.size() == 1) + .flatMap(Collection::stream) + .filter(Product::isPromotedProduct) + .collect(Collectors.toList()); + } +}
Java
์ค‘๋ณต ๋กœ์ง์„ ๋ฉ”์„œ๋“œ๋กœ ๋ถ„๋ฆฌํ•˜๋ฉด ์žฌ์‚ฌ์šฉ์„ฑ์ด ๋” ๋†’์•„์งˆ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”! ```java private static OrderStatus handlePromotionForSingleProduct(OrderItem orderItem, Product product) { boolean canGetFreeItem = product.isCanGetFreeProduct(orderItem.getQuantity()); int maxPromotionCanAppliedCount = product.getMaxAvailablePromotionQuantity(); return OrderStatus.inOnlyPromotionStock(product, canGetFreeItem, maxPromotionCanAppliedCount); } ```
@@ -0,0 +1,107 @@ +package store.domain.order.service; + +import java.util.List; +import java.util.Optional; +import store.domain.order.OrderItem; +import store.domain.order.OrderStatus; +import store.domain.product.Product; +import store.domain.receipt.BuyItem; +import store.domain.receipt.FreeItem; +import store.domain.receipt.Receipt; + +public class OrderService { + + public void order(OrderStatus orderStatus, OrderItem orderItem, Receipt receipt) { + if (orderStatus.isMultipleStock()) { + purchaseMultipleStock(orderStatus, orderItem, receipt); + return; + } + + purchaseSingleStock(orderStatus.getFirstProduct(), orderItem, receipt); + } + + private void purchaseMultipleStock(OrderStatus orderStatus, OrderItem orderItem, Receipt receipt) { + if (orderStatus.hasPromotionProduct()) { + purchaseMixedStock(orderStatus, orderItem, receipt); + return; + } + purchaseMultipleNormalStock(orderStatus, orderItem, receipt); + } + + private void purchaseMixedStock(OrderStatus orderStatus, OrderItem orderItem, Receipt receipt) { + List<Product> products = orderStatus.getMultipleProducts(); + Product promotionProduct = products.stream().filter(Product::isPromotedProduct).findFirst().get(); + Product notPromotionProduct = products.stream().filter(product -> !product.isPromotedProduct()).findFirst() + .get(); + + updateReceiptInMixedProducts(orderItem, receipt, promotionProduct, notPromotionProduct); + } + + private static void updateReceiptInMixedProducts(OrderItem orderItem, Receipt receipt, Product promotionProduct, + Product notPromotionProduct) { + int maxQuantityOfPromotionProduct = promotionProduct.getQuantity(); + + promotionProduct.sell(maxQuantityOfPromotionProduct); + notPromotionProduct.sell(orderItem.getQuantity() - maxQuantityOfPromotionProduct); + + receipt.addPriceOfPromotionItem(promotionProduct.getRegularPurchasePrice(maxQuantityOfPromotionProduct)); + updateReceiptBuyItem(receipt, orderItem, orderItem.getQuantity(), + promotionProduct.getRegularPurchasePrice(orderItem.getQuantity())); + updateReceiptFreeItem(receipt, orderItem, + promotionProduct.getPromotionDiscountAmount(maxQuantityOfPromotionProduct), + promotionProduct.getPromotionDiscountPrice(maxQuantityOfPromotionProduct)); + } + + private void purchaseMultipleNormalStock(OrderStatus orderStatus, OrderItem orderItem, Receipt receipt) { + List<Product> products = orderStatus.getMultipleProducts(); + Optional<Product> optionalProduct = products.stream() + .filter(product -> product.isStockAvailable(orderItem.getQuantity())).findFirst(); + + if (optionalProduct.isPresent()) { + purchaseSingleStock(optionalProduct.get(), orderItem, receipt); + return; + } + + updateReceiptInMultipleNormalProducts(orderItem, receipt, products); + } + + private static void updateReceiptInMultipleNormalProducts(OrderItem orderItem, Receipt receipt, + List<Product> products) { + int currentRegularPrice = 0; + + int maxQuantityOfFirstProduct = products.getFirst().getQuantity(); + products.getFirst().sell(maxQuantityOfFirstProduct); + currentRegularPrice += products.getFirst().getRegularPurchasePrice(maxQuantityOfFirstProduct); + int remainBuyQuantity = orderItem.getQuantity() - maxQuantityOfFirstProduct; + products.getLast().sell(remainBuyQuantity); + currentRegularPrice += products.getLast().getRegularPurchasePrice(remainBuyQuantity); + + updateReceiptBuyItem(receipt, orderItem, orderItem.getQuantity(), currentRegularPrice); + } + + private void purchaseSingleStock(Product product, OrderItem orderItem, Receipt receipt) { + int buyQuantity = orderItem.getQuantity(); + if (buyQuantity == 0) { + return; + } + updateReceiptBuyItem(receipt, orderItem, buyQuantity, product.getRegularPurchasePrice(buyQuantity)); + if (product.isPromotedProduct()) { + updateReceiptFreeItem(receipt, orderItem, product.getPromotionDiscountAmount(buyQuantity), + product.getPromotionDiscountPrice(buyQuantity)); + receipt.addPriceOfPromotionItem(product.getRegularPurchasePrice(buyQuantity)); + } + product.sell(buyQuantity); + } + + private static void updateReceiptBuyItem(Receipt receipt, OrderItem orderItem, int buyQuantity, + int regularPurchasePrice) { + BuyItem item = new BuyItem(orderItem.getItemName(), buyQuantity, regularPurchasePrice); + receipt.addBuyItem(item); + } + + private static void updateReceiptFreeItem(Receipt receipt, OrderItem orderItem, int discountedAmount, + int discountedPrice) { + FreeItem item = new FreeItem(orderItem.getItemName(), discountedAmount, discountedPrice); + receipt.addFreeItem(item); + } +}
Java
๋ฉ”์„œ๋“œ๊ฐ€ ์„œ๋กœ ์ฒด์ด๋‹๋˜์–ด ๊ณ„์†ํ•ด์„œ ํ˜ธ์ถœ๋˜๋Š” ๊ตฌ์กฐ๋Š” ์ฝ”๋“œ ํ๋ฆ„์„ ํŒŒ์•…ํ•˜๊ธฐ ์–ด๋ ค์šธ ์ˆ˜ ์žˆ์–ด์š”. ํ•จ์ˆ˜๋“ค์ด ์„œ๋กœ ๊ธด๋ฐ€ํ•˜๊ฒŒ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ์–ด ํ•จ์ˆ˜๋“ค์ด ํ•˜๋‚˜๋กœ ์ด์–ด์ง„ ๋А๋‚Œ์„ ๋ฐ›์„ ์ˆ˜ ์žˆ๋Š”๋ฐ, ๊ฐ ํ•จ์ˆ˜๊ฐ€ ์ž์‹ ๋งŒ์˜ ์ฑ…์ž„์„ ๊ฐ–๋„๋ก ๋งŒ๋“ค๋„๋ก ๊ณ ๋ฏผํ•ด๋ณด์‹œ๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š” ๐Ÿ˜Š ์ฑ…์ž„ ๋ถ„๋ฆฌ(SRP)์™€ ์˜์กด์„ฑ ์—ญ์ „(DIP)์„ ๊ณ ๋ คํ•˜๊ฒŒ ๋œ๋‹ค๋ฉด ๊ฐ€๋…์„ฑ, ์œ ์ง€๋ณด์ˆ˜์„ฑ, ํ…Œ์ŠคํŠธ ์šฉ์ด์„ฑ์ด ์ข‹์•„์งˆ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,54 @@ +package store.domain.promotion; + +import camp.nextstep.edu.missionutils.DateTimes; + +/** + * Promotion ์€ ํ”„๋กœ๋ชจ์…˜ ์ •๋ณด๋ฅผ ํ•„๋“œ๋กœ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. + * ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ ๊ฐ€๊ฒฉ ๋“ฑ ๋‹ค์–‘ํ•œ ํ”„๋กœ๋ชจ์…˜ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜๋Š” ๊ฒƒ์ด ์ฑ…์ž„์ž…๋‹ˆ๋‹ค. + */ +public class Promotion { + private final String promotionName; + private final int requiredBuyCount; + private final int toGiveItemCount; + private final Period period; + + public Promotion(PromotionParameter promotionParameter) { + this.promotionName = promotionParameter.getPromotionName(); + this.requiredBuyCount = promotionParameter.getRequiredBuyCount(); + this.toGiveItemCount = promotionParameter.getToGiveItemCount(); + this.period = promotionParameter.getPeriod(); + } + + /* ํ”„๋กœ๋ชจ์…˜์„ ์ ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์ƒํ’ˆ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ๋ฒ• + * ์ฝœ๋ผ 2+1 ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์ด 7๊ฐœ ์žˆ์„ ๋•Œ, ์‚ฌ์šฉ์ž๊ฐ€ ํ”„๋กœ๋ชจ์…˜์„ ์ ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์ฝœ๋ผ์˜ ์ตœ๋Œ€ ๊ฐœ์ˆ˜๋Š” 6๊ฐœ๋‹ค. 4๊ฐœ๋ฅผ ๊ตฌ๋งคํ•˜๊ณ , 2๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋ฐ›์œผ๋ฉด ์ด 6๊ฐœ์ด๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. + * 5๊ฐœ๋ฅผ ๊ตฌ๋งคํ•˜๊ณ  2+1 ์ด๋ฒคํŠธ๋ฅผ ์ตœ๋Œ€ํ•œ ์ ์šฉํ•˜์—ฌ ์ตœ๋Œ€ 7๊ฐœ๋ฅผ ์–ป๋Š” ๊ฒƒ๋„ ๊ฐ€๋Šฅํ•˜๋‹ค. ํ•˜์ง€๋งŒ ์‚ฌ์šฉ์ž๊ฐ€ ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๋กœ๋Š” ์ฒ˜๋ฆฌ๊ฐ€ ๋ถˆ๊ฐ€๋Šฅํ•œ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ–ˆ์„ ๊ฒฝ์šฐ, + * ์šฐํ…Œ์ฝ”์—์„œ ์ œ์‹œํ•œ ์‹คํ–‰ ๊ฒฐ๊ณผ ์˜ˆ์‹œ์— ๋”ฐ๋ฅด๋ฉด ์ •๊ฐ€๋กœ ๊ตฌ๋งคํ•ด์•ผ ํ•˜๋Š” ์ฝœ๋ผ์˜ ๊ฐœ์ˆ˜๋Š” (์‚ฌ์šฉ์ž๊ฐ€ ์ž…๋ ฅํ•œ ์ˆ˜๋Ÿ‰) - (์ตœ๋Œ€ ์ ์šฉ ๊ฐ€๋Šฅํ•œ ํ”„๋กœ๋ชจ์…˜ ์ˆ˜๋Ÿ‰) ์ด๊ธฐ ๋•Œ๋ฌธ์— + * ์ •๊ฐ€๋กœ ๊ตฌ๋งคํ•˜๋Š” ์ƒํ’ˆ์„ ์ œ์™ธํ•˜๋Š” ์˜ต์…˜์„ ํƒํ•  ์‹œ ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๊ฐ€ ๋ช‡ ๊ฐœ ๋‚จ์„์ˆ˜๋„ ์žˆ๋‹ค. + * + * ๋”ฐ๋ผ์„œ, ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ  ์ˆ˜๊ฐ€ N์ผ๋•Œ ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋  ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ๊ฐœ์ˆ˜๋Š” [N - (N % (requiredBuyCount + toGiveItemCount))] ์ด๋‹ค. + */ + public int getMaxAvailablePromotionQuantity(int currentStockCount) { + return currentStockCount - (currentStockCount % (requiredBuyCount + toGiveItemCount)); + } + + public String getPromotionName() { + return promotionName; + } + + public int getRequiredBuyCount() { + return requiredBuyCount; + } + + public boolean isAvailablePromotion() { + return period.isBetweenPeriod(DateTimes.now()); + } + + public int getDiscountPrice(int buyQuantity, int regularPrice) { + int freeItemCount = buyQuantity / (requiredBuyCount + toGiveItemCount); + return freeItemCount * regularPrice; + } + + public int getDiscountedQuantity(int buyQuantity) { + return buyQuantity / (requiredBuyCount + toGiveItemCount); + } +}
Java
์ฃผ์„์„ ๋งŽ์ด ๋‹ฌ์•„์ฃผ์‹œ๋Š” ๊ฑด ์ •๋ง ์ข‹์€ ์ ์ด์ง€๋งŒ, ์ „์ฒด์ ์œผ๋กœ ์กฐ๊ธˆ๋งŒ ์ค„์—ฌ๋ณด๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š”? ์‚ฌ์‹ค, ์ฝ”๋“œ๊ฐ€ ๋” ๊ฐ„๊ฒฐํ•˜๊ณ  ๋ช…ํ™•ํ•ด์ง€๋ฉด ์ฃผ์„ ์—†์ด๋„ ๊ทธ ์˜๋„๊ฐ€ ์ž˜ ์ „๋‹ฌ๋  ์ˆ˜ ์žˆ์–ด์š” ๐Ÿ˜Š ์˜ˆ์™ธ์ ์ธ ์ƒํ™ฉ์ด๋‚˜ ๋ณต์žกํ•œ ๋กœ์ง์—์„œ๋งŒ ๊ฐ„๋‹จํ•œ ์ฃผ์„์„ ์ถ”๊ฐ€ํ•˜๋Š” ๊ฒŒ ๋” ํšจ๊ณผ์ ์ผ ๊ฒƒ ๊ฐ™์•„์š” !
@@ -0,0 +1,25 @@ +package store.messages; + +public enum ErrorMessage { + INVALID_INPUT("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + INVALID_INPUT_OTHER("์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + INVALID_PROMOTION_FILE_PARAMETERS("promotions.md์˜ ํŒŒ๋ผ๋ฏธํ„ฐ ํ˜•์‹์ด ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์Šต๋‹ˆ๋‹ค."), + INVALID_PROMOTION_FILE_FORM("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ promotions.md ํ˜•์‹์ž…๋‹ˆ๋‹ค."), + INVALID_PRODUCT_FILE_PARAMETERS("products.md์˜ ํŒŒ๋ผ๋ฏธํ„ฐ ํ˜•์‹์ด ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์Šต๋‹ˆ๋‹ค."), + INVALID_PRODUCT_FILE_FORM("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ products.md ํ˜•์‹์ž…๋‹ˆ๋‹ค."), + INVALID_PRODUCT_NAME("์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + INVALID_PRODUCT_PROMOTIONS("products.md ํŒŒ์ผ์˜ ํ˜•์‹์— ๋ฌธ์ œ๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ๋™์ผ ์ƒํ’ˆ์— ์—ฌ๋Ÿฌ ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + OVER_STOCK("์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + FILE_NOT_FOUND("ํŽธ์˜์  ๊ตฌ์„ฑ ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ํ”„๋กœ๊ทธ๋žจ์„ ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค."); + + private static final String ERROR_PREFIX = "[ERROR] "; + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return ERROR_PREFIX + message; + } +}
Java
`๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.`, `(Y/N)` ๊ฐ™์€ ๋ถ€๋ถ„๋„ ์ƒ์ˆ˜๋กœ ๋”ฐ๋กœ ๋นผ๋ฉด ์œ ์ง€๋ณด์ˆ˜์— ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š” !
@@ -0,0 +1,120 @@ +package store.view; + +import java.util.List; +import store.domain.product.Product; +import store.domain.receipt.BuyItem; +import store.domain.receipt.FreeItem; +import store.domain.receipt.Receipt; +import store.messages.ReceiptForm; +import store.messages.StoreMessage; + +class OutputView { + protected void printGreetingMessage() { + System.out.println(StoreMessage.GREETING.getMessage()); + } + + protected void printContinueShoppingMessage() { + System.out.println(StoreMessage.ASK_CONTINUE_SHOPPING.getMessage()); + } + + protected void printReceipt(Receipt receipt) { + printReceiptHeader(); + printReceiptItems(receipt); + printReceiptFinals(receipt); + } + + private void printReceiptHeader() { + newLine(); + System.out.println(ReceiptForm.HEADER.getMessage()); + System.out.printf(ReceiptForm.TITLES.getMessage(), ReceiptForm.WORD_ITEM_NAME.getMessage(), + ReceiptForm.WORD_ITEM_QUANTITY.getMessage(), ReceiptForm.WORD_ITEM_PRICE.getMessage()); + } + + private void printReceiptItems(Receipt receipt) { + // ๊ตฌ๋งคํ•œ ์ƒํ’ˆ ์ถœ๋ ฅ + for (BuyItem item : receipt.getBuyItems()) { + System.out.printf(ReceiptForm.BUY_ITEMS.getMessage(), item.getName(), item.getQuantity(), + item.getTotalPrice()); + } + if (receipt.hasFreeItem()) { + System.out.println(ReceiptForm.PROMOTION_DIVIDER.getMessage()); + // ์ฆ์ • ์ƒํ’ˆ ์ถœ๋ ฅ + for (FreeItem item : receipt.getFreeItems()) { + System.out.printf(ReceiptForm.PROMOTION_ITEMS.getMessage(), item.getName(), item.getQuantity()); + } + } + } + + private void printReceiptFinals(Receipt receipt) { + System.out.println(ReceiptForm.FINAL_DIVIDER.getMessage()); + // ์ด ๊ตฌ๋งค์•ก, ํ–‰์‚ฌํ• ์ธ, ๋ฉค๋ฒ„์‹ญ ํ• ์ธ, ๋‚ด์‹ค ๋ˆ ์ถœ๋ ฅ + System.out.printf(ReceiptForm.TOTAL_PRICE.getMessage(), ReceiptForm.WORD_TOTAL_PRICE.getMessage(), + receipt.getTotalQuantity(), receipt.getTotalPrice()); + System.out.printf(ReceiptForm.PROMOTION_DISCOUNT.getMessage(), ReceiptForm.WORD_PROMOTION_DISCOUNT.getMessage(), + receipt.getTotalPromotionDiscount()); + System.out.printf(ReceiptForm.MEMBERSHIP_DISCOUNT.getMessage(), + ReceiptForm.WORD_MEMBERSHIP_DISCOUNT.getMessage(), receipt.getMembershipDiscount()); + System.out.printf(ReceiptForm.FINAL_PRICE.getMessage(), ReceiptForm.WORD_FINAL_PRICE.getMessage(), + receipt.getFinalPrice()); + newLine(); + } + + protected void printNoReceiptNotice() { + System.out.println(StoreMessage.NO_PURCHASE_NOTICE.getMessage()); + } + + protected void printBuyRequestMessage() { + newLine(); + System.out.println(StoreMessage.BUY_REQUEST.getMessage()); + } + + protected void printStockStatus(List<Product> products) { + printStockNoticeMessage(); + printStockItems(products); + } + + private void printStockItems(List<Product> products) { + newLine(); + for (Product product : products) { + if (product.getQuantity() != 0) { + System.out.printf(StoreMessage.STOCK_STATUS.getMessage(), product.getName(), product.getPrice(), + product.getQuantity(), + product.getPromotionName()); + continue; + } + System.out.printf(StoreMessage.STOCK_STATUS_NO_STOCK.getMessage(), product.getName(), product.getPrice(), + product.getPromotionName()); + } + System.out.flush(); + } + + protected void printFreePromotionNotice(String itemName, int freeItemCount) { + newLine(); + System.out.printf(StoreMessage.ASK_FREE_PROMOTION.getMessage(), itemName, freeItemCount); + System.out.flush(); + } + + protected void printInsufficientPromotionNotice(String itemName, int notAppliedItemCount) { + newLine(); + System.out.printf(StoreMessage.ASK_INSUFFICIENT_PROMOTION.getMessage(), itemName, notAppliedItemCount); + System.out.flush(); + } + + protected void printMembershipDiscountNotice() { + newLine(); + System.out.println(StoreMessage.ASK_MEMBERSHIP_DISCOUNT.getMessage()); + } + + private void printStockNoticeMessage() { + System.out.println(StoreMessage.STOCK_NOTICE.getMessage()); + } + + protected void printErrorMessage(String errorMessage) { + newLine(); + System.out.println(errorMessage); + } + + protected void newLine() { + System.out.println(); + } +}
Java
์˜ค! flush๋ผ๋Š” ๊ฒƒ๋„ ์žˆ๊ตฐ์š”! ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค ๐Ÿ‘๐Ÿ‘
@@ -0,0 +1,79 @@ +package store.util; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Scanner; +import store.domain.Stock; +import store.domain.promotion.Promotion; +import store.domain.promotion.PromotionParameter; +import store.domain.promotion.Promotions; +import store.domain.product.Product; +import store.domain.product.ProductParameter; + +/** + * StoreInitializer ๋Š” ์ƒํ’ˆ๊ณผ ํ”„๋กœ๋ชจ์…˜ ํŒŒ์ผ์„ ์ฝ๊ณ , ์žฌ๊ณ  ์ •๋ณด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์œ ํ‹ธ์„ฑ ํด๋ž˜์Šค์ž…๋‹ˆ๋‹ค. + */ +public class StoreInitializer { + private Promotions promotions; + + public Stock initStock() throws FileNotFoundException { + promotions = readPromotionFile(); + Stock stock = readProductFile(); + stock.generateNormalProductFromOnlyPromotionProduct(); + return stock; + } + + private Promotions readPromotionFile() throws FileNotFoundException { + Scanner scanner = new Scanner(new File("src/main/resources/promotions.md")); + Validator.checkPromotionFirstLine(scanner.nextLine()); + return readPromotionLines(scanner); + } + + private Promotions readPromotionLines(Scanner scanner) { + List<Promotion> promotions = new ArrayList<>(); + while (scanner.hasNext()) { + String currentLine = scanner.nextLine(); + promotions.add(initPromotionThat(currentLine)); + } + return new Promotions(promotions); + } + + private Promotion initPromotionThat(String line) { + Validator.checkPromotionInitLine(line); + List<String> parameters = List.of(line.split(",")); + PromotionParameter promotionParameter = new PromotionParameter(parameters); + return new Promotion(promotionParameter); + } + + private Stock readProductFile() throws FileNotFoundException { + Scanner scanner = new Scanner(new File("src/main/resources/products.md")); + Validator.checkProductFirstLine(scanner.nextLine()); + return readProductLines(scanner); + } + + private Stock readProductLines(Scanner scanner) { + List<Product> products = new ArrayList<>(); + while (scanner.hasNext()) { + String currentLine = scanner.nextLine(); + products.add(initProductThat(currentLine)); + } + + return new Stock(products); + } + + private Product initProductThat(String line) { + Validator.checkProductInitLine(line); + List<String> parameters = List.of(line.split(",")); + ProductParameter productParameter = new ProductParameter(parameters); + Promotion promotion = findPromotionByName(productParameter.getPromotionName()); + return new Product(productParameter, promotion); + } + + private Promotion findPromotionByName(String promotionName) { + Optional<Promotion> promotion = promotions.findPromotionByName(promotionName); + return promotion.orElse(null); + } +}
Java
์—๋Ÿฌ๋ฅผ ์ง์ ‘ ์ฒ˜๋ฆฌํ•˜์ง€ ์•Š๊ณ , ๋˜์ ธ์„œ main์—์„œ ์ฒ˜๋ฆฌํ•œ ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š”!? ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,79 @@ +package store.util; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Scanner; +import store.domain.Stock; +import store.domain.promotion.Promotion; +import store.domain.promotion.PromotionParameter; +import store.domain.promotion.Promotions; +import store.domain.product.Product; +import store.domain.product.ProductParameter; + +/** + * StoreInitializer ๋Š” ์ƒํ’ˆ๊ณผ ํ”„๋กœ๋ชจ์…˜ ํŒŒ์ผ์„ ์ฝ๊ณ , ์žฌ๊ณ  ์ •๋ณด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์œ ํ‹ธ์„ฑ ํด๋ž˜์Šค์ž…๋‹ˆ๋‹ค. + */ +public class StoreInitializer { + private Promotions promotions; + + public Stock initStock() throws FileNotFoundException { + promotions = readPromotionFile(); + Stock stock = readProductFile(); + stock.generateNormalProductFromOnlyPromotionProduct(); + return stock; + } + + private Promotions readPromotionFile() throws FileNotFoundException { + Scanner scanner = new Scanner(new File("src/main/resources/promotions.md")); + Validator.checkPromotionFirstLine(scanner.nextLine()); + return readPromotionLines(scanner); + } + + private Promotions readPromotionLines(Scanner scanner) { + List<Promotion> promotions = new ArrayList<>(); + while (scanner.hasNext()) { + String currentLine = scanner.nextLine(); + promotions.add(initPromotionThat(currentLine)); + } + return new Promotions(promotions); + } + + private Promotion initPromotionThat(String line) { + Validator.checkPromotionInitLine(line); + List<String> parameters = List.of(line.split(",")); + PromotionParameter promotionParameter = new PromotionParameter(parameters); + return new Promotion(promotionParameter); + } + + private Stock readProductFile() throws FileNotFoundException { + Scanner scanner = new Scanner(new File("src/main/resources/products.md")); + Validator.checkProductFirstLine(scanner.nextLine()); + return readProductLines(scanner); + } + + private Stock readProductLines(Scanner scanner) { + List<Product> products = new ArrayList<>(); + while (scanner.hasNext()) { + String currentLine = scanner.nextLine(); + products.add(initProductThat(currentLine)); + } + + return new Stock(products); + } + + private Product initProductThat(String line) { + Validator.checkProductInitLine(line); + List<String> parameters = List.of(line.split(",")); + ProductParameter productParameter = new ProductParameter(parameters); + Promotion promotion = findPromotionByName(productParameter.getPromotionName()); + return new Product(productParameter, promotion); + } + + private Promotion findPromotionByName(String promotionName) { + Optional<Promotion> promotion = promotions.findPromotionByName(promotionName); + return promotion.orElse(null); + } +}
Java
์‚ฌ์†Œํ•œ๊ฑฐ๊ธด ํ•˜์ง€๋งŒ `","` ์ด๊ฑฐ๋ณด๋‹ค๋Š” ์ƒ์ˆ˜๋กœ ๋ถ„๋ฆฌํ•ด ์–ด๋–ค ๊ตฌ๋ถ„์ž์ธ์ง€ ํ‘œํ˜„ํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,120 @@ +package store.view; + +import java.util.List; +import store.domain.product.Product; +import store.domain.receipt.BuyItem; +import store.domain.receipt.FreeItem; +import store.domain.receipt.Receipt; +import store.messages.ReceiptForm; +import store.messages.StoreMessage; + +class OutputView { + protected void printGreetingMessage() { + System.out.println(StoreMessage.GREETING.getMessage()); + } + + protected void printContinueShoppingMessage() { + System.out.println(StoreMessage.ASK_CONTINUE_SHOPPING.getMessage()); + } + + protected void printReceipt(Receipt receipt) { + printReceiptHeader(); + printReceiptItems(receipt); + printReceiptFinals(receipt); + } + + private void printReceiptHeader() { + newLine(); + System.out.println(ReceiptForm.HEADER.getMessage()); + System.out.printf(ReceiptForm.TITLES.getMessage(), ReceiptForm.WORD_ITEM_NAME.getMessage(), + ReceiptForm.WORD_ITEM_QUANTITY.getMessage(), ReceiptForm.WORD_ITEM_PRICE.getMessage()); + } + + private void printReceiptItems(Receipt receipt) { + // ๊ตฌ๋งคํ•œ ์ƒํ’ˆ ์ถœ๋ ฅ + for (BuyItem item : receipt.getBuyItems()) { + System.out.printf(ReceiptForm.BUY_ITEMS.getMessage(), item.getName(), item.getQuantity(), + item.getTotalPrice()); + } + if (receipt.hasFreeItem()) { + System.out.println(ReceiptForm.PROMOTION_DIVIDER.getMessage()); + // ์ฆ์ • ์ƒํ’ˆ ์ถœ๋ ฅ + for (FreeItem item : receipt.getFreeItems()) { + System.out.printf(ReceiptForm.PROMOTION_ITEMS.getMessage(), item.getName(), item.getQuantity()); + } + } + } + + private void printReceiptFinals(Receipt receipt) { + System.out.println(ReceiptForm.FINAL_DIVIDER.getMessage()); + // ์ด ๊ตฌ๋งค์•ก, ํ–‰์‚ฌํ• ์ธ, ๋ฉค๋ฒ„์‹ญ ํ• ์ธ, ๋‚ด์‹ค ๋ˆ ์ถœ๋ ฅ + System.out.printf(ReceiptForm.TOTAL_PRICE.getMessage(), ReceiptForm.WORD_TOTAL_PRICE.getMessage(), + receipt.getTotalQuantity(), receipt.getTotalPrice()); + System.out.printf(ReceiptForm.PROMOTION_DISCOUNT.getMessage(), ReceiptForm.WORD_PROMOTION_DISCOUNT.getMessage(), + receipt.getTotalPromotionDiscount()); + System.out.printf(ReceiptForm.MEMBERSHIP_DISCOUNT.getMessage(), + ReceiptForm.WORD_MEMBERSHIP_DISCOUNT.getMessage(), receipt.getMembershipDiscount()); + System.out.printf(ReceiptForm.FINAL_PRICE.getMessage(), ReceiptForm.WORD_FINAL_PRICE.getMessage(), + receipt.getFinalPrice()); + newLine(); + } + + protected void printNoReceiptNotice() { + System.out.println(StoreMessage.NO_PURCHASE_NOTICE.getMessage()); + } + + protected void printBuyRequestMessage() { + newLine(); + System.out.println(StoreMessage.BUY_REQUEST.getMessage()); + } + + protected void printStockStatus(List<Product> products) { + printStockNoticeMessage(); + printStockItems(products); + } + + private void printStockItems(List<Product> products) { + newLine(); + for (Product product : products) { + if (product.getQuantity() != 0) { + System.out.printf(StoreMessage.STOCK_STATUS.getMessage(), product.getName(), product.getPrice(), + product.getQuantity(), + product.getPromotionName()); + continue; + } + System.out.printf(StoreMessage.STOCK_STATUS_NO_STOCK.getMessage(), product.getName(), product.getPrice(), + product.getPromotionName()); + } + System.out.flush(); + } + + protected void printFreePromotionNotice(String itemName, int freeItemCount) { + newLine(); + System.out.printf(StoreMessage.ASK_FREE_PROMOTION.getMessage(), itemName, freeItemCount); + System.out.flush(); + } + + protected void printInsufficientPromotionNotice(String itemName, int notAppliedItemCount) { + newLine(); + System.out.printf(StoreMessage.ASK_INSUFFICIENT_PROMOTION.getMessage(), itemName, notAppliedItemCount); + System.out.flush(); + } + + protected void printMembershipDiscountNotice() { + newLine(); + System.out.println(StoreMessage.ASK_MEMBERSHIP_DISCOUNT.getMessage()); + } + + private void printStockNoticeMessage() { + System.out.println(StoreMessage.STOCK_NOTICE.getMessage()); + } + + protected void printErrorMessage(String errorMessage) { + newLine(); + System.out.println(errorMessage); + } + + protected void newLine() { + System.out.println(); + } +}
Java
static ์œผ๋กœ ์„ ์–ธํ•˜๋ฉด ๋กœ์ง์„ ๊ฐ„์†Œํ™”ํ•  ์ˆ˜ ์žˆ์–ด์š”! ์™€์ผ๋“œ ์นด๋“œ ์‚ฌ์šฉ์€ ์ฃผ์˜ํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค!
@@ -1 +1,90 @@ # java-convenience-store-precourse +## ํ”„๋กœ์ ํŠธ ์„ค๋ช… +๊ตฌ๋งค์ž์˜ ํ• ์ธ ํ˜œํƒ๊ณผ ์žฌ๊ณ  ์ƒํ™ฉ์„ ๊ณ ๋ คํ•˜์—ฌ ์ตœ์ข… ๊ฒฐ์ œ ๊ธˆ์•ก์„ ๊ณ„์‚ฐํ•˜๊ณ  ์•ˆ๋‚ดํ•˜๋Š” ๊ฒฐ์ œ ์‹œ์Šคํ…œ์„ ๊ตฌํ˜„ํ•˜๋Š” ๊ณผ์ œ์ž…๋‹ˆ๋‹ค. + +์‚ฌ์šฉ์ž๊ฐ€ ์ž…๋ ฅํ•œ ์ƒํ’ˆ๋ณ„ ๊ฐ€๊ฒฉ๊ณผ ์ˆ˜๋Ÿ‰์„ ๊ณฑํ•˜์—ฌ ๊ณ„์‚ฐํ•˜๊ณ , ์ตœ์ข… ๊ฒฐ์ œ ๊ธˆ์•ก์„ ๊ณ„์‚ฐํ•˜์—ฌ ์˜์ˆ˜์ฆ์„ ์ถœ๋ ฅํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. +๊ฐ ์ƒํ’ˆ์˜ ์žฌ๊ณ ๋ฅผ ๊ณ ๋ คํ•˜์—ฌ ๊ฒฐ์ œ ๊ฐ€๋Šฅ ์—ฌ๋ถ€๋ฅผ ํŒŒ์•…ํ•ด์•ผ ํ•˜๊ณ , ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋˜์–ด ์žˆ๋Š” ์ƒํ’ˆ๋“ค์ด ์žˆ์Šต๋‹ˆ๋‹ค. +ํ”„๋กœ๋ชจ์…˜์€ N๊ฐœ ๊ตฌ๋งค ์‹œ 1๊ฐœ ๋ฌด๋ฃŒ ์ฆ์ •์˜ ํ˜•ํƒœ๋กœ ์ง„ํ–‰๋˜๊ณ , ์˜ค๋Š˜ ๋‚ ์งœ๊ฐ€ ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„ ๋‚ด๋ผ๋ฉด ํ• ์ธ์„ ์ ์šฉํ•ฉ๋‹ˆ๋‹ค. +๋ฉค๋ฒ„์‹ญ ํšŒ์›์€ ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋˜์ง€ ์•Š์€ ๊ธˆ์•ก์˜ 30%๋ฅผ ํ• ์ธ๋ฐ›์Šต๋‹ˆ๋‹ค. ์ตœ๋Œ€ ํ• ์ธ ํ•œ๋„๋Š” 8,000์›์ž…๋‹ˆ๋‹ค. +์˜์ˆ˜์ฆ์€ ๊ณ ๊ฐ์˜ ๊ตฌ๋งค ๋‚ด์—ญ๊ณผ ํ• ์ธ์„ ์š”์•ฝํ•˜์—ฌ ๋ณด๊ธฐ ์ข‹๊ฒŒ ์ถœ๋ ฅํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. + +<br> + +## ๊ธฐ๋Šฅ ์š”๊ตฌ ์‚ฌํ•ญ์— ๊ธฐ์žฌ๋˜์ง€ ์•Š์•„์„œ ์Šค์Šค๋กœ ํŒ๋‹จํ•œ ๋‚ด์šฉ +์ด๋ฒˆ ๊ณผ์ œ๋Š” ๊ธฐ๋Šฅ ์š”๊ตฌ ์‚ฌํ•ญ์— ๊ธฐ์žฌ๋˜์ง€ ์•Š์€ ์• ๋งคํ•œ ๋‚ด์šฉ๋“ค์ด ๊ฝค ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค. +์ด์— ๋Œ€ํ•ด ์Šค์Šค๋กœ ํŒ๋‹จํ•œ ์š”๊ตฌ ์‚ฌํ•ญ์„ ์•Œ๋ ค๋“œ๋ฆฝ๋‹ˆ๋‹ค. + +1. ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„์ด ์•„์ง ์‹œ์ž‘๋˜์ง€ ์•Š์•˜๊ฑฐ๋‚˜ ์ด๋ฏธ ์ข…๋ฃŒ๋˜์—ˆ๋‹ค๋ฉด, ํ•ด๋‹น ์ƒํ’ˆ์€ ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋˜์ง€ ์•Š์€ ์ผ๋ฐ˜ ์ƒํ’ˆ์œผ๋กœ ์ทจ๊ธ‰๋˜๋Š” ๊ฒƒ์ด์ง€ ์žฌ๊ณ  ์ž์ฒด๊ฐ€ ์‚ฌ๋ผ์ง€์ง„ ์•Š์Šต๋‹ˆ๋‹ค. ์ฆ‰ ์ผ๋ฐ˜ ์žฌ๊ณ ๋กœ ์ทจ๊ธ‰ํ•ฉ๋‹ˆ๋‹ค. +2. ๋ฉค๋ฒ„์‹ญ ํšŒ์›์€ ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ  ์ƒํ’ˆ์˜ ์ด ๊ตฌ๋งค๊ฐ€๋ฅผ ์ œ์™ธํ•œ ๊ตฌ๋งค ๋น„์šฉ์˜ 30%๋ฅผ ํ• ์ธ๋ฐ›์Šต๋‹ˆ๋‹ค. +3. ํ”„๋กœ๋ชจ์…˜ 2+1 ์ฝœ๋ผ๊ฐ€ 7๊ฐœ ์žˆ๊ณ , ์‚ฌ์šฉ์ž๊ฐ€ 7๊ฐœ๋ฅผ ๊ตฌ๋งคํ•˜๊ธธ ์›ํ•œ๋‹ค๋ฉด ์‹ค์ œ๋กœ ํ”„๋กœ๋ชจ์…˜์„ ์ ์šฉ๋ฐ›์„ ์ˆ˜ ์žˆ๋Š” ์ฝœ๋ผ๋Š” 6๊ฐœ๊นŒ์ง€์ด์ง€๋งŒ, ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๊ฐ€ ๋ถ€์กฑํ•œ ๊ฒƒ์€ ์•„๋‹ˆ๊ธฐ์— 7๊ฐœ๋ฅผ ๋ชจ๋‘ ๊ตฌ๋งคํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. (์šฐ์•„ํ•œํ…Œํฌ์ฝ”์Šค์˜ ์˜ˆ์‹œ๋ฅผ ์ฐธ๊ณ ํ•˜๋ฉด, ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๊ฐ€ ๋ถ€์กฑํ•˜์—ฌ ์ผ๋ฐ˜ ์žฌ๊ณ ๊นŒ์ง€ ๊ตฌ๋งคํ•ด์•ผ ํ•˜๋Š” ์ƒํ™ฉ์—์„œ๋งŒ ํ”„๋กœ๋ชจ์…˜์ด ๋ฏธ์ ์šฉ ๋˜๋Š” ์ƒํ’ˆ์— ๋Œ€ํ•ด์„œ ์•ˆ๋‚ด๋ฅผ ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด์„œ ํ”„๋กœ๋ชจ์…˜ 2+1 ์ฝœ๋ผ๊ฐ€ 10๊ฐœ ์žˆ๊ณ , ์ผ๋ฐ˜ ์žฌ๊ณ ์˜ ์ฝœ๋ผ๊ฐ€ 10๊ฐœ ์žˆ๋Š” ์ƒํ™ฉ์—์„œ ์‚ฌ์šฉ์ž๊ฐ€ 12๊ฐœ๋ฅผ ๊ตฌ๋งคํ•˜๋ ค๊ณ  ํ•œ๋‹ค๋ฉด, ํ”„๋กœ๋ชจ์…˜์„ ์ ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์‹ค์ œ ์žฌ๊ณ  ๊ฐœ์ˆ˜๋Š” 9๊ฐœ ์ด๋ฏ€๋กœ 3๊ฐœ์— ๋Œ€ํ•ด ํ”„๋กœ๋ชจ์…˜ ๋ฏธ์ ์šฉ ์•ˆ๋‚ด๋ฅผ ํ•ฉ๋‹ˆ๋‹ค) +4. ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋œ ๋ชจ๋“  ์ƒํ’ˆ์€ ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋˜์ง€ ์•Š์€ ๋ฒ„์ „์˜ ์ƒํ’ˆ ์ •๋ณด๋„ ํ‘œ์‹œํ•ด์•ผ ํ•˜๊ณ , ํ”„๋กœ๋ชจ์…˜ ๋ฏธ์ ์šฉ ์ƒํ’ˆ์ด ์กด์žฌํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด "์žฌ๊ณ  ์—†์Œ" ์„ ํ‘œ์‹œํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. + +<br> + +## ์„ค๊ณ„ ๊ณผ์ • +๊ฐ์ฒด์ง€ํ–ฅ ์„ค๊ณ„์— ์žˆ์–ด์„œ ๊ฐ€์žฅ ์ค‘์š”ํ•œ ๊ฒƒ์€ ํ˜‘๋ ฅ์„ ์œ„ํ•ด ์–ด๋–ค ์ฑ…์ž„๊ณผ ์—ญํ• ์ด ํ•„์š”ํ•œ์ง€ ์ดํ•ดํ•˜๋Š” ๊ฒƒ์ด๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. +๋”ฐ๋ผ์„œ ์„ค๊ณ„์˜ ๋ฐฉํ–ฅ์„ ์žก๊ธฐ ์œ„ํ•ด ํ•„์š”ํ•œ ์—ญํ• ๊ณผ ์ฑ…์ž„ ๊ทธ๋ฆฌ๊ณ  ๋ฉ”์‹œ์ง€๋ฅผ ์ •๋ฆฌํ•ด ๋ดค์Šต๋‹ˆ๋‹ค. +์ดํ›„ ์ •๋ฆฌํ•œ ๋‚ด์šฉ์„ ํ†ตํ•ด ๋„์ถœํ•œ ๋Œ€๋žต์ ์ธ ๊ทธ๋ฆผ์„ ์ฐธ๊ณ ํ•ด์„œ ๊ตฌํ˜„ํ•  ๊ธฐ๋Šฅ ๋ชฉ๋ก์„ ํ•˜๋‹จ์— ์š”์•ฝํ–ˆ์Šต๋‹ˆ๋‹ค. + + +> ์ดํ•ดํ•œ ๊ณผ์ œ ๋‚ด์šฉ์„ ๋Œ€๋žต์ ์œผ๋กœ ์ •๋ฆฌํ•˜๋Š” ๊ฒƒ์€ ํ•„์š”ํ•œ ์—ญํ• ๊ณผ ์ฑ…์ž„์„ ์ดํ•ดํ•˜๋Š” ๋ฐ์— ๋„์›€์ด ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. +> ์ด๋ ‡๊ฒŒ ์ •๋ฆฌํ•œ ๋‚ด์šฉ์—์„œ ์˜๊ฐ์„ ๋ฐ›์•„ ๊ตฌํ˜„ํ•  ๊ธฐ๋Šฅ ๋ชฉ๋ก์„ ๋Œ€๋žต์ ์œผ๋กœ๋‚˜๋งˆ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค. +> ๋ฌผ๋ก  ๊ตฌํ˜„ ์ค‘ ๊ณ„ํšํ–ˆ๋˜ ๋‚ด์šฉ์ด ํ‹€์–ด์งˆ ์ˆ˜ ์žˆ์ง€๋งŒ, ํ”„๋กœ์ ํŠธ๋ฅผ ์‹œ์ž‘ํ•˜๋Š” ๋ฐ์— ๋„์›€์ด ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. + +<br> + +### ํ•„์š”ํ•œ ์—ญํ•  ๋ฐ ๊ธฐ๋Šฅ +- [x] ์ƒํ’ˆ์˜ ์ •๋ณด(์ƒํ’ˆ๋ช…๊ณผ ๊ฐ€๊ฒฉ)์„ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ์—ญํ• ์ด ์žˆ์–ด์•ผ ํ•œ๋‹ค. +- [x] ์ƒํ’ˆ๋ณ„ ์žฌ๊ณ  ์ •๋ณด๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ์—ญํ• ์ด ์žˆ์–ด์•ผ ํ•œ๋‹ค. +- [x] ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ๊ณ ๋ คํ•˜์—ฌ ๊ฒฐ์ œ ๊ฐ€๋Šฅ ์—ฌ๋ถ€๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์•ผ ํ•œ๋‹ค. +- [x] ์ƒํ’ˆ์ด ๊ตฌ์ž…๋  ๋•Œ๋งˆ๋‹ค, ๊ฒฐ์ œ๋œ ์ˆ˜๋Ÿ‰๋งŒํผ ํ•ด๋‹น ์ƒํ’ˆ์˜ ์žฌ๊ณ ์—์„œ ์ฐจ๊ฐํ•ด์•ผ ํ•œ๋‹ค. +- [x] ์ƒํ’ˆ์— ํ”„๋กœ๋ชจ์…˜์„ ์ ์šฉํ•  ์ˆ˜ ์žˆ์–ด์•ผ ํ•œ๋‹ค. ์˜ค๋Š˜ ๋‚ ์งœ๊ฐ€ ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„์ธ ๊ฒฝ์šฐ์—๋งŒ ํ• ์ธ์„ ์ ์šฉํ•ด์•ผ ํ•œ๋‹ค. +- [x] ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„ ์ค‘์ด๋ผ๋ฉด ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๋ฅผ ์šฐ์„ ์ ์œผ๋กœ ์ฐจ๊ฐํ•ด์•ผ ํ•œ๋‹ค. +- [x] ๋ฉค๋ฒ„์‰ฝ ํšŒ์›์€ ํ”„๋กœ๋ชจ์…˜ ๋ฏธ์ ์šฉ ๊ธˆ์•ก์˜ 30%๋ฅผ ํ• ์ธ๋ฐ›๋Š”๋‹ค. +- [x] ๋ฉค๋ฒ„์‰ฝ ํ• ์ธ์˜ ์ตœ๋Œ€ ํ•œ๋„๋Š” 8,000์›์ด๋‹ค. +- [x] ์˜์ˆ˜์ฆ ๊ธฐ๋Šฅ์ด ํ•„์š”ํ•˜๋‹ค. + + +### ๋ฉ”์‹œ์ง€ ์ •๋ฆฌ +- [x] ํ™˜์˜ ๋ฌธ๊ตฌ๋ฅผ ์ถœ๋ ฅํ•˜๋ผ -> (์ถœ๋ ฅ ์—ญํ• ) -> OutputView +- [x] ์‚ฌ์šฉ์ž์—๊ฒŒ ์ƒํ’ˆ์˜ ๊ฐ€๊ฒฉ๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅ๋ฐ›์•„๋ผ -> (์ž…๋ ฅ ์—ญํ• ) -> InputView +- [x] ์ƒํ’ˆ ์žฌ๊ณ ๋ฅผ ์ดˆ๊ธฐํ™”ํ•˜๋ผ -> (ํŒŒ์ผ ์ž…์ถœ๋ ฅํ•ด์„œ ์žฌ๊ณ  ์ดˆ๊ธฐํ™”ํ•˜๋Š” ์—ญํ• ) -> StoreInitializer +- [x] ์ƒํ’ˆ ์žฌ๊ณ ๋ฅผ ์ถœ๋ ฅํ•˜๋ผ -> OutputView -> (์ƒํ’ˆ ์žฌ๊ณ ๋ฅผ ๊ฐ–๊ณ ์žˆ๋Š” ์—ญํ• ) -> StoreStock +- [x] ๊ฒฐ์ œ ๊ฐ€๋Šฅ ์—ฌ๋ถ€๋ฅผ ํŒŒ์•…ํ•˜๋ผ -> (์ƒํ’ˆ ์žฌ๊ณ ๋ฅผ ๊ฐ–๊ณ ์žˆ๋Š” ์—ญํ• ) -> StoreStock +- [x] ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์ธ์ง€ ํ™•์ธํ•˜๋ผ -> (์ƒํ’ˆ ์—ญํ• ) -> StoreItem +- [x] ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๊ฐ€ ์ถฉ๋ถ„ํ•œ์ง€ ํŒŒ์•…ํ•˜๋ผ -> (์ƒํ’ˆ ์—ญํ• ) -> StoreItem + + +<br> + + +## ๊ตฌํ˜„ํ•  ๊ธฐ๋Šฅ ๋ชฉ๋ก +### 1. ์ถœ๋ ฅ ์—ญํ•  +- [x] ์ถœ๋ ฅ ์—ญํ• ์˜ ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ ๋‹ค +- [x] ํ™˜์˜ ๋ฌธ๊ตฌ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๊ธฐ๋Šฅ +- [x] ์žฌ๊ณ  ์ •๋ณด๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๊ธฐ๋Šฅ +- [x] ํ”„๋กฌํ”„ํŠธ ๋ฉ”์‹œ์ง€๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๊ธฐ๋Šฅ +- [x] ์˜์ˆ˜์ฆ ๋‚ด์šฉ์„ ์ถœ๋ ฅํ•˜๋Š” ๊ธฐ๋Šฅ + +### 2. ์ž…๋ ฅ ์—ญํ•  +- [x] ์ž…๋ ฅ ์—ญํ• ์˜ ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ ๋‹ค +- [x] ์‚ฌ์šฉ์ž์—๊ฒŒ ๊ตฌ๋งคํ•  ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅ๋ฐ›๋Š” ๊ธฐ๋Šฅ +- [x] Y/N ํ˜•ํƒœ๋กœ ์ž…๋ ฅ๋ฐ›๋Š” ๊ธฐ๋Šฅ +- [x] ์ž…๋ ฅ ๊ฐ’์ด ์ž˜๋ชป๋˜์—ˆ์„ ๊ฒฝ์šฐ ์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€์™€ ํ•จ๊ป˜ ์žฌ์ž…๋ ฅ ๋ฐ›๋Š” ๊ธฐ๋Šฅ + +### 3. ํŒŒ์ผ ์ž…์ถœ๋ ฅ ์—ญํ•  +- [x] ํŒŒ์ผ ์ž…์ถœ๋ ฅ ์—ญํ• ์˜ ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ ๋‹ค +- [x] .md ํŒŒ์ผ์„ ์ฝ์–ด์„œ ์ƒํ’ˆ ์žฌ๊ณ ๋ฅผ ์ดˆ๊ธฐํ™”ํ•˜๋Š” ๊ธฐ๋Šฅ + +### 4. ์ƒํ’ˆ ์—ญํ•  +- [x] ์ƒํ’ˆ์˜ ์ •๋ณด(์ƒํ’ˆ๋ช…๊ณผ ๊ฐ€๊ฒฉ ๋“ฑ)์„ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ ๋‹ค +- [x] ์ƒํ’ˆ์— ํ”„๋กœ๋ชจ์…˜ ์ •๋ณด๋ฅผ ํฌํ•จํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ์„ ๋งŒ๋“ ๋‹ค + +### 5. ์žฌ๊ณ  ์—ญํ•  +- [x] ์ƒํ’ˆ์˜ ์ •๋ณด๋“ค์„ ๊ฐ€์ง€๊ณ , ์žฌ๊ณ  ์—ญํ• ์„ ํ•˜๋Š” ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ ๋‹ค +- [x] ์žฌ๊ณ ์—์„œ ํŠน์ • ์ƒํ’ˆ์„ ์ฐพ๋Š” ๊ธฐ๋Šฅ +- [x] ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์ธ์ง€, ๋น„ ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์ธ์ง€ ๊ตฌ๋ถ„ํ•˜๋Š” ๊ธฐ๋Šฅ + +### 6. ์˜์ˆ˜์ฆ ์—ญํ•  +- [x] ์˜์ˆ˜์ฆ ์—ญํ• ์˜ ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ ๋‹ค +- [x] ๊ตฌ์ž… ๋‚ด์—ญ์„ ์ž…๋ ฅ๋ฐ›์•„์„œ ์ €์žฅํ•˜๋Š” ๊ธฐ๋Šฅ \ No newline at end of file
Unknown
๊ถ๊ธˆํ•œ ์ ์ด ์žˆ์Šต๋‹ˆ๋‹ค! ํ”„๋กœ๊ทธ๋žจ ๋กœ์ง์„ ๊ตฌ์„ฑํ•  ๋•Œ, ์ƒ์„ธํ•œ ๋ช…์„ธ์„œ๊ฐ€ ์ค‘์š”ํ•˜๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ํ˜น์‹œ, ์ž‘์„ฑํ•˜์‹  ๋ฌธ์„œ๋กœ๋„ ์ถฉ๋ถ„ํ•œ ํ”„๋กœ๊ทธ๋žจ ๊ตฌ์„ฑ์— ๋ฌธ์ œ๊ฐ€ ์—†์œผ์‹ ๊ฐ€์š”!? ๊ดœ์ฐฎ์œผ์‹œ๋‹ค๋ฉด, ๋ฌธ์ œ ์ ‘๊ทผ ๋ฐฉ๋ฒ•์ด ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค. ๋ณด๊ณ  ๋ฐฐ์šฐ๊ณ  ์‹ถ์–ด์„œ.. ํ•˜ํ•˜ ๐Ÿคฃ
@@ -0,0 +1,63 @@ +package store; + +import store.domain.Stock; +import store.domain.receipt.Receipt; +import store.domain.order.OrderItems; +import store.view.View; + +public class StoreController { + private final StoreService storeService; + private final Stock stock; + + public StoreController(StoreService storeService, Stock stock) { + this.storeService = storeService; + this.stock = stock; + } + + public void run() { + do { + runStoreProcess(); + } while (askContinueShopping()); + } + + private void runStoreProcess() { + printGreetingMessage(); + printStockStatus(stock); + OrderItems orderItems = getOrderItems(); + try { + Receipt receipt = proceedPurchase(orderItems); + printReceipt(receipt); + } catch (Exception e) { + printErrorMessage(e.getMessage()); + } + } + + private void printGreetingMessage() { + View.getInstance().printGreetingMessage(); + } + + private void printStockStatus(Stock stock) { + View.getInstance().printStockStatus(stock.getProducts()); + } + + private OrderItems getOrderItems() { + String input = View.getInstance().promptBuyItems(); + return storeService.getOrderItems(input); + } + + private Receipt proceedPurchase(OrderItems orderItems) { + return storeService.proceedPurchase(stock, orderItems); + } + + private void printReceipt(Receipt receipt) { + View.getInstance().printReceipt(receipt); + } + + private boolean askContinueShopping() { + return View.getInstance().promptContinueShopping(); + } + + private void printErrorMessage(String errorMessage) { + View.getInstance().printErrorMessage(errorMessage); + } +}
Java
์ง„์งœ ์ปจํŠธ๋กค๋Ÿฌ ๋„ˆ๋ฌด ๊น”๋”ํ•œ ๊ฑฐ ๊ฐ™์•„์š”. ๊ฐํƒ„ํ•ฉ๋‹ˆ๋‹ค.. ใ…  ๋ณด๊ณ  ๋ฐฐ์›๋‹ˆ๋‹ค.. ๐Ÿ‘
@@ -0,0 +1,35 @@ +package store.domain.order; + +/** + * OrderItem ์€ ์‚ฌ์šฉ์ž์˜ ์ฃผ๋ฌธ ๋‚ด์—ญ(์ฃผ๋ฌธํ•œ ์ƒํ’ˆ ์ด๋ฆ„, ์ˆ˜๋Ÿ‰)์„ ํ•„๋“œ๋กœ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. + * ์‚ฌ์šฉ์ž์˜ ์ฃผ๋ฌธ ๋‚ด์—ญ์„ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ์ฑ…์ž„์ž…๋‹ˆ๋‹ค. + */ +public class OrderItem { + private final String itemName; + private int quantity; + + public OrderItem(String itemName, int quantity) { + this.itemName = itemName; + this.quantity = quantity; + } + + public String getItemName() { + return itemName; + } + + public int getQuantity() { + return quantity; + } + + public void addQuantity(int amount) { + if (amount > 0) { + quantity += amount; + } + } + + public void subQuantity(int amount) { + if (amount > 0) { + quantity -= amount; + } + } +}
Java
์ €๋„ ์ด๋ถ€๋ถ„์ด ํฐ ๊ณ ๋ฏผ์ธ๋ฐ, ๊ณตํ†ต ํ”ผ๋“œ๋ฐฑ์— ๋ฉ”์‹œ์ง€์˜ ์˜๋ฏธ๊ฐ€ ์—†๋Š” get, set ์‚ฌ์šฉ์„ ์ž์ œํ•˜๋Š” ๋‚ด์šฉ์ด ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค. ์ด๋Ÿฐ ๊ฒฝ์šฐ์™€๋Š” ๋‹ค๋ฅธ ๋‚ด์šฉ์ผ๊นŒ์š”!?,, ์ €๋„ ๊ณ ๋ฏผ์ด ๊นŠ์–ด์„œ ใ… 
@@ -0,0 +1,82 @@ +package store.domain.order; + +import java.util.List; +import store.domain.product.Product; + +/** + * OrderStatus ํด๋ž˜์Šค๋Š” ์ฃผ๋ฌธ ์š”์ฒญ์— ๋Œ€ํ•œ ๊ฒฐ๊ณผ๋ฅผ ํ•„๋“œ๋กœ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. + * ๊ฒฐ์ œ์— ํ•„์š”ํ•œ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜๋Š” ๊ฒƒ์ด ์ฑ…์ž„์ž…๋‹ˆ๋‹ค. + */ +public class OrderStatus { + private List<Product> products; + private final boolean inStock; + private final boolean canGetFreeItem; + private final int promotionCanAppliedCount; + + public OrderStatus(List<Product> products, boolean inStock, boolean canGetFreeItem, int promotionCanAppliedCount) { + this.products = products; + this.inStock = inStock; + this.canGetFreeItem = canGetFreeItem; + this.promotionCanAppliedCount = promotionCanAppliedCount; + } + + public OrderStatus(List<Product> products, boolean inStock) { + this(products, inStock, false, 0); + } + + public Product getFirstProduct() { + return products.getFirst(); + } + + public void removeNormalProduct() { + products = products.stream().filter(Product::isPromotedProduct).toList(); + } + + public List<Product> getMultipleProducts() { + return products; + } + + public boolean isCanGetFreeItem() { + return canGetFreeItem; + } + + public boolean isProductFound() { + return !products.isEmpty(); + } + + public boolean isInStock() { + return inStock; + } + + public boolean hasPromotionProduct() { + return products.stream().anyMatch(Product::isPromotedProduct); + } + + public int getNotAppliedItemCount(int quantity) { + if (promotionCanAppliedCount < quantity) { + return quantity - promotionCanAppliedCount; + } + return 0; + } + + public boolean isMultipleStock() { + return products.size() == 2; + } + + public static OrderStatus inMultipleNormalProductStock(List<Product> products) { + return new OrderStatus(products, true); + } + + public static OrderStatus outOfStock(List<Product> products) { + return new OrderStatus(products, false); + } + + public static OrderStatus inOnlyNormalStock(Product product) { + return new OrderStatus(List.of(product), true); + } + + public static OrderStatus inOnlyPromotionStock(Product product, boolean canGetFreeItem, + int promotionCanAppliedCount) { + return new OrderStatus(List.of(product), true, canGetFreeItem, promotionCanAppliedCount); + } +}
Java
์ค„๋‚ด๋ฆผ์„ ์ ์šฉํ•˜๋Š” ๊ฒŒ ๊ฐ€๋…์„ฑ์ด ๋” ์ข‹์„ ๊ฑฐ ๊ฐ™์•„์š”! ```java products = products.stream(). filter(Product::isPromotedProduct) .toList(); ```
@@ -0,0 +1,31 @@ +package store.domain.receipt; + +/** + * FreeItem ์€ Receipt(์˜์ˆ˜์ฆ) ์ •๋ณด์— ์ €์žฅ๋˜๊ธฐ ์œ„ํ•ด ์กด์žฌํ•˜๋Š” ๊ฐ์ฒด๋กœ, ๊ฒฐ๋ก ์ ์œผ๋กœ ๋ฌด๋ฃŒ๋กœ ์ œ๊ณต๋ฐ›์€ ํ”„๋กœ๋ชจ์…˜ ํ’ˆ๋ชฉ์˜ ๊ฒฐ๊ณผ๋ฅผ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค. + * ๋ฌด๋ฃŒ๋กœ ์ œ๊ณต๋ฐ›์€ ํ”„๋กœ๋ชจ์…˜ ํ’ˆ๋ชฉ์˜ ์ •๋ณด๋ฅผ ์ €์žฅํ•˜๊ณ , ์ œ๊ณตํ•˜๋Š” ๊ฒƒ์ด ์ฑ…์ž„์ž…๋‹ˆ๋‹ค. + * + * @see Receipt + */ +public class FreeItem { + private final String name; + private final int quantity; + private final int totalDiscount; + + public FreeItem(String name, int quantity, int totalDiscount) { + this.name = name; + this.quantity = quantity; + this.totalDiscount = totalDiscount; + } + + public String getName() { + return name; + } + + public int getQuantity() { + return quantity; + } + + public int getTotalDiscount() { + return totalDiscount; + } +}
Java
์ด ๋ถ€๋ถ„์ด ์ €๋„ ๊ฐ€์žฅ ํฐ ๊ณ ๋ฏผ์ด์—ˆ์Šต๋‹ˆ๋‹ค. ํ˜„์žฌ ๊ฐ„๋‹จํ•œ ๋ฉ”์‹œ์ง€๋กœ get ํ•จ์ˆ˜๋กœ private ์ ‘๊ทผ์ œ์–ด์ž๋กœ ๋ช…์‹œ๋œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ค๋Š” ์—ญํ• ์„ ํ•ฉ๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ 3์ฐจ ๊ณตํ†ต ํ”ผ๋“œ๋ฐฑ์— ์ด์— ๋Œ€ํ•œ ์‚ฌ์šฉ์„ ์ง€์–‘ํ•˜๋ผ๋Š” ๋‚ด์šฉ์ด ์žˆ์—ˆ๋Š”๋ฐ ๊ทธ ๋ถ€๋ถ„์— ๋Œ€ํ•ด์„œ๋Š” ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,79 @@ +package store.util; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Scanner; +import store.domain.Stock; +import store.domain.promotion.Promotion; +import store.domain.promotion.PromotionParameter; +import store.domain.promotion.Promotions; +import store.domain.product.Product; +import store.domain.product.ProductParameter; + +/** + * StoreInitializer ๋Š” ์ƒํ’ˆ๊ณผ ํ”„๋กœ๋ชจ์…˜ ํŒŒ์ผ์„ ์ฝ๊ณ , ์žฌ๊ณ  ์ •๋ณด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์œ ํ‹ธ์„ฑ ํด๋ž˜์Šค์ž…๋‹ˆ๋‹ค. + */ +public class StoreInitializer { + private Promotions promotions; + + public Stock initStock() throws FileNotFoundException { + promotions = readPromotionFile(); + Stock stock = readProductFile(); + stock.generateNormalProductFromOnlyPromotionProduct(); + return stock; + } + + private Promotions readPromotionFile() throws FileNotFoundException { + Scanner scanner = new Scanner(new File("src/main/resources/promotions.md")); + Validator.checkPromotionFirstLine(scanner.nextLine()); + return readPromotionLines(scanner); + } + + private Promotions readPromotionLines(Scanner scanner) { + List<Promotion> promotions = new ArrayList<>(); + while (scanner.hasNext()) { + String currentLine = scanner.nextLine(); + promotions.add(initPromotionThat(currentLine)); + } + return new Promotions(promotions); + } + + private Promotion initPromotionThat(String line) { + Validator.checkPromotionInitLine(line); + List<String> parameters = List.of(line.split(",")); + PromotionParameter promotionParameter = new PromotionParameter(parameters); + return new Promotion(promotionParameter); + } + + private Stock readProductFile() throws FileNotFoundException { + Scanner scanner = new Scanner(new File("src/main/resources/products.md")); + Validator.checkProductFirstLine(scanner.nextLine()); + return readProductLines(scanner); + } + + private Stock readProductLines(Scanner scanner) { + List<Product> products = new ArrayList<>(); + while (scanner.hasNext()) { + String currentLine = scanner.nextLine(); + products.add(initProductThat(currentLine)); + } + + return new Stock(products); + } + + private Product initProductThat(String line) { + Validator.checkProductInitLine(line); + List<String> parameters = List.of(line.split(",")); + ProductParameter productParameter = new ProductParameter(parameters); + Promotion promotion = findPromotionByName(productParameter.getPromotionName()); + return new Product(productParameter, promotion); + } + + private Promotion findPromotionByName(String promotionName) { + Optional<Promotion> promotion = promotions.findPromotionByName(promotionName); + return promotion.orElse(null); + } +}
Java
System.exit()์„ ์‚ฌ์šฉํ•˜์ง€ ๋ง๋ผ๋Š” ์š”๊ตฌ์‚ฌํ•ญ์ด ์žˆ์—ˆ๊ณ , ํŒŒ์ผ ์–‘์‹ ๋ฌธ์ œ๋Š” ํ”„๋กœ๊ทธ๋žจ์˜ ์ •์ƒ์ ์ธ ์‹คํ–‰์ด ๋ถˆ๊ฐ€๋Šฅํ•œ ์˜ค๋ฅ˜์ด๊ธฐ์— main์—์„œ catchํ•ด์„œ ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ ํ”„๋กœ๊ทธ๋žจ์ด ์ข…๋ฃŒ๋˜๋„๋ก ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,79 @@ +package store.util; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Scanner; +import store.domain.Stock; +import store.domain.promotion.Promotion; +import store.domain.promotion.PromotionParameter; +import store.domain.promotion.Promotions; +import store.domain.product.Product; +import store.domain.product.ProductParameter; + +/** + * StoreInitializer ๋Š” ์ƒํ’ˆ๊ณผ ํ”„๋กœ๋ชจ์…˜ ํŒŒ์ผ์„ ์ฝ๊ณ , ์žฌ๊ณ  ์ •๋ณด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์œ ํ‹ธ์„ฑ ํด๋ž˜์Šค์ž…๋‹ˆ๋‹ค. + */ +public class StoreInitializer { + private Promotions promotions; + + public Stock initStock() throws FileNotFoundException { + promotions = readPromotionFile(); + Stock stock = readProductFile(); + stock.generateNormalProductFromOnlyPromotionProduct(); + return stock; + } + + private Promotions readPromotionFile() throws FileNotFoundException { + Scanner scanner = new Scanner(new File("src/main/resources/promotions.md")); + Validator.checkPromotionFirstLine(scanner.nextLine()); + return readPromotionLines(scanner); + } + + private Promotions readPromotionLines(Scanner scanner) { + List<Promotion> promotions = new ArrayList<>(); + while (scanner.hasNext()) { + String currentLine = scanner.nextLine(); + promotions.add(initPromotionThat(currentLine)); + } + return new Promotions(promotions); + } + + private Promotion initPromotionThat(String line) { + Validator.checkPromotionInitLine(line); + List<String> parameters = List.of(line.split(",")); + PromotionParameter promotionParameter = new PromotionParameter(parameters); + return new Promotion(promotionParameter); + } + + private Stock readProductFile() throws FileNotFoundException { + Scanner scanner = new Scanner(new File("src/main/resources/products.md")); + Validator.checkProductFirstLine(scanner.nextLine()); + return readProductLines(scanner); + } + + private Stock readProductLines(Scanner scanner) { + List<Product> products = new ArrayList<>(); + while (scanner.hasNext()) { + String currentLine = scanner.nextLine(); + products.add(initProductThat(currentLine)); + } + + return new Stock(products); + } + + private Product initProductThat(String line) { + Validator.checkProductInitLine(line); + List<String> parameters = List.of(line.split(",")); + ProductParameter productParameter = new ProductParameter(parameters); + Promotion promotion = findPromotionByName(productParameter.getPromotionName()); + return new Product(productParameter, promotion); + } + + private Promotion findPromotionByName(String promotionName) { + Optional<Promotion> promotion = promotions.findPromotionByName(promotionName); + return promotion.orElse(null); + } +}
Java
์ข‹์€ ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌ๋“œ๋ฆฝ๋‹ˆ๋‹ค !!
@@ -0,0 +1,116 @@ +package store; + +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import store.domain.Stock; +import store.domain.order.OrderItem; +import store.domain.order.OrderItems; +import store.domain.order.OrderStatus; +import store.domain.order.service.OrderService; +import store.domain.receipt.Receipt; +import store.messages.ErrorMessage; +import store.view.View; + +public class StoreService { + private static final String ORDER_ITEM_PATTERN_REGEX = "\\[(.+)-(\\d+)]"; + private static final int FREE_PROMOTION_ITEM_COUNT = 1; + + private final OrderService orderService; + + public StoreService(OrderService orderService) { + this.orderService = orderService; + } + + public OrderItems getOrderItems(String input) { + return makeOrderItems(getSeparatedInput(input)); + } + + public Receipt proceedPurchase(Stock stock, OrderItems orderItems) { + Receipt receipt = new Receipt(); + orderItems.getOrderItems().forEach(orderItem -> proceedOrder(stock, orderItem, receipt)); + checkApplyMembership(receipt); + + return receipt; + } + + private void proceedOrder(Stock stock, OrderItem orderItem, Receipt receipt) { + OrderStatus orderStatus = stock.getOrderStatus(orderItem); + checkOutOfStock(orderStatus); + confirmOrder(orderStatus, orderItem); + orderService.order(orderStatus, orderItem, receipt); + } + + private void checkOutOfStock(OrderStatus orderStatus) { + if (!orderStatus.isProductFound()) { + throw new NoSuchElementException(ErrorMessage.INVALID_PRODUCT_NAME.getMessage()); + } + if (!orderStatus.isInStock()) { + throw new IllegalStateException(ErrorMessage.OVER_STOCK.getMessage()); + } + } + + private void confirmOrder(OrderStatus orderStatus, OrderItem orderItem) { + addCanGetFreeItem(orderStatus, orderItem); + checkNotAppliedPromotionItem(orderStatus, orderItem); + } + + private void addCanGetFreeItem(OrderStatus orderStatus, OrderItem orderItem) { + if (orderStatus.isCanGetFreeItem()) { + boolean addFreeItem = View.getInstance() + .promptFreePromotion(orderItem.getItemName(), FREE_PROMOTION_ITEM_COUNT); + if (addFreeItem) { + orderItem.addQuantity(FREE_PROMOTION_ITEM_COUNT); + } + } + } + + private void checkNotAppliedPromotionItem(OrderStatus orderStatus, OrderItem orderItem) { + if (!(orderStatus.isMultipleStock() && orderStatus.hasPromotionProduct())) { + return; + } + + int notAppliedItemCount = orderStatus.getNotAppliedItemCount(orderItem.getQuantity()); + // ์ •๊ฐ€๋กœ ๊ฒฐ์ œํ•ด์•ผ ํ•˜๋Š” ์ˆ˜๋Ÿ‰์„ ์ œ์™ธํ•˜๋Š” ์˜ต์…˜์„ ์„ ํƒํ–ˆ๋‹ค๋ฉด, ๋น„ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์„ ํŒ๋งค ๋Œ€์ƒ์—์„œ ์‚ญ์ œํ•˜๊ณ  ์ฃผ๋ฌธ ๊ฐœ์ˆ˜๋ฅผ ๊ฐ์†Œ์‹œํ‚ด. + if (!askProceedWithNotPromotionItems(orderItem, notAppliedItemCount)) { + orderItem.subQuantity(notAppliedItemCount); + orderStatus.removeNormalProduct(); + } + } + + private boolean askProceedWithNotPromotionItems(OrderItem orderItem, int notAppliedItemCount) { + return View.getInstance() + .promptInsufficientPromotion(orderItem.getItemName(), notAppliedItemCount); + } + + private void checkApplyMembership(Receipt receipt) { + if (View.getInstance().promptMembershipDiscount()) { + receipt.applyMembershipDiscount(); + } + } + + private OrderItems makeOrderItems(List<String> separatedInputs) { + List<OrderItem> orderItems = new ArrayList<>(); + Pattern pattern = Pattern.compile(ORDER_ITEM_PATTERN_REGEX); + + for (String input : separatedInputs) { + Matcher matcher = pattern.matcher(input); + if (matcher.matches()) { + orderItems.add(makeOrderItem(matcher)); + } + } + return new OrderItems(orderItems); + } + + private OrderItem makeOrderItem(Matcher matcher) { + String name = matcher.group(1); + int quantity = Integer.parseInt(matcher.group(2)); + return new OrderItem(name, quantity); + } + + private List<String> getSeparatedInput(String input) { + return List.of(input.split(",")); + } +}
Java
์ข‹์€ ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌ๋“œ๋ฆฝ๋‹ˆ๋‹ค :) ํ•ด๋‹น ํ•จ์ˆ˜๊ฐ€ ํ•œ๋ฒˆ๋ฐ–์— ์‹คํ–‰ ์•ˆ๋œ๋‹ค๋Š” ์ด์œ ๋กœ ์ €๋ ‡๊ฒŒ ๋’€์—ˆ๋Š”๋ฐ, ์‚ฌ์‹ค ์ด๋Ÿฐ ์Šต๊ด€์€ ์ดํ›„์— ์ œ ์ฝ”๋“œ๋ฅผ ์ด์–ด์„œ ๊ฐœ๋ฐœํ•  ์ˆ˜๋„ ์žˆ์„ ์˜ˆ๋น„ ๊ฐœ๋ฐœ์ž์—๊ฒŒ ๋˜๊ฒŒ ์‹ค๋ก€์ธ ํ–‰๋™์ด๊ฒ ๋„ค์š”..!
@@ -0,0 +1,116 @@ +package store; + +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import store.domain.Stock; +import store.domain.order.OrderItem; +import store.domain.order.OrderItems; +import store.domain.order.OrderStatus; +import store.domain.order.service.OrderService; +import store.domain.receipt.Receipt; +import store.messages.ErrorMessage; +import store.view.View; + +public class StoreService { + private static final String ORDER_ITEM_PATTERN_REGEX = "\\[(.+)-(\\d+)]"; + private static final int FREE_PROMOTION_ITEM_COUNT = 1; + + private final OrderService orderService; + + public StoreService(OrderService orderService) { + this.orderService = orderService; + } + + public OrderItems getOrderItems(String input) { + return makeOrderItems(getSeparatedInput(input)); + } + + public Receipt proceedPurchase(Stock stock, OrderItems orderItems) { + Receipt receipt = new Receipt(); + orderItems.getOrderItems().forEach(orderItem -> proceedOrder(stock, orderItem, receipt)); + checkApplyMembership(receipt); + + return receipt; + } + + private void proceedOrder(Stock stock, OrderItem orderItem, Receipt receipt) { + OrderStatus orderStatus = stock.getOrderStatus(orderItem); + checkOutOfStock(orderStatus); + confirmOrder(orderStatus, orderItem); + orderService.order(orderStatus, orderItem, receipt); + } + + private void checkOutOfStock(OrderStatus orderStatus) { + if (!orderStatus.isProductFound()) { + throw new NoSuchElementException(ErrorMessage.INVALID_PRODUCT_NAME.getMessage()); + } + if (!orderStatus.isInStock()) { + throw new IllegalStateException(ErrorMessage.OVER_STOCK.getMessage()); + } + } + + private void confirmOrder(OrderStatus orderStatus, OrderItem orderItem) { + addCanGetFreeItem(orderStatus, orderItem); + checkNotAppliedPromotionItem(orderStatus, orderItem); + } + + private void addCanGetFreeItem(OrderStatus orderStatus, OrderItem orderItem) { + if (orderStatus.isCanGetFreeItem()) { + boolean addFreeItem = View.getInstance() + .promptFreePromotion(orderItem.getItemName(), FREE_PROMOTION_ITEM_COUNT); + if (addFreeItem) { + orderItem.addQuantity(FREE_PROMOTION_ITEM_COUNT); + } + } + } + + private void checkNotAppliedPromotionItem(OrderStatus orderStatus, OrderItem orderItem) { + if (!(orderStatus.isMultipleStock() && orderStatus.hasPromotionProduct())) { + return; + } + + int notAppliedItemCount = orderStatus.getNotAppliedItemCount(orderItem.getQuantity()); + // ์ •๊ฐ€๋กœ ๊ฒฐ์ œํ•ด์•ผ ํ•˜๋Š” ์ˆ˜๋Ÿ‰์„ ์ œ์™ธํ•˜๋Š” ์˜ต์…˜์„ ์„ ํƒํ–ˆ๋‹ค๋ฉด, ๋น„ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์„ ํŒ๋งค ๋Œ€์ƒ์—์„œ ์‚ญ์ œํ•˜๊ณ  ์ฃผ๋ฌธ ๊ฐœ์ˆ˜๋ฅผ ๊ฐ์†Œ์‹œํ‚ด. + if (!askProceedWithNotPromotionItems(orderItem, notAppliedItemCount)) { + orderItem.subQuantity(notAppliedItemCount); + orderStatus.removeNormalProduct(); + } + } + + private boolean askProceedWithNotPromotionItems(OrderItem orderItem, int notAppliedItemCount) { + return View.getInstance() + .promptInsufficientPromotion(orderItem.getItemName(), notAppliedItemCount); + } + + private void checkApplyMembership(Receipt receipt) { + if (View.getInstance().promptMembershipDiscount()) { + receipt.applyMembershipDiscount(); + } + } + + private OrderItems makeOrderItems(List<String> separatedInputs) { + List<OrderItem> orderItems = new ArrayList<>(); + Pattern pattern = Pattern.compile(ORDER_ITEM_PATTERN_REGEX); + + for (String input : separatedInputs) { + Matcher matcher = pattern.matcher(input); + if (matcher.matches()) { + orderItems.add(makeOrderItem(matcher)); + } + } + return new OrderItems(orderItems); + } + + private OrderItem makeOrderItem(Matcher matcher) { + String name = matcher.group(1); + int quantity = Integer.parseInt(matcher.group(2)); + return new OrderItem(name, quantity); + } + + private List<String> getSeparatedInput(String input) { + return List.of(input.split(",")); + } +}
Java
๋†“์นœ ๋ถ€๋ถ„์ด๋„ค์š”! ์งš์–ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :)
@@ -0,0 +1,158 @@ +package store.domain; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; +import store.domain.order.OrderItem; +import store.domain.order.OrderStatus; +import store.domain.product.Product; +import store.domain.product.ProductParameter; +import store.messages.ErrorMessage; + + +/** + * Stock ํด๋ž˜์Šค๋Š” ํŽธ์˜์ ์˜ ์ƒํ’ˆ ๋ชฉ๋ก(์žฌ๊ณ )์„ ํ•„๋“œ๋กœ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. + * OrderItem(์ฃผ๋ฌธ ๋‚ด์—ญ)์ด ๋“ค์–ด์™”์„ ๋•Œ ์žฌ๊ณ  ํ˜„ํ™ฉ์„ ํŒŒ์•…ํ•˜์—ฌ OrderStatus ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด ์ฑ…์ž„์ž…๋‹ˆ๋‹ค. + * + * @see OrderItem + * @see OrderStatus + */ +public class Stock { + private final List<Product> stock; + + public Stock(List<Product> stock) { + this.stock = stock; + } + + public List<Product> getProducts() { + return stock; + } + + /* generateNormalProductFromOnlyPromotionProduct() ๋ฉ”์„œ๋“œ์˜ ์กด์žฌ ์ด์œ  + * ์šฐ์•„ํ•œํ…Œํฌ์ฝ”์Šค์˜ ์‹คํ–‰ ๊ฒฐ๊ณผ ์˜ˆ์‹œ์— ๋”ฐ๋ฅด๋ฉด ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋œ ๋ชจ๋“  ์ƒํ’ˆ์€, ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋˜์ง€ ์•Š์€ ๋ฒ„์ „์˜ ์ƒํ’ˆ ์ •๋ณด๋„ ํ‘œ์‹œํ•ด์•ผ ํ•จ. + * ๋”ฐ๋ผ์„œ, ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋œ ์ƒํ’ˆ์— ๋Œ€ํ•ด์„œ ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋˜์ง€ ์•Š์€ ์ผ๋ฐ˜ ์ƒํ’ˆ์ด ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด ์ผ๋ฐ˜ ์ƒํ’ˆ์„ ์ƒ์„ฑํ•จ. + */ + public void generateNormalProductFromOnlyPromotionProduct() { + List<Product> onlyPromotionProducts = findOnlyPromotionProducts(stock); + for (Product product : onlyPromotionProducts) { + ProductParameter productParameter = new ProductParameter( + List.of(product.getName(), String.valueOf(product.getPrice()), "0", "null")); + insertProduct(new Product(productParameter, null)); + } + } + + public OrderStatus getOrderStatus(OrderItem orderItem) { + List<Product> foundProducts = findProductsByName(orderItem.getItemName()); + if (foundProducts.isEmpty()) { + return OrderStatus.outOfStock(foundProducts); + } + + return checkOrderAvailability(orderItem, findAvailableProductsByName(orderItem.getItemName())); + } + + private OrderStatus checkOrderAvailability(OrderItem orderItem, List<Product> foundAvailableProducts) { + if (foundAvailableProducts.isEmpty()) { + return OrderStatus.outOfStock(findProductsByName(orderItem.getItemName())); + } + if (foundAvailableProducts.size() == 1) { + return getOrderStatusWithSingleProduct(orderItem, foundAvailableProducts.getFirst()); + } + if (foundAvailableProducts.size() == 2) { + return getOrderStatusWithMultipleProducts(orderItem, foundAvailableProducts); + } + + throw new IllegalArgumentException(ErrorMessage.INVALID_PRODUCT_PROMOTIONS.getMessage()); + } + + private static OrderStatus getOrderStatusWithSingleProduct(OrderItem orderItem, Product product) { + if (!product.isStockAvailable(orderItem.getQuantity())) { + return OrderStatus.outOfStock(List.of(product)); + } + if (product.isPromotedProduct()) { + boolean canGetFreeItem = product.isCanGetFreeProduct(orderItem.getQuantity()); + int maxPromotionCanAppliedCount = product.getMaxAvailablePromotionQuantity(); + return OrderStatus.inOnlyPromotionStock(product, canGetFreeItem, maxPromotionCanAppliedCount); + } + + return OrderStatus.inOnlyNormalStock(product); + } + + private OrderStatus getOrderStatusWithMultipleProducts(OrderItem orderItem, List<Product> foundProducts) { + if (getAllQuantity(foundProducts) < orderItem.getQuantity()) { + return OrderStatus.outOfStock(foundProducts); + } + + if (hasPromotedProduct(foundProducts)) { + return checkMixedProductsSituation(orderItem, foundProducts); + } + + // ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋˜์ง€ ์•Š์€ ์ƒํ’ˆ๋งŒ 2๊ฐœ๋ผ๋ฉด + return OrderStatus.inMultipleNormalProductStock(foundProducts); + } + + private OrderStatus checkMixedProductsSituation(OrderItem orderItem, List<Product> foundProducts) { + Product promotedProduct = getPromotedProduct(foundProducts).get(); + if (promotedProduct.isStockAvailable(orderItem.getQuantity())) { // ํ”„๋กœ๋ชจ์…˜ ์ œํ’ˆ ์žฌ๊ณ ๋งŒ์œผ๋กœ ์ฒ˜๋ฆฌ ๊ฐ€๋Šฅํ•˜๋ฉด + boolean canGetFreeItem = promotedProduct.isCanGetFreeProduct(orderItem.getQuantity()); + int maxPromotionCanAppliedCount = promotedProduct.getMaxAvailablePromotionQuantity(); + return OrderStatus.inOnlyPromotionStock(promotedProduct, canGetFreeItem, maxPromotionCanAppliedCount); + } + + // ํ”„๋กœ๋ชจ์…˜ ์ œํ’ˆ์˜ ์žฌ๊ณ ๋งŒ์œผ๋กœ ์ฒ˜๋ฆฌ๊ฐ€ ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค๋ฉด, ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๋Š” ์ผ๋‹จ ๋‹ค ์“ฐ๊ณ , ๋‚˜๋จธ์ง€ ์–‘์€ ๋น„ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๋กœ ์ฒ˜๋ฆฌ + int maxPromotionCanAppliedCount = promotedProduct.getMaxAvailablePromotionQuantity(); + return new OrderStatus(foundProducts, true, false, maxPromotionCanAppliedCount); + } + + private boolean hasPromotedProduct(List<Product> products) { + return products.stream().anyMatch(Product::isPromotedProduct); + } + + private Optional<Product> getPromotedProduct(List<Product> products) { + return products.stream().filter(Product::isPromotedProduct).findFirst(); + } + + private int getAllQuantity(List<Product> products) { + return products.getFirst().getQuantity() + products.getLast().getQuantity(); + } + + private List<Product> findProductsByName(String productName) { + return stock.stream().filter(product -> Objects.equals(product.getName(), productName)).toList(); + } + + private List<Product> findAvailableProductsByName(String productName) { + return stock.stream().filter(product -> Objects.equals(product.getName(), productName)) + .filter(product -> product.getQuantity() > 0).toList(); + } + + private int findProductIndexByName(String productName) { + for (int i = 0; i < stock.size(); i++) { + if (stock.get(i).getName().equals(productName)) { + return i; + } + } + return -1; + } + + private void insertProduct(Product product) { + int index = findProductIndexByName(product.getName()); + if (index != -1) { + stock.add(index + 1, product); + return; + } + stock.add(product); + } + + private List<Product> findOnlyPromotionProducts(List<Product> products) { + Map<String, List<Product>> productByName = products.stream() + .collect(Collectors.groupingBy(Product::getName)); + + return productByName.values().stream() + .filter(productList -> productList.size() == 1) + .flatMap(Collection::stream) + .filter(Product::isPromotedProduct) + .collect(Collectors.toList()); + } +}
Java
์งš์–ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :)
@@ -0,0 +1,31 @@ +package store.domain.receipt; + +/** + * FreeItem ์€ Receipt(์˜์ˆ˜์ฆ) ์ •๋ณด์— ์ €์žฅ๋˜๊ธฐ ์œ„ํ•ด ์กด์žฌํ•˜๋Š” ๊ฐ์ฒด๋กœ, ๊ฒฐ๋ก ์ ์œผ๋กœ ๋ฌด๋ฃŒ๋กœ ์ œ๊ณต๋ฐ›์€ ํ”„๋กœ๋ชจ์…˜ ํ’ˆ๋ชฉ์˜ ๊ฒฐ๊ณผ๋ฅผ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค. + * ๋ฌด๋ฃŒ๋กœ ์ œ๊ณต๋ฐ›์€ ํ”„๋กœ๋ชจ์…˜ ํ’ˆ๋ชฉ์˜ ์ •๋ณด๋ฅผ ์ €์žฅํ•˜๊ณ , ์ œ๊ณตํ•˜๋Š” ๊ฒƒ์ด ์ฑ…์ž„์ž…๋‹ˆ๋‹ค. + * + * @see Receipt + */ +public class FreeItem { + private final String name; + private final int quantity; + private final int totalDiscount; + + public FreeItem(String name, int quantity, int totalDiscount) { + this.name = name; + this.quantity = quantity; + this.totalDiscount = totalDiscount; + } + + public String getName() { + return name; + } + + public int getQuantity() { + return quantity; + } + + public int getTotalDiscount() { + return totalDiscount; + } +}
Java
FreeItem์€ Receipt ๊ฐ์ฒด์˜ ๋ฐ์ดํ„ฐ ์ €์žฅ์†Œ ์ •๋„๋กœ๋งŒ ์‚ฌ์šฉ๋˜๋Š” ๊ฐ์ฒด์ด๊ธดํ•ฉ๋‹ˆ๋‹ค. ์ €๋Š” ํ˜„์žฌ๋กœ์ฌ ์ด ๋ฌธ์ œ๋ฅผ getter ์—†์ด ํ•ด๊ฒฐํ•˜๋Š” ๋งˆ๋•…ํ•œ ๋ฐฉ๋ฒ•์ด ๋– ์˜ค๋ฅด์ง€ ์•Š์Šต๋‹ˆ๋‹ค. 3์ฐจ ๊ณตํ†ต ํ”ผ๋“œ๋ฐฑ์˜ getter์„ ์ง€์–‘ํ•˜๋ผ๋Š” ๋‚ด์šฉ์€ ์•„๋งˆ ๋ฐ์ดํ„ฐ์™€ ๊ทธ ๋ฐ์ดํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋กœ์ง์„ ๊ฐ™์€ ๊ณณ์— ๋‘๋ผ๋Š” ๋ง์„ ๊ฐ•๋ ฅํ•˜๊ฒŒ ํ•™์Šต์‹œํ‚ค๊ธฐ ์œ„ํ•ด ํ•œ ๋ง์ด๋ผ๊ณ  ์ƒ๊ฐํ•˜๊ณ , ์•„์˜ˆ ์„ค๊ณ„ ๊ณผ์ •์—์„œ getter์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์„ ์ˆœ ์—†๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,82 @@ +package store.domain.order; + +import java.util.List; +import store.domain.product.Product; + +/** + * OrderStatus ํด๋ž˜์Šค๋Š” ์ฃผ๋ฌธ ์š”์ฒญ์— ๋Œ€ํ•œ ๊ฒฐ๊ณผ๋ฅผ ํ•„๋“œ๋กœ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. + * ๊ฒฐ์ œ์— ํ•„์š”ํ•œ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜๋Š” ๊ฒƒ์ด ์ฑ…์ž„์ž…๋‹ˆ๋‹ค. + */ +public class OrderStatus { + private List<Product> products; + private final boolean inStock; + private final boolean canGetFreeItem; + private final int promotionCanAppliedCount; + + public OrderStatus(List<Product> products, boolean inStock, boolean canGetFreeItem, int promotionCanAppliedCount) { + this.products = products; + this.inStock = inStock; + this.canGetFreeItem = canGetFreeItem; + this.promotionCanAppliedCount = promotionCanAppliedCount; + } + + public OrderStatus(List<Product> products, boolean inStock) { + this(products, inStock, false, 0); + } + + public Product getFirstProduct() { + return products.getFirst(); + } + + public void removeNormalProduct() { + products = products.stream().filter(Product::isPromotedProduct).toList(); + } + + public List<Product> getMultipleProducts() { + return products; + } + + public boolean isCanGetFreeItem() { + return canGetFreeItem; + } + + public boolean isProductFound() { + return !products.isEmpty(); + } + + public boolean isInStock() { + return inStock; + } + + public boolean hasPromotionProduct() { + return products.stream().anyMatch(Product::isPromotedProduct); + } + + public int getNotAppliedItemCount(int quantity) { + if (promotionCanAppliedCount < quantity) { + return quantity - promotionCanAppliedCount; + } + return 0; + } + + public boolean isMultipleStock() { + return products.size() == 2; + } + + public static OrderStatus inMultipleNormalProductStock(List<Product> products) { + return new OrderStatus(products, true); + } + + public static OrderStatus outOfStock(List<Product> products) { + return new OrderStatus(products, false); + } + + public static OrderStatus inOnlyNormalStock(Product product) { + return new OrderStatus(List.of(product), true); + } + + public static OrderStatus inOnlyPromotionStock(Product product, boolean canGetFreeItem, + int promotionCanAppliedCount) { + return new OrderStatus(List.of(product), true, canGetFreeItem, promotionCanAppliedCount); + } +}
Java
์ข‹์€ ํ”ผ๋“œ๋ฐฑ์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ค„ ๊ธธ์ด ์ œํ•œ์— ๋„๋‹ฌํ•˜์ง€ ์•Š์•˜๊ธฐ์— ๊ตณ์ด ๊ฐœํ–‰์„ ํ•˜์ง€ ์•Š์€๊ฒƒ์ธ๋ฐ, ์ด๋ ‡๊ฒŒ ์˜ˆ์‹œ๋ฅผ ๋ณด์—ฌ์ฃผ์‹œ๋‹ˆ .toList() ๊ฐ€ ํ•œ๋ˆˆ์— ๋ณด์ด๋Š” ๊ฒŒ ํ›จ์”ฌ ๊ฐ€๋…์„ฑ์ด ์ข‹์•„ ๋ณด์ด๋„ค์š”. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,35 @@ +package store.domain.order; + +/** + * OrderItem ์€ ์‚ฌ์šฉ์ž์˜ ์ฃผ๋ฌธ ๋‚ด์—ญ(์ฃผ๋ฌธํ•œ ์ƒํ’ˆ ์ด๋ฆ„, ์ˆ˜๋Ÿ‰)์„ ํ•„๋“œ๋กœ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. + * ์‚ฌ์šฉ์ž์˜ ์ฃผ๋ฌธ ๋‚ด์—ญ์„ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ์ฑ…์ž„์ž…๋‹ˆ๋‹ค. + */ +public class OrderItem { + private final String itemName; + private int quantity; + + public OrderItem(String itemName, int quantity) { + this.itemName = itemName; + this.quantity = quantity; + } + + public String getItemName() { + return itemName; + } + + public int getQuantity() { + return quantity; + } + + public void addQuantity(int amount) { + if (amount > 0) { + quantity += amount; + } + } + + public void subQuantity(int amount) { + if (amount > 0) { + quantity -= amount; + } + } +}
Java
์•„๋ž˜ ๋ง์”€๋“œ๋ฆฐ ๊ฒƒ๊ณผ ๊ฐ™์ด ๋ชจ๋“  ์„ค๊ณ„ ๊ณผ์ •์—์„œ get๊ณผ set์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์„ ์ˆœ ์—†๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ์ €๋„ ๊ณตํ†ต ํ”ผ๋“œ๋ฐฑ์„ ๋“ฃ๊ณ  ์‚ฌ์šฉํ•˜์ง€ ์•Š์œผ๋ ค๊ณ  ๋…ธ๋ ฅํ–ˆ์œผ๋‚˜, ๋งˆ๋•…ํ•œ ๋ฐฉ๋ฒ•์ด ๋– ์˜ค๋ฅด์ง€ ์•Š์•˜๊ณ  ๋ˆ„๊ตฐ๊ฐ€ ๋งˆ๋•…ํ•œ ๋ฐฉ๋ฒ•์„ ์•ˆ๋‹ค๋ฉด ์•Œ๋ ค์ฃผ๋ฉด ์ข‹๊ฒ ๋‹ค๋Š” ๊ฐ„์ ˆํ•œ ๋งˆ์Œ์ž…๋‹ˆ๋‹ค. ์•„๋งˆ ์šฐ์•„ํ•œํ…Œํฌ์ฝ”์Šค์—์„œ ๊ทธ์™€ ๊ฐ™์ด ๋งํ•œ๊ฒƒ์€ ๊ฐ์ฒด๋Š” ์ž๊ธฐ ์ž์‹ ์˜ ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•ด ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผ ํ•  ์ฑ…์ž„์ด ์žˆ๋Š”๋ฐ, get๊ณผ set์œผ๋กœ ๋‹ค๋ฅธ ๊ฐ์ฒด์—์„œ ๋ฐ์ดํ„ฐ ์›๋ณธ ์ž์ฒด๋ฅผ ์–ป๋„๋ก ๋งŒ๋“ค๋ฉด ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ๋ฅผ ์œ„์ž„ํ•˜๋Š” ๊ฒƒ๊ณผ ๊ฐ™๊ธฐ ๋•Œ๋ฌธ์—, ๊ฐ์ฒด์˜ ๋ณธ๋ถ„์„ ์žƒ์–ด๋ฒ„๋ฆฌ๊ธฐ ๋•Œ๋ฌธ์ด๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ๊ทธ๋ ‡๊ฒŒ ํ•ด์„ํ•ด๋ดค์„ ๋•Œ OrderItem์€ ๋‹จ์ˆœํžˆ ๋ฐ์ดํ„ฐ๋ฅผ ์ „๋‹ฌํ•˜๋Š” ๊ตฌ์กฐ์ฒด์ด์ง€, ์ž์‹ ์˜ ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•ด ์ฑ…์ž„์„ ์ง€๋Š” ๊ฐ์ฒด๋ผ๊ณ  ํ•  ์ˆ˜ ์—†์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋ชจ๋“  ํ”„๋กœ๊ทธ๋žจ์€ 100% ๊ฐ์ฒด ์ง€ํ–ฅ์œผ๋กœ ์ด๋ฃจ์–ด์ง€๊ธฐ ํž˜๋“ญ๋‹ˆ๋‹ค. ์‚ฌ์‹ค ์ €ํฌ๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜๋ฉด์„œ ๋‹ค์–‘ํ•œ ์„ค๊ณ„ ํŒจ๋Ÿฌ๋‹ค์ž„์„ ์•Œ๋งž๊ฒŒ ์ ์šฉํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. OrderItem ์ฒ˜๋Ÿผ ์‚ฌ์šฉ์ž์˜ ์ž…๋ ฅ์„ ์•„์ดํ…œ ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์œผ๋กœ ๋‚˜๋ˆ ์„œ ์ €์žฅํ•ด๋†“๋Š” ์šฉ๋„์˜ ๊ตฌ์กฐ๋Š” ์ œ๊ฐ€ ํ•œ ๋ฐฉ๋ฒ•์ฒ˜๋Ÿผ get, set์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ œ์ผ ํšจ์œจ์ ์ด๋ผ๊ณ  ์ƒ๊ฐํ•˜๊ณ , ์ด๊ฒƒ์„ ์ž์‹ ์˜ ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•ด ์ฑ…์ž„์ง€๊ณ  ๋ฐ์ดํ„ฐ์™€ ๋กœ์ง์ด ์‘์ง‘๋˜์–ด ์žˆ๋Š” ๊ฐ์ฒด๋กœ ์ „ํ™˜ํ•˜๋Š” ๊ฒƒ์€ ์˜คํžˆ๋ ค ํ”„๋กœ์ ํŠธ์˜ ๋ณต์žก์„ฑ์„ ์˜ฌ๋ฆฌ๊ณ  ์ง๊ด€์ ์ด์ง€ ์•Š์€ ์„ค๊ณ„๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ์šฐ์•„ํ•œํ…Œํฌ์ฝ”์Šค์—์„œ ์ œ์‹œํ•˜๋Š” ๋‹ค์–‘ํ•œ ํ”ผ๋“œ๋ฐฑ๋“ค์€ ์‚ฌ์‹ค ์˜๋ฌธ์˜ ์—ฌ์ง€๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. depth๋ฅผ 2 ์ดˆ๊ณผํ•˜์ง€ ๋ง๋ผ๋˜๊ฐ€, ๋ฉ”์„œ๋“œ ๋ผ์ธ์„ 10์ค„์„ ๋„˜๊ธฐ์ง€ ๋ง๋ผ๋˜์ง€์š”..! ๋ฌผ๋ก  ํŠน์ • ์ƒํ™ฉ์—์„œ๋Š” depth๋ฅผ 2 ์ดˆ๊ณผํ•˜๋Š” ๊ฒƒ์ด ๊ฐ€๋…์„ฑ์ด ๋” ์ข‹์„ ๋•Œ๊ฐ€ ์žˆ๊ณ , ๋ผ์ธ 10์ค„์„ ๋„˜์ง€ ์•Š๊ธฐ ์œ„ํ•ด ๋ฉ”์„œ๋“œ๋ฅผ ๋ถ„๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ๊ฐ€๋…์„ฑ์— ์•ˆ์ข‹์€ ์˜ํ–ฅ์„ ๋ผ์น  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ๊ฒฐ๊ณผ์ ์œผ๋กœ ์ด๋Ÿฌํ•œ ํ›ˆ๋ จ๋“ค๋กœ ์ธํ•ด์„œ ์ €ํฌ๋Š” depth๋ฅผ 2 ์ดˆ๊ณผํ•˜๋Š” ํ–‰๋™์„ ํ•  ๋•Œ, ๋ฉ”์„œ๋“œ ๋ผ์ธ์„ 10์ค„ ๋„˜๊ธฐ๋Š” ํ–‰๋™์„ ํ•  ๋•Œ, ๋˜ ์ด๋ฒˆ์ฒ˜๋Ÿผ getter์™€ setter์„ ์“ธ ๋•Œ ํ•œ๋ฒˆ ๋ฉˆ์นซํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. "์ด๊ฒƒ์ด ๊ณผ์—ฐ ์˜ฌ๋ฐ”๋ฅธ ์„ค๊ณ„์ผ๊นŒ?" ๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด์„œ์š”. ์ €๋Š” ์ด๊ฒƒ์ด ์šฐ์•„ํ•œํ…Œํฌ์ฝ”์Šค ํ”ผ๋“œ๋ฐฑ์˜ ์˜๋„๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ๊ทธ์ € ํ•œ๋ฒˆ ๋ฉˆ์นซํ•˜๊ณ  ์Šค์Šค๋กœ ์ƒ๊ฐํ•˜๋Š” ์‹œ๊ฐ„์„ ์ฃผ๋Š”๊ฑฐ์ฃ . ๊ทธ๋ฆฌ๊ณ  getter์™€ setter ์‚ฌ์šฉ ์ด์ „์— ๋ฉˆ์นซ ํ•ด๋ดค์„ ๋•Œ ์ด๊ฑด ๋„์ €ํžˆ getter์™€ setter์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์„ ์ˆ˜ ์—†๊ณ  ์˜คํžˆ๋ ค ์‚ฌ์šฉํ•˜๋ฉด ๋” ๋ณต์žกํ•œ ์„ค๊ณ„๋ฅผ ์ดˆ๋ž˜ํ•˜๊ฒ ๋‹ค๋Š” ๊ฒฐ๋ก ์— ๋„๋‹ฌํ•˜์—ฌ ์‚ฌ์šฉํ•œ ๊ฒƒ์ž…๋‹ˆ๋‹ค.