code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,48 @@ +package store.domain; + +import static store.global.constant.MessageConstant.FORMAT; + +import java.text.DecimalFormat; + +public class PaymentProduct { + + private static final DecimalFormat PRICE_FORMAT = new DecimalFormat("###,###"); + + private final String name; + private final int quantity; + private final int price; + private final int promotion; + + public PaymentProduct(String name, int quantity, int price, int promotion) { + this.name = name; + this.quantity = quantity; + this.price = price; + this.promotion = promotion; + } + + @Override + public String toString() { + String formattedPrice = PRICE_FORMAT.format(quantity * price); + return String.format(FORMAT.getMessage(), name, quantity, formattedPrice); + } + + public boolean isPromotion() { + return promotion != 0; + } + + public String buildPromotion() { + return String.format(FORMAT.getMessage(), name, promotion, ""); + } + + public int getQuantity() { + return quantity; + } + + public int getTotalPrice() { + return quantity * price; + } + + public int getPromotionPrice() { + return promotion * price; + } +}
Java
promotion ๋ณ€์ˆ˜์˜ ์ •ํ™•ํ•œ ๋œป์ด ๋ฌด์—‡์ธ๊ฐ€์š”? ํ”„๋กœ๋ชจ์…˜ ์—ฌ๋ถ€์ธ๊ฐ€์š”? ํ”„๋กœ๋ชจ์…˜ ๊ฐ€๊ฒฉ์ธ๊ฐ€์š”? ๊ตณ์ด int ํƒ€์ž…์œผ๋กœ ์ž‘์„ฑํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,89 @@ +package store.domain; + +import static store.global.constant.MessageConstant.FORMAT; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + +public class PaymentProductList { + + private static final DecimalFormat PRICE_FORMAT = new DecimalFormat("###,###"); + + private List<PaymentProduct> paymentProducts; + private int totalPrice = 0; + private int totalPromotion = 0; + private int membershipPrice = 0; + + public PaymentProductList() { + this.paymentProducts = new ArrayList<>(); + } + + public void addPaymentProduct(PaymentProduct product) { + paymentProducts.add(product); + } + + public List<Integer> getAllProductQuantities() { + return paymentProducts.stream() + .map(PaymentProduct::getQuantity) + .toList(); + } + + public List<String> infoProduct() { + return paymentProducts.stream() + .map(PaymentProduct::toString) + .toList(); + } + + public List<String> infoPromotion() { + return paymentProducts.stream() + .filter(PaymentProduct::isPromotion) + .map(PaymentProduct::buildPromotion) + .toList(); + } + + public List<String> finalResult() { + List<String> result = new ArrayList<>(); + result.add(String.format(FORMAT.getMessage(), "์ด๊ตฌ๋งค์•ก", totalQuantity(), totalPrice())); + result.add(String.format(FORMAT.getMessage(), "ํ–‰์‚ฌํ• ์ธ", "", totalPromotionPrice())); + result.add(String.format(FORMAT.getMessage(), "๋ฉค๋ฒ„์‹ญํ• ์ธ", "", "-" + PRICE_FORMAT.format(membershipPrice))); + result.add(String.format(FORMAT.getMessage(), "๋‚ด์‹ค๋ˆ", "", + PRICE_FORMAT.format(totalPrice - totalPromotion - membershipPrice))); + + return result; + } + + private int totalQuantity() { + return paymentProducts.stream() + .mapToInt(PaymentProduct::getQuantity) + .sum(); + } + + private String totalPrice() { + this.totalPrice = paymentProducts.stream() + .mapToInt(PaymentProduct::getTotalPrice) + .sum(); + return PRICE_FORMAT.format(totalPrice); + } + + private String totalPromotionPrice() { + this.totalPromotion = paymentProducts.stream() + .filter(PaymentProduct::isPromotion) + .mapToInt(PaymentProduct::getPromotionPrice) + .sum(); + return "-" + PRICE_FORMAT.format(totalPromotion); + } + + public void applyMembershipDiscount() { + int price = (int) (paymentProducts.stream() + .filter(product -> !product.isPromotion()) + .mapToInt(PaymentProduct::getTotalPrice) + .sum() * 0.3); + + if (price > 8000) { + price = 8000; + } + + this.membershipPrice = price; + } +}
Java
์šฐ์•„ํ•œํ…Œํฌ์ฝ”์Šค์˜ ๊ณตํ†ต ํ”ผ๋“œ๋ฐฑ์—์„œ ๋ณ€์ˆ˜๋ช…์— ์ž๋ฃŒํ˜•(List) ๊ฐ™์€ ๊ฑธ ๋„ฃ์ง€ ๋ง๋ผ๊ณ  ํ–ˆ๋Š”๋ฐ, ์ด์— ๋Œ€ํ•ด ๋ณ€์ˆ˜๋Š” ์•„๋‹ˆ์ง€๋งŒ PaymentProductList ๋ผ๋Š” ํด๋ž˜์Šค ๋ช…์— ๋Œ€ํ•ด ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,89 @@ +package store.domain; + +import static store.global.constant.MessageConstant.FORMAT; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + +public class PaymentProductList { + + private static final DecimalFormat PRICE_FORMAT = new DecimalFormat("###,###"); + + private List<PaymentProduct> paymentProducts; + private int totalPrice = 0; + private int totalPromotion = 0; + private int membershipPrice = 0; + + public PaymentProductList() { + this.paymentProducts = new ArrayList<>(); + } + + public void addPaymentProduct(PaymentProduct product) { + paymentProducts.add(product); + } + + public List<Integer> getAllProductQuantities() { + return paymentProducts.stream() + .map(PaymentProduct::getQuantity) + .toList(); + } + + public List<String> infoProduct() { + return paymentProducts.stream() + .map(PaymentProduct::toString) + .toList(); + } + + public List<String> infoPromotion() { + return paymentProducts.stream() + .filter(PaymentProduct::isPromotion) + .map(PaymentProduct::buildPromotion) + .toList(); + } + + public List<String> finalResult() { + List<String> result = new ArrayList<>(); + result.add(String.format(FORMAT.getMessage(), "์ด๊ตฌ๋งค์•ก", totalQuantity(), totalPrice())); + result.add(String.format(FORMAT.getMessage(), "ํ–‰์‚ฌํ• ์ธ", "", totalPromotionPrice())); + result.add(String.format(FORMAT.getMessage(), "๋ฉค๋ฒ„์‹ญํ• ์ธ", "", "-" + PRICE_FORMAT.format(membershipPrice))); + result.add(String.format(FORMAT.getMessage(), "๋‚ด์‹ค๋ˆ", "", + PRICE_FORMAT.format(totalPrice - totalPromotion - membershipPrice))); + + return result; + } + + private int totalQuantity() { + return paymentProducts.stream() + .mapToInt(PaymentProduct::getQuantity) + .sum(); + } + + private String totalPrice() { + this.totalPrice = paymentProducts.stream() + .mapToInt(PaymentProduct::getTotalPrice) + .sum(); + return PRICE_FORMAT.format(totalPrice); + } + + private String totalPromotionPrice() { + this.totalPromotion = paymentProducts.stream() + .filter(PaymentProduct::isPromotion) + .mapToInt(PaymentProduct::getPromotionPrice) + .sum(); + return "-" + PRICE_FORMAT.format(totalPromotion); + } + + public void applyMembershipDiscount() { + int price = (int) (paymentProducts.stream() + .filter(product -> !product.isPromotion()) + .mapToInt(PaymentProduct::getTotalPrice) + .sum() * 0.3); + + if (price > 8000) { + price = 8000; + } + + this.membershipPrice = price; + } +}
Java
์—ฌ๊ธฐ์„œ - ๊ฐ™์€ ๊ฒƒ์€ ์ƒ์ˆ˜๋กœ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ๋‚˜์„ ๊ฒƒ ๊ฐ™์€๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,89 @@ +package store.domain; + +import static store.global.constant.MessageConstant.FORMAT; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + +public class PaymentProductList { + + private static final DecimalFormat PRICE_FORMAT = new DecimalFormat("###,###"); + + private List<PaymentProduct> paymentProducts; + private int totalPrice = 0; + private int totalPromotion = 0; + private int membershipPrice = 0; + + public PaymentProductList() { + this.paymentProducts = new ArrayList<>(); + } + + public void addPaymentProduct(PaymentProduct product) { + paymentProducts.add(product); + } + + public List<Integer> getAllProductQuantities() { + return paymentProducts.stream() + .map(PaymentProduct::getQuantity) + .toList(); + } + + public List<String> infoProduct() { + return paymentProducts.stream() + .map(PaymentProduct::toString) + .toList(); + } + + public List<String> infoPromotion() { + return paymentProducts.stream() + .filter(PaymentProduct::isPromotion) + .map(PaymentProduct::buildPromotion) + .toList(); + } + + public List<String> finalResult() { + List<String> result = new ArrayList<>(); + result.add(String.format(FORMAT.getMessage(), "์ด๊ตฌ๋งค์•ก", totalQuantity(), totalPrice())); + result.add(String.format(FORMAT.getMessage(), "ํ–‰์‚ฌํ• ์ธ", "", totalPromotionPrice())); + result.add(String.format(FORMAT.getMessage(), "๋ฉค๋ฒ„์‹ญํ• ์ธ", "", "-" + PRICE_FORMAT.format(membershipPrice))); + result.add(String.format(FORMAT.getMessage(), "๋‚ด์‹ค๋ˆ", "", + PRICE_FORMAT.format(totalPrice - totalPromotion - membershipPrice))); + + return result; + } + + private int totalQuantity() { + return paymentProducts.stream() + .mapToInt(PaymentProduct::getQuantity) + .sum(); + } + + private String totalPrice() { + this.totalPrice = paymentProducts.stream() + .mapToInt(PaymentProduct::getTotalPrice) + .sum(); + return PRICE_FORMAT.format(totalPrice); + } + + private String totalPromotionPrice() { + this.totalPromotion = paymentProducts.stream() + .filter(PaymentProduct::isPromotion) + .mapToInt(PaymentProduct::getPromotionPrice) + .sum(); + return "-" + PRICE_FORMAT.format(totalPromotion); + } + + public void applyMembershipDiscount() { + int price = (int) (paymentProducts.stream() + .filter(product -> !product.isPromotion()) + .mapToInt(PaymentProduct::getTotalPrice) + .sum() * 0.3); + + if (price > 8000) { + price = 8000; + } + + this.membershipPrice = price; + } +}
Java
์ „์ฒด์ ์œผ๋กœ ์—ฌ๊ธฐ 8000 ์ด๋ผ๋Š” ์ˆซ์ž๋„ ๊ทธ๋ ‡๊ณ , ์ƒ์ˆ˜ํ™”๋ฅผ ํ–ˆ์œผ๋ฉด ๋” ๊ฐ€๋…์„ฑ์ด ์ข‹์•˜์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,83 @@ +package store.domain; + +import java.time.LocalDate; +import store.domain.product.Name; +import store.domain.product.Price; +import store.domain.product.Quantity; + +public class Product { + + private static final String INFO_DELIMITER = " "; + + private final Name name; + private final Price price; + private final Quantity quantity; + private final Promotions promotions; + + public Product(Name name, Price price, Quantity quantity, Promotions promotions) { + this.name = name; + this.price = price; + this.quantity = quantity; + this.promotions = promotions; + } + + @Override + public String toString() { + String info = buildInfo(); + + if (hasPromotion()) { + return String.join(INFO_DELIMITER, + info, + promotions.toString()); + } + return info; + } + + public int decreaseStock(int quantity) { + return this.quantity.decreaseStock(quantity); + } + + public int calculateRemainingStock(int purchaseQuantity) { + return quantity.calculateDifference(purchaseQuantity); + } + + public boolean hasSameName(String name) { + return this.name.toString().equals(name); + } + + public boolean hasPromotion() { + return this.promotions != null; + } + + private String buildInfo() { + return String.join(INFO_DELIMITER, + name.toString(), + price.toString(), + quantity.toString() + ); + } + + public int calculatePromotionRate(int quantity) { + return promotions.calculateRemainingItems(quantity); + } + + public String getProductName() { + return name.toString(); + } + + public int getProductPrice() { + return price.getPrice(); + } + + public boolean isPromotionAdditionalProduct(int quantity) { + return promotions.isPromotionApplicable(quantity); + } + + public int getPromotionUnits(int quantity) { + return promotions.calculatePromotionUnits(quantity); + } + + public boolean isWithinPromotionPeriod(LocalDate date) { + return promotions.isWithinPromotionPeriod(date); + } +}
Java
๋ชจ๋“  ํ•„๋“œ๊ฐ€ ๋ž˜ํ•‘๋˜์–ด ์žˆ๋Š” ๊ฒƒ์ด ๊ฐ€๋…์„ฑ๊ณผ ๋กœ์ง ๋ถ„๋ฆฌ์— ์ข‹์€ ์˜ํ–ฅ์„ ๋ผ์น˜๋Š” ๊ฒƒ ๊ฐ™์•„์š”! ๐Ÿ‘
@@ -0,0 +1,46 @@ +package store.domain; + +import java.time.LocalDate; + +public class Promotions { + + private final String name; + private final int buy; + private final int get; + private final LocalDate startDate; + private final LocalDate endDate; + + public Promotions(String name, String buy, String get, String startDate, String endDate) { + this.name = name; + this.buy = Integer.parseInt(buy); + this.get = Integer.parseInt(get); + this.startDate = LocalDate.parse(startDate); + this.endDate = LocalDate.parse(endDate); + } + + @Override + public String toString() { + return name; + } + + public boolean hasName(String name) { + return this.name.equals(name); + } + + public boolean isPromotionApplicable(int quantity) { + return calculateRemainingItems(quantity) >= get; + } + + public int calculateRemainingItems(int quantity) { + return quantity % (buy + get); + } + + public int calculatePromotionUnits(int quantity) { + return quantity / (buy + get); + } + + public boolean isWithinPromotionPeriod(LocalDate date) { + return (date.isEqual(startDate) || date.isAfter(startDate)) && + (date.isEqual(endDate) || date.isBefore(endDate)); + } +}
Java
์ €๋„ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,32 @@ +package store.global.constant; + +public enum ErrorMessage { + INVALID_INPUT_PURCHASE("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + INVALID_INPUT("์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + + INVALID_PRICE_NUMERIC("๋ฌผํ’ˆ ๊ฐ€๊ฒฉ์€ ์ˆซ์ž๋งŒ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค. ๋‹ค์‹œ ํ™•์ธํ•ด ์ฃผ์„ธ์š”."), + INVALID_PRICE_OUT_OF_RANGE("๋ฌผํ’ˆ ๊ฐ€๊ฒฉ์€ ๋ฒ”์œ„๋‚ด๋งŒ ๋“ฑ๋กํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ํ™•์ธํ•ด ์ฃผ์„ธ์š”."), + + INSUFFICIENT_STOCK("์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + INVALID_QUANTITY_NUMERIC("๋ฌผํ’ˆ ์ˆ˜๋Ÿ‰์€ ์ˆซ์ž๋งŒ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค. ๋‹ค์‹œ ํ™•์ธํ•ด ์ฃผ์„ธ์š”."), + INVALID_QUANTITY_OUT_OF_RANGE("๋ฌผํ’ˆ ์ˆ˜๋Ÿ‰์€ ๋ฒ”์œ„๋‚ด๋งŒ ๋“ฑ๋กํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ํ™•์ธํ•ด ์ฃผ์„ธ์š”."), + + PRODUCT_NOT_FOUND("์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + INVALID_PRODUCT_ELEMENT("์ƒํ’ˆ ์ •๋ณด์˜ ์š”์†Œ๊ฐ€ ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. ํŒŒ์ผ์„ ํ™•์ธํ•ด ์ฃผ์„ธ์š”."), + + FILE_NOT_FOUND("%s ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ํŒŒ์ผ ์ด๋ฆ„์„ ํ™•์ธํ•ด ์ฃผ์„ธ์š”."), + FILE_CONTAINS_BLANK_CONTENT("ํŒŒ์ผ์˜ ๋‚ด์šฉ ์ค‘ ๊ณต๋ฐฑ์ธ ๋ถ€๋ถ„์ด ์žˆ์Šต๋‹ˆ๋‹ค. ํŒŒ์ผ์„ ํ™•์ธํ•ด ์ฃผ์„ธ์š”."), + FILE_CONTENT_NULL("ํŒŒ์ผ์˜ ๋‚ด์šฉ์ด NULL ์ž…๋‹ˆ๋‹ค. ํŒŒ์ผ์„ ํ™•์ธํ•ด ์ฃผ์„ธ์š”."), + FILE_CONTENT_INSUFFICIENT("ํŒŒ์ผ์˜ ์ •๋ณด๊ฐ€ ๋ถ€์กฑํ•ฉ๋‹ˆ๋‹ค. ํŒŒ์ผ์„ ํ™•์ธํ•ด ์ฃผ์„ธ์š”."); + + private static final String ERROR_PREFIX = "[ERROR] "; + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return ERROR_PREFIX + message; + } +}
Java
์ด๋ ‡๊ฒŒ [ERROR]์„ ํ•œ๋ฒˆ์— ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฐฉ์‹ ์ข‹๋„ค์š”.
@@ -0,0 +1,13 @@ +package store.global.exception; + +import store.global.constant.ErrorMessage; + +public class FileException extends RuntimeException { + public FileException(ErrorMessage error, String fileName) { + super(String.format(error.getMessage(), fileName)); + } + + public FileException(ErrorMessage errorMessage) { + super(errorMessage.getMessage()); + } +}
Java
FileExceiption์„ ๋”ฐ๋กœ ์ •์˜ํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”? ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,61 @@ +package store.global.util; + +import java.util.ArrayList; +import java.util.List; +import store.domain.Product; +import store.domain.PromotionsList; +import store.domain.product.Name; +import store.domain.product.Price; +import store.domain.product.Quantity; + +public class ProductParser { + private static final String DEFAULT_QUANTITY = "0"; + private static final String NO_PROMOTION = "null"; + + private static PromotionsList promotionsList; + + public static List<Product> parseToProducts(final List<List<String>> inputData, + final PromotionsList promotionsList) { + ProductParser.promotionsList = promotionsList; + + List<Product> products = new ArrayList<>(); + for (List<String> productData : inputData) { + Product product = createProduct(productData); + products.add(product); + addDefaultProductIfNecessary(products, inputData, productData, product); + } + return products; + } + + private static void addDefaultProductIfNecessary(List<Product> products, List<List<String>> inputData, + List<String> productData, Product product) { + if (product.hasPromotion() && isSingleProductInInput(inputData, productData)) { + Product defaultProduct = createDefaultProduct(productData); + products.add(defaultProduct); + } + } + + private static boolean isSingleProductInInput(List<List<String>> inputData, List<String> productData) { + return inputData.stream() + .filter(info -> info.contains(productData.get(0))) + .count() == 1; + } + + private static Product createDefaultProduct(List<String> productData) { + return createProduct(List.of( + productData.get(0), + productData.get(1), + DEFAULT_QUANTITY, + NO_PROMOTION + )); + } + + private static Product createProduct(List<String> productData) { + return new Product( + new Name(productData.get(0)), + new Price(productData.get(1)), + new Quantity(productData.get(2)), + promotionsList.findPromotion(productData.get(3)) + ); + } +}
Java
์ €๋Š” FileUtil์—์„œ ์‚ฌ์‹ค ๋ชจ๋“  ํŒŒ์‹ฑ๋„ ์ฒ˜๋ฆฌํ•˜๋„๋ก ์ž‘์„ฑํ–ˆ๋Š”๋ฐ, ์ด๋ ‡๊ฒŒ Parser์„ ๋”ฐ๋กœ ๊ตฌ๋ถ„ํ•˜๋Š” ๊ฒƒ์ด ๋” ์ข‹์€ ์„ค๊ณ„์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ์นญ์ฐฌํ•ด์š” :)
@@ -0,0 +1,185 @@ +package pairmatching.controller; + +import java.util.function.Function; +import org.mockito.internal.util.Supplier; +import pairmatching.enums.Course; +import pairmatching.enums.Crew; +import pairmatching.enums.Functions; +import pairmatching.enums.Level; +import pairmatching.enums.Missions; +import pairmatching.enums.ShortAnswer; +import pairmatching.model.MatchingRecord; +import pairmatching.model.Pairs; +import pairmatching.view.InputView; +import pairmatching.view.OutputView; +import pairmatching.view.error.ErrorException; + +public class PairMatchingController { + + private static final String COMMA = "\\s*,\\s*"; + private static final String EXIT = "exit"; + public static final int MAX_TRY_COUNT = 3; + + private InputView inputView; + private OutputView outputView; + private Crew backend; + private Crew frontend; + private MatchingRecord backendRecord; + private MatchingRecord frontendRecord; + + + public PairMatchingController(InputView inputView, OutputView outputView) { + this.inputView = inputView; + this.outputView = outputView; + this.backend = new Crew(Course.BACKEND); + this.frontend = new Crew(Course.FRONTEND); + this.backendRecord = new MatchingRecord(); + this.frontendRecord = new MatchingRecord(); + } + + public void matchingSystemRun() { + while (true) { + try { + String input = getValidInput(inputView::displayStartMessage, Functions::getValidFunction); + executeWithInput(input); + } catch (IllegalArgumentException e) { + if (e.getMessage().equals(EXIT)) { + return; + } + System.out.println(e.getMessage()); + } + } + } + + private void executeWithInput(String input) throws IllegalArgumentException { + if (Functions.isEquals(input, Functions.QUIT)) { + performFunctions(input, inputView); + } + if (!Functions.isEquals(input, Functions.QUIT)) { + throw new IllegalArgumentException(EXIT); + } + } + + private void performFunctions(String input, InputView inputView) throws ErrorException { + executePairMatching(input, inputView); + executePairInquiry(input, inputView); + executePairInitialization(input); + } + + private void executePairMatching(String input, InputView inputView) throws ErrorException { + if (Functions.isEquals(input, Functions.MATCH_PAIRS)) { + String[] matchingCriteria = parseInput(inputView); + String course = Course.isCourse(matchingCriteria[0]); + Level level = Level.getLevel(matchingCriteria[1]); + Missions mission = Missions.getValidMission(level, matchingCriteria[2]); + + matchDistinctPairs(course, mission); + } + } + + private void executePairInquiry(String input, InputView inputView) throws ErrorException { + if (Functions.isEquals(input, Functions.PAIR_INQUIRY)) { + String[] matchingCriteria = parseInput(inputView); + + String course = Course.isCourse(matchingCriteria[0]); + Level level = Level.getLevel(matchingCriteria[1]); + Missions mission = Missions.getValidMission(level, matchingCriteria[2]); + MatchingRecord record = getRecordThroughCourse(course); + Pairs matchedPairs = record.getRecordThroughMission(mission); + matchedPairs.display(); + } + } + + private void executePairInitialization(String input) { + if (Functions.isEquals(input, Functions.INITIALIZE_PAIR)) { + backendRecord.clear(); + frontendRecord.clear(); + outputView.displayReset(); + } + } + + private String[] parseInput(InputView inputView) { + String matchingCriteria = inputView.enteredChoices(); + return matchingCriteria.split(COMMA); + } + + private void matchDistinctPairs(String course, Missions mission) { + MatchingRecord record = getRecordThroughCourse(course); + if (record.containPreviousMatching(mission)) { + rematching(course, mission, record); + return; + } + handleNewMatching(course, mission, record); + } + + private void rematching(String course, Missions mission, MatchingRecord record) { + String input = getValidInput(inputView::enteredRematching, ShortAnswer::getValidAnswer); + if (ShortAnswer.isEquals(input, ShortAnswer.YES)) { + Pairs matchedPairs = matchingPairs(course); + record.replace(mission, matchedPairs); + } + } + + private void handleNewMatching(String course, Missions mission, MatchingRecord record) { + int count = 0; + while (true) { + Pairs matchedPairs = matchingPairs(course); + if (record.containTheSamePairInTheSameLevel(mission, matchedPairs)) { + count = handleRetry(count); + continue; + } + record.add(mission, matchedPairs); + break; + } + } + + private int handleRetry(int count) { + count++; + overTryCount(count); + return count; + } + + private void overTryCount(int count) throws ErrorException { + if (count >= MAX_TRY_COUNT) { + throw new ErrorException("๋งค์นญ ์‹œ๋„ ํšŸ์ˆ˜๊ฐ€ 3ํšŒ๋ฅผ ์ดˆ๊ณผํ–ˆ์Šต๋‹ˆ๋‹ค."); + } + } + + private Pairs matchingPairs(String course) { + Crew crew = getCrewThroughCourse(course); + Pairs matchedPairs = crew.matchPairs(); + displayMatchedPairs(matchedPairs); + return matchedPairs; + } + + private Crew getCrewThroughCourse(String course) { + if (Course.isEquals(course, Course.BACKEND)) { + return backend; + } + return frontend; + } + + private MatchingRecord getRecordThroughCourse(String course) { + if (Course.isEquals(course, Course.BACKEND)) { + return backendRecord; + } + return frontendRecord; + } + + private void displayMatchedPairs(Pairs matchedPairs) { + outputView.displayPairMatchingResult(); + matchedPairs.display(); + } + + private <T> T getValidInput(Supplier<String> inputSupplier, Function<String, T> converter) { + while (true) { + String input = inputSupplier.get(); + try { + return converter.apply(input); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + +}
Java
```suggestion if (Functions.isEquals(input, Functions.QUIT)) { performFunctions(input, inputView); return } ``` ์‚ฌ์†Œํ•œ๊ฑฐ์ง€๋งŒ return์„ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด ์•„๋ž˜์— if๋ฌธ์„ ์•ˆ๋งŒ๋“ค๊ณ  ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์—ˆ์„ ๊ฑฐ ๊ฐ™์•„์š”
@@ -0,0 +1,34 @@ +package pairmatching.model; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class Pairs { + + private Map<String, List<String>> pairs; + + public Pairs(Map<String, List<String>> pair){ + this.pairs = pair; + } + + public Set<Map.Entry<String, List<String>>> entrySet(){ + return pairs.entrySet(); + } + + public void display() { + for (String key : pairs.keySet()) { + String value = null; + if(pairs.get(key).size() == 2){ + value = pairs.get(key).get(0); + value += " : "; + value += pairs.get(key).get(1); + } + if(pairs.get(key).size() == 1){ + value = String.valueOf(pairs.get(key).get(0)); + } + System.out.println(key+" : "+ value); + } + } + +}
Java
for-each์™€ string Joiner๋ฅผ ์จ์„œ ํ•ด๊ฒฐํ–ˆ์–ด๋„ ๋์„๊ฑฐ ๊ฐ™์•„์š”!
@@ -54,11 +54,20 @@ export const REVIEW_GROUP_API_PARAMS = { }, }; +export const WRITTEN_REVIEW_PARAMS = { + resource: 'reviews/authored', + queryString: { + lastReviewId: 'lastReviewId', + size: 'size', + }, +}; + export const REVIEW_WRITING_API_URL = `${serverUrl}/${VERSION2}/${REVIEW_WRITING_API_PARAMS.resource}`; export const REVIEW_LIST_API_URL = `${serverUrl}/${VERSION2}/${REVIEW_LIST_API_PARAMS.resource}`; export const DETAILED_REVIEW_API_URL = `${serverUrl}/${VERSION2}/${DETAILED_REVIEW_API_PARAMS.resource}`; export const REVIEW_GROUP_DATA_API_URL = `${serverUrl}/${VERSION2}/${REVIEW_GROUP_DATA_API_PARAMS.resource}`; export const REVIEW_GROUP_API_URL = `${serverUrl}/${VERSION2}/reviews/gather`; +export const WRITTEN_REVIEW_LIST_API_URL = `${serverUrl}/${VERSION2}/${WRITTEN_REVIEW_PARAMS.resource}`; const endPoint = { postingReview: `${serverUrl}/${VERSION2}/reviews`, @@ -80,6 +89,14 @@ const endPoint = { gettingGroupedReviews: (sectionId: number) => `${REVIEW_GROUP_API_URL}?${REVIEW_GROUP_API_PARAMS.queryString.sectionId}=${sectionId}`, postingHighlight: `${serverUrl}/${VERSION2}/highlight`, + + gettingWrittenReviewList: (lastReviewId: number | null, size: number) => { + const defaultEndpoint = `${WRITTEN_REVIEW_LIST_API_URL}?${WRITTEN_REVIEW_PARAMS.queryString.size}=${size}`; + if (lastReviewId) { + return defaultEndpoint + '&' + `${WRITTEN_REVIEW_PARAMS.queryString.lastReviewId}=${lastReviewId}`; + } + return defaultEndpoint; + }, }; export default endPoint;
TypeScript
```suggestion if (!lastReviewId) return defaultEndpoint; return defaultEndpoint + '&' + `${WRITTEN_REVIEW_PARAMS.queryString.lastReviewId}=${lastReviewId}`; }, ``` ์ด๋Ÿฐ ๊ตฌ์กฐ๋กœ ๋ฐ”๊พธ๋ฉด lastReviewId๊ฐ€ ์—†์„ ๋•Œ endpoint ๊ฐ’์„ ํŒŒ์•…ํ•˜๋Š”๋ฐ ๋” ์‰ฌ์šธ ๊ฒƒ ๊ฐ™๋„ค์š”
@@ -6,11 +6,17 @@ import { GroupedSection, GroupedReviews, ReviewInfoData, + WrittenReviewList, } from '@/types'; import createApiErrorMessage from './apiErrorMessageCreator'; import endPoint from './endpoints'; +export interface GetInfiniteReviewListApi { + lastReviewId: number | null; + size: number; +} + export const getDataToWriteReviewApi = async (reviewRequestCode: string) => { const response = await fetch(endPoint.gettingDataToWriteReview(reviewRequestCode), { method: 'GET', @@ -79,12 +85,7 @@ export const getDetailedReviewApi = async ({ reviewId }: GetDetailedReviewApi) = return data as DetailReviewData; }; -interface GetReviewListApi { - lastReviewId: number | null; - size: number; -} - -export const getReviewListApi = async ({ lastReviewId, size }: GetReviewListApi) => { +export const getReviewListApi = async ({ lastReviewId, size }: GetInfiniteReviewListApi) => { const response = await fetch(endPoint.gettingReviewList(lastReviewId, size), { method: 'GET', headers: { @@ -138,3 +139,20 @@ export const getGroupedReviews = async ({ sectionId }: GetGroupedReviewsProps) = const data = await response.json(); return data as GroupedReviews; }; + +export const getWrittenReviewList = async ({ lastReviewId, size }: GetInfiniteReviewListApi) => { + const response = await fetch(endPoint.gettingWrittenReviewList(lastReviewId, size), { + method: 'GET', + headers: { + 'Content-Type': 'application/json', + }, + credentials: 'include', + }); + + if (!response.ok) { + throw new Error(createApiErrorMessage(response.status)); + } + + const data = await response.json(); + return data as WrittenReviewList; +};
TypeScript
ํ•จ์ˆ˜์˜ ํŒŒ๋ผ๋ฏธํ„ฐ ํƒ€์ž…์ด๋ผ์„œ, ์ €๋Š” ์ด๋Ÿด ๋•Œ ํƒ€์ž…๋ช… ๋’ค์— params๋ฅผ ์ถ”๊ฐ€ํ•˜๋Š” ํŽธ์ด์—์š”.
@@ -0,0 +1,78 @@ +import { useMemo } from 'react'; + +import { useGetDetailedReview, useReviewId } from '@/hooks'; +import { substituteString } from '@/utils'; + +import QuestionAnswerSection from './QuestionAnswerSection'; +import ReviewDescription from './ReviewDescription'; +import * as S from './styles'; + +interface DetailedReviewProps { + $layoutStyle?: React.CSSProperties; + selectedReviewId?: number; +} + +const DetailedReview = ({ selectedReviewId, $layoutStyle }: DetailedReviewProps) => { + const reviewId = useReviewId(selectedReviewId); + + const { data: detailedReview } = useGetDetailedReview({ + reviewId: reviewId, + }); + + const parsedDetailedReview = useMemo(() => { + return { + ...detailedReview, + sections: detailedReview.sections.map((section) => { + const newHeader = substituteString({ + content: section.header, + variables: { revieweeName: detailedReview.revieweeName, projectName: detailedReview.projectName }, + }); + + const newQuestions = section.questions.map((question) => { + const newContent = substituteString({ + content: question.content, + variables: { revieweeName: detailedReview.revieweeName, projectName: detailedReview.projectName }, + }); + + return { + ...question, + content: newContent, + }; + }); + + return { + ...section, + header: newHeader, + questions: newQuestions, + }; + }), + }; + }, [detailedReview]); + + return ( + <S.DetailedReview $layoutStyle={$layoutStyle}> + <ReviewDescription + projectName={parsedDetailedReview.projectName} + date={new Date(parsedDetailedReview.createdAt)} + revieweeName={parsedDetailedReview.revieweeName} + /> + <S.Separator /> + <S.DetailedReviewContainer> + {parsedDetailedReview.sections.map((section) => + section.questions.map((question) => ( + <S.ReviewContentContainer key={question.questionId}> + <QuestionAnswerSection + question={question.content} + questionType={question.questionType} + answer={question.answer} + options={question.optionGroup?.options} + /> + </S.ReviewContentContainer> + )), + )} + </S.DetailedReviewContainer> + </S.DetailedReview> + ); +}; + +export default DetailedReview;
Unknown
sections ๊ด€๋ จ๋œ ๋ถ€๋ถ„ ์ฝ”๋“œ๊ฐ€ ๊ธธ์–ด์„œ, header์™€ questions๋ฅผ ๋ถ„๋ฆฌํ•˜๊ณ  ๊ฐ๊ฐ useMemo๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”'?
@@ -0,0 +1,28 @@ +import { Country } from "../types/country"; + +const CountryCard = ({ + country, + handleToggleCountry, +}: { + country: Country; + handleToggleCountry: (country: Country) => void; +}) => { + return ( + <div + className="flex flex-col border rounded gap-2 px-4" + onClick={() => handleToggleCountry(country)} + > + <div className="flex justify-center mb-2"> + <img + src={country.flags.svg} + alt={`${country.name.common} flag`} + className="w-32 h-20" + /> + </div> + <h2>{country.name.common}</h2> + <p>{country.capital}</p> + </div> + ); +}; + +export default CountryCard;
Unknown
h2 ํƒœ๊ทธ๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ์—” ๋„ˆ๋ฌด ๋งŽ์•„ ์งˆ ๊ฒƒ ๊ฐ™์€๋ฐ, ์ „์ฒด์ ์ธ ๊ด€์ ์œผ๋กœ ๋ดค์„๋•Œ h2์˜ ๋ ˆ๋ฒจ์„ ๊ฐ€์ง„ ํ…์ŠคํŠธ๋Š” ์•„๋‹Œ ๊ฒƒ ๊ฐ™์•„์„œ์š”! strong ํƒœ๊ทธ๋Œ€์‹  h2๋ฅผ ์“ฐ์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,66 @@ +import { useQuery } from "@tanstack/react-query"; +import { getCountries } from "../api/countryAPI"; +import CountryCard from "./CountryCard"; +import { useEffect } from "react"; +import { Country } from "../types/country"; +import useCountryStore from "../zustand/countryStore"; + +const CountryList = ({ isDone }: { isDone: boolean }) => { + const { countries, setCountries, favoriteCountries, setFavoriteCountries } = + useCountryStore(); + + const { data, error, isLoading } = useQuery({ + queryKey: ["countries"], + queryFn: getCountries, + }); + + const handleToggleCountry = (country: Country) => { + if (isDone) { + setFavoriteCountries( + favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3) + ); + setCountries([country, ...countries]); + } else { + setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3)); + setFavoriteCountries([country, ...favoriteCountries]); + } + }; + + useEffect(() => { + if (data) { + setCountries(data); + } + }, [data, setCountries]); + + if (isLoading) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">๋กœ๋”ฉ์ค‘์ž…๋‹ˆ๋‹ค!!</h1> + </div> + ); + } + + if (error) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค!</h1> + </div> + ); + } + + const isDoneCountries = isDone ? favoriteCountries : countries; + + return ( + <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8"> + {isDoneCountries.map((country) => ( + <CountryCard + key={country.cca3} + country={country} + handleToggleCountry={handleToggleCountry} + /> + ))} + </div> + ); +}; + +export default CountryList;
Unknown
early if pattern ์ถ”์ฒœ๋‘๋ฆฝ๋‹ˆ๋‹ค .. >_<
@@ -0,0 +1,66 @@ +import { useQuery } from "@tanstack/react-query"; +import { getCountries } from "../api/countryAPI"; +import CountryCard from "./CountryCard"; +import { useEffect } from "react"; +import { Country } from "../types/country"; +import useCountryStore from "../zustand/countryStore"; + +const CountryList = ({ isDone }: { isDone: boolean }) => { + const { countries, setCountries, favoriteCountries, setFavoriteCountries } = + useCountryStore(); + + const { data, error, isLoading } = useQuery({ + queryKey: ["countries"], + queryFn: getCountries, + }); + + const handleToggleCountry = (country: Country) => { + if (isDone) { + setFavoriteCountries( + favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3) + ); + setCountries([country, ...countries]); + } else { + setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3)); + setFavoriteCountries([country, ...favoriteCountries]); + } + }; + + useEffect(() => { + if (data) { + setCountries(data); + } + }, [data, setCountries]); + + if (isLoading) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">๋กœ๋”ฉ์ค‘์ž…๋‹ˆ๋‹ค!!</h1> + </div> + ); + } + + if (error) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค!</h1> + </div> + ); + } + + const isDoneCountries = isDone ? favoriteCountries : countries; + + return ( + <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8"> + {isDoneCountries.map((country) => ( + <CountryCard + key={country.cca3} + country={country} + handleToggleCountry={handleToggleCountry} + /> + ))} + </div> + ); +}; + +export default CountryList;
Unknown
countryList ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ณด๋‹ˆ, ๋‹จ์ˆœ UI๋งŒ ์ œ๊ณตํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ ํ•ต์‹ฌ ๋กœ์ง๋“ค์„ ์ „๋ถ€ ๋‹ค ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๊ฒƒ์œผ๋กœ ๋ณด์ž…๋‹ˆ๋‹ค. ํŒŒ์ผ๋ช…์œผ๋กœ๋งŒ ๋ณด์•˜์„๋•, UI ์—ญํ• ๋งŒ ํ•˜๊ณ  ์žˆ์„ ๊ฒƒ์œผ๋กœ ์ถ”์ธก๋˜์—ˆ๋Š”๋ฐ ์žฌํ™œ์šฉ ๊ฐ€๋Šฅํ•œ ์ปดํฌ๋„ŒํŠธ๋Š” ์•„๋‹Œ ๊ฒƒ ๊ฐ™์•„์„œ์š”~ ๊ฐœ์ธ์ ์ธ ์˜๊ฒฌ์œผ๋กœ๋Š” List์—๋Š” ๋‹จ์ˆœ ๋‚ด๋ ค์ค€ ๋ฐ์ดํ„ฐ๋ฅผ ๋…ธ์ถœํ•˜๊ฒŒ๋งŒ ํ•˜๊ณ , ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์€ ์œ„์—์„œ ์ „๋‹ฌํ•ด์ฃผ๋Š” ๊ฒƒ์ด ์–ด๋–ค์ง€ ์ฝ”๋ฉ˜ํŠธ ๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,15 @@ +import axios from "axios"; +import { Country } from "../types/country"; + +export const countryApi = axios.create({ + baseURL: "https://restcountries.com/v3.1", +}); + +export const getCountries = async (): Promise<Country[]> => { + try { + const response = await countryApi.get("/all"); + return response.data; + } catch (error) { + throw new Error(); + } +};
TypeScript
๋ณ„๋กœ ์ค‘์š”ํ•œ ๊ฒƒ์€ ์•„๋‹ˆ์ง€๋งŒ ใ…Žใ…Ž throw new Error() ์š”๊ธฐ์— ๋ญ”๊ฐ€๋ฅผ ๋„ฃ์–ด์ฃผ์‹œ๋ฉด ์ข‹์•„์š” ```javascript throw new Error(error.response?.data.message); ``` ์ด๋Ÿฐ์‹์œผ๋กœ์š” ใ…Žใ…Ž
@@ -0,0 +1,66 @@ +import { useQuery } from "@tanstack/react-query"; +import { getCountries } from "../api/countryAPI"; +import CountryCard from "./CountryCard"; +import { useEffect } from "react"; +import { Country } from "../types/country"; +import useCountryStore from "../zustand/countryStore"; + +const CountryList = ({ isDone }: { isDone: boolean }) => { + const { countries, setCountries, favoriteCountries, setFavoriteCountries } = + useCountryStore(); + + const { data, error, isLoading } = useQuery({ + queryKey: ["countries"], + queryFn: getCountries, + }); + + const handleToggleCountry = (country: Country) => { + if (isDone) { + setFavoriteCountries( + favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3) + ); + setCountries([country, ...countries]); + } else { + setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3)); + setFavoriteCountries([country, ...favoriteCountries]); + } + }; + + useEffect(() => { + if (data) { + setCountries(data); + } + }, [data, setCountries]); + + if (isLoading) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">๋กœ๋”ฉ์ค‘์ž…๋‹ˆ๋‹ค!!</h1> + </div> + ); + } + + if (error) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค!</h1> + </div> + ); + } + + const isDoneCountries = isDone ? favoriteCountries : countries; + + return ( + <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8"> + {isDoneCountries.map((country) => ( + <CountryCard + key={country.cca3} + country={country} + handleToggleCountry={handleToggleCountry} + /> + ))} + </div> + ); +}; + +export default CountryList;
Unknown
ํ•„ํ„ฐ๋ฅผ ํ•˜๊ธฐ ์œ„ํ•œ ์˜๋„๋กœ setCountries ๋ฅผ ๋งŒ๋“ค์–ด ๊ฐ’์„ ๋ณ€๊ฒฝํ•˜๊ณ  ์žˆ๋Š” ๊ฒƒ์œผ๋กœ ๋ณด์ž…๋‹ˆ๋‹ค! favoriteCountries ๋ผ๋Š” ์ƒํƒœ๋ฅผ ๋”ฐ๋กœ ์ง€๋‹ˆ๊ณ  ์žˆ๊ธฐ์— countries๋ฅผ ๋ณ€๊ฒฝํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค ์•„๋ž˜์—์„œ filter๋งŒ ํ•ด์ฃผ๋Š” ๋กœ์ง์œผ๋กœ ๋ณ€๊ฒฝํ•˜๋Š” ๊ฒƒ์ด ์–ด๋–จ์ง€ ์ œ์•ˆ ๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,66 @@ +import { useQuery } from "@tanstack/react-query"; +import { getCountries } from "../api/countryAPI"; +import CountryCard from "./CountryCard"; +import { useEffect } from "react"; +import { Country } from "../types/country"; +import useCountryStore from "../zustand/countryStore"; + +const CountryList = ({ isDone }: { isDone: boolean }) => { + const { countries, setCountries, favoriteCountries, setFavoriteCountries } = + useCountryStore(); + + const { data, error, isLoading } = useQuery({ + queryKey: ["countries"], + queryFn: getCountries, + }); + + const handleToggleCountry = (country: Country) => { + if (isDone) { + setFavoriteCountries( + favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3) + ); + setCountries([country, ...countries]); + } else { + setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3)); + setFavoriteCountries([country, ...favoriteCountries]); + } + }; + + useEffect(() => { + if (data) { + setCountries(data); + } + }, [data, setCountries]); + + if (isLoading) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">๋กœ๋”ฉ์ค‘์ž…๋‹ˆ๋‹ค!!</h1> + </div> + ); + } + + if (error) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค!</h1> + </div> + ); + } + + const isDoneCountries = isDone ? favoriteCountries : countries; + + return ( + <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8"> + {isDoneCountries.map((country) => ( + <CountryCard + key={country.cca3} + country={country} + handleToggleCountry={handleToggleCountry} + /> + ))} + </div> + ); +}; + +export default CountryList;
Unknown
์ด๊ฒƒ๋„ ์•„์ฃผ ์‚ฌ์†Œํ•œ ๊ฑฐ์ง€๋งŒ ใ…Žใ…Ž isDone ๋ณด๋‹ค isFavorite ์ด ์•Œ๊ธฐ ์‰ฌ์šธ๊ฒƒ ๊ฐ™์•„์šฉใ…Žใ…Ž
@@ -0,0 +1,66 @@ +import { useQuery } from "@tanstack/react-query"; +import { getCountries } from "../api/countryAPI"; +import CountryCard from "./CountryCard"; +import { useEffect } from "react"; +import { Country } from "../types/country"; +import useCountryStore from "../zustand/countryStore"; + +const CountryList = ({ isDone }: { isDone: boolean }) => { + const { countries, setCountries, favoriteCountries, setFavoriteCountries } = + useCountryStore(); + + const { data, error, isLoading } = useQuery({ + queryKey: ["countries"], + queryFn: getCountries, + }); + + const handleToggleCountry = (country: Country) => { + if (isDone) { + setFavoriteCountries( + favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3) + ); + setCountries([country, ...countries]); + } else { + setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3)); + setFavoriteCountries([country, ...favoriteCountries]); + } + }; + + useEffect(() => { + if (data) { + setCountries(data); + } + }, [data, setCountries]); + + if (isLoading) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">๋กœ๋”ฉ์ค‘์ž…๋‹ˆ๋‹ค!!</h1> + </div> + ); + } + + if (error) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค!</h1> + </div> + ); + } + + const isDoneCountries = isDone ? favoriteCountries : countries; + + return ( + <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8"> + {isDoneCountries.map((country) => ( + <CountryCard + key={country.cca3} + country={country} + handleToggleCountry={handleToggleCountry} + /> + ))} + </div> + ); +}; + +export default CountryList;
Unknown
๋™์ผํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,18 @@ +import CountryList from "../components/CountryList"; + +const Home = () => { + return ( + <> + <h1 className="flex justify-center items-center mt-8 mb-8 text-2xl font-bold"> + Favorite Countries + </h1> + <CountryList isDone={true} /> + <h1 className="flex justify-center items-center mb-8 text-3xl font-bold"> + Countries + </h1> + <CountryList isDone={false} /> + </> + ); +}; + +export default Home;
Unknown
h1์ด ๋„ˆ๋ฌด ๋งŽ์Šต๋‹ˆ๋‹ค! ํŽ˜์ด์ง€์— ํ•˜๋‚˜๋งŒ ์กด์žฌํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ์ฝ”๋“œ์—์„œ๋„ ํ˜ผ๋ž€์„ ์•ผ๊ธฐํ•  ์ˆ˜ ์žˆ๋Š” ํ—ค๋”ฉํƒœ๊ทธ๋ฅผ ์ง€์–‘ํ•˜๋Š” ๊ฒƒ์„ ์ œ์•ˆ๋“œ๋ฆฝ๋‹ˆ๋‹ค :)
@@ -0,0 +1,15 @@ +import axios from "axios"; +import { Country } from "../types/country"; + +export const countryApi = axios.create({ + baseURL: "https://restcountries.com/v3.1", +}); + +export const getCountries = async (): Promise<Country[]> => { + try { + const response = await countryApi.get("/all"); + return response.data; + } catch (error) { + throw new Error(); + } +};
TypeScript
์ œ๊ฐ€ ์ด๋ฒˆ์— ์Šค์Šค๋กœ ์จ๋ณธ๊ฑด ์ฒ˜์Œ์ด๋ผ ์ž˜ ๋ชฐ๋ž๋Š”๋ฐ ์€๋‹˜ ์ฝ”๋“œ ๋ณด๋ฉด์„œ ๊นจ๋‹ฌ์•˜์Šต๋‹ˆ๋‹ค ๊ฐ์‚ผ๋Œœ
@@ -0,0 +1,66 @@ +import { useQuery } from "@tanstack/react-query"; +import { getCountries } from "../api/countryAPI"; +import CountryCard from "./CountryCard"; +import { useEffect } from "react"; +import { Country } from "../types/country"; +import useCountryStore from "../zustand/countryStore"; + +const CountryList = ({ isDone }: { isDone: boolean }) => { + const { countries, setCountries, favoriteCountries, setFavoriteCountries } = + useCountryStore(); + + const { data, error, isLoading } = useQuery({ + queryKey: ["countries"], + queryFn: getCountries, + }); + + const handleToggleCountry = (country: Country) => { + if (isDone) { + setFavoriteCountries( + favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3) + ); + setCountries([country, ...countries]); + } else { + setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3)); + setFavoriteCountries([country, ...favoriteCountries]); + } + }; + + useEffect(() => { + if (data) { + setCountries(data); + } + }, [data, setCountries]); + + if (isLoading) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">๋กœ๋”ฉ์ค‘์ž…๋‹ˆ๋‹ค!!</h1> + </div> + ); + } + + if (error) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค!</h1> + </div> + ); + } + + const isDoneCountries = isDone ? favoriteCountries : countries; + + return ( + <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8"> + {isDoneCountries.map((country) => ( + <CountryCard + key={country.cca3} + country={country} + handleToggleCountry={handleToggleCountry} + /> + ))} + </div> + ); +}; + +export default CountryList;
Unknown
์•„๋งˆ ๊ณต๋ถ€๋ฅผ ์œ„ํ•ด์„œ ํ•˜์‹  ๋“ฏ ํ•ฉ๋‹ˆ๋‹ค๋งŒ..! zustand ์Šคํ† ์–ด์— countries ์™€ favoriteCountries ๊ฐ€ ์žˆ๊ณ  ์‹ค์ œ๋กœ ```javascript const isDoneCountries = isDone ? favoriteCountries : countries; ``` ์ด๋Ÿฐ ๋ถ€๋ถ„์—์„œ๋„ useQuery ์˜ data ๋ฅผ ๋”ฐ๋กœ ์“ฐ์ง€๋Š” ์•Š์œผ๋‹ˆ, ์ด๋Ÿฐ ๊ฒฝ์šฐ๋ผ๋ฉด tanstack์„ ์•ˆ์“ฐ๋Š” ๋ฐฉํ–ฅ๋„ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค~ ๋ฌผ๋ก  ๊ณต๋ถ€์šฉ์ด๊ธฐ ๋•Œ๋ฌธ์— ๋ฌด์‹œํ•˜์…”๋„ ๋ฉ๋‹ˆ๋‹ค ^^;;
@@ -0,0 +1,28 @@ +import { Country } from "../types/country"; + +const CountryCard = ({ + country, + handleToggleCountry, +}: { + country: Country; + handleToggleCountry: (country: Country) => void; +}) => { + return ( + <div + className="flex flex-col border rounded gap-2 px-4" + onClick={() => handleToggleCountry(country)} + > + <div className="flex justify-center mb-2"> + <img + src={country.flags.svg} + alt={`${country.name.common} flag`} + className="w-32 h-20" + /> + </div> + <h2>{country.name.common}</h2> + <p>{country.capital}</p> + </div> + ); +}; + +export default CountryCard;
Unknown
์•„ ๊ทธ๋ƒฅ..h1๋ฐ‘์— ํ•˜์œ„๋กœ ์žˆ๋‹ค ์ƒ๊ฐํ•ด์„œ ์•„๋ฌด ์ƒ๊ฐ์—†์ด h2๋ฅผ ์“ด๊ฒ๋‹ˆ๋‹ค.. ๊ทธ๋ ‡๊ตฐ์—ฌ.. html css์— ๋Œ€ํ•ด์„œ ๋”ฐ๋กœ ๊ณต๋ถ€๋ฅผ ์•ˆํ•˜๊ณ  ํ•„์š”ํ•  ๋•Œ๋งˆ๋‹ค ๊ทธ๋ƒฅ ๊ทธ ๋•Œ ๊ทธ๋•Œ ์“ฐ๋‹ค๋ณด๋‹ˆ ์ด๋Ÿฐ ๋ถ€๋ถ„์ด ์•„์ง ๋งŽ์ด ๋ฏธํกํ•œ๋“ฏํ•˜๋„ค์—ฌ ํ›„...
@@ -0,0 +1,66 @@ +import { useQuery } from "@tanstack/react-query"; +import { getCountries } from "../api/countryAPI"; +import CountryCard from "./CountryCard"; +import { useEffect } from "react"; +import { Country } from "../types/country"; +import useCountryStore from "../zustand/countryStore"; + +const CountryList = ({ isDone }: { isDone: boolean }) => { + const { countries, setCountries, favoriteCountries, setFavoriteCountries } = + useCountryStore(); + + const { data, error, isLoading } = useQuery({ + queryKey: ["countries"], + queryFn: getCountries, + }); + + const handleToggleCountry = (country: Country) => { + if (isDone) { + setFavoriteCountries( + favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3) + ); + setCountries([country, ...countries]); + } else { + setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3)); + setFavoriteCountries([country, ...favoriteCountries]); + } + }; + + useEffect(() => { + if (data) { + setCountries(data); + } + }, [data, setCountries]); + + if (isLoading) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">๋กœ๋”ฉ์ค‘์ž…๋‹ˆ๋‹ค!!</h1> + </div> + ); + } + + if (error) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค!</h1> + </div> + ); + } + + const isDoneCountries = isDone ? favoriteCountries : countries; + + return ( + <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8"> + {isDoneCountries.map((country) => ( + <CountryCard + key={country.cca3} + country={country} + handleToggleCountry={handleToggleCountry} + /> + ))} + </div> + ); +}; + +export default CountryList;
Unknown
์˜ค์˜ค ๊ฐ™์€ ์ƒ๊ฐ์ž…๋‹ˆ๋‹ค~~
@@ -0,0 +1,66 @@ +import { useQuery } from "@tanstack/react-query"; +import { getCountries } from "../api/countryAPI"; +import CountryCard from "./CountryCard"; +import { useEffect } from "react"; +import { Country } from "../types/country"; +import useCountryStore from "../zustand/countryStore"; + +const CountryList = ({ isDone }: { isDone: boolean }) => { + const { countries, setCountries, favoriteCountries, setFavoriteCountries } = + useCountryStore(); + + const { data, error, isLoading } = useQuery({ + queryKey: ["countries"], + queryFn: getCountries, + }); + + const handleToggleCountry = (country: Country) => { + if (isDone) { + setFavoriteCountries( + favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3) + ); + setCountries([country, ...countries]); + } else { + setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3)); + setFavoriteCountries([country, ...favoriteCountries]); + } + }; + + useEffect(() => { + if (data) { + setCountries(data); + } + }, [data, setCountries]); + + if (isLoading) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">๋กœ๋”ฉ์ค‘์ž…๋‹ˆ๋‹ค!!</h1> + </div> + ); + } + + if (error) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค!</h1> + </div> + ); + } + + const isDoneCountries = isDone ? favoriteCountries : countries; + + return ( + <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8"> + {isDoneCountries.map((country) => ( + <CountryCard + key={country.cca3} + country={country} + handleToggleCountry={handleToggleCountry} + /> + ))} + </div> + ); +}; + +export default CountryList;
Unknown
๋งž๋Š” ๋ง์”€์ž…๋‹ˆ๋‹ค ํ›จ์”ฌ ์ข‹๊ฒŸ๊ตฐ์—ฌ
@@ -0,0 +1,18 @@ +import CountryList from "../components/CountryList"; + +const Home = () => { + return ( + <> + <h1 className="flex justify-center items-center mt-8 mb-8 text-2xl font-bold"> + Favorite Countries + </h1> + <CountryList isDone={true} /> + <h1 className="flex justify-center items-center mb-8 text-3xl font-bold"> + Countries + </h1> + <CountryList isDone={false} /> + </> + ); +}; + +export default Home;
Unknown
h1ํƒœ๊ทธ๋Š” ํŽ˜์ด์ง€๋‹น 1๊ฐœ๋งŒ ์จ์•ผํ•˜๋Š”์ง€ ๋ชฐ๋ž๋„ค์—ฌ... ๋ช…์‹ฌํ•˜๊ฒ ์Šต๋‹ˆ๋‹น
@@ -0,0 +1,15 @@ +import axios from "axios"; +import { Country } from "../types/country"; + +export const countryApi = axios.create({ + baseURL: "https://restcountries.com/v3.1", +}); + +export const getCountries = async (): Promise<Country[]> => { + try { + const response = await countryApi.get("/all"); + return response.data; + } catch (error) { + throw new Error(); + } +};
TypeScript
์ฃผ์˜ :: ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ ์ž˜ ๋ชฐ๋ผ์„œ ์ด์ƒํ•œ ์†Œ๋ฆฌ์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค ใ…  getCountires ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜๊ฐ’์ด Promise<Country[]>์ž„์„ ๋ช…์‹œํ•ด์ฃผ๊ณ  ๊ณ„์‹œ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ €๋Š” ์ด๋ฒˆ API ๊ตฌ์กฐ๊ฐ€ ๋ณต์žกํ•ด์„œ์ธ์ง€ ๋ฌด์Šจ ์—๋Ÿฌ์˜€๋Š”์ง€ ์ž์„ธํžˆ ๊ธฐ์–ต์€ ์•ˆ ๋‚˜์ง€๋งŒ ์—๋Ÿฌ๋ฅผ ๊ณ„์† ๊ฒช์—ˆ์Šต๋‹ˆ๋‹ค~! try๋ฌธ ์•ˆ์—์„œ get ์š”์ฒญ ๋ถ€๋ถ„์„ ๋ณด๋ฉด ์‘๋‹ต๊ฐ’์˜ ํƒ€์ž… ์ง€์ •์ด ์•ˆ ๋˜์–ด ์žˆ๋Š”๋ฐ, ์ €๋Š” ์ด ๋ถ€๋ถ„์—์„œ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์—ˆ๋˜ ๊ฒƒ์œผ๋กœ ๊ธฐ์–ตํ•ฉ๋‹ˆ๋‹ค! `const response = await countryApi.get<Country[]>("/all");` ์˜ˆ๋ฅผ ๋“ค์–ด์„œ data.wonyoung.common ์ด๋ผ๋Š” ํ•„๋“œ๋Š” API ์‘๋‹ต๊ฐ’์— ์žˆ์ง€๋„ ์•Š์€๋ฐ ์ž…๋ ฅํ•ด์„œ ํœด๋จผ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•œ ๊ฒฝ์šฐ, ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜๊ฐ’์—๋งŒ ํƒ€์ž…์„ ์ง€์ •ํ•ด์ฃผ๋ฉด ๊ทธ๋ƒฅ ์ด ๋ฌธ์ œ๋ฅผ ์Šคํ‚ตํ•˜๋Š”๋ฐ, ํ†ต์‹ ์˜ ์‘๋‹ต๊ฐ’์—๋„ ํƒ€์ž…์„ ์ง€์ •ํ•ด์ฃผ๋ฉด ์ปดํŒŒ์ผ ๋‹จ๊ณ„์—์„œ ์—๋Ÿฌ์— ๋ง‰ํžˆ๋Š” ๊ฒƒ์œผ๋กœ ์ดํ•ดํ–ˆ๋Š”๋ฐ ์ œ๋Œ€๋กœ ์ดํ•ดํ•œ ๊ฑด์ง€๋Š” ์ž˜ ๋ชจ๋ฅด๊ฒ ๋„ค์š”!
@@ -0,0 +1,66 @@ +import { useQuery } from "@tanstack/react-query"; +import { getCountries } from "../api/countryAPI"; +import CountryCard from "./CountryCard"; +import { useEffect } from "react"; +import { Country } from "../types/country"; +import useCountryStore from "../zustand/countryStore"; + +const CountryList = ({ isDone }: { isDone: boolean }) => { + const { countries, setCountries, favoriteCountries, setFavoriteCountries } = + useCountryStore(); + + const { data, error, isLoading } = useQuery({ + queryKey: ["countries"], + queryFn: getCountries, + }); + + const handleToggleCountry = (country: Country) => { + if (isDone) { + setFavoriteCountries( + favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3) + ); + setCountries([country, ...countries]); + } else { + setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3)); + setFavoriteCountries([country, ...favoriteCountries]); + } + }; + + useEffect(() => { + if (data) { + setCountries(data); + } + }, [data, setCountries]); + + if (isLoading) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">๋กœ๋”ฉ์ค‘์ž…๋‹ˆ๋‹ค!!</h1> + </div> + ); + } + + if (error) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค!</h1> + </div> + ); + } + + const isDoneCountries = isDone ? favoriteCountries : countries; + + return ( + <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8"> + {isDoneCountries.map((country) => ( + <CountryCard + key={country.cca3} + country={country} + handleToggleCountry={handleToggleCountry} + /> + ))} + </div> + ); +}; + +export default CountryList;
Unknown
ํ™ˆํŽ˜์ด์ง€ ๊ด€๋ จํ•ด์„œ ์ ์–ด์ฃผ์‹  ๊ฒƒ์ฒ˜๋Ÿผ ํƒœ๊ทธ ์ด๋ฆ„์„ ๋ฐ”๊พธ๋Š”๊ฒŒ ์ข‹๋‹ค๋Š” ๋ง์”€์ด์‹ ๊ฐ€์š”?
@@ -0,0 +1,28 @@ +import { Country } from "../types/country"; + +const CountryCard = ({ + country, + handleToggleCountry, +}: { + country: Country; + handleToggleCountry: (country: Country) => void; +}) => { + return ( + <div + className="flex flex-col border rounded gap-2 px-4" + onClick={() => handleToggleCountry(country)} + > + <div className="flex justify-center mb-2"> + <img + src={country.flags.svg} + alt={`${country.name.common} flag`} + className="w-32 h-20" + /> + </div> + <h2>{country.name.common}</h2> + <p>{country.capital}</p> + </div> + ); +}; + +export default CountryCard;
Unknown
์ฐธ๊ณ : - https://techblog.woowahan.com/15541/ - https://webactually.com/2020/03/03/%3Csection%3E%EC%9D%84-%EB%B2%84%EB%A6%AC%EA%B3%A0-HTML5-%3Carticle%3E%EC%9D%84-%EC%8D%A8%EC%95%BC-%ED%95%98%EB%8A%94-%EC%9D%B4%EC%9C%A0/
@@ -0,0 +1,66 @@ +import { useQuery } from "@tanstack/react-query"; +import { getCountries } from "../api/countryAPI"; +import CountryCard from "./CountryCard"; +import { useEffect } from "react"; +import { Country } from "../types/country"; +import useCountryStore from "../zustand/countryStore"; + +const CountryList = ({ isDone }: { isDone: boolean }) => { + const { countries, setCountries, favoriteCountries, setFavoriteCountries } = + useCountryStore(); + + const { data, error, isLoading } = useQuery({ + queryKey: ["countries"], + queryFn: getCountries, + }); + + const handleToggleCountry = (country: Country) => { + if (isDone) { + setFavoriteCountries( + favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3) + ); + setCountries([country, ...countries]); + } else { + setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3)); + setFavoriteCountries([country, ...favoriteCountries]); + } + }; + + useEffect(() => { + if (data) { + setCountries(data); + } + }, [data, setCountries]); + + if (isLoading) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">๋กœ๋”ฉ์ค‘์ž…๋‹ˆ๋‹ค!!</h1> + </div> + ); + } + + if (error) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค!</h1> + </div> + ); + } + + const isDoneCountries = isDone ? favoriteCountries : countries; + + return ( + <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8"> + {isDoneCountries.map((country) => ( + <CountryCard + key={country.cca3} + country={country} + handleToggleCountry={handleToggleCountry} + /> + ))} + </div> + ); +}; + +export default CountryList;
Unknown
๊ทธ ์ƒ๊ฐ์€ ๋ชปํ•ด๋ดค๋Š”๋ฐ ๋™์ผํ•œ ๊ฒฐ๊ณผ๊ฐ€...๋‚˜์˜ค๋Š”์ง€ ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค ใ…Žใ…Ž... ํ•œ๋ฒˆ์˜ ๋™์ž‘์œผ๋กœ ์•„ ์กฐ๊ฑด๋ฌธ์„ ๊ฐœ์„ ํ•˜๋ฉด ๋˜๊ฒ ๊ตฐ์—ฌ!
@@ -0,0 +1,66 @@ +import { useQuery } from "@tanstack/react-query"; +import { getCountries } from "../api/countryAPI"; +import CountryCard from "./CountryCard"; +import { useEffect } from "react"; +import { Country } from "../types/country"; +import useCountryStore from "../zustand/countryStore"; + +const CountryList = ({ isDone }: { isDone: boolean }) => { + const { countries, setCountries, favoriteCountries, setFavoriteCountries } = + useCountryStore(); + + const { data, error, isLoading } = useQuery({ + queryKey: ["countries"], + queryFn: getCountries, + }); + + const handleToggleCountry = (country: Country) => { + if (isDone) { + setFavoriteCountries( + favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3) + ); + setCountries([country, ...countries]); + } else { + setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3)); + setFavoriteCountries([country, ...favoriteCountries]); + } + }; + + useEffect(() => { + if (data) { + setCountries(data); + } + }, [data, setCountries]); + + if (isLoading) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">๋กœ๋”ฉ์ค‘์ž…๋‹ˆ๋‹ค!!</h1> + </div> + ); + } + + if (error) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค!</h1> + </div> + ); + } + + const isDoneCountries = isDone ? favoriteCountries : countries; + + return ( + <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8"> + {isDoneCountries.map((country) => ( + <CountryCard + key={country.cca3} + country={country} + handleToggleCountry={handleToggleCountry} + /> + ))} + </div> + ); +}; + +export default CountryList;
Unknown
์ด๊ฑด ์ œ๊ฐ€ ๋ญ ๋ง์”€ํ•˜์‹œ๋Š”์ง€ ์ž˜ ๋ชฐ๋ผ์„œ...ํ•™์Šตํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค ใ… ..
@@ -0,0 +1,66 @@ +import { useQuery } from "@tanstack/react-query"; +import { getCountries } from "../api/countryAPI"; +import CountryCard from "./CountryCard"; +import { useEffect } from "react"; +import { Country } from "../types/country"; +import useCountryStore from "../zustand/countryStore"; + +const CountryList = ({ isDone }: { isDone: boolean }) => { + const { countries, setCountries, favoriteCountries, setFavoriteCountries } = + useCountryStore(); + + const { data, error, isLoading } = useQuery({ + queryKey: ["countries"], + queryFn: getCountries, + }); + + const handleToggleCountry = (country: Country) => { + if (isDone) { + setFavoriteCountries( + favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3) + ); + setCountries([country, ...countries]); + } else { + setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3)); + setFavoriteCountries([country, ...favoriteCountries]); + } + }; + + useEffect(() => { + if (data) { + setCountries(data); + } + }, [data, setCountries]); + + if (isLoading) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">๋กœ๋”ฉ์ค‘์ž…๋‹ˆ๋‹ค!!</h1> + </div> + ); + } + + if (error) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค!</h1> + </div> + ); + } + + const isDoneCountries = isDone ? favoriteCountries : countries; + + return ( + <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8"> + {isDoneCountries.map((country) => ( + <CountryCard + key={country.cca3} + country={country} + handleToggleCountry={handleToggleCountry} + /> + ))} + </div> + ); +}; + +export default CountryList;
Unknown
์ด ๋ถ€๋ถ„์€ home.tsx์—์„œ๋Š” ์ „์ฒด์ ์ธ UI ๋ฐ ํŽ˜์ด์ง€ ๊ด€๋ จ๋งŒ ๋‚˜ํƒ€๋‚ด๊ณ  List์—์„œ Card๋ฅผ ํ•ธ๋“ค๋ง ํ•  ์ˆ˜ ์žˆ๋„๋ก ์ƒ๊ฐ์„ ํ•ด์„œ ๋กœ์ง์„ ๊ตฌํ˜„ํ–ˆ๋Š”๋ฐ ์ด๋Ÿฐ ํ•ธ๋“ค๋ง ๋กœ์ง์€ home.tsx๊ฐ€ ๋” ์ ์ ˆํ•˜๋‹จ ๋ง์”€์ด์‹ค๊นŒ์—ฌ??
@@ -0,0 +1,15 @@ +import axios from "axios"; +import { Country } from "../types/country"; + +export const countryApi = axios.create({ + baseURL: "https://restcountries.com/v3.1", +}); + +export const getCountries = async (): Promise<Country[]> => { + try { + const response = await countryApi.get("/all"); + return response.data; + } catch (error) { + throw new Error(); + } +};
TypeScript
์•„ ๊ทธ๋ ‡๊ตฐ์—ฌ! ์ €๋Š” ์ผ๋‹จ jsํ•˜๋“ฏ์ด ์ž‘์„ฑ ํ•œ ํ›„์— strict๋ชจ๋“œ๊ฐ€ ์„ค์ • ๋˜์–ด์žˆ์œผ๋‹ˆ ts์—์„œ ์ƒˆ๋กœ ๋ฐœ์ƒํ•œ ์˜ค๋ฅ˜์— ๋งž์ถฐ ์ˆ˜์ •ํ–ˆ์–ด๊ฐ€์ง€๊ณ  ๋ฐ˜ํ™˜๊ฐ’๋งŒ ๋ช…์‹œํ•˜๊ณ  ์˜ค๋ฅ˜๊ฐ€ ์‚ฌ๋ผ์กŒ๊ธธ๋ž˜ ๊ทธ ๋ถ€๋ถ„์€ ๋ฏธ์ฒ˜ ์ƒ๊ฐ์„ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค. ์•„๋ฌด๋ž˜๋„ ๋ชจ๋“  ๊ฐ’์— ์ •ํ™•ํ•œ ํƒ€์ž…์„ ๋ช…์‹œํ•˜๋Š”๊ฑด ์ €๋„ ํ•ด์•ผ๊ฒ ๋‹ค ์ƒ๊ฐํ–ˆ๋Š”๋ฐ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,66 @@ +import { useQuery } from "@tanstack/react-query"; +import { getCountries } from "../api/countryAPI"; +import CountryCard from "./CountryCard"; +import { useEffect } from "react"; +import { Country } from "../types/country"; +import useCountryStore from "../zustand/countryStore"; + +const CountryList = ({ isDone }: { isDone: boolean }) => { + const { countries, setCountries, favoriteCountries, setFavoriteCountries } = + useCountryStore(); + + const { data, error, isLoading } = useQuery({ + queryKey: ["countries"], + queryFn: getCountries, + }); + + const handleToggleCountry = (country: Country) => { + if (isDone) { + setFavoriteCountries( + favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3) + ); + setCountries([country, ...countries]); + } else { + setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3)); + setFavoriteCountries([country, ...favoriteCountries]); + } + }; + + useEffect(() => { + if (data) { + setCountries(data); + } + }, [data, setCountries]); + + if (isLoading) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">๋กœ๋”ฉ์ค‘์ž…๋‹ˆ๋‹ค!!</h1> + </div> + ); + } + + if (error) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค!</h1> + </div> + ); + } + + const isDoneCountries = isDone ? favoriteCountries : countries; + + return ( + <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8"> + {isDoneCountries.map((country) => ( + <CountryCard + key={country.cca3} + country={country} + handleToggleCountry={handleToggleCountry} + /> + ))} + </div> + ); +}; + +export default CountryList;
Unknown
prop ํƒ€์ž…์„ ์ธ๋ผ์ธ์œผ๋กœ ์ •์˜ํ•œ ์ด์œ ๊ฐ€ ์žˆ๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,66 @@ +import { useQuery } from "@tanstack/react-query"; +import { getCountries } from "../api/countryAPI"; +import CountryCard from "./CountryCard"; +import { useEffect } from "react"; +import { Country } from "../types/country"; +import useCountryStore from "../zustand/countryStore"; + +const CountryList = ({ isDone }: { isDone: boolean }) => { + const { countries, setCountries, favoriteCountries, setFavoriteCountries } = + useCountryStore(); + + const { data, error, isLoading } = useQuery({ + queryKey: ["countries"], + queryFn: getCountries, + }); + + const handleToggleCountry = (country: Country) => { + if (isDone) { + setFavoriteCountries( + favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3) + ); + setCountries([country, ...countries]); + } else { + setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3)); + setFavoriteCountries([country, ...favoriteCountries]); + } + }; + + useEffect(() => { + if (data) { + setCountries(data); + } + }, [data, setCountries]); + + if (isLoading) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">๋กœ๋”ฉ์ค‘์ž…๋‹ˆ๋‹ค!!</h1> + </div> + ); + } + + if (error) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค!</h1> + </div> + ); + } + + const isDoneCountries = isDone ? favoriteCountries : countries; + + return ( + <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8"> + {isDoneCountries.map((country) => ( + <CountryCard + key={country.cca3} + country={country} + handleToggleCountry={handleToggleCountry} + /> + ))} + </div> + ); +}; + +export default CountryList;
Unknown
์•„...์›๋ž˜ data๋กœ mpa์„ ๋Œ๋ ธ์—ˆ๋Š”๋ฐ...;; ์ด๊ฒŒ isDone๊ฐ’์„ ๊ผญ ์จ๋ณด๋ ค๊ณ  ๋…ธ๋ ฅํ•˜๋‹ค๋ณด๋‹ˆ ์–ด์ฉŒ๋‹ค ๊ทธ๋ ‡๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค ใ… ใ… ... ๋ง์”€๋Œ€๋กœ ์ง€๊ธˆ ์ฟผ๋ฆฌ๊ฐ€ ์ดˆ๊ธฐ๊ฐ’ ๋„ฃ์–ด์ฃผ๋Š”๊ฑฐ๋ง๊ณ  ๋”ฑํžˆ ์•ˆ์“ฐ์ด๊ธดํ•ฉ๋‹ˆ๋‹ค..
@@ -0,0 +1,66 @@ +import { useQuery } from "@tanstack/react-query"; +import { getCountries } from "../api/countryAPI"; +import CountryCard from "./CountryCard"; +import { useEffect } from "react"; +import { Country } from "../types/country"; +import useCountryStore from "../zustand/countryStore"; + +const CountryList = ({ isDone }: { isDone: boolean }) => { + const { countries, setCountries, favoriteCountries, setFavoriteCountries } = + useCountryStore(); + + const { data, error, isLoading } = useQuery({ + queryKey: ["countries"], + queryFn: getCountries, + }); + + const handleToggleCountry = (country: Country) => { + if (isDone) { + setFavoriteCountries( + favoriteCountries.filter((toggle) => toggle.cca3 !== country.cca3) + ); + setCountries([country, ...countries]); + } else { + setCountries(countries.filter((toggle) => toggle.cca3 !== country.cca3)); + setFavoriteCountries([country, ...favoriteCountries]); + } + }; + + useEffect(() => { + if (data) { + setCountries(data); + } + }, [data, setCountries]); + + if (isLoading) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">๋กœ๋”ฉ์ค‘์ž…๋‹ˆ๋‹ค!!</h1> + </div> + ); + } + + if (error) { + return ( + <div className="flex justify-center items-center"> + <h1 className="text-4xl">์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค!</h1> + </div> + ); + } + + const isDoneCountries = isDone ? favoriteCountries : countries; + + return ( + <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 px-8"> + {isDoneCountries.map((country) => ( + <CountryCard + key={country.cca3} + country={country} + handleToggleCountry={handleToggleCountry} + /> + ))} + </div> + ); +}; + +export default CountryList;
Unknown
์ €๋„ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค..!!!
@@ -0,0 +1,84 @@ +export interface Country { + name: { + common: string; + official: string; + nativeName: { + [key: string]: { + official: string; + common: string; + }; + }; + }; + tld: string[]; + cca2: string; + ccn3: string; + cca3: string; + cioc: string; + independent: boolean; + status: string; + unMember: boolean; + currencies: { + [key: string]: { + name: string; + symbol: string; + }; + }; + idd: { + root: string; + suffixes: string[]; + }; + capital: string[]; + altSpellings: string[]; + region: string; + subregion: string; + languages: { + [key: string]: string; + }; + translations: { + [key: string]: { + official: string; + common: string; + }; + }; + latlng: number[]; + landlocked: boolean; + area: number; + demonyms: { + eng: { + f: string; + m: string; + }; + }; + flag: string; + maps: { + googleMaps: string; + openStreetMaps: string; + }; + population: number; + gini: { + [key: string]: number; + }; + fifa: string; + car: { + signs: string[]; + side: string; + }; + timezones: string[]; + continents: string[]; + flags: { + png: string; + svg: string; + }; + coatOfArms: { + png?: string; + svg?: string; + }; + startOfWeek: string; + capitalInfo: { + latlng: number[]; + }; + postalCode: { + format: string; + regex: string; + }; +}
TypeScript
์ €๋„ ์‚ฌ์‹ค ๋ชจ๋“  ๋ฐ์ดํ„ฐ๋ฅผ ๋‹ค ๋ณด์ง€ ์•Š์•˜์ง€๋งŒ, ๋ช‡๋ช‡ ๋ฐ์ดํ„ฐ๋Š” ์„ ํƒ์ ์œผ๋กœ ๋“ค์–ด์˜ค๋Š” ๊ฒƒ ๊ฐ™๋”๋ผ๊ตฌ์š”..!! ๊ทธ๋ž˜์„œ ๋ชจ๋“  ๋ฐ์ดํ„ฐ์— ๋‹ค ๋“ค์–ด์˜ค๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ๋ฉด ์˜ต์…”๋„์„ ๋ถ™์—ฌ์ฃผ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค..!!
@@ -0,0 +1,89 @@ +package store.controller; + +import java.util.ArrayList; +import java.util.List; +import store.model.Order; +import store.model.Promotion; +import store.model.Receipt; +import store.model.Store; +import store.service.StoreService; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + private final InputView inputView; + private final OutputView outputView; + private final StoreService storeService; + + public StoreController(InputView inputView, OutputView outputView, StoreService storeService) { + this.inputView = inputView; + this.outputView = outputView; + this.storeService = storeService; + } + + public void run() { + List<Store> store = printProductList(); + List<Promotion> promotions = loadPromotions(); + Order order; + + do { + order = purchaseProduct(store); + priceCalculator(store, order, promotions); + + } while (!checkEnd(store, order)); + } + + private boolean checkEnd(List<Store> store, Order order) { + while (true) { + try { + if (!storeService.isAnswer(inputView.inputEndMessage())) { + return true; + } + updateStore(store, order); + return false; + } catch (IllegalArgumentException e) { + outputView.printError(e.getMessage()); + } + } + } + + private void updateStore(List<Store> store, Order order) { + storeService.checkStock(store, order); + outputView.printProductList(store); + } + + private void priceCalculator(List<Store> store, Order order, List<Promotion> promotions) { + List<Receipt> receipts = storeService.parseReceipt(store, order, promotions); + storeService.checkTribeQuantity(receipts, store); + storeService.checkTribePromotion(receipts, store); + int discount = storeService.membershipDiscount(receipts); + + outputView.printReceipt(receipts, discount); + } + + private List<Store> printProductList() { + List<Store> store = new ArrayList<>(); + storeService.loadProductsForm(store); + outputView.printProductList(store); + return store; + } + + private List<Promotion> loadPromotions() { + List<Promotion> promotions = new ArrayList<>(); + storeService.loadPromotionsForm(promotions); + return promotions; + } + + private Order purchaseProduct(List<Store> store) { + while (true) { + try { + String inputOrder = inputView.inputPurchaseProduct(); + Order order = new Order(inputOrder); + storeService.checkProduct(store, order); + return order; + } catch (IllegalArgumentException e) { + outputView.printError(e.getMessage()); + } + } + } +}
Java
order๋ฅผ do ๋‚ด๋ถ€์—์„œ ์„ ์–ธํ•˜๋Š” ๊ฒƒ์ด ๋” ๊น”๋”ํ•˜์ง€ ์•Š์„๊นŒ ์ƒ๊ฐ์ด ๋“œ๋„ค์š”..! checkEnd() ๋‚ด๋ถ€์˜ updateStore() ๋ฅผ do ๊ตฌ๋ฌธ ๋‚ด๋ถ€๋กœ ์ด๋™์‹œํ‚จ๋‹ค๋ฉด ๊ฐ€๋Šฅํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค..!
@@ -0,0 +1,59 @@ +package store.model; + +import static store.utils.ErrorMessage.INVALID_FORMAT; + +import java.util.ArrayList; +import java.util.List; + +public class Order { + private List<Product> order; + + public Order(String inputOrder) { + validateProductFormat(inputOrder); + this.order = generateProducts(inputOrder); + } + + public List<Product> generateProducts(String inputOrder) { + List<Product> products = new ArrayList<>(); + String[] orders = inputOrder.split("],\\["); + + for (String order : orders) { + String formatOrder = order.replace("[", "").replace("]", ""); + int quantityIndex = formatOrder.lastIndexOf('-') + 1; + + String name = formatOrder.substring(0, quantityIndex - 1).trim(); + String quantity = formatOrder.substring(quantityIndex).trim(); + + products.add(new Product(name, quantity)); + } + return products; + } + + private void validateProductFormat(String inputOrder) { + String[] orderList = inputOrder.split(","); + + for (String order : orderList) { + if (!isValidProductEntry(order.trim())) { + throw new IllegalArgumentException(INVALID_FORMAT); + } + } + } + + private boolean isValidProductEntry(String order) { + if (!order.startsWith("[") || !order.endsWith("]")) { + return false; + } + + String part = order.substring(1, order.length() - 1); + String[] parts = part.split("-"); + if (parts[0].isEmpty()) { + return false; + } + + return parts.length == 2; + } + + public List<Product> getOrder() { + return order; + } +}
Java
replaceAll() ์ด๋ผ๋Š” ๋ฉ”์„œ๋“œ๋กœ๋„ ๊ฐ™์€ ๊ธฐ๋Šฅ์„ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค! ์ด๋ฏธ ์•„์‹ค์ˆ˜๋„ ์žˆ์ง€๋งŒ ํ˜น์‹œ๋‚˜ ํ•ด์„œ ๋ง์”€๋“œ๋ฆฝ๋‹ˆ๋‹ค..!
@@ -0,0 +1,73 @@ +package store.model; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +public class Promotion { + private String name; + private int buy; + private int get; + private String startDateStr; + private String endDateStr; + + public Promotion(String name, int buy, int get, String startdateStr, String enddateStr) { + this.name = name; + this.buy = buy; + this.get = get; + this.startDateStr = startdateStr; + this.endDateStr = enddateStr; + } + + public static Promotion parsePromotions(String line) { + List<String> promotion = Arrays.asList(line.split(",")); + + String name = promotion.get(0).trim(); + int buy = Integer.parseInt(promotion.get(1).trim()); + int get = Integer.parseInt(promotion.get(2).trim()); + String start_date = promotion.get(3).trim(); + String end_date = promotion.get(4).trim(); + + return new Promotion(name, buy, get, start_date, end_date); + } + + public int checkPromotionDate() { + final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); + + try { + Date startDate = DATE_FORMAT.parse(startDateStr); + Date endDate = DATE_FORMAT.parse(endDateStr); + Date now = DATE_FORMAT.parse(String.valueOf(DateTimes.now())); + + if (!now.before(startDate) && !now.after(endDate)) { + return this.buy; + } + } catch (ParseException e) { + return 0; + } + return 0; + } + + public String getName() { + return name; + } + + public int getBuy() { + return buy; + } + + public int getGet() { + return get; + } + + public String getStartDateStr() { + return startDateStr; + } + + public String getEndDateStr() { + return endDateStr; + } +}
Java
`now.after(startDate) && now.before(endDate)` ๋„ ๊ฐ™์€ ์˜๋ฏธ์ธ๋ฐ ํ˜„์žฌ ์ฝ”๋“œ์ฒ˜๋Ÿผ ์ž‘์„ฑํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š”? ๊ถ๊ธˆํ•ด์„œ ์งˆ๋ฌธ๋“œ๋ฆฝ๋‹ˆ๋‹ค..!
@@ -0,0 +1,294 @@ +package store.service; + +import static store.model.Promotion.parsePromotions; +import static store.model.Store.*; +import static store.utils.ErrorMessage.INVALID_INPUT; +import static store.utils.ErrorMessage.INVALID_NAME; +import static store.utils.ErrorMessage.INVALID_QUANTITY; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import store.model.Order; +import store.model.Product; +import store.model.Promotion; +import store.model.Receipt; +import store.model.Store; +import store.view.InputView; +import store.view.OutputView; + +public class StoreService { + private static final int NON_PROMOTION = 0; + private static final int GET = 1; + private static final int MAX_MEMBERSHIP = 8000; + + public void loadProductsForm(List<Store> store) { + try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + addProduct(store, line); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + public void loadPromotionsForm(List<Promotion> promotions) { + try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + promotions.add(parsePromotions(line)); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + private void addProduct(List<Store> store, String line) { + checkNotPromotionProduct(store, line); + store.add(parseStore(line)); + } + + public void checkProduct(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + checkName(store, product); + checkQuantity(store, product); + } + } + + private void checkName(List<Store> store, Product product) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + return; + } + } + + throw new IllegalArgumentException(INVALID_NAME); + } + + private void checkQuantity(List<Store> store, Product product) { + int quantity = 0; + + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + quantity += storeProduct.getQuantity(); + } + } + + if (quantity < product.getQuantity()) { + throw new IllegalArgumentException(INVALID_QUANTITY); + } + } + + public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) { + List<Receipt> receipts = new ArrayList<>(); + + for (Product product : order.getOrder()) { + String name = product.getName(); + int indivialPrice = getPrice(store, product.getName()); + int quantity = product.getQuantity(); + int promotinBuy = checkPromotionProduct(store, product, promotions); + receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy)); + } + return receipts; + } + + private int getPrice(List<Store> store, String productName) { + int price = 0; + for (Store storeProduct : store) { + if (storeProduct.getName().equals(productName)) { + price = storeProduct.getPrice(); + } + } + + return price; + } + + private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + if (storeProduct.getQuantity() == 0) { + return 0; + } + return getPromotion(storeProduct.getPromotion(), promotions); + } + } + + return 0; + } + + private int getPromotion(String promotion, List<Promotion> promotions) { + for (Promotion promotionType : promotions) { + if (promotionType.getName().equals(promotion)) { + return promotionType.checkPromotionDate(); + } + } + return 0; + } + + public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkPromotionQuantity(receipt, store); + } + } + } + + private void checkPromotionQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkNonGet(receipt, storeProduct.getQuantity()); + break; + } + } + } + + private void checkNonGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) { + if (isGet(receipt, storeQuantity)) { + receipt.addPromotion(); + } + } + } + + private boolean isGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() + GET <= storeQuantity) { + while (true) { + try { + return isAnswer(InputView.getFree(receipt.getName())); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + return false; + } + + public void checkTribePromotion(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkStoreQuantity(receipt, store); + } + } + } + + private void checkStoreQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkOverGet(receipt, storeProduct); + break; + } + } + } + + private void checkOverGet(Receipt receipt, Store storeProduct) { + int promotionProductQuantity = storeProduct.getQuantity() + - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET); + + int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity; + + if (nomDiscountableQuantity > 0) { + if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) { + receipt.removeNonPromotion(nomDiscountableQuantity); + } + receipt.setPromotionQuantity(promotionProductQuantity); + return; + } + receipt.setPromotionQuantity( + receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1)); + } + + private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) { + while (true) { + try { + return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity)); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + public int membershipDiscount(List<Receipt> receipts) { + int totalPrice = 0; + int promotionPrice = 0; + + if (isMembership()) { + for (Receipt receipt : receipts) { + totalPrice += receipt.getIndividualPrice() * receipt.getQuantity(); + promotionPrice += checkPromotionPrice(receipt); + } + } + + return checkDisCount(totalPrice, promotionPrice); + } + + private boolean isMembership() { + while (true) { + try { + return isAnswer(InputView.membershipMessage()); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + private int checkPromotionPrice(Receipt receipt) { + return receipt.getIndividualPrice() * receipt.getPromotionQuantity(); + } + + private int checkDisCount(int totalPrice, int promotionPrice) { + int disCount = (int) ((totalPrice - promotionPrice) * 0.3); + if (disCount > MAX_MEMBERSHIP) { + return MAX_MEMBERSHIP; + } + + return disCount; + } + + public boolean isAnswer(String answer) { + if (answer.equals("Y")) { + return true; + } + if (answer.equals("N")) { + return false; + } + + throw new IllegalArgumentException(INVALID_INPUT); + } + + public void checkStock(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + handleProductDeduction(store, product); + } + } + + private void handleProductDeduction(List<Store> store, Product product) { + Store matchedStoreProduct = findStoreProduct(store, product.getName()); + + int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity()); + if (remainingQuantity > 0) { + applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity); + } + } + + private Store findStoreProduct(List<Store> store, String productName) { + return store.stream() + .filter(storeProduct -> storeProduct.getName().equals(productName)) + .findFirst() + .orElse(null); + } + + private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) { + for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) { + remainingQuantity = store.get(i).deduction(remainingQuantity); + } + } + +}
Java
ํŒŒ์ผ๋ช…์„ ์ƒ์ˆ˜๋กœ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,294 @@ +package store.service; + +import static store.model.Promotion.parsePromotions; +import static store.model.Store.*; +import static store.utils.ErrorMessage.INVALID_INPUT; +import static store.utils.ErrorMessage.INVALID_NAME; +import static store.utils.ErrorMessage.INVALID_QUANTITY; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import store.model.Order; +import store.model.Product; +import store.model.Promotion; +import store.model.Receipt; +import store.model.Store; +import store.view.InputView; +import store.view.OutputView; + +public class StoreService { + private static final int NON_PROMOTION = 0; + private static final int GET = 1; + private static final int MAX_MEMBERSHIP = 8000; + + public void loadProductsForm(List<Store> store) { + try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + addProduct(store, line); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + public void loadPromotionsForm(List<Promotion> promotions) { + try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + promotions.add(parsePromotions(line)); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + private void addProduct(List<Store> store, String line) { + checkNotPromotionProduct(store, line); + store.add(parseStore(line)); + } + + public void checkProduct(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + checkName(store, product); + checkQuantity(store, product); + } + } + + private void checkName(List<Store> store, Product product) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + return; + } + } + + throw new IllegalArgumentException(INVALID_NAME); + } + + private void checkQuantity(List<Store> store, Product product) { + int quantity = 0; + + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + quantity += storeProduct.getQuantity(); + } + } + + if (quantity < product.getQuantity()) { + throw new IllegalArgumentException(INVALID_QUANTITY); + } + } + + public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) { + List<Receipt> receipts = new ArrayList<>(); + + for (Product product : order.getOrder()) { + String name = product.getName(); + int indivialPrice = getPrice(store, product.getName()); + int quantity = product.getQuantity(); + int promotinBuy = checkPromotionProduct(store, product, promotions); + receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy)); + } + return receipts; + } + + private int getPrice(List<Store> store, String productName) { + int price = 0; + for (Store storeProduct : store) { + if (storeProduct.getName().equals(productName)) { + price = storeProduct.getPrice(); + } + } + + return price; + } + + private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + if (storeProduct.getQuantity() == 0) { + return 0; + } + return getPromotion(storeProduct.getPromotion(), promotions); + } + } + + return 0; + } + + private int getPromotion(String promotion, List<Promotion> promotions) { + for (Promotion promotionType : promotions) { + if (promotionType.getName().equals(promotion)) { + return promotionType.checkPromotionDate(); + } + } + return 0; + } + + public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkPromotionQuantity(receipt, store); + } + } + } + + private void checkPromotionQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkNonGet(receipt, storeProduct.getQuantity()); + break; + } + } + } + + private void checkNonGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) { + if (isGet(receipt, storeQuantity)) { + receipt.addPromotion(); + } + } + } + + private boolean isGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() + GET <= storeQuantity) { + while (true) { + try { + return isAnswer(InputView.getFree(receipt.getName())); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + return false; + } + + public void checkTribePromotion(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkStoreQuantity(receipt, store); + } + } + } + + private void checkStoreQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkOverGet(receipt, storeProduct); + break; + } + } + } + + private void checkOverGet(Receipt receipt, Store storeProduct) { + int promotionProductQuantity = storeProduct.getQuantity() + - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET); + + int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity; + + if (nomDiscountableQuantity > 0) { + if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) { + receipt.removeNonPromotion(nomDiscountableQuantity); + } + receipt.setPromotionQuantity(promotionProductQuantity); + return; + } + receipt.setPromotionQuantity( + receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1)); + } + + private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) { + while (true) { + try { + return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity)); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + public int membershipDiscount(List<Receipt> receipts) { + int totalPrice = 0; + int promotionPrice = 0; + + if (isMembership()) { + for (Receipt receipt : receipts) { + totalPrice += receipt.getIndividualPrice() * receipt.getQuantity(); + promotionPrice += checkPromotionPrice(receipt); + } + } + + return checkDisCount(totalPrice, promotionPrice); + } + + private boolean isMembership() { + while (true) { + try { + return isAnswer(InputView.membershipMessage()); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + private int checkPromotionPrice(Receipt receipt) { + return receipt.getIndividualPrice() * receipt.getPromotionQuantity(); + } + + private int checkDisCount(int totalPrice, int promotionPrice) { + int disCount = (int) ((totalPrice - promotionPrice) * 0.3); + if (disCount > MAX_MEMBERSHIP) { + return MAX_MEMBERSHIP; + } + + return disCount; + } + + public boolean isAnswer(String answer) { + if (answer.equals("Y")) { + return true; + } + if (answer.equals("N")) { + return false; + } + + throw new IllegalArgumentException(INVALID_INPUT); + } + + public void checkStock(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + handleProductDeduction(store, product); + } + } + + private void handleProductDeduction(List<Store> store, Product product) { + Store matchedStoreProduct = findStoreProduct(store, product.getName()); + + int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity()); + if (remainingQuantity > 0) { + applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity); + } + } + + private Store findStoreProduct(List<Store> store, String productName) { + return store.stream() + .filter(storeProduct -> storeProduct.getName().equals(productName)) + .findFirst() + .orElse(null); + } + + private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) { + for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) { + remainingQuantity = store.get(i).deduction(remainingQuantity); + } + } + +}
Java
๋ฆฌํŒฉํ† ๋งํ•œ๋‹ค๋ฉด ์—ฌ๊ธฐ ์ƒํ’ˆ์˜ ์ˆ˜๋Ÿ‰์„ ๊ตฌํ•˜๋Š” ๋ถ€๋ถ„์„ ํ•˜๋‚˜์˜ ๋ฉ”์„œ๋“œ๋กœ ๋ถ„๋ฆฌํ•˜์‹œ๋Š” ๊ฒƒ๋„ ์ข‹๊ฒ ๋„ค์š”
@@ -0,0 +1,294 @@ +package store.service; + +import static store.model.Promotion.parsePromotions; +import static store.model.Store.*; +import static store.utils.ErrorMessage.INVALID_INPUT; +import static store.utils.ErrorMessage.INVALID_NAME; +import static store.utils.ErrorMessage.INVALID_QUANTITY; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import store.model.Order; +import store.model.Product; +import store.model.Promotion; +import store.model.Receipt; +import store.model.Store; +import store.view.InputView; +import store.view.OutputView; + +public class StoreService { + private static final int NON_PROMOTION = 0; + private static final int GET = 1; + private static final int MAX_MEMBERSHIP = 8000; + + public void loadProductsForm(List<Store> store) { + try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + addProduct(store, line); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + public void loadPromotionsForm(List<Promotion> promotions) { + try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + promotions.add(parsePromotions(line)); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + private void addProduct(List<Store> store, String line) { + checkNotPromotionProduct(store, line); + store.add(parseStore(line)); + } + + public void checkProduct(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + checkName(store, product); + checkQuantity(store, product); + } + } + + private void checkName(List<Store> store, Product product) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + return; + } + } + + throw new IllegalArgumentException(INVALID_NAME); + } + + private void checkQuantity(List<Store> store, Product product) { + int quantity = 0; + + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + quantity += storeProduct.getQuantity(); + } + } + + if (quantity < product.getQuantity()) { + throw new IllegalArgumentException(INVALID_QUANTITY); + } + } + + public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) { + List<Receipt> receipts = new ArrayList<>(); + + for (Product product : order.getOrder()) { + String name = product.getName(); + int indivialPrice = getPrice(store, product.getName()); + int quantity = product.getQuantity(); + int promotinBuy = checkPromotionProduct(store, product, promotions); + receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy)); + } + return receipts; + } + + private int getPrice(List<Store> store, String productName) { + int price = 0; + for (Store storeProduct : store) { + if (storeProduct.getName().equals(productName)) { + price = storeProduct.getPrice(); + } + } + + return price; + } + + private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + if (storeProduct.getQuantity() == 0) { + return 0; + } + return getPromotion(storeProduct.getPromotion(), promotions); + } + } + + return 0; + } + + private int getPromotion(String promotion, List<Promotion> promotions) { + for (Promotion promotionType : promotions) { + if (promotionType.getName().equals(promotion)) { + return promotionType.checkPromotionDate(); + } + } + return 0; + } + + public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkPromotionQuantity(receipt, store); + } + } + } + + private void checkPromotionQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkNonGet(receipt, storeProduct.getQuantity()); + break; + } + } + } + + private void checkNonGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) { + if (isGet(receipt, storeQuantity)) { + receipt.addPromotion(); + } + } + } + + private boolean isGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() + GET <= storeQuantity) { + while (true) { + try { + return isAnswer(InputView.getFree(receipt.getName())); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + return false; + } + + public void checkTribePromotion(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkStoreQuantity(receipt, store); + } + } + } + + private void checkStoreQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkOverGet(receipt, storeProduct); + break; + } + } + } + + private void checkOverGet(Receipt receipt, Store storeProduct) { + int promotionProductQuantity = storeProduct.getQuantity() + - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET); + + int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity; + + if (nomDiscountableQuantity > 0) { + if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) { + receipt.removeNonPromotion(nomDiscountableQuantity); + } + receipt.setPromotionQuantity(promotionProductQuantity); + return; + } + receipt.setPromotionQuantity( + receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1)); + } + + private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) { + while (true) { + try { + return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity)); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + public int membershipDiscount(List<Receipt> receipts) { + int totalPrice = 0; + int promotionPrice = 0; + + if (isMembership()) { + for (Receipt receipt : receipts) { + totalPrice += receipt.getIndividualPrice() * receipt.getQuantity(); + promotionPrice += checkPromotionPrice(receipt); + } + } + + return checkDisCount(totalPrice, promotionPrice); + } + + private boolean isMembership() { + while (true) { + try { + return isAnswer(InputView.membershipMessage()); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + private int checkPromotionPrice(Receipt receipt) { + return receipt.getIndividualPrice() * receipt.getPromotionQuantity(); + } + + private int checkDisCount(int totalPrice, int promotionPrice) { + int disCount = (int) ((totalPrice - promotionPrice) * 0.3); + if (disCount > MAX_MEMBERSHIP) { + return MAX_MEMBERSHIP; + } + + return disCount; + } + + public boolean isAnswer(String answer) { + if (answer.equals("Y")) { + return true; + } + if (answer.equals("N")) { + return false; + } + + throw new IllegalArgumentException(INVALID_INPUT); + } + + public void checkStock(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + handleProductDeduction(store, product); + } + } + + private void handleProductDeduction(List<Store> store, Product product) { + Store matchedStoreProduct = findStoreProduct(store, product.getName()); + + int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity()); + if (remainingQuantity > 0) { + applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity); + } + } + + private Store findStoreProduct(List<Store> store, String productName) { + return store.stream() + .filter(storeProduct -> storeProduct.getName().equals(productName)) + .findFirst() + .orElse(null); + } + + private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) { + for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) { + remainingQuantity = store.get(i).deduction(remainingQuantity); + } + } + +}
Java
์ž๋ฐ” ํŒŒ์ผ ์ž…์ถœ๋ ฅ์— ์—ฌ๋Ÿฌ ๋ฐฉ๋ฒ•์ด ์žˆ๋Š”๋ฐ ๋ฒ„ํผ๋ฆฌ๋“œ ํ˜•์‹์„ ์‚ฌ์šฉํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š”??
@@ -0,0 +1,294 @@ +package store.service; + +import static store.model.Promotion.parsePromotions; +import static store.model.Store.*; +import static store.utils.ErrorMessage.INVALID_INPUT; +import static store.utils.ErrorMessage.INVALID_NAME; +import static store.utils.ErrorMessage.INVALID_QUANTITY; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import store.model.Order; +import store.model.Product; +import store.model.Promotion; +import store.model.Receipt; +import store.model.Store; +import store.view.InputView; +import store.view.OutputView; + +public class StoreService { + private static final int NON_PROMOTION = 0; + private static final int GET = 1; + private static final int MAX_MEMBERSHIP = 8000; + + public void loadProductsForm(List<Store> store) { + try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + addProduct(store, line); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + public void loadPromotionsForm(List<Promotion> promotions) { + try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + promotions.add(parsePromotions(line)); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + private void addProduct(List<Store> store, String line) { + checkNotPromotionProduct(store, line); + store.add(parseStore(line)); + } + + public void checkProduct(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + checkName(store, product); + checkQuantity(store, product); + } + } + + private void checkName(List<Store> store, Product product) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + return; + } + } + + throw new IllegalArgumentException(INVALID_NAME); + } + + private void checkQuantity(List<Store> store, Product product) { + int quantity = 0; + + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + quantity += storeProduct.getQuantity(); + } + } + + if (quantity < product.getQuantity()) { + throw new IllegalArgumentException(INVALID_QUANTITY); + } + } + + public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) { + List<Receipt> receipts = new ArrayList<>(); + + for (Product product : order.getOrder()) { + String name = product.getName(); + int indivialPrice = getPrice(store, product.getName()); + int quantity = product.getQuantity(); + int promotinBuy = checkPromotionProduct(store, product, promotions); + receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy)); + } + return receipts; + } + + private int getPrice(List<Store> store, String productName) { + int price = 0; + for (Store storeProduct : store) { + if (storeProduct.getName().equals(productName)) { + price = storeProduct.getPrice(); + } + } + + return price; + } + + private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + if (storeProduct.getQuantity() == 0) { + return 0; + } + return getPromotion(storeProduct.getPromotion(), promotions); + } + } + + return 0; + } + + private int getPromotion(String promotion, List<Promotion> promotions) { + for (Promotion promotionType : promotions) { + if (promotionType.getName().equals(promotion)) { + return promotionType.checkPromotionDate(); + } + } + return 0; + } + + public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkPromotionQuantity(receipt, store); + } + } + } + + private void checkPromotionQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkNonGet(receipt, storeProduct.getQuantity()); + break; + } + } + } + + private void checkNonGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) { + if (isGet(receipt, storeQuantity)) { + receipt.addPromotion(); + } + } + } + + private boolean isGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() + GET <= storeQuantity) { + while (true) { + try { + return isAnswer(InputView.getFree(receipt.getName())); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + return false; + } + + public void checkTribePromotion(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkStoreQuantity(receipt, store); + } + } + } + + private void checkStoreQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkOverGet(receipt, storeProduct); + break; + } + } + } + + private void checkOverGet(Receipt receipt, Store storeProduct) { + int promotionProductQuantity = storeProduct.getQuantity() + - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET); + + int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity; + + if (nomDiscountableQuantity > 0) { + if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) { + receipt.removeNonPromotion(nomDiscountableQuantity); + } + receipt.setPromotionQuantity(promotionProductQuantity); + return; + } + receipt.setPromotionQuantity( + receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1)); + } + + private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) { + while (true) { + try { + return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity)); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + public int membershipDiscount(List<Receipt> receipts) { + int totalPrice = 0; + int promotionPrice = 0; + + if (isMembership()) { + for (Receipt receipt : receipts) { + totalPrice += receipt.getIndividualPrice() * receipt.getQuantity(); + promotionPrice += checkPromotionPrice(receipt); + } + } + + return checkDisCount(totalPrice, promotionPrice); + } + + private boolean isMembership() { + while (true) { + try { + return isAnswer(InputView.membershipMessage()); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + private int checkPromotionPrice(Receipt receipt) { + return receipt.getIndividualPrice() * receipt.getPromotionQuantity(); + } + + private int checkDisCount(int totalPrice, int promotionPrice) { + int disCount = (int) ((totalPrice - promotionPrice) * 0.3); + if (disCount > MAX_MEMBERSHIP) { + return MAX_MEMBERSHIP; + } + + return disCount; + } + + public boolean isAnswer(String answer) { + if (answer.equals("Y")) { + return true; + } + if (answer.equals("N")) { + return false; + } + + throw new IllegalArgumentException(INVALID_INPUT); + } + + public void checkStock(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + handleProductDeduction(store, product); + } + } + + private void handleProductDeduction(List<Store> store, Product product) { + Store matchedStoreProduct = findStoreProduct(store, product.getName()); + + int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity()); + if (remainingQuantity > 0) { + applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity); + } + } + + private Store findStoreProduct(List<Store> store, String productName) { + return store.stream() + .filter(storeProduct -> storeProduct.getName().equals(productName)) + .findFirst() + .orElse(null); + } + + private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) { + for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) { + remainingQuantity = store.get(i).deduction(remainingQuantity); + } + } + +}
Java
ํ•ด๋‹น ๋ฉ”์„œ๋“œ๋Š” ์„œ๋น„์Šค๊ฐ€ ํ•˜๋Š” ๊ธฐ๋Šฅ ๋ณด๋‹ค๋Š” ๋‹ค๋ฅธ ํด๋ž˜์Šค๋กœ ์˜ฎ๊ธฐ๋Š”๊ฒŒ ๋” ์ ํ•ฉํ•ด๋ณด์ž…๋‹ˆ๋‹ค..!
@@ -0,0 +1,294 @@ +package store.service; + +import static store.model.Promotion.parsePromotions; +import static store.model.Store.*; +import static store.utils.ErrorMessage.INVALID_INPUT; +import static store.utils.ErrorMessage.INVALID_NAME; +import static store.utils.ErrorMessage.INVALID_QUANTITY; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import store.model.Order; +import store.model.Product; +import store.model.Promotion; +import store.model.Receipt; +import store.model.Store; +import store.view.InputView; +import store.view.OutputView; + +public class StoreService { + private static final int NON_PROMOTION = 0; + private static final int GET = 1; + private static final int MAX_MEMBERSHIP = 8000; + + public void loadProductsForm(List<Store> store) { + try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + addProduct(store, line); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + public void loadPromotionsForm(List<Promotion> promotions) { + try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + promotions.add(parsePromotions(line)); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + private void addProduct(List<Store> store, String line) { + checkNotPromotionProduct(store, line); + store.add(parseStore(line)); + } + + public void checkProduct(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + checkName(store, product); + checkQuantity(store, product); + } + } + + private void checkName(List<Store> store, Product product) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + return; + } + } + + throw new IllegalArgumentException(INVALID_NAME); + } + + private void checkQuantity(List<Store> store, Product product) { + int quantity = 0; + + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + quantity += storeProduct.getQuantity(); + } + } + + if (quantity < product.getQuantity()) { + throw new IllegalArgumentException(INVALID_QUANTITY); + } + } + + public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) { + List<Receipt> receipts = new ArrayList<>(); + + for (Product product : order.getOrder()) { + String name = product.getName(); + int indivialPrice = getPrice(store, product.getName()); + int quantity = product.getQuantity(); + int promotinBuy = checkPromotionProduct(store, product, promotions); + receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy)); + } + return receipts; + } + + private int getPrice(List<Store> store, String productName) { + int price = 0; + for (Store storeProduct : store) { + if (storeProduct.getName().equals(productName)) { + price = storeProduct.getPrice(); + } + } + + return price; + } + + private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + if (storeProduct.getQuantity() == 0) { + return 0; + } + return getPromotion(storeProduct.getPromotion(), promotions); + } + } + + return 0; + } + + private int getPromotion(String promotion, List<Promotion> promotions) { + for (Promotion promotionType : promotions) { + if (promotionType.getName().equals(promotion)) { + return promotionType.checkPromotionDate(); + } + } + return 0; + } + + public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkPromotionQuantity(receipt, store); + } + } + } + + private void checkPromotionQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkNonGet(receipt, storeProduct.getQuantity()); + break; + } + } + } + + private void checkNonGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) { + if (isGet(receipt, storeQuantity)) { + receipt.addPromotion(); + } + } + } + + private boolean isGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() + GET <= storeQuantity) { + while (true) { + try { + return isAnswer(InputView.getFree(receipt.getName())); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + return false; + } + + public void checkTribePromotion(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkStoreQuantity(receipt, store); + } + } + } + + private void checkStoreQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkOverGet(receipt, storeProduct); + break; + } + } + } + + private void checkOverGet(Receipt receipt, Store storeProduct) { + int promotionProductQuantity = storeProduct.getQuantity() + - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET); + + int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity; + + if (nomDiscountableQuantity > 0) { + if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) { + receipt.removeNonPromotion(nomDiscountableQuantity); + } + receipt.setPromotionQuantity(promotionProductQuantity); + return; + } + receipt.setPromotionQuantity( + receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1)); + } + + private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) { + while (true) { + try { + return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity)); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + public int membershipDiscount(List<Receipt> receipts) { + int totalPrice = 0; + int promotionPrice = 0; + + if (isMembership()) { + for (Receipt receipt : receipts) { + totalPrice += receipt.getIndividualPrice() * receipt.getQuantity(); + promotionPrice += checkPromotionPrice(receipt); + } + } + + return checkDisCount(totalPrice, promotionPrice); + } + + private boolean isMembership() { + while (true) { + try { + return isAnswer(InputView.membershipMessage()); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + private int checkPromotionPrice(Receipt receipt) { + return receipt.getIndividualPrice() * receipt.getPromotionQuantity(); + } + + private int checkDisCount(int totalPrice, int promotionPrice) { + int disCount = (int) ((totalPrice - promotionPrice) * 0.3); + if (disCount > MAX_MEMBERSHIP) { + return MAX_MEMBERSHIP; + } + + return disCount; + } + + public boolean isAnswer(String answer) { + if (answer.equals("Y")) { + return true; + } + if (answer.equals("N")) { + return false; + } + + throw new IllegalArgumentException(INVALID_INPUT); + } + + public void checkStock(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + handleProductDeduction(store, product); + } + } + + private void handleProductDeduction(List<Store> store, Product product) { + Store matchedStoreProduct = findStoreProduct(store, product.getName()); + + int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity()); + if (remainingQuantity > 0) { + applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity); + } + } + + private Store findStoreProduct(List<Store> store, String productName) { + return store.stream() + .filter(storeProduct -> storeProduct.getName().equals(productName)) + .findFirst() + .orElse(null); + } + + private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) { + for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) { + remainingQuantity = store.get(i).deduction(remainingQuantity); + } + } + +}
Java
์ด ๋ถ€๋ถ„๋„ ๋‚˜์ค‘์— receiptservice๋กœ ๋ถ„๋ฅ˜ํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”..?
@@ -0,0 +1,294 @@ +package store.service; + +import static store.model.Promotion.parsePromotions; +import static store.model.Store.*; +import static store.utils.ErrorMessage.INVALID_INPUT; +import static store.utils.ErrorMessage.INVALID_NAME; +import static store.utils.ErrorMessage.INVALID_QUANTITY; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import store.model.Order; +import store.model.Product; +import store.model.Promotion; +import store.model.Receipt; +import store.model.Store; +import store.view.InputView; +import store.view.OutputView; + +public class StoreService { + private static final int NON_PROMOTION = 0; + private static final int GET = 1; + private static final int MAX_MEMBERSHIP = 8000; + + public void loadProductsForm(List<Store> store) { + try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + addProduct(store, line); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + public void loadPromotionsForm(List<Promotion> promotions) { + try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + promotions.add(parsePromotions(line)); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + private void addProduct(List<Store> store, String line) { + checkNotPromotionProduct(store, line); + store.add(parseStore(line)); + } + + public void checkProduct(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + checkName(store, product); + checkQuantity(store, product); + } + } + + private void checkName(List<Store> store, Product product) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + return; + } + } + + throw new IllegalArgumentException(INVALID_NAME); + } + + private void checkQuantity(List<Store> store, Product product) { + int quantity = 0; + + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + quantity += storeProduct.getQuantity(); + } + } + + if (quantity < product.getQuantity()) { + throw new IllegalArgumentException(INVALID_QUANTITY); + } + } + + public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) { + List<Receipt> receipts = new ArrayList<>(); + + for (Product product : order.getOrder()) { + String name = product.getName(); + int indivialPrice = getPrice(store, product.getName()); + int quantity = product.getQuantity(); + int promotinBuy = checkPromotionProduct(store, product, promotions); + receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy)); + } + return receipts; + } + + private int getPrice(List<Store> store, String productName) { + int price = 0; + for (Store storeProduct : store) { + if (storeProduct.getName().equals(productName)) { + price = storeProduct.getPrice(); + } + } + + return price; + } + + private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + if (storeProduct.getQuantity() == 0) { + return 0; + } + return getPromotion(storeProduct.getPromotion(), promotions); + } + } + + return 0; + } + + private int getPromotion(String promotion, List<Promotion> promotions) { + for (Promotion promotionType : promotions) { + if (promotionType.getName().equals(promotion)) { + return promotionType.checkPromotionDate(); + } + } + return 0; + } + + public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkPromotionQuantity(receipt, store); + } + } + } + + private void checkPromotionQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkNonGet(receipt, storeProduct.getQuantity()); + break; + } + } + } + + private void checkNonGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) { + if (isGet(receipt, storeQuantity)) { + receipt.addPromotion(); + } + } + } + + private boolean isGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() + GET <= storeQuantity) { + while (true) { + try { + return isAnswer(InputView.getFree(receipt.getName())); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + return false; + } + + public void checkTribePromotion(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkStoreQuantity(receipt, store); + } + } + } + + private void checkStoreQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkOverGet(receipt, storeProduct); + break; + } + } + } + + private void checkOverGet(Receipt receipt, Store storeProduct) { + int promotionProductQuantity = storeProduct.getQuantity() + - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET); + + int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity; + + if (nomDiscountableQuantity > 0) { + if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) { + receipt.removeNonPromotion(nomDiscountableQuantity); + } + receipt.setPromotionQuantity(promotionProductQuantity); + return; + } + receipt.setPromotionQuantity( + receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1)); + } + + private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) { + while (true) { + try { + return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity)); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + public int membershipDiscount(List<Receipt> receipts) { + int totalPrice = 0; + int promotionPrice = 0; + + if (isMembership()) { + for (Receipt receipt : receipts) { + totalPrice += receipt.getIndividualPrice() * receipt.getQuantity(); + promotionPrice += checkPromotionPrice(receipt); + } + } + + return checkDisCount(totalPrice, promotionPrice); + } + + private boolean isMembership() { + while (true) { + try { + return isAnswer(InputView.membershipMessage()); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + private int checkPromotionPrice(Receipt receipt) { + return receipt.getIndividualPrice() * receipt.getPromotionQuantity(); + } + + private int checkDisCount(int totalPrice, int promotionPrice) { + int disCount = (int) ((totalPrice - promotionPrice) * 0.3); + if (disCount > MAX_MEMBERSHIP) { + return MAX_MEMBERSHIP; + } + + return disCount; + } + + public boolean isAnswer(String answer) { + if (answer.equals("Y")) { + return true; + } + if (answer.equals("N")) { + return false; + } + + throw new IllegalArgumentException(INVALID_INPUT); + } + + public void checkStock(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + handleProductDeduction(store, product); + } + } + + private void handleProductDeduction(List<Store> store, Product product) { + Store matchedStoreProduct = findStoreProduct(store, product.getName()); + + int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity()); + if (remainingQuantity > 0) { + applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity); + } + } + + private Store findStoreProduct(List<Store> store, String productName) { + return store.stream() + .filter(storeProduct -> storeProduct.getName().equals(productName)) + .findFirst() + .orElse(null); + } + + private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) { + for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) { + remainingQuantity = store.get(i).deduction(remainingQuantity); + } + } + +}
Java
Math.min์„ ์‚ฌ์šฉํ•˜์‹œ๋ฉด ํ•œ์ค„๋กœ ๋งŒ๋“ค์ˆ˜์žˆ์„๊ฑฐ๊ฐ™์•„์š”
@@ -0,0 +1,14 @@ +package store.utils; + +public class ErrorMessage { + public static final String ERROR = "[ERROR] "; + public static final String RETRY = " ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + public static final String INVALID_FORMAT = " ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. "; + public static final String INVALID_NAME = " ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."; + public static final String INVALID_QUANTITY = "์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."; + public static final String INVALID_INPUT = "์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค."; + + private ErrorMessage() { + + } +}
Java
enum์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  class๋กœ ๋ถ„๋ฆฌํ•œ ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,89 @@ +package store.controller; + +import java.util.ArrayList; +import java.util.List; +import store.model.Order; +import store.model.Promotion; +import store.model.Receipt; +import store.model.Store; +import store.service.StoreService; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + private final InputView inputView; + private final OutputView outputView; + private final StoreService storeService; + + public StoreController(InputView inputView, OutputView outputView, StoreService storeService) { + this.inputView = inputView; + this.outputView = outputView; + this.storeService = storeService; + } + + public void run() { + List<Store> store = printProductList(); + List<Promotion> promotions = loadPromotions(); + Order order; + + do { + order = purchaseProduct(store); + priceCalculator(store, order, promotions); + + } while (!checkEnd(store, order)); + } + + private boolean checkEnd(List<Store> store, Order order) { + while (true) { + try { + if (!storeService.isAnswer(inputView.inputEndMessage())) { + return true; + } + updateStore(store, order); + return false; + } catch (IllegalArgumentException e) { + outputView.printError(e.getMessage()); + } + } + } + + private void updateStore(List<Store> store, Order order) { + storeService.checkStock(store, order); + outputView.printProductList(store); + } + + private void priceCalculator(List<Store> store, Order order, List<Promotion> promotions) { + List<Receipt> receipts = storeService.parseReceipt(store, order, promotions); + storeService.checkTribeQuantity(receipts, store); + storeService.checkTribePromotion(receipts, store); + int discount = storeService.membershipDiscount(receipts); + + outputView.printReceipt(receipts, discount); + } + + private List<Store> printProductList() { + List<Store> store = new ArrayList<>(); + storeService.loadProductsForm(store); + outputView.printProductList(store); + return store; + } + + private List<Promotion> loadPromotions() { + List<Promotion> promotions = new ArrayList<>(); + storeService.loadPromotionsForm(promotions); + return promotions; + } + + private Order purchaseProduct(List<Store> store) { + while (true) { + try { + String inputOrder = inputView.inputPurchaseProduct(); + Order order = new Order(inputOrder); + storeService.checkProduct(store, order); + return order; + } catch (IllegalArgumentException e) { + outputView.printError(e.getMessage()); + } + } + } +}
Java
ํ•จ์ˆ˜๋ช…์€ ๋™์‚ฌ๋กœ ํ•˜๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š”?? ์˜ˆ๋ฅผ ๋“ค์–ด `calculatePrice` ์ฒ˜๋Ÿผ ๋ง์ด์ฃ !!
@@ -0,0 +1,91 @@ +package store.model; + +import java.util.Arrays; +import java.util.List; + +public class Store { + private final String name; + private int price; + private int quantity; + private String promotion; + + public Store(String name, int price, int quantity, String promotion) { + this.name = name; + this.price = price; + this.quantity = quantity; + this.promotion = promotion; + } + + public static Store parseStore(String line) { + List<String> product = Arrays.asList(line.split(",")); + + String name = product.get(0).trim(); + int price = Integer.parseInt(product.get(1).trim()); + int quantity = Integer.parseInt(product.get(2).trim()); + String promotion = checkPromotion(product.get(3)); + + return new Store(name, price, quantity, promotion); + } + + private static String checkPromotion(String promotion) { + if (promotion.equals("null")) { + return ""; + } + return promotion.trim(); + } + + public static void checkNotPromotionProduct(List<Store> store, String line) { + if (store.isEmpty()) { + return; + } + + Store product = store.getLast(); + if (!line.contains(product.getName()) && !product.getPromotion().isEmpty()) { + store.add(new Store(product.getName(), product.getPrice(), 0, "")); + } + } + + public int deduction(int orderQuantity) { + int value = 0; + quantity -= orderQuantity; + + if (quantity < 0) { + value = Math.abs(quantity); + quantity = 0; + } + return value; + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public int getQuantity() { + return quantity; + } + + public String getPromotion() { + return promotion; + } + + @Override + public String toString() { + String formatPrice = String.format("%,d", price); + if (quantity == 0) { + return "- " + + name + " " + + formatPrice + "์› " + + "์žฌ๊ณ  ์—†์Œ" + + promotion; + } + return "- " + + name + " " + + formatPrice + "์› " + + quantity + "๊ฐœ " + + promotion; + } +}
Java
๊ฐ๊ฐ์˜ ์ธ๋ฑ์Šค๊ฐ€ ์–ด๋–ค ๊ฒƒ์„ ์˜๋ฏธํ•˜๋Š”์ง€ ์ƒ์ˆ˜ํ™” ํ–ˆ์œผ๋ฉด ๋” ์ข‹์•˜์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!!!
@@ -0,0 +1,73 @@ +package store.model; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +public class Promotion { + private String name; + private int buy; + private int get; + private String startDateStr; + private String endDateStr; + + public Promotion(String name, int buy, int get, String startdateStr, String enddateStr) { + this.name = name; + this.buy = buy; + this.get = get; + this.startDateStr = startdateStr; + this.endDateStr = enddateStr; + } + + public static Promotion parsePromotions(String line) { + List<String> promotion = Arrays.asList(line.split(",")); + + String name = promotion.get(0).trim(); + int buy = Integer.parseInt(promotion.get(1).trim()); + int get = Integer.parseInt(promotion.get(2).trim()); + String start_date = promotion.get(3).trim(); + String end_date = promotion.get(4).trim(); + + return new Promotion(name, buy, get, start_date, end_date); + } + + public int checkPromotionDate() { + final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); + + try { + Date startDate = DATE_FORMAT.parse(startDateStr); + Date endDate = DATE_FORMAT.parse(endDateStr); + Date now = DATE_FORMAT.parse(String.valueOf(DateTimes.now())); + + if (!now.before(startDate) && !now.after(endDate)) { + return this.buy; + } + } catch (ParseException e) { + return 0; + } + return 0; + } + + public String getName() { + return name; + } + + public int getBuy() { + return buy; + } + + public int getGet() { + return get; + } + + public String getStartDateStr() { + return startDateStr; + } + + public String getEndDateStr() { + return endDateStr; + } +}
Java
๋ฌธ์ž์—ด์„ ํ”„๋กœ๋ชจ์…˜์œผ๋กœ ํŒŒ์‹ฑํ•˜๋Š” ์—ญํ• ์„ ํŒŒ์‹ฑํ•˜๋Š” ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค์–ด์„œ ๊ฑฐ๊ธฐ๋กœ ๋„˜๊ธฐ๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”!!
@@ -0,0 +1,294 @@ +package store.service; + +import static store.model.Promotion.parsePromotions; +import static store.model.Store.*; +import static store.utils.ErrorMessage.INVALID_INPUT; +import static store.utils.ErrorMessage.INVALID_NAME; +import static store.utils.ErrorMessage.INVALID_QUANTITY; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import store.model.Order; +import store.model.Product; +import store.model.Promotion; +import store.model.Receipt; +import store.model.Store; +import store.view.InputView; +import store.view.OutputView; + +public class StoreService { + private static final int NON_PROMOTION = 0; + private static final int GET = 1; + private static final int MAX_MEMBERSHIP = 8000; + + public void loadProductsForm(List<Store> store) { + try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + addProduct(store, line); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + public void loadPromotionsForm(List<Promotion> promotions) { + try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + promotions.add(parsePromotions(line)); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + private void addProduct(List<Store> store, String line) { + checkNotPromotionProduct(store, line); + store.add(parseStore(line)); + } + + public void checkProduct(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + checkName(store, product); + checkQuantity(store, product); + } + } + + private void checkName(List<Store> store, Product product) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + return; + } + } + + throw new IllegalArgumentException(INVALID_NAME); + } + + private void checkQuantity(List<Store> store, Product product) { + int quantity = 0; + + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + quantity += storeProduct.getQuantity(); + } + } + + if (quantity < product.getQuantity()) { + throw new IllegalArgumentException(INVALID_QUANTITY); + } + } + + public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) { + List<Receipt> receipts = new ArrayList<>(); + + for (Product product : order.getOrder()) { + String name = product.getName(); + int indivialPrice = getPrice(store, product.getName()); + int quantity = product.getQuantity(); + int promotinBuy = checkPromotionProduct(store, product, promotions); + receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy)); + } + return receipts; + } + + private int getPrice(List<Store> store, String productName) { + int price = 0; + for (Store storeProduct : store) { + if (storeProduct.getName().equals(productName)) { + price = storeProduct.getPrice(); + } + } + + return price; + } + + private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + if (storeProduct.getQuantity() == 0) { + return 0; + } + return getPromotion(storeProduct.getPromotion(), promotions); + } + } + + return 0; + } + + private int getPromotion(String promotion, List<Promotion> promotions) { + for (Promotion promotionType : promotions) { + if (promotionType.getName().equals(promotion)) { + return promotionType.checkPromotionDate(); + } + } + return 0; + } + + public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkPromotionQuantity(receipt, store); + } + } + } + + private void checkPromotionQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkNonGet(receipt, storeProduct.getQuantity()); + break; + } + } + } + + private void checkNonGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) { + if (isGet(receipt, storeQuantity)) { + receipt.addPromotion(); + } + } + } + + private boolean isGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() + GET <= storeQuantity) { + while (true) { + try { + return isAnswer(InputView.getFree(receipt.getName())); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + return false; + } + + public void checkTribePromotion(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkStoreQuantity(receipt, store); + } + } + } + + private void checkStoreQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkOverGet(receipt, storeProduct); + break; + } + } + } + + private void checkOverGet(Receipt receipt, Store storeProduct) { + int promotionProductQuantity = storeProduct.getQuantity() + - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET); + + int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity; + + if (nomDiscountableQuantity > 0) { + if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) { + receipt.removeNonPromotion(nomDiscountableQuantity); + } + receipt.setPromotionQuantity(promotionProductQuantity); + return; + } + receipt.setPromotionQuantity( + receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1)); + } + + private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) { + while (true) { + try { + return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity)); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + public int membershipDiscount(List<Receipt> receipts) { + int totalPrice = 0; + int promotionPrice = 0; + + if (isMembership()) { + for (Receipt receipt : receipts) { + totalPrice += receipt.getIndividualPrice() * receipt.getQuantity(); + promotionPrice += checkPromotionPrice(receipt); + } + } + + return checkDisCount(totalPrice, promotionPrice); + } + + private boolean isMembership() { + while (true) { + try { + return isAnswer(InputView.membershipMessage()); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + private int checkPromotionPrice(Receipt receipt) { + return receipt.getIndividualPrice() * receipt.getPromotionQuantity(); + } + + private int checkDisCount(int totalPrice, int promotionPrice) { + int disCount = (int) ((totalPrice - promotionPrice) * 0.3); + if (disCount > MAX_MEMBERSHIP) { + return MAX_MEMBERSHIP; + } + + return disCount; + } + + public boolean isAnswer(String answer) { + if (answer.equals("Y")) { + return true; + } + if (answer.equals("N")) { + return false; + } + + throw new IllegalArgumentException(INVALID_INPUT); + } + + public void checkStock(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + handleProductDeduction(store, product); + } + } + + private void handleProductDeduction(List<Store> store, Product product) { + Store matchedStoreProduct = findStoreProduct(store, product.getName()); + + int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity()); + if (remainingQuantity > 0) { + applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity); + } + } + + private Store findStoreProduct(List<Store> store, String productName) { + return store.stream() + .filter(storeProduct -> storeProduct.getName().equals(productName)) + .findFirst() + .orElse(null); + } + + private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) { + for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) { + remainingQuantity = store.get(i).deduction(remainingQuantity); + } + } + +}
Java
answer์„ enum ์ƒ์ˆ˜๋กœ ๋งŒ๋“œ๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,59 @@ +package store.model; + +import static store.utils.ErrorMessage.INVALID_FORMAT; + +import java.util.ArrayList; +import java.util.List; + +public class Order { + private List<Product> order; + + public Order(String inputOrder) { + validateProductFormat(inputOrder); + this.order = generateProducts(inputOrder); + } + + public List<Product> generateProducts(String inputOrder) { + List<Product> products = new ArrayList<>(); + String[] orders = inputOrder.split("],\\["); + + for (String order : orders) { + String formatOrder = order.replace("[", "").replace("]", ""); + int quantityIndex = formatOrder.lastIndexOf('-') + 1; + + String name = formatOrder.substring(0, quantityIndex - 1).trim(); + String quantity = formatOrder.substring(quantityIndex).trim(); + + products.add(new Product(name, quantity)); + } + return products; + } + + private void validateProductFormat(String inputOrder) { + String[] orderList = inputOrder.split(","); + + for (String order : orderList) { + if (!isValidProductEntry(order.trim())) { + throw new IllegalArgumentException(INVALID_FORMAT); + } + } + } + + private boolean isValidProductEntry(String order) { + if (!order.startsWith("[") || !order.endsWith("]")) { + return false; + } + + String part = order.substring(1, order.length() - 1); + String[] parts = part.split("-"); + if (parts[0].isEmpty()) { + return false; + } + + return parts.length == 2; + } + + public List<Product> getOrder() { + return order; + } +}
Java
๊ฐœ์ธ์ ์œผ๋กœ ์œ„์˜ ์•ž ๋’ค [ ] ํ™•์ธํ•˜๋Š” ๋ถ€๋ถ„๊ณผ ๋นˆ๋ฌธ์ž์—ด์ธ์ง€ ํ™•์ธํ•˜๋Š” ๋กœ์ง์„ ๋ถ„๋ฆฌํ•ด๋„ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,50 @@ +package store.model; + +public class Receipt { + private String name; + private int individualPrice; + private int quantity; + private int promotionQuantity; + private int promotionBuy; + + public Receipt(String name, int individualPrice, int quantity, int promotionBuy) { + this.name = name; + this.individualPrice = individualPrice; + this.quantity = quantity; + this.promotionBuy = promotionBuy; + } + + public void addPromotion() { + quantity++; + } + + public void removeNonPromotion(int nomDiscountableQuantity) { + quantity -= nomDiscountableQuantity; + } + + public String getName() { + return name; + } + + public int getIndividualPrice() { + return individualPrice; + } + + public int getQuantity() { + return quantity; + } + + public int getPromotionQuantity() { + return promotionQuantity; + } + + public int getPromotionBuy() { + return promotionBuy; + } + + public void setPromotionQuantity(int promotionQuantity) { + this.promotionQuantity = promotionQuantity; + } +} + +
Java
์ด๋ฒˆ ๊ณผ์ œ์—์„œ ๊ฒŒํ„ฐ ์‚ฌ์šฉ์„ ์ค„์ด๊ธฐ๊ฐ€ ์‰ฝ์ง€ ์•Š์•„, ์ €๋„ ๊ฒฐ๊ตญ ์‚ฌ์šฉํ•  ์ˆ˜๋ฐ–์— ์—†์—ˆ์Šต๋‹ˆ๋‹คใ…œใ…œ ๊ฒŒํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๊ฐ์ฒด์˜ ์บก์Аํ™”๋ฅผ ์œ„๋ฐ˜ํ•  ์œ„ํ—˜์ด ์žˆ๊ณ , ๊ฐ์ฒด์˜ ์ƒํƒœ๋ฅผ ์™ธ๋ถ€์—์„œ ์‰ฝ๊ฒŒ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋˜์–ด ๊ฐ์ฒด์˜ ์ฑ…์ž„์ด ์™ธ๋ถ€๋กœ ๋ฐ€๋ ค๋‚  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ง€์–‘ํ•ด์•ผ ํ•œ๋‹ค๊ณ  ์•Œ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ์•ž์œผ๋กœ ๊ฒŒํ„ฐ ์‚ฌ์šฉ์„ ์ค„์ด๊ธฐ ์œ„ํ•ด DTO๋ฅผ ํ™œ์šฉํ•ด๋ณด๋Š” ๊ฒƒ๋„ ์ข‹์€ ๋ฐฉ๋ฒ•์ด ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,294 @@ +package store.service; + +import static store.model.Promotion.parsePromotions; +import static store.model.Store.*; +import static store.utils.ErrorMessage.INVALID_INPUT; +import static store.utils.ErrorMessage.INVALID_NAME; +import static store.utils.ErrorMessage.INVALID_QUANTITY; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import store.model.Order; +import store.model.Product; +import store.model.Promotion; +import store.model.Receipt; +import store.model.Store; +import store.view.InputView; +import store.view.OutputView; + +public class StoreService { + private static final int NON_PROMOTION = 0; + private static final int GET = 1; + private static final int MAX_MEMBERSHIP = 8000; + + public void loadProductsForm(List<Store> store) { + try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + addProduct(store, line); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + public void loadPromotionsForm(List<Promotion> promotions) { + try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + promotions.add(parsePromotions(line)); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + private void addProduct(List<Store> store, String line) { + checkNotPromotionProduct(store, line); + store.add(parseStore(line)); + } + + public void checkProduct(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + checkName(store, product); + checkQuantity(store, product); + } + } + + private void checkName(List<Store> store, Product product) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + return; + } + } + + throw new IllegalArgumentException(INVALID_NAME); + } + + private void checkQuantity(List<Store> store, Product product) { + int quantity = 0; + + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + quantity += storeProduct.getQuantity(); + } + } + + if (quantity < product.getQuantity()) { + throw new IllegalArgumentException(INVALID_QUANTITY); + } + } + + public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) { + List<Receipt> receipts = new ArrayList<>(); + + for (Product product : order.getOrder()) { + String name = product.getName(); + int indivialPrice = getPrice(store, product.getName()); + int quantity = product.getQuantity(); + int promotinBuy = checkPromotionProduct(store, product, promotions); + receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy)); + } + return receipts; + } + + private int getPrice(List<Store> store, String productName) { + int price = 0; + for (Store storeProduct : store) { + if (storeProduct.getName().equals(productName)) { + price = storeProduct.getPrice(); + } + } + + return price; + } + + private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + if (storeProduct.getQuantity() == 0) { + return 0; + } + return getPromotion(storeProduct.getPromotion(), promotions); + } + } + + return 0; + } + + private int getPromotion(String promotion, List<Promotion> promotions) { + for (Promotion promotionType : promotions) { + if (promotionType.getName().equals(promotion)) { + return promotionType.checkPromotionDate(); + } + } + return 0; + } + + public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkPromotionQuantity(receipt, store); + } + } + } + + private void checkPromotionQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkNonGet(receipt, storeProduct.getQuantity()); + break; + } + } + } + + private void checkNonGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) { + if (isGet(receipt, storeQuantity)) { + receipt.addPromotion(); + } + } + } + + private boolean isGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() + GET <= storeQuantity) { + while (true) { + try { + return isAnswer(InputView.getFree(receipt.getName())); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + return false; + } + + public void checkTribePromotion(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkStoreQuantity(receipt, store); + } + } + } + + private void checkStoreQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkOverGet(receipt, storeProduct); + break; + } + } + } + + private void checkOverGet(Receipt receipt, Store storeProduct) { + int promotionProductQuantity = storeProduct.getQuantity() + - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET); + + int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity; + + if (nomDiscountableQuantity > 0) { + if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) { + receipt.removeNonPromotion(nomDiscountableQuantity); + } + receipt.setPromotionQuantity(promotionProductQuantity); + return; + } + receipt.setPromotionQuantity( + receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1)); + } + + private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) { + while (true) { + try { + return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity)); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + public int membershipDiscount(List<Receipt> receipts) { + int totalPrice = 0; + int promotionPrice = 0; + + if (isMembership()) { + for (Receipt receipt : receipts) { + totalPrice += receipt.getIndividualPrice() * receipt.getQuantity(); + promotionPrice += checkPromotionPrice(receipt); + } + } + + return checkDisCount(totalPrice, promotionPrice); + } + + private boolean isMembership() { + while (true) { + try { + return isAnswer(InputView.membershipMessage()); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + private int checkPromotionPrice(Receipt receipt) { + return receipt.getIndividualPrice() * receipt.getPromotionQuantity(); + } + + private int checkDisCount(int totalPrice, int promotionPrice) { + int disCount = (int) ((totalPrice - promotionPrice) * 0.3); + if (disCount > MAX_MEMBERSHIP) { + return MAX_MEMBERSHIP; + } + + return disCount; + } + + public boolean isAnswer(String answer) { + if (answer.equals("Y")) { + return true; + } + if (answer.equals("N")) { + return false; + } + + throw new IllegalArgumentException(INVALID_INPUT); + } + + public void checkStock(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + handleProductDeduction(store, product); + } + } + + private void handleProductDeduction(List<Store> store, Product product) { + Store matchedStoreProduct = findStoreProduct(store, product.getName()); + + int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity()); + if (remainingQuantity > 0) { + applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity); + } + } + + private Store findStoreProduct(List<Store> store, String productName) { + return store.stream() + .filter(storeProduct -> storeProduct.getName().equals(productName)) + .findFirst() + .orElse(null); + } + + private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) { + for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) { + remainingQuantity = store.get(i).deduction(remainingQuantity); + } + } + +}
Java
์„œ๋น„์Šค์—์„œ View๋ฅผ ํ˜ธ์ถœํ•˜๋Š”๊ฑด ๊ฐœ์ธ์ ์œผ๋กœ layered architecture๊ตฌ์กฐ์ƒ ์ ํ•ฉํ•˜์ง€ ์•Š๋‹ค๊ณ  ์ƒ๊ฐ๋ฉ๋‹ˆ๋‹ค! Layered architecture๋Š” ๊ด€์‹ฌ์‚ฌ๋ณ„๋กœ ๊ณ„์ธต์„ ๋‚˜๋ˆˆ ๊ตฌ์กฐ๋กœ ์•Œ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. Presentation Layer ๋Š” ์‚ฌ์šฉ์ž์™€์˜ ์ƒํ˜ธ์ž‘์šฉ์„ ๋‹ด๋‹นํ•˜๋Š” ์—ญํ• , business Layer ๋Š” ๋น„์ง€๋‹ˆ์Šค ๋กœ์ง๋งŒ ๋‹ด๋‹นํ•˜๋Š” ์—ญํ• ์ž…๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ View ๊ฐ์ฒด๋“ค์€ presentation layer ์— ์†ํ•œ๋‹ค๊ณ  ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ํ˜„์žฌ ์ฝ”๋“œ๋ฅผ ๋ณด๋ฉด business layer ๊ฐ€ presentation layer ๋ฅผ ์˜์กดํ•˜๋Š” ๊ฒƒ์œผ๋กœ ๋ณด์ด๋Š”๋ฐ, ์ด๋ ‡๊ฒŒ ๋˜๋ฉด business layer์— presentation layer์˜ ์ฝ”๋“œ๊ฐ€ ๋…ธ์ถœ๋˜๊ธฐ๋•Œ๋ฌธ์—, ๊ด€์‹ฌ์‚ฌ๊ฐ€ ๋ถ„๋ฆฌ๋˜์ง€ ์•Š์•˜๋‹ค๊ณ  ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,86 @@ +package store.view; + +import static store.utils.ErrorMessage.ERROR; +import static store.utils.ErrorMessage.RETRY; + +import java.util.List; +import store.model.Receipt; +import store.model.Store; + +public class OutputView { + private static final String ERROR_ANSWER = "[ERROR] ์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + + private final String WECOME_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค.\nํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค.\n"; + private final String RESULT_START_MESSAGE = "\n==============W ํŽธ์˜์ ================"; + private final String RESULT_MESSAGE = "%-16s\t%-5s\t%s\n"; + private final String ORDER_LIST = "%-16s\t%-7d\t%,d\n"; + private final String PROMOTION_MESSAGE = "=============์ฆ ์ •==============="; + private final String PROMOTION_LIST = "%-16s\t%,-5d\n"; + private final String LINE = "===================================="; + + + public void printError(String errorMessage) { + System.out.println(ERROR + errorMessage + RETRY); + } + + public static void printErrorAnswer() { + System.out.println(ERROR_ANSWER); + } + + public void printProductList(List<Store> products) { + System.out.println(WECOME_MESSAGE); + + for (Store product : products) { + System.out.println(product); + } + } + + public void printReceipt(List<Receipt> receipts, int discount) { + System.out.println(RESULT_START_MESSAGE); + System.out.printf(RESULT_MESSAGE, "์ƒํ’ˆ๋ช…", "์ˆ˜๋Ÿ‰", "๊ธˆ์•ก"); + int totalOrderPrice = printOrder(receipts); + + System.out.println(PROMOTION_MESSAGE); + int totalPromotionPrice = printPromotion(receipts); + + System.out.println(LINE); + printPaymentPrice(receipts, totalOrderPrice, totalPromotionPrice, discount); + } + + private int printOrder(List<Receipt> receipts) { + int totalOrder = 0; + + for (Receipt receipt : receipts) { + int price = receipt.getIndividualPrice() * receipt.getQuantity(); + totalOrder += price; + System.out.printf(ORDER_LIST, receipt.getName(), receipt.getQuantity(), price); + } + + return totalOrder; + } + + private int printPromotion(List<Receipt> receipts) { + int totalPromotion = 0; + + for (Receipt receipt : receipts) { + if (receipt.getPromotionQuantity() != 0) { + int price = receipt.getIndividualPrice() * (receipt.getPromotionQuantity() / (receipt.getPromotionBuy() + 1)); + totalPromotion += price; + System.out.printf(PROMOTION_LIST, receipt.getName(), receipt.getPromotionQuantity() / (receipt.getPromotionBuy() + 1)); + } + } + + return totalPromotion; + } + + private void printPaymentPrice(List<Receipt> receipts, int totalOrder, int totalPromotion, int discount) { + int totalQuantity = 0; + for (Receipt receipt : receipts) { + totalQuantity += receipt.getQuantity(); + } + System.out.printf("%-16s\t%-7d\t%,-7d\n", "์ด๊ตฌ๋งค์•ก", totalQuantity, totalOrder); + System.out.printf("%-23s\t-%,d\n", "ํ–‰์‚ฌํ• ์ธ", totalPromotion); + System.out.printf("%-23s\t-%,d\n", "๋ฉค๋ฒ„์‹ญํ• ์ธ", discount); + System.out.printf("%-23s\t%,d\n", "๋‚ด์‹ค๋ˆ", (totalOrder - totalPromotion - discount)); + } +} \ No newline at end of file
Java
์ด ๋ถ€๋ถ„์„ ์ƒ์ˆ˜๋กœ ์ฒ˜๋ฆฌํ•˜์ง€ ์•Š์€ ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,89 @@ +package store.controller; + +import java.util.ArrayList; +import java.util.List; +import store.model.Order; +import store.model.Promotion; +import store.model.Receipt; +import store.model.Store; +import store.service.StoreService; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + private final InputView inputView; + private final OutputView outputView; + private final StoreService storeService; + + public StoreController(InputView inputView, OutputView outputView, StoreService storeService) { + this.inputView = inputView; + this.outputView = outputView; + this.storeService = storeService; + } + + public void run() { + List<Store> store = printProductList(); + List<Promotion> promotions = loadPromotions(); + Order order; + + do { + order = purchaseProduct(store); + priceCalculator(store, order, promotions); + + } while (!checkEnd(store, order)); + } + + private boolean checkEnd(List<Store> store, Order order) { + while (true) { + try { + if (!storeService.isAnswer(inputView.inputEndMessage())) { + return true; + } + updateStore(store, order); + return false; + } catch (IllegalArgumentException e) { + outputView.printError(e.getMessage()); + } + } + } + + private void updateStore(List<Store> store, Order order) { + storeService.checkStock(store, order); + outputView.printProductList(store); + } + + private void priceCalculator(List<Store> store, Order order, List<Promotion> promotions) { + List<Receipt> receipts = storeService.parseReceipt(store, order, promotions); + storeService.checkTribeQuantity(receipts, store); + storeService.checkTribePromotion(receipts, store); + int discount = storeService.membershipDiscount(receipts); + + outputView.printReceipt(receipts, discount); + } + + private List<Store> printProductList() { + List<Store> store = new ArrayList<>(); + storeService.loadProductsForm(store); + outputView.printProductList(store); + return store; + } + + private List<Promotion> loadPromotions() { + List<Promotion> promotions = new ArrayList<>(); + storeService.loadPromotionsForm(promotions); + return promotions; + } + + private Order purchaseProduct(List<Store> store) { + while (true) { + try { + String inputOrder = inputView.inputPurchaseProduct(); + Order order = new Order(inputOrder); + storeService.checkProduct(store, order); + return order; + } catch (IllegalArgumentException e) { + outputView.printError(e.getMessage()); + } + } + } +}
Java
do while๋ฌธ์„ ์ฒ˜์Œ ์‚ฌ์šฉํ•ด์„œ ์ž˜ ๋ชฐ๋ž๋Š”๋ฐ ์•ˆ์—์„œ ์„ ์–ธํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ์ƒ๊ฐ๋„ ๋ชปํ–ˆ๋„ค์š” ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค!
@@ -0,0 +1,73 @@ +package store.model; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +public class Promotion { + private String name; + private int buy; + private int get; + private String startDateStr; + private String endDateStr; + + public Promotion(String name, int buy, int get, String startdateStr, String enddateStr) { + this.name = name; + this.buy = buy; + this.get = get; + this.startDateStr = startdateStr; + this.endDateStr = enddateStr; + } + + public static Promotion parsePromotions(String line) { + List<String> promotion = Arrays.asList(line.split(",")); + + String name = promotion.get(0).trim(); + int buy = Integer.parseInt(promotion.get(1).trim()); + int get = Integer.parseInt(promotion.get(2).trim()); + String start_date = promotion.get(3).trim(); + String end_date = promotion.get(4).trim(); + + return new Promotion(name, buy, get, start_date, end_date); + } + + public int checkPromotionDate() { + final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); + + try { + Date startDate = DATE_FORMAT.parse(startDateStr); + Date endDate = DATE_FORMAT.parse(endDateStr); + Date now = DATE_FORMAT.parse(String.valueOf(DateTimes.now())); + + if (!now.before(startDate) && !now.after(endDate)) { + return this.buy; + } + } catch (ParseException e) { + return 0; + } + return 0; + } + + public String getName() { + return name; + } + + public int getBuy() { + return buy; + } + + public int getGet() { + return get; + } + + public String getStartDateStr() { + return startDateStr; + } + + public String getEndDateStr() { + return endDateStr; + } +}
Java
๊ฐ€๋…์„ฑ์ด ๋” ์ข‹๋‹ค๊ณ  ์ƒ๊ฐ๋˜๋Š” ๋ฐฉํ–ฅ์œผ๋กœ ์ž‘์„ฑํ–ˆ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,294 @@ +package store.service; + +import static store.model.Promotion.parsePromotions; +import static store.model.Store.*; +import static store.utils.ErrorMessage.INVALID_INPUT; +import static store.utils.ErrorMessage.INVALID_NAME; +import static store.utils.ErrorMessage.INVALID_QUANTITY; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import store.model.Order; +import store.model.Product; +import store.model.Promotion; +import store.model.Receipt; +import store.model.Store; +import store.view.InputView; +import store.view.OutputView; + +public class StoreService { + private static final int NON_PROMOTION = 0; + private static final int GET = 1; + private static final int MAX_MEMBERSHIP = 8000; + + public void loadProductsForm(List<Store> store) { + try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + addProduct(store, line); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + public void loadPromotionsForm(List<Promotion> promotions) { + try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + promotions.add(parsePromotions(line)); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + private void addProduct(List<Store> store, String line) { + checkNotPromotionProduct(store, line); + store.add(parseStore(line)); + } + + public void checkProduct(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + checkName(store, product); + checkQuantity(store, product); + } + } + + private void checkName(List<Store> store, Product product) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + return; + } + } + + throw new IllegalArgumentException(INVALID_NAME); + } + + private void checkQuantity(List<Store> store, Product product) { + int quantity = 0; + + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + quantity += storeProduct.getQuantity(); + } + } + + if (quantity < product.getQuantity()) { + throw new IllegalArgumentException(INVALID_QUANTITY); + } + } + + public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) { + List<Receipt> receipts = new ArrayList<>(); + + for (Product product : order.getOrder()) { + String name = product.getName(); + int indivialPrice = getPrice(store, product.getName()); + int quantity = product.getQuantity(); + int promotinBuy = checkPromotionProduct(store, product, promotions); + receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy)); + } + return receipts; + } + + private int getPrice(List<Store> store, String productName) { + int price = 0; + for (Store storeProduct : store) { + if (storeProduct.getName().equals(productName)) { + price = storeProduct.getPrice(); + } + } + + return price; + } + + private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + if (storeProduct.getQuantity() == 0) { + return 0; + } + return getPromotion(storeProduct.getPromotion(), promotions); + } + } + + return 0; + } + + private int getPromotion(String promotion, List<Promotion> promotions) { + for (Promotion promotionType : promotions) { + if (promotionType.getName().equals(promotion)) { + return promotionType.checkPromotionDate(); + } + } + return 0; + } + + public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkPromotionQuantity(receipt, store); + } + } + } + + private void checkPromotionQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkNonGet(receipt, storeProduct.getQuantity()); + break; + } + } + } + + private void checkNonGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) { + if (isGet(receipt, storeQuantity)) { + receipt.addPromotion(); + } + } + } + + private boolean isGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() + GET <= storeQuantity) { + while (true) { + try { + return isAnswer(InputView.getFree(receipt.getName())); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + return false; + } + + public void checkTribePromotion(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkStoreQuantity(receipt, store); + } + } + } + + private void checkStoreQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkOverGet(receipt, storeProduct); + break; + } + } + } + + private void checkOverGet(Receipt receipt, Store storeProduct) { + int promotionProductQuantity = storeProduct.getQuantity() + - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET); + + int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity; + + if (nomDiscountableQuantity > 0) { + if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) { + receipt.removeNonPromotion(nomDiscountableQuantity); + } + receipt.setPromotionQuantity(promotionProductQuantity); + return; + } + receipt.setPromotionQuantity( + receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1)); + } + + private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) { + while (true) { + try { + return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity)); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + public int membershipDiscount(List<Receipt> receipts) { + int totalPrice = 0; + int promotionPrice = 0; + + if (isMembership()) { + for (Receipt receipt : receipts) { + totalPrice += receipt.getIndividualPrice() * receipt.getQuantity(); + promotionPrice += checkPromotionPrice(receipt); + } + } + + return checkDisCount(totalPrice, promotionPrice); + } + + private boolean isMembership() { + while (true) { + try { + return isAnswer(InputView.membershipMessage()); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + private int checkPromotionPrice(Receipt receipt) { + return receipt.getIndividualPrice() * receipt.getPromotionQuantity(); + } + + private int checkDisCount(int totalPrice, int promotionPrice) { + int disCount = (int) ((totalPrice - promotionPrice) * 0.3); + if (disCount > MAX_MEMBERSHIP) { + return MAX_MEMBERSHIP; + } + + return disCount; + } + + public boolean isAnswer(String answer) { + if (answer.equals("Y")) { + return true; + } + if (answer.equals("N")) { + return false; + } + + throw new IllegalArgumentException(INVALID_INPUT); + } + + public void checkStock(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + handleProductDeduction(store, product); + } + } + + private void handleProductDeduction(List<Store> store, Product product) { + Store matchedStoreProduct = findStoreProduct(store, product.getName()); + + int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity()); + if (remainingQuantity > 0) { + applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity); + } + } + + private Store findStoreProduct(List<Store> store, String productName) { + return store.stream() + .filter(storeProduct -> storeProduct.getName().equals(productName)) + .findFirst() + .orElse(null); + } + + private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) { + for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) { + remainingQuantity = store.get(i).deduction(remainingQuantity); + } + } + +}
Java
readLine() ์„ ์‚ฌ์šฉํ•˜์—ฌ ํ•œ ์ค„์”ฉ ์ฝ๊ธฐ ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•˜์—ฌ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,14 @@ +package store.utils; + +public class ErrorMessage { + public static final String ERROR = "[ERROR] "; + public static final String RETRY = " ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + public static final String INVALID_FORMAT = " ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. "; + public static final String INVALID_NAME = " ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."; + public static final String INVALID_QUANTITY = "์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."; + public static final String INVALID_INPUT = "์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค."; + + private ErrorMessage() { + + } +}
Java
๊ฐ’๋“ค์„ ๊ทธ๋ฃนํ™” ํ•˜์—ฌ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ๋‹จ์ˆœ ๋ฉ”์„ธ์ง€ ์ถœ๋ ฅ์ด๊ธฐ์— ์ƒ์ˆ˜ ํด๋ž˜์Šค๋กœ ํ•ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,73 @@ +package store.model; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +public class Promotion { + private String name; + private int buy; + private int get; + private String startDateStr; + private String endDateStr; + + public Promotion(String name, int buy, int get, String startdateStr, String enddateStr) { + this.name = name; + this.buy = buy; + this.get = get; + this.startDateStr = startdateStr; + this.endDateStr = enddateStr; + } + + public static Promotion parsePromotions(String line) { + List<String> promotion = Arrays.asList(line.split(",")); + + String name = promotion.get(0).trim(); + int buy = Integer.parseInt(promotion.get(1).trim()); + int get = Integer.parseInt(promotion.get(2).trim()); + String start_date = promotion.get(3).trim(); + String end_date = promotion.get(4).trim(); + + return new Promotion(name, buy, get, start_date, end_date); + } + + public int checkPromotionDate() { + final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); + + try { + Date startDate = DATE_FORMAT.parse(startDateStr); + Date endDate = DATE_FORMAT.parse(endDateStr); + Date now = DATE_FORMAT.parse(String.valueOf(DateTimes.now())); + + if (!now.before(startDate) && !now.after(endDate)) { + return this.buy; + } + } catch (ParseException e) { + return 0; + } + return 0; + } + + public String getName() { + return name; + } + + public int getBuy() { + return buy; + } + + public int getGet() { + return get; + } + + public String getStartDateStr() { + return startDateStr; + } + + public String getEndDateStr() { + return endDateStr; + } +}
Java
์—ญํ•  ๋ถ„๋ฆฌ๋ฅผ ์ข€ ๋” ์ƒ์„ธํžˆ ํ•ด์•ผ ๋  ๊ฒƒ ๊ฐ™๋„ค์š”.. ์ฐธ๊ณ ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,50 @@ +package store.model; + +public class Receipt { + private String name; + private int individualPrice; + private int quantity; + private int promotionQuantity; + private int promotionBuy; + + public Receipt(String name, int individualPrice, int quantity, int promotionBuy) { + this.name = name; + this.individualPrice = individualPrice; + this.quantity = quantity; + this.promotionBuy = promotionBuy; + } + + public void addPromotion() { + quantity++; + } + + public void removeNonPromotion(int nomDiscountableQuantity) { + quantity -= nomDiscountableQuantity; + } + + public String getName() { + return name; + } + + public int getIndividualPrice() { + return individualPrice; + } + + public int getQuantity() { + return quantity; + } + + public int getPromotionQuantity() { + return promotionQuantity; + } + + public int getPromotionBuy() { + return promotionBuy; + } + + public void setPromotionQuantity(int promotionQuantity) { + this.promotionQuantity = promotionQuantity; + } +} + +
Java
๋ง์”€ํ•˜์‹  ๋‚ด์šฉ ๋“ฃ๊ณ  ์ œ ์ฝ”๋“œ๋ฅผ ๋‹ค์‹œ ์‚ดํŽด๋ณด๋‹ˆ, ๊ฐ์ฒด๋‚ด์—์„œ๋Š” ๋‹จ์ˆœํžˆ ๋ฐ์ดํ„ฐ๋งŒ ๋‹ด์•„๋‘๊ณ  ๊ฒŒํ„ฐ ์‚ฌ์šฉ์œผ๋กœ ๋Œ€๋ถ€๋ถ„ ์™ธ๋ถ€์—์„œ ๋กœ์ง์„ ์ฒ˜๋ฆฌํ•˜์—ฌ ๊ฐ์ฒด์ง€ํ–ฅ์˜ ์˜๋ฏธ๋ฅผ ์žƒ์€ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค... ๊ตฌํ˜„ํ•˜๋Š”๋ฐ ๋„ˆ๋ฌด ๊ธ‰๊ธ‰ํ–ˆ๋˜๊ฑฐ๊ฐ™๋„ค์š”ใ… ใ…  ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,294 @@ +package store.service; + +import static store.model.Promotion.parsePromotions; +import static store.model.Store.*; +import static store.utils.ErrorMessage.INVALID_INPUT; +import static store.utils.ErrorMessage.INVALID_NAME; +import static store.utils.ErrorMessage.INVALID_QUANTITY; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import store.model.Order; +import store.model.Product; +import store.model.Promotion; +import store.model.Receipt; +import store.model.Store; +import store.view.InputView; +import store.view.OutputView; + +public class StoreService { + private static final int NON_PROMOTION = 0; + private static final int GET = 1; + private static final int MAX_MEMBERSHIP = 8000; + + public void loadProductsForm(List<Store> store) { + try (InputStream in = Store.class.getResourceAsStream("/products.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + addProduct(store, line); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + public void loadPromotionsForm(List<Promotion> promotions) { + try (InputStream in = Store.class.getResourceAsStream("/promotions.md"); BufferedReader br = new BufferedReader( + new InputStreamReader(in))) { + String line = br.readLine(); + + while ((line = br.readLine()) != null) { + promotions.add(parsePromotions(line)); + } + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + private void addProduct(List<Store> store, String line) { + checkNotPromotionProduct(store, line); + store.add(parseStore(line)); + } + + public void checkProduct(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + checkName(store, product); + checkQuantity(store, product); + } + } + + private void checkName(List<Store> store, Product product) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + return; + } + } + + throw new IllegalArgumentException(INVALID_NAME); + } + + private void checkQuantity(List<Store> store, Product product) { + int quantity = 0; + + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + quantity += storeProduct.getQuantity(); + } + } + + if (quantity < product.getQuantity()) { + throw new IllegalArgumentException(INVALID_QUANTITY); + } + } + + public List<Receipt> parseReceipt(List<Store> store, Order order, List<Promotion> promotions) { + List<Receipt> receipts = new ArrayList<>(); + + for (Product product : order.getOrder()) { + String name = product.getName(); + int indivialPrice = getPrice(store, product.getName()); + int quantity = product.getQuantity(); + int promotinBuy = checkPromotionProduct(store, product, promotions); + receipts.add(new Receipt(name, indivialPrice, quantity, promotinBuy)); + } + return receipts; + } + + private int getPrice(List<Store> store, String productName) { + int price = 0; + for (Store storeProduct : store) { + if (storeProduct.getName().equals(productName)) { + price = storeProduct.getPrice(); + } + } + + return price; + } + + private int checkPromotionProduct(List<Store> store, Product product, List<Promotion> promotions) { + for (Store storeProduct : store) { + if (storeProduct.getName().equals(product.getName())) { + if (storeProduct.getQuantity() == 0) { + return 0; + } + return getPromotion(storeProduct.getPromotion(), promotions); + } + } + + return 0; + } + + private int getPromotion(String promotion, List<Promotion> promotions) { + for (Promotion promotionType : promotions) { + if (promotionType.getName().equals(promotion)) { + return promotionType.checkPromotionDate(); + } + } + return 0; + } + + public void checkTribeQuantity(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkPromotionQuantity(receipt, store); + } + } + } + + private void checkPromotionQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkNonGet(receipt, storeProduct.getQuantity()); + break; + } + } + } + + private void checkNonGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() % (receipt.getPromotionBuy() + GET) == receipt.getPromotionBuy()) { + if (isGet(receipt, storeQuantity)) { + receipt.addPromotion(); + } + } + } + + private boolean isGet(Receipt receipt, int storeQuantity) { + if (receipt.getQuantity() + GET <= storeQuantity) { + while (true) { + try { + return isAnswer(InputView.getFree(receipt.getName())); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + return false; + } + + public void checkTribePromotion(List<Receipt> receipts, List<Store> store) { + for (Receipt receipt : receipts) { + if (receipt.getPromotionBuy() != NON_PROMOTION) { + checkStoreQuantity(receipt, store); + } + } + } + + private void checkStoreQuantity(Receipt receipt, List<Store> store) { + for (Store storeProduct : store) { + if (receipt.getName().equals(storeProduct.getName())) { + checkOverGet(receipt, storeProduct); + break; + } + } + } + + private void checkOverGet(Receipt receipt, Store storeProduct) { + int promotionProductQuantity = storeProduct.getQuantity() + - (storeProduct.getQuantity() % receipt.getPromotionBuy() + GET); + + int nomDiscountableQuantity = receipt.getQuantity() - promotionProductQuantity; + + if (nomDiscountableQuantity > 0) { + if (!isPaymentConfirmed(receipt, nomDiscountableQuantity)) { + receipt.removeNonPromotion(nomDiscountableQuantity); + } + receipt.setPromotionQuantity(promotionProductQuantity); + return; + } + receipt.setPromotionQuantity( + receipt.getQuantity() / (receipt.getPromotionBuy() + 1) * (receipt.getPromotionBuy() + 1)); + } + + private boolean isPaymentConfirmed(Receipt receipt, int nomDiscountableQuantity) { + while (true) { + try { + return isAnswer(InputView.askForPayment(receipt.getName(), nomDiscountableQuantity)); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + public int membershipDiscount(List<Receipt> receipts) { + int totalPrice = 0; + int promotionPrice = 0; + + if (isMembership()) { + for (Receipt receipt : receipts) { + totalPrice += receipt.getIndividualPrice() * receipt.getQuantity(); + promotionPrice += checkPromotionPrice(receipt); + } + } + + return checkDisCount(totalPrice, promotionPrice); + } + + private boolean isMembership() { + while (true) { + try { + return isAnswer(InputView.membershipMessage()); + } catch (IllegalArgumentException e) { + OutputView.printErrorAnswer(); + } + } + } + + private int checkPromotionPrice(Receipt receipt) { + return receipt.getIndividualPrice() * receipt.getPromotionQuantity(); + } + + private int checkDisCount(int totalPrice, int promotionPrice) { + int disCount = (int) ((totalPrice - promotionPrice) * 0.3); + if (disCount > MAX_MEMBERSHIP) { + return MAX_MEMBERSHIP; + } + + return disCount; + } + + public boolean isAnswer(String answer) { + if (answer.equals("Y")) { + return true; + } + if (answer.equals("N")) { + return false; + } + + throw new IllegalArgumentException(INVALID_INPUT); + } + + public void checkStock(List<Store> store, Order order) { + for (Product product : order.getOrder()) { + handleProductDeduction(store, product); + } + } + + private void handleProductDeduction(List<Store> store, Product product) { + Store matchedStoreProduct = findStoreProduct(store, product.getName()); + + int remainingQuantity = matchedStoreProduct.deduction(product.getQuantity()); + if (remainingQuantity > 0) { + applyRemainingDeduction(store, store.indexOf(matchedStoreProduct) + 1, remainingQuantity); + } + } + + private Store findStoreProduct(List<Store> store, String productName) { + return store.stream() + .filter(storeProduct -> storeProduct.getName().equals(productName)) + .findFirst() + .orElse(null); + } + + private void applyRemainingDeduction(List<Store> store, int startIndex, int remainingQuantity) { + for (int i = startIndex; i < store.size() && remainingQuantity > 0; i++) { + remainingQuantity = store.get(i).deduction(remainingQuantity); + } + } + +}
Java
OutputView ํด๋ž˜์Šค์—์„œ ์œ ์ผํ•˜๊ฒŒ ์ž‘์„ฑํ•œ ์Šคํƒœํ‹ฑ ๋ฉ”์„œ๋“œ ์ž…๋‹ˆ๋‹ค. ์ €๋„ ๊ตฌํ˜„ํ•˜๋Š” ๊ณผ์ •์—์„œ ์˜ณ์ง€ ์•Š๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์ง€๋งŒ, ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์„ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ณผ์ •์—์„œ ์˜ณ์ง€ ์•Š์€ ์ž…๋ ฅ์ด ์™”์„ ๋•Œ outputView ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐ ํ•  ๋ฐฉ๋ฒ•์ด ๋– ์˜ค๋ฅด์ง€ ์•Š์•„ ์ด๋ ‡๊ฒŒ ์ž‘์„ฑํ•˜๊ฒŒ ๋์Šต๋‹ˆ๋‹ค.. ์ ํ•ฉํ•˜์ง€ ์•Š์€ ์ด์œ ๋ฅผ ์ƒ์„ธํ•˜๊ฒŒ ๋ง์”€ํ•ด ์ฃผ์…”์„œ ์ƒˆ๋กญ๊ฒŒ ํ•˜๋‚˜ ๋” ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค..!
@@ -0,0 +1,16 @@ +package store.constant; + +public enum CommonMessage { + YES("Y"), + NO("N"); + private final String commonMessage; + + CommonMessage(final String commonMessage) { + this.commonMessage = commonMessage; + } + + public String getCommonMessage() { + return commonMessage; + } + +}
Java
์ž…๋ ฅ์ด ๋‘˜๋ฟ์ธ ๊ฒฝ์šฐ์— ๋Œ€ํ•ด์„œ Enum์œผ๋กœ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์€ ๋ฐฉ๋ฒ•์ธ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,22 @@ +package store.constant; + +public enum FileMessage { + PRODUCTS_FILE_NAME("products.md"), + PROMOTION_FILE_NAME("promotions.md"), + NULL("null"), + SOFT_DRINK("ํƒ„์‚ฐ2+1"), + MD_RECOMMEND_PRODUCT("MD์ถ”์ฒœ์ƒํ’ˆ"), + FLASH_DISCOUNT("๋ฐ˜์งํ• ์ธ"), + FILE_START_WORD("name"); + + private final String fileMessage; + + FileMessage(final String fileMessage) { + this.fileMessage = fileMessage; + } + + public String getFileMessage() { + return fileMessage; + } + +}
Java
ํŒŒ์ผ์— ์žˆ๋Š” ํ”„๋กœ๋ชจ์…˜ ๋ฐ์ดํ„ฐ๋ฅผ Enum์œผ๋กœ ๊ด€๋ฆฌํ•˜๋Š”๊ฑด ์ข‹์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ํ”„๋กœ๋ชจ์…˜ ์ข…๋ฅ˜๊ฐ€ 3๊ฐœ ๊ณ ์ •์ด ์•„๋‹ˆ๋ผ ๊ฐ๊ธฐ ๋‹ค๋ฅธ ์ˆ˜๋ฐฑ ๊ฐœ, ์ˆ˜์ฒœ ๊ฐœ๋กœ ๋Š˜์–ด๋‚  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,71 @@ +package store.domain; + +import java.util.ArrayList; +import java.util.List; +import store.constant.CommonMessage; +import store.constant.CommonValue; + +public class Receipt { + private final double THIRTY_PERCENT = 0.3; + private final List<ReceiptItem> receiptItems = new ArrayList<>(); + + public void addItem(ReceiptItem receiptItem) { + receiptItems.add(receiptItem); + } + + public List<ReceiptItem> getReceiptItems() { + return receiptItems; + } + + public int totalPurchaseAmount() { + int sum = CommonValue.ZERO.getValue(); + for (ReceiptItem receiptItem : receiptItems) { + sum += receiptItem.getTotalBuyQuantity() * receiptItem.getPrice(); + } + return sum; + } + + public int totalPromotionDiscount() { + int sum = CommonValue.ZERO.getValue(); + for (ReceiptItem receiptItem : receiptItems) { + if (receiptItem.getGetQuantity() != CommonValue.ZERO.getValue()) { + sum += receiptItem.getGetQuantity() * receiptItem.getPrice(); + } + } + return sum; + } + + public int getTotalPurchaseCount() { + int sum = CommonValue.ZERO.getValue(); + for (ReceiptItem receiptItem : receiptItems) { + sum += receiptItem.getTotalBuyQuantity(); + } + return sum; + } + + public int validateMembership(String userAnswer) { + if (userAnswer.equals(CommonMessage.YES.getCommonMessage())) { + return getMembershipDiscount(); + } + return CommonValue.ZERO.getValue(); + } + + private int noTotalPromotionAmount() { + int sum = CommonValue.ZERO.getValue(); + for (ReceiptItem receiptItem : receiptItems) { + if (receiptItem.getGetQuantity() == CommonValue.ZERO.getValue()) { + sum += receiptItem.getBuyQuantity() * receiptItem.getPrice(); + } + } + return sum; + } + + private int getMembershipDiscount() { + int membershipDiscount = (int) (noTotalPromotionAmount() * THIRTY_PERCENT); + if (membershipDiscount > CommonValue.EIGHT_THOUSAND.getValue()) { + membershipDiscount = CommonValue.EIGHT_THOUSAND.getValue(); + } + return membershipDiscount; + } + +}
Java
model์˜ ์—ญํ• ์„ ์ˆ˜ํ–‰ํ•˜๋Š” ํด๋ž˜์Šค๋กœ ๋ณด์ด๋Š”๋ฐ ํŒจํ‚ค์ง€๋ฅผ ๋ถ„๋ฆฌํ•˜์ง€ ์•Š๊ณ , domain ํŒจํ‚ค์ง€์— ๊ฐ™์ด ๋‘์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,143 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.List; +import java.util.function.Supplier; +import store.constant.CommonMessage; +import store.constant.CommonValue; +import store.constant.SignMessage; +import store.domain.GeneralProduct; +import store.domain.PromotionProduct; +import store.domain.Receipt; +import store.domain.Storage; +import store.exception.ConvenienceStoreException; +import store.service.ReceiptService; +import store.service.StorageService; +import store.utils.Calculator; +import store.utils.Compare; +import store.utils.Parser; +import store.view.input.InputView; +import store.view.output.OutputView; + +public class ConvenienceStoreController { + private final InputView inputView; + private final OutputView outputView; + private final Storage storage; + + public ConvenienceStoreController(InputView inputView, OutputView outputView, StorageService storageService) { + this.inputView = inputView; + this.outputView = outputView; + this.storage = storageService.initializeStorage(); + } + + public void operate() { + String retryFlag; + do { + outputView.writeStorageStatus(storage); + Receipt receipt = new Receipt(); + processPurchase(userPurchaseProduct(), receipt); + outputView.writeReceipt(receipt, userMembership()); + retryFlag = userRetry(); + } while (retryFlag.equalsIgnoreCase(CommonMessage.YES.getCommonMessage())); + inputView.closeConsole(); + } + + private void processPurchase(List<String> purchaseProduct, Receipt receipt) { + for (String detail : purchaseProduct) { + List<String> item = List.of(detail.split(SignMessage.HYPHEN.getSign())); + PromotionProduct product = storage.findPromotionProduct(item.get(CommonValue.ZERO.getValue())); + if (product != null && product.getPromotion().isActive(DateTimes.now())) { + processPromotionProduct(product, Parser.parse(item.get(CommonValue.ONE.getValue())), receipt); + continue; + } + processGeneralPurchase(item, receipt); + } + } + + private void processGeneralPurchase(List<String> item, Receipt receipt) { + ReceiptService.purchaseGeneralProduct(storage, item.get(CommonValue.ZERO.getValue()), + Integer.parseInt(item.get(CommonValue.ONE.getValue())), receipt); + } + + private void processPromotionProduct(PromotionProduct promotionProduct, int itemQuantity, Receipt receipt) { + int stock = Calculator.calculateRemainStock(promotionProduct, itemQuantity); + int purchase = Calculator.calculateUserRemain(promotionProduct, itemQuantity); + boolean freeTag = userOneMoreFree(purchase, stock, promotionProduct, itemQuantity, receipt); + boolean supplementTag = supplementStock(itemQuantity, stock, promotionProduct, receipt); + useStock(freeTag, supplementTag, promotionProduct, itemQuantity, receipt); + } + + private boolean userOneMoreFree(int leftBuy, int leftStock, PromotionProduct product, int count, Receipt receipt) { + if (Compare.checkFreeOneMore(leftBuy, leftStock, product)) { + storage.subtractPromotionProduct(product, count); + if (checkUserAnswer(product).equals(CommonMessage.YES.getCommonMessage())) { + storage.subtractPromotionProduct(product, product.getPromotionGetGet()); + return ReceiptService.oneMoreReceipt(receipt, count, leftBuy, product); + } + return ReceiptService.noOneMoreReceipt(receipt, count, leftBuy, product); + } + return false; + } + + private boolean supplementStock(int quantity, int stock, PromotionProduct product, Receipt receipt) { + if (Compare.checkSupplementStock(stock)) { + int noPromotion = Calculator.calculateNoPromotion(product); + int beforePromotionQuantity = product.getQuantity(); + storage.subtractPromotionProduct(product, noPromotion); + String userAnswer = checkUserNoPromotion(product, Calculator.minus(quantity, noPromotion)); + return suppleGeneralProduct(product, userAnswer, Calculator.minus(quantity, noPromotion), receipt, + beforePromotionQuantity); + } + return false; + } + + private boolean suppleGeneralProduct(PromotionProduct product, String answer, int quantity, Receipt receipt, + int prevQuantity) { + GeneralProduct generalProduct = storage.findGeneralProduct(product.getName()); + int currentQuantity = product.getQuantity(); + if (answer.equals(CommonMessage.YES.getCommonMessage())) { + storage.subtractGeneralProduct(generalProduct, Calculator.minus(quantity, currentQuantity)); + storage.subtractPromotionProduct(product, currentQuantity); + return ReceiptService.noDiscountPurchase(receipt, quantity, prevQuantity, currentQuantity, product); + } + return ReceiptService.noOneMoreReceipt(receipt, prevQuantity, currentQuantity, product); + } + + private void useStock(boolean freeTag, boolean suppleTag, PromotionProduct product, int quantity, Receipt receipt) { + if (!freeTag && !suppleTag) { + storage.subtractPromotionProduct(product, quantity); + ReceiptService.useStock(product, quantity, receipt); + } + } + + private String userRetry() { + return handleUserInput(inputView::readRetry); + } + + private String userMembership() { + return handleUserInput(inputView::readMembership); + } + + private List<String> userPurchaseProduct() { + return handleUserInput(() -> storage.validateStorageStatus(inputView.readItems())); + } + + private String checkUserAnswer(PromotionProduct promotionProduct) { + return handleUserInput(() -> inputView.readOneMoreFree(promotionProduct.getName())); + } + + private String checkUserNoPromotion(PromotionProduct promotionProduct, int quantity) { + return handleUserInput(() -> inputView.readNoDiscountAnswer(promotionProduct.getName(), quantity)); + } + + private <T> T handleUserInput(Supplier<T> inputSupplier) { + while (true) { + try { + return inputSupplier.get(); + } catch (ConvenienceStoreException convenienceStoreException) { + outputView.displayErrorMessage(convenienceStoreException); + } + } + } + +}
Java
`userMembership()`์—์„œ ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์—ฌ๋ถ€์— ๋”ฐ๋ผ ์ตœ์ข… ๊ณ„์‚ฐ ๊ธˆ์•ก์—์„œ 30% ํ• ์ธ์ด ๋˜๊ณ  ์žˆ๋Š”๋ฐ, ์š”๊ตฌ์‚ฌํ•ญ์—์„œ๋Š” ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์„ ์ œ์™ธํ•œ ์ผ๋ฐ˜ ์ƒํ’ˆ์œผ๋กœ ๊ฒฐ์ œ๋œ ์ƒํ’ˆ๋“ค์— ๋Œ€ํ•ด์„œ๋งŒ ๋ฉค๋ฒ„์‹ญ ํ• ์ธ์ด ๋˜์–ด์•ผ ํ•œ๋‹ค๊ณ  ๋ช…์‹œ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค ์ด ๋ถ€๋ถ„์ด ์ฒ˜๋ฆฌ๋˜์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,19 @@ +package store.constant; + +public enum CommonValue { + ZERO(0), + ONE(1), + TWO(2), + EIGHT_THOUSAND(8000); + + private final int value; + + CommonValue(final int value) { + this.value = value; + } + + public int getValue() { + return value; + } + +}
Java
์ƒ์ˆ˜๋“ค์„ enum์œผ๋กœ ์ž˜ ๊ด€๋ฆฌํ•ด์ฃผ์…จ๋Š”๋ฐ์š”! ์ €๋Š” ๊ฐœ์ธ์ ์œผ๋กœ enum์˜ ๊ฐ’์„ ๊บผ๋‚ด๊ธฐ ์œ„ํ•ด `.getValue()` ๊นŒ์ง€ ๋ถ™๋Š”๊ฒŒ ์กฐ๊ธˆ ์ง€์ €๋ถ„ํ•ด๋ณด์ž…๋‹ˆ๋‹ค. static ์ƒ์ˆ˜์˜ ๊ฒฝ์šฐ `Constant.ZERO` ์ด๋Ÿฐ์‹์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์ง€๋งŒ enum์€ `CommonValue.ZERO.getValue()` ๋กœ 1depth ๋” ๋Š˜์–ด๋‚˜๋Š” ๋А๋‚Œ์ด๋ž„๊นŒ์š”..?
@@ -0,0 +1,71 @@ +package store.domain; + +import java.util.ArrayList; +import java.util.List; +import store.constant.CommonMessage; +import store.constant.CommonValue; + +public class Receipt { + private final double THIRTY_PERCENT = 0.3; + private final List<ReceiptItem> receiptItems = new ArrayList<>(); + + public void addItem(ReceiptItem receiptItem) { + receiptItems.add(receiptItem); + } + + public List<ReceiptItem> getReceiptItems() { + return receiptItems; + } + + public int totalPurchaseAmount() { + int sum = CommonValue.ZERO.getValue(); + for (ReceiptItem receiptItem : receiptItems) { + sum += receiptItem.getTotalBuyQuantity() * receiptItem.getPrice(); + } + return sum; + } + + public int totalPromotionDiscount() { + int sum = CommonValue.ZERO.getValue(); + for (ReceiptItem receiptItem : receiptItems) { + if (receiptItem.getGetQuantity() != CommonValue.ZERO.getValue()) { + sum += receiptItem.getGetQuantity() * receiptItem.getPrice(); + } + } + return sum; + } + + public int getTotalPurchaseCount() { + int sum = CommonValue.ZERO.getValue(); + for (ReceiptItem receiptItem : receiptItems) { + sum += receiptItem.getTotalBuyQuantity(); + } + return sum; + } + + public int validateMembership(String userAnswer) { + if (userAnswer.equals(CommonMessage.YES.getCommonMessage())) { + return getMembershipDiscount(); + } + return CommonValue.ZERO.getValue(); + } + + private int noTotalPromotionAmount() { + int sum = CommonValue.ZERO.getValue(); + for (ReceiptItem receiptItem : receiptItems) { + if (receiptItem.getGetQuantity() == CommonValue.ZERO.getValue()) { + sum += receiptItem.getBuyQuantity() * receiptItem.getPrice(); + } + } + return sum; + } + + private int getMembershipDiscount() { + int membershipDiscount = (int) (noTotalPromotionAmount() * THIRTY_PERCENT); + if (membershipDiscount > CommonValue.EIGHT_THOUSAND.getValue()) { + membershipDiscount = CommonValue.EIGHT_THOUSAND.getValue(); + } + return membershipDiscount; + } + +}
Java
int๋ฅผ double๊ณผ ๊ณฑํ•œ ๋’ค int๋กœ ํ˜•๋ณ€ํ™˜์„ ํ•˜๊ณ  ์žˆ๋Š”๋ฐ์š”! double๋กœ ๊ณ„์‚ฐ๋˜๋Š” ๊ณผ์ •์—์„œ ๋ถ€๋™์†Œ์ˆ˜์  ์˜ค๋ฅ˜๋ฅผ ํ”ผํ•  ์ˆ˜ ์—†์„ ๊ฒƒ์œผ๋กœ ๋ณด์ž…๋‹ˆ๋‹ค. ์ด๋•Œ๋Š” `* 30 / 100` ์œผ๋กœ ๊ณ„์‚ฐํ•ด์„œ ์•„์˜ˆ ์†Œ์ˆ˜์ ์ด ์•ˆ์ƒ๊ธฐ๋„๋ก ๊ณ„์‚ฐํ•˜์‹œ๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,143 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.List; +import java.util.function.Supplier; +import store.constant.CommonMessage; +import store.constant.CommonValue; +import store.constant.SignMessage; +import store.domain.GeneralProduct; +import store.domain.PromotionProduct; +import store.domain.Receipt; +import store.domain.Storage; +import store.exception.ConvenienceStoreException; +import store.service.ReceiptService; +import store.service.StorageService; +import store.utils.Calculator; +import store.utils.Compare; +import store.utils.Parser; +import store.view.input.InputView; +import store.view.output.OutputView; + +public class ConvenienceStoreController { + private final InputView inputView; + private final OutputView outputView; + private final Storage storage; + + public ConvenienceStoreController(InputView inputView, OutputView outputView, StorageService storageService) { + this.inputView = inputView; + this.outputView = outputView; + this.storage = storageService.initializeStorage(); + } + + public void operate() { + String retryFlag; + do { + outputView.writeStorageStatus(storage); + Receipt receipt = new Receipt(); + processPurchase(userPurchaseProduct(), receipt); + outputView.writeReceipt(receipt, userMembership()); + retryFlag = userRetry(); + } while (retryFlag.equalsIgnoreCase(CommonMessage.YES.getCommonMessage())); + inputView.closeConsole(); + } + + private void processPurchase(List<String> purchaseProduct, Receipt receipt) { + for (String detail : purchaseProduct) { + List<String> item = List.of(detail.split(SignMessage.HYPHEN.getSign())); + PromotionProduct product = storage.findPromotionProduct(item.get(CommonValue.ZERO.getValue())); + if (product != null && product.getPromotion().isActive(DateTimes.now())) { + processPromotionProduct(product, Parser.parse(item.get(CommonValue.ONE.getValue())), receipt); + continue; + } + processGeneralPurchase(item, receipt); + } + } + + private void processGeneralPurchase(List<String> item, Receipt receipt) { + ReceiptService.purchaseGeneralProduct(storage, item.get(CommonValue.ZERO.getValue()), + Integer.parseInt(item.get(CommonValue.ONE.getValue())), receipt); + } + + private void processPromotionProduct(PromotionProduct promotionProduct, int itemQuantity, Receipt receipt) { + int stock = Calculator.calculateRemainStock(promotionProduct, itemQuantity); + int purchase = Calculator.calculateUserRemain(promotionProduct, itemQuantity); + boolean freeTag = userOneMoreFree(purchase, stock, promotionProduct, itemQuantity, receipt); + boolean supplementTag = supplementStock(itemQuantity, stock, promotionProduct, receipt); + useStock(freeTag, supplementTag, promotionProduct, itemQuantity, receipt); + } + + private boolean userOneMoreFree(int leftBuy, int leftStock, PromotionProduct product, int count, Receipt receipt) { + if (Compare.checkFreeOneMore(leftBuy, leftStock, product)) { + storage.subtractPromotionProduct(product, count); + if (checkUserAnswer(product).equals(CommonMessage.YES.getCommonMessage())) { + storage.subtractPromotionProduct(product, product.getPromotionGetGet()); + return ReceiptService.oneMoreReceipt(receipt, count, leftBuy, product); + } + return ReceiptService.noOneMoreReceipt(receipt, count, leftBuy, product); + } + return false; + } + + private boolean supplementStock(int quantity, int stock, PromotionProduct product, Receipt receipt) { + if (Compare.checkSupplementStock(stock)) { + int noPromotion = Calculator.calculateNoPromotion(product); + int beforePromotionQuantity = product.getQuantity(); + storage.subtractPromotionProduct(product, noPromotion); + String userAnswer = checkUserNoPromotion(product, Calculator.minus(quantity, noPromotion)); + return suppleGeneralProduct(product, userAnswer, Calculator.minus(quantity, noPromotion), receipt, + beforePromotionQuantity); + } + return false; + } + + private boolean suppleGeneralProduct(PromotionProduct product, String answer, int quantity, Receipt receipt, + int prevQuantity) { + GeneralProduct generalProduct = storage.findGeneralProduct(product.getName()); + int currentQuantity = product.getQuantity(); + if (answer.equals(CommonMessage.YES.getCommonMessage())) { + storage.subtractGeneralProduct(generalProduct, Calculator.minus(quantity, currentQuantity)); + storage.subtractPromotionProduct(product, currentQuantity); + return ReceiptService.noDiscountPurchase(receipt, quantity, prevQuantity, currentQuantity, product); + } + return ReceiptService.noOneMoreReceipt(receipt, prevQuantity, currentQuantity, product); + } + + private void useStock(boolean freeTag, boolean suppleTag, PromotionProduct product, int quantity, Receipt receipt) { + if (!freeTag && !suppleTag) { + storage.subtractPromotionProduct(product, quantity); + ReceiptService.useStock(product, quantity, receipt); + } + } + + private String userRetry() { + return handleUserInput(inputView::readRetry); + } + + private String userMembership() { + return handleUserInput(inputView::readMembership); + } + + private List<String> userPurchaseProduct() { + return handleUserInput(() -> storage.validateStorageStatus(inputView.readItems())); + } + + private String checkUserAnswer(PromotionProduct promotionProduct) { + return handleUserInput(() -> inputView.readOneMoreFree(promotionProduct.getName())); + } + + private String checkUserNoPromotion(PromotionProduct promotionProduct, int quantity) { + return handleUserInput(() -> inputView.readNoDiscountAnswer(promotionProduct.getName(), quantity)); + } + + private <T> T handleUserInput(Supplier<T> inputSupplier) { + while (true) { + try { + return inputSupplier.get(); + } catch (ConvenienceStoreException convenienceStoreException) { + outputView.displayErrorMessage(convenienceStoreException); + } + } + } + +}
Java
์ €๋Š” MVC ํŒจํ„ด์— Service ๊ณ„์ธต์„ ์ถ”๊ฐ€ํ•ด์„œ ์ฑ…์ž„ ๋ถ„๋ฆฌ์— ์• ๋จน์—ˆ์—ˆ๋Š”๋ฐ, Service๊ฐ€ ์—†์œผ๋‹ˆ ์ข€ ๋” ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ ๋ฐ์ดํ„ฐ ์ „๋‹ฌ์ด ์ด๋ฃจ์–ด์ง€๋„ค์š”..!!
@@ -0,0 +1,141 @@ +package store.view.output; + +import java.util.List; +import store.domain.GeneralProduct; +import store.domain.PromotionProduct; +import store.domain.Receipt; +import store.domain.ReceiptItem; +import store.domain.Storage; +import store.exception.ConvenienceStoreException; + +public class OutputView { + + public void writeStorageStatus(Storage storage) { + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + System.out.println(OutputMessage.WELCOME_MESSAGE.getOutputMessage()); + System.out.println(OutputMessage.SHOW_CURRENT_ITEMS.getOutputMessage()); + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + writeInitPromotionProducts(storage); + writeInitOnlyGeneralProducts(storage); + } + + public void writeReceipt(Receipt receipt, String userAnswer) { + writeReceiptMenuHeader(); + writeReceiptMenuName(receipt); + writePresentation(receipt); + System.out.println(OutputMessage.PERFORATION_LINE.getOutputMessage()); + writeUserTotalReceipt(receipt, userAnswer); + } + + private void writeUserTotalReceipt(Receipt receipt, String userAnswer) { + writeShowTotalPurchaseAmount(receipt); + writeShowTotalPromotionDiscountAmount(receipt); + writeShowTotalMembershipDiscountAmount(receipt, userAnswer); + writeShowTotalPaymentAmount(receipt, userAnswer); + } + + private void writeShowTotalPaymentAmount(Receipt receipt, String userAnswer) { + String nameAndPrice = String.format(OutputMessage.SHOW_PAYMENT_FORMAT.getOutputMessage(), "๋‚ด์‹ค๋ˆ", + String.format("%,d", receipt.totalPurchaseAmount() - receipt.totalPromotionDiscount() - + receipt.validateMembership(userAnswer))); + System.out.println(nameAndPrice); + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + } + + + private void writeShowTotalMembershipDiscountAmount(Receipt receipt, String userAnswer) { + String name = String.format("%-14s", "๋ฉค๋ฒ„์‹ญํ• ์ธ").replace(" ", "\u3000"); + String price = String.format("-%,d", receipt.validateMembership(userAnswer)); + System.out.printf(OutputMessage.SHOW_DISCOUNT_FORMAT.getOutputMessage(), name, price); + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + } + + private void writeShowTotalPromotionDiscountAmount(Receipt receipt) { + String name = String.format("%-14s", "ํ–‰์‚ฌํ• ์ธ").replace(" ", "\u3000"); + String price = String.format("-%,d", receipt.totalPromotionDiscount()); + System.out.printf(OutputMessage.SHOW_DISCOUNT_FORMAT.getOutputMessage(), name, price); + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + } + + private void writeShowTotalPurchaseAmount(Receipt receipt) { + String name = String.format("%-14s", "์ด๊ตฌ๋งค์•ก").replace(" ", "\u3000"); + String quantity = String.format("%-10d", receipt.getTotalPurchaseCount()); + String price = String.format("%,-10d", receipt.totalPurchaseAmount()); + System.out.printf(OutputMessage.SHOW_RECEIPT_INIT_FORMAT.getOutputMessage(), name, quantity, price); + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + } + + private void writePresentation(Receipt receipt) { + System.out.println(OutputMessage.SHOW_RECEIPT_PRESENTATION_HEADER.getOutputMessage()); + for (ReceiptItem receiptItem : receipt.getReceiptItems()) { + if (receiptItem.getGetQuantity() != 0) { + String name = String.format("%-14s", receiptItem.getItemName()).replace(" ", "\u3000"); + String quantity = String.format("%,-10d", receiptItem.getGetQuantity()); + System.out.printf(OutputMessage.SHOW_PRESENTATION_FORMAT.getOutputMessage(), name, quantity); + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + } + } + } + + private void writeReceiptMenuName(Receipt receipt) { + System.out.println(OutputMessage.SHOW_RECEIPT_MENU_NAME.getOutputMessage()); + for (ReceiptItem receiptItem : receipt.getReceiptItems()) { + String name = String.format("%-14s", receiptItem.getItemName()).replace(" ", "\u3000"); + String quantity = String.format("%-10d", receiptItem.getTotalBuyQuantity()); + String price = String.format("%,-10d", receiptItem.getPrice() * receiptItem.getTotalBuyQuantity()); + System.out.printf(OutputMessage.SHOW_RECEIPT_INIT_FORMAT.getOutputMessage(), name, quantity, price); + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + } + } + + private void writeReceiptMenuHeader() { + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + System.out.println(OutputMessage.SHOW_RECEIPT_HEADER.getOutputMessage()); + } + + + private void writeInitPromotionProducts(Storage storage) { + for (PromotionProduct promotionProduct : storage.getPromotionProducts()) { + System.out.println(promotionProduct); + findEqualGeneralProductName(storage.getGeneralProducts(), promotionProduct.getName()); + } + } + + private void findEqualGeneralProductName(List<GeneralProduct> generalProducts, String name) { + for (GeneralProduct generalProduct : generalProducts) { + if (generalProduct.getName().equals(name)) { + System.out.println(generalProduct); + break; + } + } + } + + private void writeInitOnlyGeneralProducts(Storage storage) { + for (GeneralProduct generalProduct : storage.getGeneralProducts()) { + String generalProductName = generalProduct.getName(); + boolean flag = findEqualPromotionProductName(storage.getPromotionProducts(), generalProductName); + writeOnlyGeneralProduct(flag, generalProduct); + } + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + } + + private boolean findEqualPromotionProductName(List<PromotionProduct> promotionProducts, String name) { + for (PromotionProduct promotionProduct : promotionProducts) { + if (promotionProduct.getName().equals(name)) { + return true; + } + } + return false; + } + + private void writeOnlyGeneralProduct(boolean flag, GeneralProduct generalProduct) { + if (!flag) { + System.out.println(generalProduct.toString()); + } + } + + public void displayErrorMessage(ConvenienceStoreException convenienceStoreException) { + System.out.println(convenienceStoreException.getMessage()); + } + +}
Java
ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์ด ์†Œ์ง„๋˜๊ณ  ๋‚˜์„œ ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ๋„ ์žฌ๊ณ  ์—†์Œ์œผ๋กœ ์ถœ๋ ฅ๋˜๋Š”๋ฐ, ์‚ฌ์šฉ์ž๋Š” ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์„ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์œผ๋ฏ€๋กœ ์•„์˜ˆ ๋…ธ์ถœ์‹œํ‚ค์ง€ ์•Š๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! UX์ชฝ์œผ๋กœ๋„ ํ•œ๋ฒˆ ๊ณ ๋ฏผํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค๐Ÿ™‚
@@ -0,0 +1,38 @@ +package store.domain; + +public class GeneralProduct { + private final String name; + private final String price; + private int quantity; + + public GeneralProduct(final String name, final String price, final int quantity) { + this.name = name; + this.price = price; + this.quantity = quantity; + } + + public String getName() { + return name; + } + + public int getQuantity() { + return quantity; + } + + public String getPrice() { + return price; + } + + public void subtraction(int value) { + this.quantity -= Math.abs(value); + } + + @Override + public String toString() { + if (quantity == 0) { + return String.format("- %s %,d์› ์žฌ๊ณ  ์—†์Œ", name, Integer.parseInt(price)); + } + return String.format("- %s %,d์› %s๊ฐœ", name, Integer.parseInt(price), quantity); + } + +}
Java
๊ฐœ์ธ์ ์ธ ๊ถ๊ธˆ์ฆ์œผ๋กœ ์—ฌ์ญค๋ด…๋‹ˆ๋‹ค `price`๋ฅผ `String` ์œผ๋กœ ๊ด€๋ฆฌํ•˜์‹  ํŠน๋ณ„ํ•œ ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š”?
@@ -0,0 +1,143 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.List; +import java.util.function.Supplier; +import store.constant.CommonMessage; +import store.constant.CommonValue; +import store.constant.SignMessage; +import store.domain.GeneralProduct; +import store.domain.PromotionProduct; +import store.domain.Receipt; +import store.domain.Storage; +import store.exception.ConvenienceStoreException; +import store.service.ReceiptService; +import store.service.StorageService; +import store.utils.Calculator; +import store.utils.Compare; +import store.utils.Parser; +import store.view.input.InputView; +import store.view.output.OutputView; + +public class ConvenienceStoreController { + private final InputView inputView; + private final OutputView outputView; + private final Storage storage; + + public ConvenienceStoreController(InputView inputView, OutputView outputView, StorageService storageService) { + this.inputView = inputView; + this.outputView = outputView; + this.storage = storageService.initializeStorage(); + } + + public void operate() { + String retryFlag; + do { + outputView.writeStorageStatus(storage); + Receipt receipt = new Receipt(); + processPurchase(userPurchaseProduct(), receipt); + outputView.writeReceipt(receipt, userMembership()); + retryFlag = userRetry(); + } while (retryFlag.equalsIgnoreCase(CommonMessage.YES.getCommonMessage())); + inputView.closeConsole(); + } + + private void processPurchase(List<String> purchaseProduct, Receipt receipt) { + for (String detail : purchaseProduct) { + List<String> item = List.of(detail.split(SignMessage.HYPHEN.getSign())); + PromotionProduct product = storage.findPromotionProduct(item.get(CommonValue.ZERO.getValue())); + if (product != null && product.getPromotion().isActive(DateTimes.now())) { + processPromotionProduct(product, Parser.parse(item.get(CommonValue.ONE.getValue())), receipt); + continue; + } + processGeneralPurchase(item, receipt); + } + } + + private void processGeneralPurchase(List<String> item, Receipt receipt) { + ReceiptService.purchaseGeneralProduct(storage, item.get(CommonValue.ZERO.getValue()), + Integer.parseInt(item.get(CommonValue.ONE.getValue())), receipt); + } + + private void processPromotionProduct(PromotionProduct promotionProduct, int itemQuantity, Receipt receipt) { + int stock = Calculator.calculateRemainStock(promotionProduct, itemQuantity); + int purchase = Calculator.calculateUserRemain(promotionProduct, itemQuantity); + boolean freeTag = userOneMoreFree(purchase, stock, promotionProduct, itemQuantity, receipt); + boolean supplementTag = supplementStock(itemQuantity, stock, promotionProduct, receipt); + useStock(freeTag, supplementTag, promotionProduct, itemQuantity, receipt); + } + + private boolean userOneMoreFree(int leftBuy, int leftStock, PromotionProduct product, int count, Receipt receipt) { + if (Compare.checkFreeOneMore(leftBuy, leftStock, product)) { + storage.subtractPromotionProduct(product, count); + if (checkUserAnswer(product).equals(CommonMessage.YES.getCommonMessage())) { + storage.subtractPromotionProduct(product, product.getPromotionGetGet()); + return ReceiptService.oneMoreReceipt(receipt, count, leftBuy, product); + } + return ReceiptService.noOneMoreReceipt(receipt, count, leftBuy, product); + } + return false; + } + + private boolean supplementStock(int quantity, int stock, PromotionProduct product, Receipt receipt) { + if (Compare.checkSupplementStock(stock)) { + int noPromotion = Calculator.calculateNoPromotion(product); + int beforePromotionQuantity = product.getQuantity(); + storage.subtractPromotionProduct(product, noPromotion); + String userAnswer = checkUserNoPromotion(product, Calculator.minus(quantity, noPromotion)); + return suppleGeneralProduct(product, userAnswer, Calculator.minus(quantity, noPromotion), receipt, + beforePromotionQuantity); + } + return false; + } + + private boolean suppleGeneralProduct(PromotionProduct product, String answer, int quantity, Receipt receipt, + int prevQuantity) { + GeneralProduct generalProduct = storage.findGeneralProduct(product.getName()); + int currentQuantity = product.getQuantity(); + if (answer.equals(CommonMessage.YES.getCommonMessage())) { + storage.subtractGeneralProduct(generalProduct, Calculator.minus(quantity, currentQuantity)); + storage.subtractPromotionProduct(product, currentQuantity); + return ReceiptService.noDiscountPurchase(receipt, quantity, prevQuantity, currentQuantity, product); + } + return ReceiptService.noOneMoreReceipt(receipt, prevQuantity, currentQuantity, product); + } + + private void useStock(boolean freeTag, boolean suppleTag, PromotionProduct product, int quantity, Receipt receipt) { + if (!freeTag && !suppleTag) { + storage.subtractPromotionProduct(product, quantity); + ReceiptService.useStock(product, quantity, receipt); + } + } + + private String userRetry() { + return handleUserInput(inputView::readRetry); + } + + private String userMembership() { + return handleUserInput(inputView::readMembership); + } + + private List<String> userPurchaseProduct() { + return handleUserInput(() -> storage.validateStorageStatus(inputView.readItems())); + } + + private String checkUserAnswer(PromotionProduct promotionProduct) { + return handleUserInput(() -> inputView.readOneMoreFree(promotionProduct.getName())); + } + + private String checkUserNoPromotion(PromotionProduct promotionProduct, int quantity) { + return handleUserInput(() -> inputView.readNoDiscountAnswer(promotionProduct.getName(), quantity)); + } + + private <T> T handleUserInput(Supplier<T> inputSupplier) { + while (true) { + try { + return inputSupplier.get(); + } catch (ConvenienceStoreException convenienceStoreException) { + outputView.displayErrorMessage(convenienceStoreException); + } + } + } + +}
Java
`HYPHEN`์ด๋‚˜ `ZERO` ๊ฐ™์ด ์ด๋ฆ„ ์ž์ฒด๊ฐ€ ์˜๋ฏธ๋ฅผ ์ง๊ด€์ ์œผ๋กœ ๋‹ด๊ณ  ์žˆ๋Š” ๊ฒฝ์šฐ๋Š” enum๋ณด๋‹ค ์ผ๋ฐ˜ ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•ด์„œ `getValue()`๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ํŽธ์ด ์กฐ๊ธˆ ๋” ๊น”๋”ํ•˜์ง€ ์•Š์„๊นŒ์š”..?
@@ -0,0 +1,40 @@ +package store.domain; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +public class Promotion { + private final String name; + private final int buy; + private final int get; + private final LocalDate startDate; + private final LocalDate endDate; + + public Promotion(final String name, final int buy, final int get, final String startDate, final String endDate) { + this.name = name; + this.buy = buy; + this.get = get; + this.startDate = LocalDate.parse(startDate); + this.endDate = LocalDate.parse(endDate); + } + + public String getName() { + return name; + } + + public int getBuy() { + return buy; + } + + public int getGet() { + return get; + } + + public boolean isActive(LocalDateTime dateTime) { + LocalDate date = dateTime.toLocalDate(); + return (date.isEqual(startDate) || date.isAfter(startDate)) && + (date.isEqual(endDate) || date.isBefore(endDate)); + } + +} +
Java
์กฐ๊ฑด๋ถ€๊ฐ€ ๊ธธ๋‹ค๋ณด๋‹ˆ๊นŒ ๋‚ ์งœ๊ฐ€ ๊ธฐ๊ฐ„์— ํฌํ•จ๋˜๋Š”์ง€ ํ™•์ธํ•˜๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ๊ฒƒ๋„ ๋‚˜์˜์ง€ ์•Š๋‹ค๊ณ  ์ƒ๊ฐ์ด ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค ``` boolean isBetween(LocalDate date) { return !date.isBefore(startDate) && !date.isAfter(endDate); } ```
@@ -0,0 +1,83 @@ +package store.domain; + +import java.util.Collections; +import java.util.List; +import store.constant.CommonValue; +import store.constant.SignMessage; +import store.exception.ConvenienceStoreException; +import store.exception.ErrorMessage; + +public class Storage { + private final List<GeneralProduct> generalProducts; + private final List<PromotionProduct> promotionProducts; + + public Storage(final List<GeneralProduct> generalProducts, final List<PromotionProduct> promotionProducts) { + this.generalProducts = generalProducts; + this.promotionProducts = promotionProducts; + } + + public List<String> validateStorageStatus(List<String> purchaseProduct) { + for (String purchaseItem : purchaseProduct) { + List<String> item = List.of(purchaseItem.split(SignMessage.HYPHEN.getSign())); + validateItemName(item.get(CommonValue.ZERO.getValue())); + validateQuantity(item.get(CommonValue.ZERO.getValue()), item.get(CommonValue.ONE.getValue())); + } + return purchaseProduct; + } + + public List<GeneralProduct> getGeneralProducts() { + return Collections.unmodifiableList(generalProducts); + } + + public List<PromotionProduct> getPromotionProducts() { + return Collections.unmodifiableList(promotionProducts); + } + + public GeneralProduct findGeneralProduct(String productName) { + return generalProducts.stream() + .filter(product -> product.getName().equals(productName)) + .findFirst() + .orElse(null); + } + + public PromotionProduct findPromotionProduct(String productName) { + return promotionProducts.stream() + .filter(product -> product.getName().equals(productName)) + .findFirst() + .orElse(null); + } + + public void subtractPromotionProduct(PromotionProduct promotionProduct, int itemQuantity) { + promotionProduct.subtraction(itemQuantity); + } + + public void subtractGeneralProduct(GeneralProduct generalProduct, int itemQuantity) { + generalProduct.subtraction(itemQuantity); + } + + private void validateQuantity(String name, String quantity) { + if (getProductQuantity(name) < Integer.parseInt(quantity)) { + throw ConvenienceStoreException.from(ErrorMessage.STORAGE_OVER); + } + } + + private int getProductQuantity(String name) { + PromotionProduct promotionProduct = findPromotionProduct(name); + int count = CommonValue.ZERO.getValue(); + if (promotionProduct != null) { + count += promotionProduct.getQuantity(); + } + return count + findGeneralProduct(name).getQuantity(); + } + + private void validateItemName(String name) { + if (!isProductInStorage(name)) { + throw ConvenienceStoreException.from(ErrorMessage.NON_EXISTENT_PRODUCT); + } + } + + private boolean isProductInStorage(String productName) { + return generalProducts.stream().anyMatch(product -> product.getName().equals(productName)); + } + +}
Java
`Unmodifiable Collection`์„ ์‚ฌ์šฉํ•˜์…”์„œ ์™ธ๋ถ€์˜ ๋ณ€ํ˜•์„ ๋ง‰์œผ์‹  ์  ๋„ˆ๋ฌด ์ข‹์Šต๋‹ˆ๋‹ค..!
@@ -0,0 +1,114 @@ +package store.service; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import store.constant.FileMessage; +import store.constant.SignMessage; +import store.domain.GeneralProduct; +import store.domain.Promotion; +import store.domain.PromotionProduct; +import store.domain.Storage; +import store.utils.FileLoader; + +public class StorageService { + private static final String FILE_NOT_FOUND_ERROR = "[ERROR] ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."; + private final List<String> productFile; + private final List<String> promotionFile; + + public StorageService(final String productFileName, final String promotionFileName) { + this.productFile = loadFile(productFileName); + this.promotionFile = loadFile(promotionFileName); + } + + public Storage initializeStorage() { + List<Promotion> promotions = generatePromotionData(promotionFile); + List<GeneralProduct> onlyGeneralProducts = findGeneralProduct(productFile); + List<PromotionProduct> onlyPromotionProducts = findPromotionProduct(productFile, promotions); + List<GeneralProduct> insertedGeneralProducts = insertOutOfStock(onlyPromotionProducts, onlyGeneralProducts); + return new Storage(insertedGeneralProducts, onlyPromotionProducts); + } + + private List<String> loadFile(String fileName) { + try { + return FileLoader.fileReadLine(fileName); + } catch (IOException e) { + throw new IllegalArgumentException(FILE_NOT_FOUND_ERROR); + } + } + + private List<Promotion> generatePromotionData(List<String> promotionFile) { + List<Promotion> promotions = new ArrayList<>(); + for (String line : promotionFile) { + List<String> items = List.of(line.split(SignMessage.COMMA.getSign())); + promotions.add(new Promotion(items.get(0), Integer.parseInt(items.get(1)), Integer.parseInt(items.get(2)), + items.get(3), items.get(4))); + } + return promotions; + } + + private List<GeneralProduct> insertOutOfStock(List<PromotionProduct> prItem, List<GeneralProduct> generalProducts) { + int idx = 0; + for (PromotionProduct product : prItem) { + if (findEqualGeneralProductName(generalProducts, product.getName())) { + idx += 1; + continue; + } + generalProducts.add(idx, new GeneralProduct(product.getName(), product.getPrice(), 0)); + } + return generalProducts; + } + + + private boolean findEqualGeneralProductName(List<GeneralProduct> generalProducts, String name) { + for (GeneralProduct generalProduct : generalProducts) { + if (generalProduct.getName().equals(name)) { + return true; + } + } + return false; + } + + private List<GeneralProduct> findGeneralProduct(List<String> getFile) { + List<GeneralProduct> onlyGeneralProducts = new ArrayList<>(); + for (String itemDetails : getFile) { + if (itemDetails.contains(FileMessage.NULL.getFileMessage())) { + List<String> item = List.of(itemDetails.split(SignMessage.COMMA.getSign())); + onlyGeneralProducts.add(new GeneralProduct(item.get(0), item.get(1), Integer.parseInt(item.get(2)))); + } + } + return onlyGeneralProducts; + } + + private List<PromotionProduct> findPromotionProduct(List<String> getFile, List<Promotion> promotions) { + List<PromotionProduct> onlyPromotionProducts = new ArrayList<>(); + for (String itemDetails : getFile) { + if (isPromotionProduct(itemDetails)) { + addPromotionProduct(onlyPromotionProducts, itemDetails, promotions); + } + } + return onlyPromotionProducts; + } + + private boolean isPromotionProduct(String itemDetails) { + return itemDetails.contains(FileMessage.SOFT_DRINK.getFileMessage()) + || itemDetails.contains(FileMessage.MD_RECOMMEND_PRODUCT.getFileMessage()) + || itemDetails.contains(FileMessage.FLASH_DISCOUNT.getFileMessage()); + } + + private void addPromotionProduct(List<PromotionProduct> products, String itemDetails, List<Promotion> promotions) { + List<String> item = List.of(itemDetails.split(SignMessage.COMMA.getSign())); + String productName = item.get(0); + String productCategory = item.get(1); + int price = Integer.parseInt(item.get(2)); + Promotion promotion = matchingPromotion(item.get(3), promotions); + + products.add(new PromotionProduct(productName, productCategory, price, promotion)); + } + + private Promotion matchingPromotion(String promotionName, List<Promotion> promotions) { + return promotions.stream().filter(promotion -> promotion.getName().equals(promotionName)).findFirst() + .orElse(null); + } + +}
Java
์ด ์ƒ์ˆ˜๋Š” `ErrorMessage` ํด๋ž˜์Šค์— ํฌํ•จ๋˜์ง€ ์•Š์€ ์ด์œ ๊ฐ€ ํ˜น์‹œ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,16 @@ +package store.constant; + +public enum CommonMessage { + YES("Y"), + NO("N"); + private final String commonMessage; + + CommonMessage(final String commonMessage) { + this.commonMessage = commonMessage; + } + + public String getCommonMessage() { + return commonMessage; + } + +}
Java
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! ํŠน์ • ๋ฒ”์œ„์˜ ๊ฐ’๋งŒ ์‚ฌ์šฉ์„ ํ•˜๋‹ˆ๊นŒ enum์œผ๋กœ ์‚ฌ์šฉํ•ด๋ณผ๊นŒ? ์ƒ๊ฐํ•ด๋ดค์–ด์š”!
@@ -0,0 +1,19 @@ +package store.constant; + +public enum CommonValue { + ZERO(0), + ONE(1), + TWO(2), + EIGHT_THOUSAND(8000); + + private final int value; + + CommonValue(final int value) { + this.value = value; + } + + public int getValue() { + return value; + } + +}
Java
์‚ฌ์‹ค ์ด ๋ถ€๋ถ„์— ๋Œ€ํ•ด ๊ณ ๋ฏผ์„ ๋งŽ์ด ํ–ˆ์Šต๋‹ˆ๋‹ค. ์ƒ์ˆ˜๋ฅผ enum์œผ๋กœ ๊ด€๋ฆฌํ• ์ง€ ์—ฌ๋ถ€๋ฅผ ๊ณ ๋ฏผํ–ˆ๋˜ ์ด์œ ๋Š”, ํ•ด๋‹น ์ƒ์ˆ˜๋“ค์ด ํŠน์ •ํ•œ ๊ฐ’์˜ ๋ฒ”์œ„์— ์†ํ•˜์ง€ ์•Š๊ณ , `==`์„ ํ†ตํ•œ ๋น„๊ต๋ฅผ ์ˆ˜ํ–‰ํ•˜๋Š” ๋ถ€๋ถ„๋„ ์—†์—ˆ๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ๊ตณ์ด enum์„ ์‚ฌ์šฉํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค๋งŒ, ๊ฐ€๋…์„ฑ ์ธก๋ฉด์—์„œ ์ฝ”๋“œ๋ฅผ ๋ช…ํ™•ํ•˜๊ฒŒ ๋งŒ๋“ค๊ณ ์ž enum์„ ์„ ํƒํ–ˆ๋Š”๋ฐ, ์‹ค์ œ ์‚ฌ์šฉ ์‹œ `CommonValue.ZERO.getValue()`์ฒ˜๋Ÿผ ์ ‘๊ทผํ•˜๋Š” ๊ฒƒ์ด ์ฝ”๋“œ๊ฐ€ ๊ธธ์–ด์ง€๊ณ  ๋‹ค์†Œ ๋ถˆํŽธํ•˜๊ฒŒ ๋А๊ปด์งˆ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ์ ์—์„œ ๋ณด๋ฉด, ๋ง์”€ํ•˜์‹  ๋Œ€๋กœ static ์ƒ์ˆ˜๋กœ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ๋” ๊ฐ„๊ฒฐํ•˜๊ณ  ์ง๊ด€์ ์ผ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,22 @@ +package store.constant; + +public enum FileMessage { + PRODUCTS_FILE_NAME("products.md"), + PROMOTION_FILE_NAME("promotions.md"), + NULL("null"), + SOFT_DRINK("ํƒ„์‚ฐ2+1"), + MD_RECOMMEND_PRODUCT("MD์ถ”์ฒœ์ƒํ’ˆ"), + FLASH_DISCOUNT("๋ฐ˜์งํ• ์ธ"), + FILE_START_WORD("name"); + + private final String fileMessage; + + FileMessage(final String fileMessage) { + this.fileMessage = fileMessage; + } + + public String getFileMessage() { + return fileMessage; + } + +}
Java
ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌ๋“œ๋ฆฝ๋‹ˆ๋‹ค! ๋ง์”€ํ•ด์ฃผ์‹  ๋Œ€๋กœ, Enum์€ ์ฃผ๋กœ ๊ณ ์ •๋œ ์ƒ์ˆ˜ ๊ฐ’์„ ์ •์˜ํ•  ๋•Œ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค. ๊ทธ๋Ÿฐ๋ฐ ์ƒˆ๋กœ์šด ํ”„๋กœ๋ชจ์…˜์ด ์ถ”๊ฐ€๋˜๊ฑฐ๋‚˜ ๋ณ€๊ฒฝ๋  ๋•Œ๋งˆ๋‹ค ์žฌ์ปดํŒŒ์ผํ•ด์•ผ ํ•˜๋Š” ๋ถˆํŽธํ•จ์ด ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ด ๋ถ€๋ถ„์€ ์ œ๊ฐ€ ๋ฏธ์ฒ˜ ๊ณ ๋ คํ•˜์ง€ ๋ชปํ–ˆ๋˜ ์ ์ธ๋ฐ, ์ง€์ ํ•ด์ฃผ์…”์„œ ๊ฐ์‚ฌ๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,143 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.List; +import java.util.function.Supplier; +import store.constant.CommonMessage; +import store.constant.CommonValue; +import store.constant.SignMessage; +import store.domain.GeneralProduct; +import store.domain.PromotionProduct; +import store.domain.Receipt; +import store.domain.Storage; +import store.exception.ConvenienceStoreException; +import store.service.ReceiptService; +import store.service.StorageService; +import store.utils.Calculator; +import store.utils.Compare; +import store.utils.Parser; +import store.view.input.InputView; +import store.view.output.OutputView; + +public class ConvenienceStoreController { + private final InputView inputView; + private final OutputView outputView; + private final Storage storage; + + public ConvenienceStoreController(InputView inputView, OutputView outputView, StorageService storageService) { + this.inputView = inputView; + this.outputView = outputView; + this.storage = storageService.initializeStorage(); + } + + public void operate() { + String retryFlag; + do { + outputView.writeStorageStatus(storage); + Receipt receipt = new Receipt(); + processPurchase(userPurchaseProduct(), receipt); + outputView.writeReceipt(receipt, userMembership()); + retryFlag = userRetry(); + } while (retryFlag.equalsIgnoreCase(CommonMessage.YES.getCommonMessage())); + inputView.closeConsole(); + } + + private void processPurchase(List<String> purchaseProduct, Receipt receipt) { + for (String detail : purchaseProduct) { + List<String> item = List.of(detail.split(SignMessage.HYPHEN.getSign())); + PromotionProduct product = storage.findPromotionProduct(item.get(CommonValue.ZERO.getValue())); + if (product != null && product.getPromotion().isActive(DateTimes.now())) { + processPromotionProduct(product, Parser.parse(item.get(CommonValue.ONE.getValue())), receipt); + continue; + } + processGeneralPurchase(item, receipt); + } + } + + private void processGeneralPurchase(List<String> item, Receipt receipt) { + ReceiptService.purchaseGeneralProduct(storage, item.get(CommonValue.ZERO.getValue()), + Integer.parseInt(item.get(CommonValue.ONE.getValue())), receipt); + } + + private void processPromotionProduct(PromotionProduct promotionProduct, int itemQuantity, Receipt receipt) { + int stock = Calculator.calculateRemainStock(promotionProduct, itemQuantity); + int purchase = Calculator.calculateUserRemain(promotionProduct, itemQuantity); + boolean freeTag = userOneMoreFree(purchase, stock, promotionProduct, itemQuantity, receipt); + boolean supplementTag = supplementStock(itemQuantity, stock, promotionProduct, receipt); + useStock(freeTag, supplementTag, promotionProduct, itemQuantity, receipt); + } + + private boolean userOneMoreFree(int leftBuy, int leftStock, PromotionProduct product, int count, Receipt receipt) { + if (Compare.checkFreeOneMore(leftBuy, leftStock, product)) { + storage.subtractPromotionProduct(product, count); + if (checkUserAnswer(product).equals(CommonMessage.YES.getCommonMessage())) { + storage.subtractPromotionProduct(product, product.getPromotionGetGet()); + return ReceiptService.oneMoreReceipt(receipt, count, leftBuy, product); + } + return ReceiptService.noOneMoreReceipt(receipt, count, leftBuy, product); + } + return false; + } + + private boolean supplementStock(int quantity, int stock, PromotionProduct product, Receipt receipt) { + if (Compare.checkSupplementStock(stock)) { + int noPromotion = Calculator.calculateNoPromotion(product); + int beforePromotionQuantity = product.getQuantity(); + storage.subtractPromotionProduct(product, noPromotion); + String userAnswer = checkUserNoPromotion(product, Calculator.minus(quantity, noPromotion)); + return suppleGeneralProduct(product, userAnswer, Calculator.minus(quantity, noPromotion), receipt, + beforePromotionQuantity); + } + return false; + } + + private boolean suppleGeneralProduct(PromotionProduct product, String answer, int quantity, Receipt receipt, + int prevQuantity) { + GeneralProduct generalProduct = storage.findGeneralProduct(product.getName()); + int currentQuantity = product.getQuantity(); + if (answer.equals(CommonMessage.YES.getCommonMessage())) { + storage.subtractGeneralProduct(generalProduct, Calculator.minus(quantity, currentQuantity)); + storage.subtractPromotionProduct(product, currentQuantity); + return ReceiptService.noDiscountPurchase(receipt, quantity, prevQuantity, currentQuantity, product); + } + return ReceiptService.noOneMoreReceipt(receipt, prevQuantity, currentQuantity, product); + } + + private void useStock(boolean freeTag, boolean suppleTag, PromotionProduct product, int quantity, Receipt receipt) { + if (!freeTag && !suppleTag) { + storage.subtractPromotionProduct(product, quantity); + ReceiptService.useStock(product, quantity, receipt); + } + } + + private String userRetry() { + return handleUserInput(inputView::readRetry); + } + + private String userMembership() { + return handleUserInput(inputView::readMembership); + } + + private List<String> userPurchaseProduct() { + return handleUserInput(() -> storage.validateStorageStatus(inputView.readItems())); + } + + private String checkUserAnswer(PromotionProduct promotionProduct) { + return handleUserInput(() -> inputView.readOneMoreFree(promotionProduct.getName())); + } + + private String checkUserNoPromotion(PromotionProduct promotionProduct, int quantity) { + return handleUserInput(() -> inputView.readNoDiscountAnswer(promotionProduct.getName(), quantity)); + } + + private <T> T handleUserInput(Supplier<T> inputSupplier) { + while (true) { + try { + return inputSupplier.get(); + } catch (ConvenienceStoreException convenienceStoreException) { + outputView.displayErrorMessage(convenienceStoreException); + } + } + } + +}
Java
์‚ฌ์‹ค Service ๊ณ„์ธต์„ ์ถ”๊ฐ€ํ•ด์„œ ์ฑ…์ž„์„ ๋ถ„๋ฆฌํ•˜๋ ค๊ณ  ํ–ˆ์Šต๋‹ˆ๋‹ค. ์ปค๋ฐ‹ ๊ธฐ๋ก์„ ๋ณด์‹œ๋ฉด ์•„์‹œ๊ฒ ์ง€๋งŒ, ๋งˆ์ง€๋ง‰ ๋‚ ์— ReceiptService๋ฅผ ์ถ”๊ฐ€ํ–ˆ์Šต๋‹ˆ๋‹ค! ์ƒํ’ˆ ๊ด€๋ จ ๋ถ€๋ถ„๋„ ๋ถ„๋ฆฌํ•˜๋ ค๊ณ  ํ–ˆ๋Š”๋ฐ, ์‹œ๊ฐ„์ด ๋ถ€์กฑํ•ด์„œ ๋” ๋ฆฌํŒฉํ† ๋งํ•˜์ง€ ๋ชปํ•œ ์ ์ด ์•„์‰ฝ์Šต๋‹ˆ๋‹ค ๐Ÿ˜… ๊ทธ๋Ÿผ์—๋„ ์ข‹๊ฒŒ ๋ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,143 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.List; +import java.util.function.Supplier; +import store.constant.CommonMessage; +import store.constant.CommonValue; +import store.constant.SignMessage; +import store.domain.GeneralProduct; +import store.domain.PromotionProduct; +import store.domain.Receipt; +import store.domain.Storage; +import store.exception.ConvenienceStoreException; +import store.service.ReceiptService; +import store.service.StorageService; +import store.utils.Calculator; +import store.utils.Compare; +import store.utils.Parser; +import store.view.input.InputView; +import store.view.output.OutputView; + +public class ConvenienceStoreController { + private final InputView inputView; + private final OutputView outputView; + private final Storage storage; + + public ConvenienceStoreController(InputView inputView, OutputView outputView, StorageService storageService) { + this.inputView = inputView; + this.outputView = outputView; + this.storage = storageService.initializeStorage(); + } + + public void operate() { + String retryFlag; + do { + outputView.writeStorageStatus(storage); + Receipt receipt = new Receipt(); + processPurchase(userPurchaseProduct(), receipt); + outputView.writeReceipt(receipt, userMembership()); + retryFlag = userRetry(); + } while (retryFlag.equalsIgnoreCase(CommonMessage.YES.getCommonMessage())); + inputView.closeConsole(); + } + + private void processPurchase(List<String> purchaseProduct, Receipt receipt) { + for (String detail : purchaseProduct) { + List<String> item = List.of(detail.split(SignMessage.HYPHEN.getSign())); + PromotionProduct product = storage.findPromotionProduct(item.get(CommonValue.ZERO.getValue())); + if (product != null && product.getPromotion().isActive(DateTimes.now())) { + processPromotionProduct(product, Parser.parse(item.get(CommonValue.ONE.getValue())), receipt); + continue; + } + processGeneralPurchase(item, receipt); + } + } + + private void processGeneralPurchase(List<String> item, Receipt receipt) { + ReceiptService.purchaseGeneralProduct(storage, item.get(CommonValue.ZERO.getValue()), + Integer.parseInt(item.get(CommonValue.ONE.getValue())), receipt); + } + + private void processPromotionProduct(PromotionProduct promotionProduct, int itemQuantity, Receipt receipt) { + int stock = Calculator.calculateRemainStock(promotionProduct, itemQuantity); + int purchase = Calculator.calculateUserRemain(promotionProduct, itemQuantity); + boolean freeTag = userOneMoreFree(purchase, stock, promotionProduct, itemQuantity, receipt); + boolean supplementTag = supplementStock(itemQuantity, stock, promotionProduct, receipt); + useStock(freeTag, supplementTag, promotionProduct, itemQuantity, receipt); + } + + private boolean userOneMoreFree(int leftBuy, int leftStock, PromotionProduct product, int count, Receipt receipt) { + if (Compare.checkFreeOneMore(leftBuy, leftStock, product)) { + storage.subtractPromotionProduct(product, count); + if (checkUserAnswer(product).equals(CommonMessage.YES.getCommonMessage())) { + storage.subtractPromotionProduct(product, product.getPromotionGetGet()); + return ReceiptService.oneMoreReceipt(receipt, count, leftBuy, product); + } + return ReceiptService.noOneMoreReceipt(receipt, count, leftBuy, product); + } + return false; + } + + private boolean supplementStock(int quantity, int stock, PromotionProduct product, Receipt receipt) { + if (Compare.checkSupplementStock(stock)) { + int noPromotion = Calculator.calculateNoPromotion(product); + int beforePromotionQuantity = product.getQuantity(); + storage.subtractPromotionProduct(product, noPromotion); + String userAnswer = checkUserNoPromotion(product, Calculator.minus(quantity, noPromotion)); + return suppleGeneralProduct(product, userAnswer, Calculator.minus(quantity, noPromotion), receipt, + beforePromotionQuantity); + } + return false; + } + + private boolean suppleGeneralProduct(PromotionProduct product, String answer, int quantity, Receipt receipt, + int prevQuantity) { + GeneralProduct generalProduct = storage.findGeneralProduct(product.getName()); + int currentQuantity = product.getQuantity(); + if (answer.equals(CommonMessage.YES.getCommonMessage())) { + storage.subtractGeneralProduct(generalProduct, Calculator.minus(quantity, currentQuantity)); + storage.subtractPromotionProduct(product, currentQuantity); + return ReceiptService.noDiscountPurchase(receipt, quantity, prevQuantity, currentQuantity, product); + } + return ReceiptService.noOneMoreReceipt(receipt, prevQuantity, currentQuantity, product); + } + + private void useStock(boolean freeTag, boolean suppleTag, PromotionProduct product, int quantity, Receipt receipt) { + if (!freeTag && !suppleTag) { + storage.subtractPromotionProduct(product, quantity); + ReceiptService.useStock(product, quantity, receipt); + } + } + + private String userRetry() { + return handleUserInput(inputView::readRetry); + } + + private String userMembership() { + return handleUserInput(inputView::readMembership); + } + + private List<String> userPurchaseProduct() { + return handleUserInput(() -> storage.validateStorageStatus(inputView.readItems())); + } + + private String checkUserAnswer(PromotionProduct promotionProduct) { + return handleUserInput(() -> inputView.readOneMoreFree(promotionProduct.getName())); + } + + private String checkUserNoPromotion(PromotionProduct promotionProduct, int quantity) { + return handleUserInput(() -> inputView.readNoDiscountAnswer(promotionProduct.getName(), quantity)); + } + + private <T> T handleUserInput(Supplier<T> inputSupplier) { + while (true) { + try { + return inputSupplier.get(); + } catch (ConvenienceStoreException convenienceStoreException) { + outputView.displayErrorMessage(convenienceStoreException); + } + } + } + +}
Java
๋ง์”€ํ•ด์ฃผ์‹  ๋‚ด์šฉ์„ ํ™•์ธํ•ด๋ณด์•˜์Šต๋‹ˆ๋‹ค! ์ œ๊ฐ€ ์•Œ๊ณ  ์žˆ๋Š” ์š”๊ตฌ์‚ฌํ•ญ์€, `[์ฝœ๋ผ-2]`, `[์—๋„ˆ์ง€๋ฐ”-1]`์„ ๊ตฌ๋งคํ•œ ๊ฒฝ์šฐ 1๊ฐœ ๋ฌด๋ฃŒ ์ฆ์ •์„ ๋ฐ›๊ณ , ๋ฉค๋ฒ„์‹ญ์„ ์ ์šฉํ•œ๋‹ค๋ฉด ์—๋„ˆ์ง€๋ฐ” 1๊ฐœ์— ๋Œ€ํ•ด์„œ๋งŒ ๋ฉค๋ฒ„์‹ญ ํ• ์ธ์ด ์ ์šฉ๋˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค. ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ, `[์ฝœ๋ผ-2]`๊ฐœ๋ฅผ ๊ตฌ๋งคํ•˜๊ณ  ๋ฌด๋ฃŒ ์ฆ์ •์„ ๋ฐ›์ง€ ์•Š๋Š”๋‹ค๋ฉด, ์ฝœ๋ผ 2๊ฐœ์— ๋Œ€ํ•ด์„œ ๋ฉค๋ฒ„์‹ญ ํ• ์ธ์ด ์ ์šฉ๋˜๋Š” ๊ฒƒ์œผ๋กœ ์ดํ•ดํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ œ ๋กœ์ง์€ ์œ„์™€ ๊ฐ™์€ ๋ฐฉ์‹์œผ๋กœ ๋™์ž‘ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ํ˜น์‹œ ๋‹ค๋ฅธ ์š”๊ตฌ์‚ฌํ•ญ์ด ์žˆ์—ˆ๋‹ค๋ฉด ์„ค๋ช…ํ•ด ์ฃผ์‹ค ์ˆ˜ ์žˆ์œผ์‹ ๊ฐ€์š”? ์˜ˆ๋ฅผ ๋“ค์–ด, `[์ฝœ๋ผ-2]`, `[์—๋„ˆ์ง€๋ฐ”-1]`๋ฅผ ๊ตฌ๋งคํ•œ ์ƒํ™ฉ์—์„œ ์ฝœ๋ผ 1๊ฐœ๋ฅผ ๋ฌด๋ฃŒ ์ฆ์ • ๋ฐ›๋Š” ๊ฒฝ์šฐ, ๊ทธ๋ฆฌ๊ณ  ๋ฉค๋ฒ„์‹ญ ํ• ์ธ์ด ์ ์šฉ๋˜๋Š” ๊ฒฝ์šฐ๋ฅผ ์‚ดํŽด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. `ReceiptItem`์˜ `getQuantity` ๋ฉ”์„œ๋“œ์—์„œ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฐ’์€ ์‚ฌ์šฉ์ž๊ฐ€ ๋ฌด๋ฃŒ๋กœ ์ฆ์ •๋ฐ›์€ ์ƒํ’ˆ์˜ ๊ฐœ์ˆ˜๋ฅผ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค. `OutputView`์˜ `writeReceipt` ๋ฉ”์„œ๋“œ์—์„œ๋Š” `writeUserTotalReceipt()` ๋ฉ”์„œ๋“œ๋ฅผ ๋งˆ์ง€๋ง‰ ๋ผ์ธ์—์„œ ํ˜ธ์ถœํ•˜๋ฉฐ, ์ด ๋ฉ”์„œ๋“œ์—์„œ `writeShowTotalMembershipDiscountAmount()`๋ฅผ ํ†ตํ•ด ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ๋ถ€๋ถ„์ด ์ถœ๋ ฅ๋ฉ๋‹ˆ๋‹ค. `Receipt` ํด๋ž˜์Šค์˜ `validateMembership` ๋ฉ”์„œ๋“œ๋ฅผ ๋ณด๋ฉด, ์‚ฌ์šฉ์ž์˜ ๋Œ€๋‹ต์ด `Y`์ผ ๊ฒฝ์šฐ `getMembershipDiscount()`๋ฅผ ํ˜ธ์ถœํ•˜๊ฒŒ ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. `getMembershipDiscount` ๋ฉ”์„œ๋“œ์—์„œ๋Š” `noTotalPromotionAmount()`๋ฅผ ํ˜ธ์ถœํ•˜๋Š”๋ฐ, ์ด ๋ฉ”์„œ๋“œ์—์„œ๋Š” `receiptItem`์˜ `์ฆ์ • ๊ฐœ์ˆ˜๊ฐ€ 0`์ผ ๊ฒฝ์šฐ์—๋งŒ ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋˜์ง€ ์•Š์€ ์ƒํ’ˆ์œผ๋กœ ํŒ๋‹จํ•˜๊ณ , ์ด์— ๋”ฐ๋ผ ๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ์ ์šฉํ•˜๊ธฐ ์œ„ํ•ด ์ด ๊ฐ€๊ฒฉ์„ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ,` [์ฝœ๋ผ-2]`,` [์—๋„ˆ์ง€๋ฐ”-1]`์„ ๊ตฌ๋งคํ•˜๊ณ , ๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์„ ๊ฒฝ์šฐ, ์—๋„ˆ์ง€๋ฐ” 1๊ฐœ์— ๋Œ€ํ•ด์„œ๋งŒ ๋ฉค๋ฒ„์‹ญ ํ• ์ธ์ด ์ ์šฉ๋˜๋Š” ๋กœ์ง์ž…๋‹ˆ๋‹ค. ๋™์ผํ•˜๊ฒŒ `[์ฝœ๋ผ-2]`๋ฅผ ๊ตฌ๋งคํ•˜๊ณ , ๋ฌด๋ฃŒ ์ฆ์ • 1๊ฐœ๋ฅผ ๋ฐ›์ง€ ์•Š๋Š”๋‹ค๊ณ  ์„ ํƒํ–ˆ์„ ๊ฒฝ์šฐ, ๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์„ ๋•Œ ์ฝœ๋ผ 2๊ฐœ ์ „์ฒด์— ๋Œ€ํ•ด ๋ฉค๋ฒ„์‹ญ ํ• ์ธ์ด ์ ์šฉ๋ฉ๋‹ˆ๋‹ค. ์ถ”๊ฐ€์ ์œผ๋กœ ๊ฐœ์„ ํ•  ๋ถ€๋ถ„์ด ์žˆ๋‹ค๋ฉด ํ”ผ๋“œ๋ฐฑ ์ฃผ์‹œ๋ฉด ๊ฐ์‚ฌํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค! ๐Ÿ˜Š
@@ -0,0 +1,143 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.List; +import java.util.function.Supplier; +import store.constant.CommonMessage; +import store.constant.CommonValue; +import store.constant.SignMessage; +import store.domain.GeneralProduct; +import store.domain.PromotionProduct; +import store.domain.Receipt; +import store.domain.Storage; +import store.exception.ConvenienceStoreException; +import store.service.ReceiptService; +import store.service.StorageService; +import store.utils.Calculator; +import store.utils.Compare; +import store.utils.Parser; +import store.view.input.InputView; +import store.view.output.OutputView; + +public class ConvenienceStoreController { + private final InputView inputView; + private final OutputView outputView; + private final Storage storage; + + public ConvenienceStoreController(InputView inputView, OutputView outputView, StorageService storageService) { + this.inputView = inputView; + this.outputView = outputView; + this.storage = storageService.initializeStorage(); + } + + public void operate() { + String retryFlag; + do { + outputView.writeStorageStatus(storage); + Receipt receipt = new Receipt(); + processPurchase(userPurchaseProduct(), receipt); + outputView.writeReceipt(receipt, userMembership()); + retryFlag = userRetry(); + } while (retryFlag.equalsIgnoreCase(CommonMessage.YES.getCommonMessage())); + inputView.closeConsole(); + } + + private void processPurchase(List<String> purchaseProduct, Receipt receipt) { + for (String detail : purchaseProduct) { + List<String> item = List.of(detail.split(SignMessage.HYPHEN.getSign())); + PromotionProduct product = storage.findPromotionProduct(item.get(CommonValue.ZERO.getValue())); + if (product != null && product.getPromotion().isActive(DateTimes.now())) { + processPromotionProduct(product, Parser.parse(item.get(CommonValue.ONE.getValue())), receipt); + continue; + } + processGeneralPurchase(item, receipt); + } + } + + private void processGeneralPurchase(List<String> item, Receipt receipt) { + ReceiptService.purchaseGeneralProduct(storage, item.get(CommonValue.ZERO.getValue()), + Integer.parseInt(item.get(CommonValue.ONE.getValue())), receipt); + } + + private void processPromotionProduct(PromotionProduct promotionProduct, int itemQuantity, Receipt receipt) { + int stock = Calculator.calculateRemainStock(promotionProduct, itemQuantity); + int purchase = Calculator.calculateUserRemain(promotionProduct, itemQuantity); + boolean freeTag = userOneMoreFree(purchase, stock, promotionProduct, itemQuantity, receipt); + boolean supplementTag = supplementStock(itemQuantity, stock, promotionProduct, receipt); + useStock(freeTag, supplementTag, promotionProduct, itemQuantity, receipt); + } + + private boolean userOneMoreFree(int leftBuy, int leftStock, PromotionProduct product, int count, Receipt receipt) { + if (Compare.checkFreeOneMore(leftBuy, leftStock, product)) { + storage.subtractPromotionProduct(product, count); + if (checkUserAnswer(product).equals(CommonMessage.YES.getCommonMessage())) { + storage.subtractPromotionProduct(product, product.getPromotionGetGet()); + return ReceiptService.oneMoreReceipt(receipt, count, leftBuy, product); + } + return ReceiptService.noOneMoreReceipt(receipt, count, leftBuy, product); + } + return false; + } + + private boolean supplementStock(int quantity, int stock, PromotionProduct product, Receipt receipt) { + if (Compare.checkSupplementStock(stock)) { + int noPromotion = Calculator.calculateNoPromotion(product); + int beforePromotionQuantity = product.getQuantity(); + storage.subtractPromotionProduct(product, noPromotion); + String userAnswer = checkUserNoPromotion(product, Calculator.minus(quantity, noPromotion)); + return suppleGeneralProduct(product, userAnswer, Calculator.minus(quantity, noPromotion), receipt, + beforePromotionQuantity); + } + return false; + } + + private boolean suppleGeneralProduct(PromotionProduct product, String answer, int quantity, Receipt receipt, + int prevQuantity) { + GeneralProduct generalProduct = storage.findGeneralProduct(product.getName()); + int currentQuantity = product.getQuantity(); + if (answer.equals(CommonMessage.YES.getCommonMessage())) { + storage.subtractGeneralProduct(generalProduct, Calculator.minus(quantity, currentQuantity)); + storage.subtractPromotionProduct(product, currentQuantity); + return ReceiptService.noDiscountPurchase(receipt, quantity, prevQuantity, currentQuantity, product); + } + return ReceiptService.noOneMoreReceipt(receipt, prevQuantity, currentQuantity, product); + } + + private void useStock(boolean freeTag, boolean suppleTag, PromotionProduct product, int quantity, Receipt receipt) { + if (!freeTag && !suppleTag) { + storage.subtractPromotionProduct(product, quantity); + ReceiptService.useStock(product, quantity, receipt); + } + } + + private String userRetry() { + return handleUserInput(inputView::readRetry); + } + + private String userMembership() { + return handleUserInput(inputView::readMembership); + } + + private List<String> userPurchaseProduct() { + return handleUserInput(() -> storage.validateStorageStatus(inputView.readItems())); + } + + private String checkUserAnswer(PromotionProduct promotionProduct) { + return handleUserInput(() -> inputView.readOneMoreFree(promotionProduct.getName())); + } + + private String checkUserNoPromotion(PromotionProduct promotionProduct, int quantity) { + return handleUserInput(() -> inputView.readNoDiscountAnswer(promotionProduct.getName(), quantity)); + } + + private <T> T handleUserInput(Supplier<T> inputSupplier) { + while (true) { + try { + return inputSupplier.get(); + } catch (ConvenienceStoreException convenienceStoreException) { + outputView.displayErrorMessage(convenienceStoreException); + } + } + } + +}
Java
๋ง์”€ํ•˜์‹  ๋ถ€๋ถ„์— ๋™์˜ํ•ฉ๋‹ˆ๋‹ค. HYPHEN์ด๋‚˜ ZERO์™€ ๊ฐ™์ด ์ด๋ฆ„ ์ž์ฒด๊ฐ€ ์˜๋ฏธ๋ฅผ ์ง๊ด€์ ์œผ๋กœ ๋‹ด๊ณ  ์žˆ๋Š” ๊ฒฝ์šฐ, Enum๋ณด๋‹ค๋Š” ์ผ๋ฐ˜ ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ getValue() ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๋ฐฉ์‹์ด ๋” ๊น”๋”ํ•  ๊ฒƒ ๊ฐ™์•„์š”!! ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ์ด ๋†’์•„์ง€๊ณ , ๋ถˆํ•„์š”ํ•œ getValue() ํ˜ธ์ถœ์„ ํ”ผํ•  ์ˆ˜ ์žˆ์–ด ๋” ์ง๊ด€์ ์ผ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. Enum์€ ๋ณดํ†ต ์ƒํƒœ๋‚˜ ๋ฒ”์œ„๊ฐ€ ๋ช…ํ™•ํ•œ ์ƒ์ˆ˜๋“ค์„ ์ •์˜ํ•  ๋•Œ ์ ํ•ฉํ•œ๋ฐ, ์ด ๊ฒฝ์šฐ์—๋Š” ์ผ๋ฐ˜ ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ๋” ๋‚˜์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค....
@@ -0,0 +1,38 @@ +package store.domain; + +public class GeneralProduct { + private final String name; + private final String price; + private int quantity; + + public GeneralProduct(final String name, final String price, final int quantity) { + this.name = name; + this.price = price; + this.quantity = quantity; + } + + public String getName() { + return name; + } + + public int getQuantity() { + return quantity; + } + + public String getPrice() { + return price; + } + + public void subtraction(int value) { + this.quantity -= Math.abs(value); + } + + @Override + public String toString() { + if (quantity == 0) { + return String.format("- %s %,d์› ์žฌ๊ณ  ์—†์Œ", name, Integer.parseInt(price)); + } + return String.format("- %s %,d์› %s๊ฐœ", name, Integer.parseInt(price), quantity); + } + +}
Java
์•„๋‡จ.. ํŠน๋ณ„ํ•œ ์ด์œ ๋Š” ์—†์—ˆ์Šต๋‹ˆ๋‹ค ์šฐ์„  ๋ฌธ์ž์—ด๋กœ ๋ฐ›์€ ํ›„์— ์ถ”ํ›„์— intํ˜•์œผ๋กœ ์ˆ˜์ •ํ•˜๋ ค๊ณ  ํ•˜์˜€๋Š”๋ฐ ๊นŒ๋จน๊ณ  ๋†“์นœ ๊ฒƒ ๊ฐ™์•„์š”! ๋ง์”€ํ•ด์ฃผ์…”์„œ ๊ฐ์‚ฌ๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,40 @@ +package store.domain; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +public class Promotion { + private final String name; + private final int buy; + private final int get; + private final LocalDate startDate; + private final LocalDate endDate; + + public Promotion(final String name, final int buy, final int get, final String startDate, final String endDate) { + this.name = name; + this.buy = buy; + this.get = get; + this.startDate = LocalDate.parse(startDate); + this.endDate = LocalDate.parse(endDate); + } + + public String getName() { + return name; + } + + public int getBuy() { + return buy; + } + + public int getGet() { + return get; + } + + public boolean isActive(LocalDateTime dateTime) { + LocalDate date = dateTime.toLocalDate(); + return (date.isEqual(startDate) || date.isAfter(startDate)) && + (date.isEqual(endDate) || date.isBefore(endDate)); + } + +} +
Java
์กฐ๊ฑด์ด ๊ธธ์–ด์ง€๋‹ค ๋ณด๋‹ˆ, ๋‚ ์งœ๊ฐ€ ๊ธฐ๊ฐ„์— ํฌํ•จ๋˜๋Š”์ง€ ํ™•์ธํ•˜๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์€ ์ ‘๊ทผ ๊ฐ™์•„์š”. `isBetween` ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ฝ”๋“œ ๊ฐ€๋…์„ฑ์„ ๋†’์ด๋Š” ๋ฐ ๋„์›€์ด ๋  ๊ฒƒ ๊ฐ™๋„ค์š”!
@@ -0,0 +1,71 @@ +package store.domain; + +import java.util.ArrayList; +import java.util.List; +import store.constant.CommonMessage; +import store.constant.CommonValue; + +public class Receipt { + private final double THIRTY_PERCENT = 0.3; + private final List<ReceiptItem> receiptItems = new ArrayList<>(); + + public void addItem(ReceiptItem receiptItem) { + receiptItems.add(receiptItem); + } + + public List<ReceiptItem> getReceiptItems() { + return receiptItems; + } + + public int totalPurchaseAmount() { + int sum = CommonValue.ZERO.getValue(); + for (ReceiptItem receiptItem : receiptItems) { + sum += receiptItem.getTotalBuyQuantity() * receiptItem.getPrice(); + } + return sum; + } + + public int totalPromotionDiscount() { + int sum = CommonValue.ZERO.getValue(); + for (ReceiptItem receiptItem : receiptItems) { + if (receiptItem.getGetQuantity() != CommonValue.ZERO.getValue()) { + sum += receiptItem.getGetQuantity() * receiptItem.getPrice(); + } + } + return sum; + } + + public int getTotalPurchaseCount() { + int sum = CommonValue.ZERO.getValue(); + for (ReceiptItem receiptItem : receiptItems) { + sum += receiptItem.getTotalBuyQuantity(); + } + return sum; + } + + public int validateMembership(String userAnswer) { + if (userAnswer.equals(CommonMessage.YES.getCommonMessage())) { + return getMembershipDiscount(); + } + return CommonValue.ZERO.getValue(); + } + + private int noTotalPromotionAmount() { + int sum = CommonValue.ZERO.getValue(); + for (ReceiptItem receiptItem : receiptItems) { + if (receiptItem.getGetQuantity() == CommonValue.ZERO.getValue()) { + sum += receiptItem.getBuyQuantity() * receiptItem.getPrice(); + } + } + return sum; + } + + private int getMembershipDiscount() { + int membershipDiscount = (int) (noTotalPromotionAmount() * THIRTY_PERCENT); + if (membershipDiscount > CommonValue.EIGHT_THOUSAND.getValue()) { + membershipDiscount = CommonValue.EIGHT_THOUSAND.getValue(); + } + return membershipDiscount; + } + +}
Java
์ข‹์€ ์งˆ๋ฌธ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! Receipt ํด๋ž˜์Šค๋ฅผ domain ํŒจํ‚ค์ง€์— ๋‘๋Š” ์ด์œ ๋Š” ์ด ํด๋ž˜์Šค๊ฐ€ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ ํ•ต์‹ฌ ๋„๋ฉ”์ธ ๋กœ์ง์„ ์ฒ˜๋ฆฌํ•˜๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. Receipt๋Š” ๊ทธ ์ž์ฒด๋กœ ๊ตฌ๋งค ๋‚ด์—ญ์„ ๋‹ค๋ฃจ๊ณ  ์ด๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์„ ์ฒ˜๋ฆฌํ•˜๋Š” ํด๋ž˜์Šค์ด๊ธฐ ๋•Œ๋ฌธ์— ๋„๋ฉ”์ธ ๊ณ„์ธต์— ์œ„์น˜ํ•˜๋Š” ๊ฒƒ์ด ์ž์—ฐ์Šค๋Ÿฝ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค. ๋ฌผ๋ก , model์ด๋ผ๋Š” ๋ณ„๋„์˜ ํŒจํ‚ค์ง€๋ฅผ ๋‘๊ณ  ๊ด€๋ฆฌํ•  ์ˆ˜๋„ ์žˆ์ง€๋งŒ, ํ˜„์žฌ ๊ตฌ์กฐ์—์„œ๋Š” domain ํŒจํ‚ค์ง€๊ฐ€ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ ์ฃผ์š” ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์„ ๋ชจ๋‘ ํฌํ•จํ•˜๊ณ  ์žˆ์–ด์„œ, Receipt์™€ ๊ฐ™์€ ํด๋ž˜์Šค๋ฅผ ๋ณ„๋„๋กœ ๋ถ„๋ฆฌํ•˜์ง€ ์•Š๊ณ  ๋„๋ฉ”์ธ ๋‚ด์— ํฌํ•จ์‹œํ‚ค๋Š” ๊ฒƒ์ด ์ฝ”๋“œ์˜ ์ผ๊ด€์„ฑ์„ ์œ ์ง€ํ•˜๋Š” ๋ฐ ๋„์›€์ด ๋œ๋‹ค๊ณ  ํŒ๋‹จํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,71 @@ +package store.domain; + +import java.util.ArrayList; +import java.util.List; +import store.constant.CommonMessage; +import store.constant.CommonValue; + +public class Receipt { + private final double THIRTY_PERCENT = 0.3; + private final List<ReceiptItem> receiptItems = new ArrayList<>(); + + public void addItem(ReceiptItem receiptItem) { + receiptItems.add(receiptItem); + } + + public List<ReceiptItem> getReceiptItems() { + return receiptItems; + } + + public int totalPurchaseAmount() { + int sum = CommonValue.ZERO.getValue(); + for (ReceiptItem receiptItem : receiptItems) { + sum += receiptItem.getTotalBuyQuantity() * receiptItem.getPrice(); + } + return sum; + } + + public int totalPromotionDiscount() { + int sum = CommonValue.ZERO.getValue(); + for (ReceiptItem receiptItem : receiptItems) { + if (receiptItem.getGetQuantity() != CommonValue.ZERO.getValue()) { + sum += receiptItem.getGetQuantity() * receiptItem.getPrice(); + } + } + return sum; + } + + public int getTotalPurchaseCount() { + int sum = CommonValue.ZERO.getValue(); + for (ReceiptItem receiptItem : receiptItems) { + sum += receiptItem.getTotalBuyQuantity(); + } + return sum; + } + + public int validateMembership(String userAnswer) { + if (userAnswer.equals(CommonMessage.YES.getCommonMessage())) { + return getMembershipDiscount(); + } + return CommonValue.ZERO.getValue(); + } + + private int noTotalPromotionAmount() { + int sum = CommonValue.ZERO.getValue(); + for (ReceiptItem receiptItem : receiptItems) { + if (receiptItem.getGetQuantity() == CommonValue.ZERO.getValue()) { + sum += receiptItem.getBuyQuantity() * receiptItem.getPrice(); + } + } + return sum; + } + + private int getMembershipDiscount() { + int membershipDiscount = (int) (noTotalPromotionAmount() * THIRTY_PERCENT); + if (membershipDiscount > CommonValue.EIGHT_THOUSAND.getValue()) { + membershipDiscount = CommonValue.EIGHT_THOUSAND.getValue(); + } + return membershipDiscount; + } + +}
Java
์ข‹์€ ์ง€์  ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! ๋ง์”€ํ•˜์‹  ๋Œ€๋กœ ๋ถ€๋™์†Œ์ˆ˜์  ์˜ค์ฐจ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์ ์„ ๊ฐ„๊ณผํ–ˆ๋˜ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ข‹์€ ๋ฐฉ๋ฒ•์ธ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,83 @@ +package store.domain; + +import java.util.Collections; +import java.util.List; +import store.constant.CommonValue; +import store.constant.SignMessage; +import store.exception.ConvenienceStoreException; +import store.exception.ErrorMessage; + +public class Storage { + private final List<GeneralProduct> generalProducts; + private final List<PromotionProduct> promotionProducts; + + public Storage(final List<GeneralProduct> generalProducts, final List<PromotionProduct> promotionProducts) { + this.generalProducts = generalProducts; + this.promotionProducts = promotionProducts; + } + + public List<String> validateStorageStatus(List<String> purchaseProduct) { + for (String purchaseItem : purchaseProduct) { + List<String> item = List.of(purchaseItem.split(SignMessage.HYPHEN.getSign())); + validateItemName(item.get(CommonValue.ZERO.getValue())); + validateQuantity(item.get(CommonValue.ZERO.getValue()), item.get(CommonValue.ONE.getValue())); + } + return purchaseProduct; + } + + public List<GeneralProduct> getGeneralProducts() { + return Collections.unmodifiableList(generalProducts); + } + + public List<PromotionProduct> getPromotionProducts() { + return Collections.unmodifiableList(promotionProducts); + } + + public GeneralProduct findGeneralProduct(String productName) { + return generalProducts.stream() + .filter(product -> product.getName().equals(productName)) + .findFirst() + .orElse(null); + } + + public PromotionProduct findPromotionProduct(String productName) { + return promotionProducts.stream() + .filter(product -> product.getName().equals(productName)) + .findFirst() + .orElse(null); + } + + public void subtractPromotionProduct(PromotionProduct promotionProduct, int itemQuantity) { + promotionProduct.subtraction(itemQuantity); + } + + public void subtractGeneralProduct(GeneralProduct generalProduct, int itemQuantity) { + generalProduct.subtraction(itemQuantity); + } + + private void validateQuantity(String name, String quantity) { + if (getProductQuantity(name) < Integer.parseInt(quantity)) { + throw ConvenienceStoreException.from(ErrorMessage.STORAGE_OVER); + } + } + + private int getProductQuantity(String name) { + PromotionProduct promotionProduct = findPromotionProduct(name); + int count = CommonValue.ZERO.getValue(); + if (promotionProduct != null) { + count += promotionProduct.getQuantity(); + } + return count + findGeneralProduct(name).getQuantity(); + } + + private void validateItemName(String name) { + if (!isProductInStorage(name)) { + throw ConvenienceStoreException.from(ErrorMessage.NON_EXISTENT_PRODUCT); + } + } + + private boolean isProductInStorage(String productName) { + return generalProducts.stream().anyMatch(product -> product.getName().equals(productName)); + } + +}
Java
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,114 @@ +package store.service; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import store.constant.FileMessage; +import store.constant.SignMessage; +import store.domain.GeneralProduct; +import store.domain.Promotion; +import store.domain.PromotionProduct; +import store.domain.Storage; +import store.utils.FileLoader; + +public class StorageService { + private static final String FILE_NOT_FOUND_ERROR = "[ERROR] ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."; + private final List<String> productFile; + private final List<String> promotionFile; + + public StorageService(final String productFileName, final String promotionFileName) { + this.productFile = loadFile(productFileName); + this.promotionFile = loadFile(promotionFileName); + } + + public Storage initializeStorage() { + List<Promotion> promotions = generatePromotionData(promotionFile); + List<GeneralProduct> onlyGeneralProducts = findGeneralProduct(productFile); + List<PromotionProduct> onlyPromotionProducts = findPromotionProduct(productFile, promotions); + List<GeneralProduct> insertedGeneralProducts = insertOutOfStock(onlyPromotionProducts, onlyGeneralProducts); + return new Storage(insertedGeneralProducts, onlyPromotionProducts); + } + + private List<String> loadFile(String fileName) { + try { + return FileLoader.fileReadLine(fileName); + } catch (IOException e) { + throw new IllegalArgumentException(FILE_NOT_FOUND_ERROR); + } + } + + private List<Promotion> generatePromotionData(List<String> promotionFile) { + List<Promotion> promotions = new ArrayList<>(); + for (String line : promotionFile) { + List<String> items = List.of(line.split(SignMessage.COMMA.getSign())); + promotions.add(new Promotion(items.get(0), Integer.parseInt(items.get(1)), Integer.parseInt(items.get(2)), + items.get(3), items.get(4))); + } + return promotions; + } + + private List<GeneralProduct> insertOutOfStock(List<PromotionProduct> prItem, List<GeneralProduct> generalProducts) { + int idx = 0; + for (PromotionProduct product : prItem) { + if (findEqualGeneralProductName(generalProducts, product.getName())) { + idx += 1; + continue; + } + generalProducts.add(idx, new GeneralProduct(product.getName(), product.getPrice(), 0)); + } + return generalProducts; + } + + + private boolean findEqualGeneralProductName(List<GeneralProduct> generalProducts, String name) { + for (GeneralProduct generalProduct : generalProducts) { + if (generalProduct.getName().equals(name)) { + return true; + } + } + return false; + } + + private List<GeneralProduct> findGeneralProduct(List<String> getFile) { + List<GeneralProduct> onlyGeneralProducts = new ArrayList<>(); + for (String itemDetails : getFile) { + if (itemDetails.contains(FileMessage.NULL.getFileMessage())) { + List<String> item = List.of(itemDetails.split(SignMessage.COMMA.getSign())); + onlyGeneralProducts.add(new GeneralProduct(item.get(0), item.get(1), Integer.parseInt(item.get(2)))); + } + } + return onlyGeneralProducts; + } + + private List<PromotionProduct> findPromotionProduct(List<String> getFile, List<Promotion> promotions) { + List<PromotionProduct> onlyPromotionProducts = new ArrayList<>(); + for (String itemDetails : getFile) { + if (isPromotionProduct(itemDetails)) { + addPromotionProduct(onlyPromotionProducts, itemDetails, promotions); + } + } + return onlyPromotionProducts; + } + + private boolean isPromotionProduct(String itemDetails) { + return itemDetails.contains(FileMessage.SOFT_DRINK.getFileMessage()) + || itemDetails.contains(FileMessage.MD_RECOMMEND_PRODUCT.getFileMessage()) + || itemDetails.contains(FileMessage.FLASH_DISCOUNT.getFileMessage()); + } + + private void addPromotionProduct(List<PromotionProduct> products, String itemDetails, List<Promotion> promotions) { + List<String> item = List.of(itemDetails.split(SignMessage.COMMA.getSign())); + String productName = item.get(0); + String productCategory = item.get(1); + int price = Integer.parseInt(item.get(2)); + Promotion promotion = matchingPromotion(item.get(3), promotions); + + products.add(new PromotionProduct(productName, productCategory, price, promotion)); + } + + private Promotion matchingPromotion(String promotionName, List<Promotion> promotions) { + return promotions.stream().filter(promotion -> promotion.getName().equals(promotionName)).findFirst() + .orElse(null); + } + +}
Java
์•„.. ์ด ๋ถ€๋ถ„๋„ ๋ฆฌํŒฉํ† ๋งํ•˜๋ฉด์„œ ErrorMessage์— ์˜ฎ๊ฒจ์•ผ ํ–ˆ๋Š”๋ฐ ๋†“์ณค๋˜ ๊ฒƒ ๊ฐ™์•„์š”! ๋ง์”€ํ•ด์ฃผ์…”์„œ ๊ฐ์‚ฌ๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,141 @@ +package store.view.output; + +import java.util.List; +import store.domain.GeneralProduct; +import store.domain.PromotionProduct; +import store.domain.Receipt; +import store.domain.ReceiptItem; +import store.domain.Storage; +import store.exception.ConvenienceStoreException; + +public class OutputView { + + public void writeStorageStatus(Storage storage) { + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + System.out.println(OutputMessage.WELCOME_MESSAGE.getOutputMessage()); + System.out.println(OutputMessage.SHOW_CURRENT_ITEMS.getOutputMessage()); + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + writeInitPromotionProducts(storage); + writeInitOnlyGeneralProducts(storage); + } + + public void writeReceipt(Receipt receipt, String userAnswer) { + writeReceiptMenuHeader(); + writeReceiptMenuName(receipt); + writePresentation(receipt); + System.out.println(OutputMessage.PERFORATION_LINE.getOutputMessage()); + writeUserTotalReceipt(receipt, userAnswer); + } + + private void writeUserTotalReceipt(Receipt receipt, String userAnswer) { + writeShowTotalPurchaseAmount(receipt); + writeShowTotalPromotionDiscountAmount(receipt); + writeShowTotalMembershipDiscountAmount(receipt, userAnswer); + writeShowTotalPaymentAmount(receipt, userAnswer); + } + + private void writeShowTotalPaymentAmount(Receipt receipt, String userAnswer) { + String nameAndPrice = String.format(OutputMessage.SHOW_PAYMENT_FORMAT.getOutputMessage(), "๋‚ด์‹ค๋ˆ", + String.format("%,d", receipt.totalPurchaseAmount() - receipt.totalPromotionDiscount() - + receipt.validateMembership(userAnswer))); + System.out.println(nameAndPrice); + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + } + + + private void writeShowTotalMembershipDiscountAmount(Receipt receipt, String userAnswer) { + String name = String.format("%-14s", "๋ฉค๋ฒ„์‹ญํ• ์ธ").replace(" ", "\u3000"); + String price = String.format("-%,d", receipt.validateMembership(userAnswer)); + System.out.printf(OutputMessage.SHOW_DISCOUNT_FORMAT.getOutputMessage(), name, price); + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + } + + private void writeShowTotalPromotionDiscountAmount(Receipt receipt) { + String name = String.format("%-14s", "ํ–‰์‚ฌํ• ์ธ").replace(" ", "\u3000"); + String price = String.format("-%,d", receipt.totalPromotionDiscount()); + System.out.printf(OutputMessage.SHOW_DISCOUNT_FORMAT.getOutputMessage(), name, price); + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + } + + private void writeShowTotalPurchaseAmount(Receipt receipt) { + String name = String.format("%-14s", "์ด๊ตฌ๋งค์•ก").replace(" ", "\u3000"); + String quantity = String.format("%-10d", receipt.getTotalPurchaseCount()); + String price = String.format("%,-10d", receipt.totalPurchaseAmount()); + System.out.printf(OutputMessage.SHOW_RECEIPT_INIT_FORMAT.getOutputMessage(), name, quantity, price); + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + } + + private void writePresentation(Receipt receipt) { + System.out.println(OutputMessage.SHOW_RECEIPT_PRESENTATION_HEADER.getOutputMessage()); + for (ReceiptItem receiptItem : receipt.getReceiptItems()) { + if (receiptItem.getGetQuantity() != 0) { + String name = String.format("%-14s", receiptItem.getItemName()).replace(" ", "\u3000"); + String quantity = String.format("%,-10d", receiptItem.getGetQuantity()); + System.out.printf(OutputMessage.SHOW_PRESENTATION_FORMAT.getOutputMessage(), name, quantity); + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + } + } + } + + private void writeReceiptMenuName(Receipt receipt) { + System.out.println(OutputMessage.SHOW_RECEIPT_MENU_NAME.getOutputMessage()); + for (ReceiptItem receiptItem : receipt.getReceiptItems()) { + String name = String.format("%-14s", receiptItem.getItemName()).replace(" ", "\u3000"); + String quantity = String.format("%-10d", receiptItem.getTotalBuyQuantity()); + String price = String.format("%,-10d", receiptItem.getPrice() * receiptItem.getTotalBuyQuantity()); + System.out.printf(OutputMessage.SHOW_RECEIPT_INIT_FORMAT.getOutputMessage(), name, quantity, price); + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + } + } + + private void writeReceiptMenuHeader() { + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + System.out.println(OutputMessage.SHOW_RECEIPT_HEADER.getOutputMessage()); + } + + + private void writeInitPromotionProducts(Storage storage) { + for (PromotionProduct promotionProduct : storage.getPromotionProducts()) { + System.out.println(promotionProduct); + findEqualGeneralProductName(storage.getGeneralProducts(), promotionProduct.getName()); + } + } + + private void findEqualGeneralProductName(List<GeneralProduct> generalProducts, String name) { + for (GeneralProduct generalProduct : generalProducts) { + if (generalProduct.getName().equals(name)) { + System.out.println(generalProduct); + break; + } + } + } + + private void writeInitOnlyGeneralProducts(Storage storage) { + for (GeneralProduct generalProduct : storage.getGeneralProducts()) { + String generalProductName = generalProduct.getName(); + boolean flag = findEqualPromotionProductName(storage.getPromotionProducts(), generalProductName); + writeOnlyGeneralProduct(flag, generalProduct); + } + System.out.print(OutputMessage.NEW_LINE.getOutputMessage()); + } + + private boolean findEqualPromotionProductName(List<PromotionProduct> promotionProducts, String name) { + for (PromotionProduct promotionProduct : promotionProducts) { + if (promotionProduct.getName().equals(name)) { + return true; + } + } + return false; + } + + private void writeOnlyGeneralProduct(boolean flag, GeneralProduct generalProduct) { + if (!flag) { + System.out.println(generalProduct.toString()); + } + } + + public void displayErrorMessage(ConvenienceStoreException convenienceStoreException) { + System.out.println(convenienceStoreException.getMessage()); + } + +}
Java
์ €๋Š” ๊ฐœ์ธ์ ์œผ๋กœ ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์ด ์†Œ์ง„๋œ ๊ฒฝ์šฐ์—๋„ '์žฌ๊ณ  ์—†์Œ'์„ ํ‘œ์‹œํ•˜๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•˜๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ์žฌ๊ณ  ์—†์Œ์„ ํ‘œ์‹œํ•˜์ง€ ์•Š์œผ๋ฉด, ์‚ฌ์šฉ์ž๊ฐ€ ํ•ด๋‹น ์ƒํ’ˆ์ด ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„์— ํฌํ•จ๋œ ๊ฒƒ์ธ์ง€ ์•„๋‹Œ์ง€๋ฅผ ๊ตฌ๋ถ„ํ•˜๊ธฐ ์–ด๋ ค์šธ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„ ์ค‘์— ์žฌ๊ณ ๊ฐ€ ์—†๋‹ค๋ฉด '์žฌ๊ณ  ์—†์Œ'์„ ๋ช…์‹œํ•˜๋Š” ๊ฒƒ์ด ์‚ฌ์šฉ์ž์—๊ฒŒ ๋” ๋ช…ํ™•ํ•˜๊ณ  ํ˜ผ๋ž€์„ ์ค„์ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋ฌผ๋ก  ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„์ด ์•„๋‹Œ ๊ฒฝ์šฐ์—๋Š” '์žฌ๊ณ  ์—†์Œ'์ด ํ‘œ์‹œ๋˜์ง€ ์•Š๋Š” ๊ฒƒ์ด ๋งž๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค! ์ข‹์€ ์˜๊ฒฌ ๊ฐ์‚ฌ๋“œ๋ฆฝ๋‹ˆ๋‹ค! ๋ง์”€ํ•ด์ฃผ์‹  ๋‚ด์šฉ์„ ๋•๋ถ„์— UX ์ธก๋ฉด์—์„œ๋„ ๋‹ค์‹œ ํ•œ ๋ฒˆ ๊ณ ๋ฏผํ•ด๋ณผ ์ˆ˜ ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,143 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.List; +import java.util.function.Supplier; +import store.constant.CommonMessage; +import store.constant.CommonValue; +import store.constant.SignMessage; +import store.domain.GeneralProduct; +import store.domain.PromotionProduct; +import store.domain.Receipt; +import store.domain.Storage; +import store.exception.ConvenienceStoreException; +import store.service.ReceiptService; +import store.service.StorageService; +import store.utils.Calculator; +import store.utils.Compare; +import store.utils.Parser; +import store.view.input.InputView; +import store.view.output.OutputView; + +public class ConvenienceStoreController { + private final InputView inputView; + private final OutputView outputView; + private final Storage storage; + + public ConvenienceStoreController(InputView inputView, OutputView outputView, StorageService storageService) { + this.inputView = inputView; + this.outputView = outputView; + this.storage = storageService.initializeStorage(); + } + + public void operate() { + String retryFlag; + do { + outputView.writeStorageStatus(storage); + Receipt receipt = new Receipt(); + processPurchase(userPurchaseProduct(), receipt); + outputView.writeReceipt(receipt, userMembership()); + retryFlag = userRetry(); + } while (retryFlag.equalsIgnoreCase(CommonMessage.YES.getCommonMessage())); + inputView.closeConsole(); + } + + private void processPurchase(List<String> purchaseProduct, Receipt receipt) { + for (String detail : purchaseProduct) { + List<String> item = List.of(detail.split(SignMessage.HYPHEN.getSign())); + PromotionProduct product = storage.findPromotionProduct(item.get(CommonValue.ZERO.getValue())); + if (product != null && product.getPromotion().isActive(DateTimes.now())) { + processPromotionProduct(product, Parser.parse(item.get(CommonValue.ONE.getValue())), receipt); + continue; + } + processGeneralPurchase(item, receipt); + } + } + + private void processGeneralPurchase(List<String> item, Receipt receipt) { + ReceiptService.purchaseGeneralProduct(storage, item.get(CommonValue.ZERO.getValue()), + Integer.parseInt(item.get(CommonValue.ONE.getValue())), receipt); + } + + private void processPromotionProduct(PromotionProduct promotionProduct, int itemQuantity, Receipt receipt) { + int stock = Calculator.calculateRemainStock(promotionProduct, itemQuantity); + int purchase = Calculator.calculateUserRemain(promotionProduct, itemQuantity); + boolean freeTag = userOneMoreFree(purchase, stock, promotionProduct, itemQuantity, receipt); + boolean supplementTag = supplementStock(itemQuantity, stock, promotionProduct, receipt); + useStock(freeTag, supplementTag, promotionProduct, itemQuantity, receipt); + } + + private boolean userOneMoreFree(int leftBuy, int leftStock, PromotionProduct product, int count, Receipt receipt) { + if (Compare.checkFreeOneMore(leftBuy, leftStock, product)) { + storage.subtractPromotionProduct(product, count); + if (checkUserAnswer(product).equals(CommonMessage.YES.getCommonMessage())) { + storage.subtractPromotionProduct(product, product.getPromotionGetGet()); + return ReceiptService.oneMoreReceipt(receipt, count, leftBuy, product); + } + return ReceiptService.noOneMoreReceipt(receipt, count, leftBuy, product); + } + return false; + } + + private boolean supplementStock(int quantity, int stock, PromotionProduct product, Receipt receipt) { + if (Compare.checkSupplementStock(stock)) { + int noPromotion = Calculator.calculateNoPromotion(product); + int beforePromotionQuantity = product.getQuantity(); + storage.subtractPromotionProduct(product, noPromotion); + String userAnswer = checkUserNoPromotion(product, Calculator.minus(quantity, noPromotion)); + return suppleGeneralProduct(product, userAnswer, Calculator.minus(quantity, noPromotion), receipt, + beforePromotionQuantity); + } + return false; + } + + private boolean suppleGeneralProduct(PromotionProduct product, String answer, int quantity, Receipt receipt, + int prevQuantity) { + GeneralProduct generalProduct = storage.findGeneralProduct(product.getName()); + int currentQuantity = product.getQuantity(); + if (answer.equals(CommonMessage.YES.getCommonMessage())) { + storage.subtractGeneralProduct(generalProduct, Calculator.minus(quantity, currentQuantity)); + storage.subtractPromotionProduct(product, currentQuantity); + return ReceiptService.noDiscountPurchase(receipt, quantity, prevQuantity, currentQuantity, product); + } + return ReceiptService.noOneMoreReceipt(receipt, prevQuantity, currentQuantity, product); + } + + private void useStock(boolean freeTag, boolean suppleTag, PromotionProduct product, int quantity, Receipt receipt) { + if (!freeTag && !suppleTag) { + storage.subtractPromotionProduct(product, quantity); + ReceiptService.useStock(product, quantity, receipt); + } + } + + private String userRetry() { + return handleUserInput(inputView::readRetry); + } + + private String userMembership() { + return handleUserInput(inputView::readMembership); + } + + private List<String> userPurchaseProduct() { + return handleUserInput(() -> storage.validateStorageStatus(inputView.readItems())); + } + + private String checkUserAnswer(PromotionProduct promotionProduct) { + return handleUserInput(() -> inputView.readOneMoreFree(promotionProduct.getName())); + } + + private String checkUserNoPromotion(PromotionProduct promotionProduct, int quantity) { + return handleUserInput(() -> inputView.readNoDiscountAnswer(promotionProduct.getName(), quantity)); + } + + private <T> T handleUserInput(Supplier<T> inputSupplier) { + while (true) { + try { + return inputSupplier.get(); + } catch (ConvenienceStoreException convenienceStoreException) { + outputView.displayErrorMessage(convenienceStoreException); + } + } + } + +}
Java
CommonMessage.YES.getCommonMessage() ํ•ด๋‹น ๊ตฌ๋ฌธ์ด ์ž์ฃผ ์‚ฌ์šฉ๋˜์–ด ๋ณด์ด๋„ค์š”. ํ•ด๋‹น ๋ถ€๋ถ„์„ CommonMessage ํด๋ž˜์Šค์˜ ๋ฉ”์„œ๋“œ๋กœ ๊ตฌํ˜„ํ•˜๋Š” ๋ฐฉ์‹์€ ์–ด๋–จ๊นŒ์š”? ๋˜ํ•œ InputView์—์„œ validateUserAnswer() ๋ฉ”์„œ๋“œ์—์„œ ์‚ฌ์šฉ์ž ์ž…๋ ฅ์ด Y๋ƒ N ๋ƒ enum ํด๋ž˜์Šค์˜ ์ •์˜์™€ ๊ฐ™์€ ์ง€ ํ™•์ธํ•˜๊ณ  ๋‹ค๋ฅด๋ฉด ์˜ˆ์™ธ๋ฅผ ๋˜์ง€๋Š” ๊ฒƒ๋ณด๋‹ค, CommonMessage์„ Dto ์ฒ˜๋Ÿผ ํ™œ์šฉํ•˜์—ฌ ํ•ด๋‹น dto๋ฅผ ์ƒ์„ฑํ•จ์— ์žˆ์–ด์„œ ์‚ฌ์šฉ์ž ์ž…๋ ฅ์„ ๋„˜๊ฒจ์ฃผ๊ณ (new CommonMessage(String input)) ์ž…๋ ฅ ์ •์˜์™€ ๋‹ค๋ฅผ ์‹œ์— dto ์ƒ์„ฑ์ž์—์„œ ์˜ˆ์™ธ๋ฅผ ๋˜์ ธ์ฃผ๋Š” ๋ฐฉ์‹์€ ์–ด๋–จ๊นŒ์š”? ์ œ ์ƒ๊ฐ์—๋Š” ์œ„์ฒ˜๋Ÿผ ๊ตฌํ˜„ ํ•˜๋Š” ๊ฒƒ์ด InputView์˜ ์ฑ…์ž„์„ ๋œ์–ด์ฃผ๋ฉด์„œ ์ฑ…์ž„ ์กฐ์ •์ด ๋” ์•ˆ์ •์ ์ผ ๊ฒƒ ๊ฐ™์•„์š”! ์ด์— ๋Œ€ํ•œ ๋ณด์šฑ๋‹˜ ์˜๊ฒฌ์ด ๊ถ๊ธˆํ•ด์š”!
@@ -0,0 +1,19 @@ +package store.constant; + +public enum SignMessage { + COMMA(","), + LEFT_SQUARE_BRACKET("["), + RIGHT_SQUARE_BRACKET("]"), + HYPHEN("-"); + + private final String sign; + + SignMessage(final String sign) { + this.sign = sign; + } + + public String getSign() { + return sign; + } + +}
Java
์ด๋Ÿฌํ•œ ',', '[' ๋“ฑ๊ณผ ๊ฐ™์ด ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง๊ณผ ๊ด€๋ ค๋œ ๋ถ€๋ถ„์€ ๋”ฐ๋กœ ์ƒ์ˆ˜ ํด๋ž˜์Šค๋ฅผ ๋‘๋Š” ๊ฒƒ๋ณด๋‹ค ๊ทธ๋ƒฅ ์‚ฌ์šฉ ํด๋ž˜์Šค ๋‚ด์˜ ์ƒ์ˆ˜ ํ•„๋“œ๋กœ๋งŒ ๋‘์–ด๋„ ๋  ๊ฒƒ ๊ฐ™์•„์š”. ์ € ๊ฐ™์€ ๊ฒฝ์šฐ๋Š” ์ƒ์ˆ˜ ํด๋ž˜์Šค๋กœ ๋”ฐ๋กœ ๊ด€๋ฆฌํ•˜๋Š” ๋ถ€๋ถ„์€ ๋น„์ฆˆ๋‹ˆ์Šค์™€ ๊ด€๋ จ๋œ ๋ถ€๋ถ„์„ ํ•œ๋ฒˆ์— ๋ชจ์•„๋ณด๋Š” ๊ฐ€๋…์„ฑ๋ฉด์ด ์ œ์ผ ํฌ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๊ฑฐ๋“ ์š”! ์ž๋ฐ”์—์„œ๋Š” ๋ฌธ์ž์—ด ๋ฆฌํ„ฐ๋Ÿด์€ ๋”ฐ๋กœ ์ƒ์ˆ˜ํ’€์—์„œ ํ•œ๋ฒˆ์— ๊ด€๋ฆฌํ•˜๋ฏ€๋กœ ์ €๋Ÿฐ ๋ฆฌํ„ฐ๋Ÿด ๋ถ€๋ถ„์€ ํด๋ž˜์Šค์— ์ค‘๋ณต๋˜์–ด ์„ ์–ธ๋˜์–ด๋„ ๋ฉ”๋ชจ๋ฆฌ์ƒ์—์„œ๋Š” ๋ฌธ์ œ ์—†์œผ๋‹ˆ๊นŒ ์‚ฌ์šฉํ•˜๋Š” ํด๋ž˜์Šค์˜ ์ƒ์ˆ˜ ํ•„๋“œ๋กœ ๋‘์–ด๋„ ๋  ๊ฒƒ ๊ฐ™์•„์š”. ์ด๋Š” ์ œ ๊ฐœ์ธ์ ์˜๊ฒฌ์ด๋ผ ๋‹ค๋ฅธ ๋ถ„๋“ค์˜ ์˜๊ฒฌ๋„ ๊ถ๊ธˆํ•˜๋„ค์š”!
@@ -0,0 +1,143 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.List; +import java.util.function.Supplier; +import store.constant.CommonMessage; +import store.constant.CommonValue; +import store.constant.SignMessage; +import store.domain.GeneralProduct; +import store.domain.PromotionProduct; +import store.domain.Receipt; +import store.domain.Storage; +import store.exception.ConvenienceStoreException; +import store.service.ReceiptService; +import store.service.StorageService; +import store.utils.Calculator; +import store.utils.Compare; +import store.utils.Parser; +import store.view.input.InputView; +import store.view.output.OutputView; + +public class ConvenienceStoreController { + private final InputView inputView; + private final OutputView outputView; + private final Storage storage; + + public ConvenienceStoreController(InputView inputView, OutputView outputView, StorageService storageService) { + this.inputView = inputView; + this.outputView = outputView; + this.storage = storageService.initializeStorage(); + } + + public void operate() { + String retryFlag; + do { + outputView.writeStorageStatus(storage); + Receipt receipt = new Receipt(); + processPurchase(userPurchaseProduct(), receipt); + outputView.writeReceipt(receipt, userMembership()); + retryFlag = userRetry(); + } while (retryFlag.equalsIgnoreCase(CommonMessage.YES.getCommonMessage())); + inputView.closeConsole(); + } + + private void processPurchase(List<String> purchaseProduct, Receipt receipt) { + for (String detail : purchaseProduct) { + List<String> item = List.of(detail.split(SignMessage.HYPHEN.getSign())); + PromotionProduct product = storage.findPromotionProduct(item.get(CommonValue.ZERO.getValue())); + if (product != null && product.getPromotion().isActive(DateTimes.now())) { + processPromotionProduct(product, Parser.parse(item.get(CommonValue.ONE.getValue())), receipt); + continue; + } + processGeneralPurchase(item, receipt); + } + } + + private void processGeneralPurchase(List<String> item, Receipt receipt) { + ReceiptService.purchaseGeneralProduct(storage, item.get(CommonValue.ZERO.getValue()), + Integer.parseInt(item.get(CommonValue.ONE.getValue())), receipt); + } + + private void processPromotionProduct(PromotionProduct promotionProduct, int itemQuantity, Receipt receipt) { + int stock = Calculator.calculateRemainStock(promotionProduct, itemQuantity); + int purchase = Calculator.calculateUserRemain(promotionProduct, itemQuantity); + boolean freeTag = userOneMoreFree(purchase, stock, promotionProduct, itemQuantity, receipt); + boolean supplementTag = supplementStock(itemQuantity, stock, promotionProduct, receipt); + useStock(freeTag, supplementTag, promotionProduct, itemQuantity, receipt); + } + + private boolean userOneMoreFree(int leftBuy, int leftStock, PromotionProduct product, int count, Receipt receipt) { + if (Compare.checkFreeOneMore(leftBuy, leftStock, product)) { + storage.subtractPromotionProduct(product, count); + if (checkUserAnswer(product).equals(CommonMessage.YES.getCommonMessage())) { + storage.subtractPromotionProduct(product, product.getPromotionGetGet()); + return ReceiptService.oneMoreReceipt(receipt, count, leftBuy, product); + } + return ReceiptService.noOneMoreReceipt(receipt, count, leftBuy, product); + } + return false; + } + + private boolean supplementStock(int quantity, int stock, PromotionProduct product, Receipt receipt) { + if (Compare.checkSupplementStock(stock)) { + int noPromotion = Calculator.calculateNoPromotion(product); + int beforePromotionQuantity = product.getQuantity(); + storage.subtractPromotionProduct(product, noPromotion); + String userAnswer = checkUserNoPromotion(product, Calculator.minus(quantity, noPromotion)); + return suppleGeneralProduct(product, userAnswer, Calculator.minus(quantity, noPromotion), receipt, + beforePromotionQuantity); + } + return false; + } + + private boolean suppleGeneralProduct(PromotionProduct product, String answer, int quantity, Receipt receipt, + int prevQuantity) { + GeneralProduct generalProduct = storage.findGeneralProduct(product.getName()); + int currentQuantity = product.getQuantity(); + if (answer.equals(CommonMessage.YES.getCommonMessage())) { + storage.subtractGeneralProduct(generalProduct, Calculator.minus(quantity, currentQuantity)); + storage.subtractPromotionProduct(product, currentQuantity); + return ReceiptService.noDiscountPurchase(receipt, quantity, prevQuantity, currentQuantity, product); + } + return ReceiptService.noOneMoreReceipt(receipt, prevQuantity, currentQuantity, product); + } + + private void useStock(boolean freeTag, boolean suppleTag, PromotionProduct product, int quantity, Receipt receipt) { + if (!freeTag && !suppleTag) { + storage.subtractPromotionProduct(product, quantity); + ReceiptService.useStock(product, quantity, receipt); + } + } + + private String userRetry() { + return handleUserInput(inputView::readRetry); + } + + private String userMembership() { + return handleUserInput(inputView::readMembership); + } + + private List<String> userPurchaseProduct() { + return handleUserInput(() -> storage.validateStorageStatus(inputView.readItems())); + } + + private String checkUserAnswer(PromotionProduct promotionProduct) { + return handleUserInput(() -> inputView.readOneMoreFree(promotionProduct.getName())); + } + + private String checkUserNoPromotion(PromotionProduct promotionProduct, int quantity) { + return handleUserInput(() -> inputView.readNoDiscountAnswer(promotionProduct.getName(), quantity)); + } + + private <T> T handleUserInput(Supplier<T> inputSupplier) { + while (true) { + try { + return inputSupplier.get(); + } catch (ConvenienceStoreException convenienceStoreException) { + outputView.displayErrorMessage(convenienceStoreException); + } + } + } + +}
Java
์˜คํžˆ๋ ค ๊ฐ์ฒด๋กœ๋งŒ ํ˜‘๋ ฅํ•˜๋„๋ก ํ•œ ๋ถ€๋ถ„์ด ๋…ธ๋ จํ•œ ๊ฒƒ ๊ฐ™์•„์š”! ์ €๋Š” ๊ฐ์ฒด๋ฅผ ๋‹ค๋ฃจ๊ณ  ํ˜‘๋ ฅํ•˜๋Š” ๋ถ€๋ถ„์ด ์–ด๋ ค์›Œ์„œ ์„œ๋น„์Šค ์ธต์„ ๋‘์—ˆ๊ฑฐ๋“ ์š” ๐Ÿคฃ
@@ -0,0 +1,38 @@ +package store.domain; + +public class GeneralProduct { + private final String name; + private final String price; + private int quantity; + + public GeneralProduct(final String name, final String price, final int quantity) { + this.name = name; + this.price = price; + this.quantity = quantity; + } + + public String getName() { + return name; + } + + public int getQuantity() { + return quantity; + } + + public String getPrice() { + return price; + } + + public void subtraction(int value) { + this.quantity -= Math.abs(value); + } + + @Override + public String toString() { + if (quantity == 0) { + return String.format("- %s %,d์› ์žฌ๊ณ  ์—†์Œ", name, Integer.parseInt(price)); + } + return String.format("- %s %,d์› %s๊ฐœ", name, Integer.parseInt(price), quantity); + } + +}
Java
์ €๋„ ์ด๋Ÿฌํ•œ 2์ฃผ์ฐจ ๋•๊ฐ€? ๊ฐ์ฒด ์ถœ๋ ฅ๊ณผ ๊ด€๋ จ๋œ ๋ถ€๋ถ„์€ ํ•ด๋‹น ๊ฐ์ฒด ์•ˆ์—์„œ ํ•˜๋Š”๊ฒŒ ์ฝ”๋“œ๋„ ๊น”๋”ํ•˜๊ณ  ์ข‹์ง€์•Š์„๊นŒํ•˜์—ฌ ์ด๋ ‡๊ฒŒ ์ž‘์„ฑํ•œ ์ ์ด์žˆ์Šต๋‹ˆ๋‹ค! ํ•˜์ง€๋งŒ ๊ฒฐ๊ตญ ๋งˆ์ง€๋ง‰ ์ฏค toStirng๊ณผ ๊ด€๋ จ๋œ ์ฝ”๋“œ๋Š” ๋ชจ๋‘ ์ง€์šฐ๊ณ  view์—์„œ๋งŒ ๋‹ดํ•˜๋„๋ก ํ–ˆ์—ˆ๋Š”๋ฐ์š”, ๊ทธ ์ด์œ ๋กœ ์ฒซ ๋ฒˆ์งธ๋Š” toString์€ ์›ฌ๋งŒํ•˜๋ฉด ๋กœ๊ทธ ํ™•์ธ์šฉ์œผ๋กœ๋งŒ ์‚ฌ์šฉ๋œ๋‹ค๊ณ  ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค. 3์ฃผ์ฐจ ๊ณตํ†ต ํ”ผ๋“œ๋ฐฑ์—๋„ ์ด์— ๋Œ€ํ•œ ์‚ฌํ•ญ์ด ์ ํ˜€์žˆ๋”๋ผ๊ตฌ์š”! ๋‘ ๋ฒˆ์งธ๋กœ ์ถœ๋ ฅํ˜•์‹์ด ๋ฐ”๋€Œ๋ฉด View ๋ฟ๋งŒ์•„๋‹ˆ๋ผ ๊ด€๋ จ ํด๋ž˜์Šค๋“ค์„ ์ฐพ์œผ๋Ÿฌ ๋‹ค๋‹ˆ๋ฉด์„œ ๊ณ ์ณ์•ผํ•  ๊ฒƒ ๊ฐ™๋‹ค๋Š” ์ƒ๊ฐ์— ์ถœ๋ ฅ๊ด€๋ จ์€ ์˜ค์ง View์˜ ์ฑ…์ž„์œผ๋กœ๋งŒ ์ฃผ์—ˆ์—ˆ์Šต๋‹ˆ๋‹ค! ์ €๋„ ๊ฐˆํŒก์งˆํŒก ํ–ˆ๋˜ ์‚ฌํ•ญ์ด๋ผ ์ด์— ๋Œ€ํ•œ ๋ณด์šฑ๋‹˜ ์˜๊ฒฌ๋„ ๊ถ๊ธˆํ•˜๋„ค์š”๐Ÿ˜Š
@@ -0,0 +1,34 @@ +package store.view; + +public enum Sentence { + + PRODUCT_SELECT_STATEMENT("๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"), + HELLO_STATEMENT("์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค."), + CURRENT_PRODUCTS_STATEMENT("ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."), + NUMBER_FORMAT("#,###"), + PRODUCT_FORMAT("- %s %s์› "), + QUANTITY_FORMAT("%s๊ฐœ "), + OUT_OF_STOCK("์žฌ๊ณ  ์—†์Œ "), + ADDITIONAL_PURCHASE_FORMAT("ํ˜„์žฌ %s์€(๋Š”) %d๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"), + NO_PROMOTION_STATEMENT("ํ˜„์žฌ %s %d๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"), + MEMBERSHIP_STATEMENT("๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"), + START_OF_RECEIPT("==============W ํŽธ์˜์ ================"), + HEADER_OF_PURCHASE("์ƒํ’ˆ๋ช…\t\t์ˆ˜๋Ÿ‰\t๊ธˆ์•ก"), + PURCHASE_FORMAT("%s\t\t%s \t%s"), + HEADER_OF_GIVEN("=============์ฆ\t์ •==============="), + GIVEN_FORMAT("%s\t\t%s"), + DIVIDE_LINE("===================================="), + TOTAL_PRICE_FORMAT("์ด๊ตฌ๋งค์•ก\t\t%s\t%s"), + PROMOTION_DISCOUNT_FORMAT("ํ–‰์‚ฌํ• ์ธ\t\t\t-%s"), + MEMBERSHIP_DISCOUNT_FORMAT("๋ฉค๋ฒ„์‹ญํ• ์ธ\t\t\t-%s"), + PAY_PRICE_FORMAT("๋‚ด์‹ค๋ˆ\t\t\t %s"), + PURCHASE_AGAIN_STATEMENT("๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"), + BLANK(""), + NEW_LINE(System.lineSeparator()); + + final String message; + + Sentence(final String message) { + this.message = message; + } +}
Java
๋‹จ์ˆœํ•œ ์ถœ๋ ฅ ๋ฌธ๊ตฌ๋“ค๋„ ์ƒ์ˆ˜ํ™” ํ•ด์•ผ ํ•˜๋Š”์ง€ ์‚ด์ง ์˜๋ฌธ์ž…๋‹ˆ๋‹ค. ์ƒ์ˆ˜ํ™”์˜ ์ด์ ์€ ์ค‘๋ณต์„ ์ œ๊ฑฐํ•˜๊ณ  ๊ฐ€๋…์„ฑ์„ ํ–ฅ์ƒ ์‹œํ‚ค๋Š” ๋“ฑ์˜ ํšจ๊ณผ๊ฐ€ ์žˆ์ง€๋งŒ ๋ถˆํ•„์š”ํ•œ ๋ณต์žก์„ฑ ์ฆ๊ฐ€, ์ฝ”๋“œ ์œ ์ง€ ๊ด€๋ฆฌ์˜ ์–ด๋ ค์›€ ๋“ฑ์˜ ๋‹จ์ ๋„ ์žˆ์Šต๋‹ˆ๋‹ค. ์œ„ ๋ฌธ๊ตฌ๋ฅผ ์ƒ์ˆ˜ํ™” ํ–ˆ์„ ๋•Œ ์ •ํ™•ํžˆ ์–ด๋–ค ๋„์›€์ด ๋˜๋Š”์ง€ ๋‹ค์‹œ ์ƒ๊ฐํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,52 @@ +package store.view; + +import store.domain.Product; +import store.domain.Products; +import store.dto.ReceiptDto; + +public class View { + + private final InputView inputView; + private final OutputView outputView; + + public View(InputView inputView, OutputView outputView) { + this.inputView = inputView; + this.outputView = outputView; + } + + public String requestProductSelect() { + return inputView.requestProductSelect(); + } + + public String askAdditionalPurchase(Product product) { + return inputView.askAdditionalPurchase(product); + } + + public String askNoPromotion(Product product, int shortageQuantity) { + return inputView.askNoPromotion(product, shortageQuantity); + } + + public String askMembership() { + return inputView.askMembership(); + } + + public String askPurchaseAgain() { + return inputView.askPurchaseAgain(); + } + + public void printHello() { + outputView.printHello(); + } + + public void printCurrentProducts(Products products) { + outputView.printCurrentProducts(products); + } + + public void printReceipt(ReceiptDto receiptDto) { + outputView.printReceipt(receiptDto); + } + + public void printBlank() { + outputView.printBlank(); + } +}
Java
์ข‹์€ ์ : InputView์™€ OutputView๋ฅผ View ํด๋ž˜์Šค์—์„œ ๋ฌถ์–ด์ฃผ๋Š” ๊ตฌ์กฐ๋Š” ๊ฐ ๋ทฐ ๊ฐ์ฒด์— ๋Œ€ํ•œ ์˜์กด์„ฑ์„ ์ค„์ด๊ณ , View ํด๋ž˜์Šค๊ฐ€ ํ•˜๋‚˜์˜ ํ†ตํ•ฉ๋œ ์—ญํ• ์„ ํ•˜๊ฒŒ ๋งŒ๋“ค์–ด์ฃผ๋Š” ์ ์—์„œ ์ข‹์€ ์ ‘๊ทผ์ด์—์š”. ๊ฐœ์„  ์‚ฌํ•ญ: ํ•˜์ง€๋งŒ ํ˜„์žฌ View ํด๋ž˜์Šค๋Š” ์‚ฌ์‹ค์ƒ InputView์™€ OutputView์˜ ๋ฉ”์„œ๋“œ๋ฅผ ๊ทธ๋Œ€๋กœ ์ „๋‹ฌํ•˜๋Š” ์—ญํ• ๋งŒ ํ•˜๊ณ  ์žˆ์–ด์š”. ์ด๋ ‡๊ฒŒ ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ์‹๋งŒ์œผ๋กœ๋Š” View ํด๋ž˜์Šค์˜ ์กด์žฌ ์ด์œ ๊ฐ€ ์กฐ๊ธˆ ๋ถˆ๋ช…ํ™•ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋งŒ์•ฝ ์ด ํด๋ž˜์Šค๊ฐ€ ๋‹ค๋ฅธ ์—ญํ• ์„ ์ˆ˜ํ–‰ํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด, ์ค‘๊ฐ„์—์„œ ๋‹จ์ˆœํžˆ ๋ฉ”์„œ๋“œ ์ „๋‹ฌ๋งŒ ํ•˜๋Š” ๊ตฌ์กฐ๋Š” ๋ถˆํ•„์š”ํ•œ ์˜ค๋ฒ„ํ—ค๋“œ๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ์–ด์š”. ์˜ˆ๋ฅผ ๋“ค์–ด, InputView์™€ OutputView๋ฅผ ๊ฐ๊ฐ ํ˜ธ์ถœํ•˜๋Š” ๊ฒƒ๊ณผ ๋™์ผํ•œ ๋ฐฉ์‹์œผ๋กœ ๋™์ž‘ํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ, ๋‘ ํด๋ž˜์Šค์˜ ์—ญํ• ์ด ๋ช…ํ™•ํ•˜๋‹ค๋ฉด View ํด๋ž˜์Šค๋ฅผ ์ƒ๋žตํ•  ์ˆ˜๋„ ์žˆ๊ฒ ๋„ค์š”. ๋งŒ์•ฝ View ํด๋ž˜์Šค์—์„œ ํ–ฅํ›„ ์ถ”๊ฐ€์ ์ธ ๋กœ์ง์ด๋‚˜ ์ฒ˜๋ฆฌ๊ฐ€ ํ•„์š”ํ•˜๋‹ค๋ฉด, ๊ทธ๋•Œ ์—ญํ• ์„ ๋ช…ํ™•ํžˆ ์ •์˜ํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์€ ๋ฐฉ๋ฒ•์ผ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,28 @@ +package store.dto; + +import store.domain.Product; +import store.domain.PurchaseItem; + +public record GivenItemDto( + String name, + int freeQuantity, + int price) { + + public static GivenItemDto from(PurchaseItem purchaseItem) { + Product product = purchaseItem.getProduct(); + int freeQuantity = calculateFreeQuantity(purchaseItem); + + return new GivenItemDto(product.name(), freeQuantity, product.price()); + } + + private static int calculateFreeQuantity(PurchaseItem purchaseItem) { + Product product = purchaseItem.getProduct(); + + if (product.promotion() != null) { + return product.promotion() + .calculateFreeQuantity(purchaseItem.getQuantity(), product.stock().getPromotionStock()); + } + + return 0; + } +}
Java
DTO๋ฅผ ์‚ฌ์šฉํ•˜์‹œ๋Š” ๋ฐฉ์‹์ด ๋„ˆ๋ฌด ์ข‹๋„ค์š” ์ €๋„ ์ด๋Ÿฐ์‹์œผ๋กœ ๊ตฌํ˜„ํ–ˆ๋‹ค๋ฉด ํ•œ๊ฒฐ ๊น”๋”ํ–ˆ์„ ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,42 @@ +package store.domain; + +public record Product( + String name, + int price, + Stock stock, + Promotion promotion) { + + public int calculateTotalPrice(int quantity) { + return price * quantity; + } + + public void updateStock(int purchasedQuantity) { + int availablePromotionStock = stock.getPromotionStock(); + int promotionQuantity = Math.min(availablePromotionStock, purchasedQuantity); + int regularQuantity = purchasedQuantity - promotionQuantity; + + stock.minusPromotionStock(promotionQuantity); + stock.minusRegularStock(regularQuantity); + } + + public int calculatePromotionDiscount(int purchasedQuantity) { + if (promotion == null || !promotion.isWithinPromotionPeriod()) { + return 0; + } + + int eligibleForPromotion = promotion.calculateFreeQuantity(purchasedQuantity, stock.getPromotionStock()); + return eligibleForPromotion * price; + } + + public int getPromotionStock() { + return stock.getPromotionStock(); + } + + public int getRegularStock() { + return stock.getRegularStock(); + } + + public int getFullStock() { + return getPromotionStock() + getRegularStock(); + } +}
Java
๋ณ€๋™์„ฑ์ด ํฐ ๊ฐ์ฒด์ธ๋ฐ ๋ ˆ์ฝ”๋“œ๋กœ ๊ตฌํ˜„ํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,64 @@ +package store.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.time.LocalDate; +import store.dto.PromotionDetailDto; + +public class Promotion { + + private final String name; + private final int buy; + private final int get; + private final LocalDate startDate; + private final LocalDate endDate; + + public Promotion(final String name, final int buy, final int get, final LocalDate startDate, + final LocalDate endDate) { + this.name = name; + this.buy = buy; + this.get = get; + this.startDate = startDate; + this.endDate = endDate; + } + + public boolean isWithinPromotionPeriod() { + LocalDate today = DateTimes.now().toLocalDate(); + return (today.isEqual(startDate) || today.isAfter(startDate)) + && (today.isEqual(endDate) || today.isBefore(endDate)); + } + + public int calculateAdditionalPurchase(int purchaseQuantity) { + int remain = purchaseQuantity % sumOfBuyAndGet(); + + if (remain != 0) { + return sumOfBuyAndGet() - remain; + } + + return remain; + } + + public PromotionDetailDto calculatePromotionAndFree(int requestedQuantity, int promotionStock) { + int availablePromotion = (promotionStock / sumOfBuyAndGet()) * sumOfBuyAndGet(); + return new PromotionDetailDto(availablePromotion, requestedQuantity - availablePromotion); + } + + public int calculateFreeQuantity(int requestedQuantity, int promotionStock) { + if (requestedQuantity > promotionStock) { + return promotionStock / sumOfBuyAndGet(); + } + + return requestedQuantity / sumOfBuyAndGet(); + } + + private int sumOfBuyAndGet() { + return buy + get; + } + + public String getName() { + return name; + } + + public int getGet() { + return get; + } +}
Java
์ด๋ถ€๋ถ„์€ ์ €๋„ ๋™์ผํ•˜๊ฒŒ ๊ตฌํ˜„ํ–ˆ์ง€๋งŒ buy์™€ get์„ ํฌ์žฅํ•˜๊ณ  startDate์™€ endDate๋ฅผ ํฌ์žฅํ•˜์—ฌ ํ•„๋“œ ์ˆ˜๋ฅผ ์ค„์˜€์œผ๋ฉด ์–ด๋• ์„์ง€ ๊ถ๊ธˆํ•˜๋„ค์š”
@@ -0,0 +1,34 @@ +package store.view; + +public enum Sentence { + + PRODUCT_SELECT_STATEMENT("๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"), + HELLO_STATEMENT("์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค."), + CURRENT_PRODUCTS_STATEMENT("ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."), + NUMBER_FORMAT("#,###"), + PRODUCT_FORMAT("- %s %s์› "), + QUANTITY_FORMAT("%s๊ฐœ "), + OUT_OF_STOCK("์žฌ๊ณ  ์—†์Œ "), + ADDITIONAL_PURCHASE_FORMAT("ํ˜„์žฌ %s์€(๋Š”) %d๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"), + NO_PROMOTION_STATEMENT("ํ˜„์žฌ %s %d๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"), + MEMBERSHIP_STATEMENT("๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"), + START_OF_RECEIPT("==============W ํŽธ์˜์ ================"), + HEADER_OF_PURCHASE("์ƒํ’ˆ๋ช…\t\t์ˆ˜๋Ÿ‰\t๊ธˆ์•ก"), + PURCHASE_FORMAT("%s\t\t%s \t%s"), + HEADER_OF_GIVEN("=============์ฆ\t์ •==============="), + GIVEN_FORMAT("%s\t\t%s"), + DIVIDE_LINE("===================================="), + TOTAL_PRICE_FORMAT("์ด๊ตฌ๋งค์•ก\t\t%s\t%s"), + PROMOTION_DISCOUNT_FORMAT("ํ–‰์‚ฌํ• ์ธ\t\t\t-%s"), + MEMBERSHIP_DISCOUNT_FORMAT("๋ฉค๋ฒ„์‹ญํ• ์ธ\t\t\t-%s"), + PAY_PRICE_FORMAT("๋‚ด์‹ค๋ˆ\t\t\t %s"), + PURCHASE_AGAIN_STATEMENT("๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"), + BLANK(""), + NEW_LINE(System.lineSeparator()); + + final String message; + + Sentence(final String message) { + this.message = message; + } +}
Java
์ถœ๋ ฅํ•  ๋ฌธ๊ตฌ๋“ค์„ enum์œผ๋กœ ๋งŒ๋“œ๋Š” ๊ฒƒ์ด ํ…Œ์ŠคํŠธํ•  ๋•Œ ์šฉ์ดํ•˜๋‹ค๊ณ  ์ƒ๊ฐ๋ฉ๋‹ˆ๋‹ค! ์ด๋ฒˆ ํ…Œ์ŠคํŠธ ์ฝ”๋“œ์—์„œ๋Š” ๊ทธ๋Ÿฐ ๋ถ€๋ถ„๋“ค์„ ํ…Œ์ŠคํŠธํ•˜์ง€ ๋ชปํ–ˆ์ง€๋งŒ, ๊ฐœ์ธ์ ์œผ๋กœ ์ถœ๋ ฅ ๋ฌธ๊ตฌ๋“ค์„ ๋ชจ์•„๋‘๋Š” ๊ฒƒ์ด ๊ตฌํ˜„ ์‹œ ํŽธ๋ฆฌํ•˜๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.