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
|
์ ์ญ์์ ์ฌ์ฉํ ๋ชฉ์ ์ผ๋ก ์ ์ธํ์๋๋ฐ์.
์๊ฐ์ด ๋ถ์กฑํ์ฌ, ์์๋ค๊ณผ ์์ ๊ด๋ จ ๊ธฐ๋ฅ์ ๋ค๋ฅธ ํด๋์ค๋ก ์ฎ๊ธฐ์ง ๋ชปํ์ฌ ์ด๋ฐ ์ฝ๋๊ฐ ๋์ด๋ฒ๋ ธ๋ค์
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.