code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,36 @@ +package christmas.domain; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; + +import static org.junit.jupiter.api.Assertions.*; + +public class BillTest { + Order testOrder = new Order(); + + @Test + @DisplayName("์ „์ฒด_๊ฐ€๊ฒฉ_๊ณ„์‚ฐ_ํ…Œ์ŠคํŠธ") + public void testBillTotalPriceCalculation() { + testOrder.takeOrder("์–‘์†ก์ด์ˆ˜ํ”„-1,ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ-2,์ดˆ์ฝ”์ผ€์ดํฌ-3"); + Bill bill = new Bill(testOrder); + + BigDecimal expectedTotalPrice = BigDecimal + .valueOf(1).multiply(Menu.APPETIZER_MUSHROOM_SOUP.getPrice()) + .add(BigDecimal.valueOf(2).multiply(Menu.MAIN_T_BONE_STEAK.getPrice())) + .add(BigDecimal.valueOf(3).multiply(Menu.DESSERT_CHOCO_CAKE.getPrice())); + + assertEquals(expectedTotalPrice, bill.getTotalPrice()); + } + + @Test + @DisplayName("๊ฐ€๊ฒฉ_ํ• ์ธ_์ ์šฉ_ํ…Œ์ŠคํŠธ") + public void testBillDiscountPrice() { + testOrder.takeOrder("์–‘์†ก์ด์ˆ˜ํ”„-5"); //30,000์› + Bill bill = new Bill(testOrder); + bill.discountPrice(new BigDecimal(10000)); //30,000 - 10,000 ์› + + assertEquals(bill.getTotalPrice(), new BigDecimal(20000)); + } +}
Java
given when then ํŒจํ„ด์„ ์‚ฌ์šฉํ•ด์„œ ํ…Œ์ŠคํŠธ์ฝ”๋“œ๋ฅผ ๋‚˜๋ˆ  ๋ณด๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š”? https://brunch.co.kr/@springboot/292
@@ -0,0 +1,89 @@ +package christmas.domain; + +import christmas.utils.ErrorMessage; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +class OrderTest { + String validInput = "ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ-2,์–‘์†ก์ด์ˆ˜ํ”„-2"; + + @Test + @DisplayName("์ฃผ๋ฌธ_์œ ํšจ๊ฐ’_์ž…๋ ฅ_ํ…Œ์ŠคํŠธ") + void takeOrder_ValidInput_ShouldNotThrowException() { + Order order = new Order(); + assertDoesNotThrow(() -> order.takeOrder(validInput)); + } + + @Test + @DisplayName("์ฃผ๋ฌธ_์ค‘๋ณต_์˜ˆ์™ธ_ํ…Œ์ŠคํŠธ") + void takeOrder_DuplicateMenu_ShouldThrowException() { + Order order = new Order(); + String duplicateMenuInput = "ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ-2,ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ-2"; + + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () + -> order.takeOrder(duplicateMenuInput)); + assertEquals(ErrorMessage.INPUT_ORDER_ERROR_MESSAGE.getMessage(), exception.getMessage()); + } + + @Test + @DisplayName("์ฃผ๋ฌธ_์ž…๋ ฅํ˜•์‹_์˜ˆ์™ธ_ํ…Œ์ŠคํŠธ") + void takeOrder_InvalidOrderFormat_ShouldThrowException() { + Order order = new Order(); + String invalidFormatInput = "ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ+2"; + + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () + -> order.takeOrder(invalidFormatInput)); + assertEquals(ErrorMessage.INPUT_ORDER_ERROR_MESSAGE.getMessage(), exception.getMessage()); + } + + @Test + @DisplayName("์ฃผ๋ฌธ_๊ฐœ์ˆ˜์ดˆ๊ณผ_์˜ˆ์™ธ_ํ…Œ์ŠคํŠธ") + void takeOrder_ExceedMaximumQuantity_ShouldThrowException() { + Order order = new Order(); + String exceedQuantityInput = "ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ-20,์–‘์†ก์ด์ˆ˜ํ”„-10"; + + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () + -> order.takeOrder(exceedQuantityInput)); + assertEquals(ErrorMessage.INPUT_ORDER_ERROR_MESSAGE.getMessage(), exception.getMessage()); + } + + @Test + @DisplayName("์ฃผ๋ฌธ_์Œ๋ฃŒ_์˜ˆ์™ธ_ํ…Œ์ŠคํŠธ") + void takeOrder_OnlyBeverage_ValidInput_ShouldNotThrowException() { + Order order = new Order(); + String onlyBeverageInput = "์ œ๋กœ์ฝœ๋ผ-10"; + + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () + -> order.takeOrder(onlyBeverageInput)); + assertEquals(ErrorMessage.INPUT_ORDER_ERROR_MESSAGE.getMessage(), exception.getMessage()); + } + + @Test + @DisplayName("์ฃผ๋ฌธ_๊ณต๋ฐฑ_์˜ˆ์™ธ_ํ…Œ์ŠคํŠธ") + void toString_OrderDetailsEmpty_ShouldReturnEmptyString() { + Order order = new Order(); + + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () + -> order.takeOrder("")); + assertEquals(ErrorMessage.INPUT_ORDER_ERROR_MESSAGE.getMessage(), exception.getMessage()); + assertEquals("", order.toString()); + } + + @Test + @DisplayName("์ฃผ๋ฌธ_๋‚ด์—ญ_์ถœ๋ ฅ_ํ…Œ์ŠคํŠธ") + void getOrderDetails_OrderDetailsNotEmpty_ShouldReturnOrderDetails() { + Order order = new Order(); + order.takeOrder(validInput); + + Map<Menu, Integer> expectedOrderDetails = new HashMap<>(); + expectedOrderDetails.put(Menu.findMenu("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ"), 2); + expectedOrderDetails.put(Menu.findMenu("์–‘์†ก์ด์ˆ˜ํ”„"), 2); + + assertEquals(expectedOrderDetails, order.getOrderDetails()); + } +}
Java
๋ฐ˜๋ณต๋˜๋Š” Order order = new Order(); ๋Š” @BeforeAll void setUp()์„ ํ™œ์šฉํ•˜์—ฌ์„œ ๋ฏธ๋ฆฌ ์ƒ์„ฑํ•ด ์ฃผ๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,110 @@ +package christmas.controller; + +import christmas.domain.*; +import christmas.utils.EventSettings; +import christmas.parser.EventDetailsParser; +import christmas.view.EventView; + +import java.math.BigDecimal; +import java.util.Map; + +public class ChristmasEventController implements EventController { + private static final String WEEKDAY_DISCOUNT_TYPE = "dessert"; + private static final String WEEKEND_DISCOUNT_TYPE = "main"; + private static final DecemberCalendar decemberCalendar = new DecemberCalendar(); + + private boolean canPresent = false; + private BigDecimal totalBenefitAmount = new BigDecimal(0); + private Map<Menu, Integer> orderDetails; + private Badge badge; + private String eventResultDetails = ""; + private BigDecimal beforeEventApplied; + + public void applyEvent(ReservationDay reservationDay, Order order, Bill bill) { + beforeEventApplied = bill.getTotalPrice(); + if (bill.getTotalPrice().compareTo(EventSettings.EVENT_APPLY_STAND.getAmount()) >= 0) { + this.orderDetails = order.getOrderDetails(); + presentEvent(bill); + dDayDiscountEvent(reservationDay, bill); + weekdayDiscountEvent(reservationDay, bill); + weekendDiscountEvent(reservationDay, bill); + specialDayDiscountEvent(reservationDay, bill); + badgeEvent(totalBenefitAmount); + } + } + + public void presentEvent(Bill bill) { + if (bill.getTotalPrice().compareTo(EventSettings.PRESENT_STANDARD_AMOUNT.getAmount()) == 1) { + canPresent = true; + BigDecimal benefitValue = EventSettings.PRESENT_VALUE.getAmount(); + + totalBenefitAmount = totalBenefitAmount.add(benefitValue); + eventResultDetails += EventDetailsParser.parsePresentEventDetail(benefitValue); + } + } + + public void dDayDiscountEvent(ReservationDay reservationDay, Bill bill) { + if (reservationDay.dDayDiscountEventPeriod()) { + BigDecimal eventDay = new BigDecimal(reservationDay.getDay() - 1); + BigDecimal discountValue = EventSettings.D_DAY_DISCOUNT_START_VALUE.getAmount(). + add((EventSettings.D_DAY_DISCOUNT_VALUE.getAmount().multiply(eventDay))); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.parseDDayDiscountEventDetail(discountValue); + } + } + + public void weekdayDiscountEvent(ReservationDay day, Bill bill) { + if (decemberCalendar.isWeekday(day.getDay())) { + long dessertCount = orderDetails.entrySet().stream() + .filter(entry -> WEEKDAY_DISCOUNT_TYPE.equals(entry.getKey().getMenuItem().getMenuType())) + .mapToLong(Map.Entry::getValue) + .sum(); + BigDecimal discountValue = new BigDecimal(dessertCount) + .multiply(EventSettings.STANDARD_DISCOUNT_VALUE.getAmount()); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.parseWeekdayDiscountEventDetail(discountValue); + } + } + + public void weekendDiscountEvent(ReservationDay day, Bill bill) { + if (decemberCalendar.isWeekend(day.getDay())) { + long mainDishCount = orderDetails.entrySet().stream() + .filter(entry -> WEEKEND_DISCOUNT_TYPE.equals(entry.getKey().getMenuItem().getMenuType())) + .mapToLong(Map.Entry::getValue) + .sum(); + BigDecimal discountValue = new BigDecimal(mainDishCount) + .multiply(EventSettings.STANDARD_DISCOUNT_VALUE.getAmount()); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.parseWeekendDiscountEventDetail(discountValue); + } + } + + public void specialDayDiscountEvent(ReservationDay day, Bill bill) { + if (decemberCalendar.isSpecialDay(day.getDay())) { + BigDecimal discountValue = EventSettings.SPECIAL_DAY_DISCOUNT_VALUE.getAmount(); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.paresSpecialDayDiscountEventDetail(discountValue); + } + } + + public void badgeEvent(BigDecimal totalBenefitAmount) { + badge = Badge.getBadge(totalBenefitAmount); + } + + public void showEventDiscountDetails(Bill bill) { + EventView.printPriceBeforeDiscount(beforeEventApplied); + EventView.printPresentDetails(canPresent); + EventView.printEventResultDetails(eventResultDetails); + EventView.printTotalBenefitAmount(totalBenefitAmount); + EventView.printPriceAfterDiscount(bill); + EventView.printBadge(badge); + } +}
Java
ํŠน์ • ๋ฉ”์„œ๋“œ์—์„œ๋งŒ ์‚ฌ์šฉ๋˜๋Š” ํ•„๋“œ๋Š” ๋กœ์ปฌํ™”ํ•˜๊ณ  ๋‚˜๋จธ์ง„ ๊ฐ์ฒดํ™”ํ•˜์—ฌ ํ•„๋“œ ์ˆ˜๋ฅผ ์ค„์—ฌ๋ณด๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š”? ์ถ”๊ฐ€๋กœ `final` ํ‚ค์›Œ๋“œ๋ฅผ ์ƒ๋žตํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,69 @@ +package christmas.controller; + +import christmas.domain.Bill; +import christmas.domain.Order; +import christmas.domain.ReservationDay; +import christmas.view.InputView; +import christmas.view.OutputView; + +public class PlannerController { + private final Order order; + private final ReservationDay reservationDay; + private final EventController eventController; + + private Bill bill; + + public PlannerController(EventController eventController) { + this.eventController = eventController; + this.reservationDay = new ReservationDay(); + this.order = new Order(); + } + + public void run() { + OutputView.printStartMessage(); + + try { + inputDay(); + inputOrder(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return; + } + + processEvent(); + } + + private void inputDay() { + while (true) { + try { + String dayInput = InputView.inputDate(); + reservationDay.reserveDay(dayInput); + break; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private void inputOrder() { + while (true) { + try { + String orderInput = InputView.inputOrder(); + order.takeOrder(orderInput.replace(" ", "")); + break; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private void processEvent() { + OutputView.printEventPreviewMessage(reservationDay.getDay()); + OutputView.printOrderDetails(order); + + bill = new Bill(order); + + eventController.applyEvent(reservationDay, order, bill); + eventController.showEventDiscountDetails(bill); + } +}
Java
์˜ˆ์™ธ ๋ฉ”์‹œ์ง€ ์ถœ๋ ฅ๋„ `OutputView` ์—์„œ ์ฒ˜๋ฆฌํ•˜๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,69 @@ +package christmas.controller; + +import christmas.domain.Bill; +import christmas.domain.Order; +import christmas.domain.ReservationDay; +import christmas.view.InputView; +import christmas.view.OutputView; + +public class PlannerController { + private final Order order; + private final ReservationDay reservationDay; + private final EventController eventController; + + private Bill bill; + + public PlannerController(EventController eventController) { + this.eventController = eventController; + this.reservationDay = new ReservationDay(); + this.order = new Order(); + } + + public void run() { + OutputView.printStartMessage(); + + try { + inputDay(); + inputOrder(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + return; + } + + processEvent(); + } + + private void inputDay() { + while (true) { + try { + String dayInput = InputView.inputDate(); + reservationDay.reserveDay(dayInput); + break; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private void inputOrder() { + while (true) { + try { + String orderInput = InputView.inputOrder(); + order.takeOrder(orderInput.replace(" ", "")); + break; + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private void processEvent() { + OutputView.printEventPreviewMessage(reservationDay.getDay()); + OutputView.printOrderDetails(order); + + bill = new Bill(order); + + eventController.applyEvent(reservationDay, order, bill); + eventController.showEventDiscountDetails(bill); + } +}
Java
ํ•„๋“œ๊ฐ€ ์ƒ์„ฑ์ž๊ฐ€ ์•„๋‹Œ ๋‹ค๋ฅธ ๋ฉ”์„œ๋“œ์—์„œ ์ดˆ๊ธฐํ™”๋˜๋Š”๊ฒŒ ์–ด์ƒ‰ํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,35 @@ +package christmas.domain; + +import java.math.BigDecimal; + +public enum Badge { + SANTA_BADGE("์‚ฐํƒ€", new BigDecimal(20000)), + TREE_BADGE("ํŠธ๋ฆฌ", new BigDecimal(10000)), + STAR_BADGE("๋ณ„", new BigDecimal(5000)); + + private final String name; + private final BigDecimal standardAmount; + + Badge(String name, BigDecimal standardAmount) { + this.name = name; + this.standardAmount = standardAmount; + } + + public String getName() { + if (this == null) return ""; + return name; + } + + public static Badge getBadge(BigDecimal totalBenefit) { + if (totalBenefit.compareTo(SANTA_BADGE.standardAmount) >= 0) { + return SANTA_BADGE; + } + if (totalBenefit.compareTo(TREE_BADGE.standardAmount) >= 0) { + return TREE_BADGE; + } + if (totalBenefit.compareTo(STAR_BADGE.standardAmount) >= 0) { + return STAR_BADGE; + } + return null; + } +}
Java
์ด๋ฆ„์ด `null`์ด ๋˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,110 @@ +package christmas.controller; + +import christmas.domain.*; +import christmas.utils.EventSettings; +import christmas.parser.EventDetailsParser; +import christmas.view.EventView; + +import java.math.BigDecimal; +import java.util.Map; + +public class ChristmasEventController implements EventController { + private static final String WEEKDAY_DISCOUNT_TYPE = "dessert"; + private static final String WEEKEND_DISCOUNT_TYPE = "main"; + private static final DecemberCalendar decemberCalendar = new DecemberCalendar(); + + private boolean canPresent = false; + private BigDecimal totalBenefitAmount = new BigDecimal(0); + private Map<Menu, Integer> orderDetails; + private Badge badge; + private String eventResultDetails = ""; + private BigDecimal beforeEventApplied; + + public void applyEvent(ReservationDay reservationDay, Order order, Bill bill) { + beforeEventApplied = bill.getTotalPrice(); + if (bill.getTotalPrice().compareTo(EventSettings.EVENT_APPLY_STAND.getAmount()) >= 0) { + this.orderDetails = order.getOrderDetails(); + presentEvent(bill); + dDayDiscountEvent(reservationDay, bill); + weekdayDiscountEvent(reservationDay, bill); + weekendDiscountEvent(reservationDay, bill); + specialDayDiscountEvent(reservationDay, bill); + badgeEvent(totalBenefitAmount); + } + } + + public void presentEvent(Bill bill) { + if (bill.getTotalPrice().compareTo(EventSettings.PRESENT_STANDARD_AMOUNT.getAmount()) == 1) { + canPresent = true; + BigDecimal benefitValue = EventSettings.PRESENT_VALUE.getAmount(); + + totalBenefitAmount = totalBenefitAmount.add(benefitValue); + eventResultDetails += EventDetailsParser.parsePresentEventDetail(benefitValue); + } + } + + public void dDayDiscountEvent(ReservationDay reservationDay, Bill bill) { + if (reservationDay.dDayDiscountEventPeriod()) { + BigDecimal eventDay = new BigDecimal(reservationDay.getDay() - 1); + BigDecimal discountValue = EventSettings.D_DAY_DISCOUNT_START_VALUE.getAmount(). + add((EventSettings.D_DAY_DISCOUNT_VALUE.getAmount().multiply(eventDay))); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.parseDDayDiscountEventDetail(discountValue); + } + } + + public void weekdayDiscountEvent(ReservationDay day, Bill bill) { + if (decemberCalendar.isWeekday(day.getDay())) { + long dessertCount = orderDetails.entrySet().stream() + .filter(entry -> WEEKDAY_DISCOUNT_TYPE.equals(entry.getKey().getMenuItem().getMenuType())) + .mapToLong(Map.Entry::getValue) + .sum(); + BigDecimal discountValue = new BigDecimal(dessertCount) + .multiply(EventSettings.STANDARD_DISCOUNT_VALUE.getAmount()); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.parseWeekdayDiscountEventDetail(discountValue); + } + } + + public void weekendDiscountEvent(ReservationDay day, Bill bill) { + if (decemberCalendar.isWeekend(day.getDay())) { + long mainDishCount = orderDetails.entrySet().stream() + .filter(entry -> WEEKEND_DISCOUNT_TYPE.equals(entry.getKey().getMenuItem().getMenuType())) + .mapToLong(Map.Entry::getValue) + .sum(); + BigDecimal discountValue = new BigDecimal(mainDishCount) + .multiply(EventSettings.STANDARD_DISCOUNT_VALUE.getAmount()); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.parseWeekendDiscountEventDetail(discountValue); + } + } + + public void specialDayDiscountEvent(ReservationDay day, Bill bill) { + if (decemberCalendar.isSpecialDay(day.getDay())) { + BigDecimal discountValue = EventSettings.SPECIAL_DAY_DISCOUNT_VALUE.getAmount(); + + bill.discountPrice(discountValue); + totalBenefitAmount = totalBenefitAmount.add(discountValue); + eventResultDetails += EventDetailsParser.paresSpecialDayDiscountEventDetail(discountValue); + } + } + + public void badgeEvent(BigDecimal totalBenefitAmount) { + badge = Badge.getBadge(totalBenefitAmount); + } + + public void showEventDiscountDetails(Bill bill) { + EventView.printPriceBeforeDiscount(beforeEventApplied); + EventView.printPresentDetails(canPresent); + EventView.printEventResultDetails(eventResultDetails); + EventView.printTotalBenefitAmount(totalBenefitAmount); + EventView.printPriceAfterDiscount(bill); + EventView.printBadge(badge); + } +}
Java
`BigDecimal` ์˜ ๊ฒฝ์šฐ ์ผ๋ถ€ ๊ฐ’์„ ์บ์‹ฑํ•˜๊ณ  ์žˆ์–ด ์ƒ์„ฑ์ž ๋Œ€์‹  `valueOf()` ๋ฉ”์„œ๋“œ๋ฅผ ํ†ตํ•ด ๊ฐ์ฒด๋ฅผ ์–ป๋Š”๊ฒŒ ๋” ํšจ์œจ์ ์ž…๋‹ˆ๋‹ค!
@@ -0,0 +1,35 @@ +package christmas.domain; + +import java.math.BigDecimal; + +public enum Badge { + SANTA_BADGE("์‚ฐํƒ€", new BigDecimal(20000)), + TREE_BADGE("ํŠธ๋ฆฌ", new BigDecimal(10000)), + STAR_BADGE("๋ณ„", new BigDecimal(5000)); + + private final String name; + private final BigDecimal standardAmount; + + Badge(String name, BigDecimal standardAmount) { + this.name = name; + this.standardAmount = standardAmount; + } + + public String getName() { + if (this == null) return ""; + return name; + } + + public static Badge getBadge(BigDecimal totalBenefit) { + if (totalBenefit.compareTo(SANTA_BADGE.standardAmount) >= 0) { + return SANTA_BADGE; + } + if (totalBenefit.compareTo(TREE_BADGE.standardAmount) >= 0) { + return TREE_BADGE; + } + if (totalBenefit.compareTo(STAR_BADGE.standardAmount) >= 0) { + return STAR_BADGE; + } + return null; + } +}
Java
`null` ๋ฐ˜ํ™˜์ด ์œ„ํ—˜ํ•œ ๊ฒƒ ๊ฐ™์•„์š”! `NONE` ๊ณผ ๊ฐ™์€ ์ธ์Šคํ„ด์Šค๋ฅผ ์ถ”๊ฐ€ํ•˜์—ฌ ์ด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,32 @@ +package christmas.domain; + +import java.math.BigDecimal; +import java.util.Map; + +public class Bill { + private final Map<Menu, Integer> orderDetails; + + private BigDecimal totalPrice = new BigDecimal(0); + + public Bill(Order order) { + this.orderDetails = order.getOrderDetails(); + calculateTotalPrice(); + } + + private void calculateTotalPrice() { + for (Map.Entry<Menu, Integer> entry : orderDetails.entrySet()) { + Menu menu = entry.getKey(); + int count = entry.getValue(); + BigDecimal price = menu.getPrice().multiply(BigDecimal.valueOf(count)); + totalPrice = totalPrice.add(price); + } + } + + public void discountPrice(BigDecimal discountValue) { + totalPrice = totalPrice.subtract(discountValue); + } + + public BigDecimal getTotalPrice() { + return totalPrice; + } +}
Java
๋ฉ”๋‰ด ์ž…๋ ฅ ์‹œ ์ด๋ฆ„, ์ˆ˜๋Ÿ‰ ์™ธ์— ๋‹ค๋ฅธ ๊ฐ’์ด ์ถ”๊ฐ€๋˜๋Š”๊ฑธ ๊ฐ์•ˆํ•˜์—ฌ `Map<K, V>` ๋Œ€์‹  ๋ณ„๋„์˜ ํด๋ž˜์Šค ์‚ฌ์šฉ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,29 @@ +package christmas.domain; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class DecemberCalendar { + private final List<Integer> weekdays = Stream.of(3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 24, 25, 26, 27, 28, 31) + .collect(Collectors.toList()); + private final List<Integer> weekends = Stream.of(1, 2, 8, 9, 15, 16, 22, 23, 29, 30) + .collect(Collectors.toList()); + private final List<Integer> specialDays = Stream.of(3, 10, 17, 24, 25, 31) + .collect(Collectors.toList()); + + public boolean isWeekday(int day) { + if (weekdays.contains(day)) return true; + return false; + } + + public boolean isWeekend(int day) { + if (weekends.contains(day)) return true; + return false; + } + + public boolean isSpecialDay(int day) { + if (specialDays.contains(day)) return true; + return false; + } +}
Java
`Arrays.asList()` ๋Œ€์‹  Stream์„ ์‚ฌ์šฉํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,62 @@ +package christmas.domain; + +import christmas.utils.ErrorMessage; +import christmas.parser.Parser; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static christmas.domain.validator.OrderValidator.*; + +public class Order { + private final Map<Menu, Integer> orderDetails = new HashMap<>(); + private int quantity = 0; + + public void takeOrder(String input) { + List<String> eachOrderedMenu = Parser.inputToEachOrderedMenu(input); + try { + eachOrderedMenu.forEach(menuInformation -> processOrderedMenu(menuInformation)); + + calculateMenuQuantity(); + validateOnlyBeverage(orderDetails); + validateMaximumQuantity(quantity); + } catch (Exception e) { + throw new IllegalArgumentException(ErrorMessage.INPUT_ORDER_ERROR_MESSAGE.getMessage()); + } + } + + private void processOrderedMenu(String menuInformation) { + String[] menuNameAndNumber = Parser.inputToMenu(menuInformation); + String menuName = menuNameAndNumber[0]; + int menuNumber = Parser.stringToIntPaser(menuNameAndNumber[1]); + Menu orderedMenu = Menu.findMenu(menuName); + + validateDuplicateMenu(orderDetails, orderedMenu); + validateOrderFormat(menuNameAndNumber); + orderDetails.put(orderedMenu, menuNumber); + } + + private void calculateMenuQuantity() { + for (int count : orderDetails.values()) { + quantity += count; + } + } + + public String toString() { + StringBuilder output = new StringBuilder(); + for (Map.Entry<Menu, Integer> entry : orderDetails.entrySet()) { + Menu menu = entry.getKey(); + int count = entry.getValue(); + output.append(menu.getMenuItem().getName()) + .append(" ") + .append(count) + .append("๊ฐœ\n"); + } + return output.toString(); + } + + public Map<Menu, Integer> getOrderDetails() { + return orderDetails; + } +}
Java
`int`์˜ ๊ฒฝ์šฐ ํ•„๋“œ์—์„œ ๊ฐ’์„ ๋Œ€์ž…ํ•˜์ง€ ์•Š์•„๋„ ๊ฐ์ฒด ์ƒ์„ฑ์‹œ 0์œผ๋กœ ์ดˆ๊ธฐํ™” ๋ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,62 @@ +package christmas.domain; + +import christmas.utils.ErrorMessage; +import christmas.parser.Parser; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static christmas.domain.validator.OrderValidator.*; + +public class Order { + private final Map<Menu, Integer> orderDetails = new HashMap<>(); + private int quantity = 0; + + public void takeOrder(String input) { + List<String> eachOrderedMenu = Parser.inputToEachOrderedMenu(input); + try { + eachOrderedMenu.forEach(menuInformation -> processOrderedMenu(menuInformation)); + + calculateMenuQuantity(); + validateOnlyBeverage(orderDetails); + validateMaximumQuantity(quantity); + } catch (Exception e) { + throw new IllegalArgumentException(ErrorMessage.INPUT_ORDER_ERROR_MESSAGE.getMessage()); + } + } + + private void processOrderedMenu(String menuInformation) { + String[] menuNameAndNumber = Parser.inputToMenu(menuInformation); + String menuName = menuNameAndNumber[0]; + int menuNumber = Parser.stringToIntPaser(menuNameAndNumber[1]); + Menu orderedMenu = Menu.findMenu(menuName); + + validateDuplicateMenu(orderDetails, orderedMenu); + validateOrderFormat(menuNameAndNumber); + orderDetails.put(orderedMenu, menuNumber); + } + + private void calculateMenuQuantity() { + for (int count : orderDetails.values()) { + quantity += count; + } + } + + public String toString() { + StringBuilder output = new StringBuilder(); + for (Map.Entry<Menu, Integer> entry : orderDetails.entrySet()) { + Menu menu = entry.getKey(); + int count = entry.getValue(); + output.append(menu.getMenuItem().getName()) + .append(" ") + .append(count) + .append("๊ฐœ\n"); + } + return output.toString(); + } + + public Map<Menu, Integer> getOrderDetails() { + return orderDetails; + } +}
Java
๋„๋ฉ”์ธ์ด View์— ์˜์กดํ•˜๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! `OutputView`์—์„œ `Order`์— ๋Œ€ํ•œ ๊ฐ’์„ ๊ฐ€์ ธ์˜จ ํ›„ ์ถœ๋ ฅํ•˜๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -1,3 +1,5 @@ +import {ReviewLikeButtonProps} from "@review-canvas/theme"; + export type Shadow = 'NONE' | 'SMALL' | 'MEDIUM' | 'LARGE'; export type FocusAreaLayout = 'BEST_REVIEW_TOP' | 'BEST_REVIEW_BOTTOM' | 'BEST_REVIEW_LEFT' | 'BEST_REVIEW_RIGHT'; export type ReviewAreaLayout = 'REVIEW_TOP' | 'REVIEW_BOTTOM' | 'REVIEW_LEFT' | 'REVIEW_RIGHT'; @@ -6,6 +8,7 @@ export type AlignmentPosition = 'LEFT' | 'CENTER' | 'RIGHT'; export type DetailViewType = 'SPREAD' | 'MODAL'; export type PagingType = 'PAGE_NUMBER' | 'SEE_MORE_SCROLL'; export type FilterType = 'LIST' | 'DROPDOWN'; +export type ReviewLikeButtonType = 'NONE' | 'THUMB_UP_WITH_TEXT' | 'THUMB_UP'; export interface Margin { left: string; @@ -43,11 +46,11 @@ export interface Round { } export interface ReviewLike { - buttonType: string; - iconColor: string; - textColor: string; buttonBorderColor: string; buttonRound: Round; + buttonType: ReviewLikeButtonType; + iconColor: string; + textColor: string; } export interface ReviewLayout {
TypeScript
์ „์ฒด์ ์œผ๋กœ Prettier๊ฐ€ ์ ์šฉ์ด ์•ˆ ๋˜์–ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ Prettier ์ „์ฒด์ ์œผ๋กœ ์ ์šฉํ•ด ์ฃผ์„ธ์š”!
@@ -9,50 +9,55 @@ import { generateShadowCSS, } from '@review-canvas/theme'; +// import ThumbUpIcon from '@/assets/icon/icon-thumb-up.svg'; import { Star } from '@/components/review/star.tsx'; import { useReviewItemStyle } from '@/contexts/style/review-item.ts'; import useMessageToShop from '@/hooks/use-message-to-shop.ts'; -import type { ReplyItem } from '@/services/api-types/review'; +import type { ReviewItemProps } from '@/services/api-types/review'; +import { useReviewService } from '@/services/review.tsx'; import { useConnectedShop } from '@/state/shop.ts'; import { MESSAGE_TYPES } from '@/utils/message'; import Reply from './reply'; - -interface ReviewItemProps { - id: number; - rate: number; - content: string; - reviewerID: string; - reviewer: string; - replies: ReplyItem[]; -} +import { useEffect, useState } from 'react'; export default function ReviewItem(props: ReviewItemProps) { const style = useReviewItemStyle(); const { userID } = useConnectedShop(); + const reviewService = useReviewService(); const message = useMessageToShop(); + const [count, setCount] = useState(0); + + useEffect(() => { + async function fetchData() { + return reviewService.userReviewLike(props.id); + } + void fetchData().then((response) => { + setCount(response.data.count); + }); + }, [props.id, reviewService]); const edit = () => { message(MESSAGE_TYPES.OPEN_MODAL, { type: 'edit_review', url: `/reviews/${props.id}/edit`, }); }; - const deleteReview = () => { message(MESSAGE_TYPES.OPEN_SELECTING_MODAL, { type: 'delete', url: `/reviews/${props.id}/delete`, }); }; - const showReviewDetail = () => { message(MESSAGE_TYPES.OPEN_MODAL, { type: 'detail', url: `/reviews/${props.id}`, }); }; + const createLike = () => {}; + return ( <li css={[ @@ -63,6 +68,7 @@ export default function ReviewItem(props: ReviewItemProps) { generateFontCSS(style.font), generateShadowCSS(style.shadow, style.shadowColor), css` + border-color: ${style.borderColor}; background-color: ${style.backgroundColor}; display: flex; flex-direction: column; @@ -88,6 +94,68 @@ export default function ReviewItem(props: ReviewItemProps) { ์ž‘์„ฑ์ž <span>{props.reviewer}</span> </div> <p className="text-left">{props.content}</p> + {/*{style.reviewLike.buttonType !== 'NONE' ? (*/} + {/* <button*/} + {/* onClick={(evt) => {*/} + {/* evt.stopPropagation();*/} + {/* if (userID === props.reviewerID) {*/} + {/* return;*/} + {/* }*/} + {/* }}*/} + {/* css={[*/} + {/* generateBorderRadiusCSS(style.reviewLike.buttonRound),*/} + {/* css`*/} + {/* border-width: 1px;*/} + {/* padding: 2px 6px;*/} + {/* margin-top: 15px;*/} + {/* margin-bottom: 10px;*/} + {/* border-color: ${style.reviewLike.buttonBorderColor};*/} + {/* color: ${style.reviewLike.textColor};*/} + {/* transition:*/} + {/* background-color 0.5s ease,*/} + {/* color 0.5s ease;*/} + {/* display: flex;*/} + + {/* &:hover {*/} + {/* background-color: ${style.reviewLike.textColor};*/} + {/* color: white;*/} + {/* }*/} + {/* `,*/} + {/* ]}*/} + {/* >*/} + {/* <ThumbUpIcon />*/} + {/* {style.reviewLike.buttonType === 'THUMB_UP_WITH_TEXT' ? <div className="ml-1">๋„์›€๋ผ์š”!</div> : null}*/} + {/* <div className="ml-1">0</div>*/} + {/* </button>*/} + {/*) : null}*/} + <button + css={[ + generateBorderRadiusCSS(style.reviewLike.buttonRound), + css` + border-width: 1px; + padding: 2px 6px; + margin-top: 15px; + margin-bottom: 10px; + border-color: ${style.reviewLike.buttonBorderColor}; + color: ${style.reviewLike.textColor}; + transition: + background-color 0.5s ease, + color 0.5s ease; + display: flex; + + &:hover { + background-color: ${style.reviewLike.textColor}; + color: white; + } + `, + ]} + onClick={createLike} + type="button" + > + {/*<ThumbUpIcon />*/} + <div className="ml-1">๋„์›€๋ผ์š”!</div> + <div className="ml-1">{count}</div> + </button> {userID === props.reviewerID ? ( // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions -- This is intentional <div
Unknown
svg๋Š” component๋กœ ๋ถ„๋ฆฌํ•ด์„œ Importํ•ด์„œ ์“ฐ๋Š” ๊ฒŒ ์–ด๋–จ๊ฐ€์š”?? ๋‹ค๋ฅธ ๊ณณ์—์„œ๋„ ์“ธ ์ˆ˜ ์žˆ๊ณ , ์ปดํฌ๋„ŒํŠธ ์ฝ”๋“œ ๋‚ด์—์„œ ๊ฐ€๋…์„ฑ์ด ์ข‹์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™์•„์„œ์š”!
@@ -9,50 +9,55 @@ import { generateShadowCSS, } from '@review-canvas/theme'; +// import ThumbUpIcon from '@/assets/icon/icon-thumb-up.svg'; import { Star } from '@/components/review/star.tsx'; import { useReviewItemStyle } from '@/contexts/style/review-item.ts'; import useMessageToShop from '@/hooks/use-message-to-shop.ts'; -import type { ReplyItem } from '@/services/api-types/review'; +import type { ReviewItemProps } from '@/services/api-types/review'; +import { useReviewService } from '@/services/review.tsx'; import { useConnectedShop } from '@/state/shop.ts'; import { MESSAGE_TYPES } from '@/utils/message'; import Reply from './reply'; - -interface ReviewItemProps { - id: number; - rate: number; - content: string; - reviewerID: string; - reviewer: string; - replies: ReplyItem[]; -} +import { useEffect, useState } from 'react'; export default function ReviewItem(props: ReviewItemProps) { const style = useReviewItemStyle(); const { userID } = useConnectedShop(); + const reviewService = useReviewService(); const message = useMessageToShop(); + const [count, setCount] = useState(0); + + useEffect(() => { + async function fetchData() { + return reviewService.userReviewLike(props.id); + } + void fetchData().then((response) => { + setCount(response.data.count); + }); + }, [props.id, reviewService]); const edit = () => { message(MESSAGE_TYPES.OPEN_MODAL, { type: 'edit_review', url: `/reviews/${props.id}/edit`, }); }; - const deleteReview = () => { message(MESSAGE_TYPES.OPEN_SELECTING_MODAL, { type: 'delete', url: `/reviews/${props.id}/delete`, }); }; - const showReviewDetail = () => { message(MESSAGE_TYPES.OPEN_MODAL, { type: 'detail', url: `/reviews/${props.id}`, }); }; + const createLike = () => {}; + return ( <li css={[ @@ -63,6 +68,7 @@ export default function ReviewItem(props: ReviewItemProps) { generateFontCSS(style.font), generateShadowCSS(style.shadow, style.shadowColor), css` + border-color: ${style.borderColor}; background-color: ${style.backgroundColor}; display: flex; flex-direction: column; @@ -88,6 +94,68 @@ export default function ReviewItem(props: ReviewItemProps) { ์ž‘์„ฑ์ž <span>{props.reviewer}</span> </div> <p className="text-left">{props.content}</p> + {/*{style.reviewLike.buttonType !== 'NONE' ? (*/} + {/* <button*/} + {/* onClick={(evt) => {*/} + {/* evt.stopPropagation();*/} + {/* if (userID === props.reviewerID) {*/} + {/* return;*/} + {/* }*/} + {/* }}*/} + {/* css={[*/} + {/* generateBorderRadiusCSS(style.reviewLike.buttonRound),*/} + {/* css`*/} + {/* border-width: 1px;*/} + {/* padding: 2px 6px;*/} + {/* margin-top: 15px;*/} + {/* margin-bottom: 10px;*/} + {/* border-color: ${style.reviewLike.buttonBorderColor};*/} + {/* color: ${style.reviewLike.textColor};*/} + {/* transition:*/} + {/* background-color 0.5s ease,*/} + {/* color 0.5s ease;*/} + {/* display: flex;*/} + + {/* &:hover {*/} + {/* background-color: ${style.reviewLike.textColor};*/} + {/* color: white;*/} + {/* }*/} + {/* `,*/} + {/* ]}*/} + {/* >*/} + {/* <ThumbUpIcon />*/} + {/* {style.reviewLike.buttonType === 'THUMB_UP_WITH_TEXT' ? <div className="ml-1">๋„์›€๋ผ์š”!</div> : null}*/} + {/* <div className="ml-1">0</div>*/} + {/* </button>*/} + {/*) : null}*/} + <button + css={[ + generateBorderRadiusCSS(style.reviewLike.buttonRound), + css` + border-width: 1px; + padding: 2px 6px; + margin-top: 15px; + margin-bottom: 10px; + border-color: ${style.reviewLike.buttonBorderColor}; + color: ${style.reviewLike.textColor}; + transition: + background-color 0.5s ease, + color 0.5s ease; + display: flex; + + &:hover { + background-color: ${style.reviewLike.textColor}; + color: white; + } + `, + ]} + onClick={createLike} + type="button" + > + {/*<ThumbUpIcon />*/} + <div className="ml-1">๋„์›€๋ผ์š”!</div> + <div className="ml-1">{count}</div> + </button> {userID === props.reviewerID ? ( // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions -- This is intentional <div
Unknown
๋ถˆํ•„์š”ํ•œ console์€ ์ œ์™ธํ•ด์ฃผ์„ธ์š”! ์ž์‹ ์˜ ๋ฆฌ๋ทฐ์—๋Š” ๋„์›€๋ผ์š” ๊ฐ™์€ ๊ฒฝ์šฐ๋Š” ์˜คํžˆ๋ ค alert์œผ๋กœ ๋ณด์—ฌ์ฃผ๋Š” ๊ฒŒ ๋‚ซ์ง€ ์•Š์„๊นŒ ์‹ถ๋„ค์š”
@@ -9,50 +9,55 @@ import { generateShadowCSS, } from '@review-canvas/theme'; +// import ThumbUpIcon from '@/assets/icon/icon-thumb-up.svg'; import { Star } from '@/components/review/star.tsx'; import { useReviewItemStyle } from '@/contexts/style/review-item.ts'; import useMessageToShop from '@/hooks/use-message-to-shop.ts'; -import type { ReplyItem } from '@/services/api-types/review'; +import type { ReviewItemProps } from '@/services/api-types/review'; +import { useReviewService } from '@/services/review.tsx'; import { useConnectedShop } from '@/state/shop.ts'; import { MESSAGE_TYPES } from '@/utils/message'; import Reply from './reply'; - -interface ReviewItemProps { - id: number; - rate: number; - content: string; - reviewerID: string; - reviewer: string; - replies: ReplyItem[]; -} +import { useEffect, useState } from 'react'; export default function ReviewItem(props: ReviewItemProps) { const style = useReviewItemStyle(); const { userID } = useConnectedShop(); + const reviewService = useReviewService(); const message = useMessageToShop(); + const [count, setCount] = useState(0); + + useEffect(() => { + async function fetchData() { + return reviewService.userReviewLike(props.id); + } + void fetchData().then((response) => { + setCount(response.data.count); + }); + }, [props.id, reviewService]); const edit = () => { message(MESSAGE_TYPES.OPEN_MODAL, { type: 'edit_review', url: `/reviews/${props.id}/edit`, }); }; - const deleteReview = () => { message(MESSAGE_TYPES.OPEN_SELECTING_MODAL, { type: 'delete', url: `/reviews/${props.id}/delete`, }); }; - const showReviewDetail = () => { message(MESSAGE_TYPES.OPEN_MODAL, { type: 'detail', url: `/reviews/${props.id}`, }); }; + const createLike = () => {}; + return ( <li css={[ @@ -63,6 +68,7 @@ export default function ReviewItem(props: ReviewItemProps) { generateFontCSS(style.font), generateShadowCSS(style.shadow, style.shadowColor), css` + border-color: ${style.borderColor}; background-color: ${style.backgroundColor}; display: flex; flex-direction: column; @@ -88,6 +94,68 @@ export default function ReviewItem(props: ReviewItemProps) { ์ž‘์„ฑ์ž <span>{props.reviewer}</span> </div> <p className="text-left">{props.content}</p> + {/*{style.reviewLike.buttonType !== 'NONE' ? (*/} + {/* <button*/} + {/* onClick={(evt) => {*/} + {/* evt.stopPropagation();*/} + {/* if (userID === props.reviewerID) {*/} + {/* return;*/} + {/* }*/} + {/* }}*/} + {/* css={[*/} + {/* generateBorderRadiusCSS(style.reviewLike.buttonRound),*/} + {/* css`*/} + {/* border-width: 1px;*/} + {/* padding: 2px 6px;*/} + {/* margin-top: 15px;*/} + {/* margin-bottom: 10px;*/} + {/* border-color: ${style.reviewLike.buttonBorderColor};*/} + {/* color: ${style.reviewLike.textColor};*/} + {/* transition:*/} + {/* background-color 0.5s ease,*/} + {/* color 0.5s ease;*/} + {/* display: flex;*/} + + {/* &:hover {*/} + {/* background-color: ${style.reviewLike.textColor};*/} + {/* color: white;*/} + {/* }*/} + {/* `,*/} + {/* ]}*/} + {/* >*/} + {/* <ThumbUpIcon />*/} + {/* {style.reviewLike.buttonType === 'THUMB_UP_WITH_TEXT' ? <div className="ml-1">๋„์›€๋ผ์š”!</div> : null}*/} + {/* <div className="ml-1">0</div>*/} + {/* </button>*/} + {/*) : null}*/} + <button + css={[ + generateBorderRadiusCSS(style.reviewLike.buttonRound), + css` + border-width: 1px; + padding: 2px 6px; + margin-top: 15px; + margin-bottom: 10px; + border-color: ${style.reviewLike.buttonBorderColor}; + color: ${style.reviewLike.textColor}; + transition: + background-color 0.5s ease, + color 0.5s ease; + display: flex; + + &:hover { + background-color: ${style.reviewLike.textColor}; + color: white; + } + `, + ]} + onClick={createLike} + type="button" + > + {/*<ThumbUpIcon />*/} + <div className="ml-1">๋„์›€๋ผ์š”!</div> + <div className="ml-1">{count}</div> + </button> {userID === props.reviewerID ? ( // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions -- This is intentional <div
Unknown
ts ignore๋Š” ํ˜น์‹œ ์™œ ์„ค์ •ํ•ด ๋†“์œผ์‹  ๊ฑธ๊นŒ์š”??
@@ -9,50 +9,55 @@ import { generateShadowCSS, } from '@review-canvas/theme'; +// import ThumbUpIcon from '@/assets/icon/icon-thumb-up.svg'; import { Star } from '@/components/review/star.tsx'; import { useReviewItemStyle } from '@/contexts/style/review-item.ts'; import useMessageToShop from '@/hooks/use-message-to-shop.ts'; -import type { ReplyItem } from '@/services/api-types/review'; +import type { ReviewItemProps } from '@/services/api-types/review'; +import { useReviewService } from '@/services/review.tsx'; import { useConnectedShop } from '@/state/shop.ts'; import { MESSAGE_TYPES } from '@/utils/message'; import Reply from './reply'; - -interface ReviewItemProps { - id: number; - rate: number; - content: string; - reviewerID: string; - reviewer: string; - replies: ReplyItem[]; -} +import { useEffect, useState } from 'react'; export default function ReviewItem(props: ReviewItemProps) { const style = useReviewItemStyle(); const { userID } = useConnectedShop(); + const reviewService = useReviewService(); const message = useMessageToShop(); + const [count, setCount] = useState(0); + + useEffect(() => { + async function fetchData() { + return reviewService.userReviewLike(props.id); + } + void fetchData().then((response) => { + setCount(response.data.count); + }); + }, [props.id, reviewService]); const edit = () => { message(MESSAGE_TYPES.OPEN_MODAL, { type: 'edit_review', url: `/reviews/${props.id}/edit`, }); }; - const deleteReview = () => { message(MESSAGE_TYPES.OPEN_SELECTING_MODAL, { type: 'delete', url: `/reviews/${props.id}/delete`, }); }; - const showReviewDetail = () => { message(MESSAGE_TYPES.OPEN_MODAL, { type: 'detail', url: `/reviews/${props.id}`, }); }; + const createLike = () => {}; + return ( <li css={[ @@ -63,6 +68,7 @@ export default function ReviewItem(props: ReviewItemProps) { generateFontCSS(style.font), generateShadowCSS(style.shadow, style.shadowColor), css` + border-color: ${style.borderColor}; background-color: ${style.backgroundColor}; display: flex; flex-direction: column; @@ -88,6 +94,68 @@ export default function ReviewItem(props: ReviewItemProps) { ์ž‘์„ฑ์ž <span>{props.reviewer}</span> </div> <p className="text-left">{props.content}</p> + {/*{style.reviewLike.buttonType !== 'NONE' ? (*/} + {/* <button*/} + {/* onClick={(evt) => {*/} + {/* evt.stopPropagation();*/} + {/* if (userID === props.reviewerID) {*/} + {/* return;*/} + {/* }*/} + {/* }}*/} + {/* css={[*/} + {/* generateBorderRadiusCSS(style.reviewLike.buttonRound),*/} + {/* css`*/} + {/* border-width: 1px;*/} + {/* padding: 2px 6px;*/} + {/* margin-top: 15px;*/} + {/* margin-bottom: 10px;*/} + {/* border-color: ${style.reviewLike.buttonBorderColor};*/} + {/* color: ${style.reviewLike.textColor};*/} + {/* transition:*/} + {/* background-color 0.5s ease,*/} + {/* color 0.5s ease;*/} + {/* display: flex;*/} + + {/* &:hover {*/} + {/* background-color: ${style.reviewLike.textColor};*/} + {/* color: white;*/} + {/* }*/} + {/* `,*/} + {/* ]}*/} + {/* >*/} + {/* <ThumbUpIcon />*/} + {/* {style.reviewLike.buttonType === 'THUMB_UP_WITH_TEXT' ? <div className="ml-1">๋„์›€๋ผ์š”!</div> : null}*/} + {/* <div className="ml-1">0</div>*/} + {/* </button>*/} + {/*) : null}*/} + <button + css={[ + generateBorderRadiusCSS(style.reviewLike.buttonRound), + css` + border-width: 1px; + padding: 2px 6px; + margin-top: 15px; + margin-bottom: 10px; + border-color: ${style.reviewLike.buttonBorderColor}; + color: ${style.reviewLike.textColor}; + transition: + background-color 0.5s ease, + color 0.5s ease; + display: flex; + + &:hover { + background-color: ${style.reviewLike.textColor}; + color: white; + } + `, + ]} + onClick={createLike} + type="button" + > + {/*<ThumbUpIcon />*/} + <div className="ml-1">๋„์›€๋ผ์š”!</div> + <div className="ml-1">{count}</div> + </button> {userID === props.reviewerID ? ( // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions -- This is intentional <div
Unknown
P3: interface ๊ฐ™์€ ๊ฒฝ์šฐ ๋‹ค๋ฅธ ๊ณณ์—์„œ๋„ ์—ฌ๋Ÿฌ ๊ณณ์—์„œ ์“ฐ์ผ ์ˆ˜ ์žˆ๋Š”๋ฐ, type ๋””๋ ‰ํ† ๋ฆฌ ๋“ฑ์— ๊ณตํ†ต์ ์ธ model์„ ์ •์˜ํ•ด๋†“๊ณ  extends ๋“ฑ์œผ๋กœ ๊ฐ€์ ธ์™€์„œ ์“ฐ๋Š” ๋ฐฉ์‹๋„ ๊ณ ๋ คํ•ด ๋ณผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ReviewItem์€ ์ƒ๋‹นํžˆ ๋งŽ์€ ๊ณณ์—์„œ ์“ฐ์ด๋Š” ์š”์†Œ๋กœ ์ƒ๊ฐ๋˜์„œ ์ฐธ๊ณ ํ•˜์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„ ๋‚จ๊น๋‹ˆ๋‹ค!
@@ -1,3 +1,5 @@ +import {ReviewLikeButtonProps} from "@review-canvas/theme"; + export type Shadow = 'NONE' | 'SMALL' | 'MEDIUM' | 'LARGE'; export type FocusAreaLayout = 'BEST_REVIEW_TOP' | 'BEST_REVIEW_BOTTOM' | 'BEST_REVIEW_LEFT' | 'BEST_REVIEW_RIGHT'; export type ReviewAreaLayout = 'REVIEW_TOP' | 'REVIEW_BOTTOM' | 'REVIEW_LEFT' | 'REVIEW_RIGHT'; @@ -6,6 +8,7 @@ export type AlignmentPosition = 'LEFT' | 'CENTER' | 'RIGHT'; export type DetailViewType = 'SPREAD' | 'MODAL'; export type PagingType = 'PAGE_NUMBER' | 'SEE_MORE_SCROLL'; export type FilterType = 'LIST' | 'DROPDOWN'; +export type ReviewLikeButtonType = 'NONE' | 'THUMB_UP_WITH_TEXT' | 'THUMB_UP'; export interface Margin { left: string; @@ -43,11 +46,11 @@ export interface Round { } export interface ReviewLike { - buttonType: string; - iconColor: string; - textColor: string; buttonBorderColor: string; buttonRound: Round; + buttonType: ReviewLikeButtonType; + iconColor: string; + textColor: string; } export interface ReviewLayout {
TypeScript
Plugin ์„ค์น˜๋ฅผ ํ•˜๋ฉด ์™„๋ฃŒ์ธ ์ค„ ์•Œ์•˜๋Š”๋ฐ ์„ค์ •์—์„œ Manually๋กœ ๋ฐ”๊พธ์–ด์ค˜์•ผ ํ–ˆ๊ตฐ์š”... ํ˜„์žฌ Prettier๋ฅผ ํ™œ์„ฑํ™” ์ƒํƒœ๋กœ ๋ณ€๊ฒฝํ•˜์˜€์Šต๋‹ˆ๋‹ค. ์ „์ฒด ํŒŒ์ผ์— ์ ์šฉํ•˜์—ฌ ๋‹ค์‹œ ์ปค๋ฐ‹ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -9,50 +9,55 @@ import { generateShadowCSS, } from '@review-canvas/theme'; +// import ThumbUpIcon from '@/assets/icon/icon-thumb-up.svg'; import { Star } from '@/components/review/star.tsx'; import { useReviewItemStyle } from '@/contexts/style/review-item.ts'; import useMessageToShop from '@/hooks/use-message-to-shop.ts'; -import type { ReplyItem } from '@/services/api-types/review'; +import type { ReviewItemProps } from '@/services/api-types/review'; +import { useReviewService } from '@/services/review.tsx'; import { useConnectedShop } from '@/state/shop.ts'; import { MESSAGE_TYPES } from '@/utils/message'; import Reply from './reply'; - -interface ReviewItemProps { - id: number; - rate: number; - content: string; - reviewerID: string; - reviewer: string; - replies: ReplyItem[]; -} +import { useEffect, useState } from 'react'; export default function ReviewItem(props: ReviewItemProps) { const style = useReviewItemStyle(); const { userID } = useConnectedShop(); + const reviewService = useReviewService(); const message = useMessageToShop(); + const [count, setCount] = useState(0); + + useEffect(() => { + async function fetchData() { + return reviewService.userReviewLike(props.id); + } + void fetchData().then((response) => { + setCount(response.data.count); + }); + }, [props.id, reviewService]); const edit = () => { message(MESSAGE_TYPES.OPEN_MODAL, { type: 'edit_review', url: `/reviews/${props.id}/edit`, }); }; - const deleteReview = () => { message(MESSAGE_TYPES.OPEN_SELECTING_MODAL, { type: 'delete', url: `/reviews/${props.id}/delete`, }); }; - const showReviewDetail = () => { message(MESSAGE_TYPES.OPEN_MODAL, { type: 'detail', url: `/reviews/${props.id}`, }); }; + const createLike = () => {}; + return ( <li css={[ @@ -63,6 +68,7 @@ export default function ReviewItem(props: ReviewItemProps) { generateFontCSS(style.font), generateShadowCSS(style.shadow, style.shadowColor), css` + border-color: ${style.borderColor}; background-color: ${style.backgroundColor}; display: flex; flex-direction: column; @@ -88,6 +94,68 @@ export default function ReviewItem(props: ReviewItemProps) { ์ž‘์„ฑ์ž <span>{props.reviewer}</span> </div> <p className="text-left">{props.content}</p> + {/*{style.reviewLike.buttonType !== 'NONE' ? (*/} + {/* <button*/} + {/* onClick={(evt) => {*/} + {/* evt.stopPropagation();*/} + {/* if (userID === props.reviewerID) {*/} + {/* return;*/} + {/* }*/} + {/* }}*/} + {/* css={[*/} + {/* generateBorderRadiusCSS(style.reviewLike.buttonRound),*/} + {/* css`*/} + {/* border-width: 1px;*/} + {/* padding: 2px 6px;*/} + {/* margin-top: 15px;*/} + {/* margin-bottom: 10px;*/} + {/* border-color: ${style.reviewLike.buttonBorderColor};*/} + {/* color: ${style.reviewLike.textColor};*/} + {/* transition:*/} + {/* background-color 0.5s ease,*/} + {/* color 0.5s ease;*/} + {/* display: flex;*/} + + {/* &:hover {*/} + {/* background-color: ${style.reviewLike.textColor};*/} + {/* color: white;*/} + {/* }*/} + {/* `,*/} + {/* ]}*/} + {/* >*/} + {/* <ThumbUpIcon />*/} + {/* {style.reviewLike.buttonType === 'THUMB_UP_WITH_TEXT' ? <div className="ml-1">๋„์›€๋ผ์š”!</div> : null}*/} + {/* <div className="ml-1">0</div>*/} + {/* </button>*/} + {/*) : null}*/} + <button + css={[ + generateBorderRadiusCSS(style.reviewLike.buttonRound), + css` + border-width: 1px; + padding: 2px 6px; + margin-top: 15px; + margin-bottom: 10px; + border-color: ${style.reviewLike.buttonBorderColor}; + color: ${style.reviewLike.textColor}; + transition: + background-color 0.5s ease, + color 0.5s ease; + display: flex; + + &:hover { + background-color: ${style.reviewLike.textColor}; + color: white; + } + `, + ]} + onClick={createLike} + type="button" + > + {/*<ThumbUpIcon />*/} + <div className="ml-1">๋„์›€๋ผ์š”!</div> + <div className="ml-1">{count}</div> + </button> {userID === props.reviewerID ? ( // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions -- This is intentional <div
Unknown
ํ™•์ธํ•˜์˜€์Šต๋‹ˆ๋‹ค, Alert๋กœ ๋ณ€๊ฒฝํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค, ๋„์›€๋ผ์š”!์˜ ๊ฒฝ์šฐ์—๋Š” ๋ฒ„ํŠผ์ด ์ œ๋Œ€๋กœ ๋™์ž‘ํ•˜๋Š” ๊ฒƒ์„ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด ์ž„์‹œ๋กœ ๋„ฃ์–ด๋‘๊ณ  ๋‚˜์ค‘์— ๋„์›€๋ผ์š” API๊ฐ€ ๋ฐฑ์—”๋“œ์—์„œ ๊ตฌํ˜„๋˜๋ฉด ๋กœ์ง์œผ๋กœ ๋Œ€์ฒดํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -9,50 +9,55 @@ import { generateShadowCSS, } from '@review-canvas/theme'; +// import ThumbUpIcon from '@/assets/icon/icon-thumb-up.svg'; import { Star } from '@/components/review/star.tsx'; import { useReviewItemStyle } from '@/contexts/style/review-item.ts'; import useMessageToShop from '@/hooks/use-message-to-shop.ts'; -import type { ReplyItem } from '@/services/api-types/review'; +import type { ReviewItemProps } from '@/services/api-types/review'; +import { useReviewService } from '@/services/review.tsx'; import { useConnectedShop } from '@/state/shop.ts'; import { MESSAGE_TYPES } from '@/utils/message'; import Reply from './reply'; - -interface ReviewItemProps { - id: number; - rate: number; - content: string; - reviewerID: string; - reviewer: string; - replies: ReplyItem[]; -} +import { useEffect, useState } from 'react'; export default function ReviewItem(props: ReviewItemProps) { const style = useReviewItemStyle(); const { userID } = useConnectedShop(); + const reviewService = useReviewService(); const message = useMessageToShop(); + const [count, setCount] = useState(0); + + useEffect(() => { + async function fetchData() { + return reviewService.userReviewLike(props.id); + } + void fetchData().then((response) => { + setCount(response.data.count); + }); + }, [props.id, reviewService]); const edit = () => { message(MESSAGE_TYPES.OPEN_MODAL, { type: 'edit_review', url: `/reviews/${props.id}/edit`, }); }; - const deleteReview = () => { message(MESSAGE_TYPES.OPEN_SELECTING_MODAL, { type: 'delete', url: `/reviews/${props.id}/delete`, }); }; - const showReviewDetail = () => { message(MESSAGE_TYPES.OPEN_MODAL, { type: 'detail', url: `/reviews/${props.id}`, }); }; + const createLike = () => {}; + return ( <li css={[ @@ -63,6 +68,7 @@ export default function ReviewItem(props: ReviewItemProps) { generateFontCSS(style.font), generateShadowCSS(style.shadow, style.shadowColor), css` + border-color: ${style.borderColor}; background-color: ${style.backgroundColor}; display: flex; flex-direction: column; @@ -88,6 +94,68 @@ export default function ReviewItem(props: ReviewItemProps) { ์ž‘์„ฑ์ž <span>{props.reviewer}</span> </div> <p className="text-left">{props.content}</p> + {/*{style.reviewLike.buttonType !== 'NONE' ? (*/} + {/* <button*/} + {/* onClick={(evt) => {*/} + {/* evt.stopPropagation();*/} + {/* if (userID === props.reviewerID) {*/} + {/* return;*/} + {/* }*/} + {/* }}*/} + {/* css={[*/} + {/* generateBorderRadiusCSS(style.reviewLike.buttonRound),*/} + {/* css`*/} + {/* border-width: 1px;*/} + {/* padding: 2px 6px;*/} + {/* margin-top: 15px;*/} + {/* margin-bottom: 10px;*/} + {/* border-color: ${style.reviewLike.buttonBorderColor};*/} + {/* color: ${style.reviewLike.textColor};*/} + {/* transition:*/} + {/* background-color 0.5s ease,*/} + {/* color 0.5s ease;*/} + {/* display: flex;*/} + + {/* &:hover {*/} + {/* background-color: ${style.reviewLike.textColor};*/} + {/* color: white;*/} + {/* }*/} + {/* `,*/} + {/* ]}*/} + {/* >*/} + {/* <ThumbUpIcon />*/} + {/* {style.reviewLike.buttonType === 'THUMB_UP_WITH_TEXT' ? <div className="ml-1">๋„์›€๋ผ์š”!</div> : null}*/} + {/* <div className="ml-1">0</div>*/} + {/* </button>*/} + {/*) : null}*/} + <button + css={[ + generateBorderRadiusCSS(style.reviewLike.buttonRound), + css` + border-width: 1px; + padding: 2px 6px; + margin-top: 15px; + margin-bottom: 10px; + border-color: ${style.reviewLike.buttonBorderColor}; + color: ${style.reviewLike.textColor}; + transition: + background-color 0.5s ease, + color 0.5s ease; + display: flex; + + &:hover { + background-color: ${style.reviewLike.textColor}; + color: white; + } + `, + ]} + onClick={createLike} + type="button" + > + {/*<ThumbUpIcon />*/} + <div className="ml-1">๋„์›€๋ผ์š”!</div> + <div className="ml-1">{count}</div> + </button> {userID === props.reviewerID ? ( // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions -- This is intentional <div
Unknown
ํ™•์ธํ•˜์˜€์Šต๋‹ˆ๋‹ค, Import๋กœ ๋Œ€์ฒดํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -9,50 +9,55 @@ import { generateShadowCSS, } from '@review-canvas/theme'; +// import ThumbUpIcon from '@/assets/icon/icon-thumb-up.svg'; import { Star } from '@/components/review/star.tsx'; import { useReviewItemStyle } from '@/contexts/style/review-item.ts'; import useMessageToShop from '@/hooks/use-message-to-shop.ts'; -import type { ReplyItem } from '@/services/api-types/review'; +import type { ReviewItemProps } from '@/services/api-types/review'; +import { useReviewService } from '@/services/review.tsx'; import { useConnectedShop } from '@/state/shop.ts'; import { MESSAGE_TYPES } from '@/utils/message'; import Reply from './reply'; - -interface ReviewItemProps { - id: number; - rate: number; - content: string; - reviewerID: string; - reviewer: string; - replies: ReplyItem[]; -} +import { useEffect, useState } from 'react'; export default function ReviewItem(props: ReviewItemProps) { const style = useReviewItemStyle(); const { userID } = useConnectedShop(); + const reviewService = useReviewService(); const message = useMessageToShop(); + const [count, setCount] = useState(0); + + useEffect(() => { + async function fetchData() { + return reviewService.userReviewLike(props.id); + } + void fetchData().then((response) => { + setCount(response.data.count); + }); + }, [props.id, reviewService]); const edit = () => { message(MESSAGE_TYPES.OPEN_MODAL, { type: 'edit_review', url: `/reviews/${props.id}/edit`, }); }; - const deleteReview = () => { message(MESSAGE_TYPES.OPEN_SELECTING_MODAL, { type: 'delete', url: `/reviews/${props.id}/delete`, }); }; - const showReviewDetail = () => { message(MESSAGE_TYPES.OPEN_MODAL, { type: 'detail', url: `/reviews/${props.id}`, }); }; + const createLike = () => {}; + return ( <li css={[ @@ -63,6 +68,7 @@ export default function ReviewItem(props: ReviewItemProps) { generateFontCSS(style.font), generateShadowCSS(style.shadow, style.shadowColor), css` + border-color: ${style.borderColor}; background-color: ${style.backgroundColor}; display: flex; flex-direction: column; @@ -88,6 +94,68 @@ export default function ReviewItem(props: ReviewItemProps) { ์ž‘์„ฑ์ž <span>{props.reviewer}</span> </div> <p className="text-left">{props.content}</p> + {/*{style.reviewLike.buttonType !== 'NONE' ? (*/} + {/* <button*/} + {/* onClick={(evt) => {*/} + {/* evt.stopPropagation();*/} + {/* if (userID === props.reviewerID) {*/} + {/* return;*/} + {/* }*/} + {/* }}*/} + {/* css={[*/} + {/* generateBorderRadiusCSS(style.reviewLike.buttonRound),*/} + {/* css`*/} + {/* border-width: 1px;*/} + {/* padding: 2px 6px;*/} + {/* margin-top: 15px;*/} + {/* margin-bottom: 10px;*/} + {/* border-color: ${style.reviewLike.buttonBorderColor};*/} + {/* color: ${style.reviewLike.textColor};*/} + {/* transition:*/} + {/* background-color 0.5s ease,*/} + {/* color 0.5s ease;*/} + {/* display: flex;*/} + + {/* &:hover {*/} + {/* background-color: ${style.reviewLike.textColor};*/} + {/* color: white;*/} + {/* }*/} + {/* `,*/} + {/* ]}*/} + {/* >*/} + {/* <ThumbUpIcon />*/} + {/* {style.reviewLike.buttonType === 'THUMB_UP_WITH_TEXT' ? <div className="ml-1">๋„์›€๋ผ์š”!</div> : null}*/} + {/* <div className="ml-1">0</div>*/} + {/* </button>*/} + {/*) : null}*/} + <button + css={[ + generateBorderRadiusCSS(style.reviewLike.buttonRound), + css` + border-width: 1px; + padding: 2px 6px; + margin-top: 15px; + margin-bottom: 10px; + border-color: ${style.reviewLike.buttonBorderColor}; + color: ${style.reviewLike.textColor}; + transition: + background-color 0.5s ease, + color 0.5s ease; + display: flex; + + &:hover { + background-color: ${style.reviewLike.textColor}; + color: white; + } + `, + ]} + onClick={createLike} + type="button" + > + {/*<ThumbUpIcon />*/} + <div className="ml-1">๋„์›€๋ผ์š”!</div> + <div className="ml-1">{count}</div> + </button> {userID === props.reviewerID ? ( // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions -- This is intentional <div
Unknown
ํ…Œ์ŠคํŠธ๋ฅผ ํ•  ๋•Œ ReviewLikeButton์ด 'None'์œผ๋กœ ๊ณ ์ •์ด๋ผ ํ•˜๋“œ์ฝ”๋”ฉ์œผ๋กœ ReviewLikeButton์„ ๋ฐ”๊พธ๊ณ  ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค. ๊ทธ ๊ณผ์ •์—์„œ ์กฐ๊ฑด๋ฌธ ๊ฒฝ๊ณ ๊ฐ€ ๋ฐœ์ƒํ•˜์—ฌ ์„ค์ •ํ•ด๋‘์—ˆ๋Š”๋ฐ ํ•˜๋“œ์ฝ”๋”ฉ๋งŒ ์ง€์šฐ๊ณ  ์ด๊ทธ๋…ธ์–ด๋ฅผ ๋ชป ์ง€์› ๋„ค์š”... ์ง€์›Œ์„œ ๋ฐ˜์˜ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -9,50 +9,55 @@ import { generateShadowCSS, } from '@review-canvas/theme'; +// import ThumbUpIcon from '@/assets/icon/icon-thumb-up.svg'; import { Star } from '@/components/review/star.tsx'; import { useReviewItemStyle } from '@/contexts/style/review-item.ts'; import useMessageToShop from '@/hooks/use-message-to-shop.ts'; -import type { ReplyItem } from '@/services/api-types/review'; +import type { ReviewItemProps } from '@/services/api-types/review'; +import { useReviewService } from '@/services/review.tsx'; import { useConnectedShop } from '@/state/shop.ts'; import { MESSAGE_TYPES } from '@/utils/message'; import Reply from './reply'; - -interface ReviewItemProps { - id: number; - rate: number; - content: string; - reviewerID: string; - reviewer: string; - replies: ReplyItem[]; -} +import { useEffect, useState } from 'react'; export default function ReviewItem(props: ReviewItemProps) { const style = useReviewItemStyle(); const { userID } = useConnectedShop(); + const reviewService = useReviewService(); const message = useMessageToShop(); + const [count, setCount] = useState(0); + + useEffect(() => { + async function fetchData() { + return reviewService.userReviewLike(props.id); + } + void fetchData().then((response) => { + setCount(response.data.count); + }); + }, [props.id, reviewService]); const edit = () => { message(MESSAGE_TYPES.OPEN_MODAL, { type: 'edit_review', url: `/reviews/${props.id}/edit`, }); }; - const deleteReview = () => { message(MESSAGE_TYPES.OPEN_SELECTING_MODAL, { type: 'delete', url: `/reviews/${props.id}/delete`, }); }; - const showReviewDetail = () => { message(MESSAGE_TYPES.OPEN_MODAL, { type: 'detail', url: `/reviews/${props.id}`, }); }; + const createLike = () => {}; + return ( <li css={[ @@ -63,6 +68,7 @@ export default function ReviewItem(props: ReviewItemProps) { generateFontCSS(style.font), generateShadowCSS(style.shadow, style.shadowColor), css` + border-color: ${style.borderColor}; background-color: ${style.backgroundColor}; display: flex; flex-direction: column; @@ -88,6 +94,68 @@ export default function ReviewItem(props: ReviewItemProps) { ์ž‘์„ฑ์ž <span>{props.reviewer}</span> </div> <p className="text-left">{props.content}</p> + {/*{style.reviewLike.buttonType !== 'NONE' ? (*/} + {/* <button*/} + {/* onClick={(evt) => {*/} + {/* evt.stopPropagation();*/} + {/* if (userID === props.reviewerID) {*/} + {/* return;*/} + {/* }*/} + {/* }}*/} + {/* css={[*/} + {/* generateBorderRadiusCSS(style.reviewLike.buttonRound),*/} + {/* css`*/} + {/* border-width: 1px;*/} + {/* padding: 2px 6px;*/} + {/* margin-top: 15px;*/} + {/* margin-bottom: 10px;*/} + {/* border-color: ${style.reviewLike.buttonBorderColor};*/} + {/* color: ${style.reviewLike.textColor};*/} + {/* transition:*/} + {/* background-color 0.5s ease,*/} + {/* color 0.5s ease;*/} + {/* display: flex;*/} + + {/* &:hover {*/} + {/* background-color: ${style.reviewLike.textColor};*/} + {/* color: white;*/} + {/* }*/} + {/* `,*/} + {/* ]}*/} + {/* >*/} + {/* <ThumbUpIcon />*/} + {/* {style.reviewLike.buttonType === 'THUMB_UP_WITH_TEXT' ? <div className="ml-1">๋„์›€๋ผ์š”!</div> : null}*/} + {/* <div className="ml-1">0</div>*/} + {/* </button>*/} + {/*) : null}*/} + <button + css={[ + generateBorderRadiusCSS(style.reviewLike.buttonRound), + css` + border-width: 1px; + padding: 2px 6px; + margin-top: 15px; + margin-bottom: 10px; + border-color: ${style.reviewLike.buttonBorderColor}; + color: ${style.reviewLike.textColor}; + transition: + background-color 0.5s ease, + color 0.5s ease; + display: flex; + + &:hover { + background-color: ${style.reviewLike.textColor}; + color: white; + } + `, + ]} + onClick={createLike} + type="button" + > + {/*<ThumbUpIcon />*/} + <div className="ml-1">๋„์›€๋ผ์š”!</div> + <div className="ml-1">{count}</div> + </button> {userID === props.reviewerID ? ( // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions -- This is intentional <div
Unknown
service/api-types/review.tsx์— ๊ณตํ†ต ๋ชจ๋ธ๋กœ ์„ ์–ธํ•˜์—ฌ export ๋ฐ import ํ•˜์˜€์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,18 @@ +package com.codesquad.baseball09.controller; + +import java.text.SimpleDateFormat; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("hcheck") +public class HealthCheckRestController { + + private final static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + @GetMapping + public String healthCheck() { + return dateFormat.format(System.currentTimeMillis()); + } +}
Java
Spring Boot Actuator ์‚ฌ์šฉ ๊ฒ€ํ† ํ•ด๋ด…๋‹ˆ๋‹ค. https://supawer0728.github.io/2018/05/12/spring-actuator/
@@ -0,0 +1,99 @@ +package com.codesquad.baseball09.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.apache.commons.lang3.builder.ToStringBuilder; + +public class BattingLog { + + private Long id; + private Long gameId; + private Long playerId; + private int inning; + private Status status; + + private BattingLog(Long id, Long gameId, Long playerId, int inning, + Status status) { + this.id = id; + this.gameId = gameId; + this.playerId = playerId; + this.inning = inning; + this.status = status; + } + + public Long getId() { + return id; + } + + public Long getGameId() { + return gameId; + } + + public Long getPlayerId() { + return playerId; + } + + public int getInning() { + return inning; + } + + public Status getStatus() { + return status; + } + + @JsonIgnore + public int getStatusInt() { + return status.getValue(); + } + + public static class Builder { + + private Long id; + private Long gameId; + private Long playerId; + private int inning; + private Status status; + + public Builder() { + } + + public Builder id(Long id) { + this.id = id; + return this; + } + + public Builder gameId(Long gameId) { + this.gameId = gameId; + return this; + } + + public Builder playerId(Long playerId) { + this.playerId = playerId; + return this; + } + + public Builder inning(int inning) { + this.inning = inning; + return this; + } + + public Builder status(int value) { + this.status = Status.of(value); + return this; + } + + public BattingLog build() { + return new BattingLog(id, gameId, playerId, inning, status); + } + } + + @Override + public String toString() { + return new ToStringBuilder(this) + .append("id", id) + .append("gameId", gameId) + .append("playerId", playerId) + .append("inning", inning) + .append("status", status) + .toString(); + } +}
Java
์ ์ ˆํ•œ builder ์‚ฌ์šฉ ์ข‹๋„ค์š”. ๐Ÿ‘
@@ -0,0 +1,282 @@ +package com.codesquad.baseball09.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import java.util.List; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class Board { + + private Long gameId; + private int inning; + + @JsonIgnore + private Long homeId; + private String homeName; + private int homeScore; + @JsonIgnore + private int homeOrder; + + @JsonIgnore + private Long awayId; + private String awayName; + private int awayScore; + @JsonIgnore + private int awayOrder; + + private boolean isBottom; + + private Game game; + private InningStatus status; + private List<BattingLog> log; + + private Board(Long gameId, int inning, Long homeId, String homeName, int homeScore, int homeOrder, + Long awayId, String awayName, int awayScore, int awayOrder, boolean isBottom, Game game, + InningStatus status, + List<BattingLog> log) { + this.gameId = gameId; + this.inning = inning; + this.homeId = homeId; + this.homeName = homeName; + this.homeScore = homeScore; + this.homeOrder = homeOrder; + this.awayId = awayId; + this.awayName = awayName; + this.awayScore = awayScore; + this.awayOrder = awayOrder; + this.isBottom = isBottom; + this.game = game; + this.status = status; + this.log = log; + } + + public void change() { + this.homeOrder = 0; + this.awayOrder = 0; + + if (isBottom) { + isBottom = false; + this.inning++; + } else { + isBottom = true; + } + } + + public Long getGameId() { + return gameId; + } + + public int getInning() { + return inning; + } + + public Long getHomeId() { + return homeId; + } + + public String getHomeName() { + return homeName; + } + + public int getHomeScore() { + return homeScore; + } + + public int getHomeOrder() { + return homeOrder; + } + + public Long getAwayId() { + return awayId; + } + + public String getAwayName() { + return awayName; + } + + public int getAwayScore() { + return awayScore; + } + + public int getAwayOrder() { + return awayOrder; + } + + public boolean isBottom() { + return isBottom; + } + + public Game getGame() { + return game; + } + + public InningStatus getStatus() { + return status; + } + + public List<BattingLog> getLog() { + return log; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) + .append("gameId", gameId) + .append("inning", inning) + .append("homeId", homeId) + .append("homeName", homeName) + .append("homeScore", homeScore) + .append("homeOrder", homeOrder) + .append("awayId", awayId) + .append("awayName", awayName) + .append("awayScore", awayScore) + .append("awayOrder", awayOrder) + .append("isBottom", isBottom) + .append("game", game) + .append("status", status) + .append("log", log) + .toString(); + } + + public static final class Builder { + + private Long gameId; + private int inning; + private String homeName; + private Long homeId; + private int homeScore; + private int homeOrder; + private Long awayId; + private String awayName; + private int awayScore; + private int awayOrder; + private boolean isBottom; + private Game game; + private InningStatus status; + private List<BattingLog> log; + + private Builder() { + } + + public static Builder of() { + return new Builder(); + } + + public Builder(Board board) { + this.gameId = board.gameId; + this.inning = board.inning; + this.homeId = board.homeId; + this.homeName = board.homeName; + this.homeScore = board.homeScore; + this.homeOrder = board.homeOrder; + this.awayId = board.awayId; + this.awayName = board.awayName; + this.awayScore = board.awayScore; + this.awayOrder = board.awayOrder; + this.isBottom = board.isBottom; + this.game = board.game; + this.status = board.status; + this.log = board.log; + } + + public Builder gameId(Long gameId) { + this.gameId = gameId; + return this; + } + + public Builder inning(int inning) { + this.inning = inning; + return this; + } + + public Builder homeId(Long homeId) { + this.homeId = homeId; + return this; + } + + public Builder homeName(String homeName) { + this.homeName = homeName; + return this; + } + + public Builder homeScore(int homeScore) { + this.homeScore = homeScore; + return this; + } + + public Builder homeOrder(int homeOrder) { + if (homeOrder > 8) { + this.homeOrder = 0; + } else { + this.homeOrder = homeOrder; + } + return this; + } + + public Builder awayId(Long awayId) { + this.awayId = awayId; + return this; + } + + public Builder awayName(String awayName) { + this.awayName = awayName; + return this; + } + + public Builder awayScore(int awayScore) { + this.awayScore = awayScore; + return this; + } + + public Builder awayOrder(int awayOrder) { + if (awayOrder > 8) { + this.awayOrder = 0; + } else { + this.awayOrder = awayOrder; + } + return this; + } + + public Builder isBottom(boolean isBottom) { + this.isBottom = isBottom; + return this; + } + + public Builder game(Game game) { + this.game = game; + this.homeId(game.getHomeTeamId()); + this.awayId(game.getAwayTeamId()); + return this; + } + + public Builder status(InningStatus status) { + this.status = status; + return this; + } + + public Builder score(List<Score> scores) { + for (int i = 0; i < scores.size(); i++) { + Score score = scores.get(i); + if (score.getTeamId().equals(homeId)) { + homeName(score.getName()); + homeScore(score.getScore()); + } + if (score.getTeamId().equals(awayId)) { + awayName(score.getName()); + awayScore(score.getScore()); + } + } + return this; + } + + public Builder log(List<BattingLog> log) { + this.log = log; + return this; + } + + public Board build() { + return new Board(gameId, inning, homeId, homeName, homeScore, homeOrder, awayId, awayName, + awayScore, awayOrder, isBottom, game, status, log); + } + } +}
Java
์ธ์ž๊ฐ€ ๋งŽ์ด ํ•„์š”ํ•œ ์ƒ์„ฑ์ž๋ฅผ `private` ํ•˜๊ฒŒ ๊ฐ€๋ฆฌ๋Š” ๊ตฌํ˜„ ์•„์ฃผ ์ข‹์Šต๋‹ˆ๋‹ค! ๐Ÿ’ฏ ๐Ÿฅ‡
@@ -0,0 +1,282 @@ +package com.codesquad.baseball09.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import java.util.List; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class Board { + + private Long gameId; + private int inning; + + @JsonIgnore + private Long homeId; + private String homeName; + private int homeScore; + @JsonIgnore + private int homeOrder; + + @JsonIgnore + private Long awayId; + private String awayName; + private int awayScore; + @JsonIgnore + private int awayOrder; + + private boolean isBottom; + + private Game game; + private InningStatus status; + private List<BattingLog> log; + + private Board(Long gameId, int inning, Long homeId, String homeName, int homeScore, int homeOrder, + Long awayId, String awayName, int awayScore, int awayOrder, boolean isBottom, Game game, + InningStatus status, + List<BattingLog> log) { + this.gameId = gameId; + this.inning = inning; + this.homeId = homeId; + this.homeName = homeName; + this.homeScore = homeScore; + this.homeOrder = homeOrder; + this.awayId = awayId; + this.awayName = awayName; + this.awayScore = awayScore; + this.awayOrder = awayOrder; + this.isBottom = isBottom; + this.game = game; + this.status = status; + this.log = log; + } + + public void change() { + this.homeOrder = 0; + this.awayOrder = 0; + + if (isBottom) { + isBottom = false; + this.inning++; + } else { + isBottom = true; + } + } + + public Long getGameId() { + return gameId; + } + + public int getInning() { + return inning; + } + + public Long getHomeId() { + return homeId; + } + + public String getHomeName() { + return homeName; + } + + public int getHomeScore() { + return homeScore; + } + + public int getHomeOrder() { + return homeOrder; + } + + public Long getAwayId() { + return awayId; + } + + public String getAwayName() { + return awayName; + } + + public int getAwayScore() { + return awayScore; + } + + public int getAwayOrder() { + return awayOrder; + } + + public boolean isBottom() { + return isBottom; + } + + public Game getGame() { + return game; + } + + public InningStatus getStatus() { + return status; + } + + public List<BattingLog> getLog() { + return log; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) + .append("gameId", gameId) + .append("inning", inning) + .append("homeId", homeId) + .append("homeName", homeName) + .append("homeScore", homeScore) + .append("homeOrder", homeOrder) + .append("awayId", awayId) + .append("awayName", awayName) + .append("awayScore", awayScore) + .append("awayOrder", awayOrder) + .append("isBottom", isBottom) + .append("game", game) + .append("status", status) + .append("log", log) + .toString(); + } + + public static final class Builder { + + private Long gameId; + private int inning; + private String homeName; + private Long homeId; + private int homeScore; + private int homeOrder; + private Long awayId; + private String awayName; + private int awayScore; + private int awayOrder; + private boolean isBottom; + private Game game; + private InningStatus status; + private List<BattingLog> log; + + private Builder() { + } + + public static Builder of() { + return new Builder(); + } + + public Builder(Board board) { + this.gameId = board.gameId; + this.inning = board.inning; + this.homeId = board.homeId; + this.homeName = board.homeName; + this.homeScore = board.homeScore; + this.homeOrder = board.homeOrder; + this.awayId = board.awayId; + this.awayName = board.awayName; + this.awayScore = board.awayScore; + this.awayOrder = board.awayOrder; + this.isBottom = board.isBottom; + this.game = board.game; + this.status = board.status; + this.log = board.log; + } + + public Builder gameId(Long gameId) { + this.gameId = gameId; + return this; + } + + public Builder inning(int inning) { + this.inning = inning; + return this; + } + + public Builder homeId(Long homeId) { + this.homeId = homeId; + return this; + } + + public Builder homeName(String homeName) { + this.homeName = homeName; + return this; + } + + public Builder homeScore(int homeScore) { + this.homeScore = homeScore; + return this; + } + + public Builder homeOrder(int homeOrder) { + if (homeOrder > 8) { + this.homeOrder = 0; + } else { + this.homeOrder = homeOrder; + } + return this; + } + + public Builder awayId(Long awayId) { + this.awayId = awayId; + return this; + } + + public Builder awayName(String awayName) { + this.awayName = awayName; + return this; + } + + public Builder awayScore(int awayScore) { + this.awayScore = awayScore; + return this; + } + + public Builder awayOrder(int awayOrder) { + if (awayOrder > 8) { + this.awayOrder = 0; + } else { + this.awayOrder = awayOrder; + } + return this; + } + + public Builder isBottom(boolean isBottom) { + this.isBottom = isBottom; + return this; + } + + public Builder game(Game game) { + this.game = game; + this.homeId(game.getHomeTeamId()); + this.awayId(game.getAwayTeamId()); + return this; + } + + public Builder status(InningStatus status) { + this.status = status; + return this; + } + + public Builder score(List<Score> scores) { + for (int i = 0; i < scores.size(); i++) { + Score score = scores.get(i); + if (score.getTeamId().equals(homeId)) { + homeName(score.getName()); + homeScore(score.getScore()); + } + if (score.getTeamId().equals(awayId)) { + awayName(score.getName()); + awayScore(score.getScore()); + } + } + return this; + } + + public Builder log(List<BattingLog> log) { + this.log = log; + return this; + } + + public Board build() { + return new Board(gameId, inning, homeId, homeName, homeScore, homeOrder, awayId, awayName, + awayScore, awayOrder, isBottom, game, status, log); + } + } +}
Java
`else` ์—†์ด ๊ตฌํ˜„ํ•ด๋ณผ ์ˆ˜ ์žˆ์ง€ ์•Š์•˜์„๊นŒ์š”?
@@ -0,0 +1,196 @@ +package com.codesquad.baseball09.model; + +import static com.codesquad.baseball09.model.Status.BALL; +import static com.codesquad.baseball09.model.Status.HIT; +import static com.codesquad.baseball09.model.Status.OUT; +import static com.codesquad.baseball09.model.Status.STRIKE; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +public class InningStatus { + + @JsonIgnore + private Long id; + private Long gameId; + private int inning; + private int strike; + private int ball; + private int out; + private int hit; + + public InningStatus(Long id, Long gameId, int inning, int strike, int ball, int out, int hit) { + this.id = id; + this.gameId = gameId; + this.inning = inning; + this.strike = strike; + this.ball = ball; + this.out = out; + this.hit = hit; + } + + private InningStatus(Long gameId, int inning, int strike, int ball, int out, int hit) { + this.gameId = gameId; + this.inning = inning; + this.strike = strike; + this.ball = ball; + this.out = out; + this.hit = hit; + } + + public InningStatus(int strike, int ball, int out, int hit) { + this.strike = strike; + this.ball = ball; + this.out = out; + this.hit = hit; + } + + public static InningStatus of(Long gameId, int inning, int strike, int ball, int out, int hit) { + return new InningStatus(gameId, inning, strike, ball, out, hit); + } + + public int plus(Status status) { + int value = 0; + + if (STRIKE.equals(status)) { + strike++; + value = checkThreeStrike(); + } else if (BALL.equals(status)) { + ball++; + value = checkFourBall(); + } else if (OUT.equals(status)) { + out++; + resetStrikeAndBall(); + value = checkThreeOut(); + } else if (HIT.equals(status)) { + hit++; + resetStrikeAndBall(); + value = checkFourHit(); + } + return value; + } + + private void resetStrikeAndBall() { + this.strike = 0; + this.ball = 0; + } + + private void resetAll() { + resetStrikeAndBall(); + this.out = 0; + this.hit = 0; + } + + private int checkFourHit() { + if (this.hit == 4) { + resetStrikeAndBall(); + this.hit--; + return 1; + } + return 0; + } + + private int checkThreeOut() { + if (this.out == 3) { + resetAll(); + return -1; + } + return 0; + } + + private int checkFourBall() { + if (this.ball == 4) { + resetStrikeAndBall(); + plus(HIT); + } + return 2; + } + + private int checkThreeStrike() { + if (this.strike == 3) { + resetStrikeAndBall(); + plus(OUT); + } + return 2; + } + + public Long getId() { + return id; + } + + public Long getGameId() { + return gameId; + } + + public int getInning() { + return inning; + } + + public int getStrike() { + return strike; + } + + public int getBall() { + return ball; + } + + public int getOut() { + return out; + } + + public int getHit() { + return hit; + } + + public static final class Builder { + + private Long id; + private Long gameId; + private int inning; + private int strike; + private int ball; + private int out; + private int hit; + + public Builder() { + } + + public Builder id(Long id) { + this.id = id; + return this; + } + + public Builder gameId(Long gameId) { + this.gameId = gameId; + return this; + } + + public Builder inning(int inning) { + this.inning = inning; + return this; + } + + public Builder strike(int strike) { + this.strike = strike; + return this; + } + + public Builder ball(int ball) { + this.ball = ball; + return this; + } + + public Builder out(int out) { + this.out = out; + return this; + } + + public Builder hit(int hit) { + this.hit = hit; + return this; + } + + public InningStatus build() { + return new InningStatus(id, gameId, inning, strike, ball, out, hit); + } + } +}
Java
๋„ค ๊ฐœ์˜ ํ–‰์œ„์— ๋Œ€ํ•ด ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜์˜ํ•ด์•ผ ํ•˜๋‹ค ๋ณด๋‹ˆ, ๋„ค ๊ฐœ์˜ `case` ๋ฅผ ๊ฐ–๋Š” `switch` ๋ฌธ๊ณผ ๊ฐ™์€ ๊ตฌํ˜„์ด ๋‚˜์˜ค๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ด๋ฅผ ์–ด๋–ป๊ฒŒ ๊ฐ์ฒด์ง€ํ–ฅ์ ์œผ๋กœ, ๊น”๋”ํ•˜๊ฒŒ ํ’€ ์ˆ˜ ์žˆ์„๊นŒ์š”. ๋‹จ์ˆœํžˆ ์ƒ๊ฐํ•ด๋ณด๊ธฐ๋กœ๋Š” `InningCount` ๋ผ๋Š” ๊ฐ์ฒด๊ฐ€ `BallCount` ๊ฐ์ฒด๋ฅผ ๋‹ค์‹œ ๊ฐ–๊ณ  ์žˆ์œผ๋ฉด์„œ, ์•„์›ƒ ์นด์šดํŠธ์™€ ๋ณผ ์นด์šดํŠธ๋ฅผ ๊ด€๋ฆฌํ•˜๋Š” ๋ฐฉ์‹์ด ๋– ์˜ค๋ฆ…๋‹ˆ๋‹ค. ๊ฐ ํ–‰์œ„์— ํ•ด๋‹นํ•˜๋Š” `enum` ์„ ๊ฐ์ฒด์— ๋„˜๊ธฐ๋ฉด ๊ทธ ๊ฐ์ฒด๊ฐ€ ๋‚˜๋จธ์ง€ ์ผ์„ ์ฒ˜๋ฆฌํ•˜๊ฒŒ ๋˜๋Š” ๊ฑฐ์ฃ . ํ•œ ๋ฒˆ ์ƒ๊ฐํ•ด๋ณด์‹œ๊ณ  ๋Œ€๋Œ“๊ธ€๋กœ ๊ณ„์† ๊ตฌํ˜„์— ๋Œ€ํ•ด ์˜๊ฒฌ ๋‚˜๋ˆ ๋ณด๋ฉด ์žฌ๋ฐŒ๊ฒ ๋„ค์š”.
@@ -0,0 +1,18 @@ +package com.codesquad.baseball09.controller; + +import java.text.SimpleDateFormat; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("hcheck") +public class HealthCheckRestController { + + private final static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + @GetMapping + public String healthCheck() { + return dateFormat.format(System.currentTimeMillis()); + } +}
Java
๋‹ค์Œ ํ”„๋กœ์ ํŠธ์— ํ•œ๋ฒˆ ์ ์šฉํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,196 @@ +package com.codesquad.baseball09.model; + +import static com.codesquad.baseball09.model.Status.BALL; +import static com.codesquad.baseball09.model.Status.HIT; +import static com.codesquad.baseball09.model.Status.OUT; +import static com.codesquad.baseball09.model.Status.STRIKE; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +public class InningStatus { + + @JsonIgnore + private Long id; + private Long gameId; + private int inning; + private int strike; + private int ball; + private int out; + private int hit; + + public InningStatus(Long id, Long gameId, int inning, int strike, int ball, int out, int hit) { + this.id = id; + this.gameId = gameId; + this.inning = inning; + this.strike = strike; + this.ball = ball; + this.out = out; + this.hit = hit; + } + + private InningStatus(Long gameId, int inning, int strike, int ball, int out, int hit) { + this.gameId = gameId; + this.inning = inning; + this.strike = strike; + this.ball = ball; + this.out = out; + this.hit = hit; + } + + public InningStatus(int strike, int ball, int out, int hit) { + this.strike = strike; + this.ball = ball; + this.out = out; + this.hit = hit; + } + + public static InningStatus of(Long gameId, int inning, int strike, int ball, int out, int hit) { + return new InningStatus(gameId, inning, strike, ball, out, hit); + } + + public int plus(Status status) { + int value = 0; + + if (STRIKE.equals(status)) { + strike++; + value = checkThreeStrike(); + } else if (BALL.equals(status)) { + ball++; + value = checkFourBall(); + } else if (OUT.equals(status)) { + out++; + resetStrikeAndBall(); + value = checkThreeOut(); + } else if (HIT.equals(status)) { + hit++; + resetStrikeAndBall(); + value = checkFourHit(); + } + return value; + } + + private void resetStrikeAndBall() { + this.strike = 0; + this.ball = 0; + } + + private void resetAll() { + resetStrikeAndBall(); + this.out = 0; + this.hit = 0; + } + + private int checkFourHit() { + if (this.hit == 4) { + resetStrikeAndBall(); + this.hit--; + return 1; + } + return 0; + } + + private int checkThreeOut() { + if (this.out == 3) { + resetAll(); + return -1; + } + return 0; + } + + private int checkFourBall() { + if (this.ball == 4) { + resetStrikeAndBall(); + plus(HIT); + } + return 2; + } + + private int checkThreeStrike() { + if (this.strike == 3) { + resetStrikeAndBall(); + plus(OUT); + } + return 2; + } + + public Long getId() { + return id; + } + + public Long getGameId() { + return gameId; + } + + public int getInning() { + return inning; + } + + public int getStrike() { + return strike; + } + + public int getBall() { + return ball; + } + + public int getOut() { + return out; + } + + public int getHit() { + return hit; + } + + public static final class Builder { + + private Long id; + private Long gameId; + private int inning; + private int strike; + private int ball; + private int out; + private int hit; + + public Builder() { + } + + public Builder id(Long id) { + this.id = id; + return this; + } + + public Builder gameId(Long gameId) { + this.gameId = gameId; + return this; + } + + public Builder inning(int inning) { + this.inning = inning; + return this; + } + + public Builder strike(int strike) { + this.strike = strike; + return this; + } + + public Builder ball(int ball) { + this.ball = ball; + return this; + } + + public Builder out(int out) { + this.out = out; + return this; + } + + public Builder hit(int hit) { + this.hit = hit; + return this; + } + + public InningStatus build() { + return new InningStatus(id, gameId, inning, strike, ball, out, hit); + } + } +}
Java
@wheejuni ๋Šฆ๊ฒŒ ๋‹ตํ•ด๋“œ๋ ค ์ฃ„์†กํ•ฉ๋‹ˆ๋‹ค.. ํ˜„์žฌ `InningStatus` ๊ฐ์ฒด๋Š” inning, strike, ball, out, hit๋ฅผ primitive ํ•œ ๊ฐ’์œผ๋กœ ๋ณด๊ด€ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๋ง์”€ํ•˜์‹  ๋ฐฉ๋ฒ•์€ ball, out์„ ๊ด€๋ฆฌํ•˜๋Š” `BallCount`๋ผ๋Š” ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค์–ด์„œ ํ•ด๋‹น ํ–‰์œ„์— ๋Œ€ํ•ด ์ด ๊ฐ์ฒด์—์„œ ์ฒ˜๋ฆฌํ•˜๋„๋ก ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์ด๋ผ ์ดํ•ด๋ฉ๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๋‚˜๋จธ์ง€ ์ผ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ถ€๋ถ„์€, `4ball`์ผ ๊ฒฝ์šฐ, `1 out`์ด ์˜ฌ๋ผ๊ฐ€๋„๋ก ํ˜น์€ `3 out` ์‹œ ๊ณต์ˆ˜๊ต๋Œ€๋ฅผ ํ•  ์ˆ˜ ์žˆ๋„๋ก ์•Œ๋ ค์ฃผ๋Š” ์—ญํ• ์ด๋ผ ์ƒ๊ฐ๋ฉ๋‹ˆ๋‹ค. ์ œ๊ฐ€ ์ œ๋Œ€๋กœ ์ดํ•ดํ•œ ๊ฒƒ์ด ๋งž์„๊นŒ์š”?
@@ -0,0 +1,196 @@ +package com.codesquad.baseball09.model; + +import static com.codesquad.baseball09.model.Status.BALL; +import static com.codesquad.baseball09.model.Status.HIT; +import static com.codesquad.baseball09.model.Status.OUT; +import static com.codesquad.baseball09.model.Status.STRIKE; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +public class InningStatus { + + @JsonIgnore + private Long id; + private Long gameId; + private int inning; + private int strike; + private int ball; + private int out; + private int hit; + + public InningStatus(Long id, Long gameId, int inning, int strike, int ball, int out, int hit) { + this.id = id; + this.gameId = gameId; + this.inning = inning; + this.strike = strike; + this.ball = ball; + this.out = out; + this.hit = hit; + } + + private InningStatus(Long gameId, int inning, int strike, int ball, int out, int hit) { + this.gameId = gameId; + this.inning = inning; + this.strike = strike; + this.ball = ball; + this.out = out; + this.hit = hit; + } + + public InningStatus(int strike, int ball, int out, int hit) { + this.strike = strike; + this.ball = ball; + this.out = out; + this.hit = hit; + } + + public static InningStatus of(Long gameId, int inning, int strike, int ball, int out, int hit) { + return new InningStatus(gameId, inning, strike, ball, out, hit); + } + + public int plus(Status status) { + int value = 0; + + if (STRIKE.equals(status)) { + strike++; + value = checkThreeStrike(); + } else if (BALL.equals(status)) { + ball++; + value = checkFourBall(); + } else if (OUT.equals(status)) { + out++; + resetStrikeAndBall(); + value = checkThreeOut(); + } else if (HIT.equals(status)) { + hit++; + resetStrikeAndBall(); + value = checkFourHit(); + } + return value; + } + + private void resetStrikeAndBall() { + this.strike = 0; + this.ball = 0; + } + + private void resetAll() { + resetStrikeAndBall(); + this.out = 0; + this.hit = 0; + } + + private int checkFourHit() { + if (this.hit == 4) { + resetStrikeAndBall(); + this.hit--; + return 1; + } + return 0; + } + + private int checkThreeOut() { + if (this.out == 3) { + resetAll(); + return -1; + } + return 0; + } + + private int checkFourBall() { + if (this.ball == 4) { + resetStrikeAndBall(); + plus(HIT); + } + return 2; + } + + private int checkThreeStrike() { + if (this.strike == 3) { + resetStrikeAndBall(); + plus(OUT); + } + return 2; + } + + public Long getId() { + return id; + } + + public Long getGameId() { + return gameId; + } + + public int getInning() { + return inning; + } + + public int getStrike() { + return strike; + } + + public int getBall() { + return ball; + } + + public int getOut() { + return out; + } + + public int getHit() { + return hit; + } + + public static final class Builder { + + private Long id; + private Long gameId; + private int inning; + private int strike; + private int ball; + private int out; + private int hit; + + public Builder() { + } + + public Builder id(Long id) { + this.id = id; + return this; + } + + public Builder gameId(Long gameId) { + this.gameId = gameId; + return this; + } + + public Builder inning(int inning) { + this.inning = inning; + return this; + } + + public Builder strike(int strike) { + this.strike = strike; + return this; + } + + public Builder ball(int ball) { + this.ball = ball; + return this; + } + + public Builder out(int out) { + this.out = out; + return this; + } + + public Builder hit(int hit) { + this.hit = hit; + return this; + } + + public InningStatus build() { + return new InningStatus(id, gameId, inning, strike, ball, out, hit); + } + } +}
Java
strike, ball, out, hit ๊ฐ๊ฐ ์—ญํ• ์ด ์žˆ๋Š” ๋งŒํผ , ๋ชจ๋‘ ๊ฐ์ฒด๋กœ ๋งŒ๋“œ๋Š” ๊ฒƒ์ด ์ข€ ๋” ๊น”๋”ํ•œ ๋ฐฉ๋ฒ•์ผ๊นŒ์š”? ์ด๋ ‡๊ฒŒ ์–ด๋–ค ๋ณ€ํ™”์— ๋”ฐ๋ผ ์˜ํ–ฅ ๋ฐ›๋Š” ๊ฒƒ๋“ค์ด ๋งŽ์„ ๋•Œ, ์–ด๋–ป๊ฒŒ ๊ทธ๋Ÿฌํ•œ ์ƒํ˜ธ์ž‘์šฉ์„ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์„์ง€, ๋‚œ๊ฐํ•ฉ๋‹ˆ๋‹คใ… ใ… 
@@ -0,0 +1,27 @@ +package racingcar.dao; + +import java.util.HashMap; +import java.util.Map; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.simple.SimpleJdbcInsert; +import racingcar.dao.entity.GameEntity; + +public class InsertGameDao { + + private final SimpleJdbcInsert insertActor; + + public InsertGameDao(final JdbcTemplate jdbcTemplate) { + insertActor = new SimpleJdbcInsert(jdbcTemplate) + .withTableName("game") + .usingGeneratedKeyColumns("game_id"); + } + + public GameEntity insert(final GameEntity gameEntity) { + final Map<String, Object> parameters = new HashMap<>(3); + parameters.put("game_id", gameEntity.getGameId().getValue()); + parameters.put("trial_count", gameEntity.getTrialCount()); + parameters.put("created_at", gameEntity.getCreatedAt()); + + return new GameEntity(insertActor.executeAndReturnKey(parameters).intValue(), gameEntity.getTrialCount()); + } +}
Java
์ด๊ฑฐ ์™ธ ์•Š ๋Š ?
@@ -0,0 +1,97 @@ +package christmas.config; + +import christmas.controller.EventController; +import christmas.exception.RetryHandler; +import christmas.service.EventService; +import christmas.service.MenuService; +import christmas.validator.InputValidator; +import christmas.view.input.ConsoleReader; +import christmas.view.input.InputView; +import christmas.view.input.Reader; +import christmas.view.output.ConsoleWriter; +import christmas.view.output.OutputView; +import christmas.view.output.Writer; + +public class AppConfig { + private static AppConfig appConfig; + private EventController eventController; + private EventService eventService; + private MenuService menuService; + private InputValidator inputValidator; + private RetryHandler retryHandler; + private InputView inputView; + private OutputView outputView; + private Reader reader; + private Writer writer; + + public static AppConfig getInstance() { + if (appConfig == null) { + appConfig = new AppConfig(); + } + return appConfig; + } + + public EventController eventController() { + if (eventController == null) { + eventController = new EventController(discountService(), menuService(), + inputView(), outputView(), exceptionHandler()); + } + return eventController; + } + + public EventService discountService() { + if (eventService == null) { + eventService = new EventService(); + } + return eventService; + } + + public MenuService menuService() { + if (menuService == null) { + menuService = new MenuService(); + } + return menuService; + } + + public RetryHandler exceptionHandler() { + if (retryHandler == null) { + retryHandler = new RetryHandler(outputView()); + } + return retryHandler; + } + + public InputView inputView() { + if (inputView == null) { + inputView = new InputView(reader(), inputValidator()); + } + return inputView; + } + + public InputValidator inputValidator() { + if (inputValidator == null) { + inputValidator = new InputValidator(); + } + return inputValidator; + } + + public Reader reader() { + if (reader == null) { + reader = new ConsoleReader(); + } + return reader; + } + + public OutputView outputView() { + if (outputView == null) { + outputView = new OutputView(writer()); + } + return outputView; + } + + public Writer writer() { + if (writer == null) { + writer = new ConsoleWriter(); + } + return writer; + } +}
Java
์ „์ฒด์ ์œผ๋กœ null ์ฒดํฌ๋ฅผ ํ•ด์ฃผ์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,30 @@ +package christmas.constants.event; + +public enum BadgeType { + NONE("์—†์Œ", 0), + STAR("๋ณ„", 5_000), + TREE("ํŠธ๋ฆฌ", 10_000), + SANTA("์‚ฐํƒ€", 20_000); + + private final String name; + private final int threshold; + + BadgeType(String name, int threshold) { + this.name = name; + this.threshold = threshold; + } + + public static BadgeType from(int benefitPrice) { + BadgeType result = NONE; + for (BadgeType badgeType : values()) { + if (benefitPrice >= badgeType.threshold) { + result = badgeType; + } + } + return result; + } + + public String getName() { + return name; + } +}
Java
๋ฐฐ์ง€ ์—†์Œ์„ NONE์œผ๋กœ ๊ด€๋ฆฌํ•˜์‹  ๋ถ€๋ถ„๋„ ์ข‹์€ ์ „๋žต์ด๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค :) Optional์„ ๊ณ ๋ คํ•ด๋ณด์‹œ๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ์ด๋ฒˆ์— Optional์„ ์ฒ˜์Œ ํ™œ์šฉํ•ด๋ดค๋Š”๋ฐ์š”, **์—†์„ ์ˆ˜๋„ ์žˆ๋‹ค ๋ผ๋Š” ๋น„์ฆˆ๋‹ˆ์Šค ์š”๊ตฌ์‚ฌํ•ญ**์„ **์ฝ”๋“œ๋กœ ๋ช…์‹œ**ํ•  ์ˆ˜ ์žˆ๋Š” ์ ์ด ์ •๋ง ํฐ ์žฅ์ ์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค :) ๋งŒ์•ฝ Optional์„ ๋„์ž…ํ•œ๋‹ค๋ฉด `from` ๋ฉ”์„œ๋“œ๋ฅผ ์ด๋ ‡๊ฒŒ ๋ฆฌํŒฉํ„ฐ๋งํ•ด๋ณผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”! ```java public static Optional<BadgeType> from(int benefitPrice) { Optional<Badge> badge = Arrays.stream(values()) .filter(badge -> badge.minTotalBenefitAmount <= totalBenefitAmount) .findFirst(); if (badge.isPresent()) { return badge.get(); } return badge.empty(); } } ``` ์ €๋„ ์•„์ง Optional์„ ์–ธ์ œ ์‚ฌ์šฉํ•ด์•ผ ๋‚จ์šฉ์ด ์•„๋‹๊นŒ? ๋ผ๋Š” ํ™•์‹คํ•œ ๊ธฐ์ค€์€ ์—†์–ด์„œ, ์ฐธ๊ณ  ์ •๋„๋งŒ ํ•˜์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค :)
@@ -0,0 +1,54 @@ +package christmas.constants.menu; + +import static christmas.constants.menu.MenuType.APPETIZER; +import static christmas.constants.menu.MenuType.DESSERT; +import static christmas.constants.menu.MenuType.DRINKS; +import static christmas.constants.menu.MenuType.MAIN; +import static christmas.exception.ErrorCode.INVALID_MENU_ORDER; + +import java.util.Arrays; +import java.util.Objects; + +public enum Menu { + MUSHROOM_SOUP(APPETIZER, "์–‘์†ก์ด์ˆ˜ํ”„", 6000), + TAPAS(APPETIZER, "ํƒ€ํŒŒ์Šค", 5500), + SALAD(APPETIZER, "์‹œ์ €์ƒ๋Ÿฌ๋“œ", 8000), + STAKE(MAIN, "ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 55_000), + LIB(MAIN, "๋ฐ”๋น„ํ๋ฆฝ", 54_000), + PASTA_(MAIN, "ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 35_000), + PASTA(MAIN, "ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 25_000), + CAKE(DESSERT, "์ดˆ์ฝ”์ผ€์ดํฌ", 15_000), + ICE_CREAM(DESSERT, "์•„์ด์Šคํฌ๋ฆผ", 5000), + ZERO_COLA(DRINKS, "์ œ๋กœ์ฝœ๋ผ", 3000), + WINE(DRINKS, "๋ ˆ๋“œ์™€์ธ", 60_000), + CHAMPAGNE(DRINKS, "์ƒดํŽ˜์ธ", 25_000); + + private final MenuType menuType; + private final String name; + private final int price; + + Menu(MenuType menuType, String name, int price) { + this.menuType = menuType; + this.name = name; + this.price = price; + } + + public static Menu from(String input) { + return Arrays.stream(values()) + .filter(menu -> Objects.equals(menu.name, input)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException(INVALID_MENU_ORDER.getMessage())); + } + + public MenuType getMenuType() { + return menuType; + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } +}
Java
`์ด๋ฆ„`์— ๋Œ€ํ•œ `๋ฉ”๋‰ด`๋ฅผ HashMap์œผ๋กœ ์บ์‹ฑํ•ด๋‘๋Š” ์ „๋žต๋„ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค. Enum์—์„  static ๋ธ”๋ก์„ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ๋Š”๋ฐ์š”, ์š”๋Ÿฐ์‹์œผ๋กœ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค! ```java public enum Menu { // ์—ด๊ฑฐํ˜• ์ƒ์ˆ˜๋“ค ... private static final Map<String, Menu> cachedMenu = new HashMap<>(); static { for (Menu menu : values()) { cachedMenu.put(menu.getName(), menu); } } } ``` ์ด๋ ‡๊ฒŒ Map์œผ๋กœ ์บ์‹ฑํ•ด๋‘๋ฉด, ๋งค ๋ฒˆ ์—ด๊ฑฐํ˜• ์ƒ์ˆ˜๋“ค์„ ์ˆœํšŒํ•˜์ง€ ์•Š์•„๋„ ๋˜๋Š” ์žฅ์ ์ด ์žˆ์Šต๋‹ˆ๋‹ค :) ํ•˜์ง€๋งŒ NPE๊ฐ€ ๋ฐœ์ƒํ•  ์œ„ํ—˜์ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, Optional์„ ์‚ฌ์šฉํ•ด๋ณด์‹œ๋Š” ๊ฒƒ๋„ ๊ณ ๋ คํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ทธ๋ ‡๊ฒŒ ํ•˜๋ฉด ```java public static Optional<Menu> from(String menuName) { return Optional.ofNullalbe(cachedMenu.get(menuName); } ``` ์œ„์™€ ๊ฐ™์ด ๋ฆฌํŒฉํ„ฐ๋ง ํ•ด๋ณผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š” :)
@@ -0,0 +1,98 @@ +package christmas.service; + +import static christmas.constants.event.EventRule.MAX_MENU_AMOUNT; +import static christmas.constants.menu.MenuType.DRINKS; +import static christmas.exception.ErrorCode.INVALID_MENU_ORDER; + +import christmas.constants.menu.Menu; +import christmas.constants.menu.MenuType; +import christmas.dto.SingleMenu; +import java.util.Collections; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +public class MenuService { + private final Map<Menu, Integer> menuScript; + + public MenuService() { + this.menuScript = new EnumMap<>(Menu.class); + } + + public void order(List<SingleMenu> singleMenus) { + validate(singleMenus); + singleMenus.forEach(singleOrder -> { + Menu menu = Menu.from(singleOrder.menu()); + menuScript.put(menu, singleOrder.amount()); + }); + } + + public int getOrderPrice() { + return menuScript.keySet() + .stream() + .mapToInt(menu -> menu.getPrice() * menuScript.get(menu)) + .sum(); + } + + private void validate(List<SingleMenu> singleMenus) { + validateDuplicate(singleMenus); + validatePerMenuAmount(singleMenus); + validateOnlyDrink(singleMenus); + validateTotalMenuAmount(singleMenus); + } + + private void validateDuplicate(List<SingleMenu> singleMenus) { + int count = (int) getMenuStream(singleMenus) + .distinct() + .count(); + + if (count != singleMenus.size()) { + throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage()); + } + } + + private void validateOnlyDrink(List<SingleMenu> singleMenus) { + int drinks = (int) getMenuStream(singleMenus) + .filter(menu -> menu.getMenuType() == DRINKS) + .count(); + + if (drinks > 0 && drinks == singleMenus.size()) { + throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage()); + } + } + + private Stream<Menu> getMenuStream(List<SingleMenu> singleMenus) { + return singleMenus.stream() + .map(singleOrder -> Menu.from(singleOrder.menu())); + } + + private void validatePerMenuAmount(List<SingleMenu> singleMenus) { + boolean present = singleMenus.stream() + .anyMatch(singleOrder -> singleOrder.amount() < 1); + if (present) { + throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage()); + } + } + + private void validateTotalMenuAmount(List<SingleMenu> singleMenus) { + int totalAmount = singleMenus.stream() + .mapToInt(SingleMenu::amount) + .sum(); + if (totalAmount >= MAX_MENU_AMOUNT.getValue()) { + throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage()); + } + } + + public int getAmountByMenu(MenuType menuType) { + return menuScript.keySet() + .stream() + .filter(target -> target.getMenuType() == menuType) + .mapToInt(menuScript::get) + .sum(); + } + + public Map<Menu, Integer> getMenuScript() { + return Collections.unmodifiableMap(menuScript); + } +}
Java
`MenuService` ์—์„œ ์ฃผ๋ฌธ ์ •๋ณด๋“ค์„ ๋‹ด๊ณ ์žˆ๋Š”๊ฒŒ ์ธ์ƒ๊นŠ์Šต๋‹ˆ๋‹ค! ์ด๊ฒƒ๋„ ์ข‹์€ ์ ‘๊ทผ ๋ฐฉ์‹์ธ ๊ฒƒ ๊ฐ™์ง€๋งŒ, `Map<Menu, Integer>`๊ฐ€ `์ฃผ๋ฌธ ์ •๋ณด` ๋ผ๋Š” ์‚ฌ์‹ค์„ ์ถ”์ ํ•˜๊ธฐ ์–ด๋ ค์šธ ์ˆ˜๋„ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”! `Order` Domain ํด๋ž˜์Šค๋ฅผ ์ƒ์„ฑํ•˜๊ณ , validate ๊ฒ€์ฆ ์—ญํ• ๋„ ์œ„์ž„ํ•ด์ฃผ๋ฉด MenuService ํด๋ž˜์Šค๊ฐ€ ํ•œ์ธต ์–‡์•„์งˆ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์—ฌ๊ธฐ์„œ Service Layer์˜ ํด๋ž˜์Šค๊ฐ€ ์–‡์•„์ง„๋‹ค๋Š” ๊ฒƒ์€ **Domain ๊ฐ์ฒด์—๊ฒŒ ์š”์ฒญํ•˜์—ฌ ๊ฒฐ๊ณผ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ์—ญํ• **, **๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง ํ๋ฆ„์„ ๋‹ด๋‹นํ•˜๋Š” ์—ญํ• **๋กœ ์ถ•์†Œ ๋œ๋‹ค๋Š” ์˜๋ฏธ๋ผ๊ณ  ์ƒ๊ฐํ•ด์š”. ์ด๋•Œ์˜ ์žฅ์ ์€ **MenuService ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์ด ์–ด๋–ค ํ๋ฆ„์œผ๋กœ ์ง„ํ–‰๋˜๋Š”๊ตฌ๋‚˜** ์ถ”์ ํ•˜๊ธฐ ํŽธํ•ด์ง€๋Š” ์  ๊ฐ™์Šต๋‹ˆ๋‹ค :)
@@ -0,0 +1,32 @@ +package christmas.util; + +import static christmas.exception.ErrorCode.INVALID_DATE; +import static christmas.exception.ErrorCode.INVALID_MENU_ORDER; + +import java.util.List; + +public class Parser { + public static int parseToDate(String input) { + try { + return Integer.parseInt(input); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_DATE.getMessage()); + } + } + + public static int parseToAmount(String input) { + try { + return Integer.parseInt(input); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage()); + } + } + + public static List<String> parseToMenu(String input, String delimiter) { + try { + return List.of(input.split(delimiter)); + } catch (IndexOutOfBoundsException e) { + throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage()); + } + } +}
Java
catch ํ•œ ์–ด๋– ํ•œ Exception์„ ๋‹ค๋ฅธ Exception์œผ๋กœ ๋ž˜ํ•‘ํ•˜์—ฌ ๋‹ค์‹œ ๋˜์ ธ์ค„ ๋•, catch ํ–ˆ๋˜ Exception๋„ ๋„ฃ์–ด์„œ ๋„˜๊ฒจ์ฃผ๋Š” ๊ฒƒ์„ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค. ```java public static int parseToDate(String input) { try { return Integer.parseInt(input); } catch (NumberFormatException e) { throw new IllegalArgumentException(INVALID_DATE.getMessage(), e); } } ``` ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ๊ธฐ์กด์— catch ํ–ˆ๋˜ ์˜ˆ์™ธ๊ฐ€ ๋‚ ์•„๊ฐ€๋ฒ„๋ฆฌ๋Š” ์ƒํ™ฉ์ด ๋˜์–ด, ์„ธ๋ถ€ ์˜ˆ์™ธ๋ฅผ ์Šคํƒ ํŠธ๋ ˆ์ด์Šค ํ•  ์ˆ˜ ์—†๊ฒŒ๋ฉ๋‹ˆ๋‹น!
@@ -0,0 +1,25 @@ +package christmas.constants.event; + +public enum EventRule { + EVENT_THRESHOLD(10_000), + PRESENT_THRESHOLD(120_000), + EVENT_START(1), + EVENT_END(31), + MAX_MENU_AMOUNT(20), + CHRISTMAS_EVENT_END(25), + CHRISTMAS_INIT_PRICE(1_000), + CHRISTMAS_EXTRA_DISCOUNT(100), + MENU_DISCOUNT(2_023), + SPECIAL_DISCOUNT(1_000); + + + private final int value; + + EventRule(int value) { + this.value = value; + } + + public int getValue() { + return value; + } +}
Java
์ด๋ฒคํŠธ ๋ฃฐ์„ ํ•œ ๊ณณ์— ๋ชจ์•„๋†“์œผ๋‹ˆ ์ฝ”๋“œ๊ฐ€ ์‰ฝ๊ฒŒ ์ฝํžˆ์ง€ ์•Š๋Š”๊ฑฐ ๊ฐ™์•„์š”! ์ด๋ฒคํŠธ ์ข…๋ฅ˜์— ๋”ฐ๋ผ ๋ถ„๋ฆฌํ•˜๊ฑฐ๋‚˜, EventType์˜ ๋ฉค๋ฒ„๋ณ€์ˆ˜๋กœ ๋ฃฐ์„ ์ •์˜ํ•˜์‹œ๋Š” ๊ฒƒ์€ ์–ด๋–ค๊ฐ€์š”?
@@ -0,0 +1,38 @@ +package christmas.exception; + +import christmas.view.output.OutputView; +import java.util.Arrays; +import java.util.function.Supplier; + +public class RetryHandler implements ExceptionHandler { + private final OutputView outputView; + + public RetryHandler(OutputView outputView) { + this.outputView = outputView; + } + + @Override + @SafeVarargs + public final <T> T execute(Supplier<T> action, Class<? extends Exception>... exceptions) { + while (true) { + try { + return action.get(); + } catch (IllegalArgumentException e) { + printException(e, exceptions); + } + } + } + + private void printException(Exception actual, Class<? extends Exception>... exceptions) { + if (isExpectedException(actual, exceptions)) { + outputView.printError(actual.getMessage()); + return; + } + throw new RuntimeException(actual); + } + + private boolean isExpectedException(Exception actual, Class<? extends Exception>... exceptions) { + return Arrays.stream(exceptions) + .anyMatch(exception -> exception.isInstance(actual)); + } +}
Java
์‹ค์ œ exception๊ณผ ์ธ์ž๋กœ ๋ฐ›์€ exception์„ ๋น„๊ตํ•˜๋Š” ๋กœ์ง์ด ํ•„์š”ํ•œ ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ด์š”!
@@ -0,0 +1,19 @@ +package christmas.constants.event; + +public enum EventType { + CHRISTMAS("ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด ํ• ์ธ"), + WEEKDAY("ํ‰์ผ ํ• ์ธ"), + WEEKEND("์ฃผ๋ง ํ• ์ธ"), + SPECIAL("ํŠน๋ณ„ ํ• ์ธ"), + PRESENT("์ฆ์ • ์ด๋ฒคํŠธ"); + + private final String description; + + EventType(String description) { + this.description = description; + } + + public String getDescription() { + return description; + } +}
Java
`Eventable` ์ธํ„ฐํŽ˜์ด์Šค์™€ `๊ฐ๊ฐ์˜ ์ด๋ฒคํŠธ ๊ตฌํ˜„์ฒด ํด๋ž˜์Šค`์—์„œ ํ• ์ธ / ์ฆ์ • ์ƒํ’ˆ ๊ณ„์‚ฐ ์ฒ˜๋ฆฌํ•˜์‹  ๋ฐฉ๋ฒ•๋„ ๊ต‰์žฅํžˆ ์ง๊ด€์ ์œผ๋กœ ์ฝํžˆ๊ณ  ์ •๋ง ์ข‹์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ๐Ÿ‘ ์ €๋Š” `ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด/ ํ‰์ผ/ ์ฃผ๋ง /ํŠน๋ณ„ ํ• ์ธ ์ด๋ฒคํŠธ ์œ ํ˜•`๊ณผ `ํ• ์ธ ์ด๋ฒคํŠธ ์œ ํ˜•์— ํ•ด๋‹นํ•˜๋Š” ๊ณ„์‚ฐ ์ฒ˜๋ฆฌ`๋Š” **์„œ๋กœ ๋ฐ€์ ‘ํ•œ ์—ฐ๊ด€์ด ์žˆ๋Š” ์ƒ์ˆ˜**๋ผ๋Š” ์ƒ๊ฐ์ด ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค! ๊ทธ๋ž˜์„œ `EventType Enum`์—์„œ ํ• ์ธ ๊ณ„์‚ฐ ์ฒ˜๋ฆฌ๋„ ํ•จ๊ป˜ ๊ด€๋ฆฌํ•˜๋„๋ก ํ–ˆ์Šต๋‹ˆ๋‹ค. ์ด๋ ‡๊ฒŒ ์ฒ˜๋ฆฌ๋ฅผ ํ•˜๋‹ˆ **ํ• ์ธ ์ด๋ฒคํŠธ ์œ ํ˜•์ด๋ผ๋Š” ์ƒํƒœ**์™€ **์ด๋ฒคํŠธ ์œ ํ˜•์— ๋Œ€ํ•œ ๊ณ„์‚ฐ์ฒ˜๋ฆฌ๋ผ๋Š” ํ–‰์œ„**๊ฐ€ ํ•œ ๊ณณ์— ๋ฐ€์ง‘๋˜์–ด ์žˆ์–ด ์œ ์ง€๋ณด์ˆ˜ํ•˜๊ธฐ ํŽธํ•  ๊ฒƒ ๊ฐ™๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค! ์ด ๋ถ€๋ถ„์— ๋Œ€ํ•ด์„œ HEY๋‹˜ ์˜๊ฒฌ์ด ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค ๐Ÿ˜Š
@@ -0,0 +1,7 @@ +package christmas.model; + +public interface Eventable<T> { + boolean canJoinEvent(T condition); + + int getDiscountPrice(); +}
Java
Eventable์ด๋ผ๋Š” ๊ฐ์ฒด๋ช…์ด ์กฐ๊ธˆ ํ—ท๊ฐˆ๋ฆฌ๋Š”๊ฑฐ ๊ฐ™์•„์š”. ํ˜„์žฌ Eventable์€ ์ด๋ฒคํŠธ ์—ฌ๋ถ€๋ฅผ ํŒ๋‹จํ•˜๋Š” ๋ฉ”์†Œ๋“œ์™€ ํ• ์ธ ๊ธˆ์•ก์„ ๊ณ„์‚ฐํ•˜๋Š” ๋ฉ”์†Œ๋“œ๊ฐ€ ์กด์žฌํ•ด์š”. ํ•˜์ง€๋งŒ Eventable ๋„ค์ด๋ฐ์€ ํ• ์ธ ์—ฌ๋ถ€๋งŒ ํŒ๋‹จํ•˜๋Š” ์—ญํ• ์ด๋ผ๊ณ  ์˜คํ•ดํ•  ์ˆ˜ ์žˆ์„๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค ๐Ÿ”ฅ
@@ -0,0 +1,33 @@ +package christmas.model; + +import static christmas.constants.event.EventRule.PRESENT_THRESHOLD; +import static christmas.constants.menu.Menu.CHAMPAGNE; + +public class PresentEvent implements Eventable<Integer> { + private final int amount; + + private PresentEvent(int orderPrice) { + if (canJoinEvent(orderPrice)) { + this.amount = 1; + return; + } + this.amount = 0; + } + + public static PresentEvent create(int orderPrice) { + return new PresentEvent(orderPrice); + } + + @Override + public boolean canJoinEvent(Integer orderPrice) { + if (orderPrice < PRESENT_THRESHOLD.getValue()) { + return false; + } + return true; + } + + @Override + public int getDiscountPrice() { + return CHAMPAGNE.getPrice() * amount; + } +}
Java
1 ์ด๋ผ๋Š” ์ˆซ์ž๋ฅผ ์ƒ์ˆ˜๋กœ ์„ ์–ธํ•˜๋Š” ๊ฒƒ์€ ์–ด๋–ค๊ฐ€์š”? ์š”๊ตฌ์‚ฌํ•ญ์„ ์ดํ•ดํ•˜์ง€ ๋ชปํ•œ ์‚ฌ๋žŒ์ด ์ฝ”๋“œ๋ฅผ ๋ณด๋Š” ๊ฒฝ์šฐ 1์ด๋ผ๋Š” ์ˆซ์ž์˜ ์˜๋ฏธ๋ฅผ ํŒŒ์•…ํ•˜๊ธฐ ์–ด๋ ค์šธ๊ฑฐ ๊ฐ™์•„์š” :)
@@ -0,0 +1,80 @@ +package christmas.service; + +import static christmas.constants.event.EventRule.EVENT_THRESHOLD; +import static christmas.constants.event.EventType.CHRISTMAS; +import static christmas.constants.event.EventType.PRESENT; +import static christmas.constants.event.EventType.SPECIAL; +import static christmas.constants.event.EventType.WEEKDAY; +import static christmas.constants.event.EventType.WEEKEND; + +import christmas.constants.event.EventType; +import christmas.dto.EventDetail; +import christmas.dto.UserOrder; +import christmas.model.ChristmasEvent; +import christmas.model.Eventable; +import christmas.model.PresentEvent; +import christmas.model.SpecialEvent; +import christmas.model.WeekdayEvent; +import christmas.model.WeekendEvent; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + +public class EventService { + private final Map<EventType, Eventable> eventResult; + private final int INVALID_VALUE = 0; + + public EventService() { + eventResult = new EnumMap<>(EventType.class); + } + + public void applyEvent(UserOrder userOrder) { + if (!canJoinEvent(userOrder.orderPrice())) { + userOrder = new UserOrder(INVALID_VALUE, INVALID_VALUE, INVALID_VALUE, INVALID_VALUE); + } + + eventResult.put(PRESENT, PresentEvent.create(userOrder.orderPrice())); + eventResult.put(CHRISTMAS, ChristmasEvent.create(userOrder.date())); + eventResult.put(WEEKDAY, WeekdayEvent.create(userOrder)); + eventResult.put(WEEKEND, WeekendEvent.create(userOrder)); + eventResult.put(SPECIAL, SpecialEvent.create(userOrder.date())); + } + + private boolean canJoinEvent(int orderPrice) { + if (orderPrice < EVENT_THRESHOLD.getValue()) { + return false; + } + return true; + } + + public int getDiscountPriceByEvent(EventType eventType) { + return eventResult.get(eventType).getDiscountPrice(); + } + + public int getExpectedPrice(UserOrder userOrder) { + return userOrder.orderPrice() - getTotalDiscountPrice(); + } + + public int getTotalDiscountPrice() { + return eventResult.entrySet() + .stream() + .filter(entry -> entry.getKey() != PRESENT) + .mapToInt(value -> value.getValue().getDiscountPrice()) + .sum(); + } + + public int getTotalBenefitPrice() { + return eventResult.values() + .stream() + .mapToInt(Eventable::getDiscountPrice) + .sum(); + } + + public List<EventDetail> convertToEventDetails() { + return eventResult.entrySet() + .stream() + .filter(entry -> entry.getValue().getDiscountPrice() != 0) + .map(entry -> new EventDetail(entry.getKey(), entry.getValue().getDiscountPrice())) + .toList(); + } +}
Java
EventService๋„ ์ถฉ๋ถ„ํžˆ ์ข‹์€ ์ฝ”๋“œ๋ผ๊ณ  ์ƒ๊ฐ๋ฉ๋‹ˆ๋‹ค! ์ด๋ฒคํŠธ๋Š” `ํ• ์ธ`์— ๋Œ€ํ•œ ์ด๋ฒคํŠธ, `์ฆ์ •์ƒํ’ˆ`์— ๋Œ€ํ•œ ์ด๋ฒคํŠธ๋กœ ๋‚˜๋‰˜๊ธฐ ๋•Œ๋ฌธ์— `DiscountEventService`, `GiftEventService`๋กœ ๋‚˜๋ˆˆ๋‹ค๋ฉด, ๊ฐ ์„œ๋น„์Šค ํด๋ž˜์Šค๊ฐ€ ์–ด๋–ค ์ด๋ฒคํŠธ์— ๋Œ€ํ•ด ์ฒ˜๋ฆฌํ•˜๋Š”์ง€ ๋ณด๋‹ค ๋ช…ํ™•ํ•ด์ง€๊ณ  ์œ ์ง€๋ณด์ˆ˜ํ•˜๊ธฐ๋„ ์ข‹์•„์งˆ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค :)
@@ -0,0 +1,31 @@ +package christmas.model; + +import static christmas.constants.event.EventRule.SPECIAL_DISCOUNT; + +import christmas.util.DayAnalyzer; + +public class SpecialEvent implements Eventable<Integer> { + private final int discountPrice; + + private SpecialEvent(Integer date) { + if (canJoinEvent(date)) { + discountPrice = SPECIAL_DISCOUNT.getValue(); + return; + } + discountPrice = 0; + } + + public static SpecialEvent create(Integer date) { + return new SpecialEvent(date); + } + + @Override + public boolean canJoinEvent(Integer date) { + return DayAnalyzer.isSpecialDay(date); + } + + @Override + public int getDiscountPrice() { + return this.discountPrice; + } +}
Java
ํ•ด๋‹น ๋กœ์ง์€ ์ •์  ๋ฉ”์†Œ๋“œ์— ๋“ค์–ด๊ฐ€๋Š” ๊ฒƒ์ด ์ ํ•ฉํ• ๊ฑฐ ๊ฐ™์€๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”? ์ƒ์„ฑ์ž๋Š” ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์ฑ…์ž„๋งŒ ๊ฐ–๊ณ , ์ •์  ๋ฉ”์†Œ๋“œ์—์„œ ์กฐ๊ฑด์— ๋”ฐ๋ฅธ discountPrice๊ฐ’์„ ์ƒ์„ฑ์ž๋กœ ๋„˜๊ฒจ์ค„ ์ˆ˜ ์žˆ์„๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,80 @@ +package christmas.service; + +import static christmas.constants.event.EventRule.EVENT_THRESHOLD; +import static christmas.constants.event.EventType.CHRISTMAS; +import static christmas.constants.event.EventType.PRESENT; +import static christmas.constants.event.EventType.SPECIAL; +import static christmas.constants.event.EventType.WEEKDAY; +import static christmas.constants.event.EventType.WEEKEND; + +import christmas.constants.event.EventType; +import christmas.dto.EventDetail; +import christmas.dto.UserOrder; +import christmas.model.ChristmasEvent; +import christmas.model.Eventable; +import christmas.model.PresentEvent; +import christmas.model.SpecialEvent; +import christmas.model.WeekdayEvent; +import christmas.model.WeekendEvent; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + +public class EventService { + private final Map<EventType, Eventable> eventResult; + private final int INVALID_VALUE = 0; + + public EventService() { + eventResult = new EnumMap<>(EventType.class); + } + + public void applyEvent(UserOrder userOrder) { + if (!canJoinEvent(userOrder.orderPrice())) { + userOrder = new UserOrder(INVALID_VALUE, INVALID_VALUE, INVALID_VALUE, INVALID_VALUE); + } + + eventResult.put(PRESENT, PresentEvent.create(userOrder.orderPrice())); + eventResult.put(CHRISTMAS, ChristmasEvent.create(userOrder.date())); + eventResult.put(WEEKDAY, WeekdayEvent.create(userOrder)); + eventResult.put(WEEKEND, WeekendEvent.create(userOrder)); + eventResult.put(SPECIAL, SpecialEvent.create(userOrder.date())); + } + + private boolean canJoinEvent(int orderPrice) { + if (orderPrice < EVENT_THRESHOLD.getValue()) { + return false; + } + return true; + } + + public int getDiscountPriceByEvent(EventType eventType) { + return eventResult.get(eventType).getDiscountPrice(); + } + + public int getExpectedPrice(UserOrder userOrder) { + return userOrder.orderPrice() - getTotalDiscountPrice(); + } + + public int getTotalDiscountPrice() { + return eventResult.entrySet() + .stream() + .filter(entry -> entry.getKey() != PRESENT) + .mapToInt(value -> value.getValue().getDiscountPrice()) + .sum(); + } + + public int getTotalBenefitPrice() { + return eventResult.values() + .stream() + .mapToInt(Eventable::getDiscountPrice) + .sum(); + } + + public List<EventDetail> convertToEventDetails() { + return eventResult.entrySet() + .stream() + .filter(entry -> entry.getValue().getDiscountPrice() != 0) + .map(entry -> new EventDetail(entry.getKey(), entry.getValue().getDiscountPrice())) + .toList(); + } +}
Java
ํ•ด๋‹น ๋กœ์ง์€ EnumMap์„ ์ดˆ๊ธฐํ™”ํ•˜๋Š” ๋กœ์ง์ธ๊ฑฐ ๊ฐ™์•„์š”. ๊ทธ๋Ÿผ ์ƒ์„ฑ์ž๊ฐ€ ์•„๋‹Œ init ์ด๋ผ๋Š” ์ด๋ฆ„์˜ ์ •์  ๋ฉ”์†Œ๋“œ๋ฅผ ํ†ตํ•ด ๋‚ด๋ถ€ ๋กœ์ง์„ ์ข€ ๋” ๋ช…ํ™•ํžˆ ํŒŒ์•…ํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๋Š” ๊ฒƒ์€ ์–ด๋–ค๊ฐ€์š”?
@@ -0,0 +1,80 @@ +package christmas.service; + +import static christmas.constants.event.EventRule.EVENT_THRESHOLD; +import static christmas.constants.event.EventType.CHRISTMAS; +import static christmas.constants.event.EventType.PRESENT; +import static christmas.constants.event.EventType.SPECIAL; +import static christmas.constants.event.EventType.WEEKDAY; +import static christmas.constants.event.EventType.WEEKEND; + +import christmas.constants.event.EventType; +import christmas.dto.EventDetail; +import christmas.dto.UserOrder; +import christmas.model.ChristmasEvent; +import christmas.model.Eventable; +import christmas.model.PresentEvent; +import christmas.model.SpecialEvent; +import christmas.model.WeekdayEvent; +import christmas.model.WeekendEvent; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + +public class EventService { + private final Map<EventType, Eventable> eventResult; + private final int INVALID_VALUE = 0; + + public EventService() { + eventResult = new EnumMap<>(EventType.class); + } + + public void applyEvent(UserOrder userOrder) { + if (!canJoinEvent(userOrder.orderPrice())) { + userOrder = new UserOrder(INVALID_VALUE, INVALID_VALUE, INVALID_VALUE, INVALID_VALUE); + } + + eventResult.put(PRESENT, PresentEvent.create(userOrder.orderPrice())); + eventResult.put(CHRISTMAS, ChristmasEvent.create(userOrder.date())); + eventResult.put(WEEKDAY, WeekdayEvent.create(userOrder)); + eventResult.put(WEEKEND, WeekendEvent.create(userOrder)); + eventResult.put(SPECIAL, SpecialEvent.create(userOrder.date())); + } + + private boolean canJoinEvent(int orderPrice) { + if (orderPrice < EVENT_THRESHOLD.getValue()) { + return false; + } + return true; + } + + public int getDiscountPriceByEvent(EventType eventType) { + return eventResult.get(eventType).getDiscountPrice(); + } + + public int getExpectedPrice(UserOrder userOrder) { + return userOrder.orderPrice() - getTotalDiscountPrice(); + } + + public int getTotalDiscountPrice() { + return eventResult.entrySet() + .stream() + .filter(entry -> entry.getKey() != PRESENT) + .mapToInt(value -> value.getValue().getDiscountPrice()) + .sum(); + } + + public int getTotalBenefitPrice() { + return eventResult.values() + .stream() + .mapToInt(Eventable::getDiscountPrice) + .sum(); + } + + public List<EventDetail> convertToEventDetails() { + return eventResult.entrySet() + .stream() + .filter(entry -> entry.getValue().getDiscountPrice() != 0) + .map(entry -> new EventDetail(entry.getKey(), entry.getValue().getDiscountPrice())) + .toList(); + } +}
Java
์ด๋ฒคํŠธ์— ๋Œ€ํ•œ ์ •์ฑ…๋“ค์„ ์™ธ๋ถ€์—์„œ ์ฃผ์ž…๋ฐ›๋„๋ก ํ•˜๋Š” ๊ฒƒ์€ ์–ด๋–ค๊ฐ€์š”? ํ˜„์žฌ ์ฝ”๋“œ๋Š” ์˜์กด ์—ญ์ „ ์›์น™(DIP)์„ ์ค€์ˆ˜ํ•˜์ง€ ์•Š์€ ์ฝ”๋“œ๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ํ• ์ธ ์ข…๋ฅ˜์— ๋Œ€ํ•œ ์ •์ฑ…์ด ๋ณ€ํ•˜๋Š” ๊ฒฝ์šฐ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์ฝ”๋“œ๋ฅผ ์ˆ˜์ •ํ•ด์•ผํ•˜๋Š” ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•ฉ๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ, ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๋‚ด๋ถ€์—์„œ๋Š” ์ถ”์ƒ ๊ฐ์ฒด์— ์˜์กดํ•˜๊ณ , service ์ƒ์„ฑ์ž์— EnumMap์„ ๋„˜๊ฒจ์ฃผ๋Š” ๊ฒƒ์€ ์–ด๋–ค๊ฐ€์š”?
@@ -0,0 +1,98 @@ +package christmas.service; + +import static christmas.constants.event.EventRule.MAX_MENU_AMOUNT; +import static christmas.constants.menu.MenuType.DRINKS; +import static christmas.exception.ErrorCode.INVALID_MENU_ORDER; + +import christmas.constants.menu.Menu; +import christmas.constants.menu.MenuType; +import christmas.dto.SingleMenu; +import java.util.Collections; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +public class MenuService { + private final Map<Menu, Integer> menuScript; + + public MenuService() { + this.menuScript = new EnumMap<>(Menu.class); + } + + public void order(List<SingleMenu> singleMenus) { + validate(singleMenus); + singleMenus.forEach(singleOrder -> { + Menu menu = Menu.from(singleOrder.menu()); + menuScript.put(menu, singleOrder.amount()); + }); + } + + public int getOrderPrice() { + return menuScript.keySet() + .stream() + .mapToInt(menu -> menu.getPrice() * menuScript.get(menu)) + .sum(); + } + + private void validate(List<SingleMenu> singleMenus) { + validateDuplicate(singleMenus); + validatePerMenuAmount(singleMenus); + validateOnlyDrink(singleMenus); + validateTotalMenuAmount(singleMenus); + } + + private void validateDuplicate(List<SingleMenu> singleMenus) { + int count = (int) getMenuStream(singleMenus) + .distinct() + .count(); + + if (count != singleMenus.size()) { + throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage()); + } + } + + private void validateOnlyDrink(List<SingleMenu> singleMenus) { + int drinks = (int) getMenuStream(singleMenus) + .filter(menu -> menu.getMenuType() == DRINKS) + .count(); + + if (drinks > 0 && drinks == singleMenus.size()) { + throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage()); + } + } + + private Stream<Menu> getMenuStream(List<SingleMenu> singleMenus) { + return singleMenus.stream() + .map(singleOrder -> Menu.from(singleOrder.menu())); + } + + private void validatePerMenuAmount(List<SingleMenu> singleMenus) { + boolean present = singleMenus.stream() + .anyMatch(singleOrder -> singleOrder.amount() < 1); + if (present) { + throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage()); + } + } + + private void validateTotalMenuAmount(List<SingleMenu> singleMenus) { + int totalAmount = singleMenus.stream() + .mapToInt(SingleMenu::amount) + .sum(); + if (totalAmount >= MAX_MENU_AMOUNT.getValue()) { + throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage()); + } + } + + public int getAmountByMenu(MenuType menuType) { + return menuScript.keySet() + .stream() + .filter(target -> target.getMenuType() == menuType) + .mapToInt(menuScript::get) + .sum(); + } + + public Map<Menu, Integer> getMenuScript() { + return Collections.unmodifiableMap(menuScript); + } +}
Java
์ผ๋ฐ˜์ ์œผ๋กœ validate ๊ฒ€์ฆ ํ…Œ์ŠคํŠธ๋Š” public ๋ฉ”์„œ๋“œ๋ฅผ ํ…Œ์ŠคํŠธํ•˜์—ฌ ์ง„ํ–‰ํ•˜๋Š”๋ฐ, ๋ชจ๋“  private ๋ฉ”์„œ๋“œ๊ฐ€ ๋™์ผํ•œ ์˜ˆ์™ธ๋ฅผ ๋˜์ง€๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋ฉ”์‹œ์ง€ ๋‚ด์šฉ์„ ํ™•์ธํ•˜๋Š” ๋“ฑ ์„ธ๋ถ€์ ์ธ ๊ฒ€์ฆ ์ ˆ์ฐจ๊ฐ€ ํ•„์š”ํ•˜๋‹ค ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. `IllegalArgumentException`์ด ์ •ํ™•ํžˆ ์–ด๋А ์ง€์ ์—์„œ ๋ฐœ์ƒํ–ˆ๋Š”์ง€ ์•Œ๊ธฐ ์–ด๋ ค์šฐ๋‹ˆ๊นŒ์š”! ํ•˜์ง€๋งŒ ์ด๋ฒˆ ๋ฏธ์…˜์€ `์—๋Ÿฌ๋ฌธ ๋‚ด์šฉ์ด 2๊ฐ€์ง€`๋กœ ์ •ํ•ด์ ธ ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, ์ด์ „ ๋ฏธ์…˜๊ฐ™์ด `์—๋Ÿฌ๋ฌธ ๋‚ด์šฉ์œผ๋กœ ์„ธ๋ถ€์ ์ธ ํ…Œ์ŠคํŠธ`๋ฅผ ํ•˜๊ธฐ๊ฐ€ ์–ด๋ ค์› ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ์ €๋Š” ์„ธ๋ถ€ ๊ฒ€์ฆ์„ ์œ„ํ•ด **์ปค์Šคํ…€ ์˜ˆ์™ธ**๋ฅผ ๋„์ž…ํ•˜์—ฌ ์ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ–ˆ์—ˆ๋Š”๋ฐ, ์ฐธ๊ณ ํ•˜์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค :) ์กฐ๊ธˆ ์˜ค๋ฒ„์—”์ง€๋‹ˆ์–ด๋ง ๊ฐ™์€ ์ƒ๊ฐ๋„ ๋“ค์–ด ์˜ฌ๋ฐ”๋ฅธ ์ ‘๊ทผ ๋ฐฉ์‹์ธ์ง€๋Š” ์ž˜ ๋ชจ๋ฅด๊ฒ ๋„ค์š” ใ…Žใ…Ž..
@@ -0,0 +1,45 @@ +package christmas.util; + +import static christmas.constants.Day.FRIDAY; +import static christmas.constants.Day.SATURDAY; +import static christmas.constants.Day.SUNDAY; +import static christmas.constants.Day.THURSDAY; + +import christmas.constants.Day; +import java.util.Arrays; + +public class DayAnalyzer { + private static final int DAY_OF_WEEK = 7; + private static final int CHRISTMAS_DAY = 25; + + private static Day getDay(int date) { + return Arrays.stream(Day.values()) + .filter(day -> day.getIndex() == date % DAY_OF_WEEK) + .findFirst() + .orElseThrow(); + } + + public static boolean isWeekday(int date) { + Day targetDay = getDay(date); + if (targetDay.compareTo(THURSDAY) <= 0 && targetDay.compareTo(SUNDAY) >= 0) { + return true; + } + return false; + } + + public static boolean isWeekend(int date) { + Day targetDay = getDay(date); + if (targetDay == FRIDAY || targetDay == SATURDAY) { + return true; + } + return false; + } + + public static boolean isSpecialDay(int date) { + Day targetDay = getDay(date); + if (targetDay == SUNDAY || date == CHRISTMAS_DAY) { + return true; + } + return false; + } +}
Java
์ €๋Š” ๋‚ ์งœ๋ฅผ ํ•˜๋“œ์ฝ”๋”ฉํ•ด๋ฒ„๋ ธ๋Š”๋ฐ,,, DayAnalyzer ํด๋ž˜์Šค ์ •๋ง ์ง๊ด€์ ์ด๊ณ  ์ข‹์€ ์ ‘๊ทผ ๋ฐฉ์‹์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ๐Ÿ‘๐Ÿ‘
@@ -0,0 +1,7 @@ +package christmas.exception; + +import java.util.function.Supplier; + +public interface ExceptionHandler { + <T> T execute(Supplier<T> action, Class<? extends Exception>... exceptions); +}
Java
`Class<? extends Exception>... exceptions`๋Š” ์–ด๋–ค ์—ญํ• ์˜ ํŒŒ๋ผ๋ฏธํ„ฐ์ธ์ง€, ์–ด๋–ป๊ฒŒ ํ™œ์šฉ๋˜๋Š”์ง€ ์—ฌ์ญค๋ณด๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,30 @@ +package christmas.constants.event; + +public enum BadgeType { + NONE("์—†์Œ", 0), + STAR("๋ณ„", 5_000), + TREE("ํŠธ๋ฆฌ", 10_000), + SANTA("์‚ฐํƒ€", 20_000); + + private final String name; + private final int threshold; + + BadgeType(String name, int threshold) { + this.name = name; + this.threshold = threshold; + } + + public static BadgeType from(int benefitPrice) { + BadgeType result = NONE; + for (BadgeType badgeType : values()) { + if (benefitPrice >= badgeType.threshold) { + result = badgeType; + } + } + return result; + } + + public String getName() { + return name; + } +}
Java
stream์œผ๋กœ ์ตœ์ ํ™” ํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,13 @@ +package christmas.dto; + +import christmas.util.Parser; +import java.util.List; + +public record SingleMenu(String menu, int amount) { + private static final String DELIMITER = "-"; + + public static SingleMenu create(String singleOrder) { + List<String> parsed = Parser.parseToMenu(singleOrder, DELIMITER); + return new SingleMenu(parsed.get(0), Parser.parseToAmount(parsed.get(1))); + } +}
Java
SingleMenu๋ฅผ record๋กœ ํ•˜์‹  ์ด์œ ๊ฐ€ ๋ฌด์—‡์ธ๊ฐ€์š”?
@@ -0,0 +1,38 @@ +package christmas.exception; + +import christmas.view.output.OutputView; +import java.util.Arrays; +import java.util.function.Supplier; + +public class RetryHandler implements ExceptionHandler { + private final OutputView outputView; + + public RetryHandler(OutputView outputView) { + this.outputView = outputView; + } + + @Override + @SafeVarargs + public final <T> T execute(Supplier<T> action, Class<? extends Exception>... exceptions) { + while (true) { + try { + return action.get(); + } catch (IllegalArgumentException e) { + printException(e, exceptions); + } + } + } + + private void printException(Exception actual, Class<? extends Exception>... exceptions) { + if (isExpectedException(actual, exceptions)) { + outputView.printError(actual.getMessage()); + return; + } + throw new RuntimeException(actual); + } + + private boolean isExpectedException(Exception actual, Class<? extends Exception>... exceptions) { + return Arrays.stream(exceptions) + .anyMatch(exception -> exception.isInstance(actual)); + } +}
Java
@safevarargs๋Š” ์™œ ์‚ฌ์šฉํ•˜์‹ ๊ฑด๊ฐ€์š”?
@@ -0,0 +1,80 @@ +package christmas.service; + +import static christmas.constants.event.EventRule.EVENT_THRESHOLD; +import static christmas.constants.event.EventType.CHRISTMAS; +import static christmas.constants.event.EventType.PRESENT; +import static christmas.constants.event.EventType.SPECIAL; +import static christmas.constants.event.EventType.WEEKDAY; +import static christmas.constants.event.EventType.WEEKEND; + +import christmas.constants.event.EventType; +import christmas.dto.EventDetail; +import christmas.dto.UserOrder; +import christmas.model.ChristmasEvent; +import christmas.model.Eventable; +import christmas.model.PresentEvent; +import christmas.model.SpecialEvent; +import christmas.model.WeekdayEvent; +import christmas.model.WeekendEvent; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + +public class EventService { + private final Map<EventType, Eventable> eventResult; + private final int INVALID_VALUE = 0; + + public EventService() { + eventResult = new EnumMap<>(EventType.class); + } + + public void applyEvent(UserOrder userOrder) { + if (!canJoinEvent(userOrder.orderPrice())) { + userOrder = new UserOrder(INVALID_VALUE, INVALID_VALUE, INVALID_VALUE, INVALID_VALUE); + } + + eventResult.put(PRESENT, PresentEvent.create(userOrder.orderPrice())); + eventResult.put(CHRISTMAS, ChristmasEvent.create(userOrder.date())); + eventResult.put(WEEKDAY, WeekdayEvent.create(userOrder)); + eventResult.put(WEEKEND, WeekendEvent.create(userOrder)); + eventResult.put(SPECIAL, SpecialEvent.create(userOrder.date())); + } + + private boolean canJoinEvent(int orderPrice) { + if (orderPrice < EVENT_THRESHOLD.getValue()) { + return false; + } + return true; + } + + public int getDiscountPriceByEvent(EventType eventType) { + return eventResult.get(eventType).getDiscountPrice(); + } + + public int getExpectedPrice(UserOrder userOrder) { + return userOrder.orderPrice() - getTotalDiscountPrice(); + } + + public int getTotalDiscountPrice() { + return eventResult.entrySet() + .stream() + .filter(entry -> entry.getKey() != PRESENT) + .mapToInt(value -> value.getValue().getDiscountPrice()) + .sum(); + } + + public int getTotalBenefitPrice() { + return eventResult.values() + .stream() + .mapToInt(Eventable::getDiscountPrice) + .sum(); + } + + public List<EventDetail> convertToEventDetails() { + return eventResult.entrySet() + .stream() + .filter(entry -> entry.getValue().getDiscountPrice() != 0) + .map(entry -> new EventDetail(entry.getKey(), entry.getValue().getDiscountPrice())) + .toList(); + } +}
Java
์ด๋ฒคํŠธ๊ฐ€ ์ถ”๊ฐ€๋  ๋•Œ๋งˆ๋‹ค put์„ ํ•ด์•ผํ•˜๋Š” ๋ถˆํŽธํ•จ์ด ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,98 @@ +package christmas.service; + +import static christmas.constants.event.EventRule.MAX_MENU_AMOUNT; +import static christmas.constants.menu.MenuType.DRINKS; +import static christmas.exception.ErrorCode.INVALID_MENU_ORDER; + +import christmas.constants.menu.Menu; +import christmas.constants.menu.MenuType; +import christmas.dto.SingleMenu; +import java.util.Collections; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +public class MenuService { + private final Map<Menu, Integer> menuScript; + + public MenuService() { + this.menuScript = new EnumMap<>(Menu.class); + } + + public void order(List<SingleMenu> singleMenus) { + validate(singleMenus); + singleMenus.forEach(singleOrder -> { + Menu menu = Menu.from(singleOrder.menu()); + menuScript.put(menu, singleOrder.amount()); + }); + } + + public int getOrderPrice() { + return menuScript.keySet() + .stream() + .mapToInt(menu -> menu.getPrice() * menuScript.get(menu)) + .sum(); + } + + private void validate(List<SingleMenu> singleMenus) { + validateDuplicate(singleMenus); + validatePerMenuAmount(singleMenus); + validateOnlyDrink(singleMenus); + validateTotalMenuAmount(singleMenus); + } + + private void validateDuplicate(List<SingleMenu> singleMenus) { + int count = (int) getMenuStream(singleMenus) + .distinct() + .count(); + + if (count != singleMenus.size()) { + throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage()); + } + } + + private void validateOnlyDrink(List<SingleMenu> singleMenus) { + int drinks = (int) getMenuStream(singleMenus) + .filter(menu -> menu.getMenuType() == DRINKS) + .count(); + + if (drinks > 0 && drinks == singleMenus.size()) { + throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage()); + } + } + + private Stream<Menu> getMenuStream(List<SingleMenu> singleMenus) { + return singleMenus.stream() + .map(singleOrder -> Menu.from(singleOrder.menu())); + } + + private void validatePerMenuAmount(List<SingleMenu> singleMenus) { + boolean present = singleMenus.stream() + .anyMatch(singleOrder -> singleOrder.amount() < 1); + if (present) { + throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage()); + } + } + + private void validateTotalMenuAmount(List<SingleMenu> singleMenus) { + int totalAmount = singleMenus.stream() + .mapToInt(SingleMenu::amount) + .sum(); + if (totalAmount >= MAX_MENU_AMOUNT.getValue()) { + throw new IllegalArgumentException(INVALID_MENU_ORDER.getMessage()); + } + } + + public int getAmountByMenu(MenuType menuType) { + return menuScript.keySet() + .stream() + .filter(target -> target.getMenuType() == menuType) + .mapToInt(menuScript::get) + .sum(); + } + + public Map<Menu, Integer> getMenuScript() { + return Collections.unmodifiableMap(menuScript); + } +}
Java
stream์„ int๋กœ ์บ์ŠคํŒ…ํ•˜๋Š” ๊ฒƒ์ด ์ดํ•ด๊ฐ€ ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,167 @@ +## ํ•œ ์ค„๋กœ ํ‘œํ˜„ํ•˜๋Š” ํ•ต์‹ฌ ๊ธฐ๋Šฅ! + +> ๐ŸŽ„๋‚ ์งœ์™€ ์ฃผ๋ฌธ ๋‚ด์—ญ์˜ ์กฐ๊ฑด์— ๋งž์ถฐ 12์›” ํ• ์ธ ์ด๋ฒคํŠธ๋ฅผ ์ ์šฉํ•˜๊ธฐ + +--- + +### ๊ธฐ๋Šฅ ์š”๊ตฌ ์‚ฌํ•ญ + +1๏ธโƒฃ 12์›” ์ด๋ฒคํŠธ์™€ ๊ด€๋ จ๋œ ์ •๋ณด ์ž…๋ ฅ๋ฐ›๊ธฐ + +-[x] ์ธ์‚ฟ๋ง ์ถœ๋ ฅ +-[x] ์˜ˆ์ƒ ๋ฐฉ๋ฌธ ๋‚ ์งœ ์ž…๋ ฅ๋ฐ›๊ธฐ + -[x] โš ๏ธ ์œ ํšจํ•˜์ง€ ์•Š์€ ๊ฐ’์„ ๋ฐ›์•˜์„ ๋•Œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ + -[x] ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์ง€ ์•Š์•˜์„ ๋•Œ + -[x] 1์ผ์—์„œ 31์ผ ์‚ฌ์ด์˜ ์ˆ˜๊ฐ€ ์•„๋‹ ๋•Œ: *[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.* + -[x] ์œ ํšจํ•˜์ง€ ์•Š์€ ๊ฐ’์„ ์ž…๋ ฅ๋ฐ›์•˜์„ ๊ฒฝ์šฐ, ์œ ํšจํ•œ ๊ฐ’์„ ์ž…๋ ฅํ•  ๋•Œ๊นŒ์ง€ ๋‹ค์‹œ ์ž…๋ ฅ๋ฐ›๊ธฐ +-[x] ์ฃผ๋ฌธ ๋ฉ”๋‰ด ์ž…๋ ฅ๋ฐ›๊ธฐ + -[x] โš ๏ธ ์œ ํšจํ•˜์ง€ ์•Š์€ ๊ฐ’์„ ๋ฐ›์•˜์„ ๋•Œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ + -[x] ๋ฉ”๋‰ดํŒ์— ์—†๋Š” ๋ฉ”๋‰ด๋ฅผ ์ž…๋ ฅํ•˜๋Š” ๊ฒฝ์šฐ: *[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.* + -[x] ๋ฉ”๋‰ด์˜ ์ฃผ๋ฌธ ๊ฐœ์ˆ˜๊ฐ€ 1 ์ด์ƒ์˜ ์ˆซ์ž๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ: *[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.* + -[x] ์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธํ•œ ๊ฒฝ์šฐ: *[ERROR] ์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.* + -[x] ๋ฉ”๋‰ด ํ˜•์‹์ด ์˜ˆ์‹œ์™€ ๋‹ค๋ฅธ ๊ฒฝ์šฐ + -[x] `๋ฉ”๋‰ด๋ช…-๊ฐœ์ˆ˜`์˜ ํ˜•์‹์œผ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์ง€ ์•Š์€ ๊ฒฝ์šฐ + -[x] `๋ฉ”๋‰ด๋ช…-๊ฐœ์ˆ˜`๊ฐ€ ,๋ฅผ ํ†ตํ•ด ๊ตฌ๋ถ„๋˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ + -[x] ์ค‘๋ณต ๋ฉ”๋‰ด๋ฅผ ์ž…๋ ฅํ•œ ๊ฒฝ์šฐ: *[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.* + -[x] ์ฃผ๋ฌธํ•œ ๋ฉ”๋‰ด์˜ ์ด ๊ฐœ์ˆ˜๊ฐ€ 20๊ฐœ๋ฅผ ์ดˆ๊ณผํ•œ ๊ฒฝ์šฐ: *[ERROR] ๋ฉ”๋‰ด๋Š” ์ตœ๋Œ€ 20๊ฐœ๊นŒ์ง€๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.* + -[x] ์œ ํšจํ•˜์ง€ ์•Š์€ ๊ฐ’์„ ์ž…๋ ฅ๋ฐ›์•˜์„ ๊ฒฝ์šฐ, ์œ ํšจํ•œ ๊ฐ’์„ ์ž…๋ ฅํ•  ๋•Œ๊นŒ์ง€ ๋‹ค์‹œ ์ž…๋ ฅ๋ฐ›๊ธฐ + +2๏ธโƒฃ ์ฃผ๋ฌธ ๋ฉ”๋‰ด ์ถœ๋ ฅํ•˜๊ธฐ + +-[x] ์ž…๋ ฅ๋ฐ›์€ ์ฃผ๋ฌธ ๋ฉ”๋‰ด ์ถœ๋ ฅ + -[x] ์ฃผ๋ฌธ ๋ฉ”๋‰ด์˜ ์ถœ๋ ฅ ์ˆœ์„œ๋Š” ์ž์œ ๋กญ๊ฒŒ : ๐Ÿ”ฅ์—ํ”ผํƒ€์ด์ € - ๋ฉ”์ธ - ๋””์ €ํŠธ - ์Œ๋ฃŒ ์ˆœ์„œ๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค + -[x] ํฌ๋ฉง: ๋ฉ”๋‰ด "{๋ฉ”๋‰ด ์ด๋ฆ„} {x๊ฐœ}" ex) ์ œ๋กœ์ฝœ๋ผ 1๊ฐœ + +3๏ธโƒฃ ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก: MenuService + +-[x] ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก ์ถœ๋ ฅ + -[x] `๋ฉ”๋‰ด์˜ ๊ฐ€๊ฒฉ * ์ˆ˜๋Ÿ‰`์˜ ์ด ํ•ฉ๊ณ„ + +4๏ธโƒฃ ์ฆ์ • ๋ฉ”๋‰ดโœจ + +-[x] ์ด ์ฃผ๋ฌธ ๊ธˆ์•ก์„ ํ™•์ธํ•˜๊ณ , ๊ธˆ์•ก์— ๋”ฐ๋ผ ์ฆ์ • ์—ฌ๋ถ€ ๊ฒฐ์ • + -[x] ์ „๋‹ฌ๋ฐ›์€ ๋‚ ์งœ๋ฅผ ํ†ตํ•ด ์ฆ์ • ์—ฌ๋ถ€ ๊ฒฐ์ • + -[x] `์ด์ฃผ๋ฌธ ๊ธˆ์•ก`์ด `120,000์›` ์ด์ƒ์ธ ๊ฒฝ์šฐ, ์ฆ์ • ๊ฐœ์ˆ˜ 1๋กœ ์„ค์ • + -[x] `์ด์ฃผ๋ฌธ ๊ธˆ์•ก`์ด `120,000์›` ๋ฏธ๋งŒ์ธ ๊ฒฝ์šฐ, ์ฆ์ • ๊ฐœ์ˆ˜ 0์œผ๋กœ ์„ค์ • + -[x] ์กฐ๊ฑด์— ๋”ฐ๋ผ ์ฆ์ • ๊ฒฐ๊ณผ ์ถœ๋ ฅ + -[x] `์ด์ฃผ๋ฌธ ๊ธˆ์•ก`์ด `120,000์›` ์ด์ƒ์ธ ๊ฒฝ์šฐ, "์ƒดํŽ˜์ธ n๊ฐœ" ์ถœ๋ ฅ + -[x] `์ด์ฃผ๋ฌธ ๊ธˆ์•ก`์ด `120,000์›` ๋ฏธ๋งŒ์ธ ๊ฒฝ์šฐ, "์—†์Œ" ์ถœ๋ ฅ + +5๏ธโƒฃ ํ˜œํƒ ๋‚ด์—ญโœจ : DiscountService -> EventService + +-[x] ํ˜œํƒ์„ ๋ฐ›์„ ์ˆ˜ ์žˆ๋Š” ์กฐ๊ฑด์ธ์ง€ ํ™•์ธ + -[x] `์ด์ฃผ๋ฌธ๊ธˆ์•ก`์ด 10,000์› ์ด์ƒ์ธ์ง€ ํ™•์ธ +-[x] ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด ํ• ์ธ + -[x] 1์ผ๋ถ€ํ„ฐ 25์ผ ์‚ฌ์ด์˜ ๋‚ ์งœ์—๋งŒ ์ด๋ฒคํŠธ ์ ์šฉ + -[x] 1์ผ์— 1000์›๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜์—ฌ, ํ•˜๋ฃจ๊ฐ€ ์ง€๋‚ ์ˆ˜๋ก 100์›์”ฉ ์ถ”๊ฐ€ ํ• ์ธ + -[x] "ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด ํ• ์ธ: -1,200์›" ํ˜•ํƒœ๋กœ ์ถœ๋ ฅ +-[x] ํ‰์ผ ํ• ์ธ + -[x] ์ผ์š”์ผ~๋ชฉ์š”์ผ ์ง„ํ–‰ + -[x] `๋””์ €ํŠธ`๋ฉ”๋‰ด๋ฅผ `1๊ฐœ๋‹น 2023์›` ํ• ์ธ + -[x] "ํ‰์ผ ํ• ์ธ: -4,046์›" ํ˜•ํƒœ๋กœ ์ถœ๋ ฅ. ๋‹จ ํ• ์ธ์ด ์•ˆ๋˜๋Š” ๊ฒฝ์šฐ, ์ถœ๋ ฅ์„ ๋ณ„๋„๋กœ ํ•˜์ง€ ์•Š์Œ +-[x] ์ฃผ๋ง ํ• ์ธ + -[x] ๊ธˆ์š”์ผ~ํ† ์š”์ผ ์ง„ํ–‰ + -[x] `๋ฉ”์ธ`๋ฉ”๋‰ด๋ฅผ `1๊ฐœ๋‹น 2,023์›` ํ• ์ธ + -[x] "์ฃผ๋ง ํ• ์ธ: -1,000์›" ํ˜•ํƒœ๋กœ ์ถœ๋ ฅ. ๋‹จ ํ• ์ธ์ด ์•ˆ๋˜๋Š” ๊ฒฝ์šฐ, ์ถœ๋ ฅ์„ ๋ณ„๋„๋กœ ํ•˜์ง€ ์•Š์Œ +-[x] ํŠน๋ณ„ ํ• ์ธ + -[x] ์ด๋ฒคํŠธ ๋‹ฌ๋ ฅ์— ๋ณ„์ด ์žˆ๋Š” ๊ฒฝ์šฐ(๋งค์ฃผ ์ผ์š”์ผ + 25์ผ) + -[x] `์ด ๊ธˆ์•ก`์—์„œ `1000์›` ํ• ์ธ + -[x] "ํŠน๋ณ„ ํ• ์ธ: -1,000์›" ํ˜•ํƒœ๋กœ ์ถœ๋ ฅ. ๋‹จ ํ• ์ธ์ด ์•ˆ๋˜๋Š” ๊ฒฝ์šฐ, ์ถœ๋ ฅ์„ ๋ณ„๋„๋กœ ํ•˜์ง€ ์•Š์Œ +-[x] ํ˜œํƒ ๋‚ด์—ญ์— ๋Œ€ํ•ด ์ถœ๋ ฅ + -[x] ํฌ๋งท์€ {์ข…๋ฅ˜} ํ• ์ธ: -{ํ• ์ธ ๊ฐ€๊ฒฉ}์›. ์ด ๋•Œ, ๊ฐ€๊ฒฉ์€ 1000์˜ ๋‹จ์œ„๋กœ ์‰ผํ‘œ(,)๋ฅผ ๋„ฃ๋Š”๋‹ค + -[x] ๋งŒ์ผ, ๋ชจ๋“  ํ˜œํƒ์„ ๋ฐ›์ง€ ๋ชปํ•œ ๊ฒฝ์šฐ์—๋Š” "์—†์Œ"์œผ๋กœ ํ‘œ์‹œํ•œ๋‹ค + +6๏ธโƒฃ ์ดํ˜œํƒ ๊ธˆ์•ก : DiscountService -> EventService + +-[x] ์ดํ˜œํƒ ๊ธˆ์•ก์— ๋Œ€ํ•ด ๊ณ„์‚ฐ ๋ฐ ์ถœ๋ ฅ + -[x] ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด, ํ‰์ผ, ํŠน๋ณ„, ์ฆ์ • ์ด๋ฒคํŠธ ํ• ์ธ์„ ๋ชจ๋‘ ํ•ฉํ•œ ๊ฐ€๊ฒฉ์„ ํ‘œ์‹œํ•œ๋‹ค (์ด ํ• ์ธ ๊ธˆ์•ก + ์ฆ์ • ๋ฉ”๋‰ด์˜ ๊ฐ€๊ฒฉ) + -[x] ์•ž์— -๊ฐ€ ๋ถ™์œผ๋ฉฐ, 1000์˜ ๋‹จ์œ„๋งˆ๋‹ค ์‰ผํ‘œ(,)๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค + +7๏ธโƒฃ ํ• ์ธ ํ›„, ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก + +-[x] ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก์— ๋Œ€ํ•ด ๊ณ„์‚ฐ ๋ฐ ์ถœ๋ ฅ + -[x] `ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก` - `์ดํ˜œํƒ ๊ธˆ์•ก`์„ ๊ณ„์‚ฐํ•œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค + -[x] 1000์˜ ๋‹จ์œ„๋งˆ๋‹ค ์‰ผํ‘œ(,)๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค + +8๏ธโƒฃ 12์›” ์ด๋ฒคํŠธ ๋ฐฐ์ง€ + +-[x] ์ด๋ฒคํŠธ ๋ฐฐ์ง€: `์ด ํ˜œํƒ ๊ธˆ์•ก`์— ๋”ฐ๋ผ ๋ฐฐ์ง€ ๋ถ€์—ฌ ๋ฐ ์ถœ๋ ฅ + -[x] ์ด๋ฒคํŠธ ๋ฐฐ์ง€์— ๋Œ€ํ•ด ๊ณ„์‚ฐ + -[x] 5000 <= x < 10,000 : ๋ณ„ + -[x] 10,000 <= x < 20,000 : ํŠธ๋ฆฌ + -[x] 20,000 <= x : ์‚ฐํƒ€ + +--- + +### ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์š”๊ตฌ ์‚ฌํ•ญ + +-[x] ApplicationTest์˜ ๋ชจ๋“  ํ…Œ์ŠคํŠธ๊ฐ€ ์„ฑ๊ณตํ•ด์•ผ ํ•œ๋‹ค. +-[x] indent depth๋Š” 2๊นŒ์ง€ ํ—ˆ์šฉํ•œ๋‹ค. +-[x] ๋ฉ”์„œ๋“œ์˜ ๊ธธ์ด๊ฐ€ 15๋ฅผ ๋„˜์–ด๊ฐ€์ง€ ์•Š๋„๋ก ํ•œ๋‹ค. +-[x] ์‚ฌ์šฉ์ž๊ฐ€ ์ž˜๋ชป๋œ ๊ฐ’์„ ์ž…๋ ฅํ•œ ๊ฒฝ์šฐ, `IllegalArgumentException`์„ ๋ฐœ์ƒ์‹œํ‚ค๊ณ , `[ERROR]`๋กœ ์‹œ์ž‘ํ•˜๋Š” ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ์ถœ๋ ฅํ•œ ํ›„, ๊ทธ ๋ถ€๋ถ„๋ถ€ํ„ฐ ์ž…๋ ฅ์„ ๋‹ค์‹œ ๋ฐ›๋Š”๋‹ค. +-[x] ์ž…๋ ฅ๊ณผ ์ถœ๋ ฅ์„ ๋‹ด๋‹นํ•˜๋Š” ํด๋ž˜์Šค๋ฅผ ๋ณ„๋„๋กœ ๊ตฌํ˜„ํ•œ๋‹ค. + -[x] InputView: readDate()... + -[x] OutputView : printMenu()... +-[x] Console.readLine()์„ ํ™œ์šฉํ•œ๋‹ค. + +--- + +### 3์ฃผ์ฐจ ํ”ผ๋“œ๋ฐฑ ๋‚ด์šฉ + +-[x] 3์ฃผ์ฐจ ๊ณตํ†ตํ”ผ๋“œ๋ฐฑ ์ง€ํ‚ค๊ธฐ! +-[x] `Integer.parseInt()`๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ •์ˆ˜์˜ ๋ฒ”์œ„๊ฐ€ ์•„๋‹ ๋•Œ์—๋„ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜๋Š”๋ฐ, ์˜ˆ์™ธ ๋ฉ”์‹œ์ง€๋ฅด ์กฐ๊ธˆ ๋” ๊ผผ๊ผผํ•˜๊ฒŒ ์ฑ™๊ธฐ์ž +-[x] Enum์—์„œ ๋ฌธ์ž์—ด์„ ํ•ฉ์น  ๋•Œ `+`๋ณด๋‹ค๋Š”, `String.format()`์„ ์‚ฌ์šฉํ•˜์ž +-[x] `System.lineSeperator()`์™€ `String.format("%n")`์€ ๊ฐ™์€ ์—ญํ• ์„ ํ•œ๋‹ค. ํ™œ์šฉํ•ด๋ณด์ž! +-[x] ์š”๊ตฌ์‚ฌํ•ญ์„ ๊ผผ๊ผผํ•˜๊ฒŒ ์ฝ์ž. (์„ธ์ž๋ฆฌ๋งˆ๋‹ค ์‰ผํ‘œ๋ฅผ ๋„ฃ์–ด์ค€๋‹ค๋˜์ง€...) +-[x] ์ƒ์ˆ˜๋ฅผ enum์œผ๋กœ ๋บ์œผ๋ฉด ์ด๋ฅผ ํ™œ์šฉํ•˜์ž! ๋งค์ง ๋„˜๋ฒ„์˜ ์‚ฌ์šฉ์„ ์ค„์ด์ž! ํ™•์žฅ์„ฑ์„ ๊ณ ๋ คํ•œ ๊ตฌ์กฐ๋ฅผ ๋งŒ๋“ค์ž! +-[x] ์˜ˆ์™ธ๋ฅผ ๋‹ค์‹œ ๋ฐ›๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ ์žฌ๊ท€๋ฅผ ์‚ฌ์šฉํ–ˆ๋Š”๋ฐ, ๋ฉ”๋ชจ๋ฆฌ๊ฐ€ ํ„ฐ์งˆ ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๋‹ค. `Supplier`๋ฅผ ๋„์ž…ํ•ด๋ณด์ž. +-[x] ๊ฒ€์ฆ(Validate)๊ณผ ํŒŒ์‹ฑ(Parsing)์˜ ๋กœ์ง์„ ์–ด๋””์— ๋‘๋ฉด ์ข‹์„๊นŒ? ๊ณ ๋ฏผํ•ด๋ณด์ž. +-[x] ๋””๋ฏธํ„ฐ์˜ ๋ฒ•์น™! +-[x] `Console.close()`๋ฅผ ํ†ตํ•ด ์‚ฌ์šฉ ์™„๋ฃŒํ•œ ์ฝ˜์†”์„ ๋‹ซ์•„์ฃผ์ž + +--- + +### ๊ฐœ๋ฐœ ์ค‘ ์ž‘์„ฑํ•˜๋Š” ๋ฆฌํŒฉํ† ๋ง ๋ชฉ๋ก + +-[x] IoC ์ปจํ…Œ์ด๋„ˆ ์ ์šฉํ•˜๊ธฐ +-[x] Enum์ด ๋„ˆ๋ฌด ์šฐํ›„์ฃฝ์ˆœ ์ƒ๊ธด ๊ฒƒ ๊ฐ™๋‹ค! ์ •๋ฆฌํ•  ์ˆ˜ ์žˆ๋Š” ๋ถ€๋ถ„์€ ์ •๋ฆฌํ•ด๋ณด์ž +-[x] InputView, OutputView์—์„œ `readLine()`๊ณผ `System.out.print` ๋ถ€๋ถ„ ์ถ”์ƒํ™”ํ•˜๊ธฐ +-[x] `Supplier`๋ฅผ ์ด์šฉํ•˜์—ฌ ์žฌ์ž…๋ ฅ ์ฒ˜๋ฆฌํ•˜๊ธฐ +-[x] Validator(๊ฒ€์ฆ)์˜ ์—ญํ• ์ด ์ ์ ˆํ•˜๊ฒŒ ๋ถ„๋ฐฐ๋˜์–ด ์žˆ๋Š”์ง€ ํ™•์ธ + -[x] MenuService์˜ validate ํ•จ์ˆ˜๋“ค์— ๋Œ€ํ•ด ์ค‘๋ณต๋˜์–ด์žˆ๋Š” ์ฝ”๋“œ ์ฒ˜๋ฆฌํ•˜๊ธฐ +-[x] MenuService์˜ ์ฝ”๋“œ๊ฐ€ ์กฐ๊ธˆ ๋‚œ์žกํ•œ ๊ฒƒ ๊ฐ™์Œ +-[x] Message์˜ %n์— ๋Œ€ํ•ด ์–ด๋–ป๊ฒŒ...์ฒ˜๋ฆฌ ์ข€ ํ•˜๊ธฐ +-[ ] Parser์—์„œ parseToDate, parseToAmount์˜ ์ฝ”๋“œ๊ฐ€ ๊ฒน์นœ๋‹ค. ์ „๋‹ฌํ•˜๋Š” ์˜ˆ์™ธ ๋ฉ”์„ธ์ง€๋งŒ ๋‹ค๋ฅธ๋ฐ... ๋ฐฉ๋ฒ•์„ ์ฐพ์•„๋ณด์ž. +-[x] DiscountResult์— ๋„ˆ๋ฌด ๋งŽ์€ ์ฑ…์ž„์ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™๋‹ค! DiscountService์—๊ฒŒ ์ฑ…์ž„์„ ๋” ๋ถ€์—ฌํ•˜์ž. + -> DiscountResult -> EventResult -> EventService๋กœ ๋ณ€๊ฒฝ ๋ฐ ์—ญํ•  ๋ถ€์—ฌ +-[x] ๋ฉ”์„œ๋“œ, ๋ณ€์ˆ˜๋ช…์ด ์ ์ ˆํ•œ์ง€ ํ™•์ธ ํ›„ ์ˆ˜์ • +-[x] ๋ฉ”๋‰ด๋ฅผ ์ž˜๋ชป์ž…๋ ฅํ–ˆ์„ ๋•Œ `IndexOutOfBounds`๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด์„œ ์ข…๋ฃŒ๋œ๋‹ค. +-[x] OutputView์—์„œ formatting์„ ํ•˜๋ฉด์„œ ๊ฒน์น˜๋Š” ์ฝ”๋“œ๊ฐ€ ๊ณณ๊ณณ์— ์žˆ๋‹ค. ์ˆ˜์ •ํ•˜์ž! + +--- + +### ๊ตฌํ˜„ํ•˜๋ฉด์„œ ์ง‘์ค‘ํ–ˆ๋˜ ๋ถ€๋ถ„๋“ค! ๊ณ ๋ฏผ๊ฑฐ๋ฆฌ! + +#### โœ… Discountable(Eventable๋กœ ๋ณ€๊ฒฝ) ์ธํ„ฐํŽ˜์ด์Šค์— ์ œ๋„ˆ๋ฆญ์„ ์ ์šฉํ•˜์ž + +> ๐Ÿง ๊ณ ๋ฏผ ๋‚ด์šฉ ๐Ÿง +> ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด, ์ฆ์ • ์ด๋ฒคํŠธ, ํ‰์ผ ํ• ์ธ, ์ฃผ๋ง ํ• ์ธ, ํŠน๋ณ„ ํ• ์ธ ๋ชจ๋‘ ๊ฐ์ž๋งŒ์˜ ๊ณ ์œ ํ•œ ํ• ์ธ ์กฐ๊ฑด๋“ค์ด ์žˆ๋‹ค. +> ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด์™€ ์ฆ์ •์ด๋ฒคํŠธ๋Š” `์ด ์ฃผ๋ฌธ ๊ธˆ์•ก`๊ณผ `๋‚ ์งœ`๋ฅผ ํ™•์ธํ•˜๋ฉด ๋๋Š”๋ฐ, ์ด๋“ค์€ ๋ชจ๋‘ intํ˜•์œผ๋กœ ์ฒ˜๋ฆฌ๊ฐ€ ๊ฐ€๋Šฅํ–ˆ๋‹ค. +> +> ํ•˜์ง€๋งŒ ํ‰์ผ, ์ฃผ๋ง ํ• ์ธ์€ `๋‚ ์งœ`๋งŒ ๋ฐ›๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ, ๋ฉ”๋‰ด์— ๋Œ€ํ•œ ์ตœ์†Œํ•œ์˜ ์ •๋ณด๊ฐ€ ์ถ”๊ฐ€์ ์œผ๋กœ ํ•„์š”ํ–ˆ๋‹ค. +> ๋ชจ๋“  ํ• ์ธ ํด๋ž˜์Šค๋“ค์ด ๊ณตํ†ต์œผ๋กœ ๊ฐ€์ง€๊ณ  ์žˆ์–ด์•ผ ํ•˜๋Š” ๊ฒƒ๋“ค์„ `Discountable ์ธํ„ฐํŽ˜์ด์Šค(Eventable ์ธํ„ฐํŽ˜์ด์Šค๋กœ ๋ณ€๊ฒฝ)`๋กœ ํ‘œํ˜„ํ•˜๊ณ  ์‹ถ์€๋ฐ ์–ด๋–ป๊ฒŒ ํ•˜๋ฉด ์ข‹์„๊นŒ? + +์ด์— ๋Œ€ํ•ด ์ƒ๊ฐ๋‚œ ํ•ด๋‹ต์€ ๋ฐ”๋กœ `์ œ๋„ˆ๋ฆญ`์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด์—ˆ๋‹ค. +`์ œ๋„ˆ๋ฆญ`์„ ์‚ฌ์šฉํ•˜๋ฉด `canDiscount`์˜ ๋งค๊ฐœ๋ณ€์ˆ˜์— ์ž๋ฃŒํ˜•์— ์ƒ๊ด€์—†์ด ์ „๋‹ฌํ•˜๊ณ  ์‹ถ์€ ๋ฐ์ดํ„ฐ๋ฅผ ์ „๋‹ฌํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. +๋”ฐ๋ผ์„œ `Discountable` ์ธํ„ฐํŽ˜์ด์Šค์˜ `canDiscount()`์˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ „๋‹ฌ๋˜๋Š” ์กฐ๊ฑด(`condition`) `์ œ๋„ˆ๋ฆญ <T>`๋ฅผ ์ ์šฉํ–ˆ๋‹ค. + +<br> + +#### โœ… View์—์„œ ์ ์ ˆํžˆ ๋ณ€ํ™˜ํ•ด์„œ ์ „๋‹ฌํ•˜์ž. ๊ผญ String์œผ๋กœ ์ „๋‹ฌํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค. + +<br> + +#### โœ… ๋‹ค๋ฅธ ๊ณ„์ธต๊ณผ ๋ฐ์ดํ„ฐ๋ฅผ ์ฃผ๊ณ  ๋ฐ›์„ ๋•Œ์—๋Š” DTO๋ฅผ ์ด์šฉํ•˜์ž. + + +
Unknown
์ œ๋„ค๋ฆญ์„ ์‚ฌ์šฉํ•ด Discountable๋กœ ํ‘œํ˜„ํ•œ ๊ฒƒ์ด ๋งค์šฐ ์ธ์ƒ๊นŠ๋„ค์š”! ์ฝ”๋“œ ๋ฆฌ๋ทฐํ• ๋•Œ๋„ ๋ณด๋ฉด์„œ ๊ณต๋ถ€ํ•˜๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค ๐Ÿซก
@@ -0,0 +1,97 @@ +package christmas.config; + +import christmas.controller.EventController; +import christmas.exception.RetryHandler; +import christmas.service.EventService; +import christmas.service.MenuService; +import christmas.validator.InputValidator; +import christmas.view.input.ConsoleReader; +import christmas.view.input.InputView; +import christmas.view.input.Reader; +import christmas.view.output.ConsoleWriter; +import christmas.view.output.OutputView; +import christmas.view.output.Writer; + +public class AppConfig { + private static AppConfig appConfig; + private EventController eventController; + private EventService eventService; + private MenuService menuService; + private InputValidator inputValidator; + private RetryHandler retryHandler; + private InputView inputView; + private OutputView outputView; + private Reader reader; + private Writer writer; + + public static AppConfig getInstance() { + if (appConfig == null) { + appConfig = new AppConfig(); + } + return appConfig; + } + + public EventController eventController() { + if (eventController == null) { + eventController = new EventController(discountService(), menuService(), + inputView(), outputView(), exceptionHandler()); + } + return eventController; + } + + public EventService discountService() { + if (eventService == null) { + eventService = new EventService(); + } + return eventService; + } + + public MenuService menuService() { + if (menuService == null) { + menuService = new MenuService(); + } + return menuService; + } + + public RetryHandler exceptionHandler() { + if (retryHandler == null) { + retryHandler = new RetryHandler(outputView()); + } + return retryHandler; + } + + public InputView inputView() { + if (inputView == null) { + inputView = new InputView(reader(), inputValidator()); + } + return inputView; + } + + public InputValidator inputValidator() { + if (inputValidator == null) { + inputValidator = new InputValidator(); + } + return inputValidator; + } + + public Reader reader() { + if (reader == null) { + reader = new ConsoleReader(); + } + return reader; + } + + public OutputView outputView() { + if (outputView == null) { + outputView = new OutputView(writer()); + } + return outputView; + } + + public Writer writer() { + if (writer == null) { + writer = new ConsoleWriter(); + } + return writer; + } +}
Java
outview์˜ ๊ฒฝ์šฐ static๋ฉ”์„œ๋“œ๋ฅผ ํ™œ์šฉํ•ด ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜์ง€ ์•Š๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ๋Š”๋ฐ, ๊ทธ๋Ÿผ์—๋„ ์‹ฑ๊ธ€ํ†ค ํŒจํ„ด์„ ์œ ์ง€ํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,94 @@ +package christmas.controller; + +import static christmas.constants.event.EventType.PRESENT; +import static christmas.constants.menu.MenuType.DESSERT; +import static christmas.constants.menu.MenuType.MAIN; + +import christmas.constants.event.BadgeType; +import christmas.dto.SingleMenu; +import christmas.dto.UserOrder; +import christmas.exception.RetryHandler; +import christmas.service.EventService; +import christmas.service.MenuService; +import christmas.view.input.InputView; +import christmas.view.output.OutputView; +import java.util.List; + +public class EventController { + private final EventService eventService; + private final MenuService menuService; + private final InputView inputView; + private final OutputView outputView; + private final RetryHandler retryHandler; + + public EventController(EventService eventService, MenuService menuService, InputView inputView, + OutputView outputView, RetryHandler retryHandler) { + this.eventService = eventService; + this.menuService = menuService; + this.inputView = inputView; + this.outputView = outputView; + this.retryHandler = retryHandler; + } + + public void run() { + int visitDate = getVisitDate(); + UserOrder userOrder = receiveOrder(visitDate); + printOrderInformation(); + + applyEvent(userOrder); + printEventDetails(userOrder); + + printBadge(); + inputView.close(); + } + + private int getVisitDate() { + outputView.printGreeting(); + outputView.printAskVisitDate(); + + return retryHandler.execute(inputView::askVisitDate, IllegalArgumentException.class); + } + + private UserOrder receiveOrder(int visitDate) { + outputView.printAskMenu(); + UserOrder userOrder = retryHandler.execute(() -> getUserOrder(visitDate), IllegalArgumentException.class); + outputView.printPreview(visitDate); + + return userOrder; + } + + private UserOrder getUserOrder(int visitDate) { + List<SingleMenu> singleMenus = inputView.askOrderMenu(); + menuService.order(singleMenus); + return new UserOrder( + menuService.getOrderPrice(), + visitDate, + menuService.getAmountByMenu(MAIN), + menuService.getAmountByMenu(DESSERT) + ); + } + + private void printOrderInformation() { + outputView.printOrderMenu(menuService.getMenuScript()); + outputView.printBeforeDiscountPrice(menuService.getOrderPrice()); + } + + private void applyEvent(UserOrder userOrder) { + eventService.applyEvent(userOrder); + } + + private void printEventDetails(UserOrder userOrder) { + int discountPrice = eventService.getDiscountPriceByEvent(PRESENT); + int expectedPrice = eventService.getExpectedPrice(userOrder); + + outputView.printPresent(discountPrice); + outputView.printEventDetails(eventService.convertToEventDetails()); + outputView.printTotalBenefitPrice(eventService.getTotalBenefitPrice()); + outputView.printExpectedPrice(expectedPrice); + } + + private void printBadge() { + int totalDiscountPrice = eventService.getTotalBenefitPrice(); + outputView.printEventBadge(BadgeType.from(totalDiscountPrice)); + } +}
Java
print๋ผ๋Š” ๋„ค์ด๋ฐ์€ ์ปจํŠธ๋กค๋Ÿฌ๊ฐ€ ์ถœ๋ ฅ์„ ๋‹ด๋‹นํ•œ๋‹ค ๋ผ๋Š” ๋œป์œผ๋กœ ๋ณด์ž…๋‹ˆ๋‹ค! ๋‹ค๋ฅธ ๋ง๋กœ ๋Œ€์ฒด ํ•˜๋Š”๊ฑด ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์„ธ์š”?
@@ -0,0 +1,25 @@ +package christmas.constants.event; + +public enum EventRule { + EVENT_THRESHOLD(10_000), + PRESENT_THRESHOLD(120_000), + EVENT_START(1), + EVENT_END(31), + MAX_MENU_AMOUNT(20), + CHRISTMAS_EVENT_END(25), + CHRISTMAS_INIT_PRICE(1_000), + CHRISTMAS_EXTRA_DISCOUNT(100), + MENU_DISCOUNT(2_023), + SPECIAL_DISCOUNT(1_000); + + + private final int value; + + EventRule(int value) { + this.value = value; + } + + public int getValue() { + return value; + } +}
Java
๊ฐœ์ธ์ ์œผ๋กœ enum์€ ์—ฐ๊ด€๋œ ์ƒ์ˆ˜๋ฅผ ๋ชจ์•„๋‘๋Š” ๊ณณ์ด๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค! CHRISTMAS_EXTRA_DISCOUNT(100), MENU_DISCOUNT(2_023), ๋“ฑ์€ ์„œ๋กœ ๋‹ค๋ฅธ ๊ฐ์ฒด๋‹จ์œ„๋กœ ๋ถ„๋ฆฌ๊ฐ€ ๊ฐ€๋Šฅํ•ด๋ณด์—ฌ์š”! ์ฐจ๋ผ๋ฆฌ ๊ฐ์ฒด ๋‚ด๋ถ€์˜ ์ƒ์ˆ˜ ํ•„๋“œ๋กœ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒƒ์€ ์–ด๋– ์„ธ์š”?
@@ -0,0 +1,167 @@ +## ํ•œ ์ค„๋กœ ํ‘œํ˜„ํ•˜๋Š” ํ•ต์‹ฌ ๊ธฐ๋Šฅ! + +> ๐ŸŽ„๋‚ ์งœ์™€ ์ฃผ๋ฌธ ๋‚ด์—ญ์˜ ์กฐ๊ฑด์— ๋งž์ถฐ 12์›” ํ• ์ธ ์ด๋ฒคํŠธ๋ฅผ ์ ์šฉํ•˜๊ธฐ + +--- + +### ๊ธฐ๋Šฅ ์š”๊ตฌ ์‚ฌํ•ญ + +1๏ธโƒฃ 12์›” ์ด๋ฒคํŠธ์™€ ๊ด€๋ จ๋œ ์ •๋ณด ์ž…๋ ฅ๋ฐ›๊ธฐ + +-[x] ์ธ์‚ฟ๋ง ์ถœ๋ ฅ +-[x] ์˜ˆ์ƒ ๋ฐฉ๋ฌธ ๋‚ ์งœ ์ž…๋ ฅ๋ฐ›๊ธฐ + -[x] โš ๏ธ ์œ ํšจํ•˜์ง€ ์•Š์€ ๊ฐ’์„ ๋ฐ›์•˜์„ ๋•Œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ + -[x] ์ˆซ์ž๋ฅผ ์ž…๋ ฅํ•˜์ง€ ์•Š์•˜์„ ๋•Œ + -[x] 1์ผ์—์„œ 31์ผ ์‚ฌ์ด์˜ ์ˆ˜๊ฐ€ ์•„๋‹ ๋•Œ: *[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.* + -[x] ์œ ํšจํ•˜์ง€ ์•Š์€ ๊ฐ’์„ ์ž…๋ ฅ๋ฐ›์•˜์„ ๊ฒฝ์šฐ, ์œ ํšจํ•œ ๊ฐ’์„ ์ž…๋ ฅํ•  ๋•Œ๊นŒ์ง€ ๋‹ค์‹œ ์ž…๋ ฅ๋ฐ›๊ธฐ +-[x] ์ฃผ๋ฌธ ๋ฉ”๋‰ด ์ž…๋ ฅ๋ฐ›๊ธฐ + -[x] โš ๏ธ ์œ ํšจํ•˜์ง€ ์•Š์€ ๊ฐ’์„ ๋ฐ›์•˜์„ ๋•Œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ + -[x] ๋ฉ”๋‰ดํŒ์— ์—†๋Š” ๋ฉ”๋‰ด๋ฅผ ์ž…๋ ฅํ•˜๋Š” ๊ฒฝ์šฐ: *[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.* + -[x] ๋ฉ”๋‰ด์˜ ์ฃผ๋ฌธ ๊ฐœ์ˆ˜๊ฐ€ 1 ์ด์ƒ์˜ ์ˆซ์ž๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ: *[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.* + -[x] ์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธํ•œ ๊ฒฝ์šฐ: *[ERROR] ์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.* + -[x] ๋ฉ”๋‰ด ํ˜•์‹์ด ์˜ˆ์‹œ์™€ ๋‹ค๋ฅธ ๊ฒฝ์šฐ + -[x] `๋ฉ”๋‰ด๋ช…-๊ฐœ์ˆ˜`์˜ ํ˜•์‹์œผ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์ง€ ์•Š์€ ๊ฒฝ์šฐ + -[x] `๋ฉ”๋‰ด๋ช…-๊ฐœ์ˆ˜`๊ฐ€ ,๋ฅผ ํ†ตํ•ด ๊ตฌ๋ถ„๋˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ + -[x] ์ค‘๋ณต ๋ฉ”๋‰ด๋ฅผ ์ž…๋ ฅํ•œ ๊ฒฝ์šฐ: *[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.* + -[x] ์ฃผ๋ฌธํ•œ ๋ฉ”๋‰ด์˜ ์ด ๊ฐœ์ˆ˜๊ฐ€ 20๊ฐœ๋ฅผ ์ดˆ๊ณผํ•œ ๊ฒฝ์šฐ: *[ERROR] ๋ฉ”๋‰ด๋Š” ์ตœ๋Œ€ 20๊ฐœ๊นŒ์ง€๋งŒ ์ฃผ๋ฌธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.* + -[x] ์œ ํšจํ•˜์ง€ ์•Š์€ ๊ฐ’์„ ์ž…๋ ฅ๋ฐ›์•˜์„ ๊ฒฝ์šฐ, ์œ ํšจํ•œ ๊ฐ’์„ ์ž…๋ ฅํ•  ๋•Œ๊นŒ์ง€ ๋‹ค์‹œ ์ž…๋ ฅ๋ฐ›๊ธฐ + +2๏ธโƒฃ ์ฃผ๋ฌธ ๋ฉ”๋‰ด ์ถœ๋ ฅํ•˜๊ธฐ + +-[x] ์ž…๋ ฅ๋ฐ›์€ ์ฃผ๋ฌธ ๋ฉ”๋‰ด ์ถœ๋ ฅ + -[x] ์ฃผ๋ฌธ ๋ฉ”๋‰ด์˜ ์ถœ๋ ฅ ์ˆœ์„œ๋Š” ์ž์œ ๋กญ๊ฒŒ : ๐Ÿ”ฅ์—ํ”ผํƒ€์ด์ € - ๋ฉ”์ธ - ๋””์ €ํŠธ - ์Œ๋ฃŒ ์ˆœ์„œ๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค + -[x] ํฌ๋ฉง: ๋ฉ”๋‰ด "{๋ฉ”๋‰ด ์ด๋ฆ„} {x๊ฐœ}" ex) ์ œ๋กœ์ฝœ๋ผ 1๊ฐœ + +3๏ธโƒฃ ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก: MenuService + +-[x] ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก ์ถœ๋ ฅ + -[x] `๋ฉ”๋‰ด์˜ ๊ฐ€๊ฒฉ * ์ˆ˜๋Ÿ‰`์˜ ์ด ํ•ฉ๊ณ„ + +4๏ธโƒฃ ์ฆ์ • ๋ฉ”๋‰ดโœจ + +-[x] ์ด ์ฃผ๋ฌธ ๊ธˆ์•ก์„ ํ™•์ธํ•˜๊ณ , ๊ธˆ์•ก์— ๋”ฐ๋ผ ์ฆ์ • ์—ฌ๋ถ€ ๊ฒฐ์ • + -[x] ์ „๋‹ฌ๋ฐ›์€ ๋‚ ์งœ๋ฅผ ํ†ตํ•ด ์ฆ์ • ์—ฌ๋ถ€ ๊ฒฐ์ • + -[x] `์ด์ฃผ๋ฌธ ๊ธˆ์•ก`์ด `120,000์›` ์ด์ƒ์ธ ๊ฒฝ์šฐ, ์ฆ์ • ๊ฐœ์ˆ˜ 1๋กœ ์„ค์ • + -[x] `์ด์ฃผ๋ฌธ ๊ธˆ์•ก`์ด `120,000์›` ๋ฏธ๋งŒ์ธ ๊ฒฝ์šฐ, ์ฆ์ • ๊ฐœ์ˆ˜ 0์œผ๋กœ ์„ค์ • + -[x] ์กฐ๊ฑด์— ๋”ฐ๋ผ ์ฆ์ • ๊ฒฐ๊ณผ ์ถœ๋ ฅ + -[x] `์ด์ฃผ๋ฌธ ๊ธˆ์•ก`์ด `120,000์›` ์ด์ƒ์ธ ๊ฒฝ์šฐ, "์ƒดํŽ˜์ธ n๊ฐœ" ์ถœ๋ ฅ + -[x] `์ด์ฃผ๋ฌธ ๊ธˆ์•ก`์ด `120,000์›` ๋ฏธ๋งŒ์ธ ๊ฒฝ์šฐ, "์—†์Œ" ์ถœ๋ ฅ + +5๏ธโƒฃ ํ˜œํƒ ๋‚ด์—ญโœจ : DiscountService -> EventService + +-[x] ํ˜œํƒ์„ ๋ฐ›์„ ์ˆ˜ ์žˆ๋Š” ์กฐ๊ฑด์ธ์ง€ ํ™•์ธ + -[x] `์ด์ฃผ๋ฌธ๊ธˆ์•ก`์ด 10,000์› ์ด์ƒ์ธ์ง€ ํ™•์ธ +-[x] ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด ํ• ์ธ + -[x] 1์ผ๋ถ€ํ„ฐ 25์ผ ์‚ฌ์ด์˜ ๋‚ ์งœ์—๋งŒ ์ด๋ฒคํŠธ ์ ์šฉ + -[x] 1์ผ์— 1000์›๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜์—ฌ, ํ•˜๋ฃจ๊ฐ€ ์ง€๋‚ ์ˆ˜๋ก 100์›์”ฉ ์ถ”๊ฐ€ ํ• ์ธ + -[x] "ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด ํ• ์ธ: -1,200์›" ํ˜•ํƒœ๋กœ ์ถœ๋ ฅ +-[x] ํ‰์ผ ํ• ์ธ + -[x] ์ผ์š”์ผ~๋ชฉ์š”์ผ ์ง„ํ–‰ + -[x] `๋””์ €ํŠธ`๋ฉ”๋‰ด๋ฅผ `1๊ฐœ๋‹น 2023์›` ํ• ์ธ + -[x] "ํ‰์ผ ํ• ์ธ: -4,046์›" ํ˜•ํƒœ๋กœ ์ถœ๋ ฅ. ๋‹จ ํ• ์ธ์ด ์•ˆ๋˜๋Š” ๊ฒฝ์šฐ, ์ถœ๋ ฅ์„ ๋ณ„๋„๋กœ ํ•˜์ง€ ์•Š์Œ +-[x] ์ฃผ๋ง ํ• ์ธ + -[x] ๊ธˆ์š”์ผ~ํ† ์š”์ผ ์ง„ํ–‰ + -[x] `๋ฉ”์ธ`๋ฉ”๋‰ด๋ฅผ `1๊ฐœ๋‹น 2,023์›` ํ• ์ธ + -[x] "์ฃผ๋ง ํ• ์ธ: -1,000์›" ํ˜•ํƒœ๋กœ ์ถœ๋ ฅ. ๋‹จ ํ• ์ธ์ด ์•ˆ๋˜๋Š” ๊ฒฝ์šฐ, ์ถœ๋ ฅ์„ ๋ณ„๋„๋กœ ํ•˜์ง€ ์•Š์Œ +-[x] ํŠน๋ณ„ ํ• ์ธ + -[x] ์ด๋ฒคํŠธ ๋‹ฌ๋ ฅ์— ๋ณ„์ด ์žˆ๋Š” ๊ฒฝ์šฐ(๋งค์ฃผ ์ผ์š”์ผ + 25์ผ) + -[x] `์ด ๊ธˆ์•ก`์—์„œ `1000์›` ํ• ์ธ + -[x] "ํŠน๋ณ„ ํ• ์ธ: -1,000์›" ํ˜•ํƒœ๋กœ ์ถœ๋ ฅ. ๋‹จ ํ• ์ธ์ด ์•ˆ๋˜๋Š” ๊ฒฝ์šฐ, ์ถœ๋ ฅ์„ ๋ณ„๋„๋กœ ํ•˜์ง€ ์•Š์Œ +-[x] ํ˜œํƒ ๋‚ด์—ญ์— ๋Œ€ํ•ด ์ถœ๋ ฅ + -[x] ํฌ๋งท์€ {์ข…๋ฅ˜} ํ• ์ธ: -{ํ• ์ธ ๊ฐ€๊ฒฉ}์›. ์ด ๋•Œ, ๊ฐ€๊ฒฉ์€ 1000์˜ ๋‹จ์œ„๋กœ ์‰ผํ‘œ(,)๋ฅผ ๋„ฃ๋Š”๋‹ค + -[x] ๋งŒ์ผ, ๋ชจ๋“  ํ˜œํƒ์„ ๋ฐ›์ง€ ๋ชปํ•œ ๊ฒฝ์šฐ์—๋Š” "์—†์Œ"์œผ๋กœ ํ‘œ์‹œํ•œ๋‹ค + +6๏ธโƒฃ ์ดํ˜œํƒ ๊ธˆ์•ก : DiscountService -> EventService + +-[x] ์ดํ˜œํƒ ๊ธˆ์•ก์— ๋Œ€ํ•ด ๊ณ„์‚ฐ ๋ฐ ์ถœ๋ ฅ + -[x] ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด, ํ‰์ผ, ํŠน๋ณ„, ์ฆ์ • ์ด๋ฒคํŠธ ํ• ์ธ์„ ๋ชจ๋‘ ํ•ฉํ•œ ๊ฐ€๊ฒฉ์„ ํ‘œ์‹œํ•œ๋‹ค (์ด ํ• ์ธ ๊ธˆ์•ก + ์ฆ์ • ๋ฉ”๋‰ด์˜ ๊ฐ€๊ฒฉ) + -[x] ์•ž์— -๊ฐ€ ๋ถ™์œผ๋ฉฐ, 1000์˜ ๋‹จ์œ„๋งˆ๋‹ค ์‰ผํ‘œ(,)๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค + +7๏ธโƒฃ ํ• ์ธ ํ›„, ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก + +-[x] ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก์— ๋Œ€ํ•ด ๊ณ„์‚ฐ ๋ฐ ์ถœ๋ ฅ + -[x] `ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก` - `์ดํ˜œํƒ ๊ธˆ์•ก`์„ ๊ณ„์‚ฐํ•œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค + -[x] 1000์˜ ๋‹จ์œ„๋งˆ๋‹ค ์‰ผํ‘œ(,)๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค + +8๏ธโƒฃ 12์›” ์ด๋ฒคํŠธ ๋ฐฐ์ง€ + +-[x] ์ด๋ฒคํŠธ ๋ฐฐ์ง€: `์ด ํ˜œํƒ ๊ธˆ์•ก`์— ๋”ฐ๋ผ ๋ฐฐ์ง€ ๋ถ€์—ฌ ๋ฐ ์ถœ๋ ฅ + -[x] ์ด๋ฒคํŠธ ๋ฐฐ์ง€์— ๋Œ€ํ•ด ๊ณ„์‚ฐ + -[x] 5000 <= x < 10,000 : ๋ณ„ + -[x] 10,000 <= x < 20,000 : ํŠธ๋ฆฌ + -[x] 20,000 <= x : ์‚ฐํƒ€ + +--- + +### ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์š”๊ตฌ ์‚ฌํ•ญ + +-[x] ApplicationTest์˜ ๋ชจ๋“  ํ…Œ์ŠคํŠธ๊ฐ€ ์„ฑ๊ณตํ•ด์•ผ ํ•œ๋‹ค. +-[x] indent depth๋Š” 2๊นŒ์ง€ ํ—ˆ์šฉํ•œ๋‹ค. +-[x] ๋ฉ”์„œ๋“œ์˜ ๊ธธ์ด๊ฐ€ 15๋ฅผ ๋„˜์–ด๊ฐ€์ง€ ์•Š๋„๋ก ํ•œ๋‹ค. +-[x] ์‚ฌ์šฉ์ž๊ฐ€ ์ž˜๋ชป๋œ ๊ฐ’์„ ์ž…๋ ฅํ•œ ๊ฒฝ์šฐ, `IllegalArgumentException`์„ ๋ฐœ์ƒ์‹œํ‚ค๊ณ , `[ERROR]`๋กœ ์‹œ์ž‘ํ•˜๋Š” ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ์ถœ๋ ฅํ•œ ํ›„, ๊ทธ ๋ถ€๋ถ„๋ถ€ํ„ฐ ์ž…๋ ฅ์„ ๋‹ค์‹œ ๋ฐ›๋Š”๋‹ค. +-[x] ์ž…๋ ฅ๊ณผ ์ถœ๋ ฅ์„ ๋‹ด๋‹นํ•˜๋Š” ํด๋ž˜์Šค๋ฅผ ๋ณ„๋„๋กœ ๊ตฌํ˜„ํ•œ๋‹ค. + -[x] InputView: readDate()... + -[x] OutputView : printMenu()... +-[x] Console.readLine()์„ ํ™œ์šฉํ•œ๋‹ค. + +--- + +### 3์ฃผ์ฐจ ํ”ผ๋“œ๋ฐฑ ๋‚ด์šฉ + +-[x] 3์ฃผ์ฐจ ๊ณตํ†ตํ”ผ๋“œ๋ฐฑ ์ง€ํ‚ค๊ธฐ! +-[x] `Integer.parseInt()`๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ •์ˆ˜์˜ ๋ฒ”์œ„๊ฐ€ ์•„๋‹ ๋•Œ์—๋„ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜๋Š”๋ฐ, ์˜ˆ์™ธ ๋ฉ”์‹œ์ง€๋ฅด ์กฐ๊ธˆ ๋” ๊ผผ๊ผผํ•˜๊ฒŒ ์ฑ™๊ธฐ์ž +-[x] Enum์—์„œ ๋ฌธ์ž์—ด์„ ํ•ฉ์น  ๋•Œ `+`๋ณด๋‹ค๋Š”, `String.format()`์„ ์‚ฌ์šฉํ•˜์ž +-[x] `System.lineSeperator()`์™€ `String.format("%n")`์€ ๊ฐ™์€ ์—ญํ• ์„ ํ•œ๋‹ค. ํ™œ์šฉํ•ด๋ณด์ž! +-[x] ์š”๊ตฌ์‚ฌํ•ญ์„ ๊ผผ๊ผผํ•˜๊ฒŒ ์ฝ์ž. (์„ธ์ž๋ฆฌ๋งˆ๋‹ค ์‰ผํ‘œ๋ฅผ ๋„ฃ์–ด์ค€๋‹ค๋˜์ง€...) +-[x] ์ƒ์ˆ˜๋ฅผ enum์œผ๋กœ ๋บ์œผ๋ฉด ์ด๋ฅผ ํ™œ์šฉํ•˜์ž! ๋งค์ง ๋„˜๋ฒ„์˜ ์‚ฌ์šฉ์„ ์ค„์ด์ž! ํ™•์žฅ์„ฑ์„ ๊ณ ๋ คํ•œ ๊ตฌ์กฐ๋ฅผ ๋งŒ๋“ค์ž! +-[x] ์˜ˆ์™ธ๋ฅผ ๋‹ค์‹œ ๋ฐ›๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ ์žฌ๊ท€๋ฅผ ์‚ฌ์šฉํ–ˆ๋Š”๋ฐ, ๋ฉ”๋ชจ๋ฆฌ๊ฐ€ ํ„ฐ์งˆ ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๋‹ค. `Supplier`๋ฅผ ๋„์ž…ํ•ด๋ณด์ž. +-[x] ๊ฒ€์ฆ(Validate)๊ณผ ํŒŒ์‹ฑ(Parsing)์˜ ๋กœ์ง์„ ์–ด๋””์— ๋‘๋ฉด ์ข‹์„๊นŒ? ๊ณ ๋ฏผํ•ด๋ณด์ž. +-[x] ๋””๋ฏธํ„ฐ์˜ ๋ฒ•์น™! +-[x] `Console.close()`๋ฅผ ํ†ตํ•ด ์‚ฌ์šฉ ์™„๋ฃŒํ•œ ์ฝ˜์†”์„ ๋‹ซ์•„์ฃผ์ž + +--- + +### ๊ฐœ๋ฐœ ์ค‘ ์ž‘์„ฑํ•˜๋Š” ๋ฆฌํŒฉํ† ๋ง ๋ชฉ๋ก + +-[x] IoC ์ปจํ…Œ์ด๋„ˆ ์ ์šฉํ•˜๊ธฐ +-[x] Enum์ด ๋„ˆ๋ฌด ์šฐํ›„์ฃฝ์ˆœ ์ƒ๊ธด ๊ฒƒ ๊ฐ™๋‹ค! ์ •๋ฆฌํ•  ์ˆ˜ ์žˆ๋Š” ๋ถ€๋ถ„์€ ์ •๋ฆฌํ•ด๋ณด์ž +-[x] InputView, OutputView์—์„œ `readLine()`๊ณผ `System.out.print` ๋ถ€๋ถ„ ์ถ”์ƒํ™”ํ•˜๊ธฐ +-[x] `Supplier`๋ฅผ ์ด์šฉํ•˜์—ฌ ์žฌ์ž…๋ ฅ ์ฒ˜๋ฆฌํ•˜๊ธฐ +-[x] Validator(๊ฒ€์ฆ)์˜ ์—ญํ• ์ด ์ ์ ˆํ•˜๊ฒŒ ๋ถ„๋ฐฐ๋˜์–ด ์žˆ๋Š”์ง€ ํ™•์ธ + -[x] MenuService์˜ validate ํ•จ์ˆ˜๋“ค์— ๋Œ€ํ•ด ์ค‘๋ณต๋˜์–ด์žˆ๋Š” ์ฝ”๋“œ ์ฒ˜๋ฆฌํ•˜๊ธฐ +-[x] MenuService์˜ ์ฝ”๋“œ๊ฐ€ ์กฐ๊ธˆ ๋‚œ์žกํ•œ ๊ฒƒ ๊ฐ™์Œ +-[x] Message์˜ %n์— ๋Œ€ํ•ด ์–ด๋–ป๊ฒŒ...์ฒ˜๋ฆฌ ์ข€ ํ•˜๊ธฐ +-[ ] Parser์—์„œ parseToDate, parseToAmount์˜ ์ฝ”๋“œ๊ฐ€ ๊ฒน์นœ๋‹ค. ์ „๋‹ฌํ•˜๋Š” ์˜ˆ์™ธ ๋ฉ”์„ธ์ง€๋งŒ ๋‹ค๋ฅธ๋ฐ... ๋ฐฉ๋ฒ•์„ ์ฐพ์•„๋ณด์ž. +-[x] DiscountResult์— ๋„ˆ๋ฌด ๋งŽ์€ ์ฑ…์ž„์ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™๋‹ค! DiscountService์—๊ฒŒ ์ฑ…์ž„์„ ๋” ๋ถ€์—ฌํ•˜์ž. + -> DiscountResult -> EventResult -> EventService๋กœ ๋ณ€๊ฒฝ ๋ฐ ์—ญํ•  ๋ถ€์—ฌ +-[x] ๋ฉ”์„œ๋“œ, ๋ณ€์ˆ˜๋ช…์ด ์ ์ ˆํ•œ์ง€ ํ™•์ธ ํ›„ ์ˆ˜์ • +-[x] ๋ฉ”๋‰ด๋ฅผ ์ž˜๋ชป์ž…๋ ฅํ–ˆ์„ ๋•Œ `IndexOutOfBounds`๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด์„œ ์ข…๋ฃŒ๋œ๋‹ค. +-[x] OutputView์—์„œ formatting์„ ํ•˜๋ฉด์„œ ๊ฒน์น˜๋Š” ์ฝ”๋“œ๊ฐ€ ๊ณณ๊ณณ์— ์žˆ๋‹ค. ์ˆ˜์ •ํ•˜์ž! + +--- + +### ๊ตฌํ˜„ํ•˜๋ฉด์„œ ์ง‘์ค‘ํ–ˆ๋˜ ๋ถ€๋ถ„๋“ค! ๊ณ ๋ฏผ๊ฑฐ๋ฆฌ! + +#### โœ… Discountable(Eventable๋กœ ๋ณ€๊ฒฝ) ์ธํ„ฐํŽ˜์ด์Šค์— ์ œ๋„ˆ๋ฆญ์„ ์ ์šฉํ•˜์ž + +> ๐Ÿง ๊ณ ๋ฏผ ๋‚ด์šฉ ๐Ÿง +> ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด, ์ฆ์ • ์ด๋ฒคํŠธ, ํ‰์ผ ํ• ์ธ, ์ฃผ๋ง ํ• ์ธ, ํŠน๋ณ„ ํ• ์ธ ๋ชจ๋‘ ๊ฐ์ž๋งŒ์˜ ๊ณ ์œ ํ•œ ํ• ์ธ ์กฐ๊ฑด๋“ค์ด ์žˆ๋‹ค. +> ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด์™€ ์ฆ์ •์ด๋ฒคํŠธ๋Š” `์ด ์ฃผ๋ฌธ ๊ธˆ์•ก`๊ณผ `๋‚ ์งœ`๋ฅผ ํ™•์ธํ•˜๋ฉด ๋๋Š”๋ฐ, ์ด๋“ค์€ ๋ชจ๋‘ intํ˜•์œผ๋กœ ์ฒ˜๋ฆฌ๊ฐ€ ๊ฐ€๋Šฅํ–ˆ๋‹ค. +> +> ํ•˜์ง€๋งŒ ํ‰์ผ, ์ฃผ๋ง ํ• ์ธ์€ `๋‚ ์งœ`๋งŒ ๋ฐ›๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ, ๋ฉ”๋‰ด์— ๋Œ€ํ•œ ์ตœ์†Œํ•œ์˜ ์ •๋ณด๊ฐ€ ์ถ”๊ฐ€์ ์œผ๋กœ ํ•„์š”ํ–ˆ๋‹ค. +> ๋ชจ๋“  ํ• ์ธ ํด๋ž˜์Šค๋“ค์ด ๊ณตํ†ต์œผ๋กœ ๊ฐ€์ง€๊ณ  ์žˆ์–ด์•ผ ํ•˜๋Š” ๊ฒƒ๋“ค์„ `Discountable ์ธํ„ฐํŽ˜์ด์Šค(Eventable ์ธํ„ฐํŽ˜์ด์Šค๋กœ ๋ณ€๊ฒฝ)`๋กœ ํ‘œํ˜„ํ•˜๊ณ  ์‹ถ์€๋ฐ ์–ด๋–ป๊ฒŒ ํ•˜๋ฉด ์ข‹์„๊นŒ? + +์ด์— ๋Œ€ํ•ด ์ƒ๊ฐ๋‚œ ํ•ด๋‹ต์€ ๋ฐ”๋กœ `์ œ๋„ˆ๋ฆญ`์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด์—ˆ๋‹ค. +`์ œ๋„ˆ๋ฆญ`์„ ์‚ฌ์šฉํ•˜๋ฉด `canDiscount`์˜ ๋งค๊ฐœ๋ณ€์ˆ˜์— ์ž๋ฃŒํ˜•์— ์ƒ๊ด€์—†์ด ์ „๋‹ฌํ•˜๊ณ  ์‹ถ์€ ๋ฐ์ดํ„ฐ๋ฅผ ์ „๋‹ฌํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. +๋”ฐ๋ผ์„œ `Discountable` ์ธํ„ฐํŽ˜์ด์Šค์˜ `canDiscount()`์˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ „๋‹ฌ๋˜๋Š” ์กฐ๊ฑด(`condition`) `์ œ๋„ˆ๋ฆญ <T>`๋ฅผ ์ ์šฉํ–ˆ๋‹ค. + +<br> + +#### โœ… View์—์„œ ์ ์ ˆํžˆ ๋ณ€ํ™˜ํ•ด์„œ ์ „๋‹ฌํ•˜์ž. ๊ผญ String์œผ๋กœ ์ „๋‹ฌํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค. + +<br> + +#### โœ… ๋‹ค๋ฅธ ๊ณ„์ธต๊ณผ ๋ฐ์ดํ„ฐ๋ฅผ ์ฃผ๊ณ  ๋ฐ›์„ ๋•Œ์—๋Š” DTO๋ฅผ ์ด์šฉํ•˜์ž. + + +
Unknown
๊ณ ๋ฏผ ๋‚ด์šฉ์„ ์ ์œผ์‹  ๊ฒƒ... ์ฐธ์‹ ํ•˜๋„ค์š” !! ์ €๋Š” ๋ฆฌ๋“œ๋ฏธ ์ž‘์„ฑ์ด ํž˜๋“ค์–ด์„œ ใ… .ใ…  ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค ๐Ÿ˜Š
@@ -0,0 +1,24 @@ +package com.requestrealpiano.songrequest.controller; + +import com.requestrealpiano.songrequest.service.AccountService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RequiredArgsConstructor +@RestController +@RequestMapping("/api/accounts") +public class AccountController { + + private final AccountService accountService; + + @GetMapping("/auth") + public ResponseEntity<Void> generateToken(@RequestHeader HttpHeaders httpHeaders) { + String jwtToken = accountService.generateJwtToken(httpHeaders.getFirst(HttpHeaders.AUTHORIZATION)); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.add(HttpHeaders.AUTHORIZATION, jwtToken); + return new ResponseEntity<>(responseHeaders, HttpStatus.NO_CONTENT); + } +}
Java
๋‹ค๋ฅธ ์ปจํŠธ๋กค๋Ÿฌ์—์„œ๋Š” ResponseStatus๋กœ ์ง€์ •ํ–ˆ๋Š”๋ฐ ์—ฌ๊ธด ResponseEntity๋กœ ์ง€์ •ํ–ˆ๊ตฐ์š” ์–ด๋–ค ์ด์œ ๋กœ ์ง€์ •ํ–ˆ๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค.
@@ -2,18 +2,18 @@ import com.requestrealpiano.songrequest.domain.song.searchapi.response.SearchApiResponse; import com.requestrealpiano.songrequest.global.response.ApiResponse; +import com.requestrealpiano.songrequest.global.response.StatusCode; import com.requestrealpiano.songrequest.service.SongService; import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import javax.validation.constraints.Size; import static com.requestrealpiano.songrequest.global.constant.ValidationCondition.*; -import static com.requestrealpiano.songrequest.global.response.ApiResponse.OK; +import static com.requestrealpiano.songrequest.global.response.ApiResponse.SUCCESS; +import static com.requestrealpiano.songrequest.global.response.StatusCode.OK; @RequiredArgsConstructor @Validated @@ -23,12 +23,13 @@ public class SongController { private final SongService songService; + @ResponseStatus(HttpStatus.OK) @GetMapping public ApiResponse<SearchApiResponse> search(@RequestParam(defaultValue = "artist") @Size(max = ARTIST_MAX) String artist, @RequestParam(defaultValue = "title") @Size(max = TITLE_MAX) String title) { SearchApiResponse searchApiResponse = songService.searchSong(artist, title); - return OK(searchApiResponse); + return SUCCESS(OK, searchApiResponse); } }
Java
์ด ๋ถ€๋ถ„์€ ์ปจํŠธ๋กค๋Ÿฌ์—์„œ Validation์„ ์žก๊ธฐ๋ณด๋‹จ Validation DTO๋ฅผ ์ƒ์„ฑํ•ด์„œ ํ•ด๋‹น ๊ฐ์ฒด์—์„œ ๊ด€๋ฆฌํ•˜๋ฉด ๋”์šฑ ํŽธ๋ฆฌํ•˜๊ณ  ๋ณด๊ธฐ๊ฐ€ ์ข‹์„๋“ฏ ํ•ฉ๋‹ˆ๋‹ค.
@@ -1,5 +1,6 @@ package com.requestrealpiano.songrequest.domain.account; +import com.requestrealpiano.songrequest.security.oauth.OAuthAttributes; import com.requestrealpiano.songrequest.domain.base.BaseTimeEntity; import com.requestrealpiano.songrequest.domain.letter.Letter; import lombok.AccessLevel; @@ -8,9 +9,6 @@ import lombok.NoArgsConstructor; import javax.persistence.*; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; import java.util.ArrayList; import java.util.List; @@ -25,7 +23,7 @@ public class Account extends BaseTimeEntity { private Long id; @Column(name = "google_oauth_id") - private Long googleOauthId; + private String googleOauthId; private String name; @@ -44,12 +42,36 @@ public class Account extends BaseTimeEntity { private List<Letter> letters = new ArrayList<>(); @Builder - private Account(Long googleOauthId, String name, String email, Role role, String avatarUrl, Integer requestCount) { + private Account(String googleOauthId, String name, String email, Role role, String avatarUrl, Integer requestCount) { this.googleOauthId = googleOauthId; this.name = name; this.email = email; this.role = role; this.avatarUrl = avatarUrl; this.requestCount = requestCount; } + + public String getRoleKey() { return role.getKey(); } + + public String getRoleValue() { + return role.getValue(); + } + + public Account updateProfile(OAuthAttributes attributes) { + this.name = attributes.getName(); + this.email = attributes.getEmail(); + this.avatarUrl = attributes.getAvatarUrl(); + return this; + } + + public static Account from(OAuthAttributes oAuthAttributes) { + return Account.builder() + .googleOauthId(oAuthAttributes.getGoogleOauthId()) + .name(oAuthAttributes.getName()) + .email(oAuthAttributes.getEmail()) + .role(Role.MEMBER) + .avatarUrl(oAuthAttributes.getAvatarUrl()) + .requestCount(0) + .build(); + } }
Java
์—Œใ…‹ใ…‹ใ…‹ใ…‹ OAuthId๋ฅผ ํ™•์ธํ•˜์‹œ๊ณ  ๋ฐ”๊พธ์…จ๊ตฐ์š”.
@@ -1,5 +1,6 @@ package com.requestrealpiano.songrequest.domain.account; +import com.requestrealpiano.songrequest.security.oauth.OAuthAttributes; import com.requestrealpiano.songrequest.domain.base.BaseTimeEntity; import com.requestrealpiano.songrequest.domain.letter.Letter; import lombok.AccessLevel; @@ -8,9 +9,6 @@ import lombok.NoArgsConstructor; import javax.persistence.*; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; import java.util.ArrayList; import java.util.List; @@ -25,7 +23,7 @@ public class Account extends BaseTimeEntity { private Long id; @Column(name = "google_oauth_id") - private Long googleOauthId; + private String googleOauthId; private String name; @@ -44,12 +42,36 @@ public class Account extends BaseTimeEntity { private List<Letter> letters = new ArrayList<>(); @Builder - private Account(Long googleOauthId, String name, String email, Role role, String avatarUrl, Integer requestCount) { + private Account(String googleOauthId, String name, String email, Role role, String avatarUrl, Integer requestCount) { this.googleOauthId = googleOauthId; this.name = name; this.email = email; this.role = role; this.avatarUrl = avatarUrl; this.requestCount = requestCount; } + + public String getRoleKey() { return role.getKey(); } + + public String getRoleValue() { + return role.getValue(); + } + + public Account updateProfile(OAuthAttributes attributes) { + this.name = attributes.getName(); + this.email = attributes.getEmail(); + this.avatarUrl = attributes.getAvatarUrl(); + return this; + } + + public static Account from(OAuthAttributes oAuthAttributes) { + return Account.builder() + .googleOauthId(oAuthAttributes.getGoogleOauthId()) + .name(oAuthAttributes.getName()) + .email(oAuthAttributes.getEmail()) + .role(Role.MEMBER) + .avatarUrl(oAuthAttributes.getAvatarUrl()) + .requestCount(0) + .build(); + } }
Java
์—ฌ๊ธฐ ์ ํ˜€์žˆ๋Š” MaginNumber 0์€ ์–ด๋–ค์˜๋ฏธ์ธ๊ฐ€์š”?
@@ -11,6 +11,12 @@ public enum ErrorCode { METHOD_NOT_ALLOWED(405, "์ง€์›ํ•˜์ง€ ์•Š๋Š” ์š”์ฒญ ๋ฉ”์†Œ๋“œ ์ž…๋‹ˆ๋‹ค."), INTERNAL_SERVER_ERROR(500, "์„œ๋ฒ„์—์„œ ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค."), + // Auth + UNAUTHENTICATED_ERROR(401, "์ธ์ฆ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ๋กœ๊ทธ์ธ ์ดํ›„ ๋‹ค์‹œ ์‹œ๋„ ํ•ด์ฃผ์„ธ์š”."), + JWT_INVALID_ERROR(400, "์˜ฌ๋ฐ”๋ฅธ ์ธ์ฆ ์ •๋ณด๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค. ๋‹ค์‹œ ๋กœ๊ทธ์ธ ํ•ด์ฃผ์„ธ์š”."), + JWT_EXPIRATION_ERROR(401, "์ธ์ฆ ์ •๋ณด๊ฐ€ ๋งŒ๋ฃŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ๋กœ๊ทธ์ธ ํ•ด์ฃผ์„ธ์š”."), + ACCESS_DENIED_ERROR(403, "ํ•ด๋‹น ์š”์ฒญ์— ๋Œ€ํ•œ ์ ‘๊ทผ ๊ถŒํ•œ์ด ์—†์Šต๋‹ˆ๋‹ค."), + // Account ACCOUNT_NOT_FOUND(404, "ํ•ด๋‹น ๊ณ„์ •์ด ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."),
Java
์—ฌ๊ธฐ์„œ JWT ์ธ์ฆํ•  ๋•Œ ๋‘๊ฐ€์ง€ ์กฐ๊ฑด์ด ์žˆ๋”๊ตฐ์š”. 1. JWT๊ฐ€ ์•„๋‹Œ Token์„ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ - 400 2. JWT๋Š” ๋งž๋Š”๋ฐ ์˜ฌ๋ฐ”๋ฅธ JWT๊ฐ€ ์•„๋‹ ๊ฒฝ์šฐ - 401 ๋‘๊ฐ€์ง€ ๊ณ ๋ คํ•˜์‹œ๋Š”๊ฑด ์–ด๋– ์‹ ์ง€ ๋ž™๋Œ ์˜๊ฒฌ์ด ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค.
@@ -11,6 +11,12 @@ public enum ErrorCode { METHOD_NOT_ALLOWED(405, "์ง€์›ํ•˜์ง€ ์•Š๋Š” ์š”์ฒญ ๋ฉ”์†Œ๋“œ ์ž…๋‹ˆ๋‹ค."), INTERNAL_SERVER_ERROR(500, "์„œ๋ฒ„์—์„œ ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค."), + // Auth + UNAUTHENTICATED_ERROR(401, "์ธ์ฆ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ๋กœ๊ทธ์ธ ์ดํ›„ ๋‹ค์‹œ ์‹œ๋„ ํ•ด์ฃผ์„ธ์š”."), + JWT_INVALID_ERROR(400, "์˜ฌ๋ฐ”๋ฅธ ์ธ์ฆ ์ •๋ณด๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค. ๋‹ค์‹œ ๋กœ๊ทธ์ธ ํ•ด์ฃผ์„ธ์š”."), + JWT_EXPIRATION_ERROR(401, "์ธ์ฆ ์ •๋ณด๊ฐ€ ๋งŒ๋ฃŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ๋กœ๊ทธ์ธ ํ•ด์ฃผ์„ธ์š”."), + ACCESS_DENIED_ERROR(403, "ํ•ด๋‹น ์š”์ฒญ์— ๋Œ€ํ•œ ์ ‘๊ทผ ๊ถŒํ•œ์ด ์—†์Šต๋‹ˆ๋‹ค."), + // Account ACCOUNT_NOT_FOUND(404, "ํ•ด๋‹น ๊ณ„์ •์ด ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."),
Java
์—ฌ๊ธฐ์„œ๋„ ์ด์•ผ๊ธฐ ํ•˜๊ณ  ์‹ถ์€๊ฒƒ์ด ์žˆ์Šต๋‹ˆ๋‹ค. ํ•ด๋‹น API๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ ๊ถŒํ•œ์„ ๋ง‰๋Š” ๊ฒƒ์ด 403์ด์ง€๋งŒ ๋งŒ์•ฝ ๋น„๊ณต๊ฐœ๋œ ์ •๋ณด๋ฅผ API๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ฐ€์ ธ์˜ฌ๋•Œ๋Š” 404๋กœ Not Found๋กœ ๋„์›Œ์•ผํ•œ๋‹ค๊ณ  ํ•˜๋”๊ตฐ์š”. ๊ทธ์— ๋Œ€ํ•œ ๋Œ€๋น„์ฑ…๋„ ํ•„์š”ํ•ด ๋ณด์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,105 @@ +package com.requestrealpiano.songrequest.security; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.requestrealpiano.songrequest.domain.account.Role; +import com.requestrealpiano.songrequest.security.filter.JwtAuthorizationFilter; +import com.requestrealpiano.songrequest.security.jwt.JwtTokenProvider; +import com.requestrealpiano.songrequest.security.oauth.CustomAccessDeniedHandler; +import com.requestrealpiano.songrequest.security.oauth.CustomAuthenticationEntryPoint; +import com.requestrealpiano.songrequest.security.oauth.CustomAuthenticationSuccessHandler; +import com.requestrealpiano.songrequest.security.oauth.CustomOAuth2UserService; +import com.requestrealpiano.songrequest.domain.account.AccountRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.boot.autoconfigure.security.servlet.PathRequest; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.csrf.CsrfFilter; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CharacterEncodingFilter; + +import java.util.Arrays; +import java.util.Collections; + +import static org.springframework.security.config.Customizer.withDefaults; + +@RequiredArgsConstructor +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + private final CustomOAuth2UserService customOAuth2UserService; + private final CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler; + private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint; + private final CustomAccessDeniedHandler customAccessDeniedHandler; + private final AccountRepository accountRepository; + private final JwtTokenProvider jwtTokenProvider; + private final ObjectMapper objectMapper; + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations()); + + web.ignoring().antMatchers(HttpMethod.GET, "/api/accounts/auth") + .antMatchers(HttpMethod.GET, "/api/letters/**") + ; + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.cors(withDefaults()); + + http.csrf().disable() + .httpBasic().disable(); + + http.authorizeRequests() +// .antMatchers("/**").permitAll() + .antMatchers("/api/letters").hasAnyRole(Role.MEMBER.getKey(), Role.ADMIN.getKey()) + .antMatchers("/api/songs").hasAnyRole(Role.MEMBER.getKey(), Role.ADMIN.getKey()) + .anyRequest().authenticated(); + + http.sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.STATELESS); + + http.addFilterBefore(characterEncodingFilter(), CsrfFilter.class) + .addFilterBefore(JwtAuthorizationFilter.of(accountRepository, jwtTokenProvider, objectMapper), UsernamePasswordAuthenticationFilter.class); + + http.oauth2Login() + .userInfoEndpoint() + .userService(customOAuth2UserService) + .and() + .successHandler(customAuthenticationSuccessHandler); + + http.exceptionHandling() + .authenticationEntryPoint(customAuthenticationEntryPoint) + .accessDeniedHandler(customAccessDeniedHandler); + } + + public CharacterEncodingFilter characterEncodingFilter() { + CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); + encodingFilter.setEncoding("UTF-8"); + encodingFilter.setForceEncoding(true); + return encodingFilter; + } + + @Bean + CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration configuration = new CorsConfiguration(); + configuration.setAllowedOrigins(Collections.singletonList("*")); + configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")); + configuration.setAllowedHeaders(Collections.singletonList("*")); + configuration.setExposedHeaders(Collections.singletonList("Authorization")); + configuration.setAllowCredentials(true); + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + return source; + } +}
Java
์‚ฌ์šฉํ•˜์‹œ์ง€ ์•Š์„ ์ฝ”๋“œ๋ฉด ์‚ญ์ œํ•˜๊ณ  ๊ทธ๋ž˜๋„ ์ฃผ์„์ฒ˜๋ฆฌ๋ฅผ ๋‚จ๊ธฐ๊ณ  ์‹ถ๋‹ค๋ฉด ์™œ ์ฃผ์„์ฒ˜๋ฆฌํ–ˆ๋Š”์ง€์— ๋Œ€ํ•œ ์„ค๋ช…์„ ์ถ”๊ฐ€ํ•ด์ฃผ์„ธ์š”
@@ -0,0 +1,105 @@ +package com.requestrealpiano.songrequest.security; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.requestrealpiano.songrequest.domain.account.Role; +import com.requestrealpiano.songrequest.security.filter.JwtAuthorizationFilter; +import com.requestrealpiano.songrequest.security.jwt.JwtTokenProvider; +import com.requestrealpiano.songrequest.security.oauth.CustomAccessDeniedHandler; +import com.requestrealpiano.songrequest.security.oauth.CustomAuthenticationEntryPoint; +import com.requestrealpiano.songrequest.security.oauth.CustomAuthenticationSuccessHandler; +import com.requestrealpiano.songrequest.security.oauth.CustomOAuth2UserService; +import com.requestrealpiano.songrequest.domain.account.AccountRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.boot.autoconfigure.security.servlet.PathRequest; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.csrf.CsrfFilter; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CharacterEncodingFilter; + +import java.util.Arrays; +import java.util.Collections; + +import static org.springframework.security.config.Customizer.withDefaults; + +@RequiredArgsConstructor +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + private final CustomOAuth2UserService customOAuth2UserService; + private final CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler; + private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint; + private final CustomAccessDeniedHandler customAccessDeniedHandler; + private final AccountRepository accountRepository; + private final JwtTokenProvider jwtTokenProvider; + private final ObjectMapper objectMapper; + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations()); + + web.ignoring().antMatchers(HttpMethod.GET, "/api/accounts/auth") + .antMatchers(HttpMethod.GET, "/api/letters/**") + ; + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.cors(withDefaults()); + + http.csrf().disable() + .httpBasic().disable(); + + http.authorizeRequests() +// .antMatchers("/**").permitAll() + .antMatchers("/api/letters").hasAnyRole(Role.MEMBER.getKey(), Role.ADMIN.getKey()) + .antMatchers("/api/songs").hasAnyRole(Role.MEMBER.getKey(), Role.ADMIN.getKey()) + .anyRequest().authenticated(); + + http.sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.STATELESS); + + http.addFilterBefore(characterEncodingFilter(), CsrfFilter.class) + .addFilterBefore(JwtAuthorizationFilter.of(accountRepository, jwtTokenProvider, objectMapper), UsernamePasswordAuthenticationFilter.class); + + http.oauth2Login() + .userInfoEndpoint() + .userService(customOAuth2UserService) + .and() + .successHandler(customAuthenticationSuccessHandler); + + http.exceptionHandling() + .authenticationEntryPoint(customAuthenticationEntryPoint) + .accessDeniedHandler(customAccessDeniedHandler); + } + + public CharacterEncodingFilter characterEncodingFilter() { + CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); + encodingFilter.setEncoding("UTF-8"); + encodingFilter.setForceEncoding(true); + return encodingFilter; + } + + @Bean + CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration configuration = new CorsConfiguration(); + configuration.setAllowedOrigins(Collections.singletonList("*")); + configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")); + configuration.setAllowedHeaders(Collections.singletonList("*")); + configuration.setExposedHeaders(Collections.singletonList("Authorization")); + configuration.setAllowCredentials(true); + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + return source; + } +}
Java
Role์„ ์ž์ฃผ ์‚ฌ์šฉํ•˜์‹ค ๋“ฏํ•œ๋ฐ import static์œผ๋กœ ์„ ์–ธํ•˜๋Š” ๊ฒƒ๋„ ๋‚˜์˜์ง€ ์•Š๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,105 @@ +package com.requestrealpiano.songrequest.security; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.requestrealpiano.songrequest.domain.account.Role; +import com.requestrealpiano.songrequest.security.filter.JwtAuthorizationFilter; +import com.requestrealpiano.songrequest.security.jwt.JwtTokenProvider; +import com.requestrealpiano.songrequest.security.oauth.CustomAccessDeniedHandler; +import com.requestrealpiano.songrequest.security.oauth.CustomAuthenticationEntryPoint; +import com.requestrealpiano.songrequest.security.oauth.CustomAuthenticationSuccessHandler; +import com.requestrealpiano.songrequest.security.oauth.CustomOAuth2UserService; +import com.requestrealpiano.songrequest.domain.account.AccountRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.boot.autoconfigure.security.servlet.PathRequest; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.csrf.CsrfFilter; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CharacterEncodingFilter; + +import java.util.Arrays; +import java.util.Collections; + +import static org.springframework.security.config.Customizer.withDefaults; + +@RequiredArgsConstructor +@Configuration +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + private final CustomOAuth2UserService customOAuth2UserService; + private final CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler; + private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint; + private final CustomAccessDeniedHandler customAccessDeniedHandler; + private final AccountRepository accountRepository; + private final JwtTokenProvider jwtTokenProvider; + private final ObjectMapper objectMapper; + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations()); + + web.ignoring().antMatchers(HttpMethod.GET, "/api/accounts/auth") + .antMatchers(HttpMethod.GET, "/api/letters/**") + ; + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.cors(withDefaults()); + + http.csrf().disable() + .httpBasic().disable(); + + http.authorizeRequests() +// .antMatchers("/**").permitAll() + .antMatchers("/api/letters").hasAnyRole(Role.MEMBER.getKey(), Role.ADMIN.getKey()) + .antMatchers("/api/songs").hasAnyRole(Role.MEMBER.getKey(), Role.ADMIN.getKey()) + .anyRequest().authenticated(); + + http.sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.STATELESS); + + http.addFilterBefore(characterEncodingFilter(), CsrfFilter.class) + .addFilterBefore(JwtAuthorizationFilter.of(accountRepository, jwtTokenProvider, objectMapper), UsernamePasswordAuthenticationFilter.class); + + http.oauth2Login() + .userInfoEndpoint() + .userService(customOAuth2UserService) + .and() + .successHandler(customAuthenticationSuccessHandler); + + http.exceptionHandling() + .authenticationEntryPoint(customAuthenticationEntryPoint) + .accessDeniedHandler(customAccessDeniedHandler); + } + + public CharacterEncodingFilter characterEncodingFilter() { + CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); + encodingFilter.setEncoding("UTF-8"); + encodingFilter.setForceEncoding(true); + return encodingFilter; + } + + @Bean + CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration configuration = new CorsConfiguration(); + configuration.setAllowedOrigins(Collections.singletonList("*")); + configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")); + configuration.setAllowedHeaders(Collections.singletonList("*")); + configuration.setExposedHeaders(Collections.singletonList("Authorization")); + configuration.setAllowCredentials(true); + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + return source; + } +}
Java
`WebConfig`์—์„œ๋„ CORS ์—๋Ÿฌ์— ๋Œ€ํ•œ ๋Œ€๋น„์ฑ…์„ ์„ค์ •ํ•˜์…จ๋Š”๋ฐ ์—ฌ๊ธฐ์„œ๋„ ์„ค์ •ํ•œ ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,115 @@ +package com.requestrealpiano.songrequest.security.jwt; + +import com.requestrealpiano.songrequest.domain.account.Account; +import com.requestrealpiano.songrequest.global.error.exception.jwt.JwtExpirationException; +import com.requestrealpiano.songrequest.global.error.exception.jwt.JwtInvalidTokenException; +import com.requestrealpiano.songrequest.global.error.exception.jwt.JwtRequiredException; +import com.requestrealpiano.songrequest.security.jwt.claims.AccountClaims; +import io.jsonwebtoken.*; +import lombok.RequiredArgsConstructor; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Component; + +import java.util.Date; + +@RequiredArgsConstructor +@Component +public class JwtTokenProvider { + + private final JwtProperties jwtProperties; + + private final String ID = "id"; + private final String EMAIL = "email"; + private final String NAME = "name"; + private final String AVATAR_URL = "avatarUrl"; + private final String ROLE = "role"; + + public String createGenerationKey(String email) { + Date now = new Date(); + return Jwts.builder() + .setHeaderParam(Header.TYPE, Header.JWT_TYPE) + .setIssuedAt(now) + .setExpiration(new Date(now.getTime() + Long.parseLong(jwtProperties.getGenerationKeyExpiration()))) + .claim(EMAIL, email) + .signWith(SignatureAlgorithm.HS256, jwtProperties.getGenerationKeySecret()) + .compact(); + } + + public String parseGenerationKey(String authorization) { + String generationKey = extractToken(authorization); + try { + Jws<Claims> claims = Jwts.parser() + .setSigningKey(jwtProperties.getGenerationKeySecret()) + .parseClaimsJws(generationKey); + return claims.getBody() + .get(EMAIL, String.class); + } catch (ExpiredJwtException exception) { + throw new JwtExpirationException(); + } catch (JwtException exception) { + throw new JwtInvalidTokenException(); + } + } + + public String createJwtToken(Account account) { + Date now = new Date(); + String jwtToken = Jwts.builder() + .setHeaderParam(Header.TYPE, Header.JWT_TYPE) + .setIssuedAt(now) + .setExpiration(new Date(now.getTime() + Long.parseLong(jwtProperties.getTokenExpiration()))) + .claim(ID, account.getId()) + .claim(EMAIL, account.getEmail()) + .claim(NAME, account.getName()) + .claim(AVATAR_URL, account.getAvatarUrl()) + .claim(ROLE, account.getRoleKey()) + .signWith(SignatureAlgorithm.HS256, jwtProperties.getTokenSecret()) + .compact(); + return jwtProperties.getHeaderPrefix() + jwtToken; + } + + public boolean validateJwtToken(String authorization) { + String jwtToken = extractToken(authorization); + try { + Jws<Claims> claims = Jwts.parser() + .setSigningKey(jwtProperties.getTokenSecret()) + .parseClaimsJws(jwtToken); + return claims.getBody() + .getExpiration() + .after(new Date()); + } catch (ExpiredJwtException exception) { + throw new JwtExpirationException(); + } catch (JwtException exception) { + throw new JwtInvalidTokenException(); + } + } + + public AccountClaims parseJwtToken(String jwtToken) { + try { + Jws<Claims> claims = Jwts.parser() + .setSigningKey(jwtProperties.getTokenSecret()) + .parseClaimsJws(jwtToken); + Claims body = claims.getBody(); + + return AccountClaims.from(body); + } catch (ExpiredJwtException exception) { + throw new JwtExpirationException(); + } catch (JwtException exception) { + throw new JwtInvalidTokenException(); + } + } + + public String extractToken(String authorizationHeader) { + if (isTokenContained(authorizationHeader)) { + int tokenBeginIndex = jwtProperties.getHeaderPrefix().length(); + return StringUtils.substring(authorizationHeader, tokenBeginIndex); + } + throw new JwtRequiredException(); + } + + private boolean isTokenContained(String authorization) { + if (StringUtils.isEmpty(authorization)) { + return false; + } + + return authorization.startsWith(jwtProperties.getHeaderPrefix()); + } +}
Java
Date ํƒ€์ž…์„ ์“ฐ์…จ๋Š”๋ฐ LocalDate ํƒ€์ž…์ด ์•„๋‹Œ ์ด์œ ๊ฐ€ ๋ฌด์—‡์ธ๊ฐ€์š”?
@@ -0,0 +1,21 @@ +package com.requestrealpiano.songrequest.security.jwt; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.ConstructorBinding; + +@RequiredArgsConstructor +@Getter +@ConstructorBinding +@ConfigurationProperties(prefix = "jwt") +public class JwtProperties { + + private final String tokenSecret; + private final String tokenExpiration; + private final String header; + private final String headerPrefix; + private final String tokenUrl; + private final String generationKeySecret; + private final String generationKeyExpiration; +}
Java
์ƒ์„ฑ์ž๊ฐ€ ํ•„์š”ํ•œ๊ฐ€์š”? ๋ถˆํ•„์š”ํ•œ ์ƒ์„ฑ์ž๊ฐ™์•„์š”
@@ -0,0 +1,33 @@ +package com.requestrealpiano.songrequest.security.oauth; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.requestrealpiano.songrequest.global.error.response.ErrorCode; +import com.requestrealpiano.songrequest.global.error.response.ErrorResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.MediaType; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@RequiredArgsConstructor +@Component +public class CustomAccessDeniedHandler implements AccessDeniedHandler { + + private final ObjectMapper objectMapper; + + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { + ErrorCode accessDeniedError = ErrorCode.ACCESS_DENIED_ERROR; + String errorResponse = objectMapper.writeValueAsString(ErrorResponse.from(accessDeniedError)); + response.getWriter().print(errorResponse); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setStatus(accessDeniedError.getStatusCode()); + response.getWriter().flush(); + response.getWriter().close(); + } +}
Java
์ด์ •๋„ ๊ธธ์–ด์ง€๋ฉด throws๋ถ€ํ„ฐ ํ•œ์นธ ๋‚ด๋ ค์„œ ๋ณด๊ธฐ ์‰ฝ๊ฒŒ ํ•ด์ฃผ์„ธ์šฉ
@@ -0,0 +1,33 @@ +package com.requestrealpiano.songrequest.security.oauth; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.requestrealpiano.songrequest.global.error.response.ErrorCode; +import com.requestrealpiano.songrequest.global.error.response.ErrorResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.MediaType; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@RequiredArgsConstructor +@Component +public class CustomAccessDeniedHandler implements AccessDeniedHandler { + + private final ObjectMapper objectMapper; + + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { + ErrorCode accessDeniedError = ErrorCode.ACCESS_DENIED_ERROR; + String errorResponse = objectMapper.writeValueAsString(ErrorResponse.from(accessDeniedError)); + response.getWriter().print(errorResponse); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setStatus(accessDeniedError.getStatusCode()); + response.getWriter().flush(); + response.getWriter().close(); + } +}
Java
์—ฌ๊ธฐ์„œ ๊ถ๊ธˆํ•œ๊ฒŒ ์ด๋Œ€๋กœ ์‚ฌ์šฉํ–ˆ์„ ๋•Œ ์—๋Ÿฌ์ฒ˜๋ฆฌ๋Š” ๋ฐœ์ƒ์ด ์ž˜ ๋˜๊ฒ ์œผ๋‚˜ ์Šคํ”„๋ง ๋กœ๊ทธ์—๋„ ์ฐํžˆ๋Š” ์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค. ์ œ๊ฐ€ ์ด์ „ ์ฝ”๋“œ์Šค์ฟผ๋“œ ๋„์„œ๊ด€ ํ”„๋กœ์ ํŠธ์—์„œ๋„ ์ด๋Ÿฐ์‹์œผ๋กœ ์ฒ˜๋ฆฌํ–ˆ์„ ๋•Œ ๋กœ๊ทธ์— ์ฐํžˆ์ง€ ์•Š๋Š” ์‚ฌ์†Œํ•œ ๋ฌธ์ œ์ ์ด ์ƒ๊ฒผ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,33 @@ +package com.requestrealpiano.songrequest.security.oauth; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.requestrealpiano.songrequest.global.error.response.ErrorCode; +import com.requestrealpiano.songrequest.global.error.response.ErrorResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.MediaType; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@RequiredArgsConstructor +@Component +public class CustomAccessDeniedHandler implements AccessDeniedHandler { + + private final ObjectMapper objectMapper; + + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { + ErrorCode accessDeniedError = ErrorCode.ACCESS_DENIED_ERROR; + String errorResponse = objectMapper.writeValueAsString(ErrorResponse.from(accessDeniedError)); + response.getWriter().print(errorResponse); + response.setContentType(MediaType.APPLICATION_JSON_VALUE); + response.setStatus(accessDeniedError.getStatusCode()); + response.getWriter().flush(); + response.getWriter().close(); + } +}
Java
๊ทธ๋ž˜์„œ ์ƒ๊ฐํ•ด๋‚ธ ๊ฒƒ์ด `AccessDeniedException`์„ ๋ฐ›๋Š” ์—๋Ÿฌํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค๊ณ  ํ•ด๋‹น ์—๋Ÿฌ๋ฅผ ์ƒ์†๋ฐ›์•„ ์—ฌ๊ธฐ์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ํ•ด๋‹น ํด๋ž˜์Šค๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•˜์—ฌ ๋‹ค๋ฅธ exceptionHandler์ฒ˜๋Ÿผ ํ•œ๋ฒˆ์— ๊ด€๋ฆฌํ•˜๊ธฐ๋„ ํŽธํ•˜๊ณ  ๋กœ๊ทธ๋„ ์ฐํž ์ˆ˜ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค. ```java @Component("restAuthenticationEntryPoint") public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { @Autowired private HandlerExceptionResolver resolver; @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { resolver.resolveException(request, response, null, exception); } } ```
@@ -0,0 +1,14 @@ +package com.requestrealpiano.songrequest.security.oauth; + +import org.springframework.security.core.annotation.AuthenticationPrincipal; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.PARAMETER) +@Retention(RetentionPolicy.RUNTIME) +@AuthenticationPrincipal +public @interface LoginAccount { +}
Java
์ด๊ฒƒ๋งŒ ๋‹ฌ์•„๋„ GlobalAdvice ์„ค์ •์„ ํ•  ํ•„์š”๊ฐ€ ์—†์–ด์„œ ์ข‹์ฃ !
@@ -0,0 +1,24 @@ +package com.requestrealpiano.songrequest.controller; + +import com.requestrealpiano.songrequest.service.AccountService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RequiredArgsConstructor +@RestController +@RequestMapping("/api/accounts") +public class AccountController { + + private final AccountService accountService; + + @GetMapping("/auth") + public ResponseEntity<Void> generateToken(@RequestHeader HttpHeaders httpHeaders) { + String jwtToken = accountService.generateJwtToken(httpHeaders.getFirst(HttpHeaders.AUTHORIZATION)); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.add(HttpHeaders.AUTHORIZATION, jwtToken); + return new ResponseEntity<>(responseHeaders, HttpStatus.NO_CONTENT); + } +}
Java
๋ถ„๋ช… ๋ชจ๋“  ์ปจํŠธ๋กค๋Ÿฌ๋ฅผ ๋™์‹œ์— ์ˆ˜์ •์„ ํ–ˆ์„ํ…๋ฐ ์—ฌ๊ธฐ๋Š” ์ƒํƒœ์ฝ”๋“œ๋งŒ ๋ฐ”๊พธ๊ณ  ํ˜•์‹์€ ์ด๋ ‡๊ฒŒ ๋‚จ๊ฒจ ๋‘์—ˆ์—ˆ๋„ค์š”. ํ†ต์ผ์„ฑ์„ ์œ„ํ•ด ์ˆ˜์ • ํ•˜๊ฒ ์Šต๋‹ˆ๋‹คใ…Žใ…Ž
@@ -2,18 +2,18 @@ import com.requestrealpiano.songrequest.domain.song.searchapi.response.SearchApiResponse; import com.requestrealpiano.songrequest.global.response.ApiResponse; +import com.requestrealpiano.songrequest.global.response.StatusCode; import com.requestrealpiano.songrequest.service.SongService; import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import javax.validation.constraints.Size; import static com.requestrealpiano.songrequest.global.constant.ValidationCondition.*; -import static com.requestrealpiano.songrequest.global.response.ApiResponse.OK; +import static com.requestrealpiano.songrequest.global.response.ApiResponse.SUCCESS; +import static com.requestrealpiano.songrequest.global.response.StatusCode.OK; @RequiredArgsConstructor @Validated @@ -23,12 +23,13 @@ public class SongController { private final SongService songService; + @ResponseStatus(HttpStatus.OK) @GetMapping public ApiResponse<SearchApiResponse> search(@RequestParam(defaultValue = "artist") @Size(max = ARTIST_MAX) String artist, @RequestParam(defaultValue = "title") @Size(max = TITLE_MAX) String title) { SearchApiResponse searchApiResponse = songService.searchSong(artist, title); - return OK(searchApiResponse); + return SUCCESS(OK, searchApiResponse); } }
Java
์ง€๋‚œ๋ฒˆ ๋ฆฌ๋ทฐ์— ๊ฐ™์€ ์˜๊ฒฌ์„ ์ฃผ์…”์„œ ๋ณ€๊ฒฝ์„ ๊ณ ๋ ค ํ•ด๋ดค์—ˆ๋Š”๋ฐ์š”. ์—ฌ๊ธฐ ์ด ๋‘ ๊ฐ’์€ ๋นˆ ๊ฐ’์œผ๋กœ ์š”์ฒญ์ด ์™”์„ ๋•Œ `NotEmpty` ์™€ ๊ฐ™์€ ์ฒ˜๋ฆฌ๋กœ ์—๋Ÿฌ๋ฅผ ๋ฐ˜ํ™˜ํ• ๊ฒŒ ์•„๋‹ˆ๋ผ default value๋กœ ๊ฒ€์ƒ‰์„ ๊ณ„์† ์ง„ํ–‰ ์‹œํ‚ฌ ์ƒ๊ฐ ์ž…๋‹ˆ๋‹ค. ๋งŒ์•ฝ `@ModelAttribute` DTO๋กœ ๋ฐ›์„ ๊ฒฝ์šฐ์—๋Š” setter๋กœ ๊ฐ’์„ ๋ฐ”์ธ๋”ฉ ํ•ด์•ผ ํ•˜๋Š” ๊ฒƒ์œผ๋กœ ์•Œ๊ณ  ์žˆ๋Š”๋ฐ์š”. ๊ทธ๋ ‡๋‹ค๋ฉด setter์—์„œ ๋นˆ ๊ฐ’์ผ ๊ฒฝ์šฐ ๊ธฐ๋ณธ ๊ฐ’์„ ์ฃผ๋Š” ๋กœ์ง์ด ํ•„์š”ํ•  ๋“ฏ ๋ณด์ด๋Š”๋ฐ, ๊ฐ€๋Šฅํ•˜๋‹ค๋ฉด `@RequestParam` ์ฒ˜๋Ÿผ `@Something(defaultValue = "Default value")` ์ด๋Ÿฐ์‹์œผ๋กœ ์• ๋…ธํ…Œ์ด์…˜ ๊ธฐ๋ฐ˜์œผ๋กœ ์ˆ˜์ • ํ•˜๊ณ  ์‹ถ์€๋ฐ ์›๋ž˜ ์ŠคํŽ™์— ์—†๋Š”๊ฑด์ง€ ์ œ๊ฐ€ ๋ชป ์ฐพ๋Š”๊ฑด์ง€...ใ…Žใ…Ž setter์—์„œ ์ง์ ‘ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ ๋ง๊ณ  ํ˜น์‹œ ์•Œ๊ณ  ๊ณ„์‹œ๋Š” ๋” ์ข‹์€ ๋ฐฉ๋ฒ•์ด ์žˆ์„๊นŒ์š”?
@@ -1,5 +1,6 @@ package com.requestrealpiano.songrequest.domain.account; +import com.requestrealpiano.songrequest.security.oauth.OAuthAttributes; import com.requestrealpiano.songrequest.domain.base.BaseTimeEntity; import com.requestrealpiano.songrequest.domain.letter.Letter; import lombok.AccessLevel; @@ -8,9 +9,6 @@ import lombok.NoArgsConstructor; import javax.persistence.*; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; import java.util.ArrayList; import java.util.List; @@ -25,7 +23,7 @@ public class Account extends BaseTimeEntity { private Long id; @Column(name = "google_oauth_id") - private Long googleOauthId; + private String googleOauthId; private String name; @@ -44,12 +42,36 @@ public class Account extends BaseTimeEntity { private List<Letter> letters = new ArrayList<>(); @Builder - private Account(Long googleOauthId, String name, String email, Role role, String avatarUrl, Integer requestCount) { + private Account(String googleOauthId, String name, String email, Role role, String avatarUrl, Integer requestCount) { this.googleOauthId = googleOauthId; this.name = name; this.email = email; this.role = role; this.avatarUrl = avatarUrl; this.requestCount = requestCount; } + + public String getRoleKey() { return role.getKey(); } + + public String getRoleValue() { + return role.getValue(); + } + + public Account updateProfile(OAuthAttributes attributes) { + this.name = attributes.getName(); + this.email = attributes.getEmail(); + this.avatarUrl = attributes.getAvatarUrl(); + return this; + } + + public static Account from(OAuthAttributes oAuthAttributes) { + return Account.builder() + .googleOauthId(oAuthAttributes.getGoogleOauthId()) + .name(oAuthAttributes.getName()) + .email(oAuthAttributes.getEmail()) + .role(Role.MEMBER) + .avatarUrl(oAuthAttributes.getAvatarUrl()) + .requestCount(0) + .build(); + } }
Java
๊ณ„์ •์„ ์ตœ์ดˆ ์ƒ์„ฑ ํ–ˆ์„ ๋•Œ์˜ ๊ธฐ๋ณธ ๊ฐ’ (์‹ ์ฒญ๊ณก ๋“ฑ๋ก ์ˆ˜) ์ž…๋‹ˆ๋‹ค. ์ด์ „ ๋ฆฌ๋ทฐ์—์„œ ์ด๋ ‡๊ฒŒ ์ง๊ด€์ ์œผ๋กœ ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋Š” ์ด๋Ÿฐ ๊ฐ’์€ ๋ณ€์ˆ˜๋กœ ๋นผ์ง€ ์•Š์•„๋„ ๋ ๊ฑฐ ๊ฐ™๋‹ค๋Š” ํ”ผ๋“œ๋ฐฑ์„ ๋ฐ›์•˜์—ˆ๋Š”๋ฐ, ๊ทธ๊ฑธ ๋ฐ˜์˜ํ•ด์„œ ์ฝ”๋“œ ์ž‘์„ฑ์„ ํ–ˆ๋˜ ๋“ฏ ์‹ถ์Šต๋‹ˆ๋‹ค. ์šฐ์„  ์ด ์ฝ”๋“œ๋Š” ์ปฌ๋Ÿผ์— ๊ธฐ๋ณธ ๊ฐ’์„ ์ถ”๊ฐ€ ํ•  ์˜ˆ์ •์ด๊ธฐ ๋•Œ๋ฌธ์— ์—†์–ด์งˆ ์ฝ”๋“œ๊ฐ€ ๋  ๋“ฏ ํ•ฉ๋‹ˆ๋‹ค. ๊ทธ๋Ÿฐ๋ฐ ํ˜น์‹œ ์จ๋‹ˆ๋Š” ๋งค์ง๋„˜๋ฒ„๋ฅผ ์ง€์ •ํ•˜๋Š” ๊ฒƒ์— ๋Œ€ํ•œ ์–ด๋–ค ๊ธฐ์ค€์ด ์žˆ์œผ์‹ค๊นŒ์š”? ์˜ˆ์ „์— ํŒ€ ํ”„๋กœ์ ํŠธ ํ•  ๋•Œ๋„ ๋งค์ง ๋„˜๋ฒ„ ์‚ฌ์šฉ์„ ๋ฌด์กฐ๊ฑด ํ”ผํ•˜๋ ค๊ณ  ๋ชจ๋‘ ๋ณ€์ˆ˜๋กœ ์ง€์ • ํ–ˆ๋‹ค๊ฐ€ ์˜คํžˆ๋ ค ์˜๋ฏธ ํ•ด์„์ด ์–ด๋ ค์›Œ์กŒ๋‹ค๋Š” ํ”ผ๋“œ๋ฐฑ์„ ๋ฆฌ๋ทฐ์–ด ๋ถ„๊ป˜ ๋ฐ›์€์ ์ด ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค. ์ด๋Ÿฐ ๊ฒฝ์šฐ์—๋Š” ๊ทธ๋ƒฅ ์ˆซ์ž ๊ฐ’์„ ์‚ฌ์šฉํ•˜๊ณ  ์ฃผ์„์œผ๋กœ ๋ถ€๊ฐ€ ์„ค๋ช…์„ ์ ๋Š” ๊ฒƒ๋„ ๊ดœ์ฐฎ๋‹ค๊ณ  ํ•˜์‹œ๋”๋ผ๊ตฌ์š”. ์จ๋‹ˆ๋Š” ์–ด๋–ค ๊ธฐ์ค€์„ ๊ฐ€์ง€๊ณ  ๊ณ„์‹œ๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค.
@@ -1,5 +1,6 @@ package com.requestrealpiano.songrequest.domain.account; +import com.requestrealpiano.songrequest.security.oauth.OAuthAttributes; import com.requestrealpiano.songrequest.domain.base.BaseTimeEntity; import com.requestrealpiano.songrequest.domain.letter.Letter; import lombok.AccessLevel; @@ -8,9 +9,6 @@ import lombok.NoArgsConstructor; import javax.persistence.*; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; import java.util.ArrayList; import java.util.List; @@ -25,7 +23,7 @@ public class Account extends BaseTimeEntity { private Long id; @Column(name = "google_oauth_id") - private Long googleOauthId; + private String googleOauthId; private String name; @@ -44,12 +42,36 @@ public class Account extends BaseTimeEntity { private List<Letter> letters = new ArrayList<>(); @Builder - private Account(Long googleOauthId, String name, String email, Role role, String avatarUrl, Integer requestCount) { + private Account(String googleOauthId, String name, String email, Role role, String avatarUrl, Integer requestCount) { this.googleOauthId = googleOauthId; this.name = name; this.email = email; this.role = role; this.avatarUrl = avatarUrl; this.requestCount = requestCount; } + + public String getRoleKey() { return role.getKey(); } + + public String getRoleValue() { + return role.getValue(); + } + + public Account updateProfile(OAuthAttributes attributes) { + this.name = attributes.getName(); + this.email = attributes.getEmail(); + this.avatarUrl = attributes.getAvatarUrl(); + return this; + } + + public static Account from(OAuthAttributes oAuthAttributes) { + return Account.builder() + .googleOauthId(oAuthAttributes.getGoogleOauthId()) + .name(oAuthAttributes.getName()) + .email(oAuthAttributes.getEmail()) + .role(Role.MEMBER) + .avatarUrl(oAuthAttributes.getAvatarUrl()) + .requestCount(0) + .build(); + } }
Java
์ €๋Š” ๋ถ€๊ฐ€์  ์„ค๋ช…์œผ๋กœ ์ฃผ์„๋„ฃ๋Š”๊ฒƒ๋„ ๊ดœ์ฐฎ๋‹ค๊ณ  ์ƒ๊ฐํ•ด์š” ๊ทธ๋Ÿฌ๋‚˜ ๋งŒ์•ฝ ํ…Œ์ŠคํŠธ ์ฝ”๋“œ์—์„œ ์—ฌ๋Ÿฌ๋ฒˆ ์ค‘๋ณต๋์„๋•Œ๋Š” ๋”ฐ๋กœ ๊ด€๋ฆฌํ•˜๋Š”๊ฒŒ ๋‚ซ๊ฒ ๋„ค์š”
@@ -11,6 +11,12 @@ public enum ErrorCode { METHOD_NOT_ALLOWED(405, "์ง€์›ํ•˜์ง€ ์•Š๋Š” ์š”์ฒญ ๋ฉ”์†Œ๋“œ ์ž…๋‹ˆ๋‹ค."), INTERNAL_SERVER_ERROR(500, "์„œ๋ฒ„์—์„œ ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค."), + // Auth + UNAUTHENTICATED_ERROR(401, "์ธ์ฆ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ๋กœ๊ทธ์ธ ์ดํ›„ ๋‹ค์‹œ ์‹œ๋„ ํ•ด์ฃผ์„ธ์š”."), + JWT_INVALID_ERROR(400, "์˜ฌ๋ฐ”๋ฅธ ์ธ์ฆ ์ •๋ณด๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค. ๋‹ค์‹œ ๋กœ๊ทธ์ธ ํ•ด์ฃผ์„ธ์š”."), + JWT_EXPIRATION_ERROR(401, "์ธ์ฆ ์ •๋ณด๊ฐ€ ๋งŒ๋ฃŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ๋กœ๊ทธ์ธ ํ•ด์ฃผ์„ธ์š”."), + ACCESS_DENIED_ERROR(403, "ํ•ด๋‹น ์š”์ฒญ์— ๋Œ€ํ•œ ์ ‘๊ทผ ๊ถŒํ•œ์ด ์—†์Šต๋‹ˆ๋‹ค."), + // Account ACCOUNT_NOT_FOUND(404, "ํ•ด๋‹น ๊ณ„์ •์ด ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."),
Java
JWT ๊ด€๋ จ ์˜ˆ์™ธ๋ฅผ ๊ตฌ์ƒํ•  ๋•Œ ์•„๋ž˜์˜ ๋„ค๊ฐ€์ง€ ์˜ˆ์™ธ๊ฐ€ ๋งจ ์ฒ˜์Œ ๊ณ ๋ คํ–ˆ๋˜ JWT ๊ด€๋ จ ์˜ˆ์™ธ์˜€์Šต๋‹ˆ๋‹ค. 1. ExpiredJwtException : ์œ ํšจ๊ธฐ๊ฐ„์ด ์ง€๋‚œ Token์œผ๋กœ ์š”์ฒญ 2. InvalidClaimException : Claim ํŒŒ์‹ฑ ์‹คํŒจ๋กœ ์ธํ•œ ์˜ˆ์™ธ 3. MalformedJwtException : ๊ตฌ์กฐ์  ๋ฌธ์ œ๊ฐ€ ์žˆ๋Š” JWT ํ† ํฐ์œผ๋กœ ์ธํ•œ ์˜ˆ์™ธ 4. SignatureException : ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ JWT ์‹œ๊ทธ๋‹ˆ์ฒ˜๋กœ ์ธํ•œ ๊ฒ€์ฆ ์‹คํŒจ ์ด ๋•Œ 1๋ฒˆ '์œ ํšจ๊ธฐ๊ฐ„ ๋งŒ๋ฃŒ' ์™€ 2, 3, 4์— ํ•ด๋‹นํ•˜๋Š” 'JWT ๊ฒ€์ฆ ์‹คํŒจ' ๋‘๊ฐ€์ง€ ์œ ํ˜•์œผ๋กœ๋งŒ ๋‚˜๋ˆ„์–ด์„œ ์ฒ˜๋ฆฌ๋ฅผ ํ•œ ๋’ค ํด๋ผ์ด์–ธํŠธ์— ์•Œ๋ ค์ฃผ๋ฉด ๋ ๊ฑฐ๋ผ ์ƒ๊ฐํ•˜๊ณ  ๋‹ค์Œ์˜ ๋‘๊ฐ€์ง€๋กœ ์ฒ˜๋ฆฌ ํ•˜๋„๋ก ๊ตฌํ˜„ํ•˜์˜€์Šต๋‹ˆ๋‹ค. `JWT_INVALID_ERROR(400, "์˜ฌ๋ฐ”๋ฅธ ์ธ์ฆ ์ •๋ณด๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค. ๋‹ค์‹œ ๋กœ๊ทธ์ธ ํ•ด์ฃผ์„ธ์š”.") - JwtException` `JWT_EXPIRATION_ERROR(401, "์ธ์ฆ ์ •๋ณด๊ฐ€ ๋งŒ๋ฃŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ๋กœ๊ทธ์ธ ํ•ด์ฃผ์„ธ์š”.") - ExpiredJwtException` ๋ง์”€ํ•˜์‹  `JWT๊ฐ€ ์•„๋‹Œ Token ์‚ฌ์šฉ์œผ๋กœ ์ธํ•œ ์—๋Ÿฌ`์™€ `JWT ์ด์ง€๋งŒ ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ JWT๋ฅผ ์‚ฌ์šฉ` ๋‘ ๊ฐ€์ง€ ๊ฒฝ์šฐ๋ฅผ ๊ตฌ๋ถ„ ํ•  ๋•Œ ์–ด๋–ค ๋ถ€๋ถ„์—์„œ ์žฅ์ ์ด ์žˆ๋Š” ๊ฒƒ์ธ์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹คใ…Žใ…Ž ๋ฌผ๋ก  ์ด๋Ÿฐ ์ธ์ฆ๊ณผ ๋ณด์•ˆ์— ๋Œ€ํ•œ ๊ฒƒ์€ ์ตœ๋Œ€ํ•œ ๊ฒฌ๊ณ ํ•˜๊ฒŒ ํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค๋Š” ์ƒ๊ฐ์„ ๊ฐ€์ง€๊ณ  ์žˆ๋Š”๋ฐ์š”. ํ˜น์‹œ ์ด ๋‘˜์„ ๊ตฌ๋ถ„ํ•˜์ง€ ์•Š์•˜์„ ๋•Œ ์–ด๋–ค ํฐ ๋ฌธ์ œ๊ฐ€ ์ƒ๊ธธ ์—ฌ์ง€๊ฐ€ ์žˆ์„๊นŒ์š”? ์ œ๊ฐ€ ๋ชจ๋ฅด๊ณ  ์ง€๋‚˜์น˜๊ณ  ์žˆ๋Š” ๊ฒƒ์ด ์žˆ๋Š”์ง€์— ๋Œ€ํ•œ ์šฐ๋ ค์™€ ์จ๋‹ˆ์˜ ์˜๊ฒฌ์ด ๊ถ๊ธˆํ•ด์„œ ์—ฌ์ญˆ์–ด ๋ด…๋‹ˆ๋‹ค!
@@ -0,0 +1,63 @@ +language: java +jdk: + - openjdk11 + +branches: + only: + - main + +cache: + directories: + - '$HOME/.m2/repository' + - '$HOME/.gradle' + +script: "./gradlew clean build" + +before_deploy: + - mkdir -p before-deploy + - cp scripts/*.sh before-deploy/ + - cp appspec.yml before-deploy/ + - cp build/libs/*.jar before-deploy + - cd before-deploy && zip -r before-deploy * + - cd ../ && mkdir -p deploy + - mv before-deploy/before-deploy.zip deploy/songrequest-backend.zip + +deploy: + - provider: s3 + access_key_id: $AWS_ACCESS_KEY + secret_access_key: $AWS_SECRET_KEY + + bucket: songrequest-backend-build + region: ap-northeast-2 + + skip_cleanup: true + acl: private + local_dir: deploy + + wait-until-deployed: true + + on: + all_branches: true + + - provider: codedeploy + access_key_id: $AWS_ACCESS_KEY + secret_access_key: $AWS_SECRET_KEY + + bucket: songrequest-backend-build + key: songrequest-backend.zip + + bundle_type: zip + application: songrequest-backend + + deployment_group: songrequest-backend-group + + region: ap-northeast-2 + wait-until-deployed: true + + on: + all_branches: true + +notifications: + email: + recipients: + - museopkim0214@gmail.com
Unknown
travis CI ์ด๊ตฐ์š”. ์ €๋„ ์จ๋ดค์ง€๋งŒ Github Actions๋ณด๋‹ค ๋А๋ฆฌ๊ณ  ๋””๋ฒ„๊น…ํ•˜๋Š”๋ฐ ๋ถˆํŽธํ•ด์„œ ์ „ ์“ฐ๋‹ค๊ฐ€ ๋ฐ”๊ฟจ์Šต๋‹ˆ๋‹ค. ํ˜„์žฌ๋Š” Github Actions + AWS CodeBuild๋ฅผ ๋ณ‘ํ•ฉํ•ด์„œ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ๋Š”๋ฐ CIํˆด ์ค‘ travis ci๋ฅผ ์‚ฌ์šฉํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,18 @@ +version: 0.0 +os: linux +files: + - source: / + destination: /home/ubuntu/app/songrequest/zip/ + overwrite: yes + +permissions: + - object: / + pattern: "**" + owner: ubuntu + group: ubuntu + +hooks: + ApplicationStart: + - location: deploy.sh + timeout: 60 + runas: ubuntu
Unknown
์—ฌ๊ธฐ์„œ ์•„์…”์•ผํ• ๊ฑด ๋งŒ์•ฝ blue/green ๋ฐฐํฌ๋ฅผ ํ•˜์‹ค ๊ฒฝ์šฐ overwrite๊ฐ€ ๋จน์งˆ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ beforeInstall ์‰˜์Šคํฌ๋ฆฝํŠธ๋ฅผ ์ž‘์„ฑํ•˜์…”์„œ ํŒŒ์ผ ์‚ญ์ œํ•˜๋Š” ์Šคํฌ๋ฆฝํŠธ๋ฅผ ์งœ์…”์•ผํ•ฉ๋‹ˆ๋‹ค. ์ด ๋‚ด์šฉ์€ ์–ธ์  ๊ฐ€ ์ œ ๋ธ”๋กœ๊ทธ์— ์ ์„ ์˜ˆ์ •์ด๋‹ˆ ๊ถ๊ธˆํ•˜์‹œ๋ฉด ๋ณด์„ธ์šฉ
@@ -0,0 +1,18 @@ +version: 0.0 +os: linux +files: + - source: / + destination: /home/ubuntu/app/songrequest/zip/ + overwrite: yes + +permissions: + - object: / + pattern: "**" + owner: ubuntu + group: ubuntu + +hooks: + ApplicationStart: + - location: deploy.sh + timeout: 60 + runas: ubuntu
Unknown
๋งŒ์•ฝ ๋ณธ์ธ์ด blue/green ๋ฌด์ค‘๋‹จ ๋ฐฐํฌ๋ฅผ ํ•˜์‹ค๊ฒฝ์šฐ ์—ฌ๊ธฐ์„œ BeforeInstall ์‰˜์Šคํฌ๋ฆฝํŠธ ๋„ฃ์œผ์…”์„œ ์ด์ „ ๋นŒ๋“œ๋œํŒŒ์ผ ์‚ญ์ œํ•˜์‹œ๋Š” ์‰˜์Šคํฌ๋ฆฝํŠธ๋ฅผ ๋„ฃ์–ด์•ผ ์ •์ƒ์ ์œผ๋กœ ์ž‘๋™๋˜๋‹ˆ ๊ผญ ๊ธฐ์–ตํ•˜์„ธ์š”
@@ -23,13 +23,33 @@ ext { set('snippetsDir', file("build/generated-snippets")) } +bootJar { + dependsOn asciidoctor + from("${asciidoctor.outputDir}/html5") { + into 'static/docs' + } +} + +test { + outputs.dir snippetsDir + useJUnitPlatform() +} + +asciidoctor { + inputs.dir snippetsDir + dependsOn test + attributes 'snippets': snippetsDir +} + dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-web' - compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.11.1' - compile 'org.apache.commons:commons-lang3:3.11' + implementation 'javax.validation:validation-api:2.0.1.Final' + implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.11.1' + implementation 'org.hibernate.validator:hibernate-validator:6.1.7.Final' + implementation 'org.apache.commons:commons-lang3:3.11' compileOnly 'org.projectlombok:lombok' runtimeOnly 'com.h2database:h2' runtimeOnly 'mysql:mysql-connector-java'
Unknown
์ด๊ฒƒ๋„ ์ข‹์ง€๋งŒ DTO <-> Entity์—ญํ• ์„ ํ•˜๋Š” ๊ธฐ์กด์˜ modelmapper๋„ ์ข‹์ง€๋งŒ Mapstruct๋„ ํ›จ์”ฌ ์„ฑ๋Šฅ๋„ ์ข‹์Šต๋‹ˆ๋‹ค. ์‹ค๋ฌด์—์„œ๋„ ์‚ฌ์šฉํ•˜๋Š” ์ค‘์ž…๋‹ˆ๋‹ค. https://huisam.tistory.com/entry/mapStruct
@@ -0,0 +1,38 @@ +#!/bin/bash + +REPOSITORY=/home/ubuntu/app/songrequest +PROJECT_NAME=song-request + +echo "> Build ํŒŒ์ผ ๋ณต์‚ฌ" + +cp $REPOSITORY/zip/*.jar $REPOSITORY/ + +echo "> ํ˜„์žฌ ๊ตฌ๋™ ์ค‘์ธ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ pid ํ™•์ธ" + +CURRENT_PID=$(pgrep -fl song-request | grep jar | awk '{print $1}') + +echo "ํ˜„์žฌ ๊ตฌ๋™ ์ค‘์ธ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ pid : $CURRENT_PID" + +if [ -z "$CURRENT_PID" ]; then + echo "> ํ˜„์žฌ ๊ตฌ๋™ ์ค‘์ธ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ์—†์œผ๋ฏ€๋กœ ์ข…๋ฃŒํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค." +else + echo "> kill -15 $CURRENT_PID" + kill -15 $CURRENT_PID + sleep 5 +fi + +echo "> ์ƒˆ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๋ฐฐํฌ" + +JAR_NAME=$(ls -tr $REPOSITORY/*.jar | tail -n 1) + +echo "> JAR Name : $JAR_NAME" + +echo "> $JAR_NAME์— ์‹คํ–‰ ๊ถŒํ•œ ์ถ”๊ฐ€" + +chmod +x $JAR_NAME + +echo "> $JAR_NAME ์‹คํ–‰" + +nohup java -jar \ + -Dspring.profiles.active=prod \ + $JAR_NAME > $REPOSITORY/nohup.out 2>&1 &
Unknown
home์— ๊ทธ๋Œ€๋กœ ๋ฐฐํฌํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค ํด๋”๋ฅผ ์ƒ์„ฑํ•ด์„œ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒŒ ์ข‹์Šต๋‹ˆ๋‹ค. ์ž˜ ์ ์šฉํ•˜์…จ๋„ค์š”
@@ -9,14 +9,16 @@ import javax.annotation.PostConstruct; import java.util.TimeZone; +import static com.requestrealpiano.songrequest.global.constant.JpaProperties.ASIA_SEOUL; + @EnableConfigurationProperties(value = {ManiaDbProperties.class, LastFmProperties.class}) @SpringBootApplication public class SongRequestApplication { @PostConstruct public void setTimeZone() { - String SEOUL = "Asia/Seoul"; - TimeZone.setDefault(TimeZone.getTimeZone(SEOUL)); + TimeZone KST = TimeZone.getTimeZone(ASIA_SEOUL); + TimeZone.setDefault(KST); } public static void main(String[] args) {
Java
```suggestion Timezone.setDefault(TimeZone.getTimeZone(ASIA_SEOUL)); ``` ์œผ๋กœ ๋ฐ”๊พธ๋ฉด ์–ด๋–ป๊ฒŒ ๋˜๋‚˜์š”?
@@ -1,27 +1,33 @@ package com.requestrealpiano.songrequest.controller; -import com.fasterxml.jackson.core.JsonProcessingException; import com.requestrealpiano.songrequest.domain.song.searchapi.response.SearchApiResponse; import com.requestrealpiano.songrequest.global.response.ApiResponse; import com.requestrealpiano.songrequest.service.SongService; import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import javax.validation.constraints.Size; + +import static com.requestrealpiano.songrequest.global.constant.ValidationCondition.*; import static com.requestrealpiano.songrequest.global.response.ApiResponse.OK; @RequiredArgsConstructor +@Validated @RestController -@RequestMapping("/songs") +@RequestMapping("/api/songs") public class SongController { private final SongService songService; @GetMapping - public ApiResponse<SearchApiResponse> search(@RequestParam String artist, - @RequestParam String title) throws JsonProcessingException { + public ApiResponse<SearchApiResponse> search(@RequestParam(defaultValue = "artist") @Size(max = ARTIST_MAX) + String artist, + @RequestParam(defaultValue = "title") @Size(max = TITLE_MAX) + String title) { SearchApiResponse searchApiResponse = songService.searchSong(artist, title); return OK(searchApiResponse); }
Java
RequestParam๋„ ์ข‹์ง€๋งŒ artist, title๋„ ํ•œ๋ฒˆ์— ๊ด€๋ฆฌํ•˜๋Š” DTO๋ฅผ ๋งŒ๋“ค๋ฉด ์–ด๋–ค๊ฐ€์š”? ์ž์ฃผ ์“ฐ์ผ์ง€ ๋ชจ๋ฅด๋‹ˆ DTO๋ฅผ ๋งŒ๋“ค๊ณ  ๊ฑฐ๊ธฐ์„œ Validation์ฒ˜๋ฆฌํ•ด๋„ ๊ดœ์ฐฎ์•„ ๋ณด์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,32 @@ +package com.requestrealpiano.songrequest.domain.letter.request.inner; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.Size; + +import static com.requestrealpiano.songrequest.global.constant.ValidationCondition.*; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +@Getter +public class SongRequest { + + @NotEmpty(message = NOT_EMPTY_MESSAGE) + @Size(min = TITLE_MIN, max = TITLE_MAX, message = TITLE_MESSAGE) + private String title; + + @NotEmpty(message = NOT_EMPTY_MESSAGE) + @Size(min = ARTIST_MIN, max = ARTIST_MAX, message = ARTIST_MESSAGE) + private String artist; + + @Size(max = IMAGE_MAX, message = IMAGE_MESSAGE) + private String imageUrl; + + SongRequest(String title, String artist, String imageUrl) { + this.title = title; + this.artist = artist; + this.imageUrl = imageUrl; + } +}
Java
validation ๊ดœ์ฐฎ๋„ค์š”
@@ -0,0 +1,25 @@ +package com.requestrealpiano.songrequest.global.constant; + +public interface ValidationCondition { + + // Common + String NOT_EMPTY_MESSAGE = "ํ•„์ˆ˜ ์ž…๋ ฅ ์ •๋ณด ์ž…๋‹ˆ๋‹ค."; + + // Artist + String ARTIST_MESSAGE = "์•„ํ‹ฐ์ŠคํŠธ๋Š” 30์ž ๋ฏธ๋งŒ ์ž…๋‹ˆ๋‹ค."; + int ARTIST_MAX = 30; + int ARTIST_MIN = 1; + + // Title + String TITLE_MESSAGE = "์ œ๋ชฉ์€ 30์ž ๋ฏธ๋งŒ ์ž…๋‹ˆ๋‹ค."; + int TITLE_MAX = 30; + int TITLE_MIN = 1; + + // Image URL + String IMAGE_MESSAGE = "์œ ํšจํ•œ ์ด๋ฏธ์ง€ ์ •๋ณด๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค."; + int IMAGE_MAX = 100; + + // Song Story + String SONG_STORY_MESSAGE = "์‚ฌ์—ฐ์€ 500์ž ๋ฏธ๋งŒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค."; + int SONG_STORY_MAX = 500; +}
Java
interface์— ๊ทธ๋Œ€๋กœ value๊ฐ’์„ ์ง€์ •ํ•˜๋ฉด ์ข‹์ง€์•Š์Šต๋‹ˆ๋‹ค. ์ดํŽ™ํ‹ฐ๋ธŒ ์ž๋ฐ”์—์„œ ๋ณธ ๊ฑฐ๊ฐ™์€๋ฐ ๋‚ด์šฉ์ด ์ •ํ™•ํ•˜๊ฒŒ ๊ธฐ์–ต์€ ์•ˆ๋‚˜์ง€๋งŒ ์ด๋ ‡๊ฒŒ ํ•˜์ง€๋ง๋ผ๊ณ  ๊ฐ•ํ•˜๊ฒŒ ๊ฒฝ๊ณ ํ–ˆ๋˜ ๊ธฐ์–ต์ด ๋‚˜๋„ค์š”. ๊ทธ๋ฆฌ๊ณ  ๋‚ด์šฉ์ƒ interface๋ณด๋‹จ enum์— ์–ด์šธ๋ฆฌ๋Š”๋ฐ enum์€ ์–ด๋–ค๊ฐ€์š”?
@@ -0,0 +1,64 @@ +package com.requestrealpiano.songrequest.global.error; + +import com.requestrealpiano.songrequest.global.error.exception.BusinessException; +import com.requestrealpiano.songrequest.global.error.exception.ParsingFailedException; +import com.requestrealpiano.songrequest.global.error.response.ErrorCode; +import com.requestrealpiano.songrequest.global.error.response.ErrorResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import javax.validation.ConstraintViolationException; + +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(ConstraintViolationException.class) + protected ResponseEntity<ErrorResponse> handleConstraintViolationException(ConstraintViolationException exception) { + log.error("handleConstraintViolationException", exception); + ErrorResponse errorResponse = ErrorResponse.from(ErrorCode.INVALID_INPUT_VALUE); + return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + protected ResponseEntity<ErrorResponse> handleMethodArgumentNotValidException(MethodArgumentNotValidException exception){ + log.error("handleMethodArgumentNotValidException", exception); + ErrorResponse errorResponse = ErrorResponse.of(ErrorCode.INVALID_INPUT_VALUE, exception.getBindingResult()); + return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(HttpRequestMethodNotSupportedException.class) + protected ResponseEntity<ErrorResponse> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException exception) { + log.error("handleHttpRequestMethodNotSupportedException", exception); + ErrorResponse errorResponse = ErrorResponse.from(ErrorCode.METHOD_NOT_ALLOWED); + return new ResponseEntity<>(errorResponse, HttpStatus.METHOD_NOT_ALLOWED); + } + + @ExceptionHandler(ParsingFailedException.class) + protected ResponseEntity<ErrorResponse> handleParsingFailedException(ParsingFailedException exception) { + log.error("handleJsonProcessingException", exception); + ErrorCode errorCode = exception.getErrorCode(); + ErrorResponse errorResponse = ErrorResponse.from(errorCode); + return new ResponseEntity<>(errorResponse, HttpStatus.valueOf(errorResponse.getStatusCode())); + } + + @ExceptionHandler(BusinessException.class) + protected ResponseEntity<ErrorResponse> handleBusinessException(BusinessException exception) { + log.error("handleBusinessException", exception); + ErrorCode errorCode = exception.getErrorCode(); + ErrorResponse errorResponse = ErrorResponse.from(errorCode); + return new ResponseEntity<>(errorResponse, HttpStatus.valueOf(errorCode.getStatusCode())); + } + + @ExceptionHandler(Exception.class) + protected ResponseEntity<ErrorResponse> handleException(Exception exception) { + log.error("handleException", exception); + ErrorResponse errorResponse = ErrorResponse.from(ErrorCode.INTERNAL_SERVER_ERROR); + return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR); + } +}
Java
์ด ์ฝ”๋“œ๊ฐ€ validation ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋กœ ์•Œ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ž‘๋™์ด ์ž˜๋˜๋‚˜์š”? ํ•œ๋ฒˆ ํ…Œ์ŠคํŠธ์ฝ”๋“œ์—์„œ ํ™•์ธํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,38 @@ +#!/bin/bash + +REPOSITORY=/home/ubuntu/app/songrequest +PROJECT_NAME=song-request + +echo "> Build ํŒŒ์ผ ๋ณต์‚ฌ" + +cp $REPOSITORY/zip/*.jar $REPOSITORY/ + +echo "> ํ˜„์žฌ ๊ตฌ๋™ ์ค‘์ธ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ pid ํ™•์ธ" + +CURRENT_PID=$(pgrep -fl song-request | grep jar | awk '{print $1}') + +echo "ํ˜„์žฌ ๊ตฌ๋™ ์ค‘์ธ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ pid : $CURRENT_PID" + +if [ -z "$CURRENT_PID" ]; then + echo "> ํ˜„์žฌ ๊ตฌ๋™ ์ค‘์ธ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ์—†์œผ๋ฏ€๋กœ ์ข…๋ฃŒํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค." +else + echo "> kill -15 $CURRENT_PID" + kill -15 $CURRENT_PID + sleep 5 +fi + +echo "> ์ƒˆ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๋ฐฐํฌ" + +JAR_NAME=$(ls -tr $REPOSITORY/*.jar | tail -n 1) + +echo "> JAR Name : $JAR_NAME" + +echo "> $JAR_NAME์— ์‹คํ–‰ ๊ถŒํ•œ ์ถ”๊ฐ€" + +chmod +x $JAR_NAME + +echo "> $JAR_NAME ์‹คํ–‰" + +nohup java -jar \ + -Dspring.profiles.active=prod \ + $JAR_NAME > $REPOSITORY/nohup.out 2>&1 &
Unknown
p4 : ์ž๋™ ๋ฐฐํฌ ์Šคํฌ๋ฆฝํŠธ ๊ตฐ์š” ๐Ÿ‘ ๊ฐ„๋‹จํ•œ ํŒ์ด์ง€๋งŒ.. ์—ฌ๊ธฐ์„œ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ๋Š” `tail`, `grep`๋“ฑ๋“ฑ ์— ๋Œ€ํ•œ ๊ธฐ๋ณธ์ ์ธ ์ดํ•ด ์ •๋„๋Š” ์žˆ์œผ์‹œ๋ฉด ์ข‹์„๋“ฏ ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,25 @@ +package com.requestrealpiano.songrequest.global.constant; + +public interface ValidationCondition { + + // Common + String NOT_EMPTY_MESSAGE = "ํ•„์ˆ˜ ์ž…๋ ฅ ์ •๋ณด ์ž…๋‹ˆ๋‹ค."; + + // Artist + String ARTIST_MESSAGE = "์•„ํ‹ฐ์ŠคํŠธ๋Š” 30์ž ๋ฏธ๋งŒ ์ž…๋‹ˆ๋‹ค."; + int ARTIST_MAX = 30; + int ARTIST_MIN = 1; + + // Title + String TITLE_MESSAGE = "์ œ๋ชฉ์€ 30์ž ๋ฏธ๋งŒ ์ž…๋‹ˆ๋‹ค."; + int TITLE_MAX = 30; + int TITLE_MIN = 1; + + // Image URL + String IMAGE_MESSAGE = "์œ ํšจํ•œ ์ด๋ฏธ์ง€ ์ •๋ณด๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค."; + int IMAGE_MAX = 100; + + // Song Story + String SONG_STORY_MESSAGE = "์‚ฌ์—ฐ์€ 500์ž ๋ฏธ๋งŒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค."; + int SONG_STORY_MAX = 500; +}
Java
p3: ์ €๋„ enum์ด๋‚˜ ๋‹ค๋ฅธ class์œผ๋กœ ๊ด€๋ฆฌํ•˜์‹œ๋Š” ๊ฒŒ ์ข‹๋‹ค๊ณ  ์ƒ๊ฐ๋˜๋„ค์š”!
@@ -0,0 +1,63 @@ +language: java +jdk: + - openjdk11 + +branches: + only: + - main + +cache: + directories: + - '$HOME/.m2/repository' + - '$HOME/.gradle' + +script: "./gradlew clean build" + +before_deploy: + - mkdir -p before-deploy + - cp scripts/*.sh before-deploy/ + - cp appspec.yml before-deploy/ + - cp build/libs/*.jar before-deploy + - cd before-deploy && zip -r before-deploy * + - cd ../ && mkdir -p deploy + - mv before-deploy/before-deploy.zip deploy/songrequest-backend.zip + +deploy: + - provider: s3 + access_key_id: $AWS_ACCESS_KEY + secret_access_key: $AWS_SECRET_KEY + + bucket: songrequest-backend-build + region: ap-northeast-2 + + skip_cleanup: true + acl: private + local_dir: deploy + + wait-until-deployed: true + + on: + all_branches: true + + - provider: codedeploy + access_key_id: $AWS_ACCESS_KEY + secret_access_key: $AWS_SECRET_KEY + + bucket: songrequest-backend-build + key: songrequest-backend.zip + + bundle_type: zip + application: songrequest-backend + + deployment_group: songrequest-backend-group + + region: ap-northeast-2 + wait-until-deployed: true + + on: + all_branches: true + +notifications: + email: + recipients: + - museopkim0214@gmail.com
Unknown
travis CI๋ฅผ ์‚ฌ์šฉํ•œ ๊ธฐ์ˆ ์ ์ธ ์ด์œ ๋Š” ์—†์—ˆ์Šต๋‹ˆ๋‹คใ…Žใ…Ž CI / CD๋ฅผ ๋‹ค์–‘ํ•œ ํˆด๋กœ ๊ฒฝํ—˜ ํ•ด๋ณด๊ณ  ์‹ถ์–ด์„œ ๋ฐฑ์—”๋“œ๋Š” travis CI, ํ”„๋ก ํŠธ๋Š” Github Actions๋กœ ๋ฐฐํฌ ํ™˜๊ฒฝ์„ ๊ตฌ์„ฑ ํ–ˆ์Šต๋‹ˆ๋‹ค. travis CI๋ฅผ ์จ๋ณด๊ณ  ๋А๋‚€ ๊ฒƒ์€... ๋””๋ฒ„๊น… ๊ณผ์ •์—์„œ ๋ถˆํŽธํ•จ์€ ์—†์—ˆ๊ณ , ๋‹ค๋งŒ ๋ง์”€ ํ•˜์‹  ๊ฒƒ์ฒ˜๋Ÿผ ์กฐ๊ธˆ ๋А๋ฆฐ ๊ฒƒ์ด ์•ฝ๊ฐ„ ๋ถˆํŽธ ํ–ˆ์Šต๋‹ˆ๋‹ค. ํ”„๋ก ํŠธ์™€ ๋นŒ๋“œ ๊ณผ์ •์ด ๋‹ค๋ฅด๊ธฐ ๋•Œ๋ฌธ์— ์ ˆ๋Œ€์ ์ธ ๋น„๊ต๋Š” ๋ถˆ๊ฐ€ ํ•˜์ง€๋งŒ ์ €๋„ Github Actions๊ฐ€ ์•ฝ๊ฐ„ ๋” ๋น ๋ฅธ ๋А๋‚Œ์ด์—ˆ๋„ค์š”.
@@ -0,0 +1,18 @@ +version: 0.0 +os: linux +files: + - source: / + destination: /home/ubuntu/app/songrequest/zip/ + overwrite: yes + +permissions: + - object: / + pattern: "**" + owner: ubuntu + group: ubuntu + +hooks: + ApplicationStart: + - location: deploy.sh + timeout: 60 + runas: ubuntu
Unknown
๋งŒ์•ฝ ๊ฐœ์ธ ํ”„๋กœ์ ํŠธ๋กœ blue / green ๋ฐฐํฌ๊นŒ์ง€ ํ•˜๊ฒŒ ๋œ๋‹ค๋ฉด ๋งค์šฐ ํฐ ์„ฑ๊ณผ๊ฒ ๋„ค์š”ใ…Žใ…Ž ์จ๋‹ˆ ๋ธ”๋กœ๊ทธ์— ์ž˜ ๋ณด๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๐Ÿ˜„ ์ข‹์€ ํŒ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.
@@ -1,27 +1,33 @@ package com.requestrealpiano.songrequest.controller; -import com.fasterxml.jackson.core.JsonProcessingException; import com.requestrealpiano.songrequest.domain.song.searchapi.response.SearchApiResponse; import com.requestrealpiano.songrequest.global.response.ApiResponse; import com.requestrealpiano.songrequest.service.SongService; import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import javax.validation.constraints.Size; + +import static com.requestrealpiano.songrequest.global.constant.ValidationCondition.*; import static com.requestrealpiano.songrequest.global.response.ApiResponse.OK; @RequiredArgsConstructor +@Validated @RestController -@RequestMapping("/songs") +@RequestMapping("/api/songs") public class SongController { private final SongService songService; @GetMapping - public ApiResponse<SearchApiResponse> search(@RequestParam String artist, - @RequestParam String title) throws JsonProcessingException { + public ApiResponse<SearchApiResponse> search(@RequestParam(defaultValue = "artist") @Size(max = ARTIST_MAX) + String artist, + @RequestParam(defaultValue = "title") @Size(max = TITLE_MAX) + String title) { SearchApiResponse searchApiResponse = songService.searchSong(artist, title); return OK(searchApiResponse); }
Java
์•„์ง์€ ์—ฌ๊ธฐ์„œ ๋ฐ–์— ์“ฐ์ด์ง€ ์•Š๋Š”๋ฐ ์‚ฌ์šฉ ๋˜๋Š” ๊ณณ์ด ๋” ๋งŽ์•„์ง€๋ฉด `@ModelAttribute` ๊ฐ์ฒด๋กœ ํ•œ๋ฒˆ ๊ด€๋ฆฌ ํ•ด๋ณผ๊ฒŒ์š”!
@@ -0,0 +1,25 @@ +package com.requestrealpiano.songrequest.global.constant; + +public interface ValidationCondition { + + // Common + String NOT_EMPTY_MESSAGE = "ํ•„์ˆ˜ ์ž…๋ ฅ ์ •๋ณด ์ž…๋‹ˆ๋‹ค."; + + // Artist + String ARTIST_MESSAGE = "์•„ํ‹ฐ์ŠคํŠธ๋Š” 30์ž ๋ฏธ๋งŒ ์ž…๋‹ˆ๋‹ค."; + int ARTIST_MAX = 30; + int ARTIST_MIN = 1; + + // Title + String TITLE_MESSAGE = "์ œ๋ชฉ์€ 30์ž ๋ฏธ๋งŒ ์ž…๋‹ˆ๋‹ค."; + int TITLE_MAX = 30; + int TITLE_MIN = 1; + + // Image URL + String IMAGE_MESSAGE = "์œ ํšจํ•œ ์ด๋ฏธ์ง€ ์ •๋ณด๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค."; + int IMAGE_MAX = 100; + + // Song Story + String SONG_STORY_MESSAGE = "์‚ฌ์—ฐ์€ 500์ž ๋ฏธ๋งŒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค."; + int SONG_STORY_MAX = 500; +}
Java
์ธํ„ฐํŽ˜์ด์Šค๊ฐ€ static ์ƒ์ˆ˜์™€ ์ถ”์ƒ ๋ฉ”์„œ๋“œ๋งŒ ์ ‘๊ทผ ๊ฐ€๋Šฅํ•ด์„œ ์ด๋ ‡๊ฒŒ ์ ์šฉ ํ•ด๋ดค์—ˆ๋Š”๋ฐ, ๋‹ค์‹œ ๋ณด๋‹ˆ Enum์œผ๋กœ ๊ด€๋ฆฌ ํ•˜๋Š”๊ฒŒ ๋” ์ ํ•ฉ ํ• ๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค. (+) ์–ธ๊ธ‰ํ•˜์‹  ์ดํŽ™ํ‹ฐ๋ธŒ ์ž๋ฐ”์˜ ๋‚ด์šฉ์€ (3rd edition ๊ธฐ์ค€) `Item 22` ์— ์žˆ๋„ค์š”!
@@ -0,0 +1,38 @@ +#!/bin/bash + +REPOSITORY=/home/ubuntu/app/songrequest +PROJECT_NAME=song-request + +echo "> Build ํŒŒ์ผ ๋ณต์‚ฌ" + +cp $REPOSITORY/zip/*.jar $REPOSITORY/ + +echo "> ํ˜„์žฌ ๊ตฌ๋™ ์ค‘์ธ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ pid ํ™•์ธ" + +CURRENT_PID=$(pgrep -fl song-request | grep jar | awk '{print $1}') + +echo "ํ˜„์žฌ ๊ตฌ๋™ ์ค‘์ธ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ pid : $CURRENT_PID" + +if [ -z "$CURRENT_PID" ]; then + echo "> ํ˜„์žฌ ๊ตฌ๋™ ์ค‘์ธ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ์—†์œผ๋ฏ€๋กœ ์ข…๋ฃŒํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค." +else + echo "> kill -15 $CURRENT_PID" + kill -15 $CURRENT_PID + sleep 5 +fi + +echo "> ์ƒˆ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๋ฐฐํฌ" + +JAR_NAME=$(ls -tr $REPOSITORY/*.jar | tail -n 1) + +echo "> JAR Name : $JAR_NAME" + +echo "> $JAR_NAME์— ์‹คํ–‰ ๊ถŒํ•œ ์ถ”๊ฐ€" + +chmod +x $JAR_NAME + +echo "> $JAR_NAME ์‹คํ–‰" + +nohup java -jar \ + -Dspring.profiles.active=prod \ + $JAR_NAME > $REPOSITORY/nohup.out 2>&1 &
Unknown
๋ง์”€ ํ•˜์‹  ๊ฒƒ์ฒ˜๋Ÿผ EC2์™€ Nginx๋ฅผ ์„ค์ •ํ•˜๊ณ  ๋ฐฐํฌ ํ™˜๊ฒฝ์„ ๊ตฌ์„ฑํ•˜๋Š” ๊ณผ์ •์—์„œ ๋ฆฌ๋ˆ…์Šค ๋ช…๋ น์–ด๊ฐ€ ๋งŽ์ด ๋ถ€์กฑํ•˜๋‹ค๋Š” ๊ฒƒ์„ ๋А๊ผˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ๋ณ„๋„๋กœ ์กฐ๊ธˆ์”ฉ ๊ณต๋ถ€๋ฅผ ํ•˜๊ณ  ์žˆ์–ด์š”ใ…Žใ…Ž ์กฐ์–ธ ํ•ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! ๐Ÿ™‚
@@ -0,0 +1,271 @@ +var Domclass = require('../util/Domclass'); +var Eventutil = require('../util/Eventutil'); +var snippet = require('tui-code-snippet'); + +var KEY_ENTER = 13; + +var todoObjects = []; // ๋ชจ๋“  todoData +var completeTodoObjects = []; // isChecked๊ฐ€ true์ธ ๊ฐ’ +var incompleteTodoObjects = []; // isChecked๊ฐ€ false์ธ ๊ฐ’ + +var todoListWrapElement; +var completeListElement; +var incompleteListElement; +var leftItemNumElement; +var completeItemsNumElement; + +var _initElement = function() { + todoListWrapElement = document.getElementById('todoListWrap'); + completeListElement = document.getElementById('completeList'); + incompleteListElement = document.getElementById('incompleteList'); + leftItemNumElement = document.getElementById('leftItemsNum'); + completeItemsNumElement = document.getElementById('completeItemsNum'); +}; + +var _forEach = function(arr, func) { + var i = 0; + var arrLength = arr.length; + for (; i < arrLength; i += 1) { + func.call(this, i, arr[i]); + } +}; + +/** + * ๊ฐ์ฒด๊ฐ€ ๋“ฑ๋ก๋œ ์‹œ๊ฐ„์„ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ ํ•˜๋Š” ํ•จ์ˆ˜ + * @param {array} arr ๋Š” ์ •๋ ฌํ•˜๊ณ  ์‹ถ์€ ๋ฐฐ์—ด + */ +function _sortRegDateOfTodoObject(arr) { + arr.sort(function(a, b) { + if (a.regDate < b.regDate) { + return 1; + } else if (a.regDate > b.regDate) { + return -1; + } + + return 0; + }); +} + +/** + * ์ธ์ž๋กœ ๋ฐ›์€ ๋ฐ์ดํ„ฐ ์ •๋ณด๋ฅผ todoObjects์— ๋‹ด๊ณ , isChecked = false์ธ๊ฒƒ์€ incompleteTodoObjects, + * isChecked = true์ธ๊ฒƒ์€ completeTodoObjects ๋ฐฐ์—ด์— ๋‹ด์€ ๋’ค ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ + * @param {array} todoData ๋Š” todo ๋ฐ์ดํ„ฐ ์ •๋ณด + */ +function _loadTodoData(todoData) { + todoObjects = todoData; + + completeTodoObjects = snippet.filter(todoObjects, function(value) { + return value.isChecked; + }); + + _sortRegDateOfTodoObject(completeTodoObjects); + + incompleteTodoObjects = snippet.filter(todoObjects, function(value) { + return !value.isChecked; + }); + + _sortRegDateOfTodoObject(incompleteTodoObjects); +} + +/** + * completeList๋ฅผ ๋ Œ๋”๋งํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ + */ +function _renderCompleteTodoList() { + var htmlLi = ''; + var todoId, todoTitle; + + _forEach(completeTodoObjects, function(index, value) { + todoId = value.id; + todoTitle = value.title; + htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk" checked/><p class="todoTitle">' + todoTitle + '</p></li>'; + }); + + completeListElement.innerHTML = htmlLi; +} + +/** + * incompleteList๋ฅผ ๋ Œ๋”๋งํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ + */ +function _renderIncompleteTodoList() { + var htmlLi = ''; + var todoId, todoTitle; + + _forEach(incompleteTodoObjects, function(index, value) { + todoId = value.id; + todoTitle = value.title; + htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk"/><p class="todoTitle">' + todoTitle + '</p></li>'; + }); + + incompleteListElement.innerHTML = htmlLi; +} + +/** + * _renderCompleteTodoList, _renderIncompleteTodoList ํ•จ์ˆ˜ ํ˜ธ์ถœ + */ +function _renderTodoList() { + _renderCompleteTodoList(); + _renderIncompleteTodoList(); +} + +/** + * infoList๋ฅผ ๋ Œ๋”๋ง ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ + */ +function _renderInfoList() { + leftItemNumElement.innerText = incompleteTodoObjects.length; + completeItemsNumElement.innerText = completeTodoObjects.length; +} + +/** + * _renderTodoList, _renderInfoList ํ•จ์ˆ˜ ํ˜ธ์ถœ + */ +function _renderView() { + _renderTodoList(); + _renderInfoList(); +} + +/** + * ํ…์ŠคํŠธ๋ฐ•์Šค์—์„œ ๋ฐ›์€ ๊ฐ’์„ ๊ฐ€์ง€๊ณ  ์ƒˆ๋กœ์šด todo ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค๊ณ  todoObjects์— ๋„ฃ์–ด ๋‘”๋’ค ์žฌ ๋ Œ๋”๋ง + * @param {object} target ๋Š” inputTxt ๊ฐ์ฒด + */ +function _addTodoObject(target) { + var objTodo = { + id: 'todo' + snippet.stamp({}), + title: target.value, + isChecked: false, + regDate: snippet.timestamp() + }; + todoObjects.push(objTodo); + target.value = ''; + + _loadTodoData(todoObjects); + _renderView(); +} + +/** + * keypress์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ์ด๋ฒคํŠธ ๊ฐ์ฒด๋ฅผ ๋ฐ›์•„์„œ targetId๊ฐ’์— ๋”ฐ๋ผ ํ•ด๋‹น ํ•จ์ˆ˜ ํ˜ธ์ถœ + * @param {object} event ๋Š” ์ด๋ฒคํŠธ ๊ฐ์ฒด + */ +function _keypressEvent(event) { + var target, key, targetId; + target = event.target || event.srcElement; + key = event.keyCode; + targetId = target.getAttribute('id'); + + if (!target.value) { + return; + } + + if (key === KEY_ENTER && targetId === 'todoInputTxt') { + _addTodoObject(target); + } +} + +/** + * ํ•ด๋‹น todo์˜ checkbox๋ฅผ ํด๋ฆญํ•˜๋ฉด isChecked์˜ ๊ฐ’์„ ๋ณ€๊ฒฝํ•œ ๋’ค ์žฌ ๋ Œ๋”๋ง + * @param {string} idTodo ๋Š” todo์˜ id๊ฐ’ + * @param {object} isCheckedTarget ๋Š” ํด๋ฆญ๋œ checkbox์˜ isChecked๊ฐ’ + */ +function _toggleTodo(idTodo, isCheckedTarget) { + _forEach(todoObjects, function(index, value) { + if (value.id === idTodo) { + value.isChecked = (!!isCheckedTarget); + } + }); + _loadTodoData(todoObjects); + _renderView(); +} + +/** + * ์™„๋ฃŒ๋œ ๋ชจ๋“  todoํ•ญ๋ชฉ๋“ค์„ ์ œ๊ฑฐ ํ•˜๋Š” ํ•จ์ˆ˜ + */ +function _removeComplteList() { + if (completeTodoObjects.length === 0) { + return; + } + completeTodoObjects = []; + todoObjects = snippet.filter(todoObjects, function(value) { + return (value.isChecked === false); + }); + _renderView(); +} + +/** + * completeList, incompleteList ์—˜๋ฆฌ๋ฉ˜ํŠธ์˜ hide ํด๋ž˜์Šค ์ œ๊ฑฐ + */ +function _removeClassHideOfList() { + Domclass.removeClass(completeListElement, 'hide'); + Domclass.removeClass(incompleteListElement, 'hide'); +} + +/** + * filter Button ์ค‘์— ํ•˜๋‚˜๋ฅผ ํด๋ฆญํ•˜๋ฉด ํ•ด๋‹น ๋™์ž‘์— ๋งž๊ฒŒ hideํด๋ž˜์Šค๋ฅผ ์ถ”๊ฐ€ํ•˜์—ฌ List์˜ ์†์„ฑ๊ฐ’ display:none์œผ๋กœ ๋ณ€๊ฒฝ + * @param {object} target ๋Š” filter Button ๊ฐ์ฒด ์ค‘ ํ•˜๋‚˜ + */ +function _clickFilterBtn(target) { + if (target.id === 'btnAllList') { + _removeClassHideOfList(); + } else if (target.id === 'btnActiveList') { + _removeClassHideOfList(); + Domclass.addClass(completeListElement, 'hide'); + } else if (target.id === 'btnCompleteList') { + _removeClassHideOfList(); + Domclass.addClass(incompleteListElement, 'hide'); + } +} + +/** + * click ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ์ด๋ฒคํŠธ ๊ฐ์ฒด๋ฅผ ๋ฐ›์•„์„œ target ๊ฐ’์— ๋”ฐ๋ผ ํ•ด๋‹น ํ•จ์ˆ˜ ํ˜ธ์ถœ + * @param {object} event ๋Š” ์ด๋ฒคํŠธ ๊ฐ์ฒด + */ +function _clickEvent(event) { + var target; + var todoElement; + var todoId; + target = event.target || event.srcElement; + todoElement = target.parentElement; + + if (target.type === 'checkbox' && Domclass.hasClass(todoElement, 'todo')) { + todoId = todoElement.getAttribute('data-id'); + _toggleTodo(todoId, target.checked); + } else if (target.id === 'btnDelCompleteList') { + _removeComplteList(); + } else if (target.id === 'btnAllList' || target.id === 'btnActiveList' || target.id === 'btnCompleteList') { + _clickFilterBtn(target); + } +} + +/** + * keypress, click ์ด๋ฒคํŠธ ๋ฐ”์ธ๋”ฉ + */ +function _bindEvent() { + Eventutil.addHandler(todoListWrapElement, 'keypress', _keypressEvent); + Eventutil.addHandler(todoListWrapElement, 'click', _clickEvent); +} + +/** + * ๊ฐ์ข… ํ•จ์ˆ˜ ์ดˆ๊ธฐํ™” + * @param {object} todoData todoList์— ๋Œ€ํ•œ ๋ฐ์ดํ„ฐ ์ •๋ณด + */ +function init(todoData) { + _initElement(); + _loadTodoData(todoData); + _renderView(); + _bindEvent(); +} + +/** + * @returns {Object} ํ˜„์žฌ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” todo ๊ฐ์ฒด ๋ฐ˜ํ™˜ + */ +function getTodoObjects() { + return todoObjects; +} + +module.exports = { + init: init, + // test์—์„œ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ํ•จ์ˆ˜๋ฅผ ๋…ธ์ถœ์‹œ์ผœ๋‘์—ˆ์Šต๋‹ˆ๋‹ค. + _clickFilterBtn: _clickFilterBtn, + _removeComplteList: _removeComplteList, + _toggleTodo: _toggleTodo, + _addTodoObject: _addTodoObject, + getTodoObjects: getTodoObjects +};
JavaScript
ํŒŒ์ผ์ด ํ•˜๋‚˜ ๋Š˜์–ด๋‚˜๋„.. ์ด๋Ÿฐ ๋ฐฐ์—ด ์—ฐ์‚ฐ์— ๋Œ€ํ•œ ๋กœ์ง๋“ค์€ ์œ ํ‹ธ๋กœ ๋นผ๋Š”๊ฒŒ ์ข‹์Šต๋‹ˆ๋‹ค~
@@ -0,0 +1,271 @@ +var Domclass = require('../util/Domclass'); +var Eventutil = require('../util/Eventutil'); +var snippet = require('tui-code-snippet'); + +var KEY_ENTER = 13; + +var todoObjects = []; // ๋ชจ๋“  todoData +var completeTodoObjects = []; // isChecked๊ฐ€ true์ธ ๊ฐ’ +var incompleteTodoObjects = []; // isChecked๊ฐ€ false์ธ ๊ฐ’ + +var todoListWrapElement; +var completeListElement; +var incompleteListElement; +var leftItemNumElement; +var completeItemsNumElement; + +var _initElement = function() { + todoListWrapElement = document.getElementById('todoListWrap'); + completeListElement = document.getElementById('completeList'); + incompleteListElement = document.getElementById('incompleteList'); + leftItemNumElement = document.getElementById('leftItemsNum'); + completeItemsNumElement = document.getElementById('completeItemsNum'); +}; + +var _forEach = function(arr, func) { + var i = 0; + var arrLength = arr.length; + for (; i < arrLength; i += 1) { + func.call(this, i, arr[i]); + } +}; + +/** + * ๊ฐ์ฒด๊ฐ€ ๋“ฑ๋ก๋œ ์‹œ๊ฐ„์„ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ ํ•˜๋Š” ํ•จ์ˆ˜ + * @param {array} arr ๋Š” ์ •๋ ฌํ•˜๊ณ  ์‹ถ์€ ๋ฐฐ์—ด + */ +function _sortRegDateOfTodoObject(arr) { + arr.sort(function(a, b) { + if (a.regDate < b.regDate) { + return 1; + } else if (a.regDate > b.regDate) { + return -1; + } + + return 0; + }); +} + +/** + * ์ธ์ž๋กœ ๋ฐ›์€ ๋ฐ์ดํ„ฐ ์ •๋ณด๋ฅผ todoObjects์— ๋‹ด๊ณ , isChecked = false์ธ๊ฒƒ์€ incompleteTodoObjects, + * isChecked = true์ธ๊ฒƒ์€ completeTodoObjects ๋ฐฐ์—ด์— ๋‹ด์€ ๋’ค ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ + * @param {array} todoData ๋Š” todo ๋ฐ์ดํ„ฐ ์ •๋ณด + */ +function _loadTodoData(todoData) { + todoObjects = todoData; + + completeTodoObjects = snippet.filter(todoObjects, function(value) { + return value.isChecked; + }); + + _sortRegDateOfTodoObject(completeTodoObjects); + + incompleteTodoObjects = snippet.filter(todoObjects, function(value) { + return !value.isChecked; + }); + + _sortRegDateOfTodoObject(incompleteTodoObjects); +} + +/** + * completeList๋ฅผ ๋ Œ๋”๋งํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ + */ +function _renderCompleteTodoList() { + var htmlLi = ''; + var todoId, todoTitle; + + _forEach(completeTodoObjects, function(index, value) { + todoId = value.id; + todoTitle = value.title; + htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk" checked/><p class="todoTitle">' + todoTitle + '</p></li>'; + }); + + completeListElement.innerHTML = htmlLi; +} + +/** + * incompleteList๋ฅผ ๋ Œ๋”๋งํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ + */ +function _renderIncompleteTodoList() { + var htmlLi = ''; + var todoId, todoTitle; + + _forEach(incompleteTodoObjects, function(index, value) { + todoId = value.id; + todoTitle = value.title; + htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk"/><p class="todoTitle">' + todoTitle + '</p></li>'; + }); + + incompleteListElement.innerHTML = htmlLi; +} + +/** + * _renderCompleteTodoList, _renderIncompleteTodoList ํ•จ์ˆ˜ ํ˜ธ์ถœ + */ +function _renderTodoList() { + _renderCompleteTodoList(); + _renderIncompleteTodoList(); +} + +/** + * infoList๋ฅผ ๋ Œ๋”๋ง ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ + */ +function _renderInfoList() { + leftItemNumElement.innerText = incompleteTodoObjects.length; + completeItemsNumElement.innerText = completeTodoObjects.length; +} + +/** + * _renderTodoList, _renderInfoList ํ•จ์ˆ˜ ํ˜ธ์ถœ + */ +function _renderView() { + _renderTodoList(); + _renderInfoList(); +} + +/** + * ํ…์ŠคํŠธ๋ฐ•์Šค์—์„œ ๋ฐ›์€ ๊ฐ’์„ ๊ฐ€์ง€๊ณ  ์ƒˆ๋กœ์šด todo ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค๊ณ  todoObjects์— ๋„ฃ์–ด ๋‘”๋’ค ์žฌ ๋ Œ๋”๋ง + * @param {object} target ๋Š” inputTxt ๊ฐ์ฒด + */ +function _addTodoObject(target) { + var objTodo = { + id: 'todo' + snippet.stamp({}), + title: target.value, + isChecked: false, + regDate: snippet.timestamp() + }; + todoObjects.push(objTodo); + target.value = ''; + + _loadTodoData(todoObjects); + _renderView(); +} + +/** + * keypress์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ์ด๋ฒคํŠธ ๊ฐ์ฒด๋ฅผ ๋ฐ›์•„์„œ targetId๊ฐ’์— ๋”ฐ๋ผ ํ•ด๋‹น ํ•จ์ˆ˜ ํ˜ธ์ถœ + * @param {object} event ๋Š” ์ด๋ฒคํŠธ ๊ฐ์ฒด + */ +function _keypressEvent(event) { + var target, key, targetId; + target = event.target || event.srcElement; + key = event.keyCode; + targetId = target.getAttribute('id'); + + if (!target.value) { + return; + } + + if (key === KEY_ENTER && targetId === 'todoInputTxt') { + _addTodoObject(target); + } +} + +/** + * ํ•ด๋‹น todo์˜ checkbox๋ฅผ ํด๋ฆญํ•˜๋ฉด isChecked์˜ ๊ฐ’์„ ๋ณ€๊ฒฝํ•œ ๋’ค ์žฌ ๋ Œ๋”๋ง + * @param {string} idTodo ๋Š” todo์˜ id๊ฐ’ + * @param {object} isCheckedTarget ๋Š” ํด๋ฆญ๋œ checkbox์˜ isChecked๊ฐ’ + */ +function _toggleTodo(idTodo, isCheckedTarget) { + _forEach(todoObjects, function(index, value) { + if (value.id === idTodo) { + value.isChecked = (!!isCheckedTarget); + } + }); + _loadTodoData(todoObjects); + _renderView(); +} + +/** + * ์™„๋ฃŒ๋œ ๋ชจ๋“  todoํ•ญ๋ชฉ๋“ค์„ ์ œ๊ฑฐ ํ•˜๋Š” ํ•จ์ˆ˜ + */ +function _removeComplteList() { + if (completeTodoObjects.length === 0) { + return; + } + completeTodoObjects = []; + todoObjects = snippet.filter(todoObjects, function(value) { + return (value.isChecked === false); + }); + _renderView(); +} + +/** + * completeList, incompleteList ์—˜๋ฆฌ๋ฉ˜ํŠธ์˜ hide ํด๋ž˜์Šค ์ œ๊ฑฐ + */ +function _removeClassHideOfList() { + Domclass.removeClass(completeListElement, 'hide'); + Domclass.removeClass(incompleteListElement, 'hide'); +} + +/** + * filter Button ์ค‘์— ํ•˜๋‚˜๋ฅผ ํด๋ฆญํ•˜๋ฉด ํ•ด๋‹น ๋™์ž‘์— ๋งž๊ฒŒ hideํด๋ž˜์Šค๋ฅผ ์ถ”๊ฐ€ํ•˜์—ฌ List์˜ ์†์„ฑ๊ฐ’ display:none์œผ๋กœ ๋ณ€๊ฒฝ + * @param {object} target ๋Š” filter Button ๊ฐ์ฒด ์ค‘ ํ•˜๋‚˜ + */ +function _clickFilterBtn(target) { + if (target.id === 'btnAllList') { + _removeClassHideOfList(); + } else if (target.id === 'btnActiveList') { + _removeClassHideOfList(); + Domclass.addClass(completeListElement, 'hide'); + } else if (target.id === 'btnCompleteList') { + _removeClassHideOfList(); + Domclass.addClass(incompleteListElement, 'hide'); + } +} + +/** + * click ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ์ด๋ฒคํŠธ ๊ฐ์ฒด๋ฅผ ๋ฐ›์•„์„œ target ๊ฐ’์— ๋”ฐ๋ผ ํ•ด๋‹น ํ•จ์ˆ˜ ํ˜ธ์ถœ + * @param {object} event ๋Š” ์ด๋ฒคํŠธ ๊ฐ์ฒด + */ +function _clickEvent(event) { + var target; + var todoElement; + var todoId; + target = event.target || event.srcElement; + todoElement = target.parentElement; + + if (target.type === 'checkbox' && Domclass.hasClass(todoElement, 'todo')) { + todoId = todoElement.getAttribute('data-id'); + _toggleTodo(todoId, target.checked); + } else if (target.id === 'btnDelCompleteList') { + _removeComplteList(); + } else if (target.id === 'btnAllList' || target.id === 'btnActiveList' || target.id === 'btnCompleteList') { + _clickFilterBtn(target); + } +} + +/** + * keypress, click ์ด๋ฒคํŠธ ๋ฐ”์ธ๋”ฉ + */ +function _bindEvent() { + Eventutil.addHandler(todoListWrapElement, 'keypress', _keypressEvent); + Eventutil.addHandler(todoListWrapElement, 'click', _clickEvent); +} + +/** + * ๊ฐ์ข… ํ•จ์ˆ˜ ์ดˆ๊ธฐํ™” + * @param {object} todoData todoList์— ๋Œ€ํ•œ ๋ฐ์ดํ„ฐ ์ •๋ณด + */ +function init(todoData) { + _initElement(); + _loadTodoData(todoData); + _renderView(); + _bindEvent(); +} + +/** + * @returns {Object} ํ˜„์žฌ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” todo ๊ฐ์ฒด ๋ฐ˜ํ™˜ + */ +function getTodoObjects() { + return todoObjects; +} + +module.exports = { + init: init, + // test์—์„œ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ํ•จ์ˆ˜๋ฅผ ๋…ธ์ถœ์‹œ์ผœ๋‘์—ˆ์Šต๋‹ˆ๋‹ค. + _clickFilterBtn: _clickFilterBtn, + _removeComplteList: _removeComplteList, + _toggleTodo: _toggleTodo, + _addTodoObject: _addTodoObject, + getTodoObjects: getTodoObjects +};
JavaScript
์Œ. ์ด๋ฒˆ ๊ณผ์ œ์—์„œ ์ฝ”๋“œ ์Šค๋‹ˆํŽซ์„ ์‚ฌ์šฉํ•œ ๊ฒƒ์œผ๋กœ ๋ณด์•„.. `snippet.forEach` API๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ฒ ๊ตฐ์š”~
@@ -0,0 +1,271 @@ +var Domclass = require('../util/Domclass'); +var Eventutil = require('../util/Eventutil'); +var snippet = require('tui-code-snippet'); + +var KEY_ENTER = 13; + +var todoObjects = []; // ๋ชจ๋“  todoData +var completeTodoObjects = []; // isChecked๊ฐ€ true์ธ ๊ฐ’ +var incompleteTodoObjects = []; // isChecked๊ฐ€ false์ธ ๊ฐ’ + +var todoListWrapElement; +var completeListElement; +var incompleteListElement; +var leftItemNumElement; +var completeItemsNumElement; + +var _initElement = function() { + todoListWrapElement = document.getElementById('todoListWrap'); + completeListElement = document.getElementById('completeList'); + incompleteListElement = document.getElementById('incompleteList'); + leftItemNumElement = document.getElementById('leftItemsNum'); + completeItemsNumElement = document.getElementById('completeItemsNum'); +}; + +var _forEach = function(arr, func) { + var i = 0; + var arrLength = arr.length; + for (; i < arrLength; i += 1) { + func.call(this, i, arr[i]); + } +}; + +/** + * ๊ฐ์ฒด๊ฐ€ ๋“ฑ๋ก๋œ ์‹œ๊ฐ„์„ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ ํ•˜๋Š” ํ•จ์ˆ˜ + * @param {array} arr ๋Š” ์ •๋ ฌํ•˜๊ณ  ์‹ถ์€ ๋ฐฐ์—ด + */ +function _sortRegDateOfTodoObject(arr) { + arr.sort(function(a, b) { + if (a.regDate < b.regDate) { + return 1; + } else if (a.regDate > b.regDate) { + return -1; + } + + return 0; + }); +} + +/** + * ์ธ์ž๋กœ ๋ฐ›์€ ๋ฐ์ดํ„ฐ ์ •๋ณด๋ฅผ todoObjects์— ๋‹ด๊ณ , isChecked = false์ธ๊ฒƒ์€ incompleteTodoObjects, + * isChecked = true์ธ๊ฒƒ์€ completeTodoObjects ๋ฐฐ์—ด์— ๋‹ด์€ ๋’ค ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ + * @param {array} todoData ๋Š” todo ๋ฐ์ดํ„ฐ ์ •๋ณด + */ +function _loadTodoData(todoData) { + todoObjects = todoData; + + completeTodoObjects = snippet.filter(todoObjects, function(value) { + return value.isChecked; + }); + + _sortRegDateOfTodoObject(completeTodoObjects); + + incompleteTodoObjects = snippet.filter(todoObjects, function(value) { + return !value.isChecked; + }); + + _sortRegDateOfTodoObject(incompleteTodoObjects); +} + +/** + * completeList๋ฅผ ๋ Œ๋”๋งํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ + */ +function _renderCompleteTodoList() { + var htmlLi = ''; + var todoId, todoTitle; + + _forEach(completeTodoObjects, function(index, value) { + todoId = value.id; + todoTitle = value.title; + htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk" checked/><p class="todoTitle">' + todoTitle + '</p></li>'; + }); + + completeListElement.innerHTML = htmlLi; +} + +/** + * incompleteList๋ฅผ ๋ Œ๋”๋งํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ + */ +function _renderIncompleteTodoList() { + var htmlLi = ''; + var todoId, todoTitle; + + _forEach(incompleteTodoObjects, function(index, value) { + todoId = value.id; + todoTitle = value.title; + htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk"/><p class="todoTitle">' + todoTitle + '</p></li>'; + }); + + incompleteListElement.innerHTML = htmlLi; +} + +/** + * _renderCompleteTodoList, _renderIncompleteTodoList ํ•จ์ˆ˜ ํ˜ธ์ถœ + */ +function _renderTodoList() { + _renderCompleteTodoList(); + _renderIncompleteTodoList(); +} + +/** + * infoList๋ฅผ ๋ Œ๋”๋ง ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ + */ +function _renderInfoList() { + leftItemNumElement.innerText = incompleteTodoObjects.length; + completeItemsNumElement.innerText = completeTodoObjects.length; +} + +/** + * _renderTodoList, _renderInfoList ํ•จ์ˆ˜ ํ˜ธ์ถœ + */ +function _renderView() { + _renderTodoList(); + _renderInfoList(); +} + +/** + * ํ…์ŠคํŠธ๋ฐ•์Šค์—์„œ ๋ฐ›์€ ๊ฐ’์„ ๊ฐ€์ง€๊ณ  ์ƒˆ๋กœ์šด todo ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค๊ณ  todoObjects์— ๋„ฃ์–ด ๋‘”๋’ค ์žฌ ๋ Œ๋”๋ง + * @param {object} target ๋Š” inputTxt ๊ฐ์ฒด + */ +function _addTodoObject(target) { + var objTodo = { + id: 'todo' + snippet.stamp({}), + title: target.value, + isChecked: false, + regDate: snippet.timestamp() + }; + todoObjects.push(objTodo); + target.value = ''; + + _loadTodoData(todoObjects); + _renderView(); +} + +/** + * keypress์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ์ด๋ฒคํŠธ ๊ฐ์ฒด๋ฅผ ๋ฐ›์•„์„œ targetId๊ฐ’์— ๋”ฐ๋ผ ํ•ด๋‹น ํ•จ์ˆ˜ ํ˜ธ์ถœ + * @param {object} event ๋Š” ์ด๋ฒคํŠธ ๊ฐ์ฒด + */ +function _keypressEvent(event) { + var target, key, targetId; + target = event.target || event.srcElement; + key = event.keyCode; + targetId = target.getAttribute('id'); + + if (!target.value) { + return; + } + + if (key === KEY_ENTER && targetId === 'todoInputTxt') { + _addTodoObject(target); + } +} + +/** + * ํ•ด๋‹น todo์˜ checkbox๋ฅผ ํด๋ฆญํ•˜๋ฉด isChecked์˜ ๊ฐ’์„ ๋ณ€๊ฒฝํ•œ ๋’ค ์žฌ ๋ Œ๋”๋ง + * @param {string} idTodo ๋Š” todo์˜ id๊ฐ’ + * @param {object} isCheckedTarget ๋Š” ํด๋ฆญ๋œ checkbox์˜ isChecked๊ฐ’ + */ +function _toggleTodo(idTodo, isCheckedTarget) { + _forEach(todoObjects, function(index, value) { + if (value.id === idTodo) { + value.isChecked = (!!isCheckedTarget); + } + }); + _loadTodoData(todoObjects); + _renderView(); +} + +/** + * ์™„๋ฃŒ๋œ ๋ชจ๋“  todoํ•ญ๋ชฉ๋“ค์„ ์ œ๊ฑฐ ํ•˜๋Š” ํ•จ์ˆ˜ + */ +function _removeComplteList() { + if (completeTodoObjects.length === 0) { + return; + } + completeTodoObjects = []; + todoObjects = snippet.filter(todoObjects, function(value) { + return (value.isChecked === false); + }); + _renderView(); +} + +/** + * completeList, incompleteList ์—˜๋ฆฌ๋ฉ˜ํŠธ์˜ hide ํด๋ž˜์Šค ์ œ๊ฑฐ + */ +function _removeClassHideOfList() { + Domclass.removeClass(completeListElement, 'hide'); + Domclass.removeClass(incompleteListElement, 'hide'); +} + +/** + * filter Button ์ค‘์— ํ•˜๋‚˜๋ฅผ ํด๋ฆญํ•˜๋ฉด ํ•ด๋‹น ๋™์ž‘์— ๋งž๊ฒŒ hideํด๋ž˜์Šค๋ฅผ ์ถ”๊ฐ€ํ•˜์—ฌ List์˜ ์†์„ฑ๊ฐ’ display:none์œผ๋กœ ๋ณ€๊ฒฝ + * @param {object} target ๋Š” filter Button ๊ฐ์ฒด ์ค‘ ํ•˜๋‚˜ + */ +function _clickFilterBtn(target) { + if (target.id === 'btnAllList') { + _removeClassHideOfList(); + } else if (target.id === 'btnActiveList') { + _removeClassHideOfList(); + Domclass.addClass(completeListElement, 'hide'); + } else if (target.id === 'btnCompleteList') { + _removeClassHideOfList(); + Domclass.addClass(incompleteListElement, 'hide'); + } +} + +/** + * click ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ์ด๋ฒคํŠธ ๊ฐ์ฒด๋ฅผ ๋ฐ›์•„์„œ target ๊ฐ’์— ๋”ฐ๋ผ ํ•ด๋‹น ํ•จ์ˆ˜ ํ˜ธ์ถœ + * @param {object} event ๋Š” ์ด๋ฒคํŠธ ๊ฐ์ฒด + */ +function _clickEvent(event) { + var target; + var todoElement; + var todoId; + target = event.target || event.srcElement; + todoElement = target.parentElement; + + if (target.type === 'checkbox' && Domclass.hasClass(todoElement, 'todo')) { + todoId = todoElement.getAttribute('data-id'); + _toggleTodo(todoId, target.checked); + } else if (target.id === 'btnDelCompleteList') { + _removeComplteList(); + } else if (target.id === 'btnAllList' || target.id === 'btnActiveList' || target.id === 'btnCompleteList') { + _clickFilterBtn(target); + } +} + +/** + * keypress, click ์ด๋ฒคํŠธ ๋ฐ”์ธ๋”ฉ + */ +function _bindEvent() { + Eventutil.addHandler(todoListWrapElement, 'keypress', _keypressEvent); + Eventutil.addHandler(todoListWrapElement, 'click', _clickEvent); +} + +/** + * ๊ฐ์ข… ํ•จ์ˆ˜ ์ดˆ๊ธฐํ™” + * @param {object} todoData todoList์— ๋Œ€ํ•œ ๋ฐ์ดํ„ฐ ์ •๋ณด + */ +function init(todoData) { + _initElement(); + _loadTodoData(todoData); + _renderView(); + _bindEvent(); +} + +/** + * @returns {Object} ํ˜„์žฌ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” todo ๊ฐ์ฒด ๋ฐ˜ํ™˜ + */ +function getTodoObjects() { + return todoObjects; +} + +module.exports = { + init: init, + // test์—์„œ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ํ•จ์ˆ˜๋ฅผ ๋…ธ์ถœ์‹œ์ผœ๋‘์—ˆ์Šต๋‹ˆ๋‹ค. + _clickFilterBtn: _clickFilterBtn, + _removeComplteList: _removeComplteList, + _toggleTodo: _toggleTodo, + _addTodoObject: _addTodoObject, + getTodoObjects: getTodoObjects +};
JavaScript
์œ ํ‹ธ๋ฆฌํ‹ฐ์™€ ๊ด€๋ จ๋œ ํ•จ์ˆ˜๋Š” ํŒŒ์ผ๋กœ ๋ถ„๋ฆฌํ•˜์—ฌ ๊ด€๋ฆฌํ•˜๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,271 @@ +var Domclass = require('../util/Domclass'); +var Eventutil = require('../util/Eventutil'); +var snippet = require('tui-code-snippet'); + +var KEY_ENTER = 13; + +var todoObjects = []; // ๋ชจ๋“  todoData +var completeTodoObjects = []; // isChecked๊ฐ€ true์ธ ๊ฐ’ +var incompleteTodoObjects = []; // isChecked๊ฐ€ false์ธ ๊ฐ’ + +var todoListWrapElement; +var completeListElement; +var incompleteListElement; +var leftItemNumElement; +var completeItemsNumElement; + +var _initElement = function() { + todoListWrapElement = document.getElementById('todoListWrap'); + completeListElement = document.getElementById('completeList'); + incompleteListElement = document.getElementById('incompleteList'); + leftItemNumElement = document.getElementById('leftItemsNum'); + completeItemsNumElement = document.getElementById('completeItemsNum'); +}; + +var _forEach = function(arr, func) { + var i = 0; + var arrLength = arr.length; + for (; i < arrLength; i += 1) { + func.call(this, i, arr[i]); + } +}; + +/** + * ๊ฐ์ฒด๊ฐ€ ๋“ฑ๋ก๋œ ์‹œ๊ฐ„์„ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ ํ•˜๋Š” ํ•จ์ˆ˜ + * @param {array} arr ๋Š” ์ •๋ ฌํ•˜๊ณ  ์‹ถ์€ ๋ฐฐ์—ด + */ +function _sortRegDateOfTodoObject(arr) { + arr.sort(function(a, b) { + if (a.regDate < b.regDate) { + return 1; + } else if (a.regDate > b.regDate) { + return -1; + } + + return 0; + }); +} + +/** + * ์ธ์ž๋กœ ๋ฐ›์€ ๋ฐ์ดํ„ฐ ์ •๋ณด๋ฅผ todoObjects์— ๋‹ด๊ณ , isChecked = false์ธ๊ฒƒ์€ incompleteTodoObjects, + * isChecked = true์ธ๊ฒƒ์€ completeTodoObjects ๋ฐฐ์—ด์— ๋‹ด์€ ๋’ค ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ + * @param {array} todoData ๋Š” todo ๋ฐ์ดํ„ฐ ์ •๋ณด + */ +function _loadTodoData(todoData) { + todoObjects = todoData; + + completeTodoObjects = snippet.filter(todoObjects, function(value) { + return value.isChecked; + }); + + _sortRegDateOfTodoObject(completeTodoObjects); + + incompleteTodoObjects = snippet.filter(todoObjects, function(value) { + return !value.isChecked; + }); + + _sortRegDateOfTodoObject(incompleteTodoObjects); +} + +/** + * completeList๋ฅผ ๋ Œ๋”๋งํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ + */ +function _renderCompleteTodoList() { + var htmlLi = ''; + var todoId, todoTitle; + + _forEach(completeTodoObjects, function(index, value) { + todoId = value.id; + todoTitle = value.title; + htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk" checked/><p class="todoTitle">' + todoTitle + '</p></li>'; + }); + + completeListElement.innerHTML = htmlLi; +} + +/** + * incompleteList๋ฅผ ๋ Œ๋”๋งํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ + */ +function _renderIncompleteTodoList() { + var htmlLi = ''; + var todoId, todoTitle; + + _forEach(incompleteTodoObjects, function(index, value) { + todoId = value.id; + todoTitle = value.title; + htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk"/><p class="todoTitle">' + todoTitle + '</p></li>'; + }); + + incompleteListElement.innerHTML = htmlLi; +} + +/** + * _renderCompleteTodoList, _renderIncompleteTodoList ํ•จ์ˆ˜ ํ˜ธ์ถœ + */ +function _renderTodoList() { + _renderCompleteTodoList(); + _renderIncompleteTodoList(); +} + +/** + * infoList๋ฅผ ๋ Œ๋”๋ง ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ + */ +function _renderInfoList() { + leftItemNumElement.innerText = incompleteTodoObjects.length; + completeItemsNumElement.innerText = completeTodoObjects.length; +} + +/** + * _renderTodoList, _renderInfoList ํ•จ์ˆ˜ ํ˜ธ์ถœ + */ +function _renderView() { + _renderTodoList(); + _renderInfoList(); +} + +/** + * ํ…์ŠคํŠธ๋ฐ•์Šค์—์„œ ๋ฐ›์€ ๊ฐ’์„ ๊ฐ€์ง€๊ณ  ์ƒˆ๋กœ์šด todo ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค๊ณ  todoObjects์— ๋„ฃ์–ด ๋‘”๋’ค ์žฌ ๋ Œ๋”๋ง + * @param {object} target ๋Š” inputTxt ๊ฐ์ฒด + */ +function _addTodoObject(target) { + var objTodo = { + id: 'todo' + snippet.stamp({}), + title: target.value, + isChecked: false, + regDate: snippet.timestamp() + }; + todoObjects.push(objTodo); + target.value = ''; + + _loadTodoData(todoObjects); + _renderView(); +} + +/** + * keypress์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ์ด๋ฒคํŠธ ๊ฐ์ฒด๋ฅผ ๋ฐ›์•„์„œ targetId๊ฐ’์— ๋”ฐ๋ผ ํ•ด๋‹น ํ•จ์ˆ˜ ํ˜ธ์ถœ + * @param {object} event ๋Š” ์ด๋ฒคํŠธ ๊ฐ์ฒด + */ +function _keypressEvent(event) { + var target, key, targetId; + target = event.target || event.srcElement; + key = event.keyCode; + targetId = target.getAttribute('id'); + + if (!target.value) { + return; + } + + if (key === KEY_ENTER && targetId === 'todoInputTxt') { + _addTodoObject(target); + } +} + +/** + * ํ•ด๋‹น todo์˜ checkbox๋ฅผ ํด๋ฆญํ•˜๋ฉด isChecked์˜ ๊ฐ’์„ ๋ณ€๊ฒฝํ•œ ๋’ค ์žฌ ๋ Œ๋”๋ง + * @param {string} idTodo ๋Š” todo์˜ id๊ฐ’ + * @param {object} isCheckedTarget ๋Š” ํด๋ฆญ๋œ checkbox์˜ isChecked๊ฐ’ + */ +function _toggleTodo(idTodo, isCheckedTarget) { + _forEach(todoObjects, function(index, value) { + if (value.id === idTodo) { + value.isChecked = (!!isCheckedTarget); + } + }); + _loadTodoData(todoObjects); + _renderView(); +} + +/** + * ์™„๋ฃŒ๋œ ๋ชจ๋“  todoํ•ญ๋ชฉ๋“ค์„ ์ œ๊ฑฐ ํ•˜๋Š” ํ•จ์ˆ˜ + */ +function _removeComplteList() { + if (completeTodoObjects.length === 0) { + return; + } + completeTodoObjects = []; + todoObjects = snippet.filter(todoObjects, function(value) { + return (value.isChecked === false); + }); + _renderView(); +} + +/** + * completeList, incompleteList ์—˜๋ฆฌ๋ฉ˜ํŠธ์˜ hide ํด๋ž˜์Šค ์ œ๊ฑฐ + */ +function _removeClassHideOfList() { + Domclass.removeClass(completeListElement, 'hide'); + Domclass.removeClass(incompleteListElement, 'hide'); +} + +/** + * filter Button ์ค‘์— ํ•˜๋‚˜๋ฅผ ํด๋ฆญํ•˜๋ฉด ํ•ด๋‹น ๋™์ž‘์— ๋งž๊ฒŒ hideํด๋ž˜์Šค๋ฅผ ์ถ”๊ฐ€ํ•˜์—ฌ List์˜ ์†์„ฑ๊ฐ’ display:none์œผ๋กœ ๋ณ€๊ฒฝ + * @param {object} target ๋Š” filter Button ๊ฐ์ฒด ์ค‘ ํ•˜๋‚˜ + */ +function _clickFilterBtn(target) { + if (target.id === 'btnAllList') { + _removeClassHideOfList(); + } else if (target.id === 'btnActiveList') { + _removeClassHideOfList(); + Domclass.addClass(completeListElement, 'hide'); + } else if (target.id === 'btnCompleteList') { + _removeClassHideOfList(); + Domclass.addClass(incompleteListElement, 'hide'); + } +} + +/** + * click ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ์ด๋ฒคํŠธ ๊ฐ์ฒด๋ฅผ ๋ฐ›์•„์„œ target ๊ฐ’์— ๋”ฐ๋ผ ํ•ด๋‹น ํ•จ์ˆ˜ ํ˜ธ์ถœ + * @param {object} event ๋Š” ์ด๋ฒคํŠธ ๊ฐ์ฒด + */ +function _clickEvent(event) { + var target; + var todoElement; + var todoId; + target = event.target || event.srcElement; + todoElement = target.parentElement; + + if (target.type === 'checkbox' && Domclass.hasClass(todoElement, 'todo')) { + todoId = todoElement.getAttribute('data-id'); + _toggleTodo(todoId, target.checked); + } else if (target.id === 'btnDelCompleteList') { + _removeComplteList(); + } else if (target.id === 'btnAllList' || target.id === 'btnActiveList' || target.id === 'btnCompleteList') { + _clickFilterBtn(target); + } +} + +/** + * keypress, click ์ด๋ฒคํŠธ ๋ฐ”์ธ๋”ฉ + */ +function _bindEvent() { + Eventutil.addHandler(todoListWrapElement, 'keypress', _keypressEvent); + Eventutil.addHandler(todoListWrapElement, 'click', _clickEvent); +} + +/** + * ๊ฐ์ข… ํ•จ์ˆ˜ ์ดˆ๊ธฐํ™” + * @param {object} todoData todoList์— ๋Œ€ํ•œ ๋ฐ์ดํ„ฐ ์ •๋ณด + */ +function init(todoData) { + _initElement(); + _loadTodoData(todoData); + _renderView(); + _bindEvent(); +} + +/** + * @returns {Object} ํ˜„์žฌ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” todo ๊ฐ์ฒด ๋ฐ˜ํ™˜ + */ +function getTodoObjects() { + return todoObjects; +} + +module.exports = { + init: init, + // test์—์„œ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ํ•จ์ˆ˜๋ฅผ ๋…ธ์ถœ์‹œ์ผœ๋‘์—ˆ์Šต๋‹ˆ๋‹ค. + _clickFilterBtn: _clickFilterBtn, + _removeComplteList: _removeComplteList, + _toggleTodo: _toggleTodo, + _addTodoObject: _addTodoObject, + getTodoObjects: getTodoObjects +};
JavaScript
์ƒ์„ฑ์ž์˜ ๊ฒฝ์šฐ๋Š” ๋Œ€๋ฌธ์ž๋กœ ์‹œ์ž‘, ๊ทธ ์™ธ ์œ ํ‹ธ๋ฆฌํ‹ฐ ๋“ฑ ํŒฉํ† ๋ฆฌ ํ•จ์ˆ˜๋Š” ์†Œ๋ฌธ์ž๋กœ ์‹œ์ž‘ํ•˜๋ผ๊ณ  ํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,271 @@ +var Domclass = require('../util/Domclass'); +var Eventutil = require('../util/Eventutil'); +var snippet = require('tui-code-snippet'); + +var KEY_ENTER = 13; + +var todoObjects = []; // ๋ชจ๋“  todoData +var completeTodoObjects = []; // isChecked๊ฐ€ true์ธ ๊ฐ’ +var incompleteTodoObjects = []; // isChecked๊ฐ€ false์ธ ๊ฐ’ + +var todoListWrapElement; +var completeListElement; +var incompleteListElement; +var leftItemNumElement; +var completeItemsNumElement; + +var _initElement = function() { + todoListWrapElement = document.getElementById('todoListWrap'); + completeListElement = document.getElementById('completeList'); + incompleteListElement = document.getElementById('incompleteList'); + leftItemNumElement = document.getElementById('leftItemsNum'); + completeItemsNumElement = document.getElementById('completeItemsNum'); +}; + +var _forEach = function(arr, func) { + var i = 0; + var arrLength = arr.length; + for (; i < arrLength; i += 1) { + func.call(this, i, arr[i]); + } +}; + +/** + * ๊ฐ์ฒด๊ฐ€ ๋“ฑ๋ก๋œ ์‹œ๊ฐ„์„ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ ํ•˜๋Š” ํ•จ์ˆ˜ + * @param {array} arr ๋Š” ์ •๋ ฌํ•˜๊ณ  ์‹ถ์€ ๋ฐฐ์—ด + */ +function _sortRegDateOfTodoObject(arr) { + arr.sort(function(a, b) { + if (a.regDate < b.regDate) { + return 1; + } else if (a.regDate > b.regDate) { + return -1; + } + + return 0; + }); +} + +/** + * ์ธ์ž๋กœ ๋ฐ›์€ ๋ฐ์ดํ„ฐ ์ •๋ณด๋ฅผ todoObjects์— ๋‹ด๊ณ , isChecked = false์ธ๊ฒƒ์€ incompleteTodoObjects, + * isChecked = true์ธ๊ฒƒ์€ completeTodoObjects ๋ฐฐ์—ด์— ๋‹ด์€ ๋’ค ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ + * @param {array} todoData ๋Š” todo ๋ฐ์ดํ„ฐ ์ •๋ณด + */ +function _loadTodoData(todoData) { + todoObjects = todoData; + + completeTodoObjects = snippet.filter(todoObjects, function(value) { + return value.isChecked; + }); + + _sortRegDateOfTodoObject(completeTodoObjects); + + incompleteTodoObjects = snippet.filter(todoObjects, function(value) { + return !value.isChecked; + }); + + _sortRegDateOfTodoObject(incompleteTodoObjects); +} + +/** + * completeList๋ฅผ ๋ Œ๋”๋งํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ + */ +function _renderCompleteTodoList() { + var htmlLi = ''; + var todoId, todoTitle; + + _forEach(completeTodoObjects, function(index, value) { + todoId = value.id; + todoTitle = value.title; + htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk" checked/><p class="todoTitle">' + todoTitle + '</p></li>'; + }); + + completeListElement.innerHTML = htmlLi; +} + +/** + * incompleteList๋ฅผ ๋ Œ๋”๋งํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ + */ +function _renderIncompleteTodoList() { + var htmlLi = ''; + var todoId, todoTitle; + + _forEach(incompleteTodoObjects, function(index, value) { + todoId = value.id; + todoTitle = value.title; + htmlLi += '<li class="todo" data-id="' + todoId + '"><input type="checkbox" class="todoChk"/><p class="todoTitle">' + todoTitle + '</p></li>'; + }); + + incompleteListElement.innerHTML = htmlLi; +} + +/** + * _renderCompleteTodoList, _renderIncompleteTodoList ํ•จ์ˆ˜ ํ˜ธ์ถœ + */ +function _renderTodoList() { + _renderCompleteTodoList(); + _renderIncompleteTodoList(); +} + +/** + * infoList๋ฅผ ๋ Œ๋”๋ง ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ + */ +function _renderInfoList() { + leftItemNumElement.innerText = incompleteTodoObjects.length; + completeItemsNumElement.innerText = completeTodoObjects.length; +} + +/** + * _renderTodoList, _renderInfoList ํ•จ์ˆ˜ ํ˜ธ์ถœ + */ +function _renderView() { + _renderTodoList(); + _renderInfoList(); +} + +/** + * ํ…์ŠคํŠธ๋ฐ•์Šค์—์„œ ๋ฐ›์€ ๊ฐ’์„ ๊ฐ€์ง€๊ณ  ์ƒˆ๋กœ์šด todo ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค๊ณ  todoObjects์— ๋„ฃ์–ด ๋‘”๋’ค ์žฌ ๋ Œ๋”๋ง + * @param {object} target ๋Š” inputTxt ๊ฐ์ฒด + */ +function _addTodoObject(target) { + var objTodo = { + id: 'todo' + snippet.stamp({}), + title: target.value, + isChecked: false, + regDate: snippet.timestamp() + }; + todoObjects.push(objTodo); + target.value = ''; + + _loadTodoData(todoObjects); + _renderView(); +} + +/** + * keypress์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ์ด๋ฒคํŠธ ๊ฐ์ฒด๋ฅผ ๋ฐ›์•„์„œ targetId๊ฐ’์— ๋”ฐ๋ผ ํ•ด๋‹น ํ•จ์ˆ˜ ํ˜ธ์ถœ + * @param {object} event ๋Š” ์ด๋ฒคํŠธ ๊ฐ์ฒด + */ +function _keypressEvent(event) { + var target, key, targetId; + target = event.target || event.srcElement; + key = event.keyCode; + targetId = target.getAttribute('id'); + + if (!target.value) { + return; + } + + if (key === KEY_ENTER && targetId === 'todoInputTxt') { + _addTodoObject(target); + } +} + +/** + * ํ•ด๋‹น todo์˜ checkbox๋ฅผ ํด๋ฆญํ•˜๋ฉด isChecked์˜ ๊ฐ’์„ ๋ณ€๊ฒฝํ•œ ๋’ค ์žฌ ๋ Œ๋”๋ง + * @param {string} idTodo ๋Š” todo์˜ id๊ฐ’ + * @param {object} isCheckedTarget ๋Š” ํด๋ฆญ๋œ checkbox์˜ isChecked๊ฐ’ + */ +function _toggleTodo(idTodo, isCheckedTarget) { + _forEach(todoObjects, function(index, value) { + if (value.id === idTodo) { + value.isChecked = (!!isCheckedTarget); + } + }); + _loadTodoData(todoObjects); + _renderView(); +} + +/** + * ์™„๋ฃŒ๋œ ๋ชจ๋“  todoํ•ญ๋ชฉ๋“ค์„ ์ œ๊ฑฐ ํ•˜๋Š” ํ•จ์ˆ˜ + */ +function _removeComplteList() { + if (completeTodoObjects.length === 0) { + return; + } + completeTodoObjects = []; + todoObjects = snippet.filter(todoObjects, function(value) { + return (value.isChecked === false); + }); + _renderView(); +} + +/** + * completeList, incompleteList ์—˜๋ฆฌ๋ฉ˜ํŠธ์˜ hide ํด๋ž˜์Šค ์ œ๊ฑฐ + */ +function _removeClassHideOfList() { + Domclass.removeClass(completeListElement, 'hide'); + Domclass.removeClass(incompleteListElement, 'hide'); +} + +/** + * filter Button ์ค‘์— ํ•˜๋‚˜๋ฅผ ํด๋ฆญํ•˜๋ฉด ํ•ด๋‹น ๋™์ž‘์— ๋งž๊ฒŒ hideํด๋ž˜์Šค๋ฅผ ์ถ”๊ฐ€ํ•˜์—ฌ List์˜ ์†์„ฑ๊ฐ’ display:none์œผ๋กœ ๋ณ€๊ฒฝ + * @param {object} target ๋Š” filter Button ๊ฐ์ฒด ์ค‘ ํ•˜๋‚˜ + */ +function _clickFilterBtn(target) { + if (target.id === 'btnAllList') { + _removeClassHideOfList(); + } else if (target.id === 'btnActiveList') { + _removeClassHideOfList(); + Domclass.addClass(completeListElement, 'hide'); + } else if (target.id === 'btnCompleteList') { + _removeClassHideOfList(); + Domclass.addClass(incompleteListElement, 'hide'); + } +} + +/** + * click ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ์ด๋ฒคํŠธ ๊ฐ์ฒด๋ฅผ ๋ฐ›์•„์„œ target ๊ฐ’์— ๋”ฐ๋ผ ํ•ด๋‹น ํ•จ์ˆ˜ ํ˜ธ์ถœ + * @param {object} event ๋Š” ์ด๋ฒคํŠธ ๊ฐ์ฒด + */ +function _clickEvent(event) { + var target; + var todoElement; + var todoId; + target = event.target || event.srcElement; + todoElement = target.parentElement; + + if (target.type === 'checkbox' && Domclass.hasClass(todoElement, 'todo')) { + todoId = todoElement.getAttribute('data-id'); + _toggleTodo(todoId, target.checked); + } else if (target.id === 'btnDelCompleteList') { + _removeComplteList(); + } else if (target.id === 'btnAllList' || target.id === 'btnActiveList' || target.id === 'btnCompleteList') { + _clickFilterBtn(target); + } +} + +/** + * keypress, click ์ด๋ฒคํŠธ ๋ฐ”์ธ๋”ฉ + */ +function _bindEvent() { + Eventutil.addHandler(todoListWrapElement, 'keypress', _keypressEvent); + Eventutil.addHandler(todoListWrapElement, 'click', _clickEvent); +} + +/** + * ๊ฐ์ข… ํ•จ์ˆ˜ ์ดˆ๊ธฐํ™” + * @param {object} todoData todoList์— ๋Œ€ํ•œ ๋ฐ์ดํ„ฐ ์ •๋ณด + */ +function init(todoData) { + _initElement(); + _loadTodoData(todoData); + _renderView(); + _bindEvent(); +} + +/** + * @returns {Object} ํ˜„์žฌ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” todo ๊ฐ์ฒด ๋ฐ˜ํ™˜ + */ +function getTodoObjects() { + return todoObjects; +} + +module.exports = { + init: init, + // test์—์„œ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ํ•จ์ˆ˜๋ฅผ ๋…ธ์ถœ์‹œ์ผœ๋‘์—ˆ์Šต๋‹ˆ๋‹ค. + _clickFilterBtn: _clickFilterBtn, + _removeComplteList: _removeComplteList, + _toggleTodo: _toggleTodo, + _addTodoObject: _addTodoObject, + getTodoObjects: getTodoObjects +};
JavaScript
๊ตณ์ด ์–ด์‚ฌ์ธํ•  ํ•„์š”๊ฐ€ ์—†์–ด๋ณด์ž…๋‹ˆ๋‹ค.