code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,100 @@ +package store.controller; + +import store.model.Order; +import store.model.Product; +import store.model.PromotionRepository; +import store.model.Store; +import store.view.InputView; +import store.view.OutputView; + +import java.io.File; +import java.io.IOException; +import java.util.*; + +public class StoreOperationController { + public void run() { + final String productTextPath = "C:\\WoowaCourse\\java-convenience-store-7-33jyu33\\src\\main\\resources\\products.md"; + final String promotionTextPath = "C:\\WoowaCourse\\java-convenience-store-7-33jyu33\\src\\main\\resources\\promotions.md"; + // ์žฌ๊ณ , ํ”„๋กœ๋ชจ์…˜ ๋“ฑ๋ก + PromotionRepository promotionRepository = new PromotionRepository(getScanner(promotionTextPath)); + Store store = new Store(getScanner(productTextPath), promotionRepository); + + saleProduct(store); + } + + private Scanner getScanner(String path) { + try { + return new Scanner(new File(path)); + } catch (IOException e) { + throw new IllegalArgumentException("์Šค์บ๋„ˆ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค ์š˜์„์•„"); + } + } + + private void saleProduct(Store store) { + while (true) { + printProductInformation(store); + Order order = getOrder(store); + order.setMembership(InputView.askMembership()); + OutputView.receipt(order.getProducts(), order.getPromotionalProducts(), order.getResult()); + if (!InputView.askAdditionalPurchase()) break; + } + } + + private void printProductInformation(Store store) { + OutputView.productInformation(store); + } + + private Order getOrder(Store store) { + while (true) { + try { + Map<String, Integer> orderMap = InputView.getOrder(); + store.validateOrderProductName(orderMap.keySet()); + return setOrder(orderMap, store); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private Order setOrder(Map<String, Integer> orderMap, Store store) throws IllegalArgumentException { + Order order = new Order(); + orderMap.forEach((name, count) -> { + Product saleProduct = store.getSaleProduct(name, count); + Product soldProduct = getSoldProduct(saleProduct, name, count); + order.addProduct(soldProduct); + saleProduct.sold(count); + }); + return order; + } + + private Product getSoldProduct(Product saleProduct, String name, Integer count) { + Product soldProduct = saleProduct.getSoldProduct(count); + soldProduct.checkPromotionPeriod(); + checkPromotionalProductCount(soldProduct, saleProduct, count, name); + return soldProduct; + } + + private void checkPromotionalProductCount(Product soldProduct, Product saleProduct, Integer count, String name) throws IllegalArgumentException { + Integer promotionProductQuantity = soldProduct.availableProductQuantity(count); + if (checkAdditionalCount(promotionProductQuantity, soldProduct, saleProduct, count, name)) return; + checkNotApplyPromotion(promotionProductQuantity, name, count); + } + + private boolean checkAdditionalCount(Integer promotionProductQuantity, Product soldProduct, Product saleProduct, Integer count, String name){ + Integer additionalCount = soldProduct.getAdditionalFreeProductCount(count); + if ((promotionProductQuantity != null) && (0 < additionalCount) && (saleProduct.validateAdditionalQuantity(additionalCount+count))) { + if (InputView.checkAdditionalFreeProduct(name, additionalCount)) { + soldProduct.updatePromotionalQuantity(additionalCount+count); + return true; + } + } + return false; + } + + private void checkNotApplyPromotion(Integer promotionProductQuantity, String name, Integer count){ + if (promotionProductQuantity != null && !Objects.equals(promotionProductQuantity, count)) { + InputView.checkNotApplyPromotion(name, count - promotionProductQuantity); + } + } + +}
Java
if๋ฌธ์„ ์‚ฌ์šฉํ•˜๋”๋ผ๋„ `{}`๋ฅผ ์‚ฌ์šฉํ•˜์‹œ๋Š” ๊ฒƒ์„ ๊ถŒ์žฅํ•ฉ๋‹ˆ๋‹ค! ๋ฉ”์„œ๋“œ ๊ธธ์ด๋ฅผ ์ค„์ด๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋ฐ˜๋ณต๋ฌธ ๋‚ด ๋ฉ”์„œ๋“œ๋“ค์„ ๋ถ„๋ฆฌํ•˜์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋„ค์š” !
@@ -0,0 +1,59 @@ +package store.model; + +import store.constant.CompareContext; +import store.constant.StoreGuide; + +import java.util.ArrayList; +import java.util.List; + +public class Order { + List<Product> soldProducts = new ArrayList<>(); + boolean membership = false; + + public void addProduct(Product product){ + soldProducts.add(product); + } + + public void setMembership(boolean member){ + membership = member; + } + + public String getProducts(){ + ArrayList<String> productInformation = new ArrayList<>(); + for(Product product: soldProducts){ + productInformation.add(product.getProductReceipt()); + } + return String.join("\n", productInformation); + } + + public String getPromotionalProducts(){ + ArrayList<String> promotionalProductInformation = new ArrayList<>(); + for(Product product: soldProducts){ + String promotionReceipt = product.getPromotionReceipt(); + if(promotionReceipt != null) { + promotionalProductInformation.add(promotionReceipt); + } + } + return String.join("\n", promotionalProductInformation); + } + + public String getResult(){ + Integer total = 0; + Integer count = 0; + Integer promotionDiscount = 0; + Integer membershipDiscount = 0; + + for(Product product : soldProducts){ + total += product.getPrice()*product.getQuantity(); + count += product.getQuantity(); + promotionDiscount += product.getPromotionDiscount(); + membershipDiscount += product.getMembershipDiscount(); + } + membershipDiscount = membershipDiscount * 30/100; + + if(!membership) membershipDiscount = 0; + if(8000 < membershipDiscount) membershipDiscount = 8000; + Integer price = total-promotionDiscount-membershipDiscount; + return String.format(StoreGuide.RESULT.getContext(), count, total, promotionDiscount, membershipDiscount, price); + } +}
Java
๊ฒฐ๊ณผ ๊ณ„์‚ฐ ๋กœ์ง์„ ๋ฉ”์„œ๋“œ๋กœ ๋”ฐ๋กœ ๊ตฌํ˜„ํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,169 @@ +package store.model; + +import store.constant.CompareContext; +import store.constant.ErrorMessage; +import store.constant.StoreGuide; + +import java.util.List; +import java.util.Objects; + +public class Product { + private final String name; + private final Integer price; + + private Promotion promotion; + private Integer quantity; + private Integer promotionalQuantity; + + public Product(List<String> productInfo, PromotionRepository promotionRepository) { + final int INDEX_NAME = 0; + final int INDEX_PRICE = 1; + final int INDEX_QUANTITY = 2; + final int INDEX_PROMOTION = 3; + + this.name = productInfo.get(INDEX_NAME); + this.price = getPrice(productInfo.get(INDEX_PRICE)); + this.quantity = getPrice(productInfo.get(INDEX_QUANTITY)); + this.promotion = promotionRepository.getPromotion(productInfo.get(INDEX_PROMOTION)); + this.promotionalQuantity = 0; + if (!Objects.equals(productInfo.get(INDEX_PROMOTION), "null")) { + this.promotionalQuantity = getPrice(productInfo.get(INDEX_QUANTITY)); + } + } + + public void update(String quantity, Promotion promotion) { + this.quantity += getPrice(quantity); + if (promotion != null) { + this.promotion = promotion; + this.promotionalQuantity = getPrice(quantity); + } + } + + public void updatePromotionalQuantity(Integer promotionalQuantity){ + this.quantity = promotionalQuantity; + this.promotionalQuantity = promotionalQuantity; + } + + public Product(String name, Integer price, Integer quantity, Promotion promotion, Integer promotionalQuantity) { + this.name = name; + this.price = price; + this.quantity = quantity; + this.promotion = promotion; + this.promotionalQuantity = promotionalQuantity; + } + + public String getName() { + return name; + } + + public Integer getPrice() { + return price; + } + + public Integer getQuantity() { + return quantity; + } + + public Integer getAdditionalFreeProductCount(Integer quantity) { + if (promotion != null){ + return promotion.getAdditionalFreeProductCount(quantity); + } + return 0; + } + + public boolean validateAdditionalQuantity(Integer quantity) { + return quantity <= this.promotionalQuantity; + } + + public void validateOrderQuantity(Integer quantity) throws IllegalArgumentException { + if (this.quantity < quantity) { + throw new IllegalArgumentException(ErrorMessage.OVER_QUANTITY.getMessage()); + } + } + + // ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ ๊ฐ€๋Šฅํ•œ ์ˆ˜๋Ÿ‰ + public Integer availableProductQuantity(Integer quantity) { + if (promotion == null) return null; + return promotion.getDiscountedProductCount(getPromotionalProductQuantity(quantity)); + } + + public void checkPromotionPeriod() { + if (promotion == null || !promotion.inPeriod()) { + promotionalQuantity = 0; + } + } + + // ์ฃผ๋ฌธ ๋ฐ›์€ ์ˆ˜๋Ÿ‰ ์ค‘ ํ”„๋กœ๋ชจ์…˜ ์ ์šฉํ•  ์ƒํ’ˆ์˜ ๊ฐœ์ˆ˜ + private Integer getPromotionalProductQuantity(Integer quantity) { + if (promotionalQuantity < quantity) return promotionalQuantity; + return quantity; + } + + public Integer getPromotionDiscount() { + if (promotion == null) return 0; + return promotion.getFreeProductCount(promotionalQuantity) * price; + } + + public Integer getMembershipDiscount() { + if (promotion == null) return quantity * price; + return (quantity - promotion.getDiscountedProductCount(promotionalQuantity)) * price; + } + + public String getProductReceipt() { + return String.format("%s\t\t%,d\t%,d", name, quantity, quantity * price); + } + + public String getPromotionReceipt() { + if (promotion == null) return null; + Integer freeQuantity = promotion.getFreeProductCount(promotionalQuantity); + if (freeQuantity == 0) return null; + return String.format("%s\t\t%,d", name, freeQuantity); + } + + public String getProductInformation() { + if (promotion != null) { + return getPromotionalProductInformation()+getGeneralProductInformation(); + } + return getGeneralProductInformation(); + } + + private String getGeneralProductInformation(){ + String quantityContext = CompareContext.NO_STOCK.getContext(); + if (0 < quantity - promotionalQuantity){ + quantityContext = Integer.toString(quantity - promotionalQuantity)+"๊ฐœ"; + } + return String.format(StoreGuide.PRODUCT.getContext(), name, price, quantityContext, CompareContext.NULL_STRING.getContext()); + } + + private String getPromotionalProductInformation() { + String quantityContext = CompareContext.NO_STOCK.getContext(); + if (0 < promotionalQuantity){ + quantityContext = Integer.toString(promotionalQuantity)+"๊ฐœ"; + } + return String.format(StoreGuide.PRODUCT.getContext(), name, price, quantityContext, promotion.getName()); + } + + public void sold(Integer count) { + if (promotion != null) { + promotionalQuantity -= availableProductQuantity(count); + } + quantity -= count; + } + + public Product getSoldProduct(Integer count) { + Integer promotionProductQuantity = availableProductQuantity(count); + if (promotion == null) promotionProductQuantity = 0; + return new Product(name, price, count, promotion, promotionProductQuantity); + } + + private Integer getPrice(String priceContext) { + validatePrice(priceContext); + return Integer.parseInt(priceContext); + } + + private void validatePrice(String priceContext) { + if (!priceContext.matches("^[0-9]+$")) { + throw new IllegalArgumentException("product ์žฌ๊ณ  ๋“ฑ๋ก ๊ฐ€๊ฒฉ์€ ์ˆซ์ž๋กœ๋งŒ ๊ตฌ์„ฑํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค"); + } + } +} \ No newline at end of file
Java
๋„ค์ด๋ฐ์€ ์ƒ์ˆ˜ ๋„ค์ด๋ฐ์„ ํ•˜์‹  ๊ฒƒ ๊ฐ™์€๋ฐ, ์ƒ์ˆ˜๋กœ ์„ ์–ธํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” `static final`์„ ์‚ฌ์šฉํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค! ๊ทธ๋ ‡์ง€ ์•Š๊ณ  ๋ณ€์ˆ˜๋กœ ์‚ฌ์šฉํ•˜์‹ ๋‹ค๋ฉด ๋‚™ํƒ€ ๋„ค์ด๋ฐ ๊ทœ์น™์— ๋งž๊ฒŒ ๋„ค์ด๋ฐํ•˜์‹œ๋Š” ๊ฒƒ์ด ์ข‹์Šต๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์ƒ์ˆ˜๋กœ ์„ ์–ธํ•˜๋Š” ๊ฒƒ์€ ๋ฉ”์„œ๋“œ ๋‚ด๊ฐ€ ์•„๋‹ˆ๋ผ ํด๋ž˜์Šค ๋‚ด์—์„œ ์„ ์–ธํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์ƒ์ˆ˜์— ๋Œ€ํ•ด ์•Œ์•„๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š” !
@@ -0,0 +1,38 @@ +package store.model; + +import java.util.*; + +public class PromotionRepository { + private final HashMap<String, Promotion> promotions = new HashMap<>(); + + public PromotionRepository(Scanner promotionScanner){ + // ์ฒซ ์ค„ ์ œ์™ธ + promotionScanner.nextLine(); + + while(promotionScanner.hasNext()){ + setPromotions(promotionScanner.nextLine()); + } + } + + public Promotion getPromotion(String name){ + return promotions.get(name); + } + + private void setPromotions(String promotionContext){ + List<String> promotionInfo = new ArrayList<>(contextToList(promotionContext)); + String promotionName = promotionInfo.getFirst(); + this.promotions.put(promotionName, new Promotion(promotionInfo)); + } + + private List<String> contextToList(String context) { + List<String> promotionInfo = Arrays.asList(context.strip().split(",")); + validateInfoSize(promotionInfo); + return promotionInfo; + } + + private void validateInfoSize(List<String> promotionInfo) { + if (promotionInfo.size() != 5) { + throw new IllegalArgumentException("promotion ๋“ฑ๋ก ํ˜•์‹์— ๋ฌธ์ œ ์žˆ์Œ"); + } + } +}
Java
์ด๋Ÿฐ ์ฃผ์„์€ ์‚ญ์ œํ•˜์…”๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ์˜๋ฏธ ์—†๋Š” ์ฃผ์„์„ ์ง€์šฐ๋Š” ๊ฒƒ๋„ ์ปจ๋ฒค์…˜์ž…๋‹ˆ๋‹ค !
@@ -0,0 +1,71 @@ +package store.model; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.List; + +import static camp.nextstep.edu.missionutils.DateTimes.now; + +public class Promotion { + private final String name; + private final Integer buy; + private final Integer get; + private final LocalDate startDate; + private final LocalDate endDate; + + public Promotion(List<String> promotionInfo) { + final Integer INDEX_NAME = 0; + final Integer INDEX_BUY = 1; + final Integer INDEX_GET = 2; + final Integer INDEX_START_DATE = 3; + final Integer INDEX_END_DATE = 4; + + this.name = promotionInfo.get(INDEX_NAME); + this.buy = getNumber(promotionInfo.get(INDEX_BUY)); + this.get = getNumber(promotionInfo.get(INDEX_GET)); + this.startDate = LocalDate.parse(promotionInfo.get(INDEX_START_DATE), DateTimeFormatter.ISO_DATE); + this.endDate = LocalDate.parse(promotionInfo.get(INDEX_END_DATE), DateTimeFormatter.ISO_DATE); + validateDate(); + } + + public String getName() { + return this.name; + } + + public Integer getFreeProductCount(Integer count) { + return count / (get + buy) * get; + } + + public Integer getDiscountedProductCount(Integer count) { + return (count / (get + buy)) * (get + buy); + } + + public Integer getAdditionalFreeProductCount(Integer count){ + if(count - getDiscountedProductCount(count) == buy){ + return get; + } + return 0; + } + + public Boolean inPeriod() { + LocalDate now = now().toLocalDate(); + return ((!now.isBefore(startDate)) && (!now.isAfter(endDate))); + } + + private Integer getNumber(String context) { + validateOnlyNumber(context); + return Integer.parseInt(context); + } + + private void validateOnlyNumber(String context) { + if (!context.matches("^[0-9]+$")) { + throw new IllegalArgumentException("promotion get, buy๋Š” ์ˆซ์ž๋กœ๋งŒ ๊ตฌ์„ฑํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค"); + } + } + + private void validateDate() { + if (endDate.isBefore(startDate)) { + throw new IllegalArgumentException("promotion ๋งˆ๊ฐ์ผ์ด ์‹œ์ž‘์ผ๋ณด๋‹ค ๋น ๋ฅผ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + } +}
Java
๋ฉ”์‹œ์ง€๋Š” ๋”ฐ๋กœ enum์œผ๋กœ ์ฒ˜๋ฆฌํ•˜๋ฉด ์ถ”ํ›„์— ๊ด€๋ฆฌํ•˜๊ธฐ ํŽธํ•  ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,71 @@ +package store.model; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.List; + +import static camp.nextstep.edu.missionutils.DateTimes.now; + +public class Promotion { + private final String name; + private final Integer buy; + private final Integer get; + private final LocalDate startDate; + private final LocalDate endDate; + + public Promotion(List<String> promotionInfo) { + final Integer INDEX_NAME = 0; + final Integer INDEX_BUY = 1; + final Integer INDEX_GET = 2; + final Integer INDEX_START_DATE = 3; + final Integer INDEX_END_DATE = 4; + + this.name = promotionInfo.get(INDEX_NAME); + this.buy = getNumber(promotionInfo.get(INDEX_BUY)); + this.get = getNumber(promotionInfo.get(INDEX_GET)); + this.startDate = LocalDate.parse(promotionInfo.get(INDEX_START_DATE), DateTimeFormatter.ISO_DATE); + this.endDate = LocalDate.parse(promotionInfo.get(INDEX_END_DATE), DateTimeFormatter.ISO_DATE); + validateDate(); + } + + public String getName() { + return this.name; + } + + public Integer getFreeProductCount(Integer count) { + return count / (get + buy) * get; + } + + public Integer getDiscountedProductCount(Integer count) { + return (count / (get + buy)) * (get + buy); + } + + public Integer getAdditionalFreeProductCount(Integer count){ + if(count - getDiscountedProductCount(count) == buy){ + return get; + } + return 0; + } + + public Boolean inPeriod() { + LocalDate now = now().toLocalDate(); + return ((!now.isBefore(startDate)) && (!now.isAfter(endDate))); + } + + private Integer getNumber(String context) { + validateOnlyNumber(context); + return Integer.parseInt(context); + } + + private void validateOnlyNumber(String context) { + if (!context.matches("^[0-9]+$")) { + throw new IllegalArgumentException("promotion get, buy๋Š” ์ˆซ์ž๋กœ๋งŒ ๊ตฌ์„ฑํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค"); + } + } + + private void validateDate() { + if (endDate.isBefore(startDate)) { + throw new IllegalArgumentException("promotion ๋งˆ๊ฐ์ผ์ด ์‹œ์ž‘์ผ๋ณด๋‹ค ๋น ๋ฅผ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + } +}
Java
ํ•ด๋‹น ๋ฌธ์ž์—ด์€ ๋”ฐ๋กœ ์ƒ์ˆ˜ ์ฒ˜๋ฆฌํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,38 @@ +package store.model; + +import java.util.*; + +public class PromotionRepository { + private final HashMap<String, Promotion> promotions = new HashMap<>(); + + public PromotionRepository(Scanner promotionScanner){ + // ์ฒซ ์ค„ ์ œ์™ธ + promotionScanner.nextLine(); + + while(promotionScanner.hasNext()){ + setPromotions(promotionScanner.nextLine()); + } + } + + public Promotion getPromotion(String name){ + return promotions.get(name); + } + + private void setPromotions(String promotionContext){ + List<String> promotionInfo = new ArrayList<>(contextToList(promotionContext)); + String promotionName = promotionInfo.getFirst(); + this.promotions.put(promotionName, new Promotion(promotionInfo)); + } + + private List<String> contextToList(String context) { + List<String> promotionInfo = Arrays.asList(context.strip().split(",")); + validateInfoSize(promotionInfo); + return promotionInfo; + } + + private void validateInfoSize(List<String> promotionInfo) { + if (promotionInfo.size() != 5) { + throw new IllegalArgumentException("promotion ๋“ฑ๋ก ํ˜•์‹์— ๋ฌธ์ œ ์žˆ์Œ"); + } + } +}
Java
ํ”„๋กœ๋ชจ์…˜ ์ž…๋ ฅ ์‚ฌ์ด์ฆˆ๋„ ์ฒดํฌํ•˜์…จ๊ตฐ์š”! ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค ๐Ÿ‘
@@ -0,0 +1,38 @@ +package lotto.controller.validator + +class PurchaseCostValidator { + operator fun invoke(input: String) { + isEmpty(input) + isInteger(input) + isZero(input) + isNegativeNumber(input) + isBetween(input) + isUnits(input) + } + + private fun isEmpty(input: String) { + require(input.isNotEmpty()) { PurchaseErrorType.EMPTY_INPUT } + } + + private fun isInteger(input: String) { + requireNotNull(input.toIntOrNull()) { PurchaseErrorType.NOT_INTEGER } + } + + private fun isZero(input: String) { + require(input.toInt() != 0) { PurchaseErrorType.ZERO } + } + + private fun isNegativeNumber(input: String) { + require(input.toInt() > 0) { + PurchaseErrorType.NEGATIVE_NUMBER + } + } + + private fun isBetween(input: String) { + require(input.toInt() >= 1000) { PurchaseErrorType.BETWEEN } + } + + private fun isUnits(input: String) { + require(input.toInt() % 1000 == 0) { PurchaseErrorType.NO_UNITS } + } +} \ No newline at end of file
Kotlin
์ „ ๋นจ๋ฆฌ ํ’€๋ ค๊ณ  ํ•˜๋‹ค๋ณด๋‹ˆ 1000์› ์ดํ•˜๋‚˜ ์Œ์ˆ˜์— ๋Œ€ํ•œ ์ž…๋ ฅ์€ 1000์› ๋ฏธ๋งŒ ๊ธˆ์•ก ์ž…๋ ฅ์‹œ ์—๋Ÿฌ ๋ฐœ์ƒํ•˜๋Š” ์‹์œผ๋กœ ํ‰์ณค๋Š”๋ฐ ์—ญ์‹œ ๊ผผ๊ผผํ•˜์‹ญ๋‹ˆ๋‹ค ๐Ÿ‘
@@ -0,0 +1,40 @@ +package lotto.controller.validator + +class LottoNumbersValidator { + operator fun invoke(input: String) { + isEmpty(input) + val numbers = input.split(",").map { it.trim() } + isEmpty(numbers) + isInteger(numbers) + isBetween(numbers) + isDuplicate(numbers) + isSix(numbers) + } + + private fun isEmpty(input: String) { + require(input.isNotEmpty()) { LottoNumbersErrorType.EMPTY_INPUT } + } + + private fun isEmpty(numbers: List<String>) { + require(numbers.all { it.isNotEmpty() }) { LottoNumbersErrorType.EMPTY_INPUT } + } + + private fun isInteger(numbers: List<String>) { + require(numbers.all { it.toIntOrNull() != null }) { LottoNumbersErrorType.NOT_INTEGER } + } + + private fun isBetween(numbers: List<String>) { + val nums = numbers.map { it.toInt() } + require(nums.all { it in 1..45 }) { LottoNumbersErrorType.BETWEEN_1_45 } + } + + private fun isDuplicate(numbers: List<String>) { + val nums = numbers.map { it.toInt() } + require(nums.size == nums.toSet().size) { LottoNumbersErrorType.DUPLICATE } + } + + private fun isSix(numbers: List<String>) { + val nums = numbers.map { it.toInt() } + require(nums.size == 6) { LottoNumbersErrorType.SIX } + } +} \ No newline at end of file
Kotlin
ํ˜น์‹œ String Type ์—์„œ Int๋กœ ๋ณ€ํ˜•ํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์šฉ? ๋ณ€ํ˜•ํ•˜์ง€ ์•Š์•„๋„ ์›์†Œ ๊ฐœ์ˆ˜ ๋น„๊ตํ•˜๋Š”๋ด ์˜ํ–ฅ์ด ์—†์„ ๊ฒƒ ๊ฐ™๋‹ค๊ณ  ์ƒ๊ฐํ•ด์š” !
@@ -0,0 +1,54 @@ +package lotto.model + +import lotto.constant.WinnerType +import lotto.util.RandomNumbers + +data class MyLotto( + private val purchaseCost: Int, + private val _lottos: MutableList<Lotto> = mutableListOf(), + private val _winners: MutableList<WinnerType> = mutableListOf(), +) { + val lottoCount: Int + get() = purchaseCost / 1000 + + val lottos: List<Lotto> + get() = _lottos + + val winners: List<WinnerType> + get() = _winners + + val rateOfReturn: String + get() { + val totalPrizeAmount = _winners.sumOf { it.prizeAmount } + val rate = totalPrizeAmount / purchaseCost.toDouble() * 100 + return String.format("%.1f", rate) + } + + init { + generateLottos() + } + + private fun generateLottos() { + val randomNumbers = RandomNumbers() + for (count in 1..lottoCount) { + val nums = randomNumbers() + _lottos.add(Lotto(nums)) + } + } + + fun getWinner(winningNumber: Lotto, bonusNumber: Int) { + _lottos.forEach { lotto -> + val matchCount = lotto.winningNumbers.intersect(winningNumber.winningNumbers).size + val hasBonus = bonusNumber in lotto.winningNumbers + val winner = when { + matchCount == 6 -> WinnerType.FIRST + matchCount == 5 && hasBonus -> WinnerType.SECOND + matchCount == 5 -> WinnerType.THIRD + matchCount == 4 -> WinnerType.FOURTH + matchCount == 3 -> WinnerType.FIFTH + else -> WinnerType.NONE + } + _winners.add(winner) + } + } +} \ No newline at end of file
Kotlin
๋Œ€๋ฐ• ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด lottoCount๋ฅผ ์™ธ๋ถ€์—์„œ ๊ณ„์‚ฐํ•ด์ฃผ์ง€ ์•Š์•„๋„ ๋˜๋Š”๊ตฐ์š” ! ํ•˜๋‚˜ ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค ใ…Žใ…Ž
@@ -0,0 +1,54 @@ +package lotto.model + +import lotto.constant.WinnerType +import lotto.util.RandomNumbers + +data class MyLotto( + private val purchaseCost: Int, + private val _lottos: MutableList<Lotto> = mutableListOf(), + private val _winners: MutableList<WinnerType> = mutableListOf(), +) { + val lottoCount: Int + get() = purchaseCost / 1000 + + val lottos: List<Lotto> + get() = _lottos + + val winners: List<WinnerType> + get() = _winners + + val rateOfReturn: String + get() { + val totalPrizeAmount = _winners.sumOf { it.prizeAmount } + val rate = totalPrizeAmount / purchaseCost.toDouble() * 100 + return String.format("%.1f", rate) + } + + init { + generateLottos() + } + + private fun generateLottos() { + val randomNumbers = RandomNumbers() + for (count in 1..lottoCount) { + val nums = randomNumbers() + _lottos.add(Lotto(nums)) + } + } + + fun getWinner(winningNumber: Lotto, bonusNumber: Int) { + _lottos.forEach { lotto -> + val matchCount = lotto.winningNumbers.intersect(winningNumber.winningNumbers).size + val hasBonus = bonusNumber in lotto.winningNumbers + val winner = when { + matchCount == 6 -> WinnerType.FIRST + matchCount == 5 && hasBonus -> WinnerType.SECOND + matchCount == 5 -> WinnerType.THIRD + matchCount == 4 -> WinnerType.FOURTH + matchCount == 3 -> WinnerType.FIFTH + else -> WinnerType.NONE + } + _winners.add(winner) + } + } +} \ No newline at end of file
Kotlin
์š” ํด๋ž˜์Šค ๊ฐํƒ„ํ•˜๋ฉด์„œ ๋ดค์Šต๋‹ˆ๋‹ค ใ…Žใ…Ž ์‘์ง‘๋„๋ฉด์—์„œ ๋„ˆ๋ฌด๋‚˜ ์ž˜ ์„ค๊ณ„ํ•˜์‹  ๊ฒƒ ๊ฐ™์•„์š” :)
@@ -0,0 +1,40 @@ +package lotto.controller.validator + +class LottoNumbersValidator { + operator fun invoke(input: String) { + isEmpty(input) + val numbers = input.split(",").map { it.trim() } + isEmpty(numbers) + isInteger(numbers) + isBetween(numbers) + isDuplicate(numbers) + isSix(numbers) + } + + private fun isEmpty(input: String) { + require(input.isNotEmpty()) { LottoNumbersErrorType.EMPTY_INPUT } + } + + private fun isEmpty(numbers: List<String>) { + require(numbers.all { it.isNotEmpty() }) { LottoNumbersErrorType.EMPTY_INPUT } + } + + private fun isInteger(numbers: List<String>) { + require(numbers.all { it.toIntOrNull() != null }) { LottoNumbersErrorType.NOT_INTEGER } + } + + private fun isBetween(numbers: List<String>) { + val nums = numbers.map { it.toInt() } + require(nums.all { it in 1..45 }) { LottoNumbersErrorType.BETWEEN_1_45 } + } + + private fun isDuplicate(numbers: List<String>) { + val nums = numbers.map { it.toInt() } + require(nums.size == nums.toSet().size) { LottoNumbersErrorType.DUPLICATE } + } + + private fun isSix(numbers: List<String>) { + val nums = numbers.map { it.toInt() } + require(nums.size == 6) { LottoNumbersErrorType.SIX } + } +} \ No newline at end of file
Kotlin
๋งž๋„ค์š”! ์ด๊ฒŒ ์˜ค๋ฒ„ ์ฝ”๋”ฉ์„ ํ•ด๋ฒ„๋ ธ๋„ค์š” ใ…Žใ…Ž
@@ -0,0 +1,26 @@ +package lotto.constant + +import java.text.NumberFormat +import java.util.* + +enum class WinnerType( + val matchingNumberCount: Int, + val prizeAmount: Int, +) { + FIRST(6, 2_000_000_000), + SECOND(5, 30_000_000), + THIRD(5, 1_500_000), + FOURTH(4, 50_000), + FIFTH(3, 5_000), + NONE(0, 0); + + override fun toString(): String { + return when (this) { + SECOND -> "${matchingNumberCount}๊ฐœ ์ผ์น˜, ๋ณด๋„ˆ์Šค ๋ณผ ์ผ์น˜ (${ + NumberFormat.getNumberInstance(Locale.KOREA).format(prizeAmount) + }์›)" + + else -> "${matchingNumberCount}๊ฐœ ์ผ์น˜ (${NumberFormat.getNumberInstance(Locale.KOREA).format(prizeAmount)}์›)" + } + } +} \ No newline at end of file
Kotlin
์™€ 2๋“ฑ์ผ๋•Œ๋งŒ print๋‹ค๋ฅธ ๊ฒƒ ๋•Œ๋ฌธ์— ๊ณจ์น˜์•„ํŒ ๋Š”๋ฐ, ์•„์˜ˆ enum์—์„œ ๋‹ค๋ฅด๊ฒŒ toStringํ•˜์‹œ๋‹ค๋‹ˆ.. ๋˜ ํ•˜๋‚˜ ๋ฐฐ์›๋‹ˆ๋‹ค...!
@@ -0,0 +1,38 @@ +package lotto.controller.validator + +class PurchaseCostValidator { + operator fun invoke(input: String) { + isEmpty(input) + isInteger(input) + isZero(input) + isNegativeNumber(input) + isBetween(input) + isUnits(input) + } + + private fun isEmpty(input: String) { + require(input.isNotEmpty()) { PurchaseErrorType.EMPTY_INPUT } + } + + private fun isInteger(input: String) { + requireNotNull(input.toIntOrNull()) { PurchaseErrorType.NOT_INTEGER } + } + + private fun isZero(input: String) { + require(input.toInt() != 0) { PurchaseErrorType.ZERO } + } + + private fun isNegativeNumber(input: String) { + require(input.toInt() > 0) { + PurchaseErrorType.NEGATIVE_NUMBER + } + } + + private fun isBetween(input: String) { + require(input.toInt() >= 1000) { PurchaseErrorType.BETWEEN } + } + + private fun isUnits(input: String) { + require(input.toInt() % 1000 == 0) { PurchaseErrorType.NO_UNITS } + } +} \ No newline at end of file
Kotlin
๊ฐ ๋ถ„์•ผ๋ณ„๋กœ Validator๋ž‘ ErroType์ด ํ•˜๋‚˜์”ฉ ์žˆ๋Š” ๊ฒŒ ํŒŒ์ผ์ด ๊น”๋”ํ•ด์„œ ์ข‹๋„ค์š”!
@@ -0,0 +1,36 @@ +package lotto.controller.domain + +import lotto.model.MyLotto +import lotto.view.InputView +import lotto.view.OutputView + +class UserInteractionController( + private val inputView: InputView = InputView(), + private val outputView: OutputView = OutputView(), +) { + fun handlePurchaseCost(): String { + outputView.showStartMessage() + val purchaseCost = inputView.getInput() + return purchaseCost + } + + fun handlePurchaseLotto(myLotto: MyLotto) { + outputView.showPurchaseLotto(myLotto) + } + + fun handleLottoNumbers(): String { + outputView.showLottoNumbers() + val lottoNumbers = inputView.getInput() + return lottoNumbers + } + + fun handleBonusNumber(): String { + outputView.showBonusNumber() + val bonusNumber = inputView.getInput() + return bonusNumber + } + + fun handlePrize(myLotto: MyLotto) { + outputView.showPrize(myLotto) + } +} \ No newline at end of file
Kotlin
LottoController์™ธ UserController ๋งŒ๋“œ๋Š”๊ฒŒ ์ข‹๋„ค์š”! ์ €๋„ ์ž…๋ ฅ์ด๋ž‘ ํ˜ผ์žฌ๋˜์–ด์žˆ์–ด์„œ ๊ณ ๋ฏผ์ด์—ˆ๋Š”๋ฐ ์ฐธ๊ณ ํ•ด์•ผ๊ฒ ์Šต๋‹ˆ๋‹ค ใ…Žใ…Ž
@@ -0,0 +1,14 @@ +package store.common.dto; + +public record PromotionConditionResult( + int applicableSetCount, + int stockUsed, + int remainingQuantity, + String message +) { + public static PromotionConditionResult from( + int applicableSetCount, int stockUsed, int remainingQuantity, String message + ) { + return new PromotionConditionResult(applicableSetCount, stockUsed, remainingQuantity, message); + } +}
Java
์ •์  ํŒฉํ† ๋ฆฌ ๋ฉ”์„œ๋“œ ์‚ฌ์šฉ ์‹œ, from์€ ์ธ์ž ๊ฐ’์ด ํ•˜๋‚˜์ผ๋•Œ ์‚ฌ์šฉํ•˜๊ณ  of๋Š” ์ธ์ž ๊ฐ’์ด ์—ฌ๋Ÿฌ๊ฐœ์ผ๋•Œ ์ฃผ๋กœ ์‚ฌ์šฉ์„ ํ•œ๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค ๐Ÿค”
@@ -0,0 +1,24 @@ +package store.common.dto; + +import java.util.Map; +import java.util.Set; + +public record PurchaseRequest( + Map<String, Integer> items +) { + public static PurchaseRequest from(Map<String, Integer> cart) { + return new PurchaseRequest(cart); + } + + public PurchaseProductNames getProductNames() { + return PurchaseProductNames.from(items.keySet()); + } + + public record PurchaseProductNames( + Set<String> productNames + ) { + public static PurchaseProductNames from(Set<String> productNames) { + return new PurchaseProductNames(productNames); + } + } +}
Java
๋‚ด์žฅ ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•˜์‹  ์˜๋„๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!! ๐Ÿ™ƒ
@@ -0,0 +1,34 @@ +package store.common.util; + +import java.util.Arrays; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.IntStream; + +public class StringUtils { + + public static int parseInt(String message) { + try { + return Integer.parseInt(message); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(); + } + } + + public static List<String> splitWithDelimiter(String message, String delimiter) { + return Arrays.stream(message.split(delimiter)) + .map(String::strip) + .toList(); + } + + public static List<String> extractFromRegex(String message, Pattern regex) { + Matcher matcher = regex.matcher(message); + if (!matcher.matches()) { + throw new IllegalArgumentException(); + } + return IntStream.range(1, matcher.groupCount() + 1) + .mapToObj(matcher::group) + .toList(); + } +}
Java
์˜ˆ์™ธ ์ฒ˜๋ฆฌ ๋ฉ”์„ธ์ง€๋Š” ์ผ๋ถ€๋Ÿฌ ๋ณด๋‚ด์ง€ ์•Š์œผ์‹  ๊ฑธ๊นŒ์š”?
@@ -0,0 +1,144 @@ +package store.controller; + +import static store.common.constant.ErrorMessage.INPUT_INVALID_FORMAT; +import static store.common.constant.ErrorMessage.PRODUCT_NOT_FOUND_ERROR; +import static store.common.constant.ErrorMessage.PRODUCT_OUT_OF_STOCK; + +import java.io.IOException; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Locale; +import java.util.function.Supplier; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import store.common.dto.PurchaseRequest; +import store.common.dto.PurchaseRequest.PurchaseProductNames; +import store.common.util.FileReader; +import store.common.util.StringUtils; +import store.model.Product; +import store.model.ProductCatalog; +import store.model.Products; +import store.model.Promotion; +import store.model.PromotionCatalog; +import store.model.promotion.BuyNGetMFreePromotion; +import store.model.promotion.PromotionStrategy; +import store.view.InputView; + +public class InputHandler { + + private static final Pattern PURCHASE_ITEM_REGEX = Pattern.compile("^\\[(.+)\\-(.+)\\]$"); + + private final InputView inputView; + + public InputHandler(InputView inputView) { + this.inputView = inputView; + } + + public PromotionCatalog getPromotions() { + try { + List<String> fileLines = FileReader.readFile("src/main/resources/promotions.md"); + return PromotionCatalog.from(fileLines.stream() + .skip(1) + .map(fileLine -> makePromotion(StringUtils.splitWithDelimiter(fileLine, ","))) + .collect(Collectors.toMap(Promotion::name, promotion -> promotion)) + ); + } catch (IOException e) { + throw new IllegalArgumentException(); + } + } + + public ProductCatalog getProducts(PromotionCatalog promotionCatalog) { + try { + List<String> fileLines = FileReader.readFile("src/main/resources/products.md"); + return ProductCatalog.from(fileLines.stream() + .skip(1) + .map(fileLine -> makeProduct(StringUtils.splitWithDelimiter(fileLine, ","), promotionCatalog)) + .collect(Collectors.toSet()) + ); + } catch (IOException e) { + throw new IllegalArgumentException(); + } + } + + public PurchaseRequest getPurchaseItems(ProductCatalog productCatalog) { + return validate(() -> { + List<String> purchaseItems = StringUtils.splitWithDelimiter(inputView.getPurchaseItems(), ","); + PurchaseRequest request = getPurchaseRequest(purchaseItems); + validateItemsExist(request.getProductNames(), productCatalog); + checkItemsStock(request, productCatalog); + return request; + }); + } + + private PurchaseRequest getPurchaseRequest(List<String> purchaseItems) { + try { + return PurchaseRequest.from( + purchaseItems.stream() + .map(purchaseItem -> StringUtils.extractFromRegex(purchaseItem, PURCHASE_ITEM_REGEX)) + .collect(Collectors.toMap(item -> item.get(0).strip(), + item -> StringUtils.parseInt(item.get(1)))) + ); + } catch (IllegalStateException e) { + throw new IllegalArgumentException(INPUT_INVALID_FORMAT.message()); + } + } + + public boolean isAffirmative() { + return validate(() -> { + String yesOrNo = inputView.getYesOrNo().toUpperCase(Locale.ROOT); + if (!yesOrNo.equals("Y") && !yesOrNo.equals("N")) { + throw new IllegalArgumentException(INPUT_INVALID_FORMAT.message()); + } + return yesOrNo.equals("Y"); + }); + } + + private Promotion makePromotion(List<String> promotionValues) { + DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE; + + String name = promotionValues.get(0); + int purchaseQuantity = StringUtils.parseInt(promotionValues.get(1)); + int freeQuantity = StringUtils.parseInt(promotionValues.get(2)); + PromotionStrategy promotionStrategy = new BuyNGetMFreePromotion(purchaseQuantity, freeQuantity); + LocalDate startDate = LocalDate.parse(promotionValues.get(3), formatter); + LocalDate endDate = LocalDate.parse(promotionValues.get(4), formatter); + return Promotion.of(name, promotionStrategy, startDate, endDate); + } + + private Product makeProduct(List<String> productValues, PromotionCatalog promotionCatalog) { + String name = productValues.get(0); + int price = StringUtils.parseInt(productValues.get(1)); + int stock = StringUtils.parseInt(productValues.get(2)); + Promotion promotion = promotionCatalog.getPromotionByName(productValues.get(3)); + return Product.of(name, price, stock, promotion); + } + + private void validateItemsExist(PurchaseProductNames productNames, ProductCatalog productCatalog) { + boolean doesNotContainsAllProduct = !productCatalog.doesContainsAllProduct(productNames.productNames()); + if (doesNotContainsAllProduct) { + throw new IllegalArgumentException(PRODUCT_NOT_FOUND_ERROR.message()); + } + } + + private void checkItemsStock(PurchaseRequest purchaseItems, ProductCatalog productCatalog) { + purchaseItems.items().forEach((productName, quantity) -> { + Products product = productCatalog.getProductByName(productName); + int totalStock = product.products().stream().mapToInt(Product::stock).sum(); + boolean isOutOfStock = quantity > totalStock; + if (isOutOfStock) { + throw new IllegalArgumentException(PRODUCT_OUT_OF_STOCK.message()); + } + }); + } + + private <T> T validate(Supplier<T> inputSupplier) { + while (true) { + try { + return inputSupplier.get(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } +}
Java
toUpperCase()๋ž‘ toUpperCase(Locale.ROOT) ์–ด๋–ค ๋ถ€๋ถ„์ด ๋‹ค๋ฅธ๊ฐ€์š”?
@@ -0,0 +1,162 @@ +package store.controller; + +import static store.common.constant.PromotionNotice.GET_FREE_M_NOTICE; +import static store.common.constant.PromotionNotice.OUT_OF_STOCK_NOTICE; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import store.common.dto.PromotionConditionResult; +import store.common.dto.PromotionResult; +import store.common.dto.PurchaseRequest; +import store.common.dto.PurchaseRequest.PurchaseProductNames; +import store.model.Cart; +import store.model.Product; +import store.model.ProductCatalog; +import store.model.Products; +import store.model.PromotionCatalog; +import store.model.Receipt; +import store.view.OutputView; + +public class StoreController { + + private final InputHandler inputHandler; + private final OutputView outputView; + + private final ProductCatalog productCatalog; + private final PromotionCatalog promotionCatalog; + + public StoreController(InputHandler inputHandler, OutputView outputView) { + this.inputHandler = inputHandler; + this.outputView = outputView; + promotionCatalog = inputHandler.getPromotions(); + productCatalog = inputHandler.getProducts(promotionCatalog); + } + + public void run() { + PurchaseRequest purchaseItems = getPurchaseRequest(); + Cart cart = Cart.empty(); + + Products promotionalProducts = getPromotionalProducts(purchaseItems.getProductNames()); + List<PromotionResult> promotionResults = addPromotionalProductToCart(promotionalProducts, purchaseItems, cart); + addRegularProductToCart(purchaseItems, cart); + int membershipDiscount = applyMembership(cart, promotionalProducts); + purchaseProducts(cart); + printReceipt(cart, promotionResults, membershipDiscount); + repurchaseIfWant(); + } + + private PurchaseRequest getPurchaseRequest() { + outputView.printStoreInventory(productCatalog); + return inputHandler.getPurchaseItems(productCatalog); + } + + private void addRegularProductToCart(PurchaseRequest purchaseItems, Cart cart) { + purchaseItems.items().keySet().forEach(productName -> { + Product product = productCatalog.getProductByName(productName).products().stream() + .findFirst() + .orElseThrow(IllegalArgumentException::new); + cart.addProduct(product, purchaseItems.items().get(productName)); + }); + } + + private List<PromotionResult> addPromotionalProductToCart( + Products promotionalProducts, PurchaseRequest purchaseItems, Cart cart + ) { + promotionalProducts.products().forEach(product -> { + int purchaseQuantity = purchaseItems.items().get(product.name()); + PromotionConditionResult conditionResult = product.checkPromotionCondition(purchaseQuantity); + handlePromotionCondition(purchaseItems, cart, product, conditionResult); + }); + return applyPromotion(cart); + } + + private Products getPromotionalProducts(PurchaseProductNames productNames) { + return Products.from( + productCatalog.getProductsByNames(productNames.productNames()).products().stream() + .filter(Product::isPromotionApplicable) + .collect(Collectors.toSet()) + ); + } + + private List<PromotionResult> applyPromotion(Cart cart) { + return cart.cart().keySet().stream() + .filter(Product::isPromotionApplicable) + .map(product -> product.applyPromotion(cart.cart().get(product))) + .toList(); + } + + private void handlePromotionCondition( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + if (GET_FREE_M_NOTICE.matches(conditionResult.message())) { + handleGetFreeCondition(purchaseItems, cart, product, conditionResult); + return; + } + if (OUT_OF_STOCK_NOTICE.matches(conditionResult.message())) { + handleOutOfPromotionStock(purchaseItems, cart, product, conditionResult); + return; + } + cart.addProduct(product, conditionResult.stockUsed()); + purchaseItems.items() + .replace(product.name(), purchaseItems.items().get(product.name()) - conditionResult.stockUsed()); + } + + private void handleOutOfPromotionStock( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + int purchaseQuantity = purchaseItems.items().get(product.name()); + outputView.printPromotionOutOfStockNotice(conditionResult.message()); + cart.addProduct(product, conditionResult.stockUsed()); + if (inputHandler.isAffirmative()) { + purchaseItems.items().replace(product.name(), purchaseQuantity - conditionResult.stockUsed()); + return; + } + purchaseItems.items().remove(product.name()); + } + + private void handleGetFreeCondition( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + int purchaseQuantity = purchaseItems.items().get(product.name()); + outputView.printGetFreeNotice(conditionResult.message()); + if (inputHandler.isAffirmative()) { + cart.addProduct(product, purchaseQuantity + 1); + purchaseItems.items().remove(product.name()); + return; + } + cart.addProduct(product, purchaseQuantity); + purchaseItems.items().remove(product.name()); + } + + private int applyMembership(Cart cart, Products promotionalProducts) { + outputView.printMembershipNotice(); + AtomicInteger discountAmount = new AtomicInteger(); + if (inputHandler.isAffirmative()) { + cart.cart().forEach((product, quantity) -> { + if (promotionalProducts.products().contains(product)) { + return; + } + discountAmount.addAndGet(product.price() * quantity); + }); + } + discountAmount.updateAndGet(value -> Math.min(value * 30 / 100, 8000)); + return discountAmount.get(); + } + + private static void purchaseProducts(Cart cart) { + cart.cart().forEach(Product::reduceStock); + } + + private void printReceipt(Cart cart, List<PromotionResult> promotionResults, int membershipDiscount) { + Receipt receipt = Receipt.of(cart, promotionResults, membershipDiscount); + outputView.printReceipt(receipt); + } + + private void repurchaseIfWant() { + outputView.printRepurchaseNotice(); + if (inputHandler.isAffirmative()) { + run(); + } + } +}
Java
static์€ ์ž˜๋ชป ๋“ค์–ด๊ฐ„๊ฑธ๊นŒ์š”?
@@ -0,0 +1,162 @@ +package store.controller; + +import static store.common.constant.PromotionNotice.GET_FREE_M_NOTICE; +import static store.common.constant.PromotionNotice.OUT_OF_STOCK_NOTICE; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import store.common.dto.PromotionConditionResult; +import store.common.dto.PromotionResult; +import store.common.dto.PurchaseRequest; +import store.common.dto.PurchaseRequest.PurchaseProductNames; +import store.model.Cart; +import store.model.Product; +import store.model.ProductCatalog; +import store.model.Products; +import store.model.PromotionCatalog; +import store.model.Receipt; +import store.view.OutputView; + +public class StoreController { + + private final InputHandler inputHandler; + private final OutputView outputView; + + private final ProductCatalog productCatalog; + private final PromotionCatalog promotionCatalog; + + public StoreController(InputHandler inputHandler, OutputView outputView) { + this.inputHandler = inputHandler; + this.outputView = outputView; + promotionCatalog = inputHandler.getPromotions(); + productCatalog = inputHandler.getProducts(promotionCatalog); + } + + public void run() { + PurchaseRequest purchaseItems = getPurchaseRequest(); + Cart cart = Cart.empty(); + + Products promotionalProducts = getPromotionalProducts(purchaseItems.getProductNames()); + List<PromotionResult> promotionResults = addPromotionalProductToCart(promotionalProducts, purchaseItems, cart); + addRegularProductToCart(purchaseItems, cart); + int membershipDiscount = applyMembership(cart, promotionalProducts); + purchaseProducts(cart); + printReceipt(cart, promotionResults, membershipDiscount); + repurchaseIfWant(); + } + + private PurchaseRequest getPurchaseRequest() { + outputView.printStoreInventory(productCatalog); + return inputHandler.getPurchaseItems(productCatalog); + } + + private void addRegularProductToCart(PurchaseRequest purchaseItems, Cart cart) { + purchaseItems.items().keySet().forEach(productName -> { + Product product = productCatalog.getProductByName(productName).products().stream() + .findFirst() + .orElseThrow(IllegalArgumentException::new); + cart.addProduct(product, purchaseItems.items().get(productName)); + }); + } + + private List<PromotionResult> addPromotionalProductToCart( + Products promotionalProducts, PurchaseRequest purchaseItems, Cart cart + ) { + promotionalProducts.products().forEach(product -> { + int purchaseQuantity = purchaseItems.items().get(product.name()); + PromotionConditionResult conditionResult = product.checkPromotionCondition(purchaseQuantity); + handlePromotionCondition(purchaseItems, cart, product, conditionResult); + }); + return applyPromotion(cart); + } + + private Products getPromotionalProducts(PurchaseProductNames productNames) { + return Products.from( + productCatalog.getProductsByNames(productNames.productNames()).products().stream() + .filter(Product::isPromotionApplicable) + .collect(Collectors.toSet()) + ); + } + + private List<PromotionResult> applyPromotion(Cart cart) { + return cart.cart().keySet().stream() + .filter(Product::isPromotionApplicable) + .map(product -> product.applyPromotion(cart.cart().get(product))) + .toList(); + } + + private void handlePromotionCondition( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + if (GET_FREE_M_NOTICE.matches(conditionResult.message())) { + handleGetFreeCondition(purchaseItems, cart, product, conditionResult); + return; + } + if (OUT_OF_STOCK_NOTICE.matches(conditionResult.message())) { + handleOutOfPromotionStock(purchaseItems, cart, product, conditionResult); + return; + } + cart.addProduct(product, conditionResult.stockUsed()); + purchaseItems.items() + .replace(product.name(), purchaseItems.items().get(product.name()) - conditionResult.stockUsed()); + } + + private void handleOutOfPromotionStock( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + int purchaseQuantity = purchaseItems.items().get(product.name()); + outputView.printPromotionOutOfStockNotice(conditionResult.message()); + cart.addProduct(product, conditionResult.stockUsed()); + if (inputHandler.isAffirmative()) { + purchaseItems.items().replace(product.name(), purchaseQuantity - conditionResult.stockUsed()); + return; + } + purchaseItems.items().remove(product.name()); + } + + private void handleGetFreeCondition( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + int purchaseQuantity = purchaseItems.items().get(product.name()); + outputView.printGetFreeNotice(conditionResult.message()); + if (inputHandler.isAffirmative()) { + cart.addProduct(product, purchaseQuantity + 1); + purchaseItems.items().remove(product.name()); + return; + } + cart.addProduct(product, purchaseQuantity); + purchaseItems.items().remove(product.name()); + } + + private int applyMembership(Cart cart, Products promotionalProducts) { + outputView.printMembershipNotice(); + AtomicInteger discountAmount = new AtomicInteger(); + if (inputHandler.isAffirmative()) { + cart.cart().forEach((product, quantity) -> { + if (promotionalProducts.products().contains(product)) { + return; + } + discountAmount.addAndGet(product.price() * quantity); + }); + } + discountAmount.updateAndGet(value -> Math.min(value * 30 / 100, 8000)); + return discountAmount.get(); + } + + private static void purchaseProducts(Cart cart) { + cart.cart().forEach(Product::reduceStock); + } + + private void printReceipt(Cart cart, List<PromotionResult> promotionResults, int membershipDiscount) { + Receipt receipt = Receipt.of(cart, promotionResults, membershipDiscount); + outputView.printReceipt(receipt); + } + + private void repurchaseIfWant() { + outputView.printRepurchaseNotice(); + if (inputHandler.isAffirmative()) { + run(); + } + } +}
Java
์ธ๋ดํŠธ depth๋ฅผ 2๊ฐœ๊นŒ์ง€ ํ—ˆ์šฉํ•˜๋Š” ๊ฒƒ์ด ์š”๊ตฌ์‚ฌํ•ญ์ด์˜€๋Š”๋ฐ, 3๊ฐœ๊ฐ€ ๋“ค์–ด๊ฐ„ ๊ฒƒ ๊ฐ™์•„ ๋ฉ”์„œ๋“œ๋ฅผ ๋ถ„๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์—ฌ์š”!!
@@ -0,0 +1,56 @@ +package store.model; + +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; + +public class ProductCatalog { + + private final Products products; + + private ProductCatalog(Products products) { + this.products = products; + } + + public static ProductCatalog from(Set<Product> products) { + products = new HashSet<>(products); + Set<Product> additionalProducts = products.stream() + .collect(Collectors.groupingBy(Product::name)) + .entrySet().stream() + .filter(entry -> entry.getValue().stream().noneMatch(p -> p.promotion() == null)) + .map(entry -> Product.of(entry.getKey(), entry.getValue().getFirst().price(), 0, null)) + .collect(Collectors.toSet()); + + products.addAll(additionalProducts); + return new ProductCatalog(Products.from(products)); + } + + public boolean doesContainsAllProduct(Set<String> productNames) { + return this.products.products().stream() + .map(Product::name) + .collect(Collectors.toSet()) + .containsAll(productNames); + } + + public Products getProductByName(String productName) { + return Products.from( + this.products.products().stream() + .filter(product -> product.name().equals(productName)) + .collect(Collectors.toSet()) + ); + } + + public Products getProductsByNames(Set<String> productNames) { + Set<Product> productsByName = new HashSet<>(); + productNames.forEach(productName -> + productsByName.addAll(products.products().stream() + .filter(product -> product.name().equals(productName)) + .collect(Collectors.toSet())) + ); + return Products.from(productsByName); + } + + public Set<Product> products() { + return products.products(); + } +}
Java
์ค‘๋ณต ๋ฐฉ์ง€๋ฅผ ์œ„ํ•ด Set์„ ์‚ฌ์šฉํ•˜์…จ๋„ค์š”!! ๐Ÿ‘
@@ -0,0 +1,65 @@ +package store.model; + +import java.util.List; +import store.common.dto.PromotionResult; + +public class Receipt { + + private final Cart cart; + private final List<PromotionResult> promotionResults; + private final int totalPrice; + private final int promotionDiscount; + private final int membershipDiscount; + private final int paymentPrice; + + private Receipt( + Cart cart, + List<PromotionResult> promotionResults, + int totalPrice, + int promotionDiscount, + int membershipDiscount, + int paymentPrice + ) { + this.cart = cart; + this.promotionResults = promotionResults; + this.totalPrice = totalPrice; + this.promotionDiscount = promotionDiscount; + this.membershipDiscount = membershipDiscount; + this.paymentPrice = paymentPrice; + } + + public static Receipt of(Cart cart, List<PromotionResult> promotionResults, int membershipDiscount) { + int totalPrice = cart.cart().entrySet().stream() + .mapToInt(entry -> entry.getKey().price() * entry.getValue()) + .sum(); + int promotionDiscount = promotionResults.stream() + .mapToInt(PromotionResult::discountAmount) + .sum(); + return new Receipt(cart, promotionResults, totalPrice, promotionDiscount, membershipDiscount, + totalPrice - promotionDiscount - membershipDiscount); + } + + public Cart cart() { + return cart; + } + + public List<PromotionResult> promotionResults() { + return promotionResults; + } + + public int totalPrice() { + return totalPrice; + } + + public int promotionDiscount() { + return promotionDiscount; + } + + public int membershipDiscount() { + return membershipDiscount; + } + + public int paymentPrice() { + return paymentPrice; + } +}
Java
๋ฉ”์„œ๋“œ๋ฅผ ๋ถ„๋ฆฌํ•ด์„œ ๋‹จ์ผ ์ฑ…์ž„ ์›๋ฆฌ ์›์น™์„ ์ง€ํ‚ค๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”?
@@ -0,0 +1,162 @@ +package store.controller; + +import static store.common.constant.PromotionNotice.GET_FREE_M_NOTICE; +import static store.common.constant.PromotionNotice.OUT_OF_STOCK_NOTICE; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import store.common.dto.PromotionConditionResult; +import store.common.dto.PromotionResult; +import store.common.dto.PurchaseRequest; +import store.common.dto.PurchaseRequest.PurchaseProductNames; +import store.model.Cart; +import store.model.Product; +import store.model.ProductCatalog; +import store.model.Products; +import store.model.PromotionCatalog; +import store.model.Receipt; +import store.view.OutputView; + +public class StoreController { + + private final InputHandler inputHandler; + private final OutputView outputView; + + private final ProductCatalog productCatalog; + private final PromotionCatalog promotionCatalog; + + public StoreController(InputHandler inputHandler, OutputView outputView) { + this.inputHandler = inputHandler; + this.outputView = outputView; + promotionCatalog = inputHandler.getPromotions(); + productCatalog = inputHandler.getProducts(promotionCatalog); + } + + public void run() { + PurchaseRequest purchaseItems = getPurchaseRequest(); + Cart cart = Cart.empty(); + + Products promotionalProducts = getPromotionalProducts(purchaseItems.getProductNames()); + List<PromotionResult> promotionResults = addPromotionalProductToCart(promotionalProducts, purchaseItems, cart); + addRegularProductToCart(purchaseItems, cart); + int membershipDiscount = applyMembership(cart, promotionalProducts); + purchaseProducts(cart); + printReceipt(cart, promotionResults, membershipDiscount); + repurchaseIfWant(); + } + + private PurchaseRequest getPurchaseRequest() { + outputView.printStoreInventory(productCatalog); + return inputHandler.getPurchaseItems(productCatalog); + } + + private void addRegularProductToCart(PurchaseRequest purchaseItems, Cart cart) { + purchaseItems.items().keySet().forEach(productName -> { + Product product = productCatalog.getProductByName(productName).products().stream() + .findFirst() + .orElseThrow(IllegalArgumentException::new); + cart.addProduct(product, purchaseItems.items().get(productName)); + }); + } + + private List<PromotionResult> addPromotionalProductToCart( + Products promotionalProducts, PurchaseRequest purchaseItems, Cart cart + ) { + promotionalProducts.products().forEach(product -> { + int purchaseQuantity = purchaseItems.items().get(product.name()); + PromotionConditionResult conditionResult = product.checkPromotionCondition(purchaseQuantity); + handlePromotionCondition(purchaseItems, cart, product, conditionResult); + }); + return applyPromotion(cart); + } + + private Products getPromotionalProducts(PurchaseProductNames productNames) { + return Products.from( + productCatalog.getProductsByNames(productNames.productNames()).products().stream() + .filter(Product::isPromotionApplicable) + .collect(Collectors.toSet()) + ); + } + + private List<PromotionResult> applyPromotion(Cart cart) { + return cart.cart().keySet().stream() + .filter(Product::isPromotionApplicable) + .map(product -> product.applyPromotion(cart.cart().get(product))) + .toList(); + } + + private void handlePromotionCondition( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + if (GET_FREE_M_NOTICE.matches(conditionResult.message())) { + handleGetFreeCondition(purchaseItems, cart, product, conditionResult); + return; + } + if (OUT_OF_STOCK_NOTICE.matches(conditionResult.message())) { + handleOutOfPromotionStock(purchaseItems, cart, product, conditionResult); + return; + } + cart.addProduct(product, conditionResult.stockUsed()); + purchaseItems.items() + .replace(product.name(), purchaseItems.items().get(product.name()) - conditionResult.stockUsed()); + } + + private void handleOutOfPromotionStock( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + int purchaseQuantity = purchaseItems.items().get(product.name()); + outputView.printPromotionOutOfStockNotice(conditionResult.message()); + cart.addProduct(product, conditionResult.stockUsed()); + if (inputHandler.isAffirmative()) { + purchaseItems.items().replace(product.name(), purchaseQuantity - conditionResult.stockUsed()); + return; + } + purchaseItems.items().remove(product.name()); + } + + private void handleGetFreeCondition( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + int purchaseQuantity = purchaseItems.items().get(product.name()); + outputView.printGetFreeNotice(conditionResult.message()); + if (inputHandler.isAffirmative()) { + cart.addProduct(product, purchaseQuantity + 1); + purchaseItems.items().remove(product.name()); + return; + } + cart.addProduct(product, purchaseQuantity); + purchaseItems.items().remove(product.name()); + } + + private int applyMembership(Cart cart, Products promotionalProducts) { + outputView.printMembershipNotice(); + AtomicInteger discountAmount = new AtomicInteger(); + if (inputHandler.isAffirmative()) { + cart.cart().forEach((product, quantity) -> { + if (promotionalProducts.products().contains(product)) { + return; + } + discountAmount.addAndGet(product.price() * quantity); + }); + } + discountAmount.updateAndGet(value -> Math.min(value * 30 / 100, 8000)); + return discountAmount.get(); + } + + private static void purchaseProducts(Cart cart) { + cart.cart().forEach(Product::reduceStock); + } + + private void printReceipt(Cart cart, List<PromotionResult> promotionResults, int membershipDiscount) { + Receipt receipt = Receipt.of(cart, promotionResults, membershipDiscount); + outputView.printReceipt(receipt); + } + + private void repurchaseIfWant() { + outputView.printRepurchaseNotice(); + if (inputHandler.isAffirmative()) { + run(); + } + } +}
Java
์ด ๋ถ€๋ถ„์€ ๊ฐœ์ธ์ ์œผ๋กœ ๊ถ๊ธˆํ•œ ๋ถ€๋ถ„์ธ๋ฐ ์ธ์ž๊ฐ’์„ ์ด๋ ‡๊ฒŒ ์“ฐ์‹œ๋Š”๋ฐ ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ ๊ฑธ๊นŒ์š”? ๐Ÿค”
@@ -0,0 +1,60 @@ +package store.model.promotion; + +import static store.common.constant.PromotionNotice.DEFAULT_NOTICE; +import static store.common.constant.PromotionNotice.GET_FREE_M_NOTICE; +import static store.common.constant.PromotionNotice.OUT_OF_STOCK_NOTICE; + +import store.common.dto.PromotionConditionResult; +import store.common.dto.PromotionResult; +import store.model.Product; + +public class BuyNGetMFreePromotion implements PromotionStrategy { + + private final int purchaseQuantity; + private final int freeQuantity; + + public BuyNGetMFreePromotion(int purchaseQuantity, int freeQuantity) { + this.purchaseQuantity = purchaseQuantity; + this.freeQuantity = freeQuantity; + } + + @Override + public PromotionResult applyPromotion(Product product, int quantity) { + int totalFreeQuantity = getApplicableSetCount(quantity) * freeQuantity; + return PromotionResult.of(product.name(), product.price() * totalFreeQuantity, totalFreeQuantity); + } + + @Override + public PromotionConditionResult checkCondition(Product product, int quantity) { + int setCountFromRequest = getApplicableSetCount(quantity); + int setCountFromStock = getApplicableSetCount(product.stock()); + int applicableSetCount = Math.min(setCountFromRequest, setCountFromStock); + int stockUsed = applicableSetCount * getPromotionSetSize(); + int remainingQuantity = quantity - stockUsed; + + String message = getConditionMessage(product, product.stock() - stockUsed, remainingQuantity); + return PromotionConditionResult.from(applicableSetCount, stockUsed, remainingQuantity, message); + } + + private String getConditionMessage(Product product, int remainingStock, int remainingQuantity) { + if (remainingQuantity == purchaseQuantity && remainingStock > purchaseQuantity) { + return GET_FREE_M_NOTICE.message(product.name(), freeQuantity); + } + if (remainingQuantity >= getPromotionSetSize()) { + return OUT_OF_STOCK_NOTICE.message(product.name(), remainingQuantity); + } + return DEFAULT_NOTICE.message(); + } + + private int getPromotionSetSize() { + return purchaseQuantity + freeQuantity; + } + + private int getApplicableSetCount(int quantity) { + return quantity / getPromotionSetSize(); + } + + private int getRemainingQuantity(int quantity) { + return quantity % getPromotionSetSize(); + } +}
Java
PromotionStrategy ๊ตฌํ˜„์ฒด๋Š” BuyNGetMFreePromotion ๋ฟ ์ธ๊ฐ€์š”?
@@ -0,0 +1,14 @@ +package store.common.dto; + +public record PromotionConditionResult( + int applicableSetCount, + int stockUsed, + int remainingQuantity, + String message +) { + public static PromotionConditionResult from( + int applicableSetCount, int stockUsed, int remainingQuantity, String message + ) { + return new PromotionConditionResult(applicableSetCount, stockUsed, remainingQuantity, message); + } +}
Java
์•— ์•Œ๊ณ ๋Š” ์žˆ์—ˆ๋Š”๋ฐ ๋†“์ณค๋„ค์š”..๐Ÿฅฒ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!!
@@ -0,0 +1,24 @@ +package store.common.dto; + +import java.util.Map; +import java.util.Set; + +public record PurchaseRequest( + Map<String, Integer> items +) { + public static PurchaseRequest from(Map<String, Integer> cart) { + return new PurchaseRequest(cart); + } + + public PurchaseProductNames getProductNames() { + return PurchaseProductNames.from(items.keySet()); + } + + public record PurchaseProductNames( + Set<String> productNames + ) { + public static PurchaseProductNames from(Set<String> productNames) { + return new PurchaseProductNames(productNames); + } + } +}
Java
์ƒํ’ˆ ์ด๋ฆ„ ๋ชฉ๋ก์„ ํŒŒ๋ผ๋ฏธํ„ฐ์™€ ๋ฐ˜ํ™˜๊ฐ’์œผ๋กœ ์‚ฌ์šฉํ•˜๊ฒŒ ๋˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์ข€ ์žˆ์–ด์„œ dto ์— ๋‚ด๋ถ€ ํด๋ž˜์Šค๋กœ ์ •์˜ํ•ด ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค! ๊ทผ๋ฐ ์ข€ ํ†ต์ผ์„ฑ์ด ์—†๋‹ค๋Š” ๋А๋‚Œ์ด ๋“œ๋„ค์š”,,
@@ -0,0 +1,34 @@ +package store.common.util; + +import java.util.Arrays; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.IntStream; + +public class StringUtils { + + public static int parseInt(String message) { + try { + return Integer.parseInt(message); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(); + } + } + + public static List<String> splitWithDelimiter(String message, String delimiter) { + return Arrays.stream(message.split(delimiter)) + .map(String::strip) + .toList(); + } + + public static List<String> extractFromRegex(String message, Pattern regex) { + Matcher matcher = regex.matcher(message); + if (!matcher.matches()) { + throw new IllegalArgumentException(); + } + return IntStream.range(1, matcher.groupCount() + 1) + .mapToObj(matcher::group) + .toList(); + } +}
Java
์•„ ๋„ต! ์–ด์ฐจํ”ผ ํ•ด๋‹น ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ณณ์—์„œ catch ํ•˜๊ณ  ๋‹ค์‹œ ์˜ˆ์™ธ๋ฅผ ์ƒ์„ฑํ•ด์„œ ๊ตณ์ด ์‚ฌ์šฉํ•˜์ง€ ์•Š์„ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ์ •์˜ ํ•ด์•ผํ• ๊นŒ ๊ณ ๋ฏผํ•˜๋‹ค๊ฐ€ ๊ทธ๋ƒฅ ๋น„์›Œ๋’€๋Š”๋ฐ, ์ง€๊ธˆ ๋ณด๋‹ˆ๊นŒ ๊ทธ๋Ÿด๊ฑฐ๋ฉด ๊ทธ๋ƒฅ ์ด ๋ฉ”์„œ๋“œ์—์„œ๋Š” ์˜ˆ์™ธ๋ฅผ ์žก์ง€ ์•Š์•˜์œผ๋ฉด ๋๊ฒ ๋„ค์š”..! ๊ธ‰ํ•˜๊ฒŒ ๊ตฌํ˜„ํ•˜๋А๋ผ ์ด์ƒํ•œ ๋ถ€๋ถ„์ด ๋งŽ์€๋ฐ ์ฐพ์•„์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ˜ญ๐Ÿ™‡
@@ -0,0 +1,144 @@ +package store.controller; + +import static store.common.constant.ErrorMessage.INPUT_INVALID_FORMAT; +import static store.common.constant.ErrorMessage.PRODUCT_NOT_FOUND_ERROR; +import static store.common.constant.ErrorMessage.PRODUCT_OUT_OF_STOCK; + +import java.io.IOException; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Locale; +import java.util.function.Supplier; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import store.common.dto.PurchaseRequest; +import store.common.dto.PurchaseRequest.PurchaseProductNames; +import store.common.util.FileReader; +import store.common.util.StringUtils; +import store.model.Product; +import store.model.ProductCatalog; +import store.model.Products; +import store.model.Promotion; +import store.model.PromotionCatalog; +import store.model.promotion.BuyNGetMFreePromotion; +import store.model.promotion.PromotionStrategy; +import store.view.InputView; + +public class InputHandler { + + private static final Pattern PURCHASE_ITEM_REGEX = Pattern.compile("^\\[(.+)\\-(.+)\\]$"); + + private final InputView inputView; + + public InputHandler(InputView inputView) { + this.inputView = inputView; + } + + public PromotionCatalog getPromotions() { + try { + List<String> fileLines = FileReader.readFile("src/main/resources/promotions.md"); + return PromotionCatalog.from(fileLines.stream() + .skip(1) + .map(fileLine -> makePromotion(StringUtils.splitWithDelimiter(fileLine, ","))) + .collect(Collectors.toMap(Promotion::name, promotion -> promotion)) + ); + } catch (IOException e) { + throw new IllegalArgumentException(); + } + } + + public ProductCatalog getProducts(PromotionCatalog promotionCatalog) { + try { + List<String> fileLines = FileReader.readFile("src/main/resources/products.md"); + return ProductCatalog.from(fileLines.stream() + .skip(1) + .map(fileLine -> makeProduct(StringUtils.splitWithDelimiter(fileLine, ","), promotionCatalog)) + .collect(Collectors.toSet()) + ); + } catch (IOException e) { + throw new IllegalArgumentException(); + } + } + + public PurchaseRequest getPurchaseItems(ProductCatalog productCatalog) { + return validate(() -> { + List<String> purchaseItems = StringUtils.splitWithDelimiter(inputView.getPurchaseItems(), ","); + PurchaseRequest request = getPurchaseRequest(purchaseItems); + validateItemsExist(request.getProductNames(), productCatalog); + checkItemsStock(request, productCatalog); + return request; + }); + } + + private PurchaseRequest getPurchaseRequest(List<String> purchaseItems) { + try { + return PurchaseRequest.from( + purchaseItems.stream() + .map(purchaseItem -> StringUtils.extractFromRegex(purchaseItem, PURCHASE_ITEM_REGEX)) + .collect(Collectors.toMap(item -> item.get(0).strip(), + item -> StringUtils.parseInt(item.get(1)))) + ); + } catch (IllegalStateException e) { + throw new IllegalArgumentException(INPUT_INVALID_FORMAT.message()); + } + } + + public boolean isAffirmative() { + return validate(() -> { + String yesOrNo = inputView.getYesOrNo().toUpperCase(Locale.ROOT); + if (!yesOrNo.equals("Y") && !yesOrNo.equals("N")) { + throw new IllegalArgumentException(INPUT_INVALID_FORMAT.message()); + } + return yesOrNo.equals("Y"); + }); + } + + private Promotion makePromotion(List<String> promotionValues) { + DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE; + + String name = promotionValues.get(0); + int purchaseQuantity = StringUtils.parseInt(promotionValues.get(1)); + int freeQuantity = StringUtils.parseInt(promotionValues.get(2)); + PromotionStrategy promotionStrategy = new BuyNGetMFreePromotion(purchaseQuantity, freeQuantity); + LocalDate startDate = LocalDate.parse(promotionValues.get(3), formatter); + LocalDate endDate = LocalDate.parse(promotionValues.get(4), formatter); + return Promotion.of(name, promotionStrategy, startDate, endDate); + } + + private Product makeProduct(List<String> productValues, PromotionCatalog promotionCatalog) { + String name = productValues.get(0); + int price = StringUtils.parseInt(productValues.get(1)); + int stock = StringUtils.parseInt(productValues.get(2)); + Promotion promotion = promotionCatalog.getPromotionByName(productValues.get(3)); + return Product.of(name, price, stock, promotion); + } + + private void validateItemsExist(PurchaseProductNames productNames, ProductCatalog productCatalog) { + boolean doesNotContainsAllProduct = !productCatalog.doesContainsAllProduct(productNames.productNames()); + if (doesNotContainsAllProduct) { + throw new IllegalArgumentException(PRODUCT_NOT_FOUND_ERROR.message()); + } + } + + private void checkItemsStock(PurchaseRequest purchaseItems, ProductCatalog productCatalog) { + purchaseItems.items().forEach((productName, quantity) -> { + Products product = productCatalog.getProductByName(productName); + int totalStock = product.products().stream().mapToInt(Product::stock).sum(); + boolean isOutOfStock = quantity > totalStock; + if (isOutOfStock) { + throw new IllegalArgumentException(PRODUCT_OUT_OF_STOCK.message()); + } + }); + } + + private <T> T validate(Supplier<T> inputSupplier) { + while (true) { + try { + return inputSupplier.get(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } +}
Java
Locale.ROOT ๋Š” ๊ธฐ๋ณธ ์ง€์—ญ ์„ค์ •์œผ๋กœ, ์•ŒํŒŒ๋ฒณ์ด ๊ตญ๊ฐ€์— ๋”ฐ๋ผ ํ‘œ๊ธฐ๊ฐ€ ๋‹ค๋ฅธ ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ์‚ฌ์‹ค ์ฝ”๋“œ ์ž๋™์™„์„ฑ ๊ธฐ๋Šฅ์„ ์‚ฌ์šฉํ–ˆ๋Š”๋ฐ ๋ถˆํ•„์š”ํ•œ ๋ถ€๋ถ„์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค..!
@@ -0,0 +1,162 @@ +package store.controller; + +import static store.common.constant.PromotionNotice.GET_FREE_M_NOTICE; +import static store.common.constant.PromotionNotice.OUT_OF_STOCK_NOTICE; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import store.common.dto.PromotionConditionResult; +import store.common.dto.PromotionResult; +import store.common.dto.PurchaseRequest; +import store.common.dto.PurchaseRequest.PurchaseProductNames; +import store.model.Cart; +import store.model.Product; +import store.model.ProductCatalog; +import store.model.Products; +import store.model.PromotionCatalog; +import store.model.Receipt; +import store.view.OutputView; + +public class StoreController { + + private final InputHandler inputHandler; + private final OutputView outputView; + + private final ProductCatalog productCatalog; + private final PromotionCatalog promotionCatalog; + + public StoreController(InputHandler inputHandler, OutputView outputView) { + this.inputHandler = inputHandler; + this.outputView = outputView; + promotionCatalog = inputHandler.getPromotions(); + productCatalog = inputHandler.getProducts(promotionCatalog); + } + + public void run() { + PurchaseRequest purchaseItems = getPurchaseRequest(); + Cart cart = Cart.empty(); + + Products promotionalProducts = getPromotionalProducts(purchaseItems.getProductNames()); + List<PromotionResult> promotionResults = addPromotionalProductToCart(promotionalProducts, purchaseItems, cart); + addRegularProductToCart(purchaseItems, cart); + int membershipDiscount = applyMembership(cart, promotionalProducts); + purchaseProducts(cart); + printReceipt(cart, promotionResults, membershipDiscount); + repurchaseIfWant(); + } + + private PurchaseRequest getPurchaseRequest() { + outputView.printStoreInventory(productCatalog); + return inputHandler.getPurchaseItems(productCatalog); + } + + private void addRegularProductToCart(PurchaseRequest purchaseItems, Cart cart) { + purchaseItems.items().keySet().forEach(productName -> { + Product product = productCatalog.getProductByName(productName).products().stream() + .findFirst() + .orElseThrow(IllegalArgumentException::new); + cart.addProduct(product, purchaseItems.items().get(productName)); + }); + } + + private List<PromotionResult> addPromotionalProductToCart( + Products promotionalProducts, PurchaseRequest purchaseItems, Cart cart + ) { + promotionalProducts.products().forEach(product -> { + int purchaseQuantity = purchaseItems.items().get(product.name()); + PromotionConditionResult conditionResult = product.checkPromotionCondition(purchaseQuantity); + handlePromotionCondition(purchaseItems, cart, product, conditionResult); + }); + return applyPromotion(cart); + } + + private Products getPromotionalProducts(PurchaseProductNames productNames) { + return Products.from( + productCatalog.getProductsByNames(productNames.productNames()).products().stream() + .filter(Product::isPromotionApplicable) + .collect(Collectors.toSet()) + ); + } + + private List<PromotionResult> applyPromotion(Cart cart) { + return cart.cart().keySet().stream() + .filter(Product::isPromotionApplicable) + .map(product -> product.applyPromotion(cart.cart().get(product))) + .toList(); + } + + private void handlePromotionCondition( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + if (GET_FREE_M_NOTICE.matches(conditionResult.message())) { + handleGetFreeCondition(purchaseItems, cart, product, conditionResult); + return; + } + if (OUT_OF_STOCK_NOTICE.matches(conditionResult.message())) { + handleOutOfPromotionStock(purchaseItems, cart, product, conditionResult); + return; + } + cart.addProduct(product, conditionResult.stockUsed()); + purchaseItems.items() + .replace(product.name(), purchaseItems.items().get(product.name()) - conditionResult.stockUsed()); + } + + private void handleOutOfPromotionStock( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + int purchaseQuantity = purchaseItems.items().get(product.name()); + outputView.printPromotionOutOfStockNotice(conditionResult.message()); + cart.addProduct(product, conditionResult.stockUsed()); + if (inputHandler.isAffirmative()) { + purchaseItems.items().replace(product.name(), purchaseQuantity - conditionResult.stockUsed()); + return; + } + purchaseItems.items().remove(product.name()); + } + + private void handleGetFreeCondition( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + int purchaseQuantity = purchaseItems.items().get(product.name()); + outputView.printGetFreeNotice(conditionResult.message()); + if (inputHandler.isAffirmative()) { + cart.addProduct(product, purchaseQuantity + 1); + purchaseItems.items().remove(product.name()); + return; + } + cart.addProduct(product, purchaseQuantity); + purchaseItems.items().remove(product.name()); + } + + private int applyMembership(Cart cart, Products promotionalProducts) { + outputView.printMembershipNotice(); + AtomicInteger discountAmount = new AtomicInteger(); + if (inputHandler.isAffirmative()) { + cart.cart().forEach((product, quantity) -> { + if (promotionalProducts.products().contains(product)) { + return; + } + discountAmount.addAndGet(product.price() * quantity); + }); + } + discountAmount.updateAndGet(value -> Math.min(value * 30 / 100, 8000)); + return discountAmount.get(); + } + + private static void purchaseProducts(Cart cart) { + cart.cart().forEach(Product::reduceStock); + } + + private void printReceipt(Cart cart, List<PromotionResult> promotionResults, int membershipDiscount) { + Receipt receipt = Receipt.of(cart, promotionResults, membershipDiscount); + outputView.printReceipt(receipt); + } + + private void repurchaseIfWant() { + outputView.printRepurchaseNotice(); + if (inputHandler.isAffirmative()) { + run(); + } + } +}
Java
์•„ํ•˜.... ๋„ต.... ๋‹จ์ถ•ํ‚ค๋กœ extract ํ•˜๋ฉด์„œ ํ™•์ธํ•˜์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,162 @@ +package store.controller; + +import static store.common.constant.PromotionNotice.GET_FREE_M_NOTICE; +import static store.common.constant.PromotionNotice.OUT_OF_STOCK_NOTICE; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import store.common.dto.PromotionConditionResult; +import store.common.dto.PromotionResult; +import store.common.dto.PurchaseRequest; +import store.common.dto.PurchaseRequest.PurchaseProductNames; +import store.model.Cart; +import store.model.Product; +import store.model.ProductCatalog; +import store.model.Products; +import store.model.PromotionCatalog; +import store.model.Receipt; +import store.view.OutputView; + +public class StoreController { + + private final InputHandler inputHandler; + private final OutputView outputView; + + private final ProductCatalog productCatalog; + private final PromotionCatalog promotionCatalog; + + public StoreController(InputHandler inputHandler, OutputView outputView) { + this.inputHandler = inputHandler; + this.outputView = outputView; + promotionCatalog = inputHandler.getPromotions(); + productCatalog = inputHandler.getProducts(promotionCatalog); + } + + public void run() { + PurchaseRequest purchaseItems = getPurchaseRequest(); + Cart cart = Cart.empty(); + + Products promotionalProducts = getPromotionalProducts(purchaseItems.getProductNames()); + List<PromotionResult> promotionResults = addPromotionalProductToCart(promotionalProducts, purchaseItems, cart); + addRegularProductToCart(purchaseItems, cart); + int membershipDiscount = applyMembership(cart, promotionalProducts); + purchaseProducts(cart); + printReceipt(cart, promotionResults, membershipDiscount); + repurchaseIfWant(); + } + + private PurchaseRequest getPurchaseRequest() { + outputView.printStoreInventory(productCatalog); + return inputHandler.getPurchaseItems(productCatalog); + } + + private void addRegularProductToCart(PurchaseRequest purchaseItems, Cart cart) { + purchaseItems.items().keySet().forEach(productName -> { + Product product = productCatalog.getProductByName(productName).products().stream() + .findFirst() + .orElseThrow(IllegalArgumentException::new); + cart.addProduct(product, purchaseItems.items().get(productName)); + }); + } + + private List<PromotionResult> addPromotionalProductToCart( + Products promotionalProducts, PurchaseRequest purchaseItems, Cart cart + ) { + promotionalProducts.products().forEach(product -> { + int purchaseQuantity = purchaseItems.items().get(product.name()); + PromotionConditionResult conditionResult = product.checkPromotionCondition(purchaseQuantity); + handlePromotionCondition(purchaseItems, cart, product, conditionResult); + }); + return applyPromotion(cart); + } + + private Products getPromotionalProducts(PurchaseProductNames productNames) { + return Products.from( + productCatalog.getProductsByNames(productNames.productNames()).products().stream() + .filter(Product::isPromotionApplicable) + .collect(Collectors.toSet()) + ); + } + + private List<PromotionResult> applyPromotion(Cart cart) { + return cart.cart().keySet().stream() + .filter(Product::isPromotionApplicable) + .map(product -> product.applyPromotion(cart.cart().get(product))) + .toList(); + } + + private void handlePromotionCondition( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + if (GET_FREE_M_NOTICE.matches(conditionResult.message())) { + handleGetFreeCondition(purchaseItems, cart, product, conditionResult); + return; + } + if (OUT_OF_STOCK_NOTICE.matches(conditionResult.message())) { + handleOutOfPromotionStock(purchaseItems, cart, product, conditionResult); + return; + } + cart.addProduct(product, conditionResult.stockUsed()); + purchaseItems.items() + .replace(product.name(), purchaseItems.items().get(product.name()) - conditionResult.stockUsed()); + } + + private void handleOutOfPromotionStock( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + int purchaseQuantity = purchaseItems.items().get(product.name()); + outputView.printPromotionOutOfStockNotice(conditionResult.message()); + cart.addProduct(product, conditionResult.stockUsed()); + if (inputHandler.isAffirmative()) { + purchaseItems.items().replace(product.name(), purchaseQuantity - conditionResult.stockUsed()); + return; + } + purchaseItems.items().remove(product.name()); + } + + private void handleGetFreeCondition( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + int purchaseQuantity = purchaseItems.items().get(product.name()); + outputView.printGetFreeNotice(conditionResult.message()); + if (inputHandler.isAffirmative()) { + cart.addProduct(product, purchaseQuantity + 1); + purchaseItems.items().remove(product.name()); + return; + } + cart.addProduct(product, purchaseQuantity); + purchaseItems.items().remove(product.name()); + } + + private int applyMembership(Cart cart, Products promotionalProducts) { + outputView.printMembershipNotice(); + AtomicInteger discountAmount = new AtomicInteger(); + if (inputHandler.isAffirmative()) { + cart.cart().forEach((product, quantity) -> { + if (promotionalProducts.products().contains(product)) { + return; + } + discountAmount.addAndGet(product.price() * quantity); + }); + } + discountAmount.updateAndGet(value -> Math.min(value * 30 / 100, 8000)); + return discountAmount.get(); + } + + private static void purchaseProducts(Cart cart) { + cart.cart().forEach(Product::reduceStock); + } + + private void printReceipt(Cart cart, List<PromotionResult> promotionResults, int membershipDiscount) { + Receipt receipt = Receipt.of(cart, promotionResults, membershipDiscount); + outputView.printReceipt(receipt); + } + + private void repurchaseIfWant() { + outputView.printRepurchaseNotice(); + if (inputHandler.isAffirmative()) { + run(); + } + } +}
Java
๋งž์Šต๋‹ˆ๋‹ค ์ด๊ฒƒ๋„ ๊ณผ์ œ ๋งˆ๊ฐ ํ›„์— ๋ฐœ๊ฒฌํ–ˆ์–ด์š”..
@@ -0,0 +1,65 @@ +package store.model; + +import java.util.List; +import store.common.dto.PromotionResult; + +public class Receipt { + + private final Cart cart; + private final List<PromotionResult> promotionResults; + private final int totalPrice; + private final int promotionDiscount; + private final int membershipDiscount; + private final int paymentPrice; + + private Receipt( + Cart cart, + List<PromotionResult> promotionResults, + int totalPrice, + int promotionDiscount, + int membershipDiscount, + int paymentPrice + ) { + this.cart = cart; + this.promotionResults = promotionResults; + this.totalPrice = totalPrice; + this.promotionDiscount = promotionDiscount; + this.membershipDiscount = membershipDiscount; + this.paymentPrice = paymentPrice; + } + + public static Receipt of(Cart cart, List<PromotionResult> promotionResults, int membershipDiscount) { + int totalPrice = cart.cart().entrySet().stream() + .mapToInt(entry -> entry.getKey().price() * entry.getValue()) + .sum(); + int promotionDiscount = promotionResults.stream() + .mapToInt(PromotionResult::discountAmount) + .sum(); + return new Receipt(cart, promotionResults, totalPrice, promotionDiscount, membershipDiscount, + totalPrice - promotionDiscount - membershipDiscount); + } + + public Cart cart() { + return cart; + } + + public List<PromotionResult> promotionResults() { + return promotionResults; + } + + public int totalPrice() { + return totalPrice; + } + + public int promotionDiscount() { + return promotionDiscount; + } + + public int membershipDiscount() { + return membershipDiscount; + } + + public int paymentPrice() { + return paymentPrice; + } +}
Java
์˜คํ˜ธ totalPrice ์™€ promotionDiscount ๋ฅผ ๊ณ„์‚ฐํ•˜๋Š” ๋ถ€๋ถ„์„ ๋ถ„๋ฆฌํ•  ์ˆ˜ ์žˆ๊ฒ ๋„ค์š”! ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!!
@@ -0,0 +1,162 @@ +package store.controller; + +import static store.common.constant.PromotionNotice.GET_FREE_M_NOTICE; +import static store.common.constant.PromotionNotice.OUT_OF_STOCK_NOTICE; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import store.common.dto.PromotionConditionResult; +import store.common.dto.PromotionResult; +import store.common.dto.PurchaseRequest; +import store.common.dto.PurchaseRequest.PurchaseProductNames; +import store.model.Cart; +import store.model.Product; +import store.model.ProductCatalog; +import store.model.Products; +import store.model.PromotionCatalog; +import store.model.Receipt; +import store.view.OutputView; + +public class StoreController { + + private final InputHandler inputHandler; + private final OutputView outputView; + + private final ProductCatalog productCatalog; + private final PromotionCatalog promotionCatalog; + + public StoreController(InputHandler inputHandler, OutputView outputView) { + this.inputHandler = inputHandler; + this.outputView = outputView; + promotionCatalog = inputHandler.getPromotions(); + productCatalog = inputHandler.getProducts(promotionCatalog); + } + + public void run() { + PurchaseRequest purchaseItems = getPurchaseRequest(); + Cart cart = Cart.empty(); + + Products promotionalProducts = getPromotionalProducts(purchaseItems.getProductNames()); + List<PromotionResult> promotionResults = addPromotionalProductToCart(promotionalProducts, purchaseItems, cart); + addRegularProductToCart(purchaseItems, cart); + int membershipDiscount = applyMembership(cart, promotionalProducts); + purchaseProducts(cart); + printReceipt(cart, promotionResults, membershipDiscount); + repurchaseIfWant(); + } + + private PurchaseRequest getPurchaseRequest() { + outputView.printStoreInventory(productCatalog); + return inputHandler.getPurchaseItems(productCatalog); + } + + private void addRegularProductToCart(PurchaseRequest purchaseItems, Cart cart) { + purchaseItems.items().keySet().forEach(productName -> { + Product product = productCatalog.getProductByName(productName).products().stream() + .findFirst() + .orElseThrow(IllegalArgumentException::new); + cart.addProduct(product, purchaseItems.items().get(productName)); + }); + } + + private List<PromotionResult> addPromotionalProductToCart( + Products promotionalProducts, PurchaseRequest purchaseItems, Cart cart + ) { + promotionalProducts.products().forEach(product -> { + int purchaseQuantity = purchaseItems.items().get(product.name()); + PromotionConditionResult conditionResult = product.checkPromotionCondition(purchaseQuantity); + handlePromotionCondition(purchaseItems, cart, product, conditionResult); + }); + return applyPromotion(cart); + } + + private Products getPromotionalProducts(PurchaseProductNames productNames) { + return Products.from( + productCatalog.getProductsByNames(productNames.productNames()).products().stream() + .filter(Product::isPromotionApplicable) + .collect(Collectors.toSet()) + ); + } + + private List<PromotionResult> applyPromotion(Cart cart) { + return cart.cart().keySet().stream() + .filter(Product::isPromotionApplicable) + .map(product -> product.applyPromotion(cart.cart().get(product))) + .toList(); + } + + private void handlePromotionCondition( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + if (GET_FREE_M_NOTICE.matches(conditionResult.message())) { + handleGetFreeCondition(purchaseItems, cart, product, conditionResult); + return; + } + if (OUT_OF_STOCK_NOTICE.matches(conditionResult.message())) { + handleOutOfPromotionStock(purchaseItems, cart, product, conditionResult); + return; + } + cart.addProduct(product, conditionResult.stockUsed()); + purchaseItems.items() + .replace(product.name(), purchaseItems.items().get(product.name()) - conditionResult.stockUsed()); + } + + private void handleOutOfPromotionStock( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + int purchaseQuantity = purchaseItems.items().get(product.name()); + outputView.printPromotionOutOfStockNotice(conditionResult.message()); + cart.addProduct(product, conditionResult.stockUsed()); + if (inputHandler.isAffirmative()) { + purchaseItems.items().replace(product.name(), purchaseQuantity - conditionResult.stockUsed()); + return; + } + purchaseItems.items().remove(product.name()); + } + + private void handleGetFreeCondition( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + int purchaseQuantity = purchaseItems.items().get(product.name()); + outputView.printGetFreeNotice(conditionResult.message()); + if (inputHandler.isAffirmative()) { + cart.addProduct(product, purchaseQuantity + 1); + purchaseItems.items().remove(product.name()); + return; + } + cart.addProduct(product, purchaseQuantity); + purchaseItems.items().remove(product.name()); + } + + private int applyMembership(Cart cart, Products promotionalProducts) { + outputView.printMembershipNotice(); + AtomicInteger discountAmount = new AtomicInteger(); + if (inputHandler.isAffirmative()) { + cart.cart().forEach((product, quantity) -> { + if (promotionalProducts.products().contains(product)) { + return; + } + discountAmount.addAndGet(product.price() * quantity); + }); + } + discountAmount.updateAndGet(value -> Math.min(value * 30 / 100, 8000)); + return discountAmount.get(); + } + + private static void purchaseProducts(Cart cart) { + cart.cart().forEach(Product::reduceStock); + } + + private void printReceipt(Cart cart, List<PromotionResult> promotionResults, int membershipDiscount) { + Receipt receipt = Receipt.of(cart, promotionResults, membershipDiscount); + outputView.printReceipt(receipt); + } + + private void repurchaseIfWant() { + outputView.printRepurchaseNotice(); + if (inputHandler.isAffirmative()) { + run(); + } + } +}
Java
์•„ ์ฝ”๋“œ ์Šคํƒ€์ผ์— ์šฐํ…Œ์ฝ” ์Šคํ‚ค๋งˆ๋ฅผ ์ ์šฉํ•˜๋‹ˆ๊นŒ ๋ผ์ธ์ด ๊ธธ์–ด์ง€๋ฉด ๋งˆ์ง€๋ง‰ ์ธ์ž๊ฐ’๋งŒ ๊ฐœํ–‰๋ผ๋”๋ผ๊ตฌ์š”.. ํ†ต์ผ์„ฑ์ด ์—†์–ด๋ณด์ด๋Š”๋ฐ ๋˜ ํ•˜๋‚˜ํ•˜๋‚˜ ๊ฐœํ–‰ํ•˜์ž๋‹ˆ ๋„ˆ๋ฌด ๊ธธ์–ด๋ณด์—ฌ์„œ ๊ทธ๋ƒฅ ์ด๋ ‡๊ฒŒ ํ•ด๋ดค์Šต๋‹ˆ๋‹ค! @discphy ๋‹˜์€ ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฐœ์ˆ˜๊ฐ€ ๋งŽ์•„์งˆ ๋•Œ ์–ด๋–ป๊ฒŒ ํฌ๋งทํŒ…ํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,60 @@ +package store.model.promotion; + +import static store.common.constant.PromotionNotice.DEFAULT_NOTICE; +import static store.common.constant.PromotionNotice.GET_FREE_M_NOTICE; +import static store.common.constant.PromotionNotice.OUT_OF_STOCK_NOTICE; + +import store.common.dto.PromotionConditionResult; +import store.common.dto.PromotionResult; +import store.model.Product; + +public class BuyNGetMFreePromotion implements PromotionStrategy { + + private final int purchaseQuantity; + private final int freeQuantity; + + public BuyNGetMFreePromotion(int purchaseQuantity, int freeQuantity) { + this.purchaseQuantity = purchaseQuantity; + this.freeQuantity = freeQuantity; + } + + @Override + public PromotionResult applyPromotion(Product product, int quantity) { + int totalFreeQuantity = getApplicableSetCount(quantity) * freeQuantity; + return PromotionResult.of(product.name(), product.price() * totalFreeQuantity, totalFreeQuantity); + } + + @Override + public PromotionConditionResult checkCondition(Product product, int quantity) { + int setCountFromRequest = getApplicableSetCount(quantity); + int setCountFromStock = getApplicableSetCount(product.stock()); + int applicableSetCount = Math.min(setCountFromRequest, setCountFromStock); + int stockUsed = applicableSetCount * getPromotionSetSize(); + int remainingQuantity = quantity - stockUsed; + + String message = getConditionMessage(product, product.stock() - stockUsed, remainingQuantity); + return PromotionConditionResult.from(applicableSetCount, stockUsed, remainingQuantity, message); + } + + private String getConditionMessage(Product product, int remainingStock, int remainingQuantity) { + if (remainingQuantity == purchaseQuantity && remainingStock > purchaseQuantity) { + return GET_FREE_M_NOTICE.message(product.name(), freeQuantity); + } + if (remainingQuantity >= getPromotionSetSize()) { + return OUT_OF_STOCK_NOTICE.message(product.name(), remainingQuantity); + } + return DEFAULT_NOTICE.message(); + } + + private int getPromotionSetSize() { + return purchaseQuantity + freeQuantity; + } + + private int getApplicableSetCount(int quantity) { + return quantity / getPromotionSetSize(); + } + + private int getRemainingQuantity(int quantity) { + return quantity % getPromotionSetSize(); + } +}
Java
์•„ ๋„ต! ์ด ๋ถ€๋ถ„์€ ์ธํ„ฐํŽ˜์ด์Šค๋กœ ํ™•์žฅ์„ฑ ์žˆ๊ฒŒ ๋งŒ๋“ค์–ด ๋ณด๊ณ  ์‹ถ์—ˆ๋Š”๋ฐ, ๊ตฌํ˜„์€ ๋ชจ๋‘ ์š”๊ตฌ์‚ฌํ•ญ ๋ฒ”์œ„ ๋‚ด์—์„œ๋งŒ ํ–ˆ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,162 @@ +package store.controller; + +import static store.common.constant.PromotionNotice.GET_FREE_M_NOTICE; +import static store.common.constant.PromotionNotice.OUT_OF_STOCK_NOTICE; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import store.common.dto.PromotionConditionResult; +import store.common.dto.PromotionResult; +import store.common.dto.PurchaseRequest; +import store.common.dto.PurchaseRequest.PurchaseProductNames; +import store.model.Cart; +import store.model.Product; +import store.model.ProductCatalog; +import store.model.Products; +import store.model.PromotionCatalog; +import store.model.Receipt; +import store.view.OutputView; + +public class StoreController { + + private final InputHandler inputHandler; + private final OutputView outputView; + + private final ProductCatalog productCatalog; + private final PromotionCatalog promotionCatalog; + + public StoreController(InputHandler inputHandler, OutputView outputView) { + this.inputHandler = inputHandler; + this.outputView = outputView; + promotionCatalog = inputHandler.getPromotions(); + productCatalog = inputHandler.getProducts(promotionCatalog); + } + + public void run() { + PurchaseRequest purchaseItems = getPurchaseRequest(); + Cart cart = Cart.empty(); + + Products promotionalProducts = getPromotionalProducts(purchaseItems.getProductNames()); + List<PromotionResult> promotionResults = addPromotionalProductToCart(promotionalProducts, purchaseItems, cart); + addRegularProductToCart(purchaseItems, cart); + int membershipDiscount = applyMembership(cart, promotionalProducts); + purchaseProducts(cart); + printReceipt(cart, promotionResults, membershipDiscount); + repurchaseIfWant(); + } + + private PurchaseRequest getPurchaseRequest() { + outputView.printStoreInventory(productCatalog); + return inputHandler.getPurchaseItems(productCatalog); + } + + private void addRegularProductToCart(PurchaseRequest purchaseItems, Cart cart) { + purchaseItems.items().keySet().forEach(productName -> { + Product product = productCatalog.getProductByName(productName).products().stream() + .findFirst() + .orElseThrow(IllegalArgumentException::new); + cart.addProduct(product, purchaseItems.items().get(productName)); + }); + } + + private List<PromotionResult> addPromotionalProductToCart( + Products promotionalProducts, PurchaseRequest purchaseItems, Cart cart + ) { + promotionalProducts.products().forEach(product -> { + int purchaseQuantity = purchaseItems.items().get(product.name()); + PromotionConditionResult conditionResult = product.checkPromotionCondition(purchaseQuantity); + handlePromotionCondition(purchaseItems, cart, product, conditionResult); + }); + return applyPromotion(cart); + } + + private Products getPromotionalProducts(PurchaseProductNames productNames) { + return Products.from( + productCatalog.getProductsByNames(productNames.productNames()).products().stream() + .filter(Product::isPromotionApplicable) + .collect(Collectors.toSet()) + ); + } + + private List<PromotionResult> applyPromotion(Cart cart) { + return cart.cart().keySet().stream() + .filter(Product::isPromotionApplicable) + .map(product -> product.applyPromotion(cart.cart().get(product))) + .toList(); + } + + private void handlePromotionCondition( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + if (GET_FREE_M_NOTICE.matches(conditionResult.message())) { + handleGetFreeCondition(purchaseItems, cart, product, conditionResult); + return; + } + if (OUT_OF_STOCK_NOTICE.matches(conditionResult.message())) { + handleOutOfPromotionStock(purchaseItems, cart, product, conditionResult); + return; + } + cart.addProduct(product, conditionResult.stockUsed()); + purchaseItems.items() + .replace(product.name(), purchaseItems.items().get(product.name()) - conditionResult.stockUsed()); + } + + private void handleOutOfPromotionStock( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + int purchaseQuantity = purchaseItems.items().get(product.name()); + outputView.printPromotionOutOfStockNotice(conditionResult.message()); + cart.addProduct(product, conditionResult.stockUsed()); + if (inputHandler.isAffirmative()) { + purchaseItems.items().replace(product.name(), purchaseQuantity - conditionResult.stockUsed()); + return; + } + purchaseItems.items().remove(product.name()); + } + + private void handleGetFreeCondition( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + int purchaseQuantity = purchaseItems.items().get(product.name()); + outputView.printGetFreeNotice(conditionResult.message()); + if (inputHandler.isAffirmative()) { + cart.addProduct(product, purchaseQuantity + 1); + purchaseItems.items().remove(product.name()); + return; + } + cart.addProduct(product, purchaseQuantity); + purchaseItems.items().remove(product.name()); + } + + private int applyMembership(Cart cart, Products promotionalProducts) { + outputView.printMembershipNotice(); + AtomicInteger discountAmount = new AtomicInteger(); + if (inputHandler.isAffirmative()) { + cart.cart().forEach((product, quantity) -> { + if (promotionalProducts.products().contains(product)) { + return; + } + discountAmount.addAndGet(product.price() * quantity); + }); + } + discountAmount.updateAndGet(value -> Math.min(value * 30 / 100, 8000)); + return discountAmount.get(); + } + + private static void purchaseProducts(Cart cart) { + cart.cart().forEach(Product::reduceStock); + } + + private void printReceipt(Cart cart, List<PromotionResult> promotionResults, int membershipDiscount) { + Receipt receipt = Receipt.of(cart, promotionResults, membershipDiscount); + outputView.printReceipt(receipt); + } + + private void repurchaseIfWant() { + outputView.printRepurchaseNotice(); + if (inputHandler.isAffirmative()) { + run(); + } + } +}
Java
์ €๋Š” ๋‚˜๋ฆ„๋Œ€๋กœ์˜ ์ปจ๋ฒค์…˜์„ ์œ ์ง€ํ•˜๋ ค๊ณ  ํ•˜๋Š”๋ฐ ๋˜๋„๋ก์ด๋ฉด(?) ์ธ์ž๊ฐ’์ด 3๊ฐœ๊ฐ€ ๋„˜์–ด๊ฐ€๋ฉด Dto ๊ฐ์ฒด๋กœ ๋ถ„๋ฆฌํ•˜๊ณค ํ•ฉ๋‹ˆ๋‹ค! ๐Ÿ™ƒ
@@ -0,0 +1,162 @@ +package store.controller; + +import static store.common.constant.PromotionNotice.GET_FREE_M_NOTICE; +import static store.common.constant.PromotionNotice.OUT_OF_STOCK_NOTICE; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import store.common.dto.PromotionConditionResult; +import store.common.dto.PromotionResult; +import store.common.dto.PurchaseRequest; +import store.common.dto.PurchaseRequest.PurchaseProductNames; +import store.model.Cart; +import store.model.Product; +import store.model.ProductCatalog; +import store.model.Products; +import store.model.PromotionCatalog; +import store.model.Receipt; +import store.view.OutputView; + +public class StoreController { + + private final InputHandler inputHandler; + private final OutputView outputView; + + private final ProductCatalog productCatalog; + private final PromotionCatalog promotionCatalog; + + public StoreController(InputHandler inputHandler, OutputView outputView) { + this.inputHandler = inputHandler; + this.outputView = outputView; + promotionCatalog = inputHandler.getPromotions(); + productCatalog = inputHandler.getProducts(promotionCatalog); + } + + public void run() { + PurchaseRequest purchaseItems = getPurchaseRequest(); + Cart cart = Cart.empty(); + + Products promotionalProducts = getPromotionalProducts(purchaseItems.getProductNames()); + List<PromotionResult> promotionResults = addPromotionalProductToCart(promotionalProducts, purchaseItems, cart); + addRegularProductToCart(purchaseItems, cart); + int membershipDiscount = applyMembership(cart, promotionalProducts); + purchaseProducts(cart); + printReceipt(cart, promotionResults, membershipDiscount); + repurchaseIfWant(); + } + + private PurchaseRequest getPurchaseRequest() { + outputView.printStoreInventory(productCatalog); + return inputHandler.getPurchaseItems(productCatalog); + } + + private void addRegularProductToCart(PurchaseRequest purchaseItems, Cart cart) { + purchaseItems.items().keySet().forEach(productName -> { + Product product = productCatalog.getProductByName(productName).products().stream() + .findFirst() + .orElseThrow(IllegalArgumentException::new); + cart.addProduct(product, purchaseItems.items().get(productName)); + }); + } + + private List<PromotionResult> addPromotionalProductToCart( + Products promotionalProducts, PurchaseRequest purchaseItems, Cart cart + ) { + promotionalProducts.products().forEach(product -> { + int purchaseQuantity = purchaseItems.items().get(product.name()); + PromotionConditionResult conditionResult = product.checkPromotionCondition(purchaseQuantity); + handlePromotionCondition(purchaseItems, cart, product, conditionResult); + }); + return applyPromotion(cart); + } + + private Products getPromotionalProducts(PurchaseProductNames productNames) { + return Products.from( + productCatalog.getProductsByNames(productNames.productNames()).products().stream() + .filter(Product::isPromotionApplicable) + .collect(Collectors.toSet()) + ); + } + + private List<PromotionResult> applyPromotion(Cart cart) { + return cart.cart().keySet().stream() + .filter(Product::isPromotionApplicable) + .map(product -> product.applyPromotion(cart.cart().get(product))) + .toList(); + } + + private void handlePromotionCondition( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + if (GET_FREE_M_NOTICE.matches(conditionResult.message())) { + handleGetFreeCondition(purchaseItems, cart, product, conditionResult); + return; + } + if (OUT_OF_STOCK_NOTICE.matches(conditionResult.message())) { + handleOutOfPromotionStock(purchaseItems, cart, product, conditionResult); + return; + } + cart.addProduct(product, conditionResult.stockUsed()); + purchaseItems.items() + .replace(product.name(), purchaseItems.items().get(product.name()) - conditionResult.stockUsed()); + } + + private void handleOutOfPromotionStock( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + int purchaseQuantity = purchaseItems.items().get(product.name()); + outputView.printPromotionOutOfStockNotice(conditionResult.message()); + cart.addProduct(product, conditionResult.stockUsed()); + if (inputHandler.isAffirmative()) { + purchaseItems.items().replace(product.name(), purchaseQuantity - conditionResult.stockUsed()); + return; + } + purchaseItems.items().remove(product.name()); + } + + private void handleGetFreeCondition( + PurchaseRequest purchaseItems, Cart cart, Product product, PromotionConditionResult conditionResult + ) { + int purchaseQuantity = purchaseItems.items().get(product.name()); + outputView.printGetFreeNotice(conditionResult.message()); + if (inputHandler.isAffirmative()) { + cart.addProduct(product, purchaseQuantity + 1); + purchaseItems.items().remove(product.name()); + return; + } + cart.addProduct(product, purchaseQuantity); + purchaseItems.items().remove(product.name()); + } + + private int applyMembership(Cart cart, Products promotionalProducts) { + outputView.printMembershipNotice(); + AtomicInteger discountAmount = new AtomicInteger(); + if (inputHandler.isAffirmative()) { + cart.cart().forEach((product, quantity) -> { + if (promotionalProducts.products().contains(product)) { + return; + } + discountAmount.addAndGet(product.price() * quantity); + }); + } + discountAmount.updateAndGet(value -> Math.min(value * 30 / 100, 8000)); + return discountAmount.get(); + } + + private static void purchaseProducts(Cart cart) { + cart.cart().forEach(Product::reduceStock); + } + + private void printReceipt(Cart cart, List<PromotionResult> promotionResults, int membershipDiscount) { + Receipt receipt = Receipt.of(cart, promotionResults, membershipDiscount); + outputView.printReceipt(receipt); + } + + private void repurchaseIfWant() { + outputView.printRepurchaseNotice(); + if (inputHandler.isAffirmative()) { + run(); + } + } +}
Java
์•„ํ•˜ dto ๋กœ ๋ถ„๋ฆฌํ•˜์‹œ๋Š”๊ตฐ์š”! ๋ง์”€ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿ˜Š
@@ -0,0 +1,71 @@ +package hanghaeplus.signupforlecture.application.lecture.facade; + +import hanghaeplus.signupforlecture.application.lecture.domain.model.Lecture; +import hanghaeplus.signupforlecture.application.lecture.domain.model.LectureCapacity; +import hanghaeplus.signupforlecture.application.lecture.dto.request.LectureApplyRequestDto; +import hanghaeplus.signupforlecture.application.lecture.dto.request.LectureAvailableRequestDto; +import hanghaeplus.signupforlecture.application.lecture.dto.response.LectureAvailableResponseDto; +import hanghaeplus.signupforlecture.application.lecture.dto.response.LectureSignedUpResponseDto; +import hanghaeplus.signupforlecture.application.lecture.service.LectureApplyHistoryService; +import hanghaeplus.signupforlecture.application.lecture.service.LectureCapacityService; +import hanghaeplus.signupforlecture.application.lecture.service.LectureService; +import hanghaeplus.signupforlecture.application.user.domain.model.User; +import hanghaeplus.signupforlecture.application.user.service.UserService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Component +@RequiredArgsConstructor +public class LectureFacade { + + private final UserService userService; + + private final LectureService lectureService; + private final LectureApplyHistoryService lectureApplyHistoryService; + private final LectureCapacityService lectureCapacityService; + + public List<LectureAvailableResponseDto> getAvailableLectures(LectureAvailableRequestDto lectureAvailableRequestDto) { + List<Lecture> availableLectureIds = lectureService.getAvailableLectures(lectureAvailableRequestDto.requestDate()); + List<LectureCapacity> availableLectures = lectureCapacityService.getAvailableSlot(availableLectureIds); + + return LectureAvailableResponseDto.fromDomains(availableLectureIds, availableLectures); + } + + @Transactional + public void applyLecture(Long lectureId, LectureApplyRequestDto lectureApplyRequestDto) { + User user = userService.getUser(lectureApplyRequestDto.userId()); + Lecture lecture = lectureService.getLecture(lectureId); + + try { + // ์ค‘๋ณต ์ฒดํฌ (history ํ…Œ์ด๋ธ”) + lectureApplyHistoryService.checkApplyLectureHistory(lecture.id(), user.id()); + + // ์‹ ์ฒญ ๊ฐ€๋Šฅํ•œ Slot (lectureCapacity ํ…Œ์ด๋ธ”) ์กฐํšŒ <๋ฝ ํš๋“> + LectureCapacity lectureCapacity = lectureCapacityService.getAvailableSlotLock(lecture.id()); + + // ๋‚ด์—ญ ์ €์žฅ (history ํ…Œ์ด๋ธ”) + lectureApplyHistoryService.insertAppliedHistory(lecture, user.id()); + + // ์‹ ์ฒญ ๊ฐ€๋Šฅ Slot - 1 ๋กœ์ง >> ์ €์žฅ (lectureCapacity ํ…Œ์ด๋ธ”) + lectureCapacityService.applyAvailableSlot(lectureCapacity); + } catch (RuntimeException e) { + lectureApplyHistoryService.insertFailedHistory(lecture, user.id()); + } + } + + public List<LectureSignedUpResponseDto> getSignedUpLectures(Long userId) { + User user = userService.getUser(userId); + + List<Long> signedUpLectureIds = lectureApplyHistoryService.findSignedUpLectureHistories(user.id()); + List<Lecture> signedUpLectures = lectureService.findSignedUpLectures(signedUpLectureIds); + + return signedUpLectures.stream() + .map(LectureSignedUpResponseDto::fromDomain) + .toList(); + } +}
Java
์ •ํ™•ํ•œ ์ด์œ ๋Š” ๋ชจ๋ฅด๊ฒ ์ง€๋งŒ ํ•ด๋‹น ๋ฝ ํš๋“ ์ฝ”๋“œ๊ฐ€ ๋ฉ”์„œ๋“œ ์ตœ์ƒ๋‹จ์œผ๋กœ ์˜ฌ๋ผ๊ฐ€๋ฉด `fail_applyLecture2` ํ…Œ์ŠคํŠธ๊ฐ€ ์ •์ƒ ์ง„ํ–‰์ด ๋ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,44 @@ +## Default +- [x] ์•„ํ‚คํ…์ฒ˜ ์ค€์ˆ˜๋ฅผ ์œ„ํ•œ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ํŒจํ‚ค์ง€ ์„ค๊ณ„ +- [x] ํŠน๊ฐ• ๋„๋ฉ”์ธ ํ…Œ์ด๋ธ” ์„ค๊ณ„ ๋ฐ ๋ชฉ๋ก/์‹ ์ฒญ ๋“ฑ ๊ธฐ๋ณธ ๊ธฐ๋Šฅ ๊ตฌํ˜„ +- [x] ๊ฐ ๊ธฐ๋Šฅ์— ๋Œ€ํ•œ **๋‹จ์œ„ ํ…Œ์ŠคํŠธ** ์ž‘์„ฑ + +--- +### ์„ธ๋ถ€ API +- [x] ํŠน๊ฐ• ์„ ํƒ API (=์‹ ์ฒญ ๊ฐ€๋Šฅ ๊ฐ•์˜ ๋ชฉ๋ก ์กฐํšŒ API) + * ๋‚ ์งœ๋ณ„๋กœ ํ˜„์žฌ ์‹ ์ฒญ ๊ฐ€๋Šฅํ•œ ํŠน๊ฐ• ๋ชฉ๋ก์„ ์กฐํšŒํ•˜๋Š” API ๋ฅผ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค. + * ํŠน๊ฐ•์˜ ์ •์›์€ 30๋ช…์œผ๋กœ ๊ณ ์ •์ด๋ฉฐ, ์‚ฌ์šฉ์ž๋Š” ๊ฐ ํŠน๊ฐ•์— ์‹ ์ฒญํ•˜๊ธฐ์ „ ๋ชฉ๋ก์„ ์กฐํšŒํ•ด๋ณผ ์ˆ˜ ์žˆ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. + + **๋‹จ์œ„ ํ…Œ์ŠคํŠธ** + - [x] ํŒŒ๋ผ๋ฏธํ„ฐ validator + - [x] ์š”์ฒญ๋œ ๋‚ ์งœ์— ํ•ด๋‹น๋˜๋Š” ๊ฐ•์˜๊ฐ€ ์—†์œผ๋ฉด ์˜ˆ์™ธ๋ฐœ์ƒ + - [x] ์š”์ฒญ๋œ ๋‚ ์งœ์— ํ•ด๋‹น๋˜๋Š” ๊ฐ•์˜ ๋ชฉ๋ก ์กฐํšŒ + + > (์š”์ฒญํ•œ ๋‚ ์งœ์— ์žˆ๋Š” ๊ฐ•์˜ + "์‹ ์ฒญ๊ฐ€๋Šฅ ์ธ์›์ˆ˜ = 0์ดˆ๊ณผ") ๊ฐ•์˜ ๋ชฉ๋ก ์กฐํšŒ + +<br> + +- [x] ํŠน๊ฐ• ์‹ ์ฒญ ์™„๋ฃŒ ๋ชฉ๋ก ์กฐํšŒ API + * ํŠน์ • userId ๋กœ ์‹ ์ฒญ ์™„๋ฃŒ๋œ ํŠน๊ฐ• ๋ชฉ๋ก์„ ์กฐํšŒํ•˜๋Š” API ๋ฅผ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค. + * ๊ฐ ํ•ญ๋ชฉ์€ ํŠน๊ฐ• ID ๋ฐ ์ด๋ฆ„, ๊ฐ•์—ฐ์ž ์ •๋ณด๋ฅผ ๋‹ด๊ณ  ์žˆ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. + + **๋‹จ์œ„ ํ…Œ์ŠคํŠธ** + - [x] ํŒŒ๋ผ๋ฏธํ„ฐ validator + - [x] ์œ ์ € ์œ ๋ฌด + +<br> + +- [x] ํŠน๊ฐ• ์‹ ์ฒญ API + * ํŠน์ • userId ๋กœ ์„ ์ฐฉ์ˆœ์œผ๋กœ ์ œ๊ณต๋˜๋Š” ํŠน๊ฐ•์„ ์‹ ์ฒญํ•˜๋Š” API ๋ฅผ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค. + * ๋™์ผํ•œ ์‹ ์ฒญ์ž๋Š” ๋™์ผํ•œ ๊ฐ•์˜์— ๋Œ€ํ•ด์„œ ํ•œ ๋ฒˆ์˜ ์ˆ˜๊ฐ• ์‹ ์ฒญ๋งŒ ์„ฑ๊ณตํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. + * ํŠน๊ฐ•์€ ์„ ์ฐฉ์ˆœ 30๋ช…๋งŒ ์‹ ์ฒญ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค. + * ์ด๋ฏธ ์‹ ์ฒญ์ž๊ฐ€ 30๋ช…์ด ์ดˆ๊ณผ๋˜๋ฉด ์ดํ›„ ์‹ ์ฒญ์ž๋Š” ์š”์ฒญ์„ ์‹คํŒจํ•ฉ๋‹ˆ๋‹ค. + + **๋‹จ์œ„ ํ…Œ์ŠคํŠธ** + - [x] ํŒŒ๋ผ๋ฏธํ„ฐ validator + - [x] ์œ ์ €๊ฐ€ ์—†์œผ๋ฉด ์˜ˆ์™ธ ๋ฐœ์ƒ + - [x] ๊ฐ•์˜๊ฐ€ ์—†์œผ๋ฉด ์˜ˆ์™ธ ๋ฐœ์ƒ + - [x] ์ค‘๋ณต ์‹ ์ฒญ ์˜ˆ์™ธ๋ฐœ์ƒ (๋™์ผํ•œ ์‹ ์ฒญ์ž๋Š” ๋™์ผํ•œ ๊ฐ•์˜์— ๋Œ€ํ•ด์„œ ํ•œ ๋ฒˆ์˜ ์ˆ˜๊ฐ• ์‹ ์ฒญ๋งŒ ๊ฐ€๋Šฅ) + - [x] ๋‚จ์€ ์ž๋ฆฌ๊ฐ€ ์—†์œผ๋ฉด ์˜ˆ์™ธ๋ฐœ์ƒ (30๋ช…์ด ์ดˆ๊ณผ๋œ ์ƒํƒœ) + - [x] (์‹ ์ฒญ ๊ฐ€๋Šฅํ•œ ์ž๋ฆฌ์ˆ˜ - 1)์ด ์ •์ƒ ๋™์ž‘ํ•˜๋Š”์ง€ ํ™•์ธ + - [x] (์‹ ์ฒญ ๊ฐ€๋Šฅํ•œ ์ž๋ฆฌ์ˆ˜ - 1) ๋„์ค‘ ์ž๋ฆฌ์ˆ˜๊ฐ€ 0 ์ผ๋•Œ ์˜ˆ์™ธ ๋ฐœ์ƒ \ No newline at end of file
Unknown
์ฒดํฌ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ค์–ด ์ฃผ์‹  ์  ๋ฉ‹์ง€์‹ญ๋‹ˆ๋‹ค!
@@ -0,0 +1,38 @@ +# ํŒจํ‚ค์ง€ ์„ค๊ณ„ + +```text +โ”œโ”€โ”€ HanghaeplusSignupForLectureApplication.java +โ”œโ”€โ”€ api +โ”‚ย ย  โ”œโ”€โ”€ controller +โ”‚ย ย  โ””โ”€โ”€ dto +โ”‚ย ย  โ”œโ”€โ”€ request +โ”‚ย ย  โ””โ”€โ”€ response +โ”œโ”€โ”€ application +โ”‚ย ย  โ”œโ”€โ”€ lecture +โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ domain +โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ model +โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ repository +โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ dto +โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ request +โ”‚ย ย  โ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ response +โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ facade +โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ service +โ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ validator +โ”‚ย ย  โ””โ”€โ”€ user +โ”‚ย ย  โ”œโ”€โ”€ domain +โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ model +โ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ repository +โ”‚ย ย  โ”œโ”€โ”€ service +โ”‚ย ย  โ””โ”€โ”€ validator +โ””โ”€โ”€ infrastructure + โ”œโ”€โ”€ lecture + โ”‚ย ย  โ”œโ”€โ”€ entity + โ”‚ย ย  โ””โ”€โ”€ repository + โ”‚ย ย  โ”œโ”€โ”€ impl + โ”‚ย ย  โ””โ”€โ”€ jpa + โ””โ”€โ”€ user + โ”œโ”€โ”€ entity + โ””โ”€โ”€ repository + โ”œโ”€โ”€ impl + โ””โ”€โ”€ jpa +```
Unknown
application ๊ณผ domain ๊ณผ ๋ถ„๋ฆฌ๋˜์–ด์•ผ ํ•  ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,71 @@ +package hanghaeplus.signupforlecture.application.lecture.facade; + +import hanghaeplus.signupforlecture.application.lecture.domain.model.Lecture; +import hanghaeplus.signupforlecture.application.lecture.domain.model.LectureCapacity; +import hanghaeplus.signupforlecture.application.lecture.dto.request.LectureApplyRequestDto; +import hanghaeplus.signupforlecture.application.lecture.dto.request.LectureAvailableRequestDto; +import hanghaeplus.signupforlecture.application.lecture.dto.response.LectureAvailableResponseDto; +import hanghaeplus.signupforlecture.application.lecture.dto.response.LectureSignedUpResponseDto; +import hanghaeplus.signupforlecture.application.lecture.service.LectureApplyHistoryService; +import hanghaeplus.signupforlecture.application.lecture.service.LectureCapacityService; +import hanghaeplus.signupforlecture.application.lecture.service.LectureService; +import hanghaeplus.signupforlecture.application.user.domain.model.User; +import hanghaeplus.signupforlecture.application.user.service.UserService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Component +@RequiredArgsConstructor +public class LectureFacade { + + private final UserService userService; + + private final LectureService lectureService; + private final LectureApplyHistoryService lectureApplyHistoryService; + private final LectureCapacityService lectureCapacityService; + + public List<LectureAvailableResponseDto> getAvailableLectures(LectureAvailableRequestDto lectureAvailableRequestDto) { + List<Lecture> availableLectureIds = lectureService.getAvailableLectures(lectureAvailableRequestDto.requestDate()); + List<LectureCapacity> availableLectures = lectureCapacityService.getAvailableSlot(availableLectureIds); + + return LectureAvailableResponseDto.fromDomains(availableLectureIds, availableLectures); + } + + @Transactional + public void applyLecture(Long lectureId, LectureApplyRequestDto lectureApplyRequestDto) { + User user = userService.getUser(lectureApplyRequestDto.userId()); + Lecture lecture = lectureService.getLecture(lectureId); + + try { + // ์ค‘๋ณต ์ฒดํฌ (history ํ…Œ์ด๋ธ”) + lectureApplyHistoryService.checkApplyLectureHistory(lecture.id(), user.id()); + + // ์‹ ์ฒญ ๊ฐ€๋Šฅํ•œ Slot (lectureCapacity ํ…Œ์ด๋ธ”) ์กฐํšŒ <๋ฝ ํš๋“> + LectureCapacity lectureCapacity = lectureCapacityService.getAvailableSlotLock(lecture.id()); + + // ๋‚ด์—ญ ์ €์žฅ (history ํ…Œ์ด๋ธ”) + lectureApplyHistoryService.insertAppliedHistory(lecture, user.id()); + + // ์‹ ์ฒญ ๊ฐ€๋Šฅ Slot - 1 ๋กœ์ง >> ์ €์žฅ (lectureCapacity ํ…Œ์ด๋ธ”) + lectureCapacityService.applyAvailableSlot(lectureCapacity); + } catch (RuntimeException e) { + lectureApplyHistoryService.insertFailedHistory(lecture, user.id()); + } + } + + public List<LectureSignedUpResponseDto> getSignedUpLectures(Long userId) { + User user = userService.getUser(userId); + + List<Long> signedUpLectureIds = lectureApplyHistoryService.findSignedUpLectureHistories(user.id()); + List<Lecture> signedUpLectures = lectureService.findSignedUpLectures(signedUpLectureIds); + + return signedUpLectures.stream() + .map(LectureSignedUpResponseDto::fromDomain) + .toList(); + } +}
Java
๋ฝ์„ ์ง€์šฐ๊ณ  ๋น„๊ด€์ ๋ฝ๋งŒ ์ ์šฉํ•ด์„œ ํ•ด๋ณด๋Š”๊ฑด ์–ด๋– ์‹ค๊นŒ์š”?
@@ -0,0 +1,121 @@ +package store.model; + +import java.text.NumberFormat; +import java.time.LocalDateTime; +import java.util.Locale; + +public class Product { + private static final String PRICE_UNIT = "์›"; + private static final String STOCK_UNIT = "%d๊ฐœ"; + private static final String OUT_OF_STOCK = "์žฌ๊ณ  ์—†์Œ"; + + private 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 getPrice() { + return price; + } + + public int getQuantity() { + return quantity; + } + + public Promotion getPromotion() { + return promotion; + } + + public int getPromotionGet() { + if (promotion == null) { + return 0; + } + return this.promotion.getGet(); + } + + public boolean isPromotion() { + return promotion != null; + } + + public boolean matchName(String name) { + return this.name.equals(name); + } + + public boolean inStock() { + return quantity > 0; + } + + public boolean canBuy(int quantity) { + return this.quantity >= quantity; + } + + public void decreaseQuantity(int amount) { + quantity -= amount; + } + + public boolean isApplyPromotion(LocalDateTime localDateTime) { + if (promotion == null) { + return false; + } + return promotion.isApplyPromotion(localDateTime); + } + + public boolean canGetForFreeByPromotion(int quantity) { + if (promotion == null) { + return false; + } + return this.promotion.canGetForFree(quantity) && this.quantity - quantity >= this.promotion.getGet(); + } + + public int getMaxCanGetForFreeByPromotion(int quantity) { + if (promotion == null) { + return 0; + } + if (quantity > this.quantity) { + quantity = this.quantity; + } + return this.promotion.getMaxCanGetForFree(quantity); + } + + public int getMaxCanApplyPromotion(int quantity) { + if (promotion == null) { + return 0; + } + if (quantity > this.quantity) { + quantity = this.quantity; + } + return this.promotion.getMaxCanApply(quantity); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(name).append(" "); + sb.append(formatCurrency(price)).append(" "); + String stock = String.format(STOCK_UNIT, quantity); + if (quantity == 0) { + stock = OUT_OF_STOCK; + } + sb.append(stock).append(" "); + if (promotion != null) { + sb.append(promotion.getName()); + } + return sb.toString(); + } + + private String formatCurrency(int price) { + NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.KOREA); + return numberFormat.format(price) + PRICE_UNIT; + } +}
Java
quantity๋ฅผ ์ œ์™ธํ•œ ๋‹ค๋ฅธ ํ•„๋“œ๋“ค์€ ๋ณ€๊ฒฝ๋  ์—ฌ์ง€๊ฐ€ ์—†๋‹ค๊ณ  ์ƒ๊ฐ๋˜๋Š”๋ฐ, final ์„ค์ •์„ ํ•˜์ง€ ์•Š์œผ์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,125 @@ +package store.service; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.ArrayList; +import java.util.List; +import store.model.Item; +import store.model.Product; +import store.model.Products; +import store.model.PromotionApplyStatus; +import store.util.constants.ServiceConstants; + +public class StoreService { + + public StoreService() { + } + + public PromotionApplyStatus checkPromotionState(Products products, Item item) { + Product product = products.findProductByNameAndPromotionIsNotNull(item.getName()); + if (product == null || !product.inStock() || !product.isApplyPromotion(DateTimes.now())) { + return PromotionApplyStatus.NO_PROMOTION; + } + if (product.canGetForFreeByPromotion(item.getQuantity())) { + return PromotionApplyStatus.NEED_GET; + } + if (!product.canBuy(item.getQuantity()) || !product.canBuy(item.getQuantity() + product.getPromotionGet())) { + return PromotionApplyStatus.NOT_ENOUGH_STOCK; + } + return PromotionApplyStatus.NO_PROMOTION; + } + + public String getPromotionMessage(Products products, Item item, PromotionApplyStatus promotionApplyStatus) { + Product product = products.findProductByNameAndPromotionIsNotNull(item.getName()); + if (promotionApplyStatus == PromotionApplyStatus.NOT_ENOUGH_STOCK) { + int applyPromotion = product.getMaxCanApplyPromotion(item.getQuantity()); + int notApplyPromotionCount = item.getQuantity() - applyPromotion; + return String.format(promotionApplyStatus.getMessage(), item.getName(), notApplyPromotionCount); + } + if (promotionApplyStatus == PromotionApplyStatus.NEED_GET) { + return String.format(promotionApplyStatus.getMessage(), item.getName()); + } + return promotionApplyStatus.getMessage(); + } + + public void processQuantityByPromotion(Item item, PromotionApplyStatus promotionApplyStatus, String input, + Products products) { + if (promotionApplyStatus == PromotionApplyStatus.NEED_GET && input.equals(ServiceConstants.YES)) { + addGetToItem(item, products); + return; + } + if (promotionApplyStatus == PromotionApplyStatus.NOT_ENOUGH_STOCK && input.equals(ServiceConstants.NO)) { + takeOffFormItem(item, products); + } + } + + private void addGetToItem(Item item, Products products) { + Product product = products.findProductByNameAndPromotionIsNotNull(item.getName()); + int get = product.getPromotionGet(); + item.addQuantity(get); + } + + private void takeOffFormItem(Item item, Products products) { + Product product = products.findProductByNameAndPromotionIsNotNull(item.getName()); + int applyPromotion = product.getMaxCanApplyPromotion(item.getQuantity()); + int notApplyPromotionCount = item.getQuantity() - applyPromotion; + item.takeOffQuantity(notApplyPromotionCount); + } + + public List<Item> getItemsForFreeByPromotion(Products products, List<Item> items) { + List<Item> freeItems = new ArrayList<>(); + for (Item item : items) { + int getForFree = getGetCountByPromotion(products, item); + if (getForFree == 0) { + continue; + } + freeItems.add(new Item(item.getName(), getForFree)); + } + return freeItems; + } + + private int getGetCountByPromotion(Products products, Item item) { + Product product = products.findProductByNameAndPromotionIsNotNull(item.getName()); + if (product == null || !product.isApplyPromotion(DateTimes.now())) { + return 0; + } + return product.getMaxCanGetForFreeByPromotion(item.getQuantity()); + } + + public void processStock(Products products, List<Item> items) { + for (Item item : items) { + int quantity = processPromotionProduct(products, item); + processNotPromotionProduct(products, item, quantity); + } + } + + private int processPromotionProduct(Products products, Item item) { + Product product = products.findProductByNameAndPromotionIsNotNull(item.getName()); + int quantity = item.getQuantity(); + if (product != null) { + quantity = decreaseProductQuantity(product, quantity); + } + return quantity; + } + + private void processNotPromotionProduct(Products products, Item item, int quantity) { + Product product = products.findProductByNameAndPromotionIsNull(item.getName()); + if (quantity == 0 || product == null) { + return; + } + product.decreaseQuantity(quantity); + } + + private int decreaseProductQuantity(Product product, int quantity) { + if (product.canBuy(quantity)) { + product.decreaseQuantity(quantity); + return 0; + } + int remainingQuantity = quantity - product.getQuantity(); + product.decreaseQuantity(product.getQuantity()); + return remainingQuantity; + } + + public boolean isContinue(String input) { + return input.equals(ServiceConstants.YES); + } +}
Java
StoreService๊ฐ€ ์—ฌ๋Ÿฌ ์ข…๋ฅ˜์˜ ๋กœ์ง์„ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๊ฒƒ์œผ๋กœ ๋ณด์ด๋Š”๋ฐ(promotion, product, item), ๋ณ‘๊ทœ๋‹˜๊ป˜์„œ ์ •์˜ํ•˜์‹  StoreService ํด๋ž˜์Šค์˜ ์ฑ…์ž„์ด ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,26 @@ +package store.util.constants; + +public class ViewConstants { + // inputView + public static final String INPUT_ITEM_MESSAGE = "๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"; + public static final String ITEM_INPUT_FORMAT = "^\\[(\\w|[๊ฐ€-ํžฃ]|.)+-\\d+\\](,\\[(\\w|[๊ฐ€-ํžฃ]|.)+-\\d+\\])*$"; + public static final String ERROR_INPUT_FORMAT = "[ERROR] ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + public static final String INPUT_MEMBERSHIP_YN_MESSAGE = "๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"; + public static final String INPUT_CONTINUE_YN_MESSAGE = "๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"; + // outputView + public static final String WELCOME_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค."; + public static final String PRODUCT_INTRODUCE_MESSAGE = "ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."; + public static final String RECEIPT_HEADER = "\n==============W ํŽธ์˜์ ================"; + public static final String RECEIPT_MIDDLE = "=============์ฆ\t์ •==============="; + public static final String RECEIPT_BOTTOM = "====================================\n"; + public static final String RECEIPT_HEADER_FORMAT = "%-10s %5s %15s"; + public static final String RECEIPT_FORMAT = "%-10s %5d %15s"; + public static final String RECEIPT_BOTTOM_FORMAT = "%-10s %20s\n"; + public static final String RECEIPT_PRODUCT_NAME = "์ƒํ’ˆ๋ช…"; + public static final String RECEIPT_QUANTITY = "์ˆ˜๋Ÿ‰"; + public static final String RECEIPT_AMOUNT = "๊ธˆ์•ก"; + public static final String RECEIPT_TOTAL_PRICE = "์ด๊ตฌ๋งค์•ก"; + public static final String RECEIPT_PROMOTION_DISCOUNT = "ํ–‰์‚ฌํ• ์ธ"; + public static final String RECEIPT_MEMBERSHIP_DISCOUNT = "๋ฉค๋ฒ„์‹ญํ• ์ธ"; + public static final String RECEIPT_PAYMENT = "๋‚ด์‹ค๋ˆ"; +}
Java
ViewConstants ํด๋ž˜์Šค์™€ ServiceConstants ํด๋ž˜์Šค๋ฅผ ๋ณ„๋„๋กœ ์ •์˜ํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,109 @@ +package store.service; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import store.model.Item; +import store.model.Product; +import store.model.Products; +import store.model.Promotion; +import store.model.PromotionApplyStatus; +import store.util.Converter; + +class StoreServiceTest { + ItemService itemService; + StoreService storeService; + Converter converter; + Products products; + List<Item> items; + + @BeforeEach + void setUp() { + converter = new Converter(); + itemService = new ItemService(converter); + storeService = new StoreService(); + products = createProducts(); + items = createItems(); + } + + private Products createProducts() { + List<Product> products = new ArrayList<>(); + LocalDateTime start = converter.toLocalDateTime("2024-01-01"); + LocalDateTime end = converter.toLocalDateTime("2024-12-31"); + Promotion promotion = new Promotion("ํƒ„์‚ฐ2+1", 2, 1, start, end); + + products.add(new Product("์ฝœ๋ผ", 1000, 10, promotion)); + products.add(new Product("์ฝœ๋ผ", 1000, 10, null)); + products.add(new Product("์‚ฌ์ด๋‹ค", 1200, 8, promotion)); + products.add(new Product("์‚ฌ์ด๋‹ค", 1200, 7, null)); + products.add(new Product("ํƒ„์‚ฐ์ˆ˜", 1200, 6, promotion)); + products.add(new Product("ํƒ„์‚ฐ์ˆ˜", 1200, 6, null)); + return new Products(products); + } + + private List<Item> createItems() { + String input = "[์ฝœ๋ผ-2],[ํƒ„์‚ฐ์ˆ˜-4],[์‚ฌ์ด๋‹ค-10]"; + return itemService.getItems(products, input); + } + + @DisplayName("item์˜ ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ ์ƒํƒœ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค") + @Test + void checkPromotionState() { + assertThat(this.storeService.checkPromotionState(products, items.get(0))).isEqualTo( + PromotionApplyStatus.NEED_GET); + assertThat(this.storeService.checkPromotionState(products, items.get(1))).isEqualTo( + PromotionApplyStatus.NO_PROMOTION); + assertThat(this.storeService.checkPromotionState(products, items.get(2))).isEqualTo( + PromotionApplyStatus.NOT_ENOUGH_STOCK); + } + + @DisplayName("ํ”„๋กœ๋ชจ์…˜ ์ƒํƒœ์— ๋”ฐ๋ผ ์•ˆ๋‚ด ๋ฉ”์‹œ์ง€๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค") + @Test + void getPromotionMessage() { + assertThat(this.storeService.getPromotionMessage(products, items.get(0), PromotionApplyStatus.NEED_GET)) + .contains("ํ˜„์žฌ ์ฝœ๋ผ์€(๋Š”) 1๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"); + assertThat(this.storeService.getPromotionMessage(products, items.get(2), PromotionApplyStatus.NOT_ENOUGH_STOCK)) + .contains("ํ˜„์žฌ ์‚ฌ์ด๋‹ค 4๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"); + } + + @DisplayName("ํ”„๋กœ๋ชจ์…˜ ์ƒํƒœ์™€ ์‚ฌ์šฉ์ž ์ž…๋ ฅ์— ๋”ฐ๋ผ item์˜ ์ˆ˜๋Ÿ‰์„ ์ˆ˜์ •ํ•œ๋‹ค") + @Test + void processQuantityByPromotion() { + this.storeService.processQuantityByPromotion(items.get(0), PromotionApplyStatus.NEED_GET, "Y", products); + this.storeService.processQuantityByPromotion(items.get(2), PromotionApplyStatus.NOT_ENOUGH_STOCK, "N", + products); + + assertThat(items.get(0).getQuantity()).isEqualTo(3); + assertThat(items.get(1).getQuantity()).isEqualTo(4); + assertThat(items.get(2).getQuantity()).isEqualTo(6); + } + + @DisplayName("์ฆ์ •ํ’ˆ ๋ชฉ๋ก์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค") + @Test + void getItemsForFreeByPromotion() { + List<Item> freeItems = this.storeService.getItemsForFreeByPromotion(products, items); + + assertThat(freeItems.size()).isEqualTo(2); + assertThat(freeItems.get(0).getName() + freeItems.get(0).getQuantity()).isEqualTo("ํƒ„์‚ฐ์ˆ˜1"); + assertThat(freeItems.get(1).getName() + freeItems.get(1).getQuantity()).isEqualTo("์‚ฌ์ด๋‹ค2"); + } + + @DisplayName("๊ตฌ๋งคํ•œ ์ƒํ’ˆ์˜ ์ˆ˜๋Ÿ‰๋งŒํผ ์žฌ๊ณ ๋ฅผ ์ฐจ๊ฐํ•œ๋‹ค") + @Test + void processStock() { + this.storeService.processStock(products, items); + List<Product> processProduct = products.getProducts(); + + assertThat(processProduct.get(0).getQuantity()).isEqualTo(8); + assertThat(processProduct.get(1).getQuantity()).isEqualTo(10); + assertThat(processProduct.get(2).getQuantity()).isEqualTo(0); + assertThat(processProduct.get(3).getQuantity()).isEqualTo(5); + assertThat(processProduct.get(4).getQuantity()).isEqualTo(2); + assertThat(processProduct.get(5).getQuantity()).isEqualTo(6); + } +} \ No newline at end of file
Java
ํ”„๋กœ๋ชจ์…˜ ์ƒํƒœ๋‚˜ ์‚ฌ์šฉ์ž ์ž…๋ ฅ์„ ๊ตฌ์ฒด์ ์œผ๋กœ ์ •์˜ํ•ด์„œ ์‹œ๋‚˜๋ฆฌ์˜ค๋ฅผ ๋‚˜๋ˆ„๋ฉด ๋ฒ„๊ทธ๊ฐ€ ๋ฐœ์ƒํ–ˆ์„ ๋•Œ ๊ทธ๊ฒŒ ์–ด๋–ค ๋กœ์ง ๋•Œ๋ฌธ์ธ์ง€ ๋””๋ฒ„๊น…ํ•˜๊ธฐ ํ›จ์”ฌ ์‰ฌ์›Œ์งˆ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,81 @@ +package store.service; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.List; +import store.model.Item; +import store.model.Product; +import store.model.Products; +import store.model.Receipt; +import store.util.constants.ServiceConstants; + +public class ReceiptService { + public ReceiptService() { + } + + public Receipt createReceipt(Products products, List<Item> items, boolean applyMembership) { + int totalPrice = getTotalPrice(products, items); + int discountByPromotion = getPromotionDiscount(products, items); + int discountByMembership = 0; + if (applyMembership) { + discountByMembership = getMembershipDiscount(products, items); + } + int payment = totalPrice - discountByPromotion - discountByMembership; + return new Receipt(items, totalPrice, discountByPromotion, discountByMembership, payment); + } + + private int getTotalPrice(Products products, List<Item> items) { + int totalPrice = 0; + for (Item item : items) { + totalPrice += getPrice(products, item); + } + return totalPrice; + } + + private int getPrice(Products products, Item item) { + Product product = products.findProductByName(item.getName()); + return item.getQuantity() * product.getPrice(); + } + + + public int getPromotionDiscount(Products products, List<Item> items) { + int discount = 0; + for (Item item : items) { + discount += getPriceForFreeByPromotion(products, item); + } + return discount; + } + + private int getPriceForFreeByPromotion(Products products, Item item) { + Product product = products.findProductByNameAndPromotionIsNotNull(item.getName()); + if (product == null || !product.isApplyPromotion(DateTimes.now())) { + return 0; + } + int price = product.getPrice(); + int getFreeCount = product.getMaxCanGetForFreeByPromotion(item.getQuantity()); + return getFreeCount * price; + } + + public int getMembershipDiscount(Products products, List<Item> items) { + int totalPriceNotApplyPromotion = 0; + for (Item item : items) { + totalPriceNotApplyPromotion += getPriceNotApplyPromotion(products, item); + } + int discount = (int) (totalPriceNotApplyPromotion * ServiceConstants.MEMBERSHIP_DISCOUNT_RATE); + if (discount > ServiceConstants.MEMBERSHIP_DISCOUNT_LIMIT) { + discount = ServiceConstants.MEMBERSHIP_DISCOUNT_LIMIT; + } + return discount; + } + + private int getPriceNotApplyPromotion(Products products, Item item) { + Product product = products.findProductByNameAndPromotionIsNotNull(item.getName()); + if (product == null || !product.isApplyPromotion(DateTimes.now())) { + product = products.findProductByNameAndPromotionIsNull(item.getName()); + return item.getQuantity() * product.getPrice(); + } + int price = product.getPrice(); + int applyPromotion = product.getMaxCanApplyPromotion(item.getQuantity()); + int notApplyPromotionCount = item.getQuantity() - applyPromotion; + return notApplyPromotionCount * price; + } +}
Java
ByPromotion๋ž€ ๋„ค์ด๋ฐ์„ ํฌํ•จํ•œ ๋ฉ”์„œ๋“œ๊ฐ€ ๋งŽ์ด ๋ณด์—ฌ์š”! ๋งŒ์•ฝ ํ”„๋กœ๋ชจ์…˜์— ์˜ํ•œ ๋™์ž‘์ด๋ผ๋ฉด, ํ”„๋กœ๋ชจ์…˜์„ ํฌํ•จํ•œ Product์— ํ•ด๋‹น ๋ฉ”์„œ๋“œ๋ฅผ ํฌํ•จ์‹œํ‚ค๊ฑฐ๋‚˜, ํ”„๋กœ๋ชจ์…˜์„ ๋…๋ฆฝ๋œ ์ฃผ์ฒด๋กœ ์ƒ๊ฐํ•˜๊ณ  ๋ณ„๋„์˜ ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค์—ˆ ์ˆ˜๋„ ์žˆ์„ ๊ฒƒ ๊ฐ™์€๋ฐ ๊ณผ์ œ์™€ ๊ฐ™์€ ๊ตฌ์กฐ๋ฅผ ํƒํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค! ๐Ÿค”
@@ -0,0 +1,121 @@ +package store.model; + +import java.text.NumberFormat; +import java.time.LocalDateTime; +import java.util.Locale; + +public class Product { + private static final String PRICE_UNIT = "์›"; + private static final String STOCK_UNIT = "%d๊ฐœ"; + private static final String OUT_OF_STOCK = "์žฌ๊ณ  ์—†์Œ"; + + private 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 getPrice() { + return price; + } + + public int getQuantity() { + return quantity; + } + + public Promotion getPromotion() { + return promotion; + } + + public int getPromotionGet() { + if (promotion == null) { + return 0; + } + return this.promotion.getGet(); + } + + public boolean isPromotion() { + return promotion != null; + } + + public boolean matchName(String name) { + return this.name.equals(name); + } + + public boolean inStock() { + return quantity > 0; + } + + public boolean canBuy(int quantity) { + return this.quantity >= quantity; + } + + public void decreaseQuantity(int amount) { + quantity -= amount; + } + + public boolean isApplyPromotion(LocalDateTime localDateTime) { + if (promotion == null) { + return false; + } + return promotion.isApplyPromotion(localDateTime); + } + + public boolean canGetForFreeByPromotion(int quantity) { + if (promotion == null) { + return false; + } + return this.promotion.canGetForFree(quantity) && this.quantity - quantity >= this.promotion.getGet(); + } + + public int getMaxCanGetForFreeByPromotion(int quantity) { + if (promotion == null) { + return 0; + } + if (quantity > this.quantity) { + quantity = this.quantity; + } + return this.promotion.getMaxCanGetForFree(quantity); + } + + public int getMaxCanApplyPromotion(int quantity) { + if (promotion == null) { + return 0; + } + if (quantity > this.quantity) { + quantity = this.quantity; + } + return this.promotion.getMaxCanApply(quantity); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(name).append(" "); + sb.append(formatCurrency(price)).append(" "); + String stock = String.format(STOCK_UNIT, quantity); + if (quantity == 0) { + stock = OUT_OF_STOCK; + } + sb.append(stock).append(" "); + if (promotion != null) { + sb.append(promotion.getName()); + } + return sb.toString(); + } + + private String formatCurrency(int price) { + NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.KOREA); + return numberFormat.format(price) + PRICE_UNIT; + } +}
Java
์š”๊ตฌ ์‚ฌํ•ญ์„ ๋ณด๋ฉด `quantity` ์™ธ์—๋Š” ๋ณ€ํ•  ๊ฒŒ ์—†์ง€๋งŒ, `Product`๋ฅผ ์„ค๊ณ„ํ•  ๋•Œ '์ƒํ’ˆ์˜ ์ด๋ฆ„๊ณผ ๊ฐ€๊ฒฉ์€ ๋ณ€ํ•  ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ?' ๋ผ๋Š” ์ƒ๊ฐ์— ์ข€ `final`๋กœ ์„ค์ •ํ•˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. ์ง€๊ธˆ ๋ณด๋‹ˆ ์•ž์„œ๋‚˜๊ฐ„ ๋ถ€๋ถ„์ด๋ผ ์ƒ๊ฐ๋˜๋„ค์š”. `final`๋กœ ํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค!
@@ -0,0 +1,125 @@ +package store.service; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.ArrayList; +import java.util.List; +import store.model.Item; +import store.model.Product; +import store.model.Products; +import store.model.PromotionApplyStatus; +import store.util.constants.ServiceConstants; + +public class StoreService { + + public StoreService() { + } + + public PromotionApplyStatus checkPromotionState(Products products, Item item) { + Product product = products.findProductByNameAndPromotionIsNotNull(item.getName()); + if (product == null || !product.inStock() || !product.isApplyPromotion(DateTimes.now())) { + return PromotionApplyStatus.NO_PROMOTION; + } + if (product.canGetForFreeByPromotion(item.getQuantity())) { + return PromotionApplyStatus.NEED_GET; + } + if (!product.canBuy(item.getQuantity()) || !product.canBuy(item.getQuantity() + product.getPromotionGet())) { + return PromotionApplyStatus.NOT_ENOUGH_STOCK; + } + return PromotionApplyStatus.NO_PROMOTION; + } + + public String getPromotionMessage(Products products, Item item, PromotionApplyStatus promotionApplyStatus) { + Product product = products.findProductByNameAndPromotionIsNotNull(item.getName()); + if (promotionApplyStatus == PromotionApplyStatus.NOT_ENOUGH_STOCK) { + int applyPromotion = product.getMaxCanApplyPromotion(item.getQuantity()); + int notApplyPromotionCount = item.getQuantity() - applyPromotion; + return String.format(promotionApplyStatus.getMessage(), item.getName(), notApplyPromotionCount); + } + if (promotionApplyStatus == PromotionApplyStatus.NEED_GET) { + return String.format(promotionApplyStatus.getMessage(), item.getName()); + } + return promotionApplyStatus.getMessage(); + } + + public void processQuantityByPromotion(Item item, PromotionApplyStatus promotionApplyStatus, String input, + Products products) { + if (promotionApplyStatus == PromotionApplyStatus.NEED_GET && input.equals(ServiceConstants.YES)) { + addGetToItem(item, products); + return; + } + if (promotionApplyStatus == PromotionApplyStatus.NOT_ENOUGH_STOCK && input.equals(ServiceConstants.NO)) { + takeOffFormItem(item, products); + } + } + + private void addGetToItem(Item item, Products products) { + Product product = products.findProductByNameAndPromotionIsNotNull(item.getName()); + int get = product.getPromotionGet(); + item.addQuantity(get); + } + + private void takeOffFormItem(Item item, Products products) { + Product product = products.findProductByNameAndPromotionIsNotNull(item.getName()); + int applyPromotion = product.getMaxCanApplyPromotion(item.getQuantity()); + int notApplyPromotionCount = item.getQuantity() - applyPromotion; + item.takeOffQuantity(notApplyPromotionCount); + } + + public List<Item> getItemsForFreeByPromotion(Products products, List<Item> items) { + List<Item> freeItems = new ArrayList<>(); + for (Item item : items) { + int getForFree = getGetCountByPromotion(products, item); + if (getForFree == 0) { + continue; + } + freeItems.add(new Item(item.getName(), getForFree)); + } + return freeItems; + } + + private int getGetCountByPromotion(Products products, Item item) { + Product product = products.findProductByNameAndPromotionIsNotNull(item.getName()); + if (product == null || !product.isApplyPromotion(DateTimes.now())) { + return 0; + } + return product.getMaxCanGetForFreeByPromotion(item.getQuantity()); + } + + public void processStock(Products products, List<Item> items) { + for (Item item : items) { + int quantity = processPromotionProduct(products, item); + processNotPromotionProduct(products, item, quantity); + } + } + + private int processPromotionProduct(Products products, Item item) { + Product product = products.findProductByNameAndPromotionIsNotNull(item.getName()); + int quantity = item.getQuantity(); + if (product != null) { + quantity = decreaseProductQuantity(product, quantity); + } + return quantity; + } + + private void processNotPromotionProduct(Products products, Item item, int quantity) { + Product product = products.findProductByNameAndPromotionIsNull(item.getName()); + if (quantity == 0 || product == null) { + return; + } + product.decreaseQuantity(quantity); + } + + private int decreaseProductQuantity(Product product, int quantity) { + if (product.canBuy(quantity)) { + product.decreaseQuantity(quantity); + return 0; + } + int remainingQuantity = quantity - product.getQuantity(); + product.decreaseQuantity(product.getQuantity()); + return remainingQuantity; + } + + public boolean isContinue(String input) { + return input.equals(ServiceConstants.YES); + } +}
Java
์›๋ž˜๋Š” StoreController์—์„œ ๋‹ด๋‹นํ•˜๋Š” ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์„ ์ „๋ถ€ StoreService๋กœ ๋ถ„๋ฆฌํ•˜๋ ค ํ•˜์˜€์Šต๋‹ˆ๋‹ค. ๊ฐ€์žฅ ์ค‘์‹ฌ์ด ๋˜๋Š” product์™€ ๊ด€๋ จ๋œ ๋กœ์ง์„ ์ „๋ถ€ ๊ฐ€์ ธ๊ฐ€๋„๋ก ํ•˜์˜€๋Š”๋ฐ ์ด ๊ณผ์ •์—์„œ product๊ฐ€ promotion๊ณผ item์„ ๋ชจ๋‘ ์‚ฌ์šฉํ•˜๋Š” ๋กœ์ง์ด ๋งŽ์ด ํฌํ•จ๋œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. item ์ƒ์„ฑ๊ณผ ๊ด€๋ จ๋œ ๋กœ์ง๊ณผ receipt ์ƒ์„ฑ๊ณผ ๊ด€๋ จ๋œ ๋กœ์ง์€ ํ™•์‹คํžˆ ๊ตฌ๋ถ„ ์ง€์„ ์ˆ˜ ์žˆ๋‹ค ์ƒ๊ฐํ•˜์—ฌ ๊ฐ๊ฐ์˜ Service๋กœ ๋ถ„๋ฆฌํ•˜์˜€์ง€๋งŒ, ํƒ€์ž„์–ดํƒ ์ด์Šˆ๋กœ StoreService์— ๋Œ€ํ•œ ๊ณ ๋ฏผ์€ ๊นŠ๊ฒŒ ํ•ด๋ณด์ง€ ๋ชปํ•˜์˜€์Šต๋‹ˆ๋‹ค. ์‹œ๊ฐ„์ด ๋ถ€์กฑํ•˜์—ฌ ํฐ ํ‹€๋งŒ ๊ฐ€์ง€๊ณ  ๊ทธ ์•ˆ์˜ ์„ธ์„ธํ•œ ๋ถ€๋ถ„๊นŒ์ง€๋Š” ๊ณ ๋ฏผํ•˜์ง€ ๋ชปํ–ˆ๋˜ ์˜ํ–ฅ์ด ํฐ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,26 @@ +package store.util.constants; + +public class ViewConstants { + // inputView + public static final String INPUT_ITEM_MESSAGE = "๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"; + public static final String ITEM_INPUT_FORMAT = "^\\[(\\w|[๊ฐ€-ํžฃ]|.)+-\\d+\\](,\\[(\\w|[๊ฐ€-ํžฃ]|.)+-\\d+\\])*$"; + public static final String ERROR_INPUT_FORMAT = "[ERROR] ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + public static final String INPUT_MEMBERSHIP_YN_MESSAGE = "๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"; + public static final String INPUT_CONTINUE_YN_MESSAGE = "๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"; + // outputView + public static final String WELCOME_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค."; + public static final String PRODUCT_INTRODUCE_MESSAGE = "ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."; + public static final String RECEIPT_HEADER = "\n==============W ํŽธ์˜์ ================"; + public static final String RECEIPT_MIDDLE = "=============์ฆ\t์ •==============="; + public static final String RECEIPT_BOTTOM = "====================================\n"; + public static final String RECEIPT_HEADER_FORMAT = "%-10s %5s %15s"; + public static final String RECEIPT_FORMAT = "%-10s %5d %15s"; + public static final String RECEIPT_BOTTOM_FORMAT = "%-10s %20s\n"; + public static final String RECEIPT_PRODUCT_NAME = "์ƒํ’ˆ๋ช…"; + public static final String RECEIPT_QUANTITY = "์ˆ˜๋Ÿ‰"; + public static final String RECEIPT_AMOUNT = "๊ธˆ์•ก"; + public static final String RECEIPT_TOTAL_PRICE = "์ด๊ตฌ๋งค์•ก"; + public static final String RECEIPT_PROMOTION_DISCOUNT = "ํ–‰์‚ฌํ• ์ธ"; + public static final String RECEIPT_MEMBERSHIP_DISCOUNT = "๋ฉค๋ฒ„์‹ญํ• ์ธ"; + public static final String RECEIPT_PAYMENT = "๋‚ด์‹ค๋ˆ"; +}
Java
์ด๋ฒˆ ์š”๊ตฌ์‚ฌํ•ญ์— InputView, OutputView ์‚ฌ์šฉ์— ๋Œ€ํ•œ ๋‚ด์šฉ์„ ๋ณด๊ณ  MVC ํŒจํ„ด์„ ์ ์šฉํ•ด๋ณด๊ณ ์ž ํ•˜์˜€์Šต๋‹ˆ๋‹ค. Constants๊ฐ€ ์—ฌ๋Ÿฌ ๊ณณ์—์„œ ์‚ฌ์šฉ๋˜๋Š” ์ƒ์ˆ˜๋ฅผ ๋ชจ์•„๋†“๋Š” ํด๋ž˜์Šค์ด์ง€๋งŒ ๋„ˆ๋ฌด ๋งŽ์€ ๊ณณ์—์„œ ์ด๋ฅผ ์˜์กดํ•˜๋Š” ๊ฒƒ์€ ๊ฐœ์ธ์ ์œผ๋กœ ์ข‹์ง€ ์•Š๋‹ค๊ณ  ์ƒ๊ฐํ•˜์˜€์Šต๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  MVC๊ฐ€ ์—ญํ• ์— ๋”ฐ๋ผ ๊ฐ๊ฐ Model, View, Controller๋กœ ๋‚˜๋ˆ„์–ด ๋†“์€ ๊ฒƒ์ธ๋ฐ ํ•˜๋‚˜์˜ Constants์—์„œ ๋ชจ๋‘ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒŒ ๋งž์„๊นŒ๋ผ๋Š” ์ƒ๊ฐ์— View์™€ Controller ๋‹จ์—์„œ ์‚ฌ์šฉํ•˜๋Š” Constants๋ฅผ ๋‚˜๋ˆ„๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ๊ฐœ์ธ์ ์ธ ์ƒ๊ฐ์œผ๋กœ ๋‚˜๋ˆ  ๋†“์€ ๊ฒƒ์ด๋ผ ์ด๊ฒŒ ๋งž๋Š” ์„ค๊ณ„์ธ์ง€๋Š” ์ž˜ ๋ชจ๋ฅด๊ฒ ๋„ค์š”..
@@ -0,0 +1,109 @@ +package store.service; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import store.model.Item; +import store.model.Product; +import store.model.Products; +import store.model.Promotion; +import store.model.PromotionApplyStatus; +import store.util.Converter; + +class StoreServiceTest { + ItemService itemService; + StoreService storeService; + Converter converter; + Products products; + List<Item> items; + + @BeforeEach + void setUp() { + converter = new Converter(); + itemService = new ItemService(converter); + storeService = new StoreService(); + products = createProducts(); + items = createItems(); + } + + private Products createProducts() { + List<Product> products = new ArrayList<>(); + LocalDateTime start = converter.toLocalDateTime("2024-01-01"); + LocalDateTime end = converter.toLocalDateTime("2024-12-31"); + Promotion promotion = new Promotion("ํƒ„์‚ฐ2+1", 2, 1, start, end); + + products.add(new Product("์ฝœ๋ผ", 1000, 10, promotion)); + products.add(new Product("์ฝœ๋ผ", 1000, 10, null)); + products.add(new Product("์‚ฌ์ด๋‹ค", 1200, 8, promotion)); + products.add(new Product("์‚ฌ์ด๋‹ค", 1200, 7, null)); + products.add(new Product("ํƒ„์‚ฐ์ˆ˜", 1200, 6, promotion)); + products.add(new Product("ํƒ„์‚ฐ์ˆ˜", 1200, 6, null)); + return new Products(products); + } + + private List<Item> createItems() { + String input = "[์ฝœ๋ผ-2],[ํƒ„์‚ฐ์ˆ˜-4],[์‚ฌ์ด๋‹ค-10]"; + return itemService.getItems(products, input); + } + + @DisplayName("item์˜ ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ ์ƒํƒœ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค") + @Test + void checkPromotionState() { + assertThat(this.storeService.checkPromotionState(products, items.get(0))).isEqualTo( + PromotionApplyStatus.NEED_GET); + assertThat(this.storeService.checkPromotionState(products, items.get(1))).isEqualTo( + PromotionApplyStatus.NO_PROMOTION); + assertThat(this.storeService.checkPromotionState(products, items.get(2))).isEqualTo( + PromotionApplyStatus.NOT_ENOUGH_STOCK); + } + + @DisplayName("ํ”„๋กœ๋ชจ์…˜ ์ƒํƒœ์— ๋”ฐ๋ผ ์•ˆ๋‚ด ๋ฉ”์‹œ์ง€๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค") + @Test + void getPromotionMessage() { + assertThat(this.storeService.getPromotionMessage(products, items.get(0), PromotionApplyStatus.NEED_GET)) + .contains("ํ˜„์žฌ ์ฝœ๋ผ์€(๋Š”) 1๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"); + assertThat(this.storeService.getPromotionMessage(products, items.get(2), PromotionApplyStatus.NOT_ENOUGH_STOCK)) + .contains("ํ˜„์žฌ ์‚ฌ์ด๋‹ค 4๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"); + } + + @DisplayName("ํ”„๋กœ๋ชจ์…˜ ์ƒํƒœ์™€ ์‚ฌ์šฉ์ž ์ž…๋ ฅ์— ๋”ฐ๋ผ item์˜ ์ˆ˜๋Ÿ‰์„ ์ˆ˜์ •ํ•œ๋‹ค") + @Test + void processQuantityByPromotion() { + this.storeService.processQuantityByPromotion(items.get(0), PromotionApplyStatus.NEED_GET, "Y", products); + this.storeService.processQuantityByPromotion(items.get(2), PromotionApplyStatus.NOT_ENOUGH_STOCK, "N", + products); + + assertThat(items.get(0).getQuantity()).isEqualTo(3); + assertThat(items.get(1).getQuantity()).isEqualTo(4); + assertThat(items.get(2).getQuantity()).isEqualTo(6); + } + + @DisplayName("์ฆ์ •ํ’ˆ ๋ชฉ๋ก์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค") + @Test + void getItemsForFreeByPromotion() { + List<Item> freeItems = this.storeService.getItemsForFreeByPromotion(products, items); + + assertThat(freeItems.size()).isEqualTo(2); + assertThat(freeItems.get(0).getName() + freeItems.get(0).getQuantity()).isEqualTo("ํƒ„์‚ฐ์ˆ˜1"); + assertThat(freeItems.get(1).getName() + freeItems.get(1).getQuantity()).isEqualTo("์‚ฌ์ด๋‹ค2"); + } + + @DisplayName("๊ตฌ๋งคํ•œ ์ƒํ’ˆ์˜ ์ˆ˜๋Ÿ‰๋งŒํผ ์žฌ๊ณ ๋ฅผ ์ฐจ๊ฐํ•œ๋‹ค") + @Test + void processStock() { + this.storeService.processStock(products, items); + List<Product> processProduct = products.getProducts(); + + assertThat(processProduct.get(0).getQuantity()).isEqualTo(8); + assertThat(processProduct.get(1).getQuantity()).isEqualTo(10); + assertThat(processProduct.get(2).getQuantity()).isEqualTo(0); + assertThat(processProduct.get(3).getQuantity()).isEqualTo(5); + assertThat(processProduct.get(4).getQuantity()).isEqualTo(2); + assertThat(processProduct.get(5).getQuantity()).isEqualTo(6); + } +} \ No newline at end of file
Java
์ง€๊ธˆ์€ ํ•˜๋‚˜์˜ ํ…Œ์ŠคํŠธ๋กœ ๋ฌถ์–ด๋†“์•˜๋Š”๋ฐ, ๋ง์”€ํ•˜์‹  ๋Œ€๋กœ ํ”„๋กœ๋ชจ์…˜ ์ƒํƒœ์™€ ์‚ฌ์šฉ์ž ์ž…๋ ฅ์„ ๊ตฌ์ฒด์ ์œผ๋กœ ์ •์˜ํ•˜๊ณ  ๊ฒฝ์šฐ๋ฅผ ๋‚˜๋ˆ ์„œ ํ…Œ์ŠคํŠธ ํ•˜๋Š” ๊ฒƒ์ด ํ•„์š”ํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ์ข‹์€ ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,81 @@ +package store.service; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.List; +import store.model.Item; +import store.model.Product; +import store.model.Products; +import store.model.Receipt; +import store.util.constants.ServiceConstants; + +public class ReceiptService { + public ReceiptService() { + } + + public Receipt createReceipt(Products products, List<Item> items, boolean applyMembership) { + int totalPrice = getTotalPrice(products, items); + int discountByPromotion = getPromotionDiscount(products, items); + int discountByMembership = 0; + if (applyMembership) { + discountByMembership = getMembershipDiscount(products, items); + } + int payment = totalPrice - discountByPromotion - discountByMembership; + return new Receipt(items, totalPrice, discountByPromotion, discountByMembership, payment); + } + + private int getTotalPrice(Products products, List<Item> items) { + int totalPrice = 0; + for (Item item : items) { + totalPrice += getPrice(products, item); + } + return totalPrice; + } + + private int getPrice(Products products, Item item) { + Product product = products.findProductByName(item.getName()); + return item.getQuantity() * product.getPrice(); + } + + + public int getPromotionDiscount(Products products, List<Item> items) { + int discount = 0; + for (Item item : items) { + discount += getPriceForFreeByPromotion(products, item); + } + return discount; + } + + private int getPriceForFreeByPromotion(Products products, Item item) { + Product product = products.findProductByNameAndPromotionIsNotNull(item.getName()); + if (product == null || !product.isApplyPromotion(DateTimes.now())) { + return 0; + } + int price = product.getPrice(); + int getFreeCount = product.getMaxCanGetForFreeByPromotion(item.getQuantity()); + return getFreeCount * price; + } + + public int getMembershipDiscount(Products products, List<Item> items) { + int totalPriceNotApplyPromotion = 0; + for (Item item : items) { + totalPriceNotApplyPromotion += getPriceNotApplyPromotion(products, item); + } + int discount = (int) (totalPriceNotApplyPromotion * ServiceConstants.MEMBERSHIP_DISCOUNT_RATE); + if (discount > ServiceConstants.MEMBERSHIP_DISCOUNT_LIMIT) { + discount = ServiceConstants.MEMBERSHIP_DISCOUNT_LIMIT; + } + return discount; + } + + private int getPriceNotApplyPromotion(Products products, Item item) { + Product product = products.findProductByNameAndPromotionIsNotNull(item.getName()); + if (product == null || !product.isApplyPromotion(DateTimes.now())) { + product = products.findProductByNameAndPromotionIsNull(item.getName()); + return item.getQuantity() * product.getPrice(); + } + int price = product.getPrice(); + int applyPromotion = product.getMaxCanApplyPromotion(item.getQuantity()); + int notApplyPromotionCount = item.getQuantity() - applyPromotion; + return notApplyPromotionCount * price; + } +}
Java
๋จผ์ € ByPromotion ๋ฉ”์„œ๋“œ๊ฐ€ ๋งŽ์€ ์ด์œ ๋Š” ํƒ€์ž„์–ดํƒ ์ด์Šˆ๋กœ ์„ค๊ณ„๋ฅผ ์ข€ ๋” ๊ณ ๋ฏผํ•˜์ง€ ๋ชปํ•œ ๋ฌธ์ œ๋„ ์žˆ์ง€๋งŒ, ์ œ ๋„ค์ด๋ฐ์˜ ๋ฌธ์ œ๋„ ์žˆ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ByPromotion์ด ๋ถ™์€ ๋ฉ”์„œ๋“œ์˜ ๊ฒฝ์šฐ ํ”„๋กœ๋ชจ์…˜๊ณผ ๊ด€๋ จ๋œ ๋กœ์ง์ด์ง€๋งŒ, ํ•ด๋‹น ๋กœ์ง์˜ ์ฃผ์ฒด๊ฐ€ Promotion ์ž์ฒด๊ฐ€ ์•„๋‹ˆ๋ผ๊ณ  ์ƒ๊ฐํ•˜์—ฌ Promotion์—์„œ ์ฒ˜๋ฆฌํ•˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. ๊ทธ๋Ÿผ์—๋„ ByPromotion์„ ๋ถ™์ธ ์ด์œ ๋Š” ์˜๋ฏธ๋ฅผ ์‰ฝ๊ฒŒ ํŒŒ์•…ํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•œ ๊ฒƒ์ด์—ˆ๋Š”๋ฐ, ๊ฒฐ๊ณผ์ ์œผ๋กœ ํ˜ผ๋ž€์ด ์ƒ๊ฒผ๋‹ค๋ฉด ์ข‹์ง€ ๋ชปํ•œ ๋„ค์ด๋ฐ์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. (๋„ค์ด๋ฐ ๊ณ ๋ฏผ์„ ๋งŽ์ด ํ•ด๋„ ๋„ˆ๋ฌด ์–ด๋ ต๋„ค์š” ๐Ÿฅฒ๐Ÿฅฒ) ์œ„ ๋ฉ”์„œ๋“œ์˜ ๊ฒฝ์šฐ๋Š” ์˜์ˆ˜์ฆ์— ๊ด€ํ•œ ๋‚ด์šฉ์ด๋ผ ์ƒ๊ฐํ•ด ReceiptService์—์„œ ์ฒ˜๋ฆฌํ•˜์˜€์ง€๋งŒ, ๋‹ค์‹œ ๋ณด๋‹ˆ Product์— ํฌํ•จํ•ด๋„ ๊ดœ์ฐฎ์„ ๊ฒƒ์ด๋ผ ์ƒ๊ฐ๋ฉ๋‹ˆ๋‹ค! ์ข‹์€ ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,144 @@ +package store.controller; + +import static store.constant.Answer.NO; +import static store.constant.Answer.YES; +import static store.constant.OutputInfo.MAY_I_TAKE_YOUR_ORDER; +import static store.constant.OutputInfo.MEMBERSHIP_DISCOUNT; +import static store.constant.OutputInfo.PRODUCT_START_MESSAGE; +import static store.constant.OutputInfo.WANNA_BUY_MORE; +import static store.constant.OutputInfo.WELCOME_MESSAGE; +import static store.constant.StoreInfo.PRODUCTS_FILE; +import static store.constant.StoreInfo.PROMOTIONS_FILE; + +import store.constant.Answer; +import store.model.Store; +import store.model.order.Order; +import store.model.order.Orders; +import store.model.product.Products; +import store.model.product.ProductsLoader; +import store.model.product.PromotionProducts; +import store.model.promotion.Promotions; +import store.model.promotion.PromotionsLoader; +import store.model.receipt.PurchaseInfos; +import store.model.receipt.Receipt; +import store.util.Task; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + public void run() { + Store store = loadFilesAndMakeStore(); + + while (true) { + printWelcomeAndAllProducts(store); + takeOrdersAndPrintReceipt(store); + if (answerToMoreOrders() == NO) { + break; + } + } + } + + private Store loadFilesAndMakeStore() { + PromotionsLoader promotionsLoader = new PromotionsLoader(PROMOTIONS_FILE); + ProductsLoader productsLoader = new ProductsLoader(PRODUCTS_FILE, + new Promotions(promotionsLoader.getPromotions())); + + return new Store( + new Products(productsLoader.getProducts()), + new PromotionProducts(productsLoader.getPromotionProducts()) + ); + } + + private void takeOrdersAndPrintReceipt(Store store) { + Orders orders = readAvailableOrders(store); + + readAnswerToFreeGettableCount(store, orders); + readAnswerToBuyProductsWithoutPromotion(store, orders); + + OutputView.printReceipt(new Receipt( + answerToMembershipDiscount() == YES, + sellAllProducts(store, orders) + )); + } + + private void printWelcomeAndAllProducts(Store store) { + OutputView.println(WELCOME_MESSAGE); + OutputView.println(PRODUCT_START_MESSAGE); + OutputView.printProducts(store.getProducts()); + OutputView.printPromotionProducts(store.getPromotionProducts()); + } + + private Orders readAvailableOrders(Store store) { + return Task.retryTillNoException(() -> { + OutputView.println(MAY_I_TAKE_YOUR_ORDER); + Orders orders = new Orders(InputView.readOrders()); + + for (Order order : orders.toList()) { + store.checkAvailability(order); + } + return orders; + }); + } + + private void readAnswerToFreeGettableCount(Store store, Orders orders) { + for (Order order : orders.toList()) { + final int freeGettableCount = store.getFreeGettableCount(order); + if (freeGettableCount == 0) { + continue; + } + + if (answerToGetFreeProducts(order, freeGettableCount) == YES) { + order.add(freeGettableCount); + } + } + } + + private Answer answerToGetFreeProducts(Order order, final int freeGettableCount) { + return Task.retryTillNoException(() -> { + OutputView.printQuestionToFreeGettableCount(order, freeGettableCount); + return InputView.readAnswer(); + }); + } + + private void readAnswerToBuyProductsWithoutPromotion(Store store, Orders orders) { + for (Order order : orders.toList()) { + final int buyCountWithoutPromotion = store.getBuyCountWithoutPromotion(order); + if (buyCountWithoutPromotion == 0) { + continue; + } + + if (answerToBuyWithoutPromotion(order, buyCountWithoutPromotion) == NO) { + order.cancel(buyCountWithoutPromotion); + } + } + } + + private Answer answerToBuyWithoutPromotion(Order order, final int buyCountWithoutPromotion) { + return Task.retryTillNoException(() -> { + OutputView.printQuestionToBuyCountWithoutPromotion(order, buyCountWithoutPromotion); + return InputView.readAnswer(); + }); + } + + private Answer answerToMembershipDiscount() { + return Task.retryTillNoException(() -> { + OutputView.println(MEMBERSHIP_DISCOUNT); + return InputView.readAnswer(); + }); + } + + private Answer answerToMoreOrders() { + return Task.retryTillNoException(() -> { + OutputView.println(WANNA_BUY_MORE); + return InputView.readAnswer(); + }); + } + + private PurchaseInfos sellAllProducts(Store store, Orders orders) { + return new PurchaseInfos( + orders.toList().stream() + .map(store::sell) + .toList() + ); + } +}
Java
๊ฐ€๋ฒผ์šด ์ถ”์ฒœ ์‚ฌํ•ญ์ด์ง€๋งŒ..! ๋” ๊ฐ„๋‹จํ•˜๊ฒŒ ๊ฐ€์ ธ๊ฐ€๊ณ ์‹ถ์œผ์‹œ๋‹ค๋ฉด ์ด๋Ÿฐ ํ˜•ํƒœ ์ฝ”๋“œ๋„ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค ใ…Žใ…Ž ```java do { printWelcomeAndAllProducts(store); takeOrdersAndPrintReceipt(store); } while (answerToMoreOrders() != NO); ```
@@ -0,0 +1,44 @@ +package store.util; + +import static store.constant.ErrorMessage.INVALID_ORDER_FORMAT; +import static store.constant.ErrorMessage.WRONG_INPUT; +import static store.constant.OrderInfo.ORDER_PATTERN; +import static store.constant.OrderInfo.PRODUCT_COUNT_GROUP; +import static store.constant.OrderInfo.PRODUCT_NAME_GROUP; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.regex.Matcher; +import store.model.order.Order; + +public class Converter { + public static int toInteger(String number) { + try { + return Integer.parseInt(number); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(WRONG_INPUT.getMessage()); + } + } + + public static LocalDateTime toLocalDateTime(String localDate, String dateFormat) { + return LocalDate.parse( + localDate, + DateTimeFormatter.ofPattern(dateFormat) + ) + .atStartOfDay(); + } + + public static Order toOrder(String order) { + Matcher matcher = ORDER_PATTERN.matcher(order); + + if (!matcher.matches()) { + throw new IllegalArgumentException(INVALID_ORDER_FORMAT.getMessage()); + } + + return new Order( + matcher.group(PRODUCT_NAME_GROUP), + Converter.toInteger(matcher.group(PRODUCT_COUNT_GROUP)) + ); + } +}
Java
util ํด๋ž˜์Šค๋กœ ๋นผ์„œ ๊ผผ๊ผผํ•˜๊ฒŒ ์˜ˆ์™ธ์ฒ˜๋ฆฌ ํ•˜์‹  ๊ฒƒ ๋„ˆ๋ฌด ์ข‹์•„์š”! ์ €๋Š” 3์ฃผ์ฐจ๋•Œ ํ–ˆ๋‹ค๊ฐ€ ์ด๋ฒˆ์ฃผ์ฐจ์— ๊นŒ๋จน์–ด์„œ ๋ชปํ–ˆ๋„ค์š” ใ…œ
@@ -0,0 +1,29 @@ +package store.model.product; + +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +public class Products { + private final Map<String, Product> productByName; + + public Products(Map<String, Product> productByName) { + this.productByName = productByName; + } + + public Products(List<Product> products) { + this( + products.stream() + .collect(Collectors.toMap(Product::getName, Function.identity())) + ); + } + + public Product getNameWith(String toFind) { + return productByName.get(toFind); + } + + public List<Product> toList() { + return productByName.values().stream().toList(); + } +}
Java
`Function.identity()`๋Š” ์ฒ˜์Œ๋ณด๋„ค์š”..! ์–ด๋–ค ์—ญํ• ์ธ์ง€ ์•Œ๋ ค์ฃผ์‹ค ์ˆ˜ ์žˆ๋‚˜์š”?!
@@ -0,0 +1,151 @@ +package store.view; + +import static store.constant.OutputInfo.BUY_COUNT_WITHOUT_PROMOTION_QUESTION; +import static store.constant.OutputInfo.FREE_GETTABLE_COUNT_QUESTION; +import static store.constant.OutputInfo.NEW_LINE; +import static store.constant.OutputInfo.NO_QUANTITY; +import static store.constant.OutputInfo.PRODUCT_FORMAT; +import static store.constant.OutputInfo.PROMOTION_PRODUCT_FORMAT; +import static store.constant.OutputInfo.QUANTITY_FORMAT; +import static store.constant.OutputInfo.RECEIPT_AMOUNT_OF_PAY_FORMAT; +import static store.constant.OutputInfo.RECEIPT_FREE_PRODUCT_FORMAT; +import static store.constant.OutputInfo.RECEIPT_FREE_START_MESSAGE; +import static store.constant.OutputInfo.RECEIPT_MEMBERSHIP_DISCOUNT_FORMAT; +import static store.constant.OutputInfo.RECEIPT_PAY_START_MESSAGE; +import static store.constant.OutputInfo.RECEIPT_PROMOTION_DISCOUNT_FORMAT; +import static store.constant.OutputInfo.RECEIPT_PURCHASE_INFO_FORMAT; +import static store.constant.OutputInfo.RECEIPT_PURCHASE_INFO_START_MESSAGE; +import static store.constant.OutputInfo.RECEIPT_START_MESSAGE; +import static store.constant.OutputInfo.RECEIPT_TOTAL_PRICE_FORMAT; + +import java.text.NumberFormat; +import store.model.order.Order; +import store.model.product.Product; +import store.model.product.Products; +import store.model.product.PromotionProduct; +import store.model.product.PromotionProducts; +import store.model.receipt.PurchaseInfo; +import store.model.receipt.PurchaseInfos; +import store.model.receipt.Receipt; + +public class OutputView { + public static final NumberFormat NUMBER_FORMATTER = NumberFormat.getInstance(); + + public static void println(String message) { + System.out.printf(message); + System.out.printf(NEW_LINE); + } + + public static void printProducts(Products products) { + for (Product product : products.toList()) { + System.out.printf( + PRODUCT_FORMAT, + product.getName(), + NUMBER_FORMATTER.format(product.getPrice()), + getQuantityMessage(product.getQuantity()) + ); + } + } + + public static void printPromotionProducts(PromotionProducts promotionProducts) { + for (PromotionProduct promotionProduct : promotionProducts.toList()) { + System.out.printf( + PROMOTION_PRODUCT_FORMAT, + promotionProduct.getName(), + NUMBER_FORMATTER.format(promotionProduct.getPrice()), + getQuantityMessage(promotionProduct.getQuantity()), + promotionProduct.getPromotionName() + ); + } + } + + private static String getQuantityMessage(final int quantity) { + if (quantity == 0) { + return NO_QUANTITY; + } + return String.format(QUANTITY_FORMAT, quantity); + } + + public static void printQuestionToFreeGettableCount(Order order, final int freeGettableCount) { + System.out.printf( + FREE_GETTABLE_COUNT_QUESTION, + order.getProductName(), + freeGettableCount + ); + } + + public static void printQuestionToBuyCountWithoutPromotion(Order order, final int buyCountWithoutPromotion) { + System.out.printf( + BUY_COUNT_WITHOUT_PROMOTION_QUESTION, + order.getProductName(), + buyCountWithoutPromotion + ); + } + + public static void printReceipt(Receipt receipt) { + System.out.printf(RECEIPT_START_MESSAGE); + printPurchaseInfos(receipt.getPurchaseInfos()); + printFreePurchaseInfos(receipt.getPurchaseInfos()); + printPays(receipt); + } + + private static void printPurchaseInfos(PurchaseInfos purchaseInfos) { + System.out.printf(RECEIPT_PURCHASE_INFO_START_MESSAGE); + for (PurchaseInfo purchaseInfo : purchaseInfos.toList()) { + System.out.printf( + RECEIPT_PURCHASE_INFO_FORMAT, + purchaseInfo.getProductName(), + purchaseInfo.getBuyCount(), + NUMBER_FORMATTER.format(purchaseInfo.getTotalAmount()) + ); + } + } + + private static void printFreePurchaseInfos(PurchaseInfos purchaseInfos) { + System.out.printf(RECEIPT_FREE_START_MESSAGE); + for (PurchaseInfo purchaseInfo : purchaseInfos.toPromotionDiscountedList()) { + System.out.printf( + RECEIPT_FREE_PRODUCT_FORMAT, + purchaseInfo.getProductName(), + purchaseInfo.getFreeCount() + ); + } + } + + private static void printPays(Receipt receipt) { + System.out.printf(RECEIPT_PAY_START_MESSAGE); + printTotalPrice(receipt); + printPromotionDiscount(receipt); + printMemberShipDiscount(receipt); + printAmountOfPay(receipt); + } + + private static void printTotalPrice(Receipt receipt) { + System.out.printf( + RECEIPT_TOTAL_PRICE_FORMAT, + receipt.getTotalBuyCount(), + NUMBER_FORMATTER.format(receipt.getTotalAmount()) + ); + } + + private static void printPromotionDiscount(Receipt receipt) { + System.out.printf( + RECEIPT_PROMOTION_DISCOUNT_FORMAT, + NUMBER_FORMATTER.format(receipt.getPromotionDiscountAmount()) + ); + } + + private static void printMemberShipDiscount(Receipt receipt) { + System.out.printf( + RECEIPT_MEMBERSHIP_DISCOUNT_FORMAT, + NUMBER_FORMATTER.format(receipt.getMembershipDiscountAmount()) + ); + } + + private static void printAmountOfPay(Receipt receipt) { + System.out.printf( + RECEIPT_AMOUNT_OF_PAY_FORMAT, + NUMBER_FORMATTER.format(receipt.getAmountOfPay()) + ); + } +}
Java
์ €์˜€๋‹ค๋ฉด ์•„๋งˆ ๋ฉ”์†Œ๋“œ๋ฅผ ์•ˆํŒŒ๊ณ  ์•„๋ž˜์ฒ˜๋Ÿผ ๋‹ค๋ฅธ ๊ณณ์—์„œ ์‚ฌ์šฉํ–ˆ์„ ๊ฒƒ ๊ฐ™์€๋ฐ์š”! ```java System.out.println(message); ``` ์ด๋ ‡๊ฒŒ `printf()`๋กœ ํ˜ธ์ถœํ•˜๋Š” ๋ฉ”์†Œ๋“œ๋ฅผ ๋”ฐ๋กœ ํŒŒ์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,144 @@ +package store.controller; + +import static store.constant.Answer.NO; +import static store.constant.Answer.YES; +import static store.constant.OutputInfo.MAY_I_TAKE_YOUR_ORDER; +import static store.constant.OutputInfo.MEMBERSHIP_DISCOUNT; +import static store.constant.OutputInfo.PRODUCT_START_MESSAGE; +import static store.constant.OutputInfo.WANNA_BUY_MORE; +import static store.constant.OutputInfo.WELCOME_MESSAGE; +import static store.constant.StoreInfo.PRODUCTS_FILE; +import static store.constant.StoreInfo.PROMOTIONS_FILE; + +import store.constant.Answer; +import store.model.Store; +import store.model.order.Order; +import store.model.order.Orders; +import store.model.product.Products; +import store.model.product.ProductsLoader; +import store.model.product.PromotionProducts; +import store.model.promotion.Promotions; +import store.model.promotion.PromotionsLoader; +import store.model.receipt.PurchaseInfos; +import store.model.receipt.Receipt; +import store.util.Task; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + public void run() { + Store store = loadFilesAndMakeStore(); + + while (true) { + printWelcomeAndAllProducts(store); + takeOrdersAndPrintReceipt(store); + if (answerToMoreOrders() == NO) { + break; + } + } + } + + private Store loadFilesAndMakeStore() { + PromotionsLoader promotionsLoader = new PromotionsLoader(PROMOTIONS_FILE); + ProductsLoader productsLoader = new ProductsLoader(PRODUCTS_FILE, + new Promotions(promotionsLoader.getPromotions())); + + return new Store( + new Products(productsLoader.getProducts()), + new PromotionProducts(productsLoader.getPromotionProducts()) + ); + } + + private void takeOrdersAndPrintReceipt(Store store) { + Orders orders = readAvailableOrders(store); + + readAnswerToFreeGettableCount(store, orders); + readAnswerToBuyProductsWithoutPromotion(store, orders); + + OutputView.printReceipt(new Receipt( + answerToMembershipDiscount() == YES, + sellAllProducts(store, orders) + )); + } + + private void printWelcomeAndAllProducts(Store store) { + OutputView.println(WELCOME_MESSAGE); + OutputView.println(PRODUCT_START_MESSAGE); + OutputView.printProducts(store.getProducts()); + OutputView.printPromotionProducts(store.getPromotionProducts()); + } + + private Orders readAvailableOrders(Store store) { + return Task.retryTillNoException(() -> { + OutputView.println(MAY_I_TAKE_YOUR_ORDER); + Orders orders = new Orders(InputView.readOrders()); + + for (Order order : orders.toList()) { + store.checkAvailability(order); + } + return orders; + }); + } + + private void readAnswerToFreeGettableCount(Store store, Orders orders) { + for (Order order : orders.toList()) { + final int freeGettableCount = store.getFreeGettableCount(order); + if (freeGettableCount == 0) { + continue; + } + + if (answerToGetFreeProducts(order, freeGettableCount) == YES) { + order.add(freeGettableCount); + } + } + } + + private Answer answerToGetFreeProducts(Order order, final int freeGettableCount) { + return Task.retryTillNoException(() -> { + OutputView.printQuestionToFreeGettableCount(order, freeGettableCount); + return InputView.readAnswer(); + }); + } + + private void readAnswerToBuyProductsWithoutPromotion(Store store, Orders orders) { + for (Order order : orders.toList()) { + final int buyCountWithoutPromotion = store.getBuyCountWithoutPromotion(order); + if (buyCountWithoutPromotion == 0) { + continue; + } + + if (answerToBuyWithoutPromotion(order, buyCountWithoutPromotion) == NO) { + order.cancel(buyCountWithoutPromotion); + } + } + } + + private Answer answerToBuyWithoutPromotion(Order order, final int buyCountWithoutPromotion) { + return Task.retryTillNoException(() -> { + OutputView.printQuestionToBuyCountWithoutPromotion(order, buyCountWithoutPromotion); + return InputView.readAnswer(); + }); + } + + private Answer answerToMembershipDiscount() { + return Task.retryTillNoException(() -> { + OutputView.println(MEMBERSHIP_DISCOUNT); + return InputView.readAnswer(); + }); + } + + private Answer answerToMoreOrders() { + return Task.retryTillNoException(() -> { + OutputView.println(WANNA_BUY_MORE); + return InputView.readAnswer(); + }); + } + + private PurchaseInfos sellAllProducts(Store store, Orders orders) { + return new PurchaseInfos( + orders.toList().stream() + .map(store::sell) + .toList() + ); + } +}
Java
์ด๋Ÿฐ์‹์œผ๋กœ ์ถœ๋ ฅํ•˜๋ฉด ์ผ๋ฐ˜ ์ƒํ’ˆ๋“ค ๋จผ์ € ์ถœ๋ ฅํ•˜๊ณ , ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์„ ๊ทธ๋‹ค์Œ์— ๋ชฐ์•„์„œ ์ถœ๋ ฅํ•˜๊ฒŒ ๋˜๋Š” ํ˜•ํƒœ์ผ๊นŒ์š”?? ์ œ๊ฐ€ ์ฝ”๋“œ๋ฅผ ๋งž๊ฒŒ ์ดํ•ดํ•œ๊ฑด์ง€ ๋ชจ๋ฅด๊ฒ ๋„ค์š”..!
@@ -0,0 +1,129 @@ +package store.model; + +import static store.constant.ErrorMessage.CANNOT_FIND_PRODUCT; +import static store.constant.ErrorMessage.EXCEEDED_QUANTITY; + +import store.model.order.Order; +import store.model.product.Product; +import store.model.product.Products; +import store.model.product.PromotionProduct; +import store.model.product.PromotionProducts; +import store.model.receipt.PurchaseInfo; + +public class Store { + private final Products products; + private final PromotionProducts promotionProducts; + + public Store(Products products, PromotionProducts promotionProducts) { + this.products = products; + this.promotionProducts = promotionProducts; + } + + public Products getProducts() { + return products; + } + + public PromotionProducts getPromotionProducts() { + return promotionProducts; + } + + private static boolean isAvailable(PromotionProduct promotionProduct) { + return promotionProduct != null && promotionProduct.isAvailable(); + } + + public void checkAvailability(Order order) { + checkProductName(order); + checkQuantity(order); + } + + private void checkProductName(Order order) { + Product product = products.getNameWith(order.getProductName()); + if (product == null) { + throw new IllegalArgumentException(CANNOT_FIND_PRODUCT.getMessage()); + } + } + + private void checkQuantity(Order order) { + Product product = products.getNameWith(order.getProductName()); + PromotionProduct promotionProduct = promotionProducts.getNameWith(order.getProductName()); + int totalQuantity = product.getQuantity(); + if (isAvailable(promotionProduct)) { + totalQuantity += promotionProduct.getQuantity(); + } + + if (totalQuantity < order.getBuyCount()) { + throw new IllegalArgumentException(EXCEEDED_QUANTITY.getMessage()); + } + } + + public int getFreeGettableCount(Order order) { + PromotionProduct promotionProduct = promotionProducts.getNameWith(order.getProductName()); + + if (!isAvailable(promotionProduct)) { + return 0; + } + return promotionProduct.getFreeGettableCount(order.getBuyCount()); + } + + public int getBuyCountWithoutPromotion(Order order) { + PromotionProduct promotionProduct = promotionProducts.getNameWith(order.getProductName()); + + if (!isAvailable(promotionProduct) || order.getBuyCount() <= promotionProduct.getQuantity()) { + return 0; + } + return order.getBuyCount() - promotionProduct.getPromotionEffectCount(); + } + + public PurchaseInfo sell(Order order) { + Seller seller = new Seller( + order.getBuyCount(), + products.getNameWith(order.getProductName()), + promotionProducts.getNameWith(order.getProductName()) + ); + + seller.sell(); + return new PurchaseInfo(order, seller.getPrice(), seller.getFreeCount()); + } + + private static class Seller { + private int freeCount; + private int remainSellCount; + private final Product product; + private final PromotionProduct promotionProduct; + + public Seller(final int remainSellCount, Product product, PromotionProduct promotionProduct) { + this.remainSellCount = remainSellCount; + this.product = product; + this.promotionProduct = promotionProduct; + } + + public void sell() { + sellPromotionProduct(); + sellProduct(); + } + + private void sellPromotionProduct() { + if (!isAvailable(promotionProduct)) { + return; + } + + final int promotionSellCount = Math.min(remainSellCount, promotionProduct.getQuantity()); + + freeCount = promotionProduct.getFreeCountIn(promotionSellCount); + remainSellCount -= promotionSellCount; + promotionProduct.sell(promotionSellCount); + } + + private void sellProduct() { + product.sell(remainSellCount); + } + + public int getFreeCount() { + return freeCount; + } + + public int getPrice() { + return product.getPrice(); + } + } +}
Java
์ €๋Š” ์ด๋ฒˆ ํ”„๋ฆฌ์ฝ”์Šค๋ฅผ ์ง„ํ–‰ํ•˜๋ฉด์„œ validate ํ•  ๋ถ€๋ถ„์€ `Validator` ํด๋ž˜์Šค๋ฅผ ๋”ฐ๋กœ ํŒŒ์„œ input ๊ฒ€์ฆ์„ ์ง„ํ–‰ํ–ˆ์—ˆ๋Š”๋ฐ์š”! ๊ฐœ์ธ์ ์œผ๋กœ ๊ฒ€์ฆ ๋กœ์ง์„ ๋„๋ฉ”์ธ์— ๋‹ด๊ธฐ์—๋Š” ์ฑ…์ž„์ด ๋” ๋งŽ์•„์ง„๋‹ค๊ณ  ์ƒ๊ฐ์„ ํ–ˆ์–ด์„œ ํด๋ž˜์Šค๋ฅผ ๋”ฐ๋กœ ๋งŒ๋“ค์—ˆ์—ˆ์Šต๋‹ˆ๋‹ค. ํƒœ์–‘๋‹˜์€ ์ „์ฒด์ ์œผ๋กœ ๋„๋ฉ”์ธ ์ž์ฒด์— ๊ฒ€์ฆ ๋กœ์ง์„ ๋‹ด์•„๋‘์‹  ๊ฒƒ ๊ฐ™๋”๋ผ๊ตฌ์š”..! ์ €์˜ ์ƒ๊ฐ๊ณผ๋Š” ๋‹ค๋ฅธ ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ˜„ํ•˜์‹  ๊ฒƒ ๊ฐ™์•„์„œ ๊ฒ€์ฆ์˜ ์ฑ…์ž„์— ๋Œ€ํ•ด ์–ด๋–ค ์˜๊ฒฌ์ด์‹ ์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,17 @@ +package store.util; + +import store.view.OutputView; + +public interface Task<T> { + static <T> T retryTillNoException(Task<T> task) { + while (true) { + try { + return task.run(); + } catch (IllegalArgumentException e) { + OutputView.println(e.getMessage()); + } + } + } + + T run(); +}
Java
์ด๋ ‡๊ฒŒ ๋ฐ˜๋ณต ์ฒ˜๋ฆฌ๋ฅผ ํ•  ์ˆ˜๋„ ์žˆ๊ฒ ๊ตฐ์š”..! ์ €๋Š” ์˜ˆ์™ธ ์žฌ์ž…๋ ฅ ๋กœ์ง์ด ๋„ˆ๋ฌด ๋ฐ˜๋ณต์ ์ด๋ผ ์–ด๋–ป๊ฒŒ ์ฒ˜๋ฆฌํ• ์ง€ ๊ฒฐ๋ก  ๋ชป๋‚ด๊ณ  ๋๋ƒˆ๋Š”๋ฐ ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค!!
@@ -0,0 +1,35 @@ +package store.view; + +import static store.constant.ErrorMessage.WRONG_INPUT; +import static store.constant.OrderInfo.ORDER_DELIMITER; + +import camp.nextstep.edu.missionutils.Console; +import java.util.ArrayList; +import java.util.List; +import store.constant.Answer; +import store.model.order.Order; +import store.util.Converter; +import store.util.Spliter; + +public class InputView { + public static List<Order> readOrders() { + Spliter spliter = new Spliter(Console.readLine(), ORDER_DELIMITER); + List<Order> orders = new ArrayList<>(); + + while (spliter.hasMoreTokens()) { + String nextToken = spliter.nextToken(); + + orders.add(Converter.toOrder(nextToken)); + } + return orders; + } + + public static Answer readAnswer() { + Answer answer = Answer.getMatchingAnswer(Console.readLine()); + + if (answer == null) { + throw new IllegalArgumentException(WRONG_INPUT.getMessage()); + } + return answer; + } +}
Java
์ €๋Š” ์ž…๋ ฅ๋ฐ›์„ ๋•Œ ํ•„์š”ํ•œ ํ”„๋กฌํ”„ํŠธ ์ถœ๋ ฅ๋„ `InputView`์˜ ์ฑ…์ž„์ด๋ผ๊ณ  ์ƒ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค. ํƒœ์–‘๋‹˜์€ `InputView`๋Š” ๋”ฑ ์ž…๋ ฅ์˜ ์—ญํ• ๋งŒ ๊ฐ–๋Š”๋‹ค๋Š” ์ƒ๊ฐ์ด์…จ๋˜ ๊ฒƒ ๊ฐ™๋„ค์š”! ๋˜๋‹ค๋ฅธ ๊ด€์ ์ด๋ผ ํฅ๋ฏธ๋กญ์Šต๋‹ˆ๋‹ค..!
@@ -0,0 +1,12 @@ +package store.constant; + +public class StoreInfo { + public static final String PRODUCTS_FILE = "src/main/resources/products.md"; + public static final String PRODUCTS_DELIMITER = ","; + public static final String PROMOTIONS_FILE = "src/main/resources/promotions.md"; + public static final String PROMOTIONS_DATE_FORMAT = "yyyy-MM-dd"; + public static final String PROMOTIONS_DELIMITER = ","; + public static final String NO_PROMOTION = "null"; + public static final double MEMBERSHIP_DISCOUNT_PERCENTAGE = 0.3; + public static final int MAX_MEMBERSHIP_DISCOUNT_AMOUNT = 8_000; +}
Java
์ €๋Š” constants๋ฅผ enum ์—†์ด class๋กœ ์ƒ์„ฑํ•˜๋Š” ๊ฒฝ์šฐ, ์ƒ์„ฑ์ž๋ฅผ private์œผ๋กœ ๋Œ๋ฆฌ๊ณ  ํด๋ž˜์Šค๋„ final๋กœ ์„ ์–ธํ•ด ์ธ์Šคํ„ด์Šคํ™”๋ฅผ ์™„์ „ํžˆ ๋ง‰์•„๋ฒ„๋ฆฌ๊ณค ํ•ฉ๋‹ˆ๋‹ค! ์ด๋ฒˆ ๊ณผ์ œ์—์„œ๋Š” ์˜ค๋ฒ„ ์—”์ง€๋‹ˆ์–ด๋ง์ผ ์ˆ˜ ์žˆ์ง€๋งŒ..! ์ฐธ๊ณ  ์ฐจ์›์—์„œ ์ฝ”๋ฉ˜ํŠธ ๋“œ๋ฆฝ๋‹ˆ๋‹ค :)
@@ -0,0 +1,28 @@ +package store.constant; + +public class OutputInfo { + public static final String NEW_LINE = "%n"; + public static final String WELCOME_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค."; + public static final String PRODUCT_START_MESSAGE = "ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค." + NEW_LINE; + public static final String PRODUCT_FORMAT = "- %s %s์› %s" + NEW_LINE; + public static final String PROMOTION_PRODUCT_FORMAT = "- %s %s์› %s %s" + NEW_LINE; + public static final String NO_QUANTITY = "์žฌ๊ณ  ์—†์Œ"; + public static final String QUANTITY_FORMAT = "%d๊ฐœ"; + public static final String MAY_I_TAKE_YOUR_ORDER = "๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"; + public static final String FREE_GETTABLE_COUNT_QUESTION = + "ํ˜„์žฌ %s์€(๋Š”) %d๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)" + NEW_LINE; + public static final String BUY_COUNT_WITHOUT_PROMOTION_QUESTION = + "ํ˜„์žฌ %s %d๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)" + NEW_LINE; + public static final String MEMBERSHIP_DISCOUNT = "๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"; + public static final String RECEIPT_START_MESSAGE = "==============W ํŽธ์˜์ ================" + NEW_LINE; + public static final String RECEIPT_PURCHASE_INFO_START_MESSAGE = "์ƒํ’ˆ๋ช…\t\t์ˆ˜๋Ÿ‰\t๊ธˆ์•ก" + NEW_LINE; + public static final String RECEIPT_PURCHASE_INFO_FORMAT = "%s\t\t%d \t%s" + NEW_LINE; + public static final String RECEIPT_FREE_START_MESSAGE = "=============์ฆ\t์ •===============" + NEW_LINE; + public static final String RECEIPT_FREE_PRODUCT_FORMAT = "%s\t\t%d" + NEW_LINE; + public static final String RECEIPT_PAY_START_MESSAGE = "====================================" + NEW_LINE; + public static final String RECEIPT_TOTAL_PRICE_FORMAT = "์ด๊ตฌ๋งค์•ก\t\t%d\t%s" + NEW_LINE; + public static final String RECEIPT_PROMOTION_DISCOUNT_FORMAT = "ํ–‰์‚ฌํ• ์ธ\t\t\t-%s" + NEW_LINE; + public static final String RECEIPT_MEMBERSHIP_DISCOUNT_FORMAT = "๋ฉค๋ฒ„์‹ญํ• ์ธ\t\t\t-%s" + NEW_LINE; + public static final String RECEIPT_AMOUNT_OF_PAY_FORMAT = "๋‚ด์‹ค๋ˆ\t\t\t %s" + NEW_LINE; + public static final String WANNA_BUY_MORE = "๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"; +}
Java
์šฐํ…Œ์ฝ”์—์„œ๋Š” ์ƒ์ˆ˜ ๊ด€๋ฆฌ๋ฅผ enum ํƒ€์ž…์œผ๋กœ ๊ถŒ์žฅํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค! ์ €๋Š” ๊ฐœ์ธ์ ์œผ๋ก  enum์— ๋‹ค๋ฅธ ๋ฉ”์†Œ๋“œ ์ถ”๊ฐ€๊ฐ€ ์—†๋‹ค๋ฉด ํƒœ์–‘๋‹˜์ฒ˜๋Ÿผ static final์„ ์‚ฌ์šฉํ•ด ์ƒ์ˆ˜ํ™” ํ•˜๋Š” ๊ฑธ ์„ ํ˜ธํ•˜๋Š”๋ฐ.. ํƒœ์–‘๋‹˜์€ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,34 @@ +package store.model.promotion; + +import static store.constant.ErrorMessage.INVALID_PERIOD; + +import java.time.LocalDateTime; + +public class Period { + private final LocalDateTime start; + private final LocalDateTime end; + + public Period(LocalDateTime start, LocalDateTime end) { + validate(start, end); + this.start = start; + this.end = end; + } + + private void validate(LocalDateTime start, LocalDateTime end) { + validateStartIsBeforeEnd(start, end); + } + + private void validateStartIsBeforeEnd(LocalDateTime start, LocalDateTime end) { + if (!start.isBefore(end)) { + throw new IllegalArgumentException(INVALID_PERIOD.getMessage()); + } + } + + public boolean includes(LocalDateTime time) { + if (start.isEqual(time) || end.isEqual(time)) { // ์‹œ์ž‘๊ณผ ๋ ์‹œ๊ฐ„๊นŒ์ง€ ํฌํ•จ + return true; + } + + return time.isAfter(start) && time.isBefore(end); + } +}
Java
์•„๋งˆ ํ”„๋กœ๋ชจ์…˜ ์ง„ํ–‰ ๊ธฐ๊ฐ„์ธ์ง€ ํŒ๋‹จํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜์‹  ๊ฒƒ ๊ฐ™์•„์š”! ์•„๋ž˜์ฒ˜๋Ÿผ ๋‹จ์ˆœํ™” ํ•ด๋ด๋„ ๊ดœ์ฐฎ์„ ๊ฒƒ ๊ฐ™๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ญ๋‹ˆ๋‹ค :) ```java return !(time.isBefore(start) || time.isAfter(end)); ```
@@ -0,0 +1,129 @@ +package store.model; + +import static store.constant.ErrorMessage.CANNOT_FIND_PRODUCT; +import static store.constant.ErrorMessage.EXCEEDED_QUANTITY; + +import store.model.order.Order; +import store.model.product.Product; +import store.model.product.Products; +import store.model.product.PromotionProduct; +import store.model.product.PromotionProducts; +import store.model.receipt.PurchaseInfo; + +public class Store { + private final Products products; + private final PromotionProducts promotionProducts; + + public Store(Products products, PromotionProducts promotionProducts) { + this.products = products; + this.promotionProducts = promotionProducts; + } + + public Products getProducts() { + return products; + } + + public PromotionProducts getPromotionProducts() { + return promotionProducts; + } + + private static boolean isAvailable(PromotionProduct promotionProduct) { + return promotionProduct != null && promotionProduct.isAvailable(); + } + + public void checkAvailability(Order order) { + checkProductName(order); + checkQuantity(order); + } + + private void checkProductName(Order order) { + Product product = products.getNameWith(order.getProductName()); + if (product == null) { + throw new IllegalArgumentException(CANNOT_FIND_PRODUCT.getMessage()); + } + } + + private void checkQuantity(Order order) { + Product product = products.getNameWith(order.getProductName()); + PromotionProduct promotionProduct = promotionProducts.getNameWith(order.getProductName()); + int totalQuantity = product.getQuantity(); + if (isAvailable(promotionProduct)) { + totalQuantity += promotionProduct.getQuantity(); + } + + if (totalQuantity < order.getBuyCount()) { + throw new IllegalArgumentException(EXCEEDED_QUANTITY.getMessage()); + } + } + + public int getFreeGettableCount(Order order) { + PromotionProduct promotionProduct = promotionProducts.getNameWith(order.getProductName()); + + if (!isAvailable(promotionProduct)) { + return 0; + } + return promotionProduct.getFreeGettableCount(order.getBuyCount()); + } + + public int getBuyCountWithoutPromotion(Order order) { + PromotionProduct promotionProduct = promotionProducts.getNameWith(order.getProductName()); + + if (!isAvailable(promotionProduct) || order.getBuyCount() <= promotionProduct.getQuantity()) { + return 0; + } + return order.getBuyCount() - promotionProduct.getPromotionEffectCount(); + } + + public PurchaseInfo sell(Order order) { + Seller seller = new Seller( + order.getBuyCount(), + products.getNameWith(order.getProductName()), + promotionProducts.getNameWith(order.getProductName()) + ); + + seller.sell(); + return new PurchaseInfo(order, seller.getPrice(), seller.getFreeCount()); + } + + private static class Seller { + private int freeCount; + private int remainSellCount; + private final Product product; + private final PromotionProduct promotionProduct; + + public Seller(final int remainSellCount, Product product, PromotionProduct promotionProduct) { + this.remainSellCount = remainSellCount; + this.product = product; + this.promotionProduct = promotionProduct; + } + + public void sell() { + sellPromotionProduct(); + sellProduct(); + } + + private void sellPromotionProduct() { + if (!isAvailable(promotionProduct)) { + return; + } + + final int promotionSellCount = Math.min(remainSellCount, promotionProduct.getQuantity()); + + freeCount = promotionProduct.getFreeCountIn(promotionSellCount); + remainSellCount -= promotionSellCount; + promotionProduct.sell(promotionSellCount); + } + + private void sellProduct() { + product.sell(remainSellCount); + } + + public int getFreeCount() { + return freeCount; + } + + public int getPrice() { + return product.getPrice(); + } + } +}
Java
์ด ํด๋ž˜์Šค๋ฅผ ๋”ฐ๋กœ ๋นผ์ง€ ์•Š๊ณ  ๋‚ด๋ถ€์—์„œ ์‚ฌ์šฉํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,36 @@ +package store.model.order; + +import static store.constant.ErrorMessage.WRONG_INPUT; + +public class Order { + protected final String productName; + protected int buyCount; + + public Order(String productName, final int buyCount) { + validateNotNegative(buyCount); + this.productName = productName; + this.buyCount = buyCount; + } + + private void validateNotNegative(final int buyCount) { + if (buyCount < 0) { + throw new IllegalArgumentException(WRONG_INPUT.getMessage()); + } + } + + public String getProductName() { + return productName; + } + + public int getBuyCount() { + return buyCount; + } + + public void add(final int toAdd) { + buyCount += toAdd; + } + + public void cancel(final int toCancel) { + buyCount -= toCancel; + } +}
Java
์ด๋Ÿฐ๊ฒƒ๋„ ์ƒ์ˆ˜์ฒ˜๋ฆฌํ•˜๋ฉด ๋” ์ข‹์„๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,34 @@ +package store.util; + +import static store.constant.ErrorMessage.FILE_NOT_FOUND; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.List; + +public class FileLines { + private final List<String> lines; + + public FileLines(String file) { + try { + BufferedReader reader = new BufferedReader(new FileReader(file)); + + lines = new ArrayList<>(reader.lines().toList()); + } catch (FileNotFoundException e) { + throw new IllegalArgumentException(FILE_NOT_FOUND.getMessage()); + } + } + + public boolean hasMoreLines() { + return !lines.isEmpty(); + } + + public String nextLine() { + String line = lines.getFirst(); + + lines.removeFirst(); + return line; + } +}
Java
ํŒŒ์ผ์ด ์—†๋Š” ๊ฒฝ์šฐ๋Š”์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•  ์ƒ๊ฐ์„ ๋ชปํ–ˆ๋Š”๋ฐ ์˜ˆ์™ธ๋ฅผ ๊ผผ๊ผผํ•˜๊ฒŒ ์ฒ˜๋ฆฌํ•˜์…จ๋„ค์š”
@@ -0,0 +1,27 @@ +package store.util; + +import java.util.ArrayList; +import java.util.List; + +public class Spliter { + private static final int INCLUDE_TRAILING = -1; + + private final List<String> tokens; + + public Spliter(String toBeSplited, String regex) { + tokens = new ArrayList<>(List.of( + toBeSplited.split(regex, INCLUDE_TRAILING) + )); + } + + public boolean hasMoreTokens() { + return !tokens.isEmpty(); + } + + public String nextToken() { + String token = tokens.getFirst(); + + tokens.removeFirst(); + return token; + } +}
Java
ํ˜น์‹œ ์ด๊ฒŒ ์ฃผ๋ฌธ ์ƒํ’ˆ ๊ด€๋ จ๋œ ๊ฒƒ ์ผ๊นŒ์š”? ์ œ๊ฐ€ ์ฝ”๋“œ๊ฐ€ ์ž˜ ์ดํ•ด๊ฐ€ ์•ˆ๋˜์„œ ์งˆ๋ฌธ๋“œ๋ฆฝ๋‹ˆ๋‹ค...
@@ -0,0 +1,44 @@ +package store.util; + +import static store.constant.ErrorMessage.INVALID_ORDER_FORMAT; +import static store.constant.ErrorMessage.WRONG_INPUT; +import static store.constant.OrderInfo.ORDER_PATTERN; +import static store.constant.OrderInfo.PRODUCT_COUNT_GROUP; +import static store.constant.OrderInfo.PRODUCT_NAME_GROUP; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.regex.Matcher; +import store.model.order.Order; + +public class Converter { + public static int toInteger(String number) { + try { + return Integer.parseInt(number); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(WRONG_INPUT.getMessage()); + } + } + + public static LocalDateTime toLocalDateTime(String localDate, String dateFormat) { + return LocalDate.parse( + localDate, + DateTimeFormatter.ofPattern(dateFormat) + ) + .atStartOfDay(); + } + + public static Order toOrder(String order) { + Matcher matcher = ORDER_PATTERN.matcher(order); + + if (!matcher.matches()) { + throw new IllegalArgumentException(INVALID_ORDER_FORMAT.getMessage()); + } + + return new Order( + matcher.group(PRODUCT_NAME_GROUP), + Converter.toInteger(matcher.group(PRODUCT_COUNT_GROUP)) + ); + } +}
Java
์ €๋Š” ํ”„๋กœ๋ชจ์…˜ ๋‚ด๋ถ€์—์„œ ์ฒ˜๋ฆฌํ–ˆ๋Š”๋ฐ ๋”ฐ๋กœ ๋นผ๋Š” ๊ฒƒ๋„ ์ข‹์€ ๋ฐฉ๋ฒ•์ด๋„ค์š”
@@ -0,0 +1,59 @@ +package store.model.product; + +import static store.constant.StoreInfo.NO_PROMOTION; +import static store.constant.StoreInfo.PRODUCTS_DELIMITER; + +import java.util.ArrayList; +import java.util.List; +import store.model.promotion.Promotions; +import store.util.Converter; +import store.util.FileLines; +import store.util.Spliter; + +public class ProductsLoader { + private final List<Product> products; + private final List<PromotionProduct> promotionProducts; + + public ProductsLoader(String file, Promotions promotions) { + FileLines fileLines = new FileLines(file); + fileLines.nextLine(); + + products = new ArrayList<>(); + promotionProducts = new ArrayList<>(); + while (fileLines.hasMoreLines()) { + addProduct(new Spliter(fileLines.nextLine(), PRODUCTS_DELIMITER), promotions); + } + addProductsOnlyInPromotionProducts(); + } + + private void addProduct(Spliter spliter, Promotions promotions) { + String name = spliter.nextToken(); + final int price = Converter.toInteger(spliter.nextToken()); + final int quantity = Converter.toInteger(spliter.nextToken()); + String promotionName = spliter.nextToken(); + + if (promotionName.equals(NO_PROMOTION)) { + products.add(new Product(name, price, quantity)); + return; + } + promotionProducts.add(new PromotionProduct(name, price, quantity, promotions.getNameWith(promotionName))); + } + + private void addProductsOnlyInPromotionProducts() { + List<String> productNames = products.stream().map(Product::getName).toList(); + + promotionProducts.stream() + .filter(promotionProduct -> !productNames.contains(promotionProduct.getName())) + .forEach(promotionProduct -> + products.add(new Product(promotionProduct.getName(), promotionProduct.getPrice(), 0)) + ); + } + + public List<Product> getProducts() { + return products; + } + + public List<PromotionProduct> getPromotionProducts() { + return promotionProducts; + } +}
Java
ํ”„๋กœ๋ชจ์…˜๊ณผ ์ƒํ’ˆ์„ ํŒŒ์ผ์—์„œ ์ฝ์–ด์˜ค์‹ ๊ฑธ ์ €์žฅํ•˜๋Š” ํด๋ž˜์Šค๊ฐ€ ์žˆ๋˜๋ฐ ๋”ฐ๋กœ ๋งŒ๋“œ์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,27 @@ +package store.constant; + +public enum ErrorMessage { + FILE_NOT_FOUND("ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + INVALID_PERIOD("๊ธฐ๊ฐ„์ด ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์Šต๋‹ˆ๋‹ค."), + PRICE_NEGATIVE("๊ฐ€๊ฒฉ์ด ์Œ์ˆ˜์ž…๋‹ˆ๋‹ค."), + QUANTITY_NEGATIVE("์ˆ˜๋Ÿ‰์ด ์Œ์ˆ˜์ž…๋‹ˆ๋‹ค."), + BUY_COUNT_NOT_POSITIVE("์ฆ์ • ์กฐ๊ฑด์ด ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์Šต๋‹ˆ๋‹ค."), + GET_COUNT_NOT_POSITIVE("์ฆ์ • ๊ฐœ์ˆ˜๊ฐ€ ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์Šต๋‹ˆ๋‹ค."), + CANNOT_FIND_PRODUCT("์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + INVALID_ORDER_FORMAT("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + EXCEEDED_QUANTITY("์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + WRONG_INPUT("์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + ; + + private static final String ERROR_PREFIX = "[ERROR] "; + + private final String message; + + ErrorMessage(String message) { + this.message = ERROR_PREFIX + message; + } + + public String getMessage() { + return message; + } +}
Java
๋ณธ์ธ๋งŒ์˜ ์ƒ์ˆ˜๋ฅผ ENUM ํƒ€์ž…์œผ๋กœ ๊ด€๋ฆฌํ•˜๋Š” ๊ธฐ์ค€์ด ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,30 @@ +package store.constant; + +public enum Answer { + YES("Y"), + NO("N"), + ; + + private final String message; + + Answer(String message) { + this.message = message; + } + + public static Answer getMatchingAnswer(String toFind) { + for (Answer answer : Answer.values()) { + if (answer.matches(toFind)) { + return answer; + } + } + return null; + } + + private boolean matches(String answer) { + return message.equals(answer); + } + + public String getMessage() { + return message; + } +}
Java
null๋กœ ๋ฐ˜ํ™˜ํ•ด์„œ ์™ธ๋ถ€์—์„œ ์ž˜๋ชป๋œ ์ž…๋ ฅ์ธ์ง€ ํ™•์ธํ•˜๋Š”๊ฑฐ ๋ณด๋‹ค ์—ฌ๊ธฐ์„œ ์˜ˆ์™ธ๋ฅผ ๋˜์ง€๋Š” ๊ฒƒ๋„ ์ข‹์„๊ฑฐ๊ฐ™์Šต๋‹ˆ๋‹ค ใ…Žใ…Ž!๐Ÿ˜Š
@@ -0,0 +1,144 @@ +package store.controller; + +import static store.constant.Answer.NO; +import static store.constant.Answer.YES; +import static store.constant.OutputInfo.MAY_I_TAKE_YOUR_ORDER; +import static store.constant.OutputInfo.MEMBERSHIP_DISCOUNT; +import static store.constant.OutputInfo.PRODUCT_START_MESSAGE; +import static store.constant.OutputInfo.WANNA_BUY_MORE; +import static store.constant.OutputInfo.WELCOME_MESSAGE; +import static store.constant.StoreInfo.PRODUCTS_FILE; +import static store.constant.StoreInfo.PROMOTIONS_FILE; + +import store.constant.Answer; +import store.model.Store; +import store.model.order.Order; +import store.model.order.Orders; +import store.model.product.Products; +import store.model.product.ProductsLoader; +import store.model.product.PromotionProducts; +import store.model.promotion.Promotions; +import store.model.promotion.PromotionsLoader; +import store.model.receipt.PurchaseInfos; +import store.model.receipt.Receipt; +import store.util.Task; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + public void run() { + Store store = loadFilesAndMakeStore(); + + while (true) { + printWelcomeAndAllProducts(store); + takeOrdersAndPrintReceipt(store); + if (answerToMoreOrders() == NO) { + break; + } + } + } + + private Store loadFilesAndMakeStore() { + PromotionsLoader promotionsLoader = new PromotionsLoader(PROMOTIONS_FILE); + ProductsLoader productsLoader = new ProductsLoader(PRODUCTS_FILE, + new Promotions(promotionsLoader.getPromotions())); + + return new Store( + new Products(productsLoader.getProducts()), + new PromotionProducts(productsLoader.getPromotionProducts()) + ); + } + + private void takeOrdersAndPrintReceipt(Store store) { + Orders orders = readAvailableOrders(store); + + readAnswerToFreeGettableCount(store, orders); + readAnswerToBuyProductsWithoutPromotion(store, orders); + + OutputView.printReceipt(new Receipt( + answerToMembershipDiscount() == YES, + sellAllProducts(store, orders) + )); + } + + private void printWelcomeAndAllProducts(Store store) { + OutputView.println(WELCOME_MESSAGE); + OutputView.println(PRODUCT_START_MESSAGE); + OutputView.printProducts(store.getProducts()); + OutputView.printPromotionProducts(store.getPromotionProducts()); + } + + private Orders readAvailableOrders(Store store) { + return Task.retryTillNoException(() -> { + OutputView.println(MAY_I_TAKE_YOUR_ORDER); + Orders orders = new Orders(InputView.readOrders()); + + for (Order order : orders.toList()) { + store.checkAvailability(order); + } + return orders; + }); + } + + private void readAnswerToFreeGettableCount(Store store, Orders orders) { + for (Order order : orders.toList()) { + final int freeGettableCount = store.getFreeGettableCount(order); + if (freeGettableCount == 0) { + continue; + } + + if (answerToGetFreeProducts(order, freeGettableCount) == YES) { + order.add(freeGettableCount); + } + } + } + + private Answer answerToGetFreeProducts(Order order, final int freeGettableCount) { + return Task.retryTillNoException(() -> { + OutputView.printQuestionToFreeGettableCount(order, freeGettableCount); + return InputView.readAnswer(); + }); + } + + private void readAnswerToBuyProductsWithoutPromotion(Store store, Orders orders) { + for (Order order : orders.toList()) { + final int buyCountWithoutPromotion = store.getBuyCountWithoutPromotion(order); + if (buyCountWithoutPromotion == 0) { + continue; + } + + if (answerToBuyWithoutPromotion(order, buyCountWithoutPromotion) == NO) { + order.cancel(buyCountWithoutPromotion); + } + } + } + + private Answer answerToBuyWithoutPromotion(Order order, final int buyCountWithoutPromotion) { + return Task.retryTillNoException(() -> { + OutputView.printQuestionToBuyCountWithoutPromotion(order, buyCountWithoutPromotion); + return InputView.readAnswer(); + }); + } + + private Answer answerToMembershipDiscount() { + return Task.retryTillNoException(() -> { + OutputView.println(MEMBERSHIP_DISCOUNT); + return InputView.readAnswer(); + }); + } + + private Answer answerToMoreOrders() { + return Task.retryTillNoException(() -> { + OutputView.println(WANNA_BUY_MORE); + return InputView.readAnswer(); + }); + } + + private PurchaseInfos sellAllProducts(Store store, Orders orders) { + return new PurchaseInfos( + orders.toList().stream() + .map(store::sell) + .toList() + ); + } +}
Java
break๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ฝ”๋“œ ํ๋ฆ„์„ ์žก๊ธฐ๊ฐ€ ์–ด๋ ค์›Œ rladmstn๋‹˜ ๋ง์”€์ฒ˜๋Ÿผ do while๋กœ ํ•˜๋Š”๊ฒŒ ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค!
@@ -0,0 +1,44 @@ +package store.util; + +import static store.constant.ErrorMessage.INVALID_ORDER_FORMAT; +import static store.constant.ErrorMessage.WRONG_INPUT; +import static store.constant.OrderInfo.ORDER_PATTERN; +import static store.constant.OrderInfo.PRODUCT_COUNT_GROUP; +import static store.constant.OrderInfo.PRODUCT_NAME_GROUP; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.regex.Matcher; +import store.model.order.Order; + +public class Converter { + public static int toInteger(String number) { + try { + return Integer.parseInt(number); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(WRONG_INPUT.getMessage()); + } + } + + public static LocalDateTime toLocalDateTime(String localDate, String dateFormat) { + return LocalDate.parse( + localDate, + DateTimeFormatter.ofPattern(dateFormat) + ) + .atStartOfDay(); + } + + public static Order toOrder(String order) { + Matcher matcher = ORDER_PATTERN.matcher(order); + + if (!matcher.matches()) { + throw new IllegalArgumentException(INVALID_ORDER_FORMAT.getMessage()); + } + + return new Order( + matcher.group(PRODUCT_NAME_GROUP), + Converter.toInteger(matcher.group(PRODUCT_COUNT_GROUP)) + ); + } +}
Java
์œ ํ‹ธ ํด๋ž˜์Šค๋กœ ๋‚˜๋ˆ„๋Š” ๋ณธ์ธ๋งŒ์˜ ๊ธฐ์ค€์ด ์žˆ๋‚˜์š”? ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,35 @@ +package store.view; + +import static store.constant.ErrorMessage.WRONG_INPUT; +import static store.constant.OrderInfo.ORDER_DELIMITER; + +import camp.nextstep.edu.missionutils.Console; +import java.util.ArrayList; +import java.util.List; +import store.constant.Answer; +import store.model.order.Order; +import store.util.Converter; +import store.util.Spliter; + +public class InputView { + public static List<Order> readOrders() { + Spliter spliter = new Spliter(Console.readLine(), ORDER_DELIMITER); + List<Order> orders = new ArrayList<>(); + + while (spliter.hasMoreTokens()) { + String nextToken = spliter.nextToken(); + + orders.add(Converter.toOrder(nextToken)); + } + return orders; + } + + public static Answer readAnswer() { + Answer answer = Answer.getMatchingAnswer(Console.readLine()); + + if (answer == null) { + throw new IllegalArgumentException(WRONG_INPUT.getMessage()); + } + return answer; + } +}
Java
์ฃผ์ž…์„ ์•ˆ๋ฐ›๊ณ  ์œ ํ‹ธ ํด๋ž˜์Šค๋กœ ์‚ฌ์šฉํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ๋‚˜์š”??
@@ -0,0 +1,46 @@ +package store.model.receipt; + +import java.util.List; + +public class PurchaseInfos { + private final List<PurchaseInfo> purchaseInfos; + + public PurchaseInfos(List<PurchaseInfo> purchaseInfos) { + this.purchaseInfos = purchaseInfos; + } + + public List<PurchaseInfo> toList() { + return List.copyOf(purchaseInfos); + } + + public List<PurchaseInfo> toPromotionDiscountedList() { + return purchaseInfos.stream() + .filter(PurchaseInfo::isPromotionDiscounted) + .toList(); + } + + public int getTotalBuyCount() { + return purchaseInfos.stream() + .mapToInt(PurchaseInfo::getBuyCount) + .sum(); + } + + public int getTotalAmount() { + return purchaseInfos.stream() + .mapToInt(PurchaseInfo::getTotalAmount) + .sum(); + } + + public int getPromotionDiscountAmount() { + return toPromotionDiscountedList().stream() + .mapToInt(PurchaseInfo::getPromotionDiscountAmount) + .sum(); + } + + public int getNotPromotionDiscountAppliedProductsAmount() { + return purchaseInfos.stream() + .filter(PurchaseInfo::isNotPromotionDiscounted) + .mapToInt(PurchaseInfo::getTotalAmount) + .sum(); + } +}
Java
copyof์„ ํ†ตํ•ด ์ฝ๊ธฐ์šฉ ๋ฆฌ์ŠคํŠธ๋กœ ๋ฐ˜ํ™˜ํ•˜๋Š”๊ฑฐ ์ข‹์€๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค! Collections.unmodifiableList(purchaseInfos); ์ด ๋ฐฉ๋ฒ•๋„ ์žˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,30 @@ +package store.constant; + +public enum Answer { + YES("Y"), + NO("N"), + ; + + private final String message; + + Answer(String message) { + this.message = message; + } + + public static Answer getMatchingAnswer(String toFind) { + for (Answer answer : Answer.values()) { + if (answer.matches(toFind)) { + return answer; + } + } + return null; + } + + private boolean matches(String answer) { + return message.equals(answer); + } + + public String getMessage() { + return message; + } +}
Java
enumํ˜• ํ™œ์šฉํ•ด์„œ Y,N๋งŒ ๋ฐ›์„ ์ˆ˜ ์žˆ๋„๋ก ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ์—ˆ๊ตฐ์š”. ์ €๋Š” ์ƒ๊ฐํ•ด๋ณด์ง€ ๋ชปํ–ˆ๋˜ ๋ฐฉ์‹์ด๋ผ ์ƒˆ๋กญ๋„ค์š”.. ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค!!
@@ -0,0 +1,28 @@ +package store.constant; + +public class OutputInfo { + public static final String NEW_LINE = "%n"; + public static final String WELCOME_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค."; + public static final String PRODUCT_START_MESSAGE = "ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค." + NEW_LINE; + public static final String PRODUCT_FORMAT = "- %s %s์› %s" + NEW_LINE; + public static final String PROMOTION_PRODUCT_FORMAT = "- %s %s์› %s %s" + NEW_LINE; + public static final String NO_QUANTITY = "์žฌ๊ณ  ์—†์Œ"; + public static final String QUANTITY_FORMAT = "%d๊ฐœ"; + public static final String MAY_I_TAKE_YOUR_ORDER = "๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"; + public static final String FREE_GETTABLE_COUNT_QUESTION = + "ํ˜„์žฌ %s์€(๋Š”) %d๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)" + NEW_LINE; + public static final String BUY_COUNT_WITHOUT_PROMOTION_QUESTION = + "ํ˜„์žฌ %s %d๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)" + NEW_LINE; + public static final String MEMBERSHIP_DISCOUNT = "๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"; + public static final String RECEIPT_START_MESSAGE = "==============W ํŽธ์˜์ ================" + NEW_LINE; + public static final String RECEIPT_PURCHASE_INFO_START_MESSAGE = "์ƒํ’ˆ๋ช…\t\t์ˆ˜๋Ÿ‰\t๊ธˆ์•ก" + NEW_LINE; + public static final String RECEIPT_PURCHASE_INFO_FORMAT = "%s\t\t%d \t%s" + NEW_LINE; + public static final String RECEIPT_FREE_START_MESSAGE = "=============์ฆ\t์ •===============" + NEW_LINE; + public static final String RECEIPT_FREE_PRODUCT_FORMAT = "%s\t\t%d" + NEW_LINE; + public static final String RECEIPT_PAY_START_MESSAGE = "====================================" + NEW_LINE; + public static final String RECEIPT_TOTAL_PRICE_FORMAT = "์ด๊ตฌ๋งค์•ก\t\t%d\t%s" + NEW_LINE; + public static final String RECEIPT_PROMOTION_DISCOUNT_FORMAT = "ํ–‰์‚ฌํ• ์ธ\t\t\t-%s" + NEW_LINE; + public static final String RECEIPT_MEMBERSHIP_DISCOUNT_FORMAT = "๋ฉค๋ฒ„์‹ญํ• ์ธ\t\t\t-%s" + NEW_LINE; + public static final String RECEIPT_AMOUNT_OF_PAY_FORMAT = "๋‚ด์‹ค๋ˆ\t\t\t %s" + NEW_LINE; + public static final String WANNA_BUY_MORE = "๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"; +}
Java
์ €๋„ OutputView์—์„œ ์‚ฌ์šฉ๋˜๋Š” ๋ฌธ์ž์—ด์ด ์ƒ๋‹จ์— ๋„ˆ๋ฌด ๋งŽ์•„ ๋ณ„๋„์˜ ํŒŒ์ผ๋กœ ๊ด€๋ฆฌํ•ด์•ผ ํ• ์ง€ ๊ณ ๋ฏผํ–ˆ์—ˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ํ•ด๋‹น ๋ฌธ์ž์—ด๋“ค์ด OutputView์—์„œ๋งŒ ์‚ฌ์šฉ๋œ๋‹ค๊ณ  ํŒ๋‹จํ•ด ๋ณ„๋„์˜ ํด๋ž˜์Šค๋ฅผ ์ž‘์„ฑํ•˜์ง€ ์•Š์•˜๋Š”๋ฐ์š”, ์ •๋‹ต์ด ์ •ํ•ด์ ธ์žˆ๋Š” ๋ฌธ์ œ๋Š” ์•„๋‹ˆ์ง€๋งŒ ๋ณ„๋„์˜ ํด๋ž˜์Šค๋ฅผ ๋‘์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,29 @@ +package store.model.order; + +import static store.constant.ErrorMessage.WRONG_INPUT; + +import java.util.List; + +public class Orders { + private final List<Order> orders; + + public Orders(List<Order> orders) { + validate(orders); + this.orders = orders; + } + + private void validate(List<Order> orders) { + validateOrderNotDuplicated(orders); + } + + private void validateOrderNotDuplicated(List<Order> orders) { + int distinctCount = (int) orders.stream().map(Order::getProductName).distinct().count(); + if (distinctCount != orders.size()) { + throw new IllegalArgumentException(WRONG_INPUT.getMessage()); + } + } + + public List<Order> toList() { + return List.copyOf(orders); + } +}
Java
`validate` ๋ฉ”์†Œ๋“œ์—์„œ ์‹คํ–‰ํ•˜๋Š” ๊ฒƒ์ด `validateOrderNotDuplicated` ํ•˜๋‚˜์ธ๋ฐ, `validate`๋ผ๋Š” ๋ฉ”์†Œ๋“œ๋ฅผ ๋”ฐ๋กœ ๋งŒ๋“œ์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค. `Orders` ์ƒ์„ฑ์ž์—์„œ ๋ฐ”๋กœ `validateOrderNotDuplicated`๋ฅผ ํ˜ธ์ถœํ•ด๋„ ๋˜์ง€ ์•Š๋‚˜์š”?
@@ -0,0 +1,50 @@ +package store.model.product; + +import static store.constant.ErrorMessage.PRICE_NEGATIVE; +import static store.constant.ErrorMessage.QUANTITY_NEGATIVE; + +public class Product { + protected final String name; + protected final int price; + protected int quantity; + + public Product(String name, final int price, final int quantity) { + validate(price, quantity); + this.name = name; + this.price = price; + this.quantity = quantity; + } + + private void validate(final int price, final int quantity) { + validatePriceNotNegative(price); + validateQuantityNotNegative(quantity); + } + + private void validatePriceNotNegative(final int price) { + if (price < 0) { + throw new IllegalArgumentException(PRICE_NEGATIVE.getMessage()); + } + } + + private void validateQuantityNotNegative(final int quantity) { + if (quantity < 0) { + throw new IllegalArgumentException(QUANTITY_NEGATIVE.getMessage()); + } + } + + public String getName() { + return name; + } + + public int getQuantity() { + return quantity; + } + + public int getPrice() { + return price; + } + + public void sell(final int amount) { + quantity -= amount; + } +}
Java
`validate`๋ผ๋Š” ๋ฉ”์„œ๋“œ ๋ช…์ด ๋ฐ˜๋ณต๋˜์–ด์„œ ์‚ฌ์šฉ๋˜๊ณ  ์žˆ๋Š”๋ฐ, ์ €๋Š” ๊ฐœ์ธ์ ์œผ๋กœ ๋‹ค๋ฅธ ํด๋ž˜์Šค์— ์žˆ๋”๋ผ๋„ ๋™์ผํ•œ ๋ฉ”์„œ๋“œ๋ช…์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์„ ๊บผ๋ฆฌ๊ฒŒ ๋˜๋”๋ผ๊ตฌ์š”. ๋‘ ๋ฉ”์†Œ๋“œ ๋‹ค static์ด ์—†์–ด์„œ ๊ฐ์ฒด๋ช…์œผ๋กœ ๊ตฌ๋ถ„์ด ๋˜๊ฒ ์ง€๋งŒ, ๊ทธ๋ž˜๋„ `validateOrders`๋‚˜ `validateProduct`์™€ ๊ฐ™์ด ์ž‘์„ฑํ–ˆ์„ ๊ฒƒ ๊ฐ™์€๋ฐ, ์ด์— ๋Œ€ํ•œ ์˜๊ฒฌ์ด ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,44 @@ +package store.util; + +import static store.constant.ErrorMessage.INVALID_ORDER_FORMAT; +import static store.constant.ErrorMessage.WRONG_INPUT; +import static store.constant.OrderInfo.ORDER_PATTERN; +import static store.constant.OrderInfo.PRODUCT_COUNT_GROUP; +import static store.constant.OrderInfo.PRODUCT_NAME_GROUP; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.regex.Matcher; +import store.model.order.Order; + +public class Converter { + public static int toInteger(String number) { + try { + return Integer.parseInt(number); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(WRONG_INPUT.getMessage()); + } + } + + public static LocalDateTime toLocalDateTime(String localDate, String dateFormat) { + return LocalDate.parse( + localDate, + DateTimeFormatter.ofPattern(dateFormat) + ) + .atStartOfDay(); + } + + public static Order toOrder(String order) { + Matcher matcher = ORDER_PATTERN.matcher(order); + + if (!matcher.matches()) { + throw new IllegalArgumentException(INVALID_ORDER_FORMAT.getMessage()); + } + + return new Order( + matcher.group(PRODUCT_NAME_GROUP), + Converter.toInteger(matcher.group(PRODUCT_COUNT_GROUP)) + ); + } +}
Java
Integer.pasreInt์™€ ๊ฐ™์ด ์ž์ฃผ ์‚ฌ์šฉํ•˜๋Š” ๋ฉ”์†Œ๋“œ๋“ค์— ๋Œ€ํ•ด์„œ ๋งค๋ณ€ try-catch๋ฅผ ์ž‘์„ฑํ•˜๋Š” ๊ฒƒ์ด ๋ถˆํŽธํ•˜๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ, ์ด๋Ÿฐ ๋ฐฉ์‹์œผ๋กœ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ์„ ๊นจ๋‹ซ๊ณ  ๊ฐ‘๋‹ˆ๋‹ค!
@@ -0,0 +1,80 @@ +package store; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.List; +import store.io.ProductFile; +import store.io.PromotionFile; +import store.product.Product; +import store.utils.ExceptionFactory; +import store.utils.ExceptionType; +import store.utils.Transformer; +import store.utils.Validator; + +public class LoadModel { + public final static String PRODUCT_LIST_FORMAT = "name,price,quantity,promotion"; + public final static String PROMOTION_LIST_FROMAT= "name,buy,get,start_date,end_date"; + public final static String DELIMITER = "\n"; + final static String RESOURCE_PATH = "./src/main/resources/"; + final static String PRODUCT_LIST = "products.md"; + final static String PROMOTION_LIST = "promotions.md"; + public LoadModel(){ + } + + public String loadProductList(){ + String result = readFileAsString(RESOURCE_PATH + PRODUCT_LIST); + validateProductList(result); + return result; + } + + public String loadPromotionList(){ + String result = readFileAsString(RESOURCE_PATH + PROMOTION_LIST); + validatePromotionList(result); + return result; + } + + public List<String> readFile(String path){ + Validator.validateFileSize(path); + try { + return Files.readAllLines(Paths.get(path)); + } catch (IOException exception){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.READ_FILE_FAIL,exception); + throw new RuntimeException(); + } + } + + public String readFileAsString(String path){ + + List<String> contents = readFile(path); + if(contents.isEmpty()) { + ExceptionFactory.throwIllegalArgumentException(ExceptionType.EMPTY_FILE); + } + return Transformer.concatenateList(contents,DELIMITER); + } + + public static void validateProductList(String products){ + if(products.isBlank()) { + ExceptionFactory.throwIllegalArgumentException(ExceptionType.EMPTY_FILE); + } + List<String> productList = Arrays.stream(products.split(DELIMITER)).toList(); + if(!productList.getFirst().equals(PRODUCT_LIST_FORMAT)){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_FILE_FORMAT); + } + Validator.validateEachLine(productList, ProductFile.COLUMN_DELIMITER,ProductFile.values().length); + } + + public static void validatePromotionList(String promotions){ + if(promotions.isBlank()) { + ExceptionFactory.throwIllegalArgumentException(ExceptionType.EMPTY_FILE); + } + List<String> promotionList = Arrays.stream(promotions.split(DELIMITER)).toList(); + if(!promotionList.getFirst().equals(PROMOTION_LIST_FROMAT)){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_FILE_FORMAT); + } + Validator.validateEachLine(promotionList,PromotionFile.COLUMN_DELIMITER,PromotionFile.values().length); + } + + +}
Java
ํŒŒ์ผ ๋‚ด์šฉ ์ „์ฒด๋ฅผ ์ฝ์–ด์™€์„œ `\n`์œผ๋กœ splitํ•˜์‹  ๊ฒƒ์ด ์ธ์ƒ๊นŠ๋„ค์š”! ๋‹ค๋งŒ ์šด์˜์ฒด์ œ์— ๋”ฐ๋ผ ์ค„๋ฐ”๊ฟˆ ๋ฌธ์ž๊ฐ€ ๋‹ค๋ฅผ ์ˆ˜ ์žˆ์–ด์„œ, ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜๋„ ์žˆ๋‹ค๊ณ  ํ•˜๋”๋ผ๊ตฌ์š”. ๊ทธ๋ž˜์„œ ํŒŒ์ผ์— ์ ‘๊ทผํ•ด์„œ ํ•œ ์ค„์”ฉ ์ฝ์–ด์˜ค๋Š” ๋ฐฉ์‹๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,80 @@ +package store; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.List; +import store.io.ProductFile; +import store.io.PromotionFile; +import store.product.Product; +import store.utils.ExceptionFactory; +import store.utils.ExceptionType; +import store.utils.Transformer; +import store.utils.Validator; + +public class LoadModel { + public final static String PRODUCT_LIST_FORMAT = "name,price,quantity,promotion"; + public final static String PROMOTION_LIST_FROMAT= "name,buy,get,start_date,end_date"; + public final static String DELIMITER = "\n"; + final static String RESOURCE_PATH = "./src/main/resources/"; + final static String PRODUCT_LIST = "products.md"; + final static String PROMOTION_LIST = "promotions.md"; + public LoadModel(){ + } + + public String loadProductList(){ + String result = readFileAsString(RESOURCE_PATH + PRODUCT_LIST); + validateProductList(result); + return result; + } + + public String loadPromotionList(){ + String result = readFileAsString(RESOURCE_PATH + PROMOTION_LIST); + validatePromotionList(result); + return result; + } + + public List<String> readFile(String path){ + Validator.validateFileSize(path); + try { + return Files.readAllLines(Paths.get(path)); + } catch (IOException exception){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.READ_FILE_FAIL,exception); + throw new RuntimeException(); + } + } + + public String readFileAsString(String path){ + + List<String> contents = readFile(path); + if(contents.isEmpty()) { + ExceptionFactory.throwIllegalArgumentException(ExceptionType.EMPTY_FILE); + } + return Transformer.concatenateList(contents,DELIMITER); + } + + public static void validateProductList(String products){ + if(products.isBlank()) { + ExceptionFactory.throwIllegalArgumentException(ExceptionType.EMPTY_FILE); + } + List<String> productList = Arrays.stream(products.split(DELIMITER)).toList(); + if(!productList.getFirst().equals(PRODUCT_LIST_FORMAT)){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_FILE_FORMAT); + } + Validator.validateEachLine(productList, ProductFile.COLUMN_DELIMITER,ProductFile.values().length); + } + + public static void validatePromotionList(String promotions){ + if(promotions.isBlank()) { + ExceptionFactory.throwIllegalArgumentException(ExceptionType.EMPTY_FILE); + } + List<String> promotionList = Arrays.stream(promotions.split(DELIMITER)).toList(); + if(!promotionList.getFirst().equals(PROMOTION_LIST_FROMAT)){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_FILE_FORMAT); + } + Validator.validateEachLine(promotionList,PromotionFile.COLUMN_DELIMITER,PromotionFile.values().length); + } + + +}
Java
์œ ์ง€๋ณด์ˆ˜์˜ ๊ด€์ ์—์„œ ์ƒ๊ฐํ–ˆ์„ ๋•Œ, ์ €๋Š” ๊ทธ๋ƒฅ ์ฒซ ์ค„์„ skipํ•˜๋Š” ๊ฒƒ์ด ์ข‹๊ฒ ๋‹ค๊ณ  ํŒ๋‹จํ–ˆ์Šต๋‹ˆ๋‹ค! product์˜ ํ˜•์‹์€ ์–ธ์ œ๋“  ๋‹ฌ๋ผ์งˆ ์ˆ˜ ์žˆ๊ณ , ๋‹ฌ๋ผ์งˆ ๋•Œ๋งˆ๋‹ค `PRODUCT_LIST_FORMAT`๋ฅผ ์ˆ˜์ •ํ•˜๋ฉด ๋ฒˆ๊ฑฐ๋กญ๊ฒ ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๊ธฐ ๋–„๋ฌธ์ž…๋‹ˆ๋‹ค. ์—ฌ๊ธฐ์— ๋Œ€ํ•ด ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,125 @@ +package store; + +import java.util.List; +import store.product.Product; +import store.product.Receipt; +import store.utils.Transformer; + +public class StoreOutputView { + + public void welcomeConsumer(List<Product> products){ + StoreViewMessage.WELCOME.printMessage(); + for(Product product : products){ + printSellingProduct(product); + } + } + + public void printAccount(List<Receipt> receipts, int disCountPrice){ + StoreViewMessage.RECEIPT_HEAD.printMessage(); + printPurchaseProductList(receipts); + printPromotionReturnProductList(receipts); + printBill(receipts,disCountPrice); + } + + public void printSellingProduct(Product product){ + String promotionName = ""; + if(product.isPromotionExist()){ + promotionName = product.getPromotionName(); + } + + if(product.isInsufficient()){ + StoreViewMessage.printInsufficientProduct(product.getName(),product.getPrice(),promotionName); + return; + } + StoreViewMessage.printProduct(product.getName(),product.getPrice(),product.getCount(),promotionName); + } + + + public void printPurchaseProductList(List<Receipt> receipts){ + + StoreViewMessage.printReceiptProductListHead(); + for(Receipt receipt : receipts){ + StoreViewMessage.printReceiptFormat(receipt.getProductName(), Integer.toString(receipt.getActualCount()),Integer.toString(receipt.getActualPrice())); + } + + } + + public void printPromotionReturnProductList(List<Receipt> receipts){ + StoreViewMessage.RECEIPT_HEAD_PROMOTION.printMessage(); + String emtpy = ""; + List<Receipt> promotionReceipts = receipts.stream().filter((Receipt::isPromotionApplied)).toList(); + for(Receipt receipt : promotionReceipts){ + StoreViewMessage.printReceiptFormat(receipt.getProductName(),Integer.toString(receipt.getActualCount()),emtpy); + } + } + + public void printBill(List<Receipt> receipts, int disCountPrice){ + StoreViewMessage.RECEIPT_HEAD_ACCOUNT.printMessage(); + List<Integer> accounts = calculateTotalReceipt(receipts); + int totalCountColumn = 0; + int promotedPriceColumn = 1; + int totalActualPrice = 2; + + printBillMessage(accounts.get(totalCountColumn),accounts.get(promotedPriceColumn),accounts.get(totalActualPrice),disCountPrice); + } + + public void printBillMessage(int totalCount, int promotedPrice, int totalActualPrice, int disCountPrice){ + printBillMessageTotalActualPrice(totalCount,totalActualPrice); + printBillMessagePromotionDiscount(promotedPrice); + printBillMessageMembershipDiscount(disCountPrice); + printBillMessageTotalPrice(totalActualPrice - promotedPrice - disCountPrice); + } + + public void printBillMessageTotalActualPrice(int totalCount,int totalActualPrice){ + String empty = ""; + String column = "์ด๊ตฌ๋งค์•ก"; + StoreViewMessage.printReceiptFormat(column,Integer.toString(totalCount), Transformer.transformToThousandSeparated(totalActualPrice)); + } + + public void printBillMessagePromotionDiscount(int promotedPrice){ + String empty = ""; + String column = "ํ–‰์‚ฌํ• ์ธ"; + int zero = 0; + String discount = "-"; + if(promotedPrice == zero){ + discount=""; + } + discount += Transformer.transformToThousandSeparated(promotedPrice); + + StoreViewMessage.printReceiptFormat(column,empty,discount); + } + + public void printBillMessageMembershipDiscount(int disCountPrice){ + String empty = ""; + String column = "๋ฉค๋ฒ„์‹ญํ• ์ธ"; + int zero = 0; + String discount = "-"; + if(disCountPrice == zero){ + discount=""; + } + discount += Transformer.transformToThousandSeparated(disCountPrice); + + StoreViewMessage.printReceiptFormat(column,empty,discount); + } + + public void printBillMessageTotalPrice(int totalPrice){ + String empty = ""; + String column = "๋‚ด์‹ค๋ˆ"; + + StoreViewMessage.printReceiptFormat(column,empty,Transformer.transformToThousandSeparated(totalPrice)); + } + + public List<Integer> calculateTotalReceipt(List<Receipt> receipts){ + int totalCount = 0; + int promotedPrice = 0; + int totalActualPrice = 0; + for(Receipt receipt : receipts){ + totalCount += receipt.getActualCount(); + promotedPrice += receipt.getDisCountPrice(); + totalActualPrice += receipt.getActualPrice(); + } + + return List.of(totalCount,promotedPrice,totalActualPrice) ; + } + +}
Java
์ €๋Š” `model`์˜ ๋ฐ์ดํ„ฐ๋ฅผ ์ถœ๋ ฅํ•ด์ฃผ๋ ค ํ•  ๋•Œ์—๋Š” `dto`๋ฅผ ์‚ฌ์šฉํ–ˆ๋Š”๋ฐ, @armcortex3445 ๋‹˜๊ป˜์„œ ์‚ฌ์šฉํ•˜์‹  ๋ฐฉ๋ฒ•์ฒ˜๋Ÿผ ๊ฐ์ฒด๋ฅผ ๋ณต์‚ฌํ•ด์„œ `view`๋กœ ๋„˜๊ฒจ์ค˜๋„ ๋˜๊ฒ ๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“œ๋„ค์š”! ํ˜น์‹œ @armcortex3445 ๋‹˜์€ ์ถœ๋ ฅ์„ ์œ„ํ•ด `dto`๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์— ๋Œ€ํ•ด ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”? ์ €๋Š” `dto`๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ถœ๋ ฅ์— ํ•„์š”ํ•œ ๊ฐ’๋งŒ ๋”ฐ๋กœ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ๊ณ , ์ถœ๋ ฅ๋ฌธ์„ ๋งŒ๋“œ๋Š” ๋กœ์ง์„ ๊ทธ ์•ˆ์— ๋งŒ๋“ค ์ˆ˜๋„ ์žˆ์–ด์„œ ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,196 @@ +package store; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import camp.nextstep.edu.missionutils.Console; +import store.product.PurchaseRequest; +import store.product.promotion.PromotionResult; +import store.product.promotion.PromotionState; +import store.utils.ExceptionFactory; +import store.utils.ExceptionType; +import store.utils.Transformer; +import store.utils.Validator; + +public class StoreInputView { + static final Pattern PURCHASE_PATTERN = Pattern.compile(StoreViewMessage.PURCHASE_PATTERN); + + public List<PurchaseRequest> readPurchaseProduct(){ + StoreViewMessage.PURCHASE_GUIDE.printMessage(); + String purchaseList = Console.readLine(); + try { + return createPurchaseRequests(purchaseList); + }catch (IllegalArgumentException exception){ + StoreViewMessage.ERROR_INVALID_FORMAT.printMessage(); + return readPurchaseProduct(); + } + } + + public List<PurchaseRequest> retryReadPurchaseProduct(List<StoreViewMessage> errorMessages){ + for(StoreViewMessage message : errorMessages){ + message.printMessage(); + } + return readPurchaseProduct(); + } + + public List<PurchaseRequest> readAnswerPurchaseChange(List<PromotionResult> promotionResults){ + List<PurchaseRequest> newPurchaseRequest = new ArrayList<>(); + for(PromotionResult promotionResult : promotionResults){ + newPurchaseRequest.add(handlePromotionResults(promotionResult)); + } + + return newPurchaseRequest; + } + + public PurchaseRequest handlePromotionResults(PromotionResult promotionResult){ + if(promotionResult.getState().equals(PromotionState.OMISSION)) { + return readPromotionEnableProduct(promotionResult); + } + if(promotionResult.getState().equals(PromotionState.INSUFFICIENT)){ + return readPromotionInsufficient(promotionResult); + } + return new PurchaseRequest(promotionResult.getProductName(),promotionResult.getTotalItemCount(),promotionResult.getState()); + } + + public PurchaseRequest readPromotionInsufficient(PromotionResult promotionResult){ + PurchaseRequest newRequest = null; + String answer =readAnswerPromotionInSufficient(promotionResult); + + if(answer.equals(StoreViewMessage.ANSWER_NO)){ + newRequest = new PurchaseRequest(promotionResult.getProductName(),promotionResult.getTotalItemCount(),promotionResult.getState()); + newRequest.decreaseCount(promotionResult.getNonPromotedCount()); + return newRequest; + } + + return new PurchaseRequest(promotionResult.getProductName(),promotionResult.getTotalItemCount(),PromotionState.APPLIED); + } + + public boolean readAnswerContinuePurchase(){ + StoreViewMessage.RETRY_PURCHASE.printMessage(); + String answer = Console.readLine(); + try{ + validateAnswer(answer); + return answer.equals(StoreViewMessage.ANSWER_YES); + }catch (IllegalArgumentException exception){ + StoreViewMessage.ERROR_INVALID_FORMAT.printMessage(); + return readAnswerContinuePurchase(); + } + } + + public boolean readAnswerDiscountApply(){ + StoreViewMessage.MEMBERSHIP_GUIDE.printMessage(); + String answer = Console.readLine(); + try{ + validateAnswer(answer); + return answer.equals(StoreViewMessage.ANSWER_YES); + }catch (IllegalArgumentException exception){ + StoreViewMessage.ERROR_INVALID_FORMAT.printMessage(); + return readAnswerDiscountApply(); + } + } + + + public PurchaseRequest readPromotionEnableProduct(PromotionResult promotionResult){ + PurchaseRequest newRequest = new PurchaseRequest(promotionResult.getProductName(),promotionResult.getTotalItemCount(),PromotionState.APPLIED); + for(int tryCount = 0; tryCount < promotionResult.getOmittedItemCount(); tryCount++){ + String answer = readAnswerPromotionEnable(promotionResult); + newRequest.tryToIncrease(answer.equals(StoreViewMessage.ANSWER_YES)); + } + + return newRequest; + } + + public String readAnswerPromotionInSufficient(PromotionResult promotionResult){ + StoreViewMessage.printPromotionWarning(promotionResult.getProductName(),promotionResult.getNonPromotedCount()); + String answer = Console.readLine(); + try{ + validateAnswer(answer); + return answer; + }catch (IllegalArgumentException exception){ + StoreViewMessage.ERROR_INVALID_FORMAT.printMessage(); + return readAnswerPromotionInSufficient(promotionResult); + } + } + + public String readAnswerPromotionEnable(PromotionResult promotionResult){ + StoreViewMessage.printPromotionReturnAvailable(promotionResult.getProductName()); + String answer = Console.readLine(); + try{ + validateAnswer(answer); + return answer; + }catch (IllegalArgumentException exception){ + StoreViewMessage.ERROR_INVALID_FORMAT.printMessage(); + return readAnswerPromotionEnable(promotionResult); + } + } + + public List<PurchaseRequest> createPurchaseRequests(String purchaseList){ + validatePurchaseList(purchaseList); + List<String> purchases = List.of(purchaseList.split(StoreViewMessage.PURCHASE_LIST_DELIMITER)); + return purchases.stream().map((purchase)->{ + List<String> elements = extractElementsFromPurchase(purchase); + int nameIdx = 0; + int countIdx = 1; + return new PurchaseRequest(elements.get(nameIdx), Transformer.parsePositiveInt(elements.get(countIdx)),PromotionState.NONE); + }).toList(); + } + + + static public void validatePurchaseList(String purchaseList){ + Validator.validateBlankString(purchaseList); + List<String> purchases = List.of(purchaseList.split(StoreViewMessage.PURCHASE_LIST_DELIMITER)); + + for(String purchase : purchases){ + validatePurchase(purchase); + } + + } + + static public void validatePurchase(String purchase){ + + if(!purchase.matches(StoreViewMessage.PURCHASE_PATTERN)){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_INPUT_STRING_FORMAT); + } + try { + validatePurchaseElement(purchase); + }catch (Exception e){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_INPUT_STRING_FORMAT); + } + + } + + static public void validatePurchaseElement(String purchase){ + Matcher matcher = PURCHASE_PATTERN.matcher(purchase); + if(matcher.matches()) { + int productNameGroup = 1; + int countGroup = 2; + Validator.validateBlankString(matcher.group(productNameGroup)); + Validator.validatePositiveNumericString(matcher.group(countGroup)); + return; + } + ExceptionFactory.throwIllegalStateException(ExceptionType.INVALID_INPUT_STRING_FORMAT); + + + } + + static public List<String> extractElementsFromPurchase(String purchase){ + Matcher matcher = PURCHASE_PATTERN.matcher(purchase); + if(matcher.matches()){ + int nameGroup = 1; + int countGroup = 2; + return List.of(matcher.group(nameGroup), matcher.group(countGroup)); + } + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_INPUT_STRING_FORMAT); + throw new RuntimeException(); + } + + static public void validateAnswer(String answer){ + Validator.validateBlankString(answer); + if(!(answer.equals(StoreViewMessage.ANSWER_NO) + || answer.equals(StoreViewMessage.ANSWER_YES))) { + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_INPUT_STRING_FORMAT); + } + } + +}
Java
ํ˜„์žฌ `InputView`์—์„œ ๋„ˆ๋ฌด ๋งŽ์€ ์ฑ…์ž„์„ ๋‹ด๋‹นํ•˜๊ณ  ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค! ์‚ฌ์šฉ์ž์˜ ์ž…๋ ฅ์„ ๋ฐ›์•„์˜ค๋Š” ๊ฒƒ์— ์ง‘์ค‘ํ•˜๊ธฐ ๋ณด๋‹ค๋Š”, ์ž…๋ ฅ์„ ๋ณ€ํ™˜ํ•˜๊ณ  ๊ฒ€์ฆํ•˜๋Š” ๊ฒƒ์— ๋” ์ง‘์ค‘ํ•˜๊ณ  ์žˆ๋‹ค๋Š” ๋А๋‚Œ์ด ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค! ์ž…๋ ฅ์„ `Product`๋กœ ๋ณ€ํ™˜ ๋ฐ ๊ฒ€์ฆํ•˜๋Š” ๊ธฐ๋Šฅ์„ ํด๋ž˜์Šค๋กœ ๋ถ„๋ฆฌํ•ด๋ณด๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”? ์ €๋Š” `InputProcessor`๋ผ๋Š” ํด๋ž˜์Šค์— ์ž…๋ ฅ์„ ๋‹ค์‹œ ๋ฐ›์•„์˜ค๋Š” ๊ธฐ๋Šฅ์„ ๋ถ„๋ฆฌํ–ˆ๊ณ ,` InputFormatter`์— ์ž…๋ ฅ์„ ๊ฒ€์ฆํ•˜๊ณ  parseํ•˜๋Š” ๊ธฐ๋Šฅ์„ ๋ถ„๋ฆฌํ–ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,371 @@ +package store; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import store.io.ProductFile; +import store.io.PromotionFile; +import store.product.Product; +import store.product.PurchaseRequest; +import store.product.Receipt; +import store.product.promotion.Promotion; +import store.product.promotion.PromotionResult; +import store.product.promotion.PromotionState; +import store.utils.ExceptionFactory; +import store.utils.ExceptionType; +import store.utils.Transformer; + +public class StoreModel { + static private final Product NOT_FOUND = null; + private final List<Product> productRepository; + private final HashMap<String,Promotion> promotionHashMap; + final static String NAME_REGULAR_EXPRESSION = "^[a-zA-Z๊ฐ€-ํžฃ0-9]+$"; + final static Pattern NAME_PATTERN = Pattern.compile(StoreModel.NAME_REGULAR_EXPRESSION); + + StoreModel(){ + this.productRepository = new ArrayList<>(); + this.promotionHashMap = new HashMap<>(); + } + + public void initStore(List<Product> products, List<Promotion> promotions){ + addProducts(products); + putPromotion(promotions); + applyPromotions(); + } + + private void addProducts(List<Product> products){ + for(Product origin : products){ + this.productRepository.add(origin.clone()); + } + checkInitProduct(this.productRepository); + } + + public void checkInitProduct(List<Product> products){ + for(Product product : products){ + validateSameProductsHaveSamePrice(product); + } + } + + public void validateSameProductsHaveSamePrice(Product product){ + List<Product> finds = findProduct(product.getName()); + int price = 0; + for(Product find : finds){ + price += find.getPrice(); + } + int averagePrice = price / finds.size(); + if(finds.getFirst().getPrice() != averagePrice){ + System.out.println("[Error] ๋™์ผ ์ด๋ฆ„์˜ ์ƒํ’ˆ์€ ๊ฐ€๊ฒฉ์ด ๊ฐ™์•„์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์ž˜๋ชป๋œ ์ƒํ’ˆ :" + product.getName()); + ExceptionFactory.throwIllegalStateException(ExceptionType.INVALID_FILE_FORMAT); + } + } + + private void putPromotion(List<Promotion> promotions){ + /*TODO + - ํ”„๋กœ๋ชจ์…˜ ์ด๋ฆ„ ์ค‘๋ณต์ด ์—†๋„๋ก ํ•ด์•ผํ•จ. + - ๋‚ ์งœ๊ฐ€ ๋‹ค๋ฅด๋”๋ผ๋„, ์ด๋ฆ„ ์ค‘๋ณต์ด ์—†๋„๋ก ํ•ด์•ผํ•จ. + - ํ”„๋กœ๋ชจ์…˜ ์ค‘๋ณต์ด ์žˆ๋Š” ๊ฒฝ์šฐ, promotions.md ํŒŒ์ผ์ด ๋ฌธ์ œ์ด๋ฏ€๋กœ ํ•ด๋‹น ํŒŒ์ผ์—์„œ ํ™•์ธ ํ•„์š”. + * */ + for(Promotion promotion : promotions){ + this.promotionHashMap.put(promotion.getName(),promotion.clone()); + } + } + + private void applyPromotions(){ + for(Product product : this.productRepository){ + product.setPromotion(this.promotionHashMap.get(product.getPromotionName())); + } + } + + public List<Product> getProducts(){ + List<Product> copied = new ArrayList<>(); + for(Product origin : this.productRepository){ + copied.add(origin.clone()); + } + + return copied; + } + + /*TODO + - ์ ‘๊ทผ์ง€์‹œ์ž, static ํ‚ค์›Œ๋“œ ๊ธฐ์ค€์œผ๋กœ ๋ฉ”์†Œ๋“œ ์ •๋ ฌํ•˜๊ธฐ + * */ + public Product findOneProduct(String name, boolean isPromoted){ + return this.findOneOriginProduct(name,isPromoted).clone(); + } + + public List<Product> findProduct(String name){ + return this.findProductOrigin(name).stream() + .map(Product::clone) + .toList(); + } + + public Product findOneOriginProduct(String name, boolean isPromoted){ + if(isPromoted){ + return findProductPromoted(name); + } + return findProductNonPromoted(name); + } + + public List<Product> findProductOrigin(String name){ + return this.productRepository.stream() + .filter((product)->product.getName().equals(name)) + .collect(Collectors.toList()); + } + + private Product findProductPromoted(String name){ + List<Product> finds = findProductOrigin(name).stream() + .filter((product -> product.getPromotionName()!=null)) + .toList(); + validateFindList(finds); + if(finds.isEmpty()){ + return NOT_FOUND; + } + return finds.getFirst(); + } + + private Product findProductNonPromoted(String name){ + List<Product> finds = findProductOrigin(name).stream() + .filter(product -> product.getPromotionName() == Product.NO_PROMOTION) + .toList(); + validateFindList(finds); + if(finds.isEmpty()){ + return NOT_FOUND; + } + return finds.getFirst(); + } + + private void validateFindList(List<?> finds){ + int limit = 1; + if(finds.size() > limit){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + } + + /*TODO + * - promotion๊ณผ product ์ƒ์„ฑ ๊ด€๋ จ static ํ•จ์ˆ˜๋ฅผ ๋‹ค๋ฅธ ํด๋ž˜์Šค์— ์ฑ…์ž„ ๋งก๊ธธ ๊ฒƒ์œผ ๊ณ ๋ คํ•˜๊ธฐ + * - promotion๊ณผ product ์ƒ์„ฑ์‹œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ ๊ณ ๋ ค + * - ์ž˜๋ชป๋œ ํƒ€์ž… ์ž…๋ ฅ + * - ์ž˜๋ชป๋œ ํ˜•์‹ ์ž…๋ ฅ + * */ + + static public List<String> parseString(String string){ + if (string == null || string.isBlank()) { + throw new IllegalArgumentException("List is empty"); + } + final String delimiter = ","; + String[] parsed = string.split(delimiter); + + return List.of(parsed); + } + + static public Product createProduct(String rawProduct){ + List<String> parsedRawProduct = StoreModel.parseString(rawProduct); + String name = parsedRawProduct.get(ProductFile.NAME.getColumnIdx()); + String price = parsedRawProduct.get(ProductFile.PRICE.getColumnIdx()); + String quantity = parsedRawProduct.get(ProductFile.QUANTITY.getColumnIdx()); + String promotion = parsedRawProduct.get(ProductFile.PROMOTION.getColumnIdx()); + validateNameFormat(name); + if(promotion.equals("null")){ + promotion = null; + } + return new Product(name, Transformer.parsePositiveInt(price),Transformer.parseNonNegativeNumber(quantity),promotion); + } + + static public List<Product> createProducts(String rawProductList){ + List<Product> products = new ArrayList<>(); + String[] rawProducts = rawProductList.split("\n"); + + int idx = 1; + + for( ; idx < rawProducts.length; idx++){ + String rawProduct = rawProducts[idx]; + products.add(StoreModel.createProduct(rawProduct)); + } + return products; + } + static public void validateNameFormat(String name){ + Matcher matcher = NAME_PATTERN.matcher(name); + if(!matcher.matches()){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_NAME_FORMAT); + } + } + + static public Promotion createPromotion(String rawPromotion){ + List<String> parsedRawPromotion = StoreModel.parseString(rawPromotion); + String name = parsedRawPromotion.get(PromotionFile.NAME.getColumnIdx()); + String buyCount = parsedRawPromotion.get(PromotionFile.BUY.getColumnIdx()); + String returnCount = parsedRawPromotion.get(PromotionFile.GET.getColumnIdx()); + String startDate = parsedRawPromotion.get(PromotionFile.START_DATE.getColumnIdx()); + String endDate = parsedRawPromotion.get(PromotionFile.END_DATE.getColumnIdx()); + Promotion.validateReturnCount(returnCount); + return new Promotion(name, Transformer.parseStartDate(startDate,PromotionFile.DATE_TIME_FORMATTER),Transformer.parseEndDate(endDate,PromotionFile.DATE_TIME_FORMATTER),Transformer.parsePositiveInt(buyCount)); + } + + static public List<Promotion> createPromotions(String rawPromotionList){ + List<Promotion> promotions = new ArrayList<>(); + String[] rawPromotions = rawPromotionList.split("\n"); + + int idx = 1; + + for( ; idx < rawPromotions.length; idx++){ + String rawPromotion = rawPromotions[idx]; + promotions.add(StoreModel.createPromotion(rawPromotion)); + } + return promotions; + } + + public List<StoreViewMessage> checkPurchaseRequests(List<PurchaseRequest> requests) { + List<StoreViewMessage> messageBox = new ArrayList<>(); + + for(PurchaseRequest request : requests){ + checkPurchaseRequest(request,messageBox); + } + + return messageBox; + } + + public void checkPurchaseRequest(PurchaseRequest request, List<StoreViewMessage> messageBox){ + checkPurchaseProductExist(request,messageBox); + checkPurchaseProductCount(request,messageBox); + + } + + public void checkPurchaseProductExist(PurchaseRequest request, List<StoreViewMessage> messageBox){ + List<Product> finds = findProduct(request.getProductName()); + if(finds.isEmpty()){ + messageBox.add(StoreViewMessage.ERROR_NOT_EXIST_PRODUCT); + } + } + + public void checkPurchaseProductCount(PurchaseRequest request, List<StoreViewMessage> messageBox){ + List<Product> finds = findProduct(request.getProductName()); + int zero = 0; + int totalCount = finds.stream().map(Product::getCount).reduce(zero,Integer::sum); + if(totalCount == zero){ + messageBox.add(StoreViewMessage.ERROR_NO_COUNT_PRODUCT); + } + if(totalCount != zero && totalCount < request.getCountPurchased()){ + messageBox.add(StoreViewMessage.ERROR_OVERFLOW_PURCHASE); + } + } + + public List<PromotionResult> checkPromotionAvailable(List<PurchaseRequest> purchaseRequests){ + List<PromotionResult> promotionResults = new ArrayList<>(); + for(PurchaseRequest request : purchaseRequests){ + promotionResults.addAll(checkPromotionBoth(request.getProductName(),request.getCountPurchased())); + } + + return promotionResults; + } + + public List<PromotionResult> checkPromotionBoth(String productName , int buyCount){ + PromotionResult resultPromotion = checkProductPromotionAvailable(productName,buyCount); + PromotionResult resultNonPromotion = null; + + Product product = findProductNonPromoted(productName); + if(findProductPromoted(productName) == NOT_FOUND){ + resultNonPromotion = PromotionResult.createNoPromotion(productName,buyCount); + return List.of(resultNonPromotion); + } + + if(resultPromotion.getState()==PromotionState.INSUFFICIENT + && resultPromotion.getTotalItemCount() < buyCount){ + int remainCountToBuy = buyCount - resultPromotion.getTotalItemCount(); + resultNonPromotion = PromotionResult.createNoPromotion(productName,remainCountToBuy); + return List.of(resultPromotion, resultNonPromotion); + } + + return List.of(resultPromotion); + } + + public PromotionResult checkProductPromotionAvailable(String productName, int buyCount){ + Product product = findProductPromoted(productName); + if(findProductPromoted(productName) == NOT_FOUND){ + return PromotionResult.createNoPromotion(productName,buyCount); + } + if(product.isEnoughToBuy(buyCount)){ + return product.estimatePromotionResult(buyCount, DateTimes.now()); + } + + int maxCountToBuyPromotion = product.calculateMaxCountToBuy(buyCount); + PromotionResult promotionResult = product.estimatePromotionResult(maxCountToBuyPromotion,DateTimes.now()); + return promotionResult.transitState(PromotionState.INSUFFICIENT); + + } + + public List<Receipt> buyProducts(List<PurchaseRequest> purchaseRequests){ + List<Receipt> receipts = new ArrayList<>(); + for(PurchaseRequest request : purchaseRequests){ + receipts.add(buyProduct(request)); + } + return receipts; + } + + public Receipt buyProduct(PurchaseRequest request){ + + if(request.getPromotionState() == PromotionState.NO_PROMOTION){ + return tryBuyProductNonPromoted(request); + } + + Receipt resultPromoted = tryBuyProductPromoted(request); + Receipt resultNonPromoted = tryBuyProductNonPromoted(request); + + return combineReceipt(resultPromoted,resultNonPromoted); + } + + public int calculateDiscount(List<Receipt> receipts){ + /*TODO + * - ํ•ฉ๊ณ„์‚ฐ ๋„์ค‘ ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ ์ ๊ฒ€ ํ•„์š”*/ + final int maxDisCount = 8000; + final double disCountRate = 0.3; + int totalNonPromotedPrice = 0; + for(Receipt receipt : receipts){ + totalNonPromotedPrice += receipt.getNonPromotedPrice(); + } + int disCountPrice = (int)Math.round(disCountRate * totalNonPromotedPrice); + return Math.min(maxDisCount, disCountPrice); + } + + private Receipt combineReceipt(Receipt promoted, Receipt nonPromoted) { + if(!promoted.getProductName().equals(nonPromoted.getProductName())){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + return promoted.combine(nonPromoted); + } + + private Receipt tryBuyProductPromoted(PurchaseRequest request){ + boolean isPromoted = true; + Product product = this.findOneOriginProduct(request.getProductName(),isPromoted); + if(product == NOT_FOUND){ + return Receipt.createEmptyReceipt(request.getProductName()); + } + if(product.getCount() < request.getCountPurchased()){ + int buyCount = product.getCount(); + return buyProduct(product,buyCount,request); + } + return buyProduct(product,request.getCountPurchased(),request); + } + + + private Receipt tryBuyProductNonPromoted(PurchaseRequest request){ + boolean isPromoted = false; + Product product = this.findOneOriginProduct(request.getProductName(),isPromoted); + if(product == NOT_FOUND){ + return Receipt.createEmptyReceipt(request.getProductName()); + } + if(product.getCount() < request.getCountPurchased()){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + return buyProduct(product,request.getCountPurchased(),request); + } + + private Receipt buyProduct(Product product, int buyCount, PurchaseRequest request){ + request.decreaseCount(buyCount); + return product.buy(buyCount); + } + +}
Java
`null`๋„ ์ƒ์ˆ˜๋กœ ์ฒ˜๋ฆฌํ•˜์‹  ๊ฒƒ์ด ์ธ์ƒ๊นŠ๋„ค์š”! ์ €๋Š” `null` ์ž์ฒด๋งŒ์œผ๋กœ๋„ ์ถฉ๋ถ„ํžˆ ์˜๋ฏธ๋ฅผ ๋“œ๋Ÿฌ๋‚ธ๋‹ค๊ณ  ์ƒ๊ฐํ•˜์—ฌ ์ƒ์ˆ˜ํ™”ํ•˜์ง€ ์•Š์•˜๋Š”๋ฐ, @armcortex3445 ๋‹˜์˜ ์ƒ์ˆ˜ํ™” ๊ธฐ์ค€์ด ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,371 @@ +package store; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import store.io.ProductFile; +import store.io.PromotionFile; +import store.product.Product; +import store.product.PurchaseRequest; +import store.product.Receipt; +import store.product.promotion.Promotion; +import store.product.promotion.PromotionResult; +import store.product.promotion.PromotionState; +import store.utils.ExceptionFactory; +import store.utils.ExceptionType; +import store.utils.Transformer; + +public class StoreModel { + static private final Product NOT_FOUND = null; + private final List<Product> productRepository; + private final HashMap<String,Promotion> promotionHashMap; + final static String NAME_REGULAR_EXPRESSION = "^[a-zA-Z๊ฐ€-ํžฃ0-9]+$"; + final static Pattern NAME_PATTERN = Pattern.compile(StoreModel.NAME_REGULAR_EXPRESSION); + + StoreModel(){ + this.productRepository = new ArrayList<>(); + this.promotionHashMap = new HashMap<>(); + } + + public void initStore(List<Product> products, List<Promotion> promotions){ + addProducts(products); + putPromotion(promotions); + applyPromotions(); + } + + private void addProducts(List<Product> products){ + for(Product origin : products){ + this.productRepository.add(origin.clone()); + } + checkInitProduct(this.productRepository); + } + + public void checkInitProduct(List<Product> products){ + for(Product product : products){ + validateSameProductsHaveSamePrice(product); + } + } + + public void validateSameProductsHaveSamePrice(Product product){ + List<Product> finds = findProduct(product.getName()); + int price = 0; + for(Product find : finds){ + price += find.getPrice(); + } + int averagePrice = price / finds.size(); + if(finds.getFirst().getPrice() != averagePrice){ + System.out.println("[Error] ๋™์ผ ์ด๋ฆ„์˜ ์ƒํ’ˆ์€ ๊ฐ€๊ฒฉ์ด ๊ฐ™์•„์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์ž˜๋ชป๋œ ์ƒํ’ˆ :" + product.getName()); + ExceptionFactory.throwIllegalStateException(ExceptionType.INVALID_FILE_FORMAT); + } + } + + private void putPromotion(List<Promotion> promotions){ + /*TODO + - ํ”„๋กœ๋ชจ์…˜ ์ด๋ฆ„ ์ค‘๋ณต์ด ์—†๋„๋ก ํ•ด์•ผํ•จ. + - ๋‚ ์งœ๊ฐ€ ๋‹ค๋ฅด๋”๋ผ๋„, ์ด๋ฆ„ ์ค‘๋ณต์ด ์—†๋„๋ก ํ•ด์•ผํ•จ. + - ํ”„๋กœ๋ชจ์…˜ ์ค‘๋ณต์ด ์žˆ๋Š” ๊ฒฝ์šฐ, promotions.md ํŒŒ์ผ์ด ๋ฌธ์ œ์ด๋ฏ€๋กœ ํ•ด๋‹น ํŒŒ์ผ์—์„œ ํ™•์ธ ํ•„์š”. + * */ + for(Promotion promotion : promotions){ + this.promotionHashMap.put(promotion.getName(),promotion.clone()); + } + } + + private void applyPromotions(){ + for(Product product : this.productRepository){ + product.setPromotion(this.promotionHashMap.get(product.getPromotionName())); + } + } + + public List<Product> getProducts(){ + List<Product> copied = new ArrayList<>(); + for(Product origin : this.productRepository){ + copied.add(origin.clone()); + } + + return copied; + } + + /*TODO + - ์ ‘๊ทผ์ง€์‹œ์ž, static ํ‚ค์›Œ๋“œ ๊ธฐ์ค€์œผ๋กœ ๋ฉ”์†Œ๋“œ ์ •๋ ฌํ•˜๊ธฐ + * */ + public Product findOneProduct(String name, boolean isPromoted){ + return this.findOneOriginProduct(name,isPromoted).clone(); + } + + public List<Product> findProduct(String name){ + return this.findProductOrigin(name).stream() + .map(Product::clone) + .toList(); + } + + public Product findOneOriginProduct(String name, boolean isPromoted){ + if(isPromoted){ + return findProductPromoted(name); + } + return findProductNonPromoted(name); + } + + public List<Product> findProductOrigin(String name){ + return this.productRepository.stream() + .filter((product)->product.getName().equals(name)) + .collect(Collectors.toList()); + } + + private Product findProductPromoted(String name){ + List<Product> finds = findProductOrigin(name).stream() + .filter((product -> product.getPromotionName()!=null)) + .toList(); + validateFindList(finds); + if(finds.isEmpty()){ + return NOT_FOUND; + } + return finds.getFirst(); + } + + private Product findProductNonPromoted(String name){ + List<Product> finds = findProductOrigin(name).stream() + .filter(product -> product.getPromotionName() == Product.NO_PROMOTION) + .toList(); + validateFindList(finds); + if(finds.isEmpty()){ + return NOT_FOUND; + } + return finds.getFirst(); + } + + private void validateFindList(List<?> finds){ + int limit = 1; + if(finds.size() > limit){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + } + + /*TODO + * - promotion๊ณผ product ์ƒ์„ฑ ๊ด€๋ จ static ํ•จ์ˆ˜๋ฅผ ๋‹ค๋ฅธ ํด๋ž˜์Šค์— ์ฑ…์ž„ ๋งก๊ธธ ๊ฒƒ์œผ ๊ณ ๋ คํ•˜๊ธฐ + * - promotion๊ณผ product ์ƒ์„ฑ์‹œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ ๊ณ ๋ ค + * - ์ž˜๋ชป๋œ ํƒ€์ž… ์ž…๋ ฅ + * - ์ž˜๋ชป๋œ ํ˜•์‹ ์ž…๋ ฅ + * */ + + static public List<String> parseString(String string){ + if (string == null || string.isBlank()) { + throw new IllegalArgumentException("List is empty"); + } + final String delimiter = ","; + String[] parsed = string.split(delimiter); + + return List.of(parsed); + } + + static public Product createProduct(String rawProduct){ + List<String> parsedRawProduct = StoreModel.parseString(rawProduct); + String name = parsedRawProduct.get(ProductFile.NAME.getColumnIdx()); + String price = parsedRawProduct.get(ProductFile.PRICE.getColumnIdx()); + String quantity = parsedRawProduct.get(ProductFile.QUANTITY.getColumnIdx()); + String promotion = parsedRawProduct.get(ProductFile.PROMOTION.getColumnIdx()); + validateNameFormat(name); + if(promotion.equals("null")){ + promotion = null; + } + return new Product(name, Transformer.parsePositiveInt(price),Transformer.parseNonNegativeNumber(quantity),promotion); + } + + static public List<Product> createProducts(String rawProductList){ + List<Product> products = new ArrayList<>(); + String[] rawProducts = rawProductList.split("\n"); + + int idx = 1; + + for( ; idx < rawProducts.length; idx++){ + String rawProduct = rawProducts[idx]; + products.add(StoreModel.createProduct(rawProduct)); + } + return products; + } + static public void validateNameFormat(String name){ + Matcher matcher = NAME_PATTERN.matcher(name); + if(!matcher.matches()){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_NAME_FORMAT); + } + } + + static public Promotion createPromotion(String rawPromotion){ + List<String> parsedRawPromotion = StoreModel.parseString(rawPromotion); + String name = parsedRawPromotion.get(PromotionFile.NAME.getColumnIdx()); + String buyCount = parsedRawPromotion.get(PromotionFile.BUY.getColumnIdx()); + String returnCount = parsedRawPromotion.get(PromotionFile.GET.getColumnIdx()); + String startDate = parsedRawPromotion.get(PromotionFile.START_DATE.getColumnIdx()); + String endDate = parsedRawPromotion.get(PromotionFile.END_DATE.getColumnIdx()); + Promotion.validateReturnCount(returnCount); + return new Promotion(name, Transformer.parseStartDate(startDate,PromotionFile.DATE_TIME_FORMATTER),Transformer.parseEndDate(endDate,PromotionFile.DATE_TIME_FORMATTER),Transformer.parsePositiveInt(buyCount)); + } + + static public List<Promotion> createPromotions(String rawPromotionList){ + List<Promotion> promotions = new ArrayList<>(); + String[] rawPromotions = rawPromotionList.split("\n"); + + int idx = 1; + + for( ; idx < rawPromotions.length; idx++){ + String rawPromotion = rawPromotions[idx]; + promotions.add(StoreModel.createPromotion(rawPromotion)); + } + return promotions; + } + + public List<StoreViewMessage> checkPurchaseRequests(List<PurchaseRequest> requests) { + List<StoreViewMessage> messageBox = new ArrayList<>(); + + for(PurchaseRequest request : requests){ + checkPurchaseRequest(request,messageBox); + } + + return messageBox; + } + + public void checkPurchaseRequest(PurchaseRequest request, List<StoreViewMessage> messageBox){ + checkPurchaseProductExist(request,messageBox); + checkPurchaseProductCount(request,messageBox); + + } + + public void checkPurchaseProductExist(PurchaseRequest request, List<StoreViewMessage> messageBox){ + List<Product> finds = findProduct(request.getProductName()); + if(finds.isEmpty()){ + messageBox.add(StoreViewMessage.ERROR_NOT_EXIST_PRODUCT); + } + } + + public void checkPurchaseProductCount(PurchaseRequest request, List<StoreViewMessage> messageBox){ + List<Product> finds = findProduct(request.getProductName()); + int zero = 0; + int totalCount = finds.stream().map(Product::getCount).reduce(zero,Integer::sum); + if(totalCount == zero){ + messageBox.add(StoreViewMessage.ERROR_NO_COUNT_PRODUCT); + } + if(totalCount != zero && totalCount < request.getCountPurchased()){ + messageBox.add(StoreViewMessage.ERROR_OVERFLOW_PURCHASE); + } + } + + public List<PromotionResult> checkPromotionAvailable(List<PurchaseRequest> purchaseRequests){ + List<PromotionResult> promotionResults = new ArrayList<>(); + for(PurchaseRequest request : purchaseRequests){ + promotionResults.addAll(checkPromotionBoth(request.getProductName(),request.getCountPurchased())); + } + + return promotionResults; + } + + public List<PromotionResult> checkPromotionBoth(String productName , int buyCount){ + PromotionResult resultPromotion = checkProductPromotionAvailable(productName,buyCount); + PromotionResult resultNonPromotion = null; + + Product product = findProductNonPromoted(productName); + if(findProductPromoted(productName) == NOT_FOUND){ + resultNonPromotion = PromotionResult.createNoPromotion(productName,buyCount); + return List.of(resultNonPromotion); + } + + if(resultPromotion.getState()==PromotionState.INSUFFICIENT + && resultPromotion.getTotalItemCount() < buyCount){ + int remainCountToBuy = buyCount - resultPromotion.getTotalItemCount(); + resultNonPromotion = PromotionResult.createNoPromotion(productName,remainCountToBuy); + return List.of(resultPromotion, resultNonPromotion); + } + + return List.of(resultPromotion); + } + + public PromotionResult checkProductPromotionAvailable(String productName, int buyCount){ + Product product = findProductPromoted(productName); + if(findProductPromoted(productName) == NOT_FOUND){ + return PromotionResult.createNoPromotion(productName,buyCount); + } + if(product.isEnoughToBuy(buyCount)){ + return product.estimatePromotionResult(buyCount, DateTimes.now()); + } + + int maxCountToBuyPromotion = product.calculateMaxCountToBuy(buyCount); + PromotionResult promotionResult = product.estimatePromotionResult(maxCountToBuyPromotion,DateTimes.now()); + return promotionResult.transitState(PromotionState.INSUFFICIENT); + + } + + public List<Receipt> buyProducts(List<PurchaseRequest> purchaseRequests){ + List<Receipt> receipts = new ArrayList<>(); + for(PurchaseRequest request : purchaseRequests){ + receipts.add(buyProduct(request)); + } + return receipts; + } + + public Receipt buyProduct(PurchaseRequest request){ + + if(request.getPromotionState() == PromotionState.NO_PROMOTION){ + return tryBuyProductNonPromoted(request); + } + + Receipt resultPromoted = tryBuyProductPromoted(request); + Receipt resultNonPromoted = tryBuyProductNonPromoted(request); + + return combineReceipt(resultPromoted,resultNonPromoted); + } + + public int calculateDiscount(List<Receipt> receipts){ + /*TODO + * - ํ•ฉ๊ณ„์‚ฐ ๋„์ค‘ ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ ์ ๊ฒ€ ํ•„์š”*/ + final int maxDisCount = 8000; + final double disCountRate = 0.3; + int totalNonPromotedPrice = 0; + for(Receipt receipt : receipts){ + totalNonPromotedPrice += receipt.getNonPromotedPrice(); + } + int disCountPrice = (int)Math.round(disCountRate * totalNonPromotedPrice); + return Math.min(maxDisCount, disCountPrice); + } + + private Receipt combineReceipt(Receipt promoted, Receipt nonPromoted) { + if(!promoted.getProductName().equals(nonPromoted.getProductName())){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + return promoted.combine(nonPromoted); + } + + private Receipt tryBuyProductPromoted(PurchaseRequest request){ + boolean isPromoted = true; + Product product = this.findOneOriginProduct(request.getProductName(),isPromoted); + if(product == NOT_FOUND){ + return Receipt.createEmptyReceipt(request.getProductName()); + } + if(product.getCount() < request.getCountPurchased()){ + int buyCount = product.getCount(); + return buyProduct(product,buyCount,request); + } + return buyProduct(product,request.getCountPurchased(),request); + } + + + private Receipt tryBuyProductNonPromoted(PurchaseRequest request){ + boolean isPromoted = false; + Product product = this.findOneOriginProduct(request.getProductName(),isPromoted); + if(product == NOT_FOUND){ + return Receipt.createEmptyReceipt(request.getProductName()); + } + if(product.getCount() < request.getCountPurchased()){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + return buyProduct(product,request.getCountPurchased(),request); + } + + private Receipt buyProduct(Product product, int buyCount, PurchaseRequest request){ + request.decreaseCount(buyCount); + return product.buy(buyCount); + } + +}
Java
์ƒ์„ฑ์ž์— ์ ‘๊ทผ์ œ์–ด์ž๋ฅผ ๋ช…์‹œํ•˜์ง€ ์•Š์œผ์‹  ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ ์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,371 @@ +package store; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import store.io.ProductFile; +import store.io.PromotionFile; +import store.product.Product; +import store.product.PurchaseRequest; +import store.product.Receipt; +import store.product.promotion.Promotion; +import store.product.promotion.PromotionResult; +import store.product.promotion.PromotionState; +import store.utils.ExceptionFactory; +import store.utils.ExceptionType; +import store.utils.Transformer; + +public class StoreModel { + static private final Product NOT_FOUND = null; + private final List<Product> productRepository; + private final HashMap<String,Promotion> promotionHashMap; + final static String NAME_REGULAR_EXPRESSION = "^[a-zA-Z๊ฐ€-ํžฃ0-9]+$"; + final static Pattern NAME_PATTERN = Pattern.compile(StoreModel.NAME_REGULAR_EXPRESSION); + + StoreModel(){ + this.productRepository = new ArrayList<>(); + this.promotionHashMap = new HashMap<>(); + } + + public void initStore(List<Product> products, List<Promotion> promotions){ + addProducts(products); + putPromotion(promotions); + applyPromotions(); + } + + private void addProducts(List<Product> products){ + for(Product origin : products){ + this.productRepository.add(origin.clone()); + } + checkInitProduct(this.productRepository); + } + + public void checkInitProduct(List<Product> products){ + for(Product product : products){ + validateSameProductsHaveSamePrice(product); + } + } + + public void validateSameProductsHaveSamePrice(Product product){ + List<Product> finds = findProduct(product.getName()); + int price = 0; + for(Product find : finds){ + price += find.getPrice(); + } + int averagePrice = price / finds.size(); + if(finds.getFirst().getPrice() != averagePrice){ + System.out.println("[Error] ๋™์ผ ์ด๋ฆ„์˜ ์ƒํ’ˆ์€ ๊ฐ€๊ฒฉ์ด ๊ฐ™์•„์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์ž˜๋ชป๋œ ์ƒํ’ˆ :" + product.getName()); + ExceptionFactory.throwIllegalStateException(ExceptionType.INVALID_FILE_FORMAT); + } + } + + private void putPromotion(List<Promotion> promotions){ + /*TODO + - ํ”„๋กœ๋ชจ์…˜ ์ด๋ฆ„ ์ค‘๋ณต์ด ์—†๋„๋ก ํ•ด์•ผํ•จ. + - ๋‚ ์งœ๊ฐ€ ๋‹ค๋ฅด๋”๋ผ๋„, ์ด๋ฆ„ ์ค‘๋ณต์ด ์—†๋„๋ก ํ•ด์•ผํ•จ. + - ํ”„๋กœ๋ชจ์…˜ ์ค‘๋ณต์ด ์žˆ๋Š” ๊ฒฝ์šฐ, promotions.md ํŒŒ์ผ์ด ๋ฌธ์ œ์ด๋ฏ€๋กœ ํ•ด๋‹น ํŒŒ์ผ์—์„œ ํ™•์ธ ํ•„์š”. + * */ + for(Promotion promotion : promotions){ + this.promotionHashMap.put(promotion.getName(),promotion.clone()); + } + } + + private void applyPromotions(){ + for(Product product : this.productRepository){ + product.setPromotion(this.promotionHashMap.get(product.getPromotionName())); + } + } + + public List<Product> getProducts(){ + List<Product> copied = new ArrayList<>(); + for(Product origin : this.productRepository){ + copied.add(origin.clone()); + } + + return copied; + } + + /*TODO + - ์ ‘๊ทผ์ง€์‹œ์ž, static ํ‚ค์›Œ๋“œ ๊ธฐ์ค€์œผ๋กœ ๋ฉ”์†Œ๋“œ ์ •๋ ฌํ•˜๊ธฐ + * */ + public Product findOneProduct(String name, boolean isPromoted){ + return this.findOneOriginProduct(name,isPromoted).clone(); + } + + public List<Product> findProduct(String name){ + return this.findProductOrigin(name).stream() + .map(Product::clone) + .toList(); + } + + public Product findOneOriginProduct(String name, boolean isPromoted){ + if(isPromoted){ + return findProductPromoted(name); + } + return findProductNonPromoted(name); + } + + public List<Product> findProductOrigin(String name){ + return this.productRepository.stream() + .filter((product)->product.getName().equals(name)) + .collect(Collectors.toList()); + } + + private Product findProductPromoted(String name){ + List<Product> finds = findProductOrigin(name).stream() + .filter((product -> product.getPromotionName()!=null)) + .toList(); + validateFindList(finds); + if(finds.isEmpty()){ + return NOT_FOUND; + } + return finds.getFirst(); + } + + private Product findProductNonPromoted(String name){ + List<Product> finds = findProductOrigin(name).stream() + .filter(product -> product.getPromotionName() == Product.NO_PROMOTION) + .toList(); + validateFindList(finds); + if(finds.isEmpty()){ + return NOT_FOUND; + } + return finds.getFirst(); + } + + private void validateFindList(List<?> finds){ + int limit = 1; + if(finds.size() > limit){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + } + + /*TODO + * - promotion๊ณผ product ์ƒ์„ฑ ๊ด€๋ จ static ํ•จ์ˆ˜๋ฅผ ๋‹ค๋ฅธ ํด๋ž˜์Šค์— ์ฑ…์ž„ ๋งก๊ธธ ๊ฒƒ์œผ ๊ณ ๋ คํ•˜๊ธฐ + * - promotion๊ณผ product ์ƒ์„ฑ์‹œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ ๊ณ ๋ ค + * - ์ž˜๋ชป๋œ ํƒ€์ž… ์ž…๋ ฅ + * - ์ž˜๋ชป๋œ ํ˜•์‹ ์ž…๋ ฅ + * */ + + static public List<String> parseString(String string){ + if (string == null || string.isBlank()) { + throw new IllegalArgumentException("List is empty"); + } + final String delimiter = ","; + String[] parsed = string.split(delimiter); + + return List.of(parsed); + } + + static public Product createProduct(String rawProduct){ + List<String> parsedRawProduct = StoreModel.parseString(rawProduct); + String name = parsedRawProduct.get(ProductFile.NAME.getColumnIdx()); + String price = parsedRawProduct.get(ProductFile.PRICE.getColumnIdx()); + String quantity = parsedRawProduct.get(ProductFile.QUANTITY.getColumnIdx()); + String promotion = parsedRawProduct.get(ProductFile.PROMOTION.getColumnIdx()); + validateNameFormat(name); + if(promotion.equals("null")){ + promotion = null; + } + return new Product(name, Transformer.parsePositiveInt(price),Transformer.parseNonNegativeNumber(quantity),promotion); + } + + static public List<Product> createProducts(String rawProductList){ + List<Product> products = new ArrayList<>(); + String[] rawProducts = rawProductList.split("\n"); + + int idx = 1; + + for( ; idx < rawProducts.length; idx++){ + String rawProduct = rawProducts[idx]; + products.add(StoreModel.createProduct(rawProduct)); + } + return products; + } + static public void validateNameFormat(String name){ + Matcher matcher = NAME_PATTERN.matcher(name); + if(!matcher.matches()){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_NAME_FORMAT); + } + } + + static public Promotion createPromotion(String rawPromotion){ + List<String> parsedRawPromotion = StoreModel.parseString(rawPromotion); + String name = parsedRawPromotion.get(PromotionFile.NAME.getColumnIdx()); + String buyCount = parsedRawPromotion.get(PromotionFile.BUY.getColumnIdx()); + String returnCount = parsedRawPromotion.get(PromotionFile.GET.getColumnIdx()); + String startDate = parsedRawPromotion.get(PromotionFile.START_DATE.getColumnIdx()); + String endDate = parsedRawPromotion.get(PromotionFile.END_DATE.getColumnIdx()); + Promotion.validateReturnCount(returnCount); + return new Promotion(name, Transformer.parseStartDate(startDate,PromotionFile.DATE_TIME_FORMATTER),Transformer.parseEndDate(endDate,PromotionFile.DATE_TIME_FORMATTER),Transformer.parsePositiveInt(buyCount)); + } + + static public List<Promotion> createPromotions(String rawPromotionList){ + List<Promotion> promotions = new ArrayList<>(); + String[] rawPromotions = rawPromotionList.split("\n"); + + int idx = 1; + + for( ; idx < rawPromotions.length; idx++){ + String rawPromotion = rawPromotions[idx]; + promotions.add(StoreModel.createPromotion(rawPromotion)); + } + return promotions; + } + + public List<StoreViewMessage> checkPurchaseRequests(List<PurchaseRequest> requests) { + List<StoreViewMessage> messageBox = new ArrayList<>(); + + for(PurchaseRequest request : requests){ + checkPurchaseRequest(request,messageBox); + } + + return messageBox; + } + + public void checkPurchaseRequest(PurchaseRequest request, List<StoreViewMessage> messageBox){ + checkPurchaseProductExist(request,messageBox); + checkPurchaseProductCount(request,messageBox); + + } + + public void checkPurchaseProductExist(PurchaseRequest request, List<StoreViewMessage> messageBox){ + List<Product> finds = findProduct(request.getProductName()); + if(finds.isEmpty()){ + messageBox.add(StoreViewMessage.ERROR_NOT_EXIST_PRODUCT); + } + } + + public void checkPurchaseProductCount(PurchaseRequest request, List<StoreViewMessage> messageBox){ + List<Product> finds = findProduct(request.getProductName()); + int zero = 0; + int totalCount = finds.stream().map(Product::getCount).reduce(zero,Integer::sum); + if(totalCount == zero){ + messageBox.add(StoreViewMessage.ERROR_NO_COUNT_PRODUCT); + } + if(totalCount != zero && totalCount < request.getCountPurchased()){ + messageBox.add(StoreViewMessage.ERROR_OVERFLOW_PURCHASE); + } + } + + public List<PromotionResult> checkPromotionAvailable(List<PurchaseRequest> purchaseRequests){ + List<PromotionResult> promotionResults = new ArrayList<>(); + for(PurchaseRequest request : purchaseRequests){ + promotionResults.addAll(checkPromotionBoth(request.getProductName(),request.getCountPurchased())); + } + + return promotionResults; + } + + public List<PromotionResult> checkPromotionBoth(String productName , int buyCount){ + PromotionResult resultPromotion = checkProductPromotionAvailable(productName,buyCount); + PromotionResult resultNonPromotion = null; + + Product product = findProductNonPromoted(productName); + if(findProductPromoted(productName) == NOT_FOUND){ + resultNonPromotion = PromotionResult.createNoPromotion(productName,buyCount); + return List.of(resultNonPromotion); + } + + if(resultPromotion.getState()==PromotionState.INSUFFICIENT + && resultPromotion.getTotalItemCount() < buyCount){ + int remainCountToBuy = buyCount - resultPromotion.getTotalItemCount(); + resultNonPromotion = PromotionResult.createNoPromotion(productName,remainCountToBuy); + return List.of(resultPromotion, resultNonPromotion); + } + + return List.of(resultPromotion); + } + + public PromotionResult checkProductPromotionAvailable(String productName, int buyCount){ + Product product = findProductPromoted(productName); + if(findProductPromoted(productName) == NOT_FOUND){ + return PromotionResult.createNoPromotion(productName,buyCount); + } + if(product.isEnoughToBuy(buyCount)){ + return product.estimatePromotionResult(buyCount, DateTimes.now()); + } + + int maxCountToBuyPromotion = product.calculateMaxCountToBuy(buyCount); + PromotionResult promotionResult = product.estimatePromotionResult(maxCountToBuyPromotion,DateTimes.now()); + return promotionResult.transitState(PromotionState.INSUFFICIENT); + + } + + public List<Receipt> buyProducts(List<PurchaseRequest> purchaseRequests){ + List<Receipt> receipts = new ArrayList<>(); + for(PurchaseRequest request : purchaseRequests){ + receipts.add(buyProduct(request)); + } + return receipts; + } + + public Receipt buyProduct(PurchaseRequest request){ + + if(request.getPromotionState() == PromotionState.NO_PROMOTION){ + return tryBuyProductNonPromoted(request); + } + + Receipt resultPromoted = tryBuyProductPromoted(request); + Receipt resultNonPromoted = tryBuyProductNonPromoted(request); + + return combineReceipt(resultPromoted,resultNonPromoted); + } + + public int calculateDiscount(List<Receipt> receipts){ + /*TODO + * - ํ•ฉ๊ณ„์‚ฐ ๋„์ค‘ ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ ์ ๊ฒ€ ํ•„์š”*/ + final int maxDisCount = 8000; + final double disCountRate = 0.3; + int totalNonPromotedPrice = 0; + for(Receipt receipt : receipts){ + totalNonPromotedPrice += receipt.getNonPromotedPrice(); + } + int disCountPrice = (int)Math.round(disCountRate * totalNonPromotedPrice); + return Math.min(maxDisCount, disCountPrice); + } + + private Receipt combineReceipt(Receipt promoted, Receipt nonPromoted) { + if(!promoted.getProductName().equals(nonPromoted.getProductName())){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + return promoted.combine(nonPromoted); + } + + private Receipt tryBuyProductPromoted(PurchaseRequest request){ + boolean isPromoted = true; + Product product = this.findOneOriginProduct(request.getProductName(),isPromoted); + if(product == NOT_FOUND){ + return Receipt.createEmptyReceipt(request.getProductName()); + } + if(product.getCount() < request.getCountPurchased()){ + int buyCount = product.getCount(); + return buyProduct(product,buyCount,request); + } + return buyProduct(product,request.getCountPurchased(),request); + } + + + private Receipt tryBuyProductNonPromoted(PurchaseRequest request){ + boolean isPromoted = false; + Product product = this.findOneOriginProduct(request.getProductName(),isPromoted); + if(product == NOT_FOUND){ + return Receipt.createEmptyReceipt(request.getProductName()); + } + if(product.getCount() < request.getCountPurchased()){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + return buyProduct(product,request.getCountPurchased(),request); + } + + private Receipt buyProduct(Product product, int buyCount, PurchaseRequest request){ + request.decreaseCount(buyCount); + return product.buy(buyCount); + } + +}
Java
์˜ค.. ์ƒ๊ฐํ•ด๋ณด๋ฉด ํ”„๋กœ๋ชจ์…˜์€ `buy n get 1`์— ๋Œ€ํ•œ ๊ฒƒ์ด๋‹ˆ๊นŒ, ํ”„๋กœ๋ชจ์…˜์ด๋“  ์ผ๋ฐ˜์ด๋“  ์ œํ’ˆ ์ž์ฒด์˜ ๊ฐ€๊ฒฉ์€ ๊ฐ™์€ ๊ฒŒ ๋งž๊ฒ ๋„ค์š”! ๊ผผ๊ผผํ•˜๊ฒŒ ์ƒ๊ฐํ•ด๋ณด์‹  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค๐Ÿ‘
@@ -0,0 +1,371 @@ +package store; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import store.io.ProductFile; +import store.io.PromotionFile; +import store.product.Product; +import store.product.PurchaseRequest; +import store.product.Receipt; +import store.product.promotion.Promotion; +import store.product.promotion.PromotionResult; +import store.product.promotion.PromotionState; +import store.utils.ExceptionFactory; +import store.utils.ExceptionType; +import store.utils.Transformer; + +public class StoreModel { + static private final Product NOT_FOUND = null; + private final List<Product> productRepository; + private final HashMap<String,Promotion> promotionHashMap; + final static String NAME_REGULAR_EXPRESSION = "^[a-zA-Z๊ฐ€-ํžฃ0-9]+$"; + final static Pattern NAME_PATTERN = Pattern.compile(StoreModel.NAME_REGULAR_EXPRESSION); + + StoreModel(){ + this.productRepository = new ArrayList<>(); + this.promotionHashMap = new HashMap<>(); + } + + public void initStore(List<Product> products, List<Promotion> promotions){ + addProducts(products); + putPromotion(promotions); + applyPromotions(); + } + + private void addProducts(List<Product> products){ + for(Product origin : products){ + this.productRepository.add(origin.clone()); + } + checkInitProduct(this.productRepository); + } + + public void checkInitProduct(List<Product> products){ + for(Product product : products){ + validateSameProductsHaveSamePrice(product); + } + } + + public void validateSameProductsHaveSamePrice(Product product){ + List<Product> finds = findProduct(product.getName()); + int price = 0; + for(Product find : finds){ + price += find.getPrice(); + } + int averagePrice = price / finds.size(); + if(finds.getFirst().getPrice() != averagePrice){ + System.out.println("[Error] ๋™์ผ ์ด๋ฆ„์˜ ์ƒํ’ˆ์€ ๊ฐ€๊ฒฉ์ด ๊ฐ™์•„์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์ž˜๋ชป๋œ ์ƒํ’ˆ :" + product.getName()); + ExceptionFactory.throwIllegalStateException(ExceptionType.INVALID_FILE_FORMAT); + } + } + + private void putPromotion(List<Promotion> promotions){ + /*TODO + - ํ”„๋กœ๋ชจ์…˜ ์ด๋ฆ„ ์ค‘๋ณต์ด ์—†๋„๋ก ํ•ด์•ผํ•จ. + - ๋‚ ์งœ๊ฐ€ ๋‹ค๋ฅด๋”๋ผ๋„, ์ด๋ฆ„ ์ค‘๋ณต์ด ์—†๋„๋ก ํ•ด์•ผํ•จ. + - ํ”„๋กœ๋ชจ์…˜ ์ค‘๋ณต์ด ์žˆ๋Š” ๊ฒฝ์šฐ, promotions.md ํŒŒ์ผ์ด ๋ฌธ์ œ์ด๋ฏ€๋กœ ํ•ด๋‹น ํŒŒ์ผ์—์„œ ํ™•์ธ ํ•„์š”. + * */ + for(Promotion promotion : promotions){ + this.promotionHashMap.put(promotion.getName(),promotion.clone()); + } + } + + private void applyPromotions(){ + for(Product product : this.productRepository){ + product.setPromotion(this.promotionHashMap.get(product.getPromotionName())); + } + } + + public List<Product> getProducts(){ + List<Product> copied = new ArrayList<>(); + for(Product origin : this.productRepository){ + copied.add(origin.clone()); + } + + return copied; + } + + /*TODO + - ์ ‘๊ทผ์ง€์‹œ์ž, static ํ‚ค์›Œ๋“œ ๊ธฐ์ค€์œผ๋กœ ๋ฉ”์†Œ๋“œ ์ •๋ ฌํ•˜๊ธฐ + * */ + public Product findOneProduct(String name, boolean isPromoted){ + return this.findOneOriginProduct(name,isPromoted).clone(); + } + + public List<Product> findProduct(String name){ + return this.findProductOrigin(name).stream() + .map(Product::clone) + .toList(); + } + + public Product findOneOriginProduct(String name, boolean isPromoted){ + if(isPromoted){ + return findProductPromoted(name); + } + return findProductNonPromoted(name); + } + + public List<Product> findProductOrigin(String name){ + return this.productRepository.stream() + .filter((product)->product.getName().equals(name)) + .collect(Collectors.toList()); + } + + private Product findProductPromoted(String name){ + List<Product> finds = findProductOrigin(name).stream() + .filter((product -> product.getPromotionName()!=null)) + .toList(); + validateFindList(finds); + if(finds.isEmpty()){ + return NOT_FOUND; + } + return finds.getFirst(); + } + + private Product findProductNonPromoted(String name){ + List<Product> finds = findProductOrigin(name).stream() + .filter(product -> product.getPromotionName() == Product.NO_PROMOTION) + .toList(); + validateFindList(finds); + if(finds.isEmpty()){ + return NOT_FOUND; + } + return finds.getFirst(); + } + + private void validateFindList(List<?> finds){ + int limit = 1; + if(finds.size() > limit){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + } + + /*TODO + * - promotion๊ณผ product ์ƒ์„ฑ ๊ด€๋ จ static ํ•จ์ˆ˜๋ฅผ ๋‹ค๋ฅธ ํด๋ž˜์Šค์— ์ฑ…์ž„ ๋งก๊ธธ ๊ฒƒ์œผ ๊ณ ๋ คํ•˜๊ธฐ + * - promotion๊ณผ product ์ƒ์„ฑ์‹œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ ๊ณ ๋ ค + * - ์ž˜๋ชป๋œ ํƒ€์ž… ์ž…๋ ฅ + * - ์ž˜๋ชป๋œ ํ˜•์‹ ์ž…๋ ฅ + * */ + + static public List<String> parseString(String string){ + if (string == null || string.isBlank()) { + throw new IllegalArgumentException("List is empty"); + } + final String delimiter = ","; + String[] parsed = string.split(delimiter); + + return List.of(parsed); + } + + static public Product createProduct(String rawProduct){ + List<String> parsedRawProduct = StoreModel.parseString(rawProduct); + String name = parsedRawProduct.get(ProductFile.NAME.getColumnIdx()); + String price = parsedRawProduct.get(ProductFile.PRICE.getColumnIdx()); + String quantity = parsedRawProduct.get(ProductFile.QUANTITY.getColumnIdx()); + String promotion = parsedRawProduct.get(ProductFile.PROMOTION.getColumnIdx()); + validateNameFormat(name); + if(promotion.equals("null")){ + promotion = null; + } + return new Product(name, Transformer.parsePositiveInt(price),Transformer.parseNonNegativeNumber(quantity),promotion); + } + + static public List<Product> createProducts(String rawProductList){ + List<Product> products = new ArrayList<>(); + String[] rawProducts = rawProductList.split("\n"); + + int idx = 1; + + for( ; idx < rawProducts.length; idx++){ + String rawProduct = rawProducts[idx]; + products.add(StoreModel.createProduct(rawProduct)); + } + return products; + } + static public void validateNameFormat(String name){ + Matcher matcher = NAME_PATTERN.matcher(name); + if(!matcher.matches()){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_NAME_FORMAT); + } + } + + static public Promotion createPromotion(String rawPromotion){ + List<String> parsedRawPromotion = StoreModel.parseString(rawPromotion); + String name = parsedRawPromotion.get(PromotionFile.NAME.getColumnIdx()); + String buyCount = parsedRawPromotion.get(PromotionFile.BUY.getColumnIdx()); + String returnCount = parsedRawPromotion.get(PromotionFile.GET.getColumnIdx()); + String startDate = parsedRawPromotion.get(PromotionFile.START_DATE.getColumnIdx()); + String endDate = parsedRawPromotion.get(PromotionFile.END_DATE.getColumnIdx()); + Promotion.validateReturnCount(returnCount); + return new Promotion(name, Transformer.parseStartDate(startDate,PromotionFile.DATE_TIME_FORMATTER),Transformer.parseEndDate(endDate,PromotionFile.DATE_TIME_FORMATTER),Transformer.parsePositiveInt(buyCount)); + } + + static public List<Promotion> createPromotions(String rawPromotionList){ + List<Promotion> promotions = new ArrayList<>(); + String[] rawPromotions = rawPromotionList.split("\n"); + + int idx = 1; + + for( ; idx < rawPromotions.length; idx++){ + String rawPromotion = rawPromotions[idx]; + promotions.add(StoreModel.createPromotion(rawPromotion)); + } + return promotions; + } + + public List<StoreViewMessage> checkPurchaseRequests(List<PurchaseRequest> requests) { + List<StoreViewMessage> messageBox = new ArrayList<>(); + + for(PurchaseRequest request : requests){ + checkPurchaseRequest(request,messageBox); + } + + return messageBox; + } + + public void checkPurchaseRequest(PurchaseRequest request, List<StoreViewMessage> messageBox){ + checkPurchaseProductExist(request,messageBox); + checkPurchaseProductCount(request,messageBox); + + } + + public void checkPurchaseProductExist(PurchaseRequest request, List<StoreViewMessage> messageBox){ + List<Product> finds = findProduct(request.getProductName()); + if(finds.isEmpty()){ + messageBox.add(StoreViewMessage.ERROR_NOT_EXIST_PRODUCT); + } + } + + public void checkPurchaseProductCount(PurchaseRequest request, List<StoreViewMessage> messageBox){ + List<Product> finds = findProduct(request.getProductName()); + int zero = 0; + int totalCount = finds.stream().map(Product::getCount).reduce(zero,Integer::sum); + if(totalCount == zero){ + messageBox.add(StoreViewMessage.ERROR_NO_COUNT_PRODUCT); + } + if(totalCount != zero && totalCount < request.getCountPurchased()){ + messageBox.add(StoreViewMessage.ERROR_OVERFLOW_PURCHASE); + } + } + + public List<PromotionResult> checkPromotionAvailable(List<PurchaseRequest> purchaseRequests){ + List<PromotionResult> promotionResults = new ArrayList<>(); + for(PurchaseRequest request : purchaseRequests){ + promotionResults.addAll(checkPromotionBoth(request.getProductName(),request.getCountPurchased())); + } + + return promotionResults; + } + + public List<PromotionResult> checkPromotionBoth(String productName , int buyCount){ + PromotionResult resultPromotion = checkProductPromotionAvailable(productName,buyCount); + PromotionResult resultNonPromotion = null; + + Product product = findProductNonPromoted(productName); + if(findProductPromoted(productName) == NOT_FOUND){ + resultNonPromotion = PromotionResult.createNoPromotion(productName,buyCount); + return List.of(resultNonPromotion); + } + + if(resultPromotion.getState()==PromotionState.INSUFFICIENT + && resultPromotion.getTotalItemCount() < buyCount){ + int remainCountToBuy = buyCount - resultPromotion.getTotalItemCount(); + resultNonPromotion = PromotionResult.createNoPromotion(productName,remainCountToBuy); + return List.of(resultPromotion, resultNonPromotion); + } + + return List.of(resultPromotion); + } + + public PromotionResult checkProductPromotionAvailable(String productName, int buyCount){ + Product product = findProductPromoted(productName); + if(findProductPromoted(productName) == NOT_FOUND){ + return PromotionResult.createNoPromotion(productName,buyCount); + } + if(product.isEnoughToBuy(buyCount)){ + return product.estimatePromotionResult(buyCount, DateTimes.now()); + } + + int maxCountToBuyPromotion = product.calculateMaxCountToBuy(buyCount); + PromotionResult promotionResult = product.estimatePromotionResult(maxCountToBuyPromotion,DateTimes.now()); + return promotionResult.transitState(PromotionState.INSUFFICIENT); + + } + + public List<Receipt> buyProducts(List<PurchaseRequest> purchaseRequests){ + List<Receipt> receipts = new ArrayList<>(); + for(PurchaseRequest request : purchaseRequests){ + receipts.add(buyProduct(request)); + } + return receipts; + } + + public Receipt buyProduct(PurchaseRequest request){ + + if(request.getPromotionState() == PromotionState.NO_PROMOTION){ + return tryBuyProductNonPromoted(request); + } + + Receipt resultPromoted = tryBuyProductPromoted(request); + Receipt resultNonPromoted = tryBuyProductNonPromoted(request); + + return combineReceipt(resultPromoted,resultNonPromoted); + } + + public int calculateDiscount(List<Receipt> receipts){ + /*TODO + * - ํ•ฉ๊ณ„์‚ฐ ๋„์ค‘ ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ ์ ๊ฒ€ ํ•„์š”*/ + final int maxDisCount = 8000; + final double disCountRate = 0.3; + int totalNonPromotedPrice = 0; + for(Receipt receipt : receipts){ + totalNonPromotedPrice += receipt.getNonPromotedPrice(); + } + int disCountPrice = (int)Math.round(disCountRate * totalNonPromotedPrice); + return Math.min(maxDisCount, disCountPrice); + } + + private Receipt combineReceipt(Receipt promoted, Receipt nonPromoted) { + if(!promoted.getProductName().equals(nonPromoted.getProductName())){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + return promoted.combine(nonPromoted); + } + + private Receipt tryBuyProductPromoted(PurchaseRequest request){ + boolean isPromoted = true; + Product product = this.findOneOriginProduct(request.getProductName(),isPromoted); + if(product == NOT_FOUND){ + return Receipt.createEmptyReceipt(request.getProductName()); + } + if(product.getCount() < request.getCountPurchased()){ + int buyCount = product.getCount(); + return buyProduct(product,buyCount,request); + } + return buyProduct(product,request.getCountPurchased(),request); + } + + + private Receipt tryBuyProductNonPromoted(PurchaseRequest request){ + boolean isPromoted = false; + Product product = this.findOneOriginProduct(request.getProductName(),isPromoted); + if(product == NOT_FOUND){ + return Receipt.createEmptyReceipt(request.getProductName()); + } + if(product.getCount() < request.getCountPurchased()){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + return buyProduct(product,request.getCountPurchased(),request); + } + + private Receipt buyProduct(Product product, int buyCount, PurchaseRequest request){ + request.decreaseCount(buyCount); + return product.buy(buyCount); + } + +}
Java
idx๋ฅผ for๋ฌธ ์กฐ๊ฑด๋ถ€์—์„œ ์ดˆ๊ธฐํ™”์‹œ์ผœ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ```java for(int idx = 1; idx < rawPromotions.length; idx++) { String rawPromotion = rawPromotions[idx]; } ```
@@ -0,0 +1,371 @@ +package store; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import store.io.ProductFile; +import store.io.PromotionFile; +import store.product.Product; +import store.product.PurchaseRequest; +import store.product.Receipt; +import store.product.promotion.Promotion; +import store.product.promotion.PromotionResult; +import store.product.promotion.PromotionState; +import store.utils.ExceptionFactory; +import store.utils.ExceptionType; +import store.utils.Transformer; + +public class StoreModel { + static private final Product NOT_FOUND = null; + private final List<Product> productRepository; + private final HashMap<String,Promotion> promotionHashMap; + final static String NAME_REGULAR_EXPRESSION = "^[a-zA-Z๊ฐ€-ํžฃ0-9]+$"; + final static Pattern NAME_PATTERN = Pattern.compile(StoreModel.NAME_REGULAR_EXPRESSION); + + StoreModel(){ + this.productRepository = new ArrayList<>(); + this.promotionHashMap = new HashMap<>(); + } + + public void initStore(List<Product> products, List<Promotion> promotions){ + addProducts(products); + putPromotion(promotions); + applyPromotions(); + } + + private void addProducts(List<Product> products){ + for(Product origin : products){ + this.productRepository.add(origin.clone()); + } + checkInitProduct(this.productRepository); + } + + public void checkInitProduct(List<Product> products){ + for(Product product : products){ + validateSameProductsHaveSamePrice(product); + } + } + + public void validateSameProductsHaveSamePrice(Product product){ + List<Product> finds = findProduct(product.getName()); + int price = 0; + for(Product find : finds){ + price += find.getPrice(); + } + int averagePrice = price / finds.size(); + if(finds.getFirst().getPrice() != averagePrice){ + System.out.println("[Error] ๋™์ผ ์ด๋ฆ„์˜ ์ƒํ’ˆ์€ ๊ฐ€๊ฒฉ์ด ๊ฐ™์•„์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์ž˜๋ชป๋œ ์ƒํ’ˆ :" + product.getName()); + ExceptionFactory.throwIllegalStateException(ExceptionType.INVALID_FILE_FORMAT); + } + } + + private void putPromotion(List<Promotion> promotions){ + /*TODO + - ํ”„๋กœ๋ชจ์…˜ ์ด๋ฆ„ ์ค‘๋ณต์ด ์—†๋„๋ก ํ•ด์•ผํ•จ. + - ๋‚ ์งœ๊ฐ€ ๋‹ค๋ฅด๋”๋ผ๋„, ์ด๋ฆ„ ์ค‘๋ณต์ด ์—†๋„๋ก ํ•ด์•ผํ•จ. + - ํ”„๋กœ๋ชจ์…˜ ์ค‘๋ณต์ด ์žˆ๋Š” ๊ฒฝ์šฐ, promotions.md ํŒŒ์ผ์ด ๋ฌธ์ œ์ด๋ฏ€๋กœ ํ•ด๋‹น ํŒŒ์ผ์—์„œ ํ™•์ธ ํ•„์š”. + * */ + for(Promotion promotion : promotions){ + this.promotionHashMap.put(promotion.getName(),promotion.clone()); + } + } + + private void applyPromotions(){ + for(Product product : this.productRepository){ + product.setPromotion(this.promotionHashMap.get(product.getPromotionName())); + } + } + + public List<Product> getProducts(){ + List<Product> copied = new ArrayList<>(); + for(Product origin : this.productRepository){ + copied.add(origin.clone()); + } + + return copied; + } + + /*TODO + - ์ ‘๊ทผ์ง€์‹œ์ž, static ํ‚ค์›Œ๋“œ ๊ธฐ์ค€์œผ๋กœ ๋ฉ”์†Œ๋“œ ์ •๋ ฌํ•˜๊ธฐ + * */ + public Product findOneProduct(String name, boolean isPromoted){ + return this.findOneOriginProduct(name,isPromoted).clone(); + } + + public List<Product> findProduct(String name){ + return this.findProductOrigin(name).stream() + .map(Product::clone) + .toList(); + } + + public Product findOneOriginProduct(String name, boolean isPromoted){ + if(isPromoted){ + return findProductPromoted(name); + } + return findProductNonPromoted(name); + } + + public List<Product> findProductOrigin(String name){ + return this.productRepository.stream() + .filter((product)->product.getName().equals(name)) + .collect(Collectors.toList()); + } + + private Product findProductPromoted(String name){ + List<Product> finds = findProductOrigin(name).stream() + .filter((product -> product.getPromotionName()!=null)) + .toList(); + validateFindList(finds); + if(finds.isEmpty()){ + return NOT_FOUND; + } + return finds.getFirst(); + } + + private Product findProductNonPromoted(String name){ + List<Product> finds = findProductOrigin(name).stream() + .filter(product -> product.getPromotionName() == Product.NO_PROMOTION) + .toList(); + validateFindList(finds); + if(finds.isEmpty()){ + return NOT_FOUND; + } + return finds.getFirst(); + } + + private void validateFindList(List<?> finds){ + int limit = 1; + if(finds.size() > limit){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + } + + /*TODO + * - promotion๊ณผ product ์ƒ์„ฑ ๊ด€๋ จ static ํ•จ์ˆ˜๋ฅผ ๋‹ค๋ฅธ ํด๋ž˜์Šค์— ์ฑ…์ž„ ๋งก๊ธธ ๊ฒƒ์œผ ๊ณ ๋ คํ•˜๊ธฐ + * - promotion๊ณผ product ์ƒ์„ฑ์‹œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ ๊ณ ๋ ค + * - ์ž˜๋ชป๋œ ํƒ€์ž… ์ž…๋ ฅ + * - ์ž˜๋ชป๋œ ํ˜•์‹ ์ž…๋ ฅ + * */ + + static public List<String> parseString(String string){ + if (string == null || string.isBlank()) { + throw new IllegalArgumentException("List is empty"); + } + final String delimiter = ","; + String[] parsed = string.split(delimiter); + + return List.of(parsed); + } + + static public Product createProduct(String rawProduct){ + List<String> parsedRawProduct = StoreModel.parseString(rawProduct); + String name = parsedRawProduct.get(ProductFile.NAME.getColumnIdx()); + String price = parsedRawProduct.get(ProductFile.PRICE.getColumnIdx()); + String quantity = parsedRawProduct.get(ProductFile.QUANTITY.getColumnIdx()); + String promotion = parsedRawProduct.get(ProductFile.PROMOTION.getColumnIdx()); + validateNameFormat(name); + if(promotion.equals("null")){ + promotion = null; + } + return new Product(name, Transformer.parsePositiveInt(price),Transformer.parseNonNegativeNumber(quantity),promotion); + } + + static public List<Product> createProducts(String rawProductList){ + List<Product> products = new ArrayList<>(); + String[] rawProducts = rawProductList.split("\n"); + + int idx = 1; + + for( ; idx < rawProducts.length; idx++){ + String rawProduct = rawProducts[idx]; + products.add(StoreModel.createProduct(rawProduct)); + } + return products; + } + static public void validateNameFormat(String name){ + Matcher matcher = NAME_PATTERN.matcher(name); + if(!matcher.matches()){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_NAME_FORMAT); + } + } + + static public Promotion createPromotion(String rawPromotion){ + List<String> parsedRawPromotion = StoreModel.parseString(rawPromotion); + String name = parsedRawPromotion.get(PromotionFile.NAME.getColumnIdx()); + String buyCount = parsedRawPromotion.get(PromotionFile.BUY.getColumnIdx()); + String returnCount = parsedRawPromotion.get(PromotionFile.GET.getColumnIdx()); + String startDate = parsedRawPromotion.get(PromotionFile.START_DATE.getColumnIdx()); + String endDate = parsedRawPromotion.get(PromotionFile.END_DATE.getColumnIdx()); + Promotion.validateReturnCount(returnCount); + return new Promotion(name, Transformer.parseStartDate(startDate,PromotionFile.DATE_TIME_FORMATTER),Transformer.parseEndDate(endDate,PromotionFile.DATE_TIME_FORMATTER),Transformer.parsePositiveInt(buyCount)); + } + + static public List<Promotion> createPromotions(String rawPromotionList){ + List<Promotion> promotions = new ArrayList<>(); + String[] rawPromotions = rawPromotionList.split("\n"); + + int idx = 1; + + for( ; idx < rawPromotions.length; idx++){ + String rawPromotion = rawPromotions[idx]; + promotions.add(StoreModel.createPromotion(rawPromotion)); + } + return promotions; + } + + public List<StoreViewMessage> checkPurchaseRequests(List<PurchaseRequest> requests) { + List<StoreViewMessage> messageBox = new ArrayList<>(); + + for(PurchaseRequest request : requests){ + checkPurchaseRequest(request,messageBox); + } + + return messageBox; + } + + public void checkPurchaseRequest(PurchaseRequest request, List<StoreViewMessage> messageBox){ + checkPurchaseProductExist(request,messageBox); + checkPurchaseProductCount(request,messageBox); + + } + + public void checkPurchaseProductExist(PurchaseRequest request, List<StoreViewMessage> messageBox){ + List<Product> finds = findProduct(request.getProductName()); + if(finds.isEmpty()){ + messageBox.add(StoreViewMessage.ERROR_NOT_EXIST_PRODUCT); + } + } + + public void checkPurchaseProductCount(PurchaseRequest request, List<StoreViewMessage> messageBox){ + List<Product> finds = findProduct(request.getProductName()); + int zero = 0; + int totalCount = finds.stream().map(Product::getCount).reduce(zero,Integer::sum); + if(totalCount == zero){ + messageBox.add(StoreViewMessage.ERROR_NO_COUNT_PRODUCT); + } + if(totalCount != zero && totalCount < request.getCountPurchased()){ + messageBox.add(StoreViewMessage.ERROR_OVERFLOW_PURCHASE); + } + } + + public List<PromotionResult> checkPromotionAvailable(List<PurchaseRequest> purchaseRequests){ + List<PromotionResult> promotionResults = new ArrayList<>(); + for(PurchaseRequest request : purchaseRequests){ + promotionResults.addAll(checkPromotionBoth(request.getProductName(),request.getCountPurchased())); + } + + return promotionResults; + } + + public List<PromotionResult> checkPromotionBoth(String productName , int buyCount){ + PromotionResult resultPromotion = checkProductPromotionAvailable(productName,buyCount); + PromotionResult resultNonPromotion = null; + + Product product = findProductNonPromoted(productName); + if(findProductPromoted(productName) == NOT_FOUND){ + resultNonPromotion = PromotionResult.createNoPromotion(productName,buyCount); + return List.of(resultNonPromotion); + } + + if(resultPromotion.getState()==PromotionState.INSUFFICIENT + && resultPromotion.getTotalItemCount() < buyCount){ + int remainCountToBuy = buyCount - resultPromotion.getTotalItemCount(); + resultNonPromotion = PromotionResult.createNoPromotion(productName,remainCountToBuy); + return List.of(resultPromotion, resultNonPromotion); + } + + return List.of(resultPromotion); + } + + public PromotionResult checkProductPromotionAvailable(String productName, int buyCount){ + Product product = findProductPromoted(productName); + if(findProductPromoted(productName) == NOT_FOUND){ + return PromotionResult.createNoPromotion(productName,buyCount); + } + if(product.isEnoughToBuy(buyCount)){ + return product.estimatePromotionResult(buyCount, DateTimes.now()); + } + + int maxCountToBuyPromotion = product.calculateMaxCountToBuy(buyCount); + PromotionResult promotionResult = product.estimatePromotionResult(maxCountToBuyPromotion,DateTimes.now()); + return promotionResult.transitState(PromotionState.INSUFFICIENT); + + } + + public List<Receipt> buyProducts(List<PurchaseRequest> purchaseRequests){ + List<Receipt> receipts = new ArrayList<>(); + for(PurchaseRequest request : purchaseRequests){ + receipts.add(buyProduct(request)); + } + return receipts; + } + + public Receipt buyProduct(PurchaseRequest request){ + + if(request.getPromotionState() == PromotionState.NO_PROMOTION){ + return tryBuyProductNonPromoted(request); + } + + Receipt resultPromoted = tryBuyProductPromoted(request); + Receipt resultNonPromoted = tryBuyProductNonPromoted(request); + + return combineReceipt(resultPromoted,resultNonPromoted); + } + + public int calculateDiscount(List<Receipt> receipts){ + /*TODO + * - ํ•ฉ๊ณ„์‚ฐ ๋„์ค‘ ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ ์ ๊ฒ€ ํ•„์š”*/ + final int maxDisCount = 8000; + final double disCountRate = 0.3; + int totalNonPromotedPrice = 0; + for(Receipt receipt : receipts){ + totalNonPromotedPrice += receipt.getNonPromotedPrice(); + } + int disCountPrice = (int)Math.round(disCountRate * totalNonPromotedPrice); + return Math.min(maxDisCount, disCountPrice); + } + + private Receipt combineReceipt(Receipt promoted, Receipt nonPromoted) { + if(!promoted.getProductName().equals(nonPromoted.getProductName())){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + return promoted.combine(nonPromoted); + } + + private Receipt tryBuyProductPromoted(PurchaseRequest request){ + boolean isPromoted = true; + Product product = this.findOneOriginProduct(request.getProductName(),isPromoted); + if(product == NOT_FOUND){ + return Receipt.createEmptyReceipt(request.getProductName()); + } + if(product.getCount() < request.getCountPurchased()){ + int buyCount = product.getCount(); + return buyProduct(product,buyCount,request); + } + return buyProduct(product,request.getCountPurchased(),request); + } + + + private Receipt tryBuyProductNonPromoted(PurchaseRequest request){ + boolean isPromoted = false; + Product product = this.findOneOriginProduct(request.getProductName(),isPromoted); + if(product == NOT_FOUND){ + return Receipt.createEmptyReceipt(request.getProductName()); + } + if(product.getCount() < request.getCountPurchased()){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + return buyProduct(product,request.getCountPurchased(),request); + } + + private Receipt buyProduct(Product product, int buyCount, PurchaseRequest request){ + request.decreaseCount(buyCount); + return product.buy(buyCount); + } + +}
Java
์ ์–ด์ฃผ์‹ ๋Œ€๋กœ ์ฑ…์ž„ ๋ถ„๋ฆฌ๋ฅผ ํ•˜์‹ ๋‹ค๋ฉด ์ฝ”๋“œ๊ฐ€ ํ›จ์”ฌ ๊น”๋”ํ•ด์งˆ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,73 @@ +package store; + +public enum StoreViewMessage { + + WELCOME("์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค.\n" + + "ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."), + PURCHASE_GUIDE("๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"), + MEMBERSHIP_GUIDE("๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"), + + RECEIPT_HEAD("==============W ํŽธ์˜์ ================"), + RECEIPT_HEAD_PROMOTION("=============์ฆ\t์ •==============="), + RECEIPT_HEAD_ACCOUNT("===================================="), + RETRY_PURCHASE("๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"), + + ERROR_INVALID_FORMAT("[ERROR] ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + + ERROR_NOT_EXIST_PRODUCT("[ERROR] ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + ERROR_OVERFLOW_PURCHASE("[ERROR] ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + ERROR_NO_COUNT_PRODUCT("[ERROR] ์žฌ๊ณ ๊ฐ€ ์—†๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + + private final String message; + + static public final String PURCHASE_PATTERN = "\\[([a-zA-Z๊ฐ€-ํžฃ0-9]+)-(\\d+)]"; + static public final String PURCHASE_LIST_DELIMITER = ","; + static public final String ANSWER_NO = "N"; + static public final String ANSWER_YES = "Y"; + + private StoreViewMessage(String message){ + this.message = message; + } + + public String getMessage() { + return message; + } + + public void printMessage(){ + System.out.println(this.message); + } + + public static void printReceiptFormat(String first, String second, String third){ + final int FIRST_WIDTH = 15; + final int SECOND_WIDTH = 8; + final int THIRD_WIDTH = 10; + System.out.printf("%-" + FIRST_WIDTH + "s%-" + SECOND_WIDTH + "s%-" + THIRD_WIDTH + "s\n", first, second, third); + } + + public static void printReceiptProductListHead(){ + final String productNameColumn = "์ƒํ’ˆ๋ช…"; + final String countColumn = "์ˆ˜๋Ÿ‰"; + final String priceColumn = "๊ธˆ์•ก"; + printReceiptFormat(productNameColumn,countColumn,priceColumn); + } + + public static void printProduct(String ProductName, int price, int count, String promotionName){ + final String format = "- %s %,d์› %d๊ฐœ %s\n"; + System.out.printf(format,ProductName,price,count,promotionName); + } + + public static void printInsufficientProduct(String ProductName, int price, String promotionName){ + final String format = "- %s %,d์› ์žฌ๊ณ  ์—†์Œ %s\n"; + System.out.printf(format,ProductName,price,promotionName); + } + + public static void printPromotionReturnAvailable(String productName){ + String format = "ํ˜„์žฌ %s์€(๋Š”) 1๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)\n"; + System.out.printf(format,productName); + } + + public static void printPromotionWarning(String productName,int count) { + String format = "ํ˜„์žฌ %s %d๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)\n"; + System.out.printf(format, productName, count); + } +}
Java
๊ทธ๋Ÿฐ๋ฐ ์—ฌ๊ธฐ์„œ ์„ ์–ธ๋œ ์ƒ์ˆ˜๋“ค์€ ์ „์—ญ์—์„œ ์‚ฌ์šฉํ•˜์‹ค ๋ชฉ์ ์œผ๋กœ ์„ ์–ธํ•˜์‹  ๊ฑด์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค! ์ €๋Š” `enum`ํด๋ž˜์Šค์—์„œ ๋”ฐ๋กœ ์ƒ์ˆ˜๋กœ ์„ ์–ธํ•˜๋Š” ๋ถ€๋ถ„์€, ํ•ด๋‹น enum ํŒŒ์ผ ๋‚ด์—์„œ ์‚ฌ์šฉ๋˜๋Š” ๊ฒƒ์ด ๋ชฉ์ ์ด๋ผ๊ณ  ์ƒ๊ฐํ–ˆ๊ฑฐ๋“ ์š”, ํ•ด๋‹น ์ƒ์ˆ˜๋“ค์„ ์„ ์–ธํ•˜๋Š” ํด๋ž˜์Šค๋ฅผ ๋”ฐ๋กœ ๋ถ„๋ฆฌํ•˜๊ฑฐ๋‚˜, ์œ„์˜ ๋ฉ”์‹œ์ง€๋“ค๊ณผ ๊ฐ™์ด `enum ์ƒ์ˆ˜`๋กœ ์ƒ์„ฑํ•ด๋„ ๊ดœ์ฐฎ์„ ๊ฒƒ ๊ฐ™์€๋ฐ, ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”? +) ๋‹ค๋ฅธ ๋ถ„๋“ค์˜ ์ฝ”๋“œ ์ค‘์—์„œ "Y", "N"๋ฅผ ํ•˜๋‚˜์˜ enum์œผ๋กœ ๊ตฌ๋ถ„ํ•˜์‹  ๊ฒฝ์šฐ๋„ ์žˆ๋”๋ผ๊ตฌ์š”!
@@ -0,0 +1,32 @@ +package store.io; + +public enum ProductFile { + NAME(0,"name",String.class), + PRICE(1,"price",Integer.class), + QUANTITY(2,"quantitiy",Integer.class), + PROMOTION(3,"promotion",String.class); + + private int columnIdx; + private String columName; + private Class<?> type; + + static final public String COLUMN_DELIMITER = ","; + + private ProductFile(int colunmIdx, String columName, Class<?> type){ + this.columName = columName; + this.columnIdx = colunmIdx; + this.type = type; + } + + public int getColumnIdx(){ + return this.columnIdx; + } + + public String getColumName(){ + return this.columName; + } + + public Class<?> getType(){ + return this.type; + } +}
Java
`enum`์„ ์ด๋ ‡๊ฒŒ๋„ ์‚ฌ์šฉํ•  ์ˆ˜๊ฐ€ ์žˆ๋„ค์š”! ์ข‹์€ ๋ฐฉ๋ฒ• ์•Œ์•„๊ฐ‘๋‹ˆ๋‹ค๐Ÿ‘
@@ -0,0 +1,191 @@ +package store.product; + +import java.time.LocalDateTime; +import java.util.Objects; +import store.product.promotion.Promotion; +import store.product.promotion.PromotionResult; +import store.product.promotion.PromotionState; +import store.utils.ExceptionFactory; +import store.utils.ExceptionType; +import camp.nextstep.edu.missionutils.DateTimes; + +public class Product implements Cloneable{ + + public static final String NO_PROMOTION = null; + private String name; + private int price; + private Promotion promotion = Promotion.NULL; + private String promotionName = NO_PROMOTION; + private int count; + + public Product(){ + + } + + public Product(Product src){ + this.name = src.name; + this.price = src.price; + this.count = src.count; + if(src.promotion != Promotion.NULL) { + this.promotion = src.promotion.clone(); + this.promotionName = src.promotionName; + } + } + + public Product(String name, int price, int count,String promotionName){ + this.name = name; + this.price = price; + this.count = count; + if(promotionName != Product.NO_PROMOTION){ + this.promotionName = promotionName; + } + } + + public int getPrice() { + return price; + } + + public String getName(){ + return name; + } + + public int getCount(){ + return count; + } + + public String getPromotionName(){ + return promotionName; + } + + public Promotion getPromotion(){ + return promotion.clone(); + } + + public void setPromotion(String name, LocalDateTime start , LocalDateTime end, int conditionCount){ + if(this.promotion != Promotion.NULL){ + throw new IllegalStateException("Promotion is already exist."); + } + + if(!this.promotionName.equals(name)){ + throw new IllegalStateException("Promotion is not correspond to promotionName field"); + } + this.promotion = new Promotion(name,start,end,conditionCount); + } + + public void setPromotion(Promotion promotion){ + if(this.promotion != Promotion.NULL){ + throw new IllegalStateException("Promotion is already exist."); + } + if(promotion == Promotion.NULL){ + return; + } + this.promotion = new Promotion(promotion); + } + + public boolean isPromotionActive(LocalDateTime today){ + if(!isPromotionExist()){ + return false; + } + return this.promotion.isActive(today); + } + + public boolean isBuyEnable(){ + int zero = 0; + return this.count > zero; + } + + @Override + public Product clone(){ + try { + Product cloned = (Product) super.clone(); + cloned.clonePromotion(this); + return cloned; + }catch (CloneNotSupportedException e){ + throw new AssertionError("Cloning not supported"); + } + + } + + public void clonePromotion(Product origin){ + if(origin.promotion != Promotion.NULL) { + this.promotion = origin.promotion; + } + } + + public Receipt buy(int count){ + decreaseCount(count); + + return new Receipt(name, + this.calculateTotalPrice(count), + this.calculateDiscountPrice(count), + this.price, + calculateNonPromotedCount(count) + ); + } + + public int calculateNonPromotedCount(int buyCount){ + int nonPromotedCount = buyCount; + int zero = 0; + if(this.calculateDiscountPrice(buyCount) > zero){ + int promotionUnit= this.getPromotion().getConditionCount() + Promotion.RETURN_COUNT; + nonPromotedCount = buyCount % promotionUnit; + } + + return nonPromotedCount; + } + + public PromotionResult estimatePromotionResult(int count, LocalDateTime now){ + if(this.isPromotionExist() && this.isPromotionActive(now)) { + return this.promotion.estimate(name,count); + } + + return PromotionResult.createNoPromotion(name,count); + } + + public int calculateMaxCountToBuy(int buyCount){ + if(count < buyCount){ + return count; + } + + return buyCount; + } + + public boolean isEnoughToBuy(int buyCount){ + return count > buyCount; + } + + public boolean isPromotionExist(){ + boolean isPromotionNotNull = this.promotion != Promotion.NULL; + boolean isPromotionNameExist = this.promotionName != NO_PROMOTION; + if(isPromotionNotNull != isPromotionNameExist){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + return isPromotionNotNull; + } + + public boolean isInsufficient(){ + int zero = 0; + return count == zero; + } + + private void decreaseCount(int count){ + if(count > this.count){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + this.count -=count; + } + + private int calculateTotalPrice(int count){ + return this.price*count; + } + + private int calculateDiscountPrice(int count){ + int result = 0; + if(isPromotionActive(DateTimes.now())){ + result = this.promotion.checkReturn(count) * this.price; + } + + return result; + } + +}
Java
์ด๋ ‡๊ฒŒ ํ•˜๋ฉด `getter`๋กœ ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•ด๋„ ์›๋ณธ ๊ฐ’์ด ์˜ค์—ผ๋  ์œ„ํ—˜์ด ์ ๊ฒ ๋„ค์š”! ์ข‹์€ ๋ฐฉ๋ฒ• ์•Œ์•„๊ฐ‘๋‹ˆ๋‹ค๐Ÿ‘
@@ -0,0 +1,58 @@ +package store.product; + +import store.product.promotion.PromotionState; +import store.utils.ExceptionFactory; +import store.utils.ExceptionType; +import store.utils.Validator; + +public class PurchaseRequest { + private String productName; + private int countPurchased; + private PromotionState promotionState; + public PurchaseRequest(){ + + } + + public PurchaseRequest(String productName, int countPurchased, PromotionState promotionState){ + this.countPurchased = countPurchased; + this.productName = productName; + this.promotionState = promotionState; + } + + public String getProductName(){ + return this.productName; + } + public int getCountPurchased(){ + return this.countPurchased; + } + + public PromotionState getPromotionState(){ + return this.promotionState; + } + + public void increaseCount(int value){ + Validator.validatePositiveNumber(value); + this.countPurchased += value; + } + + public PurchaseRequest tryToIncrease(boolean isIncrease){ + int step = 1; + if(isIncrease){ + this.increaseCount(step); + return this; + } + return this; + } + + public void decreaseCount(int value){ + if(value > this.countPurchased){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + this.countPurchased -=value; + } + + public boolean isCountMet(){ + int zero = 0; + return this.countPurchased == zero; + } +}
Java
`public` ๊ธฐ๋ณธ ์ƒ์„ฑ์ž๋ฅผ ์„ ์–ธํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,71 @@ +package store.product.promotion; + + +import store.utils.ExceptionFactory; +import store.utils.ExceptionType; + +public class PromotionResult { + + private int appliedItemCount = 0; + private int omittedItemCount = 0; + private int totalItemCount = 0; + private PromotionState state; + private String productName; + + public PromotionResult(){ + + } + + public PromotionResult(PromotionState state, int totalItemCount,int appliedItemCount, int omittedItemCount, String productName){ + this.state = state; + this.totalItemCount = totalItemCount; + this.appliedItemCount = appliedItemCount; + this.omittedItemCount = omittedItemCount; + this.productName = productName; + + } + +// public void setAppliedItemCount(int appliedItemCount) { +// this.appliedItemCount = appliedItemCount; +// } +// +// public void setNeededItemCount(int enableItemCount) { +// this.omittedItemCount = enableItemCount; +// } + + public int getAppliedItemCount() { + return appliedItemCount; + } + + public int getOmittedItemCount() { + return omittedItemCount; + } + + public int getTotalItemCount() { return totalItemCount;} + + public int getNonPromotedCount() { + int fullPromotedCount = totalItemCount + omittedItemCount; + int appliedCountWhenFullPromoted = appliedItemCount + 1; + int zero = 0; + if(fullPromotedCount% appliedCountWhenFullPromoted != zero){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + int promotionUnit = fullPromotedCount/appliedCountWhenFullPromoted; + return totalItemCount % promotionUnit; + } + + public PromotionState getState() { return state; } + + public String getProductName() {return productName;} + + public PromotionResult transitState(PromotionState newState){ + return new PromotionResult(newState,totalItemCount,appliedItemCount,omittedItemCount,productName); + } + + static public PromotionResult createNoPromotion(String productName,int totalItemCount){ + final int zero = 0; + return new PromotionResult(PromotionState.NO_PROMOTION,totalItemCount,zero,zero,productName); + } + + +}
Java
์ €๋Š” ๋ฉ”์„œ๋“œ ๋ฐ”๋””๊ฐ€ ํ•œ ์ค„์ด์–ด๋„ ๊ฐœํ–‰์„ ํ•ด์ฃผ๋Š” ๊ฒƒ์ด ๊ฐ€๋…์„ฑ์— ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค! @armcortex3445 ๋‹˜ ์˜๊ฒฌ์€ ์–ด๋– ์‹ ๊ฐ€์š”? ๊ทธ๋ฆฌ๊ณ  ๊ณต๋ฐฑ๋„ ์กฐ๊ธˆ ๋” ์‹ ๊ฒฝ์จ์ฃผ์‹œ๋ฉด ๊ฐ€๋…์„ฑ์ด ๋” ์ข‹์•„์งˆ ๊ฒƒ ๊ฐ™๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค! ```java public PromotionState getState() { return state; } public String getProductName() { return productName; } ```
@@ -0,0 +1,10 @@ +package store.product.promotion; + +public enum PromotionState { + APPLIED, + OMISSION, + + NO_PROMOTION, + INSUFFICIENT, + NONE; +}
Java
Promotion์˜ ์ƒํƒœ๋ฅผ ์ด๋ ‡๊ฒŒ ๊ด€๋ฆฌํ•  ์ˆ˜๋„ ์žˆ๊ฒ ๋„ค์š”! ์ข‹์€ ๋ฐฉ๋ฒ• ์•Œ์•„๊ฐ‘๋‹ˆ๋‹ค๐Ÿ‘
@@ -0,0 +1,80 @@ +package store; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.List; +import store.io.ProductFile; +import store.io.PromotionFile; +import store.product.Product; +import store.utils.ExceptionFactory; +import store.utils.ExceptionType; +import store.utils.Transformer; +import store.utils.Validator; + +public class LoadModel { + public final static String PRODUCT_LIST_FORMAT = "name,price,quantity,promotion"; + public final static String PROMOTION_LIST_FROMAT= "name,buy,get,start_date,end_date"; + public final static String DELIMITER = "\n"; + final static String RESOURCE_PATH = "./src/main/resources/"; + final static String PRODUCT_LIST = "products.md"; + final static String PROMOTION_LIST = "promotions.md"; + public LoadModel(){ + } + + public String loadProductList(){ + String result = readFileAsString(RESOURCE_PATH + PRODUCT_LIST); + validateProductList(result); + return result; + } + + public String loadPromotionList(){ + String result = readFileAsString(RESOURCE_PATH + PROMOTION_LIST); + validatePromotionList(result); + return result; + } + + public List<String> readFile(String path){ + Validator.validateFileSize(path); + try { + return Files.readAllLines(Paths.get(path)); + } catch (IOException exception){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.READ_FILE_FAIL,exception); + throw new RuntimeException(); + } + } + + public String readFileAsString(String path){ + + List<String> contents = readFile(path); + if(contents.isEmpty()) { + ExceptionFactory.throwIllegalArgumentException(ExceptionType.EMPTY_FILE); + } + return Transformer.concatenateList(contents,DELIMITER); + } + + public static void validateProductList(String products){ + if(products.isBlank()) { + ExceptionFactory.throwIllegalArgumentException(ExceptionType.EMPTY_FILE); + } + List<String> productList = Arrays.stream(products.split(DELIMITER)).toList(); + if(!productList.getFirst().equals(PRODUCT_LIST_FORMAT)){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_FILE_FORMAT); + } + Validator.validateEachLine(productList, ProductFile.COLUMN_DELIMITER,ProductFile.values().length); + } + + public static void validatePromotionList(String promotions){ + if(promotions.isBlank()) { + ExceptionFactory.throwIllegalArgumentException(ExceptionType.EMPTY_FILE); + } + List<String> promotionList = Arrays.stream(promotions.split(DELIMITER)).toList(); + if(!promotionList.getFirst().equals(PROMOTION_LIST_FROMAT)){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_FILE_FORMAT); + } + Validator.validateEachLine(promotionList,PromotionFile.COLUMN_DELIMITER,PromotionFile.values().length); + } + + +}
Java
๋ง์”€ํ•˜์‹  ๋ฐฉ๋ฒ•์ด OS ํ”Œ๋žซํผ ๋…๋ฆฝ์ ์ด์–ด์„œ ํ™•์žฅ์„ฑ๊ณผ ์žฌ์‚ฌ์šฉ์„ฑ ๊ทธ๋ฆฌ๊ณ  ์•ˆ์ •์„ฑ์ด ๋†’์€ ์ฝ”๋“œ๋ผ ์ƒ๊ฐ๋ฉ๋‹ˆ๋‹ค. ์ข‹์€ ์ข‹์–ธ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,80 @@ +package store; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.List; +import store.io.ProductFile; +import store.io.PromotionFile; +import store.product.Product; +import store.utils.ExceptionFactory; +import store.utils.ExceptionType; +import store.utils.Transformer; +import store.utils.Validator; + +public class LoadModel { + public final static String PRODUCT_LIST_FORMAT = "name,price,quantity,promotion"; + public final static String PROMOTION_LIST_FROMAT= "name,buy,get,start_date,end_date"; + public final static String DELIMITER = "\n"; + final static String RESOURCE_PATH = "./src/main/resources/"; + final static String PRODUCT_LIST = "products.md"; + final static String PROMOTION_LIST = "promotions.md"; + public LoadModel(){ + } + + public String loadProductList(){ + String result = readFileAsString(RESOURCE_PATH + PRODUCT_LIST); + validateProductList(result); + return result; + } + + public String loadPromotionList(){ + String result = readFileAsString(RESOURCE_PATH + PROMOTION_LIST); + validatePromotionList(result); + return result; + } + + public List<String> readFile(String path){ + Validator.validateFileSize(path); + try { + return Files.readAllLines(Paths.get(path)); + } catch (IOException exception){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.READ_FILE_FAIL,exception); + throw new RuntimeException(); + } + } + + public String readFileAsString(String path){ + + List<String> contents = readFile(path); + if(contents.isEmpty()) { + ExceptionFactory.throwIllegalArgumentException(ExceptionType.EMPTY_FILE); + } + return Transformer.concatenateList(contents,DELIMITER); + } + + public static void validateProductList(String products){ + if(products.isBlank()) { + ExceptionFactory.throwIllegalArgumentException(ExceptionType.EMPTY_FILE); + } + List<String> productList = Arrays.stream(products.split(DELIMITER)).toList(); + if(!productList.getFirst().equals(PRODUCT_LIST_FORMAT)){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_FILE_FORMAT); + } + Validator.validateEachLine(productList, ProductFile.COLUMN_DELIMITER,ProductFile.values().length); + } + + public static void validatePromotionList(String promotions){ + if(promotions.isBlank()) { + ExceptionFactory.throwIllegalArgumentException(ExceptionType.EMPTY_FILE); + } + List<String> promotionList = Arrays.stream(promotions.split(DELIMITER)).toList(); + if(!promotionList.getFirst().equals(PROMOTION_LIST_FROMAT)){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_FILE_FORMAT); + } + Validator.validateEachLine(promotionList,PromotionFile.COLUMN_DELIMITER,PromotionFile.values().length); + } + + +}
Java
์ฒซ ์ค„์„ ๊ทธ๋ƒฅ ์Šคํ‚ตํ•˜๊ธฐ ๋ณด๋‹ค๋Š”, ๊ฐ ํ”Œ๋žซํผ(products.md ํŒŒ์ผ ํ˜•์‹)์— ๋งž๊ฒŒ ํด๋ž˜์Šค๋ฅผ ์„ ์–ธํ•˜์—ฌ ๊ด€๋ฆฌํ•˜๋Š”๊ฒŒ ์•ˆ์ •์„ฑ์ด ๋†’์ง€ ์•Š์„๊นŒ ์ƒ๊ฐ๋ฉ๋‹ˆ๋‹ค. ์ฒซ ์ค„์ด product.md์˜ ํ˜•์‹์„ ์˜๋ฏธํ•œ๋‹ค๊ณ  ์ƒ๊ฐ๋˜๋Š”๋ฐ์š”. ๊ณผ์ œ์—์„œ๋Š” ๊ฐ ํ–‰์˜ ์—ด์ด๋ฆ„์„ ๋‚˜ํƒ€๋‚ด์ง€๋งŒ, ๋‹ค๋ฅธ ํ”Œ๋žซํผ์—์„œ๋Š” ์—ด ์ด๋ฆ„ ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ๋„ ํฌํ•จ๋  ์ˆ˜ ๋„ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐ๋ฉ๋‹ˆ๋‹ค. ๋˜ํ•œ, ์ฒซ ์ค„์ด ๋‹ฌ๋ผ์ง€๋ฉด, ํŒŒ์‹ฑ ๋ฐ ์œ ํšจ์„ฑ ๊ฒ€์ฆ ๋กœ์ง๋„ ๋‹ฌ๋ผ์งˆ ๊ฑฐ๋ผ ์ƒ๊ฐ๋ฉ๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ, ํ”Œ๋žซํผ ์˜์กดํ•˜์—ฌ ์•Œ๋งž์€ ๋กœ์ง์ด ๋™์ž‘ํ•˜๋„๋ก ํ•˜๋Š” ๊ฒŒ ์ค‘์š”ํ•˜๊ณ , ์ฒซ์ค„์„ ์ฝ์–ด์„œ ํ”Œ๋žซํผ ํŒŒ์ผ ํ˜•์‹ ์œ ํšจ์„ฑ์„ ๊ฒ€์ฆํ•˜๋Š” ๊ฒƒ์ด ์ œ๊ฐ€ ์„ ํƒํ•  ๋ฐฉ์‹์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,196 @@ +package store; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import camp.nextstep.edu.missionutils.Console; +import store.product.PurchaseRequest; +import store.product.promotion.PromotionResult; +import store.product.promotion.PromotionState; +import store.utils.ExceptionFactory; +import store.utils.ExceptionType; +import store.utils.Transformer; +import store.utils.Validator; + +public class StoreInputView { + static final Pattern PURCHASE_PATTERN = Pattern.compile(StoreViewMessage.PURCHASE_PATTERN); + + public List<PurchaseRequest> readPurchaseProduct(){ + StoreViewMessage.PURCHASE_GUIDE.printMessage(); + String purchaseList = Console.readLine(); + try { + return createPurchaseRequests(purchaseList); + }catch (IllegalArgumentException exception){ + StoreViewMessage.ERROR_INVALID_FORMAT.printMessage(); + return readPurchaseProduct(); + } + } + + public List<PurchaseRequest> retryReadPurchaseProduct(List<StoreViewMessage> errorMessages){ + for(StoreViewMessage message : errorMessages){ + message.printMessage(); + } + return readPurchaseProduct(); + } + + public List<PurchaseRequest> readAnswerPurchaseChange(List<PromotionResult> promotionResults){ + List<PurchaseRequest> newPurchaseRequest = new ArrayList<>(); + for(PromotionResult promotionResult : promotionResults){ + newPurchaseRequest.add(handlePromotionResults(promotionResult)); + } + + return newPurchaseRequest; + } + + public PurchaseRequest handlePromotionResults(PromotionResult promotionResult){ + if(promotionResult.getState().equals(PromotionState.OMISSION)) { + return readPromotionEnableProduct(promotionResult); + } + if(promotionResult.getState().equals(PromotionState.INSUFFICIENT)){ + return readPromotionInsufficient(promotionResult); + } + return new PurchaseRequest(promotionResult.getProductName(),promotionResult.getTotalItemCount(),promotionResult.getState()); + } + + public PurchaseRequest readPromotionInsufficient(PromotionResult promotionResult){ + PurchaseRequest newRequest = null; + String answer =readAnswerPromotionInSufficient(promotionResult); + + if(answer.equals(StoreViewMessage.ANSWER_NO)){ + newRequest = new PurchaseRequest(promotionResult.getProductName(),promotionResult.getTotalItemCount(),promotionResult.getState()); + newRequest.decreaseCount(promotionResult.getNonPromotedCount()); + return newRequest; + } + + return new PurchaseRequest(promotionResult.getProductName(),promotionResult.getTotalItemCount(),PromotionState.APPLIED); + } + + public boolean readAnswerContinuePurchase(){ + StoreViewMessage.RETRY_PURCHASE.printMessage(); + String answer = Console.readLine(); + try{ + validateAnswer(answer); + return answer.equals(StoreViewMessage.ANSWER_YES); + }catch (IllegalArgumentException exception){ + StoreViewMessage.ERROR_INVALID_FORMAT.printMessage(); + return readAnswerContinuePurchase(); + } + } + + public boolean readAnswerDiscountApply(){ + StoreViewMessage.MEMBERSHIP_GUIDE.printMessage(); + String answer = Console.readLine(); + try{ + validateAnswer(answer); + return answer.equals(StoreViewMessage.ANSWER_YES); + }catch (IllegalArgumentException exception){ + StoreViewMessage.ERROR_INVALID_FORMAT.printMessage(); + return readAnswerDiscountApply(); + } + } + + + public PurchaseRequest readPromotionEnableProduct(PromotionResult promotionResult){ + PurchaseRequest newRequest = new PurchaseRequest(promotionResult.getProductName(),promotionResult.getTotalItemCount(),PromotionState.APPLIED); + for(int tryCount = 0; tryCount < promotionResult.getOmittedItemCount(); tryCount++){ + String answer = readAnswerPromotionEnable(promotionResult); + newRequest.tryToIncrease(answer.equals(StoreViewMessage.ANSWER_YES)); + } + + return newRequest; + } + + public String readAnswerPromotionInSufficient(PromotionResult promotionResult){ + StoreViewMessage.printPromotionWarning(promotionResult.getProductName(),promotionResult.getNonPromotedCount()); + String answer = Console.readLine(); + try{ + validateAnswer(answer); + return answer; + }catch (IllegalArgumentException exception){ + StoreViewMessage.ERROR_INVALID_FORMAT.printMessage(); + return readAnswerPromotionInSufficient(promotionResult); + } + } + + public String readAnswerPromotionEnable(PromotionResult promotionResult){ + StoreViewMessage.printPromotionReturnAvailable(promotionResult.getProductName()); + String answer = Console.readLine(); + try{ + validateAnswer(answer); + return answer; + }catch (IllegalArgumentException exception){ + StoreViewMessage.ERROR_INVALID_FORMAT.printMessage(); + return readAnswerPromotionEnable(promotionResult); + } + } + + public List<PurchaseRequest> createPurchaseRequests(String purchaseList){ + validatePurchaseList(purchaseList); + List<String> purchases = List.of(purchaseList.split(StoreViewMessage.PURCHASE_LIST_DELIMITER)); + return purchases.stream().map((purchase)->{ + List<String> elements = extractElementsFromPurchase(purchase); + int nameIdx = 0; + int countIdx = 1; + return new PurchaseRequest(elements.get(nameIdx), Transformer.parsePositiveInt(elements.get(countIdx)),PromotionState.NONE); + }).toList(); + } + + + static public void validatePurchaseList(String purchaseList){ + Validator.validateBlankString(purchaseList); + List<String> purchases = List.of(purchaseList.split(StoreViewMessage.PURCHASE_LIST_DELIMITER)); + + for(String purchase : purchases){ + validatePurchase(purchase); + } + + } + + static public void validatePurchase(String purchase){ + + if(!purchase.matches(StoreViewMessage.PURCHASE_PATTERN)){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_INPUT_STRING_FORMAT); + } + try { + validatePurchaseElement(purchase); + }catch (Exception e){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_INPUT_STRING_FORMAT); + } + + } + + static public void validatePurchaseElement(String purchase){ + Matcher matcher = PURCHASE_PATTERN.matcher(purchase); + if(matcher.matches()) { + int productNameGroup = 1; + int countGroup = 2; + Validator.validateBlankString(matcher.group(productNameGroup)); + Validator.validatePositiveNumericString(matcher.group(countGroup)); + return; + } + ExceptionFactory.throwIllegalStateException(ExceptionType.INVALID_INPUT_STRING_FORMAT); + + + } + + static public List<String> extractElementsFromPurchase(String purchase){ + Matcher matcher = PURCHASE_PATTERN.matcher(purchase); + if(matcher.matches()){ + int nameGroup = 1; + int countGroup = 2; + return List.of(matcher.group(nameGroup), matcher.group(countGroup)); + } + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_INPUT_STRING_FORMAT); + throw new RuntimeException(); + } + + static public void validateAnswer(String answer){ + Validator.validateBlankString(answer); + if(!(answer.equals(StoreViewMessage.ANSWER_NO) + || answer.equals(StoreViewMessage.ANSWER_YES))) { + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_INPUT_STRING_FORMAT); + } + } + +}
Java
์กฐ์–ธํ•˜์‹  ๋ฐฉํ–ฅ์ด ๊ธฐ๋Šฅ ๊ด€๋ฆฌ ๋ฐ ์žฌ์‚ฌ์šฉ์„ฑ์ด ํ–ฅ์ƒ๋ ๊ฑฐ๋ผ ์ƒ๊ฐ๋˜๋„ค์š”! InputView์—์„œ ์ž…๋ ฅ๊ฐ’ ์ฝ๊ธฐ ์ด์™ธ์˜ ๋„ˆ๋ฌด ๋งŽ์€ ๋กœ์ง์ด ์žˆ๋„ค์š”.
@@ -0,0 +1,371 @@ +package store; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import store.io.ProductFile; +import store.io.PromotionFile; +import store.product.Product; +import store.product.PurchaseRequest; +import store.product.Receipt; +import store.product.promotion.Promotion; +import store.product.promotion.PromotionResult; +import store.product.promotion.PromotionState; +import store.utils.ExceptionFactory; +import store.utils.ExceptionType; +import store.utils.Transformer; + +public class StoreModel { + static private final Product NOT_FOUND = null; + private final List<Product> productRepository; + private final HashMap<String,Promotion> promotionHashMap; + final static String NAME_REGULAR_EXPRESSION = "^[a-zA-Z๊ฐ€-ํžฃ0-9]+$"; + final static Pattern NAME_PATTERN = Pattern.compile(StoreModel.NAME_REGULAR_EXPRESSION); + + StoreModel(){ + this.productRepository = new ArrayList<>(); + this.promotionHashMap = new HashMap<>(); + } + + public void initStore(List<Product> products, List<Promotion> promotions){ + addProducts(products); + putPromotion(promotions); + applyPromotions(); + } + + private void addProducts(List<Product> products){ + for(Product origin : products){ + this.productRepository.add(origin.clone()); + } + checkInitProduct(this.productRepository); + } + + public void checkInitProduct(List<Product> products){ + for(Product product : products){ + validateSameProductsHaveSamePrice(product); + } + } + + public void validateSameProductsHaveSamePrice(Product product){ + List<Product> finds = findProduct(product.getName()); + int price = 0; + for(Product find : finds){ + price += find.getPrice(); + } + int averagePrice = price / finds.size(); + if(finds.getFirst().getPrice() != averagePrice){ + System.out.println("[Error] ๋™์ผ ์ด๋ฆ„์˜ ์ƒํ’ˆ์€ ๊ฐ€๊ฒฉ์ด ๊ฐ™์•„์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์ž˜๋ชป๋œ ์ƒํ’ˆ :" + product.getName()); + ExceptionFactory.throwIllegalStateException(ExceptionType.INVALID_FILE_FORMAT); + } + } + + private void putPromotion(List<Promotion> promotions){ + /*TODO + - ํ”„๋กœ๋ชจ์…˜ ์ด๋ฆ„ ์ค‘๋ณต์ด ์—†๋„๋ก ํ•ด์•ผํ•จ. + - ๋‚ ์งœ๊ฐ€ ๋‹ค๋ฅด๋”๋ผ๋„, ์ด๋ฆ„ ์ค‘๋ณต์ด ์—†๋„๋ก ํ•ด์•ผํ•จ. + - ํ”„๋กœ๋ชจ์…˜ ์ค‘๋ณต์ด ์žˆ๋Š” ๊ฒฝ์šฐ, promotions.md ํŒŒ์ผ์ด ๋ฌธ์ œ์ด๋ฏ€๋กœ ํ•ด๋‹น ํŒŒ์ผ์—์„œ ํ™•์ธ ํ•„์š”. + * */ + for(Promotion promotion : promotions){ + this.promotionHashMap.put(promotion.getName(),promotion.clone()); + } + } + + private void applyPromotions(){ + for(Product product : this.productRepository){ + product.setPromotion(this.promotionHashMap.get(product.getPromotionName())); + } + } + + public List<Product> getProducts(){ + List<Product> copied = new ArrayList<>(); + for(Product origin : this.productRepository){ + copied.add(origin.clone()); + } + + return copied; + } + + /*TODO + - ์ ‘๊ทผ์ง€์‹œ์ž, static ํ‚ค์›Œ๋“œ ๊ธฐ์ค€์œผ๋กœ ๋ฉ”์†Œ๋“œ ์ •๋ ฌํ•˜๊ธฐ + * */ + public Product findOneProduct(String name, boolean isPromoted){ + return this.findOneOriginProduct(name,isPromoted).clone(); + } + + public List<Product> findProduct(String name){ + return this.findProductOrigin(name).stream() + .map(Product::clone) + .toList(); + } + + public Product findOneOriginProduct(String name, boolean isPromoted){ + if(isPromoted){ + return findProductPromoted(name); + } + return findProductNonPromoted(name); + } + + public List<Product> findProductOrigin(String name){ + return this.productRepository.stream() + .filter((product)->product.getName().equals(name)) + .collect(Collectors.toList()); + } + + private Product findProductPromoted(String name){ + List<Product> finds = findProductOrigin(name).stream() + .filter((product -> product.getPromotionName()!=null)) + .toList(); + validateFindList(finds); + if(finds.isEmpty()){ + return NOT_FOUND; + } + return finds.getFirst(); + } + + private Product findProductNonPromoted(String name){ + List<Product> finds = findProductOrigin(name).stream() + .filter(product -> product.getPromotionName() == Product.NO_PROMOTION) + .toList(); + validateFindList(finds); + if(finds.isEmpty()){ + return NOT_FOUND; + } + return finds.getFirst(); + } + + private void validateFindList(List<?> finds){ + int limit = 1; + if(finds.size() > limit){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + } + + /*TODO + * - promotion๊ณผ product ์ƒ์„ฑ ๊ด€๋ จ static ํ•จ์ˆ˜๋ฅผ ๋‹ค๋ฅธ ํด๋ž˜์Šค์— ์ฑ…์ž„ ๋งก๊ธธ ๊ฒƒ์œผ ๊ณ ๋ คํ•˜๊ธฐ + * - promotion๊ณผ product ์ƒ์„ฑ์‹œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ ๊ณ ๋ ค + * - ์ž˜๋ชป๋œ ํƒ€์ž… ์ž…๋ ฅ + * - ์ž˜๋ชป๋œ ํ˜•์‹ ์ž…๋ ฅ + * */ + + static public List<String> parseString(String string){ + if (string == null || string.isBlank()) { + throw new IllegalArgumentException("List is empty"); + } + final String delimiter = ","; + String[] parsed = string.split(delimiter); + + return List.of(parsed); + } + + static public Product createProduct(String rawProduct){ + List<String> parsedRawProduct = StoreModel.parseString(rawProduct); + String name = parsedRawProduct.get(ProductFile.NAME.getColumnIdx()); + String price = parsedRawProduct.get(ProductFile.PRICE.getColumnIdx()); + String quantity = parsedRawProduct.get(ProductFile.QUANTITY.getColumnIdx()); + String promotion = parsedRawProduct.get(ProductFile.PROMOTION.getColumnIdx()); + validateNameFormat(name); + if(promotion.equals("null")){ + promotion = null; + } + return new Product(name, Transformer.parsePositiveInt(price),Transformer.parseNonNegativeNumber(quantity),promotion); + } + + static public List<Product> createProducts(String rawProductList){ + List<Product> products = new ArrayList<>(); + String[] rawProducts = rawProductList.split("\n"); + + int idx = 1; + + for( ; idx < rawProducts.length; idx++){ + String rawProduct = rawProducts[idx]; + products.add(StoreModel.createProduct(rawProduct)); + } + return products; + } + static public void validateNameFormat(String name){ + Matcher matcher = NAME_PATTERN.matcher(name); + if(!matcher.matches()){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_NAME_FORMAT); + } + } + + static public Promotion createPromotion(String rawPromotion){ + List<String> parsedRawPromotion = StoreModel.parseString(rawPromotion); + String name = parsedRawPromotion.get(PromotionFile.NAME.getColumnIdx()); + String buyCount = parsedRawPromotion.get(PromotionFile.BUY.getColumnIdx()); + String returnCount = parsedRawPromotion.get(PromotionFile.GET.getColumnIdx()); + String startDate = parsedRawPromotion.get(PromotionFile.START_DATE.getColumnIdx()); + String endDate = parsedRawPromotion.get(PromotionFile.END_DATE.getColumnIdx()); + Promotion.validateReturnCount(returnCount); + return new Promotion(name, Transformer.parseStartDate(startDate,PromotionFile.DATE_TIME_FORMATTER),Transformer.parseEndDate(endDate,PromotionFile.DATE_TIME_FORMATTER),Transformer.parsePositiveInt(buyCount)); + } + + static public List<Promotion> createPromotions(String rawPromotionList){ + List<Promotion> promotions = new ArrayList<>(); + String[] rawPromotions = rawPromotionList.split("\n"); + + int idx = 1; + + for( ; idx < rawPromotions.length; idx++){ + String rawPromotion = rawPromotions[idx]; + promotions.add(StoreModel.createPromotion(rawPromotion)); + } + return promotions; + } + + public List<StoreViewMessage> checkPurchaseRequests(List<PurchaseRequest> requests) { + List<StoreViewMessage> messageBox = new ArrayList<>(); + + for(PurchaseRequest request : requests){ + checkPurchaseRequest(request,messageBox); + } + + return messageBox; + } + + public void checkPurchaseRequest(PurchaseRequest request, List<StoreViewMessage> messageBox){ + checkPurchaseProductExist(request,messageBox); + checkPurchaseProductCount(request,messageBox); + + } + + public void checkPurchaseProductExist(PurchaseRequest request, List<StoreViewMessage> messageBox){ + List<Product> finds = findProduct(request.getProductName()); + if(finds.isEmpty()){ + messageBox.add(StoreViewMessage.ERROR_NOT_EXIST_PRODUCT); + } + } + + public void checkPurchaseProductCount(PurchaseRequest request, List<StoreViewMessage> messageBox){ + List<Product> finds = findProduct(request.getProductName()); + int zero = 0; + int totalCount = finds.stream().map(Product::getCount).reduce(zero,Integer::sum); + if(totalCount == zero){ + messageBox.add(StoreViewMessage.ERROR_NO_COUNT_PRODUCT); + } + if(totalCount != zero && totalCount < request.getCountPurchased()){ + messageBox.add(StoreViewMessage.ERROR_OVERFLOW_PURCHASE); + } + } + + public List<PromotionResult> checkPromotionAvailable(List<PurchaseRequest> purchaseRequests){ + List<PromotionResult> promotionResults = new ArrayList<>(); + for(PurchaseRequest request : purchaseRequests){ + promotionResults.addAll(checkPromotionBoth(request.getProductName(),request.getCountPurchased())); + } + + return promotionResults; + } + + public List<PromotionResult> checkPromotionBoth(String productName , int buyCount){ + PromotionResult resultPromotion = checkProductPromotionAvailable(productName,buyCount); + PromotionResult resultNonPromotion = null; + + Product product = findProductNonPromoted(productName); + if(findProductPromoted(productName) == NOT_FOUND){ + resultNonPromotion = PromotionResult.createNoPromotion(productName,buyCount); + return List.of(resultNonPromotion); + } + + if(resultPromotion.getState()==PromotionState.INSUFFICIENT + && resultPromotion.getTotalItemCount() < buyCount){ + int remainCountToBuy = buyCount - resultPromotion.getTotalItemCount(); + resultNonPromotion = PromotionResult.createNoPromotion(productName,remainCountToBuy); + return List.of(resultPromotion, resultNonPromotion); + } + + return List.of(resultPromotion); + } + + public PromotionResult checkProductPromotionAvailable(String productName, int buyCount){ + Product product = findProductPromoted(productName); + if(findProductPromoted(productName) == NOT_FOUND){ + return PromotionResult.createNoPromotion(productName,buyCount); + } + if(product.isEnoughToBuy(buyCount)){ + return product.estimatePromotionResult(buyCount, DateTimes.now()); + } + + int maxCountToBuyPromotion = product.calculateMaxCountToBuy(buyCount); + PromotionResult promotionResult = product.estimatePromotionResult(maxCountToBuyPromotion,DateTimes.now()); + return promotionResult.transitState(PromotionState.INSUFFICIENT); + + } + + public List<Receipt> buyProducts(List<PurchaseRequest> purchaseRequests){ + List<Receipt> receipts = new ArrayList<>(); + for(PurchaseRequest request : purchaseRequests){ + receipts.add(buyProduct(request)); + } + return receipts; + } + + public Receipt buyProduct(PurchaseRequest request){ + + if(request.getPromotionState() == PromotionState.NO_PROMOTION){ + return tryBuyProductNonPromoted(request); + } + + Receipt resultPromoted = tryBuyProductPromoted(request); + Receipt resultNonPromoted = tryBuyProductNonPromoted(request); + + return combineReceipt(resultPromoted,resultNonPromoted); + } + + public int calculateDiscount(List<Receipt> receipts){ + /*TODO + * - ํ•ฉ๊ณ„์‚ฐ ๋„์ค‘ ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ ์ ๊ฒ€ ํ•„์š”*/ + final int maxDisCount = 8000; + final double disCountRate = 0.3; + int totalNonPromotedPrice = 0; + for(Receipt receipt : receipts){ + totalNonPromotedPrice += receipt.getNonPromotedPrice(); + } + int disCountPrice = (int)Math.round(disCountRate * totalNonPromotedPrice); + return Math.min(maxDisCount, disCountPrice); + } + + private Receipt combineReceipt(Receipt promoted, Receipt nonPromoted) { + if(!promoted.getProductName().equals(nonPromoted.getProductName())){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + return promoted.combine(nonPromoted); + } + + private Receipt tryBuyProductPromoted(PurchaseRequest request){ + boolean isPromoted = true; + Product product = this.findOneOriginProduct(request.getProductName(),isPromoted); + if(product == NOT_FOUND){ + return Receipt.createEmptyReceipt(request.getProductName()); + } + if(product.getCount() < request.getCountPurchased()){ + int buyCount = product.getCount(); + return buyProduct(product,buyCount,request); + } + return buyProduct(product,request.getCountPurchased(),request); + } + + + private Receipt tryBuyProductNonPromoted(PurchaseRequest request){ + boolean isPromoted = false; + Product product = this.findOneOriginProduct(request.getProductName(),isPromoted); + if(product == NOT_FOUND){ + return Receipt.createEmptyReceipt(request.getProductName()); + } + if(product.getCount() < request.getCountPurchased()){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + return buyProduct(product,request.getCountPurchased(),request); + } + + private Receipt buyProduct(Product product, int buyCount, PurchaseRequest request){ + request.decreaseCount(buyCount); + return product.buy(buyCount); + } + +}
Java
์ €๋Š” ์žฌ์‚ฌ์šฉ์„ฑ ํ™•๋ฅ ์ด ๋†’๊ณ , ๊ฐ’ ์ž์ฒด๋กœ ์˜๋ฏธ๋ฅผ ์•Œ๊ธฐ ํž˜๋“  ๊ฐ’๋“ค์„ ์ƒ์ˆ˜ํ™”ํ•˜์˜€์Šต๋‹ˆ๋‹ค. ๊ฐ์ฒด ๋ ˆํผ๋Ÿฐ์Šค ํƒ€์ž…์— null ์ž์ฒด๋„ ์ถฉ๋ถ„ํžˆ ์˜๋ฏธ๊ฐ€ ์žˆ์ง€๋งŒ, ํ•ด๋‹น ๋ฌธ๋งฅ์—์„œ null์ด ๋ฌด์—‡์„ ์˜๋ฏธํ•˜๋Š”์ง€๋ฅผ ๋ช…ํ™•ํ•˜๊ฒŒ ๋‚˜ํƒ€๋‚ด๋ ค ํ•˜์˜€์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,371 @@ +package store; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import store.io.ProductFile; +import store.io.PromotionFile; +import store.product.Product; +import store.product.PurchaseRequest; +import store.product.Receipt; +import store.product.promotion.Promotion; +import store.product.promotion.PromotionResult; +import store.product.promotion.PromotionState; +import store.utils.ExceptionFactory; +import store.utils.ExceptionType; +import store.utils.Transformer; + +public class StoreModel { + static private final Product NOT_FOUND = null; + private final List<Product> productRepository; + private final HashMap<String,Promotion> promotionHashMap; + final static String NAME_REGULAR_EXPRESSION = "^[a-zA-Z๊ฐ€-ํžฃ0-9]+$"; + final static Pattern NAME_PATTERN = Pattern.compile(StoreModel.NAME_REGULAR_EXPRESSION); + + StoreModel(){ + this.productRepository = new ArrayList<>(); + this.promotionHashMap = new HashMap<>(); + } + + public void initStore(List<Product> products, List<Promotion> promotions){ + addProducts(products); + putPromotion(promotions); + applyPromotions(); + } + + private void addProducts(List<Product> products){ + for(Product origin : products){ + this.productRepository.add(origin.clone()); + } + checkInitProduct(this.productRepository); + } + + public void checkInitProduct(List<Product> products){ + for(Product product : products){ + validateSameProductsHaveSamePrice(product); + } + } + + public void validateSameProductsHaveSamePrice(Product product){ + List<Product> finds = findProduct(product.getName()); + int price = 0; + for(Product find : finds){ + price += find.getPrice(); + } + int averagePrice = price / finds.size(); + if(finds.getFirst().getPrice() != averagePrice){ + System.out.println("[Error] ๋™์ผ ์ด๋ฆ„์˜ ์ƒํ’ˆ์€ ๊ฐ€๊ฒฉ์ด ๊ฐ™์•„์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์ž˜๋ชป๋œ ์ƒํ’ˆ :" + product.getName()); + ExceptionFactory.throwIllegalStateException(ExceptionType.INVALID_FILE_FORMAT); + } + } + + private void putPromotion(List<Promotion> promotions){ + /*TODO + - ํ”„๋กœ๋ชจ์…˜ ์ด๋ฆ„ ์ค‘๋ณต์ด ์—†๋„๋ก ํ•ด์•ผํ•จ. + - ๋‚ ์งœ๊ฐ€ ๋‹ค๋ฅด๋”๋ผ๋„, ์ด๋ฆ„ ์ค‘๋ณต์ด ์—†๋„๋ก ํ•ด์•ผํ•จ. + - ํ”„๋กœ๋ชจ์…˜ ์ค‘๋ณต์ด ์žˆ๋Š” ๊ฒฝ์šฐ, promotions.md ํŒŒ์ผ์ด ๋ฌธ์ œ์ด๋ฏ€๋กœ ํ•ด๋‹น ํŒŒ์ผ์—์„œ ํ™•์ธ ํ•„์š”. + * */ + for(Promotion promotion : promotions){ + this.promotionHashMap.put(promotion.getName(),promotion.clone()); + } + } + + private void applyPromotions(){ + for(Product product : this.productRepository){ + product.setPromotion(this.promotionHashMap.get(product.getPromotionName())); + } + } + + public List<Product> getProducts(){ + List<Product> copied = new ArrayList<>(); + for(Product origin : this.productRepository){ + copied.add(origin.clone()); + } + + return copied; + } + + /*TODO + - ์ ‘๊ทผ์ง€์‹œ์ž, static ํ‚ค์›Œ๋“œ ๊ธฐ์ค€์œผ๋กœ ๋ฉ”์†Œ๋“œ ์ •๋ ฌํ•˜๊ธฐ + * */ + public Product findOneProduct(String name, boolean isPromoted){ + return this.findOneOriginProduct(name,isPromoted).clone(); + } + + public List<Product> findProduct(String name){ + return this.findProductOrigin(name).stream() + .map(Product::clone) + .toList(); + } + + public Product findOneOriginProduct(String name, boolean isPromoted){ + if(isPromoted){ + return findProductPromoted(name); + } + return findProductNonPromoted(name); + } + + public List<Product> findProductOrigin(String name){ + return this.productRepository.stream() + .filter((product)->product.getName().equals(name)) + .collect(Collectors.toList()); + } + + private Product findProductPromoted(String name){ + List<Product> finds = findProductOrigin(name).stream() + .filter((product -> product.getPromotionName()!=null)) + .toList(); + validateFindList(finds); + if(finds.isEmpty()){ + return NOT_FOUND; + } + return finds.getFirst(); + } + + private Product findProductNonPromoted(String name){ + List<Product> finds = findProductOrigin(name).stream() + .filter(product -> product.getPromotionName() == Product.NO_PROMOTION) + .toList(); + validateFindList(finds); + if(finds.isEmpty()){ + return NOT_FOUND; + } + return finds.getFirst(); + } + + private void validateFindList(List<?> finds){ + int limit = 1; + if(finds.size() > limit){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + } + + /*TODO + * - promotion๊ณผ product ์ƒ์„ฑ ๊ด€๋ จ static ํ•จ์ˆ˜๋ฅผ ๋‹ค๋ฅธ ํด๋ž˜์Šค์— ์ฑ…์ž„ ๋งก๊ธธ ๊ฒƒ์œผ ๊ณ ๋ คํ•˜๊ธฐ + * - promotion๊ณผ product ์ƒ์„ฑ์‹œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ ๊ณ ๋ ค + * - ์ž˜๋ชป๋œ ํƒ€์ž… ์ž…๋ ฅ + * - ์ž˜๋ชป๋œ ํ˜•์‹ ์ž…๋ ฅ + * */ + + static public List<String> parseString(String string){ + if (string == null || string.isBlank()) { + throw new IllegalArgumentException("List is empty"); + } + final String delimiter = ","; + String[] parsed = string.split(delimiter); + + return List.of(parsed); + } + + static public Product createProduct(String rawProduct){ + List<String> parsedRawProduct = StoreModel.parseString(rawProduct); + String name = parsedRawProduct.get(ProductFile.NAME.getColumnIdx()); + String price = parsedRawProduct.get(ProductFile.PRICE.getColumnIdx()); + String quantity = parsedRawProduct.get(ProductFile.QUANTITY.getColumnIdx()); + String promotion = parsedRawProduct.get(ProductFile.PROMOTION.getColumnIdx()); + validateNameFormat(name); + if(promotion.equals("null")){ + promotion = null; + } + return new Product(name, Transformer.parsePositiveInt(price),Transformer.parseNonNegativeNumber(quantity),promotion); + } + + static public List<Product> createProducts(String rawProductList){ + List<Product> products = new ArrayList<>(); + String[] rawProducts = rawProductList.split("\n"); + + int idx = 1; + + for( ; idx < rawProducts.length; idx++){ + String rawProduct = rawProducts[idx]; + products.add(StoreModel.createProduct(rawProduct)); + } + return products; + } + static public void validateNameFormat(String name){ + Matcher matcher = NAME_PATTERN.matcher(name); + if(!matcher.matches()){ + ExceptionFactory.throwIllegalArgumentException(ExceptionType.INVALID_NAME_FORMAT); + } + } + + static public Promotion createPromotion(String rawPromotion){ + List<String> parsedRawPromotion = StoreModel.parseString(rawPromotion); + String name = parsedRawPromotion.get(PromotionFile.NAME.getColumnIdx()); + String buyCount = parsedRawPromotion.get(PromotionFile.BUY.getColumnIdx()); + String returnCount = parsedRawPromotion.get(PromotionFile.GET.getColumnIdx()); + String startDate = parsedRawPromotion.get(PromotionFile.START_DATE.getColumnIdx()); + String endDate = parsedRawPromotion.get(PromotionFile.END_DATE.getColumnIdx()); + Promotion.validateReturnCount(returnCount); + return new Promotion(name, Transformer.parseStartDate(startDate,PromotionFile.DATE_TIME_FORMATTER),Transformer.parseEndDate(endDate,PromotionFile.DATE_TIME_FORMATTER),Transformer.parsePositiveInt(buyCount)); + } + + static public List<Promotion> createPromotions(String rawPromotionList){ + List<Promotion> promotions = new ArrayList<>(); + String[] rawPromotions = rawPromotionList.split("\n"); + + int idx = 1; + + for( ; idx < rawPromotions.length; idx++){ + String rawPromotion = rawPromotions[idx]; + promotions.add(StoreModel.createPromotion(rawPromotion)); + } + return promotions; + } + + public List<StoreViewMessage> checkPurchaseRequests(List<PurchaseRequest> requests) { + List<StoreViewMessage> messageBox = new ArrayList<>(); + + for(PurchaseRequest request : requests){ + checkPurchaseRequest(request,messageBox); + } + + return messageBox; + } + + public void checkPurchaseRequest(PurchaseRequest request, List<StoreViewMessage> messageBox){ + checkPurchaseProductExist(request,messageBox); + checkPurchaseProductCount(request,messageBox); + + } + + public void checkPurchaseProductExist(PurchaseRequest request, List<StoreViewMessage> messageBox){ + List<Product> finds = findProduct(request.getProductName()); + if(finds.isEmpty()){ + messageBox.add(StoreViewMessage.ERROR_NOT_EXIST_PRODUCT); + } + } + + public void checkPurchaseProductCount(PurchaseRequest request, List<StoreViewMessage> messageBox){ + List<Product> finds = findProduct(request.getProductName()); + int zero = 0; + int totalCount = finds.stream().map(Product::getCount).reduce(zero,Integer::sum); + if(totalCount == zero){ + messageBox.add(StoreViewMessage.ERROR_NO_COUNT_PRODUCT); + } + if(totalCount != zero && totalCount < request.getCountPurchased()){ + messageBox.add(StoreViewMessage.ERROR_OVERFLOW_PURCHASE); + } + } + + public List<PromotionResult> checkPromotionAvailable(List<PurchaseRequest> purchaseRequests){ + List<PromotionResult> promotionResults = new ArrayList<>(); + for(PurchaseRequest request : purchaseRequests){ + promotionResults.addAll(checkPromotionBoth(request.getProductName(),request.getCountPurchased())); + } + + return promotionResults; + } + + public List<PromotionResult> checkPromotionBoth(String productName , int buyCount){ + PromotionResult resultPromotion = checkProductPromotionAvailable(productName,buyCount); + PromotionResult resultNonPromotion = null; + + Product product = findProductNonPromoted(productName); + if(findProductPromoted(productName) == NOT_FOUND){ + resultNonPromotion = PromotionResult.createNoPromotion(productName,buyCount); + return List.of(resultNonPromotion); + } + + if(resultPromotion.getState()==PromotionState.INSUFFICIENT + && resultPromotion.getTotalItemCount() < buyCount){ + int remainCountToBuy = buyCount - resultPromotion.getTotalItemCount(); + resultNonPromotion = PromotionResult.createNoPromotion(productName,remainCountToBuy); + return List.of(resultPromotion, resultNonPromotion); + } + + return List.of(resultPromotion); + } + + public PromotionResult checkProductPromotionAvailable(String productName, int buyCount){ + Product product = findProductPromoted(productName); + if(findProductPromoted(productName) == NOT_FOUND){ + return PromotionResult.createNoPromotion(productName,buyCount); + } + if(product.isEnoughToBuy(buyCount)){ + return product.estimatePromotionResult(buyCount, DateTimes.now()); + } + + int maxCountToBuyPromotion = product.calculateMaxCountToBuy(buyCount); + PromotionResult promotionResult = product.estimatePromotionResult(maxCountToBuyPromotion,DateTimes.now()); + return promotionResult.transitState(PromotionState.INSUFFICIENT); + + } + + public List<Receipt> buyProducts(List<PurchaseRequest> purchaseRequests){ + List<Receipt> receipts = new ArrayList<>(); + for(PurchaseRequest request : purchaseRequests){ + receipts.add(buyProduct(request)); + } + return receipts; + } + + public Receipt buyProduct(PurchaseRequest request){ + + if(request.getPromotionState() == PromotionState.NO_PROMOTION){ + return tryBuyProductNonPromoted(request); + } + + Receipt resultPromoted = tryBuyProductPromoted(request); + Receipt resultNonPromoted = tryBuyProductNonPromoted(request); + + return combineReceipt(resultPromoted,resultNonPromoted); + } + + public int calculateDiscount(List<Receipt> receipts){ + /*TODO + * - ํ•ฉ๊ณ„์‚ฐ ๋„์ค‘ ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ ์ ๊ฒ€ ํ•„์š”*/ + final int maxDisCount = 8000; + final double disCountRate = 0.3; + int totalNonPromotedPrice = 0; + for(Receipt receipt : receipts){ + totalNonPromotedPrice += receipt.getNonPromotedPrice(); + } + int disCountPrice = (int)Math.round(disCountRate * totalNonPromotedPrice); + return Math.min(maxDisCount, disCountPrice); + } + + private Receipt combineReceipt(Receipt promoted, Receipt nonPromoted) { + if(!promoted.getProductName().equals(nonPromoted.getProductName())){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + return promoted.combine(nonPromoted); + } + + private Receipt tryBuyProductPromoted(PurchaseRequest request){ + boolean isPromoted = true; + Product product = this.findOneOriginProduct(request.getProductName(),isPromoted); + if(product == NOT_FOUND){ + return Receipt.createEmptyReceipt(request.getProductName()); + } + if(product.getCount() < request.getCountPurchased()){ + int buyCount = product.getCount(); + return buyProduct(product,buyCount,request); + } + return buyProduct(product,request.getCountPurchased(),request); + } + + + private Receipt tryBuyProductNonPromoted(PurchaseRequest request){ + boolean isPromoted = false; + Product product = this.findOneOriginProduct(request.getProductName(),isPromoted); + if(product == NOT_FOUND){ + return Receipt.createEmptyReceipt(request.getProductName()); + } + if(product.getCount() < request.getCountPurchased()){ + ExceptionFactory.throwIllegalStateException(ExceptionType.INTERNAL_ERROR); + } + return buyProduct(product,request.getCountPurchased(),request); + } + + private Receipt buyProduct(Product product, int buyCount, PurchaseRequest request){ + request.decreaseCount(buyCount); + return product.buy(buyCount); + } + +}
Java
ํ•ด๋‹น ํŒจํ‚ค์ง€์—์„œ๋งŒ ์‚ฌ์šฉ๋  ๊ฑฐ๋ผ์„œ default ์ ‘๊ทผ์ œ์–ด์ž๋ฅผ ์‚ฌ์šฉํ•˜์˜€์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,125 @@ +package store; + +import java.util.List; +import store.product.Product; +import store.product.Receipt; +import store.utils.Transformer; + +public class StoreOutputView { + + public void welcomeConsumer(List<Product> products){ + StoreViewMessage.WELCOME.printMessage(); + for(Product product : products){ + printSellingProduct(product); + } + } + + public void printAccount(List<Receipt> receipts, int disCountPrice){ + StoreViewMessage.RECEIPT_HEAD.printMessage(); + printPurchaseProductList(receipts); + printPromotionReturnProductList(receipts); + printBill(receipts,disCountPrice); + } + + public void printSellingProduct(Product product){ + String promotionName = ""; + if(product.isPromotionExist()){ + promotionName = product.getPromotionName(); + } + + if(product.isInsufficient()){ + StoreViewMessage.printInsufficientProduct(product.getName(),product.getPrice(),promotionName); + return; + } + StoreViewMessage.printProduct(product.getName(),product.getPrice(),product.getCount(),promotionName); + } + + + public void printPurchaseProductList(List<Receipt> receipts){ + + StoreViewMessage.printReceiptProductListHead(); + for(Receipt receipt : receipts){ + StoreViewMessage.printReceiptFormat(receipt.getProductName(), Integer.toString(receipt.getActualCount()),Integer.toString(receipt.getActualPrice())); + } + + } + + public void printPromotionReturnProductList(List<Receipt> receipts){ + StoreViewMessage.RECEIPT_HEAD_PROMOTION.printMessage(); + String emtpy = ""; + List<Receipt> promotionReceipts = receipts.stream().filter((Receipt::isPromotionApplied)).toList(); + for(Receipt receipt : promotionReceipts){ + StoreViewMessage.printReceiptFormat(receipt.getProductName(),Integer.toString(receipt.getActualCount()),emtpy); + } + } + + public void printBill(List<Receipt> receipts, int disCountPrice){ + StoreViewMessage.RECEIPT_HEAD_ACCOUNT.printMessage(); + List<Integer> accounts = calculateTotalReceipt(receipts); + int totalCountColumn = 0; + int promotedPriceColumn = 1; + int totalActualPrice = 2; + + printBillMessage(accounts.get(totalCountColumn),accounts.get(promotedPriceColumn),accounts.get(totalActualPrice),disCountPrice); + } + + public void printBillMessage(int totalCount, int promotedPrice, int totalActualPrice, int disCountPrice){ + printBillMessageTotalActualPrice(totalCount,totalActualPrice); + printBillMessagePromotionDiscount(promotedPrice); + printBillMessageMembershipDiscount(disCountPrice); + printBillMessageTotalPrice(totalActualPrice - promotedPrice - disCountPrice); + } + + public void printBillMessageTotalActualPrice(int totalCount,int totalActualPrice){ + String empty = ""; + String column = "์ด๊ตฌ๋งค์•ก"; + StoreViewMessage.printReceiptFormat(column,Integer.toString(totalCount), Transformer.transformToThousandSeparated(totalActualPrice)); + } + + public void printBillMessagePromotionDiscount(int promotedPrice){ + String empty = ""; + String column = "ํ–‰์‚ฌํ• ์ธ"; + int zero = 0; + String discount = "-"; + if(promotedPrice == zero){ + discount=""; + } + discount += Transformer.transformToThousandSeparated(promotedPrice); + + StoreViewMessage.printReceiptFormat(column,empty,discount); + } + + public void printBillMessageMembershipDiscount(int disCountPrice){ + String empty = ""; + String column = "๋ฉค๋ฒ„์‹ญํ• ์ธ"; + int zero = 0; + String discount = "-"; + if(disCountPrice == zero){ + discount=""; + } + discount += Transformer.transformToThousandSeparated(disCountPrice); + + StoreViewMessage.printReceiptFormat(column,empty,discount); + } + + public void printBillMessageTotalPrice(int totalPrice){ + String empty = ""; + String column = "๋‚ด์‹ค๋ˆ"; + + StoreViewMessage.printReceiptFormat(column,empty,Transformer.transformToThousandSeparated(totalPrice)); + } + + public List<Integer> calculateTotalReceipt(List<Receipt> receipts){ + int totalCount = 0; + int promotedPrice = 0; + int totalActualPrice = 0; + for(Receipt receipt : receipts){ + totalCount += receipt.getActualCount(); + promotedPrice += receipt.getDisCountPrice(); + totalActualPrice += receipt.getActualPrice(); + } + + return List.of(totalCount,promotedPrice,totalActualPrice) ; + } + +}
Java
์ €๋„ dto๋ฅผ ์„ ์–ธํ•˜์—ฌ ๊ฐ์ฒด๊ฐ„์˜ ์ปค๋ฎค๋‹ˆ์ผ€์ด์…˜์— ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์„ ์„ ํ˜ธํ•˜๋Š”๋ฐ์š”. ์‹œ๊ฐ„์ด ๋ถ€์กฑํ•˜์—ฌ dto๋ฅผ ๋”ฐ๋กœ ์„ ์–ธํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค, ๋„๋ฉ”์ธ ๋ฐ์ดํ„ฐ ํด๋ž˜์Šค๋ฅผ dto์ฒ˜๋Ÿผ ํ™œ์šฉํ•˜๋Š” ๋ฐฉ์‹์„ ํƒํ•˜์˜€์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,73 @@ +package store; + +public enum StoreViewMessage { + + WELCOME("์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค.\n" + + "ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."), + PURCHASE_GUIDE("๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"), + MEMBERSHIP_GUIDE("๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"), + + RECEIPT_HEAD("==============W ํŽธ์˜์ ================"), + RECEIPT_HEAD_PROMOTION("=============์ฆ\t์ •==============="), + RECEIPT_HEAD_ACCOUNT("===================================="), + RETRY_PURCHASE("๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"), + + ERROR_INVALID_FORMAT("[ERROR] ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + + ERROR_NOT_EXIST_PRODUCT("[ERROR] ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + ERROR_OVERFLOW_PURCHASE("[ERROR] ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + ERROR_NO_COUNT_PRODUCT("[ERROR] ์žฌ๊ณ ๊ฐ€ ์—†๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + + private final String message; + + static public final String PURCHASE_PATTERN = "\\[([a-zA-Z๊ฐ€-ํžฃ0-9]+)-(\\d+)]"; + static public final String PURCHASE_LIST_DELIMITER = ","; + static public final String ANSWER_NO = "N"; + static public final String ANSWER_YES = "Y"; + + private StoreViewMessage(String message){ + this.message = message; + } + + public String getMessage() { + return message; + } + + public void printMessage(){ + System.out.println(this.message); + } + + public static void printReceiptFormat(String first, String second, String third){ + final int FIRST_WIDTH = 15; + final int SECOND_WIDTH = 8; + final int THIRD_WIDTH = 10; + System.out.printf("%-" + FIRST_WIDTH + "s%-" + SECOND_WIDTH + "s%-" + THIRD_WIDTH + "s\n", first, second, third); + } + + public static void printReceiptProductListHead(){ + final String productNameColumn = "์ƒํ’ˆ๋ช…"; + final String countColumn = "์ˆ˜๋Ÿ‰"; + final String priceColumn = "๊ธˆ์•ก"; + printReceiptFormat(productNameColumn,countColumn,priceColumn); + } + + public static void printProduct(String ProductName, int price, int count, String promotionName){ + final String format = "- %s %,d์› %d๊ฐœ %s\n"; + System.out.printf(format,ProductName,price,count,promotionName); + } + + public static void printInsufficientProduct(String ProductName, int price, String promotionName){ + final String format = "- %s %,d์› ์žฌ๊ณ  ์—†์Œ %s\n"; + System.out.printf(format,ProductName,price,promotionName); + } + + public static void printPromotionReturnAvailable(String productName){ + String format = "ํ˜„์žฌ %s์€(๋Š”) 1๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)\n"; + System.out.printf(format,productName); + } + + public static void printPromotionWarning(String productName,int count) { + String format = "ํ˜„์žฌ %s %d๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)\n"; + System.out.printf(format, productName, count); + } +}
Java
์ „์—ญ์—์„œ ์‚ฌ์šฉํ•  ๋ชฉ์ ์œผ๋กœ ์„ ์–ธํ•˜์˜€๋Š”๋ฐ์š”. ์‹œ๊ฐ„์ด ๋ถ€์กฑํ•˜์—ฌ, ์ƒ์ˆ˜๋“ค๊ณผ ์ƒ์ˆ˜ ๊ด€๋ จ ๊ธฐ๋Šฅ์„ ๋‹ค๋ฅธ ํด๋ž˜์Šค๋กœ ์˜ฎ๊ธฐ์ง€ ๋ชปํ•˜์—ฌ ์ด๋Ÿฐ ์ฝ”๋“œ๊ฐ€ ๋˜์–ด๋ฒ„๋ ธ๋„ค์š”