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์ ์ฌ์ฉํ์ง ์์ ์ ์๊ณ ์คํ๋ ค ์ฌ์ฉํ๋ฉด ๋ ๋ณต์กํ ์ค๊ณ๋ฅผ ์ด๋ํ๊ฒ ๋ค๋ ๊ฒฐ๋ก ์ ๋๋ฌํ์ฌ ์ฌ์ฉํ ๊ฒ์
๋๋ค. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.