code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,71 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+import store.constant.CommonMessage;
+import store.constant.CommonValue;
+
+public class Receipt {
+ private final double THIRTY_PERCENT = 0.3;
+ private final List<ReceiptItem> receiptItems = new ArrayList<>();
+
+ public void addItem(ReceiptItem receiptItem) {
+ receiptItems.add(receiptItem);
+ }
+
+ public List<ReceiptItem> getReceiptItems() {
+ return receiptItems;
+ }
+
+ public int totalPurchaseAmount() {
+ int sum = CommonValue.ZERO.getValue();
+ for (ReceiptItem receiptItem : receiptItems) {
+ sum += receiptItem.getTotalBuyQuantity() * receiptItem.getPrice();
+ }
+ return sum;
+ }
+
+ public int totalPromotionDiscount() {
+ int sum = CommonValue.ZERO.getValue();
+ for (ReceiptItem receiptItem : receiptItems) {
+ if (receiptItem.getGetQuantity() != CommonValue.ZERO.getValue()) {
+ sum += receiptItem.getGetQuantity() * receiptItem.getPrice();
+ }
+ }
+ return sum;
+ }
+
+ public int getTotalPurchaseCount() {
+ int sum = CommonValue.ZERO.getValue();
+ for (ReceiptItem receiptItem : receiptItems) {
+ sum += receiptItem.getTotalBuyQuantity();
+ }
+ return sum;
+ }
+
+ public int validateMembership(String userAnswer) {
+ if (userAnswer.equals(CommonMessage.YES.getCommonMessage())) {
+ return getMembershipDiscount();
+ }
+ return CommonValue.ZERO.getValue();
+ }
+
+ private int noTotalPromotionAmount() {
+ int sum = CommonValue.ZERO.getValue();
+ for (ReceiptItem receiptItem : receiptItems) {
+ if (receiptItem.getGetQuantity() == CommonValue.ZERO.getValue()) {
+ sum += receiptItem.getBuyQuantity() * receiptItem.getPrice();
+ }
+ }
+ return sum;
+ }
+
+ private int getMembershipDiscount() {
+ int membershipDiscount = (int) (noTotalPromotionAmount() * THIRTY_PERCENT);
+ if (membershipDiscount > CommonValue.EIGHT_THOUSAND.getValue()) {
+ membershipDiscount = CommonValue.EIGHT_THOUSAND.getValue();
+ }
+ return membershipDiscount;
+ }
+
+} | Java | ์ข์ ์ง์ ๊ฐ์ฌํฉ๋๋ค!
๋ง์ํ์ ๋๋ก ๋ถ๋์์์ ์ค์ฐจ๊ฐ ๋ฐ์ํ ์ ์๋ค๋ ์ ์ ๊ฐ๊ณผํ๋ ๊ฒ ๊ฐ์ต๋๋ค.
์ข์ ๋ฐฉ๋ฒ์ธ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,83 @@
+package store.domain;
+
+import java.util.Collections;
+import java.util.List;
+import store.constant.CommonValue;
+import store.constant.SignMessage;
+import store.exception.ConvenienceStoreException;
+import store.exception.ErrorMessage;
+
+public class Storage {
+ private final List<GeneralProduct> generalProducts;
+ private final List<PromotionProduct> promotionProducts;
+
+ public Storage(final List<GeneralProduct> generalProducts, final List<PromotionProduct> promotionProducts) {
+ this.generalProducts = generalProducts;
+ this.promotionProducts = promotionProducts;
+ }
+
+ public List<String> validateStorageStatus(List<String> purchaseProduct) {
+ for (String purchaseItem : purchaseProduct) {
+ List<String> item = List.of(purchaseItem.split(SignMessage.HYPHEN.getSign()));
+ validateItemName(item.get(CommonValue.ZERO.getValue()));
+ validateQuantity(item.get(CommonValue.ZERO.getValue()), item.get(CommonValue.ONE.getValue()));
+ }
+ return purchaseProduct;
+ }
+
+ public List<GeneralProduct> getGeneralProducts() {
+ return Collections.unmodifiableList(generalProducts);
+ }
+
+ public List<PromotionProduct> getPromotionProducts() {
+ return Collections.unmodifiableList(promotionProducts);
+ }
+
+ public GeneralProduct findGeneralProduct(String productName) {
+ return generalProducts.stream()
+ .filter(product -> product.getName().equals(productName))
+ .findFirst()
+ .orElse(null);
+ }
+
+ public PromotionProduct findPromotionProduct(String productName) {
+ return promotionProducts.stream()
+ .filter(product -> product.getName().equals(productName))
+ .findFirst()
+ .orElse(null);
+ }
+
+ public void subtractPromotionProduct(PromotionProduct promotionProduct, int itemQuantity) {
+ promotionProduct.subtraction(itemQuantity);
+ }
+
+ public void subtractGeneralProduct(GeneralProduct generalProduct, int itemQuantity) {
+ generalProduct.subtraction(itemQuantity);
+ }
+
+ private void validateQuantity(String name, String quantity) {
+ if (getProductQuantity(name) < Integer.parseInt(quantity)) {
+ throw ConvenienceStoreException.from(ErrorMessage.STORAGE_OVER);
+ }
+ }
+
+ private int getProductQuantity(String name) {
+ PromotionProduct promotionProduct = findPromotionProduct(name);
+ int count = CommonValue.ZERO.getValue();
+ if (promotionProduct != null) {
+ count += promotionProduct.getQuantity();
+ }
+ return count + findGeneralProduct(name).getQuantity();
+ }
+
+ private void validateItemName(String name) {
+ if (!isProductInStorage(name)) {
+ throw ConvenienceStoreException.from(ErrorMessage.NON_EXISTENT_PRODUCT);
+ }
+ }
+
+ private boolean isProductInStorage(String productName) {
+ return generalProducts.stream().anyMatch(product -> product.getName().equals(productName));
+ }
+
+} | Java | ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,114 @@
+package store.service;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import store.constant.FileMessage;
+import store.constant.SignMessage;
+import store.domain.GeneralProduct;
+import store.domain.Promotion;
+import store.domain.PromotionProduct;
+import store.domain.Storage;
+import store.utils.FileLoader;
+
+public class StorageService {
+ private static final String FILE_NOT_FOUND_ERROR = "[ERROR] ํ์ผ์ ์ฐพ์ ์ ์์ต๋๋ค.";
+ private final List<String> productFile;
+ private final List<String> promotionFile;
+
+ public StorageService(final String productFileName, final String promotionFileName) {
+ this.productFile = loadFile(productFileName);
+ this.promotionFile = loadFile(promotionFileName);
+ }
+
+ public Storage initializeStorage() {
+ List<Promotion> promotions = generatePromotionData(promotionFile);
+ List<GeneralProduct> onlyGeneralProducts = findGeneralProduct(productFile);
+ List<PromotionProduct> onlyPromotionProducts = findPromotionProduct(productFile, promotions);
+ List<GeneralProduct> insertedGeneralProducts = insertOutOfStock(onlyPromotionProducts, onlyGeneralProducts);
+ return new Storage(insertedGeneralProducts, onlyPromotionProducts);
+ }
+
+ private List<String> loadFile(String fileName) {
+ try {
+ return FileLoader.fileReadLine(fileName);
+ } catch (IOException e) {
+ throw new IllegalArgumentException(FILE_NOT_FOUND_ERROR);
+ }
+ }
+
+ private List<Promotion> generatePromotionData(List<String> promotionFile) {
+ List<Promotion> promotions = new ArrayList<>();
+ for (String line : promotionFile) {
+ List<String> items = List.of(line.split(SignMessage.COMMA.getSign()));
+ promotions.add(new Promotion(items.get(0), Integer.parseInt(items.get(1)), Integer.parseInt(items.get(2)),
+ items.get(3), items.get(4)));
+ }
+ return promotions;
+ }
+
+ private List<GeneralProduct> insertOutOfStock(List<PromotionProduct> prItem, List<GeneralProduct> generalProducts) {
+ int idx = 0;
+ for (PromotionProduct product : prItem) {
+ if (findEqualGeneralProductName(generalProducts, product.getName())) {
+ idx += 1;
+ continue;
+ }
+ generalProducts.add(idx, new GeneralProduct(product.getName(), product.getPrice(), 0));
+ }
+ return generalProducts;
+ }
+
+
+ private boolean findEqualGeneralProductName(List<GeneralProduct> generalProducts, String name) {
+ for (GeneralProduct generalProduct : generalProducts) {
+ if (generalProduct.getName().equals(name)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private List<GeneralProduct> findGeneralProduct(List<String> getFile) {
+ List<GeneralProduct> onlyGeneralProducts = new ArrayList<>();
+ for (String itemDetails : getFile) {
+ if (itemDetails.contains(FileMessage.NULL.getFileMessage())) {
+ List<String> item = List.of(itemDetails.split(SignMessage.COMMA.getSign()));
+ onlyGeneralProducts.add(new GeneralProduct(item.get(0), item.get(1), Integer.parseInt(item.get(2))));
+ }
+ }
+ return onlyGeneralProducts;
+ }
+
+ private List<PromotionProduct> findPromotionProduct(List<String> getFile, List<Promotion> promotions) {
+ List<PromotionProduct> onlyPromotionProducts = new ArrayList<>();
+ for (String itemDetails : getFile) {
+ if (isPromotionProduct(itemDetails)) {
+ addPromotionProduct(onlyPromotionProducts, itemDetails, promotions);
+ }
+ }
+ return onlyPromotionProducts;
+ }
+
+ private boolean isPromotionProduct(String itemDetails) {
+ return itemDetails.contains(FileMessage.SOFT_DRINK.getFileMessage())
+ || itemDetails.contains(FileMessage.MD_RECOMMEND_PRODUCT.getFileMessage())
+ || itemDetails.contains(FileMessage.FLASH_DISCOUNT.getFileMessage());
+ }
+
+ private void addPromotionProduct(List<PromotionProduct> products, String itemDetails, List<Promotion> promotions) {
+ List<String> item = List.of(itemDetails.split(SignMessage.COMMA.getSign()));
+ String productName = item.get(0);
+ String productCategory = item.get(1);
+ int price = Integer.parseInt(item.get(2));
+ Promotion promotion = matchingPromotion(item.get(3), promotions);
+
+ products.add(new PromotionProduct(productName, productCategory, price, promotion));
+ }
+
+ private Promotion matchingPromotion(String promotionName, List<Promotion> promotions) {
+ return promotions.stream().filter(promotion -> promotion.getName().equals(promotionName)).findFirst()
+ .orElse(null);
+ }
+
+} | Java | ์.. ์ด ๋ถ๋ถ๋ ๋ฆฌํฉํ ๋งํ๋ฉด์ ErrorMessage์ ์ฎ๊ฒจ์ผ ํ๋๋ฐ ๋์ณค๋ ๊ฒ ๊ฐ์์!
๋ง์ํด์ฃผ์
์ ๊ฐ์ฌ๋๋ฆฝ๋๋ค! |
@@ -0,0 +1,141 @@
+package store.view.output;
+
+import java.util.List;
+import store.domain.GeneralProduct;
+import store.domain.PromotionProduct;
+import store.domain.Receipt;
+import store.domain.ReceiptItem;
+import store.domain.Storage;
+import store.exception.ConvenienceStoreException;
+
+public class OutputView {
+
+ public void writeStorageStatus(Storage storage) {
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ System.out.println(OutputMessage.WELCOME_MESSAGE.getOutputMessage());
+ System.out.println(OutputMessage.SHOW_CURRENT_ITEMS.getOutputMessage());
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ writeInitPromotionProducts(storage);
+ writeInitOnlyGeneralProducts(storage);
+ }
+
+ public void writeReceipt(Receipt receipt, String userAnswer) {
+ writeReceiptMenuHeader();
+ writeReceiptMenuName(receipt);
+ writePresentation(receipt);
+ System.out.println(OutputMessage.PERFORATION_LINE.getOutputMessage());
+ writeUserTotalReceipt(receipt, userAnswer);
+ }
+
+ private void writeUserTotalReceipt(Receipt receipt, String userAnswer) {
+ writeShowTotalPurchaseAmount(receipt);
+ writeShowTotalPromotionDiscountAmount(receipt);
+ writeShowTotalMembershipDiscountAmount(receipt, userAnswer);
+ writeShowTotalPaymentAmount(receipt, userAnswer);
+ }
+
+ private void writeShowTotalPaymentAmount(Receipt receipt, String userAnswer) {
+ String nameAndPrice = String.format(OutputMessage.SHOW_PAYMENT_FORMAT.getOutputMessage(), "๋ด์ค๋",
+ String.format("%,d", receipt.totalPurchaseAmount() - receipt.totalPromotionDiscount() -
+ receipt.validateMembership(userAnswer)));
+ System.out.println(nameAndPrice);
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ }
+
+
+ private void writeShowTotalMembershipDiscountAmount(Receipt receipt, String userAnswer) {
+ String name = String.format("%-14s", "๋ฉค๋ฒ์ญํ ์ธ").replace(" ", "\u3000");
+ String price = String.format("-%,d", receipt.validateMembership(userAnswer));
+ System.out.printf(OutputMessage.SHOW_DISCOUNT_FORMAT.getOutputMessage(), name, price);
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ }
+
+ private void writeShowTotalPromotionDiscountAmount(Receipt receipt) {
+ String name = String.format("%-14s", "ํ์ฌํ ์ธ").replace(" ", "\u3000");
+ String price = String.format("-%,d", receipt.totalPromotionDiscount());
+ System.out.printf(OutputMessage.SHOW_DISCOUNT_FORMAT.getOutputMessage(), name, price);
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ }
+
+ private void writeShowTotalPurchaseAmount(Receipt receipt) {
+ String name = String.format("%-14s", "์ด๊ตฌ๋งค์ก").replace(" ", "\u3000");
+ String quantity = String.format("%-10d", receipt.getTotalPurchaseCount());
+ String price = String.format("%,-10d", receipt.totalPurchaseAmount());
+ System.out.printf(OutputMessage.SHOW_RECEIPT_INIT_FORMAT.getOutputMessage(), name, quantity, price);
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ }
+
+ private void writePresentation(Receipt receipt) {
+ System.out.println(OutputMessage.SHOW_RECEIPT_PRESENTATION_HEADER.getOutputMessage());
+ for (ReceiptItem receiptItem : receipt.getReceiptItems()) {
+ if (receiptItem.getGetQuantity() != 0) {
+ String name = String.format("%-14s", receiptItem.getItemName()).replace(" ", "\u3000");
+ String quantity = String.format("%,-10d", receiptItem.getGetQuantity());
+ System.out.printf(OutputMessage.SHOW_PRESENTATION_FORMAT.getOutputMessage(), name, quantity);
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ }
+ }
+ }
+
+ private void writeReceiptMenuName(Receipt receipt) {
+ System.out.println(OutputMessage.SHOW_RECEIPT_MENU_NAME.getOutputMessage());
+ for (ReceiptItem receiptItem : receipt.getReceiptItems()) {
+ String name = String.format("%-14s", receiptItem.getItemName()).replace(" ", "\u3000");
+ String quantity = String.format("%-10d", receiptItem.getTotalBuyQuantity());
+ String price = String.format("%,-10d", receiptItem.getPrice() * receiptItem.getTotalBuyQuantity());
+ System.out.printf(OutputMessage.SHOW_RECEIPT_INIT_FORMAT.getOutputMessage(), name, quantity, price);
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ }
+ }
+
+ private void writeReceiptMenuHeader() {
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ System.out.println(OutputMessage.SHOW_RECEIPT_HEADER.getOutputMessage());
+ }
+
+
+ private void writeInitPromotionProducts(Storage storage) {
+ for (PromotionProduct promotionProduct : storage.getPromotionProducts()) {
+ System.out.println(promotionProduct);
+ findEqualGeneralProductName(storage.getGeneralProducts(), promotionProduct.getName());
+ }
+ }
+
+ private void findEqualGeneralProductName(List<GeneralProduct> generalProducts, String name) {
+ for (GeneralProduct generalProduct : generalProducts) {
+ if (generalProduct.getName().equals(name)) {
+ System.out.println(generalProduct);
+ break;
+ }
+ }
+ }
+
+ private void writeInitOnlyGeneralProducts(Storage storage) {
+ for (GeneralProduct generalProduct : storage.getGeneralProducts()) {
+ String generalProductName = generalProduct.getName();
+ boolean flag = findEqualPromotionProductName(storage.getPromotionProducts(), generalProductName);
+ writeOnlyGeneralProduct(flag, generalProduct);
+ }
+ System.out.print(OutputMessage.NEW_LINE.getOutputMessage());
+ }
+
+ private boolean findEqualPromotionProductName(List<PromotionProduct> promotionProducts, String name) {
+ for (PromotionProduct promotionProduct : promotionProducts) {
+ if (promotionProduct.getName().equals(name)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private void writeOnlyGeneralProduct(boolean flag, GeneralProduct generalProduct) {
+ if (!flag) {
+ System.out.println(generalProduct.toString());
+ }
+ }
+
+ public void displayErrorMessage(ConvenienceStoreException convenienceStoreException) {
+ System.out.println(convenienceStoreException.getMessage());
+ }
+
+} | Java | ์ ๋ ๊ฐ์ธ์ ์ผ๋ก ํ๋ก๋ชจ์
์ํ์ด ์์ง๋ ๊ฒฝ์ฐ์๋ '์ฌ๊ณ ์์'์ ํ์ํ๋ ๊ฒ์ด ์ค์ํ๋ค๊ณ ์๊ฐํฉ๋๋ค.
์ฌ๊ณ ์์์ ํ์ํ์ง ์์ผ๋ฉด, ์ฌ์ฉ์๊ฐ ํด๋น ์ํ์ด ํ๋ก๋ชจ์
๊ธฐ๊ฐ์ ํฌํจ๋ ๊ฒ์ธ์ง ์๋์ง๋ฅผ ๊ตฌ๋ถํ๊ธฐ ์ด๋ ค์ธ ์ ์๊ธฐ ๋๋ฌธ์
๋๋ค.
๋ฐ๋ผ์ ํ๋ก๋ชจ์
๊ธฐ๊ฐ ์ค์ ์ฌ๊ณ ๊ฐ ์๋ค๋ฉด '์ฌ๊ณ ์์'์ ๋ช
์ํ๋ ๊ฒ์ด ์ฌ์ฉ์์๊ฒ ๋ ๋ช
ํํ๊ณ ํผ๋์ ์ค์ผ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค.
๋ฌผ๋ก ํ๋ก๋ชจ์
๊ธฐ๊ฐ์ด ์๋ ๊ฒฝ์ฐ์๋ '์ฌ๊ณ ์์'์ด ํ์๋์ง ์๋ ๊ฒ์ด ๋ง๋ค๊ณ ์๊ฐํฉ๋๋ค!
์ข์ ์๊ฒฌ ๊ฐ์ฌ๋๋ฆฝ๋๋ค! ๋ง์ํด์ฃผ์ ๋ด์ฉ์ ๋๋ถ์ UX ์ธก๋ฉด์์๋ ๋ค์ ํ ๋ฒ ๊ณ ๋ฏผํด๋ณผ ์ ์์์ต๋๋ค. |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.util.List;
+import java.util.function.Supplier;
+import store.constant.CommonMessage;
+import store.constant.CommonValue;
+import store.constant.SignMessage;
+import store.domain.GeneralProduct;
+import store.domain.PromotionProduct;
+import store.domain.Receipt;
+import store.domain.Storage;
+import store.exception.ConvenienceStoreException;
+import store.service.ReceiptService;
+import store.service.StorageService;
+import store.utils.Calculator;
+import store.utils.Compare;
+import store.utils.Parser;
+import store.view.input.InputView;
+import store.view.output.OutputView;
+
+public class ConvenienceStoreController {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final Storage storage;
+
+ public ConvenienceStoreController(InputView inputView, OutputView outputView, StorageService storageService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.storage = storageService.initializeStorage();
+ }
+
+ public void operate() {
+ String retryFlag;
+ do {
+ outputView.writeStorageStatus(storage);
+ Receipt receipt = new Receipt();
+ processPurchase(userPurchaseProduct(), receipt);
+ outputView.writeReceipt(receipt, userMembership());
+ retryFlag = userRetry();
+ } while (retryFlag.equalsIgnoreCase(CommonMessage.YES.getCommonMessage()));
+ inputView.closeConsole();
+ }
+
+ private void processPurchase(List<String> purchaseProduct, Receipt receipt) {
+ for (String detail : purchaseProduct) {
+ List<String> item = List.of(detail.split(SignMessage.HYPHEN.getSign()));
+ PromotionProduct product = storage.findPromotionProduct(item.get(CommonValue.ZERO.getValue()));
+ if (product != null && product.getPromotion().isActive(DateTimes.now())) {
+ processPromotionProduct(product, Parser.parse(item.get(CommonValue.ONE.getValue())), receipt);
+ continue;
+ }
+ processGeneralPurchase(item, receipt);
+ }
+ }
+
+ private void processGeneralPurchase(List<String> item, Receipt receipt) {
+ ReceiptService.purchaseGeneralProduct(storage, item.get(CommonValue.ZERO.getValue()),
+ Integer.parseInt(item.get(CommonValue.ONE.getValue())), receipt);
+ }
+
+ private void processPromotionProduct(PromotionProduct promotionProduct, int itemQuantity, Receipt receipt) {
+ int stock = Calculator.calculateRemainStock(promotionProduct, itemQuantity);
+ int purchase = Calculator.calculateUserRemain(promotionProduct, itemQuantity);
+ boolean freeTag = userOneMoreFree(purchase, stock, promotionProduct, itemQuantity, receipt);
+ boolean supplementTag = supplementStock(itemQuantity, stock, promotionProduct, receipt);
+ useStock(freeTag, supplementTag, promotionProduct, itemQuantity, receipt);
+ }
+
+ private boolean userOneMoreFree(int leftBuy, int leftStock, PromotionProduct product, int count, Receipt receipt) {
+ if (Compare.checkFreeOneMore(leftBuy, leftStock, product)) {
+ storage.subtractPromotionProduct(product, count);
+ if (checkUserAnswer(product).equals(CommonMessage.YES.getCommonMessage())) {
+ storage.subtractPromotionProduct(product, product.getPromotionGetGet());
+ return ReceiptService.oneMoreReceipt(receipt, count, leftBuy, product);
+ }
+ return ReceiptService.noOneMoreReceipt(receipt, count, leftBuy, product);
+ }
+ return false;
+ }
+
+ private boolean supplementStock(int quantity, int stock, PromotionProduct product, Receipt receipt) {
+ if (Compare.checkSupplementStock(stock)) {
+ int noPromotion = Calculator.calculateNoPromotion(product);
+ int beforePromotionQuantity = product.getQuantity();
+ storage.subtractPromotionProduct(product, noPromotion);
+ String userAnswer = checkUserNoPromotion(product, Calculator.minus(quantity, noPromotion));
+ return suppleGeneralProduct(product, userAnswer, Calculator.minus(quantity, noPromotion), receipt,
+ beforePromotionQuantity);
+ }
+ return false;
+ }
+
+ private boolean suppleGeneralProduct(PromotionProduct product, String answer, int quantity, Receipt receipt,
+ int prevQuantity) {
+ GeneralProduct generalProduct = storage.findGeneralProduct(product.getName());
+ int currentQuantity = product.getQuantity();
+ if (answer.equals(CommonMessage.YES.getCommonMessage())) {
+ storage.subtractGeneralProduct(generalProduct, Calculator.minus(quantity, currentQuantity));
+ storage.subtractPromotionProduct(product, currentQuantity);
+ return ReceiptService.noDiscountPurchase(receipt, quantity, prevQuantity, currentQuantity, product);
+ }
+ return ReceiptService.noOneMoreReceipt(receipt, prevQuantity, currentQuantity, product);
+ }
+
+ private void useStock(boolean freeTag, boolean suppleTag, PromotionProduct product, int quantity, Receipt receipt) {
+ if (!freeTag && !suppleTag) {
+ storage.subtractPromotionProduct(product, quantity);
+ ReceiptService.useStock(product, quantity, receipt);
+ }
+ }
+
+ private String userRetry() {
+ return handleUserInput(inputView::readRetry);
+ }
+
+ private String userMembership() {
+ return handleUserInput(inputView::readMembership);
+ }
+
+ private List<String> userPurchaseProduct() {
+ return handleUserInput(() -> storage.validateStorageStatus(inputView.readItems()));
+ }
+
+ private String checkUserAnswer(PromotionProduct promotionProduct) {
+ return handleUserInput(() -> inputView.readOneMoreFree(promotionProduct.getName()));
+ }
+
+ private String checkUserNoPromotion(PromotionProduct promotionProduct, int quantity) {
+ return handleUserInput(() -> inputView.readNoDiscountAnswer(promotionProduct.getName(), quantity));
+ }
+
+ private <T> T handleUserInput(Supplier<T> inputSupplier) {
+ while (true) {
+ try {
+ return inputSupplier.get();
+ } catch (ConvenienceStoreException convenienceStoreException) {
+ outputView.displayErrorMessage(convenienceStoreException);
+ }
+ }
+ }
+
+} | Java | CommonMessage.YES.getCommonMessage() ํด๋น ๊ตฌ๋ฌธ์ด ์์ฃผ ์ฌ์ฉ๋์ด ๋ณด์ด๋ค์. ํด๋น ๋ถ๋ถ์ CommonMessage ํด๋์ค์ ๋ฉ์๋๋ก ๊ตฌํํ๋ ๋ฐฉ์์ ์ด๋จ๊น์?
๋ํ InputView์์ validateUserAnswer() ๋ฉ์๋์์ ์ฌ์ฉ์ ์
๋ ฅ์ด Y๋ N ๋ enum ํด๋์ค์ ์ ์์ ๊ฐ์ ์ง ํ์ธํ๊ณ ๋ค๋ฅด๋ฉด ์์ธ๋ฅผ ๋์ง๋ ๊ฒ๋ณด๋ค, CommonMessage์ Dto ์ฒ๋ผ ํ์ฉํ์ฌ ํด๋น dto๋ฅผ ์์ฑํจ์ ์์ด์ ์ฌ์ฉ์ ์
๋ ฅ์ ๋๊ฒจ์ฃผ๊ณ (new CommonMessage(String input)) ์
๋ ฅ ์ ์์ ๋ค๋ฅผ ์์ dto ์์ฑ์์์ ์์ธ๋ฅผ ๋์ ธ์ฃผ๋ ๋ฐฉ์์ ์ด๋จ๊น์?
์ ์๊ฐ์๋ ์์ฒ๋ผ ๊ตฌํ ํ๋ ๊ฒ์ด InputView์ ์ฑ
์์ ๋์ด์ฃผ๋ฉด์ ์ฑ
์ ์กฐ์ ์ด ๋ ์์ ์ ์ผ ๊ฒ ๊ฐ์์! ์ด์ ๋ํ ๋ณด์ฑ๋ ์๊ฒฌ์ด ๊ถ๊ธํด์! |
@@ -0,0 +1,19 @@
+package store.constant;
+
+public enum SignMessage {
+ COMMA(","),
+ LEFT_SQUARE_BRACKET("["),
+ RIGHT_SQUARE_BRACKET("]"),
+ HYPHEN("-");
+
+ private final String sign;
+
+ SignMessage(final String sign) {
+ this.sign = sign;
+ }
+
+ public String getSign() {
+ return sign;
+ }
+
+} | Java | ์ด๋ฌํ ',', '[' ๋ฑ๊ณผ ๊ฐ์ด ๋น์ฆ๋์ค ๋ก์ง๊ณผ ๊ด๋ ค๋ ๋ถ๋ถ์ ๋ฐ๋ก ์์ ํด๋์ค๋ฅผ ๋๋ ๊ฒ๋ณด๋ค ๊ทธ๋ฅ ์ฌ์ฉ ํด๋์ค ๋ด์ ์์ ํ๋๋ก๋ง ๋์ด๋ ๋ ๊ฒ ๊ฐ์์.
์ ๊ฐ์ ๊ฒฝ์ฐ๋ ์์ ํด๋์ค๋ก ๋ฐ๋ก ๊ด๋ฆฌํ๋ ๋ถ๋ถ์ ๋น์ฆ๋์ค์ ๊ด๋ จ๋ ๋ถ๋ถ์ ํ๋ฒ์ ๋ชจ์๋ณด๋ ๊ฐ๋
์ฑ๋ฉด์ด ์ ์ผ ํฌ๋ค๊ณ ์๊ฐํ๊ฑฐ๋ ์! ์๋ฐ์์๋ ๋ฌธ์์ด ๋ฆฌํฐ๋ด์ ๋ฐ๋ก ์์ํ์์ ํ๋ฒ์ ๊ด๋ฆฌํ๋ฏ๋ก ์ ๋ฐ ๋ฆฌํฐ๋ด ๋ถ๋ถ์ ํด๋์ค์ ์ค๋ณต๋์ด ์ ์ธ๋์ด๋ ๋ฉ๋ชจ๋ฆฌ์์์๋ ๋ฌธ์ ์์ผ๋๊น ์ฌ์ฉํ๋ ํด๋์ค์ ์์ ํ๋๋ก ๋์ด๋ ๋ ๊ฒ ๊ฐ์์.
์ด๋ ์ ๊ฐ์ธ์ ์๊ฒฌ์ด๋ผ ๋ค๋ฅธ ๋ถ๋ค์ ์๊ฒฌ๋ ๊ถ๊ธํ๋ค์! |
@@ -0,0 +1,143 @@
+package store.controller;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.util.List;
+import java.util.function.Supplier;
+import store.constant.CommonMessage;
+import store.constant.CommonValue;
+import store.constant.SignMessage;
+import store.domain.GeneralProduct;
+import store.domain.PromotionProduct;
+import store.domain.Receipt;
+import store.domain.Storage;
+import store.exception.ConvenienceStoreException;
+import store.service.ReceiptService;
+import store.service.StorageService;
+import store.utils.Calculator;
+import store.utils.Compare;
+import store.utils.Parser;
+import store.view.input.InputView;
+import store.view.output.OutputView;
+
+public class ConvenienceStoreController {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final Storage storage;
+
+ public ConvenienceStoreController(InputView inputView, OutputView outputView, StorageService storageService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.storage = storageService.initializeStorage();
+ }
+
+ public void operate() {
+ String retryFlag;
+ do {
+ outputView.writeStorageStatus(storage);
+ Receipt receipt = new Receipt();
+ processPurchase(userPurchaseProduct(), receipt);
+ outputView.writeReceipt(receipt, userMembership());
+ retryFlag = userRetry();
+ } while (retryFlag.equalsIgnoreCase(CommonMessage.YES.getCommonMessage()));
+ inputView.closeConsole();
+ }
+
+ private void processPurchase(List<String> purchaseProduct, Receipt receipt) {
+ for (String detail : purchaseProduct) {
+ List<String> item = List.of(detail.split(SignMessage.HYPHEN.getSign()));
+ PromotionProduct product = storage.findPromotionProduct(item.get(CommonValue.ZERO.getValue()));
+ if (product != null && product.getPromotion().isActive(DateTimes.now())) {
+ processPromotionProduct(product, Parser.parse(item.get(CommonValue.ONE.getValue())), receipt);
+ continue;
+ }
+ processGeneralPurchase(item, receipt);
+ }
+ }
+
+ private void processGeneralPurchase(List<String> item, Receipt receipt) {
+ ReceiptService.purchaseGeneralProduct(storage, item.get(CommonValue.ZERO.getValue()),
+ Integer.parseInt(item.get(CommonValue.ONE.getValue())), receipt);
+ }
+
+ private void processPromotionProduct(PromotionProduct promotionProduct, int itemQuantity, Receipt receipt) {
+ int stock = Calculator.calculateRemainStock(promotionProduct, itemQuantity);
+ int purchase = Calculator.calculateUserRemain(promotionProduct, itemQuantity);
+ boolean freeTag = userOneMoreFree(purchase, stock, promotionProduct, itemQuantity, receipt);
+ boolean supplementTag = supplementStock(itemQuantity, stock, promotionProduct, receipt);
+ useStock(freeTag, supplementTag, promotionProduct, itemQuantity, receipt);
+ }
+
+ private boolean userOneMoreFree(int leftBuy, int leftStock, PromotionProduct product, int count, Receipt receipt) {
+ if (Compare.checkFreeOneMore(leftBuy, leftStock, product)) {
+ storage.subtractPromotionProduct(product, count);
+ if (checkUserAnswer(product).equals(CommonMessage.YES.getCommonMessage())) {
+ storage.subtractPromotionProduct(product, product.getPromotionGetGet());
+ return ReceiptService.oneMoreReceipt(receipt, count, leftBuy, product);
+ }
+ return ReceiptService.noOneMoreReceipt(receipt, count, leftBuy, product);
+ }
+ return false;
+ }
+
+ private boolean supplementStock(int quantity, int stock, PromotionProduct product, Receipt receipt) {
+ if (Compare.checkSupplementStock(stock)) {
+ int noPromotion = Calculator.calculateNoPromotion(product);
+ int beforePromotionQuantity = product.getQuantity();
+ storage.subtractPromotionProduct(product, noPromotion);
+ String userAnswer = checkUserNoPromotion(product, Calculator.minus(quantity, noPromotion));
+ return suppleGeneralProduct(product, userAnswer, Calculator.minus(quantity, noPromotion), receipt,
+ beforePromotionQuantity);
+ }
+ return false;
+ }
+
+ private boolean suppleGeneralProduct(PromotionProduct product, String answer, int quantity, Receipt receipt,
+ int prevQuantity) {
+ GeneralProduct generalProduct = storage.findGeneralProduct(product.getName());
+ int currentQuantity = product.getQuantity();
+ if (answer.equals(CommonMessage.YES.getCommonMessage())) {
+ storage.subtractGeneralProduct(generalProduct, Calculator.minus(quantity, currentQuantity));
+ storage.subtractPromotionProduct(product, currentQuantity);
+ return ReceiptService.noDiscountPurchase(receipt, quantity, prevQuantity, currentQuantity, product);
+ }
+ return ReceiptService.noOneMoreReceipt(receipt, prevQuantity, currentQuantity, product);
+ }
+
+ private void useStock(boolean freeTag, boolean suppleTag, PromotionProduct product, int quantity, Receipt receipt) {
+ if (!freeTag && !suppleTag) {
+ storage.subtractPromotionProduct(product, quantity);
+ ReceiptService.useStock(product, quantity, receipt);
+ }
+ }
+
+ private String userRetry() {
+ return handleUserInput(inputView::readRetry);
+ }
+
+ private String userMembership() {
+ return handleUserInput(inputView::readMembership);
+ }
+
+ private List<String> userPurchaseProduct() {
+ return handleUserInput(() -> storage.validateStorageStatus(inputView.readItems()));
+ }
+
+ private String checkUserAnswer(PromotionProduct promotionProduct) {
+ return handleUserInput(() -> inputView.readOneMoreFree(promotionProduct.getName()));
+ }
+
+ private String checkUserNoPromotion(PromotionProduct promotionProduct, int quantity) {
+ return handleUserInput(() -> inputView.readNoDiscountAnswer(promotionProduct.getName(), quantity));
+ }
+
+ private <T> T handleUserInput(Supplier<T> inputSupplier) {
+ while (true) {
+ try {
+ return inputSupplier.get();
+ } catch (ConvenienceStoreException convenienceStoreException) {
+ outputView.displayErrorMessage(convenienceStoreException);
+ }
+ }
+ }
+
+} | Java | ์คํ๋ ค ๊ฐ์ฒด๋ก๋ง ํ๋ ฅํ๋๋ก ํ ๋ถ๋ถ์ด ๋
ธ๋ จํ ๊ฒ ๊ฐ์์! ์ ๋ ๊ฐ์ฒด๋ฅผ ๋ค๋ฃจ๊ณ ํ๋ ฅํ๋ ๋ถ๋ถ์ด ์ด๋ ค์์ ์๋น์ค ์ธต์ ๋์๊ฑฐ๋ ์ ๐คฃ |
@@ -0,0 +1,38 @@
+package store.domain;
+
+public class GeneralProduct {
+ private final String name;
+ private final String price;
+ private int quantity;
+
+ public GeneralProduct(final String name, final String price, final int quantity) {
+ this.name = name;
+ this.price = price;
+ this.quantity = quantity;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public String getPrice() {
+ return price;
+ }
+
+ public void subtraction(int value) {
+ this.quantity -= Math.abs(value);
+ }
+
+ @Override
+ public String toString() {
+ if (quantity == 0) {
+ return String.format("- %s %,d์ ์ฌ๊ณ ์์", name, Integer.parseInt(price));
+ }
+ return String.format("- %s %,d์ %s๊ฐ", name, Integer.parseInt(price), quantity);
+ }
+
+} | Java | ์ ๋ ์ด๋ฌํ 2์ฃผ์ฐจ ๋๊ฐ? ๊ฐ์ฒด ์ถ๋ ฅ๊ณผ ๊ด๋ จ๋ ๋ถ๋ถ์ ํด๋น ๊ฐ์ฒด ์์์ ํ๋๊ฒ ์ฝ๋๋ ๊น๋ํ๊ณ ์ข์ง์์๊นํ์ฌ ์ด๋ ๊ฒ ์์ฑํ ์ ์ด์์ต๋๋ค!
ํ์ง๋ง ๊ฒฐ๊ตญ ๋ง์ง๋ง ์ฏค toStirng๊ณผ ๊ด๋ จ๋ ์ฝ๋๋ ๋ชจ๋ ์ง์ฐ๊ณ view์์๋ง ๋ดํ๋๋ก ํ์๋๋ฐ์, ๊ทธ ์ด์ ๋ก ์ฒซ ๋ฒ์งธ๋ toString์ ์ฌ๋งํ๋ฉด ๋ก๊ทธ ํ์ธ์ฉ์ผ๋ก๋ง ์ฌ์ฉ๋๋ค๊ณ ๋ค์์ต๋๋ค. 3์ฃผ์ฐจ ๊ณตํต ํผ๋๋ฐฑ์๋ ์ด์ ๋ํ ์ฌํญ์ด ์ ํ์๋๋ผ๊ตฌ์! ๋ ๋ฒ์งธ๋ก ์ถ๋ ฅํ์์ด ๋ฐ๋๋ฉด View ๋ฟ๋ง์๋๋ผ ๊ด๋ จ ํด๋์ค๋ค์ ์ฐพ์ผ๋ฌ ๋ค๋๋ฉด์ ๊ณ ์ณ์ผํ ๊ฒ ๊ฐ๋ค๋ ์๊ฐ์ ์ถ๋ ฅ๊ด๋ จ์ ์ค์ง View์ ์ฑ
์์ผ๋ก๋ง ์ฃผ์์์ต๋๋ค!
์ ๋ ๊ฐํก์งํก ํ๋ ์ฌํญ์ด๋ผ ์ด์ ๋ํ ๋ณด์ฑ๋ ์๊ฒฌ๋ ๊ถ๊ธํ๋ค์๐ |
@@ -0,0 +1,34 @@
+package store.view;
+
+public enum Sentence {
+
+ PRODUCT_SELECT_STATEMENT("๊ตฌ๋งคํ์ค ์ํ๋ช
๊ณผ ์๋์ ์
๋ ฅํด ์ฃผ์ธ์. (์: [์ฌ์ด๋ค-2],[๊ฐ์์นฉ-1])"),
+ HELLO_STATEMENT("์๋
ํ์ธ์. Wํธ์์ ์
๋๋ค."),
+ CURRENT_PRODUCTS_STATEMENT("ํ์ฌ ๋ณด์ ํ๊ณ ์๋ ์ํ์
๋๋ค."),
+ NUMBER_FORMAT("#,###"),
+ PRODUCT_FORMAT("- %s %s์ "),
+ QUANTITY_FORMAT("%s๊ฐ "),
+ OUT_OF_STOCK("์ฌ๊ณ ์์ "),
+ ADDITIONAL_PURCHASE_FORMAT("ํ์ฌ %s์(๋) %d๊ฐ๋ฅผ ๋ฌด๋ฃ๋ก ๋ ๋ฐ์ ์ ์์ต๋๋ค. ์ถ๊ฐํ์๊ฒ ์ต๋๊น? (Y/N)"),
+ NO_PROMOTION_STATEMENT("ํ์ฌ %s %d๊ฐ๋ ํ๋ก๋ชจ์
ํ ์ธ์ด ์ ์ฉ๋์ง ์์ต๋๋ค. ๊ทธ๋๋ ๊ตฌ๋งคํ์๊ฒ ์ต๋๊น? (Y/N)"),
+ MEMBERSHIP_STATEMENT("๋ฉค๋ฒ์ญ ํ ์ธ์ ๋ฐ์ผ์๊ฒ ์ต๋๊น? (Y/N)"),
+ START_OF_RECEIPT("==============W ํธ์์ ================"),
+ HEADER_OF_PURCHASE("์ํ๋ช
\t\t์๋\t๊ธ์ก"),
+ PURCHASE_FORMAT("%s\t\t%s \t%s"),
+ HEADER_OF_GIVEN("=============์ฆ\t์ ==============="),
+ GIVEN_FORMAT("%s\t\t%s"),
+ DIVIDE_LINE("===================================="),
+ TOTAL_PRICE_FORMAT("์ด๊ตฌ๋งค์ก\t\t%s\t%s"),
+ PROMOTION_DISCOUNT_FORMAT("ํ์ฌํ ์ธ\t\t\t-%s"),
+ MEMBERSHIP_DISCOUNT_FORMAT("๋ฉค๋ฒ์ญํ ์ธ\t\t\t-%s"),
+ PAY_PRICE_FORMAT("๋ด์ค๋\t\t\t %s"),
+ PURCHASE_AGAIN_STATEMENT("๊ฐ์ฌํฉ๋๋ค. ๊ตฌ๋งคํ๊ณ ์ถ์ ๋ค๋ฅธ ์ํ์ด ์๋์? (Y/N)"),
+ BLANK(""),
+ NEW_LINE(System.lineSeparator());
+
+ final String message;
+
+ Sentence(final String message) {
+ this.message = message;
+ }
+} | Java | ๋จ์ํ ์ถ๋ ฅ ๋ฌธ๊ตฌ๋ค๋ ์์ํ ํด์ผ ํ๋์ง ์ด์ง ์๋ฌธ์
๋๋ค. ์์ํ์ ์ด์ ์ ์ค๋ณต์ ์ ๊ฑฐํ๊ณ ๊ฐ๋
์ฑ์ ํฅ์ ์ํค๋ ๋ฑ์ ํจ๊ณผ๊ฐ ์์ง๋ง ๋ถํ์ํ ๋ณต์ก์ฑ ์ฆ๊ฐ, ์ฝ๋ ์ ์ง ๊ด๋ฆฌ์ ์ด๋ ค์ ๋ฑ์ ๋จ์ ๋ ์์ต๋๋ค. ์ ๋ฌธ๊ตฌ๋ฅผ ์์ํ ํ์ ๋ ์ ํํ ์ด๋ค ๋์์ด ๋๋์ง ๋ค์ ์๊ฐํด๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,52 @@
+package store.view;
+
+import store.domain.Product;
+import store.domain.Products;
+import store.dto.ReceiptDto;
+
+public class View {
+
+ private final InputView inputView;
+ private final OutputView outputView;
+
+ public View(InputView inputView, OutputView outputView) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ }
+
+ public String requestProductSelect() {
+ return inputView.requestProductSelect();
+ }
+
+ public String askAdditionalPurchase(Product product) {
+ return inputView.askAdditionalPurchase(product);
+ }
+
+ public String askNoPromotion(Product product, int shortageQuantity) {
+ return inputView.askNoPromotion(product, shortageQuantity);
+ }
+
+ public String askMembership() {
+ return inputView.askMembership();
+ }
+
+ public String askPurchaseAgain() {
+ return inputView.askPurchaseAgain();
+ }
+
+ public void printHello() {
+ outputView.printHello();
+ }
+
+ public void printCurrentProducts(Products products) {
+ outputView.printCurrentProducts(products);
+ }
+
+ public void printReceipt(ReceiptDto receiptDto) {
+ outputView.printReceipt(receiptDto);
+ }
+
+ public void printBlank() {
+ outputView.printBlank();
+ }
+} | Java | ์ข์ ์ :
InputView์ OutputView๋ฅผ View ํด๋์ค์์ ๋ฌถ์ด์ฃผ๋ ๊ตฌ์กฐ๋ ๊ฐ ๋ทฐ ๊ฐ์ฒด์ ๋ํ ์์กด์ฑ์ ์ค์ด๊ณ , View ํด๋์ค๊ฐ ํ๋์ ํตํฉ๋ ์ญํ ์ ํ๊ฒ ๋ง๋ค์ด์ฃผ๋ ์ ์์ ์ข์ ์ ๊ทผ์ด์์.
๊ฐ์ ์ฌํญ:
ํ์ง๋ง ํ์ฌ View ํด๋์ค๋ ์ฌ์ค์ InputView์ OutputView์ ๋ฉ์๋๋ฅผ ๊ทธ๋๋ก ์ ๋ฌํ๋ ์ญํ ๋ง ํ๊ณ ์์ด์. ์ด๋ ๊ฒ ์ ๋ฌํ๋ ๋ฐฉ์๋ง์ผ๋ก๋ View ํด๋์ค์ ์กด์ฌ ์ด์ ๊ฐ ์กฐ๊ธ ๋ถ๋ช
ํํ ์ ์์ต๋๋ค. ๋ง์ฝ ์ด ํด๋์ค๊ฐ ๋ค๋ฅธ ์ญํ ์ ์ํํ์ง ์๋๋ค๋ฉด, ์ค๊ฐ์์ ๋จ์ํ ๋ฉ์๋ ์ ๋ฌ๋ง ํ๋ ๊ตฌ์กฐ๋ ๋ถํ์ํ ์ค๋ฒํค๋๋ฅผ ๋ง๋ค ์ ์์ด์. ์๋ฅผ ๋ค์ด, InputView์ OutputView๋ฅผ ๊ฐ๊ฐ ํธ์ถํ๋ ๊ฒ๊ณผ ๋์ผํ ๋ฐฉ์์ผ๋ก ๋์ํ ์ ์์ผ๋ฏ๋ก, ๋ ํด๋์ค์ ์ญํ ์ด ๋ช
ํํ๋ค๋ฉด View ํด๋์ค๋ฅผ ์๋ตํ ์๋ ์๊ฒ ๋ค์.
๋ง์ฝ View ํด๋์ค์์ ํฅํ ์ถ๊ฐ์ ์ธ ๋ก์ง์ด๋ ์ฒ๋ฆฌ๊ฐ ํ์ํ๋ค๋ฉด, ๊ทธ๋ ์ญํ ์ ๋ช
ํํ ์ ์ํ๋ ๊ฒ๋ ์ข์ ๋ฐฉ๋ฒ์ผ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,28 @@
+package store.dto;
+
+import store.domain.Product;
+import store.domain.PurchaseItem;
+
+public record GivenItemDto(
+ String name,
+ int freeQuantity,
+ int price) {
+
+ public static GivenItemDto from(PurchaseItem purchaseItem) {
+ Product product = purchaseItem.getProduct();
+ int freeQuantity = calculateFreeQuantity(purchaseItem);
+
+ return new GivenItemDto(product.name(), freeQuantity, product.price());
+ }
+
+ private static int calculateFreeQuantity(PurchaseItem purchaseItem) {
+ Product product = purchaseItem.getProduct();
+
+ if (product.promotion() != null) {
+ return product.promotion()
+ .calculateFreeQuantity(purchaseItem.getQuantity(), product.stock().getPromotionStock());
+ }
+
+ return 0;
+ }
+} | Java | DTO๋ฅผ ์ฌ์ฉํ์๋ ๋ฐฉ์์ด ๋๋ฌด ์ข๋ค์
์ ๋ ์ด๋ฐ์์ผ๋ก ๊ตฌํํ๋ค๋ฉด ํ๊ฒฐ ๊น๋ํ์ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,42 @@
+package store.domain;
+
+public record Product(
+ String name,
+ int price,
+ Stock stock,
+ Promotion promotion) {
+
+ public int calculateTotalPrice(int quantity) {
+ return price * quantity;
+ }
+
+ public void updateStock(int purchasedQuantity) {
+ int availablePromotionStock = stock.getPromotionStock();
+ int promotionQuantity = Math.min(availablePromotionStock, purchasedQuantity);
+ int regularQuantity = purchasedQuantity - promotionQuantity;
+
+ stock.minusPromotionStock(promotionQuantity);
+ stock.minusRegularStock(regularQuantity);
+ }
+
+ public int calculatePromotionDiscount(int purchasedQuantity) {
+ if (promotion == null || !promotion.isWithinPromotionPeriod()) {
+ return 0;
+ }
+
+ int eligibleForPromotion = promotion.calculateFreeQuantity(purchasedQuantity, stock.getPromotionStock());
+ return eligibleForPromotion * price;
+ }
+
+ public int getPromotionStock() {
+ return stock.getPromotionStock();
+ }
+
+ public int getRegularStock() {
+ return stock.getRegularStock();
+ }
+
+ public int getFullStock() {
+ return getPromotionStock() + getRegularStock();
+ }
+} | Java | ๋ณ๋์ฑ์ด ํฐ ๊ฐ์ฒด์ธ๋ฐ ๋ ์ฝ๋๋ก ๊ตฌํํ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค |
@@ -0,0 +1,64 @@
+package store.domain;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.time.LocalDate;
+import store.dto.PromotionDetailDto;
+
+public class Promotion {
+
+ private final String name;
+ private final int buy;
+ private final int get;
+ private final LocalDate startDate;
+ private final LocalDate endDate;
+
+ public Promotion(final String name, final int buy, final int get, final LocalDate startDate,
+ final LocalDate endDate) {
+ this.name = name;
+ this.buy = buy;
+ this.get = get;
+ this.startDate = startDate;
+ this.endDate = endDate;
+ }
+
+ public boolean isWithinPromotionPeriod() {
+ LocalDate today = DateTimes.now().toLocalDate();
+ return (today.isEqual(startDate) || today.isAfter(startDate))
+ && (today.isEqual(endDate) || today.isBefore(endDate));
+ }
+
+ public int calculateAdditionalPurchase(int purchaseQuantity) {
+ int remain = purchaseQuantity % sumOfBuyAndGet();
+
+ if (remain != 0) {
+ return sumOfBuyAndGet() - remain;
+ }
+
+ return remain;
+ }
+
+ public PromotionDetailDto calculatePromotionAndFree(int requestedQuantity, int promotionStock) {
+ int availablePromotion = (promotionStock / sumOfBuyAndGet()) * sumOfBuyAndGet();
+ return new PromotionDetailDto(availablePromotion, requestedQuantity - availablePromotion);
+ }
+
+ public int calculateFreeQuantity(int requestedQuantity, int promotionStock) {
+ if (requestedQuantity > promotionStock) {
+ return promotionStock / sumOfBuyAndGet();
+ }
+
+ return requestedQuantity / sumOfBuyAndGet();
+ }
+
+ private int sumOfBuyAndGet() {
+ return buy + get;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getGet() {
+ return get;
+ }
+} | Java | ์ด๋ถ๋ถ์ ์ ๋ ๋์ผํ๊ฒ ๊ตฌํํ์ง๋ง buy์ get์ ํฌ์ฅํ๊ณ startDate์ endDate๋ฅผ ํฌ์ฅํ์ฌ ํ๋ ์๋ฅผ ์ค์์ผ๋ฉด ์ด๋ ์์ง ๊ถ๊ธํ๋ค์ |
@@ -0,0 +1,34 @@
+package store.view;
+
+public enum Sentence {
+
+ PRODUCT_SELECT_STATEMENT("๊ตฌ๋งคํ์ค ์ํ๋ช
๊ณผ ์๋์ ์
๋ ฅํด ์ฃผ์ธ์. (์: [์ฌ์ด๋ค-2],[๊ฐ์์นฉ-1])"),
+ HELLO_STATEMENT("์๋
ํ์ธ์. Wํธ์์ ์
๋๋ค."),
+ CURRENT_PRODUCTS_STATEMENT("ํ์ฌ ๋ณด์ ํ๊ณ ์๋ ์ํ์
๋๋ค."),
+ NUMBER_FORMAT("#,###"),
+ PRODUCT_FORMAT("- %s %s์ "),
+ QUANTITY_FORMAT("%s๊ฐ "),
+ OUT_OF_STOCK("์ฌ๊ณ ์์ "),
+ ADDITIONAL_PURCHASE_FORMAT("ํ์ฌ %s์(๋) %d๊ฐ๋ฅผ ๋ฌด๋ฃ๋ก ๋ ๋ฐ์ ์ ์์ต๋๋ค. ์ถ๊ฐํ์๊ฒ ์ต๋๊น? (Y/N)"),
+ NO_PROMOTION_STATEMENT("ํ์ฌ %s %d๊ฐ๋ ํ๋ก๋ชจ์
ํ ์ธ์ด ์ ์ฉ๋์ง ์์ต๋๋ค. ๊ทธ๋๋ ๊ตฌ๋งคํ์๊ฒ ์ต๋๊น? (Y/N)"),
+ MEMBERSHIP_STATEMENT("๋ฉค๋ฒ์ญ ํ ์ธ์ ๋ฐ์ผ์๊ฒ ์ต๋๊น? (Y/N)"),
+ START_OF_RECEIPT("==============W ํธ์์ ================"),
+ HEADER_OF_PURCHASE("์ํ๋ช
\t\t์๋\t๊ธ์ก"),
+ PURCHASE_FORMAT("%s\t\t%s \t%s"),
+ HEADER_OF_GIVEN("=============์ฆ\t์ ==============="),
+ GIVEN_FORMAT("%s\t\t%s"),
+ DIVIDE_LINE("===================================="),
+ TOTAL_PRICE_FORMAT("์ด๊ตฌ๋งค์ก\t\t%s\t%s"),
+ PROMOTION_DISCOUNT_FORMAT("ํ์ฌํ ์ธ\t\t\t-%s"),
+ MEMBERSHIP_DISCOUNT_FORMAT("๋ฉค๋ฒ์ญํ ์ธ\t\t\t-%s"),
+ PAY_PRICE_FORMAT("๋ด์ค๋\t\t\t %s"),
+ PURCHASE_AGAIN_STATEMENT("๊ฐ์ฌํฉ๋๋ค. ๊ตฌ๋งคํ๊ณ ์ถ์ ๋ค๋ฅธ ์ํ์ด ์๋์? (Y/N)"),
+ BLANK(""),
+ NEW_LINE(System.lineSeparator());
+
+ final String message;
+
+ Sentence(final String message) {
+ this.message = message;
+ }
+} | Java | ์ถ๋ ฅํ ๋ฌธ๊ตฌ๋ค์ enum์ผ๋ก ๋ง๋๋ ๊ฒ์ด ํ
์คํธํ ๋ ์ฉ์ดํ๋ค๊ณ ์๊ฐ๋ฉ๋๋ค!
์ด๋ฒ ํ
์คํธ ์ฝ๋์์๋ ๊ทธ๋ฐ ๋ถ๋ถ๋ค์ ํ
์คํธํ์ง ๋ชปํ์ง๋ง, ๊ฐ์ธ์ ์ผ๋ก ์ถ๋ ฅ ๋ฌธ๊ตฌ๋ค์ ๋ชจ์๋๋ ๊ฒ์ด ๊ตฌํ ์ ํธ๋ฆฌํ๋ค๊ณ ์๊ฐํฉ๋๋ค. |
@@ -0,0 +1,52 @@
+package store.view;
+
+import store.domain.Product;
+import store.domain.Products;
+import store.dto.ReceiptDto;
+
+public class View {
+
+ private final InputView inputView;
+ private final OutputView outputView;
+
+ public View(InputView inputView, OutputView outputView) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ }
+
+ public String requestProductSelect() {
+ return inputView.requestProductSelect();
+ }
+
+ public String askAdditionalPurchase(Product product) {
+ return inputView.askAdditionalPurchase(product);
+ }
+
+ public String askNoPromotion(Product product, int shortageQuantity) {
+ return inputView.askNoPromotion(product, shortageQuantity);
+ }
+
+ public String askMembership() {
+ return inputView.askMembership();
+ }
+
+ public String askPurchaseAgain() {
+ return inputView.askPurchaseAgain();
+ }
+
+ public void printHello() {
+ outputView.printHello();
+ }
+
+ public void printCurrentProducts(Products products) {
+ outputView.printCurrentProducts(products);
+ }
+
+ public void printReceipt(ReceiptDto receiptDto) {
+ outputView.printReceipt(receiptDto);
+ }
+
+ public void printBlank() {
+ outputView.printBlank();
+ }
+} | Java | controller๊ฐ ๋ง์ ๊ฒ์ ์์กดํ๊ณ ์๋ค๋ ํผ๋๋ฐฑ์ ๋ฐ์์ด์, ์ต๋ํ ์ค์ฌ๋ณด๋ ค View๋ฅผ ๋ง๋ค์์ต๋๋ค. ์ค๊ฐ๋ถํฐ View์ ์ญํ ์ด ์๋ค๋ ์๊ฐ์ด ๋ค์์ง๋ง ์์ ํ ์๊ฐ์ด ์์ด ๊ทธ๋๋ก ์ ์ถํ์ต๋๋ค ใ
ใ
... ์ข์ ์ ๊น์ง ์ ์ด์ฃผ์
์ ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,42 @@
+package store.domain;
+
+public record Product(
+ String name,
+ int price,
+ Stock stock,
+ Promotion promotion) {
+
+ public int calculateTotalPrice(int quantity) {
+ return price * quantity;
+ }
+
+ public void updateStock(int purchasedQuantity) {
+ int availablePromotionStock = stock.getPromotionStock();
+ int promotionQuantity = Math.min(availablePromotionStock, purchasedQuantity);
+ int regularQuantity = purchasedQuantity - promotionQuantity;
+
+ stock.minusPromotionStock(promotionQuantity);
+ stock.minusRegularStock(regularQuantity);
+ }
+
+ public int calculatePromotionDiscount(int purchasedQuantity) {
+ if (promotion == null || !promotion.isWithinPromotionPeriod()) {
+ return 0;
+ }
+
+ int eligibleForPromotion = promotion.calculateFreeQuantity(purchasedQuantity, stock.getPromotionStock());
+ return eligibleForPromotion * price;
+ }
+
+ public int getPromotionStock() {
+ return stock.getPromotionStock();
+ }
+
+ public int getRegularStock() {
+ return stock.getRegularStock();
+ }
+
+ public int getFullStock() {
+ return getPromotionStock() + getRegularStock();
+ }
+} | Java | name, price๋ ๋ณ๊ฒฝ๋์ง ์์ ๊ฒ์ผ๋ก ์๊ฐ๋๊ณ ,
Stock๋ ํ ๋ฒ ์์ฑ๋ ๊ฐ์ฒด๋ฅผ ๊ฐ์ง๊ณ ๊ณ์ ํ์ฉํ ๊ฒ์ผ๋ก ์๊ฐํ์ต๋๋ค.
๊ทธ์น๋ง Promotion์ final์ด ์๋๋ฉด ๋ ์ข์ ๊ฒ ๊ฐ๋ค์ ใ
ใ
... |
@@ -0,0 +1,64 @@
+package store.domain;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.time.LocalDate;
+import store.dto.PromotionDetailDto;
+
+public class Promotion {
+
+ private final String name;
+ private final int buy;
+ private final int get;
+ private final LocalDate startDate;
+ private final LocalDate endDate;
+
+ public Promotion(final String name, final int buy, final int get, final LocalDate startDate,
+ final LocalDate endDate) {
+ this.name = name;
+ this.buy = buy;
+ this.get = get;
+ this.startDate = startDate;
+ this.endDate = endDate;
+ }
+
+ public boolean isWithinPromotionPeriod() {
+ LocalDate today = DateTimes.now().toLocalDate();
+ return (today.isEqual(startDate) || today.isAfter(startDate))
+ && (today.isEqual(endDate) || today.isBefore(endDate));
+ }
+
+ public int calculateAdditionalPurchase(int purchaseQuantity) {
+ int remain = purchaseQuantity % sumOfBuyAndGet();
+
+ if (remain != 0) {
+ return sumOfBuyAndGet() - remain;
+ }
+
+ return remain;
+ }
+
+ public PromotionDetailDto calculatePromotionAndFree(int requestedQuantity, int promotionStock) {
+ int availablePromotion = (promotionStock / sumOfBuyAndGet()) * sumOfBuyAndGet();
+ return new PromotionDetailDto(availablePromotion, requestedQuantity - availablePromotion);
+ }
+
+ public int calculateFreeQuantity(int requestedQuantity, int promotionStock) {
+ if (requestedQuantity > promotionStock) {
+ return promotionStock / sumOfBuyAndGet();
+ }
+
+ return requestedQuantity / sumOfBuyAndGet();
+ }
+
+ private int sumOfBuyAndGet() {
+ return buy + get;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getGet() {
+ return get;
+ }
+} | Java | ์ข์ ์๊ฒฌ์ธ ๊ฒ ๊ฐ์ต๋๋ค! ํ์คํ ํ๋๊ฐ ๊ฐ๊ฒฐํด์ง ๊ฒ ๊ฐ๋ค์ ใ
.ใ
|
@@ -0,0 +1,34 @@
+package store.view;
+
+public enum Sentence {
+
+ PRODUCT_SELECT_STATEMENT("๊ตฌ๋งคํ์ค ์ํ๋ช
๊ณผ ์๋์ ์
๋ ฅํด ์ฃผ์ธ์. (์: [์ฌ์ด๋ค-2],[๊ฐ์์นฉ-1])"),
+ HELLO_STATEMENT("์๋
ํ์ธ์. Wํธ์์ ์
๋๋ค."),
+ CURRENT_PRODUCTS_STATEMENT("ํ์ฌ ๋ณด์ ํ๊ณ ์๋ ์ํ์
๋๋ค."),
+ NUMBER_FORMAT("#,###"),
+ PRODUCT_FORMAT("- %s %s์ "),
+ QUANTITY_FORMAT("%s๊ฐ "),
+ OUT_OF_STOCK("์ฌ๊ณ ์์ "),
+ ADDITIONAL_PURCHASE_FORMAT("ํ์ฌ %s์(๋) %d๊ฐ๋ฅผ ๋ฌด๋ฃ๋ก ๋ ๋ฐ์ ์ ์์ต๋๋ค. ์ถ๊ฐํ์๊ฒ ์ต๋๊น? (Y/N)"),
+ NO_PROMOTION_STATEMENT("ํ์ฌ %s %d๊ฐ๋ ํ๋ก๋ชจ์
ํ ์ธ์ด ์ ์ฉ๋์ง ์์ต๋๋ค. ๊ทธ๋๋ ๊ตฌ๋งคํ์๊ฒ ์ต๋๊น? (Y/N)"),
+ MEMBERSHIP_STATEMENT("๋ฉค๋ฒ์ญ ํ ์ธ์ ๋ฐ์ผ์๊ฒ ์ต๋๊น? (Y/N)"),
+ START_OF_RECEIPT("==============W ํธ์์ ================"),
+ HEADER_OF_PURCHASE("์ํ๋ช
\t\t์๋\t๊ธ์ก"),
+ PURCHASE_FORMAT("%s\t\t%s \t%s"),
+ HEADER_OF_GIVEN("=============์ฆ\t์ ==============="),
+ GIVEN_FORMAT("%s\t\t%s"),
+ DIVIDE_LINE("===================================="),
+ TOTAL_PRICE_FORMAT("์ด๊ตฌ๋งค์ก\t\t%s\t%s"),
+ PROMOTION_DISCOUNT_FORMAT("ํ์ฌํ ์ธ\t\t\t-%s"),
+ MEMBERSHIP_DISCOUNT_FORMAT("๋ฉค๋ฒ์ญํ ์ธ\t\t\t-%s"),
+ PAY_PRICE_FORMAT("๋ด์ค๋\t\t\t %s"),
+ PURCHASE_AGAIN_STATEMENT("๊ฐ์ฌํฉ๋๋ค. ๊ตฌ๋งคํ๊ณ ์ถ์ ๋ค๋ฅธ ์ํ์ด ์๋์? (Y/N)"),
+ BLANK(""),
+ NEW_LINE(System.lineSeparator());
+
+ final String message;
+
+ Sentence(final String message) {
+ this.message = message;
+ }
+} | Java | ์ ๋ @SeongUk52 ๋๊ณผ ๋ง์ฐฌ๊ฐ์ง๋ก ์ถ๋ ฅ ๋ฌธ๊ตฌ๋ค์ ์์ํ ํด์ผํ๋์ง ์๋ฌธ์ด ๋ญ๋๋ค.
`OutputView`๋ฅผ ๋ณด์์ ๋ ํจ์๋ช
์ผ๋ก ์ ์ถ๊ฐ ๊ฐ๋ฅํ๋, ๋ง์ฝ ์ถ๋ ฅ๋ถ๋ถ์ ์์ ํ๋ค๊ณ ๊ฐ๋ฅํ๋ฉด, ๊ฒฐ์ฝ ์ ์ง๋ณด์๊ฐ ์ฌ์ธ ๊ฒ ๊ฐ์ง ์์ต๋๋ค.
#### ์ญ์ผ๋ก ์ง๋ฌธ ๋๋ฆฌ๊ณ ์ถ์ ๊ฒ์ด ์์ต๋๋ค. ํ
์คํธ ํ ๋ ์ฉ์ดํ๋ค๊ณ ๋ง์ํ์
จ๋๋ฐ, ์ถ๋ ฅ๋๋ ๋ด์ฉ๋ค์ ๋ํด ํ
์คํธ๊ฐ ํ์ํ ๊น์?
์ ์ ์๊ฒฌ์ ๋จผ์ ๋ง์๋๋ฆฌ์๋ฉด, OutputView๋ ๊ฒฐ๊ตญ์ ๋ฐ์ดํฐ๋ฅผ ์๊ฐ์ ์ผ๋ก ํํํ๋๊ฒ ์ธ์๋ ๋ด๋นํ๋ ๊ฒ์ด ์์ต๋๋ค.
OutputView์ ๋ณธ์ง์ ์ธ ์ญํ ์ ๋ฐ์ดํฐ๋ฅผ ๋จ์ํ ํํํ๋ ๊ฒ์ ์์ผ๋ฏ๋ก, ์ถ๋ ฅ๋๋ ๋ฌธ๊ตฌ ์์ฒด๊ฐ ํ
์คํธ์ ์ฃผ์ ๋์์ด ๋๊ธฐ๋ณด๋ค๋, View์ ์ ๋ฌ๋๋ ๋ฐ์ดํฐ๊ฐ ์ฌ๋ฐ๋ฅธ์ง์ ์ค์ ์ ๋๋ ๊ฒ์ด ํ๋นํ๋ค๊ณ ์๊ฐํฉ๋๋ค.
ํนํ, ์ถ๋ ฅ ๋ฌธ๊ตฌ๋ฅผ ์์ํํ์ ๋์ ์ฅ์ ์ด ๋ช
ํํ์ง ์๋ค๋ฉด, ์คํ๋ ค ์ฝ๋๊ฐ ๋ณต์กํด์ง๊ณ ์ ์ง๋ณด์ ๋น์ฉ์ด ๋์ด๋ ์ ์์ต๋๋ค.
์ด์ ๊ด๋ จํ์ฌ, ์ฝ๋ ์์ ์ ๊ท๋ฆฌ๋์ด OutputView์ ๋ฉ์๋๋ช
์ ์์ฑํ์๊ธฐ ๋๋ฌธ์, ๋ฉ์๋ ๋ช
์ ํตํด ๊ธฐ๋ฅ์ ์ ์ถํ ์ ์๋ ์ ์ ์ถฉ๋ถํ ์ฅ์ ์ผ๋ก ์์ฉํ ์ ์์ ๊ฑฐ๋ผ๊ณ ์๊ฐํฉ๋๋ค~!
๋ฐ๋ผ์, OutputView๊ฐ ๋จ์ํ ๋ฐ์ดํฐ ์ ๋ฌ์ ์ต์ข
๋จ๊ณ์ ์๋ค๊ณ ๋ณด๊ณ , ์ด ๋ฐ์ดํฐ๊ฐ ์ฌ๋ฐ๋ฅด๊ฒ ์ ๋ฌ๋๋์ง๋ฅผ ๊ฒ์ฆํ๋ ๋ฐ ๋ ์ด์ ์ ๋ง์ถ๋ ํธ์ด OutputView์ ๋ณธ์ง์ ์ธ ์ญํ ์ ๋ ๋ถํฉํ๋ ๋ฐฉ์์ด๋ผ ์๊ฐํฉ๋๋ค. |
@@ -0,0 +1,13 @@
+package store.dto;
+
+import java.util.List;
+
+public record ReceiptDto(
+ List<PurchasedDto> purchasedItems,
+ List<GivenItemDto> givenItems,
+ int totalQuantity,
+ int totalPrice,
+ int promotionDiscountPrice,
+ int membershipDiscountPrice,
+ int payPrice) {
+} | Java | ํด๋น DTO์ ํ๋ผ๋ฏธํฐ๊ฐ ๋ง์ ์ํฉ์ธ๋ฐ, Builderํจํด์ ์ฌ์ฉํ๋๊ฑด ์ด๋จ๊น์??? |
@@ -0,0 +1,42 @@
+package store.domain;
+
+public record Product(
+ String name,
+ int price,
+ Stock stock,
+ Promotion promotion) {
+
+ public int calculateTotalPrice(int quantity) {
+ return price * quantity;
+ }
+
+ public void updateStock(int purchasedQuantity) {
+ int availablePromotionStock = stock.getPromotionStock();
+ int promotionQuantity = Math.min(availablePromotionStock, purchasedQuantity);
+ int regularQuantity = purchasedQuantity - promotionQuantity;
+
+ stock.minusPromotionStock(promotionQuantity);
+ stock.minusRegularStock(regularQuantity);
+ }
+
+ public int calculatePromotionDiscount(int purchasedQuantity) {
+ if (promotion == null || !promotion.isWithinPromotionPeriod()) {
+ return 0;
+ }
+
+ int eligibleForPromotion = promotion.calculateFreeQuantity(purchasedQuantity, stock.getPromotionStock());
+ return eligibleForPromotion * price;
+ }
+
+ public int getPromotionStock() {
+ return stock.getPromotionStock();
+ }
+
+ public int getRegularStock() {
+ return stock.getRegularStock();
+ }
+
+ public int getFullStock() {
+ return getPromotionStock() + getRegularStock();
+ }
+} | Java | record๋ ๊ธฐ๋ณธ์ ์ผ๋ก ๋ฐ์ดํฐ ์ปจํ
์ด๋ ์ญํ ์ ์ง์คํ๊ธฐ ๋๋ฌธ์ ๋ค์ ์ด์ธ๋ฆฌ์ง ์์ ์ ์์ง ์์๊น ์๊ฐํฉ๋๋ค.
๋ํ ๋ง์ฝ Product๊ฐ ์ํ๊ฐ์ ๊ฐ์ ธ์ผ ํ๋ ์ํฉ์ด ์๊ธด๋ค๋ฉด ๋น์ฉ์ด ํฌ๊ฒ ๋ฐ์ํ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,42 @@
+package store.domain;
+
+public record Product(
+ String name,
+ int price,
+ Stock stock,
+ Promotion promotion) {
+
+ public int calculateTotalPrice(int quantity) {
+ return price * quantity;
+ }
+
+ public void updateStock(int purchasedQuantity) {
+ int availablePromotionStock = stock.getPromotionStock();
+ int promotionQuantity = Math.min(availablePromotionStock, purchasedQuantity);
+ int regularQuantity = purchasedQuantity - promotionQuantity;
+
+ stock.minusPromotionStock(promotionQuantity);
+ stock.minusRegularStock(regularQuantity);
+ }
+
+ public int calculatePromotionDiscount(int purchasedQuantity) {
+ if (promotion == null || !promotion.isWithinPromotionPeriod()) {
+ return 0;
+ }
+
+ int eligibleForPromotion = promotion.calculateFreeQuantity(purchasedQuantity, stock.getPromotionStock());
+ return eligibleForPromotion * price;
+ }
+
+ public int getPromotionStock() {
+ return stock.getPromotionStock();
+ }
+
+ public int getRegularStock() {
+ return stock.getRegularStock();
+ }
+
+ public int getFullStock() {
+ return getPromotionStock() + getRegularStock();
+ }
+} | Java | ํน์ ์ผ๋ฐ์ํ๊ณผ ํ๋ก๋ชจ์
์ํ์ ๊ฐ๊ฒฉ์ด ๋ค๋ฅด๋ค๋ฉด ์ด๋ป๊ฒ ์ฒ๋ฆฌ๊ฐ ๋๋์?? |
@@ -0,0 +1,50 @@
+package store.config;
+
+import store.controller.StoreController;
+import store.service.StoreService;
+import store.util.ProductLoader;
+import store.util.PromotionLoader;
+import store.util.PurchaseItemProcessor;
+import store.view.InputView;
+import store.view.OutputView;
+import store.view.View;
+
+public enum AppConfig {
+
+ INSTANCE;
+
+ private static final String PROMOTION_FILE_PATH = "src/main/resources/promotions.md";
+
+ public StoreController storeController() {
+ return new StoreController(view(), storeService());
+ }
+
+ private StoreService storeService() {
+ return new StoreService(productLoader(), purchaseItemParser());
+ }
+
+ private ProductLoader productLoader() {
+ return new ProductLoader(promotionLoader()
+ .loadPromotions(PROMOTION_FILE_PATH));
+ }
+
+ private PromotionLoader promotionLoader() {
+ return new PromotionLoader();
+ }
+
+ private PurchaseItemProcessor purchaseItemParser() {
+ return new PurchaseItemProcessor();
+ }
+
+ private View view() {
+ return new View(inputView(), outputView());
+ }
+
+ private InputView inputView() {
+ return new InputView();
+ }
+
+ private OutputView outputView() {
+ return new OutputView();
+ }
+} | Java | IOC๋ฅผ ์ ์ฉํ ๋ถ๋ถ์ด ์ข์ต๋๋ค!
๋ค๋ง, ๋ฉ์๋๋ก ๋๋์ง ์์๋ ์ถฉ๋ถํ ๊ฐ๋
์ฑ ์๋ ์ฝ๋๊ฐ ๋ ์ ์์์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,34 @@
+package store.view;
+
+public enum Sentence {
+
+ PRODUCT_SELECT_STATEMENT("๊ตฌ๋งคํ์ค ์ํ๋ช
๊ณผ ์๋์ ์
๋ ฅํด ์ฃผ์ธ์. (์: [์ฌ์ด๋ค-2],[๊ฐ์์นฉ-1])"),
+ HELLO_STATEMENT("์๋
ํ์ธ์. Wํธ์์ ์
๋๋ค."),
+ CURRENT_PRODUCTS_STATEMENT("ํ์ฌ ๋ณด์ ํ๊ณ ์๋ ์ํ์
๋๋ค."),
+ NUMBER_FORMAT("#,###"),
+ PRODUCT_FORMAT("- %s %s์ "),
+ QUANTITY_FORMAT("%s๊ฐ "),
+ OUT_OF_STOCK("์ฌ๊ณ ์์ "),
+ ADDITIONAL_PURCHASE_FORMAT("ํ์ฌ %s์(๋) %d๊ฐ๋ฅผ ๋ฌด๋ฃ๋ก ๋ ๋ฐ์ ์ ์์ต๋๋ค. ์ถ๊ฐํ์๊ฒ ์ต๋๊น? (Y/N)"),
+ NO_PROMOTION_STATEMENT("ํ์ฌ %s %d๊ฐ๋ ํ๋ก๋ชจ์
ํ ์ธ์ด ์ ์ฉ๋์ง ์์ต๋๋ค. ๊ทธ๋๋ ๊ตฌ๋งคํ์๊ฒ ์ต๋๊น? (Y/N)"),
+ MEMBERSHIP_STATEMENT("๋ฉค๋ฒ์ญ ํ ์ธ์ ๋ฐ์ผ์๊ฒ ์ต๋๊น? (Y/N)"),
+ START_OF_RECEIPT("==============W ํธ์์ ================"),
+ HEADER_OF_PURCHASE("์ํ๋ช
\t\t์๋\t๊ธ์ก"),
+ PURCHASE_FORMAT("%s\t\t%s \t%s"),
+ HEADER_OF_GIVEN("=============์ฆ\t์ ==============="),
+ GIVEN_FORMAT("%s\t\t%s"),
+ DIVIDE_LINE("===================================="),
+ TOTAL_PRICE_FORMAT("์ด๊ตฌ๋งค์ก\t\t%s\t%s"),
+ PROMOTION_DISCOUNT_FORMAT("ํ์ฌํ ์ธ\t\t\t-%s"),
+ MEMBERSHIP_DISCOUNT_FORMAT("๋ฉค๋ฒ์ญํ ์ธ\t\t\t-%s"),
+ PAY_PRICE_FORMAT("๋ด์ค๋\t\t\t %s"),
+ PURCHASE_AGAIN_STATEMENT("๊ฐ์ฌํฉ๋๋ค. ๊ตฌ๋งคํ๊ณ ์ถ์ ๋ค๋ฅธ ์ํ์ด ์๋์? (Y/N)"),
+ BLANK(""),
+ NEW_LINE(System.lineSeparator());
+
+ final String message;
+
+ Sentence(final String message) {
+ this.message = message;
+ }
+} | Java | ์ข์ ์๊ฒฌ ๊ฐ์ฌํฉ๋๋ค!
์ถ๋ ฅ ๋ฌธ๊ตฌ๋ฅผ ํ
์คํธํด์ผ ํ๋์ง์ ๋ํด ๊น๊ฒ ๊ณ ๋ฏผํด ๋ณธ ์ ์ด ์๋ ๊ฒ ๊ฐ์ต๋๋ค...
๋จ๊ฒจ์ฃผ์ ๊ธ์ ์ฝ๊ณ ๋๋ ์๊ฐ์ด ๋ง์์ง๋ค์.
๋ค๋ง ์ ์๊ฒ ์์ด OutputView๋ ๋จ์ํ ๋ฐ์ดํฐ๋ฅผ ์ ๋ฌ ๋ฐ์ ์ถ๋ ฅํ๋ ์ญํ ์ ๋ด๋นํ๋ค๊ณ ์๊ฐ๋ฉ๋๋ค. ๋ฐ์ดํฐ๊ฐ ์ฌ๋ฐ๋ฅด๊ฒ ์ ๋ฌ๋๋์ง ๊ฒ์ฆํ๋ค๋ ๊ฒ์ด ์ด๋ค ์ ์์์ ๊ฒ์ฆ์ ์๋ฏธํ๋์ง ์ฌ์ญค๋ณด๊ณ ์ถ์ต๋๋ค! |
@@ -0,0 +1,42 @@
+package store.domain;
+
+public record Product(
+ String name,
+ int price,
+ Stock stock,
+ Promotion promotion) {
+
+ public int calculateTotalPrice(int quantity) {
+ return price * quantity;
+ }
+
+ public void updateStock(int purchasedQuantity) {
+ int availablePromotionStock = stock.getPromotionStock();
+ int promotionQuantity = Math.min(availablePromotionStock, purchasedQuantity);
+ int regularQuantity = purchasedQuantity - promotionQuantity;
+
+ stock.minusPromotionStock(promotionQuantity);
+ stock.minusRegularStock(regularQuantity);
+ }
+
+ public int calculatePromotionDiscount(int purchasedQuantity) {
+ if (promotion == null || !promotion.isWithinPromotionPeriod()) {
+ return 0;
+ }
+
+ int eligibleForPromotion = promotion.calculateFreeQuantity(purchasedQuantity, stock.getPromotionStock());
+ return eligibleForPromotion * price;
+ }
+
+ public int getPromotionStock() {
+ return stock.getPromotionStock();
+ }
+
+ public int getRegularStock() {
+ return stock.getRegularStock();
+ }
+
+ public int getFullStock() {
+ return getPromotionStock() + getRegularStock();
+ }
+} | Java | ๊ทธ๋ ๋ค๋ฉด dto์์๋ record๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ด ์ด์ ์ด ๋ ์ ์์๊น์?
ํ๋๋ค์ final๋ก ๊ฐ์ง๋ค๋ฉด record๋ก ๊ตฌํํ์๋๋ฐ, ์ํ๊ฐ ๋ณํ ์ ์๋ domain๋ค์ class๋ก ๊ตฌํํ๋ ๊ฒ์ด ์ข์์ง ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,13 @@
+package store.dto;
+
+import java.util.List;
+
+public record ReceiptDto(
+ List<PurchasedDto> purchasedItems,
+ List<GivenItemDto> givenItems,
+ int totalQuantity,
+ int totalPrice,
+ int promotionDiscountPrice,
+ int membershipDiscountPrice,
+ int payPrice) {
+} | Java | Builder๋ฅผ ๋ฐ๋ก ๋ง๋ค๊ธฐ์ ์๊ฐ์ด ๋ถ์กฑํ์ต๋๋ค ใ
.ใ
... ๋ฆฌํฉํ ๋งํ๋ฉฐ ๊ตฌํํด๋ณด๊ฒ ์ต๋๋ค! |
@@ -0,0 +1,42 @@
+package store.domain;
+
+public record Product(
+ String name,
+ int price,
+ Stock stock,
+ Promotion promotion) {
+
+ public int calculateTotalPrice(int quantity) {
+ return price * quantity;
+ }
+
+ public void updateStock(int purchasedQuantity) {
+ int availablePromotionStock = stock.getPromotionStock();
+ int promotionQuantity = Math.min(availablePromotionStock, purchasedQuantity);
+ int regularQuantity = purchasedQuantity - promotionQuantity;
+
+ stock.minusPromotionStock(promotionQuantity);
+ stock.minusRegularStock(regularQuantity);
+ }
+
+ public int calculatePromotionDiscount(int purchasedQuantity) {
+ if (promotion == null || !promotion.isWithinPromotionPeriod()) {
+ return 0;
+ }
+
+ int eligibleForPromotion = promotion.calculateFreeQuantity(purchasedQuantity, stock.getPromotionStock());
+ return eligibleForPromotion * price;
+ }
+
+ public int getPromotionStock() {
+ return stock.getPromotionStock();
+ }
+
+ public int getRegularStock() {
+ return stock.getRegularStock();
+ }
+
+ public int getFullStock() {
+ return getPromotionStock() + getRegularStock();
+ }
+} | Java | ์ฃผ์ด์ง ์์๋ ๊ทธ๋ ๊ณ , ๊ฐ์ ์ํ์ธ๋ฐ ๊ฐ๊ฒฉ์ด ๋ค๋ฅธ ์ํฉ์ด ์์ง ์์ ๊ฑฐ๋ผ ๊ฐ์ ํ์ต๋๋ค.
์ค์ ๋ก ํธ์์ ์์ ๋ฌผ๊ฑด์ ๊ตฌ์
ํ ๋ N + 1 ํ์ฌ๋ฅผ ํ๋ ๊ฒฝ์ฐ ์๋ก ๊ฐ๊ฒฉ์ด ๋ค๋ฅธ ๊ฒฝ์ฐ๋ ์๊ธฐ ๋๋ฌธ์
๋๋ค. |
@@ -0,0 +1,22 @@
+package store.exception;
+
+import java.util.function.Supplier;
+import store.view.OutputView;
+
+public class ExceptionHandler {
+
+ private static final int MAX_ATTEMPTS = 5;
+
+ public static <T> T getValidInput(final Supplier<T> supplier) {
+ int attempts = 0;
+ while (attempts < MAX_ATTEMPTS) {
+ try {
+ return supplier.get();
+ } catch (IllegalArgumentException e) {
+ attempts++;
+ OutputView.printErrorMessage(e.getMessage());
+ }
+ }
+ throw new IllegalArgumentException(ErrorMessage.TOO_MANY_INVALID_INPUT.message);
+ }
+}
\ No newline at end of file | Java | posix new line์ ๋ํด์ ์์๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์์ ! |
@@ -0,0 +1,90 @@
+package store.service;
+
+import java.util.List;
+import store.domain.Product;
+import store.domain.Products;
+import store.domain.PurchaseItem;
+import store.dto.GivenItemDto;
+import store.dto.PromotionDetailDto;
+import store.dto.PurchasedDto;
+import store.dto.ReceiptDto;
+import store.util.MembershipCalculator;
+import store.util.ProductLoader;
+import store.util.PurchaseItemProcessor;
+
+public class StoreService {
+
+ private final ProductLoader productLoader;
+ private final PurchaseItemProcessor purchaseItemProcessor;
+
+ public StoreService(ProductLoader productLoader, PurchaseItemProcessor purchaseItemProcessor) {
+ this.productLoader = productLoader;
+ this.purchaseItemProcessor = purchaseItemProcessor;
+ }
+
+ public Products loadProductsFromFile(String productFilePath) {
+ return productLoader.loadProducts(productFilePath);
+ }
+
+ public List<PurchaseItem> parsePurchaseItems(String inputStatement, Products products) {
+ return purchaseItemProcessor.parsePurchaseItems(inputStatement, products);
+ }
+
+ public int calculateMembershipDiscount(int currentPrice, boolean isMember) {
+ if (isMember) {
+ return MembershipCalculator.calculateMembershipDiscount(currentPrice);
+ }
+
+ return 0;
+ }
+
+ public int calculateTotalPrice(List<PurchaseItem> purchaseItems) {
+ return purchaseItems.stream()
+ .mapToInt(item -> item.getProduct().calculateTotalPrice(item.getQuantity()))
+ .sum();
+ }
+
+ public int calculatePromotionDiscount(List<PurchaseItem> purchaseItems) {
+ return purchaseItems.stream()
+ .mapToInt(purchaseItem -> purchaseItem.getProduct()
+ .calculatePromotionDiscount(purchaseItem.getQuantity()))
+ .sum();
+ }
+
+ public List<PurchasedDto> createPurchasedResults(List<PurchaseItem> purchaseItems) {
+ return purchaseItems.stream()
+ .map(PurchasedDto::from)
+ .toList();
+ }
+
+ public List<GivenItemDto> createGivenItems(List<PurchaseItem> purchaseItems) {
+ return purchaseItems.stream()
+ .map(GivenItemDto::from)
+ .toList();
+ }
+
+ public synchronized void updateProductStock(List<PurchaseItem> purchaseItems) {
+ purchaseItems.forEach(purchaseItem -> {
+ Product product = purchaseItem.getProduct();
+ int purchasedQuantity = purchaseItem.getQuantity();
+ product.updateStock(purchasedQuantity);
+ });
+ }
+
+ public PromotionDetailDto getPromotionDetail(PurchaseItem purchaseItem) {
+ return PromotionDetailDto.from(purchaseItem);
+ }
+
+ public ReceiptDto generateReceipt(List<PurchaseItem> purchaseItems, boolean isMember) {
+ int totalQuantity = purchaseItems.stream()
+ .mapToInt(PurchaseItem::getQuantity)
+ .sum();
+ int totalPrice = calculateTotalPrice(purchaseItems);
+ int promotionDiscount = calculatePromotionDiscount(purchaseItems);
+ int membershipDiscount = calculateMembershipDiscount(totalPrice - promotionDiscount, isMember);
+
+ return new ReceiptDto(createPurchasedResults(purchaseItems)
+ , createGivenItems(purchaseItems), totalQuantity, totalPrice, promotionDiscount,
+ membershipDiscount, totalPrice - promotionDiscount - membershipDiscount);
+ }
+} | Java | ๋ฏธ๋์ ๋ฉํฐ์ฐ๋ ๋ ํ๊ฒฝ๊น์ง ์๊ฐํ์ ๊ฒ ๊ฐ์์ !
ํ์ง๋ง ํ์ฌ๋ ๋จ์ผ ์ฐ๋ ๋ ํ๊ฒฝ์ด๊ธฐ ๋๋ฌธ์ ํ์ฌ ํ๊ฒฝ์ ๋ง๋ ๋๊ธฐํ๋ฅผ ์ ์งํ๋๊ฒ ์ข์ง ์์๊น์ ? ์ด๋ป๊ฒ ์๊ฐํ์๋์ง ๊ถ๊ธํด์ |
@@ -0,0 +1,36 @@
+package store.domain;
+
+public class Stock {
+
+ private int promotionStock;
+ private int regularStock;
+
+ public Stock(int promotionStock, int regularStock) {
+ this.promotionStock = promotionStock;
+ this.regularStock = regularStock;
+ }
+
+ public void minusPromotionStock(int quantity) {
+ promotionStock -= quantity;
+ }
+
+ public void minusRegularStock(int quantity) {
+ regularStock -= quantity;
+ }
+
+ public int getRegularStock() {
+ return regularStock;
+ }
+
+ public int getPromotionStock() {
+ return promotionStock;
+ }
+
+ public void setRegularStock(int regularStock) {
+ this.regularStock = regularStock;
+ }
+
+ public void setPromotionStock(int promotionStock) {
+ this.promotionStock = promotionStock;
+ }
+} | Java | Product ํด๋์ค์ ๋ถ๋ณ์ฑ์ ๊ฐ์กฐํ๊ณ ์ถ์ผ์๋ค๋ฉด Stock ํด๋์ค ๋ํ setter๋ฅผ ์ ๊ฑฐํ๊ณ ์ ๊ฐ์ฒด๋ฅผ ๋ง๋๋ ๋ฐฉ์์ผ๋ก ํ์๋๊ฑด ์ด๋จ๊น์ ? ๋ณ๋์ฑ์ด ํด ๊ฒฝ์ฐ ๋ฆฌ์์ค ์๋ชจ๊ฐ ์๊ธฐ ๋๋ฌธ์ ๊ณ ๋ คํ์๋ฉด ์ข์ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,28 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Products {
+ private List<Product> products;
+
+ public Products(
+ List<Product> products) {
+ this.products = new ArrayList<>(products);
+ }
+
+ public Product findProductByName(String name) {
+ return products.stream()
+ .filter(product -> product.name().equals(name))
+ .findFirst()
+ .orElse(null);
+ }
+
+ public void addProduct(Product product) {
+ products.add(product);
+ }
+
+ public List<Product> getProducts() {
+ return products.stream().toList();
+ }
+} | Java | ๋ฆฌ์คํธ ์์ฒด๋ ๋ณ๊ฒฝํ ์ ์์ง๋ง
`Product product = new Product("item1", 100, new Stock(10, 5), null);
product.stock().minusPromotionStock(2);` ์ฒ๋ผ ๋ด๋ถ ๊ฐ์ฒด๋ ๋ณ๊ฒฝ์ด ๊ฐ๋ฅํด์.
Stock์ ๋ถ๋ณ๊ฐ์ฒด๋ก ๋ง๋๋๊ฒ ์ข์ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,60 @@
+package store.view;
+
+import camp.nextstep.edu.missionutils.Console;
+import store.domain.Product;
+import store.exception.ErrorMessage;
+import store.exception.ValidatorBuilder;
+
+public class InputView {
+
+ private static final String YES_ANSWER = "Y";
+ private static final String NO_ANSWER = "N";
+
+ public String requestProductSelect() {
+ System.out.println(Sentence.PRODUCT_SELECT_STATEMENT.message);
+ return Console.readLine();
+ }
+
+ public String askAdditionalPurchase(Product product) {
+ System.out.printf(
+ Sentence.NEW_LINE.message + Sentence.ADDITIONAL_PURCHASE_FORMAT.message + Sentence.NEW_LINE.message,
+ product.name(), product.promotion().getGet());
+ String userInput = Console.readLine();
+
+ validateInput(userInput);
+ return userInput;
+ }
+
+ public String askNoPromotion(Product product, int shortageQuantity) {
+ System.out.printf(Sentence.NEW_LINE.message + Sentence.NO_PROMOTION_STATEMENT.message
+ + Sentence.NEW_LINE.message, product.name(), shortageQuantity);
+ String userInput = Console.readLine();
+
+ validateInput(userInput);
+ return userInput;
+ }
+
+ public String askMembership() {
+ System.out.println(Sentence.NEW_LINE.message + Sentence.MEMBERSHIP_STATEMENT.message);
+ String userInput = Console.readLine();
+
+ validateInput(userInput);
+ return userInput;
+ }
+
+ public String askPurchaseAgain() {
+ System.out.println(Sentence.NEW_LINE.message + Sentence.PURCHASE_AGAIN_STATEMENT.message);
+ String userInput = Console.readLine();
+
+ validateInput(userInput);
+ return userInput;
+ }
+
+ void validateInput(String userInput) {
+ ValidatorBuilder.from(userInput)
+ .validate(input -> input == null || input.isBlank(), ErrorMessage.INPUT_NOT_EMPTY)
+ .validate(input -> !input.equals(YES_ANSWER) && !input.equals(
+ NO_ANSWER), ErrorMessage.INVALID_YN_INPUT)
+ .get();
+ }
+} | Java | ์ปจํธ๋กค๋ฌ์์๋ ๊ฐ์ ์์๋ฅผ ์ฌ์ฉํ๋๋ฐ public์ผ๋ก ์ฌ์ฉํ๋ฉด ์ด๋จ๊น์ ? private๋ก ํ์ ์ด์ ๊ฐ ์์ผ์ ์ง ๊ถ๊ธํฉ๋๋ค ! |
@@ -0,0 +1,28 @@
+package store.dto;
+
+import store.domain.Product;
+import store.domain.PurchaseItem;
+
+public record GivenItemDto(
+ String name,
+ int freeQuantity,
+ int price) {
+
+ public static GivenItemDto from(PurchaseItem purchaseItem) {
+ Product product = purchaseItem.getProduct();
+ int freeQuantity = calculateFreeQuantity(purchaseItem);
+
+ return new GivenItemDto(product.name(), freeQuantity, product.price());
+ }
+
+ private static int calculateFreeQuantity(PurchaseItem purchaseItem) {
+ Product product = purchaseItem.getProduct();
+
+ if (product.promotion() != null) {
+ return product.promotion()
+ .calculateFreeQuantity(purchaseItem.getQuantity(), product.stock().getPromotionStock());
+ }
+
+ return 0;
+ }
+} | Java | DTO๋ ๋ฐ์ดํฐ๋ฅผ ์ ๋ฌํ๊ธฐ ์ํ ๊ฐ์ฒด๋ก ์๊ณ ์๋๋ฐ ์ด๋ ๊ฒ ์๋น์ค ๊ด๋ จ ๋ก์ง๊น์ง ๋ค์ด์์ด ์ด ๋ถ๋ถ์ ๋ฐ์ผ๋ก ๋นผ๋๊ฒ ์ข์๊ฑฐ๊ฐ์๋ฐ ์ด๋ป๊ฒ ์๊ฐํ์๋์? |
@@ -0,0 +1,28 @@
+package store.dto;
+
+import store.domain.Product;
+import store.domain.PurchaseItem;
+
+public record GivenItemDto(
+ String name,
+ int freeQuantity,
+ int price) {
+
+ public static GivenItemDto from(PurchaseItem purchaseItem) {
+ Product product = purchaseItem.getProduct();
+ int freeQuantity = calculateFreeQuantity(purchaseItem);
+
+ return new GivenItemDto(product.name(), freeQuantity, product.price());
+ }
+
+ private static int calculateFreeQuantity(PurchaseItem purchaseItem) {
+ Product product = purchaseItem.getProduct();
+
+ if (product.promotion() != null) {
+ return product.promotion()
+ .calculateFreeQuantity(purchaseItem.getQuantity(), product.stock().getPromotionStock());
+ }
+
+ return 0;
+ }
+} | Java | ์ ์ ํฉํ ๋ฆฌ ๋ฉ์๋ ํจํด์ ์ฌ์ฉํ์๋ ๊ธฐ์ค์ด ๊ถ๊ธํฉ๋๋ค! ์ธ์ ์์ฑ์๋ฅผ ์ฌ์ฉํ์๊ณ ์ธ์ ์ ์ ํฉํ ๋ฆฌ ๋ฉ์๋ ํจํด์ ์ฌ์ฉํ์๋์? |
@@ -0,0 +1,94 @@
+package store.util;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Map;
+import store.domain.Product;
+import store.domain.Products;
+import store.domain.Promotion;
+import store.domain.Stock;
+
+public class ProductLoader {
+
+ private static final String SPLITTER = ",";
+ private static final int NAME_INDEX = 0;
+ private static final int PRICE_INDEX = 1;
+ private static final int STOCK_INDEX = 2;
+ private static final int PROMOTION_INDEX = 3;
+
+ private final Map<String, Promotion> promotions;
+
+ public ProductLoader(Map<String, Promotion> promotions) {
+ this.promotions = promotions;
+ }
+
+ public Products loadProducts(String filePath) {
+ Products products = new Products(new ArrayList<>());
+ try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
+ br.readLine();
+ br.lines().forEach(line -> processLine(line, products));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ return products;
+ }
+
+ private void processLine(String line, Products products) {
+ String[] parts = line.split(SPLITTER);
+ String name = parts[NAME_INDEX];
+ int price = parseNumber(parts[PRICE_INDEX]);
+ int stockQuantity = parseNumber(parts[STOCK_INDEX]);
+ Promotion promotion = parsePromotion(parts[PROMOTION_INDEX]);
+
+ updateOrAddProduct(name, price, stockQuantity, promotion, products);
+ }
+
+ private void updateOrAddProduct(String name, int price, int stockQuantity, Promotion promotion, Products products) {
+ Product existingProduct = products.findProductByName(name);
+
+ if (existingProduct == null) {
+ addNewProduct(name, price, stockQuantity, promotion, products);
+ return;
+ }
+
+ updateStock(existingProduct, stockQuantity, promotion);
+ }
+
+ private void addNewProduct(String name, Integer price, Integer stockQuantity, Promotion promotion,
+ Products products) {
+ if (promotion != null) {
+ Stock stock = new Stock(stockQuantity, 0);
+ products.addProduct(new Product(name, price, stock, promotion));
+ return;
+ }
+
+ Stock stock = new Stock(0, stockQuantity);
+ products.addProduct(new Product(name, price, stock, promotion));
+ }
+
+ private void updateStock(Product product, int stockQuantity, Promotion promotion) {
+ Stock currentStock = product.stock();
+
+ if (promotion != null) {
+ currentStock.setPromotionStock(stockQuantity);
+ return;
+ }
+
+ currentStock.setRegularStock(stockQuantity);
+ }
+
+ private int parseNumber(String number) {
+ try {
+ return Integer.parseInt(number);
+ } catch (NumberFormatException e) {
+ throw e;
+ }
+ }
+
+ private Promotion parsePromotion(String promotionName) {
+ return promotions.get(promotionName);
+ }
+} | Java | ์ธ๋ฑ์ค๋ฅผ ์์ํํด์ ๊ฐ ์ธ๋ฑ์ค์ ์๋ฏธ๋ฅผ ์ ํํ ํ์
ํ ์ ์๋ค์! ํ๋ ๋ฐฐ์๊ฐ๋๋ค ๐ |
@@ -0,0 +1,64 @@
+package store.domain;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.time.LocalDate;
+import store.dto.PromotionDetailDto;
+
+public class Promotion {
+
+ private final String name;
+ private final int buy;
+ private final int get;
+ private final LocalDate startDate;
+ private final LocalDate endDate;
+
+ public Promotion(final String name, final int buy, final int get, final LocalDate startDate,
+ final LocalDate endDate) {
+ this.name = name;
+ this.buy = buy;
+ this.get = get;
+ this.startDate = startDate;
+ this.endDate = endDate;
+ }
+
+ public boolean isWithinPromotionPeriod() {
+ LocalDate today = DateTimes.now().toLocalDate();
+ return (today.isEqual(startDate) || today.isAfter(startDate))
+ && (today.isEqual(endDate) || today.isBefore(endDate));
+ }
+
+ public int calculateAdditionalPurchase(int purchaseQuantity) {
+ int remain = purchaseQuantity % sumOfBuyAndGet();
+
+ if (remain != 0) {
+ return sumOfBuyAndGet() - remain;
+ }
+
+ return remain;
+ }
+
+ public PromotionDetailDto calculatePromotionAndFree(int requestedQuantity, int promotionStock) {
+ int availablePromotion = (promotionStock / sumOfBuyAndGet()) * sumOfBuyAndGet();
+ return new PromotionDetailDto(availablePromotion, requestedQuantity - availablePromotion);
+ }
+
+ public int calculateFreeQuantity(int requestedQuantity, int promotionStock) {
+ if (requestedQuantity > promotionStock) {
+ return promotionStock / sumOfBuyAndGet();
+ }
+
+ return requestedQuantity / sumOfBuyAndGet();
+ }
+
+ private int sumOfBuyAndGet() {
+ return buy + get;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getGet() {
+ return get;
+ }
+} | Java | ์ข์ ์๊ฒฌ์ธ๊ฑฐ ๊ฐ์ต๋๋ค! ์ ๋ ํ๋ ๋ฐฐ์๊ฐ๋ค์ |
@@ -0,0 +1,28 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Products {
+ private List<Product> products;
+
+ public Products(
+ List<Product> products) {
+ this.products = new ArrayList<>(products);
+ }
+
+ public Product findProductByName(String name) {
+ return products.stream()
+ .filter(product -> product.name().equals(name))
+ .findFirst()
+ .orElse(null);
+ }
+
+ public void addProduct(Product product) {
+ products.add(product);
+ }
+
+ public List<Product> getProducts() {
+ return products.stream().toList();
+ }
+} | Java | ์ ๋ null์ ๋ฐํํ๋ ๊ฒ๋ณด๋ค Optional์ ํตํด null์ด ๋ฐ์ํ ์ ์์์ ํ์คํ ์๋ฆฌ๋ ๊ฒ์ ์ ํธํฉ๋๋ค. ํ์ฌ๋ ๊ฐ์ธ ํผ์ ๊ฐ๋ฐํ๊ธฐ์ null์ด ๋ฐ์ํ ์ ์์์ ์๊ณ ๋ก์ง์ ์์ฑํ ์ ์์ต๋๋ค. ํ์ง๋ง ๋ง์ฝ ํ์
์ํฉ์์ ์ฒ์ ํด๋์ค์ ๋ฉ์๋๋ฅผ ๋ณด๋ฉด ๋ณดํต ๋ฉ์๋ ๋ช
, ํ๋ผ๋ฏธํฐ, ๋ฆฌํด ํ์
์ผ๋ก ๋ฉ์๋์ ์ญํ ๊ณผ ๊ธฐ๋ฅ์ ํ์
ํ๊ฒ ๋๋๋ฐ null์ด ๋ฐ์ํ๋์ง ๋ก์ง์ ์ธ๋ถ์ ์ผ๋ก ์ฝ์ด๋ด์ผํ๋ ์ํฉ์ด ๋ฐ์ํฉ๋๋ค. ์ด์ ๋๋นํ์ฌ Optional์ ํตํด null์ด ๋ฐ์ํ ์ ์์์ ์๋ฆฝ๋๋ค! ์ ์ ๊ฐ์ธ์ ์ธ ์๊ฐ์ด๋ ์ฐธ๊ณ ๋ง ๋ถํ๋๋ฆด๊ฒ์ ใ
ใ
๐ |
@@ -0,0 +1,50 @@
+package store.exception;
+
+import java.util.function.Predicate;
+
+public class ValidatorBuilder<T> {
+
+ private final T value;
+ private int numericValue;
+
+ private ValidatorBuilder(final T Value) {
+ this.value = Value;
+ }
+
+ public static <T> ValidatorBuilder<T> from(final T Value) {
+ return new ValidatorBuilder<T>(Value);
+ }
+
+ public ValidatorBuilder<T> validate(final Predicate<T> condition, final ErrorMessage errorMessage) {
+ if (condition.test(value)) {
+ throw new IllegalArgumentException(errorMessage.message);
+ }
+
+ return this;
+ }
+
+ public ValidatorBuilder<T> validateInteger(final Predicate<Integer> condition, final ErrorMessage errorMessage) {
+ if (condition.test(numericValue)) {
+ throw new IllegalArgumentException(errorMessage.message);
+ }
+
+ return this;
+ }
+
+ public ValidatorBuilder<T> validateIsInteger() {
+ try {
+ numericValue = Integer.parseInt(value.toString());
+ return this;
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(ErrorMessage.PURCHASE_QUANTITY_NOT_INTEGER.message);
+ }
+ }
+
+ public T get() {
+ return value;
+ }
+
+ public int getNumericValue() {
+ return numericValue;
+ }
+} | Java | ์ ๋ค๋ฆญ ํ์ฉ์ ์ ํ์๋ค์! ๐ |
@@ -0,0 +1,66 @@
+package christmas.domain;
+
+import static christmas.exception.ErrorMessage.DAY_NOT_IN_RANGE;
+import static christmas.exception.ErrorMessage.ENDS_WITH_DELIMITER;
+
+import christmas.domain.constant.EventConstraint;
+import christmas.exception.OrderException;
+
+public class Day {
+ private final int day;
+
+ private Day(int day) {
+ this.day = day;
+ validate();
+ }
+
+ public static Day of(int day){
+ return new Day(day);
+ }
+
+ public int getDDayDiscountAmount(){
+ if(isBeforeDDay()){
+ return EventConstraint.INITIAL_D_DAY_DISCOUNT_AMOUNT.getValue() + (day-1) * 100;
+ }
+ return 0;
+ }
+
+ public boolean isBeforeDDay(){
+ return day <= EventConstraint.D_DAY.getValue();
+ }
+
+ public boolean isWeekDay(){
+ for (int i = 1; i <= 30; i += 7) {
+ if (day == i || day == i + 1) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public boolean isWeekEnd(){
+ for (int i = 1; i <= 30; i += 7) {
+ if (day == i || day == i + 1) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public boolean hasStar(){
+ if(day == 25)return true;
+ for(int i = 3; i <= 31; i += 7){
+ if(day == i)return true;
+ }
+ return false;
+ }
+
+ public void validate(){
+ validateEventPeriod();
+ }
+ private void validateEventPeriod(){
+ if (day < EventConstraint.MIN_DAY.getValue() || day > EventConstraint.MAX_DAY.getValue()) {
+ throw OrderException.from(DAY_NOT_IN_RANGE);
+ }
+ }
+} | Java | EventConstraint์์ ์ ์ธํ ์์๋ฅผ ๊ฐ์ ธ๋ค ์ฐ์ง ์์ ์ด์ ๊ฐ ์๋์? |
@@ -0,0 +1,64 @@
+package christmas.domain;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import christmas.domain.constant.EventConstraint;
+import christmas.exception.ErrorMessage;
+import christmas.exception.OrderException;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+public class DayTest {
+
+ @DisplayName("Day ๊ฐ์ฒด๋ฅผ ์ฌ๋ฐ๋ฅด๊ฒ ์์ฑํ๋์ง ํ
์คํธ")
+ @Test
+ void createDay() {
+ assertThat(Day.of(5)).isNotNull();
+ }
+
+ @DisplayName("Day ๊ฐ์ฒด๋ฅผ ์์ฑํ ๋ day๊ฐ ์ ํจํ ๋ฒ์ ๋ด์ธ์ง ํ์ธ")
+ @Test
+ void createDayWithInvalidDay() {
+ assertThatThrownBy(() -> Day.of(40))
+ .isInstanceOf(OrderException.class)
+ .hasMessageContaining(ErrorMessage.DAY_NOT_IN_RANGE.getMessage());
+ }
+
+ @DisplayName("getDDayDiscountAmount ๋ฉ์๋ ํ
์คํธ")
+ @Test
+ void getDDayDiscountAmount() {
+ assertThat(Day.of(24).getDDayDiscountAmount()).isEqualTo(
+ EventConstraint.INITIAL_D_DAY_DISCOUNT_AMOUNT.getValue() + (24-1) * 100);
+ assertThat(Day.of(26).getDDayDiscountAmount()).isEqualTo(0);
+ }
+
+ @DisplayName("isBeforeDDay ๋ฉ์๋ ํ
์คํธ")
+ @Test
+ void isBeforeDDay() {
+ assertThat(Day.of(24).isBeforeDDay()).isTrue();
+ assertThat(Day.of(26).isBeforeDDay()).isFalse();
+ }
+
+ @DisplayName("isWeekDay ๋ฉ์๋ ํ
์คํธ")
+ @Test
+ void isWeekDay() {
+ assertThat(Day.of(5).isWeekDay()).isTrue();
+ assertThat(Day.of(8).isWeekDay()).isFalse();
+ }
+
+ @DisplayName("isWeekEnd ๋ฉ์๋ ํ
์คํธ")
+ @Test
+ void isWeekEnd() {
+ assertThat(Day.of(5).isWeekEnd()).isFalse();
+ assertThat(Day.of(8).isWeekEnd()).isTrue();
+ }
+
+ @DisplayName("hasStar ๋ฉ์๋ ํ
์คํธ")
+ @Test
+ void hasStar() {
+ assertThat(Day.of(25).hasStar()).isTrue();
+ assertThat(Day.of(26).hasStar()).isFalse();
+ }
+}
+ | Java | @ParamiterizedTest์ ์ด๋
ธํ
์ด์
์ ํ์ฉํด์ ์ค๋ณต์ ์ค์ผ ์ ์์๊ฑฐ ๊ฐ์ต๋๋ค. |
@@ -26,11 +26,32 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
- compileOnly 'org.projectlombok:lombok'
+ implementation 'org.springframework.boot:spring-boot-starter-security'
+ implementation 'org.springframework.boot:spring-boot-starter-validation'
+ implementation 'org.springframework.boot:spring-boot-starter-mail'
+
+ // jwt
+ implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.5'
+ runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.5'
+ runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.5'
+
+ // MapStruct
+ implementation 'org.mapstruct:mapstruct:1.4.2.Final'
+ annotationProcessor "org.mapstruct:mapstruct-processor:1.4.2.Final"
+ annotationProcessor "org.projectlombok:lombok-mapstruct-binding:0.1.0"
+
+ // H2
runtimeOnly 'com.h2database:h2'
+
+ // Lombok
+ compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
+
+ // Test
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
+
+
}
tasks.named('test') { | Unknown | Gradle ํ์์ด ์ผ์นํ์ง ์์ต๋๋ค.
๋ค๋ฅธ ๊ณณ๊ณผ ๋์ผํ๊ฒ ์กฐ์ ํด์ฃผ์ธ์.
```groovy
implementaion 'io.jsonwebtoken:jjwt-api:0.11.5'
``` |
@@ -0,0 +1,83 @@
+package io.study.springbootlayered.api.member.application;
+
+import java.security.SecureRandom;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import java.util.stream.Collectors;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import io.study.springbootlayered.api.member.domain.MemberProcessor;
+import io.study.springbootlayered.api.member.domain.dto.MemberPasswordResetDto;
+import io.study.springbootlayered.api.member.domain.event.ResetPasswordEvent;
+import io.study.springbootlayered.web.base.Events;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@Service
+@RequiredArgsConstructor
+@Transactional(readOnly = true)
+public class MemberResetService {
+
+ private final MemberProcessor memberProcessor;
+
+ private static final String VALID_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ private static final String SPECIAL_CHARACTERS = "!@#$%^&*()\\-_=+";
+ private static final int MAX_SPECIAL_CHARACTER = 3;
+ private static final int MIN_LENGTH = 8;
+ private static final int MAX_LENGTH = 16;
+
+ @Transactional
+ public void resetPassword(final MemberPasswordResetDto.Command request) {
+ String resetPassword = createResetPassword();
+
+ memberProcessor.resetPassword(new MemberPasswordResetDto.Command(request.getEmail(), resetPassword));
+
+ Events.raise(ResetPasswordEvent.of(request.getEmail(), resetPassword));
+ }
+
+ public String createResetPassword() {
+ Random random = new SecureRandom();
+ final int passwordLength = MIN_LENGTH + random.nextInt(MAX_LENGTH - MIN_LENGTH + 1);
+ StringBuilder password = new StringBuilder(passwordLength);
+
+ int specialCharacterLength = addSpecialCharacters(password);
+ addValidCharacters(specialCharacterLength, passwordLength, password);
+
+ return shufflePassword(password);
+ }
+
+ private String shufflePassword(final StringBuilder password) {
+ List<Character> characters = password.toString().chars()
+ .mapToObj(i -> (char)i)
+ .collect(Collectors.toList());
+ Collections.shuffle(characters);
+ StringBuilder result = new StringBuilder(characters.size());
+ characters.forEach(result::append);
+
+ return result.toString();
+ }
+
+ private void addValidCharacters(final int specialCharacterLength, final int passwordLength,
+ final StringBuilder password) {
+ Random random = new SecureRandom();
+ for (int i = specialCharacterLength; i < passwordLength; i++) {
+ int index = random.nextInt(VALID_CHARACTERS.length());
+ password.append(VALID_CHARACTERS.charAt(index));
+ }
+ }
+
+ private int addSpecialCharacters(final StringBuilder password) {
+ Random random = new SecureRandom();
+ final int specialCharacterLength = random.nextInt(MAX_SPECIAL_CHARACTER) + 1;
+
+ for (int i = 0; i < specialCharacterLength; i++) {
+ password.append(SPECIAL_CHARACTERS.charAt(random.nextInt(SPECIAL_CHARACTERS.length())));
+ }
+
+ return specialCharacterLength;
+ }
+} | Java | `@Transactional` ์ด๋
ธํ
์ด์
์ ํด๋์ค ๋ ๋ฒจ๋ก ์ฌ๋ฆฌ๋๊ฒ ๋ง๋์ง์ ๋ํด์๋ ์๋ฌธ์ด ๋ญ๋๋ค.
- DB์ ์ ๊ทผํ์ง ์๋ ๋ฉ์๋๋ฅผ ์ํํ ๋๋ `@Transactional` ์ ์ํด ์๋ค๋ก ์ถ๊ฐ ๋ก์ง์ด ์คํ๋๋ฉฐ.
- readonly ๊ฐ ์๋ ๊ฒฝ์ฐ์ ์๋์์ ์ด์ฐจํผ ๋ ์ฌ์ฉํ๋์ง๋ผ ๋ถํ์ํ ์ฝ๋๊ฐ ๋์ด๋๋๊ฒ ์๋๊ฐ ์ถ์ต๋๋ค. |
@@ -0,0 +1,30 @@
+package io.study.springbootlayered.api.member.domain.dto;
+
+import java.util.List;
+
+import io.study.springbootlayered.api.member.domain.entity.AuthorityType;
+import io.study.springbootlayered.api.member.domain.entity.Member;
+import io.study.springbootlayered.api.member.domain.entity.MemberAuthority;
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.RequiredArgsConstructor;
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class MemberDetailDto {
+
+ @Getter
+ @RequiredArgsConstructor
+ public static class Info {
+ private final String email;
+ private final String nickname;
+ private final List<AuthorityType> roles;
+
+ public static MemberDetailDto.Info of(Member member) {
+ List<AuthorityType> roles = member.getAuthorities().stream()
+ .map(MemberAuthority::getAuthority)
+ .toList();
+ return new MemberDetailDto.Info(member.getEmail(), member.getNickname(), roles);
+ }
+ }
+} | Java | Gradle ์ค์ ์ ์ํ๋ฉด Java ๋ฒ์ ์ด 21์ธ๋ฐ, ์ถฉ๋ถํ Record๋ก ๋์ฒด ๊ฐ๋ฅํ ์ฝ๋๋ก ๋ณด์
๋๋ค. |
@@ -0,0 +1,30 @@
+package io.study.springbootlayered.api.member.domain.dto;
+
+import java.util.List;
+
+import io.study.springbootlayered.api.member.domain.entity.AuthorityType;
+import io.study.springbootlayered.api.member.domain.entity.Member;
+import io.study.springbootlayered.api.member.domain.entity.MemberAuthority;
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.RequiredArgsConstructor;
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class MemberDetailDto {
+
+ @Getter
+ @RequiredArgsConstructor
+ public static class Info {
+ private final String email;
+ private final String nickname;
+ private final List<AuthorityType> roles;
+
+ public static MemberDetailDto.Info of(Member member) {
+ List<AuthorityType> roles = member.getAuthorities().stream()
+ .map(MemberAuthority::getAuthority)
+ .toList();
+ return new MemberDetailDto.Info(member.getEmail(), member.getNickname(), roles);
+ }
+ }
+} | Java | Validation ์ ์ฌ์ฉํด์ ๋น๊ฐ์ด ๋ค์ด์ค์ง ์๋๋ก ํ๋ฉด ์ข๊ฒ ๋ค์. |
@@ -0,0 +1,19 @@
+package io.study.springbootlayered.api.member.domain.dto;
+
+import lombok.AccessLevel;
+import lombok.Builder;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.RequiredArgsConstructor;
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class MemberPasswordResetDto {
+
+ @Getter
+ @Builder
+ @RequiredArgsConstructor
+ public static class Command {
+ private final String email;
+ private final String password;
+ }
+} | Java | ํ๋๊ฐ ๋๊ฐ์ธ๋ฐ ๊ตณ์ด ๋น๋๋ฅผ ์ฌ์ฉํด์ผ ํ๋ ์ถ์๋ฐ์,
๋น์ฅ ๋ฐ๋ก ์๋์ MemberSigninDto ์์๋ `@Builder`๊ฐ ์๋ค์. |
@@ -0,0 +1,19 @@
+package io.study.springbootlayered.api.member.domain.dto;
+
+import lombok.AccessLevel;
+import lombok.Builder;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.RequiredArgsConstructor;
+
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class MemberPasswordResetDto {
+
+ @Getter
+ @Builder
+ @RequiredArgsConstructor
+ public static class Command {
+ private final String email;
+ private final String password;
+ }
+} | Java | ๋ชจ๋ Dto๊ฐ ๋ด๋ถ์ ์ผ๋ก ๋ Dto๋ฅผ ๊ฐ๊ณ ์๋ ์ด์ํ ๊ตฌ์กฐ๋ค์...
๊ทธ๋ฅ ์๋ก ๋ค๋ฅธ ํ์ผ๋ก ๋ถ๋ฆฌํ๋๊ฒ ๊ฐ๋
์ฑ ์ธก๋ฉด์์ ๋ ๋ซ์ง ์์๊น์?
ํนํ๋ ๋ด๋ถ์ ์ผ๋ก ๊ฐ์ ์ด๋ฆ์ ์ฐ๊ณ ์๊ธฐ ๋๋ฌธ์, ํ์ฌ๋ ์ค์๋ก Static Import๋ฅผ ํ๋ ์๊ฐ ์ด๊ฒ ์ด๋์์ ์จ๊ฑด์ง ํ์
ํ ๋ฐฉ๋ฒ์ด ์์ ์์ด์ง๋๋ค. |
@@ -0,0 +1,83 @@
+package io.study.springbootlayered.api.member.application;
+
+import java.security.SecureRandom;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import java.util.stream.Collectors;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import io.study.springbootlayered.api.member.domain.MemberProcessor;
+import io.study.springbootlayered.api.member.domain.dto.MemberPasswordResetDto;
+import io.study.springbootlayered.api.member.domain.event.ResetPasswordEvent;
+import io.study.springbootlayered.web.base.Events;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@Service
+@RequiredArgsConstructor
+@Transactional(readOnly = true)
+public class MemberResetService {
+
+ private final MemberProcessor memberProcessor;
+
+ private static final String VALID_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ private static final String SPECIAL_CHARACTERS = "!@#$%^&*()\\-_=+";
+ private static final int MAX_SPECIAL_CHARACTER = 3;
+ private static final int MIN_LENGTH = 8;
+ private static final int MAX_LENGTH = 16;
+
+ @Transactional
+ public void resetPassword(final MemberPasswordResetDto.Command request) {
+ String resetPassword = createResetPassword();
+
+ memberProcessor.resetPassword(new MemberPasswordResetDto.Command(request.getEmail(), resetPassword));
+
+ Events.raise(ResetPasswordEvent.of(request.getEmail(), resetPassword));
+ }
+
+ public String createResetPassword() {
+ Random random = new SecureRandom();
+ final int passwordLength = MIN_LENGTH + random.nextInt(MAX_LENGTH - MIN_LENGTH + 1);
+ StringBuilder password = new StringBuilder(passwordLength);
+
+ int specialCharacterLength = addSpecialCharacters(password);
+ addValidCharacters(specialCharacterLength, passwordLength, password);
+
+ return shufflePassword(password);
+ }
+
+ private String shufflePassword(final StringBuilder password) {
+ List<Character> characters = password.toString().chars()
+ .mapToObj(i -> (char)i)
+ .collect(Collectors.toList());
+ Collections.shuffle(characters);
+ StringBuilder result = new StringBuilder(characters.size());
+ characters.forEach(result::append);
+
+ return result.toString();
+ }
+
+ private void addValidCharacters(final int specialCharacterLength, final int passwordLength,
+ final StringBuilder password) {
+ Random random = new SecureRandom();
+ for (int i = specialCharacterLength; i < passwordLength; i++) {
+ int index = random.nextInt(VALID_CHARACTERS.length());
+ password.append(VALID_CHARACTERS.charAt(index));
+ }
+ }
+
+ private int addSpecialCharacters(final StringBuilder password) {
+ Random random = new SecureRandom();
+ final int specialCharacterLength = random.nextInt(MAX_SPECIAL_CHARACTER) + 1;
+
+ for (int i = 0; i < specialCharacterLength; i++) {
+ password.append(SPECIAL_CHARACTERS.charAt(random.nextInt(SPECIAL_CHARACTERS.length())));
+ }
+
+ return specialCharacterLength;
+ }
+} | Java | ๊ฒฐ๊ตญ `SpecialCharactes` ์ `ValidCharacters` ์ ์กฐํฉ์ผ๋ก ๊ตฌ์ฑ๋๋ค๊ณ ๋ณผ ์ ์๊ฒ ๋ค์.
- ์ด์ฐจํผ ๋ฌธ์์ด ์๋๊ฑด ๋๊ฐ์ต๋๋ค.
```java
private String createRandomString(String baseStr, int length) {
return random.ints(length, 0, baseStr.length())
.mapToObj(baseStr::charAt)
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString();
}
```
- ๊ทธ๋ฌ๋ฉด, ์ฐ๋ฆฌ๋ ๊ธธ์ด๋ง ์ ํ๋ฉด ๋๊ฒ ๋ค์. ๊ตณ์ด ๋ถ๋ฆฌ๋ ๋ฉ์๋๊ฐ ์๋๋ผ, ์ ๋์ ๊ธธ์ด๋ฅผ ๋ฏธ๋ฆฌ ์ ํ๊ณ ์ ๋ฉ์๋๋ฅผ ํธ์ถํด๋ฒ๋ฆฌ๋ฉด ํจ์ฌ ๋ซ๊ฒ ์ฃ ? |
@@ -0,0 +1,83 @@
+package io.study.springbootlayered.api.member.application;
+
+import java.security.SecureRandom;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import java.util.stream.Collectors;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import io.study.springbootlayered.api.member.domain.MemberProcessor;
+import io.study.springbootlayered.api.member.domain.dto.MemberPasswordResetDto;
+import io.study.springbootlayered.api.member.domain.event.ResetPasswordEvent;
+import io.study.springbootlayered.web.base.Events;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@Service
+@RequiredArgsConstructor
+@Transactional(readOnly = true)
+public class MemberResetService {
+
+ private final MemberProcessor memberProcessor;
+
+ private static final String VALID_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ private static final String SPECIAL_CHARACTERS = "!@#$%^&*()\\-_=+";
+ private static final int MAX_SPECIAL_CHARACTER = 3;
+ private static final int MIN_LENGTH = 8;
+ private static final int MAX_LENGTH = 16;
+
+ @Transactional
+ public void resetPassword(final MemberPasswordResetDto.Command request) {
+ String resetPassword = createResetPassword();
+
+ memberProcessor.resetPassword(new MemberPasswordResetDto.Command(request.getEmail(), resetPassword));
+
+ Events.raise(ResetPasswordEvent.of(request.getEmail(), resetPassword));
+ }
+
+ public String createResetPassword() {
+ Random random = new SecureRandom();
+ final int passwordLength = MIN_LENGTH + random.nextInt(MAX_LENGTH - MIN_LENGTH + 1);
+ StringBuilder password = new StringBuilder(passwordLength);
+
+ int specialCharacterLength = addSpecialCharacters(password);
+ addValidCharacters(specialCharacterLength, passwordLength, password);
+
+ return shufflePassword(password);
+ }
+
+ private String shufflePassword(final StringBuilder password) {
+ List<Character> characters = password.toString().chars()
+ .mapToObj(i -> (char)i)
+ .collect(Collectors.toList());
+ Collections.shuffle(characters);
+ StringBuilder result = new StringBuilder(characters.size());
+ characters.forEach(result::append);
+
+ return result.toString();
+ }
+
+ private void addValidCharacters(final int specialCharacterLength, final int passwordLength,
+ final StringBuilder password) {
+ Random random = new SecureRandom();
+ for (int i = specialCharacterLength; i < passwordLength; i++) {
+ int index = random.nextInt(VALID_CHARACTERS.length());
+ password.append(VALID_CHARACTERS.charAt(index));
+ }
+ }
+
+ private int addSpecialCharacters(final StringBuilder password) {
+ Random random = new SecureRandom();
+ final int specialCharacterLength = random.nextInt(MAX_SPECIAL_CHARACTER) + 1;
+
+ for (int i = 0; i < specialCharacterLength; i++) {
+ password.append(SPECIAL_CHARACTERS.charAt(random.nextInt(SPECIAL_CHARACTERS.length())));
+ }
+
+ return specialCharacterLength;
+ }
+} | Java | ๋งค๋ฒ Random ๊ฐ์ฒด๋ฅผ ์์ฑํ์ง ๋ง๊ณ , ๊ทธ๋ฅ ์ต์๋จ์ private final ๋ก ์ฌ๋ ค๋ฒ๋ฆฌ์ธ์.
`private final Random random = new SecureRandom();` |
@@ -0,0 +1,32 @@
+package io.study.springbootlayered.api.member.application;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import io.study.springbootlayered.api.member.domain.MemberProcessor;
+import io.study.springbootlayered.api.member.domain.dto.MemberSignupDto;
+import io.study.springbootlayered.api.member.domain.event.SignupEvent;
+import io.study.springbootlayered.web.base.Events;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@Service
+@RequiredArgsConstructor
+@Transactional(readOnly = true)
+public class MemberSignupService {
+
+ private final MemberProcessor memberProcessor;
+
+ @Transactional
+ public MemberSignupDto.Info signup(final MemberSignupDto.Command request) {
+ /** ํ์ ๊ฐ์
**/
+ MemberSignupDto.Info info = memberProcessor.register(request);
+
+ /** ํ์๊ฐ์
์๋ฃ ํ ์ด๋ฉ์ผ ์ ์ก **/
+ String registeredEmail = info.getEmail();
+ Events.raise(SignupEvent.of(registeredEmail));
+
+ return info;
+ }
+} | Java | ์ธ๋ผ์ธ ์ฃผ์์ // ๊ฐ ์ข๊ฒ ์ฃ ? |
@@ -0,0 +1,23 @@
+package io.study.springbootlayered.api.member.domain.entity;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Embeddable;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+
+@Embeddable
+@Getter
+@EqualsAndHashCode
+public class MemberPassword {
+
+ @Column(name = "password", nullable = false)
+ private String value;
+
+ protected MemberPassword() {
+ }
+
+ public MemberPassword(final String value) {
+ this.value = value;
+ }
+
+} | Java | ์์๋ Equals์ hashCode๋ฅผ ์ง์ ์ ์ํ๋๋, ์ด๋ฒ์๋ ๋กฌ๋ณต์ ์ฌ์ฉํ๋ค์? |
@@ -0,0 +1,42 @@
+package io.study.springbootlayered.api.member.domain.event;
+
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.event.TransactionalEventListener;
+
+import io.study.springbootlayered.infra.mail.MailService;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@Component
+@RequiredArgsConstructor
+public class MemberEventListener {
+
+ private final MailService mailService;
+
+ @Async
+ @TransactionalEventListener
+ public void signupEventListener(final SignupEvent event) {
+ log.info("MemberEventListener.signupEventListener !!");
+
+ String[] toEmail = toEmailArray(event.getEmail());
+ mailService.sendMail(toEmail, "ํ์๊ฐ์
์๋ฃ ์๋ด", "ํ์๊ฐ์
์ด ์๋ฃ๋์์ต๋๋ค.");
+ }
+
+ private String[] toEmailArray(final String... email) {
+ return email;
+ }
+
+ @Async
+ @TransactionalEventListener
+ public void resetPasswordEventListener(final ResetPasswordEvent event) {
+ log.info("MemberEventListener.resetPasswordEventListener !!");
+
+ String[] toEmail = toEmailArray(event.getEmail());
+ String password = event.getTempPassword();
+
+ mailService.sendMail(toEmail, "์์ ๋น๋ฐ๋ฒํธ ๋ฐ๊ธ ์๋ด", "์์ ๋น๋ฐ๋ฒํธ : " + password);
+ }
+
+} | Java | ์ผ๋ฐ์ ์ผ๋ก ๊ฐ๋ฐ ํ๊ฒฝ์์๋ log level์ debug๋ก, ์ด์ ํ๊ฒฝ์์๋ info/warn ์์ค์ผ๋ก ์ค์ ํฉ๋๋ค.
์ด์ ํ๊ฒฝ์์ ํด๋น ์์ฒญ์ด ๋ค์ด์ฌ "๋ ๋ง๋ค" ํด๋น ๋ก๊ทธ๊ฐ ์ถ๋ ฅ๋๊ฒ ๋๋ฉด, ์๋ฌ ๋๋ฒ๊น
๊ณผ์ ์์ ๋งค์ฐ ๋ฒ๊ฑฐ๋ก์์ง ํ๋ฅ ์ด ๋์ต๋๋ค.
๊ฐ๋ฐ ๊ณผ์ ์์์ ๋๋ฒ๊น
์ฉ์ธ์ง, ์ด์ ํ๊ฒฝ์์ ์ค์ ๋ก ํ์ํ ๋ก๊ทธ์ธ์ง ์ ์๊ฐํด๋ณด์๊ณ ๋ก๊ทธ ๋ ๋ฒจ์ ์ง์ ํ๋๊ฒ ์ข์ต๋๋ค. |
@@ -0,0 +1,15 @@
+package io.study.springbootlayered.api.member.domain.event;
+
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+
+@Getter
+@RequiredArgsConstructor
+public class SignupEvent {
+
+ private final String email;
+
+ public static SignupEvent of(String email) {
+ return new SignupEvent(email);
+ }
+} | Java | ์์ฑ์๋ ์ญํ ์ด ๋๊ฐ๋ค์. |
@@ -0,0 +1,63 @@
+package io.study.springbootlayered.api.member.domain;
+
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.stereotype.Component;
+
+import io.study.springbootlayered.api.member.domain.dto.MemberDetailDto;
+import io.study.springbootlayered.api.member.domain.dto.MemberPasswordResetDto;
+import io.study.springbootlayered.api.member.domain.dto.MemberSignupDto;
+import io.study.springbootlayered.api.member.domain.entity.Member;
+import io.study.springbootlayered.api.member.domain.repository.MemberQueryRepository;
+import io.study.springbootlayered.api.member.domain.repository.MemberRepository;
+import io.study.springbootlayered.api.member.domain.validation.MemberValidator;
+import io.study.springbootlayered.web.exception.ApiException;
+import io.study.springbootlayered.web.exception.error.MemberErrorCode;
+import lombok.RequiredArgsConstructor;
+
+@Component
+@RequiredArgsConstructor
+public class MemberProcessorImpl implements MemberProcessor {
+
+ private final MemberQueryRepository memberQueryRepository;
+ private final MemberRepository memberRepository;
+ private final PasswordEncoder passwordEncoder;
+ private final MemberValidator memberValidator;
+
+ @Override
+ public MemberSignupDto.Info register(final MemberSignupDto.Command request) {
+ memberValidator.signinValidate(request);
+ Member initBasicMember = Member.createBasicMember(request.getEmail(), request.getNickname(),
+ encodePassword(request.getPassword()));
+ Member savedMember = memberRepository.save(initBasicMember);
+
+ return new MemberSignupDto.Info(savedMember.getEmail());
+ }
+
+ @Override
+ public MemberDetailDto.Info getMember(final Long memberId) {
+ Member findMember = findById(memberId);
+
+ return MemberDetailDto.Info.of(findMember);
+ }
+
+ @Override
+ public void resetPassword(final MemberPasswordResetDto.Command command) {
+ Member findMember = findByEmail(command.getEmail());
+ findMember.changePassword(encodePassword(command.getPassword()));
+ }
+
+ private Member findById(final Long memberId) {
+ return memberQueryRepository.findById(memberId)
+ .orElseThrow(() -> new ApiException(MemberErrorCode.NOT_FOUND_MEMBER));
+ }
+
+ private Member findByEmail(final String email) {
+ return memberQueryRepository.findByEmail(email)
+ .orElseThrow(() -> new ApiException(MemberErrorCode.NOT_FOUND_MEMBER));
+ }
+
+ private String encodePassword(final String password) {
+ return passwordEncoder.encode(password);
+ }
+
+} | Java | ~~Impl ํ์์ ํด๋์ค์ ์กด์ฌ ์ฌ๋ถ๋ฅผ ์ดํดํ๊ธด ์ด๋ ต๋ค์.
- ๋ค๋ฅธ ๊ตฌํ์ฒด์ ๊ฐ๋ฅ์ฑ์ด ์กด์ฌํ๋์?
- ์์ ๋ค๋ฅธ Processor๋ ๋ง์ ํ ํด๋์ค๋ฅผ ์์ํ๋ ๊ตฌ์กฐ๋ผ Impl์ ์ ๋ฌ๊ณ ์๋ค์. |
@@ -0,0 +1,63 @@
+package io.study.springbootlayered.api.member.domain;
+
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.stereotype.Component;
+
+import io.study.springbootlayered.api.member.domain.dto.MemberDetailDto;
+import io.study.springbootlayered.api.member.domain.dto.MemberPasswordResetDto;
+import io.study.springbootlayered.api.member.domain.dto.MemberSignupDto;
+import io.study.springbootlayered.api.member.domain.entity.Member;
+import io.study.springbootlayered.api.member.domain.repository.MemberQueryRepository;
+import io.study.springbootlayered.api.member.domain.repository.MemberRepository;
+import io.study.springbootlayered.api.member.domain.validation.MemberValidator;
+import io.study.springbootlayered.web.exception.ApiException;
+import io.study.springbootlayered.web.exception.error.MemberErrorCode;
+import lombok.RequiredArgsConstructor;
+
+@Component
+@RequiredArgsConstructor
+public class MemberProcessorImpl implements MemberProcessor {
+
+ private final MemberQueryRepository memberQueryRepository;
+ private final MemberRepository memberRepository;
+ private final PasswordEncoder passwordEncoder;
+ private final MemberValidator memberValidator;
+
+ @Override
+ public MemberSignupDto.Info register(final MemberSignupDto.Command request) {
+ memberValidator.signinValidate(request);
+ Member initBasicMember = Member.createBasicMember(request.getEmail(), request.getNickname(),
+ encodePassword(request.getPassword()));
+ Member savedMember = memberRepository.save(initBasicMember);
+
+ return new MemberSignupDto.Info(savedMember.getEmail());
+ }
+
+ @Override
+ public MemberDetailDto.Info getMember(final Long memberId) {
+ Member findMember = findById(memberId);
+
+ return MemberDetailDto.Info.of(findMember);
+ }
+
+ @Override
+ public void resetPassword(final MemberPasswordResetDto.Command command) {
+ Member findMember = findByEmail(command.getEmail());
+ findMember.changePassword(encodePassword(command.getPassword()));
+ }
+
+ private Member findById(final Long memberId) {
+ return memberQueryRepository.findById(memberId)
+ .orElseThrow(() -> new ApiException(MemberErrorCode.NOT_FOUND_MEMBER));
+ }
+
+ private Member findByEmail(final String email) {
+ return memberQueryRepository.findByEmail(email)
+ .orElseThrow(() -> new ApiException(MemberErrorCode.NOT_FOUND_MEMBER));
+ }
+
+ private String encodePassword(final String password) {
+ return passwordEncoder.encode(password);
+ }
+
+} | Java | ํด๋น ์ฟผ๋ฆฌ๊ฐ ๋ค๋ฅธ ๊ณณ์์ ์ฌ์ฌ์ฉ๋์ง ์์ ๊ฒ์ด๋ผ๋ ๋ณด์ฅ์ด ์๋์?
์ด๋ฐ ๊ธฐ๋ณธ์ ์ธ Validation ์ฉ ์ฟผ๋ฆฌ๋ ๋ถ๋ฆฌํด์ ๋ค๋ฃจ๋๊ฒ ์ข์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,32 @@
+package io.study.springbootlayered.api.member.application;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import io.study.springbootlayered.api.member.domain.MemberProcessor;
+import io.study.springbootlayered.api.member.domain.dto.MemberSignupDto;
+import io.study.springbootlayered.api.member.domain.event.SignupEvent;
+import io.study.springbootlayered.web.base.Events;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@Service
+@RequiredArgsConstructor
+@Transactional(readOnly = true)
+public class MemberSignupService {
+
+ private final MemberProcessor memberProcessor;
+
+ @Transactional
+ public MemberSignupDto.Info signup(final MemberSignupDto.Command request) {
+ /** ํ์ ๊ฐ์
**/
+ MemberSignupDto.Info info = memberProcessor.register(request);
+
+ /** ํ์๊ฐ์
์๋ฃ ํ ์ด๋ฉ์ผ ์ ์ก **/
+ String registeredEmail = info.getEmail();
+ Events.raise(SignupEvent.of(registeredEmail));
+
+ return info;
+ }
+} | Java | ๋ก๊ทธ ๋ฏธ์ฌ์ฉ์ธ๋ฐ ํด๋น ์ด๋
ธํ
์ด์
์ฌ์ฉํ๊ณ ์๋ค์. |
@@ -1,7 +1,15 @@
package store;
+import java.io.IOException;
+import store.controller.StoreManager;
+
public class Application {
public static void main(String[] args) {
- // TODO: ํ๋ก๊ทธ๋จ ๊ตฌํ
+ try {
+ StoreManager storeManager = new StoreManager();
+ storeManager.run();
+ } catch (IOException e) {
+ System.err.println("[ERROR] ํ๋ก๊ทธ๋จ ์คํ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค: " + e.getMessage());
+ }
}
} | Java | ํด๋น ์์ธ๋ Controller์์ ์ฒ๋ฆฌํด์ฃผ๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,38 @@
+package store.view;
+
+import camp.nextstep.edu.missionutils.Console;
+
+public class InputView {
+
+ public String readPurchaseList() {
+ String message = "\n๊ตฌ๋งคํ์ค ์ํ๋ช
๊ณผ ์๋์ ์
๋ ฅํด ์ฃผ์ธ์. (์: [์ฌ์ด๋ค-2],[๊ฐ์์นฉ-1])";
+ return prompt(message);
+ }
+
+ public String readAdditionalPromotion(String productName, int quantity) {
+ String message = String.format("\nํ์ฌ %s %d๊ฐ๋ฅผ ๋ฌด๋ฃ๋ก ๋ ๋ฐ์ ์ ์์ต๋๋ค. ์ถ๊ฐํ์๊ฒ ์ต๋๊น? (Y/N)", productName, quantity);
+ return prompt(message);
+ }
+
+ public String readProceedWithoutPromotion(String productName, int quantity) {
+ String message = String.format("\nํ์ฌ %s %d๊ฐ๋ ํ๋ก๋ชจ์
ํ ์ธ์ด ์ ์ฉ๋์ง ์์ต๋๋ค. ๊ทธ๋๋ ๊ตฌ๋งคํ์๊ฒ ์ต๋๊น? (Y/N)", productName, quantity);
+ return prompt(message);
+
+ }
+
+ public String readMembershipDiscount() {
+ String message = "\n๋ฉค๋ฒ์ญ ํ ์ธ์ ๋ฐ์ผ์๊ฒ ์ต๋๊น? (Y/N)";
+ return prompt(message);
+
+ }
+
+ public String readContinueShopping() {
+ String message = "\n๊ฐ์ฌํฉ๋๋ค. ๊ตฌ๋งคํ๊ณ ์ถ์ ๋ค๋ฅธ ์ํ์ด ์๋์? (Y/N)";
+ return prompt(message);
+ }
+
+ private String prompt(String message) {
+ System.out.println(message);
+ return Console.readLine();
+ }
+} | Java | ์ฌ์ฉํ๋ ๋ฌธ์์ด์ ์์ํ ํด์ฃผ๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,19 @@
+name,price,quantity,promotion
+์ฝ๋ผ,1000,10,ํ์ฐ2+1
+์ฝ๋ผ,1000,10,null
+์ฌ์ด๋ค,1000,8,ํ์ฐ2+1
+์ฌ์ด๋ค,1000,7,null
+์ค๋ ์ง์ฃผ์ค,1800,9,MD์ถ์ฒ์ํ
+์ค๋ ์ง์ฃผ์ค,1800,0,null
+ํ์ฐ์,1200,5,ํ์ฐ2+1
+ํ์ฐ์,1200,0,null
+๋ฌผ,500,10,null
+๋นํ๋ฏผ์ํฐ,1500,6,null
+๊ฐ์์นฉ,1500,5,๋ฐ์งํ ์ธ
+๊ฐ์์นฉ,1500,5,null
+์ด์ฝ๋ฐ,1200,5,MD์ถ์ฒ์ํ
+์ด์ฝ๋ฐ,1200,5,null
+์๋์ง๋ฐ,2000,5,null
+์ ์๋์๋ฝ,6400,8,null
+์ปต๋ผ๋ฉด,1700,1,MD์ถ์ฒ์ํ
+์ปต๋ผ๋ฉด,1700,10,null | Unknown | ํ์ผ ์ด๋ฆ์ ๋ณ๊ฒฝํ์๋ ํ
์คํธ๊ฐ ์คํจํ์ง๋ ์์๋์? |
@@ -0,0 +1,18 @@
+package store.handler;
+
+public enum ErrorHandler {
+ INVALID_FORMAT("์ฌ๋ฐ๋ฅด์ง ์์ ํ์์ผ๋ก ์
๋ ฅํ์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
+ PRODUCT_NOT_FOUND("์กด์ฌํ์ง ์๋ ์ํ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
+ QUANTITY_EXCEEDS_STOCK("์ฌ๊ณ ์๋์ ์ด๊ณผํ์ฌ ๊ตฌ๋งคํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
+ GENERIC_INVALID_INPUT("์๋ชป๋ ์
๋ ฅ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.");
+
+ private final String message;
+
+ ErrorHandler(String message) {
+ this.message = message;
+ }
+
+ public IllegalArgumentException getException() {
+ return new IllegalArgumentException(message);
+ }
+} | Java | enum์ ์ด์ฉํ ์์ธ์ฒ๋ฆฌ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค๐๐ |
@@ -0,0 +1,81 @@
+package store.handler;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import store.domain.Product;
+
+public class ProductsFileHandler {
+ private static final Path PRODUCTS_FILE_PATH = Path.of("src/main/resources/products.md");
+ public static final String HEADER = "name,price,quantity,promotion";
+
+ private final Path latestFilePath;
+
+ public ProductsFileHandler(Path latestFilePath) {
+ this.latestFilePath = latestFilePath;
+ }
+
+ public void loadLatestProductsFile() throws IOException {
+ List<Product> products = parseItemsFromFile(PRODUCTS_FILE_PATH);
+ Map<String, Boolean> nonPromotionalEntries = identifyNonPromotionalProducts(products);
+ List<String> lines = buildProductLines(products, nonPromotionalEntries);
+ Files.write(latestFilePath, lines);
+ }
+
+ public List<Product> parseItemsFromFile(Path path) throws IOException {
+ try (Stream<String> lines = Files.lines(path)) {
+ return lines.skip(1)
+ .map(this::parseProductLine)
+ .collect(Collectors.toList());
+ }
+ }
+
+ public boolean shouldAddNonPromotional(Product product, Map<String, Boolean> nonPromotionalEntries) {
+ return product.hasPromotion() && !nonPromotionalEntries.getOrDefault(product.getName(), false);
+ }
+
+ public String formatProductLine(Product product) {
+ return String.format("%s,%d,%d,%s", product.getName(), product.getPrice(),
+ product.getQuantity(), product.promoName());
+ }
+
+ private Product parseProductLine(String line) {
+ String[] parts = line.split(",");
+ return new Product(
+ parts[0].trim(),
+ Integer.parseInt(parts[1].trim()),
+ Integer.parseInt(parts[2].trim()),
+ PromotionsFileHandler.getPromotionByName(parts[3].trim())
+ );
+ }
+
+ private Map<String, Boolean> identifyNonPromotionalProducts(List<Product> products) {
+ Map<String, Boolean> nonPromotionalEntries = new HashMap<>();
+ products.stream()
+ .filter(product -> !product.hasPromotion())
+ .forEach(product -> nonPromotionalEntries.put(product.getName(), true));
+ return nonPromotionalEntries;
+ }
+
+ private List<String> buildProductLines(List<Product> products, Map<String, Boolean> nonPromotionalEntries) {
+ List<String> lines = new ArrayList<>();
+ lines.add(HEADER);
+ products.forEach(product -> addProductLines(lines, product, nonPromotionalEntries));
+ return lines;
+ }
+
+ private void addProductLines(List<String> lines, Product product, Map<String, Boolean> nonPromotionalEntries) {
+ lines.add(formatProductLine(product));
+ if (shouldAddNonPromotional(product, nonPromotionalEntries)) {
+ lines.add(formatProductLine(
+ new Product(product.getName(), product.getPrice(), 0, PromotionsFileHandler.NON_PROMOTION)));
+ nonPromotionalEntries.put(product.getName(), true);
+ }
+ }
+} | Java | ํ์ผ ์
์ถ๋ ฅ์ view์ ์ญํ ์ด๋ผ๊ณ ์๊ฐํ๋๋ฐ ์ด๋ป๊ฒ ์๊ฐํ์๋์!? |
@@ -0,0 +1,53 @@
+package store.handler;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.LocalDate;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import store.domain.Promotion;
+
+public class PromotionsFileHandler {
+ private static final Path PROMOTIONS_FILE_PATH = Path.of("src/main/resources/promotions.md");
+ public static final String NON_PROMOTION_NAME = "null";
+ public static final Promotion NON_PROMOTION = new Promotion(NON_PROMOTION_NAME, 1, 0);
+ private static final Map<String, Promotion> promotions = new HashMap<>();
+
+ public void loadPromotions() throws IOException {
+ List<String> lines = Files.readAllLines(PROMOTIONS_FILE_PATH);
+ promotions.put(NON_PROMOTION_NAME, NON_PROMOTION);
+ lines.stream().skip(1).forEach(this::processPromotionLine); // Skip header line
+ }
+
+ private void processPromotionLine(String line) {
+ String[] parts = parseAndTrimLine(line);
+ String name = parts[0];
+ int discountRate = Integer.parseInt(parts[1]);
+ int limit = Integer.parseInt(parts[2]);
+
+ if (isPromotionValid(parts)) {
+ promotions.put(name, new Promotion(name, discountRate, limit));
+ }
+ }
+
+ private String[] parseAndTrimLine(String line) {
+ return Arrays.stream(line.split(","))
+ .map(String::trim)
+ .toArray(String[]::new);
+ }
+
+ private boolean isPromotionValid(String[] parts) {
+ LocalDate today = DateTimes.now().toLocalDate();
+ LocalDate startDate = LocalDate.parse(parts[3]);
+ LocalDate endDate = LocalDate.parse(parts[4]);
+ return !today.isBefore(startDate) && !today.isAfter(endDate);
+ }
+
+ public static Promotion getPromotionByName(String name) {
+ return promotions.getOrDefault(name, promotions.get(NON_PROMOTION_NAME));
+ }
+} | Java | ์ฃผ์๋ณด๋ค๋ ๋ฉ์๋์ ์ด๋ฆ์ผ๋ก ๋ช
์ํด๋ณด๋๊ฑด ์ด๋จ๊น์? |
@@ -0,0 +1,34 @@
+package store.domain;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class Cart {
+ private final List<CartItem> items = new ArrayList<>();
+
+ public void addItem(CartItem item) {
+ items.add(item);
+ }
+
+ public List<CartItem> getItems() {
+ return Collections.unmodifiableList(items);
+ }
+
+ public int totalQuantity() {
+ return items.stream().mapToInt(CartItem::calcTotalQuantity).sum();
+ }
+
+ public int totalPrice() {
+ return items.stream().mapToInt(CartItem::totalPrice).sum();
+ }
+
+ public int totalRetailPrice() {
+ return items.stream().mapToInt(CartItem::totalRetailPrice).sum();
+ }
+
+ public int totalFreePrice() {
+ return items.stream().mapToInt(CartItem::totalFreePrice).sum();
+ }
+}
+ | Java | ์ ์ฒด์ ์ผ๋ก Model์ด ํด๋น ๋๋ฉ์ธ์ ๋ํ ๋น์ฆ๋์ค ๋ก์ง์ ์ํํ๊ธฐ ๋ณด๋ค๋ Dataclass์ฒ๋ผ ์ฌ์ฉ๋๊ณ ์๋ ๊ฒ ๊ฐ์์!
์ด์ธ๋ฆฌ๋ ๋ก์ง๋ค์ Model๋ก ์ฎ๊ฒจ์ฌ ์ ์์ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,38 @@
+package store.service;
+
+import store.controller.CartManager;
+import store.domain.Cart;
+import store.domain.Receipt;
+
+public class PaymentService {
+ private static final double MEMBERSHIP_DISCOUNT_RATE = 0.3;
+ private final static int MEMBERSHIP_DISCOUNT_LIMIT = 8000;
+
+ private final CartManager cartManager;
+ private int membershipDiscountBalance;
+
+ public PaymentService(CartManager cartManager) {
+ this.cartManager = cartManager;
+ this.membershipDiscountBalance = MEMBERSHIP_DISCOUNT_LIMIT;
+ }
+
+ public Cart getCartItems(String purchaseList) {
+ return cartManager.generateCart(purchaseList);
+ }
+
+ public Receipt createReceipt(Cart cart, boolean applyMembership) {
+ int membershipDiscount = calcMembershipDiscount(applyMembership, cart.totalRetailPrice());
+ return new Receipt(cart, cart.totalPrice(), cart.totalFreePrice(), membershipDiscount);
+ }
+
+ private int calcMembershipDiscount(boolean apply, int eligibleAmount) {
+ if (apply) {
+ int discountAmount = Math.min((int) (eligibleAmount * MEMBERSHIP_DISCOUNT_RATE),
+ membershipDiscountBalance);
+ membershipDiscountBalance -= discountAmount;
+
+ return discountAmount;
+ }
+ return 0;
+ }
+} | Java | ๋ผ์ธ ํฌ๋งทํ
์ ๋ ์ด์๊ฒ ํ ์ ์์ ๊ฒ ๊ฐ์์!
๋ชจ๋ํ ํ๋ ๊ฒ๋ ๋ฐฉ๋ฒ์ธ๊ฒ ๊ฐ์์๐
```suggestion
int discountAmount = Math.min(
(int) (eligibleAmount * MEMBERSHIP_DISCOUNT_RATE),
membershipDiscountBalance
);
``` |
@@ -0,0 +1,162 @@
+package store.controller;
+
+import static store.handler.ErrorHandler.PRODUCT_NOT_FOUND;
+import static store.handler.ErrorHandler.QUANTITY_EXCEEDS_STOCK;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.stream.Collectors;
+import store.domain.Cart;
+import store.domain.CartItem;
+import store.domain.Product;
+import store.handler.PromotionsFileHandler;
+import store.handler.StocksFileHandler;
+import store.view.InputView;
+
+public class CartManager {
+ private List<Product> products;
+ private final InputView inputView = new InputView();
+ private Cart cart;
+ private int totalCnt;
+ private int promoSet;
+
+ public CartManager() throws IOException {
+ loadPromotionsAndStocks();
+ }
+
+ private void loadPromotionsAndStocks() throws IOException {
+ new PromotionsFileHandler().loadPromotions();
+ this.products = new StocksFileHandler().loadStocks();
+ }
+
+ public List<Product> getAllProducts() {
+ return products;
+ }
+
+ public List<Product> findProductsByName(String name) {
+ return products.stream()
+ .filter(product -> product.getName().equalsIgnoreCase(name))
+ .collect(Collectors.toList());
+ }
+
+ public Cart generateCart(String purchaseList) {
+ cart = new Cart();
+ String[] cartItems = purchaseList.split(",");
+ for (String item : cartItems) {
+ validateCartItem(item);
+ }
+ for (String item : cartItems) {
+ processCartItem(item);
+ }
+ return cart;
+ }
+
+ private void validateCartItem(String item) {
+ String[] parts = parseItem(item);
+ String name = parts[0];
+ int requestedCnt = Integer.parseInt(parts[1]);
+
+ List<Product> matchingProducts = findProductsByName(name);
+ validateProductAvailability(matchingProducts);
+ validateStockAvailability(matchingProducts, requestedCnt);
+ }
+
+ private void processCartItem(String item) {
+ String[] parts = parseItem(item);
+ String name = parts[0];
+ int requestedCnt = Integer.parseInt(parts[1]);
+
+ List<Product> matchingProducts = findProductsByName(name);
+ processPromotionsAndQuantities(matchingProducts, name, requestedCnt);
+ }
+
+ private String[] parseItem(String item) {
+ return item.replaceAll("[\\[\\]]", "").split("-");
+ }
+
+ private void processPromotionsAndQuantities(List<Product> products, String name, int requestedCnt) {
+ int remainingCnt = requestedCnt;
+ totalCnt = requestedCnt;
+ promoSet = 0;
+ for (Product product : products) {
+ if (remainingCnt <= 0) {
+ break;
+ }
+ remainingCnt = handleProductPromotion(product, name, remainingCnt);
+ }
+ cart.addItem(new CartItem(products.getFirst(), totalCnt, promoSet));
+ }
+
+ private int handleProductPromotion(Product product, String name, int remainingCnt) {
+ int availableCnt = Math.min(remainingCnt, product.getQuantity());
+ if (!product.hasPromotion()) {
+ product.reduceQuantity(remainingCnt);
+ return 0;
+ }
+ promoSet = calculatePromoSet(product, availableCnt);
+ remainingCnt = processIncompletePromoSet(product, name, remainingCnt);
+ remainingCnt = processExactPromoSet(product, name, remainingCnt);
+ return remainingCnt;
+ }
+
+ private int processIncompletePromoSet(Product product, String name, int remainingCnt) {
+ if (isExactPromoSet(product, remainingCnt) && (promoSet + 1) * product.promoCycle() <= product.getQuantity()) {
+ String response = inputView.readAdditionalPromotion(name, calculateNonPromoCount(product, remainingCnt));
+ if (response.equals("Y")) {
+ promoSet += 1;
+ totalCnt += product.promoFree();
+ }
+ }
+ product.reduceQuantity(promoSet * product.promoCycle());
+ return Math.max(remainingCnt - promoSet * product.promoCycle(), 0);
+ }
+
+ private int processExactPromoSet(Product product, String name, int remainingCnt) {
+ if (!hasIncompletePromoSet(product, remainingCnt)) {
+ return remainingCnt;
+ }
+ String response = inputView.readProceedWithoutPromotion(name, remainingCnt);
+ int nonPromoCnt = calculateNonPromoCount(product, remainingCnt);
+ if (response.equals("N")) {
+ totalCnt -= nonPromoCnt;
+ return remainingCnt;
+ }
+ remainingCnt -= nonPromoCnt;
+ product.reduceQuantity(nonPromoCnt);
+ return remainingCnt;
+ }
+
+ private void validateProductAvailability(List<Product> products) {
+ if (products.isEmpty()) {
+ throw PRODUCT_NOT_FOUND.getException();
+ }
+ }
+
+ private void validateStockAvailability(List<Product> products, int requestedQuantity) {
+ int availableQuantity = products.stream().mapToInt(Product::getQuantity).sum();
+ if (availableQuantity < requestedQuantity) {
+ throw QUANTITY_EXCEEDS_STOCK.getException();
+ }
+ }
+
+ private boolean hasIncompletePromoSet(Product product, int quantity) {
+ return quantity % product.promoCycle() != 0;
+ }
+
+ private boolean isExactPromoSet(Product product, int quantity) {
+ int remainder = quantity % product.promoCycle();
+ return remainder > 0 && remainder % product.promoBuy() == 0;
+ }
+
+ private int calculateNonPromoCount(Product product, int quantity) {
+ int remainder = quantity % product.promoCycle();
+ if (remainder % product.promoCycle() == 0) {
+ return product.promoFree();
+ }
+ return remainder;
+ }
+
+ private int calculatePromoSet(Product product, int quantity) {
+ return quantity / product.promoCycle();
+ }
+} | Java | ์ ์ฒด์ ์ผ๋ก ๋น์ฆ๋์ค ๋ก์ง์ด Controller์ ์์ฑ๋์ด์๋ ๋๋์ด ๋ญ๋๋ค! ๋ณ๋์ Service์ ์ฑ
์์ ๋ถ๋ฆฌํด๋ณด๋๊ฑด ์ด๋จ๊น์? |
@@ -1,7 +1,15 @@
package store;
+import java.io.IOException;
+import store.controller.StoreManager;
+
public class Application {
public static void main(String[] args) {
- // TODO: ํ๋ก๊ทธ๋จ ๊ตฌํ
+ try {
+ StoreManager storeManager = new StoreManager();
+ storeManager.run();
+ } catch (IOException e) {
+ System.err.println("[ERROR] ํ๋ก๊ทธ๋จ ์คํ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค: " + e.getMessage());
+ }
}
} | Java | ์ถ๋ ฅ์ OutputView์์ ์ฒ๋ฆฌํ๋ ๊ฒ์ด ์ ์ ํด๋ณด์
๋๋ค! |
@@ -0,0 +1,162 @@
+package store.controller;
+
+import static store.handler.ErrorHandler.PRODUCT_NOT_FOUND;
+import static store.handler.ErrorHandler.QUANTITY_EXCEEDS_STOCK;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.stream.Collectors;
+import store.domain.Cart;
+import store.domain.CartItem;
+import store.domain.Product;
+import store.handler.PromotionsFileHandler;
+import store.handler.StocksFileHandler;
+import store.view.InputView;
+
+public class CartManager {
+ private List<Product> products;
+ private final InputView inputView = new InputView();
+ private Cart cart;
+ private int totalCnt;
+ private int promoSet;
+
+ public CartManager() throws IOException {
+ loadPromotionsAndStocks();
+ }
+
+ private void loadPromotionsAndStocks() throws IOException {
+ new PromotionsFileHandler().loadPromotions();
+ this.products = new StocksFileHandler().loadStocks();
+ }
+
+ public List<Product> getAllProducts() {
+ return products;
+ }
+
+ public List<Product> findProductsByName(String name) {
+ return products.stream()
+ .filter(product -> product.getName().equalsIgnoreCase(name))
+ .collect(Collectors.toList());
+ }
+
+ public Cart generateCart(String purchaseList) {
+ cart = new Cart();
+ String[] cartItems = purchaseList.split(",");
+ for (String item : cartItems) {
+ validateCartItem(item);
+ }
+ for (String item : cartItems) {
+ processCartItem(item);
+ }
+ return cart;
+ }
+
+ private void validateCartItem(String item) {
+ String[] parts = parseItem(item);
+ String name = parts[0];
+ int requestedCnt = Integer.parseInt(parts[1]);
+
+ List<Product> matchingProducts = findProductsByName(name);
+ validateProductAvailability(matchingProducts);
+ validateStockAvailability(matchingProducts, requestedCnt);
+ }
+
+ private void processCartItem(String item) {
+ String[] parts = parseItem(item);
+ String name = parts[0];
+ int requestedCnt = Integer.parseInt(parts[1]);
+
+ List<Product> matchingProducts = findProductsByName(name);
+ processPromotionsAndQuantities(matchingProducts, name, requestedCnt);
+ }
+
+ private String[] parseItem(String item) {
+ return item.replaceAll("[\\[\\]]", "").split("-");
+ }
+
+ private void processPromotionsAndQuantities(List<Product> products, String name, int requestedCnt) {
+ int remainingCnt = requestedCnt;
+ totalCnt = requestedCnt;
+ promoSet = 0;
+ for (Product product : products) {
+ if (remainingCnt <= 0) {
+ break;
+ }
+ remainingCnt = handleProductPromotion(product, name, remainingCnt);
+ }
+ cart.addItem(new CartItem(products.getFirst(), totalCnt, promoSet));
+ }
+
+ private int handleProductPromotion(Product product, String name, int remainingCnt) {
+ int availableCnt = Math.min(remainingCnt, product.getQuantity());
+ if (!product.hasPromotion()) {
+ product.reduceQuantity(remainingCnt);
+ return 0;
+ }
+ promoSet = calculatePromoSet(product, availableCnt);
+ remainingCnt = processIncompletePromoSet(product, name, remainingCnt);
+ remainingCnt = processExactPromoSet(product, name, remainingCnt);
+ return remainingCnt;
+ }
+
+ private int processIncompletePromoSet(Product product, String name, int remainingCnt) {
+ if (isExactPromoSet(product, remainingCnt) && (promoSet + 1) * product.promoCycle() <= product.getQuantity()) {
+ String response = inputView.readAdditionalPromotion(name, calculateNonPromoCount(product, remainingCnt));
+ if (response.equals("Y")) {
+ promoSet += 1;
+ totalCnt += product.promoFree();
+ }
+ }
+ product.reduceQuantity(promoSet * product.promoCycle());
+ return Math.max(remainingCnt - promoSet * product.promoCycle(), 0);
+ }
+
+ private int processExactPromoSet(Product product, String name, int remainingCnt) {
+ if (!hasIncompletePromoSet(product, remainingCnt)) {
+ return remainingCnt;
+ }
+ String response = inputView.readProceedWithoutPromotion(name, remainingCnt);
+ int nonPromoCnt = calculateNonPromoCount(product, remainingCnt);
+ if (response.equals("N")) {
+ totalCnt -= nonPromoCnt;
+ return remainingCnt;
+ }
+ remainingCnt -= nonPromoCnt;
+ product.reduceQuantity(nonPromoCnt);
+ return remainingCnt;
+ }
+
+ private void validateProductAvailability(List<Product> products) {
+ if (products.isEmpty()) {
+ throw PRODUCT_NOT_FOUND.getException();
+ }
+ }
+
+ private void validateStockAvailability(List<Product> products, int requestedQuantity) {
+ int availableQuantity = products.stream().mapToInt(Product::getQuantity).sum();
+ if (availableQuantity < requestedQuantity) {
+ throw QUANTITY_EXCEEDS_STOCK.getException();
+ }
+ }
+
+ private boolean hasIncompletePromoSet(Product product, int quantity) {
+ return quantity % product.promoCycle() != 0;
+ }
+
+ private boolean isExactPromoSet(Product product, int quantity) {
+ int remainder = quantity % product.promoCycle();
+ return remainder > 0 && remainder % product.promoBuy() == 0;
+ }
+
+ private int calculateNonPromoCount(Product product, int quantity) {
+ int remainder = quantity % product.promoCycle();
+ if (remainder % product.promoCycle() == 0) {
+ return product.promoFree();
+ }
+ return remainder;
+ }
+
+ private int calculatePromoSet(Product product, int quantity) {
+ return quantity / product.promoCycle();
+ }
+} | Java | `replaceAll("[\\[\\]]", "")` ๋ณํ๋์์ธ ๋ฌธ์์ด์ด ์ด๋ค ์๋ฏธ๋ฅผ ๊ฐ์ง๊ณ ์๋์ง ์์๋ก ๋ํ๋ด์ฃผ์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,162 @@
+package store.controller;
+
+import static store.handler.ErrorHandler.PRODUCT_NOT_FOUND;
+import static store.handler.ErrorHandler.QUANTITY_EXCEEDS_STOCK;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.stream.Collectors;
+import store.domain.Cart;
+import store.domain.CartItem;
+import store.domain.Product;
+import store.handler.PromotionsFileHandler;
+import store.handler.StocksFileHandler;
+import store.view.InputView;
+
+public class CartManager {
+ private List<Product> products;
+ private final InputView inputView = new InputView();
+ private Cart cart;
+ private int totalCnt;
+ private int promoSet;
+
+ public CartManager() throws IOException {
+ loadPromotionsAndStocks();
+ }
+
+ private void loadPromotionsAndStocks() throws IOException {
+ new PromotionsFileHandler().loadPromotions();
+ this.products = new StocksFileHandler().loadStocks();
+ }
+
+ public List<Product> getAllProducts() {
+ return products;
+ }
+
+ public List<Product> findProductsByName(String name) {
+ return products.stream()
+ .filter(product -> product.getName().equalsIgnoreCase(name))
+ .collect(Collectors.toList());
+ }
+
+ public Cart generateCart(String purchaseList) {
+ cart = new Cart();
+ String[] cartItems = purchaseList.split(",");
+ for (String item : cartItems) {
+ validateCartItem(item);
+ }
+ for (String item : cartItems) {
+ processCartItem(item);
+ }
+ return cart;
+ }
+
+ private void validateCartItem(String item) {
+ String[] parts = parseItem(item);
+ String name = parts[0];
+ int requestedCnt = Integer.parseInt(parts[1]);
+
+ List<Product> matchingProducts = findProductsByName(name);
+ validateProductAvailability(matchingProducts);
+ validateStockAvailability(matchingProducts, requestedCnt);
+ }
+
+ private void processCartItem(String item) {
+ String[] parts = parseItem(item);
+ String name = parts[0];
+ int requestedCnt = Integer.parseInt(parts[1]);
+
+ List<Product> matchingProducts = findProductsByName(name);
+ processPromotionsAndQuantities(matchingProducts, name, requestedCnt);
+ }
+
+ private String[] parseItem(String item) {
+ return item.replaceAll("[\\[\\]]", "").split("-");
+ }
+
+ private void processPromotionsAndQuantities(List<Product> products, String name, int requestedCnt) {
+ int remainingCnt = requestedCnt;
+ totalCnt = requestedCnt;
+ promoSet = 0;
+ for (Product product : products) {
+ if (remainingCnt <= 0) {
+ break;
+ }
+ remainingCnt = handleProductPromotion(product, name, remainingCnt);
+ }
+ cart.addItem(new CartItem(products.getFirst(), totalCnt, promoSet));
+ }
+
+ private int handleProductPromotion(Product product, String name, int remainingCnt) {
+ int availableCnt = Math.min(remainingCnt, product.getQuantity());
+ if (!product.hasPromotion()) {
+ product.reduceQuantity(remainingCnt);
+ return 0;
+ }
+ promoSet = calculatePromoSet(product, availableCnt);
+ remainingCnt = processIncompletePromoSet(product, name, remainingCnt);
+ remainingCnt = processExactPromoSet(product, name, remainingCnt);
+ return remainingCnt;
+ }
+
+ private int processIncompletePromoSet(Product product, String name, int remainingCnt) {
+ if (isExactPromoSet(product, remainingCnt) && (promoSet + 1) * product.promoCycle() <= product.getQuantity()) {
+ String response = inputView.readAdditionalPromotion(name, calculateNonPromoCount(product, remainingCnt));
+ if (response.equals("Y")) {
+ promoSet += 1;
+ totalCnt += product.promoFree();
+ }
+ }
+ product.reduceQuantity(promoSet * product.promoCycle());
+ return Math.max(remainingCnt - promoSet * product.promoCycle(), 0);
+ }
+
+ private int processExactPromoSet(Product product, String name, int remainingCnt) {
+ if (!hasIncompletePromoSet(product, remainingCnt)) {
+ return remainingCnt;
+ }
+ String response = inputView.readProceedWithoutPromotion(name, remainingCnt);
+ int nonPromoCnt = calculateNonPromoCount(product, remainingCnt);
+ if (response.equals("N")) {
+ totalCnt -= nonPromoCnt;
+ return remainingCnt;
+ }
+ remainingCnt -= nonPromoCnt;
+ product.reduceQuantity(nonPromoCnt);
+ return remainingCnt;
+ }
+
+ private void validateProductAvailability(List<Product> products) {
+ if (products.isEmpty()) {
+ throw PRODUCT_NOT_FOUND.getException();
+ }
+ }
+
+ private void validateStockAvailability(List<Product> products, int requestedQuantity) {
+ int availableQuantity = products.stream().mapToInt(Product::getQuantity).sum();
+ if (availableQuantity < requestedQuantity) {
+ throw QUANTITY_EXCEEDS_STOCK.getException();
+ }
+ }
+
+ private boolean hasIncompletePromoSet(Product product, int quantity) {
+ return quantity % product.promoCycle() != 0;
+ }
+
+ private boolean isExactPromoSet(Product product, int quantity) {
+ int remainder = quantity % product.promoCycle();
+ return remainder > 0 && remainder % product.promoBuy() == 0;
+ }
+
+ private int calculateNonPromoCount(Product product, int quantity) {
+ int remainder = quantity % product.promoCycle();
+ if (remainder % product.promoCycle() == 0) {
+ return product.promoFree();
+ }
+ return remainder;
+ }
+
+ private int calculatePromoSet(Product product, int quantity) {
+ return quantity / product.promoCycle();
+ }
+} | Java | `remainingCnt` Cnt ์ ๋๋ฉด ์ถฉ๋ถํ ์ด๋ค ์๋ฏธ๋ก ์์ฑ๋ ๊ฒ์ธ์ง ์ ์ ์์ง๋ง, ๊ฐ๊ธ์ ์ด๋ฉด ์ข ๊ธธ๋๋ผ๋ Count๋ผ๋
ํ๋ค์์ ์จ์ฃผ์
๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,162 @@
+package store.controller;
+
+import static store.handler.ErrorHandler.PRODUCT_NOT_FOUND;
+import static store.handler.ErrorHandler.QUANTITY_EXCEEDS_STOCK;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.stream.Collectors;
+import store.domain.Cart;
+import store.domain.CartItem;
+import store.domain.Product;
+import store.handler.PromotionsFileHandler;
+import store.handler.StocksFileHandler;
+import store.view.InputView;
+
+public class CartManager {
+ private List<Product> products;
+ private final InputView inputView = new InputView();
+ private Cart cart;
+ private int totalCnt;
+ private int promoSet;
+
+ public CartManager() throws IOException {
+ loadPromotionsAndStocks();
+ }
+
+ private void loadPromotionsAndStocks() throws IOException {
+ new PromotionsFileHandler().loadPromotions();
+ this.products = new StocksFileHandler().loadStocks();
+ }
+
+ public List<Product> getAllProducts() {
+ return products;
+ }
+
+ public List<Product> findProductsByName(String name) {
+ return products.stream()
+ .filter(product -> product.getName().equalsIgnoreCase(name))
+ .collect(Collectors.toList());
+ }
+
+ public Cart generateCart(String purchaseList) {
+ cart = new Cart();
+ String[] cartItems = purchaseList.split(",");
+ for (String item : cartItems) {
+ validateCartItem(item);
+ }
+ for (String item : cartItems) {
+ processCartItem(item);
+ }
+ return cart;
+ }
+
+ private void validateCartItem(String item) {
+ String[] parts = parseItem(item);
+ String name = parts[0];
+ int requestedCnt = Integer.parseInt(parts[1]);
+
+ List<Product> matchingProducts = findProductsByName(name);
+ validateProductAvailability(matchingProducts);
+ validateStockAvailability(matchingProducts, requestedCnt);
+ }
+
+ private void processCartItem(String item) {
+ String[] parts = parseItem(item);
+ String name = parts[0];
+ int requestedCnt = Integer.parseInt(parts[1]);
+
+ List<Product> matchingProducts = findProductsByName(name);
+ processPromotionsAndQuantities(matchingProducts, name, requestedCnt);
+ }
+
+ private String[] parseItem(String item) {
+ return item.replaceAll("[\\[\\]]", "").split("-");
+ }
+
+ private void processPromotionsAndQuantities(List<Product> products, String name, int requestedCnt) {
+ int remainingCnt = requestedCnt;
+ totalCnt = requestedCnt;
+ promoSet = 0;
+ for (Product product : products) {
+ if (remainingCnt <= 0) {
+ break;
+ }
+ remainingCnt = handleProductPromotion(product, name, remainingCnt);
+ }
+ cart.addItem(new CartItem(products.getFirst(), totalCnt, promoSet));
+ }
+
+ private int handleProductPromotion(Product product, String name, int remainingCnt) {
+ int availableCnt = Math.min(remainingCnt, product.getQuantity());
+ if (!product.hasPromotion()) {
+ product.reduceQuantity(remainingCnt);
+ return 0;
+ }
+ promoSet = calculatePromoSet(product, availableCnt);
+ remainingCnt = processIncompletePromoSet(product, name, remainingCnt);
+ remainingCnt = processExactPromoSet(product, name, remainingCnt);
+ return remainingCnt;
+ }
+
+ private int processIncompletePromoSet(Product product, String name, int remainingCnt) {
+ if (isExactPromoSet(product, remainingCnt) && (promoSet + 1) * product.promoCycle() <= product.getQuantity()) {
+ String response = inputView.readAdditionalPromotion(name, calculateNonPromoCount(product, remainingCnt));
+ if (response.equals("Y")) {
+ promoSet += 1;
+ totalCnt += product.promoFree();
+ }
+ }
+ product.reduceQuantity(promoSet * product.promoCycle());
+ return Math.max(remainingCnt - promoSet * product.promoCycle(), 0);
+ }
+
+ private int processExactPromoSet(Product product, String name, int remainingCnt) {
+ if (!hasIncompletePromoSet(product, remainingCnt)) {
+ return remainingCnt;
+ }
+ String response = inputView.readProceedWithoutPromotion(name, remainingCnt);
+ int nonPromoCnt = calculateNonPromoCount(product, remainingCnt);
+ if (response.equals("N")) {
+ totalCnt -= nonPromoCnt;
+ return remainingCnt;
+ }
+ remainingCnt -= nonPromoCnt;
+ product.reduceQuantity(nonPromoCnt);
+ return remainingCnt;
+ }
+
+ private void validateProductAvailability(List<Product> products) {
+ if (products.isEmpty()) {
+ throw PRODUCT_NOT_FOUND.getException();
+ }
+ }
+
+ private void validateStockAvailability(List<Product> products, int requestedQuantity) {
+ int availableQuantity = products.stream().mapToInt(Product::getQuantity).sum();
+ if (availableQuantity < requestedQuantity) {
+ throw QUANTITY_EXCEEDS_STOCK.getException();
+ }
+ }
+
+ private boolean hasIncompletePromoSet(Product product, int quantity) {
+ return quantity % product.promoCycle() != 0;
+ }
+
+ private boolean isExactPromoSet(Product product, int quantity) {
+ int remainder = quantity % product.promoCycle();
+ return remainder > 0 && remainder % product.promoBuy() == 0;
+ }
+
+ private int calculateNonPromoCount(Product product, int quantity) {
+ int remainder = quantity % product.promoCycle();
+ if (remainder % product.promoCycle() == 0) {
+ return product.promoFree();
+ }
+ return remainder;
+ }
+
+ private int calculatePromoSet(Product product, int quantity) {
+ return quantity / product.promoCycle();
+ }
+} | Java | `isExactPromoSet(product, remainingCnt) && (promoSet + 1) * product.promoCycle() <= product.getQuantity()`
if๋ฌธ ๋ด์ ์ฌ๋ฌ ์กฐ๊ฑด์ ๊ฒ์ฆํ๋ ๊ฒ์ด ๋ณด์ฌ์ง๋๊น ์ฝ๋ ์
์ฅ์์ ๋ค์ ๋ณต์กํ๊ฒ ๋๊ปด์ง ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค.
ํด๋น ์กฐ๊ฑด๋ค์ ๊ฒ์ฆํ๋ ํ๋์ ๋ฉ์๋๋ฅผ ์ ์ํ์ฌ ์ฌ์ฉํด์ฃผ์๋ฉด ๋์ ๋ ์ ๋ค์ด์ฌ ๊ฒ ๊ฐ๋จ ์๊ฐ์ด ๋ญ๋๋ค! |
@@ -0,0 +1,99 @@
+package store.controller;
+
+import static store.handler.ErrorHandler.GENERIC_INVALID_INPUT;
+import static store.handler.ErrorHandler.INVALID_FORMAT;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.function.Supplier;
+import java.util.regex.Pattern;
+import store.domain.Cart;
+import store.domain.Product;
+import store.domain.Receipt;
+import store.service.PaymentService;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class StoreManager {
+ private static final Pattern PURCHASE_LIST_PATTERN = Pattern.compile(
+ "\\[(\\p{L}+)-(\\d+)](,\\[(\\p{L}+)-(\\d+)])*");
+
+ private final InputView inputView = new InputView();
+ private final OutputView outputView = new OutputView();
+ private final PaymentService paymentService;
+ private final List<Product> products;
+
+ public StoreManager() throws IOException {
+ CartManager cartManager = new CartManager();
+ paymentService = new PaymentService(cartManager);
+ products = cartManager.getAllProducts();
+ }
+
+ public void run() {
+ boolean continueShopping;
+ do {
+ displayStoreProducts();
+ Cart cart = getValidCart();
+ boolean applyMembership = getMembershipStatus();
+ processPayment(cart, applyMembership);
+ continueShopping = checkContinueShopping();
+ } while (continueShopping);
+ }
+
+ private void displayStoreProducts() {
+ outputView.printWelcomeMessage();
+ outputView.printStockOverviewMessage();
+ outputView.printStockItemDetails(products);
+ }
+
+ private Cart getValidCart() {
+ return repeatUntilSuccess(() -> {
+ String purchaseList = inputView.readPurchaseList();
+ validatePurchaseList(purchaseList);
+ return paymentService.getCartItems(purchaseList);
+ });
+ }
+
+ private boolean getMembershipStatus() {
+ return repeatUntilSuccess(() -> {
+ String input = inputView.readMembershipDiscount();
+ validateYesNoInput(input);
+ return input.equals("Y");
+ });
+ }
+
+ private void processPayment(Cart cart, boolean applyMembership) {
+ Receipt receipt = paymentService.createReceipt(cart, applyMembership);
+ outputView.printReceipt(receipt);
+ }
+
+ private boolean checkContinueShopping() {
+ return repeatUntilSuccess(() -> {
+ String input = inputView.readContinueShopping();
+ validateYesNoInput(input);
+ return input.equals("Y");
+ });
+ }
+
+ private void validatePurchaseList(String input) {
+ if (!PURCHASE_LIST_PATTERN.matcher(input).matches()) {
+ throw INVALID_FORMAT.getException();
+ }
+ }
+
+ private void validateYesNoInput(String input) {
+ if (!input.equals("Y") && !input.equals("N")) {
+ throw GENERIC_INVALID_INPUT.getException();
+ }
+ }
+
+ private <T> T repeatUntilSuccess(Supplier<T> supplier) {
+ while (true) {
+ try {
+ return supplier.get();
+ } catch (IllegalArgumentException e) {
+ outputView.printErrorMessage(e.getMessage());
+ }
+ }
+ }
+} | Java | ํจ์ํ ์ธํฐํ์ด์ค๋ฅผ ์ฌ์ฉํด์ ๋ฐ๋ณต๋ก์ง์ ๊ฐ์์์ผ์ฃผ์
จ๋ค์! ๐๐ |
@@ -0,0 +1,81 @@
+package store.handler;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import store.domain.Product;
+
+public class ProductsFileHandler {
+ private static final Path PRODUCTS_FILE_PATH = Path.of("src/main/resources/products.md");
+ public static final String HEADER = "name,price,quantity,promotion";
+
+ private final Path latestFilePath;
+
+ public ProductsFileHandler(Path latestFilePath) {
+ this.latestFilePath = latestFilePath;
+ }
+
+ public void loadLatestProductsFile() throws IOException {
+ List<Product> products = parseItemsFromFile(PRODUCTS_FILE_PATH);
+ Map<String, Boolean> nonPromotionalEntries = identifyNonPromotionalProducts(products);
+ List<String> lines = buildProductLines(products, nonPromotionalEntries);
+ Files.write(latestFilePath, lines);
+ }
+
+ public List<Product> parseItemsFromFile(Path path) throws IOException {
+ try (Stream<String> lines = Files.lines(path)) {
+ return lines.skip(1)
+ .map(this::parseProductLine)
+ .collect(Collectors.toList());
+ }
+ }
+
+ public boolean shouldAddNonPromotional(Product product, Map<String, Boolean> nonPromotionalEntries) {
+ return product.hasPromotion() && !nonPromotionalEntries.getOrDefault(product.getName(), false);
+ }
+
+ public String formatProductLine(Product product) {
+ return String.format("%s,%d,%d,%s", product.getName(), product.getPrice(),
+ product.getQuantity(), product.promoName());
+ }
+
+ private Product parseProductLine(String line) {
+ String[] parts = line.split(",");
+ return new Product(
+ parts[0].trim(),
+ Integer.parseInt(parts[1].trim()),
+ Integer.parseInt(parts[2].trim()),
+ PromotionsFileHandler.getPromotionByName(parts[3].trim())
+ );
+ }
+
+ private Map<String, Boolean> identifyNonPromotionalProducts(List<Product> products) {
+ Map<String, Boolean> nonPromotionalEntries = new HashMap<>();
+ products.stream()
+ .filter(product -> !product.hasPromotion())
+ .forEach(product -> nonPromotionalEntries.put(product.getName(), true));
+ return nonPromotionalEntries;
+ }
+
+ private List<String> buildProductLines(List<Product> products, Map<String, Boolean> nonPromotionalEntries) {
+ List<String> lines = new ArrayList<>();
+ lines.add(HEADER);
+ products.forEach(product -> addProductLines(lines, product, nonPromotionalEntries));
+ return lines;
+ }
+
+ private void addProductLines(List<String> lines, Product product, Map<String, Boolean> nonPromotionalEntries) {
+ lines.add(formatProductLine(product));
+ if (shouldAddNonPromotional(product, nonPromotionalEntries)) {
+ lines.add(formatProductLine(
+ new Product(product.getName(), product.getPrice(), 0, PromotionsFileHandler.NON_PROMOTION)));
+ nonPromotionalEntries.put(product.getName(), true);
+ }
+ }
+} | Java | 1์ ์์๋ก ์ ์ํด์ฃผ์๋ฉด ์คํตํ๋ ๋ถ๋ถ์ด ์ด๋ ๋ถ๋ถ์ธ์ง ์๊ธฐ ์ฌ์ธ ๊ฒ ๊ฐ์ต๋๋ค |
@@ -0,0 +1,81 @@
+package store.handler;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import store.domain.Product;
+
+public class ProductsFileHandler {
+ private static final Path PRODUCTS_FILE_PATH = Path.of("src/main/resources/products.md");
+ public static final String HEADER = "name,price,quantity,promotion";
+
+ private final Path latestFilePath;
+
+ public ProductsFileHandler(Path latestFilePath) {
+ this.latestFilePath = latestFilePath;
+ }
+
+ public void loadLatestProductsFile() throws IOException {
+ List<Product> products = parseItemsFromFile(PRODUCTS_FILE_PATH);
+ Map<String, Boolean> nonPromotionalEntries = identifyNonPromotionalProducts(products);
+ List<String> lines = buildProductLines(products, nonPromotionalEntries);
+ Files.write(latestFilePath, lines);
+ }
+
+ public List<Product> parseItemsFromFile(Path path) throws IOException {
+ try (Stream<String> lines = Files.lines(path)) {
+ return lines.skip(1)
+ .map(this::parseProductLine)
+ .collect(Collectors.toList());
+ }
+ }
+
+ public boolean shouldAddNonPromotional(Product product, Map<String, Boolean> nonPromotionalEntries) {
+ return product.hasPromotion() && !nonPromotionalEntries.getOrDefault(product.getName(), false);
+ }
+
+ public String formatProductLine(Product product) {
+ return String.format("%s,%d,%d,%s", product.getName(), product.getPrice(),
+ product.getQuantity(), product.promoName());
+ }
+
+ private Product parseProductLine(String line) {
+ String[] parts = line.split(",");
+ return new Product(
+ parts[0].trim(),
+ Integer.parseInt(parts[1].trim()),
+ Integer.parseInt(parts[2].trim()),
+ PromotionsFileHandler.getPromotionByName(parts[3].trim())
+ );
+ }
+
+ private Map<String, Boolean> identifyNonPromotionalProducts(List<Product> products) {
+ Map<String, Boolean> nonPromotionalEntries = new HashMap<>();
+ products.stream()
+ .filter(product -> !product.hasPromotion())
+ .forEach(product -> nonPromotionalEntries.put(product.getName(), true));
+ return nonPromotionalEntries;
+ }
+
+ private List<String> buildProductLines(List<Product> products, Map<String, Boolean> nonPromotionalEntries) {
+ List<String> lines = new ArrayList<>();
+ lines.add(HEADER);
+ products.forEach(product -> addProductLines(lines, product, nonPromotionalEntries));
+ return lines;
+ }
+
+ private void addProductLines(List<String> lines, Product product, Map<String, Boolean> nonPromotionalEntries) {
+ lines.add(formatProductLine(product));
+ if (shouldAddNonPromotional(product, nonPromotionalEntries)) {
+ lines.add(formatProductLine(
+ new Product(product.getName(), product.getPrice(), 0, PromotionsFileHandler.NON_PROMOTION)));
+ nonPromotionalEntries.put(product.getName(), true);
+ }
+ }
+} | Java | `0`์ด ์๋ฏธํ๋ ๋ฐ๊ฐ ๋ฌด์์ธ์ง ์ ์ ์์๊น์? |
@@ -0,0 +1,53 @@
+package store.handler;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.LocalDate;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import store.domain.Promotion;
+
+public class PromotionsFileHandler {
+ private static final Path PROMOTIONS_FILE_PATH = Path.of("src/main/resources/promotions.md");
+ public static final String NON_PROMOTION_NAME = "null";
+ public static final Promotion NON_PROMOTION = new Promotion(NON_PROMOTION_NAME, 1, 0);
+ private static final Map<String, Promotion> promotions = new HashMap<>();
+
+ public void loadPromotions() throws IOException {
+ List<String> lines = Files.readAllLines(PROMOTIONS_FILE_PATH);
+ promotions.put(NON_PROMOTION_NAME, NON_PROMOTION);
+ lines.stream().skip(1).forEach(this::processPromotionLine); // Skip header line
+ }
+
+ private void processPromotionLine(String line) {
+ String[] parts = parseAndTrimLine(line);
+ String name = parts[0];
+ int discountRate = Integer.parseInt(parts[1]);
+ int limit = Integer.parseInt(parts[2]);
+
+ if (isPromotionValid(parts)) {
+ promotions.put(name, new Promotion(name, discountRate, limit));
+ }
+ }
+
+ private String[] parseAndTrimLine(String line) {
+ return Arrays.stream(line.split(","))
+ .map(String::trim)
+ .toArray(String[]::new);
+ }
+
+ private boolean isPromotionValid(String[] parts) {
+ LocalDate today = DateTimes.now().toLocalDate();
+ LocalDate startDate = LocalDate.parse(parts[3]);
+ LocalDate endDate = LocalDate.parse(parts[4]);
+ return !today.isBefore(startDate) && !today.isAfter(endDate);
+ }
+
+ public static Promotion getPromotionByName(String name) {
+ return promotions.getOrDefault(name, promotions.get(NON_PROMOTION_NAME));
+ }
+} | Java | `today.isAfter(startDate) && today.isBefore(endDate);`์ ์ด๋จ๊น์?
๊ฐ์ธ์ ์ผ๋ก ! ์ฐ์ฐ์๊ฐ ๋ค์ด๊ฐ๋ฉด ์ฝ๋๋ฅผ ๋ณด๋ ์
์ฅ์์ ํ๋ฒ ๋ ์๊ฐ์ ํ๊ฒ ๋ง๋๋ ๊ฒ ๊ฐ์ต๋๋ค |
@@ -0,0 +1,59 @@
+package store.handler;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import store.domain.Product;
+
+public class StocksFileHandler {
+ private static final Path STOCKS_FILE_PATH = Path.of("src/main/resources/stocks.md");
+
+ private final ProductsFileHandler productsFileHandler;
+
+ public StocksFileHandler() {
+ this.productsFileHandler = new ProductsFileHandler(STOCKS_FILE_PATH);
+ }
+
+ public List<Product> loadStocks() throws IOException {
+ ensureStocksFileExists();
+ productsFileHandler.loadLatestProductsFile();
+ updateStocksFile();
+ return productsFileHandler.parseItemsFromFile(STOCKS_FILE_PATH);
+ }
+
+ private void ensureStocksFileExists() throws IOException {
+ if (Files.notExists(STOCKS_FILE_PATH)) {
+ Files.createFile(STOCKS_FILE_PATH);
+ }
+ }
+
+ private void updateStocksFile() throws IOException {
+ Map<String, Product> productMap = buildProductsMap();
+ writeProductsToStocksFile(productMap);
+ }
+
+ private Map<String, Product> buildProductsMap() throws IOException {
+ List<Product> products = productsFileHandler.parseItemsFromFile(STOCKS_FILE_PATH);
+ Map<String, Product> productMap = new LinkedHashMap<>();
+ for (Product product : products) {
+ productMap.merge(product.getKeyForMap(), product, this::mergeProducts);
+ }
+ return productMap;
+ }
+
+ private Product mergeProducts(Product existing, Product toAdd) {
+ return new Product(existing.getName(), existing.getPrice(),
+ existing.getQuantity() + toAdd.getQuantity(), existing.getPromotion());
+ }
+
+ private void writeProductsToStocksFile(Map<String, Product> productMap) throws IOException {
+ List<String> lines = new ArrayList<>();
+ lines.add(ProductsFileHandler.HEADER);
+ productMap.values().forEach(product -> lines.add(productsFileHandler.formatProductLine(product)));
+ Files.write(STOCKS_FILE_PATH, lines);
+ }
+} | Java | ๋ณ์๋ช
์ ์๋ฃํ์ด ๋ค์ด๊ฐ๋ ๊ฒ์ ์ง์ํ๋ ๊ฒ์ด ์ข๋ค๊ณ ๋ค์์ต๋๋ค! |
@@ -0,0 +1,38 @@
+package store.service;
+
+import store.controller.CartManager;
+import store.domain.Cart;
+import store.domain.Receipt;
+
+public class PaymentService {
+ private static final double MEMBERSHIP_DISCOUNT_RATE = 0.3;
+ private final static int MEMBERSHIP_DISCOUNT_LIMIT = 8000;
+
+ private final CartManager cartManager;
+ private int membershipDiscountBalance;
+
+ public PaymentService(CartManager cartManager) {
+ this.cartManager = cartManager;
+ this.membershipDiscountBalance = MEMBERSHIP_DISCOUNT_LIMIT;
+ }
+
+ public Cart getCartItems(String purchaseList) {
+ return cartManager.generateCart(purchaseList);
+ }
+
+ public Receipt createReceipt(Cart cart, boolean applyMembership) {
+ int membershipDiscount = calcMembershipDiscount(applyMembership, cart.totalRetailPrice());
+ return new Receipt(cart, cart.totalPrice(), cart.totalFreePrice(), membershipDiscount);
+ }
+
+ private int calcMembershipDiscount(boolean apply, int eligibleAmount) {
+ if (apply) {
+ int discountAmount = Math.min((int) (eligibleAmount * MEMBERSHIP_DISCOUNT_RATE),
+ membershipDiscountBalance);
+ membershipDiscountBalance -= discountAmount;
+
+ return discountAmount;
+ }
+ return 0;
+ }
+} | Java | ์ ๊ทผ ์ ์ด์ ์์ฑ ์์๊ฐ `static final`๋ก ํต์ผ๋๋ ๊ฒ์ด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค |
@@ -0,0 +1,81 @@
+package store.handler;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import store.domain.Product;
+
+public class ProductsFileHandler {
+ private static final Path PRODUCTS_FILE_PATH = Path.of("src/main/resources/products.md");
+ public static final String HEADER = "name,price,quantity,promotion";
+
+ private final Path latestFilePath;
+
+ public ProductsFileHandler(Path latestFilePath) {
+ this.latestFilePath = latestFilePath;
+ }
+
+ public void loadLatestProductsFile() throws IOException {
+ List<Product> products = parseItemsFromFile(PRODUCTS_FILE_PATH);
+ Map<String, Boolean> nonPromotionalEntries = identifyNonPromotionalProducts(products);
+ List<String> lines = buildProductLines(products, nonPromotionalEntries);
+ Files.write(latestFilePath, lines);
+ }
+
+ public List<Product> parseItemsFromFile(Path path) throws IOException {
+ try (Stream<String> lines = Files.lines(path)) {
+ return lines.skip(1)
+ .map(this::parseProductLine)
+ .collect(Collectors.toList());
+ }
+ }
+
+ public boolean shouldAddNonPromotional(Product product, Map<String, Boolean> nonPromotionalEntries) {
+ return product.hasPromotion() && !nonPromotionalEntries.getOrDefault(product.getName(), false);
+ }
+
+ public String formatProductLine(Product product) {
+ return String.format("%s,%d,%d,%s", product.getName(), product.getPrice(),
+ product.getQuantity(), product.promoName());
+ }
+
+ private Product parseProductLine(String line) {
+ String[] parts = line.split(",");
+ return new Product(
+ parts[0].trim(),
+ Integer.parseInt(parts[1].trim()),
+ Integer.parseInt(parts[2].trim()),
+ PromotionsFileHandler.getPromotionByName(parts[3].trim())
+ );
+ }
+
+ private Map<String, Boolean> identifyNonPromotionalProducts(List<Product> products) {
+ Map<String, Boolean> nonPromotionalEntries = new HashMap<>();
+ products.stream()
+ .filter(product -> !product.hasPromotion())
+ .forEach(product -> nonPromotionalEntries.put(product.getName(), true));
+ return nonPromotionalEntries;
+ }
+
+ private List<String> buildProductLines(List<Product> products, Map<String, Boolean> nonPromotionalEntries) {
+ List<String> lines = new ArrayList<>();
+ lines.add(HEADER);
+ products.forEach(product -> addProductLines(lines, product, nonPromotionalEntries));
+ return lines;
+ }
+
+ private void addProductLines(List<String> lines, Product product, Map<String, Boolean> nonPromotionalEntries) {
+ lines.add(formatProductLine(product));
+ if (shouldAddNonPromotional(product, nonPromotionalEntries)) {
+ lines.add(formatProductLine(
+ new Product(product.getName(), product.getPrice(), 0, PromotionsFileHandler.NON_PROMOTION)));
+ nonPromotionalEntries.put(product.getName(), true);
+ }
+ }
+} | Java | ํธ์์ ์ ํ์ผ ์
์ถ๋ ฅ์ ๋ฐ์ดํฐ ์์ค ๊ด๋ฆฌ์ ๊ฐ๊น์ handler๋ repository์ ์ญํ ์ ๋ ๊ฐ๊น์ด ๊ฒ ๊ฐ์ต๋๋ค..! |
@@ -0,0 +1,81 @@
+package store.handler;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import store.domain.Product;
+
+public class ProductsFileHandler {
+ private static final Path PRODUCTS_FILE_PATH = Path.of("src/main/resources/products.md");
+ public static final String HEADER = "name,price,quantity,promotion";
+
+ private final Path latestFilePath;
+
+ public ProductsFileHandler(Path latestFilePath) {
+ this.latestFilePath = latestFilePath;
+ }
+
+ public void loadLatestProductsFile() throws IOException {
+ List<Product> products = parseItemsFromFile(PRODUCTS_FILE_PATH);
+ Map<String, Boolean> nonPromotionalEntries = identifyNonPromotionalProducts(products);
+ List<String> lines = buildProductLines(products, nonPromotionalEntries);
+ Files.write(latestFilePath, lines);
+ }
+
+ public List<Product> parseItemsFromFile(Path path) throws IOException {
+ try (Stream<String> lines = Files.lines(path)) {
+ return lines.skip(1)
+ .map(this::parseProductLine)
+ .collect(Collectors.toList());
+ }
+ }
+
+ public boolean shouldAddNonPromotional(Product product, Map<String, Boolean> nonPromotionalEntries) {
+ return product.hasPromotion() && !nonPromotionalEntries.getOrDefault(product.getName(), false);
+ }
+
+ public String formatProductLine(Product product) {
+ return String.format("%s,%d,%d,%s", product.getName(), product.getPrice(),
+ product.getQuantity(), product.promoName());
+ }
+
+ private Product parseProductLine(String line) {
+ String[] parts = line.split(",");
+ return new Product(
+ parts[0].trim(),
+ Integer.parseInt(parts[1].trim()),
+ Integer.parseInt(parts[2].trim()),
+ PromotionsFileHandler.getPromotionByName(parts[3].trim())
+ );
+ }
+
+ private Map<String, Boolean> identifyNonPromotionalProducts(List<Product> products) {
+ Map<String, Boolean> nonPromotionalEntries = new HashMap<>();
+ products.stream()
+ .filter(product -> !product.hasPromotion())
+ .forEach(product -> nonPromotionalEntries.put(product.getName(), true));
+ return nonPromotionalEntries;
+ }
+
+ private List<String> buildProductLines(List<Product> products, Map<String, Boolean> nonPromotionalEntries) {
+ List<String> lines = new ArrayList<>();
+ lines.add(HEADER);
+ products.forEach(product -> addProductLines(lines, product, nonPromotionalEntries));
+ return lines;
+ }
+
+ private void addProductLines(List<String> lines, Product product, Map<String, Boolean> nonPromotionalEntries) {
+ lines.add(formatProductLine(product));
+ if (shouldAddNonPromotional(product, nonPromotionalEntries)) {
+ lines.add(formatProductLine(
+ new Product(product.getName(), product.getPrice(), 0, PromotionsFileHandler.NON_PROMOTION)));
+ nonPromotionalEntries.put(product.getName(), true);
+ }
+ }
+} | Java | ์ฌ๊ณ ๊ฐ ์๋ ๊ฒฝ์ฐ ์ํ์ ์๋์ ์๋ฏธํฉ๋๋ค! ์ด๊ฒ๋ ๋ณ๋์ ์์๋ก ์ฒ๋ฆฌํ๋ฉด ์ข์์ ๊ฒ ๊ฐ๋ค์. |
@@ -0,0 +1,53 @@
+package store.handler;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.LocalDate;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import store.domain.Promotion;
+
+public class PromotionsFileHandler {
+ private static final Path PROMOTIONS_FILE_PATH = Path.of("src/main/resources/promotions.md");
+ public static final String NON_PROMOTION_NAME = "null";
+ public static final Promotion NON_PROMOTION = new Promotion(NON_PROMOTION_NAME, 1, 0);
+ private static final Map<String, Promotion> promotions = new HashMap<>();
+
+ public void loadPromotions() throws IOException {
+ List<String> lines = Files.readAllLines(PROMOTIONS_FILE_PATH);
+ promotions.put(NON_PROMOTION_NAME, NON_PROMOTION);
+ lines.stream().skip(1).forEach(this::processPromotionLine); // Skip header line
+ }
+
+ private void processPromotionLine(String line) {
+ String[] parts = parseAndTrimLine(line);
+ String name = parts[0];
+ int discountRate = Integer.parseInt(parts[1]);
+ int limit = Integer.parseInt(parts[2]);
+
+ if (isPromotionValid(parts)) {
+ promotions.put(name, new Promotion(name, discountRate, limit));
+ }
+ }
+
+ private String[] parseAndTrimLine(String line) {
+ return Arrays.stream(line.split(","))
+ .map(String::trim)
+ .toArray(String[]::new);
+ }
+
+ private boolean isPromotionValid(String[] parts) {
+ LocalDate today = DateTimes.now().toLocalDate();
+ LocalDate startDate = LocalDate.parse(parts[3]);
+ LocalDate endDate = LocalDate.parse(parts[4]);
+ return !today.isBefore(startDate) && !today.isAfter(endDate);
+ }
+
+ public static Promotion getPromotionByName(String name) {
+ return promotions.getOrDefault(name, promotions.get(NON_PROMOTION_NAME));
+ }
+} | Java | ๋ฉ์๋์ ์ด๋ฆ์ผ๋ก ์ด๋ป๊ฒ ๋ช
์ํ๋ฉด ๋ ๊น์? ๋ณ๋์ ๋ฉ์๋๋ก ๋ถ๋ฆฌํ๋ผ๋ ์๋ฏธ์ด์ค๊น์? |
@@ -0,0 +1,19 @@
+name,price,quantity,promotion
+์ฝ๋ผ,1000,10,ํ์ฐ2+1
+์ฝ๋ผ,1000,10,null
+์ฌ์ด๋ค,1000,8,ํ์ฐ2+1
+์ฌ์ด๋ค,1000,7,null
+์ค๋ ์ง์ฃผ์ค,1800,9,MD์ถ์ฒ์ํ
+์ค๋ ์ง์ฃผ์ค,1800,0,null
+ํ์ฐ์,1200,5,ํ์ฐ2+1
+ํ์ฐ์,1200,0,null
+๋ฌผ,500,10,null
+๋นํ๋ฏผ์ํฐ,1500,6,null
+๊ฐ์์นฉ,1500,5,๋ฐ์งํ ์ธ
+๊ฐ์์นฉ,1500,5,null
+์ด์ฝ๋ฐ,1200,5,MD์ถ์ฒ์ํ
+์ด์ฝ๋ฐ,1200,5,null
+์๋์ง๋ฐ,2000,5,null
+์ ์๋์๋ฝ,6400,8,null
+์ปต๋ผ๋ฉด,1700,1,MD์ถ์ฒ์ํ
+์ปต๋ผ๋ฉด,1700,10,null | Unknown | ์๋ณธ products.md ํ์ผ์ ํ์ผ ์ด๋ฆ๊ณผ ๋ฐ์ดํฐ๋ฅผ ์์ ๋ณ๊ฒฝํ์ง ์์์ต๋๋ค! product.md๋ก ์๋ก์ด stocks.md ํ์ผ์ ์์ฑํด ์ํ ๋ฐ์ดํฐ ์ฒ๋ฆฌ๋ฅผ ํ์ต๋๋ค! |
@@ -0,0 +1,5 @@
+const API_URL = `${import.meta.env.VITE_API_URL}`;
+
+export const PRODUCTS_ENDPOINT = `${API_URL}/products`;
+export const CART_ITEMS_ENDPOINT = `${API_URL}/cart-items`;
+export const CART_ITEMS_COUNTS_ENDPOINT = `${CART_ITEMS_ENDPOINT}/counts`; | TypeScript | ์ด๋ฐ endpoint๋ค์ ํ๋์ ๊ฐ์ฒด๋ก ๊ด๋ฆฌํด๋ ์ข์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,49 @@
+const generateBasicToken = (userId: string, userPassword: string): string => {
+ const token = btoa(`${userId}:${userPassword}`);
+ return `Basic ${token}`;
+};
+
+const API_URL = `${import.meta.env.VITE_API_URL}`;
+const USER_ID = `${import.meta.env.VITE_USER_ID}`;
+const USER_PASSWORD = `${import.meta.env.VITE_USER_PASSWORD}`;
+
+if (!API_URL || !USER_ID || !USER_PASSWORD) {
+ throw new Error(
+ "API_URL, USER_ID, PASSWORD environment variables are not set"
+ );
+}
+
+type HttpMethod = "GET" | "POST" | "PATCH" | "DELETE";
+
+interface RequestOptions {
+ method: HttpMethod;
+ body?: Record<string, unknown>;
+}
+
+export const fetchWithAuth = async (path: string, options: RequestOptions) => {
+ const requestInit = requestBuilder(options);
+ const response = await fetch(path, requestInit);
+
+ if (!response.ok) {
+ throw new Error(`Failed to ${options.method} ${path}`);
+ }
+
+ return response;
+};
+
+const requestBuilder = (options: RequestOptions): RequestInit => {
+ const token = generateBasicToken(USER_ID, USER_PASSWORD);
+
+ const { method, body } = options;
+
+ const headers: HeadersInit = {
+ "Content-Type": "application/json",
+ Authorization: token,
+ };
+
+ return {
+ method,
+ headers,
+ body: body ? JSON.stringify(body) : undefined,
+ };
+}; | TypeScript | fetch์ ํ์ํ ์ค๋ณต๋ ๋ก์ง์ ๋ถ๋ฆฌํ ๋ถ๋ถ. ์ธ์์ ์
๋๋ค. |
@@ -0,0 +1,25 @@
+import { useEffect } from "react";
+import { useErrorContext } from "../../hooks/useErrorContext";
+import { ErrorToastStyle } from "./ErrorToast.style";
+
+const ErrorToast = () => {
+ const { error, hideError } = useErrorContext();
+
+ useEffect(() => {
+ setTimeout(() => {
+ hideError();
+ }, 3000);
+ }, [error, hideError]);
+
+ if (!error) {
+ return null;
+ }
+
+ return (
+ <ErrorToastStyle>
+ ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค. ์ ์ ํ ๋ค์ ์๋ํด ์ฃผ์ธ์.
+ </ErrorToastStyle>
+ );
+};
+
+export default ErrorToast; | Unknown | toast๋ฅผ ๋์ด์ค ์๊ฐ์ ๋ฐ๋ก ์์๋ก ๊ด๋ฆฌํ๋ ๊ฒ๋ ์ข์ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,51 @@
+import useProducts from "../../hooks/useProducts";
+import ProductListHeader from "../ProductListHeader/ProductListHeader";
+import ProductItem from "./ProductItem/ProductItem";
+import * as PL from "./ProductList.style";
+import useInfiniteScroll from "../../hooks/useInfiniteScroll";
+import usePagination from "../../hooks/usePagination";
+
+const ProductList = () => {
+ const { page, nextPage, resetPage } = usePagination();
+
+ const { products, loading, hasMore, handleCategory, handleSort } =
+ useProducts({
+ page,
+ resetPage,
+ });
+
+ const { lastElementRef: lastProductElementRef } = useInfiniteScroll({
+ hasMore,
+ loading,
+ nextPage,
+ });
+
+ return (
+ <>
+ <ProductListHeader
+ handleCategory={handleCategory}
+ handleSort={handleSort}
+ />
+ {!loading && products.length === 0 ? (
+ <PL.Empty>์ํ์ด ์กด์ฌํ์ง ์์ต๋๋ค! ๐ฅฒ</PL.Empty>
+ ) : (
+ <PL.ProductListStyle>
+ {products.map((item, index) => {
+ return (
+ <ProductItem
+ product={item}
+ key={item.id}
+ ref={
+ index === products.length - 1 ? lastProductElementRef : null
+ }
+ />
+ );
+ })}
+ </PL.ProductListStyle>
+ )}
+ {loading && <PL.Loading>๋ก๋ฉ์ค! ๐ช</PL.Loading>}
+ </>
+ );
+};
+
+export default ProductList; | Unknown | ํ์ฌ ์๋ก์ด fetch๋ฅผ ํตํด ์๋ก์ด ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ง๊ณ ์ค๋ฉด ์คํฌ๋กค ์์น๊ฐ ๊ฐ์ ๋ก ์ฌ๋ผ๊ฐ๋ ๋ฒ๊ทธ๊ฐ ์์ต๋๋ค. ์ ๊ฐ ์๊ฐํ๊ธฐ์๋ ProductListStyle๊ฐ ์กฐ๊ฑด๋ถ๋ก ๋ ๋๋ง๋์ด ์ปดํฌ๋ํธ๊ฐ ๋งค๋ฒ ์๋กญ๊ฒ ๋ง๋ค์ด์ง๋๋ค. ๊ทธ๋์ ๋ฆฌ์กํธ๊ฐ ๋์ผํ ์ปดํฌ๋ํธ๋ก ์ธ์งํ์ง ๋ชปํด์ ๋ฐ์ํ ๋ฌธ์ ๊ฐ์ต๋๋ค. ๋ค์๊ณผ ๊ฐ์ ์ฝ๋๋ก ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค.
```tsx
return (
<>
<ProductListHeader
handleCategory={handleCategory}
handleSort={handleSort}
/>
{products !== null && (
<PL.ProductListStyle>
{products.map((item, index) => {
return (
<ProductItem
product={item}
key={`${item.id}${index}`}
/>
);
})}
</PL.ProductListStyle>
)}
{!loading && products.length === 0 && (
<PL.Empty>์ํ์ด ์กด์ฌํ์ง ์์ต๋๋ค! ๐ฅฒ</PL.Empty>
)}
{loading && <PL.Loading>๋ก๋ฉ์ค! ๐ช</PL.Loading>}
{!loading && (
<div
ref={lastProductElementRef}
style={{ height: '30px', fontSize: '5rem' }}
></div>
)}
</>
);
};
```
์ด๋ฐ ๋ฐฉ์์ผ๋ก ๋ ๋๋งํ๊ฒ๋๋ฉด ProductListStyle์์น๋ products๊ฐ null์ด ์๋ ์ด์์์ผ ๊ณ์ ๊ฐ์ ์์น์ ์กด์ฌํ๋ฏ๋ก ์คํฌ๋กค์ด ์๋ก ์ฌ๋ผ๊ฐ์ง ์์ต๋๋ค. |
@@ -0,0 +1,49 @@
+const generateBasicToken = (userId: string, userPassword: string): string => {
+ const token = btoa(`${userId}:${userPassword}`);
+ return `Basic ${token}`;
+};
+
+const API_URL = `${import.meta.env.VITE_API_URL}`;
+const USER_ID = `${import.meta.env.VITE_USER_ID}`;
+const USER_PASSWORD = `${import.meta.env.VITE_USER_PASSWORD}`;
+
+if (!API_URL || !USER_ID || !USER_PASSWORD) {
+ throw new Error(
+ "API_URL, USER_ID, PASSWORD environment variables are not set"
+ );
+}
+
+type HttpMethod = "GET" | "POST" | "PATCH" | "DELETE";
+
+interface RequestOptions {
+ method: HttpMethod;
+ body?: Record<string, unknown>;
+}
+
+export const fetchWithAuth = async (path: string, options: RequestOptions) => {
+ const requestInit = requestBuilder(options);
+ const response = await fetch(path, requestInit);
+
+ if (!response.ok) {
+ throw new Error(`Failed to ${options.method} ${path}`);
+ }
+
+ return response;
+};
+
+const requestBuilder = (options: RequestOptions): RequestInit => {
+ const token = generateBasicToken(USER_ID, USER_PASSWORD);
+
+ const { method, body } = options;
+
+ const headers: HeadersInit = {
+ "Content-Type": "application/json",
+ Authorization: token,
+ };
+
+ return {
+ method,
+ headers,
+ body: body ? JSON.stringify(body) : undefined,
+ };
+}; | TypeScript | fetch์ ๊ณตํต๋ ๋ก์ง์ ๋๋ฒ์ด๋ ๊ฐ์ธ์ ๊น๋ํ๊ฒ ์ ๋ฆฌํด ์ค ๊ฒ์ด ๋ง์์ ๋๋ค์~!
์ ๋ฏธ์
์๋ ์ ์ฉ์์ผ๋ด์ผ๊ฒ ์ด์ ใ
ใ
ใ
๐ ๐๐๐ |
@@ -0,0 +1,118 @@
+import { RULE } from "../constants/rules";
+import {
+ CART_ITEMS_COUNTS_ENDPOINT,
+ CART_ITEMS_ENDPOINT,
+ PRODUCTS_ENDPOINT,
+} from "./endpoints";
+import { fetchWithAuth } from "./fetchWithAuth";
+
+interface QueryParams {
+ [key: string]:
+ | undefined
+ | string
+ | number
+ | boolean
+ | (string | number | boolean)[];
+}
+
+export interface GetProductsParams {
+ category?: Category;
+ page?: number;
+ size?: number;
+ sort?: Sort;
+}
+
+const createQueryString = (params: QueryParams): string => {
+ return Object.entries(params)
+ .map(([key, value]) => {
+ if (value === undefined) {
+ return;
+ }
+ if (Array.isArray(value)) {
+ return `${encodeURIComponent(key)}=${encodeURIComponent(
+ value.join(",")
+ )}`;
+ }
+ return `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`;
+ })
+ .join("&");
+};
+
+export const getProducts = async ({
+ category,
+ page = 0,
+ size = 20,
+ sort = "asc",
+}: GetProductsParams = {}) => {
+ const params = {
+ category,
+ page,
+ size,
+ sort: ["price", sort],
+ };
+ const queryString = createQueryString(params) + RULE.sortQueryByIdAsc;
+
+ const response = await fetchWithAuth(`${PRODUCTS_ENDPOINT}?${queryString}`, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get products item");
+ }
+
+ return data;
+};
+
+export const postProductInCart = async (
+ productId: number,
+ quantity: number = 1
+) => {
+ const response = await fetchWithAuth(CART_ITEMS_ENDPOINT, {
+ method: "POST",
+ body: {
+ productId,
+ quantity,
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to post product item in cart");
+ }
+};
+
+export const deleteProductInCart = async (cartId: number) => {
+ const response = await fetchWithAuth(`${CART_ITEMS_ENDPOINT}/${cartId}`, {
+ method: "DELETE",
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to delete product item in cart");
+ }
+};
+
+export const getCartItemsCount = async () => {
+ const response = await fetchWithAuth(CART_ITEMS_COUNTS_ENDPOINT, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get cart items count");
+ }
+
+ return data;
+};
+
+export const getCartItems = async (): Promise<CartItem[]> => {
+ const response = await fetchWithAuth(CART_ITEMS_ENDPOINT, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get cart items count");
+ }
+
+ return data.content;
+}; | TypeScript | ์๋ง key๋ก ์ ๊ทผํด์ ๊ฐ์ ๊ฐ์ ธ์ค๊ธฐ ์ํด์ index signature๋ฅผ ์ฌ์ฉํ๋ ค๊ณ ํ์
จ๋ ๊ฑธ๊น์?!
ํ์ง๋ง ์ด๋ ๊ฒ ๋๋ฉด, ์์์น ๋ชปํ๊ฒ `page = "page1"` ๊ณผ ๊ฐ์ prop์ด๋
์๋ํ์ง ์์ key๊ฐ์ด ๋ค์ด์ฌ ๊ฒฝ์ฐ, queryParams interface์์ ๊ฑธ๋ฌ์ง์ง ์์ ๊ฒ ๊ฐ์์.
์ฌ์ ์์ผ์ค ๋ ํ๋ฒ ์๊ฐํด ๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์์ :) |
@@ -0,0 +1,34 @@
+import styled from "styled-components";
+
+export const ButtonStyle = styled.button`
+ cursor: pointer;
+ border: none;
+ outline: none;
+`;
+
+export const CartControlButtonStyle = styled(ButtonStyle)`
+ display: flex;
+ position: absolute;
+ right: 8px;
+ align-items: center;
+ border-radius: 4px;
+ padding: 4px 8px;
+ gap: 1px;
+ bottom: 15px;
+ font-weight: 600;
+ font-size: 12px;
+
+ img {
+ width: 14px;
+ height: 14px;
+ }
+`;
+
+export const AddCartStyle = styled(CartControlButtonStyle)`
+ background-color: #000000;
+ color: #ffffff;
+`;
+export const RemoveCartStyle = styled(CartControlButtonStyle)`
+ background-color: #eaeaea;
+ color: #000000;
+`; | TypeScript | ์ ๋ Button์ Prop์ ๋ฐ์์ ์์์ ๋ฐ๊ฟ์ฃผ๋ ์์ผ๋ก ์์ฑํ์ด์!
```suggestion
export const ButtonStyle = styled.button<ButtonProps>`
cursor: pointer;
border: none;
outline: none;
${({ color }) => {
if (color === "primary") {
return `
background-color: black;
color: white;
`;
}
if (color === "secondary") {
return `
background-color: lightGrey;
color: black;
`;
}
return `
background-color: white;
color: black;
border: 1px solid lightGray;
`;
}}
`;
```
style์ ์ฝ๋๊ฐ ๋ณด๊ธฐ ์ข์ง ์์ง๋ง, ์ฌ์ฉํ๋ ๊ณณ์์ ๋ณ๋์ ํ๊ทธ๋ฅผ ์ ์ธํ์ง ์์๋ ์ธ ์ ์๋ ์ฅ์ ์ด ์๋๋ผ๊ตฌ์~
์๋ง ์์ผ์ ์ฝ๋์์๋ ์ด๋ ๊ฒ ๋๊ฒ ๋ค์
```tsx
const CartControlButton = ({ isInCart, onClick }: CartControlButtonProps) => {
return (
<CartControlButtonStyle onClick={onClick} $color={isInCart?'secondary':'primary'}>
<img src={isInCart?RemoveCart:AddCart} alt={isInCart?'์ฅ๋ฐ๊ตฌ๋ ๋นผ๊ธฐ':'์ฅ๋ฐ๊ตฌ๋ ๋ํ๊ธฐ'} />
<span>{isInCart?'๋นผ๊ธฐ':'๋ํ๊ธฐ'}</span>
</CartControlButtonStyle>
);
};
```
๋ง์ ๋ค ์ ๊ณ ๋ณด๋๊น, ์์ผ์ ์ฝ๋๊ฐ ๋ ๊น๋ํด ๋ณด์ด๋ค์ ใ
ใ
ใ
ใ
ใ
์ฐธ๊ณ ํ์ค ์ ์์ ๊ฒ ๊ฐ์์ ์ ์ด๋ดค๊ณ , ์ ๋ ์ ์ ๋ค๋ฅธ ์ฝ๋ ๋ฐฉ์์ ๋ณด๋ ์ฌ๋ฐ์์ต๋๋ค :) |
@@ -0,0 +1,39 @@
+import styled from "styled-components";
+
+export const HeaderStyle = styled.header`
+ display: flex;
+ background-color: #000000;
+ width: inherit;
+ height: 64px;
+ position: fixed;
+ z-index: 1;
+ padding: 16px 24px 16px;
+ box-sizing: border-box;
+`;
+
+export const LogoImg = styled.img`
+ width: 56px;
+`;
+
+export const CartImg = styled.img`
+ width: 32px;
+ position: absolute;
+ right: 24px;
+ bottom: 16px;
+`;
+
+export const CartCount = styled.div`
+ background-color: #ffffff;
+ border-radius: 999px;
+ width: 19px;
+ height: 19px;
+ font-size: 10px;
+ font-weight: 700;
+ position: absolute;
+ right: 24px;
+ bottom: 16px;
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+`; | TypeScript | ํ๋ก์ ํธ์ ์ปดํฌ๋ํธ ๊ท๋ชจ๊ฐ ๋ณต์กํด์ง๋ฉด, zindex ๊ด๋ฆฌ๊ฐ ํ๋ค๋๋ผ๊ตฌ์
ํค๋๋ฅผ 1๋ก ํด๋จ๋๋ฐ, ํค๋๋ณด๋ค ๋ฎ์ ์ด๋ ํ component๊ฐ ์๊ธธ์๋ ์๊ณ ...!
๊ทธ๋์ ์ ๋ ์ถ์ฒ๋ฐ์ ๋ฐฉ๋ฒ์ด zIndex๋ค์ ์์๋ก ๊ด๋ฆฌํด์ ํ๊ณณ์์ ํธํ๊ฒ ๋ณผ ์ ์๋๋ก ํ๋๊ฑฐ์์ด์
์ ๋ ์์ฃผ ์ฌ์ฉํ์ง ์์ง๋ง, ๊ฟํ ๊ณต์ ํด๋ด
๋๋ค ใ
ใ
|
@@ -0,0 +1,57 @@
+import {
+ createContext,
+ useState,
+ ReactNode,
+ useEffect,
+ useCallback,
+} from "react";
+import { getCartItems } from "../api";
+import { useErrorContext } from "../hooks/useErrorContext";
+
+export interface CartItemsContextType {
+ cartItems: CartItem[];
+ refreshCartItems: () => void;
+}
+
+export const CartItemsContext = createContext<CartItemsContextType | undefined>(
+ undefined
+);
+
+interface CartItemsProviderProps {
+ children: ReactNode;
+}
+
+export const CartItemsProvider: React.FC<CartItemsProviderProps> = ({
+ children,
+}) => {
+ const { showError } = useErrorContext();
+
+ const [toggle, setToggle] = useState(false);
+
+ const [cartItems, setCartItems] = useState<CartItem[]>([]);
+
+ const refreshCartItems = useCallback(() => {
+ setToggle((prev) => !prev);
+ }, []);
+
+ useEffect(() => {
+ const fetchCartItems = async () => {
+ try {
+ const cartItems = await getCartItems();
+ setCartItems(cartItems);
+ } catch (error) {
+ if (error instanceof Error) {
+ showError(error.message);
+ }
+ }
+ };
+
+ fetchCartItems();
+ }, [toggle, showError]);
+
+ return (
+ <CartItemsContext.Provider value={{ cartItems, refreshCartItems }}>
+ {children}
+ </CartItemsContext.Provider>
+ );
+}; | Unknown | ์ ๋ Quantity๋ง์ context๋ก ๊ด๋ฆฌํ๋๋ฐ, ์ ์ฒด List๋ฅผ context ๋ก ๊ด๋ฆฌํ์
จ๊ตฐ์!!
Provider๋ฅผ custom ํด์ฃผ๋ ๊ฒ๋ ๋งค์ฐ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค :)
์ข์ ์ ๋ณด ๋ฐฐ์ฐ๊ณ ๊ฐ๋๋ค!! |
@@ -0,0 +1,34 @@
+import styled from "styled-components";
+
+export const ButtonStyle = styled.button`
+ cursor: pointer;
+ border: none;
+ outline: none;
+`;
+
+export const CartControlButtonStyle = styled(ButtonStyle)`
+ display: flex;
+ position: absolute;
+ right: 8px;
+ align-items: center;
+ border-radius: 4px;
+ padding: 4px 8px;
+ gap: 1px;
+ bottom: 15px;
+ font-weight: 600;
+ font-size: 12px;
+
+ img {
+ width: 14px;
+ height: 14px;
+ }
+`;
+
+export const AddCartStyle = styled(CartControlButtonStyle)`
+ background-color: #000000;
+ color: #ffffff;
+`;
+export const RemoveCartStyle = styled(CartControlButtonStyle)`
+ background-color: #eaeaea;
+ color: #000000;
+`; | TypeScript | Button์ `hover` ์์ฑ๋ ์์ผ๋ฉด ์ด๋จ๊น ์ถ๋ค์! |
@@ -0,0 +1,37 @@
+import { forwardRef } from "react";
+import * as PI from "./ProductItem.style";
+import CartControlButton from "../../Button/CartControlButton";
+import useProductInCart from "../../../hooks/useProductInCart";
+
+interface ProductProps {
+ product: Product;
+}
+
+const ProductItem = forwardRef<HTMLDivElement, ProductProps>(
+ ({ product }, ref) => {
+ const { isProductInCart, handleProductInCart } = useProductInCart(
+ product.id
+ );
+
+ return (
+ <PI.ProductItemStyle ref={ref}>
+ <PI.ProductImg
+ src={`${product.imageUrl}`}
+ alt={`${product.name} ์ํ ์ด๋ฏธ์ง`}
+ />
+ <PI.ProductGroup>
+ <PI.ProductContent>
+ <PI.ProductName>{product.name}</PI.ProductName>
+ <span>{product.price.toLocaleString("ko-kr")}์</span>
+ </PI.ProductContent>
+ <CartControlButton
+ onClick={handleProductInCart}
+ isInCart={isProductInCart}
+ />
+ </PI.ProductGroup>
+ </PI.ProductItemStyle>
+ );
+ }
+);
+
+export default ProductItem; | Unknown | ํน์ try-catch ์์ catch๋๋ error๊ฐ `Error` ํ์
์ด ์๋ ๊ฒฝ์ฐ๋ ์๋์?!
๋จ์ํ ๊ถ๊ธํด์ ์ฌ์ญค๋ด
๋๋ค...!
catch๋๋ ๊ฒ์ Error๋ง catch๋๋์ค ์์์, ์ด ๋ก์ง์ด ํ์ํ๊ฐ ํ๋ ์๊ฐ์ด ๋ค์์ด์ ใ
ใ
|
@@ -0,0 +1,51 @@
+import useProducts from "../../hooks/useProducts";
+import ProductListHeader from "../ProductListHeader/ProductListHeader";
+import ProductItem from "./ProductItem/ProductItem";
+import * as PL from "./ProductList.style";
+import useInfiniteScroll from "../../hooks/useInfiniteScroll";
+import usePagination from "../../hooks/usePagination";
+
+const ProductList = () => {
+ const { page, nextPage, resetPage } = usePagination();
+
+ const { products, loading, hasMore, handleCategory, handleSort } =
+ useProducts({
+ page,
+ resetPage,
+ });
+
+ const { lastElementRef: lastProductElementRef } = useInfiniteScroll({
+ hasMore,
+ loading,
+ nextPage,
+ });
+
+ return (
+ <>
+ <ProductListHeader
+ handleCategory={handleCategory}
+ handleSort={handleSort}
+ />
+ {!loading && products.length === 0 ? (
+ <PL.Empty>์ํ์ด ์กด์ฌํ์ง ์์ต๋๋ค! ๐ฅฒ</PL.Empty>
+ ) : (
+ <PL.ProductListStyle>
+ {products.map((item, index) => {
+ return (
+ <ProductItem
+ product={item}
+ key={item.id}
+ ref={
+ index === products.length - 1 ? lastProductElementRef : null
+ }
+ />
+ );
+ })}
+ </PL.ProductListStyle>
+ )}
+ {loading && <PL.Loading>๋ก๋ฉ์ค! ๐ช</PL.Loading>}
+ </>
+ );
+};
+
+export default ProductList; | Unknown | ์ค... ํด๊ฒฐ๋ฒ ์ ์๊น์ง ๋๋จํ๋ค์ ๐ ๐๐๐๐๐๐ |
@@ -0,0 +1,49 @@
+const generateBasicToken = (userId: string, userPassword: string): string => {
+ const token = btoa(`${userId}:${userPassword}`);
+ return `Basic ${token}`;
+};
+
+const API_URL = `${import.meta.env.VITE_API_URL}`;
+const USER_ID = `${import.meta.env.VITE_USER_ID}`;
+const USER_PASSWORD = `${import.meta.env.VITE_USER_PASSWORD}`;
+
+if (!API_URL || !USER_ID || !USER_PASSWORD) {
+ throw new Error(
+ "API_URL, USER_ID, PASSWORD environment variables are not set"
+ );
+}
+
+type HttpMethod = "GET" | "POST" | "PATCH" | "DELETE";
+
+interface RequestOptions {
+ method: HttpMethod;
+ body?: Record<string, unknown>;
+}
+
+export const fetchWithAuth = async (path: string, options: RequestOptions) => {
+ const requestInit = requestBuilder(options);
+ const response = await fetch(path, requestInit);
+
+ if (!response.ok) {
+ throw new Error(`Failed to ${options.method} ${path}`);
+ }
+
+ return response;
+};
+
+const requestBuilder = (options: RequestOptions): RequestInit => {
+ const token = generateBasicToken(USER_ID, USER_PASSWORD);
+
+ const { method, body } = options;
+
+ const headers: HeadersInit = {
+ "Content-Type": "application/json",
+ Authorization: token,
+ };
+
+ return {
+ method,
+ headers,
+ body: body ? JSON.stringify(body) : undefined,
+ };
+}; | TypeScript | `requestBuilder` ๋ผ๋ ์ด๋ฆ์ผ๋ก ์์ฒญ์ ๋ง๋๋ ์ฑ
์์ ๊ฐ์ง ํจ์๋ฅผ ๋ณ๋๋ก ๋ถ๋ฆฌํด์ฃผ์ ๋ถ๋ถ์ด ์ธ์๊น๋ค์!๐๐ |
@@ -0,0 +1,57 @@
+import {
+ createContext,
+ useState,
+ ReactNode,
+ useEffect,
+ useCallback,
+} from "react";
+import { getCartItems } from "../api";
+import { useErrorContext } from "../hooks/useErrorContext";
+
+export interface CartItemsContextType {
+ cartItems: CartItem[];
+ refreshCartItems: () => void;
+}
+
+export const CartItemsContext = createContext<CartItemsContextType | undefined>(
+ undefined
+);
+
+interface CartItemsProviderProps {
+ children: ReactNode;
+}
+
+export const CartItemsProvider: React.FC<CartItemsProviderProps> = ({
+ children,
+}) => {
+ const { showError } = useErrorContext();
+
+ const [toggle, setToggle] = useState(false);
+
+ const [cartItems, setCartItems] = useState<CartItem[]>([]);
+
+ const refreshCartItems = useCallback(() => {
+ setToggle((prev) => !prev);
+ }, []);
+
+ useEffect(() => {
+ const fetchCartItems = async () => {
+ try {
+ const cartItems = await getCartItems();
+ setCartItems(cartItems);
+ } catch (error) {
+ if (error instanceof Error) {
+ showError(error.message);
+ }
+ }
+ };
+
+ fetchCartItems();
+ }, [toggle, showError]);
+
+ return (
+ <CartItemsContext.Provider value={{ cartItems, refreshCartItems }}>
+ {children}
+ </CartItemsContext.Provider>
+ );
+}; | Unknown | `useCallback`๊ณผ`toggle`์ด๋ผ๋ ์ํ๋ฅผ ํตํด `fetchCartItems`์ ์ฌ์คํ์ํจ๋ค๋ ๋ฐ์์ด ๋ชน์ ์๋กญ๊ฒ ๋๊ปด์ง๋ค์! ํ ๋ฒ๋ ์๊ฐํด๋ณด์ง ๋ชปํ๋ ๋ฐฉ์์ธ๋ฐ... ์ํ๋ ์ต์ํ๋์ด์ผ ํ๋ค๊ณ ์๊ฐํ๋ ํธ์ด์ง๋ง, ํน์ ํธ๋ฆฌ๊ฑฐ๋ฅผ ์ํด ์ํ๋ฅผ ํ์ฉํ๋ ๊ฒ์ด ์ข์์ง ์ ๋ ํ ๋ฒ ๊ณ ๋ฏผํด๋ณผ ์ ์์๋ ๊ฒ ๊ฐ์์!
ํํธ์ผ๋ก๋ ์ํ๋ฅผ ๋ง๋ค์ง์๊ณ , `fetchCartItems`๋ก์ง์ `useEffect` ๋ฐ์ผ๋ก ๋บ ๋ค refreshCartItems ์ ์ ์์ฑํด์ฃผ๋ฉด ์ํ๊ฐ ํ์ํ์ง ์์ ๊ฒ ๊ฐ๋ค๋ ์๊ฐ์ด ๋ค๊ธฐ๋ ํฉ๋๋ค! (์ด ๋ถ๋ถ์ ๊ฐ๋ฐ์์ ์ทจํฅ์ด๋ ์ ํธ์ ๊ฐ๊น์ธ ์ ์์ ๊ฒ ๊ฐ์์..!) |
@@ -0,0 +1,15 @@
+import { useContext } from "react";
+import {
+ CartItemsContext,
+ CartItemsContextType,
+} from "../context/CartItemsContext";
+
+export const useCartItemsContext = (): CartItemsContextType => {
+ const context = useContext(CartItemsContext);
+ if (!context) {
+ throw new Error(
+ "useCartItemsContext must be used within an CartItemsProvider"
+ );
+ }
+ return context;
+}; | TypeScript | ํ์ฌ `useErrorContext`์ `useCartItemsContext`๋ context๊ฐ `undefined`์ธ ๊ฒฝ์ฐ ์๋ฌ๋ฅผ ๋์ ธ ํ์
์ ์ขํ๊ธฐ ์ํ ์ปค์คํ
ํ
์ธ ๊ฒ ๊ฐ์ต๋๋ค. ์ ๊ฐ ๋๋ผ๊ธฐ์ ๋ ํ
๋ชจ๋ ๊ฐ์ ์ญํ ์ ํด์ฃผ๊ณ ์๋ ๊ฒ ๊ฐ์์ context๋ฅผ ์ธ์๋ก ๋ฐ๋๋ค๋ฉด ํ๋์ ํ
์ผ๋ก ํฉ์ณ์ ์ฌ์ฌ์ฉํด์ฃผ์ด๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค!ใ
ใ
|
@@ -0,0 +1,118 @@
+import { RULE } from "../constants/rules";
+import {
+ CART_ITEMS_COUNTS_ENDPOINT,
+ CART_ITEMS_ENDPOINT,
+ PRODUCTS_ENDPOINT,
+} from "./endpoints";
+import { fetchWithAuth } from "./fetchWithAuth";
+
+interface QueryParams {
+ [key: string]:
+ | undefined
+ | string
+ | number
+ | boolean
+ | (string | number | boolean)[];
+}
+
+export interface GetProductsParams {
+ category?: Category;
+ page?: number;
+ size?: number;
+ sort?: Sort;
+}
+
+const createQueryString = (params: QueryParams): string => {
+ return Object.entries(params)
+ .map(([key, value]) => {
+ if (value === undefined) {
+ return;
+ }
+ if (Array.isArray(value)) {
+ return `${encodeURIComponent(key)}=${encodeURIComponent(
+ value.join(",")
+ )}`;
+ }
+ return `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`;
+ })
+ .join("&");
+};
+
+export const getProducts = async ({
+ category,
+ page = 0,
+ size = 20,
+ sort = "asc",
+}: GetProductsParams = {}) => {
+ const params = {
+ category,
+ page,
+ size,
+ sort: ["price", sort],
+ };
+ const queryString = createQueryString(params) + RULE.sortQueryByIdAsc;
+
+ const response = await fetchWithAuth(`${PRODUCTS_ENDPOINT}?${queryString}`, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get products item");
+ }
+
+ return data;
+};
+
+export const postProductInCart = async (
+ productId: number,
+ quantity: number = 1
+) => {
+ const response = await fetchWithAuth(CART_ITEMS_ENDPOINT, {
+ method: "POST",
+ body: {
+ productId,
+ quantity,
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to post product item in cart");
+ }
+};
+
+export const deleteProductInCart = async (cartId: number) => {
+ const response = await fetchWithAuth(`${CART_ITEMS_ENDPOINT}/${cartId}`, {
+ method: "DELETE",
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to delete product item in cart");
+ }
+};
+
+export const getCartItemsCount = async () => {
+ const response = await fetchWithAuth(CART_ITEMS_COUNTS_ENDPOINT, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get cart items count");
+ }
+
+ return data;
+};
+
+export const getCartItems = async (): Promise<CartItem[]> => {
+ const response = await fetchWithAuth(CART_ITEMS_ENDPOINT, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get cart items count");
+ }
+
+ return data.content;
+}; | TypeScript | ๋ชน์ ํฅ๋ฏธ๋ก์ด ํจ์๋ค์!๐๐ ๋ณ๊ฑฐ ์๋์ง๋ง ์ด๋ฌํ ๋ถ๋ถ์ api ๋ด๋ถ util๋ก ํ์ผ์ ๋ถ๋ฆฌํด์ฃผ์
๋ ์ข์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,118 @@
+import { RULE } from "../constants/rules";
+import {
+ CART_ITEMS_COUNTS_ENDPOINT,
+ CART_ITEMS_ENDPOINT,
+ PRODUCTS_ENDPOINT,
+} from "./endpoints";
+import { fetchWithAuth } from "./fetchWithAuth";
+
+interface QueryParams {
+ [key: string]:
+ | undefined
+ | string
+ | number
+ | boolean
+ | (string | number | boolean)[];
+}
+
+export interface GetProductsParams {
+ category?: Category;
+ page?: number;
+ size?: number;
+ sort?: Sort;
+}
+
+const createQueryString = (params: QueryParams): string => {
+ return Object.entries(params)
+ .map(([key, value]) => {
+ if (value === undefined) {
+ return;
+ }
+ if (Array.isArray(value)) {
+ return `${encodeURIComponent(key)}=${encodeURIComponent(
+ value.join(",")
+ )}`;
+ }
+ return `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`;
+ })
+ .join("&");
+};
+
+export const getProducts = async ({
+ category,
+ page = 0,
+ size = 20,
+ sort = "asc",
+}: GetProductsParams = {}) => {
+ const params = {
+ category,
+ page,
+ size,
+ sort: ["price", sort],
+ };
+ const queryString = createQueryString(params) + RULE.sortQueryByIdAsc;
+
+ const response = await fetchWithAuth(`${PRODUCTS_ENDPOINT}?${queryString}`, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get products item");
+ }
+
+ return data;
+};
+
+export const postProductInCart = async (
+ productId: number,
+ quantity: number = 1
+) => {
+ const response = await fetchWithAuth(CART_ITEMS_ENDPOINT, {
+ method: "POST",
+ body: {
+ productId,
+ quantity,
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to post product item in cart");
+ }
+};
+
+export const deleteProductInCart = async (cartId: number) => {
+ const response = await fetchWithAuth(`${CART_ITEMS_ENDPOINT}/${cartId}`, {
+ method: "DELETE",
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to delete product item in cart");
+ }
+};
+
+export const getCartItemsCount = async () => {
+ const response = await fetchWithAuth(CART_ITEMS_COUNTS_ENDPOINT, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get cart items count");
+ }
+
+ return data;
+};
+
+export const getCartItems = async (): Promise<CartItem[]> => {
+ const response = await fetchWithAuth(CART_ITEMS_ENDPOINT, {
+ method: "GET",
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to get cart items count");
+ }
+
+ return data.content;
+}; | TypeScript | ์ถ์ํ๋ `fetchWithAuth` ๋ด๋ถ์์ ์ด๋ฏธ `response.ok`๊ฐ ์๋ ๊ฒฝ์ฐ ์๋ฌ๋ฅผ ๋์ง๋๋ก ์ฒ๋ฆฌํด๋์๋๋ฐ ์ฌ๊ธฐ๋ฅผ ํฌํจํ์ฌ ๋ชจ๋ fetch ํจ์์์ ์ฌ์ ํ ์๋ฌ๋ฅผ ๋์ง์๋ ์ด์ ๊ฐ ์์ผ์ค๊น์..?? |
@@ -0,0 +1,78 @@
+import {
+ ChampagnePromotionAvailable,
+ receivedD_dayPromotion,
+ toTalPriceLogic,
+} from "../src/DomainLogic";
+import menuAndQuantity from "../src/utils/menuAndQuantity";
+
+jest.mock("../src/InputView", () => ({
+ christmasInstance: {
+ getMenus: jest.fn(),
+ getDate: jest.fn(),
+ },
+}));
+
+jest.mock("../src/utils/menuAndQuantity", () => ({
+ __esModule: true,
+ default: jest.fn(),
+}));
+
+jest.mock("../src/DomainLogic", () => ({
+ ...jest.requireActual("../src/DomainLogic"),
+ toTalPriceLogic: jest.fn(),
+}));
+
+describe("DomainLogic ๊ธฐ๋ฅ ํ
์คํธ", () => {
+ test("ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก", () => {
+ const mockedMenus = ["์์ก์ด์ํ-2", "์์ก์ด์ํ-1", "ํฐ๋ณธ์คํ
์ดํฌ-3"];
+ require("../src/InputView").christmasInstance.getMenus.mockReturnValue(
+ mockedMenus
+ );
+
+ menuAndQuantity
+ .mockReturnValueOnce({ MENU_NAME: "์์ก์ด์ํ", QUANTITY: 2 })
+ .mockReturnValueOnce({ MENU_NAME: "์ด์ฝ์ผ์ดํฌ", QUANTITY: 1 })
+ .mockReturnValueOnce({ MENU_NAME: "ํฐ๋ณธ์คํ
์ดํฌ", QUANTITY: 3 });
+
+ const MENUS_PRICE = {
+ ์์ก์ด์ํ: 6000,
+ ์ด์ฝ์ผ์ดํฌ: 15000,
+ ํฐ๋ณธ์คํ
์ดํฌ: 55000,
+ };
+
+ toTalPriceLogic.mockReturnValueOnce(192000);
+
+ const result = toTalPriceLogic(MENUS_PRICE);
+ const expectedTotalPrice = 2 * 6000 + 1 * 15000 + 3 * 55000;
+
+ expect(result).toBe(expectedTotalPrice);
+ });
+
+ test("์ฆ์ ๋ฉ๋ด", () => {
+ const mockedMenus = ["์์ด์คํฌ๋ฆผ-2", "์ด์ฝ์ผ์ดํฌ-1"];
+ require("../src/InputView").christmasInstance.getMenus.mockReturnValue(
+ mockedMenus
+ );
+
+ toTalPriceLogic.mockReturnValueOnce(25000);
+
+ const result = ChampagnePromotionAvailable();
+ expect(result).toBe(false);
+ });
+
+ test("ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ", () => {
+ require("../src/InputView").christmasInstance.getDate.mockReturnValue(25);
+
+ const result = receivedD_dayPromotion();
+
+ expect(result).toBe(3400);
+ });
+
+ test("ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ ์์ธ", () => {
+ require("../src/InputView").christmasInstance.getDate.mockReturnValue(26);
+
+ const result = receivedD_dayPromotion();
+
+ expect(result).toBe(0);
+ });
+}); | JavaScript | ๊ฐ ํ
์คํธ์ผ์ด์ค๋ง๋ค ์ธ์คํด์ค๋ฅผ ์์ฑํ๋ ์์ด ์๋ mock์ผ๋ก ์ฌ์ฉํ์ ์ด์ ๊ฐ ์์๊น์? |
@@ -1,5 +1,29 @@
+import { MissionUtils } from "@woowacourse/mission-utils";
+import InputView from "./InputView.js";
+import OutputView from "./OutputView.js";
+
class App {
- async run() {}
+ async run() {
+ await christmasPromotionProcess();
+ }
+}
+
+async function christmasPromotionProcess() {
+ try {
+ OutputView.printIntroduction();
+ await InputView.readDate();
+ await InputView.readOrderMenu();
+ OutputView.printBenefitIntroduction();
+ OutputView.printMenu();
+ OutputView.printTotalPrice();
+ OutputView.printChampagnePromotion();
+ OutputView.printReceivedPromotion();
+ OutputView.printReceivedTotalBenefitPrice();
+ OutputView.printTotalPriceAfterDiscount();
+ OutputView.printEventBadge();
+ } catch (error) {
+ MissionUtils.Console.print(error.message);
+ }
}
export default App; | JavaScript | ๊ฒฐ๊ณผ ์ถ๋ ฅ์ ๋ฐ๋ผ ๋ค์ ๋ฉ์๋๋ก ๋ฌถ์ด์ ๊ฐ๊ฒฐํ๊ฒ ๋ณด์ฌ์ฃผ๋ ๊ฑด ์ด๋จ๊น์?
์๋ฅผ ๋ค๋ฉด ํ์ฌ Menu๋ถํฐ Badge๊น์ง ํญ๋ชฉ๋ค์ ๋ค ๊ฒฐ๊ณผ์ถ๋ ฅ์ ํด๋น๋๋๊น printResult () ๊ฐ์ด ๋ฉ์๋๋ฅผ ํ๋ ๋ง๋ค๊ณ ๊ทธ ์์์ ์ ๋ถ ๋ค ํธ์ถํ๋ ์์ผ๋ก ๊ฐ ์ธ๋ถ์ฌํญ์ ์จ๊ธฐ๋ฉด ๋ ์ฝ๊ธฐ ํธํ ๊ฑฐ ๊ฐ์์ |
@@ -0,0 +1,86 @@
+class ChristmasPromotion {
+ #date;
+ #menus;
+
+ constructor(date, menus) {
+ this.#date = date;
+ this.#menus = menus;
+ }
+
+ #dateValidate(date) {
+ if (!(date >= 1 && date <= 31)) {
+ throw new Error("[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.");
+ }
+ }
+
+ startDateValidate(date) {
+ this.#dateValidate(date);
+ this.#date = date;
+ }
+
+ #menusValidate(menus) {
+ const SEENMENUS = new Set();
+
+ for (const menu of menus) {
+ if (!/^(.+)-(.+)$/.test(menu)) {
+ throw new Error(
+ `[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.`
+ );
+ }
+
+ const MENU_LIST = [
+ "์์ก์ด์ํ",
+ "ํํ์ค",
+ "์์ ์๋ฌ๋",
+ "ํฐ๋ณธ์คํ
์ดํฌ",
+ "๋ฐ๋นํ๋ฆฝ",
+ "ํด์ฐ๋ฌผํ์คํ",
+ "ํฌ๋ฆฌ์ค๋ง์คํ์คํ",
+ "์ด์ฝ์ผ์ดํฌ",
+ "์์ด์คํฌ๋ฆผ",
+ "์ ๋ก์ฝ๋ผ",
+ "๋ ๋์์ธ",
+ "์ดํ์ธ",
+ ];
+
+ const [MENU_PART, QUANTITY] = menu.split("-");
+ const QUANTITY_PART = parseInt(QUANTITY, 10);
+
+ if (!MENU_LIST.includes(MENU_PART)) {
+ throw new Error(
+ `[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.`
+ );
+ }
+
+ if (isNaN(QUANTITY_PART) || QUANTITY_PART <= 0) {
+ throw new Error(
+ `[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.`
+ );
+ }
+
+ // ์ค๋ณต ๋ํ
์ผํ๊ฒ ์๋ฌ ์ฒ๋ฆฌ ํ์
+ if (SEENMENUS.has(menu)) {
+ throw new Error(
+ `[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.`
+ );
+ }
+
+ SEENMENUS.add(menu);
+ }
+ }
+
+ startMenuValidate(menus) {
+ this.#menusValidate(menus);
+ this.#menus = menus;
+ }
+
+ getDate() {
+ return this.#date;
+ }
+
+ getMenus() {
+ return this.#menus;
+ }
+}
+
+export default ChristmasPromotion; | JavaScript | ์กฐ๊ฑด์ ๋ณด๋ฉด 1์์ 31๊น์ง์ ์๋ง ํ์ฉํ๋ค๋ ๊ฑด ์์ง๋ง ์ฒ์ ์ฝ๋ ์
์ฅ์์ ์ ๊ทธ ์ฌ์ด์ ์๋ง ํ์ฉ๋๋ ์ง ๋ฐ๋ก ์บ์นํ๊ธฐ๋ ์ด๋ ค์ธ ์๋ ์์ต๋๋ค.
์ด๋ฐ ๋ถ๋ถ ๋๋ฌธ์ ๋งค์ง๋๋ฒ๋ฅผ ์ ๊ฑฐํ๊ณ , ๋ณ์๋ช
์ ์ ๊ฒฝ์ ์จ์ผ ํ๋ ๋ฏ ํด์. ์ง๋ ์ฃผ์ฐจ์ ์ด ๋ถ๋ถ์ ๋ํด ์ ๋ ์ง์งํ๊ฒ ์๊ฐํ๊ณ ์์๊ณ , ์๋์ ๊ฐ์ด ๋ณ๊ฒฝํด ๋ณด์๋๋ฐ ์ด๋ฐ ์์ผ๋ก ์ ๋ชฉํด ๋ณด์๋ ๊ฑด ์ด๋จ๊น์?
```js
dayValidCheck (date) {
const date = new Date('2023-12-${date}').getDate()
if (Number.isNaN(date)) return false
return true
}
```
// ์ฌ์ฉ ์์
```js
if (dayValidCheck(date)) {
... ์ ์ ๋ก์ง
}
// ์์ธ ๋ฐ์
throw new Error("[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.");
``` |
@@ -0,0 +1,86 @@
+class ChristmasPromotion {
+ #date;
+ #menus;
+
+ constructor(date, menus) {
+ this.#date = date;
+ this.#menus = menus;
+ }
+
+ #dateValidate(date) {
+ if (!(date >= 1 && date <= 31)) {
+ throw new Error("[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.");
+ }
+ }
+
+ startDateValidate(date) {
+ this.#dateValidate(date);
+ this.#date = date;
+ }
+
+ #menusValidate(menus) {
+ const SEENMENUS = new Set();
+
+ for (const menu of menus) {
+ if (!/^(.+)-(.+)$/.test(menu)) {
+ throw new Error(
+ `[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.`
+ );
+ }
+
+ const MENU_LIST = [
+ "์์ก์ด์ํ",
+ "ํํ์ค",
+ "์์ ์๋ฌ๋",
+ "ํฐ๋ณธ์คํ
์ดํฌ",
+ "๋ฐ๋นํ๋ฆฝ",
+ "ํด์ฐ๋ฌผํ์คํ",
+ "ํฌ๋ฆฌ์ค๋ง์คํ์คํ",
+ "์ด์ฝ์ผ์ดํฌ",
+ "์์ด์คํฌ๋ฆผ",
+ "์ ๋ก์ฝ๋ผ",
+ "๋ ๋์์ธ",
+ "์ดํ์ธ",
+ ];
+
+ const [MENU_PART, QUANTITY] = menu.split("-");
+ const QUANTITY_PART = parseInt(QUANTITY, 10);
+
+ if (!MENU_LIST.includes(MENU_PART)) {
+ throw new Error(
+ `[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.`
+ );
+ }
+
+ if (isNaN(QUANTITY_PART) || QUANTITY_PART <= 0) {
+ throw new Error(
+ `[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.`
+ );
+ }
+
+ // ์ค๋ณต ๋ํ
์ผํ๊ฒ ์๋ฌ ์ฒ๋ฆฌ ํ์
+ if (SEENMENUS.has(menu)) {
+ throw new Error(
+ `[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.`
+ );
+ }
+
+ SEENMENUS.add(menu);
+ }
+ }
+
+ startMenuValidate(menus) {
+ this.#menusValidate(menus);
+ this.#menus = menus;
+ }
+
+ getDate() {
+ return this.#date;
+ }
+
+ getMenus() {
+ return this.#menus;
+ }
+}
+
+export default ChristmasPromotion; | JavaScript | ์ ๊ทํํ์์ ๋ณ์์ ๋ด์์ฃผ๋ฉด ๋ ์ฝ๊ฒ ์ดํดํ ์ ์์ ๊ฑฐ ๊ฐ์์.
์๋ฅผ ๋ค๋ฉด
```js
const MenuFormat = !/^(.+)-(.+)$/
'''
'''
for (const menu of menus) {
if (MenuFormat.test(menu)) {
'''
'''
```
์ด๋ฐ ์์ผ๋ก ๊ฐ๊ธ์ ์ฝ์ ์ ์๋ ๋ฌธ์๋ก ๋ณ๊ฒฝํด์ฃผ๋ฉด ๋ ์ข์ ๋ฏ ํฉ๋๋ค |
@@ -0,0 +1,86 @@
+class ChristmasPromotion {
+ #date;
+ #menus;
+
+ constructor(date, menus) {
+ this.#date = date;
+ this.#menus = menus;
+ }
+
+ #dateValidate(date) {
+ if (!(date >= 1 && date <= 31)) {
+ throw new Error("[ERROR] ์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.");
+ }
+ }
+
+ startDateValidate(date) {
+ this.#dateValidate(date);
+ this.#date = date;
+ }
+
+ #menusValidate(menus) {
+ const SEENMENUS = new Set();
+
+ for (const menu of menus) {
+ if (!/^(.+)-(.+)$/.test(menu)) {
+ throw new Error(
+ `[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.`
+ );
+ }
+
+ const MENU_LIST = [
+ "์์ก์ด์ํ",
+ "ํํ์ค",
+ "์์ ์๋ฌ๋",
+ "ํฐ๋ณธ์คํ
์ดํฌ",
+ "๋ฐ๋นํ๋ฆฝ",
+ "ํด์ฐ๋ฌผํ์คํ",
+ "ํฌ๋ฆฌ์ค๋ง์คํ์คํ",
+ "์ด์ฝ์ผ์ดํฌ",
+ "์์ด์คํฌ๋ฆผ",
+ "์ ๋ก์ฝ๋ผ",
+ "๋ ๋์์ธ",
+ "์ดํ์ธ",
+ ];
+
+ const [MENU_PART, QUANTITY] = menu.split("-");
+ const QUANTITY_PART = parseInt(QUANTITY, 10);
+
+ if (!MENU_LIST.includes(MENU_PART)) {
+ throw new Error(
+ `[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.`
+ );
+ }
+
+ if (isNaN(QUANTITY_PART) || QUANTITY_PART <= 0) {
+ throw new Error(
+ `[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.`
+ );
+ }
+
+ // ์ค๋ณต ๋ํ
์ผํ๊ฒ ์๋ฌ ์ฒ๋ฆฌ ํ์
+ if (SEENMENUS.has(menu)) {
+ throw new Error(
+ `[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.`
+ );
+ }
+
+ SEENMENUS.add(menu);
+ }
+ }
+
+ startMenuValidate(menus) {
+ this.#menusValidate(menus);
+ this.#menus = menus;
+ }
+
+ getDate() {
+ return this.#date;
+ }
+
+ getMenus() {
+ return this.#menus;
+ }
+}
+
+export default ChristmasPromotion; | JavaScript | includes๋ ์ฐพ๋ ์ฒซ๋ฒ์งธ ์์๋ฅผ ๋ฐฐ์ด ์ ์ฒด๋ฅผ ์ํํ๋ฉฐ ์ฐพ์์ ๋ฐํํฉ๋๋ค. ๋ฐ๋ผ์ ๊ท๋ชจ๊ฐ ์ปค์ง๋ฉด ๋นํจ์จ์ ์ผ ์๋ ์์ต๋๋ค.
find๋ ์ฐพ์ผ๋ ค๋ ์ฒซ๋ฒ์งธ ์์๋ฅผ ์ฐพ์ผ๋ฉด true๋ฅผ ๋ฐํํ๊ณ ์ข
๋ฃ๋ฉ๋๋ค. ์ ๋ ๊ทธ๋์ find๋ฅผ ์ ์ฉํ๋ ๋ฐ ๊ทธ ๋ฐ์๋ ๋ค๋ฅธ ๋ฐฉ๋ฒ๋ค๋ ์์ผ๋ ์ฌ๋ฌ ๋ฐฉ๋ฉด์ผ๋ก ์๊ฐํด ๋ณด์
๋ ์ข์ ๋ฏ ํฉ๋๋ค |
@@ -0,0 +1,174 @@
+import { christmasInstance } from "./InputView.js";
+import menuAndQuantity from "./utils/menuAndQuantity.js";
+
+const MENUS_PRICE = {
+ ์์ก์ด์ํ: 6000,
+ ํํ์ค: 5500,
+ ์์ ์๋ฌ๋: 8000,
+ ํฐ๋ณธ์คํ
์ดํฌ: 55000,
+ ๋ฐ๋นํ๋ฆฝ: 54000,
+ ํด์ฐ๋ฌผํ์คํ: 35000,
+ ํฌ๋ฆฌ์ค๋ง์คํ์คํ: 25000,
+ ์ด์ฝ์ผ์ดํฌ: 15000,
+ ์์ด์คํฌ๋ฆผ: 5000,
+ ์ ๋ก์ฝ๋ผ: 3000,
+ ๋ ๋์์ธ: 60000,
+ ์ดํ์ธ: 25000,
+};
+const WEEKDAY = [
+ 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 24, 25, 26, 27, 28, 31,
+];
+const WEEKEND = [1, 2, 8, 9, 15, 16, 22, 23, 29, 30];
+const STAR_DAY = [3, 10, 17, 24, 25, 31];
+
+export function toTalPriceLogic() {
+ const MENUS = christmasInstance.getMenus();
+ let totalPrice = 0;
+
+ MENUS.forEach((menu) => {
+ const { MENU_NAME, QUANTITY } = menuAndQuantity(menu);
+ if (MENUS_PRICE.hasOwnProperty(MENU_NAME))
+ totalPrice += MENUS_PRICE[MENU_NAME] * QUANTITY;
+ });
+
+ return totalPrice;
+}
+
+export function ChampagnePromotionAvailable() {
+ const TOTAL_PRICE = toTalPriceLogic(christmasInstance.getMenus());
+ if (TOTAL_PRICE >= 120000) {
+ return true;
+ } else return false;
+}
+
+// d-day ํ ์ธ
+export function receivedD_dayPromotion() {
+ const DATE = christmasInstance.getDate();
+ let minusPrice = 1000;
+ let available = true;
+
+ if (DATE >= 26) {
+ available = false;
+ }
+
+ if (available) {
+ for (let i = 1; i < DATE; i++) {
+ minusPrice += 100;
+ }
+ } else {
+ minusPrice = 0;
+ }
+
+ return minusPrice;
+}
+
+function minusPriceCalculator(
+ menus,
+ date,
+ validDays,
+ targetMenuCategories,
+ discountMultiplier
+) {
+ let minusPrice = 0;
+
+ if (!validDays.includes(date)) {
+ return minusPrice;
+ }
+
+ menus.forEach((menu) => {
+ const { MENU_NAME, QUANTITY } = menuAndQuantity(menu);
+ if (targetMenuCategories.includes(MENU_NAME))
+ minusPrice += discountMultiplier * QUANTITY;
+ });
+
+ return minusPrice;
+}
+
+// WEEKDAY ํ ์ธ
+export function receivedWeekDayPromotion() {
+ const MENUS = christmasInstance.getMenus();
+ const DATE = christmasInstance.getDate();
+ const DESSERT = [`์ด์ฝ์ผ์ดํฌ`, `์์ด์คํฌ๋ฆผ`];
+
+ return minusPriceCalculator(MENUS, DATE, WEEKDAY, DESSERT, 2023);
+}
+
+// WEEKEND ํ ์ธ
+export function receivedWeekendPromotion() {
+ const MENUS = christmasInstance.getMenus();
+ const DATE = christmasInstance.getDate();
+ const MAIN = ["ํฐ๋ณธ์คํ
์ดํฌ", "๋ฐ๋นํ๋ฆฝ", "ํด์ฐ๋ฌผํ์คํ", "ํฌ๋ฆฌ์ค๋ง์คํ์คํ"];
+
+ return minusPriceCalculator(MENUS, DATE, WEEKEND, MAIN, 2023);
+}
+
+export function receivedSpecialPromotion() {
+ const DATE = christmasInstance.getDate();
+ const MINUS_PRICE = 1000;
+ if (STAR_DAY.includes(DATE)) {
+ return MINUS_PRICE;
+ } else return 0;
+}
+
+// ์ดํ์ธ ์ฆ์ ์ด๋ฒคํธ
+export function receivedChampagnePromotion() {
+ const CHAMPAGNE_AVAILABLE = ChampagnePromotionAvailable();
+ const CHAMPAGNE_PRICE = 25000;
+
+ if (CHAMPAGNE_AVAILABLE) {
+ return CHAMPAGNE_PRICE;
+ } else return 0;
+}
+
+export function receivedTotalBenefitPrice() {
+ const DDAY_AVAILABLE = receivedD_dayPromotion();
+ const WEEKDAY_AVAILABLE = receivedWeekDayPromotion();
+ const WEEKEND_AVAILABLE = receivedWeekendPromotion();
+ const CHAMPAGNE_AVAILABLE = receivedChampagnePromotion();
+ const SPECIAL_AVAILABLE = receivedSpecialPromotion();
+ let resultTotalBenefitPrice;
+
+ const totalBenefitPrice =
+ DDAY_AVAILABLE +
+ WEEKDAY_AVAILABLE +
+ WEEKEND_AVAILABLE +
+ CHAMPAGNE_AVAILABLE +
+ SPECIAL_AVAILABLE;
+
+ if (totalBenefitPrice === 0) return 0;
+ if (totalBenefitPrice > 0) return -totalBenefitPrice;
+}
+
+export function receivedTotalDsicountPrice() {
+ const DDAY_AVAILABLE = receivedD_dayPromotion();
+ const WEEKDAY_AVAILABLE = receivedWeekDayPromotion();
+ const WEEKEND_AVAILABLE = receivedWeekendPromotion();
+ const SPECIAL_AVAILABLE = receivedSpecialPromotion();
+
+ const TOTAL_DISCOUNTPRICE =
+ DDAY_AVAILABLE + WEEKDAY_AVAILABLE + WEEKEND_AVAILABLE + SPECIAL_AVAILABLE;
+
+ return TOTAL_DISCOUNTPRICE;
+}
+
+export function totalPriceAfterDiscount() {
+ const TOTAL_DISCOUNTPRICE = receivedTotalDsicountPrice();
+ const TOTAL_PRICE = toTalPriceLogic();
+
+ const TOTAL_AFTER = TOTAL_PRICE - TOTAL_DISCOUNTPRICE;
+
+ return TOTAL_AFTER;
+}
+
+export function sendBadge() {
+ const TOTAL_AFTER = -receivedTotalBenefitPrice();
+ if (TOTAL_AFTER >= 20000) {
+ return "์ฐํ";
+ } else if (TOTAL_AFTER >= 10000) {
+ return "ํธ๋ฆฌ";
+ } else if (TOTAL_AFTER >= 5000) {
+ return "๋ณ";
+ } else {
+ return "์์";
+ }
+} | JavaScript | new Date ์์ฑ ๊ฐ์ฒด์ getDay ๋ฉ์๋๋ฅผ ํ์ฉํด์ ์ฃผ๋ง, ํ์ผ์ ์ฒดํฌํ ์ ์์ต๋๋ค. ํ๋์ฝ๋ฉ ๋ณด๋ค๋ ์ด ๋ฐฉ์์ ์ฌ์ฉํด๋ณด์๊ธธ ์ถ์ฒ๋๋ ค์ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.