code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -1,7 +1,20 @@ package lotto; +import lotto.config.Configuration; +import lotto.controller.BuyLottoController; +import lotto.controller.LottoController; +import lotto.dto.BuyLottoDto; + public class Application { public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + Configuration configuration = new Configuration(); + LottoController lottoController = configuration.getLottoController(); + BuyLottoController buyLottoController = configuration.getBuyLottoController(); + executeControllers(buyLottoController, lottoController); + } + + private static void executeControllers(BuyLottoController buyLottoController, LottoController lottoController) { + BuyLottoDto buyLottoDto = buyLottoController.buyLotto(); + lottoController.getStatistics(buyLottoDto); } }
Java
์Œ.. ๋งž์•„์š” ์ €๋„ ์ด ๋ถ€๋ถ„์ด ๋งŽ์ด ๊ฑธ๋ ธ์–ด์š”. ํ•˜์ง€๋งŒ ๋ชจ๋“ˆํ™” ํ•˜๋ฉด ํ•  ์ˆ˜๋ก Application์—์„œ ์ƒ์„ฑํ•ด์ค˜์•ผ ํ•˜๋Š”๊ฒŒ ๋งŽ์•„์ ธ์„œ ๊ณ ๋ฏผ์ด ๋์–ด์š”... ๋‹ค์Œ์—๋Š” controller๋งŒ ์˜์กดํ•˜๊ฒŒ๋” ์ˆ˜์ •ํ•ด๋ด์•ผ๊ฒ ์–ด์š”!!
@@ -0,0 +1,34 @@ +package lotto.model; + +import static lotto.constant.Constant.THOUSAND; +import static lotto.constant.Constant.ZERO; +import static lotto.exception.ErrorInputException.ErrorMessage.PURCHASE_PRICE_CAN_DIVIDE_BY_THOUSAND; + +import lotto.exception.ErrorInputException; + +public class PurchasePrice { + private final int price; + + private PurchasePrice(int price) { + this.price = price; + isDividedByThousand(); + } + + public static PurchasePrice createPurchasePrice(int price) { + return new PurchasePrice(price); + } + + public int getPrice() { + return price; + } + + private void isDividedByThousand() { + if (price % THOUSAND != ZERO) { + throw new ErrorInputException(PURCHASE_PRICE_CAN_DIVIDE_BY_THOUSAND); + } + } + + public int calculateLottoCount() { + return price / THOUSAND; + } +}
Java
๋กœ๋˜์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ•จ์ˆ˜(calculateLottoCount)๋กœ ๋งŒ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค! ๋“ฃ๊ณ ๋ณด๋‹ˆ ๋งŒ์•ฝ ๋กœ๋˜ ๊ฐ€๊ฒฉ์ด ๋ฐ”๋€Œ๊ฒŒ ๋œ๋‹ค๋ฉด ๋‚˜๋ˆ„๋Š” ๊ฐ€๊ฒฉ์„ ์ˆ˜์ •ํ•ด์•ผ ํ•˜๋‹ˆ `THOSAND` ๋Œ€์‹  `LOTTOPRICE`๋กœ ๋ฐ”๋€Œ๋Š”๊ฒŒ ์ข‹๊ฒ ๊ตฐ์š”!
@@ -0,0 +1,57 @@ +package lotto.model; + +import static lotto.constant.Constant.ZERO; + +import java.util.Collections; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import lotto.constant.Rank; + +public class Statistics { + private final Map<Rank, Integer> result; + + private Statistics() { + result = new EnumMap<>(Rank.class); + for (Rank rank : Rank.values()) { + result.put(rank, ZERO); + } + } + + public static Statistics createStatistics() { + return new Statistics(); + } + + public Map<Rank, Integer> getResult() { + return Collections.unmodifiableMap(result); + } + + public void calculateMatching(LottoNumbers lottoNumbers, WinnerNumber winnerNumber, BonusNumber bonusNumber) { + List<Lotto> lottos = lottoNumbers.getNumbers(); + + for (Lotto lotto : lottos) { + Rank rank = findRank(lotto, winnerNumber, bonusNumber); + int lottoCount = result.get(rank) + 1; + + result.put(rank, lottoCount); + } + } + + private Rank findRank(Lotto lotto, WinnerNumber winnerNumber, BonusNumber bonusNumber) { + long winnerMatch = countMatchingWinnerNumber(lotto, winnerNumber); + boolean bonusMatch = matchingBonusNumber(lotto, bonusNumber); + + return Rank.findRank(winnerMatch, bonusMatch); + } + + private boolean matchingBonusNumber(Lotto lotto, BonusNumber bonusNumber) { + return lotto.getNumbers().stream() + .anyMatch(number -> number.equals(bonusNumber.isSameBonusNumber(bonusNumber))); + } + + private long countMatchingWinnerNumber(Lotto lotto, WinnerNumber winnerNumber) { + return lotto.getNumbers().stream() + .filter(winnerNumber.getWinnerNumbers()::contains) + .count(); + } +}
Java
`countMatchingWinnerNumber()` ํ•จ์ˆ˜์—์„œ stream์„ ์“ฐ๋‹ค๋ณด๋‹ˆ return ๊ฐ’์ด long์ด ๋˜์—ˆ์–ด์š”! long์ด๋“  int๋“  ํฌ๊ฒŒ ์˜ํ–ฅ์„ ์ฃผ์ง€ ์•Š์„ ๊ฒƒ์ด๋ผ๊ณ  ์ƒ๊ฐํ•˜์—ฌ long์œผ๋กœ ์„ ์–ธํ–ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,40 @@ +package lotto.dto; + +import lotto.model.BonusNumber; +import lotto.model.LottoNumbers; +import lotto.model.PurchasePrice; +import lotto.model.Statistics; +import lotto.model.WinnerNumber; + +public class BuyLottoDto { + private PurchasePrice purchasePrice; + private LottoNumbers lottoNumbers; + private WinnerNumber winnerNumber; + private BonusNumber bonusNumber; + + private BuyLottoDto(PurchasePrice purchasePrice, LottoNumbers lottoNumbers, WinnerNumber winnerNumber, + BonusNumber bonusNumber) { + this.purchasePrice = purchasePrice; + this.lottoNumbers = lottoNumbers; + this.winnerNumber = winnerNumber; + this.bonusNumber = bonusNumber; + } + + public static BuyLottoDto createBuyLottoDto(PurchasePrice purchasePrice, + LottoNumbers lottoNumbers, + WinnerNumber winnerNumber, + BonusNumber bonusNumber) { + return new BuyLottoDto(purchasePrice, lottoNumbers, winnerNumber, bonusNumber); + } + + public PurchasePrice getPurchasePrice() { + return purchasePrice; + } + + public Statistics calculateMatching() { + Statistics statistics = Statistics.createStatistics(); + statistics.calculateMatching(this.lottoNumbers, this.winnerNumber, this.bonusNumber); + return statistics; + } + +}
Java
๋งž์•„์š”! ์ด ๋กœ์ง์€ service์— ๋ฐฐ์น˜ํ•˜๋Š”๊ฒŒ ๋” ์ ์ ˆํ•  ๊ฒƒ ๊ฐ™๊ตฐ์š”! ๐Ÿ‘
@@ -0,0 +1,109 @@ +package christmas.controller; + +import christmas.domain.Date; +import christmas.domain.EventBadge; +import christmas.domain.Orders; +import christmas.domain.discount.DDayStrategy; +import christmas.domain.discount.Discount; +import christmas.domain.discount.GiftStrategy; +import christmas.domain.discount.SpecialStrategy; +import christmas.domain.discount.WeekdayStrategy; +import christmas.domain.discount.WeekendStrategy; +import christmas.exception.InputException; +import christmas.util.CurrencyUtil; +import christmas.view.InputView; +import christmas.view.OutputView; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; + +public class PromotionController { + + + public void run() { + OutputView.printGreeting(); + + Date date = initVisitDate(); + Orders orders = initOrders(); + + displayPreviewForEvent(date, orders); + } + + private void displayPreviewForEvent(Date date, Orders orders) { + OutputView.printPreviewTitle(date.getDay()); + OutputView.printOrderedMenu(orders.getStringOrders()); + displayTotalBeforeDiscount(orders); + displayDiscountDetails(date, orders); + } + + private void displayDiscountDetails(Date date, Orders orders) { + Discount discount = applyDiscount(date, orders); + + OutputView.printGiftMenu(discount.getStringGiftMenu()); + OutputView.printBenefitHistory(discount.getDetailedEventHistory()); + + int totalBenefitAmount = discount.getTotalBenefitAmount(); + displayTotalBenefitAmount(totalBenefitAmount); + displayDiscountedTotal(orders, discount); + + displayEventBadge(totalBenefitAmount); + } + + private void displayEventBadge(int totalBenefitAmount) { + EventBadge eventBadge = EventBadge.getEventBadge(totalBenefitAmount); + OutputView.printEventBadge(eventBadge.getName()); + } + + private void displayDiscountedTotal(Orders orders, Discount discount) { + String amount = CurrencyUtil.formatToKor( + orders.calculateTotalBeforeDiscount() + discount.getTotalDiscountAmount()); + OutputView.printDiscountedTotal(amount); + } + + private void displayTotalBenefitAmount(int totalBenefitAmount) { + String totalBenefit = CurrencyUtil.formatToKor(totalBenefitAmount); + OutputView.printTotalBenefit(totalBenefit); + } + + private void displayTotalBeforeDiscount(Orders orders) { + String totalAmount = CurrencyUtil.formatToKor(orders.calculateTotalBeforeDiscount()); + OutputView.printTotalBeforeDiscount(totalAmount); + } + + private Discount applyDiscount(Date date, Orders orders) { + Discount discount = new Discount(List.of( + new DDayStrategy(), + new WeekdayStrategy(), + new WeekendStrategy(), + new SpecialStrategy(), + new GiftStrategy()), + date + ); + discount.checkEvent(orders); + + return discount; + } + + private Orders initOrders() { + return wrapByLoop(() -> { + Orders orders = new Orders(new ArrayList<>()); + orders.createOrder(InputView.getMenu()); + + return orders; + }); + } + + private Date initVisitDate() { + return wrapByLoop(() -> Date.from(InputView.getDate())); + } + + private <T> T wrapByLoop(Supplier<T> supplier) { + while (true) { + try { + return supplier.get(); + } catch (InputException exception) { + System.out.println(exception.getMessage()); + } + } + } +}
Java
์ปจํŠธ๋กค๋Ÿฌ๋‹จ์—์„œ ํ•˜๋Š”๊ฒƒ๋„ ๊ดœ์ฐฎ์ง€๋งŒ ํ•ด๋‹น ๋„๋ฉ”์ธ ๋กœ์ง์œผ๋กœ ๊ฐ€์ ธ๊ฐ€๋Š” ๊ฒƒ๋„ ์ข‹์•„๋ณด์—ฌ์š”!
@@ -0,0 +1,48 @@ +package christmas.domain; + +public enum Event { + NONE("์—†์Œ", 0), + CHRISTMAS_D_DAY_DISCOUNT("ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด ํ• ์ธ", 1_000), + WEEKDAY_DISCOUNT("ํ‰์ผ ํ• ์ธ", 2_023), + WEEKEND_DISCOUNT("์ฃผ๋ง ํ• ์ธ", 2_023), + SPECIAL_DISCOUNT("ํŠน๋ณ„ ํ• ์ธ", 1_000), + GIFT("์ฆ์ • ์ด๋ฒคํŠธ", 25_000); + + private static final int BASE_AMOUNT_PER_DATE = 100; + + private final String name; + private final int amount; + + Event(String name, int amount) { + this.name = name; + this.amount = amount; + } + + public int calculateTotalAmount(int count, Date date) { + if (this.equals(CHRISTMAS_D_DAY_DISCOUNT)) { + return getAmountOfDDayDiscount(date); + } + + if (isOneTimeEvent()) { + return amount; + } + + return count * amount; + } + + public String getName() { + return name; + } + + public int getAmount() { + return amount; + } + + private boolean isOneTimeEvent() { + return this.equals(SPECIAL_DISCOUNT) || this.equals(GIFT); + } + + private int getAmountOfDDayDiscount(Date date) { + return CHRISTMAS_D_DAY_DISCOUNT.amount + (BASE_AMOUNT_PER_DATE * date.daysSince1Day()); + } +}
Java
์ฝ”๋“œ๊ฐ€ ์ฝ๊ธฐ ํŽธํ•ด์š”!
@@ -0,0 +1,57 @@ +package christmas.domain; + +import christmas.exception.ExceptionMessage; +import christmas.exception.InputException; +import java.util.Arrays; + +public enum Menu { + MUSHROOM_CREAM_SOUP("์–‘์†ก์ด์ˆ˜ํ”„", 6_000, FoodType.APPETIZER), + TAPAS("ํƒ€ํŒŒ์Šค", 5_500, FoodType.APPETIZER), + CAESAR_SALAD("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 8_000, FoodType.APPETIZER), + T_BONE_STEAK("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 55_000, FoodType.MAIN), + BARBECUE_RIBS("๋ฐ”๋น„ํ๋ฆฝ", 54_000, FoodType.MAIN), + SEAFOOD_PASTA("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 35_000, FoodType.MAIN), + CHRISTMAS_PASTA("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 25_000, FoodType.MAIN), + CHOCOLATE_CAKE("์ดˆ์ฝ”์ผ€์ดํฌ", 15_000, FoodType.DESSERT), + ICE_CREAM("์•„์ด์Šคํฌ๋ฆผ", 5_000, FoodType.DESSERT), + ZERO_COLA("์ œ๋กœ์ฝœ๋ผ", 3_000, FoodType.BEVERAGE), + RED_WINE("๋ ˆ๋“œ์™€์ธ", 60_000, FoodType.BEVERAGE), + CHAMPAGNE("์ƒดํŽ˜์ธ", 25_000, FoodType.BEVERAGE); + + private final String name; + private final int price; + private final FoodType type; + + Menu(String name, int price, FoodType type) { + this.name = name; + this.price = price; + this.type = type; + } + + public static Menu findMenuByName(String name) { + return Arrays.stream(values()) + .filter(value -> value.name.equals(name)) + .findFirst() + .orElseThrow(() -> new InputException(ExceptionMessage.INVALID_ORDER)); + } + + public static boolean isBeverage(String name) { + return findMenuByName(name).type.equals(FoodType.BEVERAGE); + } + + public boolean isDessert() { + return this.type.equals(FoodType.DESSERT); + } + + public boolean isMain() { + return this.type.equals(FoodType.MAIN); + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } +}
Java
Menu Enum์— FoodType Enum ์„ ๊ฐ€์ ธ์™€์„œ ์“ฐ์‹œ๋Š” ์˜๋„๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,19 @@ +package christmas.domain.discount; + +import christmas.domain.Date; +import christmas.domain.Event; +import christmas.domain.Orders; +import java.util.List; + +public class GiftStrategy implements DiscountStrategy { + private static final int GIFT_BASE_AMOUNT = 120_000; + + @Override + public List<Event> getShouldApplyEvents(Orders orders, Date date) { + if (orders.calculateTotalBeforeDiscount() >= GIFT_BASE_AMOUNT) { + return List.of(Event.GIFT); + } + + return List.of(Event.NONE); + } +}
Java
์ธํ„ฐํŽ˜์ด์Šค ํ™œ์šฉ ์ข‹๋„ค์š”!
@@ -0,0 +1,4 @@ +package christmas.dto; + +public record OrderParam(String name, int count) { +}
Java
ํ•ด๋‹น record ๊ฐ์ฒด์˜ ์˜๋„๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,9 @@ +package christmas.exception; + +public class InputException extends IllegalArgumentException { + public static final String PREFIX = "[ERROR] "; + + public InputException(String message) { + super(PREFIX + message); + } +}
Java
์ €๋Š” ํ”„๋กœ๊ทธ๋žจ์—์„œ ๋ฐœ์ƒํ•˜๋Š” ์˜ˆ์™ธ ์ฒ˜๋ฆฌ ๋ฉ”์†Œ๋“œ๋ฅผ ํ•œ ํŒจํ‚ค์ง€์— ๋ชจ์•„์„œ ๊ด€๋ฆฌํ•˜๊ณ  ์žˆ๋Š”๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹ค๊นŒ์š”?
@@ -0,0 +1,72 @@ +package christmas.view; + +public class OutputView { + private static final String GREETING = "์•ˆ๋…•ํ•˜์„ธ์š”! ์šฐํ…Œ์ฝ” ์‹๋‹น 12์›” ์ด๋ฒคํŠธ ํ”Œ๋ž˜๋„ˆ์ž…๋‹ˆ๋‹ค."; + private static final String PREVIEW_TITLE = "12์›” %d์ผ์— ์šฐํ…Œ์ฝ” ์‹๋‹น์—์„œ ๋ฐ›์„ ์ด๋ฒคํŠธ ํ˜œํƒ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!"; + private static final String ORDERED_MENU = "<์ฃผ๋ฌธ ๋ฉ”๋‰ด>"; + private static final String TOTAL_BEFORE_DISCOUNT = "<ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก>"; + private static final String GIFT_MENU = "<์ฆ์ • ๋ฉ”๋‰ด>"; + private static final String BENEFIT_HISTORY = "<ํ˜œํƒ ๋‚ด์—ญ>"; + private static final String TOTAL_BENEFIT = "<์ดํ˜œํƒ ๊ธˆ์•ก>"; + private static final String DISCOUNTED_TOTAL = "<ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก>"; + private static final String EVENT_BADGE = "<12์›” ์ด๋ฒคํŠธ ๋ฐฐ์ง€>"; + + private OutputView() { + } + + public static void printGreeting() { + print(GREETING); + } + + public static void printPreviewTitle(int date) { + print(String.format(PREVIEW_TITLE, date)); + printLineFeed(); + } + + public static void printOrderedMenu(String orders) { + print(ORDERED_MENU); + print(orders); + } + + public static void printTotalBeforeDiscount(String amount) { + print(TOTAL_BEFORE_DISCOUNT); + print(amount); + printLineFeed(); + } + + public static void printGiftMenu(String menu) { + print(GIFT_MENU); + print(menu); + printLineFeed(); + } + + public static void printBenefitHistory(String history) { + print(BENEFIT_HISTORY); + print(history); + } + + public static void printTotalBenefit(String amount) { + print(TOTAL_BENEFIT); + print(amount); + printLineFeed(); + } + + public static void printDiscountedTotal(String amount) { + print(DISCOUNTED_TOTAL); + print(amount); + printLineFeed(); + } + + public static void printEventBadge(String badge) { + print(EVENT_BADGE); + print(badge); + } + + private static void print(String input) { + System.out.println(input); + } + + private static void printLineFeed() { + System.out.println(); + } +}
Java
ํ•ด๋‹น ๋กœ์ง์„ ๊ตณ์ด Enum์œผ๋กœ ๊ด€๋ฆฌํ•˜์ง€ ์•Š์•˜๋Š”๋ฐ๋„ ๊ฐ€๋…์„ฑ์ด ์ •๋ง ์ข‹๋„ค์š”! ์ธ์‚ฌ์ดํŠธ ์–ป์–ด๊ฐ‘๋‹ˆ๋‹ค!
@@ -0,0 +1,171 @@ +package christmas.domain; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import christmas.exception.ExceptionMessage; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +class OrdersTest { + @DisplayName("์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธํ–ˆ์œผ๋ฉด ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•ด์•ผ ํ•œ๋‹ค.") + @ParameterizedTest + @MethodSource("getOnlyBeverages") + void validateOnlyBeverageTest(List<String> orders) { + // given + Orders newOrders = new Orders(new ArrayList<>()); + + // when, then + assertThatThrownBy(() -> newOrders.createOrder(orders)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(ExceptionMessage.ONLY_BEVERAGE_ORDER); + } + + static Stream<List<String>> getOnlyBeverages() { + return Stream.of( + List.of("์ œ๋กœ์ฝœ๋ผ-10"), + List.of("๋ ˆ๋“œ์™€์ธ-2"), + List.of("์ƒดํŽ˜์ธ-1", "๋ ˆ๋“œ์™€์ธ-2"), + List.of("์ œ๋กœ์ฝœ๋ผ-3", "๋ ˆ๋“œ์™€์ธ-3", "์ƒดํŽ˜์ธ-3") + ); + } + + @DisplayName("์Œ๋ฃŒ์™€ ์Œ์‹์„ ๊ฐ™์ด ์ฃผ๋ฌธํ–ˆ์œผ๋ฉด ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š๋Š”๋‹ค.") + @Test + void validateOnlyBeverageWithFoodTest() { + // given + List<String> orders = Arrays.asList("์ œ๋กœ์ฝœ๋ผ-3", "๋ ˆ๋“œ์™€์ธ-3", "์ƒดํŽ˜์ธ-3", "์ดˆ์ฝ”์ผ€์ดํฌ-1"); + Orders newOrders = new Orders(new ArrayList<>()); + + // when, then + assertThatNoException().isThrownBy(() -> newOrders.createOrder(orders)); + } + + @DisplayName("์ค‘๋ณต ๋ฉ”๋‰ด๋ฅผ ์ฃผ๋ฌธํ–ˆ์„ ๊ฒฝ์šฐ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•ด์•ผ ํ•œ๋‹ค.") + @ParameterizedTest + @MethodSource("getDuplicatedOrders") + void validateDuplicateTest(List<String> orders) { + // given + Orders newOrders = new Orders(new ArrayList<>()); + + // when, then + assertThatThrownBy(() -> newOrders.createOrder(orders)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(ExceptionMessage.INVALID_ORDER); + } + + static Stream<List<String>> getDuplicatedOrders() { + return Stream.of( + List.of("์ƒดํŽ˜์ธ-1", "์ƒดํŽ˜์ธ-9"), + List.of("์•„์ด์Šคํฌ๋ฆผ-2", "ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€-1", "์•„์ด์Šคํฌ๋ฆผ-11"), + List.of("์ œ๋กœ์ฝœ๋ผ-1", "ํƒ€ํŒŒ์Šค-1", "๋ฐ”๋น„ํ๋ฆฝ-2", "์ œ๋กœ์ฝœ๋ผ-1") + ); + } + + @DisplayName("20๊ฐœ ์ดˆ๊ณผ ์ฃผ๋ฌธํ–ˆ์œผ๋ฉด ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•ด์•ผ ํ•œ๋‹ค.") + @ParameterizedTest + @MethodSource("getOverLimitOrders") + void validateOverLimitTest(List<String> orders) { + // given + Orders newOrders = new Orders(new ArrayList<>()); + + // when, then + assertThatThrownBy(() -> newOrders.createOrder(orders)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(ExceptionMessage.OVER_LIMIT_ORDER); + } + + static Stream<List<String>> getOverLimitOrders() { + return Stream.of( + List.of("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ-21"), + List.of("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€-10", "์‹œ์ €์ƒ๋Ÿฌ๋“œ-11"), + List.of("์ œ๋กœ์ฝœ๋ผ-5", "์ดˆ์ฝ”์ผ€์ดํฌ-5", "๋ฐ”๋น„ํ๋ฆฝ-5", "ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€-5", "ํƒ€ํŒŒ์Šค-1") + ); + } + + @DisplayName("ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก์„ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•œ๋‹ค.") + @Test + void calculateTotalBeforeDiscountTest() { + // given + Orders newOrders = new Orders( + List.of( + Order.of("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 2), + Order.of("์ œ๋กœ์ฝœ๋ผ", 2), + Order.of("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 1), + Order.of("์ดˆ์ฝ”์ผ€์ดํฌ", 1), + Order.of("์•„์ด์Šคํฌ๋ฆผ", 1) + )); + + // when + int totalPrice = newOrders.calculateTotalBeforeDiscount(); + + // then + assertThat(totalPrice).isEqualTo(144_000); + } + + @DisplayName("๋””์ €ํŠธ์˜ ๊ฐœ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•œ๋‹ค.") + @Test + void getCountOfDessertTest() { + // given + Orders newOrders = new Orders( + List.of( + Order.of("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 2), + Order.of("์ œ๋กœ์ฝœ๋ผ", 2), + Order.of("์ดˆ์ฝ”์ผ€์ดํฌ", 3), + Order.of("์•„์ด์Šคํฌ๋ฆผ", 5) + )); + + // when + int countOfDessert = newOrders.getCountOfDessert(); + + // then + assertThat(countOfDessert).isEqualTo(8); + } + + @DisplayName("๋ฉ”์ธ ๋ฉ”๋‰ด์˜ ๊ฐœ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•œ๋‹ค.") + @Test + void getCountOfMainTest() { + // given + Orders newOrders = new Orders( + List.of( + Order.of("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 3), + Order.of("์ œ๋กœ์ฝœ๋ผ", 2), + Order.of("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 1), + Order.of("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 2) + )); + + // when + int countOfMain = newOrders.getCountOfMain(); + + // then + assertThat(countOfMain).isEqualTo(6); + } + + @DisplayName("๋ฉ”๋‰ด์™€ ๊ฐœ์ˆ˜๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•œ๋‹ค.") + @Test + void getStringOrdersTest() { + // given + Orders newOrders = new Orders( + List.of( + Order.of("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 3), + Order.of("์ œ๋กœ์ฝœ๋ผ", 2), + Order.of("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 1) + )); + + // when + String stringOfOrders = newOrders.getStringOrders(); + + // then + assertThat(stringOfOrders) + .contains("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ 3๊ฐœ") + .contains("์ œ๋กœ์ฝœ๋ผ 2๊ฐœ") + .contains("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€ 1๊ฐœ"); + } +} \ No newline at end of file
Java
ํ•ด๋‹น ๋กœ์ง์„ @BeforEach ์–ด๋…ธํ…Œ์ด์…˜์„ ํ™œ์šฉํ•˜๋Š”๊ฑด ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹ค๊นŒ์š”?
@@ -0,0 +1,109 @@ +package christmas.controller; + +import christmas.domain.Date; +import christmas.domain.EventBadge; +import christmas.domain.Orders; +import christmas.domain.discount.DDayStrategy; +import christmas.domain.discount.Discount; +import christmas.domain.discount.GiftStrategy; +import christmas.domain.discount.SpecialStrategy; +import christmas.domain.discount.WeekdayStrategy; +import christmas.domain.discount.WeekendStrategy; +import christmas.exception.InputException; +import christmas.util.CurrencyUtil; +import christmas.view.InputView; +import christmas.view.OutputView; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; + +public class PromotionController { + + + public void run() { + OutputView.printGreeting(); + + Date date = initVisitDate(); + Orders orders = initOrders(); + + displayPreviewForEvent(date, orders); + } + + private void displayPreviewForEvent(Date date, Orders orders) { + OutputView.printPreviewTitle(date.getDay()); + OutputView.printOrderedMenu(orders.getStringOrders()); + displayTotalBeforeDiscount(orders); + displayDiscountDetails(date, orders); + } + + private void displayDiscountDetails(Date date, Orders orders) { + Discount discount = applyDiscount(date, orders); + + OutputView.printGiftMenu(discount.getStringGiftMenu()); + OutputView.printBenefitHistory(discount.getDetailedEventHistory()); + + int totalBenefitAmount = discount.getTotalBenefitAmount(); + displayTotalBenefitAmount(totalBenefitAmount); + displayDiscountedTotal(orders, discount); + + displayEventBadge(totalBenefitAmount); + } + + private void displayEventBadge(int totalBenefitAmount) { + EventBadge eventBadge = EventBadge.getEventBadge(totalBenefitAmount); + OutputView.printEventBadge(eventBadge.getName()); + } + + private void displayDiscountedTotal(Orders orders, Discount discount) { + String amount = CurrencyUtil.formatToKor( + orders.calculateTotalBeforeDiscount() + discount.getTotalDiscountAmount()); + OutputView.printDiscountedTotal(amount); + } + + private void displayTotalBenefitAmount(int totalBenefitAmount) { + String totalBenefit = CurrencyUtil.formatToKor(totalBenefitAmount); + OutputView.printTotalBenefit(totalBenefit); + } + + private void displayTotalBeforeDiscount(Orders orders) { + String totalAmount = CurrencyUtil.formatToKor(orders.calculateTotalBeforeDiscount()); + OutputView.printTotalBeforeDiscount(totalAmount); + } + + private Discount applyDiscount(Date date, Orders orders) { + Discount discount = new Discount(List.of( + new DDayStrategy(), + new WeekdayStrategy(), + new WeekendStrategy(), + new SpecialStrategy(), + new GiftStrategy()), + date + ); + discount.checkEvent(orders); + + return discount; + } + + private Orders initOrders() { + return wrapByLoop(() -> { + Orders orders = new Orders(new ArrayList<>()); + orders.createOrder(InputView.getMenu()); + + return orders; + }); + } + + private Date initVisitDate() { + return wrapByLoop(() -> Date.from(InputView.getDate())); + } + + private <T> T wrapByLoop(Supplier<T> supplier) { + while (true) { + try { + return supplier.get(); + } catch (InputException exception) { + System.out.println(exception.getMessage()); + } + } + } +}
Java
๊ณต๊ฐํ•ฉ๋‹ˆ๋‹ค!!
@@ -0,0 +1,58 @@ +package christmas.domain; + +import christmas.exception.ExceptionMessage; +import christmas.exception.InputException; +import java.time.LocalDate; +import java.time.format.TextStyle; +import java.util.List; +import java.util.Locale; + +public class Date { + private static final int MIN_DATE = 1; + private static final int MAX_DATE = 31; + private static final int OFFSET = 1; + private static final int CHRISTMAS = 25; + private static final String SUNDAY = "์ผ"; + private static final List<String> WEEKDAY = List.of(SUNDAY, "์›”", "ํ™”", "์ˆ˜", "๋ชฉ"); + + private final LocalDate date; + + private Date(int date) { + validateRange(date); + this.date = LocalDate.of(2023, 12, date); + } + + public static Date from(int date) { + return new Date(date); + } + + public boolean isBetween1And25days() { + return getDay() <= CHRISTMAS; + } + + public int daysSince1Day() { + return getDay() - OFFSET; + } + + public boolean isSpecialDay() { + return getDay() == CHRISTMAS || getDayOfWeek().equals(SUNDAY); + } + + public boolean isWeekday() { + return WEEKDAY.contains(getDayOfWeek()); + } + + public int getDay() { + return date.getDayOfMonth(); + } + + private String getDayOfWeek() { + return date.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.KOREA); + } + + private void validateRange(int date) { + if (date < MIN_DATE || date > MAX_DATE) { + throw new InputException(ExceptionMessage.INVALID_DATE); + } + } +}
Java
"SUNDAY" ๋ฅผ "์ผ" ๋กœ ํ•˜์ง€ ์•Š์œผ์‹  ์ด์œ ๊ฐ€ ์žˆ๋‚˜์š”??
@@ -0,0 +1,61 @@ +package christmas.domain; + +import static christmas.Constants.BASE_COUNT; +import static christmas.Constants.BLANK; +import static christmas.Constants.COUNT; +import static christmas.Constants.LINE_FEED; +import static christmas.Constants.NONE; + +import christmas.exception.ExceptionMessage; +import christmas.exception.InputException; + +public class Order { + private final Menu menu; + private final int count; + + private Order(Menu menu, int count) { + validateCount(count); + this.menu = menu; + this.count = count; + } + + public static Order of(String name, int count) { + return new Order(Menu.findMenuByName(name), count); + } + + public int getTotalPrice() { + return menu.getPrice() * count; + } + + public int getCountPerDessert() { + if (menu.isDessert()) { + return count; + } + + return NONE; + } + + public int getCountPerMain() { + if (menu.isMain()) { + return count; + } + + return NONE; + } + + public String getStringMenuAndCount() { + return new StringBuilder() + .append(menu.getName()) + .append(BLANK) + .append(count) + .append(COUNT) + .append(LINE_FEED) + .toString(); + } + + private void validateCount(int count) { + if (count < BASE_COUNT) { + throw new InputException(ExceptionMessage.INVALID_ORDER); + } + } +}
Java
์ด๊ฑด OutputView ์—์„œ ํ•ด๋„ ์ข‹์„๊ฒƒ ๊ฐ™์€๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”??
@@ -0,0 +1,36 @@ +package christmas.domain; + +import java.util.Arrays; +import java.util.Comparator; + +public enum EventBadge { + NONE("์—†์Œ", 0), + STAR("๋ณ„", 5_000), + TREE("ํŠธ๋ฆฌ", 10_000), + SANTA("์‚ฐํƒ€", 20_000); + + private final String name; + private final int price; + + EventBadge(String name, int price) { + this.name = name; + this.price = price; + } + + public static EventBadge getEventBadge(int amount) { + return Arrays.stream(values()) + .sorted(descendOrderByPrice()) + .filter(badge -> badge.price <= Math.abs(amount)) + .findFirst() + .orElse(NONE); + } + + public String getName() { + return name; + } + + private static Comparator<EventBadge> descendOrderByPrice() { + return (o1, o2) -> o2.price - o1.price; + } + +}
Java
์ •๋ง ๊น”๋”ํ•˜๋„ค์š”!!
@@ -0,0 +1,17 @@ +package christmas.domain.discount; + +import christmas.domain.Date; +import christmas.domain.Event; +import christmas.domain.Orders; +import java.util.List; + +public class DDayStrategy implements DiscountStrategy { + @Override + public List<Event> getShouldApplyEvents(Orders orders, Date date) { + if (date.isBetween1And25days()) { + return List.of(Event.CHRISTMAS_D_DAY_DISCOUNT); + } + + return List.of(Event.NONE); + } +}
Java
์ „๋žต ํŒจํ„ด ์‚ฌ์šฉํ•˜์…จ๋„ค์š”! ๐Ÿ‘๐Ÿ‘
@@ -21,6 +21,7 @@ package { if (_instance) { + // NOTE throw ์‹œ์ผœ๋†“๊ณ  catch ์•ˆํ•ด์ฃผ๋ฉด ์–ด๋–ป๊ฒŒ ๋ ๊นŒ์š”? throw new Error("Use getInstance()."); } _instance = this;
Unknown
์‚ฌ์‹ค ์—ฌ๊ธฐ์„œ throw๊ฐ€ ๋‚  ๊ฐ€๋Šฅ์„ฑ์€ ๊ฑฐ์˜ ์—†์–ด๋ณด์ž…๋‹ˆ๋‹ค๋งŒ... ๋ฐ”๊นฅ์— try catch ์ฒ˜๋ฆฌ๋ฅผ ํ•˜์ง€ ์•Š์€ ์ฑ„๋กœ throw๊ฐ€ ๋ฐœ์ƒํ•ด๋ฒ„๋ฆฌ๋ฉด ์–ด๋–ป๊ฒŒ ๋ ๊นŒ์š”?
@@ -1,10 +1,113 @@ package subway; import java.util.Scanner; +import subway.controller.InitController; +import subway.controller.InputController; +import subway.controller.SubwayController; +import subway.domain.Station; +import subway.repository.LineRepository; +import subway.repository.StationRepository; +import subway.service.LineService; +import subway.service.MinimumTimeService; +import subway.service.ShortestPathService; +import subway.service.StationService; +import subway.validation.EndStationValidation; +import subway.validation.MainFunctionValidation; +import subway.validation.SelectRouteValidation; +import subway.validation.StartStationValidation; +import subway.view.Input.InputView; +import subway.view.output.OutputView; public class Application { public static void main(String[] args) { final Scanner scanner = new Scanner(System.in); - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + + // ๊ฐ์ฒด ์ƒ์„ฑ + InputView inputView = createInputView(); + OutputView outputView = new OutputView(); + + StationService stationService = createStationService(new StationRepository()); + LineService lineService = createLineService(new LineRepository()); + ShortestPathService shortestPathService = new ShortestPathService(); + MinimumTimeService minimumTimeService = new MinimumTimeService(); + + InitController initController = createInitController(stationService, lineService); + InputController inputController = createInputController(inputView, outputView, scanner); + SubwayController subwayController = createSubwayController(shortestPathService, minimumTimeService, outputView); + + // ๋ฉ”์„œ๋“œ ํ˜ธ์ถœ + executeControllers(initController, inputController, subwayController); + } + + private static InputView createInputView() { + MainFunctionValidation mainFunctionValidation = new MainFunctionValidation(); + SelectRouteValidation selectRouteValidation = new SelectRouteValidation(); + StartStationValidation startStationValidation = new StartStationValidation(); + EndStationValidation endStationValidation = new EndStationValidation(); + return new InputView(mainFunctionValidation, selectRouteValidation, startStationValidation, + endStationValidation); + } + + private static StationService createStationService(StationRepository stationRepository) { + return StationService.createStationService(stationRepository); + } + + private static LineService createLineService(LineRepository lineRepository) { + return LineService.createLineService(lineRepository); + } + + + private static InitController createInitController(StationService stationService, LineService lineService) { + return InitController.createInitController(stationService, lineService); + } + + private static InputController createInputController(InputView inputView, OutputView outputView, Scanner scanner) { + return InputController.createInputController(inputView, outputView, scanner); + } + + private static SubwayController createSubwayController(ShortestPathService shortestPathService, + MinimumTimeService minimumTimeService, + OutputView outputView) { + return SubwayController.createSubwayController(shortestPathService, minimumTimeService, outputView); + } + + + private static void executeControllers(InitController initController, InputController inputController, + SubwayController subwayController) { + initController.init(); + + while (true) { + String mainFunc = inputController.inputMainFunc(); + if (mainFunc.equals("Q")) { + System.exit(0); + } + + if (mainFunc.equals("1")) { + executeRouteSelection(inputController, subwayController); + } + } + } + + private static void executeRouteSelection(InputController inputController, SubwayController subwayController) { + String selectRouteFunc = inputController.inputSelectRoute(); + if (selectRouteFunc.equals("B")) { + return; + } + + Station start = inputStartStation(inputController); + Station end = inputEndStation(inputController, start); + + subwayController.calculateAndPrintRoute(selectRouteFunc, start, end); + } + + private static Station inputStartStation(InputController inputController) { + String stationName = inputController.inputStartStation(); + return new Station(stationName); + } + + private static Station inputEndStation(InputController inputController, Station start) { + String stationName = inputController.inputEndStation(start.getName()); + return new Station(stationName); } } +
Java
์›€ ์—ฌ๊ธฐ๋„ ๋กœ๋˜์™€ ๊ฐ™๊ตฐ์š”! ๋งŒ์•ฝ controller์™€ service์— ๋Œ€ํ•œ ๊ฐ์ฒด ์ƒ์„ฑํ•˜๋Š” ๊ด€์‹ฌ์‚ฌ๋ฅผ ํŠน์ • ํด๋ž˜์Šค์—์„œ ํ•˜๊ณ ์‹ถ๋‹ค๋ฉด Configurationํด๋ž˜์Šค๋ฅผ ๋งŒ๋“œ๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”? ์Šคํ”„๋ง๋ถ€ํŠธ์—์„œ @Configuration์ด Bean์„ ๋“ฑ๋กํ•ด์ฃผ๋Š” ์–ด๋…ธํ…Œ์ด์…˜์ด๋‹ˆ๊นŒ์š”!
@@ -1,10 +1,113 @@ package subway; import java.util.Scanner; +import subway.controller.InitController; +import subway.controller.InputController; +import subway.controller.SubwayController; +import subway.domain.Station; +import subway.repository.LineRepository; +import subway.repository.StationRepository; +import subway.service.LineService; +import subway.service.MinimumTimeService; +import subway.service.ShortestPathService; +import subway.service.StationService; +import subway.validation.EndStationValidation; +import subway.validation.MainFunctionValidation; +import subway.validation.SelectRouteValidation; +import subway.validation.StartStationValidation; +import subway.view.Input.InputView; +import subway.view.output.OutputView; public class Application { public static void main(String[] args) { final Scanner scanner = new Scanner(System.in); - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + + // ๊ฐ์ฒด ์ƒ์„ฑ + InputView inputView = createInputView(); + OutputView outputView = new OutputView(); + + StationService stationService = createStationService(new StationRepository()); + LineService lineService = createLineService(new LineRepository()); + ShortestPathService shortestPathService = new ShortestPathService(); + MinimumTimeService minimumTimeService = new MinimumTimeService(); + + InitController initController = createInitController(stationService, lineService); + InputController inputController = createInputController(inputView, outputView, scanner); + SubwayController subwayController = createSubwayController(shortestPathService, minimumTimeService, outputView); + + // ๋ฉ”์„œ๋“œ ํ˜ธ์ถœ + executeControllers(initController, inputController, subwayController); + } + + private static InputView createInputView() { + MainFunctionValidation mainFunctionValidation = new MainFunctionValidation(); + SelectRouteValidation selectRouteValidation = new SelectRouteValidation(); + StartStationValidation startStationValidation = new StartStationValidation(); + EndStationValidation endStationValidation = new EndStationValidation(); + return new InputView(mainFunctionValidation, selectRouteValidation, startStationValidation, + endStationValidation); + } + + private static StationService createStationService(StationRepository stationRepository) { + return StationService.createStationService(stationRepository); + } + + private static LineService createLineService(LineRepository lineRepository) { + return LineService.createLineService(lineRepository); + } + + + private static InitController createInitController(StationService stationService, LineService lineService) { + return InitController.createInitController(stationService, lineService); + } + + private static InputController createInputController(InputView inputView, OutputView outputView, Scanner scanner) { + return InputController.createInputController(inputView, outputView, scanner); + } + + private static SubwayController createSubwayController(ShortestPathService shortestPathService, + MinimumTimeService minimumTimeService, + OutputView outputView) { + return SubwayController.createSubwayController(shortestPathService, minimumTimeService, outputView); + } + + + private static void executeControllers(InitController initController, InputController inputController, + SubwayController subwayController) { + initController.init(); + + while (true) { + String mainFunc = inputController.inputMainFunc(); + if (mainFunc.equals("Q")) { + System.exit(0); + } + + if (mainFunc.equals("1")) { + executeRouteSelection(inputController, subwayController); + } + } + } + + private static void executeRouteSelection(InputController inputController, SubwayController subwayController) { + String selectRouteFunc = inputController.inputSelectRoute(); + if (selectRouteFunc.equals("B")) { + return; + } + + Station start = inputStartStation(inputController); + Station end = inputEndStation(inputController, start); + + subwayController.calculateAndPrintRoute(selectRouteFunc, start, end); + } + + private static Station inputStartStation(InputController inputController) { + String stationName = inputController.inputStartStation(); + return new Station(stationName); + } + + private static Station inputEndStation(InputController inputController, Station start) { + String stationName = inputController.inputEndStation(start.getName()); + return new Station(stationName); } } +
Java
Q๋‚˜ 1๊ฐ™์€ ๊ฐ’์€ Function enumํด๋ž˜์Šค๋กœ ์ ‘๊ทผํ•ด์„œ ์ž‘์„ฑํ•˜์…จ์„ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,44 @@ +package subway.service; + +import static subway.domain.RouteInfo.calculateTotalDistance; +import static subway.domain.RouteInfo.calculateTotalTime; +import static subway.domain.RouteInfo.values; + +import java.util.List; +import org.jgrapht.GraphPath; +import org.jgrapht.alg.shortestpath.DijkstraShortestPath; +import org.jgrapht.graph.DefaultWeightedEdge; +import org.jgrapht.graph.WeightedMultigraph; +import subway.domain.Result; +import subway.domain.RouteInfo; +import subway.domain.Station; + +public class MinimumTimeService { + public Result calculate(Station start, Station end) { + WeightedMultigraph<String, DefaultWeightedEdge> graph = createGraph(values()); + + DijkstraShortestPath<String, DefaultWeightedEdge> dijkstraShortestPath = + new DijkstraShortestPath<>(graph); + + GraphPath<String, DefaultWeightedEdge> shortestPath = + dijkstraShortestPath.getPath(start.getName(), end.getName()); + + List<DefaultWeightedEdge> edges = shortestPath.getEdgeList(); + + int totalDistance = calculateTotalDistance(graph, edges); + int totalTime = calculateTotalTime(graph, edges); + + return Result.createResult(totalDistance, totalTime, shortestPath.getVertexList()); + } + + private WeightedMultigraph<String, DefaultWeightedEdge> createGraph(RouteInfo[] routeInfos) { + WeightedMultigraph<String, DefaultWeightedEdge> graph = + new WeightedMultigraph<>(DefaultWeightedEdge.class); + + for (RouteInfo routeInfo : routeInfos) { + routeInfo.calculateMinimumTime(graph, routeInfo); + } + + return graph; + } +} \ No newline at end of file
Java
์˜คํ˜ธ!! ๊ฐ์ฒด ์ƒ์„ฑํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ๋ถ„๋ฆฌ์‹œ์ผฐ๊ตฐ์š”!! ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค..!!
@@ -0,0 +1,59 @@ +package subway.view.Input; + +import subway.validation.EndStationValidation; +import subway.validation.MainFunctionValidation; +import subway.validation.SelectRouteValidation; +import subway.validation.StartStationValidation; + +public class InputView { + private final MainFunctionValidation mainFunctionValidation; + private final SelectRouteValidation selectRouteValidation; + private final StartStationValidation startStationValidation; + private final EndStationValidation endStationValidation; + + public InputView(MainFunctionValidation mainFunctionValidation, SelectRouteValidation selectRouteValidation, + StartStationValidation startStationValidation, EndStationValidation endStationValidation) { + this.mainFunctionValidation = mainFunctionValidation; + this.selectRouteValidation = selectRouteValidation; + this.startStationValidation = startStationValidation; + this.endStationValidation = endStationValidation; + } + + public String readMainFunc(String input) { + return mainFunctionValidate(input); + } + + public String readSelectRoute(String input) { + return selectRouteValidate(input); + } + + public String readStartStation(String input) { + return startStationValidate(input); + } + + public String readEndStation(String start, String input) { + return endStationValidate(start, input); + } + + private String mainFunctionValidate(String input) { + mainFunctionValidation.isBlank(input); + return mainFunctionValidation.isOneOrQ(input); + } + + private String selectRouteValidate(String input) { + selectRouteValidation.isBlank(input); + return selectRouteValidation.isOneOrTwoOrB(input); + } + + private String startStationValidate(String input) { + startStationValidation.isBlank(input); + return startStationValidation.isRegister(input); + } + + private String endStationValidate(String start, String input) { + endStationValidation.isBlank(input); + endStationValidation.isRegister(input); + return endStationValidation.isDuplicate(start, input); + } +} +
Java
์ด๋ฏธ isBlank๋ฉ”์†Œ๋“œ๊ฐ€ static์œผ๋กœ ํ• ๋‹น๋˜์–ด์žˆ๊ธฐ๋•Œ๋ฌธ์— mainFunctionValidation.isBlank๊ฐ€ ์•„๋‹Œ, MainFunctionValidation.isBlank๋กœ ํ•˜๋Š”๊ฒŒ ๋” ์ ํ•ฉํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -1,10 +1,113 @@ package subway; import java.util.Scanner; +import subway.controller.InitController; +import subway.controller.InputController; +import subway.controller.SubwayController; +import subway.domain.Station; +import subway.repository.LineRepository; +import subway.repository.StationRepository; +import subway.service.LineService; +import subway.service.MinimumTimeService; +import subway.service.ShortestPathService; +import subway.service.StationService; +import subway.validation.EndStationValidation; +import subway.validation.MainFunctionValidation; +import subway.validation.SelectRouteValidation; +import subway.validation.StartStationValidation; +import subway.view.Input.InputView; +import subway.view.output.OutputView; public class Application { public static void main(String[] args) { final Scanner scanner = new Scanner(System.in); - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + + // ๊ฐ์ฒด ์ƒ์„ฑ + InputView inputView = createInputView(); + OutputView outputView = new OutputView(); + + StationService stationService = createStationService(new StationRepository()); + LineService lineService = createLineService(new LineRepository()); + ShortestPathService shortestPathService = new ShortestPathService(); + MinimumTimeService minimumTimeService = new MinimumTimeService(); + + InitController initController = createInitController(stationService, lineService); + InputController inputController = createInputController(inputView, outputView, scanner); + SubwayController subwayController = createSubwayController(shortestPathService, minimumTimeService, outputView); + + // ๋ฉ”์„œ๋“œ ํ˜ธ์ถœ + executeControllers(initController, inputController, subwayController); + } + + private static InputView createInputView() { + MainFunctionValidation mainFunctionValidation = new MainFunctionValidation(); + SelectRouteValidation selectRouteValidation = new SelectRouteValidation(); + StartStationValidation startStationValidation = new StartStationValidation(); + EndStationValidation endStationValidation = new EndStationValidation(); + return new InputView(mainFunctionValidation, selectRouteValidation, startStationValidation, + endStationValidation); + } + + private static StationService createStationService(StationRepository stationRepository) { + return StationService.createStationService(stationRepository); + } + + private static LineService createLineService(LineRepository lineRepository) { + return LineService.createLineService(lineRepository); + } + + + private static InitController createInitController(StationService stationService, LineService lineService) { + return InitController.createInitController(stationService, lineService); + } + + private static InputController createInputController(InputView inputView, OutputView outputView, Scanner scanner) { + return InputController.createInputController(inputView, outputView, scanner); + } + + private static SubwayController createSubwayController(ShortestPathService shortestPathService, + MinimumTimeService minimumTimeService, + OutputView outputView) { + return SubwayController.createSubwayController(shortestPathService, minimumTimeService, outputView); + } + + + private static void executeControllers(InitController initController, InputController inputController, + SubwayController subwayController) { + initController.init(); + + while (true) { + String mainFunc = inputController.inputMainFunc(); + if (mainFunc.equals("Q")) { + System.exit(0); + } + + if (mainFunc.equals("1")) { + executeRouteSelection(inputController, subwayController); + } + } + } + + private static void executeRouteSelection(InputController inputController, SubwayController subwayController) { + String selectRouteFunc = inputController.inputSelectRoute(); + if (selectRouteFunc.equals("B")) { + return; + } + + Station start = inputStartStation(inputController); + Station end = inputEndStation(inputController, start); + + subwayController.calculateAndPrintRoute(selectRouteFunc, start, end); + } + + private static Station inputStartStation(InputController inputController) { + String stationName = inputController.inputStartStation(); + return new Station(stationName); + } + + private static Station inputEndStation(InputController inputController, Station start) { + String stationName = inputController.inputEndStation(start.getName()); + return new Station(stationName); } } +
Java
์ตœ์ข… ์ฝ”ํ…Œ์—์„œ ์‚ฌ์šฉํ•  ํ…œํ”Œ๋ฆฟ์„ ๋งŒ๋“ค๋‹ค๋ณด๋‹ˆ ๊ฐ™์€ ํ˜•์‹์œผ๋กœ ๋งŒ๋“ค์–ด์กŒ๊ตฐ์š” ใ…œใ…œ ๋‹ค์‹œ ๊ณ ๋ฏผํ•ด๋ด์•ผ๊ฒ ์Šต๋‹ˆ๋‹ค!!
@@ -0,0 +1,15 @@ +package config; + +import controller.UserController; +import service.UserJoinService; + +public class AppConfig { + + public static UserController userController() { + return new UserController(userJoinService()); + } + + public static UserJoinService userJoinService() { + return new UserJoinService(); + } +}
Java
AppConfig๋กœ DI๋ฅผ ์ฃผ์ž…ํ•ด์ฃผ๋ ค๋Š” ์‹œ๋„๐Ÿ‘
@@ -0,0 +1,45 @@ +package controller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import service.UserJoinService; +import util.HttpRequest; +import util.HttpResponse; + +public class UserController { + private final String HTTP_GET = "GET"; + private final String JOIN_FORM = "/user/form.html"; + private final String CREATE_USER_URL = "/user/create"; + private UserJoinService userJoinService; + private Logger log = LoggerFactory.getLogger(getClass()); + + public UserController(UserJoinService userJoinService) { + this.userJoinService = userJoinService; + } + + // TODO : ์—๋ŸฌํŽ˜์ด์ง€ ์ƒ์„ฑ, ํšŒ์›๊ฐ€์ž… ๊ฒ€์ฆ + public String process(HttpRequest request, HttpResponse response) { + // GET ์š”์ฒญ์ธ ๊ฒฝ์šฐ ๋ถ„๋ฆฌ + if (request.getMethod().equals(HTTP_GET)) { + // ํšŒ์› ๊ฐ€์ž… ํผ ๋ณด์—ฌ์ฃผ๊ธฐ + if (request.getUrl().equals(JOIN_FORM)) { + return JOIN_FORM; + } + // ํšŒ์›๊ฐ€์ž…์ผ ๊ฒฝ์šฐ + if (request.getUrl().equals(CREATE_USER_URL)) { + return addUser(request.getQueryString(), response); + } + } + + return "/error"; + } + + private String addUser(String queryParameters, HttpResponse response) { + userJoinService.addUser(queryParameters); + + response.setStatus(302); + response.setHeader("Location", "/index.html"); + return response.getResponse(); + } + +}
Java
```suggestion if (request.getUrl().equals(JOIN_FORM)) { return JOIN_FORM; } ``` ๋‘ ๊ฐœ ๊ฐ’์ด ๊ฐ™์•„์„œ ์ด ์ฝ”๋“œ์™€ ๊ฐ™์€ ์˜๋ฏธ์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,45 @@ +package controller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import service.UserJoinService; +import util.HttpRequest; +import util.HttpResponse; + +public class UserController { + private final String HTTP_GET = "GET"; + private final String JOIN_FORM = "/user/form.html"; + private final String CREATE_USER_URL = "/user/create"; + private UserJoinService userJoinService; + private Logger log = LoggerFactory.getLogger(getClass()); + + public UserController(UserJoinService userJoinService) { + this.userJoinService = userJoinService; + } + + // TODO : ์—๋ŸฌํŽ˜์ด์ง€ ์ƒ์„ฑ, ํšŒ์›๊ฐ€์ž… ๊ฒ€์ฆ + public String process(HttpRequest request, HttpResponse response) { + // GET ์š”์ฒญ์ธ ๊ฒฝ์šฐ ๋ถ„๋ฆฌ + if (request.getMethod().equals(HTTP_GET)) { + // ํšŒ์› ๊ฐ€์ž… ํผ ๋ณด์—ฌ์ฃผ๊ธฐ + if (request.getUrl().equals(JOIN_FORM)) { + return JOIN_FORM; + } + // ํšŒ์›๊ฐ€์ž…์ผ ๊ฒฝ์šฐ + if (request.getUrl().equals(CREATE_USER_URL)) { + return addUser(request.getQueryString(), response); + } + } + + return "/error"; + } + + private String addUser(String queryParameters, HttpResponse response) { + userJoinService.addUser(queryParameters); + + response.setStatus(302); + response.setHeader("Location", "/index.html"); + return response.getResponse(); + } + +}
Java
response ๊ตฌ์กฐ๋ฅผ ์ ๊ทน ์ฝ”๋“œ์— ๋ฐ˜์˜ํ•˜์…จ๋„ค์š”!
@@ -0,0 +1,45 @@ +package controller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import service.UserJoinService; +import util.HttpRequest; +import util.HttpResponse; + +public class UserController { + private final String HTTP_GET = "GET"; + private final String JOIN_FORM = "/user/form.html"; + private final String CREATE_USER_URL = "/user/create"; + private UserJoinService userJoinService; + private Logger log = LoggerFactory.getLogger(getClass()); + + public UserController(UserJoinService userJoinService) { + this.userJoinService = userJoinService; + } + + // TODO : ์—๋ŸฌํŽ˜์ด์ง€ ์ƒ์„ฑ, ํšŒ์›๊ฐ€์ž… ๊ฒ€์ฆ + public String process(HttpRequest request, HttpResponse response) { + // GET ์š”์ฒญ์ธ ๊ฒฝ์šฐ ๋ถ„๋ฆฌ + if (request.getMethod().equals(HTTP_GET)) { + // ํšŒ์› ๊ฐ€์ž… ํผ ๋ณด์—ฌ์ฃผ๊ธฐ + if (request.getUrl().equals(JOIN_FORM)) { + return JOIN_FORM; + } + // ํšŒ์›๊ฐ€์ž…์ผ ๊ฒฝ์šฐ + if (request.getUrl().equals(CREATE_USER_URL)) { + return addUser(request.getQueryString(), response); + } + } + + return "/error"; + } + + private String addUser(String queryParameters, HttpResponse response) { + userJoinService.addUser(queryParameters); + + response.setStatus(302); + response.setHeader("Location", "/index.html"); + return response.getResponse(); + } + +}
Java
์ด ๋ถ€๋ถ„์„ ์—†์• ๊ณ  ๋ฒ”์šฉ์ ์ธ ๋ฉ”์„œ๋“œ๋กœ ๋”ฐ๋กœ ๋นผ์„œ ๋ฆฌํŒฉํ† ๋งํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,56 @@ +package util; + +public class HttpRequest { + + private String method; + private String url; + private String queryString; + + public HttpRequest(String line) { + String[] splitHeader = line.split(" "); + // uriPath = ์ „์ฒด uri (์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ ๋ถ„๋ฆฌ ์ „) + String uriPath = getURIPath(splitHeader); + + // ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ ๋ถ„๋ฆฌ ํ›„ url + this.url = getPath(uriPath); + this.method = splitHeader[0]; + this.queryString = getQueryParameters(uriPath); + } + + public String getMethod() { + return method; + } + + public String getUrl() { + return url; + } + + public String getQueryString() { + return queryString; + } + + @Override + public String toString() { + return "HttpRequest{" + + "method='" + method + '\'' + + ", url='" + url + '\'' + + ", queryString='" + queryString + '\'' + + '}'; + } + + private String getURIPath(String[] splitHeader) { + return splitHeader[1]; + } + + private String getPath(String uriPath) { + return uriPath.split("\\?")[0]; + } + + private String getQueryParameters(String uriPath) { + String[] split = uriPath.split("\\?"); + if (split.length > 1) { + return split[1]; + } + return ""; + } +}
Java
์ฟผ๋ฆฌ๋ฅผ String์œผ๋กœ ์ €์žฅํ•˜๋„๋ก ๊ตฌํ˜„ํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ๋‚˜์š”?
@@ -0,0 +1,81 @@ +package util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.Map; + +public class HttpResponse { + + private Logger log = LoggerFactory.getLogger(getClass()); + private int status; + private Map<String, String> headers = new HashMap<>(); + + public void processResponse(String path, HttpResponse response, OutputStream out) throws IOException { + String contentType = response.getContentType(path); + byte[] body = findBody(contentType, path); + DataOutputStream dos = new DataOutputStream(out); + responseHeader(dos, body.length, contentType); + responseBody(dos, body); + } + + + private void responseHeader(DataOutputStream dos, int lengthOfBodyContent, String contentType) { + try { + dos.writeBytes("HTTP/1.1 " + status + " " + getStatusCode(status) + "\r\n"); + dos.writeBytes("Content-Type: " + contentType + "\r\n"); + dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n"); + + for (Map.Entry<String, String> header : headers.entrySet()) { + dos.writeBytes(header.getKey() + ": " + header.getValue() + "\r\n"); + } + + dos.writeBytes("\r\n"); + } catch (IOException e) { + log.error(e.getMessage()); + } + } + + private void responseBody(DataOutputStream dos, byte[] body) { + try { + dos.write(body, 0, body.length); + dos.flush(); + } catch (IOException e) { + log.error(e.getMessage()); + } + } + + private String getContentType(String path) { + return ContentType.findContentType(path).getValue(); + } + + private byte[] findBody(String contentType, String path) throws IOException { + return Files.readAllBytes(new File(ResponseBody.findResponseBody(contentType).getPath() + path).toPath()); + } + + public void setStatus(int status) { + this.status = status; + } + + public void setHeader(String name, String value) { + headers.put(name, value); + } + + private String getStatusCode(int status) { + if (status == HttpStatus.MOVED_TEMPORARILY.getValue()) { + return HttpStatus.MOVED_TEMPORARILY.getReason(); + } + + return HttpStatus.OK.getReason(); + } + + public String getResponse() { + return headers.getOrDefault("Location", ""); + } +}
Java
path๊ฐ€ `/fonts/~` ์ด๋ ‡๊ฒŒ ์š”์ฒญ๋“ค์–ด์˜ค์ง€ ์•Š๋‚˜์š”?
@@ -0,0 +1,81 @@ +package util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.Map; + +public class HttpResponse { + + private Logger log = LoggerFactory.getLogger(getClass()); + private int status; + private Map<String, String> headers = new HashMap<>(); + + public void processResponse(String path, HttpResponse response, OutputStream out) throws IOException { + String contentType = response.getContentType(path); + byte[] body = findBody(contentType, path); + DataOutputStream dos = new DataOutputStream(out); + responseHeader(dos, body.length, contentType); + responseBody(dos, body); + } + + + private void responseHeader(DataOutputStream dos, int lengthOfBodyContent, String contentType) { + try { + dos.writeBytes("HTTP/1.1 " + status + " " + getStatusCode(status) + "\r\n"); + dos.writeBytes("Content-Type: " + contentType + "\r\n"); + dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n"); + + for (Map.Entry<String, String> header : headers.entrySet()) { + dos.writeBytes(header.getKey() + ": " + header.getValue() + "\r\n"); + } + + dos.writeBytes("\r\n"); + } catch (IOException e) { + log.error(e.getMessage()); + } + } + + private void responseBody(DataOutputStream dos, byte[] body) { + try { + dos.write(body, 0, body.length); + dos.flush(); + } catch (IOException e) { + log.error(e.getMessage()); + } + } + + private String getContentType(String path) { + return ContentType.findContentType(path).getValue(); + } + + private byte[] findBody(String contentType, String path) throws IOException { + return Files.readAllBytes(new File(ResponseBody.findResponseBody(contentType).getPath() + path).toPath()); + } + + public void setStatus(int status) { + this.status = status; + } + + public void setHeader(String name, String value) { + headers.put(name, value); + } + + private String getStatusCode(int status) { + if (status == HttpStatus.MOVED_TEMPORARILY.getValue()) { + return HttpStatus.MOVED_TEMPORARILY.getReason(); + } + + return HttpStatus.OK.getReason(); + } + + public String getResponse() { + return headers.getOrDefault("Location", ""); + } +}
Java
status์™€ header๋กœ ๋‚˜๋ˆ„์–ด ์ €์žฅํ•˜๋Š” ๊ฒƒ ์ข‹๋„ค์š”!!
@@ -0,0 +1,81 @@ +package util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.Map; + +public class HttpResponse { + + private Logger log = LoggerFactory.getLogger(getClass()); + private int status; + private Map<String, String> headers = new HashMap<>(); + + public void processResponse(String path, HttpResponse response, OutputStream out) throws IOException { + String contentType = response.getContentType(path); + byte[] body = findBody(contentType, path); + DataOutputStream dos = new DataOutputStream(out); + responseHeader(dos, body.length, contentType); + responseBody(dos, body); + } + + + private void responseHeader(DataOutputStream dos, int lengthOfBodyContent, String contentType) { + try { + dos.writeBytes("HTTP/1.1 " + status + " " + getStatusCode(status) + "\r\n"); + dos.writeBytes("Content-Type: " + contentType + "\r\n"); + dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n"); + + for (Map.Entry<String, String> header : headers.entrySet()) { + dos.writeBytes(header.getKey() + ": " + header.getValue() + "\r\n"); + } + + dos.writeBytes("\r\n"); + } catch (IOException e) { + log.error(e.getMessage()); + } + } + + private void responseBody(DataOutputStream dos, byte[] body) { + try { + dos.write(body, 0, body.length); + dos.flush(); + } catch (IOException e) { + log.error(e.getMessage()); + } + } + + private String getContentType(String path) { + return ContentType.findContentType(path).getValue(); + } + + private byte[] findBody(String contentType, String path) throws IOException { + return Files.readAllBytes(new File(ResponseBody.findResponseBody(contentType).getPath() + path).toPath()); + } + + public void setStatus(int status) { + this.status = status; + } + + public void setHeader(String name, String value) { + headers.put(name, value); + } + + private String getStatusCode(int status) { + if (status == HttpStatus.MOVED_TEMPORARILY.getValue()) { + return HttpStatus.MOVED_TEMPORARILY.getReason(); + } + + return HttpStatus.OK.getReason(); + } + + public String getResponse() { + return headers.getOrDefault("Location", ""); + } +}
Java
์ด ํด๋ž˜์Šค์—์„œ ์ „์ฒด์ ์œผ๋กœ ์ œ๊ฐ€ ๊ตฌํ˜„ํ•˜๊ณ  ์‹ถ์€ ๋ถ€๋ถ„๋“ค์„ ์ž˜ ๋‚˜๋ˆ„์–ด์ฃผ์‹ ๊ฒƒ ๊ฐ™์•„์š”! ๋งŽ์ด ๋ฐฐ์› ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,81 @@ +package util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.Map; + +public class HttpResponse { + + private Logger log = LoggerFactory.getLogger(getClass()); + private int status; + private Map<String, String> headers = new HashMap<>(); + + public void processResponse(String path, HttpResponse response, OutputStream out) throws IOException { + String contentType = response.getContentType(path); + byte[] body = findBody(contentType, path); + DataOutputStream dos = new DataOutputStream(out); + responseHeader(dos, body.length, contentType); + responseBody(dos, body); + } + + + private void responseHeader(DataOutputStream dos, int lengthOfBodyContent, String contentType) { + try { + dos.writeBytes("HTTP/1.1 " + status + " " + getStatusCode(status) + "\r\n"); + dos.writeBytes("Content-Type: " + contentType + "\r\n"); + dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n"); + + for (Map.Entry<String, String> header : headers.entrySet()) { + dos.writeBytes(header.getKey() + ": " + header.getValue() + "\r\n"); + } + + dos.writeBytes("\r\n"); + } catch (IOException e) { + log.error(e.getMessage()); + } + } + + private void responseBody(DataOutputStream dos, byte[] body) { + try { + dos.write(body, 0, body.length); + dos.flush(); + } catch (IOException e) { + log.error(e.getMessage()); + } + } + + private String getContentType(String path) { + return ContentType.findContentType(path).getValue(); + } + + private byte[] findBody(String contentType, String path) throws IOException { + return Files.readAllBytes(new File(ResponseBody.findResponseBody(contentType).getPath() + path).toPath()); + } + + public void setStatus(int status) { + this.status = status; + } + + public void setHeader(String name, String value) { + headers.put(name, value); + } + + private String getStatusCode(int status) { + if (status == HttpStatus.MOVED_TEMPORARILY.getValue()) { + return HttpStatus.MOVED_TEMPORARILY.getReason(); + } + + return HttpStatus.OK.getReason(); + } + + public String getResponse() { + return headers.getOrDefault("Location", ""); + } +}
Java
`headers` ๋ฅผ ์ด์šฉํ•ด์„œ ๋” ๋ฆฌํŒฉํ† ๋ง ํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,56 @@ +package util; + +public class HttpRequest { + + private String method; + private String url; + private String queryString; + + public HttpRequest(String line) { + String[] splitHeader = line.split(" "); + // uriPath = ์ „์ฒด uri (์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ ๋ถ„๋ฆฌ ์ „) + String uriPath = getURIPath(splitHeader); + + // ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ ๋ถ„๋ฆฌ ํ›„ url + this.url = getPath(uriPath); + this.method = splitHeader[0]; + this.queryString = getQueryParameters(uriPath); + } + + public String getMethod() { + return method; + } + + public String getUrl() { + return url; + } + + public String getQueryString() { + return queryString; + } + + @Override + public String toString() { + return "HttpRequest{" + + "method='" + method + '\'' + + ", url='" + url + '\'' + + ", queryString='" + queryString + '\'' + + '}'; + } + + private String getURIPath(String[] splitHeader) { + return splitHeader[1]; + } + + private String getPath(String uriPath) { + return uriPath.split("\\?")[0]; + } + + private String getQueryParameters(String uriPath) { + String[] split = uriPath.split("\\?"); + if (split.length > 1) { + return split[1]; + } + return ""; + } +}
Java
inline์œผ๋กœ ์ค„์—ฌ๋ณด๋Š” ๊ฑด์–ด๋–จ๊นŒ์š”? ์˜๋ฏธ๋ฅผ ๋“œ๋Ÿฌ๋‚ด๋Š” ์ง€์—ญ๋ณ€์ˆ˜๊ฐ€ ์•„๋‹ˆ๋ผ๋ฉด ์ƒ๋žตํ•˜๋Š” ํŽธ์ด ๊น”๋”ํ•œ ๊ฑฐ๊ฐ™์•„์š”.
@@ -0,0 +1,45 @@ +package controller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import service.UserJoinService; +import util.HttpRequest; +import util.HttpResponse; + +public class UserController { + private final String HTTP_GET = "GET"; + private final String JOIN_FORM = "/user/form.html"; + private final String CREATE_USER_URL = "/user/create"; + private UserJoinService userJoinService; + private Logger log = LoggerFactory.getLogger(getClass()); + + public UserController(UserJoinService userJoinService) { + this.userJoinService = userJoinService; + } + + // TODO : ์—๋ŸฌํŽ˜์ด์ง€ ์ƒ์„ฑ, ํšŒ์›๊ฐ€์ž… ๊ฒ€์ฆ + public String process(HttpRequest request, HttpResponse response) { + // GET ์š”์ฒญ์ธ ๊ฒฝ์šฐ ๋ถ„๋ฆฌ + if (request.getMethod().equals(HTTP_GET)) { + // ํšŒ์› ๊ฐ€์ž… ํผ ๋ณด์—ฌ์ฃผ๊ธฐ + if (request.getUrl().equals(JOIN_FORM)) { + return JOIN_FORM; + } + // ํšŒ์›๊ฐ€์ž…์ผ ๊ฒฝ์šฐ + if (request.getUrl().equals(CREATE_USER_URL)) { + return addUser(request.getQueryString(), response); + } + } + + return "/error"; + } + + private String addUser(String queryParameters, HttpResponse response) { + userJoinService.addUser(queryParameters); + + response.setStatus(302); + response.setHeader("Location", "/index.html"); + return response.getResponse(); + } + +}
Java
์ƒ์ˆ˜๊ฐ€ ๋งŽ์•„์ง€๋ฉด ์ข€ ํ—ท๊ฐˆ๋ฆด๊ฑฐ๊ฐ™์•„์„œ, ์‹œ๊ทธ๋‹ˆ์ฒ˜์— ๊ทœ์น™๊ฐ™์€๊ฒŒ ์žˆ์œผ๋ฉด ์ข‹๊ฒ ๋„ค์š”
@@ -0,0 +1,141 @@ +package com.example.firstproject.controller; + +import com.example.firstproject.dto.ArticleDto; +import com.example.firstproject.dto.BoardDto; +import com.example.firstproject.entity.Article; +import com.example.firstproject.entity.Board; +import com.example.firstproject.service.ArticleService; +import com.example.firstproject.service.BoardService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +import java.util.List; + +@Controller +@RequiredArgsConstructor +@RequestMapping("article") +public class ArticleController { + private final ArticleService articleService; + private final BoardService boardService; + + // #.๊ฒŒ์‹œ๋ฌผ ์กฐํšŒ + @GetMapping("{id}") + public String readArticle(@PathVariable("id") Long id, Model model) { + ArticleDto article = articleService.read(id); + model.addAttribute("article", article); + return "article/read"; + } + + // #.๊ฒŒ์‹œ๋ฌผ ์ˆ˜์ • + @GetMapping("/{id}/update") + public String checkUpdatePasswordForm(@PathVariable("id") Long id, Model model) { + model.addAttribute("article", articleService.read(id)); + return "article/updateCheck"; + } + // @.๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ + @PostMapping("/{id}/verify-update-password") + public String verifyUpdatePassword( + @PathVariable("id") Long id, + @RequestParam("password") String password + ) { + if (articleService.checkingPassword(id,password)) { + // ์ผ์น˜ ํ–ˆ์„ ์‹œ ์ˆ˜์ •ํผ์œผ๋กœ ์ด๋™ + return String.format("redirect:/article/%d/update-form",id); + } else { + // ํ‹€๋ ธ์„ ์‹œ ์—๋Ÿฌ ํŽ˜์ด์ง€๋กœ ์ด๋™ + return "redirect:/article/{id}/password-incorrect"; + } + } + // @.์ˆ˜์ •ํผ + @GetMapping("/{id}/update-form") + public String editForm(@PathVariable("id") Long id, Model model) { + model.addAttribute("article", articleService.read(id)); + return "article/update"; + } + + @PostMapping("/{id}/update-article") + public String updateArticle( + @PathVariable("id") Long id, + @RequestParam("title") String title, + @RequestParam("content") String content, + @RequestParam("password") String password + ) { + articleService.update(id,new ArticleDto(title,content,password)); + return String.format("redirect:/article/%d", id); + } + + + // #.๊ฒŒ์‹œ๋ฌผ ์‚ญ์ œ + @GetMapping("/{id}/delete") + public String checkDeletePasswordForm(@PathVariable("id") Long id, Model model) { + model.addAttribute("article", articleService.read(id)); + return "article/deleteCheck"; + } + // @.๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ + @PostMapping("/{id}/verify-delete-password") + public String verifyDeletePassword( + @PathVariable("id") Long id, + @RequestParam("password") String password + ) { + if (articleService.checkingPassword(id,password)) { + // ์ผ์น˜ ํ–ˆ์„ ์‹œ ์‚ญ์ œํผ์œผ๋กœ ์ด๋™ + return String.format("redirect:/article/%d/delete-form",id); + } else { + // ํ‹€๋ ธ์„ ์‹œ ์—๋Ÿฌ ํŽ˜์ด์ง€๋กœ ์ด๋™ + return "redirect:/article/{id}/password-incorrect"; + } + } + // @.์‚ญ์ œํผ + @GetMapping("/{id}/delete-form") + public String deleteForm(@PathVariable("id") Long id, Model model) { + model.addAttribute("article", articleService.read(id)); + return "article/delete"; + } + + @PostMapping("/{id}/delete-article") + public String deleteArticle(@PathVariable("id") Long articleId, RedirectAttributes redirectAttributes) { + + articleService.delete(articleId); + Board foundBoard = articleService.findBoardByArticle(articleId); + + redirectAttributes.addAttribute("boardId",foundBoard.getId()); + + return "redirect:/boards/boardId"; + } + +// @GetMapping("/{id}/delete") +// public String deleteForm(@PathVariable("id")Long id, Model model) { +// model.addAttribute("article",articleService.read(id)); +// return "article/delete"; +// } +// @PostMapping("/{id}/delete-article") +// public String deleteArticle( +// @PathVariable("id")Long id, +// @RequestParam("password") String password +// ){ +// +// articleService.delete(id,password); +// +// return String.format("redirect:/article/%d",id); +// } + + + // #. ๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ํ‹€๋ ธ์„ ์‹œ + @GetMapping("/{id}/password-incorrect") + public String incorrect(@PathVariable("id")Long id, Model model) { + model.addAttribute("article",articleService.read(id)); + return "article/incorrect"; + } + @PostMapping("/{id}/update-article/incorrect") + public String incorrectError(@PathVariable("id")Long id, Model model) { + model.addAttribute("article",articleService.read(id)); + return "redirect:/article/{id}"; + } + + + +} +
Java
delete ๋ฉ”์„œ๋“œ์™€ articleId๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฉ”์„œ๋“œ์˜ ์‹œ์ ์„ ๊ณ ๋ คํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,41 @@ +package com.example.firstproject.controller; + +import com.example.firstproject.service.ArticleService; +import com.example.firstproject.service.BoardService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; + + +@Controller +@RequiredArgsConstructor +@RequestMapping("boards") +public class BoardController { + + private final BoardService boardService; + private final ArticleService articleService; + + + @GetMapping + public String readAllBoard(Model model){ + model.addAttribute("boards", boardService.readAllBoard()); + return "board/home"; + } + + + @GetMapping("{boardId}") + public String readBoard(@PathVariable("boardId") Long id, Model model) { + model.addAttribute("board", boardService.read(id)); + model.addAttribute("articles", boardService.readByBoardId(id)); + return "board/board"; + } + + // "์ „์ฒด ๊ฒŒ์‹œํŒ" + @GetMapping("/entire-board") + public String entireBoard(Model model) { + model.addAttribute("articles", boardService.readAll()); + return "board/entireBoard"; + } + +}
Java
/ ์Šฌ๋ž˜์‹œ์˜ ์œ ๋ฌด์— ๋”ฐ๋ฅธ ์ฐจ์ด์ ์„ ํ•จ๊ป˜ ๊ณต๋ถ€ํ•ด๋ด…์‹œ๋‹ค
@@ -29,14 +29,14 @@ public Game findMatchTypeById(Integer matchId) { "FROM matches WHERE id = ?"; return jdbcTemplate.queryForObject(SQL, new Object[]{matchId}, (rs, rowNum) -> Game.builder() - .id(rs.getInt("id")) - .awayTeam(rs.getInt("away_team")) - .homeTeam(rs.getInt("home_team")) - .awayUser(rs.getInt("away_user")) - .homeUser(rs.getInt("home_user")) - .inning(rs.getInt("inning")) - .isFirsthalf(rs.getBoolean("is_firsthalf")) - .build()); + .id(rs.getInt("id")) + .awayTeam(rs.getInt("away_team")) + .homeTeam(rs.getInt("home_team")) + .awayUser(rs.getInt("away_user")) + .homeUser(rs.getInt("home_user")) + .inning(rs.getInt("inning")) + .isFirsthalf(rs.getBoolean("is_firsthalf")) + .build()); } public Game findGameById(Integer gameId) { @@ -58,10 +58,10 @@ public Integer insertNewGame(Game matchType) { String SQL = "INSERT INTO game (away_team, home_Team, inning, is_firsthalf) " + "VALUES (:awayTeam, :homeTeam, :inning, :isFirsthalf)"; SqlParameterSource namedParameters = new MapSqlParameterSource() - .addValue("awayTeam", matchType.getAwayTeam()) - .addValue("homeTeam", matchType.getHomeTeam()) - .addValue("inning", matchType.getInning()) - .addValue("isFirsthalf", matchType.isFirsthalf()); + .addValue("awayTeam", matchType.getAwayTeam()) + .addValue("homeTeam", matchType.getHomeTeam()) + .addValue("inning", matchType.getInning()) + .addValue("isFirsthalf", matchType.isFirsthalf()); KeyHolder keyHolder = new GeneratedKeyHolder(); Integer generatedGameId = namedParameterJdbcTemplate.update(SQL, namedParameters, keyHolder, new String[]{"generatedGameId"}); return keyHolder.getKey().intValue(); @@ -75,11 +75,11 @@ public List<Integer> findAllGameIds() { public List<Game> findAllMatches() { String SQL = "SELECT id, away_team, home_team, away_user, home_user FROM matches"; return jdbcTemplate.query(SQL, (rs, rowNum) -> Game.builder() - .id(rs.getInt("id")) - .awayTeam(rs.getInt("away_team")) - .homeTeam(rs.getInt("home_team")) - .awayUser(rs.getInt("away_user")) - .homeUser(rs.getInt("home_user")) - .build()); + .id(rs.getInt("id")) + .awayTeam(rs.getInt("away_team")) + .homeTeam(rs.getInt("home_team")) + .awayUser(rs.getInt("away_user")) + .homeUser(rs.getInt("home_user")) + .build()); } }
Java
์กฐ๊ธˆ์ด๋ผ๋„ ๋” ๋ณด๊ธฐ์ข‹์€ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๊ธฐ ์œ„ํ•œ ๋…ธ๋ ฅ์ธ๊ฐ€์š”. ๐Ÿ‘
@@ -1,13 +1,16 @@ package kr.codesquad.baseball.dto; -import lombok.AllArgsConstructor; import lombok.Getter; -import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter -@AllArgsConstructor @NoArgsConstructor public class GameInitializingRequestDto { private Integer matchId; + + public GameInitializingRequestDto() {} + + public GameInitializingRequestDto(Integer matchId) { + this.matchId = matchId; + } }
Java
Lombok ์‚ฌ์šฉ์— ๋Œ€ํ•ด์„œ ์กฐ๊ธˆ ๊บผ๋ ค์ง€์‹œ๋Š” ๋ฉด์ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ lombok ์ด์ œ ์“ฐ์…”๋„ ๊ดœ์ฐฎ์•„์š”. ๋‹ค๋งŒ ๊ณตํ†ต์ ์œผ๋กœ ์ฃผ์˜ํ•ด์•ผ ํ•  ์‚ฌํ•ญ๋“ค์ด ์žˆ๋Š”๋ฐ, ์•„๋ž˜ ๋งํฌ๋ฅผ ์ฐธ๊ณ ํ•ด ์ฃผ์„ธ์š”. https://kwonnam.pe.kr/wiki/java/lombok/pitfall
@@ -1,13 +1,10 @@ package kr.codesquad.baseball.dto.teamVO; import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @Getter @Setter -@AllArgsConstructor public class TeamVO { @JsonIgnore @@ -19,4 +16,13 @@ public class TeamVO { @JsonIgnore private int score; + + public TeamVO() {} + + public TeamVO(Integer teamId, String teamName, int totalScore, int score) { + this.teamId = teamId; + this.teamName = teamName; + this.totalScore = totalScore; + this.score = score; + } }
Java
`VO`, `DTO`, ๊ทธ๋ฆฌ๊ณ  ๋ชจ๋ธ ํด๋ž˜์Šค๋ฅผ ์–ด๋–ค ๊ธฐ์ค€์œผ๋กœ ๊ตฌ๋ถ„ํ•˜์…จ๋‚˜์š”?
@@ -1,13 +1,16 @@ package kr.codesquad.baseball.dto; -import lombok.AllArgsConstructor; import lombok.Getter; -import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter -@AllArgsConstructor @NoArgsConstructor public class GameInitializingRequestDto { private Integer matchId; + + public GameInitializingRequestDto() {} + + public GameInitializingRequestDto(Integer matchId) { + this.matchId = matchId; + } }
Java
์ด์ „๋ถ€ํ„ฐ ๋กฌ๋ณต์„ ์•„๋ฌด ์ƒ๊ฐ ์—†์ด ๊ธฐ๊ณ„์ ์œผ๋กœ ์‚ฌ์šฉ ํ–ˆ๋˜๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ง€๋‚œ ํ”„๋กœ์ ํŠธ์— ๋นŒ๋”๋ฅผ ์จ๋ณด๋ฉด์„œ ๋”๋”์šฑ ๋กฌ๋ณต ์—†์ด ๊ตฌํ˜„์„ ํ•ด๋ด์•ผ๊ฒ ๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์–ด์„œ ํŽ˜์–ด์—๊ฒŒ ์“ฐ์ง€ ๋ง์ž๊ณ  ์ œ์•ˆํ–ˆ๊ณ , ์ด๋ฒˆ ํ”„๋กœ์ ํŠธ์—๋Š” ํด๋ž˜์Šค์— ๋นŒ๋”๋ฅผ ์ง์ ‘ ๋งŒ๋“ค์–ด๋ณด๊ณ  ์žˆ๋Š”๋ฐ ๊ณต๋ถ€๊ฐ€ ๋งŽ์ด ๋˜๊ณ  ์žˆ๋„ค์š”. ์•Œ๋ ค์ฃผ์‹  ์ฃผ์˜์‚ฌํ•ญ ๋งํฌ๋„ ์ฝ์–ด ๋ดค๋Š”๋ฐ ๋ชจ๋ฅด๊ณ  ์“ด๊ฒŒ ์ฐธ ๋งŽ์•˜๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“œ๋„ค์š”! ๋‹ค์Œ ํ”„๋กœ์ ํŠธ๋ถ€ํ„ฐ ์œ ์˜ํ•˜๋ฉฐ ์‚ฌ์šฉ ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค. ์กฐ์–ธ ํ•ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.
@@ -1,13 +1,10 @@ package kr.codesquad.baseball.dto.teamVO; import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @Getter @Setter -@AllArgsConstructor public class TeamVO { @JsonIgnore @@ -19,4 +16,13 @@ public class TeamVO { @JsonIgnore private int score; + + public TeamVO() {} + + public TeamVO(Integer teamId, String teamName, int totalScore, int score) { + this.teamId = teamId; + this.teamName = teamName; + this.totalScore = totalScore; + this.score = score; + } }
Java
๋ชจ๋ธ ํด๋ž˜์Šค๋Š” DB์˜ ์—”ํ„ฐํ‹ฐ์™€ ์ง์ ‘ ๋Œ€์‘๋˜๋Š” ํด๋ž˜์Šค๋ผ ์ƒ๊ฐ ํ–ˆ๊ณ , VO๋Š” DB์˜ ์—ฌ๋Ÿฌ ์—”ํ„ฐํ‹ฐ ๋ฐ์ดํ„ฐ๋ฅผ DTO์— ์•Œ๋งž๊ฒŒ ๊ฐ€๊ณตํ•œ ์ตœ์†Œ ๋‹จ์œ„(DTO์˜ ๋ถ€๋ถ„ ์ง‘ํ•ฉ), DTO๋Š” ํด๋ผ์ด์–ธํŠธ์™€ ํ†ต์‹ ์„ ํ•˜๋Š” ์ ‘์ ์—์„œ ์‚ฌ์šฉ๋˜๋Š” ์ตœ์ข… ๋ฐ์ดํ„ฐ ํด๋ž˜์Šค๋ผ๋Š” ๊ธฐ์ค€์„ ์„ธ์šฐ๊ณ  ์‚ฌ์šฉ์„ ํ–ˆ์—ˆ์Šต๋‹ˆ๋‹ค. ๋ฐฑ์—”๋“œ ์š”๊ตฌ ์‚ฌํ•ญ์ธ(์˜ต์…˜) ํŒ€, ์„ ์ˆ˜ ๋ฐ์ดํ„ฐ ๊ด€๋ฆฌ ํˆด์„ ์—ผ๋‘์— ๋‘๊ณ  ๋ถ„๋ฅ˜๋ฅผ ํ–ˆ๋˜๊ฑด๋ฐ, ๋กœ์ง์ด ๋ณต์žกํ•ด์ง€๋‹ค ๋ณด๋‹ˆ VO์™€ ๋ชจ๋ธ ์‚ฌ์ด์˜ ๊ฒฝ๊ณ„๊ฐ€ ๋งŽ์ด ๋ชจํ˜ธํ•ด์ง„๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹คใ…œใ…œ ์ด๋Ÿฐ ๊ฒฝ์šฐ์— VO๋ผ๋Š” ์•ฝ์–ด๋ฅผ ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ๋งž๋Š”๊ฑด์ง€ ์• ๋งคํ•œ ์ ์ด ์žˆ์—ˆ๋Š”๋ฐ, ์•„๋ฌด๋ž˜๋„ ๋” ๊ณต๋ถ€ํ•˜๊ณ  ์ƒ๊ฐ์„ ํ•ด๋ด์•ผ ํ• ๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์กฐ์–ธ ํ•ด์ฃผ์‹  ๊ฒƒ์ฒ˜๋Ÿผ ํ•™์Šต์„ ๋” ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,48 @@ +/* http://meyerweb.com/eric/tools/css/reset/ + v2.0 | 20110126 + License: none (public domain) +*/ + +html, body, div, span, applet, object, iframe, +h1, h2, h3, h4, h5, h6, p, blockquote, pre, +a, abbr, acronym, address, big, cite, code, +del, dfn, em, img, ins, kbd, q, s, samp, +small, strike, strong, sub, sup, tt, var, +b, u, i, center, +dl, dt, dd, ol, ul, li, +fieldset, form, label, legend, +table, caption, tbody, tfoot, thead, tr, th, td, +article, aside, canvas, details, embed, +figure, figcaption, footer, header, hgroup, +menu, nav, output, ruby, section, summary, +time, mark, audio, video { + margin: 0; + padding: 0; + border: 0; + font-size: 100%; + font: inherit; + vertical-align: baseline; +} +/* HTML5 display-role reset for older browsers */ +article, aside, details, figcaption, figure, +footer, header, hgroup, menu, nav, section { + display: block; +} +body { + line-height: 1; +} +ol, ul { + list-style: none; +} +blockquote, q { + quotes: none; +} +blockquote:before, blockquote:after, +q:before, q:after { + content: ''; + content: none; +} +table { + border-collapse: collapse; + border-spacing: 0; +}
Unknown
css ๋ฆฌ์…‹ ์žŠ๊ณ  ์žˆ์—ˆ๋Š”๋ฐ ๋ฆฌ๋งˆ์ธ๋“œํ•˜๊ณ  ๊ฐ‘๋‹ˆ๋‹ค!
@@ -1,9 +1,10 @@ import { useState } from "react"; -import Input from "../components/Input"; import InputBox from "../components/InputBox"; -import validation from "../utils/validation"; +import InputCheckBox from "../components/InputCheckBox"; +import validateFormInfos from "../utils/validation"; import checking from "../utils/checking"; import { useNavigate } from "react-router-dom"; +import './Signup.css'; function Signup() { const [infos, setInfos] = useState({ @@ -14,8 +15,8 @@ function Signup() { userName: "", recommender: "", allTerms: false, - term1: false, - term2: false, + term: false, + privacy: false, marketing: false }); @@ -38,7 +39,7 @@ function Signup() { const checkedList = ["email", "phone", "userName", "recommender"] const {id, value} = e.currentTarget; setInfos({...infos, [id]: value}); - if (validationList.includes(id) && !validation({id, value, isValidInfos, setIsValidInfos})) { + if (validationList.includes(id) && !validateFormInfos({id, value, isValidInfos, setIsValidInfos})) { if (checkedList.includes(id)) setIsCheckedInfos({...isCheckedInfos, [id]: false}) return; @@ -49,153 +50,166 @@ function Signup() { checking({id, value, isCheckedInfos, setIsCheckedInfos}) } - const handleChangeInputBox = (e : React.FormEvent<HTMLInputElement>) => { + const handleChangeInputCheckBox = (e : React.FormEvent<HTMLInputElement>) => { const {id, checked} = e.currentTarget; if (id === "allTerms") { - setInfos({...infos, allTerms: checked, term1: checked, term2: checked, marketing: checked}); + setInfos({...infos, allTerms: checked, term: checked, privacy: checked, marketing: checked}); } else { setInfos({...infos, [id]: checked}) if (!checked) { setInfos({...infos, [id]: false, allTerms: false}) - } else if ((infos.term1 && infos.term2) || (infos.term2 && infos.marketing) || (infos.term1 && infos.marketing)) { + } else if ((infos.term && infos.privacy) || (infos.privacy && infos.marketing) || (infos.term && infos.marketing)) { setInfos({...infos, [id]: true, allTerms: true}) } } } const navigate = useNavigate(); - const handleSubmit = (e : any) => { + const handleSubmit = (e : React.FormEvent<HTMLFormElement>) => { e.preventDefault(); navigate("/greeting"); } return( - <form onSubmit={handleSubmit}> - <div> + <div className="signup"> + <div className="signup__title"> + ํšŒ์›๊ฐ€์ž… + </div> + <div className="signup__msg"> * ํ‘œ์‹œ๋œ ํ•ญ๋ชฉ์€ ํ•„์ˆ˜๋กœ ์ž…๋ ฅํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค </div> - <div> - ์ด๋ฉ”์ผ* - <div> - <Input + <form className="signup__form" onSubmit={handleSubmit}> + <div className="signup__form__content"> + <InputBox type="text" id="email" value={infos.email} onChange={handleChange} + label="์ด๋ฉ”์ผ" + required={true} /> - {isValidInfos.email ? isCheckedInfos.email ? "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค" : "์ด๋ฏธ ์‚ฌ์šฉ์ค‘์ธ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค" : "์œ ํšจํ•˜์ง€ ์•Š์€ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค"} + <div className="signup__form__content__msg"> + {isValidInfos.email ? isCheckedInfos.email ? "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค" : "์ด๋ฏธ ์‚ฌ์šฉ์ค‘์ธ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค" : "์œ ํšจํ•˜์ง€ ์•Š์€ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค"} + </div> </div> - </div> - <div> - ์ „ํ™”๋ฒˆํ˜ธ* - <div> - <Input + <div className="signup__form__content"> + <InputBox type="text" id="phone" value={infos.phone} onChange={handleChange} + label="์ „ํ™”๋ฒˆํ˜ธ" + required={true} /> - {isValidInfos.phone ? isCheckedInfos.phone? "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์ „ํ™”๋ฒˆํ˜ธ์ž…๋‹ˆ๋‹ค" : "์ด๋ฏธ ์‚ฌ์šฉ์ค‘์ธ ์ „ํ™”๋ฒˆํ˜ธ์ž…๋‹ˆ๋‹ค" : "์œ ํšจํ•˜์ง€ ์•Š์€ ์ „ํ™”๋ฒˆํ˜ธ์ž…๋‹ˆ๋‹ค"} + <div className="signup__form__content__msg"> + {isValidInfos.phone ? isCheckedInfos.phone? "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์ „ํ™”๋ฒˆํ˜ธ์ž…๋‹ˆ๋‹ค" : "์ด๋ฏธ ์‚ฌ์šฉ์ค‘์ธ ์ „ํ™”๋ฒˆํ˜ธ์ž…๋‹ˆ๋‹ค" : "์œ ํšจํ•˜์ง€ ์•Š์€ ์ „ํ™”๋ฒˆํ˜ธ์ž…๋‹ˆ๋‹ค"} + </div> </div> - </div> - <div> - ๋น„๋ฐ€๋ฒˆํ˜ธ* (๋น„๋ฐ€๋ฒˆํ˜ธ๋Š” 8์ž ์ด์ƒ, ์˜๋ฌธ ๋Œ€,์†Œ๋ฌธ์ž, ์ˆซ์ž๋ฅผ ํฌํ•จํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค) - <div> - <Input + <div className="signup__form__content"> + <InputBox type="password" id="password" value={infos.password} onChange={handleChange} + label="๋น„๋ฐ€๋ฒˆํ˜ธ(๋น„๋ฐ€๋ฒˆํ˜ธ๋Š” 8์ž ์ด์ƒ, ์˜๋ฌธ ๋Œ€,์†Œ๋ฌธ์ž, ์ˆซ์ž๋ฅผ ํฌํ•จํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค)" + required={true} /> - {isValidInfos.password ? "" : "๋น„๋ฐ€๋ฒˆํ˜ธ ํ˜•์‹์— ๋งž์ง€ ์•Š์Šต๋‹ˆ๋‹ค"} + <div className="signup__form__content__msg"> + {isValidInfos.password ? "" : "๋น„๋ฐ€๋ฒˆํ˜ธ ํ˜•์‹์— ๋งž์ง€ ์•Š์Šต๋‹ˆ๋‹ค"} + </div> </div> - ๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ* - <div> - <Input + <div className="signup__form__content"> + <InputBox type="password" id="repassword" value={infos.repassword} onChange={handleChange} + label="๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ" + required={true} /> - {isCheckedInfos.password ? "" : "๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค"} + <div className="signup__form__content__msg"> + {isCheckedInfos.password ? "" : "๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค"} + </div> </div> - </div> - <div> - ์œ ์ €๋„ค์ž„* - <div> - <Input + <div className="signup__form__content"> + <InputBox type="text" id="userName" value={infos.userName} onChange={handleChange} + label="์œ ์ €๋„ค์ž„" + required={true} /> - {isCheckedInfos.userName ? "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์œ ์ €๋„ค์ž„์ž…๋‹ˆ๋‹ค" : "์‚ฌ์šฉ์ค‘์ธ ์œ ์ €๋„ค์ž„์ž…๋‹ˆ๋‹ค"} + <div className="signup__form__content__msg"> + {isCheckedInfos.userName ? "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์œ ์ €๋„ค์ž„์ž…๋‹ˆ๋‹ค" : "์‚ฌ์šฉ์ค‘์ธ ์œ ์ €๋„ค์ž„์ž…๋‹ˆ๋‹ค"} + </div> </div> - </div> - <div> - ์ถ”์ฒœ์ธ ์œ ์ €๋„ค์ž„ - <div> - <Input + <div className="signup__form__content"> + <InputBox type="text" id="recommender" value={infos.recommender} onChange={handleChange} + label="์ถ”์ฒœ์ธ ์œ ์ €๋„ค์ž„" + required={false} /> - {infos.recommender && (isCheckedInfos.recommender ? "์ถ”์ฒœ์ธ์ด ํ™•์ธ๋˜์—ˆ์Šต๋‹ˆ๋‹ค" : "์ถ”์ฒœ์ธ์ด ํ™•์ธ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค")} - </div> - </div> - <div> - ์•ฝ๊ด€ ๋ฐ ๋งˆ์ผ“ํŒ… ๋™์˜ - <div> - ๋ชจ๋‘ ๋™์˜ - <InputBox - id="allTerms" - checked={infos.allTerms} - onChange={handleChangeInputBox} - /> - - </div> - <div> - ์•ฝ๊ด€ 1* - <InputBox - id="term1" - checked={infos.term1} - onChange={handleChangeInputBox} - /> + <div className="signup__form__content__msg"> + {infos.recommender && (isCheckedInfos.recommender ? "์ถ”์ฒœ์ธ์ด ํ™•์ธ๋˜์—ˆ์Šต๋‹ˆ๋‹ค" : "์ถ”์ฒœ์ธ์ด ํ™•์ธ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค")} + </div> </div> - <div> - ์•ฝ๊ด€2* - <InputBox - id="term2" - checked={infos.term2} - onChange={handleChangeInputBox} - /> + <div className="signup__form__checkbox"> + <div className="signup__form__checkbox__title"> + ์•ฝ๊ด€ ๋ฐ ๋งˆ์ผ€ํŒ… ๋™์˜ + </div> + <div> + <InputCheckBox + id="allTerms" + checked={infos.allTerms} + onChange={handleChangeInputCheckBox} + label="๋ชจ๋‘ ๋™์˜" + required={false} + /> + <InputCheckBox + id="term" + checked={infos.term} + onChange={handleChangeInputCheckBox} + label="์•ฝ๊ด€" + required={true} + /> + <InputCheckBox + id="privacy" + checked={infos.privacy} + onChange={handleChangeInputCheckBox} + label="๊ฐœ์ธ์ •๋ณดํ™œ์šฉ๋™์˜" + required={true} + /> + <InputCheckBox + id="marketing" + checked={infos.marketing} + onChange={handleChangeInputCheckBox} + label="๋งˆ์ผ€ํŒ…๋™์˜" + required={false} + /> + </div> </div> - <div> - ๋งˆ์ผ“ํŒ…๋™์˜ - <InputBox - id="marketing" - checked={infos.marketing} - onChange={handleChangeInputBox} + <div className="signup__form__submit"> + <input + className="signup__form__submit__input" + type="submit" + value="์ œ์ถœ" + disabled={ + isCheckedInfos.email && isCheckedInfos.phone + && isValidInfos.password && isCheckedInfos.password + && isCheckedInfos.userName + && ((infos.recommender && isCheckedInfos.recommender) || !infos.recommender) + && infos.term && infos.privacy + ? false : true + } /> </div> - </div> - <div> - <input - type="submit" - value="์ œ์ถœ" - disabled={ - isCheckedInfos.email && isCheckedInfos.phone - && isValidInfos.password && isCheckedInfos.password - && isCheckedInfos.userName - && ((infos.recommender && isCheckedInfos.recommender) || !infos.recommender) - && infos.term1 && infos.term2 - ? false : true - } - /> - </div> - </form> + </form> + </div> ) }
Unknown
๋ณ€์ˆ˜๋ช… ๋ฐ”๊พธ์‹  ๊ฑฐ ๊ตฟ๊ตฟ
@@ -1,19 +1,28 @@ +import './InputBox.css'; + type InputBoxProps = { + type: string; id: string; - checked: boolean; - onChange: any; + value: string; + onChange: (e : React.FormEvent<HTMLInputElement>) => void; + label: string; + required: boolean; } -const InputBox = ({id, checked, onChange}: InputBoxProps) => { +const InputBox = ({type, id, value, onChange, label, required}: InputBoxProps) => { return ( - <> + <div className='inputBox'> + <div className={required ? 'inputBox__title inputBox__title__required' : 'inputBox__title'}> + {label}{required && '*'} + </div> <input - type="checkbox" + className='inputBox__input' + type={type} id={id} - checked={checked} + value={value} onChange={onChange} /> - </> + </div> ) }
Unknown
์ปดํฌ๋„ŒํŠธ ์ด๋ฆ„์ด InputBox๋‹ˆ๊นŒ checkbox์šฉ input ์š”์†Œ๋ฅผ ์œ„ํ•œ ์ปดํฌ๋„ŒํŠธ ๊ฐ™์€๋ฐ, type props๋ฅผ ์ถ”๊ฐ€ํ•˜๊ณ  checked ์†์„ฑ ๋Œ€์‹  value ์†์„ฑ์œผ๋กœ ๋ณ€๊ฒฝํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -1,19 +1,28 @@ +import './InputBox.css'; + type InputBoxProps = { + type: string; id: string; - checked: boolean; - onChange: any; + value: string; + onChange: (e : React.FormEvent<HTMLInputElement>) => void; + label: string; + required: boolean; } -const InputBox = ({id, checked, onChange}: InputBoxProps) => { +const InputBox = ({type, id, value, onChange, label, required}: InputBoxProps) => { return ( - <> + <div className='inputBox'> + <div className={required ? 'inputBox__title inputBox__title__required' : 'inputBox__title'}> + {label}{required && '*'} + </div> <input - type="checkbox" + className='inputBox__input' + type={type} id={id} - checked={checked} + value={value} onChange={onChange} /> - </> + </div> ) }
Unknown
์•„! ๋ฐ‘์— InputCheckBox๊ฐ€ ๋”ฐ๋กœ ์žˆ๊ณ  ์›๋ž˜์˜ Input์ด InputBox๋กœ ๋ณ€๊ฒฝ๋œ๊ฑฐ์˜€๊ตฐ์š”. ์ €๋Š” ์ˆ˜์ • ์ „ ๊ทธ๋Œ€๋กœ Input๊ณผ InputCheckBox๊ฐ€ ๋” ๋‚˜์•„๋ณด์—ฌ์š”..!
@@ -1,9 +1,10 @@ import { useState } from "react"; -import Input from "../components/Input"; import InputBox from "../components/InputBox"; -import validation from "../utils/validation"; +import InputCheckBox from "../components/InputCheckBox"; +import validateFormInfos from "../utils/validation"; import checking from "../utils/checking"; import { useNavigate } from "react-router-dom"; +import './Signup.css'; function Signup() { const [infos, setInfos] = useState({ @@ -14,8 +15,8 @@ function Signup() { userName: "", recommender: "", allTerms: false, - term1: false, - term2: false, + term: false, + privacy: false, marketing: false }); @@ -38,7 +39,7 @@ function Signup() { const checkedList = ["email", "phone", "userName", "recommender"] const {id, value} = e.currentTarget; setInfos({...infos, [id]: value}); - if (validationList.includes(id) && !validation({id, value, isValidInfos, setIsValidInfos})) { + if (validationList.includes(id) && !validateFormInfos({id, value, isValidInfos, setIsValidInfos})) { if (checkedList.includes(id)) setIsCheckedInfos({...isCheckedInfos, [id]: false}) return; @@ -49,153 +50,166 @@ function Signup() { checking({id, value, isCheckedInfos, setIsCheckedInfos}) } - const handleChangeInputBox = (e : React.FormEvent<HTMLInputElement>) => { + const handleChangeInputCheckBox = (e : React.FormEvent<HTMLInputElement>) => { const {id, checked} = e.currentTarget; if (id === "allTerms") { - setInfos({...infos, allTerms: checked, term1: checked, term2: checked, marketing: checked}); + setInfos({...infos, allTerms: checked, term: checked, privacy: checked, marketing: checked}); } else { setInfos({...infos, [id]: checked}) if (!checked) { setInfos({...infos, [id]: false, allTerms: false}) - } else if ((infos.term1 && infos.term2) || (infos.term2 && infos.marketing) || (infos.term1 && infos.marketing)) { + } else if ((infos.term && infos.privacy) || (infos.privacy && infos.marketing) || (infos.term && infos.marketing)) { setInfos({...infos, [id]: true, allTerms: true}) } } } const navigate = useNavigate(); - const handleSubmit = (e : any) => { + const handleSubmit = (e : React.FormEvent<HTMLFormElement>) => { e.preventDefault(); navigate("/greeting"); } return( - <form onSubmit={handleSubmit}> - <div> + <div className="signup"> + <div className="signup__title"> + ํšŒ์›๊ฐ€์ž… + </div> + <div className="signup__msg"> * ํ‘œ์‹œ๋œ ํ•ญ๋ชฉ์€ ํ•„์ˆ˜๋กœ ์ž…๋ ฅํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค </div> - <div> - ์ด๋ฉ”์ผ* - <div> - <Input + <form className="signup__form" onSubmit={handleSubmit}> + <div className="signup__form__content"> + <InputBox type="text" id="email" value={infos.email} onChange={handleChange} + label="์ด๋ฉ”์ผ" + required={true} /> - {isValidInfos.email ? isCheckedInfos.email ? "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค" : "์ด๋ฏธ ์‚ฌ์šฉ์ค‘์ธ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค" : "์œ ํšจํ•˜์ง€ ์•Š์€ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค"} + <div className="signup__form__content__msg"> + {isValidInfos.email ? isCheckedInfos.email ? "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค" : "์ด๋ฏธ ์‚ฌ์šฉ์ค‘์ธ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค" : "์œ ํšจํ•˜์ง€ ์•Š์€ ์ด๋ฉ”์ผ์ž…๋‹ˆ๋‹ค"} + </div> </div> - </div> - <div> - ์ „ํ™”๋ฒˆํ˜ธ* - <div> - <Input + <div className="signup__form__content"> + <InputBox type="text" id="phone" value={infos.phone} onChange={handleChange} + label="์ „ํ™”๋ฒˆํ˜ธ" + required={true} /> - {isValidInfos.phone ? isCheckedInfos.phone? "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์ „ํ™”๋ฒˆํ˜ธ์ž…๋‹ˆ๋‹ค" : "์ด๋ฏธ ์‚ฌ์šฉ์ค‘์ธ ์ „ํ™”๋ฒˆํ˜ธ์ž…๋‹ˆ๋‹ค" : "์œ ํšจํ•˜์ง€ ์•Š์€ ์ „ํ™”๋ฒˆํ˜ธ์ž…๋‹ˆ๋‹ค"} + <div className="signup__form__content__msg"> + {isValidInfos.phone ? isCheckedInfos.phone? "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์ „ํ™”๋ฒˆํ˜ธ์ž…๋‹ˆ๋‹ค" : "์ด๋ฏธ ์‚ฌ์šฉ์ค‘์ธ ์ „ํ™”๋ฒˆํ˜ธ์ž…๋‹ˆ๋‹ค" : "์œ ํšจํ•˜์ง€ ์•Š์€ ์ „ํ™”๋ฒˆํ˜ธ์ž…๋‹ˆ๋‹ค"} + </div> </div> - </div> - <div> - ๋น„๋ฐ€๋ฒˆํ˜ธ* (๋น„๋ฐ€๋ฒˆํ˜ธ๋Š” 8์ž ์ด์ƒ, ์˜๋ฌธ ๋Œ€,์†Œ๋ฌธ์ž, ์ˆซ์ž๋ฅผ ํฌํ•จํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค) - <div> - <Input + <div className="signup__form__content"> + <InputBox type="password" id="password" value={infos.password} onChange={handleChange} + label="๋น„๋ฐ€๋ฒˆํ˜ธ(๋น„๋ฐ€๋ฒˆํ˜ธ๋Š” 8์ž ์ด์ƒ, ์˜๋ฌธ ๋Œ€,์†Œ๋ฌธ์ž, ์ˆซ์ž๋ฅผ ํฌํ•จํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค)" + required={true} /> - {isValidInfos.password ? "" : "๋น„๋ฐ€๋ฒˆํ˜ธ ํ˜•์‹์— ๋งž์ง€ ์•Š์Šต๋‹ˆ๋‹ค"} + <div className="signup__form__content__msg"> + {isValidInfos.password ? "" : "๋น„๋ฐ€๋ฒˆํ˜ธ ํ˜•์‹์— ๋งž์ง€ ์•Š์Šต๋‹ˆ๋‹ค"} + </div> </div> - ๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ* - <div> - <Input + <div className="signup__form__content"> + <InputBox type="password" id="repassword" value={infos.repassword} onChange={handleChange} + label="๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ" + required={true} /> - {isCheckedInfos.password ? "" : "๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค"} + <div className="signup__form__content__msg"> + {isCheckedInfos.password ? "" : "๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค"} + </div> </div> - </div> - <div> - ์œ ์ €๋„ค์ž„* - <div> - <Input + <div className="signup__form__content"> + <InputBox type="text" id="userName" value={infos.userName} onChange={handleChange} + label="์œ ์ €๋„ค์ž„" + required={true} /> - {isCheckedInfos.userName ? "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์œ ์ €๋„ค์ž„์ž…๋‹ˆ๋‹ค" : "์‚ฌ์šฉ์ค‘์ธ ์œ ์ €๋„ค์ž„์ž…๋‹ˆ๋‹ค"} + <div className="signup__form__content__msg"> + {isCheckedInfos.userName ? "์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์œ ์ €๋„ค์ž„์ž…๋‹ˆ๋‹ค" : "์‚ฌ์šฉ์ค‘์ธ ์œ ์ €๋„ค์ž„์ž…๋‹ˆ๋‹ค"} + </div> </div> - </div> - <div> - ์ถ”์ฒœ์ธ ์œ ์ €๋„ค์ž„ - <div> - <Input + <div className="signup__form__content"> + <InputBox type="text" id="recommender" value={infos.recommender} onChange={handleChange} + label="์ถ”์ฒœ์ธ ์œ ์ €๋„ค์ž„" + required={false} /> - {infos.recommender && (isCheckedInfos.recommender ? "์ถ”์ฒœ์ธ์ด ํ™•์ธ๋˜์—ˆ์Šต๋‹ˆ๋‹ค" : "์ถ”์ฒœ์ธ์ด ํ™•์ธ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค")} - </div> - </div> - <div> - ์•ฝ๊ด€ ๋ฐ ๋งˆ์ผ“ํŒ… ๋™์˜ - <div> - ๋ชจ๋‘ ๋™์˜ - <InputBox - id="allTerms" - checked={infos.allTerms} - onChange={handleChangeInputBox} - /> - - </div> - <div> - ์•ฝ๊ด€ 1* - <InputBox - id="term1" - checked={infos.term1} - onChange={handleChangeInputBox} - /> + <div className="signup__form__content__msg"> + {infos.recommender && (isCheckedInfos.recommender ? "์ถ”์ฒœ์ธ์ด ํ™•์ธ๋˜์—ˆ์Šต๋‹ˆ๋‹ค" : "์ถ”์ฒœ์ธ์ด ํ™•์ธ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค")} + </div> </div> - <div> - ์•ฝ๊ด€2* - <InputBox - id="term2" - checked={infos.term2} - onChange={handleChangeInputBox} - /> + <div className="signup__form__checkbox"> + <div className="signup__form__checkbox__title"> + ์•ฝ๊ด€ ๋ฐ ๋งˆ์ผ€ํŒ… ๋™์˜ + </div> + <div> + <InputCheckBox + id="allTerms" + checked={infos.allTerms} + onChange={handleChangeInputCheckBox} + label="๋ชจ๋‘ ๋™์˜" + required={false} + /> + <InputCheckBox + id="term" + checked={infos.term} + onChange={handleChangeInputCheckBox} + label="์•ฝ๊ด€" + required={true} + /> + <InputCheckBox + id="privacy" + checked={infos.privacy} + onChange={handleChangeInputCheckBox} + label="๊ฐœ์ธ์ •๋ณดํ™œ์šฉ๋™์˜" + required={true} + /> + <InputCheckBox + id="marketing" + checked={infos.marketing} + onChange={handleChangeInputCheckBox} + label="๋งˆ์ผ€ํŒ…๋™์˜" + required={false} + /> + </div> </div> - <div> - ๋งˆ์ผ“ํŒ…๋™์˜ - <InputBox - id="marketing" - checked={infos.marketing} - onChange={handleChangeInputBox} + <div className="signup__form__submit"> + <input + className="signup__form__submit__input" + type="submit" + value="์ œ์ถœ" + disabled={ + isCheckedInfos.email && isCheckedInfos.phone + && isValidInfos.password && isCheckedInfos.password + && isCheckedInfos.userName + && ((infos.recommender && isCheckedInfos.recommender) || !infos.recommender) + && infos.term && infos.privacy + ? false : true + } /> </div> - </div> - <div> - <input - type="submit" - value="์ œ์ถœ" - disabled={ - isCheckedInfos.email && isCheckedInfos.phone - && isValidInfos.password && isCheckedInfos.password - && isCheckedInfos.userName - && ((infos.recommender && isCheckedInfos.recommender) || !infos.recommender) - && infos.term1 && infos.term2 - ? false : true - } - /> - </div> - </form> + </form> + </div> ) }
Unknown
์ •ํ™•ํ•œ ํƒ€์ž… ์ข‹์Šต๋‹ˆ๋‹ค~!
@@ -0,0 +1,28 @@ +import './InputCheckBox.css'; + +type InputCheckBoxProps = { + id: string; + checked: boolean; + onChange: (e : React.FormEvent<HTMLInputElement>) => void; + label?: string; + required?: boolean; +} + +const InputCheckBox = ({id, checked, onChange, label, required}: InputCheckBoxProps) => { + return ( + <div className='inputCheckBox'> + <input + className='inputCheckBox__input' + type="checkbox" + id={id} + checked={checked} + onChange={onChange} + /> + <label htmlFor={id} className={required ? 'inputCheckBox__title inputCheckBox__title__required' : 'inputCheckBox__title'}> + {label}{required && '*'} + </label> + </div> + ) +} + +export default InputCheckBox; \ No newline at end of file
Unknown
label์˜ className์„ ๊ฒฐ์ •ํ•˜๋Š” ๋ถ€๋ถ„์ด inputBox์™€ inputCheckBox์—์„œ ๋ฐ˜๋ณต๋ฉ๋‹ˆ๋‹ค. ์ด ๋ถ€๋ถ„์„ ํ•„์ˆ˜ className๊ณผ ํ”Œ๋ž˜๊ทธ์— ๋”ฐ๋ผ ์ถ”๊ฐ€์—ฌ๋ถ€๊ฐ€ ์ •ํ•ด์ง€๋Š” className, ๊ทธ๋ฆฌ๊ณ  ํ”Œ๋ž˜๊ทธ๋ฅผ ์ธ์ž๋กœ ๋ฐ›์•„์„œ ํด๋ž˜์Šค ๋„ค์ž„์„ ๋ฆฌํ„ดํ•ด์ฃผ๋Š” ํ•จ์ˆ˜๋กœ ๋ฐ”๊ฟ”๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”? ```suggestion const InputCheckBox = ({id, checked, onChange, label, required}: InputCheckBoxProps) => { const labelClassName = getClassNameByRequired('inputCheckBox__title', 'inputCheckBox__title__required', required); return ( <div className='inputCheckBox'> <input className='inputCheckBox__input' type="checkbox" id={id} checked={checked} onChange={onChange} /> <label htmlFor={id} className={labelClassName}> {label}{required && '*'} </label> </div> ) } ``` ```js const getClassNameByRequired = (core:string, suffix:string, required:boolean) => { return (required) ? `${core} ${suffix}` : `${core}` } ```
@@ -0,0 +1,65 @@ + +package basball.view; + +import basball.baseball.model.GameStatus; + +import java.util.Arrays; +import java.util.Scanner; +import java.util.regex.Pattern; + +public final class InputView { + + private static final String INPUT_NUMBER_MESSAGE = "์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š” : "; + private static final Scanner sc = new Scanner(System.in); + + public int[] getInputNumber() { + System.out.print(INPUT_NUMBER_MESSAGE); + String next = sc.next().trim(); + + Validator.hasThreeNumber(next); + + return getNumberArray(next); + } + + private int[] getNumberArray(String next) { + return Arrays.stream(next.split("")).mapToInt(value -> Integer.parseInt(value)).toArray(); + } + + public GameStatus getRestartInput() { + String answer = sc.next(); + Validator.validateAnswer(answer); + + if (answer.equals("1")) { + return GameStatus.RUNNING; + } + return GameStatus.END; + } + + public static class Validator { + private static final Pattern PATTERN = Pattern.compile("[1-9]{3}"); + + public static void hasThreeNumber(String next) { + + if (!PATTERN.matcher(next).matches()) { + throw new IllegalArgumentException("์„œ๋กœ ๋‹ค๋ฅธ 3์ž๋ฆฌ ์ˆซ์ž๋งŒ ์ž…๋ ฅ ํ•ด์ฃผ์„ธ์š”"); + } + } + + public static void isDifferentNumbers(int[] numbers) { + + if (isSameNumber(numbers[0], numbers[1]) || isSameNumber(numbers[0], numbers[2]) || isSameNumber(numbers[1], numbers[2])) { + throw new IllegalArgumentException("์„œ๋กœ ๋‹ค๋ฅธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”"); + } + } + + private static boolean isSameNumber(int number1, int number2) { + return number1 == number2; + } + + public static void validateAnswer(String answer) { + if (!answer.equals("1") && !answer.equals("2")) { + throw new IllegalArgumentException("1 ๋˜๋Š” 2๋งŒ ์ž…๋ ฅ ํ•ด ์ฃผ์„ธ์š”"); + } + } + } +}
Java
(nit) Inner class๋กœ ๋‘์‹ค๊ฑฐ๋ฉด Validator์™€ ๋‚ด๋ถ€ ๋ฉ”์†Œ๋“œ ๋ชจ๋‘ private์œผ๋กœ ํ•˜๋Š”๊ฒŒ ์ข‹๊ฒ ์–ด์š”.
@@ -0,0 +1,65 @@ + +package basball.view; + +import basball.baseball.model.GameStatus; + +import java.util.Arrays; +import java.util.Scanner; +import java.util.regex.Pattern; + +public final class InputView { + + private static final String INPUT_NUMBER_MESSAGE = "์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š” : "; + private static final Scanner sc = new Scanner(System.in); + + public int[] getInputNumber() { + System.out.print(INPUT_NUMBER_MESSAGE); + String next = sc.next().trim(); + + Validator.hasThreeNumber(next); + + return getNumberArray(next); + } + + private int[] getNumberArray(String next) { + return Arrays.stream(next.split("")).mapToInt(value -> Integer.parseInt(value)).toArray(); + } + + public GameStatus getRestartInput() { + String answer = sc.next(); + Validator.validateAnswer(answer); + + if (answer.equals("1")) { + return GameStatus.RUNNING; + } + return GameStatus.END; + } + + public static class Validator { + private static final Pattern PATTERN = Pattern.compile("[1-9]{3}"); + + public static void hasThreeNumber(String next) { + + if (!PATTERN.matcher(next).matches()) { + throw new IllegalArgumentException("์„œ๋กœ ๋‹ค๋ฅธ 3์ž๋ฆฌ ์ˆซ์ž๋งŒ ์ž…๋ ฅ ํ•ด์ฃผ์„ธ์š”"); + } + } + + public static void isDifferentNumbers(int[] numbers) { + + if (isSameNumber(numbers[0], numbers[1]) || isSameNumber(numbers[0], numbers[2]) || isSameNumber(numbers[1], numbers[2])) { + throw new IllegalArgumentException("์„œ๋กœ ๋‹ค๋ฅธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”"); + } + } + + private static boolean isSameNumber(int number1, int number2) { + return number1 == number2; + } + + public static void validateAnswer(String answer) { + if (!answer.equals("1") && !answer.equals("2")) { + throw new IllegalArgumentException("1 ๋˜๋Š” 2๋งŒ ์ž…๋ ฅ ํ•ด ์ฃผ์„ธ์š”"); + } + } + } +}
Java
๋ฉ˜ํ† ๋‹˜ ์•ˆ๋…•ํ•˜์„ธ์š” ! ๋‹ต๋ณ€ ๋‚จ๊ฒจ์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๊ทธ๋Ÿฐ๋ฐ Validator ๋ฅผ private ๋กœ ๋ฐ”๊พธ๋ฉด Balls ๋ž‘ InputView ํ…Œ์ŠคํŠธ ๊ฐ™์€ ๊ณณ ์—์„œ๋Š” ์–ด๋–ป๊ฒŒ ์‚ฌ์šฉํ•ด์•ผ ํ•˜๋‚˜์š” ? ์ œ ์ƒ๊ฐ์œผ๋กœ๋Š” InputView ์•ˆ์— get ๋ฉ”์„œ๋“œ๋กœ ์ ‘๊ทผ ๋ฉ”์„œ๋“œ๋ฅผ ์ œ๊ณตํ•˜๋Š” ๋ฐฉ๋ฒ• ๋ฟ์ธ๋ฐ ์ด๋ ‡๊ฒŒ ๋˜๋ฉด InputView ํ…Œ์ŠคํŠธ๋Š” ๊ทธ๋ ‡๋‹ค ์ณ๋„ Balls ๋ถ€๋ถ„์—์„œ Validator ๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ๋ถˆํ•„์š”ํ•˜๊ฒŒ InputView ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค์–ด์•ผ ํ•˜๋Š”๋ฐ ๋งž์„๊นŒ์š” !? ์•„๋‹ˆ๋ฉด ์ €๋ฒˆ์— ๋‚จ๊ฒจ์ฃผ์‹  static class ๋กœ ๋ฐ”๊พธ๋ผ๋Š”๊ฒŒ ์ด๋ ‡๊ฒŒ ๋ฐ”๊พธ๋ผ๊ณ  ํ•˜์‹ ๊ฒŒ ์•„๋‹ˆ์˜€๋‚˜์š” !??
@@ -0,0 +1,65 @@ + +package basball.view; + +import basball.baseball.model.GameStatus; + +import java.util.Arrays; +import java.util.Scanner; +import java.util.regex.Pattern; + +public final class InputView { + + private static final String INPUT_NUMBER_MESSAGE = "์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š” : "; + private static final Scanner sc = new Scanner(System.in); + + public int[] getInputNumber() { + System.out.print(INPUT_NUMBER_MESSAGE); + String next = sc.next().trim(); + + Validator.hasThreeNumber(next); + + return getNumberArray(next); + } + + private int[] getNumberArray(String next) { + return Arrays.stream(next.split("")).mapToInt(value -> Integer.parseInt(value)).toArray(); + } + + public GameStatus getRestartInput() { + String answer = sc.next(); + Validator.validateAnswer(answer); + + if (answer.equals("1")) { + return GameStatus.RUNNING; + } + return GameStatus.END; + } + + public static class Validator { + private static final Pattern PATTERN = Pattern.compile("[1-9]{3}"); + + public static void hasThreeNumber(String next) { + + if (!PATTERN.matcher(next).matches()) { + throw new IllegalArgumentException("์„œ๋กœ ๋‹ค๋ฅธ 3์ž๋ฆฌ ์ˆซ์ž๋งŒ ์ž…๋ ฅ ํ•ด์ฃผ์„ธ์š”"); + } + } + + public static void isDifferentNumbers(int[] numbers) { + + if (isSameNumber(numbers[0], numbers[1]) || isSameNumber(numbers[0], numbers[2]) || isSameNumber(numbers[1], numbers[2])) { + throw new IllegalArgumentException("์„œ๋กœ ๋‹ค๋ฅธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”"); + } + } + + private static boolean isSameNumber(int number1, int number2) { + return number1 == number2; + } + + public static void validateAnswer(String answer) { + if (!answer.equals("1") && !answer.equals("2")) { + throw new IllegalArgumentException("1 ๋˜๋Š” 2๋งŒ ์ž…๋ ฅ ํ•ด ์ฃผ์„ธ์š”"); + } + } + } +}
Java
์ „์— ๋‚จ๊ฒจ๋“œ๋ฆฐ๊ฑด static ๊ฐœ๋ณ„ ํด๋ž˜์Šค๋กœ ๋‘๋ผ๋Š” ์–˜๊ธฐ์˜€์–ด์š” ใ…Žใ…Ž ์ œ๊ฐ€ private๋กœ ํ•˜๋ผ๊ณ  ๋ง์”€๋“œ๋ฆฐ๊ฑด ์‚ฌ์‹ค InputView ๋‚ด์—์„œ๋งŒ ์“ฐ์—ฌ์„œ ๊ทธ๋ ‡๊ฒŒ ๋ง์”€๋“œ๋ฆฐ๊ฑฐ์˜€์–ด์š”. ๋งŒ์•ฝ Validator ์ž์ฒด๊ฐ€ ๋ฐ–์œผ๋กœ ๋‚˜์™€์žˆ์„ ์ด์œ ๊ฐ€ ์—†๋‹ค๋ฉด ํ…Œ์ŠคํŠธ๋„ ํ•„์š”์—†๋Š”๊ฑฐ๊ฒ ์ฃ . (์บก์Аํ™”์˜ ์˜๋ฏธ์˜€์–ด์š”. Validator๋ฅผ ๊ฐ€์ ธ๋‹ค ์“ธ ๋ฐ๊ฐ€ InputView ์™ธ์— ์—†๋‹ค๋ฉด ๊ตณ์ด Validator๊ฐ€ ์–ด๋–ป๊ฒŒ ๊ตฌํ˜„๋˜์—ˆ๋Š”์ง€ ํ…Œ์ŠคํŠธ๋ฅผ ์–ด๋–ป๊ฒŒ ํ• ์ง€๋„ ๊ณ ๋ฏผํ•  ํ•„์š”๊ฐ€ ์—†๋Š”๊ฑฐ๊ฒ ์ฃ ) ํ•˜์ง€๋งŒ Validator๊ฐ€ ๋‹ค๋ฅธ๋ฐ์„œ๋„ ์“ฐ์ผ๊ฑฐ๋ผ๋ฉด ๊ฐœ๋ณ„ static ํด๋ž˜์Šค๋กœ ๋นผ๋‘๋Š”๊ฒŒ ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,65 @@ + +package basball.view; + +import basball.baseball.model.GameStatus; + +import java.util.Arrays; +import java.util.Scanner; +import java.util.regex.Pattern; + +public final class InputView { + + private static final String INPUT_NUMBER_MESSAGE = "์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š” : "; + private static final Scanner sc = new Scanner(System.in); + + public int[] getInputNumber() { + System.out.print(INPUT_NUMBER_MESSAGE); + String next = sc.next().trim(); + + Validator.hasThreeNumber(next); + + return getNumberArray(next); + } + + private int[] getNumberArray(String next) { + return Arrays.stream(next.split("")).mapToInt(value -> Integer.parseInt(value)).toArray(); + } + + public GameStatus getRestartInput() { + String answer = sc.next(); + Validator.validateAnswer(answer); + + if (answer.equals("1")) { + return GameStatus.RUNNING; + } + return GameStatus.END; + } + + public static class Validator { + private static final Pattern PATTERN = Pattern.compile("[1-9]{3}"); + + public static void hasThreeNumber(String next) { + + if (!PATTERN.matcher(next).matches()) { + throw new IllegalArgumentException("์„œ๋กœ ๋‹ค๋ฅธ 3์ž๋ฆฌ ์ˆซ์ž๋งŒ ์ž…๋ ฅ ํ•ด์ฃผ์„ธ์š”"); + } + } + + public static void isDifferentNumbers(int[] numbers) { + + if (isSameNumber(numbers[0], numbers[1]) || isSameNumber(numbers[0], numbers[2]) || isSameNumber(numbers[1], numbers[2])) { + throw new IllegalArgumentException("์„œ๋กœ ๋‹ค๋ฅธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”"); + } + } + + private static boolean isSameNumber(int number1, int number2) { + return number1 == number2; + } + + public static void validateAnswer(String answer) { + if (!answer.equals("1") && !answer.equals("2")) { + throw new IllegalArgumentException("1 ๋˜๋Š” 2๋งŒ ์ž…๋ ฅ ํ•ด ์ฃผ์„ธ์š”"); + } + } + } +}
Java
์•ˆ๋…•ํ•˜์„ธ์š” ๋ฉ˜ํ† ๋‹˜ ! `๊ฐœ๋ณ„ static ํด๋ž˜์Šค` ๋ผ๋Š” ๋ง์ด ์ž˜ ์ดํ•ด๊ฐ€ ์•ˆ๋˜๋Š”๋ฐ ํ˜น์‹œ `Math` ํด๋ž˜์Šค ์ฒ˜๋Ÿผ `final ๊ณผ private ์ƒ์„ฑ์ž` ๋ฅผ ํ†ตํ•ด ์ƒ์„ฑ์„ ๋ง‰๊ณ  ๋‹จ์ง€ `Utils` ํด๋ž˜์Šค ์ฒ˜๋Ÿผ ์‚ฌ์šฉ ์„ ์˜๋ฏธ ํ•˜์‹œ๋Š”๊ฑด๊ฐ€์š” ? ?์•„๋‹ˆ๋ฉด ์™ธ๋ถ€๋Š” `public ํด๋ž˜์Šค` ๋กœ ๋งŒ๋“ค๊ณ  ๋‚ด๋ถ€์— `public static class` ๋กœ ๋งŒ๋“ค๋ผ๊ณ  ํ•˜์‹œ๋Š” ๊ฑด๊ฐ€์š” ?? < final ์‚ฌ์šฉ > ``` public final class Validator { private Validator() { } private static final Pattern PATTERN = Pattern.compile("[1-9]{3}"); public static void hasThreeNumber(String next) { if (!PATTERN.matcher(next).matches()) { throw new IllegalArgumentException("์„œ๋กœ ๋‹ค๋ฅธ 3์ž๋ฆฌ ์ˆซ์ž๋งŒ ์ž…๋ ฅ ํ•ด์ฃผ์„ธ์š”"); } } ... } ``` < static ์‚ฌ์šฉ > ``` public class Validators { public static class Validator { private static final Pattern PATTERN = Pattern.compile("[1-9]{3}"); public static void hasThreeNumber(String next) { if (!PATTERN.matcher(next).matches()) { throw new IllegalArgumentException("์„œ๋กœ ๋‹ค๋ฅธ 3์ž๋ฆฌ ์ˆซ์ž๋งŒ ์ž…๋ ฅ ํ•ด์ฃผ์„ธ์š”"); } } ... } } ```
@@ -0,0 +1,65 @@ + +package basball.view; + +import basball.baseball.model.GameStatus; + +import java.util.Arrays; +import java.util.Scanner; +import java.util.regex.Pattern; + +public final class InputView { + + private static final String INPUT_NUMBER_MESSAGE = "์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š” : "; + private static final Scanner sc = new Scanner(System.in); + + public int[] getInputNumber() { + System.out.print(INPUT_NUMBER_MESSAGE); + String next = sc.next().trim(); + + Validator.hasThreeNumber(next); + + return getNumberArray(next); + } + + private int[] getNumberArray(String next) { + return Arrays.stream(next.split("")).mapToInt(value -> Integer.parseInt(value)).toArray(); + } + + public GameStatus getRestartInput() { + String answer = sc.next(); + Validator.validateAnswer(answer); + + if (answer.equals("1")) { + return GameStatus.RUNNING; + } + return GameStatus.END; + } + + public static class Validator { + private static final Pattern PATTERN = Pattern.compile("[1-9]{3}"); + + public static void hasThreeNumber(String next) { + + if (!PATTERN.matcher(next).matches()) { + throw new IllegalArgumentException("์„œ๋กœ ๋‹ค๋ฅธ 3์ž๋ฆฌ ์ˆซ์ž๋งŒ ์ž…๋ ฅ ํ•ด์ฃผ์„ธ์š”"); + } + } + + public static void isDifferentNumbers(int[] numbers) { + + if (isSameNumber(numbers[0], numbers[1]) || isSameNumber(numbers[0], numbers[2]) || isSameNumber(numbers[1], numbers[2])) { + throw new IllegalArgumentException("์„œ๋กœ ๋‹ค๋ฅธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”"); + } + } + + private static boolean isSameNumber(int number1, int number2) { + return number1 == number2; + } + + public static void validateAnswer(String answer) { + if (!answer.equals("1") && !answer.equals("2")) { + throw new IllegalArgumentException("1 ๋˜๋Š” 2๋งŒ ์ž…๋ ฅ ํ•ด ์ฃผ์„ธ์š”"); + } + } + } +}
Java
์•— ์Œ..์ œ๊ฐ€ ๋ง์”€๋“œ๋ฆฐ๊ฑธ ๋„ˆ๋ฌด ํฌ๊ฒŒ ์ƒ๊ฐํ•˜์‹  ๊ฒƒ ๊ฐ™๊ตฐ์š”..^^; ์ œ๊ฐ€ ๋ง์”€๋“œ๋ฆฐ๊ฑด ๋‹จ์ˆœํžˆ Validator.java ํŒŒ์ผ์„ ํ•˜๋‚˜ ๋” ๋งŒ๋“ค์–ด์„œ ๊ฑฐ๊ธฐ๋‹ค ๋„ฃ๋Š”๋‹ค๋Š” ์–˜๊ธฐ์˜€์–ด์š”. ๊ทธ๋Ÿฌ๋ฉด ๊ตณ์ด InputView์— ์ข…์†์ ์ธ namespace๋ฅผ ๊ฐ€์งˆ ํ•„์š”๊ฐ€ ์—†์œผ๋‹ˆ๊นŒ์š” ใ…Žใ…Ž
@@ -88,5 +88,186 @@ export default { display: flex; align-items: center; justify-content: center; + html, + body { + height: 100%; + width: 100%; + padding: 0; + margin: 0; + } + .container { + background: white; + width: 100%; + height: 100%; + display: flex; + flex-direction: column; + flex-wrap: nowrap; + } + .container .main { + display: flex; + flex: 1; + flex-direction: column; + } + + .container .main-content { + background-color: #7278c6; + display: flex; + flex: 1; + height: 100%; + color: #f0f0f6; + flex-direction: column; + align-items: center; + padding-top: 20px; + font-weight: bold; + font-size: 20px; + } + .container .main-center { + display: flex; + background-color: #f7f7f7; + flex: 1; + height: 100%; + justify-content: center; + + position: relative; + } + .main-center .car-card { + display: flex; + flex-direction: column; + width: 70%; + background-color: #ffffff; + justify-content: center; + padding: 10px 30px; + position: absolute; + top: -100px; + } + .main-center .car-card .top { + display: flex; + justify-content: center; + } + .main-center .car-card .bottom { + display: flex; + } + + .main-center .car-card .bottom .left { + display: flex; + flex-direction: column; + flex: 1; + font-weight: bold; + } + + .main-center .car-card .bottom .right { + display: flex; + flex-direction: column; + align-items: flex-end; + flex: 1; + } + + .container .main-center-footer { + display: flex; + color: #5c63b9; + align-items: flex-end; + justify-content: start; + background-color: #f7f7f7; + font-weight: bold; + padding: 10px 30px; + } + + .container .main-bottom { + display: flex; + flex: 1; + height: 100%; + flex-direction: column; + } + + .main-bottom .content { + display: flex; + height: 100%; + } + .main-bottom .content .left { + display: flex; + flex: 1; + flex-direction: column; + justify-content: flex-start; + } + + .main-bottom .content .right-img { + display: flex; + flex: 1; + align-items: flex-start; + justify-content: center; + } + .main-bottom .content .right-img img { + width: 200px; + height: 120px; + } + + .main-bottom .first-line { + display: flex; + padding-left: 30px; + margin: 10px 0px; + } + + .main-bottom .first-line .left-txt { + display: flex; + justify-content: center; + background-color: #565db7; + flex: 1; + font-size: 12px; + color: #f6f7fb; + padding: 3px; + } + + .main-bottom .first-line .right { + display: flex; + padding-left: 10px; + flex: 3; + font-weight: bold; + } + + .main-bottom .second-line { + display: flex; + padding-left: 30px; + font-size: 15px; + color: #5e5e5e; + } + + .main-bottom .third-line { + display: flex; + padding-left: 30px; + font-size: 15px; + color: #c6c6d1; + } + .main-bottom .fourth-line { + display: flex; + padding-left: 30px; + color: #555555; + font-weight: bold; + } + + .main-bottom .last-line { + display: flex; + padding: 10px; + border-top: solid 1px #f7f7f7; + } + .main-bottom .last-line .left { + display: flex; + justify-content: center; + flex: 1; + color: #575cb5; + font-weight: bold; + } + .main-bottom .last-line .right { + display: flex; + justify-content: center; + flex: 1; + color: #575cb5; + font-weight: bold; + } + + .container .event { + display: flex; + flex: 1; + background-color: #f7f7f7; + } } </style> \ No newline at end of file
Unknown
์—ฌ๊ธฐ์ด๋ ‡๊ฒŒํ•˜๋ฉด์•ˆ๋ผ์š”
@@ -88,5 +88,186 @@ export default { display: flex; align-items: center; justify-content: center; + html, + body { + height: 100%; + width: 100%; + padding: 0; + margin: 0; + } + .container { + background: white; + width: 100%; + height: 100%; + display: flex; + flex-direction: column; + flex-wrap: nowrap; + } + .container .main { + display: flex; + flex: 1; + flex-direction: column; + } + + .container .main-content { + background-color: #7278c6; + display: flex; + flex: 1; + height: 100%; + color: #f0f0f6; + flex-direction: column; + align-items: center; + padding-top: 20px; + font-weight: bold; + font-size: 20px; + } + .container .main-center { + display: flex; + background-color: #f7f7f7; + flex: 1; + height: 100%; + justify-content: center; + + position: relative; + } + .main-center .car-card { + display: flex; + flex-direction: column; + width: 70%; + background-color: #ffffff; + justify-content: center; + padding: 10px 30px; + position: absolute; + top: -100px; + } + .main-center .car-card .top { + display: flex; + justify-content: center; + } + .main-center .car-card .bottom { + display: flex; + } + + .main-center .car-card .bottom .left { + display: flex; + flex-direction: column; + flex: 1; + font-weight: bold; + } + + .main-center .car-card .bottom .right { + display: flex; + flex-direction: column; + align-items: flex-end; + flex: 1; + } + + .container .main-center-footer { + display: flex; + color: #5c63b9; + align-items: flex-end; + justify-content: start; + background-color: #f7f7f7; + font-weight: bold; + padding: 10px 30px; + } + + .container .main-bottom { + display: flex; + flex: 1; + height: 100%; + flex-direction: column; + } + + .main-bottom .content { + display: flex; + height: 100%; + } + .main-bottom .content .left { + display: flex; + flex: 1; + flex-direction: column; + justify-content: flex-start; + } + + .main-bottom .content .right-img { + display: flex; + flex: 1; + align-items: flex-start; + justify-content: center; + } + .main-bottom .content .right-img img { + width: 200px; + height: 120px; + } + + .main-bottom .first-line { + display: flex; + padding-left: 30px; + margin: 10px 0px; + } + + .main-bottom .first-line .left-txt { + display: flex; + justify-content: center; + background-color: #565db7; + flex: 1; + font-size: 12px; + color: #f6f7fb; + padding: 3px; + } + + .main-bottom .first-line .right { + display: flex; + padding-left: 10px; + flex: 3; + font-weight: bold; + } + + .main-bottom .second-line { + display: flex; + padding-left: 30px; + font-size: 15px; + color: #5e5e5e; + } + + .main-bottom .third-line { + display: flex; + padding-left: 30px; + font-size: 15px; + color: #c6c6d1; + } + .main-bottom .fourth-line { + display: flex; + padding-left: 30px; + color: #555555; + font-weight: bold; + } + + .main-bottom .last-line { + display: flex; + padding: 10px; + border-top: solid 1px #f7f7f7; + } + .main-bottom .last-line .left { + display: flex; + justify-content: center; + flex: 1; + color: #575cb5; + font-weight: bold; + } + .main-bottom .last-line .right { + display: flex; + justify-content: center; + flex: 1; + color: #575cb5; + font-weight: bold; + } + + .container .event { + display: flex; + flex: 1; + background-color: #f7f7f7; + } } </style> \ No newline at end of file
Unknown
์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,105 @@ +import { Helmet } from 'react-helmet-async'; +import titles from '../routes/titles'; +import styled from 'styled-components'; +import MainCard from './components/MainCard'; +import Tag from './components/Tag'; +import Card from './components/Card'; +import { useQuery } from 'react-query'; +import { getArticles } from '../api/ArticlesController'; +import { useState } from 'react'; +import { useNavigate } from 'react-router-dom'; + +const BlogWrapper = styled.div` + display: flex; + flex-direction: column; + justify-content: center; + width: 100%; + margin: 0px 120px 0px 120px; +`; + +const TagBox = styled.div` + display: flex; + gap: 10px; + margin-bottom: 44px; + margin: 0px 48px; +`; + +const CardBox = styled.div` + display: grid; + grid-template-columns: repeat(2, 1fr); + row-gap: 3rem; + column-gap: 6rem; + margin: 44px 48px 0px 48px; + + a { + display: flex; + justify-items: center; + justify-content: center; + } +`; + +function BlogPage() { + const navigate = useNavigate(); + + const { + data: cardData, + isLoading, + error, + } = useQuery({ + queryKey: ['articles'], + queryFn: getArticles, + }); + + const [activeTag, setActiveTag] = useState('์ „์ฒด'); + + if (isLoading) return 'Loading...'; + + if (error) return 'An error has occurred: ' + error; + + if (!cardData || cardData.length === 0) return 'No data available'; + + const mainCardData = cardData[0]; + + const categories = [ + { id: 0, text: '์ „์ฒด' }, + { id: 1, text: '๋ฌธํ™”' }, + { id: 2, text: '์„œ๋น„์Šค' }, + { id: 3, text: '์ปค๋ฆฌ์–ด' }, + ]; + + return ( + <> + <Helmet> + <title>{titles.blog}</title> + </Helmet> + <BlogWrapper> + <MainCard + mainCard={mainCardData} + onClick={()=>navigate(`/blog/${mainCardData.articleId}`)} + /> + <TagBox> + {categories.map((category) => ( + <Tag + key={category.id} + text={category.text} + onClick={() => setActiveTag(category.text)} + isActive={category.text === activeTag} + /> + ))} + </TagBox> + <CardBox> + {cardData.map((card) => ( + <Card + key={card.articleId} + card={card} + isActive={card.categories[0] === activeTag || '์ „์ฒด' === activeTag } + onClick={()=>navigate(`/blog/${card.articleId}`)} + /> + ))} + </CardBox> + </BlogWrapper> + </> + ); +} + +export default BlogPage;
Unknown
P4: margin์ด๋ž‘ margin-bottom ๊ฐ™์ด ์“ด ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”? ํ•˜๋‚˜๋กœ ํ†ต์ผํ•˜๋ฉด ๋  ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,105 @@ +import { Helmet } from 'react-helmet-async'; +import titles from '../routes/titles'; +import styled from 'styled-components'; +import MainCard from './components/MainCard'; +import Tag from './components/Tag'; +import Card from './components/Card'; +import { useQuery } from 'react-query'; +import { getArticles } from '../api/ArticlesController'; +import { useState } from 'react'; +import { useNavigate } from 'react-router-dom'; + +const BlogWrapper = styled.div` + display: flex; + flex-direction: column; + justify-content: center; + width: 100%; + margin: 0px 120px 0px 120px; +`; + +const TagBox = styled.div` + display: flex; + gap: 10px; + margin-bottom: 44px; + margin: 0px 48px; +`; + +const CardBox = styled.div` + display: grid; + grid-template-columns: repeat(2, 1fr); + row-gap: 3rem; + column-gap: 6rem; + margin: 44px 48px 0px 48px; + + a { + display: flex; + justify-items: center; + justify-content: center; + } +`; + +function BlogPage() { + const navigate = useNavigate(); + + const { + data: cardData, + isLoading, + error, + } = useQuery({ + queryKey: ['articles'], + queryFn: getArticles, + }); + + const [activeTag, setActiveTag] = useState('์ „์ฒด'); + + if (isLoading) return 'Loading...'; + + if (error) return 'An error has occurred: ' + error; + + if (!cardData || cardData.length === 0) return 'No data available'; + + const mainCardData = cardData[0]; + + const categories = [ + { id: 0, text: '์ „์ฒด' }, + { id: 1, text: '๋ฌธํ™”' }, + { id: 2, text: '์„œ๋น„์Šค' }, + { id: 3, text: '์ปค๋ฆฌ์–ด' }, + ]; + + return ( + <> + <Helmet> + <title>{titles.blog}</title> + </Helmet> + <BlogWrapper> + <MainCard + mainCard={mainCardData} + onClick={()=>navigate(`/blog/${mainCardData.articleId}`)} + /> + <TagBox> + {categories.map((category) => ( + <Tag + key={category.id} + text={category.text} + onClick={() => setActiveTag(category.text)} + isActive={category.text === activeTag} + /> + ))} + </TagBox> + <CardBox> + {cardData.map((card) => ( + <Card + key={card.articleId} + card={card} + isActive={card.categories[0] === activeTag || '์ „์ฒด' === activeTag } + onClick={()=>navigate(`/blog/${card.articleId}`)} + /> + ))} + </CardBox> + </BlogWrapper> + </> + ); +} + +export default BlogPage;
Unknown
P1: suspense๋กœ ์˜ฎ๊ธฐ๋Š” ๊ฒƒ ๊ณต๋ถ€ https://blog.jbee.io/react/React%EC%97%90%EC%84%9C+%EC%84%A0%EC%96%B8%EC%A0%81%EC%9C%BC%EB%A1%9C+%EB%B9%84%EB%8F%99%EA%B8%B0+%EB%8B%A4%EB%A3%A8%EA%B8%B0
@@ -0,0 +1,32 @@ +import styled from 'styled-components'; + +const TagWrapper = styled.div<{ $isActive: boolean }>` + border-radius: 40px; + border: none; + padding: 14px 20px; + font-size: 18px; + cursor: pointer; + line-height: 22px; + color: ${(props) => (props.$isActive ? '#ffffff' : '#868b94')}; + background-color: ${(props) => (props.$isActive ? '#212124' : '#f2f3f6')}; + font-weight: ${(props) => (props.$isActive ? '600' : '400')}; + &:hover { + background-color: #212124; + color: #ffffff; + font-weight: 600; + } +`; + +interface TagProps { + text: string; + isActive: boolean; + onClick: () => void; +}; + +export default function Tag({ isActive, onClick, text }: TagProps) { + return ( + <TagWrapper $isActive={isActive} onClick={onClick}> + {text} + </TagWrapper> + ); +}
Unknown
P3: ์ดํ›„์— css variables๋กœ ๋นผ์„œ ๊ด€๋ฆฌํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,31 @@ +class VisitDateError { + #notInputDate(visitDate) { + if (visitDate.length === 0) { + throw new Error('[ERROR] ๋ฐฉ๋ฌธ ๋‚ ์งœ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.'); + } + } + + #dateNotNum(visitDate) { + if ( + Number.isNaN(Number(visitDate)) || + Number.isInteger(Number(visitDate)) === false || + visitDate.includes('.') + ) { + throw new Error('[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.'); + } + } + + #dateNotInRange(visitDate) { + if (Number(visitDate) < 1 || Number(visitDate) > 31) { + throw new Error('[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.'); + } + } + + valid(visitDate) { + this.#notInputDate(visitDate); + this.#dateNotNum(visitDate); + this.#dateNotInRange(visitDate); + } +} + +export default VisitDateError;
JavaScript
ํ•ด๋‹น ๋ถ€๋ถ„ ์ •๊ทœ ํ‘œํ˜„์‹์œผ๋กœ ํ•˜๋ฉด if๋ฌธ์„ ํ•˜๋‚˜๋กœ ์ค„์ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค !
@@ -0,0 +1,31 @@ +class VisitDateError { + #notInputDate(visitDate) { + if (visitDate.length === 0) { + throw new Error('[ERROR] ๋ฐฉ๋ฌธ ๋‚ ์งœ๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.'); + } + } + + #dateNotNum(visitDate) { + if ( + Number.isNaN(Number(visitDate)) || + Number.isInteger(Number(visitDate)) === false || + visitDate.includes('.') + ) { + throw new Error('[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.'); + } + } + + #dateNotInRange(visitDate) { + if (Number(visitDate) < 1 || Number(visitDate) > 31) { + throw new Error('[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.'); + } + } + + valid(visitDate) { + this.#notInputDate(visitDate); + this.#dateNotNum(visitDate); + this.#dateNotInRange(visitDate); + } +} + +export default VisitDateError;
JavaScript
ํ•ด๋‹น ๋ฌธ๊ตฌ๋„ constant์— ๋”ฐ๋กœ error.js๋ฅผ ์ƒ์„ฑํ•˜์…”์„œ ํ•˜์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค !
@@ -0,0 +1,61 @@ +import { MENU_NAMES, MENUS } from '../../constant/menu.js'; + +class OrderMenuError { + #orderNotInput(orderMenu) { + if ( + orderMenu.length === 1 && + orderMenu[0].menu.trim() === '' + ) { + throw new Error('[ERROR] ์ฃผ๋ฌธํ•˜์‹ค ๋ฉ”๋‰ด์™€ ๊ฐœ์ˆ˜๋ฅผ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.'); + } + } + + #orderWrongInput(orderMenu) { + if (!orderMenu + .every((order) => Number.isNaN(order.cnt) === false && + Number.isInteger(order.cnt) && + order.cnt > 0) + ) { + throw new Error('[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.'); + } + } + + #orderNotExistMenu(orderMenu) { + if (!orderMenu.every((order) => MENU_NAMES.includes(order.menu))) { + throw new Error('[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.'); + } + } + + #orderDuplication(orderMenu) { + const originOrderMenu = orderMenu.map((order) => order.menu); + const setOrderMenu = new Set(originOrderMenu); + if (originOrderMenu.length !== setOrderMenu.size) { + throw new Error('[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.'); + } + } + + #orderTypeOnlyDrink(orderMenu) { + const DRINK = Object.keys(MENUS.Drink); + if (orderMenu.every((order) => DRINK.includes(order.menu))) { + throw new Error('[ERROR] ์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธํ•˜์‹ค ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.'); + } + } + + #totalOrderCntOverRange(orderMenu) { + const totalMenuCnt = orderMenu.reduce((acc, order) => acc + order.cnt, 0); + if (totalMenuCnt > 20) { + throw new Error('[ERROR] ๋ฉ”๋‰ด๋Š” ์ตœ๋Œ€ 20๊ฐœ ๊นŒ์ง€ ์ฃผ๋ฌธ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.'); + } + } + + valid(orderMenu) { + this.#orderNotInput(orderMenu); + this.#orderWrongInput(orderMenu); + this.#orderNotExistMenu(orderMenu); + this.#orderTypeOnlyDrink(orderMenu); + this.#orderDuplication(orderMenu); + this.#totalOrderCntOverRange(orderMenu); + } +} + +export default OrderMenuError;
JavaScript
์ €๋„ ์‹ค์ˆ˜๋กœ ๋†“์นœ ๋ถ€๋ถ„์ด์ง€๋งŒ 1.0์„ ํฌํ•จํ•  ์ง€ ์•ˆํ• ์ง€ ๊ณ ๋ฏผํ•˜์…จ๋‹ค๊ณ  ํ•˜์…จ๋Š”๋ฐ ๊ทธ ๋ถ€๋ถ„ ์ดํ•ดํ•ฉ๋‹ˆ๋‹ค... ๋ฏธ์…˜์ด ๋๋‚˜๊ณ  ์ƒ๊ฐ๋‚œ๊ฑฐ์ง€๋งŒ 1.0๋„ ํฌํ•จ์„ ํ•œ๋‹ค๋ฉด 1.000000000000000... ๋„ 1๋กœ ๋˜๋Š”๊ฑฐ๋ผ 0์„ ๋ฌดํ•œ๋Œ€๋กœ ์ž…๋ ฅํ•˜๋ฉด ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š์„๊นŒ ํ•˜๋Š” ์šฐ๋ ค๊ฐ€ ๋˜๋Š”๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,28 @@ +const EVENT_NAMES = ['ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด ํ• ์ธ', 'ํ‰์ผ ํ• ์ธ', '์ฃผ๋ง ํ• ์ธ', 'ํŠน๋ณ„ ํ• ์ธ', '์ฆ์ • ์ด๋ฒคํŠธ']; + +const WEEKDAY_DISCOUNT_DATE = [ + 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 17, + 18, 19, 20, 21, 24, 25, 26, 27, 28, 31, +]; + +const WEEKEND_DISCOUNT_DATE = [ + 1, 2, 8, 9, 15, 16, 22, 23, 29, 30, +]; + +const SPECIAL_DISCOUNT_DATE = [ + 3, 10, 17, 24, 25, 31, +]; + +Object.freeze( + EVENT_NAMES, + WEEKDAY_DISCOUNT_DATE, + WEEKEND_DISCOUNT_DATE, + SPECIAL_DISCOUNT_DATE, +); + +export { + EVENT_NAMES, + WEEKDAY_DISCOUNT_DATE, + WEEKEND_DISCOUNT_DATE, + SPECIAL_DISCOUNT_DATE, +};
JavaScript
ํ•ด๋‹น ๋ถ€๋ถ„์€ `new Date()` ๋ฉ”์„œ๋“œ๋กœ ํ‘œํ˜„์ด ๊ฐ€๋Šฅํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ! `new Date()`๋ฅผ ์‚ฌ์šฉํ•˜์‹œ๋ฉด 0-์ผ์š”์ผ ~ 6-ํ† ์š”์ผ๋กœ 0~6๊นŒ์ง€์˜ number๋กœ ์ถœ๋ ฅ๋ฉ๋‹ˆ๋‹ค !
@@ -0,0 +1,66 @@ +import OUTPUT from '../../utils/constant/output.js'; +import OutputView from '../../utils/view_type/OutputView.js'; +import { EVENT_NAMES } from '../../utils/constant/event.js'; + +class PrintEventResult { + #totalOrderAmount(TOTAL_AMOUNT) { + OutputView.printOutput(`${OUTPUT.TOTAL_AMOUNT.BEFORE_DISCOUNT}`); + OutputView.printOutput(`${TOTAL_AMOUNT.toLocaleString()}์›`); + OutputView.printOutput(''); + } + + #giveawayMenu(GIVEAWAY_MENU) { + OutputView.printOutput(`${OUTPUT.MENU.GIVEAWAY_MENU}`); + OutputView.printOutput(`${GIVEAWAY_MENU}`); + OutputView.printOutput(''); + } + + #eventDetails(EVENT_DETAILS_RESULT) { + if (EVENT_DETAILS_RESULT === '์—†์Œ') { + OutputView.printOutput(`${OUTPUT.BENEFIT.LIST}`); + OutputView.printOutput(`${EVENT_DETAILS_RESULT}`); + OutputView.printOutput(''); + return; + } + this.#validEventDetails(EVENT_DETAILS_RESULT); + } + + #validEventDetails(EVENT_DETAILS_RESULT) { + OutputView.printOutput(OUTPUT.BENEFIT.LIST); + Object.keys(EVENT_DETAILS_RESULT).forEach((event, idx) => { + if (EVENT_DETAILS_RESULT[event] > 0) { + OutputView.printOutput(`${EVENT_NAMES[idx]}: -${EVENT_DETAILS_RESULT[event].toLocaleString()}์›`); + } + }); + OutputView.printOutput(''); + } + + #totalBenefitAmount(BENEFIT_AMOUNT_RESULT) { + OutputView.printOutput(`${OUTPUT.BENEFIT.TOTAL_BENEFIT_AMOUNT}`); + OutputView.printOutput(`-${BENEFIT_AMOUNT_RESULT.toLocaleString()}์›`); + OutputView.printOutput(''); + } + + #expectPaymentAmount(EXPEXT_PAYMENT_AMOUNT) { + OutputView.printOutput(`${OUTPUT.TOTAL_AMOUNT.AFTER_DISCOUNT}`); + OutputView.printOutput(`${EXPEXT_PAYMENT_AMOUNT.toLocaleString()}์›`); + OutputView.printOutput(''); + } + + #evnetBadge(BADGE) { + OutputView.printOutput(`${OUTPUT.EVENT.BADGE}`); + OutputView.printOutput(`${BADGE}`); + OutputView.printOutput(''); + } + + print(AMOUNT_RESULT, BENEFIT_RESULT) { + this.#totalOrderAmount(AMOUNT_RESULT.TOTAL_AMOUNT); + this.#giveawayMenu(BENEFIT_RESULT.GIVEAWAY_MENU); + this.#eventDetails(BENEFIT_RESULT.EVENT_DETAILS_RESULT); + this.#totalBenefitAmount(AMOUNT_RESULT.BENEFIT_AMOUNT_RESULT); + this.#expectPaymentAmount(AMOUNT_RESULT.EXPECT_PAYMENT_AMOUNT); + this.#evnetBadge(BENEFIT_RESULT.BADGE); + } +} + +export default PrintEventResult;
JavaScript
```jsx OutputView.printOutput(''); ``` ์ด ๋ฌธ๊ตฌ ๊ฐœํ–‰๋•Œ๋ฌธ์— ์ž…๋ ฅํ•˜์‹  ๊ฒƒ ๊ฐ™์€๋ฐ `์›`๋„ ๋ณ€์ˆ˜ํ™” ํ•˜์…”์„œ `์›\n`์„ ํ•˜์…”๋„ ๋˜๊ณ  ๊ทธ ๋‹ค์Œ ๋ฌธ๊ตฌ์— `OutputView.printOutput(${OUTPUT.EVENT.BADGE});`๊ฐ€ ๋‚˜์˜ค๋‹ˆ `BADGE: '\n<12์›” ์ด๋ฒคํŠธ ๋ฐฐ์ง€>'` ์ด๋Ÿฐ์‹์œผ๋กœ ์ถ”๊ฐ€ํ•˜๋ฉด ์ฝ”๋“œ๊ฐ€ ์กฐ๊ธˆ ๋” ๊น”๋”ํ•ด ์งˆ ๊ฒƒ ๊ฐ™์•„์š” !
@@ -0,0 +1,56 @@ +import { WEEKDAY_DISCOUNT_DATE, WEEKEND_DISCOUNT_DATE, SPECIAL_DISCOUNT_DATE } from '../../utils/constant/event.js'; +import { MENUS } from '../../utils/constant/menu.js'; + +class CalculateEventBenefit { + #event = { + christmas: 0, + weekday: 0, + weekend: 0, + special: 0, + giveaway: 0, + }; + + #christmasEvent(visitDate) { + if (visitDate > 0 && visitDate < 26) { + this.#event.christmas = 1000 + (visitDate - 1) * 100; + } + } + + #specialEvent(visitDate) { + if (SPECIAL_DISCOUNT_DATE.includes(visitDate)) { + this.#event.special = 1000; + } + } + + #weekdayEvent(order, DESSERT, visitDate) { + if ( + WEEKDAY_DISCOUNT_DATE.includes(visitDate) && + DESSERT.includes(order.menu) + ) { + this.#event.weekday += 2023 * order.cnt; + } + } + + #weekendEvent(order, MAIN, visitDate) { + if ( + WEEKEND_DISCOUNT_DATE.includes(visitDate) && + MAIN.includes(order.menu) + ) { + this.#event.weekend += 2023 * order.cnt; + } + } + + result(visitDate, orderMenu) { + const DESSERT = Object.keys(MENUS.Dessert); + const MAIN = Object.keys(MENUS.Main); + this.#christmasEvent(visitDate); + this.#specialEvent(visitDate); + orderMenu.forEach((order) => { + this.#weekdayEvent(order, DESSERT, visitDate); + this.#weekendEvent(order, MAIN, visitDate); + }); + return this.#event; + } +} + +export default CalculateEventBenefit;
JavaScript
```jsx #event = { christmas: 0, weekday: 0, weekend: 0, special: 0, giveaway: 0, }; ``` ์ด๋ ‡๊ฒŒ ์ž‘์„ฑํ•˜์‹  ๊ฒƒ ์ฒ˜๋Ÿผ ํ•ด๋‹น ์ƒ์ˆ˜ ๊ฐ’๋„ ๊ณ ์ •๊ฐ’์ด๋‹ˆ ๋ณ€์ˆ˜ํ™”ํ•ด์„œ ์˜๋ฏธ๋ฅผ ๋ถ€์—ฌํ•˜๋Š” ๊ฒƒ๋„ ๊ดœ์ฐฎ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค !
@@ -0,0 +1,41 @@ +import VisitDateError from '../../../utils/error/type/visit_date_error.js'; +import printError from '../../../utils/error/print_error.js'; +import INPUT_QUESTION from '../../../utils/constant/input_question.js'; +import OUTPUT from '../../../utils/constant/output.js'; +import InputView from '../../../utils/view_type/InputView.js'; +import OutputView from '../../../utils/view_type/OutputView.js'; + +class VisitDateManage { + #visitDate = null; + + get getVisitDate() { + return this.#visitDate; + } + + async firstGreeting() { + OutputView.printOutput(OUTPUT.FIRST_GREETING); + await this.#inputVisitDate(); + } + + async #inputVisitDate() { + while (true) { + this.#visitDate = await InputView.userInput(INPUT_QUESTION.VISIT_DATE); + if (this.#isValidDate()) { + break; + } + } + } + + #isValidDate() { + const ERROR = new VisitDateError(); + try { + ERROR.valid(this.#visitDate); + return true; + } catch (error) { + printError(error); + return false; + } + } +} + +export default VisitDateManage;
JavaScript
์š”๊ตฌ์‚ฌํ•ญ์— ์žˆ๋Š” ๋งŒ์•ฝ ํ˜•์‹์— ๋งž์ง€ ์•Š์œผ๋ฉด ์ƒˆ๋กœ์šด ๊ฐ’์„ ๋ฐ›์•„์˜ค๋Š” ๊ณผ์ •์ด ์—†๋Š”๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. (ํ˜น์‹œ ์ œ๊ฐ€ ๋ชป ์ฐพ๋Š” ๊ฒƒ์ด๋ผ๋ฉด ์ œ์‹œํ•ด์ฃผ์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค) ํ•ด๋‹น ๊ตฌ๋ฌธ์—์„œ๋Š” return false๋ฅผ ํ•˜๊ณ  ๊ทธ๋ƒฅ break์จ์„œ ๋น ์ ธ ๋‚˜์˜จ๊ฒƒ ๊ฐ™์€๋ฐ return false ๋Œ€์‹  return this.#inputVisitDate() ํ•˜๋ฉด ๋‹ค์‹œ ๊ฐ’์„ ๋ฐ›์•„ ์˜ฌ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,48 @@ +import CalculateOrderMenu from '../../model/calculate_order_menu.js'; +import PrintOrderMenu from '../../view/print_order_menu.js'; +import OrderMenuError from '../../../utils/error/type/order_menu_error.js'; +import printError from '../../../utils/error/print_error.js'; +import INPUT_QUESTION from '../../../utils/constant/input_question.js'; +import InputView from '../../../utils/view_type/InputView.js'; + +class OrderMenuManage { + #orderMenu = null; + + get getOrderMenu() { + return this.#orderMenu; + } + + async inputOrderMenu(visitDate) { + while (true) { + this.#orderMenu = await InputView.userInput(INPUT_QUESTION.ORDER_MENU); + this.#orderMenu = this.#calculateOrderMenu(); + if (this.#isValidOrderMenu()) { + break; + } + } + this.#print(visitDate); + } + + #calculateOrderMenu() { + const calculateOrderMenu = new CalculateOrderMenu(); + return calculateOrderMenu.calculate(this.#orderMenu); + } + + #isValidOrderMenu() { + const ERROR = new OrderMenuError(); + try { + ERROR.valid(this.#orderMenu); + return true; + } catch (error) { + printError(error); + return false; + } + } + + #print(visitDate) { + const printOrderMenu = new PrintOrderMenu(); + printOrderMenu.print(visitDate, this.#orderMenu); + } +} + +export default OrderMenuManage;
JavaScript
์ด ๋ถ€๋ถ„๋„ ๋‚ ์งœ ๋ฐ›์•„์˜ฌ๋•Œ์™€ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ์ž˜๋ชป๋œ ๊ฒฝ์šฐ ์ƒˆ ๊ฐ’์„ ๊ฐ€์ ธ์˜ค๋Š” ๊ณผ์ •์ด ์—†์–ด๋ณด์ž…๋‹ˆ๋‹ค
@@ -0,0 +1,67 @@ +import CalculateTotalOrderAmount from '../../model/calculate_total_order_amount.js'; +import CalculateEventDetails from '../../model/calculate_event_details.js'; +import PrintEventResult from '../../view/print_event_result.js'; + +class EventManage { + #visitDate; + #orderMenu; + + constructor(visitDate, orderMenu) { + this.#visitDate = Number(visitDate); + this.#orderMenu = orderMenu; + } + + totalOrderAmount() { + const TOTAL_AMOUNT = this.#calculateTotalOrderAmount(); + if (TOTAL_AMOUNT < 10000) { + return this.#printEventResult(TOTAL_AMOUNT, 0, null); + } + return this.#eventBenefit(TOTAL_AMOUNT); + } + + #eventBenefit(TOTAL_AMOUNT) { + const EVENT_DETAILS = this.#calculateEventDetails(); + EVENT_DETAILS.giveaway = TOTAL_AMOUNT >= 120000 ? 25000 : 0; + const BENEFIT_AMOUNT = Object.values(EVENT_DETAILS).reduce((acc, cur) => acc + cur, 0); + this.#printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS); + } + + #calculateTotalOrderAmount() { + const calculateTotalOrderAmount = new CalculateTotalOrderAmount(); + return calculateTotalOrderAmount.result(this.#orderMenu); + } + + #calculateEventDetails() { + const calculateEventDetails = new CalculateEventDetails(); + return calculateEventDetails.result(this.#visitDate, this.#orderMenu); + } + + #eventBadgeResult(BENEFIT_AMOUNT) { + if (BENEFIT_AMOUNT < 5000) { + return '์—†์Œ'; + } + if (BENEFIT_AMOUNT < 10000) { + return '๋ณ„'; + } + if (BENEFIT_AMOUNT < 20000) { + return 'ํŠธ๋ฆฌ'; + } + return '์‚ฐํƒ€'; + } + + #printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS) { + const GIVEAWAY_MENU = TOTAL_AMOUNT >= 120000 ? '์ƒดํŽ˜์ธ 1๊ฐœ' : '์—†์Œ'; + const EVENT_DETAILS_RESULT = EVENT_DETAILS === null ? '์—†์Œ' : EVENT_DETAILS; + const BENEFIT_AMOUNT_RESULT = BENEFIT_AMOUNT === 0 ? '์—†์Œ' : BENEFIT_AMOUNT; + const DISCOUNT_AMOUNT = TOTAL_AMOUNT >= 120000 ? BENEFIT_AMOUNT - 25000 : BENEFIT_AMOUNT; + const EXPECT_PAYMENT_AMOUNT = TOTAL_AMOUNT - DISCOUNT_AMOUNT; + const BADGE = this.#eventBadgeResult(BENEFIT_AMOUNT); + + const AMOUNT_RESULT = { TOTAL_AMOUNT, BENEFIT_AMOUNT_RESULT, EXPECT_PAYMENT_AMOUNT }; + const BENEFIT_RESULT = { GIVEAWAY_MENU, EVENT_DETAILS_RESULT, BADGE }; + const printEventResult = new PrintEventResult(); + printEventResult.print(AMOUNT_RESULT, BENEFIT_RESULT); + } +} + +export default EventManage;
JavaScript
์ด ๋ถ€๋ถ„์—์„œ 10000์ด ์–ด๋–ค ์˜๋ฏธ๋ฅผ ๊ฐ–๊ณ  ์žˆ๋Š”์ง€ ํŒ๋‹จํ•˜๊ธฐ ํž˜๋“ญ๋‹ˆ๋‹ค. ์ด ํ›„๋กœ๋„ ์ˆซ์ž๊ฐ€ ํ•˜๋“œ์ฝ”๋”ฉ ๋œ ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋Š”๋ฐ ์˜๋ฏธ๋ฅผ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋„๋ก ์ƒ์ˆ˜์ชฝ์œผ๋กœ ๋นผ์ฃผ๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,67 @@ +import CalculateTotalOrderAmount from '../../model/calculate_total_order_amount.js'; +import CalculateEventDetails from '../../model/calculate_event_details.js'; +import PrintEventResult from '../../view/print_event_result.js'; + +class EventManage { + #visitDate; + #orderMenu; + + constructor(visitDate, orderMenu) { + this.#visitDate = Number(visitDate); + this.#orderMenu = orderMenu; + } + + totalOrderAmount() { + const TOTAL_AMOUNT = this.#calculateTotalOrderAmount(); + if (TOTAL_AMOUNT < 10000) { + return this.#printEventResult(TOTAL_AMOUNT, 0, null); + } + return this.#eventBenefit(TOTAL_AMOUNT); + } + + #eventBenefit(TOTAL_AMOUNT) { + const EVENT_DETAILS = this.#calculateEventDetails(); + EVENT_DETAILS.giveaway = TOTAL_AMOUNT >= 120000 ? 25000 : 0; + const BENEFIT_AMOUNT = Object.values(EVENT_DETAILS).reduce((acc, cur) => acc + cur, 0); + this.#printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS); + } + + #calculateTotalOrderAmount() { + const calculateTotalOrderAmount = new CalculateTotalOrderAmount(); + return calculateTotalOrderAmount.result(this.#orderMenu); + } + + #calculateEventDetails() { + const calculateEventDetails = new CalculateEventDetails(); + return calculateEventDetails.result(this.#visitDate, this.#orderMenu); + } + + #eventBadgeResult(BENEFIT_AMOUNT) { + if (BENEFIT_AMOUNT < 5000) { + return '์—†์Œ'; + } + if (BENEFIT_AMOUNT < 10000) { + return '๋ณ„'; + } + if (BENEFIT_AMOUNT < 20000) { + return 'ํŠธ๋ฆฌ'; + } + return '์‚ฐํƒ€'; + } + + #printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS) { + const GIVEAWAY_MENU = TOTAL_AMOUNT >= 120000 ? '์ƒดํŽ˜์ธ 1๊ฐœ' : '์—†์Œ'; + const EVENT_DETAILS_RESULT = EVENT_DETAILS === null ? '์—†์Œ' : EVENT_DETAILS; + const BENEFIT_AMOUNT_RESULT = BENEFIT_AMOUNT === 0 ? '์—†์Œ' : BENEFIT_AMOUNT; + const DISCOUNT_AMOUNT = TOTAL_AMOUNT >= 120000 ? BENEFIT_AMOUNT - 25000 : BENEFIT_AMOUNT; + const EXPECT_PAYMENT_AMOUNT = TOTAL_AMOUNT - DISCOUNT_AMOUNT; + const BADGE = this.#eventBadgeResult(BENEFIT_AMOUNT); + + const AMOUNT_RESULT = { TOTAL_AMOUNT, BENEFIT_AMOUNT_RESULT, EXPECT_PAYMENT_AMOUNT }; + const BENEFIT_RESULT = { GIVEAWAY_MENU, EVENT_DETAILS_RESULT, BADGE }; + const printEventResult = new PrintEventResult(); + printEventResult.print(AMOUNT_RESULT, BENEFIT_RESULT); + } +} + +export default EventManage;
JavaScript
else๋ฅผ ์ง€์–‘ํ•˜๋ผ๊ณ  ํ•œ ๊ฒƒ์˜ ์˜๋ฏธ๊ฐ€ ๊ฑฐ์˜ ๋น„์Šทํ•œ ์˜๋ฏธ๋ฅผ ๊ฐ–๊ณ  ์žˆ๋Š” ์‚ผํ•ญ ์—ฐ์‚ฐ์ž๋ฅผ ์“ฐ๋ผ๊ณ  ํ•œ ๊ฒƒ์€ ์•„๋‹ˆ๋ผ๊ณ  ์ƒ๊ฐํ•˜๋Š”๋ฐ, ์‚ผํ•ญ ์—ฐ์‚ฐ์ž๋ฅผ ์“ด ์ด์œ ๊ฐ€ ๋”ฐ๋กœ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,67 @@ +import CalculateTotalOrderAmount from '../../model/calculate_total_order_amount.js'; +import CalculateEventDetails from '../../model/calculate_event_details.js'; +import PrintEventResult from '../../view/print_event_result.js'; + +class EventManage { + #visitDate; + #orderMenu; + + constructor(visitDate, orderMenu) { + this.#visitDate = Number(visitDate); + this.#orderMenu = orderMenu; + } + + totalOrderAmount() { + const TOTAL_AMOUNT = this.#calculateTotalOrderAmount(); + if (TOTAL_AMOUNT < 10000) { + return this.#printEventResult(TOTAL_AMOUNT, 0, null); + } + return this.#eventBenefit(TOTAL_AMOUNT); + } + + #eventBenefit(TOTAL_AMOUNT) { + const EVENT_DETAILS = this.#calculateEventDetails(); + EVENT_DETAILS.giveaway = TOTAL_AMOUNT >= 120000 ? 25000 : 0; + const BENEFIT_AMOUNT = Object.values(EVENT_DETAILS).reduce((acc, cur) => acc + cur, 0); + this.#printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS); + } + + #calculateTotalOrderAmount() { + const calculateTotalOrderAmount = new CalculateTotalOrderAmount(); + return calculateTotalOrderAmount.result(this.#orderMenu); + } + + #calculateEventDetails() { + const calculateEventDetails = new CalculateEventDetails(); + return calculateEventDetails.result(this.#visitDate, this.#orderMenu); + } + + #eventBadgeResult(BENEFIT_AMOUNT) { + if (BENEFIT_AMOUNT < 5000) { + return '์—†์Œ'; + } + if (BENEFIT_AMOUNT < 10000) { + return '๋ณ„'; + } + if (BENEFIT_AMOUNT < 20000) { + return 'ํŠธ๋ฆฌ'; + } + return '์‚ฐํƒ€'; + } + + #printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS) { + const GIVEAWAY_MENU = TOTAL_AMOUNT >= 120000 ? '์ƒดํŽ˜์ธ 1๊ฐœ' : '์—†์Œ'; + const EVENT_DETAILS_RESULT = EVENT_DETAILS === null ? '์—†์Œ' : EVENT_DETAILS; + const BENEFIT_AMOUNT_RESULT = BENEFIT_AMOUNT === 0 ? '์—†์Œ' : BENEFIT_AMOUNT; + const DISCOUNT_AMOUNT = TOTAL_AMOUNT >= 120000 ? BENEFIT_AMOUNT - 25000 : BENEFIT_AMOUNT; + const EXPECT_PAYMENT_AMOUNT = TOTAL_AMOUNT - DISCOUNT_AMOUNT; + const BADGE = this.#eventBadgeResult(BENEFIT_AMOUNT); + + const AMOUNT_RESULT = { TOTAL_AMOUNT, BENEFIT_AMOUNT_RESULT, EXPECT_PAYMENT_AMOUNT }; + const BENEFIT_RESULT = { GIVEAWAY_MENU, EVENT_DETAILS_RESULT, BADGE }; + const printEventResult = new PrintEventResult(); + printEventResult.print(AMOUNT_RESULT, BENEFIT_RESULT); + } +} + +export default EventManage;
JavaScript
์ž…๋ ฅ 2๊ฐœ์™€ ์ด๋ฒคํŠธ๋กœ ํด๋ž˜์Šค๋ฅผ ๋‚˜๋ˆ„์…จ๋˜๋ฐ ๋ฐฐ์ง€๋Š” ๋‚˜๋จธ์ง€ ์ชฝ(ํ• ์ธ์ด๋‚˜ ํ˜œํƒ ๋“ฑ ๊ณ„์‚ฐํŒŒํŠธ)์™€ ๊ธฐ๋Šฅ์ด ๋‹ฌ๋ผ๋ณด์ด๋Š”๋ฐ ๋‹ค๋ฅธ ํด๋ž˜์Šค๋กœ ๋นผ๋Š”๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”
@@ -0,0 +1,41 @@ +import VisitDateError from '../../../utils/error/type/visit_date_error.js'; +import printError from '../../../utils/error/print_error.js'; +import INPUT_QUESTION from '../../../utils/constant/input_question.js'; +import OUTPUT from '../../../utils/constant/output.js'; +import InputView from '../../../utils/view_type/InputView.js'; +import OutputView from '../../../utils/view_type/OutputView.js'; + +class VisitDateManage { + #visitDate = null; + + get getVisitDate() { + return this.#visitDate; + } + + async firstGreeting() { + OutputView.printOutput(OUTPUT.FIRST_GREETING); + await this.#inputVisitDate(); + } + + async #inputVisitDate() { + while (true) { + this.#visitDate = await InputView.userInput(INPUT_QUESTION.VISIT_DATE); + if (this.#isValidDate()) { + break; + } + } + } + + #isValidDate() { + const ERROR = new VisitDateError(); + try { + ERROR.valid(this.#visitDate); + return true; + } catch (error) { + printError(error); + return false; + } + } +} + +export default VisitDateManage;
JavaScript
3์ฃผ์ฐจ ๊ณตํ†ต ํ”ผ๋“œ๋ฐฑ์— "๊ฐ์ฒด๋กœ๋ถ€ํ„ฐ ๋ฐ์ดํ„ฐ๋ฅผ ๊บผ๋‚ด๋Š” ๊ฒƒ(get)์ด ์•„๋‹ˆ๋ผ, ๋ฉ”์‹œ์ง€๋ฅผ ๋˜์ง€๋„๋ก ๊ตฌ์กฐ๋ฅผ ๋ฐ”๊ฟ” ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ง€๋Š” ๊ฐœ์ฒด๊ฐ€ ์ผํ•˜๋„๋ก ํ•ด์•ผํ•œ๋‹ค"๊ณ  ํ–ˆ๋Š”๋ฐ, getter๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ํ•ด๊ฒฐํ•  ๋ฐฉ๋ฒ•์„ ๊ณ ๋ฏผํ•ด๋ณด๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,41 @@ +import VisitDateError from '../../../utils/error/type/visit_date_error.js'; +import printError from '../../../utils/error/print_error.js'; +import INPUT_QUESTION from '../../../utils/constant/input_question.js'; +import OUTPUT from '../../../utils/constant/output.js'; +import InputView from '../../../utils/view_type/InputView.js'; +import OutputView from '../../../utils/view_type/OutputView.js'; + +class VisitDateManage { + #visitDate = null; + + get getVisitDate() { + return this.#visitDate; + } + + async firstGreeting() { + OutputView.printOutput(OUTPUT.FIRST_GREETING); + await this.#inputVisitDate(); + } + + async #inputVisitDate() { + while (true) { + this.#visitDate = await InputView.userInput(INPUT_QUESTION.VISIT_DATE); + if (this.#isValidDate()) { + break; + } + } + } + + #isValidDate() { + const ERROR = new VisitDateError(); + try { + ERROR.valid(this.#visitDate); + return true; + } catch (error) { + printError(error); + return false; + } + } +} + +export default VisitDateManage;
JavaScript
๋ณ€์ˆ˜๋ช…์„ `ERROR`๋กœ ํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,41 @@ +import VisitDateError from '../../../utils/error/type/visit_date_error.js'; +import printError from '../../../utils/error/print_error.js'; +import INPUT_QUESTION from '../../../utils/constant/input_question.js'; +import OUTPUT from '../../../utils/constant/output.js'; +import InputView from '../../../utils/view_type/InputView.js'; +import OutputView from '../../../utils/view_type/OutputView.js'; + +class VisitDateManage { + #visitDate = null; + + get getVisitDate() { + return this.#visitDate; + } + + async firstGreeting() { + OutputView.printOutput(OUTPUT.FIRST_GREETING); + await this.#inputVisitDate(); + } + + async #inputVisitDate() { + while (true) { + this.#visitDate = await InputView.userInput(INPUT_QUESTION.VISIT_DATE); + if (this.#isValidDate()) { + break; + } + } + } + + #isValidDate() { + const ERROR = new VisitDateError(); + try { + ERROR.valid(this.#visitDate); + return true; + } catch (error) { + printError(error); + return false; + } + } +} + +export default VisitDateManage;
JavaScript
(์ง€๋‚˜๊ฐ€๋‹ค) ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜์—ฌ `return false`๋ฅผ ํ•˜๋ฉด `#inputVisitDate()` ๋ฉ”์„œ๋“œ์—์„œ ์กฐ๊ฑด์‹์— ๊ฑธ๋ฆฌ์ง€ ์•Š์„ ๊ฒƒ์ด๊ณ , ๋ฌดํ•œ ๋ฃจํ”„์— ์˜ํ•ด ์žฌ์ž…๋ ฅ์„ ๋ฐ›๊ฒŒ๋  ๊ฒƒ ๊ฐ™๋„ค์š”! ๋ฌดํ•œ ๋ฃจํ”„๊ฐ€ ์•„๋‹Œ ๋‹ค๋ฅธ ๋ฐฉ์‹์˜ ํ•ด๊ฒฐ๋ฐฉ๋ฒ•๋„ ๊ณ ๋ฏผํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,29 @@ +import VisitDateManage from '../child/visit_date_manage.js'; +import OrderMenuManage from '../child/order_menu_manage.js'; +import EventManage from '../child/event_manage.js'; + +class PlannerManage { + #VISIT_DATE = null; + #ORDER_MENU = null; + + async visitDate() { + const visitDateManage = new VisitDateManage(); + await visitDateManage.firstGreeting(); + this.#VISIT_DATE = visitDateManage.getVisitDate; + await this.#orderMenu(); + } + + async #orderMenu() { + const orderMenuManage = new OrderMenuManage(); + await orderMenuManage.inputOrderMenu(this.#VISIT_DATE); + this.#ORDER_MENU = orderMenuManage.getOrderMenu; + await this.#eventDetails(); + } + + async #eventDetails() { + const eventManage = new EventManage(this.#VISIT_DATE, this.#ORDER_MENU); + eventManage.totalOrderAmount(); + } +} + +export default PlannerManage;
JavaScript
3์ฃผ์ฐจ ๊ณตํ†ต ํ”ผ๋“œ๋ฐฑ์— ํ•„๋“œ์˜ ์ˆ˜๋ฅผ ์ตœ์†Œํ™”ํ•œ๋‹ค๋Š” ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์žˆ๋Š”๋ฐ, ํ•„๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ์ธ์ž๋กœ ์ „ํ•ด์ฃผ์–ด ์‚ฌ์šฉํ–ˆ๋‹ค๋ฉด ์–ด๋• ์„๊นŒ์š”?
@@ -0,0 +1,29 @@ +import VisitDateManage from '../child/visit_date_manage.js'; +import OrderMenuManage from '../child/order_menu_manage.js'; +import EventManage from '../child/event_manage.js'; + +class PlannerManage { + #VISIT_DATE = null; + #ORDER_MENU = null; + + async visitDate() { + const visitDateManage = new VisitDateManage(); + await visitDateManage.firstGreeting(); + this.#VISIT_DATE = visitDateManage.getVisitDate; + await this.#orderMenu(); + } + + async #orderMenu() { + const orderMenuManage = new OrderMenuManage(); + await orderMenuManage.inputOrderMenu(this.#VISIT_DATE); + this.#ORDER_MENU = orderMenuManage.getOrderMenu; + await this.#eventDetails(); + } + + async #eventDetails() { + const eventManage = new EventManage(this.#VISIT_DATE, this.#ORDER_MENU); + eventManage.totalOrderAmount(); + } +} + +export default PlannerManage;
JavaScript
๋„๋ฉ”์ธ ๋กœ์ง๊ณผ UI ๋กœ์ง์ด ๋ถ„๋ฆฌ๋˜์–ด ์žˆ์ง€์•Š์€ ์ฑ„ ๋กœ์ง์ด ์ „๊ฐœ๋˜๋‹ค ๋ณด๋‹ˆ ํฐ ํ๋ฆ„์„ ํŒŒ์•…ํ•˜๊ธฐ ์–ด๋ ค์›Œ๋ณด์ž…๋‹ˆ๋‹ค. PlannerManage์—์„œ๋Š” ํŽ˜์ด์ฆˆ๋ฅผ ๋‚˜๋ˆ„๊ณ  ๋„ค์ด๋ฐ์„ ํ†ตํ•ด ํฐ ํ”„๋กœ์„ธ์Šค๋ฅผ ํ‘œํ˜„ํ•˜๊ณ , ๋‚ด๋ถ€ ๋™์ž‘์€ ๋„๋ฉ”์ธ, UI ๋กœ์ง์„ ๋ถ„๋ฆฌํ•˜์—ฌ ๋‹ด๋‹นํ•˜๋„๋ก ํ•˜๋ฉด ๋”์šฑ ์˜๋ฏธ๊ฐ€ ๋“œ๋Ÿฌ๋‚˜๊ณ  ํ”„๋กœ์„ธ์Šค๋ฅผ ์ดํ•ดํ•˜๊ธฐ ์ˆ˜์›”ํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,67 @@ +import CalculateTotalOrderAmount from '../../model/calculate_total_order_amount.js'; +import CalculateEventDetails from '../../model/calculate_event_details.js'; +import PrintEventResult from '../../view/print_event_result.js'; + +class EventManage { + #visitDate; + #orderMenu; + + constructor(visitDate, orderMenu) { + this.#visitDate = Number(visitDate); + this.#orderMenu = orderMenu; + } + + totalOrderAmount() { + const TOTAL_AMOUNT = this.#calculateTotalOrderAmount(); + if (TOTAL_AMOUNT < 10000) { + return this.#printEventResult(TOTAL_AMOUNT, 0, null); + } + return this.#eventBenefit(TOTAL_AMOUNT); + } + + #eventBenefit(TOTAL_AMOUNT) { + const EVENT_DETAILS = this.#calculateEventDetails(); + EVENT_DETAILS.giveaway = TOTAL_AMOUNT >= 120000 ? 25000 : 0; + const BENEFIT_AMOUNT = Object.values(EVENT_DETAILS).reduce((acc, cur) => acc + cur, 0); + this.#printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS); + } + + #calculateTotalOrderAmount() { + const calculateTotalOrderAmount = new CalculateTotalOrderAmount(); + return calculateTotalOrderAmount.result(this.#orderMenu); + } + + #calculateEventDetails() { + const calculateEventDetails = new CalculateEventDetails(); + return calculateEventDetails.result(this.#visitDate, this.#orderMenu); + } + + #eventBadgeResult(BENEFIT_AMOUNT) { + if (BENEFIT_AMOUNT < 5000) { + return '์—†์Œ'; + } + if (BENEFIT_AMOUNT < 10000) { + return '๋ณ„'; + } + if (BENEFIT_AMOUNT < 20000) { + return 'ํŠธ๋ฆฌ'; + } + return '์‚ฐํƒ€'; + } + + #printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS) { + const GIVEAWAY_MENU = TOTAL_AMOUNT >= 120000 ? '์ƒดํŽ˜์ธ 1๊ฐœ' : '์—†์Œ'; + const EVENT_DETAILS_RESULT = EVENT_DETAILS === null ? '์—†์Œ' : EVENT_DETAILS; + const BENEFIT_AMOUNT_RESULT = BENEFIT_AMOUNT === 0 ? '์—†์Œ' : BENEFIT_AMOUNT; + const DISCOUNT_AMOUNT = TOTAL_AMOUNT >= 120000 ? BENEFIT_AMOUNT - 25000 : BENEFIT_AMOUNT; + const EXPECT_PAYMENT_AMOUNT = TOTAL_AMOUNT - DISCOUNT_AMOUNT; + const BADGE = this.#eventBadgeResult(BENEFIT_AMOUNT); + + const AMOUNT_RESULT = { TOTAL_AMOUNT, BENEFIT_AMOUNT_RESULT, EXPECT_PAYMENT_AMOUNT }; + const BENEFIT_RESULT = { GIVEAWAY_MENU, EVENT_DETAILS_RESULT, BADGE }; + const printEventResult = new PrintEventResult(); + printEventResult.print(AMOUNT_RESULT, BENEFIT_RESULT); + } +} + +export default EventManage;
JavaScript
10,000๋„ ์ƒ์ˆ˜๋กœ ๊ด€๋ฆฌํ•ด์ฃผ๋ฉด ๋”์šฑ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์˜๋ฏธ๋ฅผ ํŒŒ์•…ํ•˜๊ธฐ๋„ ์ˆ˜์›”ํ•˜๊ณ , ๋งŒ์•ฝ ์กฐ๊ฑด์ด ๋ณ€๊ฒฝ๋˜๋Š” ์ƒํ™ฉ์ด ์žˆ๋Š” ๊ฒฝ์šฐ ์ˆ˜์ •ํ•˜๊ธฐ ์ˆ˜์›”ํ•˜๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,67 @@ +import CalculateTotalOrderAmount from '../../model/calculate_total_order_amount.js'; +import CalculateEventDetails from '../../model/calculate_event_details.js'; +import PrintEventResult from '../../view/print_event_result.js'; + +class EventManage { + #visitDate; + #orderMenu; + + constructor(visitDate, orderMenu) { + this.#visitDate = Number(visitDate); + this.#orderMenu = orderMenu; + } + + totalOrderAmount() { + const TOTAL_AMOUNT = this.#calculateTotalOrderAmount(); + if (TOTAL_AMOUNT < 10000) { + return this.#printEventResult(TOTAL_AMOUNT, 0, null); + } + return this.#eventBenefit(TOTAL_AMOUNT); + } + + #eventBenefit(TOTAL_AMOUNT) { + const EVENT_DETAILS = this.#calculateEventDetails(); + EVENT_DETAILS.giveaway = TOTAL_AMOUNT >= 120000 ? 25000 : 0; + const BENEFIT_AMOUNT = Object.values(EVENT_DETAILS).reduce((acc, cur) => acc + cur, 0); + this.#printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS); + } + + #calculateTotalOrderAmount() { + const calculateTotalOrderAmount = new CalculateTotalOrderAmount(); + return calculateTotalOrderAmount.result(this.#orderMenu); + } + + #calculateEventDetails() { + const calculateEventDetails = new CalculateEventDetails(); + return calculateEventDetails.result(this.#visitDate, this.#orderMenu); + } + + #eventBadgeResult(BENEFIT_AMOUNT) { + if (BENEFIT_AMOUNT < 5000) { + return '์—†์Œ'; + } + if (BENEFIT_AMOUNT < 10000) { + return '๋ณ„'; + } + if (BENEFIT_AMOUNT < 20000) { + return 'ํŠธ๋ฆฌ'; + } + return '์‚ฐํƒ€'; + } + + #printEventResult(TOTAL_AMOUNT, BENEFIT_AMOUNT, EVENT_DETAILS) { + const GIVEAWAY_MENU = TOTAL_AMOUNT >= 120000 ? '์ƒดํŽ˜์ธ 1๊ฐœ' : '์—†์Œ'; + const EVENT_DETAILS_RESULT = EVENT_DETAILS === null ? '์—†์Œ' : EVENT_DETAILS; + const BENEFIT_AMOUNT_RESULT = BENEFIT_AMOUNT === 0 ? '์—†์Œ' : BENEFIT_AMOUNT; + const DISCOUNT_AMOUNT = TOTAL_AMOUNT >= 120000 ? BENEFIT_AMOUNT - 25000 : BENEFIT_AMOUNT; + const EXPECT_PAYMENT_AMOUNT = TOTAL_AMOUNT - DISCOUNT_AMOUNT; + const BADGE = this.#eventBadgeResult(BENEFIT_AMOUNT); + + const AMOUNT_RESULT = { TOTAL_AMOUNT, BENEFIT_AMOUNT_RESULT, EXPECT_PAYMENT_AMOUNT }; + const BENEFIT_RESULT = { GIVEAWAY_MENU, EVENT_DETAILS_RESULT, BADGE }; + const printEventResult = new PrintEventResult(); + printEventResult.print(AMOUNT_RESULT, BENEFIT_RESULT); + } +} + +export default EventManage;
JavaScript
์‚ฌ์†Œํ•˜์ง€๋งŒ, ์กฐ๊ฑด์„ ์—ญ์ˆœ์œผ๋กœ ์ ์—ˆ๋‹ค๋ฉด ๋” ์ดํ•ดํ•˜๊ธฐ ์ˆ˜์›”ํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. `20000 ์ด์ƒ: ์‚ฐํƒ€ / 10000 ์ด์ƒ: ํŠธ๋ฆฌ / 5000 ์ด์ƒ: ๋ณ„ / ๋‚˜๋จธ์ง€: ์—†์Œ`
@@ -0,0 +1,28 @@ +const EVENT_NAMES = ['ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด ํ• ์ธ', 'ํ‰์ผ ํ• ์ธ', '์ฃผ๋ง ํ• ์ธ', 'ํŠน๋ณ„ ํ• ์ธ', '์ฆ์ • ์ด๋ฒคํŠธ']; + +const WEEKDAY_DISCOUNT_DATE = [ + 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 17, + 18, 19, 20, 21, 24, 25, 26, 27, 28, 31, +]; + +const WEEKEND_DISCOUNT_DATE = [ + 1, 2, 8, 9, 15, 16, 22, 23, 29, 30, +]; + +const SPECIAL_DISCOUNT_DATE = [ + 3, 10, 17, 24, 25, 31, +]; + +Object.freeze( + EVENT_NAMES, + WEEKDAY_DISCOUNT_DATE, + WEEKEND_DISCOUNT_DATE, + SPECIAL_DISCOUNT_DATE, +); + +export { + EVENT_NAMES, + WEEKDAY_DISCOUNT_DATE, + WEEKEND_DISCOUNT_DATE, + SPECIAL_DISCOUNT_DATE, +};
JavaScript
์—ฌ๋Ÿฌ ๊ฐœ์˜ ์ธ์ž๋ฅผ ๋„˜๊ฒจ์ฃผ๊ณ  freeze ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด ํ”„๋ฆฌ์ง•๋˜์ง€ ์•Š์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,33 @@ +const MENU_NAMES = [ + '์–‘์†ก์ด์ˆ˜ํ”„', 'ํƒ€ํŒŒ์Šค', '์‹œ์ €์ƒ๋Ÿฌ๋“œ', + 'ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ', '๋ฐ”๋น„ํ๋ฆฝ', 'ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€', 'ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€', + '์ดˆ์ฝ”์ผ€์ดํฌ', '์•„์ด์Šคํฌ๋ฆผ', + '์ œ๋กœ์ฝœ๋ผ', '๋ ˆ๋“œ์™€์ธ', '์ƒดํŽ˜์ธ', +]; + +const MENUS = { + Epitizer: { + ์–‘์†ก์ด์ˆ˜ํ”„: 6000, + ํƒ€ํŒŒ์Šค: 5500, + ์‹œ์ €์ƒ๋Ÿฌ๋“œ: 8000, + }, + Main: { + ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ: 55000, + ๋ฐ”๋น„ํ๋ฆฝ: 54000, + ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€: 35000, + ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€: 25000, + }, + Dessert: { + ์ดˆ์ฝ”์ผ€์ดํฌ: 15000, + ์•„์ด์Šคํฌ๋ฆผ: 5000, + }, + Drink: { + ์ œ๋กœ์ฝœ๋ผ: 3000, + ๋ ˆ๋“œ์™€์ธ: 60000, + ์ƒดํŽ˜์ธ: 25000, + }, +}; + +Object.freeze(MENU_NAMES, MENUS); + +export { MENU_NAMES, MENUS };
JavaScript
์ค‘์ฒฉ๋œ ๊ฐ์ฒด์˜ ๊ฒฝ์šฐ, ์™ธ๋ถ€๋ฅผ ํ”„๋ฆฌ์ง• ํ•ด์ฃผ์–ด๋„ ๋‚ด๋ถ€๋Š” ํ”„๋ฆฌ์ง• ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. deep freeze ํ‚ค์›Œ๋“œ๋กœ ํ•™์Šตํ•ด๋ณด๋Š” ๊ฒƒ์„ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค.
@@ -0,0 +1,30 @@ +package store.contant; + +public enum Constant { + PRODUCTS_FILE_PATH("./src/main/resources/products.md"), + PROMOTIONS_FILE_PATH("./src/main/resources/promotions.md"), + + Y("Y"), + N("N"), + + YEAR("year"), + MONTH("month"), + DAY("day"), + + DEFAULT_DELIMITER("-"), + COMMA_DELIMITER(","), + + ITEM_DELIMITER("\\[(.*?)]"), + DATE_DELIMITER("(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})"); + + private final String detail; + + Constant(String detail) { + this.detail = detail; + } + + @Override + public String toString() { + return detail; + } +}
Java
์ €๋Š” ๋ชฐ๋ž๋˜ ์ •๊ทœํ‘œํ˜„์‹ ๋ฌธ๋ฒ•์ด๋ผ ์ฐพ์•„๋ณด๋‹ˆ๊นŒ named capturing group ์ด๋ผ๊ณ  ํ•˜๋Š”๊ตฐ์š”.. ์ƒˆ๋กœ์šด๊ฑฐ ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค!
@@ -0,0 +1,126 @@ +package store.view; + +import java.text.NumberFormat; +import store.domain.Product; +import store.domain.Products; +import store.dto.PurchaseDTO; +import store.dto.ReceiptDTO; + +public class OutputView { + private static final NumberFormat format = NumberFormat.getNumberInstance(); + + public static void printProducts(Products products) { + System.out.println(OutputMessage.OUTPUT_HELLO_CONVENIENCE_MESSAGE); + for (String product : products.getNames()) { + Product with = products.getItemWithPromotion(product); + Product without = products.getItemWithoutPromotion(product); + + printWith(with); + printWithout(without, with); + } + System.out.println(); + } + + private static void printWith(Product with) { + if (with != null) { + String price = getPrice(with); + String quantity = getQuantity(with); + String promotion = getPromotion(with); + System.out.println("- " + with.getName() + " " + price + " " + quantity + " " + promotion); + } + } + + private static void printWithout(Product without, Product with) { + if (without == null) { + String price = getPrice(with); + System.out.println("- " + with.getName() + " " + price + " ์žฌ๊ณ  ์—†์Œ"); + return; + } + String price = getPrice(without); + String quantity = getQuantity(without); + System.out.println("- " + without.getName() + " " + price + " " + quantity); + } + + public static void printReceipt(ReceiptDTO receiptDTO, boolean isMembership) { + printPurchaseItems(receiptDTO); + printFreeItems(receiptDTO); + printAccount(receiptDTO, isMembership); + } + + private static void printAccount(ReceiptDTO receiptDTO, boolean isMembership) { + System.out.println(OutputMessage.OUTPUT_RECEIPT_BOTTOM_MESSAGE); + printTotalPrice(receiptDTO); + printPromotionDiscount(receiptDTO); + printMembershipDiscount(receiptDTO, isMembership); + printPayment(receiptDTO, isMembership); + } + + private static void printPayment(ReceiptDTO receiptDTO, boolean isMembership) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_PAY_MESSAGE.format( + OutputMessage.TO_BE_PAID, + format.format(totalPayment(receiptDTO, isMembership)))); + System.out.println(); + } + + private static int totalPayment(ReceiptDTO receiptDTO, boolean isMembership) { + return receiptDTO.getTotalAmount() - receiptDTO.getFreeAmount() - receiptDTO.getMembershipAmount(isMembership); + } + + private static void printMembershipDiscount(ReceiptDTO receiptDTO, boolean isMembership) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_DISCOUNT_MESSAGE.format( + OutputMessage.MEMBERSHIP_DISCOUNT, + "-" + format.format(receiptDTO.getMembershipAmount(isMembership)))); + } + + private static void printPromotionDiscount(ReceiptDTO receiptDTO) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_DISCOUNT_MESSAGE.format( + OutputMessage.PROMOTION_DISCOUNT, + "-" + format.format(receiptDTO.getFreeAmount()))); + } + + private static void printTotalPrice(ReceiptDTO receiptDTO) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_PRODUCT_MESSAGE.format( + OutputMessage.TOTAL_PRICE, + receiptDTO.getTotalQuantity(), + format.format(receiptDTO.getTotalAmount()))); + } + + private static void printFreeItems(ReceiptDTO receiptDTO) { + System.out.println(OutputMessage.OUTPUT_RECEIPT_MIDDLE_MESSAGE); + for (PurchaseDTO purchaseDTO : receiptDTO.free()) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_FREE_MESSAGE.format( + purchaseDTO.name(), purchaseDTO.quantity())); + } + } + + private static void printPurchaseItems(ReceiptDTO receiptDTO) { + System.out.println(OutputMessage.OUTPUT_RECEIPT_TOP_MESSAGE); + for (PurchaseDTO purchaseDTO : receiptDTO.cart()) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_PRODUCT_MESSAGE.format( + purchaseDTO.name(), + purchaseDTO.quantity(), + format.format(purchaseDTO.getTotalAmount())) + ); + } + } + + private static String getPrice(Product product) { + return format.format(product.getPrice()) + OutputMessage.CURRENCY_UNIT; + } + + private static String getPromotion(Product product) { + String promotion = ""; + if (product.getPromotion() != null) { + promotion = product.getPromotion().getName(); + } + return promotion; + } + + private static String getQuantity(Product product) { + String quantity = format.format(product.getStock()) + OutputMessage.QUANTITY_UNIT; + if (product.getStock() == 0) { + quantity = OutputMessage.QUANTITY_EMPTY.toString(); + } + return quantity; + } +}
Java
์ด๋Ÿฐ ๋ถ€๋ถ„์—๋„ DTO๋ฅผ ๋ฐ›์•„์„œ ์ฒ˜๋ฆฌํ•˜๋Š”๊ฑด ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,14 @@ +package store.exception; + +public class CustomException extends IllegalArgumentException { + private final String errorMessage; + + public CustomException(String errorMessage) { + super(errorMessage); + this.errorMessage = errorMessage; + } + + public String getErrorMessage() { + return errorMessage; + } +}
Java
CustomException ํด๋ž˜์Šค๋ฅผ ๋”ฐ๋กœ ๋งŒ๋“œ์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค (์ด ๋ถ€๋ถ„์€ ์ž˜ ๋ชฐ๋ผ์„œ).
@@ -0,0 +1,57 @@ +package store.view; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import store.contant.Constant; +import store.dto.BuyDTO; +import store.exception.CustomException; +import store.exception.ErrorMessage; + +public class InputHandler { + private static final Pattern patternItem = Pattern.compile(Constant.ITEM_DELIMITER.toString()); + private static final Pattern patternDate = Pattern.compile(Constant.DATE_DELIMITER.toString()); + + public static List<BuyDTO> splitItems(String input) { + Matcher matcher = patternItem.matcher(input); + return matcher.results() + .map(find -> { + String content = find.group(1); + validate(content); + String[] item = split(content); + return new BuyDTO(item[0], toInt(item[1])); + }) + .toList(); + } + + private static void validate(String input) { + if (input.contains("[") || input.contains("]")) { + throw new CustomException(ErrorMessage.NOT_FIT_THE_FORM_MESSAGE.toString()); + } + } + + public static LocalDateTime parseDate(String input) { + Matcher matcher = patternDate.matcher(input); + if (matcher.matches()) { + int year = Integer.parseInt(matcher.group(Constant.YEAR.toString())); + int month = Integer.parseInt(matcher.group(Constant.MONTH.toString())); + int day = Integer.parseInt(matcher.group(Constant.DAY.toString())); + return LocalDate.of(year, month, day).atStartOfDay(); + } + throw new CustomException(ErrorMessage.FILE_IOEXCEPTION_MESSAGE.toString()); + } + + public static int toInt(String input) { + try { + return Integer.parseInt(input); + } catch (NumberFormatException e) { + throw new CustomException(ErrorMessage.NOT_FIT_THE_FORM_MESSAGE.toString()); + } + } + + private static String[] split(String input) { + return input.split(Constant.DEFAULT_DELIMITER.toString()); + } +}
Java
Matcher.results()๋กœ ๋‚˜๋ˆ„๋Š”๊ฑด ๊น”๋”ํ•˜์ง€๋งŒ ํ’ˆ๋ชฉ์„ ๋‚˜๋ˆ„๋Š” ๊ตฌ๋ถ„์ž๋กœ ์‰ผํ‘œ๊ฐ€ ์•„๋‹ˆ์–ด๋„ ์ž‘๋™ํ•ด์„œ, ์š”๊ตฌ์‚ฌํ•ญ์— ๋งž์ถ”๋ ค๋ฉด ์ˆ˜์ •ํ•ด์•ผ ํ•  ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,83 @@ +package store.view; + +import camp.nextstep.edu.missionutils.Console; +import java.util.List; +import store.contant.Constant; +import store.dto.BuyDTO; +import store.exception.CustomException; +import store.exception.ErrorMessage; + +public class InputView { + public static List<BuyDTO> readItem() { + while (true) { + try { + System.out.println(InputMessage.INPUT_PURCHASE_PRODUCT_MESSAGE); + return InputHandler.splitItems(Console.readLine()); + } catch (CustomException e) { + System.out.println(e.getErrorMessage()); + } + } + } + + public static String readMembership() { + while (true) { + try { + System.out.println(InputMessage.INPUT_MEMBERSHIP_MESSAGE); + String input = Console.readLine(); + validate(input); + return input; + } catch (CustomException e) { + System.out.println(e.getErrorMessage()); + } + } + } + + public static String readPromotion(String name, int quantity) { + while (true) { + try { + System.out.printf(InputMessage.INPUT_PROMOTION_MESSAGE.format(name, quantity)); + String input = Console.readLine(); + validate(input); + return input; + } catch (CustomException e) { + System.out.println(e.getErrorMessage()); + } + } + } + + public static String readGetOneFree(String name, int quantity) { + while (true) { + try { + System.out.printf(InputMessage.INPUT_GET_ONE_FREE_MESSAGE.format(name, quantity)); + String input = Console.readLine(); + validate(input); + return input; + } catch (CustomException e) { + System.out.println(e.getErrorMessage()); + } + } + } + + public static String readRePurchase() { + while (true) { + try { + System.out.println(InputMessage.INPUT_RE_PURCHASE_MESSAGE); + String input = Console.readLine(); + validate(input); + return input; + } catch (CustomException e) { + System.out.println(e.getErrorMessage()); + } + } + } + + private static void validate(String input) { + if (isCorrectInput(input)) { + throw new CustomException(ErrorMessage.INVALID_INPUT_MESSAGE.toString()); + } + } + + private static boolean isCorrectInput(String input) { + return !(input.equals(Constant.Y.toString()) || input.equals(Constant.N.toString())); + } +}
Java
validate() ๋„ค์ด๋ฐ์ด ์กฐ๊ธˆ ๋” ๊ตฌ์ฒด์ ์ด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,108 @@ +package store.controller; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.util.List; +import org.junit.platform.commons.logging.Logger; +import org.junit.platform.commons.logging.LoggerFactory; +import store.contant.Constant; +import store.domain.Product; +import store.domain.Products; +import store.domain.Promotion; +import store.domain.Promotions; +import store.dto.ProductsDTO; +import store.dto.ReceiptDTO; +import store.exception.CustomException; +import store.exception.ErrorMessage; +import store.view.InputHandler; +import store.view.InputView; +import store.view.OutputView; + +public class ConvenienceManager { + private final Logger logger = LoggerFactory.getLogger(getClass()); + + private static final String PRODUCTS_FILE_PATH = Constant.PRODUCTS_FILE_PATH.toString(); + private static final String PROMOTIONS_FILE_PATH = Constant.PROMOTIONS_FILE_PATH.toString(); + + private Promotions promotions; + private Products products; + + public ConvenienceManager() { + try { + this.promotions = new Promotions(initPromotions()); + this.products = new Products(initProducts(this.promotions)); + } catch (IOException e) { + logger.info(ErrorMessage.FILE_IOEXCEPTION_MESSAGE::toString); + } + } + + public void run() { + try { + do { + OutputView.printProducts(products); + List<ProductsDTO> sameItems = products.getSameProducts(); + ReceiptDTO receiptDTO = products.buyProduct(sameItems); + membership(receiptDTO); + } while (hasRePurchase()); + } catch (CustomException e) { + System.out.println(e.getErrorMessage()); + } + } + + private void membership(ReceiptDTO receiptDTO) { + if (hasApplyMembership()) { + OutputView.printReceipt(receiptDTO, true); + return; + } + OutputView.printReceipt(receiptDTO, false); + } + + private List<Promotion> initPromotions() throws IOException { + List<String> strings = Files.readAllLines(Paths.get(PROMOTIONS_FILE_PATH)); + return strings.stream() + .skip(1) + .map(this::makePromotion) + .toList(); + } + + private List<Product> initProducts(Promotions promotions) throws IOException { + List<String> strings = Files.readAllLines(Paths.get(PRODUCTS_FILE_PATH)); + return strings.stream() + .skip(1) + .map(line -> makeProduct(promotions, line)) + .toList(); + } + + private Promotion makePromotion(String line) { + final String[] promotion = split(line); + final String name = promotion[0]; + final int buy = Integer.parseInt(promotion[1]); + final int get = Integer.parseInt(promotion[2]); + final LocalDateTime startDate = InputHandler.parseDate(promotion[3]); + final LocalDateTime endDate = InputHandler.parseDate(promotion[4]); + return new Promotion(name, buy, get, startDate, endDate); + } + + private Product makeProduct(Promotions promotions, String line) { + final String[] product = split(line); + final String name = product[0]; + final int price = Integer.parseInt(product[1]); + final int stock = Integer.parseInt(product[2]); + final Promotion promotion = promotions.findPromotion(product[3]); + return new Product(name, price, stock, promotion); + } + + private static String[] split(String line) { + return line.split(Constant.COMMA_DELIMITER.toString()); + } + + private boolean hasRePurchase() { + return InputView.readRePurchase().equals(Constant.Y.toString()); + } + + private boolean hasApplyMembership() { + return InputView.readMembership().equals(Constant.Y.toString()); + } +}
Java
์ปจํŠธ๋กค๋Ÿฌ์˜ ์ƒ์„ฑ์ž๋ž‘ run ๋ถ€๋ถ„์ด ์ •๋ง ๊น”๋”ํ•˜๊ณ  ์ข‹์€ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,206 @@ +package store.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import store.contant.Constant; +import store.dto.BuyDTO; +import store.dto.ProductsDTO; +import store.dto.PurchaseDTO; +import store.dto.ReceiptDTO; +import store.dto.StockDTO; +import store.exception.CustomException; +import store.exception.ErrorMessage; +import store.view.InputView; + +public class Products { + private static final int ZERO = 0; + private static final int MINIMUM_STOCK = 1; + + private final List<Product> products; + + public Products(List<Product> products) { + this.products = products; + } + + public ReceiptDTO buyProduct(List<ProductsDTO> items) { + List<PurchaseDTO> purchaseItem = new ArrayList<>(); + List<PurchaseDTO> freeItem = new ArrayList<>(); + addReceipt(items, purchaseItem, freeItem); + return new ReceiptDTO(purchaseItem, freeItem); + } + + private void addReceipt(List<ProductsDTO> items, List<PurchaseDTO> purchaseItem, List<PurchaseDTO> freeItem) { + for (ProductsDTO productsDTO : items) { + buy( + productsDTO.name(), + productsDTO.quantity(), + productsDTO.with(), + productsDTO.without(), + purchaseItem, + freeItem + ); + } + } + + public List<ProductsDTO> getSameProducts() { + while (true) { + try { + List<BuyDTO> shopping = InputView.readItem(); + return changeProductsDTO(shopping); + } catch (CustomException e) { + System.out.println(e.getErrorMessage()); + } + } + } + + public List<Product> getProducts() { + return products; + } + + public List<ProductsDTO> changeProductsDTO(List<BuyDTO> shopping) { + return shopping.stream() + .map(find -> { + Product with = getItemWithPromotion(find.name()); + Product without = getItemWithoutPromotion(find.name()); + return new ProductsDTO(find.name(), find.quantity(), with, without); + }).toList(); + } + + public List<String> getNames() { + return products.stream() + .map(Product::getName) + .distinct() + .toList(); + } + + private void buy( + String name, int quantity, + Product with, Product without, List<PurchaseDTO> purchases, List<PurchaseDTO> frees + ) { + if (hasNullPromotion(purchases, with, without, quantity, name)) { + return; + } + quantity = fillQuantity(quantity, with, name); + StockDTO stockDTO = getPurchaseState(with, quantity, without, name); + addCart(name, purchases, frees, with, stockDTO); + } + + private void addCart( + String name, + List<PurchaseDTO> purchases, List<PurchaseDTO> frees, + Product withPromotion, StockDTO stockDTO + ) { + purchases.add(new PurchaseDTO( + name, withPromotion.getPrice(), stockDTO.getTotalStock(), stockDTO.freeStock(), + stockDTO.remainStock())); + frees.add(new PurchaseDTO( + name, withPromotion.getPrice(), stockDTO.freeStock(), 0, 0)); + } + + private boolean hasNullPromotion( + List<PurchaseDTO> purchaseItem, + Product withPromotion, Product withoutPromotion, + int quantity, String name + ) { + if (isInvalidPromotion(withPromotion)) { + withoutPromotion.notApplyClearanceStock(quantity); + purchaseItem.add(new PurchaseDTO(name, withoutPromotion.getPrice(), quantity, 0, quantity)); + return true; + } + return false; + } + + private StockDTO getPurchaseState(Product withPromotion, int quantity, Product withoutPromotion, String name) { + StockDTO stockDTO = withPromotion.getPurchaseState(quantity); + return clearance(withPromotion, withoutPromotion, name, quantity, stockDTO); + } + + private int fillQuantity(int quantity, Product withPromotion, String name) { + if (isNotApplyPromotion(quantity, withPromotion)) { + int addition = withPromotion.getPromotion().getApplyPromotion() - quantity; + if (hasGetOneFree(name, addition)) { + quantity += addition; + } + } + return quantity; + } + + private StockDTO clearance( + Product with, Product without, + String name, int quantity, StockDTO stockDTO + ) { + if (with.getStock() < quantity) { + if (hasApplyPromotion(name, stockDTO)) { + return nonApplyPromotionItem(with, without, stockDTO); + } + return onlyPromotionItem(with, without, stockDTO); + } + return applyPromotion(with, quantity, stockDTO); + } + + private StockDTO applyPromotion(Product with, int quantity, StockDTO stockDTO) { + with.applyClearanceStock(quantity); + return new StockDTO(0, stockDTO.applyStock(), stockDTO.freeStock()); + } + + private StockDTO onlyPromotionItem(Product with, Product without, StockDTO stockDTO) { + applyPromotionClearance(with, without, stockDTO.applyStock() + stockDTO.freeStock()); + return new StockDTO(0, stockDTO.applyStock(), stockDTO.freeStock()); + } + + private StockDTO nonApplyPromotionItem(Product with, Product without, StockDTO stockDTO) { + applyPromotionClearance(with, without, stockDTO.getTotalStock()); + return new StockDTO(stockDTO.remainStock(), stockDTO.applyStock(), stockDTO.freeStock()); + } + + private void applyPromotionClearance(Product withPromotion, Product withoutPromotion, int quantity) { + validateQuantity(quantity); + int remain = withPromotion.applyClearanceStock(quantity); + if (isRemainStock(remain)) { + withoutPromotion.notApplyClearanceStock(remain); + } + } + + private boolean isRemainStock(int remain) { + return remain > ZERO; + } + + public Product getItemWithPromotion(String name) { + return products.stream() + .filter(product -> product.isSameName(name) && product.isWithPromotion()) + .findFirst() + .orElse(null); + } + + public Product getItemWithoutPromotion(String name) { + return products.stream() + .filter(product -> product.isSameName(name) && !product.isWithPromotion()) + .findFirst() + .orElse(null); + } + + private void validateQuantity(int quantity) { + if (quantity < MINIMUM_STOCK) { + throw new CustomException(ErrorMessage.QUANTITY_OVER_MESSAGE.toString()); + } + } + + private boolean hasGetOneFree(String name, int addition) { + return InputView.readGetOneFree(name, addition).equals(Constant.Y.toString()); + } + + private boolean hasApplyPromotion(String name, StockDTO stockDTO) { + return InputView.readPromotion(name, stockDTO.remainStock()).equals(Constant.Y.toString()); + } + + private boolean isInvalidPromotion(Product withPromotion) { + return withPromotion == null || withPromotion.getPromotion().isLastDate(DateTimes.now()); + } + + private boolean isNotApplyPromotion(int quantity, Product withPromotion) { + return quantity < withPromotion.getPromotion().getApplyPromotion(); + } +}
Java
InputView๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๋ถ€๋ถ„์„ ์ปจํŠธ๋กค๋Ÿฌ๋ฅผ ๊ฑฐ์น˜๋Š”๊ฒŒ ์ข‹์ง€ ์•Š์„๊นŒ ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,35 @@ +package store.dto; + +import java.util.List; + +public record ReceiptDTO( + List<PurchaseDTO> cart, + List<PurchaseDTO> free +) { + public int getTotalQuantity() { + return cart.stream() + .mapToInt(PurchaseDTO::quantity) + .sum(); + } + + public int getTotalAmount() { + return cart.stream() + .mapToInt(PurchaseDTO::getTotalAmount) + .sum(); + } + + public int getFreeAmount() { + return free.stream() + .mapToInt(PurchaseDTO::getTotalAmount) + .sum(); + } + + public int getMembershipAmount(boolean isMembership) { + if (isMembership) { + return (int) (cart.stream() + .mapToInt(PurchaseDTO::getNotApplyAmount) + .sum() * 0.3); + } + return 0; + } +}
Java
0.3์€ ์ค‘์š”ํ•œ ์ˆซ์ž๋ผ ์ƒ์ˆ˜๋กœ ๋ฐ”๊พธ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,126 @@ +package store.view; + +import java.text.NumberFormat; +import store.domain.Product; +import store.domain.Products; +import store.dto.PurchaseDTO; +import store.dto.ReceiptDTO; + +public class OutputView { + private static final NumberFormat format = NumberFormat.getNumberInstance(); + + public static void printProducts(Products products) { + System.out.println(OutputMessage.OUTPUT_HELLO_CONVENIENCE_MESSAGE); + for (String product : products.getNames()) { + Product with = products.getItemWithPromotion(product); + Product without = products.getItemWithoutPromotion(product); + + printWith(with); + printWithout(without, with); + } + System.out.println(); + } + + private static void printWith(Product with) { + if (with != null) { + String price = getPrice(with); + String quantity = getQuantity(with); + String promotion = getPromotion(with); + System.out.println("- " + with.getName() + " " + price + " " + quantity + " " + promotion); + } + } + + private static void printWithout(Product without, Product with) { + if (without == null) { + String price = getPrice(with); + System.out.println("- " + with.getName() + " " + price + " ์žฌ๊ณ  ์—†์Œ"); + return; + } + String price = getPrice(without); + String quantity = getQuantity(without); + System.out.println("- " + without.getName() + " " + price + " " + quantity); + } + + public static void printReceipt(ReceiptDTO receiptDTO, boolean isMembership) { + printPurchaseItems(receiptDTO); + printFreeItems(receiptDTO); + printAccount(receiptDTO, isMembership); + } + + private static void printAccount(ReceiptDTO receiptDTO, boolean isMembership) { + System.out.println(OutputMessage.OUTPUT_RECEIPT_BOTTOM_MESSAGE); + printTotalPrice(receiptDTO); + printPromotionDiscount(receiptDTO); + printMembershipDiscount(receiptDTO, isMembership); + printPayment(receiptDTO, isMembership); + } + + private static void printPayment(ReceiptDTO receiptDTO, boolean isMembership) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_PAY_MESSAGE.format( + OutputMessage.TO_BE_PAID, + format.format(totalPayment(receiptDTO, isMembership)))); + System.out.println(); + } + + private static int totalPayment(ReceiptDTO receiptDTO, boolean isMembership) { + return receiptDTO.getTotalAmount() - receiptDTO.getFreeAmount() - receiptDTO.getMembershipAmount(isMembership); + } + + private static void printMembershipDiscount(ReceiptDTO receiptDTO, boolean isMembership) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_DISCOUNT_MESSAGE.format( + OutputMessage.MEMBERSHIP_DISCOUNT, + "-" + format.format(receiptDTO.getMembershipAmount(isMembership)))); + } + + private static void printPromotionDiscount(ReceiptDTO receiptDTO) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_DISCOUNT_MESSAGE.format( + OutputMessage.PROMOTION_DISCOUNT, + "-" + format.format(receiptDTO.getFreeAmount()))); + } + + private static void printTotalPrice(ReceiptDTO receiptDTO) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_PRODUCT_MESSAGE.format( + OutputMessage.TOTAL_PRICE, + receiptDTO.getTotalQuantity(), + format.format(receiptDTO.getTotalAmount()))); + } + + private static void printFreeItems(ReceiptDTO receiptDTO) { + System.out.println(OutputMessage.OUTPUT_RECEIPT_MIDDLE_MESSAGE); + for (PurchaseDTO purchaseDTO : receiptDTO.free()) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_FREE_MESSAGE.format( + purchaseDTO.name(), purchaseDTO.quantity())); + } + } + + private static void printPurchaseItems(ReceiptDTO receiptDTO) { + System.out.println(OutputMessage.OUTPUT_RECEIPT_TOP_MESSAGE); + for (PurchaseDTO purchaseDTO : receiptDTO.cart()) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_PRODUCT_MESSAGE.format( + purchaseDTO.name(), + purchaseDTO.quantity(), + format.format(purchaseDTO.getTotalAmount())) + ); + } + } + + private static String getPrice(Product product) { + return format.format(product.getPrice()) + OutputMessage.CURRENCY_UNIT; + } + + private static String getPromotion(Product product) { + String promotion = ""; + if (product.getPromotion() != null) { + promotion = product.getPromotion().getName(); + } + return promotion; + } + + private static String getQuantity(Product product) { + String quantity = format.format(product.getStock()) + OutputMessage.QUANTITY_UNIT; + if (product.getStock() == 0) { + quantity = OutputMessage.QUANTITY_EMPTY.toString(); + } + return quantity; + } +}
Java
๊ฐœ์ˆ˜๊ฐ€ 0์ด์–ด๋„ ์ถœ๋ ฅ์ด ๋˜๋˜๋ฐ, 0์ผ๋•Œ ์ถœ๋ ฅ์—์„œ ์ œ์™ธ์‹œํ‚ค๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,108 @@ +package store.controller; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.util.List; +import org.junit.platform.commons.logging.Logger; +import org.junit.platform.commons.logging.LoggerFactory; +import store.contant.Constant; +import store.domain.Product; +import store.domain.Products; +import store.domain.Promotion; +import store.domain.Promotions; +import store.dto.ProductsDTO; +import store.dto.ReceiptDTO; +import store.exception.CustomException; +import store.exception.ErrorMessage; +import store.view.InputHandler; +import store.view.InputView; +import store.view.OutputView; + +public class ConvenienceManager { + private final Logger logger = LoggerFactory.getLogger(getClass()); + + private static final String PRODUCTS_FILE_PATH = Constant.PRODUCTS_FILE_PATH.toString(); + private static final String PROMOTIONS_FILE_PATH = Constant.PROMOTIONS_FILE_PATH.toString(); + + private Promotions promotions; + private Products products; + + public ConvenienceManager() { + try { + this.promotions = new Promotions(initPromotions()); + this.products = new Products(initProducts(this.promotions)); + } catch (IOException e) { + logger.info(ErrorMessage.FILE_IOEXCEPTION_MESSAGE::toString); + } + } + + public void run() { + try { + do { + OutputView.printProducts(products); + List<ProductsDTO> sameItems = products.getSameProducts(); + ReceiptDTO receiptDTO = products.buyProduct(sameItems); + membership(receiptDTO); + } while (hasRePurchase()); + } catch (CustomException e) { + System.out.println(e.getErrorMessage()); + } + } + + private void membership(ReceiptDTO receiptDTO) { + if (hasApplyMembership()) { + OutputView.printReceipt(receiptDTO, true); + return; + } + OutputView.printReceipt(receiptDTO, false); + } + + private List<Promotion> initPromotions() throws IOException { + List<String> strings = Files.readAllLines(Paths.get(PROMOTIONS_FILE_PATH)); + return strings.stream() + .skip(1) + .map(this::makePromotion) + .toList(); + } + + private List<Product> initProducts(Promotions promotions) throws IOException { + List<String> strings = Files.readAllLines(Paths.get(PRODUCTS_FILE_PATH)); + return strings.stream() + .skip(1) + .map(line -> makeProduct(promotions, line)) + .toList(); + } + + private Promotion makePromotion(String line) { + final String[] promotion = split(line); + final String name = promotion[0]; + final int buy = Integer.parseInt(promotion[1]); + final int get = Integer.parseInt(promotion[2]); + final LocalDateTime startDate = InputHandler.parseDate(promotion[3]); + final LocalDateTime endDate = InputHandler.parseDate(promotion[4]); + return new Promotion(name, buy, get, startDate, endDate); + } + + private Product makeProduct(Promotions promotions, String line) { + final String[] product = split(line); + final String name = product[0]; + final int price = Integer.parseInt(product[1]); + final int stock = Integer.parseInt(product[2]); + final Promotion promotion = promotions.findPromotion(product[3]); + return new Product(name, price, stock, promotion); + } + + private static String[] split(String line) { + return line.split(Constant.COMMA_DELIMITER.toString()); + } + + private boolean hasRePurchase() { + return InputView.readRePurchase().equals(Constant.Y.toString()); + } + + private boolean hasApplyMembership() { + return InputView.readMembership().equals(Constant.Y.toString()); + } +}
Java
์ด๋ ‡๊ฒŒ ๋˜๋ฉด ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„์— ์ข…๋ฃŒ๋‚ ์งœ๊ฐ€ ์‚ฌ์‹ค ํฌํ•จ์ด ์•ˆ๋˜์–ด์„œ (์ข…๋ฃŒ๋‚ ์งœ๋กœ ๋„˜์–ด๊ฐ€๋Š” 00์‹œ 00๋ถ„ 00์ดˆ ๊นŒ์ง€๋งŒ ํฌํ•จ๋˜๋”๋ผ๊ตฌ์š”), endDate.plusDays(1) ์˜ .atStartOfDay() ๋ฅผ ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ๋” ๋งž๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,31 @@ +package dto; + +import domain.car.Car; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static util.Splitter.BLANK; + +public class CarDto { + private String name; + private List<String> whiteSpaceList; + + public CarDto(Car car) { + assert car != null; + this.name = car.getName(); + this.whiteSpaceList = IntStream.range(0, car.getPosition()) + .mapToObj(num -> BLANK) + .collect(Collectors.toList()); + } + + public String getName() { + return name; + } + + public List<String> getWhiteSpaceList() { + return whiteSpaceList; + } + +}
Java
carDto์˜ position์€ ์ƒ์„ฑ์ž์—์„œ whiteSpaceList ๋งŒ๋“œ๋Š” ๊ฑธ ์ œ์™ธํ•˜๊ณค ์“ฐ๋Š”๋ฐ๊ฐ€ ์—†๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ, carDto์—์„œ ๋นผ๋Š” ๊ฑด ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -1,79 +1,83 @@ <!DOCTYPE html> <html> + <head> -<meta charset="UTF-8"> -<title>๋ ˆ์ด์Šค!</title> + <meta charset="UTF-8"> + <title>๋ ˆ์ด์Šค!</title> -<!-- Latest compiled and minified CSS --> -<link rel="stylesheet" - href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" - integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" - crossorigin="anonymous"> + <!-- Latest compiled and minified CSS --> + <link rel="stylesheet" + href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" + integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" + crossorigin="anonymous"> -<!-- Optional theme --> -<link rel="stylesheet" - href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" - integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" - crossorigin="anonymous"> + <!-- Optional theme --> + <link rel="stylesheet" + href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" + integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" + crossorigin="anonymous"> -<!-- Latest compiled and minified JavaScript --> -<script - src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" - integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" - crossorigin="anonymous"></script> -<style> -body { - padding-top: 40px; - padding-bottom: 40px; - background-color: #eee; -} + <!-- Latest compiled and minified JavaScript --> + <script + src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" + integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" + crossorigin="anonymous"></script> + <style> + body { + padding-top: 40px; + padding-bottom: 40px; + background-color: #eee; + } -.form-lotto { - max-width: 1000px; - padding: 15px; - margin: 0 auto; -} + .form-lotto { + max-width: 1000px; + padding: 15px; + margin: 0 auto; + } -.form-lotto .form-control { - position: relative; - height: auto; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - padding: 10px; - font-size: 16px; -} + .form-lotto .form-control { + position: relative; + height: auto; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + padding: 10px; + font-size: 16px; + } -.submit-button { - margin-top: 10px; -} -</style> + .submit-button { + margin-top: 10px; + } + </style> </head> <body> - <div class="container"> +<div class="container"> <div class="row"> - <div class="col-md-12"> + <div class="col-md-12"> - <h2 class="text-center">๋ฐ•์ง„๊ฐ ๋„˜์น˜๋Š” ์ž๋™์ฐจ ๋ ˆ์ด์‹ฑ ๊ฒŒ์ž„ with Pobi</h2> - <div class="form-show-div" class="form-group"> - <h3>๊ฒฐ๊ณผ์ž…๋‹ˆ๋‹ค</h3> - (์ด๋ฆ„๋งˆ๋‹ค ๋„์–ด์“ฐ๊ธฐ๋กœ ๊ตฌ๋ถ„ํ•ด ์ฃผ์„ธ์š”.) - <div id="standings">๋ฐ•์žฌ์„ฑ : &nbsp;&nbsp;&nbsp;&#128652;</div> - <div id="standings">์œค์ง€์ˆ˜ : &nbsp;&nbsp;&#128652;</div> - <div id="standings">์ •ํ˜ธ์˜ : &nbsp;&nbsp;&nbsp;&#128652;</div> - <div id="standings">๊น€์ • : &nbsp;&#128652;</div> - <br /> - <div>๋ฐ•์žฌ์„ฑ, ์ •ํ˜ธ์˜์ด ์šฐ์Šนํ–ˆ์Šต๋‹ˆ๋‹ค.</div> + <h2 class="text-center">๋ฐ•์ง„๊ฐ ๋„˜์น˜๋Š” ์ž๋™์ฐจ ๋ ˆ์ด์‹ฑ ๊ฒŒ์ž„ with Pobi</h2> + <div class="form-show-div" class="form-group"> + <h3>๊ฒฐ๊ณผ์ž…๋‹ˆ๋‹ค</h3> + (์ด๋ฆ„๋งˆ๋‹ค ๋„์–ด์“ฐ๊ธฐ๋กœ ๊ตฌ๋ถ„ํ•ด ์ฃผ์„ธ์š”.) + {{#cars}} + <div id="standings">{{name}} : {{#whiteSpaceList}}&nbsp;&nbsp;{{/whiteSpaceList}}&#128652;</div> + {{/cars}} + <br/> + <div>{{#winners}} + {{#if @last}} + {{this}} + {{else}} + {{this}}, + {{/if}} + {{/winners}}์ด ์šฐ์Šนํ–ˆ์Šต๋‹ˆ๋‹ค.</div> + </div> </div> - </div> </div> - </div> +</div> </body> -<script src="/js/race.js"> -</script> </html> \ No newline at end of file
Unknown
์ด ๋ถ€๋ถ„์„ ์–ด๋–ป๊ฒŒ ํ• ๊นŒ ๊ณ ๋ฏผํ•˜๋‹ค๊ฐ€..๊ทธ๋ƒฅ ๋ฌธ๊ตฌ๋ฅผ ์ˆ˜์ •ํ–ˆ๋Š”๋ฐ, ์ด ๋ถ„๊ธฐ๋ฌธ ๋„ฃ๋Š” ๊ฒƒ๋„ ์ƒ๊ฐํ•ด๋ด์•ผ๊ฒ ๋„ค์š”๐Ÿ‘
@@ -0,0 +1,79 @@ +package view; + +import domain.car.Car; +import domain.game.RacingGame; +import domain.game.Track; +import domain.random.RandomGenerator; +import domain.strategy.RandomMovingStrategy; +import dto.CarDto; +import dto.RacingGameRequestDto; +import spark.Route; +import util.Splitter; + +import java.util.HashMap; +import java.util.List; +import java.util.Random; + +import static java.util.stream.Collectors.toList; +import static util.RenderUtil.render; +import static util.Splitter.COMMA; + +public class WebRacingHandler { + public Route handleGetName() { + return (req, res) -> { + HashMap<String, Object> model = new HashMap<>(); + String names = req.queryParams("names"); + + List<String> splitNames = Splitter.splitBlank(names); + model.put("names", splitNames); + model.put("nameStrings", String.join(COMMA, splitNames)); + return render(model, "/game.html"); + }; + } + + public Route handleResult() { + return (req, res) -> { + final HashMap<String, Object> model = new HashMap<>(); + final RacingGameRequestDto racingGameRequestDto = new RacingGameRequestDto(Integer.parseInt(req.queryParams("turn")), req.queryParams("names")); + + final RacingGame racingGame = generateRacingGame(racingGameRequestDto); + + finishGame(racingGame); + Track track = racingGame.getTrack(); + + List<CarDto> carDtos = mapToCarDto(track); + List<String> nameOfWinners = mapToName(racingGame); + + + model.put("cars", carDtos); + model.put("winners", nameOfWinners); + return render(model, "/result.html"); + }; + } + + private void finishGame(RacingGame racingGame) { + while (!racingGame.isDone()) { + racingGame.proceedOneTurn(); + } + } + + private RacingGame generateRacingGame(RacingGameRequestDto racingGameRequestDto) { + final Random generate = RandomGenerator.generate(); + final RandomMovingStrategy movingStrategy = new RandomMovingStrategy(generate); + return RacingGame.newInstance(racingGameRequestDto.getNames(), racingGameRequestDto.getTurn(), movingStrategy); + } + + private List<String> mapToName(RacingGame racingGame) { + return racingGame.getWinner() + .stream() + .map(Car::getName) + .collect(toList()); + } + + private List<CarDto> mapToCarDto(Track track) { + return track.getCars() + .stream() + .map(CarDto::new) + .collect(toList()); + } +}
Java
๊ฒŒ์ž„์‹œ์ž‘์— ํ•„์š”ํ•œ input๊ณผ ๊ฒฐ๊ณผ๊ฐ’์ธ result๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ๋กœ์ง์„ ๋ฉ”์†Œ๋“œ๋กœ ๋ถ„๋ฆฌํ•˜๋ฉด ๋” ๊น”๋”ํ•ด ์งˆ๊ฑฐ ๊ฐ™์•„์š”
@@ -0,0 +1,79 @@ +package view; + +import domain.car.Car; +import domain.game.RacingGame; +import domain.game.Track; +import domain.random.RandomGenerator; +import domain.strategy.RandomMovingStrategy; +import dto.CarDto; +import dto.RacingGameRequestDto; +import spark.Route; +import util.Splitter; + +import java.util.HashMap; +import java.util.List; +import java.util.Random; + +import static java.util.stream.Collectors.toList; +import static util.RenderUtil.render; +import static util.Splitter.COMMA; + +public class WebRacingHandler { + public Route handleGetName() { + return (req, res) -> { + HashMap<String, Object> model = new HashMap<>(); + String names = req.queryParams("names"); + + List<String> splitNames = Splitter.splitBlank(names); + model.put("names", splitNames); + model.put("nameStrings", String.join(COMMA, splitNames)); + return render(model, "/game.html"); + }; + } + + public Route handleResult() { + return (req, res) -> { + final HashMap<String, Object> model = new HashMap<>(); + final RacingGameRequestDto racingGameRequestDto = new RacingGameRequestDto(Integer.parseInt(req.queryParams("turn")), req.queryParams("names")); + + final RacingGame racingGame = generateRacingGame(racingGameRequestDto); + + finishGame(racingGame); + Track track = racingGame.getTrack(); + + List<CarDto> carDtos = mapToCarDto(track); + List<String> nameOfWinners = mapToName(racingGame); + + + model.put("cars", carDtos); + model.put("winners", nameOfWinners); + return render(model, "/result.html"); + }; + } + + private void finishGame(RacingGame racingGame) { + while (!racingGame.isDone()) { + racingGame.proceedOneTurn(); + } + } + + private RacingGame generateRacingGame(RacingGameRequestDto racingGameRequestDto) { + final Random generate = RandomGenerator.generate(); + final RandomMovingStrategy movingStrategy = new RandomMovingStrategy(generate); + return RacingGame.newInstance(racingGameRequestDto.getNames(), racingGameRequestDto.getTurn(), movingStrategy); + } + + private List<String> mapToName(RacingGame racingGame) { + return racingGame.getWinner() + .stream() + .map(Car::getName) + .collect(toList()); + } + + private List<CarDto> mapToCarDto(Track track) { + return track.getCars() + .stream() + .map(CarDto::new) + .collect(toList()); + } +}
Java
๋ฉ”์†Œ๋“œ๋ฅผ ๋ถ„ํ•ดํ•ด๋„ ์ข‹์„๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ๐Ÿ‘ !
@@ -0,0 +1,25 @@ +import view.WebRacingHandler; + +import java.util.HashMap; + +import static spark.Spark.*; +import static util.RenderUtil.render; + +public class WebMain { + public static final int PORT = 8080; + private static WebRacingHandler webRacingHandler = new WebRacingHandler(); + + public static void main(String[] args) { + port(PORT); + + get("/", (req, res) -> render(new HashMap<>(), "/index.html")); + + post("/name", webRacingHandler.handleGetName()); + + post("/result", webRacingHandler.handleResult()); + } + + + + +} \ No newline at end of file
Java
ํ—›, ๋ณ„๊ฑด์•„๋‹Œ๋ฐ `post`๊ฐ€ ์š”๊ตฌ์‚ฌํ•ญ์ด์—ˆ์Šต๋‹ˆ๋‹ค ๐Ÿ˜„
@@ -0,0 +1,79 @@ +package view; + +import domain.car.Car; +import domain.game.RacingGame; +import domain.game.Track; +import domain.random.RandomGenerator; +import domain.strategy.RandomMovingStrategy; +import dto.CarDto; +import dto.RacingGameRequestDto; +import spark.Route; +import util.Splitter; + +import java.util.HashMap; +import java.util.List; +import java.util.Random; + +import static java.util.stream.Collectors.toList; +import static util.RenderUtil.render; +import static util.Splitter.COMMA; + +public class WebRacingHandler { + public Route handleGetName() { + return (req, res) -> { + HashMap<String, Object> model = new HashMap<>(); + String names = req.queryParams("names"); + + List<String> splitNames = Splitter.splitBlank(names); + model.put("names", splitNames); + model.put("nameStrings", String.join(COMMA, splitNames)); + return render(model, "/game.html"); + }; + } + + public Route handleResult() { + return (req, res) -> { + final HashMap<String, Object> model = new HashMap<>(); + final RacingGameRequestDto racingGameRequestDto = new RacingGameRequestDto(Integer.parseInt(req.queryParams("turn")), req.queryParams("names")); + + final RacingGame racingGame = generateRacingGame(racingGameRequestDto); + + finishGame(racingGame); + Track track = racingGame.getTrack(); + + List<CarDto> carDtos = mapToCarDto(track); + List<String> nameOfWinners = mapToName(racingGame); + + + model.put("cars", carDtos); + model.put("winners", nameOfWinners); + return render(model, "/result.html"); + }; + } + + private void finishGame(RacingGame racingGame) { + while (!racingGame.isDone()) { + racingGame.proceedOneTurn(); + } + } + + private RacingGame generateRacingGame(RacingGameRequestDto racingGameRequestDto) { + final Random generate = RandomGenerator.generate(); + final RandomMovingStrategy movingStrategy = new RandomMovingStrategy(generate); + return RacingGame.newInstance(racingGameRequestDto.getNames(), racingGameRequestDto.getTurn(), movingStrategy); + } + + private List<String> mapToName(RacingGame racingGame) { + return racingGame.getWinner() + .stream() + .map(Car::getName) + .collect(toList()); + } + + private List<CarDto> mapToCarDto(Track track) { + return track.getCars() + .stream() + .map(CarDto::new) + .collect(toList()); + } +}
Java
์š”๊ฑด ๋ฐ˜ํ™˜๊ฐ’์ด ๋”ฐ๋กœ ์žˆ๋Š”์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š” ? `getTracks()`๋Š” ๋ฉ”์†Œ๋“œ๊ฐ€ ๋”ฐ๋กœ์žˆ์–ด์„œ์š”!
@@ -0,0 +1,79 @@ +package view; + +import domain.car.Car; +import domain.game.RacingGame; +import domain.game.Track; +import domain.random.RandomGenerator; +import domain.strategy.RandomMovingStrategy; +import dto.CarDto; +import dto.RacingGameRequestDto; +import spark.Route; +import util.Splitter; + +import java.util.HashMap; +import java.util.List; +import java.util.Random; + +import static java.util.stream.Collectors.toList; +import static util.RenderUtil.render; +import static util.Splitter.COMMA; + +public class WebRacingHandler { + public Route handleGetName() { + return (req, res) -> { + HashMap<String, Object> model = new HashMap<>(); + String names = req.queryParams("names"); + + List<String> splitNames = Splitter.splitBlank(names); + model.put("names", splitNames); + model.put("nameStrings", String.join(COMMA, splitNames)); + return render(model, "/game.html"); + }; + } + + public Route handleResult() { + return (req, res) -> { + final HashMap<String, Object> model = new HashMap<>(); + final RacingGameRequestDto racingGameRequestDto = new RacingGameRequestDto(Integer.parseInt(req.queryParams("turn")), req.queryParams("names")); + + final RacingGame racingGame = generateRacingGame(racingGameRequestDto); + + finishGame(racingGame); + Track track = racingGame.getTrack(); + + List<CarDto> carDtos = mapToCarDto(track); + List<String> nameOfWinners = mapToName(racingGame); + + + model.put("cars", carDtos); + model.put("winners", nameOfWinners); + return render(model, "/result.html"); + }; + } + + private void finishGame(RacingGame racingGame) { + while (!racingGame.isDone()) { + racingGame.proceedOneTurn(); + } + } + + private RacingGame generateRacingGame(RacingGameRequestDto racingGameRequestDto) { + final Random generate = RandomGenerator.generate(); + final RandomMovingStrategy movingStrategy = new RandomMovingStrategy(generate); + return RacingGame.newInstance(racingGameRequestDto.getNames(), racingGameRequestDto.getTurn(), movingStrategy); + } + + private List<String> mapToName(RacingGame racingGame) { + return racingGame.getWinner() + .stream() + .map(Car::getName) + .collect(toList()); + } + + private List<CarDto> mapToCarDto(Track track) { + return track.getCars() + .stream() + .map(CarDto::new) + .collect(toList()); + } +}
Java
ํ•ด๋‹น ์˜์—ญ์„ ๋ถ„๋ฆฌํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,25 @@ +package com.example.chatgptcodereviewtest.controller; + +import com.example.chatgptcodereviewtest.dto.InputDto; +import com.example.chatgptcodereviewtest.service.TestService; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +/** + * ์„ค๋ช…: + * + * @author ์ตœํ˜„๋ฒ”(Jayce) / hb.choi@dreamus.io + * @since 2023/03/23 + */ +@RestController +@RequestMapping("/test") +@RequiredArgsConstructor +public class TestController { + + private final TestService testService; + + @PostMapping + public int convertText(@RequestBody InputDto inputDto) { + return testService.addAgeAndNameLength(inputDto); + } +}
Java
์œ„ ์ฝ”๋“œ ์กฐ๊ฐ์—์„œ๋Š” `TestController` ํด๋ž˜์Šค๋ฅผ ์ •์˜ํ•˜๊ณ  ์žˆ์œผ๋ฉฐ, ํ•ด๋‹น ์ปจํŠธ๋กค๋Ÿฌ์˜ `convertText` ๋ฉ”์†Œ๋“œ๋Š” `InputDto` ๊ฐ์ฒด๋ฅผ ๋ฐ›์•„๋“ค์—ฌ `testService`์—์„œ `addAgeAndNameLength` ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•œ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. ์ด ์ฝ”๋“œ ์กฐ๊ฐ์— ๋Œ€ํ•œ ์ฃผ์š” ๊ฐœ์„  ์ œ์•ˆ์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค: 1. ์ปจํŠธ๋กค๋Ÿฌ์™€ ์„œ๋น„์Šค ํด๋ž˜์Šค์˜ ์ด๋ฆ„์„ ๋” ๋ช…ํ™•ํ•˜๊ฒŒ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ๋„๋ก ๋ณ€๊ฒฝํ•˜๋Š” ๊ฒƒ์ด ์ข‹์Šต๋‹ˆ๋‹ค. 2. ์ปจํŠธ๋กค๋Ÿฌ์—์„œ ์‚ฌ์šฉ๋œ ๊ฒฝ๋กœ๋ช…(`"/test"`) ๋ฐ HTTP ๋ฉ”์†Œ๋“œ(`@PostMapping`)์— ๋Œ€ํ•ด ์ถฉ๋ถ„ํ•œ ์„ค๋ช…์ด ์—†์œผ๋ฏ€๋กœ API์˜ ์˜๋„๋ฅผ ๋” ์ž˜ ์„ค๋ช…ํ•  ํ•„์š”๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. 3. `InputDto` ํด๋ž˜์Šค์˜ ํ•„๋“œ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ์œ„ํ•œ ๊ฒ€์ฆ ์–ด๋…ธํ…Œ์ด์…˜ ๋“ฑ์˜ ์ถ”๊ฐ€์ ์ธ ๋ฒจ๋ฆฌ๋ฐ์ด์…˜ ๋กœ์ง์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ๋ฌธ์ œ์ ์œผ๋กœ๋Š” ํ˜„์žฌ ์ฝ”๋“œ ์ƒํƒœ์— ๋ฌธ๋ฒ•์ ์ธ ์˜ค๋ฅ˜๋‚˜ ๊ธฐ๋Šฅ์ƒ์˜ ํฐ ์œ„ํ—˜์€ ๋ณด์ด์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,22 @@ +package com.example.chatgptcodereviewtest.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.ToString; + +/** + * ์„ค๋ช…: + * + * @author ์ตœํ˜„๋ฒ”(Jayce) / hb.choi@dreamus.io + * @since 2023/03/23 + */ +@Getter +@ToString +@NoArgsConstructor +@AllArgsConstructor +public class InputDto { + + private String name; + private int age; +}
Java
์œ„ ์ฝ”๋“œ๋Š” lombok ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์ด์šฉํ•ด InputDto ํด๋ž˜์Šค๋ฅผ ์ƒ์„ฑํ•˜๊ณ  ์žˆ๋Š” ๊ฒƒ์œผ๋กœ ๋ณด์ž…๋‹ˆ๋‹ค. ๊ฐœ์„ ์ : 1. ํด๋ž˜์Šค์™€ ๋ณ€์ˆ˜ ์ด๋ฆ„์„ ๋” ๋ช…ํ™•ํ•˜๊ฒŒ ์ ์–ด์ฃผ๋ฉด ์ข‹๊ฒ ์Šต๋‹ˆ๋‹ค. 2. Setter๊ฐ€ ์—†๊ธฐ ๋•Œ๋ฌธ์— name๊ณผ age์— ๋Œ€ํ•œ ์ผ๋ถ€ ์ •๋ณด ๋ณ€๊ฒฝ์ด ๋ถˆ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ, ํ•ด๋‹น DTO๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ํด๋ž˜์Šค์—์„œ ์ œ์–ดํ•  ์ˆ˜ ์žˆ๋„๋ก Setter ๋ฉ”์†Œ๋“œ ์ถ”๊ฐ€๋ฅผ ๊ณ ๋ คํ•ด๋ณผ ํ•„์š”์„ฑ์ด ์žˆ์Šต๋‹ˆ๋‹ค. ๋ฒ„๊ทธ ๊ฐ€๋Šฅ์„ฑ: ํ˜„์žฌ ํ•ด๋‹น ์ฝ”๋“œ์—์„œ ๋ฒ„๊ทธ๋Š” ๋ณด์ด์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,20 @@ +package com.example.chatgptcodereviewtest.service; + +import com.example.chatgptcodereviewtest.dto.InputDto; +import org.springframework.stereotype.Service; + +/** + * ์„ค๋ช…: + * + * @author ์ตœํ˜„๋ฒ”(Jayce) / hb.choi@dreamus.io + * @since 2023/03/23 + */ +@Service +public class TestService { + + public int addAgeAndNameLength(InputDto inputDto) { + int age = inputDto.getAge(); + int nameLength = inputDto.getName().length(); + return age + nameLength; + } +}
Java
์œ„์˜ ์ฝ”๋“œ ๋ฆฌ๋ทฐ์— ๋Œ€ํ•œ ์ œ ์ƒ๊ฐ์ž…๋‹ˆ๋‹ค. ๊ธฐ๋Šฅ์ ์œผ๋กœ ๋ฌธ์ œ๊ฐ€ ์—†์–ด ๋ณด์ด๋ฉฐ, ์ถ”๊ฐ€ ๊ฐœ์„  ์‚ฌํ•ญ์€ ์—†์Šต๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ๋ช‡ ๊ฐ€์ง€ ์ž‘์€ ์ˆ˜์ • ์‚ฌํ•ญ์„ ์ œ์•ˆํ•ด ๋“œ๋ฆฌ๊ฒ ์Šต๋‹ˆ๋‹ค: - ์ฃผ์„์ด ์ƒ์„ธํ•˜์ง€ ์•Š์•„ ๋ณ€๊ฒฝ ๋œ ํ”„๋กœ์ ํŠธ์— ๋Œ€ํ•ด ์ถฉ๋ถ„ํ•œ ์„ค๋ช…์„ ์ œ๊ณตํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋ฉ”์†Œ๋“œ ์ด๋ฆ„ 'addAgeAndNameLength' ์ž์ฒด๊ฐ€ ๊ธฐ๋Šฅ์„ ์„ค๋ช…ํ•˜๋Š” ๋ฐ ๋งค์šฐ ํฌ๊ด„์ ์ž…๋‹ˆ๋‹ค. ์ข€ ๋” ๊ตฌ์ฒด์ ์ธ ๋ฉ”์†Œ๋“œ ๋ฐ ํด๋ž˜์Šค ์„ค๋ช…๊ณผ ํ•จ๊ป˜ ์ฃผ์„์„ ์ถ”๊ฐ€ํ•˜๋Š” ๊ฒƒ์ด ์ข‹์Šต๋‹ˆ๋‹ค. - ๋ชจ๋“  ์˜ˆ์™ธ๋ฅผ ์ฒ˜๋ฆฌ ํ•  ์ˆ˜ ์žˆ๋„๋ก try-catch ๋ธ”๋ก์„ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ์ธกํ•  ์ˆ˜์—†๋Š” ๊ฐ’์„ ์ „๋‹ฌํ•˜์—ฌ ์ถœ๋ ฅ ๊ฐ’์ด ์Œ์ˆ˜๊ฐ€๋˜๋Š” ๊ฒฝ์šฐ ๋“ฑ ์œ„ํ—˜์„ฑ์ด ์žˆ๋Š” ๊ธฐ๋Šฅ์€ ์—†์œผ๋ฉฐ, ๊ธฐ๋ณธ ์œ ๋‹› ํ…Œ์ŠคํŠธ๋ฅผ ์ž‘์„ฑํ•˜์—ฌ ์ฝ”๋“œ์˜ ์ •ํ™•์„ฑ์„ ๊ฒ€์ฆํ•˜๋Š” ๊ฒƒ์ด ์ข‹์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,39 @@ +package nextstep.auth.authentication; + +import nextstep.member.application.UserDetailsService; +import nextstep.member.domain.User; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +public abstract class Authenticator implements HandlerInterceptor { + + private final UserDetailsService userDetailsService; + + public Authenticator(UserDetailsService userDetailsService) { + this.userDetailsService = userDetailsService; + } + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { + AuthenticationToken token = convert(request); + User user = userDetailsService.loadUserByUsername(token.getPrincipal()); + + checkAuthentication(user, token.getCredentials()); + authenticate(user, response); + + return false; + } + + abstract public AuthenticationToken convert(HttpServletRequest request) throws IOException; + + abstract public void authenticate(User user, HttpServletResponse response) throws IOException; + + private void checkAuthentication(User user, String password) { + if (!user.checkPassword(password)) { + throw new AuthenticationException(); + } + } +}
Java
์•„๋ž˜ ์š”๊ตฌ์‚ฌํ•ญ์ด ๋ฐ˜์˜๋˜์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ˜ข <img width="516" alt="แ„‰แ…ณแ„แ…ณแ„…แ…ตแ†ซแ„‰แ…ฃแ†บ 2022-08-16 แ„‹แ…ฉแ„’แ…ฎ 10 07 08" src="https://user-images.githubusercontent.com/17218212/184886987-febc108f-8b2f-403b-a53e-bf36f069cc24.png">
@@ -1,51 +1,45 @@ package nextstep.auth.token; import com.fasterxml.jackson.databind.ObjectMapper; -import nextstep.auth.authentication.AuthenticationException; -import nextstep.member.application.LoginMemberService; -import nextstep.member.domain.LoginMember; +import nextstep.auth.authentication.AuthenticationToken; +import nextstep.auth.authentication.Authenticator; +import nextstep.member.application.UserDetailsService; +import nextstep.member.domain.User; import org.springframework.http.MediaType; -import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import java.io.IOException; import java.util.stream.Collectors; -public class TokenAuthenticationInterceptor implements HandlerInterceptor { - private LoginMemberService loginMemberService; - private JwtTokenProvider jwtTokenProvider; +public class TokenAuthenticationInterceptor extends Authenticator { + private final JwtTokenProvider jwtTokenProvider; + private final ObjectMapper objectMapper = new ObjectMapper(); - public TokenAuthenticationInterceptor(LoginMemberService loginMemberService, JwtTokenProvider jwtTokenProvider) { - this.loginMemberService = loginMemberService; + public TokenAuthenticationInterceptor(UserDetailsService userDetailsService, JwtTokenProvider jwtTokenProvider) { + super(userDetailsService); this.jwtTokenProvider = jwtTokenProvider; } @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + public AuthenticationToken convert(HttpServletRequest request) throws IOException { String content = request.getReader().lines().collect(Collectors.joining(System.lineSeparator())); TokenRequest tokenRequest = new ObjectMapper().readValue(content, TokenRequest.class); String principal = tokenRequest.getEmail(); String credentials = tokenRequest.getPassword(); - LoginMember loginMember = loginMemberService.loadUserByUsername(principal); - - if (loginMember == null) { - throw new AuthenticationException(); - } - - if (!loginMember.checkPassword(credentials)) { - throw new AuthenticationException(); - } + return new AuthenticationToken(principal, credentials); + } - String token = jwtTokenProvider.createToken(loginMember.getEmail(), loginMember.getAuthorities()); + @Override + public void authenticate(User member, HttpServletResponse response) throws IOException { + String token = jwtTokenProvider.createToken(member.getEmail(), member.getAuthorities()); TokenResponse tokenResponse = new TokenResponse(token); - String responseToClient = new ObjectMapper().writeValueAsString(tokenResponse); + String responseToClient = objectMapper.writeValueAsString(tokenResponse); response.setStatus(HttpServletResponse.SC_OK); response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.getOutputStream().print(responseToClient); - - return false; } }
Java
`ObjectMapper` ๋Š” ์ƒ์„ฑ ๋น„์šฉ์ด ๋น„์‹ธ๋‹ค๊ณ  ์•Œ๋ ค์ง„ ๊ฐ์ฒด์ž…๋‹ˆ๋‹ค. ์˜์กด์„ฑ ์ฃผ์ž…์„ ํ†ตํ•ด ํ•ด๊ฒฐํ•ด๋ณผ ์ˆ˜ ์žˆ์„๊นŒ์š”? ๐Ÿ˜„
@@ -0,0 +1,8 @@ +package nextstep.member.application; + +import nextstep.member.domain.User; + +public interface UserDetailsService { + + User loadUserByUsername(String email); +}
Java
์ด ์ธํ„ฐํŽ˜์ด์Šค๊ฐ€ `member` ํŒจํ‚ค์ง€์— ์žˆ๋Š”๊ฒŒ ๋งž์„๊นŒ์š”? ๐Ÿค”