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