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