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 ๋ฉ”์„œ๋“œ๋ฅผ ํ™œ์šฉํ•ด์„œ ์ฃผ๋ง, ํ‰์ผ์„ ์ฒดํฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํ•˜๋“œ์ฝ”๋”ฉ ๋ณด๋‹ค๋Š” ์ด ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•ด๋ณด์‹œ๊ธธ ์ถ”์ฒœ๋“œ๋ ค์š”