code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,142 @@ +package store; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class BuyerTest { + + private Buyer buyer; + + @BeforeEach + public void setUp() { + buyer = new Buyer(); + buyer.initializationReceiptMap(); + } + + @Test + @DisplayName("ํ”„๋กœ๋ชจ์…˜_๋‚ด์šฉ์ด_์žˆ๋Š”_์ œํ’ˆ์€_๋ฌด์กฐ๊ฑด_products๊ฐ€_๊ฐ€์ง€๊ณ ์žˆ๋Š”_๋ฆฌ์ŠคํŠธ์˜_์‚ฌ์ด์ฆˆ๊ฐ€_2๋‹ค") + void ํ”„๋กœ๋ชจ์…˜_๋‚ด์šฉ์ด_์žˆ๋Š”_์ œํ’ˆ์€_๋ฌด์กฐ๊ฑด_products๊ฐ€_๊ฐ€์ง€๊ณ ์žˆ๋Š”_๋ฆฌ์ŠคํŠธ์˜_์‚ฌ์ด์ฆˆ๊ฐ€_2๋‹ค() { + LinkedHashMap<String, List<Product>> products = buyer.getProducts(); + for (String category : products.keySet()) { + List<Product> productList = products.get(category); + + if (productList.getFirst().getPromotion() != null) { + assertThat(productList.size()).isEqualTo(2); + } + } + } + + @ParameterizedTest + @ValueSource(strings = {"์ปฌ๋ผ", "์‹ธ์ด๋‹ค", "๋ด‰์ง€๋ผ๋ฉด", "ํ™”๋ถ„"}) + @DisplayName("์ œํ’ˆ๋ชฉ๋ก์— ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ œํ’ˆ๋ช…์„ ์ž…๋ ฅ ์‹œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.") + void ์ œํ’ˆ๋ชฉ๋ก์—_์กด์žฌํ•˜์ง€_์•Š๋Š”_์ œํ’ˆ๋ช…์„_์ž…๋ ฅ_์‹œ_์—๋Ÿฌ๊ฐ€_๋ฐœ์ƒํ•œ๋‹ค(String productName) { + List<Product> wantBuyProducts = new ArrayList<>(); + wantBuyProducts.add(new Product(productName, 10)); + + assertThatThrownBy(() -> buyer.productNameCheck(wantBuyProducts)) + .isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @ValueSource(ints = {1, 2, 3, 4, 5, 6, 7}) + @DisplayName("๊ตฌ๋งคํ•œ_๊ฐฏ์ˆ˜๋งŒํผ_์‹ค์ œ_products_๊ฐ์ฒด์—์„œ_์ˆ˜๋Ÿ‰_๊ฐ์†Œํ•˜๋Š”์ง€_ํ™•์ธ") + void ๊ตฌ๋งคํ•œ_๊ฐฏ์ˆ˜๋งŒํผ_์‹ค์ œ_products_๊ฐ์ฒด์—์„œ_์ˆ˜๋Ÿ‰_๊ฐ์†Œํ•˜๋Š”์ง€_ํ™•์ธ(int buyCount) { + //ํ˜„์žฌ ์ดˆ๊ธฐ์— ์„ค์ •๋œ ์ฝœ๋ผ ๊ฐฏ์ˆ˜๋Š” 10๊ฐœ + int canPromotionCokeSize = buyer.getProducts().get("์ฝœ๋ผ").getFirst().getQuantity(); + List<Product> wantBuyProducts = new ArrayList<>(); + wantBuyProducts.add(new Product("์ฝœ๋ผ", buyCount)); + + buyer.realBuyProducts(wantBuyProducts); + + assertThat(canPromotionCokeSize - buyCount).isEqualTo( + buyer.getProducts().get("์ฝœ๋ผ").getFirst().getQuantity()); + + } + + @Test + @DisplayName("๊ตฌ๋งค๋ฅผ_์›ํ•˜๋Š”_๊ฐฏ์ˆ˜๊ฐ€_๊ตฌ๋งค๊ฐ€๋Šฅ๊ฐฏ์ˆ˜์ดํ•˜๋ฉด_true_๋„˜์œผ๋ฉด_false๋ฐ˜ํ™˜_ํ™•์ธ") + void ๊ตฌ๋งค๋ฅผ_์›ํ•˜๋Š”_๊ฐฏ์ˆ˜๊ฐ€_๊ตฌ๋งค๊ฐ€๋Šฅ๊ฐฏ์ˆ˜์ดํ•˜๋ฉด_true_๋„˜์œผ๋ฉด_false๋ฐ˜ํ™˜_ํ™•์ธ() { + int wantBuyQuantity = 10; + Product product = new Product("์ฝœ๋ผ", 9); + Product exceedProduct = new Product("์ฝœ๋ผ", 11); + + assertThat(buyer.withinQuantity(product, wantBuyQuantity)).isEqualTo(false); + assertThat(buyer.withinQuantity(exceedProduct, wantBuyQuantity)).isEqualTo(true); + } + + @Test + void ๊ตฌ๋งคํ•œ_์ œํ’ˆ์˜_์ด์ˆ˜๋Ÿ‰์„_๊ตฌํ•œ๋‹ค() { + List<Product> wantBuyProducts = new ArrayList<>(); + int cokeCount = 10; + int spriteCount = 7; + wantBuyProducts.add(new Product("์ฝœ๋ผ", cokeCount)); + wantBuyProducts.add(new Product("์‚ฌ์ด๋‹ค", spriteCount)); + + assertThat(buyer.calculateTotalBuyCount(wantBuyProducts)).isEqualTo(cokeCount + spriteCount); + } + + @ParameterizedTest + @ValueSource(ints = {21, 100, 22222222}) + @DisplayName("์‹ค์ œ_๊ตฌ๋งค_๊ฐ€๋Šฅํ•œ_๊ฐฏ์ˆ˜๊ฐ€_์•„๋‹ˆ๋ฉด_์—๋Ÿฌ_๋ฐœ์ƒ์—ฌ๋ถ€_ํ™•์ธ") + void ์‹ค์ œ_๊ตฌ๋งค_๊ฐ€๋Šฅํ•œ_๊ฐฏ์ˆ˜๊ฐ€_์•„๋‹ˆ๋ฉด_์—๋Ÿฌ_๋ฐœ์ƒ์—ฌ๋ถ€_ํ™•์ธ(int buyCount) { + //์ฝœ๋ผ ์ด ๊ฐฏ์ˆ˜๋Š” 20๊ฐœ + List<Product> wantBuyProducts = new ArrayList<>(); + wantBuyProducts.add(new Product("์ฝœ๋ผ", buyCount)); + + assertThatThrownBy(() -> buyer.checkCanBuyQuantity(wantBuyProducts)) + .isInstanceOf(IllegalArgumentException.class); + } + + + @Test + @DisplayName("ํ”„๋กœ๋ชจ์…˜_์ œํ’ˆ์ด_์žฌ๊ณ ๊ฐ€_๋ถ€์กฑํ• ๋•Œ_๋ช‡๊ฐœ_๋ถ€์กฑํ•œ์ง€_์ •์ƒ์ ์œผ๋กœ_๋ฐ˜ํ™˜ํ•˜๋Š”์ง€_ํ™•์ธ") + void ํ”„๋กœ๋ชจ์…˜_์ œํ’ˆ์ด_์žฌ๊ณ ๊ฐ€_๋ถ€์กฑํ• ๋•Œ_๋ช‡๊ฐœ_๋ถ€์กฑํ•œ์ง€_์ •์ƒ์ ์œผ๋กœ_๋ฐ˜ํ™˜ํ•˜๋Š”์ง€_ํ™•์ธ() { + int cokeCount = 12; //์ฝœ๋ผ๋Š” 2+1 ํ–‰์‚ฌ์ค‘ / ํ–‰์‚ฌ์ œํ’ˆ ๊ตฌ๋งค๊ฐ€๋Šฅ ๊ฐœ์ˆ˜ = 9 + int instantCupRamenCount = 2; //์ปต๋ผ๋ฉด์€ 1+1 ํ–‰์‚ฌ์ค‘ / ํ–‰์‚ฌ์ œํ’ˆ ๊ตฌ๋งค๊ฐ€๋Šฅ ๊ฐœ์ˆ˜ = 1 + + assertThat(buyer.calculateNotPromotionCount(new Product("์ฝœ๋ผ", cokeCount))).isEqualTo(3); + assertThat(buyer.calculateNotPromotionCount(new Product("์ปต๋ผ๋ฉด", instantCupRamenCount))).isEqualTo(2); + } + + @Test + @DisplayName("ํ”„๋กœ๋ชจ์…˜์œผ๋กœ_๋ฌด๋ฃŒ๊ตฌ๋งค๋˜๋Š”_์ œํ’ˆ์˜_๊ฐฏ์ˆ˜๋ฅผ_๊ตฌํ•œ๋‹ค / 2+1์„ 3์„ธํŠธ ๊ตฌ๋งคํ•˜๋ฉด ๋ฌด๋ฃŒ๋กœ ๋ฐ›๋Š”๊ฑด 3๊ฐœ") + void ํ”„๋กœ๋ชจ์…˜์œผ๋กœ_๋ฌด๋ฃŒ๊ตฌ๋งค๋˜๋Š”_์ œํ’ˆ์˜_๊ฐฏ์ˆ˜๋ฅผ_๊ตฌํ•œ๋‹ค() { + int cokeCount = 10; //์ฝœ๋ผ๋Š” 2+1 ํ–‰์‚ฌ์ค‘ / ํ–‰์‚ฌ์ œํ’ˆ ๊ตฌ๋งค๊ฐ€๋Šฅ ๊ฐœ์ˆ˜ = 9 -> ์ฆ‰ 3์„ธํŠธ์ด๋ฏ€๋กœ 3๊ฐœ ๋ฐ˜ํ™˜ + int instantCupRamenCount = 10; //์ปต๋ผ๋ฉด์€ 1+1 ํ–‰์‚ฌ์ค‘ / ํ–‰์‚ฌ์ œํ’ˆ ๊ตฌ๋งค๊ฐ€๋Šฅ ๊ฐœ์ˆ˜ = 1 ์ฆ‰ 1+1๋„ ์•ˆ๋œ๋‹ค. 0๊ฐœ ๋ฐ˜ํ™˜ + + assertThat(buyer.calculatePromotionCount(new Product("์ฝœ๋ผ", cokeCount))).isEqualTo(3); + assertThat(buyer.calculatePromotionCount(new Product("์ปต๋ผ๋ฉด", instantCupRamenCount))).isEqualTo(0); + } + + @Test + @DisplayName("ํ”„๋กœ๋ชจ์…˜_ํ•œ์„ธํŠธ(ํ•œ๋ฌถ์Œ)์˜_๋“ค์–ด๊ฐ€๋Š”_์ œํ’ˆ๊ฐฏ์ˆ˜๋ฅผ_๊ตฌํ•œ๋‹ค / 2+1์ด๋ฉด ํ•œ ์„ธํŠธ์˜ 3 / 1+1์ด๋ฉด ํ•œ ์„ธํŠธ์— 2") + void ํ”„๋กœ๋ชจ์…˜_์„ธํŠธ์˜_๊ฐฏ์ˆ˜๋ฅผ_๊ตฌํ•œ๋‹ค() { + String product1 = "์ฝœ๋ผ"; // 2+1 ํ–‰์‚ฌ์ค‘ + String product2 = "์‚ฌ์ด๋‹ค"; // 2+1 ํ–‰์‚ฌ์ค‘ + String product3 = "์ปต๋ผ๋ฉด"; // 1+1 ํ–‰์‚ฌ์ค‘ + + assertThat(buyer.getPromotionSetSize(product1)).isEqualTo(3); + assertThat(buyer.getPromotionSetSize(product2)).isEqualTo(3); + assertThat(buyer.getPromotionSetSize(product3)).isEqualTo(2); + } + + @Test + @DisplayName("์•ˆ๊ฐ€์ ธ์˜จ_ํ”„๋กœ๋ชจ์…˜_์ œํ’ˆ์˜_๊ฐฏ์ˆ˜๋ฅผ_๊ตฌํ•œ๋‹ค / 2+1์ผ๋•Œ 5๊ฐœ๋ฅผ ์‚ฌ๋ฉด 1๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ์Œ") + void ์•ˆ๊ฐ€์ ธ์˜จ_ํ”„๋กœ๋ชจ์…˜_์ œํ’ˆ์˜_๊ฐฏ์ˆ˜๋ฅผ_๊ตฌํ•œ๋‹ค() { + assertThat(buyer.calculateBonus(2, 1, 3)).isEqualTo(0); + assertThat(buyer.calculateBonus(2, 1, 5)).isEqualTo(1); + assertThat(buyer.calculateBonus(1, 1, 3)).isEqualTo(1); + assertThat(buyer.calculateBonus(2, 1, 2)).isEqualTo(1); + assertThat(buyer.calculateBonus(1, 1, 4)).isEqualTo(0); + } + +} \ No newline at end of file
Java
๊ผผ๊ผผํ•œ ํ…Œ์ŠคํŠธ๊ฐ€ ์ธ์ƒ์ ์ด๋„ค์š”! ์ฒ˜์Œ assert๊ฐ€ ์‹คํŒจํ•˜๋ฉด, ์•„๋ž˜์— ์žˆ๋Š” assert๋Š” ํ™•์ธ์„ ๋ชป ํ•  ๊ฑฐ ๊ฐ™์•„์š”! `assertAll`ํ•จ์ˆ˜์— ๋Œ€ํ•ด์„œ๋„ ์•Œ์•„๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,357 @@ +package store; + +import static exception.Exception.EXCEED_QUANTITY; +import static exception.Exception.NON_EXIST_PRODUCT; +import static exception.Exception.WRONG_INPUT; +import static exception.Exception.throwException; +import static util.ProductValidator.INVALID_FORMAT; +import static view.InputView.handleRetryOnError; +import static view.OutputView.MEMBERSHIP_BUY; +import static view.OutputView.NOW; +import static view.OutputView.NO_PROMOTION_BUY; +import static view.OutputView.printMessage; + +import dto.Status; +import exception.Exception; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import view.InputView; +import view.OutputView; + +public class Buyer { + + private static final String PROMOTIONAL_SEPARATOR = "P_"; + private static final String PRODUCTS_FILE_NAME = "products.md"; + private static final String PROMOTION_FILE_NAME = "promotions.md"; + private static final String THANK_YOU_MORE_BUY = "\n๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"; + private static final String BLANK_SEPARATOR = "===================================="; + private static final String PROMOTION_SEPARATOR = "=============์ฆ\t\t์ •==============="; + private static final String DUPL_NAME = "[์ค‘๋ณต๋œ ์ œํ’ˆ๋ช…] : "; + private static final int MEMBERSHIP_MAX_DISCOUNT = 8000; + private final InputView inputView; + private final OutputView outputView; + private final LinkedHashMap<String, List<Product>> products; + private final Map<String, Promotion> promotions; + private Map<String, Integer> receiptMap; + private Status memberShip; + + public Buyer() { + this.inputView = new InputView(); + this.outputView = new OutputView(); + this.products = makeProducts(inputView.loadProducts(PRODUCTS_FILE_NAME)); + this.promotions = makePromotions(inputView.loadPromotions(PROMOTION_FILE_NAME)); + outputView.printProducts(products); + } + + public void makePrintProduct(LinkedHashMap<String, List<Product>> products) { + for (String key : products.keySet()) { + List<Product> productList = products.get(key); + if (productList.size() == 1 && productList.getFirst().getPromotion() != null) { + Product product = productList.getFirst(); + productList.add(new Product(product.getName(), product.getPrice(), 0)); + } + } + } + + + public LinkedHashMap<String, List<Product>> makeProducts(List<Product> products) { + LinkedHashMap<String, List<Product>> map = new LinkedHashMap<>(); + for (Product product : products) { + map.computeIfAbsent(product.getName(), k -> new ArrayList<>()) + .add(product); + } + makePrintProduct(map); + return map; + } + + public Map<String, Promotion> makePromotions(List<Promotion> promotions) { + HashMap<String, Promotion> map = new HashMap<>(); + for (Promotion promotion : promotions) { + map.put(promotion.getName(), promotion); + } + return map; + } + + public void buyProducts() { + initializationReceiptMap(); + List<Product> wantBuyProducts = inputBuyProduct(); + checkNotPromotionApply(wantBuyProducts); + applyMemberShip(); + printReceipt(wantBuyProducts); + realBuyProducts(wantBuyProducts); + } + + public void initializationReceiptMap() { + receiptMap = new HashMap<>(); + } + + public List<Product> inputBuyProduct() { + return handleRetryOnError(() -> { + List<Product> wantBuyProducts = inputView.readItem(); + checkDuplProductName(wantBuyProducts); + productNameCheck(wantBuyProducts); + checkPromotionApply(wantBuyProducts); + checkCanBuyQuantity(wantBuyProducts); + return wantBuyProducts; + }); + } + + public void checkDuplProductName(List<Product> wantBuyProducts) { + Set<String> uniqueNames = new HashSet<>(); + for (Product product : wantBuyProducts) { + String productName = product.getName(); + if (!uniqueNames.add(productName)) { + throwException(INVALID_FORMAT + DUPL_NAME + productName); + } + } + } + + public void productNameCheck(List<Product> wantBuyProducts) { + if (wantBuyProducts.isEmpty()) { + Exception.throwException(WRONG_INPUT); + } + for (Product wantBuyProduct : wantBuyProducts) { + if (products.get(wantBuyProduct.getName()) == null) { + Exception.throwException(NON_EXIST_PRODUCT); + } + } + } + + public void realBuyProducts(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + int quantity = wantBuyProduct.getQuantity(); + Product firstProduct = products.get(wantBuyProduct.getName()).getFirst(); + if (withinQuantity(firstProduct, quantity)) { + continue; + } + int restQuantity = quantity - firstProduct.getQuantity(); + firstProduct.subtractQuantity(firstProduct.getQuantity()); + products.get(wantBuyProduct.getName()).get(1).subtractQuantity(restQuantity); + } + } + + public boolean withinQuantity(Product firstProduct, int quantity) { + boolean exceed = false; + if (firstProduct.getQuantity() >= quantity) { + firstProduct.subtractQuantity(quantity); + return true; + } + return exceed; + } + + public void wantContinue() { + while (true) { + printMessage(THANK_YOU_MORE_BUY); + Status status = inputView.wantContinue(); + if (status == Status.Y) { + convenienceContinue(); + } + break; + } + } + + public void convenienceContinue() { + printMessage(null); + outputView.printProducts(products); + buyProducts(); + wantContinue(); + } + + public void printReceipt(List<Product> wantBuyProducts) { + int totalBuyCount = printFirstReceipt(wantBuyProducts); + printPresentReceipt(wantBuyProducts); + printFinalReceipt(totalBuyCount); + } + + + public void printFinalReceipt(int totalBuyCount) { + printMessage(BLANK_SEPARATOR); + int totalMoney = totalMoney(); + int promotionDiscount = promotionDiscount(); + int memberShipDiscount = memberShipDiscount(); + outputView.printFinalReceipt(totalBuyCount, totalMoney, promotionDiscount, memberShipDiscount); + } + + + public int memberShipDiscount() { + int memberShipMoney = 0; + if (memberShip != Status.Y) { + return memberShipMoney; + } + for (String key : receiptMap.keySet()) { + if (!key.startsWith(PROMOTIONAL_SEPARATOR)) { + memberShipMoney += (int) (receiptMap.get(key) * 0.3); + } + } + return Math.min(memberShipMoney, MEMBERSHIP_MAX_DISCOUNT); + } + + public int promotionDiscount() { + int promotionDiscount = 0; + ArrayList<String> removes = new ArrayList<>(); + for (String key : receiptMap.keySet()) { + if (key.startsWith(PROMOTIONAL_SEPARATOR)) { + promotionDiscount += receiptMap.get(key); + removes.add(key.substring(key.indexOf(PROMOTIONAL_SEPARATOR) + PROMOTIONAL_SEPARATOR.length())); + } + } + removeReceiptMap(removes); + return promotionDiscount; + } + + public void removeReceiptMap(List<String> removes) { + for (String remove : removes) { + receiptMap.remove(remove); + } + } + + public int totalMoney() { + int totalMoney = 0; + for (String key : receiptMap.keySet()) { + if (!key.startsWith(PROMOTIONAL_SEPARATOR)) { + totalMoney += receiptMap.get(key); + } + } + return totalMoney; + } + + public void printPresentReceipt(List<Product> wantBuyProducts) { + printMessage(PROMOTION_SEPARATOR); + for (Product wantBuyProduct : wantBuyProducts) { + Promotion promotion = promotions.get(products.get(wantBuyProduct.getName()).getFirst().getPromotion()); + if (products.get(wantBuyProduct.getName()).size() == 1 || !promotion.checkPromotionDate()) { + continue; + } + printProvenPresent(wantBuyProduct); + } + } + + public void printProvenPresent(Product wantBuyProduct) { + int promotionCount = calculatePromotionCount(wantBuyProduct); + if (promotionCount > 0) { + outputView.printPresentReceipt(wantBuyProduct, promotionCount); + receiptMap.put(PROMOTIONAL_SEPARATOR + wantBuyProduct.getName(), + promotionCount * products.get(wantBuyProduct.getName()).getFirst().getPrice()); + } + } + + public int printFirstReceipt(List<Product> wantBuyProducts) { + outputView.printFirstReceipt(); + int totalBuyCount = calculateTotalBuyCount(wantBuyProducts); + return totalBuyCount; + } + + public int calculateTotalBuyCount(List<Product> wantBuyProducts) { + int totalBuyCount = 0; + for (Product wantBuyProduct : wantBuyProducts) { + Product findProduct = products.get(wantBuyProduct.getName()).getFirst(); + int totalPrice = outputView.printPurchaseReceipt(findProduct, wantBuyProduct); + receiptMap.put(findProduct.getName(), totalPrice); + totalBuyCount += wantBuyProduct.getQuantity(); + } + return totalBuyCount; + } + + + public void applyMemberShip() { + OutputView.printMessage(MEMBERSHIP_BUY); + this.memberShip = inputView.memberShipApply(); + } + + public void checkCanBuyQuantity(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + int count = 0; + List<Product> getProducts = products.get(wantBuyProduct.getName()); + for (Product p : getProducts) { + count += p.getQuantity(); + } + if (wantBuyProduct.getQuantity() > count) { + Exception.throwException(EXCEED_QUANTITY); + } + } + } + + public void checkNotPromotionApply(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + if (products.get(wantBuyProduct.getName()).size() == 1) { + continue; + } + int notPromotionCount = calculateNotPromotionCount(wantBuyProduct); + questionPromotionApply(wantBuyProduct, notPromotionCount); + } + } + + public void questionPromotionApply(Product wantBuyProduct, int notPromotionCount) { + if (notPromotionCount > 0) { + printMessage(NOW + wantBuyProduct.getName() + " " + notPromotionCount + NO_PROMOTION_BUY); + inputView.promotionApply(wantBuyProduct, notPromotionCount); + } + } + + public int calculateNotPromotionCount(Product wantBuyProduct) { + int promotionSetSize = getPromotionSetSize(wantBuyProduct.getName()); + int canBuyPromotionCount = canBuyPromotionProductCount(wantBuyProduct.getName()); + int promotionCount = (canBuyPromotionCount / promotionSetSize) * promotionSetSize; + return wantBuyProduct.getQuantity() - promotionCount; + } + + public int calculatePromotionCount(Product wantBuyProduct) { + int promotionSetSize = getPromotionSetSize(wantBuyProduct.getName()); + return Math.min(products.get(wantBuyProduct.getName()).getFirst().getQuantity() / promotionSetSize, + wantBuyProduct.getQuantity() / promotionSetSize); + } + + public int canBuyPromotionProductCount(String productName) { + return products.get(productName).getFirst().getQuantity(); + } + + public int getPromotionSetSize(String productName) { // 2+1์ผ ๊ฒฝ์šฐ ํ•œ set size๋Š” 3 / 1+1์ผ๋•Œ๋Š” 2 + String promotionName = products.get(productName).getFirst().getPromotion(); + int setSize = 0; + Promotion promotion = promotions.get(promotionName); + setSize = promotion.getBuy() + promotion.getGet(); + return setSize; + } + + + public void checkPromotionApply(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + Promotion promotion = promotions.get(products.get(wantBuyProduct.getName()).getFirst().getPromotion()); + if (promotion != null && promotion.checkPromotionDate()) { + int notBringBonus = calculateBonus(promotion.getBuy(), promotion.getGet(), + wantBuyProduct.getQuantity()); + bringBonus(wantBuyProduct, notBringBonus); + } + } + } + + public int calculateBonus(int buy, int get, int purchasedCount) { + int bonusCount = 0; + if (buy == purchasedCount) { + bonusCount = get; + return bonusCount; + } + if (purchasedCount > buy && purchasedCount % (buy + get) == buy) { + bonusCount = get; + return bonusCount; + } + return bonusCount; + } + + public void bringBonus(Product wantBuyProduct, int notBringBonus) { + if (notBringBonus > 0) { + outputView.printBringPromotion(wantBuyProduct.getName(), notBringBonus); + inputView.addPromotion(wantBuyProduct, notBringBonus); + } + } + + public LinkedHashMap<String, List<Product>> getProducts() { + LinkedHashMap<String, List<Product>> copiedProdcuts = new LinkedHashMap<>(this.products); + return copiedProdcuts; + } +}
Java
while-true์™€ ์žฌ๊ท€๋ฅผ ๊ฐ™์ด ์‚ฌ์šฉํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”? ํ•˜๋‚˜๋งŒ ์žˆ์–ด๋„ ๋  ๊ฑฐ ๊ฐ™์•„์š”!
@@ -1 +1,78 @@ # java-convenience-store-precourse + +## ๊ตฌํ˜„ํ•ญ๋ชฉ + +### ์ž…์ถœ๋ ฅ + +- ์˜์ˆ˜์ฆ + - ๊ตฌ๋งค ์ƒํ’ˆ ๋‚ด์—ญ : ๊ตฌ๋งคํ•œ ์ƒํ’ˆ๋ช…, ์ˆ˜๋Ÿ‰, ๊ฐ€๊ฒฉ + - ์ฆ์ • ์ƒํ’ˆ ๋‚ด์—ญ : ํ”„๋กœ๋ชจ์…˜์— ๋”ฐ๋ผ ๋ฌด๋ฃŒ๋กœ ์ œ๊ณต๋œ ์ฆ์ • ์ƒํ’ˆ์˜ ๋ชฉ๋ก + - ๊ธˆ์•ก ์ •๋ณด + - ์ด๊ตฌ๋งค์•ก: ๊ตฌ๋งคํ•œ ์ƒํ’ˆ์˜ ์ด ๊ธˆ์•ก + - ์ด๊ตฌ๋งค์ˆ˜๋Ÿ‰ : ๊ตฌ๋งคํ•œ ์ƒํ’ˆ์˜ ์ด ์ˆ˜๋Ÿ‰ + - ํ–‰์‚ฌํ• ์ธ: ํ”„๋กœ๋ชจ์…˜์— ์˜ํ•ด ํ• ์ธ๋œ ๊ธˆ์•ก + - ๋ฉค๋ฒ„์‹ญํ• ์ธ: ๋ฉค๋ฒ„์‹ญ์— ์˜ํ•ด ์ถ”๊ฐ€๋กœ ํ• ์ธ๋œ ๊ธˆ์•ก(์ตœ๋Œ€ 8000์›) + - ๋‚ด์‹ค๋ˆ: ์ตœ์ข… ๊ฒฐ์ œ ๊ธˆ์•ก(์ด๊ตฌ๋งค์•ก์—์„œ ํ• ์ธ ๊ฐ€๊ฒฉ์„ ๋บธ ๊ธˆ์•ก) + + * ์˜์ˆ˜์ฆ์˜ ๊ตฌ์„ฑ ์š”์†Œ๋ฅผ ๋ณด๊ธฐ ์ข‹๊ฒŒ ์ •๋ ฌ + * ์ˆ˜๋Ÿ‰ ์—†์„ ์‹œ "์žฌ๊ณ  ์—†์Œ" ์ถœ๋ ฅ + * ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์ด ์žˆ๋Š” ๊ฒฝ์šฐ ๋™์ผํ•œ ์ œํ’ˆ๋ช…์˜ ์ผ๋ฐ˜ ์ƒํ’ˆ ์žฌ๊ณ ๊ฐ€ ์—†์œผ๋ฉด ์ผ๋ฐ˜์ƒํ’ˆ์—๋„ "์žฌ๊ณ  ์—†์Œ" ์ถœ๋ ฅ +- ์ƒํ’ˆ์ž…๋ ฅ + - ์ƒํ’ˆ ์ž…๋ ฅ ํ˜•์‹์ด [์ œํ’ˆ๋ช…:๊ฐฏ์ˆ˜] ๋กœ ๋“ค์–ด์™”๋Š”์ง€ ํ™•์ธ + +### ์ƒํ’ˆ + +* ์ƒํ’ˆ promotion์ด "null" string์œผ๋กœ ๋“ค์–ด์˜ฌ ๊ฒฝ์šฐ ๋นˆ ๊ฐ’์œผ๋กœ ์ฒ˜๋ฆฌ + +### ์žฌ๊ณ ๊ด€๋ฆฌ + +* ์žฌ๊ณ  ์ˆ˜๋Ÿ‰ ํŒŒ์•…ํ•˜์—ฌ ๊ฒฐ์ œ ๊ฐ€๋Šฅ ์—ฌ๋ถ€ ํ™•์ธ +* ์ƒํ’ˆ ๊ตฌ๋งค ์‹œ ์žฌ๊ณ  ์ฐจ๊ฐ + +### ํ”„๋กœ๋ชจ์…˜(n๊ฐœ ๊ตฌ๋งค ์‹œ 1๊ฐœ ๋ฌด๋ฃŒ ์ฆ์ •) + +* ์˜ค๋Š˜ ๋‚ ์งœ๊ฐ€ ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„ ์ด๋‚ด์ธ์ง€ ํ™•์ธ +* ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธ(์žฌ๊ณ  ์—†์„ ์‹œ ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ ๋ถˆ๊ฐ€) +* ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๋ฅผ ์šฐ์„ ์ ์œผ๋กœ ์ฐจ๊ฐ +* ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ์ด ๊ฐ€๋Šฅํ•œ ์ƒํ’ˆ์ผ๋•Œ ํ”„๋กœ๋ชจ์…˜ ์กฐ๊ฑด ์ˆ˜๋Ÿ‰๋ณด๋‹ค ์ ๊ฒŒ ๊ฐ€์ ธ์˜จ๊ฒฝ์šฐ + ์ถ”๊ฐ€ ํ•„์š”์ˆ˜๋Ÿ‰ ์•ˆ๋‚ด + * Y ์ž…๋ ฅ ์‹œ ์ฆ์ • ๋ฐ›์„ ์ˆ˜ ์žˆ๋Š” ์ƒํ’ˆ ์ถ”๊ฐ€ +* ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ  ๋ถ€์กฑ์œผ๋กœ ์ผ๋ถ€์ˆ˜๋Ÿ‰์„ ํ˜œํƒ ์—†์ด ๊ฒฐ์ œ ์‹œ ์ •๊ฐ€๋กœ ๊ฒฐ์ œํ• ์ง€ ์—ฌ๋ถ€ ์•ˆ๋‚ด + * ex)ํ˜„์žฌ {์ƒํ’ˆ๋ช…} {์ˆ˜๋Ÿ‰}๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N) + * N ์ž…๋ ฅ ์‹œ ์ •๊ฐ€๋กœ ๊ฒฐ์ œํ•ด์•ผํ•˜๋Š” ์ˆ˜๋Ÿ‰๋งŒํผ ์ œ์™ธ ํ›„ ๊ฒฐ์ œ ์ง„ํ–‰ +* ํ”„๋กœ๋ชจ์…˜ ์ƒํ’ˆ์˜ ๊ตฌ๋งค๋Ÿ‰์„ ํŒŒ์•…ํ•˜์—ฌ ์•ˆ๊ฐ€์ ธ์˜จ ๋ฌด๋ฃŒ์ˆ˜๋Ÿ‰์„ ๊ณ„์‚ฐํ•˜๋Š” ํ•จ์ˆ˜ ex) 2+1์ผ๋•Œ 5๊ฐœ ์‚ฌ๋ฉด 1๊ฐœ ๋ฌด๋ฃŒ๊ตฌ๋งค ๊ฐ€๋Šฅ + +### ๋ฉค๋ฒ„์‹ญ + +* ๋ฉค๋ฒ„์‹ญ ํšŒ์›์€ ํ”„๋กœ๋ชจ์…˜ ๋ฏธ์ ์šฉ ๊ธˆ์•ก์˜ 30% ํ• ์ธ +* ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ ํ›„ ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ์ด ๋˜์ง€์•Š์€ ์ œํ’ˆ ๊ฒฐ์ œ์•ก์— ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ ์šฉ +* ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ตœ๋Œ€ ํ•œ๋„๋Š” 8000์› +* ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์—ฌ๋ถ€ ๋ฌผ์–ด๋ณด๊ณ  Y ์ธ ๊ฒฝ์šฐ์—๋งŒ ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ ์šฉ + +### ๊ธฐํƒ€ + +* mdํŒŒ์ผ ์ฝ์–ด์˜ค๋Š” ๊ธฐ๋Šฅ(์ƒํ’ˆ ๋ชฉ๋ก, ํ–‰์‚ฌ ๋ชฉ๋ก) +* ์‹คํŒจํ•  ๊ฒฝ์šฐ ์‹คํŒจ๋ฅผ ํ•œ ํ•ด๋‹น ์งˆ๋ฌธ๋ถ€ํ„ฐ ์žฌ์‹œ์ž‘ํ•˜๋Š” ๊ธฐ๋Šฅ +* ์ƒํ’ˆ ๊ตฌ๋งค๋ถ€ํ„ฐ ์˜์ˆ˜์ฆ ์ถœ๋ ฅ๊นŒ์ง€(ํ”„๋กœ๊ทธ๋žจ 1์‚ฌ์ดํด) ์ˆ˜ํ–‰ ํ›„ ์žฌ๊ตฌ๋งค์›ํ• ์‹œ ์ œํ’ˆ์ถœ๋ ฅ๋ถ€ํ„ฐ ์žฌ์‹œ์ž‘ํ•˜๋Š” ๊ธฐ๋Šฅ + +### ์˜ˆ์™ธ์ฒ˜๋ฆฌ + +* ํ˜•์‹ : ์—๋Ÿฌ๋Š” [ERROR]๋กœ ์‹œ์ž‘ +* ์ƒํ’ˆ ์ž…๋ ฅ ํ˜•์‹์ด [์ œํ’ˆ๋ช…:๊ฐฏ์ˆ˜] ํ˜•์‹์œผ๋กœ ๋“ค์–ด์˜ค์ง€ ์•Š๋Š” ๊ฒฝ์šฐ +* ์—ฌ๋Ÿฌ๊ฐœ์ผ ๊ฒฝ์šฐ ,๋กœ ๊ตฌ๋ถ„๋˜์–ด ๋“ค์–ด์˜ค์ง€ ์•Š๋Š” ๊ฒฝ์šฐ +* ๊ฐฏ์ˆ˜๊ฐ€ ์ž์—ฐ์ˆ˜๊ฐ’์ด ์•„๋‹Œ ๊ฒฝ์šฐ +* ์ƒํ’ˆ๋ช…์ด ์ค‘๋ณต์œผ๋กœ ๋“ค์–ด์˜ค๋Š” ๊ฒฝ์šฐ +* ์ž…๋ ฅํ•œ ์ƒํ’ˆ๋ช…์ด ์‹ค์ œ ์ƒํ’ˆ์— ์—†๋Š” ์ด๋ฆ„์ผ ๊ฒฝ์šฐ +* ๊ฐฏ์ˆ˜๊ฐ€ int ๋ฒ”์œ„ ์ด๋‚ด๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ +* Y/N์œผ๋กœ ์ž…๋ ฅ๋ฐ›๋Š” ์งˆ๋ฌธ์˜ ๊ฒฝ์šฐ Y/N์ด ์•„๋‹Œ ๊ฒฝ์šฐ +* ์ œํ’ˆ์˜ ์žฌ๊ณ ์ˆ˜๋Ÿ‰๋ณด๋‹ค ๊ตฌ์ž…์ˆ˜๋Ÿ‰์œผ๋กœ ๋” ํฐ ๊ฐ’์„ ์ž…๋ ฅํ•œ ๊ฒฝ์šฐ + +## ํ”„๋กœ๊ทธ๋žจ ์š”๊ตฌ์‚ฌํ•ญ + +* else ์‚ฌ์šฉ ๊ธˆ์ง€ +* enum ์ ์šฉ +* ๋‹จ์œ„ ํ…Œ์ŠคํŠธ ์ž‘์„ฑ +* ํ•จ์ˆ˜ ๊ธธ์ด 10๋ผ์ธ ์ดํ•˜ +* ์ž…์ถœ๋ ฅ ๋ณ„๋„ ํด๋ž˜์Šค ๋ถ„๋ฆฌ (InputView, OutputView) +* ํ˜„์žฌ ๋‚ ์งœ์™€ ์‹œ๊ฐ„ -> DateTimes.now() ํ™œ์šฉ +* ์‚ฌ์šฉ์ž ์ž…๋ ฅ -> Console.readLine() ํ™œ์šฉ \ No newline at end of file
Unknown
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค^&^
@@ -0,0 +1,21 @@ +package util; + +import exception.Exception; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ProductValidator { + + private static final String PRODUCT_PATTERN = "^\\[([a-zA-Z๊ฐ€-ํžฃ]+)-([1-9]\\d*)\\]$"; + public static final String INVALID_FORMAT = "์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + + public static boolean isValidProductFormat(String input) { + Pattern pattern = Pattern.compile(PRODUCT_PATTERN); + Matcher matcher = pattern.matcher(input); + boolean result = matcher.matches(); + if (!result) { + Exception.throwException(INVALID_FORMAT); + } + return result; + } +}
Java
์˜ค ์ด๋ถ€๋ถ„์€ ์‚ฌ์‹ค ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด return๋ฌธ์ด ํ•„์š”์—†์ง€๋งŒ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š์œผ๋ฉด ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š”๊ฒƒ์ด ํ•„์š”ํ• ๊ฒƒ ๊ฐ™์•„์„œ ๋„ฃ์–ด๋‘์—ˆ์Šต๋‹ˆ๋‹ค. ์—„์ฒญ ์˜ˆ๋ฆฌํ•˜์‹œ๋„ค์š”...ใ…Žใ…Ž ์ƒ๊ฐ์„ ํ•ด๋ณด๋‹ˆ ๋ฐ˜ํ™˜๊ฐ’์„ ์—†์• ๋Š” ๋ฐฉํ–ฅ์ด ๋” ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค!! ๋ง์”€ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,139 @@ +package view; + +import static exception.Exception.EXCEED_QUANTITY; +import static exception.Exception.WRONG_INPUT; + +import camp.nextstep.edu.missionutils.Console; +import dto.Status; +import exception.Exception; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import store.Application; +import store.Product; +import store.Promotion; +import util.ProductValidator; + +public class InputView { + + private static final String WANT_BUY_PRODUCT = "\n๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"; + + public List<Product> readItem() { + return handleRetryOnError(() -> { + String[] items = preWorkBuyProduct(); + List<Product> buyProducts = new ArrayList<>(); + for (String item : items) { + ProductValidator.isValidProductFormat(item); + addBuyProduct(item, buyProducts); + } + return buyProducts; + }); + } + + public String[] preWorkBuyProduct() { + System.out.println(WANT_BUY_PRODUCT); + String input = Console.readLine().trim(); + return input.split(","); + } + + public void addBuyProduct(String item, List<Product> buyProducts) { + String cleanInput = item.replace("[", "").replace("]", ""); + String[] nameAndQuantity = cleanInput.split("-"); + String name = nameAndQuantity[0]; + int quantity = 0; + try { + quantity = Integer.parseInt(nameAndQuantity[1]); + } catch (java.lang.Exception e) { + Exception.throwException(EXCEED_QUANTITY); + } + buyProducts.add(new Product(name, quantity)); + } + + public <T> List<T> loadItems(String fileName, Function<String, T> mapper) { + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(Application.class.getClassLoader().getResourceAsStream(fileName)))) { + return reader.lines() + .skip(1) // ์ฒซ ๋ฒˆ์งธ ์ค„ ๊ฑด๋„ˆ๋›ฐ๊ธฐ + .map(mapper) + .collect(Collectors.toList()); + } catch (IOException e) { + throw new RuntimeException("[ERROR] reading file: " + fileName, e); + } + } + + public List<Product> loadProducts(String fileName) { + return loadItems(fileName, line -> { + String[] productInfo = line.split(","); + int price = Integer.parseInt(productInfo[1]); + int quantity = Integer.parseInt(productInfo[2]); + String promotion = productInfo[3]; + if ("null".equals(promotion)) { + promotion = null; + } + return new Product(productInfo[0], price, quantity, promotion); + }); + } + + public List<Promotion> loadPromotions(String fileName) { + return loadItems(fileName, line -> { + String[] promotionInfo = line.split(","); + String name = promotionInfo[0]; + int buy = Integer.parseInt(promotionInfo[1]); + int get = Integer.parseInt(promotionInfo[2]); + LocalDate startDate = LocalDate.parse(promotionInfo[3]); + LocalDate endDate = LocalDate.parse(promotionInfo[4]); + return new Promotion(name, buy, get, startDate, endDate); + }); + } + + public void addPromotion(Product wantBuyProduct, int notBringBonus) { + String input = checkInputYorN(); + if (Status.Y == Status.checkStatusInput(input)) { + wantBuyProduct.addQuantity(notBringBonus); + } + } + + public void promotionApply(Product wantBuyProduct, int notPromotionCount) { + String input = checkInputYorN(); + if (Status.N == Status.checkStatusInput(input)) { + wantBuyProduct.subtractQuantity(notPromotionCount); + } + } + + public Status memberShipApply() { + String input = checkInputYorN(); + return Status.checkStatusInput(input); + } + + public String checkInputYorN() { + return handleRetryOnError(() -> { + String input = Console.readLine().trim(); + if (!"Y".equalsIgnoreCase(input) && !"N".equalsIgnoreCase(input)) { + Exception.throwException(WRONG_INPUT); + } + return input; + }); + } + + public Status wantContinue() { + String input = checkInputYorN(); + return Status.checkStatusInput(input); + } + + public static <T> T handleRetryOnError(Supplier<T> method) { + try { + return method.get(); + } catch (IllegalArgumentException e) { + OutputView.printMessage(e.getMessage()); + return handleRetryOnError(method); + } + } + + +} \ No newline at end of file
Java
์ œ๊ฐ€ ์ƒ๊ฐํ–ˆ๋˜๊ฒƒ์€ ๋กœ์ง์ƒ ์ € ๋ถ€๋ถ„์— ๋“ค์–ด๊ฐˆ๊ฒƒ์€ ์ˆซ์ž๋งŒ ๊ฐ€๋Šฅํ•œ๋ฐ(์•ž์—์„œ ์ •๊ทœ์‹์œผ๋กœ ๊ฑฐ๋ฅด๊ณ ์žˆ์Œ) Integer.parseInt์—์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค๋ฉด ์ˆซ์ž์ด๊ธฐ๋Š” ์ˆซ์ž์ธ๋ฐ int๊ฐ’์„ ๋ฒ—์–ด๋‚˜๋Š” ์ˆซ์ž๋ผ๊ณ  ์ƒ๊ฐํ–ˆ๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค!! ์˜ˆ์™ธ์ฒ˜๋ฆฌ๊ฐ€ ์ •ํ™•ํ•˜์ง€ ๋ชปํ–ˆ๋˜ ๊ฒƒ ๊ฐ™๋„ค์š”!! ๋ง์”€ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,139 @@ +package view; + +import static exception.Exception.EXCEED_QUANTITY; +import static exception.Exception.WRONG_INPUT; + +import camp.nextstep.edu.missionutils.Console; +import dto.Status; +import exception.Exception; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import store.Application; +import store.Product; +import store.Promotion; +import util.ProductValidator; + +public class InputView { + + private static final String WANT_BUY_PRODUCT = "\n๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"; + + public List<Product> readItem() { + return handleRetryOnError(() -> { + String[] items = preWorkBuyProduct(); + List<Product> buyProducts = new ArrayList<>(); + for (String item : items) { + ProductValidator.isValidProductFormat(item); + addBuyProduct(item, buyProducts); + } + return buyProducts; + }); + } + + public String[] preWorkBuyProduct() { + System.out.println(WANT_BUY_PRODUCT); + String input = Console.readLine().trim(); + return input.split(","); + } + + public void addBuyProduct(String item, List<Product> buyProducts) { + String cleanInput = item.replace("[", "").replace("]", ""); + String[] nameAndQuantity = cleanInput.split("-"); + String name = nameAndQuantity[0]; + int quantity = 0; + try { + quantity = Integer.parseInt(nameAndQuantity[1]); + } catch (java.lang.Exception e) { + Exception.throwException(EXCEED_QUANTITY); + } + buyProducts.add(new Product(name, quantity)); + } + + public <T> List<T> loadItems(String fileName, Function<String, T> mapper) { + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(Application.class.getClassLoader().getResourceAsStream(fileName)))) { + return reader.lines() + .skip(1) // ์ฒซ ๋ฒˆ์งธ ์ค„ ๊ฑด๋„ˆ๋›ฐ๊ธฐ + .map(mapper) + .collect(Collectors.toList()); + } catch (IOException e) { + throw new RuntimeException("[ERROR] reading file: " + fileName, e); + } + } + + public List<Product> loadProducts(String fileName) { + return loadItems(fileName, line -> { + String[] productInfo = line.split(","); + int price = Integer.parseInt(productInfo[1]); + int quantity = Integer.parseInt(productInfo[2]); + String promotion = productInfo[3]; + if ("null".equals(promotion)) { + promotion = null; + } + return new Product(productInfo[0], price, quantity, promotion); + }); + } + + public List<Promotion> loadPromotions(String fileName) { + return loadItems(fileName, line -> { + String[] promotionInfo = line.split(","); + String name = promotionInfo[0]; + int buy = Integer.parseInt(promotionInfo[1]); + int get = Integer.parseInt(promotionInfo[2]); + LocalDate startDate = LocalDate.parse(promotionInfo[3]); + LocalDate endDate = LocalDate.parse(promotionInfo[4]); + return new Promotion(name, buy, get, startDate, endDate); + }); + } + + public void addPromotion(Product wantBuyProduct, int notBringBonus) { + String input = checkInputYorN(); + if (Status.Y == Status.checkStatusInput(input)) { + wantBuyProduct.addQuantity(notBringBonus); + } + } + + public void promotionApply(Product wantBuyProduct, int notPromotionCount) { + String input = checkInputYorN(); + if (Status.N == Status.checkStatusInput(input)) { + wantBuyProduct.subtractQuantity(notPromotionCount); + } + } + + public Status memberShipApply() { + String input = checkInputYorN(); + return Status.checkStatusInput(input); + } + + public String checkInputYorN() { + return handleRetryOnError(() -> { + String input = Console.readLine().trim(); + if (!"Y".equalsIgnoreCase(input) && !"N".equalsIgnoreCase(input)) { + Exception.throwException(WRONG_INPUT); + } + return input; + }); + } + + public Status wantContinue() { + String input = checkInputYorN(); + return Status.checkStatusInput(input); + } + + public static <T> T handleRetryOnError(Supplier<T> method) { + try { + return method.get(); + } catch (IllegalArgumentException e) { + OutputView.printMessage(e.getMessage()); + return handleRetryOnError(method); + } + } + + +} \ No newline at end of file
Java
๋ฌด์—‡์ธ๊ฐ€ ์ฝ์–ด์˜ค๊ฑฐ๋‚˜ ์ž…๋ ฅ์„ ๋ฐ›๊ฑฐ๋‚˜ ํ•˜๋Š” ๋ถ€๋ถ„์€ ๋‹ค inputView์—์„œ ์ฒ˜๋ฆฌํ•˜๋Š”๊ฒŒ ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค!! ์ง€๊ธˆ ์ƒ๊ฐํ•ด๋ณด๋‹ˆ ๋”ฐ๋กœ ๋ถ„๋ฆฌํ•ด๋„ ๊ดœ์ฐฎ๊ฒ ๋„ค์š”! ๋ง์”€ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!!
@@ -0,0 +1,139 @@ +package view; + +import static exception.Exception.EXCEED_QUANTITY; +import static exception.Exception.WRONG_INPUT; + +import camp.nextstep.edu.missionutils.Console; +import dto.Status; +import exception.Exception; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import store.Application; +import store.Product; +import store.Promotion; +import util.ProductValidator; + +public class InputView { + + private static final String WANT_BUY_PRODUCT = "\n๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"; + + public List<Product> readItem() { + return handleRetryOnError(() -> { + String[] items = preWorkBuyProduct(); + List<Product> buyProducts = new ArrayList<>(); + for (String item : items) { + ProductValidator.isValidProductFormat(item); + addBuyProduct(item, buyProducts); + } + return buyProducts; + }); + } + + public String[] preWorkBuyProduct() { + System.out.println(WANT_BUY_PRODUCT); + String input = Console.readLine().trim(); + return input.split(","); + } + + public void addBuyProduct(String item, List<Product> buyProducts) { + String cleanInput = item.replace("[", "").replace("]", ""); + String[] nameAndQuantity = cleanInput.split("-"); + String name = nameAndQuantity[0]; + int quantity = 0; + try { + quantity = Integer.parseInt(nameAndQuantity[1]); + } catch (java.lang.Exception e) { + Exception.throwException(EXCEED_QUANTITY); + } + buyProducts.add(new Product(name, quantity)); + } + + public <T> List<T> loadItems(String fileName, Function<String, T> mapper) { + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(Application.class.getClassLoader().getResourceAsStream(fileName)))) { + return reader.lines() + .skip(1) // ์ฒซ ๋ฒˆ์งธ ์ค„ ๊ฑด๋„ˆ๋›ฐ๊ธฐ + .map(mapper) + .collect(Collectors.toList()); + } catch (IOException e) { + throw new RuntimeException("[ERROR] reading file: " + fileName, e); + } + } + + public List<Product> loadProducts(String fileName) { + return loadItems(fileName, line -> { + String[] productInfo = line.split(","); + int price = Integer.parseInt(productInfo[1]); + int quantity = Integer.parseInt(productInfo[2]); + String promotion = productInfo[3]; + if ("null".equals(promotion)) { + promotion = null; + } + return new Product(productInfo[0], price, quantity, promotion); + }); + } + + public List<Promotion> loadPromotions(String fileName) { + return loadItems(fileName, line -> { + String[] promotionInfo = line.split(","); + String name = promotionInfo[0]; + int buy = Integer.parseInt(promotionInfo[1]); + int get = Integer.parseInt(promotionInfo[2]); + LocalDate startDate = LocalDate.parse(promotionInfo[3]); + LocalDate endDate = LocalDate.parse(promotionInfo[4]); + return new Promotion(name, buy, get, startDate, endDate); + }); + } + + public void addPromotion(Product wantBuyProduct, int notBringBonus) { + String input = checkInputYorN(); + if (Status.Y == Status.checkStatusInput(input)) { + wantBuyProduct.addQuantity(notBringBonus); + } + } + + public void promotionApply(Product wantBuyProduct, int notPromotionCount) { + String input = checkInputYorN(); + if (Status.N == Status.checkStatusInput(input)) { + wantBuyProduct.subtractQuantity(notPromotionCount); + } + } + + public Status memberShipApply() { + String input = checkInputYorN(); + return Status.checkStatusInput(input); + } + + public String checkInputYorN() { + return handleRetryOnError(() -> { + String input = Console.readLine().trim(); + if (!"Y".equalsIgnoreCase(input) && !"N".equalsIgnoreCase(input)) { + Exception.throwException(WRONG_INPUT); + } + return input; + }); + } + + public Status wantContinue() { + String input = checkInputYorN(); + return Status.checkStatusInput(input); + } + + public static <T> T handleRetryOnError(Supplier<T> method) { + try { + return method.get(); + } catch (IllegalArgumentException e) { + OutputView.printMessage(e.getMessage()); + return handleRetryOnError(method); + } + } + + +} \ No newline at end of file
Java
ใ…Žใ…Ž๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!! ํญํ’๊ฒ€์ƒ‰์˜ ํ”์ ..
@@ -0,0 +1,357 @@ +package store; + +import static exception.Exception.EXCEED_QUANTITY; +import static exception.Exception.NON_EXIST_PRODUCT; +import static exception.Exception.WRONG_INPUT; +import static exception.Exception.throwException; +import static util.ProductValidator.INVALID_FORMAT; +import static view.InputView.handleRetryOnError; +import static view.OutputView.MEMBERSHIP_BUY; +import static view.OutputView.NOW; +import static view.OutputView.NO_PROMOTION_BUY; +import static view.OutputView.printMessage; + +import dto.Status; +import exception.Exception; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import view.InputView; +import view.OutputView; + +public class Buyer { + + private static final String PROMOTIONAL_SEPARATOR = "P_"; + private static final String PRODUCTS_FILE_NAME = "products.md"; + private static final String PROMOTION_FILE_NAME = "promotions.md"; + private static final String THANK_YOU_MORE_BUY = "\n๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"; + private static final String BLANK_SEPARATOR = "===================================="; + private static final String PROMOTION_SEPARATOR = "=============์ฆ\t\t์ •==============="; + private static final String DUPL_NAME = "[์ค‘๋ณต๋œ ์ œํ’ˆ๋ช…] : "; + private static final int MEMBERSHIP_MAX_DISCOUNT = 8000; + private final InputView inputView; + private final OutputView outputView; + private final LinkedHashMap<String, List<Product>> products; + private final Map<String, Promotion> promotions; + private Map<String, Integer> receiptMap; + private Status memberShip; + + public Buyer() { + this.inputView = new InputView(); + this.outputView = new OutputView(); + this.products = makeProducts(inputView.loadProducts(PRODUCTS_FILE_NAME)); + this.promotions = makePromotions(inputView.loadPromotions(PROMOTION_FILE_NAME)); + outputView.printProducts(products); + } + + public void makePrintProduct(LinkedHashMap<String, List<Product>> products) { + for (String key : products.keySet()) { + List<Product> productList = products.get(key); + if (productList.size() == 1 && productList.getFirst().getPromotion() != null) { + Product product = productList.getFirst(); + productList.add(new Product(product.getName(), product.getPrice(), 0)); + } + } + } + + + public LinkedHashMap<String, List<Product>> makeProducts(List<Product> products) { + LinkedHashMap<String, List<Product>> map = new LinkedHashMap<>(); + for (Product product : products) { + map.computeIfAbsent(product.getName(), k -> new ArrayList<>()) + .add(product); + } + makePrintProduct(map); + return map; + } + + public Map<String, Promotion> makePromotions(List<Promotion> promotions) { + HashMap<String, Promotion> map = new HashMap<>(); + for (Promotion promotion : promotions) { + map.put(promotion.getName(), promotion); + } + return map; + } + + public void buyProducts() { + initializationReceiptMap(); + List<Product> wantBuyProducts = inputBuyProduct(); + checkNotPromotionApply(wantBuyProducts); + applyMemberShip(); + printReceipt(wantBuyProducts); + realBuyProducts(wantBuyProducts); + } + + public void initializationReceiptMap() { + receiptMap = new HashMap<>(); + } + + public List<Product> inputBuyProduct() { + return handleRetryOnError(() -> { + List<Product> wantBuyProducts = inputView.readItem(); + checkDuplProductName(wantBuyProducts); + productNameCheck(wantBuyProducts); + checkPromotionApply(wantBuyProducts); + checkCanBuyQuantity(wantBuyProducts); + return wantBuyProducts; + }); + } + + public void checkDuplProductName(List<Product> wantBuyProducts) { + Set<String> uniqueNames = new HashSet<>(); + for (Product product : wantBuyProducts) { + String productName = product.getName(); + if (!uniqueNames.add(productName)) { + throwException(INVALID_FORMAT + DUPL_NAME + productName); + } + } + } + + public void productNameCheck(List<Product> wantBuyProducts) { + if (wantBuyProducts.isEmpty()) { + Exception.throwException(WRONG_INPUT); + } + for (Product wantBuyProduct : wantBuyProducts) { + if (products.get(wantBuyProduct.getName()) == null) { + Exception.throwException(NON_EXIST_PRODUCT); + } + } + } + + public void realBuyProducts(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + int quantity = wantBuyProduct.getQuantity(); + Product firstProduct = products.get(wantBuyProduct.getName()).getFirst(); + if (withinQuantity(firstProduct, quantity)) { + continue; + } + int restQuantity = quantity - firstProduct.getQuantity(); + firstProduct.subtractQuantity(firstProduct.getQuantity()); + products.get(wantBuyProduct.getName()).get(1).subtractQuantity(restQuantity); + } + } + + public boolean withinQuantity(Product firstProduct, int quantity) { + boolean exceed = false; + if (firstProduct.getQuantity() >= quantity) { + firstProduct.subtractQuantity(quantity); + return true; + } + return exceed; + } + + public void wantContinue() { + while (true) { + printMessage(THANK_YOU_MORE_BUY); + Status status = inputView.wantContinue(); + if (status == Status.Y) { + convenienceContinue(); + } + break; + } + } + + public void convenienceContinue() { + printMessage(null); + outputView.printProducts(products); + buyProducts(); + wantContinue(); + } + + public void printReceipt(List<Product> wantBuyProducts) { + int totalBuyCount = printFirstReceipt(wantBuyProducts); + printPresentReceipt(wantBuyProducts); + printFinalReceipt(totalBuyCount); + } + + + public void printFinalReceipt(int totalBuyCount) { + printMessage(BLANK_SEPARATOR); + int totalMoney = totalMoney(); + int promotionDiscount = promotionDiscount(); + int memberShipDiscount = memberShipDiscount(); + outputView.printFinalReceipt(totalBuyCount, totalMoney, promotionDiscount, memberShipDiscount); + } + + + public int memberShipDiscount() { + int memberShipMoney = 0; + if (memberShip != Status.Y) { + return memberShipMoney; + } + for (String key : receiptMap.keySet()) { + if (!key.startsWith(PROMOTIONAL_SEPARATOR)) { + memberShipMoney += (int) (receiptMap.get(key) * 0.3); + } + } + return Math.min(memberShipMoney, MEMBERSHIP_MAX_DISCOUNT); + } + + public int promotionDiscount() { + int promotionDiscount = 0; + ArrayList<String> removes = new ArrayList<>(); + for (String key : receiptMap.keySet()) { + if (key.startsWith(PROMOTIONAL_SEPARATOR)) { + promotionDiscount += receiptMap.get(key); + removes.add(key.substring(key.indexOf(PROMOTIONAL_SEPARATOR) + PROMOTIONAL_SEPARATOR.length())); + } + } + removeReceiptMap(removes); + return promotionDiscount; + } + + public void removeReceiptMap(List<String> removes) { + for (String remove : removes) { + receiptMap.remove(remove); + } + } + + public int totalMoney() { + int totalMoney = 0; + for (String key : receiptMap.keySet()) { + if (!key.startsWith(PROMOTIONAL_SEPARATOR)) { + totalMoney += receiptMap.get(key); + } + } + return totalMoney; + } + + public void printPresentReceipt(List<Product> wantBuyProducts) { + printMessage(PROMOTION_SEPARATOR); + for (Product wantBuyProduct : wantBuyProducts) { + Promotion promotion = promotions.get(products.get(wantBuyProduct.getName()).getFirst().getPromotion()); + if (products.get(wantBuyProduct.getName()).size() == 1 || !promotion.checkPromotionDate()) { + continue; + } + printProvenPresent(wantBuyProduct); + } + } + + public void printProvenPresent(Product wantBuyProduct) { + int promotionCount = calculatePromotionCount(wantBuyProduct); + if (promotionCount > 0) { + outputView.printPresentReceipt(wantBuyProduct, promotionCount); + receiptMap.put(PROMOTIONAL_SEPARATOR + wantBuyProduct.getName(), + promotionCount * products.get(wantBuyProduct.getName()).getFirst().getPrice()); + } + } + + public int printFirstReceipt(List<Product> wantBuyProducts) { + outputView.printFirstReceipt(); + int totalBuyCount = calculateTotalBuyCount(wantBuyProducts); + return totalBuyCount; + } + + public int calculateTotalBuyCount(List<Product> wantBuyProducts) { + int totalBuyCount = 0; + for (Product wantBuyProduct : wantBuyProducts) { + Product findProduct = products.get(wantBuyProduct.getName()).getFirst(); + int totalPrice = outputView.printPurchaseReceipt(findProduct, wantBuyProduct); + receiptMap.put(findProduct.getName(), totalPrice); + totalBuyCount += wantBuyProduct.getQuantity(); + } + return totalBuyCount; + } + + + public void applyMemberShip() { + OutputView.printMessage(MEMBERSHIP_BUY); + this.memberShip = inputView.memberShipApply(); + } + + public void checkCanBuyQuantity(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + int count = 0; + List<Product> getProducts = products.get(wantBuyProduct.getName()); + for (Product p : getProducts) { + count += p.getQuantity(); + } + if (wantBuyProduct.getQuantity() > count) { + Exception.throwException(EXCEED_QUANTITY); + } + } + } + + public void checkNotPromotionApply(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + if (products.get(wantBuyProduct.getName()).size() == 1) { + continue; + } + int notPromotionCount = calculateNotPromotionCount(wantBuyProduct); + questionPromotionApply(wantBuyProduct, notPromotionCount); + } + } + + public void questionPromotionApply(Product wantBuyProduct, int notPromotionCount) { + if (notPromotionCount > 0) { + printMessage(NOW + wantBuyProduct.getName() + " " + notPromotionCount + NO_PROMOTION_BUY); + inputView.promotionApply(wantBuyProduct, notPromotionCount); + } + } + + public int calculateNotPromotionCount(Product wantBuyProduct) { + int promotionSetSize = getPromotionSetSize(wantBuyProduct.getName()); + int canBuyPromotionCount = canBuyPromotionProductCount(wantBuyProduct.getName()); + int promotionCount = (canBuyPromotionCount / promotionSetSize) * promotionSetSize; + return wantBuyProduct.getQuantity() - promotionCount; + } + + public int calculatePromotionCount(Product wantBuyProduct) { + int promotionSetSize = getPromotionSetSize(wantBuyProduct.getName()); + return Math.min(products.get(wantBuyProduct.getName()).getFirst().getQuantity() / promotionSetSize, + wantBuyProduct.getQuantity() / promotionSetSize); + } + + public int canBuyPromotionProductCount(String productName) { + return products.get(productName).getFirst().getQuantity(); + } + + public int getPromotionSetSize(String productName) { // 2+1์ผ ๊ฒฝ์šฐ ํ•œ set size๋Š” 3 / 1+1์ผ๋•Œ๋Š” 2 + String promotionName = products.get(productName).getFirst().getPromotion(); + int setSize = 0; + Promotion promotion = promotions.get(promotionName); + setSize = promotion.getBuy() + promotion.getGet(); + return setSize; + } + + + public void checkPromotionApply(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + Promotion promotion = promotions.get(products.get(wantBuyProduct.getName()).getFirst().getPromotion()); + if (promotion != null && promotion.checkPromotionDate()) { + int notBringBonus = calculateBonus(promotion.getBuy(), promotion.getGet(), + wantBuyProduct.getQuantity()); + bringBonus(wantBuyProduct, notBringBonus); + } + } + } + + public int calculateBonus(int buy, int get, int purchasedCount) { + int bonusCount = 0; + if (buy == purchasedCount) { + bonusCount = get; + return bonusCount; + } + if (purchasedCount > buy && purchasedCount % (buy + get) == buy) { + bonusCount = get; + return bonusCount; + } + return bonusCount; + } + + public void bringBonus(Product wantBuyProduct, int notBringBonus) { + if (notBringBonus > 0) { + outputView.printBringPromotion(wantBuyProduct.getName(), notBringBonus); + inputView.addPromotion(wantBuyProduct, notBringBonus); + } + } + + public LinkedHashMap<String, List<Product>> getProducts() { + LinkedHashMap<String, List<Product>> copiedProdcuts = new LinkedHashMap<>(this.products); + return copiedProdcuts; + } +}
Java
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!! ์ด๊ฒƒ๋„ ํญํ’๊ฒ€์ƒ‰์˜ ํž˜....
@@ -0,0 +1,357 @@ +package store; + +import static exception.Exception.EXCEED_QUANTITY; +import static exception.Exception.NON_EXIST_PRODUCT; +import static exception.Exception.WRONG_INPUT; +import static exception.Exception.throwException; +import static util.ProductValidator.INVALID_FORMAT; +import static view.InputView.handleRetryOnError; +import static view.OutputView.MEMBERSHIP_BUY; +import static view.OutputView.NOW; +import static view.OutputView.NO_PROMOTION_BUY; +import static view.OutputView.printMessage; + +import dto.Status; +import exception.Exception; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import view.InputView; +import view.OutputView; + +public class Buyer { + + private static final String PROMOTIONAL_SEPARATOR = "P_"; + private static final String PRODUCTS_FILE_NAME = "products.md"; + private static final String PROMOTION_FILE_NAME = "promotions.md"; + private static final String THANK_YOU_MORE_BUY = "\n๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"; + private static final String BLANK_SEPARATOR = "===================================="; + private static final String PROMOTION_SEPARATOR = "=============์ฆ\t\t์ •==============="; + private static final String DUPL_NAME = "[์ค‘๋ณต๋œ ์ œํ’ˆ๋ช…] : "; + private static final int MEMBERSHIP_MAX_DISCOUNT = 8000; + private final InputView inputView; + private final OutputView outputView; + private final LinkedHashMap<String, List<Product>> products; + private final Map<String, Promotion> promotions; + private Map<String, Integer> receiptMap; + private Status memberShip; + + public Buyer() { + this.inputView = new InputView(); + this.outputView = new OutputView(); + this.products = makeProducts(inputView.loadProducts(PRODUCTS_FILE_NAME)); + this.promotions = makePromotions(inputView.loadPromotions(PROMOTION_FILE_NAME)); + outputView.printProducts(products); + } + + public void makePrintProduct(LinkedHashMap<String, List<Product>> products) { + for (String key : products.keySet()) { + List<Product> productList = products.get(key); + if (productList.size() == 1 && productList.getFirst().getPromotion() != null) { + Product product = productList.getFirst(); + productList.add(new Product(product.getName(), product.getPrice(), 0)); + } + } + } + + + public LinkedHashMap<String, List<Product>> makeProducts(List<Product> products) { + LinkedHashMap<String, List<Product>> map = new LinkedHashMap<>(); + for (Product product : products) { + map.computeIfAbsent(product.getName(), k -> new ArrayList<>()) + .add(product); + } + makePrintProduct(map); + return map; + } + + public Map<String, Promotion> makePromotions(List<Promotion> promotions) { + HashMap<String, Promotion> map = new HashMap<>(); + for (Promotion promotion : promotions) { + map.put(promotion.getName(), promotion); + } + return map; + } + + public void buyProducts() { + initializationReceiptMap(); + List<Product> wantBuyProducts = inputBuyProduct(); + checkNotPromotionApply(wantBuyProducts); + applyMemberShip(); + printReceipt(wantBuyProducts); + realBuyProducts(wantBuyProducts); + } + + public void initializationReceiptMap() { + receiptMap = new HashMap<>(); + } + + public List<Product> inputBuyProduct() { + return handleRetryOnError(() -> { + List<Product> wantBuyProducts = inputView.readItem(); + checkDuplProductName(wantBuyProducts); + productNameCheck(wantBuyProducts); + checkPromotionApply(wantBuyProducts); + checkCanBuyQuantity(wantBuyProducts); + return wantBuyProducts; + }); + } + + public void checkDuplProductName(List<Product> wantBuyProducts) { + Set<String> uniqueNames = new HashSet<>(); + for (Product product : wantBuyProducts) { + String productName = product.getName(); + if (!uniqueNames.add(productName)) { + throwException(INVALID_FORMAT + DUPL_NAME + productName); + } + } + } + + public void productNameCheck(List<Product> wantBuyProducts) { + if (wantBuyProducts.isEmpty()) { + Exception.throwException(WRONG_INPUT); + } + for (Product wantBuyProduct : wantBuyProducts) { + if (products.get(wantBuyProduct.getName()) == null) { + Exception.throwException(NON_EXIST_PRODUCT); + } + } + } + + public void realBuyProducts(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + int quantity = wantBuyProduct.getQuantity(); + Product firstProduct = products.get(wantBuyProduct.getName()).getFirst(); + if (withinQuantity(firstProduct, quantity)) { + continue; + } + int restQuantity = quantity - firstProduct.getQuantity(); + firstProduct.subtractQuantity(firstProduct.getQuantity()); + products.get(wantBuyProduct.getName()).get(1).subtractQuantity(restQuantity); + } + } + + public boolean withinQuantity(Product firstProduct, int quantity) { + boolean exceed = false; + if (firstProduct.getQuantity() >= quantity) { + firstProduct.subtractQuantity(quantity); + return true; + } + return exceed; + } + + public void wantContinue() { + while (true) { + printMessage(THANK_YOU_MORE_BUY); + Status status = inputView.wantContinue(); + if (status == Status.Y) { + convenienceContinue(); + } + break; + } + } + + public void convenienceContinue() { + printMessage(null); + outputView.printProducts(products); + buyProducts(); + wantContinue(); + } + + public void printReceipt(List<Product> wantBuyProducts) { + int totalBuyCount = printFirstReceipt(wantBuyProducts); + printPresentReceipt(wantBuyProducts); + printFinalReceipt(totalBuyCount); + } + + + public void printFinalReceipt(int totalBuyCount) { + printMessage(BLANK_SEPARATOR); + int totalMoney = totalMoney(); + int promotionDiscount = promotionDiscount(); + int memberShipDiscount = memberShipDiscount(); + outputView.printFinalReceipt(totalBuyCount, totalMoney, promotionDiscount, memberShipDiscount); + } + + + public int memberShipDiscount() { + int memberShipMoney = 0; + if (memberShip != Status.Y) { + return memberShipMoney; + } + for (String key : receiptMap.keySet()) { + if (!key.startsWith(PROMOTIONAL_SEPARATOR)) { + memberShipMoney += (int) (receiptMap.get(key) * 0.3); + } + } + return Math.min(memberShipMoney, MEMBERSHIP_MAX_DISCOUNT); + } + + public int promotionDiscount() { + int promotionDiscount = 0; + ArrayList<String> removes = new ArrayList<>(); + for (String key : receiptMap.keySet()) { + if (key.startsWith(PROMOTIONAL_SEPARATOR)) { + promotionDiscount += receiptMap.get(key); + removes.add(key.substring(key.indexOf(PROMOTIONAL_SEPARATOR) + PROMOTIONAL_SEPARATOR.length())); + } + } + removeReceiptMap(removes); + return promotionDiscount; + } + + public void removeReceiptMap(List<String> removes) { + for (String remove : removes) { + receiptMap.remove(remove); + } + } + + public int totalMoney() { + int totalMoney = 0; + for (String key : receiptMap.keySet()) { + if (!key.startsWith(PROMOTIONAL_SEPARATOR)) { + totalMoney += receiptMap.get(key); + } + } + return totalMoney; + } + + public void printPresentReceipt(List<Product> wantBuyProducts) { + printMessage(PROMOTION_SEPARATOR); + for (Product wantBuyProduct : wantBuyProducts) { + Promotion promotion = promotions.get(products.get(wantBuyProduct.getName()).getFirst().getPromotion()); + if (products.get(wantBuyProduct.getName()).size() == 1 || !promotion.checkPromotionDate()) { + continue; + } + printProvenPresent(wantBuyProduct); + } + } + + public void printProvenPresent(Product wantBuyProduct) { + int promotionCount = calculatePromotionCount(wantBuyProduct); + if (promotionCount > 0) { + outputView.printPresentReceipt(wantBuyProduct, promotionCount); + receiptMap.put(PROMOTIONAL_SEPARATOR + wantBuyProduct.getName(), + promotionCount * products.get(wantBuyProduct.getName()).getFirst().getPrice()); + } + } + + public int printFirstReceipt(List<Product> wantBuyProducts) { + outputView.printFirstReceipt(); + int totalBuyCount = calculateTotalBuyCount(wantBuyProducts); + return totalBuyCount; + } + + public int calculateTotalBuyCount(List<Product> wantBuyProducts) { + int totalBuyCount = 0; + for (Product wantBuyProduct : wantBuyProducts) { + Product findProduct = products.get(wantBuyProduct.getName()).getFirst(); + int totalPrice = outputView.printPurchaseReceipt(findProduct, wantBuyProduct); + receiptMap.put(findProduct.getName(), totalPrice); + totalBuyCount += wantBuyProduct.getQuantity(); + } + return totalBuyCount; + } + + + public void applyMemberShip() { + OutputView.printMessage(MEMBERSHIP_BUY); + this.memberShip = inputView.memberShipApply(); + } + + public void checkCanBuyQuantity(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + int count = 0; + List<Product> getProducts = products.get(wantBuyProduct.getName()); + for (Product p : getProducts) { + count += p.getQuantity(); + } + if (wantBuyProduct.getQuantity() > count) { + Exception.throwException(EXCEED_QUANTITY); + } + } + } + + public void checkNotPromotionApply(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + if (products.get(wantBuyProduct.getName()).size() == 1) { + continue; + } + int notPromotionCount = calculateNotPromotionCount(wantBuyProduct); + questionPromotionApply(wantBuyProduct, notPromotionCount); + } + } + + public void questionPromotionApply(Product wantBuyProduct, int notPromotionCount) { + if (notPromotionCount > 0) { + printMessage(NOW + wantBuyProduct.getName() + " " + notPromotionCount + NO_PROMOTION_BUY); + inputView.promotionApply(wantBuyProduct, notPromotionCount); + } + } + + public int calculateNotPromotionCount(Product wantBuyProduct) { + int promotionSetSize = getPromotionSetSize(wantBuyProduct.getName()); + int canBuyPromotionCount = canBuyPromotionProductCount(wantBuyProduct.getName()); + int promotionCount = (canBuyPromotionCount / promotionSetSize) * promotionSetSize; + return wantBuyProduct.getQuantity() - promotionCount; + } + + public int calculatePromotionCount(Product wantBuyProduct) { + int promotionSetSize = getPromotionSetSize(wantBuyProduct.getName()); + return Math.min(products.get(wantBuyProduct.getName()).getFirst().getQuantity() / promotionSetSize, + wantBuyProduct.getQuantity() / promotionSetSize); + } + + public int canBuyPromotionProductCount(String productName) { + return products.get(productName).getFirst().getQuantity(); + } + + public int getPromotionSetSize(String productName) { // 2+1์ผ ๊ฒฝ์šฐ ํ•œ set size๋Š” 3 / 1+1์ผ๋•Œ๋Š” 2 + String promotionName = products.get(productName).getFirst().getPromotion(); + int setSize = 0; + Promotion promotion = promotions.get(promotionName); + setSize = promotion.getBuy() + promotion.getGet(); + return setSize; + } + + + public void checkPromotionApply(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + Promotion promotion = promotions.get(products.get(wantBuyProduct.getName()).getFirst().getPromotion()); + if (promotion != null && promotion.checkPromotionDate()) { + int notBringBonus = calculateBonus(promotion.getBuy(), promotion.getGet(), + wantBuyProduct.getQuantity()); + bringBonus(wantBuyProduct, notBringBonus); + } + } + } + + public int calculateBonus(int buy, int get, int purchasedCount) { + int bonusCount = 0; + if (buy == purchasedCount) { + bonusCount = get; + return bonusCount; + } + if (purchasedCount > buy && purchasedCount % (buy + get) == buy) { + bonusCount = get; + return bonusCount; + } + return bonusCount; + } + + public void bringBonus(Product wantBuyProduct, int notBringBonus) { + if (notBringBonus > 0) { + outputView.printBringPromotion(wantBuyProduct.getName(), notBringBonus); + inputView.addPromotion(wantBuyProduct, notBringBonus); + } + } + + public LinkedHashMap<String, List<Product>> getProducts() { + LinkedHashMap<String, List<Product>> copiedProdcuts = new LinkedHashMap<>(this.products); + return copiedProdcuts; + } +}
Java
์ข‹์€ ๋ง์”€ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ํ•ด๋‹น ์ด๋ฆ„์ด ๋” ์ง๊ด€์ ์ด๊ณ  ํ›จ์‹  ๋” ์•Œ์•„๋ณด๊ธฐ ์‰ฌ์šด๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ์•ž์œผ๋กœ๋Š” ๋” ์‹ ๊ฒฝ์จ๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,357 @@ +package store; + +import static exception.Exception.EXCEED_QUANTITY; +import static exception.Exception.NON_EXIST_PRODUCT; +import static exception.Exception.WRONG_INPUT; +import static exception.Exception.throwException; +import static util.ProductValidator.INVALID_FORMAT; +import static view.InputView.handleRetryOnError; +import static view.OutputView.MEMBERSHIP_BUY; +import static view.OutputView.NOW; +import static view.OutputView.NO_PROMOTION_BUY; +import static view.OutputView.printMessage; + +import dto.Status; +import exception.Exception; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import view.InputView; +import view.OutputView; + +public class Buyer { + + private static final String PROMOTIONAL_SEPARATOR = "P_"; + private static final String PRODUCTS_FILE_NAME = "products.md"; + private static final String PROMOTION_FILE_NAME = "promotions.md"; + private static final String THANK_YOU_MORE_BUY = "\n๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"; + private static final String BLANK_SEPARATOR = "===================================="; + private static final String PROMOTION_SEPARATOR = "=============์ฆ\t\t์ •==============="; + private static final String DUPL_NAME = "[์ค‘๋ณต๋œ ์ œํ’ˆ๋ช…] : "; + private static final int MEMBERSHIP_MAX_DISCOUNT = 8000; + private final InputView inputView; + private final OutputView outputView; + private final LinkedHashMap<String, List<Product>> products; + private final Map<String, Promotion> promotions; + private Map<String, Integer> receiptMap; + private Status memberShip; + + public Buyer() { + this.inputView = new InputView(); + this.outputView = new OutputView(); + this.products = makeProducts(inputView.loadProducts(PRODUCTS_FILE_NAME)); + this.promotions = makePromotions(inputView.loadPromotions(PROMOTION_FILE_NAME)); + outputView.printProducts(products); + } + + public void makePrintProduct(LinkedHashMap<String, List<Product>> products) { + for (String key : products.keySet()) { + List<Product> productList = products.get(key); + if (productList.size() == 1 && productList.getFirst().getPromotion() != null) { + Product product = productList.getFirst(); + productList.add(new Product(product.getName(), product.getPrice(), 0)); + } + } + } + + + public LinkedHashMap<String, List<Product>> makeProducts(List<Product> products) { + LinkedHashMap<String, List<Product>> map = new LinkedHashMap<>(); + for (Product product : products) { + map.computeIfAbsent(product.getName(), k -> new ArrayList<>()) + .add(product); + } + makePrintProduct(map); + return map; + } + + public Map<String, Promotion> makePromotions(List<Promotion> promotions) { + HashMap<String, Promotion> map = new HashMap<>(); + for (Promotion promotion : promotions) { + map.put(promotion.getName(), promotion); + } + return map; + } + + public void buyProducts() { + initializationReceiptMap(); + List<Product> wantBuyProducts = inputBuyProduct(); + checkNotPromotionApply(wantBuyProducts); + applyMemberShip(); + printReceipt(wantBuyProducts); + realBuyProducts(wantBuyProducts); + } + + public void initializationReceiptMap() { + receiptMap = new HashMap<>(); + } + + public List<Product> inputBuyProduct() { + return handleRetryOnError(() -> { + List<Product> wantBuyProducts = inputView.readItem(); + checkDuplProductName(wantBuyProducts); + productNameCheck(wantBuyProducts); + checkPromotionApply(wantBuyProducts); + checkCanBuyQuantity(wantBuyProducts); + return wantBuyProducts; + }); + } + + public void checkDuplProductName(List<Product> wantBuyProducts) { + Set<String> uniqueNames = new HashSet<>(); + for (Product product : wantBuyProducts) { + String productName = product.getName(); + if (!uniqueNames.add(productName)) { + throwException(INVALID_FORMAT + DUPL_NAME + productName); + } + } + } + + public void productNameCheck(List<Product> wantBuyProducts) { + if (wantBuyProducts.isEmpty()) { + Exception.throwException(WRONG_INPUT); + } + for (Product wantBuyProduct : wantBuyProducts) { + if (products.get(wantBuyProduct.getName()) == null) { + Exception.throwException(NON_EXIST_PRODUCT); + } + } + } + + public void realBuyProducts(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + int quantity = wantBuyProduct.getQuantity(); + Product firstProduct = products.get(wantBuyProduct.getName()).getFirst(); + if (withinQuantity(firstProduct, quantity)) { + continue; + } + int restQuantity = quantity - firstProduct.getQuantity(); + firstProduct.subtractQuantity(firstProduct.getQuantity()); + products.get(wantBuyProduct.getName()).get(1).subtractQuantity(restQuantity); + } + } + + public boolean withinQuantity(Product firstProduct, int quantity) { + boolean exceed = false; + if (firstProduct.getQuantity() >= quantity) { + firstProduct.subtractQuantity(quantity); + return true; + } + return exceed; + } + + public void wantContinue() { + while (true) { + printMessage(THANK_YOU_MORE_BUY); + Status status = inputView.wantContinue(); + if (status == Status.Y) { + convenienceContinue(); + } + break; + } + } + + public void convenienceContinue() { + printMessage(null); + outputView.printProducts(products); + buyProducts(); + wantContinue(); + } + + public void printReceipt(List<Product> wantBuyProducts) { + int totalBuyCount = printFirstReceipt(wantBuyProducts); + printPresentReceipt(wantBuyProducts); + printFinalReceipt(totalBuyCount); + } + + + public void printFinalReceipt(int totalBuyCount) { + printMessage(BLANK_SEPARATOR); + int totalMoney = totalMoney(); + int promotionDiscount = promotionDiscount(); + int memberShipDiscount = memberShipDiscount(); + outputView.printFinalReceipt(totalBuyCount, totalMoney, promotionDiscount, memberShipDiscount); + } + + + public int memberShipDiscount() { + int memberShipMoney = 0; + if (memberShip != Status.Y) { + return memberShipMoney; + } + for (String key : receiptMap.keySet()) { + if (!key.startsWith(PROMOTIONAL_SEPARATOR)) { + memberShipMoney += (int) (receiptMap.get(key) * 0.3); + } + } + return Math.min(memberShipMoney, MEMBERSHIP_MAX_DISCOUNT); + } + + public int promotionDiscount() { + int promotionDiscount = 0; + ArrayList<String> removes = new ArrayList<>(); + for (String key : receiptMap.keySet()) { + if (key.startsWith(PROMOTIONAL_SEPARATOR)) { + promotionDiscount += receiptMap.get(key); + removes.add(key.substring(key.indexOf(PROMOTIONAL_SEPARATOR) + PROMOTIONAL_SEPARATOR.length())); + } + } + removeReceiptMap(removes); + return promotionDiscount; + } + + public void removeReceiptMap(List<String> removes) { + for (String remove : removes) { + receiptMap.remove(remove); + } + } + + public int totalMoney() { + int totalMoney = 0; + for (String key : receiptMap.keySet()) { + if (!key.startsWith(PROMOTIONAL_SEPARATOR)) { + totalMoney += receiptMap.get(key); + } + } + return totalMoney; + } + + public void printPresentReceipt(List<Product> wantBuyProducts) { + printMessage(PROMOTION_SEPARATOR); + for (Product wantBuyProduct : wantBuyProducts) { + Promotion promotion = promotions.get(products.get(wantBuyProduct.getName()).getFirst().getPromotion()); + if (products.get(wantBuyProduct.getName()).size() == 1 || !promotion.checkPromotionDate()) { + continue; + } + printProvenPresent(wantBuyProduct); + } + } + + public void printProvenPresent(Product wantBuyProduct) { + int promotionCount = calculatePromotionCount(wantBuyProduct); + if (promotionCount > 0) { + outputView.printPresentReceipt(wantBuyProduct, promotionCount); + receiptMap.put(PROMOTIONAL_SEPARATOR + wantBuyProduct.getName(), + promotionCount * products.get(wantBuyProduct.getName()).getFirst().getPrice()); + } + } + + public int printFirstReceipt(List<Product> wantBuyProducts) { + outputView.printFirstReceipt(); + int totalBuyCount = calculateTotalBuyCount(wantBuyProducts); + return totalBuyCount; + } + + public int calculateTotalBuyCount(List<Product> wantBuyProducts) { + int totalBuyCount = 0; + for (Product wantBuyProduct : wantBuyProducts) { + Product findProduct = products.get(wantBuyProduct.getName()).getFirst(); + int totalPrice = outputView.printPurchaseReceipt(findProduct, wantBuyProduct); + receiptMap.put(findProduct.getName(), totalPrice); + totalBuyCount += wantBuyProduct.getQuantity(); + } + return totalBuyCount; + } + + + public void applyMemberShip() { + OutputView.printMessage(MEMBERSHIP_BUY); + this.memberShip = inputView.memberShipApply(); + } + + public void checkCanBuyQuantity(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + int count = 0; + List<Product> getProducts = products.get(wantBuyProduct.getName()); + for (Product p : getProducts) { + count += p.getQuantity(); + } + if (wantBuyProduct.getQuantity() > count) { + Exception.throwException(EXCEED_QUANTITY); + } + } + } + + public void checkNotPromotionApply(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + if (products.get(wantBuyProduct.getName()).size() == 1) { + continue; + } + int notPromotionCount = calculateNotPromotionCount(wantBuyProduct); + questionPromotionApply(wantBuyProduct, notPromotionCount); + } + } + + public void questionPromotionApply(Product wantBuyProduct, int notPromotionCount) { + if (notPromotionCount > 0) { + printMessage(NOW + wantBuyProduct.getName() + " " + notPromotionCount + NO_PROMOTION_BUY); + inputView.promotionApply(wantBuyProduct, notPromotionCount); + } + } + + public int calculateNotPromotionCount(Product wantBuyProduct) { + int promotionSetSize = getPromotionSetSize(wantBuyProduct.getName()); + int canBuyPromotionCount = canBuyPromotionProductCount(wantBuyProduct.getName()); + int promotionCount = (canBuyPromotionCount / promotionSetSize) * promotionSetSize; + return wantBuyProduct.getQuantity() - promotionCount; + } + + public int calculatePromotionCount(Product wantBuyProduct) { + int promotionSetSize = getPromotionSetSize(wantBuyProduct.getName()); + return Math.min(products.get(wantBuyProduct.getName()).getFirst().getQuantity() / promotionSetSize, + wantBuyProduct.getQuantity() / promotionSetSize); + } + + public int canBuyPromotionProductCount(String productName) { + return products.get(productName).getFirst().getQuantity(); + } + + public int getPromotionSetSize(String productName) { // 2+1์ผ ๊ฒฝ์šฐ ํ•œ set size๋Š” 3 / 1+1์ผ๋•Œ๋Š” 2 + String promotionName = products.get(productName).getFirst().getPromotion(); + int setSize = 0; + Promotion promotion = promotions.get(promotionName); + setSize = promotion.getBuy() + promotion.getGet(); + return setSize; + } + + + public void checkPromotionApply(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + Promotion promotion = promotions.get(products.get(wantBuyProduct.getName()).getFirst().getPromotion()); + if (promotion != null && promotion.checkPromotionDate()) { + int notBringBonus = calculateBonus(promotion.getBuy(), promotion.getGet(), + wantBuyProduct.getQuantity()); + bringBonus(wantBuyProduct, notBringBonus); + } + } + } + + public int calculateBonus(int buy, int get, int purchasedCount) { + int bonusCount = 0; + if (buy == purchasedCount) { + bonusCount = get; + return bonusCount; + } + if (purchasedCount > buy && purchasedCount % (buy + get) == buy) { + bonusCount = get; + return bonusCount; + } + return bonusCount; + } + + public void bringBonus(Product wantBuyProduct, int notBringBonus) { + if (notBringBonus > 0) { + outputView.printBringPromotion(wantBuyProduct.getName(), notBringBonus); + inputView.addPromotion(wantBuyProduct, notBringBonus); + } + } + + public LinkedHashMap<String, List<Product>> getProducts() { + LinkedHashMap<String, List<Product>> copiedProdcuts = new LinkedHashMap<>(this.products); + return copiedProdcuts; + } +}
Java
๋ฉ”์„œ๋“œ ๋ช…์€ ๋™์‚ฌ๋‚˜ ์ „์น˜์‚ฌ๋กœ ์‹œ์ž‘ํ•˜๋Š” ๊ฑธ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,357 @@ +package store; + +import static exception.Exception.EXCEED_QUANTITY; +import static exception.Exception.NON_EXIST_PRODUCT; +import static exception.Exception.WRONG_INPUT; +import static exception.Exception.throwException; +import static util.ProductValidator.INVALID_FORMAT; +import static view.InputView.handleRetryOnError; +import static view.OutputView.MEMBERSHIP_BUY; +import static view.OutputView.NOW; +import static view.OutputView.NO_PROMOTION_BUY; +import static view.OutputView.printMessage; + +import dto.Status; +import exception.Exception; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import view.InputView; +import view.OutputView; + +public class Buyer { + + private static final String PROMOTIONAL_SEPARATOR = "P_"; + private static final String PRODUCTS_FILE_NAME = "products.md"; + private static final String PROMOTION_FILE_NAME = "promotions.md"; + private static final String THANK_YOU_MORE_BUY = "\n๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"; + private static final String BLANK_SEPARATOR = "===================================="; + private static final String PROMOTION_SEPARATOR = "=============์ฆ\t\t์ •==============="; + private static final String DUPL_NAME = "[์ค‘๋ณต๋œ ์ œํ’ˆ๋ช…] : "; + private static final int MEMBERSHIP_MAX_DISCOUNT = 8000; + private final InputView inputView; + private final OutputView outputView; + private final LinkedHashMap<String, List<Product>> products; + private final Map<String, Promotion> promotions; + private Map<String, Integer> receiptMap; + private Status memberShip; + + public Buyer() { + this.inputView = new InputView(); + this.outputView = new OutputView(); + this.products = makeProducts(inputView.loadProducts(PRODUCTS_FILE_NAME)); + this.promotions = makePromotions(inputView.loadPromotions(PROMOTION_FILE_NAME)); + outputView.printProducts(products); + } + + public void makePrintProduct(LinkedHashMap<String, List<Product>> products) { + for (String key : products.keySet()) { + List<Product> productList = products.get(key); + if (productList.size() == 1 && productList.getFirst().getPromotion() != null) { + Product product = productList.getFirst(); + productList.add(new Product(product.getName(), product.getPrice(), 0)); + } + } + } + + + public LinkedHashMap<String, List<Product>> makeProducts(List<Product> products) { + LinkedHashMap<String, List<Product>> map = new LinkedHashMap<>(); + for (Product product : products) { + map.computeIfAbsent(product.getName(), k -> new ArrayList<>()) + .add(product); + } + makePrintProduct(map); + return map; + } + + public Map<String, Promotion> makePromotions(List<Promotion> promotions) { + HashMap<String, Promotion> map = new HashMap<>(); + for (Promotion promotion : promotions) { + map.put(promotion.getName(), promotion); + } + return map; + } + + public void buyProducts() { + initializationReceiptMap(); + List<Product> wantBuyProducts = inputBuyProduct(); + checkNotPromotionApply(wantBuyProducts); + applyMemberShip(); + printReceipt(wantBuyProducts); + realBuyProducts(wantBuyProducts); + } + + public void initializationReceiptMap() { + receiptMap = new HashMap<>(); + } + + public List<Product> inputBuyProduct() { + return handleRetryOnError(() -> { + List<Product> wantBuyProducts = inputView.readItem(); + checkDuplProductName(wantBuyProducts); + productNameCheck(wantBuyProducts); + checkPromotionApply(wantBuyProducts); + checkCanBuyQuantity(wantBuyProducts); + return wantBuyProducts; + }); + } + + public void checkDuplProductName(List<Product> wantBuyProducts) { + Set<String> uniqueNames = new HashSet<>(); + for (Product product : wantBuyProducts) { + String productName = product.getName(); + if (!uniqueNames.add(productName)) { + throwException(INVALID_FORMAT + DUPL_NAME + productName); + } + } + } + + public void productNameCheck(List<Product> wantBuyProducts) { + if (wantBuyProducts.isEmpty()) { + Exception.throwException(WRONG_INPUT); + } + for (Product wantBuyProduct : wantBuyProducts) { + if (products.get(wantBuyProduct.getName()) == null) { + Exception.throwException(NON_EXIST_PRODUCT); + } + } + } + + public void realBuyProducts(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + int quantity = wantBuyProduct.getQuantity(); + Product firstProduct = products.get(wantBuyProduct.getName()).getFirst(); + if (withinQuantity(firstProduct, quantity)) { + continue; + } + int restQuantity = quantity - firstProduct.getQuantity(); + firstProduct.subtractQuantity(firstProduct.getQuantity()); + products.get(wantBuyProduct.getName()).get(1).subtractQuantity(restQuantity); + } + } + + public boolean withinQuantity(Product firstProduct, int quantity) { + boolean exceed = false; + if (firstProduct.getQuantity() >= quantity) { + firstProduct.subtractQuantity(quantity); + return true; + } + return exceed; + } + + public void wantContinue() { + while (true) { + printMessage(THANK_YOU_MORE_BUY); + Status status = inputView.wantContinue(); + if (status == Status.Y) { + convenienceContinue(); + } + break; + } + } + + public void convenienceContinue() { + printMessage(null); + outputView.printProducts(products); + buyProducts(); + wantContinue(); + } + + public void printReceipt(List<Product> wantBuyProducts) { + int totalBuyCount = printFirstReceipt(wantBuyProducts); + printPresentReceipt(wantBuyProducts); + printFinalReceipt(totalBuyCount); + } + + + public void printFinalReceipt(int totalBuyCount) { + printMessage(BLANK_SEPARATOR); + int totalMoney = totalMoney(); + int promotionDiscount = promotionDiscount(); + int memberShipDiscount = memberShipDiscount(); + outputView.printFinalReceipt(totalBuyCount, totalMoney, promotionDiscount, memberShipDiscount); + } + + + public int memberShipDiscount() { + int memberShipMoney = 0; + if (memberShip != Status.Y) { + return memberShipMoney; + } + for (String key : receiptMap.keySet()) { + if (!key.startsWith(PROMOTIONAL_SEPARATOR)) { + memberShipMoney += (int) (receiptMap.get(key) * 0.3); + } + } + return Math.min(memberShipMoney, MEMBERSHIP_MAX_DISCOUNT); + } + + public int promotionDiscount() { + int promotionDiscount = 0; + ArrayList<String> removes = new ArrayList<>(); + for (String key : receiptMap.keySet()) { + if (key.startsWith(PROMOTIONAL_SEPARATOR)) { + promotionDiscount += receiptMap.get(key); + removes.add(key.substring(key.indexOf(PROMOTIONAL_SEPARATOR) + PROMOTIONAL_SEPARATOR.length())); + } + } + removeReceiptMap(removes); + return promotionDiscount; + } + + public void removeReceiptMap(List<String> removes) { + for (String remove : removes) { + receiptMap.remove(remove); + } + } + + public int totalMoney() { + int totalMoney = 0; + for (String key : receiptMap.keySet()) { + if (!key.startsWith(PROMOTIONAL_SEPARATOR)) { + totalMoney += receiptMap.get(key); + } + } + return totalMoney; + } + + public void printPresentReceipt(List<Product> wantBuyProducts) { + printMessage(PROMOTION_SEPARATOR); + for (Product wantBuyProduct : wantBuyProducts) { + Promotion promotion = promotions.get(products.get(wantBuyProduct.getName()).getFirst().getPromotion()); + if (products.get(wantBuyProduct.getName()).size() == 1 || !promotion.checkPromotionDate()) { + continue; + } + printProvenPresent(wantBuyProduct); + } + } + + public void printProvenPresent(Product wantBuyProduct) { + int promotionCount = calculatePromotionCount(wantBuyProduct); + if (promotionCount > 0) { + outputView.printPresentReceipt(wantBuyProduct, promotionCount); + receiptMap.put(PROMOTIONAL_SEPARATOR + wantBuyProduct.getName(), + promotionCount * products.get(wantBuyProduct.getName()).getFirst().getPrice()); + } + } + + public int printFirstReceipt(List<Product> wantBuyProducts) { + outputView.printFirstReceipt(); + int totalBuyCount = calculateTotalBuyCount(wantBuyProducts); + return totalBuyCount; + } + + public int calculateTotalBuyCount(List<Product> wantBuyProducts) { + int totalBuyCount = 0; + for (Product wantBuyProduct : wantBuyProducts) { + Product findProduct = products.get(wantBuyProduct.getName()).getFirst(); + int totalPrice = outputView.printPurchaseReceipt(findProduct, wantBuyProduct); + receiptMap.put(findProduct.getName(), totalPrice); + totalBuyCount += wantBuyProduct.getQuantity(); + } + return totalBuyCount; + } + + + public void applyMemberShip() { + OutputView.printMessage(MEMBERSHIP_BUY); + this.memberShip = inputView.memberShipApply(); + } + + public void checkCanBuyQuantity(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + int count = 0; + List<Product> getProducts = products.get(wantBuyProduct.getName()); + for (Product p : getProducts) { + count += p.getQuantity(); + } + if (wantBuyProduct.getQuantity() > count) { + Exception.throwException(EXCEED_QUANTITY); + } + } + } + + public void checkNotPromotionApply(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + if (products.get(wantBuyProduct.getName()).size() == 1) { + continue; + } + int notPromotionCount = calculateNotPromotionCount(wantBuyProduct); + questionPromotionApply(wantBuyProduct, notPromotionCount); + } + } + + public void questionPromotionApply(Product wantBuyProduct, int notPromotionCount) { + if (notPromotionCount > 0) { + printMessage(NOW + wantBuyProduct.getName() + " " + notPromotionCount + NO_PROMOTION_BUY); + inputView.promotionApply(wantBuyProduct, notPromotionCount); + } + } + + public int calculateNotPromotionCount(Product wantBuyProduct) { + int promotionSetSize = getPromotionSetSize(wantBuyProduct.getName()); + int canBuyPromotionCount = canBuyPromotionProductCount(wantBuyProduct.getName()); + int promotionCount = (canBuyPromotionCount / promotionSetSize) * promotionSetSize; + return wantBuyProduct.getQuantity() - promotionCount; + } + + public int calculatePromotionCount(Product wantBuyProduct) { + int promotionSetSize = getPromotionSetSize(wantBuyProduct.getName()); + return Math.min(products.get(wantBuyProduct.getName()).getFirst().getQuantity() / promotionSetSize, + wantBuyProduct.getQuantity() / promotionSetSize); + } + + public int canBuyPromotionProductCount(String productName) { + return products.get(productName).getFirst().getQuantity(); + } + + public int getPromotionSetSize(String productName) { // 2+1์ผ ๊ฒฝ์šฐ ํ•œ set size๋Š” 3 / 1+1์ผ๋•Œ๋Š” 2 + String promotionName = products.get(productName).getFirst().getPromotion(); + int setSize = 0; + Promotion promotion = promotions.get(promotionName); + setSize = promotion.getBuy() + promotion.getGet(); + return setSize; + } + + + public void checkPromotionApply(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + Promotion promotion = promotions.get(products.get(wantBuyProduct.getName()).getFirst().getPromotion()); + if (promotion != null && promotion.checkPromotionDate()) { + int notBringBonus = calculateBonus(promotion.getBuy(), promotion.getGet(), + wantBuyProduct.getQuantity()); + bringBonus(wantBuyProduct, notBringBonus); + } + } + } + + public int calculateBonus(int buy, int get, int purchasedCount) { + int bonusCount = 0; + if (buy == purchasedCount) { + bonusCount = get; + return bonusCount; + } + if (purchasedCount > buy && purchasedCount % (buy + get) == buy) { + bonusCount = get; + return bonusCount; + } + return bonusCount; + } + + public void bringBonus(Product wantBuyProduct, int notBringBonus) { + if (notBringBonus > 0) { + outputView.printBringPromotion(wantBuyProduct.getName(), notBringBonus); + inputView.addPromotion(wantBuyProduct, notBringBonus); + } + } + + public LinkedHashMap<String, List<Product>> getProducts() { + LinkedHashMap<String, List<Product>> copiedProdcuts = new LinkedHashMap<>(this.products); + return copiedProdcuts; + } +}
Java
๊ฐœ์ธ์ ์œผ๋กœ buyer๋ผ๋Š” ํด๋ž˜์Šค์— ๋„ˆ๋ฌด ๋งŽ์€ ์—ญํ• ์„ ๋‹ด๊ณ  ์žˆ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! buyer๋Š” ๊ตฌ๋งค์ž๋ผ๋Š” ์˜๋ฏธ ์ฆ‰, ์‚ฌ์šฉ์ž ์ž…์žฅ์—์„œ ์ž‘์„ฑ๋œ ํด๋ž˜์Šค๋ผ ์ƒ๊ฐ์ด ๋˜๋Š”๋ฐ, ์‚ฌ์šฉ์ž๊ฐ€ ์˜์ˆ˜์ฆ์„ ์ถœ๋ ฅํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค Order๊ฐ™์€ ํด๋ž˜์Šค๋ฅผ ์ƒˆ๋กœ ๋งŒ๋“ค์–ด ์—ญํ• ์„ ๋ถ„๋ฆฌํ•˜๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,139 @@ +package view; + +import static exception.Exception.EXCEED_QUANTITY; +import static exception.Exception.WRONG_INPUT; + +import camp.nextstep.edu.missionutils.Console; +import dto.Status; +import exception.Exception; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import store.Application; +import store.Product; +import store.Promotion; +import util.ProductValidator; + +public class InputView { + + private static final String WANT_BUY_PRODUCT = "\n๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"; + + public List<Product> readItem() { + return handleRetryOnError(() -> { + String[] items = preWorkBuyProduct(); + List<Product> buyProducts = new ArrayList<>(); + for (String item : items) { + ProductValidator.isValidProductFormat(item); + addBuyProduct(item, buyProducts); + } + return buyProducts; + }); + } + + public String[] preWorkBuyProduct() { + System.out.println(WANT_BUY_PRODUCT); + String input = Console.readLine().trim(); + return input.split(","); + } + + public void addBuyProduct(String item, List<Product> buyProducts) { + String cleanInput = item.replace("[", "").replace("]", ""); + String[] nameAndQuantity = cleanInput.split("-"); + String name = nameAndQuantity[0]; + int quantity = 0; + try { + quantity = Integer.parseInt(nameAndQuantity[1]); + } catch (java.lang.Exception e) { + Exception.throwException(EXCEED_QUANTITY); + } + buyProducts.add(new Product(name, quantity)); + } + + public <T> List<T> loadItems(String fileName, Function<String, T> mapper) { + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(Application.class.getClassLoader().getResourceAsStream(fileName)))) { + return reader.lines() + .skip(1) // ์ฒซ ๋ฒˆ์งธ ์ค„ ๊ฑด๋„ˆ๋›ฐ๊ธฐ + .map(mapper) + .collect(Collectors.toList()); + } catch (IOException e) { + throw new RuntimeException("[ERROR] reading file: " + fileName, e); + } + } + + public List<Product> loadProducts(String fileName) { + return loadItems(fileName, line -> { + String[] productInfo = line.split(","); + int price = Integer.parseInt(productInfo[1]); + int quantity = Integer.parseInt(productInfo[2]); + String promotion = productInfo[3]; + if ("null".equals(promotion)) { + promotion = null; + } + return new Product(productInfo[0], price, quantity, promotion); + }); + } + + public List<Promotion> loadPromotions(String fileName) { + return loadItems(fileName, line -> { + String[] promotionInfo = line.split(","); + String name = promotionInfo[0]; + int buy = Integer.parseInt(promotionInfo[1]); + int get = Integer.parseInt(promotionInfo[2]); + LocalDate startDate = LocalDate.parse(promotionInfo[3]); + LocalDate endDate = LocalDate.parse(promotionInfo[4]); + return new Promotion(name, buy, get, startDate, endDate); + }); + } + + public void addPromotion(Product wantBuyProduct, int notBringBonus) { + String input = checkInputYorN(); + if (Status.Y == Status.checkStatusInput(input)) { + wantBuyProduct.addQuantity(notBringBonus); + } + } + + public void promotionApply(Product wantBuyProduct, int notPromotionCount) { + String input = checkInputYorN(); + if (Status.N == Status.checkStatusInput(input)) { + wantBuyProduct.subtractQuantity(notPromotionCount); + } + } + + public Status memberShipApply() { + String input = checkInputYorN(); + return Status.checkStatusInput(input); + } + + public String checkInputYorN() { + return handleRetryOnError(() -> { + String input = Console.readLine().trim(); + if (!"Y".equalsIgnoreCase(input) && !"N".equalsIgnoreCase(input)) { + Exception.throwException(WRONG_INPUT); + } + return input; + }); + } + + public Status wantContinue() { + String input = checkInputYorN(); + return Status.checkStatusInput(input); + } + + public static <T> T handleRetryOnError(Supplier<T> method) { + try { + return method.get(); + } catch (IllegalArgumentException e) { + OutputView.printMessage(e.getMessage()); + return handleRetryOnError(method); + } + } + + +} \ No newline at end of file
Java
'[' ๋‚˜ ']' ๋ฅผ ์ƒ์ˆ˜๋กœ ๋นผ๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,357 @@ +package store; + +import static exception.Exception.EXCEED_QUANTITY; +import static exception.Exception.NON_EXIST_PRODUCT; +import static exception.Exception.WRONG_INPUT; +import static exception.Exception.throwException; +import static util.ProductValidator.INVALID_FORMAT; +import static view.InputView.handleRetryOnError; +import static view.OutputView.MEMBERSHIP_BUY; +import static view.OutputView.NOW; +import static view.OutputView.NO_PROMOTION_BUY; +import static view.OutputView.printMessage; + +import dto.Status; +import exception.Exception; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import view.InputView; +import view.OutputView; + +public class Buyer { + + private static final String PROMOTIONAL_SEPARATOR = "P_"; + private static final String PRODUCTS_FILE_NAME = "products.md"; + private static final String PROMOTION_FILE_NAME = "promotions.md"; + private static final String THANK_YOU_MORE_BUY = "\n๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"; + private static final String BLANK_SEPARATOR = "===================================="; + private static final String PROMOTION_SEPARATOR = "=============์ฆ\t\t์ •==============="; + private static final String DUPL_NAME = "[์ค‘๋ณต๋œ ์ œํ’ˆ๋ช…] : "; + private static final int MEMBERSHIP_MAX_DISCOUNT = 8000; + private final InputView inputView; + private final OutputView outputView; + private final LinkedHashMap<String, List<Product>> products; + private final Map<String, Promotion> promotions; + private Map<String, Integer> receiptMap; + private Status memberShip; + + public Buyer() { + this.inputView = new InputView(); + this.outputView = new OutputView(); + this.products = makeProducts(inputView.loadProducts(PRODUCTS_FILE_NAME)); + this.promotions = makePromotions(inputView.loadPromotions(PROMOTION_FILE_NAME)); + outputView.printProducts(products); + } + + public void makePrintProduct(LinkedHashMap<String, List<Product>> products) { + for (String key : products.keySet()) { + List<Product> productList = products.get(key); + if (productList.size() == 1 && productList.getFirst().getPromotion() != null) { + Product product = productList.getFirst(); + productList.add(new Product(product.getName(), product.getPrice(), 0)); + } + } + } + + + public LinkedHashMap<String, List<Product>> makeProducts(List<Product> products) { + LinkedHashMap<String, List<Product>> map = new LinkedHashMap<>(); + for (Product product : products) { + map.computeIfAbsent(product.getName(), k -> new ArrayList<>()) + .add(product); + } + makePrintProduct(map); + return map; + } + + public Map<String, Promotion> makePromotions(List<Promotion> promotions) { + HashMap<String, Promotion> map = new HashMap<>(); + for (Promotion promotion : promotions) { + map.put(promotion.getName(), promotion); + } + return map; + } + + public void buyProducts() { + initializationReceiptMap(); + List<Product> wantBuyProducts = inputBuyProduct(); + checkNotPromotionApply(wantBuyProducts); + applyMemberShip(); + printReceipt(wantBuyProducts); + realBuyProducts(wantBuyProducts); + } + + public void initializationReceiptMap() { + receiptMap = new HashMap<>(); + } + + public List<Product> inputBuyProduct() { + return handleRetryOnError(() -> { + List<Product> wantBuyProducts = inputView.readItem(); + checkDuplProductName(wantBuyProducts); + productNameCheck(wantBuyProducts); + checkPromotionApply(wantBuyProducts); + checkCanBuyQuantity(wantBuyProducts); + return wantBuyProducts; + }); + } + + public void checkDuplProductName(List<Product> wantBuyProducts) { + Set<String> uniqueNames = new HashSet<>(); + for (Product product : wantBuyProducts) { + String productName = product.getName(); + if (!uniqueNames.add(productName)) { + throwException(INVALID_FORMAT + DUPL_NAME + productName); + } + } + } + + public void productNameCheck(List<Product> wantBuyProducts) { + if (wantBuyProducts.isEmpty()) { + Exception.throwException(WRONG_INPUT); + } + for (Product wantBuyProduct : wantBuyProducts) { + if (products.get(wantBuyProduct.getName()) == null) { + Exception.throwException(NON_EXIST_PRODUCT); + } + } + } + + public void realBuyProducts(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + int quantity = wantBuyProduct.getQuantity(); + Product firstProduct = products.get(wantBuyProduct.getName()).getFirst(); + if (withinQuantity(firstProduct, quantity)) { + continue; + } + int restQuantity = quantity - firstProduct.getQuantity(); + firstProduct.subtractQuantity(firstProduct.getQuantity()); + products.get(wantBuyProduct.getName()).get(1).subtractQuantity(restQuantity); + } + } + + public boolean withinQuantity(Product firstProduct, int quantity) { + boolean exceed = false; + if (firstProduct.getQuantity() >= quantity) { + firstProduct.subtractQuantity(quantity); + return true; + } + return exceed; + } + + public void wantContinue() { + while (true) { + printMessage(THANK_YOU_MORE_BUY); + Status status = inputView.wantContinue(); + if (status == Status.Y) { + convenienceContinue(); + } + break; + } + } + + public void convenienceContinue() { + printMessage(null); + outputView.printProducts(products); + buyProducts(); + wantContinue(); + } + + public void printReceipt(List<Product> wantBuyProducts) { + int totalBuyCount = printFirstReceipt(wantBuyProducts); + printPresentReceipt(wantBuyProducts); + printFinalReceipt(totalBuyCount); + } + + + public void printFinalReceipt(int totalBuyCount) { + printMessage(BLANK_SEPARATOR); + int totalMoney = totalMoney(); + int promotionDiscount = promotionDiscount(); + int memberShipDiscount = memberShipDiscount(); + outputView.printFinalReceipt(totalBuyCount, totalMoney, promotionDiscount, memberShipDiscount); + } + + + public int memberShipDiscount() { + int memberShipMoney = 0; + if (memberShip != Status.Y) { + return memberShipMoney; + } + for (String key : receiptMap.keySet()) { + if (!key.startsWith(PROMOTIONAL_SEPARATOR)) { + memberShipMoney += (int) (receiptMap.get(key) * 0.3); + } + } + return Math.min(memberShipMoney, MEMBERSHIP_MAX_DISCOUNT); + } + + public int promotionDiscount() { + int promotionDiscount = 0; + ArrayList<String> removes = new ArrayList<>(); + for (String key : receiptMap.keySet()) { + if (key.startsWith(PROMOTIONAL_SEPARATOR)) { + promotionDiscount += receiptMap.get(key); + removes.add(key.substring(key.indexOf(PROMOTIONAL_SEPARATOR) + PROMOTIONAL_SEPARATOR.length())); + } + } + removeReceiptMap(removes); + return promotionDiscount; + } + + public void removeReceiptMap(List<String> removes) { + for (String remove : removes) { + receiptMap.remove(remove); + } + } + + public int totalMoney() { + int totalMoney = 0; + for (String key : receiptMap.keySet()) { + if (!key.startsWith(PROMOTIONAL_SEPARATOR)) { + totalMoney += receiptMap.get(key); + } + } + return totalMoney; + } + + public void printPresentReceipt(List<Product> wantBuyProducts) { + printMessage(PROMOTION_SEPARATOR); + for (Product wantBuyProduct : wantBuyProducts) { + Promotion promotion = promotions.get(products.get(wantBuyProduct.getName()).getFirst().getPromotion()); + if (products.get(wantBuyProduct.getName()).size() == 1 || !promotion.checkPromotionDate()) { + continue; + } + printProvenPresent(wantBuyProduct); + } + } + + public void printProvenPresent(Product wantBuyProduct) { + int promotionCount = calculatePromotionCount(wantBuyProduct); + if (promotionCount > 0) { + outputView.printPresentReceipt(wantBuyProduct, promotionCount); + receiptMap.put(PROMOTIONAL_SEPARATOR + wantBuyProduct.getName(), + promotionCount * products.get(wantBuyProduct.getName()).getFirst().getPrice()); + } + } + + public int printFirstReceipt(List<Product> wantBuyProducts) { + outputView.printFirstReceipt(); + int totalBuyCount = calculateTotalBuyCount(wantBuyProducts); + return totalBuyCount; + } + + public int calculateTotalBuyCount(List<Product> wantBuyProducts) { + int totalBuyCount = 0; + for (Product wantBuyProduct : wantBuyProducts) { + Product findProduct = products.get(wantBuyProduct.getName()).getFirst(); + int totalPrice = outputView.printPurchaseReceipt(findProduct, wantBuyProduct); + receiptMap.put(findProduct.getName(), totalPrice); + totalBuyCount += wantBuyProduct.getQuantity(); + } + return totalBuyCount; + } + + + public void applyMemberShip() { + OutputView.printMessage(MEMBERSHIP_BUY); + this.memberShip = inputView.memberShipApply(); + } + + public void checkCanBuyQuantity(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + int count = 0; + List<Product> getProducts = products.get(wantBuyProduct.getName()); + for (Product p : getProducts) { + count += p.getQuantity(); + } + if (wantBuyProduct.getQuantity() > count) { + Exception.throwException(EXCEED_QUANTITY); + } + } + } + + public void checkNotPromotionApply(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + if (products.get(wantBuyProduct.getName()).size() == 1) { + continue; + } + int notPromotionCount = calculateNotPromotionCount(wantBuyProduct); + questionPromotionApply(wantBuyProduct, notPromotionCount); + } + } + + public void questionPromotionApply(Product wantBuyProduct, int notPromotionCount) { + if (notPromotionCount > 0) { + printMessage(NOW + wantBuyProduct.getName() + " " + notPromotionCount + NO_PROMOTION_BUY); + inputView.promotionApply(wantBuyProduct, notPromotionCount); + } + } + + public int calculateNotPromotionCount(Product wantBuyProduct) { + int promotionSetSize = getPromotionSetSize(wantBuyProduct.getName()); + int canBuyPromotionCount = canBuyPromotionProductCount(wantBuyProduct.getName()); + int promotionCount = (canBuyPromotionCount / promotionSetSize) * promotionSetSize; + return wantBuyProduct.getQuantity() - promotionCount; + } + + public int calculatePromotionCount(Product wantBuyProduct) { + int promotionSetSize = getPromotionSetSize(wantBuyProduct.getName()); + return Math.min(products.get(wantBuyProduct.getName()).getFirst().getQuantity() / promotionSetSize, + wantBuyProduct.getQuantity() / promotionSetSize); + } + + public int canBuyPromotionProductCount(String productName) { + return products.get(productName).getFirst().getQuantity(); + } + + public int getPromotionSetSize(String productName) { // 2+1์ผ ๊ฒฝ์šฐ ํ•œ set size๋Š” 3 / 1+1์ผ๋•Œ๋Š” 2 + String promotionName = products.get(productName).getFirst().getPromotion(); + int setSize = 0; + Promotion promotion = promotions.get(promotionName); + setSize = promotion.getBuy() + promotion.getGet(); + return setSize; + } + + + public void checkPromotionApply(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + Promotion promotion = promotions.get(products.get(wantBuyProduct.getName()).getFirst().getPromotion()); + if (promotion != null && promotion.checkPromotionDate()) { + int notBringBonus = calculateBonus(promotion.getBuy(), promotion.getGet(), + wantBuyProduct.getQuantity()); + bringBonus(wantBuyProduct, notBringBonus); + } + } + } + + public int calculateBonus(int buy, int get, int purchasedCount) { + int bonusCount = 0; + if (buy == purchasedCount) { + bonusCount = get; + return bonusCount; + } + if (purchasedCount > buy && purchasedCount % (buy + get) == buy) { + bonusCount = get; + return bonusCount; + } + return bonusCount; + } + + public void bringBonus(Product wantBuyProduct, int notBringBonus) { + if (notBringBonus > 0) { + outputView.printBringPromotion(wantBuyProduct.getName(), notBringBonus); + inputView.addPromotion(wantBuyProduct, notBringBonus); + } + } + + public LinkedHashMap<String, List<Product>> getProducts() { + LinkedHashMap<String, List<Product>> copiedProdcuts = new LinkedHashMap<>(this.products); + return copiedProdcuts; + } +}
Java
ํ˜น์‹œ ์ด ๋ถ€๋ถ„์„ ๋ฉ”์„œ๋“œ๋กœ ๋นผ์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”??
@@ -0,0 +1,357 @@ +package store; + +import static exception.Exception.EXCEED_QUANTITY; +import static exception.Exception.NON_EXIST_PRODUCT; +import static exception.Exception.WRONG_INPUT; +import static exception.Exception.throwException; +import static util.ProductValidator.INVALID_FORMAT; +import static view.InputView.handleRetryOnError; +import static view.OutputView.MEMBERSHIP_BUY; +import static view.OutputView.NOW; +import static view.OutputView.NO_PROMOTION_BUY; +import static view.OutputView.printMessage; + +import dto.Status; +import exception.Exception; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import view.InputView; +import view.OutputView; + +public class Buyer { + + private static final String PROMOTIONAL_SEPARATOR = "P_"; + private static final String PRODUCTS_FILE_NAME = "products.md"; + private static final String PROMOTION_FILE_NAME = "promotions.md"; + private static final String THANK_YOU_MORE_BUY = "\n๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"; + private static final String BLANK_SEPARATOR = "===================================="; + private static final String PROMOTION_SEPARATOR = "=============์ฆ\t\t์ •==============="; + private static final String DUPL_NAME = "[์ค‘๋ณต๋œ ์ œํ’ˆ๋ช…] : "; + private static final int MEMBERSHIP_MAX_DISCOUNT = 8000; + private final InputView inputView; + private final OutputView outputView; + private final LinkedHashMap<String, List<Product>> products; + private final Map<String, Promotion> promotions; + private Map<String, Integer> receiptMap; + private Status memberShip; + + public Buyer() { + this.inputView = new InputView(); + this.outputView = new OutputView(); + this.products = makeProducts(inputView.loadProducts(PRODUCTS_FILE_NAME)); + this.promotions = makePromotions(inputView.loadPromotions(PROMOTION_FILE_NAME)); + outputView.printProducts(products); + } + + public void makePrintProduct(LinkedHashMap<String, List<Product>> products) { + for (String key : products.keySet()) { + List<Product> productList = products.get(key); + if (productList.size() == 1 && productList.getFirst().getPromotion() != null) { + Product product = productList.getFirst(); + productList.add(new Product(product.getName(), product.getPrice(), 0)); + } + } + } + + + public LinkedHashMap<String, List<Product>> makeProducts(List<Product> products) { + LinkedHashMap<String, List<Product>> map = new LinkedHashMap<>(); + for (Product product : products) { + map.computeIfAbsent(product.getName(), k -> new ArrayList<>()) + .add(product); + } + makePrintProduct(map); + return map; + } + + public Map<String, Promotion> makePromotions(List<Promotion> promotions) { + HashMap<String, Promotion> map = new HashMap<>(); + for (Promotion promotion : promotions) { + map.put(promotion.getName(), promotion); + } + return map; + } + + public void buyProducts() { + initializationReceiptMap(); + List<Product> wantBuyProducts = inputBuyProduct(); + checkNotPromotionApply(wantBuyProducts); + applyMemberShip(); + printReceipt(wantBuyProducts); + realBuyProducts(wantBuyProducts); + } + + public void initializationReceiptMap() { + receiptMap = new HashMap<>(); + } + + public List<Product> inputBuyProduct() { + return handleRetryOnError(() -> { + List<Product> wantBuyProducts = inputView.readItem(); + checkDuplProductName(wantBuyProducts); + productNameCheck(wantBuyProducts); + checkPromotionApply(wantBuyProducts); + checkCanBuyQuantity(wantBuyProducts); + return wantBuyProducts; + }); + } + + public void checkDuplProductName(List<Product> wantBuyProducts) { + Set<String> uniqueNames = new HashSet<>(); + for (Product product : wantBuyProducts) { + String productName = product.getName(); + if (!uniqueNames.add(productName)) { + throwException(INVALID_FORMAT + DUPL_NAME + productName); + } + } + } + + public void productNameCheck(List<Product> wantBuyProducts) { + if (wantBuyProducts.isEmpty()) { + Exception.throwException(WRONG_INPUT); + } + for (Product wantBuyProduct : wantBuyProducts) { + if (products.get(wantBuyProduct.getName()) == null) { + Exception.throwException(NON_EXIST_PRODUCT); + } + } + } + + public void realBuyProducts(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + int quantity = wantBuyProduct.getQuantity(); + Product firstProduct = products.get(wantBuyProduct.getName()).getFirst(); + if (withinQuantity(firstProduct, quantity)) { + continue; + } + int restQuantity = quantity - firstProduct.getQuantity(); + firstProduct.subtractQuantity(firstProduct.getQuantity()); + products.get(wantBuyProduct.getName()).get(1).subtractQuantity(restQuantity); + } + } + + public boolean withinQuantity(Product firstProduct, int quantity) { + boolean exceed = false; + if (firstProduct.getQuantity() >= quantity) { + firstProduct.subtractQuantity(quantity); + return true; + } + return exceed; + } + + public void wantContinue() { + while (true) { + printMessage(THANK_YOU_MORE_BUY); + Status status = inputView.wantContinue(); + if (status == Status.Y) { + convenienceContinue(); + } + break; + } + } + + public void convenienceContinue() { + printMessage(null); + outputView.printProducts(products); + buyProducts(); + wantContinue(); + } + + public void printReceipt(List<Product> wantBuyProducts) { + int totalBuyCount = printFirstReceipt(wantBuyProducts); + printPresentReceipt(wantBuyProducts); + printFinalReceipt(totalBuyCount); + } + + + public void printFinalReceipt(int totalBuyCount) { + printMessage(BLANK_SEPARATOR); + int totalMoney = totalMoney(); + int promotionDiscount = promotionDiscount(); + int memberShipDiscount = memberShipDiscount(); + outputView.printFinalReceipt(totalBuyCount, totalMoney, promotionDiscount, memberShipDiscount); + } + + + public int memberShipDiscount() { + int memberShipMoney = 0; + if (memberShip != Status.Y) { + return memberShipMoney; + } + for (String key : receiptMap.keySet()) { + if (!key.startsWith(PROMOTIONAL_SEPARATOR)) { + memberShipMoney += (int) (receiptMap.get(key) * 0.3); + } + } + return Math.min(memberShipMoney, MEMBERSHIP_MAX_DISCOUNT); + } + + public int promotionDiscount() { + int promotionDiscount = 0; + ArrayList<String> removes = new ArrayList<>(); + for (String key : receiptMap.keySet()) { + if (key.startsWith(PROMOTIONAL_SEPARATOR)) { + promotionDiscount += receiptMap.get(key); + removes.add(key.substring(key.indexOf(PROMOTIONAL_SEPARATOR) + PROMOTIONAL_SEPARATOR.length())); + } + } + removeReceiptMap(removes); + return promotionDiscount; + } + + public void removeReceiptMap(List<String> removes) { + for (String remove : removes) { + receiptMap.remove(remove); + } + } + + public int totalMoney() { + int totalMoney = 0; + for (String key : receiptMap.keySet()) { + if (!key.startsWith(PROMOTIONAL_SEPARATOR)) { + totalMoney += receiptMap.get(key); + } + } + return totalMoney; + } + + public void printPresentReceipt(List<Product> wantBuyProducts) { + printMessage(PROMOTION_SEPARATOR); + for (Product wantBuyProduct : wantBuyProducts) { + Promotion promotion = promotions.get(products.get(wantBuyProduct.getName()).getFirst().getPromotion()); + if (products.get(wantBuyProduct.getName()).size() == 1 || !promotion.checkPromotionDate()) { + continue; + } + printProvenPresent(wantBuyProduct); + } + } + + public void printProvenPresent(Product wantBuyProduct) { + int promotionCount = calculatePromotionCount(wantBuyProduct); + if (promotionCount > 0) { + outputView.printPresentReceipt(wantBuyProduct, promotionCount); + receiptMap.put(PROMOTIONAL_SEPARATOR + wantBuyProduct.getName(), + promotionCount * products.get(wantBuyProduct.getName()).getFirst().getPrice()); + } + } + + public int printFirstReceipt(List<Product> wantBuyProducts) { + outputView.printFirstReceipt(); + int totalBuyCount = calculateTotalBuyCount(wantBuyProducts); + return totalBuyCount; + } + + public int calculateTotalBuyCount(List<Product> wantBuyProducts) { + int totalBuyCount = 0; + for (Product wantBuyProduct : wantBuyProducts) { + Product findProduct = products.get(wantBuyProduct.getName()).getFirst(); + int totalPrice = outputView.printPurchaseReceipt(findProduct, wantBuyProduct); + receiptMap.put(findProduct.getName(), totalPrice); + totalBuyCount += wantBuyProduct.getQuantity(); + } + return totalBuyCount; + } + + + public void applyMemberShip() { + OutputView.printMessage(MEMBERSHIP_BUY); + this.memberShip = inputView.memberShipApply(); + } + + public void checkCanBuyQuantity(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + int count = 0; + List<Product> getProducts = products.get(wantBuyProduct.getName()); + for (Product p : getProducts) { + count += p.getQuantity(); + } + if (wantBuyProduct.getQuantity() > count) { + Exception.throwException(EXCEED_QUANTITY); + } + } + } + + public void checkNotPromotionApply(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + if (products.get(wantBuyProduct.getName()).size() == 1) { + continue; + } + int notPromotionCount = calculateNotPromotionCount(wantBuyProduct); + questionPromotionApply(wantBuyProduct, notPromotionCount); + } + } + + public void questionPromotionApply(Product wantBuyProduct, int notPromotionCount) { + if (notPromotionCount > 0) { + printMessage(NOW + wantBuyProduct.getName() + " " + notPromotionCount + NO_PROMOTION_BUY); + inputView.promotionApply(wantBuyProduct, notPromotionCount); + } + } + + public int calculateNotPromotionCount(Product wantBuyProduct) { + int promotionSetSize = getPromotionSetSize(wantBuyProduct.getName()); + int canBuyPromotionCount = canBuyPromotionProductCount(wantBuyProduct.getName()); + int promotionCount = (canBuyPromotionCount / promotionSetSize) * promotionSetSize; + return wantBuyProduct.getQuantity() - promotionCount; + } + + public int calculatePromotionCount(Product wantBuyProduct) { + int promotionSetSize = getPromotionSetSize(wantBuyProduct.getName()); + return Math.min(products.get(wantBuyProduct.getName()).getFirst().getQuantity() / promotionSetSize, + wantBuyProduct.getQuantity() / promotionSetSize); + } + + public int canBuyPromotionProductCount(String productName) { + return products.get(productName).getFirst().getQuantity(); + } + + public int getPromotionSetSize(String productName) { // 2+1์ผ ๊ฒฝ์šฐ ํ•œ set size๋Š” 3 / 1+1์ผ๋•Œ๋Š” 2 + String promotionName = products.get(productName).getFirst().getPromotion(); + int setSize = 0; + Promotion promotion = promotions.get(promotionName); + setSize = promotion.getBuy() + promotion.getGet(); + return setSize; + } + + + public void checkPromotionApply(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + Promotion promotion = promotions.get(products.get(wantBuyProduct.getName()).getFirst().getPromotion()); + if (promotion != null && promotion.checkPromotionDate()) { + int notBringBonus = calculateBonus(promotion.getBuy(), promotion.getGet(), + wantBuyProduct.getQuantity()); + bringBonus(wantBuyProduct, notBringBonus); + } + } + } + + public int calculateBonus(int buy, int get, int purchasedCount) { + int bonusCount = 0; + if (buy == purchasedCount) { + bonusCount = get; + return bonusCount; + } + if (purchasedCount > buy && purchasedCount % (buy + get) == buy) { + bonusCount = get; + return bonusCount; + } + return bonusCount; + } + + public void bringBonus(Product wantBuyProduct, int notBringBonus) { + if (notBringBonus > 0) { + outputView.printBringPromotion(wantBuyProduct.getName(), notBringBonus); + inputView.addPromotion(wantBuyProduct, notBringBonus); + } + } + + public LinkedHashMap<String, List<Product>> getProducts() { + LinkedHashMap<String, List<Product>> copiedProdcuts = new LinkedHashMap<>(this.products); + return copiedProdcuts; + } +}
Java
๊ฐœ์ธ์ ์œผ๋กœ ์ด ๋ถ€๋ถ„์ด ๊ฐ€๋…์„ฑ์ด ์กฐ๊ธˆ์€ ์ข‹์ง€ ์•Š์€ ๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค! ๋ฉ”์†Œ๋“œ๋ฅผ ๋ถ„๋ฆฌํ•˜๋Š” ๋ฐฉ๋ฒ•๊ณผ ๋ณ€์ˆ˜๋ฅผ ์„ค์ •ํ•˜๋Š” ๊ฑธ ์ถ”์ฒœ๋“œ๋ ค๋ด…๋‹ˆ๋‹ค!
@@ -0,0 +1,357 @@ +package store; + +import static exception.Exception.EXCEED_QUANTITY; +import static exception.Exception.NON_EXIST_PRODUCT; +import static exception.Exception.WRONG_INPUT; +import static exception.Exception.throwException; +import static util.ProductValidator.INVALID_FORMAT; +import static view.InputView.handleRetryOnError; +import static view.OutputView.MEMBERSHIP_BUY; +import static view.OutputView.NOW; +import static view.OutputView.NO_PROMOTION_BUY; +import static view.OutputView.printMessage; + +import dto.Status; +import exception.Exception; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import view.InputView; +import view.OutputView; + +public class Buyer { + + private static final String PROMOTIONAL_SEPARATOR = "P_"; + private static final String PRODUCTS_FILE_NAME = "products.md"; + private static final String PROMOTION_FILE_NAME = "promotions.md"; + private static final String THANK_YOU_MORE_BUY = "\n๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"; + private static final String BLANK_SEPARATOR = "===================================="; + private static final String PROMOTION_SEPARATOR = "=============์ฆ\t\t์ •==============="; + private static final String DUPL_NAME = "[์ค‘๋ณต๋œ ์ œํ’ˆ๋ช…] : "; + private static final int MEMBERSHIP_MAX_DISCOUNT = 8000; + private final InputView inputView; + private final OutputView outputView; + private final LinkedHashMap<String, List<Product>> products; + private final Map<String, Promotion> promotions; + private Map<String, Integer> receiptMap; + private Status memberShip; + + public Buyer() { + this.inputView = new InputView(); + this.outputView = new OutputView(); + this.products = makeProducts(inputView.loadProducts(PRODUCTS_FILE_NAME)); + this.promotions = makePromotions(inputView.loadPromotions(PROMOTION_FILE_NAME)); + outputView.printProducts(products); + } + + public void makePrintProduct(LinkedHashMap<String, List<Product>> products) { + for (String key : products.keySet()) { + List<Product> productList = products.get(key); + if (productList.size() == 1 && productList.getFirst().getPromotion() != null) { + Product product = productList.getFirst(); + productList.add(new Product(product.getName(), product.getPrice(), 0)); + } + } + } + + + public LinkedHashMap<String, List<Product>> makeProducts(List<Product> products) { + LinkedHashMap<String, List<Product>> map = new LinkedHashMap<>(); + for (Product product : products) { + map.computeIfAbsent(product.getName(), k -> new ArrayList<>()) + .add(product); + } + makePrintProduct(map); + return map; + } + + public Map<String, Promotion> makePromotions(List<Promotion> promotions) { + HashMap<String, Promotion> map = new HashMap<>(); + for (Promotion promotion : promotions) { + map.put(promotion.getName(), promotion); + } + return map; + } + + public void buyProducts() { + initializationReceiptMap(); + List<Product> wantBuyProducts = inputBuyProduct(); + checkNotPromotionApply(wantBuyProducts); + applyMemberShip(); + printReceipt(wantBuyProducts); + realBuyProducts(wantBuyProducts); + } + + public void initializationReceiptMap() { + receiptMap = new HashMap<>(); + } + + public List<Product> inputBuyProduct() { + return handleRetryOnError(() -> { + List<Product> wantBuyProducts = inputView.readItem(); + checkDuplProductName(wantBuyProducts); + productNameCheck(wantBuyProducts); + checkPromotionApply(wantBuyProducts); + checkCanBuyQuantity(wantBuyProducts); + return wantBuyProducts; + }); + } + + public void checkDuplProductName(List<Product> wantBuyProducts) { + Set<String> uniqueNames = new HashSet<>(); + for (Product product : wantBuyProducts) { + String productName = product.getName(); + if (!uniqueNames.add(productName)) { + throwException(INVALID_FORMAT + DUPL_NAME + productName); + } + } + } + + public void productNameCheck(List<Product> wantBuyProducts) { + if (wantBuyProducts.isEmpty()) { + Exception.throwException(WRONG_INPUT); + } + for (Product wantBuyProduct : wantBuyProducts) { + if (products.get(wantBuyProduct.getName()) == null) { + Exception.throwException(NON_EXIST_PRODUCT); + } + } + } + + public void realBuyProducts(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + int quantity = wantBuyProduct.getQuantity(); + Product firstProduct = products.get(wantBuyProduct.getName()).getFirst(); + if (withinQuantity(firstProduct, quantity)) { + continue; + } + int restQuantity = quantity - firstProduct.getQuantity(); + firstProduct.subtractQuantity(firstProduct.getQuantity()); + products.get(wantBuyProduct.getName()).get(1).subtractQuantity(restQuantity); + } + } + + public boolean withinQuantity(Product firstProduct, int quantity) { + boolean exceed = false; + if (firstProduct.getQuantity() >= quantity) { + firstProduct.subtractQuantity(quantity); + return true; + } + return exceed; + } + + public void wantContinue() { + while (true) { + printMessage(THANK_YOU_MORE_BUY); + Status status = inputView.wantContinue(); + if (status == Status.Y) { + convenienceContinue(); + } + break; + } + } + + public void convenienceContinue() { + printMessage(null); + outputView.printProducts(products); + buyProducts(); + wantContinue(); + } + + public void printReceipt(List<Product> wantBuyProducts) { + int totalBuyCount = printFirstReceipt(wantBuyProducts); + printPresentReceipt(wantBuyProducts); + printFinalReceipt(totalBuyCount); + } + + + public void printFinalReceipt(int totalBuyCount) { + printMessage(BLANK_SEPARATOR); + int totalMoney = totalMoney(); + int promotionDiscount = promotionDiscount(); + int memberShipDiscount = memberShipDiscount(); + outputView.printFinalReceipt(totalBuyCount, totalMoney, promotionDiscount, memberShipDiscount); + } + + + public int memberShipDiscount() { + int memberShipMoney = 0; + if (memberShip != Status.Y) { + return memberShipMoney; + } + for (String key : receiptMap.keySet()) { + if (!key.startsWith(PROMOTIONAL_SEPARATOR)) { + memberShipMoney += (int) (receiptMap.get(key) * 0.3); + } + } + return Math.min(memberShipMoney, MEMBERSHIP_MAX_DISCOUNT); + } + + public int promotionDiscount() { + int promotionDiscount = 0; + ArrayList<String> removes = new ArrayList<>(); + for (String key : receiptMap.keySet()) { + if (key.startsWith(PROMOTIONAL_SEPARATOR)) { + promotionDiscount += receiptMap.get(key); + removes.add(key.substring(key.indexOf(PROMOTIONAL_SEPARATOR) + PROMOTIONAL_SEPARATOR.length())); + } + } + removeReceiptMap(removes); + return promotionDiscount; + } + + public void removeReceiptMap(List<String> removes) { + for (String remove : removes) { + receiptMap.remove(remove); + } + } + + public int totalMoney() { + int totalMoney = 0; + for (String key : receiptMap.keySet()) { + if (!key.startsWith(PROMOTIONAL_SEPARATOR)) { + totalMoney += receiptMap.get(key); + } + } + return totalMoney; + } + + public void printPresentReceipt(List<Product> wantBuyProducts) { + printMessage(PROMOTION_SEPARATOR); + for (Product wantBuyProduct : wantBuyProducts) { + Promotion promotion = promotions.get(products.get(wantBuyProduct.getName()).getFirst().getPromotion()); + if (products.get(wantBuyProduct.getName()).size() == 1 || !promotion.checkPromotionDate()) { + continue; + } + printProvenPresent(wantBuyProduct); + } + } + + public void printProvenPresent(Product wantBuyProduct) { + int promotionCount = calculatePromotionCount(wantBuyProduct); + if (promotionCount > 0) { + outputView.printPresentReceipt(wantBuyProduct, promotionCount); + receiptMap.put(PROMOTIONAL_SEPARATOR + wantBuyProduct.getName(), + promotionCount * products.get(wantBuyProduct.getName()).getFirst().getPrice()); + } + } + + public int printFirstReceipt(List<Product> wantBuyProducts) { + outputView.printFirstReceipt(); + int totalBuyCount = calculateTotalBuyCount(wantBuyProducts); + return totalBuyCount; + } + + public int calculateTotalBuyCount(List<Product> wantBuyProducts) { + int totalBuyCount = 0; + for (Product wantBuyProduct : wantBuyProducts) { + Product findProduct = products.get(wantBuyProduct.getName()).getFirst(); + int totalPrice = outputView.printPurchaseReceipt(findProduct, wantBuyProduct); + receiptMap.put(findProduct.getName(), totalPrice); + totalBuyCount += wantBuyProduct.getQuantity(); + } + return totalBuyCount; + } + + + public void applyMemberShip() { + OutputView.printMessage(MEMBERSHIP_BUY); + this.memberShip = inputView.memberShipApply(); + } + + public void checkCanBuyQuantity(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + int count = 0; + List<Product> getProducts = products.get(wantBuyProduct.getName()); + for (Product p : getProducts) { + count += p.getQuantity(); + } + if (wantBuyProduct.getQuantity() > count) { + Exception.throwException(EXCEED_QUANTITY); + } + } + } + + public void checkNotPromotionApply(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + if (products.get(wantBuyProduct.getName()).size() == 1) { + continue; + } + int notPromotionCount = calculateNotPromotionCount(wantBuyProduct); + questionPromotionApply(wantBuyProduct, notPromotionCount); + } + } + + public void questionPromotionApply(Product wantBuyProduct, int notPromotionCount) { + if (notPromotionCount > 0) { + printMessage(NOW + wantBuyProduct.getName() + " " + notPromotionCount + NO_PROMOTION_BUY); + inputView.promotionApply(wantBuyProduct, notPromotionCount); + } + } + + public int calculateNotPromotionCount(Product wantBuyProduct) { + int promotionSetSize = getPromotionSetSize(wantBuyProduct.getName()); + int canBuyPromotionCount = canBuyPromotionProductCount(wantBuyProduct.getName()); + int promotionCount = (canBuyPromotionCount / promotionSetSize) * promotionSetSize; + return wantBuyProduct.getQuantity() - promotionCount; + } + + public int calculatePromotionCount(Product wantBuyProduct) { + int promotionSetSize = getPromotionSetSize(wantBuyProduct.getName()); + return Math.min(products.get(wantBuyProduct.getName()).getFirst().getQuantity() / promotionSetSize, + wantBuyProduct.getQuantity() / promotionSetSize); + } + + public int canBuyPromotionProductCount(String productName) { + return products.get(productName).getFirst().getQuantity(); + } + + public int getPromotionSetSize(String productName) { // 2+1์ผ ๊ฒฝ์šฐ ํ•œ set size๋Š” 3 / 1+1์ผ๋•Œ๋Š” 2 + String promotionName = products.get(productName).getFirst().getPromotion(); + int setSize = 0; + Promotion promotion = promotions.get(promotionName); + setSize = promotion.getBuy() + promotion.getGet(); + return setSize; + } + + + public void checkPromotionApply(List<Product> wantBuyProducts) { + for (Product wantBuyProduct : wantBuyProducts) { + Promotion promotion = promotions.get(products.get(wantBuyProduct.getName()).getFirst().getPromotion()); + if (promotion != null && promotion.checkPromotionDate()) { + int notBringBonus = calculateBonus(promotion.getBuy(), promotion.getGet(), + wantBuyProduct.getQuantity()); + bringBonus(wantBuyProduct, notBringBonus); + } + } + } + + public int calculateBonus(int buy, int get, int purchasedCount) { + int bonusCount = 0; + if (buy == purchasedCount) { + bonusCount = get; + return bonusCount; + } + if (purchasedCount > buy && purchasedCount % (buy + get) == buy) { + bonusCount = get; + return bonusCount; + } + return bonusCount; + } + + public void bringBonus(Product wantBuyProduct, int notBringBonus) { + if (notBringBonus > 0) { + outputView.printBringPromotion(wantBuyProduct.getName(), notBringBonus); + inputView.addPromotion(wantBuyProduct, notBringBonus); + } + } + + public LinkedHashMap<String, List<Product>> getProducts() { + LinkedHashMap<String, List<Product>> copiedProdcuts = new LinkedHashMap<>(this.products); + return copiedProdcuts; + } +}
Java
ํ•œ ํด๋ž˜์Šค๊ฐ€ ๋„ˆ๋ฌด๋‚˜ ๋งŽ์€ ์—ญํ• ์„ ํ•˜๊ณ  ์žˆ๋Š” ๊ฑฐ ๊ฐ™์•„์š”!! ๊ตฌ๋งค์ž๊ฐ€ ํ•˜๋Š” ์—ญํ• , ํŽธ์˜์ ์—์„œ ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ๊ณผ ๊ฐ™์€ ์—ญํ•  ๋“ฑ ํด๋ž˜์Šค ๋ถ„๋ฆฌํ•ด ์ž‘์„ฑํ•˜๋Š” ๊ฑธ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,25 @@ +package christmas.config; + +public enum Configuration { + ; + + private final Object value; + + Configuration(Object value) { + this.value = value; + } + + public int getIntValue() { + if (value instanceof Integer) { + return (int) value; + } + throw new IllegalStateException("Value is not an integer: " + value); + } + + public String getStringValue() { + if (value instanceof String) { + return (String) value; + } + throw new IllegalStateException("Value is not a string: " + value); + } +}
Java
Configuration์€ ์–ด๋””์„œ ํ™œ์šฉ๋˜๋‚˜์š”?
@@ -0,0 +1,45 @@ +package christmas.controller; + +import christmas.domain.Order; +import christmas.domain.Orders; +import christmas.domain.product.Product; +import christmas.repository.ProductRepository; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +public class InputParser { + public static final int ITEM_NAME_INDEX = 0; + public static final int ITEM_QUANTITY_INDEX = 1; + private final ProductRepository productRepository; + + public InputParser(ProductRepository productRepository) { + this.productRepository = productRepository; + } + + public int parseInt(String input) { + try { + return Integer.parseInt(input); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(e); + } + } + + public Orders parseOrders(String input) { + List<Order> orders = new ArrayList<>(); + + List<String> splitInput = Arrays.stream(input.split(",")).toList(); + for (String itemInput : splitInput) { + List<String> field = Arrays.stream(itemInput.split("-")).toList(); + + Optional<Product> product = this.productRepository.findByName(field.get(ITEM_NAME_INDEX).strip()); + if (product.isEmpty()) { + throw new IllegalArgumentException(); + } + orders.add(new Order(product.get(), parseInt(field.get(ITEM_QUANTITY_INDEX).strip()))); + } + return new Orders(orders); + } + +}
Java
Repository๋ฅผ static์ด ์•„๋‹Œ ์˜์กด์„ฑ ์ฃผ์ž…์œผ๋กœ ์‚ฌ์šฉํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค! ๋‘˜ ์ค‘ ์–ด๋–ค ๊ฒŒ ์ ์ ˆํ•œ์ง€ ๊ณ ๋ฏผ๋ผ์„œ์š”
@@ -0,0 +1,56 @@ +package christmas.controller; + +import christmas.domain.Orders; +import christmas.view.InputView; +import christmas.view.OutputView; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +public class RetryInputUtil { + + private final InputParser inputParser; + + public RetryInputUtil(InputParser inputParser) { + this.inputParser = inputParser; + } + + public int getDay() { + return retryLogics(InputView::getDay, inputParser::parseInt, this::dayValidate, "์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + public Orders getOrders() { + return retryLogics(InputView::getOrders, inputParser::parseOrders, "์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + private void dayValidate(int day) { + if (!(1 <= day && day <= 31)) { + throw new IllegalArgumentException(); + } + } + + private <T> T retryLogics(Supplier<String> userInputReader, Function<String, T> parser, Consumer<T> validator, String errorMessage) { + while (true) { + try { + String userInput = userInputReader.get(); + T parsedInput = parser.apply(userInput); + validator.accept(parsedInput); + return parsedInput; + } catch (IllegalArgumentException error) { + OutputView.printError(errorMessage); + } + } + } + + private <T> T retryLogics(Supplier<String> userInputReader, Function<String, T> parser, String errorMessage) { + while (true) { + try { + String userInput = userInputReader.get(); + return parser.apply(userInput); + } catch (IllegalArgumentException error) { + OutputView.printError(errorMessage); + } + + } + } +}
Java
Orders์— ๋Œ€ํ•œ validation๋„ ์ถ”๊ฐ€ํ•œ๋‹ค๋ฉด retryLogics() ํ•˜๋‚˜๋กœ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,76 @@ +package christmas.dto; + +import christmas.enums.Badge; +import christmas.enums.BenefitType; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +public record BenefitResultDto( + int day, + List<ItemDto> orderedItems, + int totalPrice, + Optional<ItemDto> giveaway, + Map<BenefitType, Integer> benefits, + int totalBenefitAmount, + int expectedPaymentAmount, + Optional<Badge> badge +) { + + public static class Builder { + int day; + List<ItemDto> orderedItems; + int totalPrice; + Optional<ItemDto> giveaway; + Map<BenefitType, Integer> benefits; + int totalBenefitAmount; + int expectedPaymentAmount; + Optional<Badge> badge; + + public Builder day(int day) { + this.day = day; + return this; + } + + public Builder orderedItems(List<ItemDto> orderedItems) { + this.orderedItems = orderedItems; + return this; + } + + public Builder totalPrice(int totalPrice) { + this.totalPrice = totalPrice; + return this; + } + + public Builder giveaway(Optional<ItemDto> giveaway) { + this.giveaway = giveaway; + return this; + } + + public Builder benefits(Map<BenefitType, Integer> benefits) { + this.benefits = benefits; + return this; + } + + public Builder totalBenefitAmount(int totalBenefitAmount) { + this.totalBenefitAmount = totalBenefitAmount; + return this; + } + + public Builder expectedPaymentAmount(int expectedPaymentAmount) { + this.expectedPaymentAmount = expectedPaymentAmount; + return this; + } + + public Builder badge(Optional<Badge> badge) { + this.badge = badge; + return this; + } + + public BenefitResultDto build() { + return new BenefitResultDto(day, orderedItems, totalPrice, giveaway, benefits, + totalBenefitAmount, + expectedPaymentAmount, badge); + } + } +}
Java
์ €๋„ ๊ฒฐ๊ณผ ์ •๋ณด๋“ค์„ dto๋กœ ๋งŒ๋“ค์—ˆ์ง€๋งŒ ํ•„๋“œ๊ฐ€ ๋„ˆ๋ฌด ๋งŽ์€ ๊ฒƒ์ด ๊ณ ๋ฏผ์ด ๋˜์—ˆ๋Š”๋ฐ, ๋นŒ๋”๋ฅผ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๊ฒ ๋„ค์š”!
@@ -0,0 +1,35 @@ +package christmas.enums; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +public enum Badge { + STAR(5_000, "๋ณ„"), + TREE(10_000, "ํŠธ๋ฆฌ"), + SANTA(20_000, "์‚ฐํƒ€"); + + private final int discountAmount; + private final String name; + + Badge(int discountAmount, String name) { + this.discountAmount = discountAmount; + this.name = name; + } + + public String getName() { + return name; + } + + public static Optional<Badge> getBadgeByPaymentAmount(int discountAmount) { + List<Badge> badges = Arrays.stream(Badge.values()).sorted().toList(); + + Badge selectedBadge = null; + for (Badge badge : badges) { + if (badge.discountAmount <= discountAmount) { + selectedBadge = badge; + } + } + return Optional.ofNullable(selectedBadge); + } +}
Java
์—ฌ๊ธฐ์— "์—†์Œ"์„ name์œผ๋กœ ๊ฐ–๋Š” enum์„ ์ถ”๊ฐ€ํ•˜๋ฉด Optional<Badge> ๋Œ€์‹  ํ™œ์šฉํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,56 @@ +package christmas.controller; + +import christmas.domain.Orders; +import christmas.view.InputView; +import christmas.view.OutputView; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +public class RetryInputUtil { + + private final InputParser inputParser; + + public RetryInputUtil(InputParser inputParser) { + this.inputParser = inputParser; + } + + public int getDay() { + return retryLogics(InputView::getDay, inputParser::parseInt, this::dayValidate, "์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + public Orders getOrders() { + return retryLogics(InputView::getOrders, inputParser::parseOrders, "์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + private void dayValidate(int day) { + if (!(1 <= day && day <= 31)) { + throw new IllegalArgumentException(); + } + } + + private <T> T retryLogics(Supplier<String> userInputReader, Function<String, T> parser, Consumer<T> validator, String errorMessage) { + while (true) { + try { + String userInput = userInputReader.get(); + T parsedInput = parser.apply(userInput); + validator.accept(parsedInput); + return parsedInput; + } catch (IllegalArgumentException error) { + OutputView.printError(errorMessage); + } + } + } + + private <T> T retryLogics(Supplier<String> userInputReader, Function<String, T> parser, String errorMessage) { + while (true) { + try { + String userInput = userInputReader.get(); + return parser.apply(userInput); + } catch (IllegalArgumentException error) { + OutputView.printError(errorMessage); + } + + } + } +}
Java
1๊ณผ 31๊ฐ™์€ ๋งค์ง๋„˜๋ฒ„๋Š” ์ƒ์ˆ˜๋กœ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ์–ด๋–จ๊นŒ์š”? ๊ทธ๋ฆฌ๊ณ  ์กฐ๊ฑด์‹์˜ ๊ฒฝ์šฐ, ๊ธ์ • ์กฐ๊ฑด์‹์ด ๊ฐ€๋…์„ฑ์ด ๋” ์ข‹๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,38 @@ +package christmas.domain; + +import christmas.dto.ItemDto; +import christmas.validator.OrdersValidator; +import java.util.ArrayList; +import java.util.List; + +public class Orders { + private final List<Order> orders; + + public Orders(List<Order> orders) { + OrdersValidator.validate(orders); + this.orders = orders; + } + + public int calculateTotalPrice() { + return orders.stream().mapToInt(Order::getPrice).sum(); + } + + public List<Order> getOrders() { + return List.copyOf(orders); + } + + public List<ItemDto> toDto() { + List<ItemDto> items = new ArrayList<>(); + for (Order order : orders) { + items.add(new ItemDto(order.getProduct(), order.getQuantity())); + } + return items; + } + + @Override + public String toString() { + return "Orders{" + + "orders=" + orders + + '}'; + } +}
Java
Stream์„ ์ด์šฉํ•ด๋ณด๋Š”๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,36 @@ +package christmas.domain.product; + +import christmas.enums.ProductType; + +public class Product { + private final String name; + private final int price; + private final ProductType type; + + public Product(String name, int price, ProductType type) { + this.name = name; + this.price = price; + this.type = type; + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public ProductType getType() { + return type; + } + + @Override + public String toString() { + return "Product{" + + "name='" + name + '\'' + + ", price=" + price + + ", type=" + type + + '}'; + } +}
Java
์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” toString์„ ์žฌ์ •์˜ํ•œ ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,37 @@ +package christmas.enums; + +public enum DayOfWeek { + MONDAY(0), + TUESDAY(1), + WEDNESDAY(2), + THURSDAY(3), + FRIDAY(4), + SATURDAY(5), + SUNDAY(6); + + public static final DayOfWeek START_OF_WEEK = FRIDAY; + private final int order; + + + DayOfWeek(int order) { + this.order = order; + } + + public int getOrder() { + return this.order; + } + + private static DayOfWeek getDayOfWeekByOrder(int order) { + for (DayOfWeek day : DayOfWeek.values()) { + if (day.order == order) { + return day; + } + } + throw new IllegalArgumentException("Invalid day of week: " + order); + } + + public static DayOfWeek getDayOfWeekAsDate(int day) { + int order = (START_OF_WEEK.getOrder() + day - 1) / 7; + return getDayOfWeekByOrder(order); + } +}
Java
์ €๋Š” ๋ฆฌ์ŠคํŠธ๋กœ ๋ชจ๋“  ๋‚ ์งœ๋ฅผ enum์œผ๋กœ ๊ด€๋ฆฌํ–ˆ๋Š”๋ฐ, ์ด๋ ‡๊ฒŒ ์ˆ˜์‹์œผ๋กœ ์ฒ˜๋ฆฌํ•  ์ˆ˜๋„ ์žˆ๊ฒ ๋„ค์š”!
@@ -0,0 +1,37 @@ +package christmas.config; + +import christmas.controller.Controller; +import christmas.controller.InputParser; +import christmas.controller.RetryInputUtil; +import christmas.file.parser.ProductParser; +import christmas.file.reader.CsvReader; +import christmas.initializer.ProductInitializer; +import christmas.repository.ProductRepository; +import christmas.service.PromotionService; + +public class DependencyInjector { + public Controller createController() { + ProductRepository productRepository = getProductRepository(); + InputParser inputParser = getInputParser(productRepository); + RetryInputUtil retryInputUtil = getRetryInputUtil(inputParser); + PromotionService promotionService = new PromotionService(productRepository); + + ProductParser productParser = new ProductParser(CsvReader.of("products.md", false)); + ProductInitializer initializer = new ProductInitializer(productRepository, productParser); + initializer.init(); + + return new Controller(retryInputUtil, promotionService); + } + + private static ProductRepository getProductRepository() { + return new ProductRepository(); + } + + private static InputParser getInputParser(ProductRepository productRepository) { + return new InputParser(productRepository); + } + + private static RetryInputUtil getRetryInputUtil(InputParser inputParser) { + return new RetryInputUtil(inputParser); + } +}
Java
์ด๋ฒˆ ํ”„๋ฆฌ์ฝ”์Šค 4์ฃผ์ฐจ ๋ฏธ์…˜์—์„œ mdํŒŒ์ผ์„ ์ฝ์–ด์˜ค๋Š”๊ฒƒ์ด ์žˆ์—ˆ๋Š”๋ฐ ํฌ๋ฆฌ์Šค๋งˆ์Šค ๊ณผ์ œ๋„ ์ด๋ ‡๊ฒŒ ํ‘ธ์‹œ๋‹ค๋‹ˆ ์ตœ์ข… ์ฝ”ํ…Œ ๋Œ€๋น„๋ฅผ ์ œ๋Œ€๋กœ ํ•˜์‹œ๋Š”๊ตฐ์š”!
@@ -0,0 +1,23 @@ +package christmas.domain.promotion; + +public class GiveawayPromotion { + + private static final int GIVEAWAY_PAYMENT_AMOUNT = 120_000; + private static final String GIVEAWAY_PRODUCT_NAME = "์ƒดํŽ˜์ธ"; + private static final int GIVEAWAY_PRODUCT_AMOUNT = 1; + + public static boolean isAvailable(int paymentAmount) { + if (paymentAmount < GIVEAWAY_PAYMENT_AMOUNT) { + return false; + } + return true; + } + + public static String getGiveawayProductName() { + return GIVEAWAY_PRODUCT_NAME; + } + + public static int getGiveawayProductQuantity() { + return GIVEAWAY_PRODUCT_AMOUNT; + } +}
Java
์ฆ์ •ํ’ˆ ๋ถ€๋ถ„์„ ํ•˜๋“œ์ฝ”๋”ฉํ•˜๋Š”๊ฒŒ ์•„๋‹Œ, ๋ ˆํŒŒ์ง€ํ† ๋ฆฌ์—์„œ ๊ฐ€์ ธ์˜ค๋Š” ๋กœ์ง์€ ์–ด๋– ์‹ ๊ฐ€์š”?
@@ -3,38 +3,52 @@ import com.flab.ccinside.api.trendingpost.application.port.ViewPostEvent; import com.flab.ccinside.api.trendingpost.application.port.in.PostSystemUsecase; import com.flab.ccinside.api.trendingpost.application.port.in.UpdateViewCountCommand; -import jakarta.annotation.PostConstruct; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import lombok.RequiredArgsConstructor; +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; @Slf4j @Component -@RequiredArgsConstructor public class InMemoryMessageQueue { - private final PostSystemUsecase postSystemUsecase; - private final BlockingQueue<ViewPostEvent> queue; - private final ExecutorService executorService = Executors.newSingleThreadExecutor(); + private static final Long INITIAL_DELAY = 10L; + private static final Long FIXED_DELAY = 100L; + private static final int THRESHOLD = 100; - @PostConstruct - public void init() { - executorService.submit( - () -> { - try { - while (true) { - var event = queue.take(); - log.info("View post event consumed. postId: {}", event.postId()); - var command = new UpdateViewCountCommand(event.postId()); - postSystemUsecase.updateViewCount(command); - } - } catch (InterruptedException e) { - log.error("consume error: {}", e.getMessage()); - throw new RuntimeException(e); - } - }); + public InMemoryMessageQueue( + PostSystemUsecase postSystemUsecase, + Queue<ViewPostEvent> queue, + ScheduledExecutorService executorService) { + + executorService.scheduleWithFixedDelay( + createEventConsumerRunnable(postSystemUsecase, queue), + INITIAL_DELAY, + FIXED_DELAY, + TimeUnit.MILLISECONDS); + } + + private Runnable createEventConsumerRunnable( + PostSystemUsecase postSystemUsecase, Queue<ViewPostEvent> queue) { + return () -> { + try { + List<UpdateViewCountCommand> commands = new ArrayList<>(); + ViewPostEvent event; + int count = 0; + while ((event = queue.poll()) != null && count < THRESHOLD) { + log.info("View post event consumed. postId: {}", event.postId()); + var command = new UpdateViewCountCommand(event.postId()); + postSystemUsecase.updateViewCount(command); + commands.add(command); + count++; + } + postSystemUsecase.persistViewCountsInBatch(commands); + } catch (Exception e) { + log.error("error: {}", e.getMessage()); + } + }; } }
Java
queue๊ฐ€ ๊ณ„์† ์ฐจ ์žˆ๋Š” ๊ฒฝ์šฐ์—๋Š” ๋ฌดํ•œ ๋ฃจํ”„์— ๋น ์ง€๊ฒŒ ๋  ๊ฒƒ ๊ฐ™๋„ค์š”.
@@ -3,38 +3,52 @@ import com.flab.ccinside.api.trendingpost.application.port.ViewPostEvent; import com.flab.ccinside.api.trendingpost.application.port.in.PostSystemUsecase; import com.flab.ccinside.api.trendingpost.application.port.in.UpdateViewCountCommand; -import jakarta.annotation.PostConstruct; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import lombok.RequiredArgsConstructor; +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; @Slf4j @Component -@RequiredArgsConstructor public class InMemoryMessageQueue { - private final PostSystemUsecase postSystemUsecase; - private final BlockingQueue<ViewPostEvent> queue; - private final ExecutorService executorService = Executors.newSingleThreadExecutor(); + private static final Long INITIAL_DELAY = 10L; + private static final Long FIXED_DELAY = 100L; + private static final int THRESHOLD = 100; - @PostConstruct - public void init() { - executorService.submit( - () -> { - try { - while (true) { - var event = queue.take(); - log.info("View post event consumed. postId: {}", event.postId()); - var command = new UpdateViewCountCommand(event.postId()); - postSystemUsecase.updateViewCount(command); - } - } catch (InterruptedException e) { - log.error("consume error: {}", e.getMessage()); - throw new RuntimeException(e); - } - }); + public InMemoryMessageQueue( + PostSystemUsecase postSystemUsecase, + Queue<ViewPostEvent> queue, + ScheduledExecutorService executorService) { + + executorService.scheduleWithFixedDelay( + createEventConsumerRunnable(postSystemUsecase, queue), + INITIAL_DELAY, + FIXED_DELAY, + TimeUnit.MILLISECONDS); + } + + private Runnable createEventConsumerRunnable( + PostSystemUsecase postSystemUsecase, Queue<ViewPostEvent> queue) { + return () -> { + try { + List<UpdateViewCountCommand> commands = new ArrayList<>(); + ViewPostEvent event; + int count = 0; + while ((event = queue.poll()) != null && count < THRESHOLD) { + log.info("View post event consumed. postId: {}", event.postId()); + var command = new UpdateViewCountCommand(event.postId()); + postSystemUsecase.updateViewCount(command); + commands.add(command); + count++; + } + postSystemUsecase.persistViewCountsInBatch(commands); + } catch (Exception e) { + log.error("error: {}", e.getMessage()); + } + }; } }
Java
executorService๊ฐ€ ๋กœ์ง์„ ์ œ๋Œ€๋กœ ์‹คํ–‰ํ•œ๋‹ค๋Š” ๊ฒƒ์€ ์–ด๋–ป๊ฒŒ ํ…Œ์ŠคํŠธ ํ•  ์ˆ˜ ์žˆ์„๊นŒ์š”?
@@ -3,38 +3,52 @@ import com.flab.ccinside.api.trendingpost.application.port.ViewPostEvent; import com.flab.ccinside.api.trendingpost.application.port.in.PostSystemUsecase; import com.flab.ccinside.api.trendingpost.application.port.in.UpdateViewCountCommand; -import jakarta.annotation.PostConstruct; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import lombok.RequiredArgsConstructor; +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; @Slf4j @Component -@RequiredArgsConstructor public class InMemoryMessageQueue { - private final PostSystemUsecase postSystemUsecase; - private final BlockingQueue<ViewPostEvent> queue; - private final ExecutorService executorService = Executors.newSingleThreadExecutor(); + private static final Long INITIAL_DELAY = 10L; + private static final Long FIXED_DELAY = 100L; + private static final int THRESHOLD = 100; - @PostConstruct - public void init() { - executorService.submit( - () -> { - try { - while (true) { - var event = queue.take(); - log.info("View post event consumed. postId: {}", event.postId()); - var command = new UpdateViewCountCommand(event.postId()); - postSystemUsecase.updateViewCount(command); - } - } catch (InterruptedException e) { - log.error("consume error: {}", e.getMessage()); - throw new RuntimeException(e); - } - }); + public InMemoryMessageQueue( + PostSystemUsecase postSystemUsecase, + Queue<ViewPostEvent> queue, + ScheduledExecutorService executorService) { + + executorService.scheduleWithFixedDelay( + createEventConsumerRunnable(postSystemUsecase, queue), + INITIAL_DELAY, + FIXED_DELAY, + TimeUnit.MILLISECONDS); + } + + private Runnable createEventConsumerRunnable( + PostSystemUsecase postSystemUsecase, Queue<ViewPostEvent> queue) { + return () -> { + try { + List<UpdateViewCountCommand> commands = new ArrayList<>(); + ViewPostEvent event; + int count = 0; + while ((event = queue.poll()) != null && count < THRESHOLD) { + log.info("View post event consumed. postId: {}", event.postId()); + var command = new UpdateViewCountCommand(event.postId()); + postSystemUsecase.updateViewCount(command); + commands.add(command); + count++; + } + postSystemUsecase.persistViewCountsInBatch(commands); + } catch (Exception e) { + log.error("error: {}", e.getMessage()); + } + }; } }
Java
๋ง์”€ํ•ด์ฃผ์‹ ๋Œ€๋กœ, ๋น„๋™๊ธฐ ํ”„๋กœ์„ธ์Šค ์ƒ์„ฑ์— ๋Œ€ํ•œ ๋ถ€๋ถ„๊ณผ, ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง ์ฒ˜๋ฆฌ์—๋Œ€ํ•œ ๋ถ€๋ถ„์„ ๋ถ„๋ฆฌํ•˜์—ฌ ๊ฐ๊ฐ ํ…Œ์ŠคํŠธํ•˜๋„๋ก ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :)
@@ -3,38 +3,52 @@ import com.flab.ccinside.api.trendingpost.application.port.ViewPostEvent; import com.flab.ccinside.api.trendingpost.application.port.in.PostSystemUsecase; import com.flab.ccinside.api.trendingpost.application.port.in.UpdateViewCountCommand; -import jakarta.annotation.PostConstruct; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import lombok.RequiredArgsConstructor; +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; @Slf4j @Component -@RequiredArgsConstructor public class InMemoryMessageQueue { - private final PostSystemUsecase postSystemUsecase; - private final BlockingQueue<ViewPostEvent> queue; - private final ExecutorService executorService = Executors.newSingleThreadExecutor(); + private static final Long INITIAL_DELAY = 10L; + private static final Long FIXED_DELAY = 100L; + private static final int THRESHOLD = 100; - @PostConstruct - public void init() { - executorService.submit( - () -> { - try { - while (true) { - var event = queue.take(); - log.info("View post event consumed. postId: {}", event.postId()); - var command = new UpdateViewCountCommand(event.postId()); - postSystemUsecase.updateViewCount(command); - } - } catch (InterruptedException e) { - log.error("consume error: {}", e.getMessage()); - throw new RuntimeException(e); - } - }); + public InMemoryMessageQueue( + PostSystemUsecase postSystemUsecase, + Queue<ViewPostEvent> queue, + ScheduledExecutorService executorService) { + + executorService.scheduleWithFixedDelay( + createEventConsumerRunnable(postSystemUsecase, queue), + INITIAL_DELAY, + FIXED_DELAY, + TimeUnit.MILLISECONDS); + } + + private Runnable createEventConsumerRunnable( + PostSystemUsecase postSystemUsecase, Queue<ViewPostEvent> queue) { + return () -> { + try { + List<UpdateViewCountCommand> commands = new ArrayList<>(); + ViewPostEvent event; + int count = 0; + while ((event = queue.poll()) != null && count < THRESHOLD) { + log.info("View post event consumed. postId: {}", event.postId()); + var command = new UpdateViewCountCommand(event.postId()); + postSystemUsecase.updateViewCount(command); + commands.add(command); + count++; + } + postSystemUsecase.persistViewCountsInBatch(commands); + } catch (Exception e) { + log.error("error: {}", e.getMessage()); + } + }; } }
Java
ํ™•์ธํ•ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. Threshold๋ฅผ ์„ค์ •ํ•˜๋„๋ก ๋ณ€๊ฒฝํ–ˆ์Šต๋‹ˆ๋‹ค :)
@@ -0,0 +1,27 @@ +package store.exception.messages; + +public enum ErrorMessage { + + INVALID_FILE_FORMAT_ERROR("ํŒŒ์ผ ์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค"), + INVALID_FORMAT("์ž˜๋ชป๋œ ์ž…๋ ฅ ํ˜•์‹์ž…๋‹ˆ๋‹ค. [์ƒํ’ˆ๋ช…-์ˆ˜๋Ÿ‰] ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + INVALID_NUMBER("์œ ํšจํ•œ ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + INVALID_ANSWER("์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค. Y ๋˜๋Š” N์œผ๋กœ ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + MAXIMUM_NUMBER_LENGTH("์ˆซ์ž๋Š” 9์ž ์ด๋‚ด์—ฌ์•ผํ•ฉ๋‹ˆ๋‹ค."), + DUPLICATE_ORDER_ITEM("์ค‘๋ณต๋œ ์ƒํ’ˆ์ด ์žˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + INSUFFICIENT_STOCK("์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."), + NOT_FOUND("์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return "[ERROR] " + message; + } + + public String format(Object... args) { + return String.format(getMessage(), args); + } +}
Java
๊ณตํ†ต๋œ [ERROR]๋ฅผ ๋ถ„๋ฆฌํ•˜์‹  ๋ถ€๋ถ„์ด ๋˜๊ฒŒ ์ข‹๋„ค์š”!
@@ -0,0 +1,39 @@ +package store.inventory.parser; + +import java.io.BufferedReader; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import store.inventory.domain.Promotion; + +public class PromotionParser { + + private static final int HEADER_LINE = 1; + private static final String DELIMITER = ","; + + public static List<Promotion> parsePromotions(String filePath) throws IOException { + List<Promotion> promotions = new ArrayList<>(); + + try (BufferedReader reader = Files.newBufferedReader(Paths.get(filePath))) { + reader.lines() + .skip(HEADER_LINE) + .filter(line -> !line.isBlank()) + .forEach(line -> promotions.add(parsePromotion(line))); + } + return promotions; + } + + private static Promotion parsePromotion(String line) { + String[] data = line.split(DELIMITER); + String name = data[0].trim(); + int buyQuantity = Integer.parseInt(data[1].trim()); + int freeQuantity = Integer.parseInt(data[2].trim()); + LocalDate startDate = LocalDate.parse(data[3].trim()); + LocalDate endDate = LocalDate.parse(data[4].trim()); + + return new Promotion(name, buyQuantity, freeQuantity, startDate, endDate); + } +} \ No newline at end of file
Java
์•ˆ๋…•ํ•˜์„ธ์š”! ํ˜„์žฌ data ๋ฐฐ์—ด์€ ๊ฐ’์ด ๋ณ€๊ฒฝ๋˜์ง€ ์•Š๊ณ , ์˜ค๋กœ์ง€ ์ฝ๊ธฐ ์ „์šฉ์œผ๋กœ ์‚ฌ์šฉ๋˜๊ณ  ์žˆ๋Š”๋ฐ์š”. ์ด๋ฅผ ๋ถˆ๋ณ€ ๋ฆฌ์ŠคํŠธ๋กœ ๊ด€๋ฆฌํ•˜๋ฉด ๋” ์•ˆ์ „ํ•˜๊ณ , ๋ช…ํ™•ํ•˜๊ฒŒ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ ์‹ถ์–ด ๋ฆฌ๋ทฐ ๋‚จ๊ฒจ๋ด…๋‹ˆ๋‹ค. ๋ฐฐ์—ด ๋Œ€์‹  List.of๋ฅผ ์‚ฌ์šฉํ•ด ๋ถˆ๋ณ€ ๋ฆฌ์ŠคํŠธ๋กœ ๋งŒ๋“ค๋ฉด, ๋ฐ์ดํ„ฐ์˜ ์•ˆ์ „์„ฑ์„ ๋ณด์žฅํ•˜๋ฉด์„œ๋„ ์ฝ”๋“œ ๊ฐ€๋…์„ฑ๋„ ๊ฐœ์„ ๋  ๊ฒƒ ๊ฐ™์€๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”? ๐Ÿ˜Š ``` private static Promotion parsePromotion(String line) { List<String> data = List.of(line.split(DELIMITER)); String name = data.get(0).trim(); int buyQuantity = Integer.parseInt(data.get(1).trim()); int freeQuantity = Integer.parseInt(data.get(2).trim()); LocalDate startDate = LocalDate.parse(data.get(3).trim()); LocalDate endDate = LocalDate.parse(data.get(4).trim()); return new Promotion(name, buyQuantity, freeQuantity, startDate, endDate); } ```
@@ -0,0 +1,55 @@ +package store.order.domain; + +import static store.order.validator.CartValidator.findInventoryItem; + +import java.time.LocalDate; +import java.util.List; +import java.util.stream.Collectors; +import store.inventory.domain.InventoryItem; +import store.order.dto.FreeItemDto; +import store.order.dto.OrderItemDto; +import store.order.dto.ReceiptItemDto; + +public class Cart { + + private final List<CartItem> items; + + public Cart(final List<CartItem> items) { + this.items = items; + } + + public static Cart of( + final List<OrderItemDto> orderItems, + final List<InventoryItem> inventoryItems, + final LocalDate today) { + List<CartItem> cartItems = orderItems.stream().map(orderItemDto -> { + final InventoryItem inventoryItem = findInventoryItem(orderItemDto.productName(), inventoryItems); + return CartItem.from(orderItemDto, inventoryItem, today); + }).collect(Collectors.toList()); + return new Cart(cartItems); + } + + public PaymentCalculator createPaymentCalculator(final boolean membershipStatus) { + return new PaymentCalculator(this, membershipStatus); + } + + public int calculateTotalPrice() { + return items.stream().mapToInt(CartItem::calculateTotalPrice).sum(); + } + + public int calculatePromotionDiscount() { + return items.stream().mapToInt(CartItem::calculatePromotionDiscount).sum(); + } + + public List<ReceiptItemDto> getPurchasedItems() { + return ReceiptItemDto.from(items); + } + + public List<FreeItemDto> getFreeItems() { + return FreeItemDto.from(items); + } + + public List<CartItem> getItems() { + return items; + } +}
Java
`findInventoryItem` ๋ฉ”์„œ๋“œ๊ฐ€ `CartValidator` ํด๋ž˜์Šค์— ์œ„์น˜ํ•˜๊ณ  ์žˆ์—ˆ๊ตฐ์š”! ์ฒ˜์Œ์—๋Š” ๋ฉ”์„œ๋“œ ์ด๋ฆ„๋งŒ ๋ณด๊ณ  `Cart` ํด๋ž˜์Šค์— ์žˆ๋Š” ๋ฉ”์„œ๋“œ๋ผ๊ณ  ์ฐฉ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค. ํŠน์ž„ํฌํŠธ ๊ตฌ๋ฌธ์„ ๋ณด๊ณ  ๋‚˜์„œ์•ผ` CartValidator`์— ์žˆ๋Š” ๋ฉ”์„œ๋“œ๋ผ๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค. ์ด์™€ ๊ฐ™์€ ํ˜ผ๋ž€์„ ์ค„์ด๊ธฐ ์œ„ํ•ด ๋ฉ”์„œ๋“œ ํ˜ธ์ถœ ์‹œ ํด๋ž˜์Šค๋ช…์„ ๋ช…์‹œํ•˜๋Š” ๊ฒƒ์— ๋Œ€ํ•ด ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”? `final InventoryItem inventoryItem = CartValidator.findInventoryItem(orderItemDto.productName(), inventoryItems);`
@@ -0,0 +1,25 @@ +package store; + +import store.controller.StoreController; +import store.exception.ExceptionHandler; +import store.inventory.repository.InventoryRepository; +import store.inventory.repository.PromotionRepository; +import store.inventory.service.InventoryService; +import store.inventory.service.PromotionService; +import store.service.StoreService; + +public class Configuration { + + private final InventoryRepository inventoryRepository = new InventoryRepository(); + private final PromotionRepository promotionRepository = new PromotionRepository(); + private final PromotionService promotionService = new PromotionService(promotionRepository); + private final InventoryService inventoryService = new InventoryService(inventoryRepository, promotionRepository); + private final StoreService storeService = new StoreService(inventoryService, promotionService); + private final ExceptionHandler exceptionHandler = new ExceptionHandler(); + + public StoreController storeController() { + StoreController storeController = new StoreController(storeService, exceptionHandler); + storeController.init(); + return storeController; + } +} \ No newline at end of file
Java
storeController.init()์„ Configuration ํด๋ž˜์Šค ์•ˆ์—์„œ ํ˜ธ์ถœํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -1,7 +1,11 @@ package store; +import store.controller.StoreController; + public class Application { public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + final Configuration configuration = new Configuration(); + StoreController storeController = configuration.storeController(); + storeController.run(); } }
Java
๋ฉ”์„œ๋“œ ๋‚ด๋ถ€์—์„œ final ํ‚ค์›Œ๋“œ๋กœ ์„ ์–ธํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,73 @@ +package store.inventory.domain; + +import java.time.LocalDate; +import java.util.Optional; +import store.exception.AdditionalBenefitException; +import store.exception.PromotionNotAvailableException; + +public class PromotionHandler { + + private static final int ZERO = 0; + + private final Stock stock; + private Optional<Promotion> promotion; + + public PromotionHandler(final Promotion promotion, final Stock stock) { + this.promotion = Optional.ofNullable(promotion); + this.stock = stock; + } + + public boolean isApplicable(final int quantity, final LocalDate today) { + return promotion.isPresent() && promotion.get().isApplicable(quantity, today); + } + + public int calculateFreeQuantity(final int quantity) { + return promotion.map(promo -> promo.calculateFreeQuantity(quantity, stock.getPromotionStock())).orElse(0); + } + + public void applyDiscount(final int quantity, String productName) { + final int promotionQuantity = calculatePromotionStock(quantity); + final int nonPromotionQuantity = quantity - promotionQuantity; + + stock.drainDuringPromotionPeriod(promotionQuantity); + if (nonPromotionQuantity > ZERO) { + throw new PromotionNotAvailableException(productName, nonPromotionQuantity); + } + } + + public void checkAdditionalBenefitEligibility(final int quantity, final String productName) { + final int additionalEligibleQuantity = calculateRemainingFreeQuantity(quantity); + if (isEligibleForAdditionalBenefit(additionalEligibleQuantity, quantity)) { + throw new AdditionalBenefitException(productName, additionalEligibleQuantity); + } + } + + public void changePromotion(final Promotion promotion) { + this.promotion = Optional.ofNullable(promotion); + } + + public String getPromotionName() { + return promotion.map(Promotion::getName).orElse(""); + } + + private int calculateRemainingFreeQuantity(final int quantity) { + return promotion.map(promo -> promo.calculateRemainingFreeQuantity(quantity)).orElse(ZERO); + } + + private boolean isEligibleForAdditionalBenefit(final int additionalEligibleQuantity, final int quantity) { + final int availablePromotionStock = calculatePromotionStock(quantity); + final int totalRequiredStock = calculateTotalRequiredStock(additionalEligibleQuantity, availablePromotionStock); + + return additionalEligibleQuantity > ZERO && stock.getPromotionStock() >= totalRequiredStock; + } + + private int calculatePromotionStock(final int quantity) { + return promotion.map(promo -> promo.calculateAvailablePromotionStock(quantity, stock.getPromotionStock())) + .orElse(ZERO); + } + + private int calculateTotalRequiredStock(final int additionalEligibleQuantity, final int availablePromotionStock) { + final int promotionSetSize = promotion.get().getPromotionSetSize(); + return availablePromotionStock + additionalEligibleQuantity * promotionSetSize; + } +}
Java
Promotion์„ Optional๋กœ ๊ด€๋ฆฌํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”??
@@ -0,0 +1,56 @@ +package store.inventory.domain; + +import static store.exception.messages.ErrorMessage.INSUFFICIENT_STOCK; + +public class Stock { + + private int generalStock; + private int promotionStock; + + public Stock(final int generalStock, final int promotionStock) { + this.generalStock = generalStock; + this.promotionStock = promotionStock; + } + + public void useGeneralStock(final int quantity) { + validateGeneralStock(quantity); + generalStock -= quantity; + } + + public void drainDuringPromotionPeriod(final int totalQuantity) { + final int remainingPromo = usePromotionStock(totalQuantity); + useGeneralStock(remainingPromo); + } + + public void addGeneralStock(final int quantity) { + this.generalStock += quantity; + } + + public void addPromotionStock(final int quantity) { + this.promotionStock += quantity; + } + + public int getGeneralStock() { + return generalStock; + } + + public int getPromotionStock() { + return promotionStock; + } + + public int getTotalStock() { + return generalStock + promotionStock; + } + + private int usePromotionStock(final int quantity) { + final int usedStock = Math.min(quantity, promotionStock); + promotionStock -= usedStock; + return quantity - usedStock; + } + + private void validateGeneralStock(final int quantity) { + if (quantity > generalStock) { + throw new IllegalArgumentException(INSUFFICIENT_STOCK.getMessage()); + } + } +}
Java
calculateRemainStock๊ณผ ๊ฐ™์€ ๋„ค์ด๋ฐ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,73 @@ +package store.inventory.domain; + +import java.time.LocalDate; +import java.util.Optional; +import store.exception.AdditionalBenefitException; +import store.exception.PromotionNotAvailableException; + +public class PromotionHandler { + + private static final int ZERO = 0; + + private final Stock stock; + private Optional<Promotion> promotion; + + public PromotionHandler(final Promotion promotion, final Stock stock) { + this.promotion = Optional.ofNullable(promotion); + this.stock = stock; + } + + public boolean isApplicable(final int quantity, final LocalDate today) { + return promotion.isPresent() && promotion.get().isApplicable(quantity, today); + } + + public int calculateFreeQuantity(final int quantity) { + return promotion.map(promo -> promo.calculateFreeQuantity(quantity, stock.getPromotionStock())).orElse(0); + } + + public void applyDiscount(final int quantity, String productName) { + final int promotionQuantity = calculatePromotionStock(quantity); + final int nonPromotionQuantity = quantity - promotionQuantity; + + stock.drainDuringPromotionPeriod(promotionQuantity); + if (nonPromotionQuantity > ZERO) { + throw new PromotionNotAvailableException(productName, nonPromotionQuantity); + } + } + + public void checkAdditionalBenefitEligibility(final int quantity, final String productName) { + final int additionalEligibleQuantity = calculateRemainingFreeQuantity(quantity); + if (isEligibleForAdditionalBenefit(additionalEligibleQuantity, quantity)) { + throw new AdditionalBenefitException(productName, additionalEligibleQuantity); + } + } + + public void changePromotion(final Promotion promotion) { + this.promotion = Optional.ofNullable(promotion); + } + + public String getPromotionName() { + return promotion.map(Promotion::getName).orElse(""); + } + + private int calculateRemainingFreeQuantity(final int quantity) { + return promotion.map(promo -> promo.calculateRemainingFreeQuantity(quantity)).orElse(ZERO); + } + + private boolean isEligibleForAdditionalBenefit(final int additionalEligibleQuantity, final int quantity) { + final int availablePromotionStock = calculatePromotionStock(quantity); + final int totalRequiredStock = calculateTotalRequiredStock(additionalEligibleQuantity, availablePromotionStock); + + return additionalEligibleQuantity > ZERO && stock.getPromotionStock() >= totalRequiredStock; + } + + private int calculatePromotionStock(final int quantity) { + return promotion.map(promo -> promo.calculateAvailablePromotionStock(quantity, stock.getPromotionStock())) + .orElse(ZERO); + } + + private int calculateTotalRequiredStock(final int additionalEligibleQuantity, final int availablePromotionStock) { + final int promotionSetSize = promotion.get().getPromotionSetSize(); + return availablePromotionStock + additionalEligibleQuantity * promotionSetSize; + } +}
Java
Promotion ํด๋ž˜์Šค์—์„œ๋„ ํ•ด๋‹น ์ƒ์ˆ˜๊ฐ€ ์„ ์–ธ๋˜์–ด์žˆ๋Š”๋ฐ, ๋”ฐ๋กœ ํด๋ž˜์Šค๋กœ ๋ถ„๋ฆฌํ•ด ์žฌ์‚ฌ์šฉ์„ฑ์„ ๊ณ ๋ คํ•˜๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,25 @@ +package store.inventory.repository; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import store.inventory.domain.InventoryItem; + +public class InventoryRepository { + + private final List<InventoryItem> inventories = new ArrayList<>(); + + public void save(InventoryItem inventoryItem) { + inventories.add(inventoryItem); + } + + public List<InventoryItem> findAll() { + return new ArrayList<>(inventories); + } + + public Optional<InventoryItem> findByProductName(String productName) { + return inventories.stream() + .filter(inventory -> inventory.getProductName().equals(productName)) + .findFirst(); + } +}
Java
repository๋ฅผ ๊ตฌํ˜„ํ•  ์ƒ๊ฐ์€ ๋ชปํ–ˆ๋Š”๋ฐ, ์ •๋ง ์ข‹์€ ๊ฒƒ ๊ฐ™์•„์š”!!๐Ÿ‘
@@ -0,0 +1,101 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.nio.file.Paths; +import java.time.LocalDate; +import java.util.function.Supplier; +import store.exception.ExceptionHandler; +import store.exception.ExceptionResponse; +import store.exception.UserDecisionException; +import store.order.domain.Cart; +import store.order.domain.CartItem; +import store.order.domain.PaymentCalculator; +import store.order.dto.ReceiptDto; +import store.order.dto.YesOrNoDto; +import store.service.StoreService; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + + private static final String PROMOTION_FILE_PATH = Paths.get("src", "main", "resources", "promotions.md").toString(); + private static final String PRODUCT_FILE_PATH = Paths.get("src", "main", "resources", "products.md").toString(); + + private final StoreService storeService; + private final ExceptionHandler exceptionHandler; + + public StoreController(StoreService storeService, ExceptionHandler exceptionHandler) { + this.storeService = storeService; + this.exceptionHandler = exceptionHandler; + } + + public void init() { + exceptionHandler.handleVoidWithIOException( + () -> storeService.loadInitialData(PROMOTION_FILE_PATH, PRODUCT_FILE_PATH)); + } + + public void run() { + do { + displayInventory(); + final Cart cart = createCartWithRetry(); + processCart(cart); + } while (continueShopping()); + } + + private Cart createCartWithRetry() { + return exceptionHandler.handleWithRetry(() -> storeService.prepareCart(InputView.readOrder())).result(); + } + + private void displayInventory() { + OutputView.displayInventory(storeService.getAllInventoryPairs()); + } + + private void processCart(final Cart cart) { + applyPromotions(cart); + final PaymentCalculator calculator = requestMembershipStatus(cart); + displayReceipt(calculator); + } + + private boolean continueShopping() { + return handleYesOrNoRetry(InputView::readRetryStatus); + } + + private PaymentCalculator requestMembershipStatus(final Cart cart) { + final boolean membershipStatus = handleYesOrNoRetry(InputView::readMembershipStatus); + return cart.createPaymentCalculator(membershipStatus); + } + + private boolean handleYesOrNoRetry(final Supplier<String> inputSupplier) { + return exceptionHandler.handleWithRetry(() -> YesOrNoDto.from(inputSupplier.get())).result().isYesOrNo(); + } + + private void applyPromotions(final Cart cart) { + cart.getItems().forEach(this::applyPromotionWithRetry); + } + + private void displayReceipt(final PaymentCalculator calculator) { + final ReceiptDto receipt = calculator.generateReceipt(); + OutputView.displayReceipt(receipt); + } + + private void applyPromotionWithRetry(final CartItem cartItem) { + ExceptionResponse<Void> response = exceptionHandler.handleWithRetry(() -> { + cartItem.drainStock(LocalDate.from(DateTimes.now())); + return null; + }); + if (response.hasException()) { + processUserDecision(response.userDecisionException(), cartItem); + } + } + + private void processUserDecision(final UserDecisionException exception, final CartItem cartItem) { + if (exception.isPromotionNotAvailableException()) { + cartItem.handlePromotionShortage(exception.getUserChoice(), exception.getQuantity()); + return; + } + + if (exception.isAdditionalBenefitException() && exception.getUserChoice()) { + cartItem.addEligibleFreeItems(exception.getQuantity()); + } + } +}
Java
๊ฐ๊ฐ์˜ ํŒŒ์ผ์„ ๋ถˆ๋Ÿฌ์˜ค๊ณ , ์—๋Ÿฌ ํ•ธ๋“ค๋ง๊นŒ์ง€ ํ•œ ๊ฒŒ ์ธ์ƒ์ ์ด๋„ค์š”..!
@@ -0,0 +1,73 @@ +package store.inventory.domain; + +import java.time.LocalDate; +import java.util.Optional; +import store.exception.AdditionalBenefitException; +import store.exception.PromotionNotAvailableException; + +public class PromotionHandler { + + private static final int ZERO = 0; + + private final Stock stock; + private Optional<Promotion> promotion; + + public PromotionHandler(final Promotion promotion, final Stock stock) { + this.promotion = Optional.ofNullable(promotion); + this.stock = stock; + } + + public boolean isApplicable(final int quantity, final LocalDate today) { + return promotion.isPresent() && promotion.get().isApplicable(quantity, today); + } + + public int calculateFreeQuantity(final int quantity) { + return promotion.map(promo -> promo.calculateFreeQuantity(quantity, stock.getPromotionStock())).orElse(0); + } + + public void applyDiscount(final int quantity, String productName) { + final int promotionQuantity = calculatePromotionStock(quantity); + final int nonPromotionQuantity = quantity - promotionQuantity; + + stock.drainDuringPromotionPeriod(promotionQuantity); + if (nonPromotionQuantity > ZERO) { + throw new PromotionNotAvailableException(productName, nonPromotionQuantity); + } + } + + public void checkAdditionalBenefitEligibility(final int quantity, final String productName) { + final int additionalEligibleQuantity = calculateRemainingFreeQuantity(quantity); + if (isEligibleForAdditionalBenefit(additionalEligibleQuantity, quantity)) { + throw new AdditionalBenefitException(productName, additionalEligibleQuantity); + } + } + + public void changePromotion(final Promotion promotion) { + this.promotion = Optional.ofNullable(promotion); + } + + public String getPromotionName() { + return promotion.map(Promotion::getName).orElse(""); + } + + private int calculateRemainingFreeQuantity(final int quantity) { + return promotion.map(promo -> promo.calculateRemainingFreeQuantity(quantity)).orElse(ZERO); + } + + private boolean isEligibleForAdditionalBenefit(final int additionalEligibleQuantity, final int quantity) { + final int availablePromotionStock = calculatePromotionStock(quantity); + final int totalRequiredStock = calculateTotalRequiredStock(additionalEligibleQuantity, availablePromotionStock); + + return additionalEligibleQuantity > ZERO && stock.getPromotionStock() >= totalRequiredStock; + } + + private int calculatePromotionStock(final int quantity) { + return promotion.map(promo -> promo.calculateAvailablePromotionStock(quantity, stock.getPromotionStock())) + .orElse(ZERO); + } + + private int calculateTotalRequiredStock(final int additionalEligibleQuantity, final int availablePromotionStock) { + final int promotionSetSize = promotion.get().getPromotionSetSize(); + return availablePromotionStock + additionalEligibleQuantity * promotionSetSize; + } +}
Java
์ œ๊ฐ€ ์•Œ๊ธฐ๋กœ๋Š” Optional์ด ๊ฐ์ฒด ํ•„๋“œ๋กœ ์„ ์–ธํ•˜๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•˜์ง€ ์•Š๊ณ  ๋งŒ๋“ค์–ด์ ธ ์ง๋ ฌํ™” ๋ฐ ์—ญ์ง๋ ฌํ™”์‹œ ๋ฌธ์ œ๊ฐ€ ์ƒ๊ธธ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์œผ๋กœ ์•Œ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ๋ฐ˜ํ™˜๊ฐ’์œผ๋กœ๋งŒ ์‚ฌ์šฉ๋˜๋Š”๊ฒŒ ์ข‹๋‹ค๊ณ  ์•Œ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,17 @@ +package store.exception; + +import static store.exception.messages.UserPromotionMessage.ADDITIONAL_BENEFIT_AVAILABLE; + +public class AdditionalBenefitException extends RuntimeException { + + private final int additionalEligibleQuantity; + + public AdditionalBenefitException(String productName, int additionalEligibleQuantity) { + super(ADDITIONAL_BENEFIT_AVAILABLE.format(productName, additionalEligibleQuantity)); + this.additionalEligibleQuantity = additionalEligibleQuantity; + } + + public int getAdditionalEligibleQuantity() { + return additionalEligibleQuantity; + } +}
Java
์ €๋Š” ์ด๋ฒˆ์— ์‹œ๊ฐ„์ด ์—†์–ด์„œ ์ปค์Šคํ…€ ์˜ˆ์™ธ ํด๋ž˜์Šค๋ฅผ ์ƒ๊ฐ๋งŒ ํ•˜๊ณ  ๋งŒ๋“ค์ง€ ๋ชปํ–ˆ๋Š”๋ฐ,, ๋Œ€๋‹จํ•˜์‹ ๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,73 @@ +package store.inventory.domain; + +import java.time.LocalDate; +import java.util.Optional; +import store.exception.AdditionalBenefitException; +import store.exception.PromotionNotAvailableException; + +public class PromotionHandler { + + private static final int ZERO = 0; + + private final Stock stock; + private Optional<Promotion> promotion; + + public PromotionHandler(final Promotion promotion, final Stock stock) { + this.promotion = Optional.ofNullable(promotion); + this.stock = stock; + } + + public boolean isApplicable(final int quantity, final LocalDate today) { + return promotion.isPresent() && promotion.get().isApplicable(quantity, today); + } + + public int calculateFreeQuantity(final int quantity) { + return promotion.map(promo -> promo.calculateFreeQuantity(quantity, stock.getPromotionStock())).orElse(0); + } + + public void applyDiscount(final int quantity, String productName) { + final int promotionQuantity = calculatePromotionStock(quantity); + final int nonPromotionQuantity = quantity - promotionQuantity; + + stock.drainDuringPromotionPeriod(promotionQuantity); + if (nonPromotionQuantity > ZERO) { + throw new PromotionNotAvailableException(productName, nonPromotionQuantity); + } + } + + public void checkAdditionalBenefitEligibility(final int quantity, final String productName) { + final int additionalEligibleQuantity = calculateRemainingFreeQuantity(quantity); + if (isEligibleForAdditionalBenefit(additionalEligibleQuantity, quantity)) { + throw new AdditionalBenefitException(productName, additionalEligibleQuantity); + } + } + + public void changePromotion(final Promotion promotion) { + this.promotion = Optional.ofNullable(promotion); + } + + public String getPromotionName() { + return promotion.map(Promotion::getName).orElse(""); + } + + private int calculateRemainingFreeQuantity(final int quantity) { + return promotion.map(promo -> promo.calculateRemainingFreeQuantity(quantity)).orElse(ZERO); + } + + private boolean isEligibleForAdditionalBenefit(final int additionalEligibleQuantity, final int quantity) { + final int availablePromotionStock = calculatePromotionStock(quantity); + final int totalRequiredStock = calculateTotalRequiredStock(additionalEligibleQuantity, availablePromotionStock); + + return additionalEligibleQuantity > ZERO && stock.getPromotionStock() >= totalRequiredStock; + } + + private int calculatePromotionStock(final int quantity) { + return promotion.map(promo -> promo.calculateAvailablePromotionStock(quantity, stock.getPromotionStock())) + .orElse(ZERO); + } + + private int calculateTotalRequiredStock(final int additionalEligibleQuantity, final int availablePromotionStock) { + final int promotionSetSize = promotion.get().getPromotionSetSize(); + return availablePromotionStock + additionalEligibleQuantity * promotionSetSize; + } +}
Java
์ €๋„ ์ด ๋ถ€๋ถ„์„ ์˜ˆ์™ธ๋กœ ๋งŒ๋“ค๊นŒ ๊ณ ๋ฏผ์„ ๋งŽ์ด ํ–ˆ์—ˆ๋Š”๋ฐ, ์˜ˆ์™ธ๋Š” ์˜ˆ์™ธ๋กœ๋งŒ ์‚ฌ์šฉ์„ ํ•ด์•ผํ•œ๋‹ค๊ณ  ์ƒ๊ฐ์„ ํ•ด์„œ ์ด๋ ‡๊ฒŒ ๊ตฌํ˜„ํ•˜์ง€ ์•Š์•˜๋Š”๋ฐ ์ด๋ ‡๊ฒŒ ๋ณด๋‹ˆ ์˜ˆ์™ธ๋ผ๊ณ  ์ƒ๊ฐํ•  ์ˆ˜๋„ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”. ํ™•์‹คํžˆ ์˜ˆ์™ธ๋กœ ๊ตฌํ˜„ํ•˜๋Š”๊ฒŒ ๊น”๋”ํ•ด ๋ณด์ด๋„ค์š”!
@@ -0,0 +1,25 @@ +package store.inventory.repository; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import store.inventory.domain.InventoryItem; + +public class InventoryRepository { + + private final List<InventoryItem> inventories = new ArrayList<>(); + + public void save(InventoryItem inventoryItem) { + inventories.add(inventoryItem); + } + + public List<InventoryItem> findAll() { + return new ArrayList<>(inventories); + } + + public Optional<InventoryItem> findByProductName(String productName) { + return inventories.stream() + .filter(inventory -> inventory.getProductName().equals(productName)) + .findFirst(); + } +}
Java
JPA์ฒ˜๋Ÿผ Optional๋กœ ๋ฐ˜ํ™˜ํ•˜๋Š”๊ฒƒ ์ž˜ ๋ฐฐ์šฐ๊ณ  ๊ฐ‘๋‹ˆ๋‹ค!
@@ -0,0 +1,39 @@ +package store.inventory.parser; + +import java.io.BufferedReader; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import store.inventory.domain.Promotion; + +public class PromotionParser { + + private static final int HEADER_LINE = 1; + private static final String DELIMITER = ","; + + public static List<Promotion> parsePromotions(String filePath) throws IOException { + List<Promotion> promotions = new ArrayList<>(); + + try (BufferedReader reader = Files.newBufferedReader(Paths.get(filePath))) { + reader.lines() + .skip(HEADER_LINE) + .filter(line -> !line.isBlank()) + .forEach(line -> promotions.add(parsePromotion(line))); + } + return promotions; + } + + private static Promotion parsePromotion(String line) { + String[] data = line.split(DELIMITER); + String name = data[0].trim(); + int buyQuantity = Integer.parseInt(data[1].trim()); + int freeQuantity = Integer.parseInt(data[2].trim()); + LocalDate startDate = LocalDate.parse(data[3].trim()); + LocalDate endDate = LocalDate.parse(data[4].trim()); + + return new Promotion(name, buyQuantity, freeQuantity, startDate, endDate); + } +} \ No newline at end of file
Java
์ข‹์€ ์˜๊ฒฌ์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ž์„ธํ•œ ๋ฆฌ๋ทฐ ๋ฐ ์„ค๋ช… ์ •๋ง ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,55 @@ +package store.order.domain; + +import static store.order.validator.CartValidator.findInventoryItem; + +import java.time.LocalDate; +import java.util.List; +import java.util.stream.Collectors; +import store.inventory.domain.InventoryItem; +import store.order.dto.FreeItemDto; +import store.order.dto.OrderItemDto; +import store.order.dto.ReceiptItemDto; + +public class Cart { + + private final List<CartItem> items; + + public Cart(final List<CartItem> items) { + this.items = items; + } + + public static Cart of( + final List<OrderItemDto> orderItems, + final List<InventoryItem> inventoryItems, + final LocalDate today) { + List<CartItem> cartItems = orderItems.stream().map(orderItemDto -> { + final InventoryItem inventoryItem = findInventoryItem(orderItemDto.productName(), inventoryItems); + return CartItem.from(orderItemDto, inventoryItem, today); + }).collect(Collectors.toList()); + return new Cart(cartItems); + } + + public PaymentCalculator createPaymentCalculator(final boolean membershipStatus) { + return new PaymentCalculator(this, membershipStatus); + } + + public int calculateTotalPrice() { + return items.stream().mapToInt(CartItem::calculateTotalPrice).sum(); + } + + public int calculatePromotionDiscount() { + return items.stream().mapToInt(CartItem::calculatePromotionDiscount).sum(); + } + + public List<ReceiptItemDto> getPurchasedItems() { + return ReceiptItemDto.from(items); + } + + public List<FreeItemDto> getFreeItems() { + return FreeItemDto.from(items); + } + + public List<CartItem> getItems() { + return items; + } +}
Java
์ฝ”๋“œ์˜ ๊ฐ„๊ฒฐ์„ฑ์„ ์œ„ํ•ด ์ƒ๋žตํ–ˆ์—ˆ๋Š”๋ฐ ์˜คํžˆ๋ ค ๋‹ค๋ฅธ ์‚ฌ๋žŒ ์ž…์žฅ์—์„œ ๊ฐ€๋…์„ฑ์ด ๋‚ฎ์•„์งˆ ์ˆ˜๋„ ์žˆ๊ฒ ๊ตฌ๋‚˜ ๊นจ๋‹ซ๊ฒŒ๋œ ๋ฆฌ๋ทฐ์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ดํ›„์˜ ํ˜‘์—…์„ ์œ„ํ•ด ์ด๋Ÿฌํ•œ ์‚ฌํ•ญ์„ ๊ณ ๋ คํ•˜๋Š” ๋” ์„ฌ์„ธํ•œ ๊ฐœ๋ฐœ์ž๊ฐ€ ๋˜์–ด์•ผ๊ฒ ์Šต๋‹ˆ๋‹ค. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,25 @@ +package store; + +import store.controller.StoreController; +import store.exception.ExceptionHandler; +import store.inventory.repository.InventoryRepository; +import store.inventory.repository.PromotionRepository; +import store.inventory.service.InventoryService; +import store.inventory.service.PromotionService; +import store.service.StoreService; + +public class Configuration { + + private final InventoryRepository inventoryRepository = new InventoryRepository(); + private final PromotionRepository promotionRepository = new PromotionRepository(); + private final PromotionService promotionService = new PromotionService(promotionRepository); + private final InventoryService inventoryService = new InventoryService(inventoryRepository, promotionRepository); + private final StoreService storeService = new StoreService(inventoryService, promotionService); + private final ExceptionHandler exceptionHandler = new ExceptionHandler(); + + public StoreController storeController() { + StoreController storeController = new StoreController(storeService, exceptionHandler); + storeController.init(); + return storeController; + } +} \ No newline at end of file
Java
ํŒŒ์ผ ์ผ๊ด€์„ฑ ์ƒ ์ปจํ”ผ๊ทธ ํŒŒ์ผ์—์„œ ํ”„๋กœ๊ทธ๋žจ ์„ค์ •์„ ์™„๋ฃŒํ•ด์•ผํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค. ์ง€๊ธˆ ์ƒ๊ฐํ•ด๋ณด๋‹ˆ ์ปจํŠธ๋กค๋Ÿฌ ๋‚ด์˜ init์„ ์ปจํ”ผ๊ทธ ํŒŒ์ผ๋กœ ์ด์ „ํ•˜์ง€ ์•Š๋Š” ์ด์ƒ ์ปจํŠธ๋กค๋Ÿฌ start() ๋ฉ”์„œ๋“œ ๋‚ด์—์„œ ํ˜ธ์ถœํ•ด๋„ ๋์„ ๊ฒƒ ๊ฐ™๋„ค์š”!
@@ -1,7 +1,11 @@ package store; +import store.controller.StoreController; + public class Application { public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + final Configuration configuration = new Configuration(); + StoreController storeController = configuration.storeController(); + storeController.run(); } }
Java
์ตœ๋Œ€ํ•œ ํ”ผ๋“œ๋ฐฑ ๋Œ€๋กœ final์„ ์‚ฌ์šฉํ•˜๊ณ  ์‹ถ์—ˆ์Šต๋‹ˆ๋‹ค. final์„ ์ ์šฉํ•˜๋ฉด์„œ ์–ด๋””๋ถ€ํ„ฐ ์–ด๋””๊นŒ์ง€ ์ ์šฉํ•ด์•ผํ•˜๋‚˜๋ผ๋Š” ์˜๋ฌธ์ด ์ƒ๊ฒผ์—ˆ๋Š”๋ฐ ๊ทธ๋•Œ ์‹œ๊ฐ„์ด ๋ถ€์กฑํ•˜์—ฌ ์ผ๋‹จ ์›ฌ๋งŒํ•˜๋ฉด ์ ์šฉํ•˜๋Š” ์‹์œผ๋กœ ํ–ˆ์Šต๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ํ˜„์žฌ ๊ณผ์ œ์—์„œ๋Š” final ์ ์šฉ์— ๋Œ€ํ•ด ๋งŽ์ด ์„œํˆฐ ๊ฒƒ ๊ฐ™๋„ค์š” ๋งค๊ฐœ๋ณ€์ˆ˜, ์ •๋ง ๋ฐ”๋€Œ์ง€ ์•Š๋Š” ๊ณณ์—์„œ๋งŒ final ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ด์•ผ๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,73 @@ +package store.inventory.domain; + +import java.time.LocalDate; +import java.util.Optional; +import store.exception.AdditionalBenefitException; +import store.exception.PromotionNotAvailableException; + +public class PromotionHandler { + + private static final int ZERO = 0; + + private final Stock stock; + private Optional<Promotion> promotion; + + public PromotionHandler(final Promotion promotion, final Stock stock) { + this.promotion = Optional.ofNullable(promotion); + this.stock = stock; + } + + public boolean isApplicable(final int quantity, final LocalDate today) { + return promotion.isPresent() && promotion.get().isApplicable(quantity, today); + } + + public int calculateFreeQuantity(final int quantity) { + return promotion.map(promo -> promo.calculateFreeQuantity(quantity, stock.getPromotionStock())).orElse(0); + } + + public void applyDiscount(final int quantity, String productName) { + final int promotionQuantity = calculatePromotionStock(quantity); + final int nonPromotionQuantity = quantity - promotionQuantity; + + stock.drainDuringPromotionPeriod(promotionQuantity); + if (nonPromotionQuantity > ZERO) { + throw new PromotionNotAvailableException(productName, nonPromotionQuantity); + } + } + + public void checkAdditionalBenefitEligibility(final int quantity, final String productName) { + final int additionalEligibleQuantity = calculateRemainingFreeQuantity(quantity); + if (isEligibleForAdditionalBenefit(additionalEligibleQuantity, quantity)) { + throw new AdditionalBenefitException(productName, additionalEligibleQuantity); + } + } + + public void changePromotion(final Promotion promotion) { + this.promotion = Optional.ofNullable(promotion); + } + + public String getPromotionName() { + return promotion.map(Promotion::getName).orElse(""); + } + + private int calculateRemainingFreeQuantity(final int quantity) { + return promotion.map(promo -> promo.calculateRemainingFreeQuantity(quantity)).orElse(ZERO); + } + + private boolean isEligibleForAdditionalBenefit(final int additionalEligibleQuantity, final int quantity) { + final int availablePromotionStock = calculatePromotionStock(quantity); + final int totalRequiredStock = calculateTotalRequiredStock(additionalEligibleQuantity, availablePromotionStock); + + return additionalEligibleQuantity > ZERO && stock.getPromotionStock() >= totalRequiredStock; + } + + private int calculatePromotionStock(final int quantity) { + return promotion.map(promo -> promo.calculateAvailablePromotionStock(quantity, stock.getPromotionStock())) + .orElse(ZERO); + } + + private int calculateTotalRequiredStock(final int additionalEligibleQuantity, final int availablePromotionStock) { + final int promotionSetSize = promotion.get().getPromotionSetSize(); + return availablePromotionStock + additionalEligibleQuantity * promotionSetSize; + } +}
Java
ํ—‰ ๊ธฐ๋ณธ์ ์ธ ๊ฐœ๋…์„ ๋†“์น˜๊ณ  ์žˆ์—ˆ๋„ค์š”. ์กฐ์–ธ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,56 @@ +package store.inventory.domain; + +import static store.exception.messages.ErrorMessage.INSUFFICIENT_STOCK; + +public class Stock { + + private int generalStock; + private int promotionStock; + + public Stock(final int generalStock, final int promotionStock) { + this.generalStock = generalStock; + this.promotionStock = promotionStock; + } + + public void useGeneralStock(final int quantity) { + validateGeneralStock(quantity); + generalStock -= quantity; + } + + public void drainDuringPromotionPeriod(final int totalQuantity) { + final int remainingPromo = usePromotionStock(totalQuantity); + useGeneralStock(remainingPromo); + } + + public void addGeneralStock(final int quantity) { + this.generalStock += quantity; + } + + public void addPromotionStock(final int quantity) { + this.promotionStock += quantity; + } + + public int getGeneralStock() { + return generalStock; + } + + public int getPromotionStock() { + return promotionStock; + } + + public int getTotalStock() { + return generalStock + promotionStock; + } + + private int usePromotionStock(final int quantity) { + final int usedStock = Math.min(quantity, promotionStock); + promotionStock -= usedStock; + return quantity - usedStock; + } + + private void validateGeneralStock(final int quantity) { + if (quantity > generalStock) { + throw new IllegalArgumentException(INSUFFICIENT_STOCK.getMessage()); + } + } +}
Java
ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ค‘์ ์ด๋ผ ์ƒ๊ฐํ•˜์—ฌ ํ•ด๋‹น ๋„ค์ด๋ฐ์œผ๋กœ ๋ฉ”์„œ๋“œ๋ช…์„ ๋ช…๋ช…ํ–ˆ์—ˆ๋Š”๋ฐ, ๋ถ€์กฑํ•˜๋ฉด ์ผ๋ฐ˜ ์žฌ๊ณ ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค๋ผ๋Š” ์˜๋ฏธ๋ฅผ ํฌํ•จํ•˜์—ฌ ๋ฉ”์„œ๋“œ๋ช…์„ ์ •ํ–ˆ์–ด๋„ ๋์„ ๊ฒƒ ๊ฐ™๋„ค์š”! ํ•œ๋ฒˆ ๋” ์ƒ๊ฐํ•  ๊ธฐํšŒ๋ฅผ ์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,73 @@ +package store.inventory.domain; + +import java.time.LocalDate; +import java.util.Optional; +import store.exception.AdditionalBenefitException; +import store.exception.PromotionNotAvailableException; + +public class PromotionHandler { + + private static final int ZERO = 0; + + private final Stock stock; + private Optional<Promotion> promotion; + + public PromotionHandler(final Promotion promotion, final Stock stock) { + this.promotion = Optional.ofNullable(promotion); + this.stock = stock; + } + + public boolean isApplicable(final int quantity, final LocalDate today) { + return promotion.isPresent() && promotion.get().isApplicable(quantity, today); + } + + public int calculateFreeQuantity(final int quantity) { + return promotion.map(promo -> promo.calculateFreeQuantity(quantity, stock.getPromotionStock())).orElse(0); + } + + public void applyDiscount(final int quantity, String productName) { + final int promotionQuantity = calculatePromotionStock(quantity); + final int nonPromotionQuantity = quantity - promotionQuantity; + + stock.drainDuringPromotionPeriod(promotionQuantity); + if (nonPromotionQuantity > ZERO) { + throw new PromotionNotAvailableException(productName, nonPromotionQuantity); + } + } + + public void checkAdditionalBenefitEligibility(final int quantity, final String productName) { + final int additionalEligibleQuantity = calculateRemainingFreeQuantity(quantity); + if (isEligibleForAdditionalBenefit(additionalEligibleQuantity, quantity)) { + throw new AdditionalBenefitException(productName, additionalEligibleQuantity); + } + } + + public void changePromotion(final Promotion promotion) { + this.promotion = Optional.ofNullable(promotion); + } + + public String getPromotionName() { + return promotion.map(Promotion::getName).orElse(""); + } + + private int calculateRemainingFreeQuantity(final int quantity) { + return promotion.map(promo -> promo.calculateRemainingFreeQuantity(quantity)).orElse(ZERO); + } + + private boolean isEligibleForAdditionalBenefit(final int additionalEligibleQuantity, final int quantity) { + final int availablePromotionStock = calculatePromotionStock(quantity); + final int totalRequiredStock = calculateTotalRequiredStock(additionalEligibleQuantity, availablePromotionStock); + + return additionalEligibleQuantity > ZERO && stock.getPromotionStock() >= totalRequiredStock; + } + + private int calculatePromotionStock(final int quantity) { + return promotion.map(promo -> promo.calculateAvailablePromotionStock(quantity, stock.getPromotionStock())) + .orElse(ZERO); + } + + private int calculateTotalRequiredStock(final int additionalEligibleQuantity, final int availablePromotionStock) { + final int promotionSetSize = promotion.get().getPromotionSetSize(); + return availablePromotionStock + additionalEligibleQuantity * promotionSetSize; + } +}
Java
0๊ณผ ๊ฐ™์ด ๋น„์ฆˆ๋‹ˆ์Šค์ ์œผ๋กœ ์˜๋ฏธ ์—†๋Š” ์ƒ์ˆ˜๋Š” ๊ทธ๋ƒฅ ํ•ด๋‹น ํด๋ž˜์Šค ๋‚ด์—์„œ๋งŒ ๊ฐ€์ง€๊ณ  ์žˆ๋„๋ก ํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ์ž์ฃผ ์“ฐ๋Š” ๊ฒƒ๋“ค์€ ํด๋ž˜์Šค๋กœ ๋ถ„๋ฆฌํ• ๊นŒ๋ผ๋Š” ์ƒ๊ฐ๋„ ์ž ๊น ์Šค์ณ์ง€๋‚˜๊ฐ”์—ˆ๋Š”๋ฐ ๊ฐœ์ธ์ ์œผ๋กœ ํ•ด๋‹น ์ฃผ์ฐจ ๊ณผ์ œ๊ฐ€ ์‹œ๊ฐ„์ ์œผ๋กœ ๋ถ€์กฑํ–ˆ์–ด์„œ ์˜๋ฏธ ์—†๋Š” ์ˆ˜๋“ค์„ ์œ„ํ•ด ๋”ฐ๋กœ ํด๋ž˜์Šค๊นŒ์ง€ ๋ถ„๋ฆฌํ•˜๊ณ  ์ž‘์„ฑํ•  ์‹œ๊ฐ„ ๋ฐ ๋น„์šฉ์  ์ธก๋ฉด์—์„œ ZERO์˜ ์žฌ์‚ฌ์šฉ์„ฑ์„ ์ตœ๋Œ€๋กœ ๋Œ์–ด์˜ฌ๋ฆด ํ•„์š” ์—†๋‹ค๊ณ  ๊ฒฐ์ •ํ–ˆ์—ˆ์Šต๋‹ˆ๋‹ค.
@@ -1 +1,239 @@ # java-convenience-store-precourse +## ๐Ÿช ํ”„๋กœ๊ทธ๋žจ ์†Œ๊ฐœ +๊ตฌ๋งค์ž์˜ ํ• ์ธ ํ˜œํƒ๊ณผ ์žฌ๊ณ  ์ƒํ™ฉ์„ ๊ณ ๋ คํ•˜์—ฌ ์ตœ์ข… ๊ฒฐ์ œ ๊ธˆ์•ก์„ ๊ณ„์‚ฐํ•˜๊ณ  ์•ˆ๋‚ดํ•˜๋Š” ๊ฒฐ์ œ ์‹œ์Šคํ…œ +### ์ž…๋ ฅ +- ์ƒํ’ˆ ๋ชฉ๋ก๊ณผ ํ–‰์‚ฌ ๋ชฉ๋ก ํŒŒ์ผ +- ๊ตฌ๋งคํ•  ์ƒํ’ˆ๊ณผ ์ˆ˜๋Ÿ‰ + - ์ƒํ’ˆ๋ช…, ์ˆ˜๋Ÿ‰์€ ํ•˜์ดํ”ˆ(-), ๊ฐœ๋ณ„ ์ƒํ’ˆ ๋Œ€๊ด„ํ˜ธ([])๋กœ ๋ฌถ์–ด ์‰ผํ‘œ(,)๋กœ ๊ตฌ๋ถ„ + - ex) [์ฝœ๋ผ-10],[์‚ฌ์ด๋‹ค-3] +- ํ”„๋ฆฌ๋ชจ์…˜ ์ ์šฉ์ด ๊ฐ€๋Šฅํ•œ ์ƒํ’ˆ์— ๋Œ€ํ•ด ๊ณ ๊ฐ์ด ํ•ด๋‹น ์ˆ˜๋Ÿ‰๋ณด๋‹ค ์ ๊ฒŒ ๊ฐ€์ ธ์˜จ ๊ฒฝ์šฐ, ๊ทธ ์ˆ˜๋Ÿ‰๋งŒํผ ์ถ”๊ฐ€ ์—ฌ๋ถ€ + - Y: ์ฆ์ • ๋ฐ›์„ ์ˆ˜ ์žˆ๋Š” ์ƒํ’ˆ์„ ์ถ”๊ฐ€ + - N: ์ฆ์ • ๋ฐ›์„ ์ˆ˜ ์žˆ๋Š” ์ƒํ’ˆ์„ ์ถ”๊ฐ€ํ•˜์ง€ ์•Š์Œ +- ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๊ฐ€ ๋ถ€์กฑํ•˜์—ฌ ์ผ๋ถ€ ์ˆ˜๋Ÿ‰์„ ํ”„๋กœ๋ชจ์…˜ ํ˜œํƒ ์—†์ด ๊ฒฐ์ œํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ, ์ผ๋ถ€ ์ˆ˜๋Ÿ‰์— ๋Œ€ํ•ด ์ •๊ฐ€๋กœ ๊ฒฐ์ œํ• ์ง€ ์—ฌ๋ถ€ + - Y: ์ผ๋ถ€ ์ˆ˜๋Ÿ‰์— ๋Œ€ํ•ด ์ •๊ฐ€๋กœ ๊ฒฐ์ œ + - N: ์ •๊ฐ€๋กœ ๊ฒฐ์ œํ•ด์•ผํ•˜๋Š” ์ˆ˜๋Ÿ‰๋งŒํผ ์ œ์™ธํ•œ ํ›„ ๊ฒฐ์ œ๋ฅผ ์ง„ํ–‰ +- ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ ์šฉ ์—ฌ๋ถ€ + - Y: ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ ์šฉ + - N: ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ ์šฉํ•˜์ง€ ์•Š์Œ +- ์ถ”๊ฐ€ ๊ตฌ๋งค ์—ฌ๋ถ€ + - Y: ์žฌ๊ณ ๊ฐ€ ์—…๋ฐ์ดํŠธ๋œ ์ƒํ’ˆ ๋ชฉ๋ก์„ ํ™•์ธ ํ›„ ์ถ”๊ฐ€๋กœ ๊ตฌ๋งค ์ง„ํ–‰ + - N: ๊ตฌ๋งค ์ข…๋ฃŒ +### ์ถœ๋ ฅ +- ํ™˜์˜ ์ธ์‚ฌ +- ์ƒํ’ˆ๋ช…, ๊ฐ€๊ฒฉ, ํ”„๋กœ๋ชจ์…˜ ์ด๋ฆ„, ์žฌ๊ณ  + - ์žฌ๊ณ ๊ฐ€ 0๊ฐœ๋ผ๋ฉด ```์žฌ๊ณ ์—†์Œ```์„ ์ถœ๋ ฅ +- ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ์ด ๊ฐ€๋Šฅํ•œ ์ƒํ’ˆ์— ๋Œ€ํ•ด ๊ณ ๊ฐ์ด ํ•ด๋‹น ์ˆ˜๋Ÿ‰๋งŒํผ ๊ฐ€์ ธ์˜ค์ง€ ์•Š์•˜์„ ๊ฒฝ์šฐ, ํ˜œํƒ์— ๋Œ€ํ•œ ์•ˆ๋‚ด ๋ฉ”์‹œ์ง€๋ฅผ ์ถœ๋ ฅ +- ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๊ฐ€ ๋ถ€์กฑํ•˜์—ฌ ์ผ๋ถ€ ์ˆ˜๋Ÿ‰์„ ํ”„๋กœ๋ชจ์…˜ ํ˜œํƒ ์—†์ด ๊ฒฐ์ œํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ, ์ผ๋ถ€ ์ˆ˜๋Ÿ‰์— ๋Œ€ํ•ด ์ •๊ฐ€๋กœ ๊ฒฐ์ œํ• ์ง€ ์—ฌ๋ถ€์— ๋Œ€ํ•œ ์•ˆ๋‚ด ๋ฉ”์‹œ์ง€ ์ถœ๋ ฅ +- ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ ์šฉ ์—ฌ๋ถ€๋ฅผ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด ์•ˆ๋‚ด ๋ฌธ๊ตฌ ์ถœ๋ ฅ +- ๊ตฌ๋งค ์ƒํ’ˆ ๋‚ด์—ญ, ์ฆ์ • ์ƒํ’ˆ ๋‚ด์—ญ, ๊ธˆ์•ก ์ •๋ณด ์ถœ๋ ฅ +- ์ถ”๊ฐ€ ๊ตฌ๋งค ์—ฌ๋ถ€๋ฅผ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•œ ์•ˆ๋‚ด ๋ฌธ๊ตฌ ์ถœ๋ ฅ +- ์‚ฌ์šฉ์ž๊ฐ€ ์ž˜๋ชป๋œ ๊ฐ’์„ ์ž…๋ ฅํ–ˆ์„ ๋•Œ, โ€œERRORโ€๋กœ ์‹œ์ž‘ํ•˜๋Š” ์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€์™€ ํ•จ๊ป˜ ์ƒํ™ฉ์— ๋งž๋Š” ์•ˆ๋‚ด ์ถœ๋ ฅ +``` +์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค. +ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. + +- ์ฝœ๋ผ 1,000์› 10๊ฐœ ํƒ„์‚ฐ2+1 +- ์ฝœ๋ผ 1,000์› 10๊ฐœ +- ์‚ฌ์ด๋‹ค 1,000์› 8๊ฐœ ํƒ„์‚ฐ2+1 +- ์‚ฌ์ด๋‹ค 1,000์› 7๊ฐœ +- ์˜ค๋ Œ์ง€์ฃผ์Šค 1,800์› 9๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์˜ค๋ Œ์ง€์ฃผ์Šค 1,800์› ์žฌ๊ณ  ์—†์Œ +- ํƒ„์‚ฐ์ˆ˜ 1,200์› 5๊ฐœ ํƒ„์‚ฐ2+1 +- ํƒ„์‚ฐ์ˆ˜ 1,200์› ์žฌ๊ณ  ์—†์Œ +- ๋ฌผ 500์› 10๊ฐœ +- ๋น„ํƒ€๋ฏผ์›Œํ„ฐ 1,500์› 6๊ฐœ +- ๊ฐ์ž์นฉ 1,500์› 5๊ฐœ ๋ฐ˜์งํ• ์ธ +- ๊ฐ์ž์นฉ 1,500์› 5๊ฐœ +- ์ดˆ์ฝ”๋ฐ” 1,200์› 5๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์ดˆ์ฝ”๋ฐ” 1,200์› 5๊ฐœ +- ์—๋„ˆ์ง€๋ฐ” 2,000์› 5๊ฐœ +- ์ •์‹๋„์‹œ๋ฝ 6,400์› 8๊ฐœ +- ์ปต๋ผ๋ฉด 1,700์› 1๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์ปต๋ผ๋ฉด 1,700์› 10๊ฐœ + +๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1]) +[์ฝœ๋ผ-3],[์—๋„ˆ์ง€๋ฐ”-5] + +๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N) +Y + +==============W ํŽธ์˜์ ================ +์ƒํ’ˆ๋ช… ์ˆ˜๋Ÿ‰ ๊ธˆ์•ก +์ฝœ๋ผ 3 3,000 +์—๋„ˆ์ง€๋ฐ” 5 10,000 +=============์ฆ ์ •=============== +์ฝœ๋ผ 1 +==================================== +์ด๊ตฌ๋งค์•ก 8 13,000 +ํ–‰์‚ฌํ• ์ธ -1,000 +๋ฉค๋ฒ„์‹ญํ• ์ธ -3,000 +๋‚ด์‹ค๋ˆ 9,000 + +๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N) +Y + +์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค. +ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. + +- ์ฝœ๋ผ 1,000์› 7๊ฐœ ํƒ„์‚ฐ2+1 +- ์ฝœ๋ผ 1,000์› 10๊ฐœ +- ์‚ฌ์ด๋‹ค 1,000์› 8๊ฐœ ํƒ„์‚ฐ2+1 +- ์‚ฌ์ด๋‹ค 1,000์› 7๊ฐœ +- ์˜ค๋ Œ์ง€์ฃผ์Šค 1,800์› 9๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์˜ค๋ Œ์ง€์ฃผ์Šค 1,800์› ์žฌ๊ณ  ์—†์Œ +- ํƒ„์‚ฐ์ˆ˜ 1,200์› 5๊ฐœ ํƒ„์‚ฐ2+1 +- ํƒ„์‚ฐ์ˆ˜ 1,200์› ์žฌ๊ณ  ์—†์Œ +- ๋ฌผ 500์› 10๊ฐœ +- ๋น„ํƒ€๋ฏผ์›Œํ„ฐ 1,500์› 6๊ฐœ +- ๊ฐ์ž์นฉ 1,500์› 5๊ฐœ ๋ฐ˜์งํ• ์ธ +- ๊ฐ์ž์นฉ 1,500์› 5๊ฐœ +- ์ดˆ์ฝ”๋ฐ” 1,200์› 5๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์ดˆ์ฝ”๋ฐ” 1,200์› 5๊ฐœ +- ์—๋„ˆ์ง€๋ฐ” 2,000์› ์žฌ๊ณ  ์—†์Œ +- ์ •์‹๋„์‹œ๋ฝ 6,400์› 8๊ฐœ +- ์ปต๋ผ๋ฉด 1,700์› 1๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์ปต๋ผ๋ฉด 1,700์› 10๊ฐœ + +๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1]) +[์ฝœ๋ผ-10] + +ํ˜„์žฌ ์ฝœ๋ผ 4๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N) +Y + +๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N) +N + +==============W ํŽธ์˜์ ================ +์ƒํ’ˆ๋ช… ์ˆ˜๋Ÿ‰ ๊ธˆ์•ก +์ฝœ๋ผ 10 10,000 +=============์ฆ ์ •=============== +์ฝœ๋ผ 2 +==================================== +์ด๊ตฌ๋งค์•ก 10 10,000 +ํ–‰์‚ฌํ• ์ธ -2,000 +๋ฉค๋ฒ„์‹ญํ• ์ธ -0 +๋‚ด์‹ค๋ˆ 8,000 + +๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N) +Y + +์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค. +ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. + +- ์ฝœ๋ผ 1,000์› ์žฌ๊ณ  ์—†์Œ ํƒ„์‚ฐ2+1 +- ์ฝœ๋ผ 1,000์› 7๊ฐœ +- ์‚ฌ์ด๋‹ค 1,000์› 8๊ฐœ ํƒ„์‚ฐ2+1 +- ์‚ฌ์ด๋‹ค 1,000์› 7๊ฐœ +- ์˜ค๋ Œ์ง€์ฃผ์Šค 1,800์› 9๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์˜ค๋ Œ์ง€์ฃผ์Šค 1,800์› ์žฌ๊ณ  ์—†์Œ +- ํƒ„์‚ฐ์ˆ˜ 1,200์› 5๊ฐœ ํƒ„์‚ฐ2+1 +- ํƒ„์‚ฐ์ˆ˜ 1,200์› ์žฌ๊ณ  ์—†์Œ +- ๋ฌผ 500์› 10๊ฐœ +- ๋น„ํƒ€๋ฏผ์›Œํ„ฐ 1,500์› 6๊ฐœ +- ๊ฐ์ž์นฉ 1,500์› 5๊ฐœ ๋ฐ˜์งํ• ์ธ +- ๊ฐ์ž์นฉ 1,500์› 5๊ฐœ +- ์ดˆ์ฝ”๋ฐ” 1,200์› 5๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์ดˆ์ฝ”๋ฐ” 1,200์› 5๊ฐœ +- ์—๋„ˆ์ง€๋ฐ” 2,000์› ์žฌ๊ณ  ์—†์Œ +- ์ •์‹๋„์‹œ๋ฝ 6,400์› 8๊ฐœ +- ์ปต๋ผ๋ฉด 1,700์› 1๊ฐœ MD์ถ”์ฒœ์ƒํ’ˆ +- ์ปต๋ผ๋ฉด 1,700์› 10๊ฐœ + +๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1]) +[์˜ค๋ Œ์ง€์ฃผ์Šค-1] + +ํ˜„์žฌ ์˜ค๋ Œ์ง€์ฃผ์Šค์€(๋Š”) 1๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N) +Y + +๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N) +Y + +==============W ํŽธ์˜์ ================ +์ƒํ’ˆ๋ช… ์ˆ˜๋Ÿ‰ ๊ธˆ์•ก +์˜ค๋ Œ์ง€์ฃผ์Šค 2 3,600 +=============์ฆ ์ •=============== +์˜ค๋ Œ์ง€์ฃผ์Šค 1 +==================================== +์ด๊ตฌ๋งค์•ก 2 3,600 +ํ–‰์‚ฌํ• ์ธ -1,800 +๋ฉค๋ฒ„์‹ญํ• ์ธ -0 +๋‚ด์‹ค๋ˆ 1,800 + +๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N) +N +``` + +## ๐Ÿ› ๏ธ ๊ตฌํ˜„ ๊ธฐ๋Šฅ ๋ชฉ๋ก +### ์ž…๋ ฅ +- ```camp.nextstep.edu.missionutils.Console```์˜ ```readLine()``` ์œผ๋กœ ์ž…๋ ฅ์„ ๋ฐ›๋Š”๋‹ค. + - ๊ตฌ๋งคํ•  ์ƒํ’ˆ๊ณผ ์ˆ˜๋Ÿ‰ + - ex) [์ฝœ๋ผ-10],[์‚ฌ์ด๋‹ค-3] + - Y/N + - ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ์ด ๊ฐ€๋Šฅํ•œ ์ƒํ’ˆ์— ๋Œ€ํ•ด ๊ณ ๊ฐ์ด ํ•ด๋‹น ์ˆ˜๋Ÿ‰๋ณด๋‹ค ์ ๊ฒŒ ๊ฐ€์ ธ์˜จ ๊ฒฝ์šฐ, ๊ทธ ์ˆ˜๋Ÿ‰๋งŒํผ ์ถ”๊ฐ€ ์—ฌ๋ถ€ + - ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๊ฐ€ ๋ถ€์กฑํ•˜์—ฌ ์ผ๋ถ€ ์ˆ˜๋Ÿ‰์„ ํ”„๋กœ๋ชจ์…˜ ํ˜œํƒ ์—†์ด ๊ฒฐ์ œํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ, ์ผ๋ถ€ ์ˆ˜๋Ÿ‰์— ๋Œ€ํ•ด ์ •๊ฐ€๋กœ ๊ฒฐ์ œํ• ์ง€ ์—ฌ๋ถ€ + - ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ ์šฉ ์—ฌ๋ถ€ + - ์ถ”๊ฐ€ ๊ตฌ๋งค ์—ฌ๋ถ€ +- ์ž˜๋ชป๋œ ์ž…๋ ฅ์„ ๋ฐ›์„ ์‹œ ```IllegalArgumentException```๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๊ณ  ๊ทธ ๋ถ€๋ถ„๋ถ€ํ„ฐ ์ž…๋ ฅ์„ ๋‹ค์‹œ ๋ฐ›๋Š”๋‹ค. + - ```IllegalArgumentException```, ```IllegalStateException``` ๊ณผ ๊ฐ™์€ ๋ช…ํ™•์„ ์œ ํ˜•์œผ๋กœ ์ฒ˜๋ฆฌ๋œ๋‹ค. +### ์˜ˆ์™ธ ์ž…๋ ฅ +- ๊ณตํ†ต + - ๋นˆ ์ž…๋ ฅ + - ๊ณต๋ฐฑ์ด ํฌํ•จ๋œ ์ž…๋ ฅ +- ๊ตฌ๋งคํ•  ์ƒํ’ˆ + - ์ž˜๋ชป๋œ ์ƒํ’ˆ๋ช… +- ๊ตฌ๋งคํ•  ์ˆ˜๋Ÿ‰ + - ์ •์ˆ˜๊ฐ€ ์•„๋‹Œ ๊ฐ’ + - ์žฌ๊ณ ๋ณด๋‹ค ์ ์€ ๊ฐ’ + - ์žฌ๊ณ ๋ณด๋‹ค ํฐ ๊ฐ’ +- ๊ตฌ๋งคํ•  ์ƒํ’ˆ๊ณผ ์ˆ˜๋Ÿ‰ + - [์ƒํ’ˆ๋ช…-์ˆ˜๋Ÿ‰],[์ƒํ’ˆ๋ช…-์ˆ˜๋Ÿ‰]์ด ์•„๋‹Œ ์ž˜๋ชป๋œ ํ˜•์‹ +- Y/N + - Y/N ์ด์™ธ์˜ ๋ฌธ์ž์—ด +### ๊ธฐ๋Šฅ +- ์ƒํ’ˆ ๋ชฉ๋ก๊ณผ ํ–‰์‚ฌ ๋ชฉ๋ก ํŒŒ์ผ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ +- ์žฌ๊ณ ๊ด€๋ฆฌ + - ๊ฐ ์ƒํ’ˆ์˜ ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ๊ณ ๋ คํ•˜์—ฌ ๊ฒฐ์ œ ๊ฐ€๋Šฅ ์—ฌ๋ถ€ ํ™•์ธ + - ๊ณ ๊ฐ์ด ์ƒํ’ˆ์„ ๊ตฌ๋งคํ•  ๋•Œ๋งˆ๋‹ค, ๊ฒฐ์ œ๋œ ์ˆ˜๋Ÿ‰๋งŒํผ ํ•ด๋‹น ์ƒํ’ˆ์˜ ์žฌ๊ณ ์—์„œ ์ฐจ๊ฐํ•˜์—ฌ ์ˆ˜๋Ÿ‰ ๊ด€๋ฆฌ + - ์žฌ๊ณ ๋ฅผ ์ฐจ๊ฐํ•จ์œผ๋กœ์จ ์‹œ์Šคํ…œ์€ ์ตœ๊ณ  ์žฌ๊ณ  ์ƒํƒœ๋ฅผ ์œ ์ง€ํ•˜๋ฉฐ, ๋‹ค์Œ ๊ณ ๊ฐ์ด ๊ตฌ๋งคํ•  ๋•Œ ์ •ํ™•ํ•œ ์žฌ๊ณ  ์ •๋ณด๋ฅผ ์ œ๊ณต +- ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ + - ์˜ค๋Š˜ ๋‚ ์งœ๊ฐ€ ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„ ๋‚ด์— ํฌํ•จ๋œ ๊ฒฝ์šฐ์—๋งŒ ํ• ์ธ ์ œ๊ณต + - ํ˜„์žฌ ๋‚ ์งœ์™€ ์‹œ๊ฐ„ ๊ฐ€์ ธ์˜ค๊ธฐ๋Š” ```camp.nextstep.edu.missionutils.DateTimes```์˜ ```now()``` ํ™œ์šฉ + - ํ”„๋กœ๋ชจ์…˜์€ N๊ฐœ ๊ตฌ๋งค ์‹œ 1๊ฐœ ๋ฌด๋ฃŒ ์ฆ์ •์˜ ํ˜•ํƒœ๋กœ ์ง„ํ–‰ + - 1+1 ๋˜๋Š” 2+1 ํ”„๋กœ๋ชจ์…˜์ด ๊ฐ๊ฐ ์ง€์ •๋œ ์ƒํ’ˆ์— ์ ์šฉ๋˜๋ฉฐ, ๋™์ผ ์ƒํ’ˆ์— ์—ฌ๋Ÿฌ ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ๋˜์ง€ ์•Š์Œ + - ํ”„๋กœ๋ชจ์…˜ ํ˜œํƒ์€ ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ  ๋‚ด์—์„œ๋งŒ ์ ์šฉ ๊ฐ€๋Šฅ + - ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„ ์ค‘์ด๋ผ๋ฉด ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ  ์šฐ์„ ์ ์œผ๋กœ ์ฐจ๊ฐ + - ์žฌ๊ณ ๊ฐ€ ๋ถ€์กฑํ•  ๊ฒฝ์šฐ ์ผ๋ฐ˜ ์žฌ๊ณ  ์‚ฌ์šฉ + - ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ์ด ๊ฐ€๋Šฅํ•œ ์ƒํ’ˆ์— ๋Œ€ํ•ด ๊ณ ๊ฐ์ด ํ•ด๋‹น ์ˆ˜๋Ÿ‰๋ณด๋‹ค ์ ๊ฒŒ ๊ฐ€์ ธ์˜จ ๊ฒฝ์šฐ, ํ•„์š”ํ•œ ์ˆ˜๋Ÿ‰์„ ์ถ”๊ฐ€๋กœ ๊ฐ€์ ธ์˜ค๋ฉด ํ˜œํƒ์„ ๋ฐ›์„ ์ˆ˜ ์žˆ์Œ์„ ์•ˆ๋‚ด + - ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๊ฐ€ ๋ถ€์กฑํ•˜์—ฌ ์ผ๋ถ€ ์ˆ˜๋Ÿ‰์„ ํ”„๋กœ๋ชจ์…˜ ํ˜œํƒ ์—†์ด ๊ฒฐ์ œํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ, ์ผ๋ถ€ ์ˆ˜๋Ÿ‰์— ๋Œ€ํ•ด ์ •๊ฐ€๋กœ ๊ฒฐ์ œํ•˜๊ฒŒ ๋จ์„ ์•ˆ๋‚ด +- ๋ฉค๋ฒ„์‹ญ ํ• ์ธ + - ๋ฉค๋ฒ„์‹ญ ํšŒ์›์€ ํ”„๋กœ๋ชจ์…˜ ๋ฏธ์ ์šฉ ๊ธˆ์•ก์˜ 30%๋ฅผ ํ• ์ธ ๋ฐ›์Œ + - ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ ํ›„ ๋‚จ์€ ๊ธˆ์•ก์— ๋Œ€ํ•ด ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ ์šฉ + - ๋ฉค๋ฒ„์‹ญ ํ• ์ธ์˜ ์ตœ๋Œ€ ํ•œ๋„๋Š” 8,000์› +### ์ถœ๋ ฅ +- ํ™˜์˜์ธ์‚ฌ +- ์ƒํ’ˆ๋ช…, ๊ฐ€๊ฒฉ, ํ”„๋กœ๋ชจ์…˜ ์ด๋ฆ„, ์žฌ๊ณ  +- ์•ˆ๋‚ด ๋ฉ”์‹œ์ง€ + - ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ์ด ๊ฐ€๋Šฅํ•œ ์ƒํ’ˆ์— ๋Œ€ํ•ด ๊ณ ๊ฐ์ด ํ•ด๋‹น ์ˆ˜๋Ÿ‰๋งŒํผ ๊ฐ€์ ธ์˜ค์ง€ ์•Š์•˜์„ ๊ฒฝ์šฐ + - ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๊ฐ€ ๋ถ€์กฑํ•˜์—ฌ ์ผ๋ถ€ ์ˆ˜๋Ÿ‰์„ ํ”„๋กœ๋ชจ์…˜ ํ˜œํƒ ์—†์ด ๊ฒฐ์ œํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ + - ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ ์šฉ ์—ฌ๋ถ€๋ฅผ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•œ ๊ฒฝ์šฐ +- ์˜์ˆ˜์ฆ: ๊ณ ๊ฐ์˜ ๊ตฌ๋งค ๋‚ด์—ญ๊ณผ ํ• ์ธ์„ ์š”์•ฝํ•˜์—ฌ ์ถœ๋ ฅ + - ๊ตฌ๋งค ์ƒํ’ˆ ๋‚ด์—ญ + - ๊ตฌ๋งคํ•œ ์ƒํ’ˆ๋ช… + - ์ˆ˜๋Ÿ‰ + - ๊ฐ€๊ฒฉ + - ์ฆ์ • ์ƒํ’ˆ ๋‚ด์—ญ + - ํ”„๋กœ๋ชจ์…˜์— ๋”ฐ๋ผ ๋ฌด๋ฃŒ๋กœ ์ œ๊ณต๋œ ์ฆ์  ์ƒํ’ˆ ๋ชฉ๋ก + - ๊ธˆ์•ก ์ •๋ณด + - ์ด ๊ตฌ๋งค์•ก: ๊ตฌ๋งคํ•œ ์ƒํ’ˆ์˜ ์ด ์ˆ˜๋Ÿ‰๊ณผ ์ด ๊ธˆ์•ก + - ํ–‰์‚ฌํ• ์ธ: ํ”„๋กœ๋ชจ์…˜์— ์˜ํ•ด ํ• ์ธ๋œ ๊ธˆ์•ก + - ๋ฉค๋ฒ„์‹ญํ• ์ธ: ๋ฉค๋ฒ„์‹ญ์— ์˜ํ•ด ์ถ”๊ฐ€๋กœ ํ• ์ธ๋œ ๊ธˆ์•ก + - ๋‚ด์‹ค๋ˆ: ์ตœ์ข… ๊ฒฐ์ œ ๊ธˆ์•ก +- ```IllegalArgumentException``` ๊ฐ€ ๋ฐœ์ƒํ•  ๋•Œ โ€œ[ERROR]โ€๋กœ ์‹œ์ž‘ํ•˜๋Š” ์˜ค๋ฅ˜ ๋ฉ”์‹œ์ง€์™€ ํ•จ๊ป˜ ์ƒํ™ฉ์— ๋งž๋Š” ์•ˆ๋‚ด๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. + - ๊ตฌ๋งคํ•  ์ƒํ’ˆ๊ณผ ์ˆ˜๋Ÿ‰ ํ˜•์‹์ด ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ๊ฒฝ์šฐ + - ```[ERROR] ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.``` + - ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์„ ์ž…๋ ฅํ•œ ๊ฒฝ์šฐ + - ```[ERROR] ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.``` + - ๊ตฌ๋งค ์ˆ˜๋Ÿ‰์ด ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•œ ๊ฒฝ์šฐ + - ```[ERROR] ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.``` + - ๊ธฐํƒ€ ์ž˜๋ชป๋œ ์ž…๋ ฅ์˜ ๊ฒฝ์šฐ + - ```[ERROR] ์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.```
Unknown
๊ผผ๊ผผํ•˜๊ฒŒ ์ž˜ ์ •๋ฆฌํ•˜์‹  ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,52 @@ +package store.io; + +import store.object.Receipt; +import store.product.Product; + +import java.util.List; + +public class OutputView { + public void greeting() { + System.out.println("์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค."); + System.out.println("ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค.\n"); + } + + public void printProducts(List<Product> products) { + products.forEach(System.out::println); + } + + public void purchaseGuide() { + System.out.println("\n๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"); + } + + public void promotionAdditionalGuide(String productName) { + System.out.printf("\nํ˜„์žฌ %s์€(๋Š”) 1๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)\n", productName); + } + + public void promotionImpossibleGuide(String productName, int amount) { + System.out.printf("\nํ˜„์žฌ %s %d๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)\n", productName, amount); + } + + public void membershipGuide() { + System.out.println("\n๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๋‹ค? (Y/N)"); + } + + public void printReceipt(Receipt receipt) { + System.out.println("\n==============W ํŽธ์˜์ ================"); + String productReportFormat = "%-19s%-10s%-6s"; + System.out.printf((productReportFormat) + "%n", "์ƒํ’ˆ๋ช…", "์ˆ˜๋Ÿ‰", "๊ธˆ์•ก"); + System.out.printf(receipt.productReport()); + System.out.println("==============์ฆ ์ •================"); + System.out.printf(receipt.promotionReport()); + System.out.println("======================================"); + System.out.printf(receipt.paymentReport()); + } + + public void closingGuide() { + System.out.println("\n๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"); + } + + public void printError(String errorMessage) { + System.out.println("\n" + errorMessage); + } +}
Java
`\n`์€ OS์— ์ข…์†์ ์ธ ๊ฐœํ–‰ ๋ฌธ์ž์ธ ๊ฑฐ ๊ฐ™์•„์š”! `System.lineSeparator()`๋ฅผ ํ™œ์šฉํ•ด๋ณด์‹œ๋ฉด ๋” ์ข‹์„ ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,61 @@ +package store.product; + +import store.file.FileReader; +import store.io.OutputView; +import store.object.Amount; +import store.type.ErrorMessage; + +import java.util.List; +import java.util.Map; + +public class ProductManager { + private final List<Product> products; + + public ProductManager() { + FileReader fileReader = new FileReader(); + products = fileReader.createProduct(); + } + + public Amount purchase(String name, int amount) { + List<Product> purchaseProducts = products.stream() + .filter(product -> product.isCorrect(name)) + .toList(); + + isExceed(purchaseProducts, amount); + return applyPromotion(purchaseProducts, amount); + } + + public Amount applyPromotion(List<Product> purchaseProducts, int amount) { + Amount purchaseAmount = purchaseProducts.getFirst().buy(amount); + if (purchaseAmount.isAdditional()) { + Amount additionalAmount = purchaseProducts.getLast().buy(purchaseAmount.getAdditional()); + purchaseAmount.addBuyAmount(additionalAmount.getBuy()); + } + return purchaseAmount; + } + + public void print() { + OutputView outputView = new OutputView(); + outputView.printProducts(products); + } + + public void isExceed(List<Product> purchaseProducts, int amount) { + int totalQuantity = 0; + for (Product product : purchaseProducts) { + totalQuantity += product.getQuantity(); + } + if (totalQuantity < amount) { + throw new IllegalArgumentException(ErrorMessage.EXCEED_QUANTITY.getMessage()); + } + } + + public void validate(Map<String, Integer> purchaseData) { + for (String productName : purchaseData.keySet()) { + boolean exists = products.stream() + .anyMatch(product -> product.isExist(productName)); + if (!exists) { + throw new IllegalArgumentException(ErrorMessage.NON_EXISTING_PRODUCT.getMessage()); + } + } + } +}
Java
`ConvenienceStore`์—์„œ `outputview`๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š”๋ฐ, ๋”ฐ๋กœ ๋˜ ์ƒ์„ฑํ•ด์„œ ์ถœ๋ ฅํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,81 @@ +package store.promotion; + +import store.io.InputView; +import store.io.OutputView; +import store.object.Amount; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +public class Promotion { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + private final String name; + private final int buy; + private final int get; + private final LocalDate startDate; + private final LocalDate endDate; + + public Promotion(String name, int buy, int get, LocalDate startDate, LocalDate endDate) { + this.name = name; + this.buy = buy; + this.get = get; + this.startDate = startDate; + this.endDate = endDate; + } + + public Amount apply(String productName, int price, int quantity, int amount) { + int total = buy + get; + int maxAmount = quantity / total * total; + if (amount <= maxAmount && amount % total == 0) { + return new Amount(productName, price, amount, amount / total, 0, 0); + } + if (amount % total == buy && amount < maxAmount) { + return additionalGet(productName, price, quantity, amount, total); + } + return additionalBuy(productName, price, quantity, amount, total, maxAmount); + } + + public Amount additionalGet(String productName, int price, int quantity, int amount, int total) { + outputView.promotionAdditionalGuide(productName); + if (inputView.readAnswer().equals("Y")) { + return new Amount(productName, price, amount + 1, (amount + 1) / total, 0, 0); + } + return new Amount(productName, price, amount, amount / total, 0, 0); + } + + public Amount additionalBuy(String productName, int price, int quantity, int amount, int total, int maxAmount) { + int impossibleAmount = calcImpossibleAmount(amount, total, maxAmount); + outputView.promotionImpossibleGuide(productName, impossibleAmount); + if (inputView.readAnswer().trim().equals("Y")) { + if (quantity - (amount - impossibleAmount) < impossibleAmount) { + return new Amount(productName, price, quantity, (amount - impossibleAmount) / total, amount - quantity, impossibleAmount); + } + return new Amount(productName, price, amount, (amount - impossibleAmount) / total, 0, impossibleAmount); + } + return new Amount(productName, price, amount - impossibleAmount, (amount - impossibleAmount) / total, 0, 0); + } + + public int calcImpossibleAmount(int amount, int total, int maxAmount) { + int impossibleAmount = amount % total; + if (amount > maxAmount) { + impossibleAmount = amount - maxAmount; + } + return impossibleAmount; + } + + public boolean isPossible(LocalDateTime now) { + LocalDate nowDate = now.toLocalDate(); + return (startDate.isBefore(nowDate) || startDate.isEqual(nowDate)) && + (endDate.isAfter(nowDate) || endDate.isEqual(nowDate)); + } + + public boolean isMatch(String promotion) { + return promotion.equals(name); + } + + @Override + public String toString() { + return this.name; + } +}
Java
`toLocalDate`๋ฉ”์„œ๋“œ๋ฅผ ์ž˜ ํ™œ์šฉํ•˜์‹  ๋ถ€๋ถ„์ด ์ธ์ƒ์ ์ž…๋‹ˆ๋‹ค!
@@ -0,0 +1,18 @@ +package store.type; + +public enum ProductType { + NAME(0), + PRICE(1), + QUANTITY(2), + PROMOTION(3); + + private final int value; + + ProductType(int value) { + this.value = value; + } + + public int getValue() { + return value; + } +}
Java
splitํ•œ ๋ฐฐ์—ด์„ ์ ‘๊ทผํ•  ์ธ๋ฑ์Šค๋ฅผ enum์œผ๋กœ ๋งŒ๋“œ์‹  ์ ์ด ์ธ์ƒ์ ์ž…๋‹ˆ๋‹ค! `value`๋Š” ์˜๋ฏธ๊ฐ€ ๋ช…ํ™•ํ•˜์ง€ ์•Š์€ ๊ฑฐ ๊ฐ™์•„์š”! `index`๋Š” ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,24 @@ +package store.file; + +import store.product.Product; +import store.promotion.Promotion; +import store.promotion.PromotionManager; + +import java.io.InputStream; +import java.util.List; + +public class FileReader { + public List<Product> createProduct() { + ProductParser productParser = new ProductParser(new PromotionManager(createPromotion())); + return productParser.read(road("products")); + } + + public List<Promotion> createPromotion() { + PromotionParser promotionParser = new PromotionParser(); + return promotionParser.read(road("promotions")); + } + + public InputStream road(String filename) { + return getClass().getClassLoader().getResourceAsStream(filename + ".md"); + } +}
Java
ํ˜น์‹œ `load`๋‚˜ `read`๋ฅผ ์ž˜๋ชป ์ž‘์„ฑํ•˜์‹  ๋ถ€๋ถ„์ผ๊นŒ์š”?
@@ -0,0 +1,45 @@ +package store.io; + +import camp.nextstep.edu.missionutils.Console; +import store.type.ErrorMessage; + +public class InputView { + private final OutputView outputView = new OutputView(); + + public String readAnswer() { + while (true) { + try { + String input = Console.readLine(); + answerValidate(input); + return input; + } catch (IllegalArgumentException e) { + outputView.printError(e.getMessage()); + } + } + } + + public String readPurchaseProduct() { + while (true) { + try { + String input = Console.readLine(); + purchaseProductValidate(input); + return input; + } catch (IllegalArgumentException e) { + outputView.printError(e.getMessage()); + } + } + } + + public void answerValidate(String input) { + if (!"Y".equals(input) && !"N".equals(input)) { + throw new IllegalArgumentException(ErrorMessage.INVALID_INPUT.getMessage()); + } + } + + public void purchaseProductValidate(String input) { + String regex = "\\[([a-zA-Z๊ฐ€-ํžฃ]+-[1-9][0-9]*)\\](,\\[([a-zA-Z๊ฐ€-ํžฃ]+-[1-9][0-9]*)\\])*"; + if (!input.matches(regex)) { + throw new IllegalArgumentException(ErrorMessage.INVALID_FORMAT.getMessage()); + } + } +}
Java
while-true ๋ถ€๋ถ„์ด ๋ฐ˜๋ณต๋˜์–ด์„œ ํ•จ์ˆ˜ํ˜• ์ธํ„ฐํŽ˜์ด์Šค๋„ ํ™œ์šฉํ•ด๋ณด์‹œ๋ฉด ์œ ์ง€๋ณด์ˆ˜์— ๋” ์ข‹์„ ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,77 @@ +package store.object; + +import java.util.ArrayList; +import java.util.List; + +public class Receipt { + private final List<Amount> amounts = new ArrayList<>(); + private boolean membershipDiscount; + private int totalPrice = 0; + private int totalBuyAmount = 0; + private int promotionPrice = 0; + private int membershipAvailablePrice = 0; + private int membershipPrice = 0; + private int payment = 0; + + public void addAmount(Amount amount) { + if (amount.isPurchase()) { + amounts.add(amount); + } + } + + public void membershipApply(String input) { + if (input.equals("Y")) { + membershipDiscount = true; + } + } + + public String productReport() { + StringBuilder productReport = new StringBuilder(); + amounts.forEach(amount -> productReport.append(amount.parseProductDetails())); + return productReport.toString(); + } + + public String promotionReport() { + StringBuilder promotionReport = new StringBuilder(); + amounts.forEach(amount -> promotionReport.append(amount.parsePromotionDetails())); + return promotionReport.toString(); + } + + public String paymentReport() { + calcPayment(); + return parsePaymentDetails(); + } + + public void calcPayment() { + amounts.forEach(amount -> totalPrice += amount.totalPrice()); + amounts.forEach(amount -> totalBuyAmount += amount.getBuy()); + amounts.forEach(amount -> promotionPrice += amount.promotionPrice()); + calcMembershipPrice(); + + payment = totalPrice - promotionPrice - membershipPrice; + } + + public void calcMembershipPrice() { + amounts.forEach(amount -> membershipAvailablePrice += amount.membershipAvailablePrice()); + if (membershipDiscount) { + membershipPrice = (int) Math.floor(membershipAvailablePrice * 0.3); + } + if (membershipPrice > 8000) { + membershipPrice = 8000; + } + } + + public String parsePaymentDetails() { + StringBuilder paymentReport = new StringBuilder(); + String totalPriceFormat = "%-19s%-10d%,-6d"; + String otherPriceFormat = "%-29s%s%,-6d"; + return (paymentReport.append(String.format(totalPriceFormat, "์ด๊ตฌ๋งค์•ก", totalBuyAmount, totalPrice)).append("\n") + .append(String.format(otherPriceFormat, "ํ–‰์‚ฌํ• ์ธ", "-", promotionPrice)).append("\n") + .append(String.format(otherPriceFormat, "๋ฉค๋ฒ„์‹ญํ• ์ธ", "-", membershipPrice)).append("\n") + .append(String.format(otherPriceFormat, "๋‚ด์‹ค๋ˆ", "", payment)).append("\n")).toString(); + } + + public boolean isExistence() { + return amounts.size() > 0; + } +}
Java
`0.3`๊ณผ `8000`๋Š” ์ƒ์ˆ˜ํ™”ํ•˜์‹œ๋ฉด ์˜๋ฏธ๊ฐ€ ๋” ๋ช…ํ™•ํ•ด์งˆ ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,80 @@ +package store; + +import camp.nextstep.edu.missionutils.Console; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import store.object.ConvenienceStore; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class ReceiptTest { + private static ByteArrayOutputStream outputStream; + + @BeforeEach + void setUpStream() { + outputStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outputStream)); + } + + @AfterEach + void restoreStream() { + Console.close(); + System.setOut(System.out); + } + + @ParameterizedTest + @CsvSource(value = {"3,1", "4,1", "10,3", "12,3"}) + void ์˜์ˆ˜์ฆ์œผ๋กœ_๊ณ ๊ฐ์˜_๊ตฌ๋งค์™€_์ฆ์ •_๋‚ด์—ญ_๋ณด๊ธฐ(int amount, int promotionAmount) { + String yes = "Y\n"; + String input = yes + yes; + System.setIn(new ByteArrayInputStream(input.getBytes())); + + ConvenienceStore convenienceStore = new ConvenienceStore(); + convenienceStore.init(); + Map<String, Integer> purchaseData = Map.of( + "์ฝœ๋ผ", amount + ); + convenienceStore.createReceipt(purchaseData); + convenienceStore.showReceipt(); + + String expectedProduct = String.format("์ฝœ๋ผ%d%,d", amount, amount * 1000); + String expectedPromotion = String.format("์ฝœ๋ผ%d", promotionAmount); + + assertTrue(outputStream.toString().replaceAll("\\s", "").contains(expectedProduct)); + assertTrue(outputStream.toString().replaceAll("\\s", "").contains(expectedPromotion)); + } + + @Test + void ์˜์ˆ˜์ฆ์œผ๋กœ_๊ธˆ์•ก_์ •๋ณด_๋ณด๊ธฐ() { + String yes = "Y\n"; + String input = yes + yes; + System.setIn(new ByteArrayInputStream(input.getBytes())); + + ConvenienceStore convenienceStore = new ConvenienceStore(); + convenienceStore.init(); + Map<String, Integer> purchaseData = Map.of( + "์ฝœ๋ผ", 3, + "์—๋„ˆ์ง€๋ฐ”", 5 + ); + convenienceStore.createReceipt(purchaseData); + convenienceStore.showReceipt(); + + String expectedReceipt = "์ด๊ตฌ๋งค์•ก813,000"; + String expectedPromotion = "ํ–‰์‚ฌํ• ์ธ-1,000"; + String expectedMembership = "๋ฉค๋ฒ„์‹ญํ• ์ธ-3,000"; + String expectedPayment = "๋‚ด์‹ค๋ˆ9,000"; + + assertTrue(outputStream.toString().replaceAll("\\s", "").contains(expectedReceipt)); + assertTrue(outputStream.toString().replaceAll("\\s", "").contains(expectedPromotion)); + assertTrue(outputStream.toString().replaceAll("\\s", "").contains(expectedMembership)); + assertTrue(outputStream.toString().replaceAll("\\s", "").contains(expectedPayment)); + } +}
Java
๊ผผ๊ผผํ•œ ํ…Œ์ŠคํŠธ๊ฐ€ ์ธ์ƒ์ ์ž…๋‹ˆ๋‹ค! ์‚ฌ์†Œํ•œ ๋ถ€๋ถ„์ด์ง€๋งŒ, ์œ„์— ์žˆ๋Š” assert๊ฐ€ ์‹คํŒจํ•˜๋ฉด ๋ฐ‘์— ์žˆ๋Š” assert๋Š” ์‹คํ–‰๋˜์ง€ ์•Š์„ ๊ฑฐ ๊ฐ™์•„์š”! assertAll๋„ ํ™œ์šฉํ•ด๋ณด์‹œ๋ฉด ๋” ์ข‹์„ ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,82 @@ +package store.object; + +import store.io.InputParser; +import store.io.InputView; +import store.io.OutputView; +import store.product.ProductManager; + +import java.util.Map; + +public class ConvenienceStore { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + private final InputParser inputParser = new InputParser(); + private final ProductManager productManager = new ProductManager(); + private Receipt receipt; + private boolean isOpen = true; + + public void open() { + while (isOpen) { + init(); + announcement(); + purchase(); + close(); + System.out.println(); + } + } + + public void init() { + receipt = new Receipt(); + } + + public void announcement() { + outputView.greeting(); + productManager.print(); + } + + public void purchase() { + outputView.purchaseGuide(); + while (true) { + try { + inputHandle(); + return; + } catch (IllegalArgumentException e) { + outputView.printError(e.getMessage()); + } + } + } + + public void inputHandle() { + String purchaseProducts = inputView.readPurchaseProduct(); + Map<String, Integer> purchaseData = inputParser.mapping(purchaseProducts); + productManager.validate(purchaseData); + createReceipt(purchaseData); + } + + public void createReceipt(Map<String, Integer> purchaseData) { + purchaseData.forEach((name, amount) -> { + Amount purchaseAmount = productManager.purchase(name, amount); + receipt.addAmount(purchaseAmount); + }); + if (receipt.isExistence()) { + membership(); + showReceipt(); + } + } + + public void membership() { + outputView.membershipGuide(); + receipt.membershipApply(inputView.readAnswer().trim()); + } + + public void showReceipt() { + outputView.printReceipt(receipt); + } + + public void close() { + outputView.closingGuide(); + if (inputView.readAnswer().equals("N")) { + isOpen = false; + } + } +}
Java
์ถ”์ถœํ•˜๊ธฐ๋ณด๋‹ค ๊ทธ๋Œ€๋กœ ์“ฐ๋Š” ๊ฒŒ ๊ฐ€๋…์„ฑ ์ธก๋ฉด์œผ๋กœ ๋” ๊ดœ์ฐฎ์•„๋ณด์ด๋Š”๋ฐ, ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,61 @@ +package store.product; + +import store.file.FileReader; +import store.io.OutputView; +import store.object.Amount; +import store.type.ErrorMessage; + +import java.util.List; +import java.util.Map; + +public class ProductManager { + private final List<Product> products; + + public ProductManager() { + FileReader fileReader = new FileReader(); + products = fileReader.createProduct(); + } + + public Amount purchase(String name, int amount) { + List<Product> purchaseProducts = products.stream() + .filter(product -> product.isCorrect(name)) + .toList(); + + isExceed(purchaseProducts, amount); + return applyPromotion(purchaseProducts, amount); + } + + public Amount applyPromotion(List<Product> purchaseProducts, int amount) { + Amount purchaseAmount = purchaseProducts.getFirst().buy(amount); + if (purchaseAmount.isAdditional()) { + Amount additionalAmount = purchaseProducts.getLast().buy(purchaseAmount.getAdditional()); + purchaseAmount.addBuyAmount(additionalAmount.getBuy()); + } + return purchaseAmount; + } + + public void print() { + OutputView outputView = new OutputView(); + outputView.printProducts(products); + } + + public void isExceed(List<Product> purchaseProducts, int amount) { + int totalQuantity = 0; + for (Product product : purchaseProducts) { + totalQuantity += product.getQuantity(); + } + if (totalQuantity < amount) { + throw new IllegalArgumentException(ErrorMessage.EXCEED_QUANTITY.getMessage()); + } + } + + public void validate(Map<String, Integer> purchaseData) { + for (String productName : purchaseData.keySet()) { + boolean exists = products.stream() + .anyMatch(product -> product.isExist(productName)); + if (!exists) { + throw new IllegalArgumentException(ErrorMessage.NON_EXISTING_PRODUCT.getMessage()); + } + } + } +}
Java
```suggestion products.stream() .findAny(product -> product.isExist(productName)) .orElseThrow(() -> new IllegalArgumentException()); ``` ์ด ํ˜•ํƒœ๋กœ ๋” ๊ฐ„๋‹จํ•˜๊ฒŒ ๋งŒ๋“œ๋Š” ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•ด๋„ ๊ดœ์ฐฎ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,18 @@ +package store.promotion; + +import java.util.List; + +public class PromotionManager { + private final List<Promotion> promotions; + + public PromotionManager(List<Promotion> promotions) { + this.promotions = promotions; + } + + public Promotion match(String promotion) { + return promotions.stream() + .filter(p -> p.isMatch(promotion)) + .findFirst() + .orElse(null); + } +}
Java
๊ตณ์ด null๋กœ ๋ฆฌํ„ดํ•˜์‹œ๋Š” ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”? ํด๋ผ์ด์–ธํŠธ๊ฐ€ null์— ๋Œ€ํ•œ ๋Œ€๋น„๊ฐ€ ์•ˆ๋˜์–ด์žˆ๋‹ค๋ฉด NPE๊ฐ€ ๋ฐœ์ƒํ• ํ…๋ฐ, ์—ฌ๊ธฐ์„œ ๋ฐ”๋กœ ์˜ˆ์™ธ๋ฅผ ๋˜์ง€๋Š” ๊ฒƒ์€ ์–ด๋– ์‹ ๊ฐ€์š”?
@@ -0,0 +1,19 @@ +package store.type; + +public enum PromotionType { + NAME(0), + GET(1), + BUY(2), + START_DATE(3), + END_DATE(4); + + private final int value; + + PromotionType(int value) { + this.value = value; + } + + public int getValue() { + return value; + } +}
Java
์ด๊ฑธ ๊ตณ์ด enum์œผ๋กœ ๋งŒ๋“œ์‹  ์˜๋„๊ฐ€ ์žˆ๋‚˜์š”? ๋”ฑํžˆ enumericํ•ด๋ณด์ด์ง€ ์•Š์Šต๋‹ˆ๋‹ค..
@@ -1,7 +1,11 @@ package store; +import store.object.ConvenienceStore; + public class Application { public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + ConvenienceStore convenienceStore = new ConvenienceStore(); + convenienceStore.open(); + System.out.println(); } -} +} \ No newline at end of file
Java
์ด ๋ถ€๋ถ„์€ ์™œ ์žˆ๋Š”๊ฑด์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,24 @@ +package store.file; + +import store.product.Product; +import store.promotion.Promotion; +import store.promotion.PromotionManager; + +import java.io.InputStream; +import java.util.List; + +public class FileReader { + public List<Product> createProduct() { + ProductParser productParser = new ProductParser(new PromotionManager(createPromotion())); + return productParser.read(road("products")); + } + + public List<Promotion> createPromotion() { + PromotionParser promotionParser = new PromotionParser(); + return promotionParser.read(road("promotions")); + } + + public InputStream road(String filename) { + return getClass().getClassLoader().getResourceAsStream(filename + ".md"); + } +}
Java
ํŒŒ์ผ๋ช…์„ ์ƒ์ˆ˜๋กœ ๋”ฐ๋กœ ์ €์žฅํ•ด๋‘๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,24 @@ +package store.file; + +import store.product.Product; +import store.promotion.Promotion; +import store.promotion.PromotionManager; + +import java.io.InputStream; +import java.util.List; + +public class FileReader { + public List<Product> createProduct() { + ProductParser productParser = new ProductParser(new PromotionManager(createPromotion())); + return productParser.read(road("products")); + } + + public List<Promotion> createPromotion() { + PromotionParser promotionParser = new PromotionParser(); + return promotionParser.read(road("promotions")); + } + + public InputStream road(String filename) { + return getClass().getClassLoader().getResourceAsStream(filename + ".md"); + } +}
Java
์ฐพ์•„๋ณด๋‹ˆ ํŒŒ์ผ์„ ์ฝ์–ด์˜ค๋Š” ๋ฐฉ๋ฒ•์ด๋”๋ผ๊ณ ์š”. ์ฒ˜์Œ๋ด์„œ ์‹ ๊ธฐํ–ˆ์–ด์š”
@@ -0,0 +1,43 @@ +package store.file; + +import store.product.Product; +import store.promotion.Promotion; +import store.promotion.PromotionManager; +import store.type.ProductType; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +public class ProductParser { + private final PromotionManager promotionManager; + + public ProductParser(PromotionManager promotionManager) { + this.promotionManager = promotionManager; + } + + public List<Product> read(InputStream productsInputStream) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(productsInputStream))) { + return reader.lines() + .skip(1) + .map(this::parse) + .collect(Collectors.toList()); + } catch (IOException e) { + return Collections.emptyList(); + } + } + + public Product parse(String product) { + String[] productParts = product.split(","); + String name = productParts[ProductType.NAME.getValue()]; + int price = Integer.parseInt(productParts[ProductType.PRICE.getValue()]); + int quantity = Integer.parseInt(productParts[ProductType.QUANTITY.getValue()]); + Promotion promotion = promotionManager.match(productParts[ProductType.PROMOTION.getValue()]); + + return new Product(name, price, quantity, promotion); + } +}
Java
readLine์„ ์‚ฌ์šฉํ•ด ์ฝ์„๋•Œ๋ณด๋‹ค stream์„ ํ™œ์šฉํ•˜๋ฉด skip(1)์„ ํ†ตํ•ด ๋” ๊น”๋”ํ•œ ์ฝ”๋“œ๊ฐ€ ๋˜๋Š”๊ฒŒ ์ •๋ง ์ข‹์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. skip(1)์—์„œ 1์„ titleLine๊ณผ ๊ฐ™์€ ์ƒ์ˆ˜๋กœ ์ฒ˜๋ฆฌํ•ด๋ฒ„๋ฆฐ๋‹ค๋ฉด ๊ฐ€๋…์„ฑ์ด ๋”์šฑ ์ข‹์•„์งˆ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,43 @@ +package store.file; + +import store.product.Product; +import store.promotion.Promotion; +import store.promotion.PromotionManager; +import store.type.ProductType; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +public class ProductParser { + private final PromotionManager promotionManager; + + public ProductParser(PromotionManager promotionManager) { + this.promotionManager = promotionManager; + } + + public List<Product> read(InputStream productsInputStream) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(productsInputStream))) { + return reader.lines() + .skip(1) + .map(this::parse) + .collect(Collectors.toList()); + } catch (IOException e) { + return Collections.emptyList(); + } + } + + public Product parse(String product) { + String[] productParts = product.split(","); + String name = productParts[ProductType.NAME.getValue()]; + int price = Integer.parseInt(productParts[ProductType.PRICE.getValue()]); + int quantity = Integer.parseInt(productParts[ProductType.QUANTITY.getValue()]); + Promotion promotion = promotionManager.match(productParts[ProductType.PROMOTION.getValue()]); + + return new Product(name, price, quantity, promotion); + } +}
Java
getValue๋ณด๋‹ค getIdx์™€ ๊ฐ™์€ ๋ฉ”์„œ๋“œ๋กœ ๋งŒ๋“ค์–ด์ง„๋‹ค๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,43 @@ +package store.file; + +import store.product.Product; +import store.promotion.Promotion; +import store.promotion.PromotionManager; +import store.type.ProductType; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +public class ProductParser { + private final PromotionManager promotionManager; + + public ProductParser(PromotionManager promotionManager) { + this.promotionManager = promotionManager; + } + + public List<Product> read(InputStream productsInputStream) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(productsInputStream))) { + return reader.lines() + .skip(1) + .map(this::parse) + .collect(Collectors.toList()); + } catch (IOException e) { + return Collections.emptyList(); + } + } + + public Product parse(String product) { + String[] productParts = product.split(","); + String name = productParts[ProductType.NAME.getValue()]; + int price = Integer.parseInt(productParts[ProductType.PRICE.getValue()]); + int quantity = Integer.parseInt(productParts[ProductType.QUANTITY.getValue()]); + Promotion promotion = promotionManager.match(productParts[ProductType.PROMOTION.getValue()]); + + return new Product(name, price, quantity, promotion); + } +}
Java
์ด๊ฒƒ๋„ ์ƒ์ˆ˜๋กœ ๋งŒ๋“ ๋‹ค๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,47 @@ +package store.file; + +import store.promotion.Promotion; +import store.type.PromotionType; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +public class PromotionParser { + public List<Promotion> read(InputStream productsInputStream) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(productsInputStream))) { + return reader.lines() + .skip(1) + .map(this::parse) + .collect(Collectors.toList()); + } catch (IOException e) { + return Collections.emptyList(); + } + } + + public Promotion parse(String promotion) { + String[] promotionParts = promotion.split(","); + String name = promotionParts[PromotionType.NAME.getValue()]; + int get = Integer.parseInt(promotionParts[PromotionType.GET.getValue()]); + int buy = Integer.parseInt(promotionParts[PromotionType.BUY.getValue()]); + LocalDate startDate = formatDate(promotionParts[PromotionType.START_DATE.getValue()]); + LocalDate endDate = formatDate(promotionParts[PromotionType.END_DATE.getValue()]); + + return new Promotion(name, get, buy, startDate, endDate); + } + + public LocalDate formatDate(String date) { + try { + DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + return LocalDate.parse(date, dateFormat); + } catch (Exception e) { + return null; + } + } +}
Java
์˜ˆ์™ธ์ฒ˜๋ฆฌ๋กœ ๋‹จ์ˆœํžˆ ๋ฉ”์„ธ์ง€๋ฅผ ๋ณด์—ฌ์ฃผ๊ณ  ์ข…๋ฃŒํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ ๋นˆ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ค์–ด ๋„˜๊ธฐ๋Š” ๋ถ€๋ถ„์—์„œ ์ข‹์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ํŒŒ์ผ์ด ๋น„์–ด์„œ ๋นˆ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋‚˜ํƒ€๋‚ธ ๊ฒƒ์ธ์ง€ ํŒŒ์ผ์„ ์ฝ๋‹ค๊ฐ€ ์˜ค๋ฅ˜๊ฐ€ ๋‚˜์„œ ๋นˆ ๋ฆฌ์ŠคํŠธ์ธ์ง€์— ๋Œ€ํ•œ ๊ตฌ๋ถ„์ด ํ•„์š”ํ•˜๋‹ค ์ƒ๊ฐํ•ด ์ถ”๊ฐ€์ ์ธ ๋ฉ”์„ธ์ง€๋ฅผ ๋„์šฐ๋Š” ๊ฒƒ์ด๋‚˜ ์ฐจ์ด์ ์„ ๋งŒ๋“ ๋‹ค๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,47 @@ +package store.file; + +import store.promotion.Promotion; +import store.type.PromotionType; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +public class PromotionParser { + public List<Promotion> read(InputStream productsInputStream) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(productsInputStream))) { + return reader.lines() + .skip(1) + .map(this::parse) + .collect(Collectors.toList()); + } catch (IOException e) { + return Collections.emptyList(); + } + } + + public Promotion parse(String promotion) { + String[] promotionParts = promotion.split(","); + String name = promotionParts[PromotionType.NAME.getValue()]; + int get = Integer.parseInt(promotionParts[PromotionType.GET.getValue()]); + int buy = Integer.parseInt(promotionParts[PromotionType.BUY.getValue()]); + LocalDate startDate = formatDate(promotionParts[PromotionType.START_DATE.getValue()]); + LocalDate endDate = formatDate(promotionParts[PromotionType.END_DATE.getValue()]); + + return new Promotion(name, get, buy, startDate, endDate); + } + + public LocalDate formatDate(String date) { + try { + DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + return LocalDate.parse(date, dateFormat); + } catch (Exception e) { + return null; + } + } +}
Java
๋‹จ์ˆœํžˆ null์„ ๋‚ด๋ณด๋‚ธ๋‹ค๋ฉด ์—๋Ÿฌ๋ฅผ ์žก์•„๋‚ด๊ธฐ ์–ด๋ ค์šธ ์ˆ˜ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค ์ถ”๊ฐ€์ ์ธ ์˜ˆ์™ธ์ฒ˜๋ฆฌ๊ฐ€ ํ•„์š”ํ•˜๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,45 @@ +package store.io; + +import camp.nextstep.edu.missionutils.Console; +import store.type.ErrorMessage; + +public class InputView { + private final OutputView outputView = new OutputView(); + + public String readAnswer() { + while (true) { + try { + String input = Console.readLine(); + answerValidate(input); + return input; + } catch (IllegalArgumentException e) { + outputView.printError(e.getMessage()); + } + } + } + + public String readPurchaseProduct() { + while (true) { + try { + String input = Console.readLine(); + purchaseProductValidate(input); + return input; + } catch (IllegalArgumentException e) { + outputView.printError(e.getMessage()); + } + } + } + + public void answerValidate(String input) { + if (!"Y".equals(input) && !"N".equals(input)) { + throw new IllegalArgumentException(ErrorMessage.INVALID_INPUT.getMessage()); + } + } + + public void purchaseProductValidate(String input) { + String regex = "\\[([a-zA-Z๊ฐ€-ํžฃ]+-[1-9][0-9]*)\\](,\\[([a-zA-Z๊ฐ€-ํžฃ]+-[1-9][0-9]*)\\])*"; + if (!input.matches(regex)) { + throw new IllegalArgumentException(ErrorMessage.INVALID_FORMAT.getMessage()); + } + } +}
Java
๋ฉ”์„œ๋“œ์—์„œ ๋งค๋ฒˆ ์ƒ์„ฑ๋˜๋Š” ๊ฒƒ๋ณด๋‹ค๋Š” ์ƒ์ˆ˜๋กœ ์˜ฌ๋ ค๋‘๋Š” ๊ฒƒ์€ ์–ด๋–ค๊ฐ€์š”? ํ•„๋“œ์— ๋ชจ์—ฌ์žˆ์œผ๋ฉด ์ฐพ๊ธฐ๋„ ํŽธํ•ด์„œ ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,45 @@ +package store.io; + +import camp.nextstep.edu.missionutils.Console; +import store.type.ErrorMessage; + +public class InputView { + private final OutputView outputView = new OutputView(); + + public String readAnswer() { + while (true) { + try { + String input = Console.readLine(); + answerValidate(input); + return input; + } catch (IllegalArgumentException e) { + outputView.printError(e.getMessage()); + } + } + } + + public String readPurchaseProduct() { + while (true) { + try { + String input = Console.readLine(); + purchaseProductValidate(input); + return input; + } catch (IllegalArgumentException e) { + outputView.printError(e.getMessage()); + } + } + } + + public void answerValidate(String input) { + if (!"Y".equals(input) && !"N".equals(input)) { + throw new IllegalArgumentException(ErrorMessage.INVALID_INPUT.getMessage()); + } + } + + public void purchaseProductValidate(String input) { + String regex = "\\[([a-zA-Z๊ฐ€-ํžฃ]+-[1-9][0-9]*)\\](,\\[([a-zA-Z๊ฐ€-ํžฃ]+-[1-9][0-9]*)\\])*"; + if (!input.matches(regex)) { + throw new IllegalArgumentException(ErrorMessage.INVALID_FORMAT.getMessage()); + } + } +}
Java
Y์™€ N์„ ์ƒ์ˆ˜๋กœ ์˜ฌ๋ฆฌ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์š”๊ตฌ์‚ฌํ•ญ์— ์ƒ์ˆ˜ํ™”๊ฐ€ ์žˆ์–ด์„œ ์ฐธ๊ณ ํ•˜์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,52 @@ +package store.io; + +import store.object.Receipt; +import store.product.Product; + +import java.util.List; + +public class OutputView { + public void greeting() { + System.out.println("์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค."); + System.out.println("ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค.\n"); + } + + public void printProducts(List<Product> products) { + products.forEach(System.out::println); + } + + public void purchaseGuide() { + System.out.println("\n๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"); + } + + public void promotionAdditionalGuide(String productName) { + System.out.printf("\nํ˜„์žฌ %s์€(๋Š”) 1๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)\n", productName); + } + + public void promotionImpossibleGuide(String productName, int amount) { + System.out.printf("\nํ˜„์žฌ %s %d๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)\n", productName, amount); + } + + public void membershipGuide() { + System.out.println("\n๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๋‹ค? (Y/N)"); + } + + public void printReceipt(Receipt receipt) { + System.out.println("\n==============W ํŽธ์˜์ ================"); + String productReportFormat = "%-19s%-10s%-6s"; + System.out.printf((productReportFormat) + "%n", "์ƒํ’ˆ๋ช…", "์ˆ˜๋Ÿ‰", "๊ธˆ์•ก"); + System.out.printf(receipt.productReport()); + System.out.println("==============์ฆ ์ •================"); + System.out.printf(receipt.promotionReport()); + System.out.println("======================================"); + System.out.printf(receipt.paymentReport()); + } + + public void closingGuide() { + System.out.println("\n๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"); + } + + public void printError(String errorMessage) { + System.out.println("\n" + errorMessage); + } +}
Java
toString์„ ํ™œ์šฉํ•œ ๊น”๋”ํ•œ ์ฒ˜๋ฆฌ๊ฐ€ ์ข‹์€ ๊ฒƒ ๊ฐ™์•„์š”. ํ•œ๊ฐ€์ง€ ์•„์‰ฝ๋‹ค๋ฉด StringBuilder์™€ ๊ฐ™์€ ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•ด ์ถœ๋ ฅํ•  ๋ฉ”์„ธ์ง€๋“ค์„ ๋ชจ์•„์„œ ํ•œ๋ฒˆ์— ์ถœ๋ ฅํ•˜๋Š”๋ฐ IO์ž‘์—…์ด ์ค„์–ด๋“ค์–ด ๋”์šฑ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,82 @@ +package store.object; + +import store.io.InputParser; +import store.io.InputView; +import store.io.OutputView; +import store.product.ProductManager; + +import java.util.Map; + +public class ConvenienceStore { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + private final InputParser inputParser = new InputParser(); + private final ProductManager productManager = new ProductManager(); + private Receipt receipt; + private boolean isOpen = true; + + public void open() { + while (isOpen) { + init(); + announcement(); + purchase(); + close(); + System.out.println(); + } + } + + public void init() { + receipt = new Receipt(); + } + + public void announcement() { + outputView.greeting(); + productManager.print(); + } + + public void purchase() { + outputView.purchaseGuide(); + while (true) { + try { + inputHandle(); + return; + } catch (IllegalArgumentException e) { + outputView.printError(e.getMessage()); + } + } + } + + public void inputHandle() { + String purchaseProducts = inputView.readPurchaseProduct(); + Map<String, Integer> purchaseData = inputParser.mapping(purchaseProducts); + productManager.validate(purchaseData); + createReceipt(purchaseData); + } + + public void createReceipt(Map<String, Integer> purchaseData) { + purchaseData.forEach((name, amount) -> { + Amount purchaseAmount = productManager.purchase(name, amount); + receipt.addAmount(purchaseAmount); + }); + if (receipt.isExistence()) { + membership(); + showReceipt(); + } + } + + public void membership() { + outputView.membershipGuide(); + receipt.membershipApply(inputView.readAnswer().trim()); + } + + public void showReceipt() { + outputView.printReceipt(receipt); + } + + public void close() { + outputView.closingGuide(); + if (inputView.readAnswer().equals("N")) { + isOpen = false; + } + } +}
Java
์–˜๋„ ์ถœ๋ ฅ์„ ๋‹ด๋‹นํ•˜๋Š” ๋ถ€๋ถ„์ด๋ผ OutputView์— ๋„ฃ์–ด ์‚ฌ์šฉํ•˜๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,82 @@ +package store.object; + +import store.io.InputParser; +import store.io.InputView; +import store.io.OutputView; +import store.product.ProductManager; + +import java.util.Map; + +public class ConvenienceStore { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + private final InputParser inputParser = new InputParser(); + private final ProductManager productManager = new ProductManager(); + private Receipt receipt; + private boolean isOpen = true; + + public void open() { + while (isOpen) { + init(); + announcement(); + purchase(); + close(); + System.out.println(); + } + } + + public void init() { + receipt = new Receipt(); + } + + public void announcement() { + outputView.greeting(); + productManager.print(); + } + + public void purchase() { + outputView.purchaseGuide(); + while (true) { + try { + inputHandle(); + return; + } catch (IllegalArgumentException e) { + outputView.printError(e.getMessage()); + } + } + } + + public void inputHandle() { + String purchaseProducts = inputView.readPurchaseProduct(); + Map<String, Integer> purchaseData = inputParser.mapping(purchaseProducts); + productManager.validate(purchaseData); + createReceipt(purchaseData); + } + + public void createReceipt(Map<String, Integer> purchaseData) { + purchaseData.forEach((name, amount) -> { + Amount purchaseAmount = productManager.purchase(name, amount); + receipt.addAmount(purchaseAmount); + }); + if (receipt.isExistence()) { + membership(); + showReceipt(); + } + } + + public void membership() { + outputView.membershipGuide(); + receipt.membershipApply(inputView.readAnswer().trim()); + } + + public void showReceipt() { + outputView.printReceipt(receipt); + } + + public void close() { + outputView.closingGuide(); + if (inputView.readAnswer().equals("N")) { + isOpen = false; + } + } +}
Java
์ž…๋ ฅ ํŒŒ๋ผ๋ฏธํ„ฐ์— ๋„ฃ์ง€ ์•Š๊ธฐ์œ„ํ•ด ํ•„๋“œ์— ๋„ฃ์œผ์‹  ๋А๋‚Œ์ธ๋ฐ ์ง€์—ญ ๋ณ€์ˆ˜๋กœ ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,82 @@ +package store.object; + +import store.io.InputParser; +import store.io.InputView; +import store.io.OutputView; +import store.product.ProductManager; + +import java.util.Map; + +public class ConvenienceStore { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + private final InputParser inputParser = new InputParser(); + private final ProductManager productManager = new ProductManager(); + private Receipt receipt; + private boolean isOpen = true; + + public void open() { + while (isOpen) { + init(); + announcement(); + purchase(); + close(); + System.out.println(); + } + } + + public void init() { + receipt = new Receipt(); + } + + public void announcement() { + outputView.greeting(); + productManager.print(); + } + + public void purchase() { + outputView.purchaseGuide(); + while (true) { + try { + inputHandle(); + return; + } catch (IllegalArgumentException e) { + outputView.printError(e.getMessage()); + } + } + } + + public void inputHandle() { + String purchaseProducts = inputView.readPurchaseProduct(); + Map<String, Integer> purchaseData = inputParser.mapping(purchaseProducts); + productManager.validate(purchaseData); + createReceipt(purchaseData); + } + + public void createReceipt(Map<String, Integer> purchaseData) { + purchaseData.forEach((name, amount) -> { + Amount purchaseAmount = productManager.purchase(name, amount); + receipt.addAmount(purchaseAmount); + }); + if (receipt.isExistence()) { + membership(); + showReceipt(); + } + } + + public void membership() { + outputView.membershipGuide(); + receipt.membershipApply(inputView.readAnswer().trim()); + } + + public void showReceipt() { + outputView.printReceipt(receipt); + } + + public void close() { + outputView.closingGuide(); + if (inputView.readAnswer().equals("N")) { + isOpen = false; + } + } +}
Java
์–˜๋ฅผ boolean์„ ๋ฐ˜ํ™˜ํ•˜๊ฒŒ ํ•ด์„œ ์ฒ˜๋ฆฌํ–ˆ๋‹ค๋ฉด isOpen์€ ํ•„๋“œ๋กœ ์•ˆ๋‚˜๊ฐ€๋„ ๋˜์ง€ ์•Š์•˜์„๊นŒ์š”?
@@ -0,0 +1,69 @@ +package store.product; + +import camp.nextstep.edu.missionutils.DateTimes; +import store.object.Amount; +import store.promotion.Promotion; +import store.type.ErrorMessage; + +import java.util.Optional; + +public class Product { + private final String name; + private final int price; + private int quantity; + private final Promotion promotion; + + public Product(String name, int price, int quantity, Promotion promotion) { + this.name = name; + this.price = price; + this.quantity = quantity; + this.promotion = promotion; + } + + public int getQuantity() { + return quantity; + } + + public Amount buy(int amount) { + if (promotion != null) { + return promotionBuy(amount); + } + isExceed(amount); + quantity -= amount; + return new Amount(name, price, amount, 0, 0, amount); + } + + public Amount promotionBuy(int amount) { + if (promotion.isPossible(DateTimes.now())) { + Amount purchaseAmount = promotion.apply(name, price, quantity, amount); + quantity -= purchaseAmount.getBuy(); + return purchaseAmount; + } + return new Amount(name, price, 0, 0, amount, 0); + } + + public boolean isCorrect(String name) { + return name.equals(this.name); + } + + public void isExceed(int amount) { + if (amount > quantity) { + throw new IllegalArgumentException(ErrorMessage.EXCEED_QUANTITY.getMessage()); + } + } + + public boolean isExist(String otherName) { + return this.name.equals(otherName); + } + + @Override + public String toString() { + String promotionName = Optional.ofNullable(promotion) + .map(Promotion::toString) + .orElse(""); + if (quantity == 0) { + return String.format("- %s %,d์› ์žฌ๊ณ  ์—†์Œ %s", name, price, promotionName).trim(); + } + return String.format("- %s %,d์› %d๊ฐœ %s", name, price, quantity, promotionName).trim(); + } +}
Java
์ฝ”๋“œ์— ์ž…๋ ฅ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ 0๊ณผ ๊ฐ™์€ ํŠน์ •ํ•œ ๊ฐ’์ด ๋“ค์–ด๊ฐ€๋Š” ๊ฒฝ์šฐ ๊ฐ€๋…์„ฑ์„ ๋งค์šฐ ํ•ด์นœ๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ์ด๋ณด๋‹ค๋Š” Amount์˜ ์ƒ์„ฑ์ž๋ฅผ 0, 0์„ ๋„ฃ์ง€ ์•Š์œผ๋ฉด ์ž๋™์œผ๋กœ 0์ด ๋“ค์–ด๊ฐ€๋„๋ก ์ž‘์„ฑํ•ด๋ณด๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,81 @@ +package store.promotion; + +import store.io.InputView; +import store.io.OutputView; +import store.object.Amount; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +public class Promotion { + private final InputView inputView = new InputView(); + private final OutputView outputView = new OutputView(); + private final String name; + private final int buy; + private final int get; + private final LocalDate startDate; + private final LocalDate endDate; + + public Promotion(String name, int buy, int get, LocalDate startDate, LocalDate endDate) { + this.name = name; + this.buy = buy; + this.get = get; + this.startDate = startDate; + this.endDate = endDate; + } + + public Amount apply(String productName, int price, int quantity, int amount) { + int total = buy + get; + int maxAmount = quantity / total * total; + if (amount <= maxAmount && amount % total == 0) { + return new Amount(productName, price, amount, amount / total, 0, 0); + } + if (amount % total == buy && amount < maxAmount) { + return additionalGet(productName, price, quantity, amount, total); + } + return additionalBuy(productName, price, quantity, amount, total, maxAmount); + } + + public Amount additionalGet(String productName, int price, int quantity, int amount, int total) { + outputView.promotionAdditionalGuide(productName); + if (inputView.readAnswer().equals("Y")) { + return new Amount(productName, price, amount + 1, (amount + 1) / total, 0, 0); + } + return new Amount(productName, price, amount, amount / total, 0, 0); + } + + public Amount additionalBuy(String productName, int price, int quantity, int amount, int total, int maxAmount) { + int impossibleAmount = calcImpossibleAmount(amount, total, maxAmount); + outputView.promotionImpossibleGuide(productName, impossibleAmount); + if (inputView.readAnswer().trim().equals("Y")) { + if (quantity - (amount - impossibleAmount) < impossibleAmount) { + return new Amount(productName, price, quantity, (amount - impossibleAmount) / total, amount - quantity, impossibleAmount); + } + return new Amount(productName, price, amount, (amount - impossibleAmount) / total, 0, impossibleAmount); + } + return new Amount(productName, price, amount - impossibleAmount, (amount - impossibleAmount) / total, 0, 0); + } + + public int calcImpossibleAmount(int amount, int total, int maxAmount) { + int impossibleAmount = amount % total; + if (amount > maxAmount) { + impossibleAmount = amount - maxAmount; + } + return impossibleAmount; + } + + public boolean isPossible(LocalDateTime now) { + LocalDate nowDate = now.toLocalDate(); + return (startDate.isBefore(nowDate) || startDate.isEqual(nowDate)) && + (endDate.isAfter(nowDate) || endDate.isEqual(nowDate)); + } + + public boolean isMatch(String promotion) { + return promotion.equals(name); + } + + @Override + public String toString() { + return this.name; + } +}
Java
```suggestion return !startDate.isAfter(nowDate) && !endDate.isBefore(nowDate); ``` ์ด๋ ‡๊ฒŒ ๋ฐ”๊พธ๋ฉด ๋” ๊น”๋”ํ•˜๊ฒŒ ์ฝ”๋“œ๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,19 @@ +package store.type; + +public enum PromotionType { + NAME(0), + GET(1), + BUY(2), + START_DATE(3), + END_DATE(4); + + private final int value; + + PromotionType(int value) { + this.value = value; + } + + public int getValue() { + return value; + } +}
Java
์ €๋„ ์ด ๋ถ€๋ถ„์€ ๊ทธ๋ƒฅ ํ•„๋“œ๋กœ ์ž‘์„ฑํ•˜์…จ์–ด๋„ ๊ดœ์ฐฎ๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,77 @@ +package store.view.utils; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import store.common.constants.StringConstants; + +public class InputParser { + public static String inventoryParser(String name, Long price, Long quantity, String promotion) { + StringBuilder stringBuilderWithDash = new StringBuilder(giveBlankToEnd(StringConstants.DASH)); + + return appendAll( + stringBuilderWithDash, + giveBlankToEnd(name), + giveBlankToEnd(parsePrice(price)), + giveBlankToEnd(parseQuantity(quantity)), + parsePromotion(promotion) + ).toString(); + } + + public static Map<String, Long> purchaseInputParser(String[] inputArray) { + Map<String, Long> purchaseDetail = new HashMap<>(); + Arrays.stream(inputArray).forEach(input -> { + String bracketsRemoved = input.replace("[", "").replace("]", ""); + String[] inputSplit = bracketsRemoved.split(StringConstants.DASH); + purchaseDetail.put(inputSplit[0], Long.parseLong(inputSplit[1])); + }); + return purchaseDetail; + } + + public static StringBuilder giveCommaToPrice(String[] splitPrice) { + StringBuilder priceWithComma = new StringBuilder(); + for (int i = splitPrice.length - 1 ; i >= 0; i--) { + priceWithComma.insert(0, splitPrice[i]); + if ((splitPrice.length - i) % 3 == 0 && i != 0) { + priceWithComma.insert(0, StringConstants.COMMA); + } + } + return priceWithComma; + } + + private static String giveBlankToEnd(String name) { + return name + StringConstants.BLANK; + } + + private static String parsePromotion(String promotion) { + String promotionNullConverted = promotion; + if (Objects.equals(promotion, "null")) { + promotionNullConverted = ""; + } + return promotionNullConverted; + } + + private static String parseQuantity(Long quantity) { + String quantityWithPieces = quantity.toString() + StringConstants.PIECES; + if (quantity == 0) { + quantityWithPieces = StringConstants.OUT_OF_STOCK; + } + return quantityWithPieces; + } + + private static String parsePrice(Long price) { + if (price >= 1000) { + String[] splitPrice = price.toString().split(""); + return giveCommaToPrice(splitPrice).append(StringConstants.WON).toString(); + } + return price + StringConstants.WON; + } + + private static StringBuilder appendAll(StringBuilder stringbuilder, String... strings) { + for (String string : strings) { + stringbuilder.append(string); + } + return stringbuilder; + } +}
Java
`parsePrice` ๋ฉ”์„œ๋“œ๋Š” ์ˆซ์ž์— ์ฒœ ๋‹จ์œ„ ์ฝค๋งˆ๋ฅผ ์ถ”๊ฐ€ํ•˜๋Š” ๊ณผ์ •์„ ์ง„ํ–‰ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ž๋ฐ”์—์„œ ์ œ๊ณตํ•˜๋Š” `String.format` ์˜ `%,d` ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹์„ ๋“ฏ ํ•ฉ๋‹ˆ๋‹ค:)
@@ -0,0 +1,8 @@ +package store.common.constants; + +public class AddressConstants { + public static final String productFilePath = + "/Users/hanwool/WooTeco/java-convenience-store-7-hanwool1643/src/main/resources/products.md"; + public static final String promotionFilePath = + "/Users/hanwool/WooTeco/java-convenience-store-7-hanwool1643/src/main/resources/promotions.md"; +}
Java
์ด ๋ถ€๋ถ„์ด ํŒŒ์ผ์œ„์น˜์— ๋”ฐ๋ผ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜๋„ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”! ์ ˆ๋Œ€ ๊ฒฝ๋กœ๊ฐ€ ์•„๋‹Œ ์ƒ๋Œ€ ๊ฒฝ๋กœ๋กœ ๋ณ€๊ฒฝํ•˜๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,63 @@ +package store.view; + +import camp.nextstep.edu.missionutils.Console; +import java.util.Map; +import store.common.constants.ErrorConstants; +import store.common.constants.MessageConstants; +import store.common.constants.StringConstants; +import store.view.utils.InputParser; +import store.view.utils.InputValidation; + +public class InputView { + + public static Map<String, Long> askPurchaseProduct() { + System.out.println(MessageConstants.PRODUCT_PURCHASE_MESSAGE); + while (true) { + try { + String input = Console.readLine(); + String[] inputSplit = InputValidation.validatePurchaseInput(input); + System.out.println(); + return InputParser.purchaseInputParser(inputSplit); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + public static String tellPromotionNotApplicable(String name, Long quantity) { + System.out.printf(MessageConstants.PROMOTION_NOT_APPLY_MESSAGE, name, quantity); + System.out.println(); + return getYesOrNoAnswer(); + } + + private static String getYesOrNoAnswer() { + while(true) { + try { + String answer = Console.readLine(); + System.out.println(); + if (!(answer.equals(StringConstants.NO) || answer.equals(StringConstants.YES))) { + throw new IllegalArgumentException(ErrorConstants.INPUT_FORMAT_ERROR_MESSAGE); + } + return answer; + } catch(IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + public static String tellFreeProductProvide(String name, Long quantity) { + System.out.printf(MessageConstants.PROMOTION_PROVIDE_FREE_PRODUCT_MESSAGE, name, quantity); + System.out.println(); + return getYesOrNoAnswer(); + } + + public static String askMembershipDiscount() { + System.out.println(MessageConstants.MEMBERSHIP_DISCOUNT_MESSAGE); + return getYesOrNoAnswer(); + } + + public static String buyAnotherProduct() { + System.out.println(MessageConstants.EXIT_MESSAGE); + return getYesOrNoAnswer(); + } +}
Java
validation ๋กœ์ง๊ณผ parser ๋กœ์ง์„ InputView์—์„œ ์‹คํ–‰ํ•˜๋Š” ๊ฒƒ์€ InputView์— ๋„ˆ๋ฌด ๋งŽ์€ ์ฑ…์ž„์„ ๋ถ€๊ณผํ•˜๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! InputView์—์„œ๋Š” ์•ˆ๋‚ด ๋ฉ”์‹œ์ง€ ์ถœ๋ ฅ๊ณผ ์ž…๋ ฅ์„ ๋ฐ›๋Š” ๋ถ€๋ถ„๋งŒ ๋‚จ๊ฒจ๋‘๊ณ , ๋‚˜๋จธ์ง€ ๋ถ€๋ถ„์„ controller์— ์ž‘์„ฑํ•˜์‹œ๋Š” ๊ฒƒ์€ ์–ด๋– ์‹ค๊นŒ์š”?
@@ -0,0 +1,63 @@ +package store.view; + +import camp.nextstep.edu.missionutils.Console; +import java.util.Map; +import store.common.constants.ErrorConstants; +import store.common.constants.MessageConstants; +import store.common.constants.StringConstants; +import store.view.utils.InputParser; +import store.view.utils.InputValidation; + +public class InputView { + + public static Map<String, Long> askPurchaseProduct() { + System.out.println(MessageConstants.PRODUCT_PURCHASE_MESSAGE); + while (true) { + try { + String input = Console.readLine(); + String[] inputSplit = InputValidation.validatePurchaseInput(input); + System.out.println(); + return InputParser.purchaseInputParser(inputSplit); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + public static String tellPromotionNotApplicable(String name, Long quantity) { + System.out.printf(MessageConstants.PROMOTION_NOT_APPLY_MESSAGE, name, quantity); + System.out.println(); + return getYesOrNoAnswer(); + } + + private static String getYesOrNoAnswer() { + while(true) { + try { + String answer = Console.readLine(); + System.out.println(); + if (!(answer.equals(StringConstants.NO) || answer.equals(StringConstants.YES))) { + throw new IllegalArgumentException(ErrorConstants.INPUT_FORMAT_ERROR_MESSAGE); + } + return answer; + } catch(IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + public static String tellFreeProductProvide(String name, Long quantity) { + System.out.printf(MessageConstants.PROMOTION_PROVIDE_FREE_PRODUCT_MESSAGE, name, quantity); + System.out.println(); + return getYesOrNoAnswer(); + } + + public static String askMembershipDiscount() { + System.out.println(MessageConstants.MEMBERSHIP_DISCOUNT_MESSAGE); + return getYesOrNoAnswer(); + } + + public static String buyAnotherProduct() { + System.out.println(MessageConstants.EXIT_MESSAGE); + return getYesOrNoAnswer(); + } +}
Java
๊ทธ๋ฆฌ๊ณ  validation ๋กœ์ง์„ parser ๋กœ์ง์— ๋„ฃ์œผ์‹œ๋ฉด ์ข‹์„ ๋“ฏ ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,77 @@ +package store.view.utils; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import store.common.constants.StringConstants; + +public class InputParser { + public static String inventoryParser(String name, Long price, Long quantity, String promotion) { + StringBuilder stringBuilderWithDash = new StringBuilder(giveBlankToEnd(StringConstants.DASH)); + + return appendAll( + stringBuilderWithDash, + giveBlankToEnd(name), + giveBlankToEnd(parsePrice(price)), + giveBlankToEnd(parseQuantity(quantity)), + parsePromotion(promotion) + ).toString(); + } + + public static Map<String, Long> purchaseInputParser(String[] inputArray) { + Map<String, Long> purchaseDetail = new HashMap<>(); + Arrays.stream(inputArray).forEach(input -> { + String bracketsRemoved = input.replace("[", "").replace("]", ""); + String[] inputSplit = bracketsRemoved.split(StringConstants.DASH); + purchaseDetail.put(inputSplit[0], Long.parseLong(inputSplit[1])); + }); + return purchaseDetail; + } + + public static StringBuilder giveCommaToPrice(String[] splitPrice) { + StringBuilder priceWithComma = new StringBuilder(); + for (int i = splitPrice.length - 1 ; i >= 0; i--) { + priceWithComma.insert(0, splitPrice[i]); + if ((splitPrice.length - i) % 3 == 0 && i != 0) { + priceWithComma.insert(0, StringConstants.COMMA); + } + } + return priceWithComma; + } + + private static String giveBlankToEnd(String name) { + return name + StringConstants.BLANK; + } + + private static String parsePromotion(String promotion) { + String promotionNullConverted = promotion; + if (Objects.equals(promotion, "null")) { + promotionNullConverted = ""; + } + return promotionNullConverted; + } + + private static String parseQuantity(Long quantity) { + String quantityWithPieces = quantity.toString() + StringConstants.PIECES; + if (quantity == 0) { + quantityWithPieces = StringConstants.OUT_OF_STOCK; + } + return quantityWithPieces; + } + + private static String parsePrice(Long price) { + if (price >= 1000) { + String[] splitPrice = price.toString().split(""); + return giveCommaToPrice(splitPrice).append(StringConstants.WON).toString(); + } + return price + StringConstants.WON; + } + + private static StringBuilder appendAll(StringBuilder stringbuilder, String... strings) { + for (String string : strings) { + stringbuilder.append(string); + } + return stringbuilder; + } +}
Java
๋™์˜ํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,82 @@ +package store.controller; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Scanner; +import store.common.FileReader; +import store.common.constants.AddressConstants; +import store.common.constants.StringConstants; +import store.domain.Product; +import store.domain.Promotion; +import store.domain.Receipt; +import store.service.FileService; +import store.service.StoreService; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + private final FileService fileService; + private final StoreService storeService; + + public StoreController(FileService fileService, StoreService storeService) { + this.fileService = fileService; + this.storeService = storeService; + } + + public void run() { + List<Product> inventory = extractProducts(fileService); // ์ œํ’ˆ ์ถ”์ถœ + List<Promotion> promotions = extractPromotions(fileService); //ํ”„๋กœ๋ชจ์…˜ ์ถ”์ถœ + + while (true) { + String answerToContinue = processPurchase(inventory, storeService, promotions); + if (answerToContinue.equals(StringConstants.NO)) break; + } + } + + private static List<Promotion> extractPromotions(FileService fileServiceImpl) { + Scanner promotionFile = FileReader.readFile(AddressConstants.promotionFilePath); + return fileServiceImpl.extractPromotion(promotionFile); + } + + private static List<Product> extractProducts(FileService fileServiceImpl) { + Scanner productsFile = FileReader.readFile(AddressConstants.productFilePath); + return fileServiceImpl.extractProduct(productsFile); + } + + private static String processPurchase(List<Product> inventory, StoreService storeService, List<Promotion> promotions) { + OutputView.printWelcome(); // ํ™˜์˜ ์ธ์‚ฌ + OutputView.printInventoryDetail(inventory); // ์žฌ๊ณ  ํ™•์ธ + + List<Receipt> receipts = buyProducts(storeService, inventory, promotions); // ๊ตฌ๋งค + Long[] totalReceipts = storeService.calculateTotalReceipts(receipts); // totalReceipts[0]: ์ด๊ตฌ๋งค ๊ธˆ์•ก, totalReceipts[1]: ์ดํ• ์ธ ๊ธˆ์•ก + Long priceAfterPromotionDiscount = totalReceipts[0] - totalReceipts[1]; + Long membershipDiscount = calculateMembershipDiscount(storeService, priceAfterPromotionDiscount); // ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ ์šฉ + + OutputView.printFinalReceipt(receipts, totalReceipts[1], membershipDiscount); // ์˜์ˆ˜์ฆ ์ถœ๋ ฅ + + return InputView.buyAnotherProduct(); // ๋ฌผ๊ฑด ๋ฐ˜๋ณต ๊ตฌ๋งค ๋ฌธ์˜ + } + + private static Long calculateMembershipDiscount(StoreService storeService, Long priceAfterPromotionDiscount) { + String answerToApplyMembership = InputView.askMembershipDiscount(); + return storeService.calculateMembershipDiscount(priceAfterPromotionDiscount, answerToApplyMembership); + } + + private static List<Receipt> buyProducts(StoreService storeService, List<Product> inventory, + List<Promotion> promotions) { + List<Receipt> receipts = new ArrayList<>(); + while (receipts.isEmpty()) { + try { + Map<String, Long> productsToBuy = InputView.askPurchaseProduct(); + productsToBuy.forEach((name, quantity) -> { + Receipt receipt = storeService.buy(name, quantity, inventory, promotions); + receipts.add(receipt); + }); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + return receipts; + } +}
Java
Receipt์— ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ ์šฉ์„ ํฌํ•จ ์‹œํ‚ค๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,8 @@ +package store.common.constants; + +public class AddressConstants { + public static final String productFilePath = + "/Users/hanwool/WooTeco/java-convenience-store-7-hanwool1643/src/main/resources/products.md"; + public static final String promotionFilePath = + "/Users/hanwool/WooTeco/java-convenience-store-7-hanwool1643/src/main/resources/promotions.md"; +}
Java
๋™์˜ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,82 @@ +package store.controller; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Scanner; +import store.common.FileReader; +import store.common.constants.AddressConstants; +import store.common.constants.StringConstants; +import store.domain.Product; +import store.domain.Promotion; +import store.domain.Receipt; +import store.service.FileService; +import store.service.StoreService; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + private final FileService fileService; + private final StoreService storeService; + + public StoreController(FileService fileService, StoreService storeService) { + this.fileService = fileService; + this.storeService = storeService; + } + + public void run() { + List<Product> inventory = extractProducts(fileService); // ์ œํ’ˆ ์ถ”์ถœ + List<Promotion> promotions = extractPromotions(fileService); //ํ”„๋กœ๋ชจ์…˜ ์ถ”์ถœ + + while (true) { + String answerToContinue = processPurchase(inventory, storeService, promotions); + if (answerToContinue.equals(StringConstants.NO)) break; + } + } + + private static List<Promotion> extractPromotions(FileService fileServiceImpl) { + Scanner promotionFile = FileReader.readFile(AddressConstants.promotionFilePath); + return fileServiceImpl.extractPromotion(promotionFile); + } + + private static List<Product> extractProducts(FileService fileServiceImpl) { + Scanner productsFile = FileReader.readFile(AddressConstants.productFilePath); + return fileServiceImpl.extractProduct(productsFile); + } + + private static String processPurchase(List<Product> inventory, StoreService storeService, List<Promotion> promotions) { + OutputView.printWelcome(); // ํ™˜์˜ ์ธ์‚ฌ + OutputView.printInventoryDetail(inventory); // ์žฌ๊ณ  ํ™•์ธ + + List<Receipt> receipts = buyProducts(storeService, inventory, promotions); // ๊ตฌ๋งค + Long[] totalReceipts = storeService.calculateTotalReceipts(receipts); // totalReceipts[0]: ์ด๊ตฌ๋งค ๊ธˆ์•ก, totalReceipts[1]: ์ดํ• ์ธ ๊ธˆ์•ก + Long priceAfterPromotionDiscount = totalReceipts[0] - totalReceipts[1]; + Long membershipDiscount = calculateMembershipDiscount(storeService, priceAfterPromotionDiscount); // ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ ์šฉ + + OutputView.printFinalReceipt(receipts, totalReceipts[1], membershipDiscount); // ์˜์ˆ˜์ฆ ์ถœ๋ ฅ + + return InputView.buyAnotherProduct(); // ๋ฌผ๊ฑด ๋ฐ˜๋ณต ๊ตฌ๋งค ๋ฌธ์˜ + } + + private static Long calculateMembershipDiscount(StoreService storeService, Long priceAfterPromotionDiscount) { + String answerToApplyMembership = InputView.askMembershipDiscount(); + return storeService.calculateMembershipDiscount(priceAfterPromotionDiscount, answerToApplyMembership); + } + + private static List<Receipt> buyProducts(StoreService storeService, List<Product> inventory, + List<Promotion> promotions) { + List<Receipt> receipts = new ArrayList<>(); + while (receipts.isEmpty()) { + try { + Map<String, Long> productsToBuy = InputView.askPurchaseProduct(); + productsToBuy.forEach((name, quantity) -> { + Receipt receipt = storeService.buy(name, quantity, inventory, promotions); + receipts.add(receipt); + }); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + return receipts; + } +}
Java
์˜์ˆ˜์ฆ ์ œ์ž‘ ๊ด€๋ จ ๋ฉ”์„œ๋“œ๋ฅผ ๋”ฐ๋กœ ๋งŒ๋“ค๊ณ , ํ•ด๋‹น ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ์‹์œผ๋กœ ์ž‘์„ฑํ•˜์‹œ๋ฉด ์ข€ ๋” ๋ณด๊ธฐ ํŽธํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,82 @@ +package store.controller; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Scanner; +import store.common.FileReader; +import store.common.constants.AddressConstants; +import store.common.constants.StringConstants; +import store.domain.Product; +import store.domain.Promotion; +import store.domain.Receipt; +import store.service.FileService; +import store.service.StoreService; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + private final FileService fileService; + private final StoreService storeService; + + public StoreController(FileService fileService, StoreService storeService) { + this.fileService = fileService; + this.storeService = storeService; + } + + public void run() { + List<Product> inventory = extractProducts(fileService); // ์ œํ’ˆ ์ถ”์ถœ + List<Promotion> promotions = extractPromotions(fileService); //ํ”„๋กœ๋ชจ์…˜ ์ถ”์ถœ + + while (true) { + String answerToContinue = processPurchase(inventory, storeService, promotions); + if (answerToContinue.equals(StringConstants.NO)) break; + } + } + + private static List<Promotion> extractPromotions(FileService fileServiceImpl) { + Scanner promotionFile = FileReader.readFile(AddressConstants.promotionFilePath); + return fileServiceImpl.extractPromotion(promotionFile); + } + + private static List<Product> extractProducts(FileService fileServiceImpl) { + Scanner productsFile = FileReader.readFile(AddressConstants.productFilePath); + return fileServiceImpl.extractProduct(productsFile); + } + + private static String processPurchase(List<Product> inventory, StoreService storeService, List<Promotion> promotions) { + OutputView.printWelcome(); // ํ™˜์˜ ์ธ์‚ฌ + OutputView.printInventoryDetail(inventory); // ์žฌ๊ณ  ํ™•์ธ + + List<Receipt> receipts = buyProducts(storeService, inventory, promotions); // ๊ตฌ๋งค + Long[] totalReceipts = storeService.calculateTotalReceipts(receipts); // totalReceipts[0]: ์ด๊ตฌ๋งค ๊ธˆ์•ก, totalReceipts[1]: ์ดํ• ์ธ ๊ธˆ์•ก + Long priceAfterPromotionDiscount = totalReceipts[0] - totalReceipts[1]; + Long membershipDiscount = calculateMembershipDiscount(storeService, priceAfterPromotionDiscount); // ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ ์šฉ + + OutputView.printFinalReceipt(receipts, totalReceipts[1], membershipDiscount); // ์˜์ˆ˜์ฆ ์ถœ๋ ฅ + + return InputView.buyAnotherProduct(); // ๋ฌผ๊ฑด ๋ฐ˜๋ณต ๊ตฌ๋งค ๋ฌธ์˜ + } + + private static Long calculateMembershipDiscount(StoreService storeService, Long priceAfterPromotionDiscount) { + String answerToApplyMembership = InputView.askMembershipDiscount(); + return storeService.calculateMembershipDiscount(priceAfterPromotionDiscount, answerToApplyMembership); + } + + private static List<Receipt> buyProducts(StoreService storeService, List<Product> inventory, + List<Promotion> promotions) { + List<Receipt> receipts = new ArrayList<>(); + while (receipts.isEmpty()) { + try { + Map<String, Long> productsToBuy = InputView.askPurchaseProduct(); + productsToBuy.forEach((name, quantity) -> { + Receipt receipt = storeService.buy(name, quantity, inventory, promotions); + receipts.add(receipt); + }); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + return receipts; + } +}
Java
๋™์˜ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,50 @@ +package store.domain; + +import static store.common.constants.NumberConstants.PRODUCT_NAME_INDEX; +import static store.common.constants.NumberConstants.PRODUCT_PRICE_INDEX; +import static store.common.constants.NumberConstants.PRODUCT_PROMOTION_INDEX; +import static store.common.constants.NumberConstants.PRODUCT_QUANTITY_INDEX; + +import store.common.constants.ErrorConstants; + +public class Product { + private final String name; + private final Long price; + private Long quantity; + private final String promotion; + + public Product(String[] productsInfo) { + String name = productsInfo[PRODUCT_NAME_INDEX]; + long price = Long.parseLong(productsInfo[PRODUCT_PRICE_INDEX]); + long quantity = Long.parseLong(productsInfo[PRODUCT_QUANTITY_INDEX]); + String promotion = productsInfo[PRODUCT_PROMOTION_INDEX]; + + this.name = name; + this.price = price; + this.quantity = quantity; + this.promotion = promotion; + } + + public void buy(Long quantity) { + if (quantity > this.quantity) { + throw new IllegalArgumentException(ErrorConstants.INVENTORY_SHORT_ERROR_MESSAGE); + } + this.quantity -= quantity; + } + + public Long getPrice() { + return price; + } + + public Long getQuantity() { + return quantity; + } + + public String getPromotion() { + return promotion; + } + + public String getName() { + return name; + } +}
Java
์™œ ๋ฐฐ์—ด๋กœ ๋„˜๊ธฐ๋Š” ๋ฐฉ์‹์„ ํƒํ•˜์…จ๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค! DTO๋กœ ๋„˜๊ธฐ๋Š” ๊ฒฝ์šฐ๋‚˜ ์ œ๋„ค๋ฆญํƒ€์ž…์œผ๋กœ ๋„˜๊ธฐ๋Š” ๊ฒฝ์šฐ๋„ ์žˆ์„๊ฑฐ ๊ฐ™์•„์„œ์š”!
@@ -0,0 +1,217 @@ +package store.service; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Stream; +import store.common.constants.ErrorConstants; +import store.common.constants.NumberConstants; +import store.common.constants.StringConstants; +import store.domain.Product; +import store.domain.Promotion; +import store.domain.Receipt; +import store.view.InputView; + +public class StoreServiceImpl implements StoreService { + @Override + public Receipt buy(String name, Long quantity, List<Product> inventory, List<Promotion> promotions) { + List<Product> products = findProductByName(name, inventory); + + Product[] separatedProducts = separatePromotionProduct(products); + Product nonPromotionProduct = separatedProducts[0]; + Product promotionProduct = separatedProducts[1]; + + if (promotionProduct != null) { + Promotion promotion = findApplicablePromotion(promotionProduct, promotions); + if (promotion.checkPromotionPeriod(DateTimes.now().toLocalDate())) { + return handlePromotionPurchase(promotionProduct, nonPromotionProduct, promotion, quantity); + } + } + + return handleNonPromotionPurchase(nonPromotionProduct, quantity); + } + + @Override + public Long[] calculateTotalReceipts(List<Receipt> receipts) { + Long totalPrice = 0L; + Long discountPrice = 0L; + + for (Receipt receipt : receipts) { + totalPrice += receipt.getTotalPrice(); + discountPrice += receipt.getDiscountPrice(); + } + return new Long[]{totalPrice, discountPrice}; + } + + @Override + public Long calculateMembershipDiscount(Long price, String answer) { + if (StringConstants.YES.equals(answer)) { + double membershipDiscountPrice = price * NumberConstants.MEMBERSHIP_DISCOUNT_RATIO; + if (membershipDiscountPrice > NumberConstants.MAX_MEMBERSHIP_DISCOUNT) { + return NumberConstants.MAX_MEMBERSHIP_DISCOUNT; + } + return (long) membershipDiscountPrice; + } + return NumberConstants.NO_MEMBERSHIP_DISCOUNT; + } + + // ์ œํ’ˆ ์ด๋ฆ„์œผ๋กœ Product ๋ฆฌ์ŠคํŠธ๋ฅผ ๊ฒ€์ƒ‰ + private List<Product> findProductByName(String name, List<Product> inventory) { + List<Product> products = inventory.stream() + .filter(component -> component.getName().equals(name)) + .toList(); + + if (products.isEmpty()) { + throw new IllegalArgumentException(ErrorConstants.NOT_EXIST_PRODUCT_ERROR_MESSAGE); + } + return products; + } + + // ์ผ๋ฐ˜ ์ œํ’ˆ๊ณผ ํ”„๋กœ๋ชจ์…˜ ์ œํ’ˆ์„ ๊ตฌ๋ถ„ํ•˜์—ฌ ๋ฐฐ์—ด๋กœ ๋ฐ˜ํ™˜ + private Product[] separatePromotionProduct(List<Product> products) { + Supplier<Stream<Product>> productStreamSupplier = products::stream; + + Product nonPromotionProduct = productStreamSupplier.get() + .filter(product -> StringConstants.NULL.equals(product.getPromotion())) + .findFirst() + .orElse(null); + + Product promotionProduct = productStreamSupplier.get() + .filter(product -> !StringConstants.NULL.equals(product.getPromotion())) + .findFirst() + .orElse(null); + + return new Product[]{nonPromotionProduct, promotionProduct}; + } + + // ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋œ ์ œํ’ˆ์˜ Promotion ๋ฐ˜ํ™˜ + private Promotion findApplicablePromotion(Product promotionProduct, List<Promotion> promotions) { + return promotions.stream() + .filter(promo -> promo.getName().equals(promotionProduct.getPromotion())) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException(ErrorConstants.NOT_EXIST_PROMOTION_ERROR_MESSAGE)); + } + + // ํ”„๋กœ๋ชจ์…˜ ์ œํ’ˆ ๊ตฌ๋งค ์ฒ˜๋ฆฌ + private Receipt handlePromotionPurchase(Product promotionProduct, Product nonPromotionProduct, + Promotion promotion, Long quantity) { + Long promotionProductQuantity = promotionProduct.getQuantity(); + Long freeQuantity = calculateFreeQuantity(quantity, promotion); + + if (promotionProductQuantity >= quantity + freeQuantity) { + return applyFullPromotion(promotionProduct, quantity, freeQuantity, promotion); + } + if (promotionProductQuantity < quantity + freeQuantity) { + return handleInsufficientPromotionStock(promotionProduct, nonPromotionProduct, + promotionProductQuantity, promotion, quantity); + } + throw new IllegalArgumentException(ErrorConstants.NOT_EXIST_CASE_ERROR_MESSAGE); + } + + // ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋˜๋Š” ์ƒํ’ˆ์— ๋Œ€ํ•ด ๋ฌด๋ฃŒ ์ˆ˜๋Ÿ‰ ๊ณ„์‚ฐ + private Long calculateFreeQuantity(Long quantity, Promotion promotion) { + return (quantity / promotion.getBuy()) * promotion.getGet(); + } + + // ํ”„๋กœ๋ชจ์…˜์ด ์ „์ฒด ์ˆ˜๋Ÿ‰์ด ๊ตฌ๋งค ์ˆ˜๋Ÿ‰๊ณผ ๋ฌด๋ฃŒ ์ˆ˜๋Ÿ‰์˜ ํ•ฉ๋ณด๋‹ค ํด ๋•Œ + private Receipt applyFullPromotion(Product promotionProduct, Long quantity, Long freeQuantity, + Promotion promotion) { + if (quantity % promotion.getBuy() == 0) { + String answer = InputView.tellFreeProductProvide(promotionProduct.getName(), freeQuantity); + Receipt productReceipt = getProductFreeOrNot(promotionProduct, quantity, freeQuantity, answer); + if (productReceipt != null) { + return productReceipt; + } + } + promotionProduct.buy(quantity + freeQuantity); + return new Receipt(promotionProduct.getName(), quantity + freeQuantity, freeQuantity, + promotionProduct.getPrice()); + } + + // ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ ๊ตฌ๋งค ์ ์šฉ์— ๋”ฐ๋ฅธ ๊ตฌ๋งค ์ฒ˜๋ฆฌ + @Override + public Receipt getProductFreeOrNot(Product promotionProduct, Long quantity, Long freeQuantity, String answer) { + if (StringConstants.YES.equals(answer)) { + promotionProduct.buy(quantity + freeQuantity); + return new Receipt(promotionProduct.getName(), quantity + freeQuantity, freeQuantity, + promotionProduct.getPrice()); + } + if (StringConstants.NO.equals(answer)) { + promotionProduct.buy(quantity); + return new Receipt(promotionProduct.getName(), quantity, 0L, promotionProduct.getPrice()); + } + throw new IllegalArgumentException(ErrorConstants.INPUT_FORMAT_ERROR_MESSAGE); + } + + // ํ”„๋กœ๋ชจ์…˜์ด ์ „์ฒด ์ˆ˜๋Ÿ‰์ด ๊ตฌ๋งค ์ˆ˜๋Ÿ‰๊ณผ ๋ฌด๋ฃŒ ์ˆ˜๋Ÿ‰์˜ ํ•ฉ๋ณด๋‹ค ์ž‘์„ ๋•Œ + private Receipt handleInsufficientPromotionStock(Product promotionProduct, Product nonPromotionProduct, + Long promotionProductQuantity, Promotion promotion, Long quantity) { + Long promotionNotAppliedQuantity = calculatePromotionNotAppliedQuantity(quantity, promotionProductQuantity, promotion); + Long actualFreeQuantity = calculateActualFreeQuantity(promotionProductQuantity, promotion); + String answer = InputView.tellPromotionNotApplicable(promotionProduct.getName(), promotionNotAppliedQuantity); + + return buyInSufficientPromotionStockOrNot(promotionProduct, nonPromotionProduct, quantity, + actualFreeQuantity, answer, promotionNotAppliedQuantity); + } + + @Override + public long calculatePromotionNotAppliedQuantity(Long quantity, Long promotionProductQuantity, Promotion promotion) { + return quantity - (promotionProductQuantity / promotion.getBuy() * (promotion.getGet() + promotion.getBuy())); + } + + @Override + public long calculateActualFreeQuantity(Long promotionProductQuantity, Promotion promotion) { + return promotionProductQuantity / (promotion.getGet() + promotion.getBuy()); + } + + // ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ  ๋ถ€์กฑ ์‹œ ๋ถ€์กฑ๋ถ„ ์ •๊ฐ€ ๊ตฌ๋งค ํ˜น์€ ๋ฏธ๊ตฌ๋งค ์ฒ˜๋ฆฌ + @Override + public Receipt buyInSufficientPromotionStockOrNot(Product promotionProduct, Product nonPromotionProduct, + Long quantity, Long freeQuantity, String answer, + Long promotionNotAppliedQuantity) { + Receipt allProductReceipt = answerYes(promotionProduct, nonPromotionProduct, promotionProduct.getQuantity(), + quantity, freeQuantity, answer, promotionNotAppliedQuantity); + if (allProductReceipt != null) { + return allProductReceipt; + } + + Receipt promotionProductReceipt = answerNo(promotionProduct, quantity, freeQuantity, answer, + promotionNotAppliedQuantity); + if (promotionProductReceipt != null) { + return promotionProductReceipt; + } + + throw new IllegalArgumentException(ErrorConstants.INPUT_FORMAT_ERROR_MESSAGE); + } + + // ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ  ๋ถ€์กฑ ์‹œ ๋ถ€์กฑ๋ถ„ ๋ฏธ๊ตฌ๋งค + private static Receipt answerNo(Product promotionProduct, Long quantity, Long freeQuantity, + String answer, Long promotionNotAppliedQuantity) { + if (StringConstants.NO.equals(answer)) { + long quantityToBuy = quantity - promotionNotAppliedQuantity; + promotionProduct.buy(quantityToBuy); + return new Receipt(promotionProduct.getName(), quantityToBuy, freeQuantity - promotionNotAppliedQuantity, + promotionProduct.getPrice()); + } + return null; + } + + // ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ  ๋ถ€์กฑ ์‹œ ๋ถ€์กฑ๋ถ„ ์ •๊ฐ€ ๊ตฌ๋งค + private static Receipt answerYes(Product promotionProduct, Product nonPromotionProduct, + Long promotionProductQuantity, + Long quantity, Long freeQuantity, String answer, + Long promotionNotAppliedQuantity) { + if (StringConstants.YES.equals(answer)) { + promotionProduct.buy(promotionProductQuantity); + nonPromotionProduct.buy(quantity - promotionProductQuantity); + return new Receipt(promotionProduct.getName(), quantity, freeQuantity, promotionProduct.getPrice()); + } + return null; + } + + // ํ”„๋กœ๋ชจ์…˜์ด ์ ์šฉ๋˜์ง€ ์•Š๋Š” ์ผ๋ฐ˜ ์ƒํ’ˆ ๊ตฌ๋งค ์ฒ˜๋ฆฌ + private Receipt handleNonPromotionPurchase(Product nonPromotionProduct, Long quantity) { + nonPromotionProduct.buy(quantity); + return new Receipt(nonPromotionProduct.getName(), quantity, 0L, nonPromotionProduct.getPrice()); + } +}
Java
์˜ค ์ „์ฒด์ ์œผ๋กœ ๊น”๋”ํ•˜๋‹ค๋Š” ๋А๋‚Œ์„ ๋งŽ์ด ๋ฐ›์•˜์–ด์š”! ๊ฐ€๋…์„ฑ์ด ์ข‹๋„ค์š” !!
@@ -0,0 +1,63 @@ +package store.view; + +import camp.nextstep.edu.missionutils.Console; +import java.util.Map; +import store.common.constants.ErrorConstants; +import store.common.constants.MessageConstants; +import store.common.constants.StringConstants; +import store.view.utils.InputParser; +import store.view.utils.InputValidation; + +public class InputView { + + public static Map<String, Long> askPurchaseProduct() { + System.out.println(MessageConstants.PRODUCT_PURCHASE_MESSAGE); + while (true) { + try { + String input = Console.readLine(); + String[] inputSplit = InputValidation.validatePurchaseInput(input); + System.out.println(); + return InputParser.purchaseInputParser(inputSplit); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + public static String tellPromotionNotApplicable(String name, Long quantity) { + System.out.printf(MessageConstants.PROMOTION_NOT_APPLY_MESSAGE, name, quantity); + System.out.println(); + return getYesOrNoAnswer(); + } + + private static String getYesOrNoAnswer() { + while(true) { + try { + String answer = Console.readLine(); + System.out.println(); + if (!(answer.equals(StringConstants.NO) || answer.equals(StringConstants.YES))) { + throw new IllegalArgumentException(ErrorConstants.INPUT_FORMAT_ERROR_MESSAGE); + } + return answer; + } catch(IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + public static String tellFreeProductProvide(String name, Long quantity) { + System.out.printf(MessageConstants.PROMOTION_PROVIDE_FREE_PRODUCT_MESSAGE, name, quantity); + System.out.println(); + return getYesOrNoAnswer(); + } + + public static String askMembershipDiscount() { + System.out.println(MessageConstants.MEMBERSHIP_DISCOUNT_MESSAGE); + return getYesOrNoAnswer(); + } + + public static String buyAnotherProduct() { + System.out.println(MessageConstants.EXIT_MESSAGE); + return getYesOrNoAnswer(); + } +}
Java
parser๋ฅผ ๋ทฐ์—์„œ ์“ฐ๋Š” ๊ฒฝ์šฐ๋Š” ๋ณดํ†ต '๋‹จ์ˆœํ•œ ์ž‘์—…์ผ๋•Œ' ๋˜๋Š” '์„œ๋น„์Šค ๋ ˆ์ด์–ด๋กœ ๋ถ„๋ฆฌํ•˜๋Š”๊ฒŒ ๋น„๋Œ€ํ•˜๋‹ค๊ณ  ์ƒ๊ฐ๋ ๋•Œ'๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ๋งŒ์•ฝ ํ•ด๋‹น ๋กœ์ง์„ ํ™•์žฅํ•œ๋‹ค๋ฉด ๋ทฐ์˜ ์—ญํ• ์ด ๋งŽ์•„์งˆ์ˆ˜๋„ ์žˆ์„๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,11 @@ +package store.common.constants; + +public class ErrorConstants { + public static final String PRODUCT_PURCHASE_FORMAT_ERROR_MESSAGE = "[ERROR] ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + public static final String NOT_EXIST_PRODUCT_ERROR_MESSAGE = "[ERROR] ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + public static final String INVENTORY_SHORT_ERROR_MESSAGE = "[ERROR] ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + public static final String INPUT_FORMAT_ERROR_MESSAGE = "[ERROR] ์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + public static final String FILE_NOT_FOUND = "[ERROR] ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."; + public static final String NOT_EXIST_PROMOTION_ERROR_MESSAGE = "[ERROR] ํ”„๋กœ๋ชจ์…˜์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."; + public static final String NOT_EXIST_CASE_ERROR_MESSAGE = "[ERROR] ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ  ์ˆ˜๋Ÿ‰์— ๋ฌธ์ œ๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ๋ฐ์ดํ„ฐ๋ฅผ ํ™•์ธํ•ด์ฃผ์„ธ์š”"; +}
Java
4์ฃผ์ฐจ ๋ฏธ์…˜ ์กฐ๊ฑด์— ์—ด๊ฑฐํ˜•์„ ์‚ฌ์šฉํ•˜๋Š”๊ฒƒ์ด ์žˆ์—ˆ๋˜๊ฑธ๋กœ ๊ธฐ์–ตํ•ฉ๋‹ˆ๋‹ค! ๋‹ค์‹œ ๋กœ์ง์„ ๊ตฌ์„ฑํ•ด๋ณผ๋•Œ ๊ณ ๋ คํ•ด๋ณด๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,23 @@ +package store.service; + +import java.util.List; +import store.domain.Product; +import store.domain.Promotion; +import store.domain.Receipt; + +public interface StoreService { + Receipt buy(String name, Long quantity, List<Product> inventory, List<Promotion> promotions); + + Long[] calculateTotalReceipts(List<Receipt> receipts); + + Long calculateMembershipDiscount(Long price, String answer); + + Receipt getProductFreeOrNot(Product promotionProduct, Long quantity, Long freeQuantity, String answer); + + Receipt buyInSufficientPromotionStockOrNot(Product promotionProduct, Product nonPromotionProduct, + Long quantity, Long freeQuantity, String answer, Long promotionNotAppliedQuantity); + + long calculatePromotionNotAppliedQuantity(Long quantity, Long promotionProductQuantity, Promotion promotion); + + long calculateActualFreeQuantity(Long promotionProductQuantity, Promotion promotion); +}
Java
์ด๋ฒˆ์— ์ €๋Š” ์ธํ„ฐํŽ˜์ด์Šค๋กœ ๋ถ„๋ฆฌํ•˜๋Š”๊ฑธ ์‹คํŒจํ–ˆ๋Š”๋ฐ, ์ž˜ ์ ์šฉํ•ด์ฃผ์…จ๋„ค์š”! ์–ด๋–ค ๊ฒƒ์„ ์ถ”์ƒํ™”ํ–ˆ๋Š”์ง€ ๋ณด๋ฉด์„œ '์–ด๋””๊นŒ์ง€ ์ถ”์ƒํ™”๋ฅผ ํ•ด์•ผํ• ๊นŒ'์— ๋Œ€ํ•œ ๊ณ ๋ฏผ์— ๋„์›€์ด ๋๋˜๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,24 @@ +package store.common.constants; + +public class NumberConstants { + //product row index + public static final int PRODUCT_NAME_INDEX = 0; + public static final int PRODUCT_PRICE_INDEX = 1; + public static final int PRODUCT_QUANTITY_INDEX = 2; + public static final int PRODUCT_PROMOTION_INDEX = 3; + + //promotion row index + public static final int PROMOTION_NAME_INDEX = 0; + public static final int PROMOTION_BUY_INDEX = 1; + public static final int PROMOTION_GET_INDEX = 2; + public static final int PROMOTION_START_DATE_INDEX = 3; + public static final int PROMOTION_END_DATE_INDEX = 4; + + public static final long MAX_MEMBERSHIP_DISCOUNT = 8000L; + public static final long NO_MEMBERSHIP_DISCOUNT = 0L; + public static final double MEMBERSHIP_DISCOUNT_RATIO = 0.3; + + public static final int RECEIPT_THREE_SECTION_WIDTH = 12; + public static final int RECEIPT_TWO_SECTION_WIDTH = 24; + +}
Java
long, double ํƒ€์ž…์œผ๋กœ ๋‘” ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?? ์ƒ์ˆ˜์—ฌ์„œ ๋ฐ”๋€”์ผ๋„ ์—†๊ณ  20์–ต์ด ๋„˜์–ด๊ฐ€๋Š” ํฐ ์ˆ˜๋ฅผ ๋งŒ์งˆ ์ผ์ด ์—†์„ ๊ฒƒ ๊ฐ™์•„์„œ์š” ๋’ค์—์„œ๋„ ์š”๊ฑธ ๋งŽ์ด ์“ฐ์‹  ๊ฒƒ ๊ฐ™์€๋ฐ ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ด์š”!
@@ -0,0 +1,82 @@ +package store.controller; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Scanner; +import store.common.FileReader; +import store.common.constants.AddressConstants; +import store.common.constants.StringConstants; +import store.domain.Product; +import store.domain.Promotion; +import store.domain.Receipt; +import store.service.FileService; +import store.service.StoreService; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + private final FileService fileService; + private final StoreService storeService; + + public StoreController(FileService fileService, StoreService storeService) { + this.fileService = fileService; + this.storeService = storeService; + } + + public void run() { + List<Product> inventory = extractProducts(fileService); // ์ œํ’ˆ ์ถ”์ถœ + List<Promotion> promotions = extractPromotions(fileService); //ํ”„๋กœ๋ชจ์…˜ ์ถ”์ถœ + + while (true) { + String answerToContinue = processPurchase(inventory, storeService, promotions); + if (answerToContinue.equals(StringConstants.NO)) break; + } + } + + private static List<Promotion> extractPromotions(FileService fileServiceImpl) { + Scanner promotionFile = FileReader.readFile(AddressConstants.promotionFilePath); + return fileServiceImpl.extractPromotion(promotionFile); + } + + private static List<Product> extractProducts(FileService fileServiceImpl) { + Scanner productsFile = FileReader.readFile(AddressConstants.productFilePath); + return fileServiceImpl.extractProduct(productsFile); + } + + private static String processPurchase(List<Product> inventory, StoreService storeService, List<Promotion> promotions) { + OutputView.printWelcome(); // ํ™˜์˜ ์ธ์‚ฌ + OutputView.printInventoryDetail(inventory); // ์žฌ๊ณ  ํ™•์ธ + + List<Receipt> receipts = buyProducts(storeService, inventory, promotions); // ๊ตฌ๋งค + Long[] totalReceipts = storeService.calculateTotalReceipts(receipts); // totalReceipts[0]: ์ด๊ตฌ๋งค ๊ธˆ์•ก, totalReceipts[1]: ์ดํ• ์ธ ๊ธˆ์•ก + Long priceAfterPromotionDiscount = totalReceipts[0] - totalReceipts[1]; + Long membershipDiscount = calculateMembershipDiscount(storeService, priceAfterPromotionDiscount); // ๋ฉค๋ฒ„์‹ญ ํ• ์ธ ์ ์šฉ + + OutputView.printFinalReceipt(receipts, totalReceipts[1], membershipDiscount); // ์˜์ˆ˜์ฆ ์ถœ๋ ฅ + + return InputView.buyAnotherProduct(); // ๋ฌผ๊ฑด ๋ฐ˜๋ณต ๊ตฌ๋งค ๋ฌธ์˜ + } + + private static Long calculateMembershipDiscount(StoreService storeService, Long priceAfterPromotionDiscount) { + String answerToApplyMembership = InputView.askMembershipDiscount(); + return storeService.calculateMembershipDiscount(priceAfterPromotionDiscount, answerToApplyMembership); + } + + private static List<Receipt> buyProducts(StoreService storeService, List<Product> inventory, + List<Promotion> promotions) { + List<Receipt> receipts = new ArrayList<>(); + while (receipts.isEmpty()) { + try { + Map<String, Long> productsToBuy = InputView.askPurchaseProduct(); + productsToBuy.forEach((name, quantity) -> { + Receipt receipt = storeService.buy(name, quantity, inventory, promotions); + receipts.add(receipt); + }); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + return receipts; + } +}
Java
๋™์˜ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,50 @@ +package store.domain; + +import static store.common.constants.NumberConstants.PRODUCT_NAME_INDEX; +import static store.common.constants.NumberConstants.PRODUCT_PRICE_INDEX; +import static store.common.constants.NumberConstants.PRODUCT_PROMOTION_INDEX; +import static store.common.constants.NumberConstants.PRODUCT_QUANTITY_INDEX; + +import store.common.constants.ErrorConstants; + +public class Product { + private final String name; + private final Long price; + private Long quantity; + private final String promotion; + + public Product(String[] productsInfo) { + String name = productsInfo[PRODUCT_NAME_INDEX]; + long price = Long.parseLong(productsInfo[PRODUCT_PRICE_INDEX]); + long quantity = Long.parseLong(productsInfo[PRODUCT_QUANTITY_INDEX]); + String promotion = productsInfo[PRODUCT_PROMOTION_INDEX]; + + this.name = name; + this.price = price; + this.quantity = quantity; + this.promotion = promotion; + } + + public void buy(Long quantity) { + if (quantity > this.quantity) { + throw new IllegalArgumentException(ErrorConstants.INVENTORY_SHORT_ERROR_MESSAGE); + } + this.quantity -= quantity; + } + + public Long getPrice() { + return price; + } + + public Long getQuantity() { + return quantity; + } + + public String getPromotion() { + return promotion; + } + + public String getName() { + return name; + } +}
Java
์žฌ๊ณ  ํ™•์ธ์„ ๋ณ„๋„์˜ ๋ฉ”์†Œ๋“œ๋กœ ๋ถ„๋ฆฌํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,8 @@ +package store.common.constants; + +public class AddressConstants { + public static final String productFilePath = + "/Users/hanwool/WooTeco/java-convenience-store-7-hanwool1643/src/main/resources/products.md"; + public static final String promotionFilePath = + "/Users/hanwool/WooTeco/java-convenience-store-7-hanwool1643/src/main/resources/promotions.md"; +}
Java
๋™์˜ํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,12 @@ +package store.service; + +import java.util.List; +import java.util.Scanner; +import store.domain.Product; +import store.domain.Promotion; + +public interface FileService { + List<Product> extractProduct(Scanner productsFile); + + List<Promotion> extractPromotion(Scanner promotionsFile); +}
Java
์ €๋„ ์ž˜ ๋ชฐ๋ž๋Š”๋ฐ Scanner๋ฅผ ์ธ์ž๋กœ ๋ฐ›๋Š”๊ฑด ๊ตฌํ˜„ ์„ธ๋ถ€ ์‚ฌํ•ญ์— ๋Œ€ํ•œ ์˜์กด์„ ์œ ๋ฐœํ•˜๋ฏ€๋กœ, ์ถ”์ƒํ™” ์ˆ˜์ค€์„ ๋†’์—ฌ ํŒŒ์ผ ๊ฒฝ๋กœ๋‚˜ ๋ฌธ์ž์—ด ๋“ฑ์„ ๋ฐ›๋„๋ก ํ•˜๋ฉด ์ข‹๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค!