code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,75 @@ +package christmas.global.view.io; + +import christmas.domain.badge.Enum.EventBadge; +import christmas.domain.sale.BenefitDetails; +import christmas.domain.sale.enums.Giveaway; +import christmas.global.view.output.OutputView; + +import static christmas.global.view.message.PriceMessage.getDiscountPriceMessage; +import static christmas.global.view.message.PriceMessage.getPriceMessage; +import static christmas.global.view.message.TitleMessage.*; + +public class BenefitDetailsView implements InteractionRepeatable{ + private final BenefitDetails benefitDetails; + + public BenefitDetailsView(BenefitDetails benefitDetails) { + this.benefitDetails = benefitDetails; + } + + public void showEventPreview() { + calculateTotalPrice(); + showResult(); + } + + public void calculateTotalPrice() { + benefitDetails.calculateTotalPrice(); + benefitDetails.calculateTotalSaleAmount(); + + int totalPrice = benefitDetails.getTotalPrice(); + + OutputView.println(BEFORE_SALE_PRICE.get()); + OutputView.println(getPriceMessage(totalPrice)); + } + + public void showResult() { + showFreeGift(); + showTotalBenefitDetails(); + int totalBenefitAmount = showTotalBenefitAmount(); + showFinalTotalPrice(); + showBadge(totalBenefitAmount); + } + + private void showFreeGift() { + Giveaway giveaway = benefitDetails.calculateFreeGiftPrice(); + + OutputView.println(GIVEAWAY_MENU.get()); + OutputView.println(giveaway.getProduct()); + OutputView.printNextLine(); + } + + private void showTotalBenefitDetails() { + OutputView.println(BENEFIT.get()); + String benefitDetails = this.benefitDetails.getTotalBenefitMessage(); + OutputView.println(benefitDetails); + } + + private int showTotalBenefitAmount() { + int totalBenefitAmount = benefitDetails.calculateTotalBenefitAmount(); + OutputView.println(TOTAL_BENEFIT_AMOUNT.get()); + OutputView.println(getDiscountPriceMessage(totalBenefitAmount)); + + return totalBenefitAmount; + } + + private void showFinalTotalPrice() { + OutputView.println(AFTER_SALE_PRICE.get()); + int totalFinalPrice = this.benefitDetails.calculateFinalPrice(); + OutputView.println(getPriceMessage(totalFinalPrice)); + } + + private void showBadge(int totalBenefitAmount) { + String badge = EventBadge.getBadge(totalBenefitAmount); + OutputView.println(EVENT_BADGE.get()); + OutputView.println(badge); + } +}
Java
P5: benefitDetails๋ฅผ ํ•„๋“œ๋กœ ๋‘๊ณ , ์ด๋ ‡๊ฒŒ showResult() ์•ˆ์—์„œ ์‚ฌ์šฉํ•˜๋‹ˆ ์ฝ”๋“œ๊ฐ€ ๊น”๋”ํ•ด์ง€๊ณ  ์ข‹๋„ค์š” ๐Ÿ˜‡ ๐Ÿ‘
@@ -0,0 +1,39 @@ +package christmas.domain.badge.Enum; + +import static christmas.global.exception.CommonExceptionMessage.UNEXPECTED_EXCEPTION; + +public enum EventBadge { + NONE("์—†์Œ", 0) + ,STAR("๋ณ„", 5_000) + ,TREE("ํŠธ๋ฆฌ", 10_000) + ,SANTA("์‚ฐํƒ€", 20_000) + ; + + private final String badge; + private final int benefitPrice; + + EventBadge(String badge, int benefitPrice) { + this.badge = badge; + this.benefitPrice = benefitPrice; + } + + public static String getBadge(int benefitPrice) { + validateBenefitPrice(benefitPrice); + if(benefitPrice >= SANTA.benefitPrice) { + return SANTA.badge; + } + if(benefitPrice >= TREE.benefitPrice) { + return TREE.badge; + } + if(benefitPrice >= STAR.benefitPrice) { + return STAR.badge; + } + return NONE.badge; + } + + public static void validateBenefitPrice(int benefitPrice) { + if (benefitPrice < 0) { + throw new IllegalStateException(UNEXPECTED_EXCEPTION.get()); + } + } +}
Java
P4: ์ •์ ๋ฉ”์„œ๋“œ์—์„œ ์œ ํšจ์„ฑ ๊ฒ€์ฆ์„ ํ•œ๋ฒˆ ๋” ๊ฑฐ์น˜๋Š” ๊ฒƒ ์ •๋ง ๊ผผ๊ผผํ•˜๊ณ  ์ข‹๋„ค์š” ๐Ÿ‘ P4: 22~31๋ผ์ธ์˜ ๋‹ค์ค‘ if ๋ฌธ์€ enum์˜ ๊ธฐ๋Šฅ์„ ํ™œ์šฉํ•ด์„œ ํ•ด๊ฒฐ ํ•  ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ์š”? ๐Ÿ˜‡
@@ -0,0 +1,38 @@ +package christmas.global.config; + +import christmas.domain.EventController; +import christmas.domain.calendar.EventCalendar; +import christmas.domain.order.Orders; +import christmas.domain.sale.BenefitDetails; +import christmas.domain.sale.ChristmasDDaySale; +import christmas.domain.sale.SaleDetails; +import christmas.global.view.io.BenefitDetailsView; +import christmas.global.view.io.EventCalendarView; +import christmas.global.view.io.OrdersView; + +public class Dependency { + public static EventController eventController() { + return new EventController(eventCalendarView(), ordersView(), benefitDetailsView()); + } + + public static BenefitDetailsView benefitDetailsView() { + return new BenefitDetailsView(benefitDetails()); + } + + public static OrdersView ordersView() { + return new OrdersView(Orders.getInstance()); + } + + public static EventCalendarView eventCalendarView() { + return new EventCalendarView(EventCalendar.getInstance()); + } + + public static BenefitDetails benefitDetails() { + return new BenefitDetails(saleDetails()); + } + + public static SaleDetails saleDetails() { + return new SaleDetails(Orders.getInstance(), EventCalendar.getInstance(), ChristmasDDaySale.getInstance()); + } + +}
Java
P3: ์—ฐ๊ด€๊ด€๊ณ„ ์ •๋ณด๊ฐ€ ์™„์ „ํžˆ ๋ถ„๋ฆฌ๋˜์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™์•„์š”..! ์ฝ”๋“œ ์•ˆ์—์„œ๋งŒ ๋ถ„๋ฆฌํ• ๊ฑฐ๋ผ๋ฉด Application์ชฝ์˜ ๋ฉ”์„œ๋“œ๋กœ๋งŒ ๋ถ„๋ฆฌํ•ด๋„ ์ถฉ๋ถ„ํ• ๊ฑฐ ๊ฐ™๊ณ , ์ง€๊ธˆ์ฒ˜๋Ÿผ Dependency ํŒŒ์ผ์„ ์•„์˜ˆ ๋”ฐ๋กœ ๋บ„ ๊ฑฐ๋ผ๋ฉด, Orders๊ฐ€ ์ž์‹ ์˜ ์ธ์Šคํ„ด์Šค๊ฐ€ ๋ฌด์—‡์ธ์ง€ ์ „ํ˜€ ์•Œ์ง€ ๋ชปํ•˜๊ฒŒ ๋ฐ–์—์„œ ์ฃผ์ž…ํ•˜๋„๋ก ๋งŒ๋“ค์–ด์ฃผ๋Š”๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -1,7 +1,16 @@ package christmas; +import christmas.config.Dependency; + public class Application { public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + + try { + EventPlanner eventPlanner = Dependency.eventPlannner(); + eventPlanner.run(); + } catch (Exception e) { + System.out.println(); + throw e; + } } }
Java
P5: ์š”๊ตฌ์‚ฌํ•ญ์ด ๋‹ค ๊ตฌํ˜„๋˜์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ˜ญ ...
@@ -1,7 +1,16 @@ package christmas; +import christmas.config.Dependency; + public class Application { public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + + try { + EventPlanner eventPlanner = Dependency.eventPlannner(); + eventPlanner.run(); + } catch (Exception e) { + System.out.println(); + throw e; + } } }
Java
P5: ์ง„์งœ ์‚ฌ์†Œํ•œ ๊ฑด๋ฐ์š”. ์ด ๊ณต๋ฐฑ ์ถœ๋ ฅ์˜ ์˜๋ฏธ...๋Š” ๋ญ˜๊นŒ์š”?... ๐Ÿค” ...
@@ -0,0 +1,42 @@ +package christmas.domain; + +import christmas.constant.Calendar; +import christmas.constant.FoodName; +import christmas.validator.DateValidator; +import christmas.view.InputView; +import christmas.view.OutputView; + +public class Date { + int date; + + public void saveDate(){ + String input = InputView.inputDate(); + this.date = DateValidator.validateDate(input); + } + + + + public int calculateChristmasEvent() { + if(25 < date){ + return 0; + }else if(1 <= date && date <= 25){ + return 900 + date * 100 ; + //christmas ์ด๋ฒคํŠธ ํ• ์ธ ๊ฐ’ ๊ตฌํ•˜๋Š” ์‹ + } + return 0; + } + + public boolean checkStarEvent(){ + return Calendar.isStarByDate(this.date); + } + + public String checkSaleSort(){ + return Calendar.getSaleSortByDate(this.date); + } + + public void printStartResultLine(){ + OutputView.printResultStart(date); + } + + +}
Java
P2: `Date`๊ฐ€ ๋‹จ์ˆœ ๊ฐ’ํƒ€์ž…์€ ์•„๋‹ˆ๊ณ  ์ž๊ธฐ๋งŒ์˜ ์—ญํ• ์„ ๊ฐ€์ง„ ๊ฐ์ฒด๋กœ ๋ณด์—ฌ์ง€๋Š”๋ฐ์š”! ๊ทธ๋ ‡๋‹ค๋ฉด ์—ฌ๊ธฐ์„œ ๋ทฐ๋ฅผ ํ˜ธ์ถœํ•˜๊ฒŒ ๋˜๋ฉด, ๋ทฐ์™€ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์ด ๊ฐ•ํ•˜๊ฒŒ ์—ฐ๊ด€๋œ๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์–ด์š”. ์šฐํ…Œ์ฝ” ์š”๊ตฌ์‚ฌํ•ญ์— ์žˆ์—ˆ๋“ฏ์ด ๋ทฐ๋ฅผ ๋ถ„๋ฆฌํ•ด์ฃผ๋ ค๋ฉด, ์Šนํ›ˆ๋‹˜๊ป˜์„œ ๊ตฌํ˜„ํ•ด๋†“์œผ์‹  ์ปจํŠธ๋กค๋Ÿฌ๋‚˜, `EventPlanner`๋‚˜, ์•„๋‹ˆ๋ฉด ์„œ๋น„์Šค ๋ณด๋‹ค ์•ž์„œ์žˆ๋Š” ์–ด๋–ค ์ œ3์˜ ๊ฐ์ฒด์—์„œ, ๋ทฐ๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ณ  ๊ฐ’๋งŒ `Date`์ชฝ์œผ๋กœ ๋„˜๊ฒจ์ฃผ๋ฉด ๋  ๊ฒƒ ๊ฐ™์•„์š”..!
@@ -0,0 +1,33 @@ +package christmas.validator; + +import jdk.jshell.spi.ExecutionControl.RunException; + +public class DateValidator { + + public static int validateDate(String input) { + validateInputType(input); + + try { + if (input == null) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + int date = Integer.parseInt(input); + + if (date < 1 || date > 31) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + return date; + + } catch (NumberFormatException e) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ ํ˜•์‹์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } + + private static void validateInputType(String input) { + if (!(input instanceof String)) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } +} \ No newline at end of file
Java
P5: ํƒ€์ž…๊นŒ์ง€ ๊ฒ€์ฆํ•˜์‹œ๋ ค๊ณ  ๋…ธ๋ ฅํ•˜์‹  ๋ถ€๋ถ„์ด ๋ณด์—ฌ์„œ ์ •๋ง ์ข‹์€ ๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ˜‡ ๐Ÿ‘ ๊ทธ๋Ÿฐ๋ฐ ์›์ฒœ input์˜ ํƒ€์ž…์€ ๋ฌด์กฐ๊ฑด String์ด ๋  ์ˆ˜ ๋ฐ–์— ์—†์–ด์š”! ์ผ๋ถ€๋Ÿฌ ์•ž์—์„œ ํƒ€์ž…์„ ๋ณ€ํ™˜ํ•˜์ง€ ์•Š๋Š” ์ด์ƒ์€์š”(๋งŒ์•ฝ ๊ทธ๋ ‡๋‹ค๋ฉด, ์˜๋„์— ๋”ฐ๋ผ ๋ฐ”๋€ ๊ฒƒ์ด๋‹ˆ ์˜ˆ์™ธ์ ์ธ ์ƒํ™ฉ์ด ์•„๋‹ˆ๊ฒ ์ฃ ..!) ๊ทธ๋ž˜์„œ ์ด ๋ถ€๋ถ„์˜ ์ฝ”๋“œ๋Š” ์ œ๊ฑฐํ•ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค..!
@@ -0,0 +1,60 @@ +package christmas.constant; + +import java.util.Arrays; +import java.util.stream.Stream; + +public enum FoodName { + MUSHROOM_SOUP("์–‘์†ก์ด์ˆ˜ํ”„",6000,"APPITIZER"), + TAPAS("ํƒ€ํŒŒ์Šค", 6000,"APPITIZER"), + CEASAR_SALAD("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 6000,"APPITIZER"), + T_BONE_STAKE("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 6000,"MAIN"), + BARBECUE_RIBS("๋ฐ”๋ฒ ํ๋ฆฝ", 6000,"MAIN"), + SEAFOOD_PASTA("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 6000,"MAIN"), + CHRISTMAS_PASTA("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 6000,"MAIN"), + CHOCOLATE_CAKE("์ดˆ์ฝ”์ผ€์ดํฌ", 6000,"DESSERT"), + ICE_CREAM("์•„์ด์Šคํฌ๋ฆผ", 6000,"DESSERT"), + ZERO_COLA("์ œ๋กœ์ฝœ๋ผ", 6000,"DRINK"), + RED_WINE("๋ ˆ๋“œ์™€์ธ", 6000,"DRINK"), + CHAMPAGNE("์ƒดํŽ˜์ธ", 6000,"DRINK"); + + private final String name; + private final int price; + private final String sort; + + FoodName(String name, int price, String sort) {this.name = name; this.price = price; + this.sort = sort; + } + + private String getName() { + return name; + } + + private int getPrice() { + return price; + } + + private String getSort() {return sort;} + + public static String[] getAllFoodNames() { + return Arrays.stream(FoodName.values()) + .map(FoodName::getName) + .toArray(String[]::new); + } + + public static int getPriceByName(String name) { + return Stream.of(values()) + .filter(foodName -> foodName.getName().equals(name)) + .findFirst() + .map(FoodName::getPrice) + .orElse(0); + } + + public static boolean isNameAndSortMatch(String name, String sort) { + return Arrays.stream(values()) + .filter(foodName -> foodName.getSort().equals(sort)) + .anyMatch(foodName -> foodName.getName().equals(name)); + } + + + +}
Java
P4: enum์œผ๋กœ ๋ฉ”๋‰ด๋ฅผ ๊ตฌํ˜„ํ•˜์‹  ๋ถ€๋ถ„ ์ •๋ง ์ข‹์€ ๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ‘ ๊ทธ๋Ÿฐ๋ฐ ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ์ •์ƒ๋™์ž‘ ํ•˜์ง€ ์•Š๋Š” ์ด์œ  ์ค‘ ์ผ๋ถ€๊ฐ€ ์—ฌ๊ธฐ ์ˆจ์–ด์žˆ์—ˆ๊ตฐ์š” ๊ฐ€๊ฒฉ์ด ์ „๋ถ€ 6000์›... ๐Ÿ˜ญ ํ•œ๊ฐ€์ง€๋งŒ ์˜๊ฒฌ์„ ๋‚ด๋ณด์ž๋ฉด, ์Œ์‹์˜ ์นดํ…Œ๊ณ ๋ฆฌ(`sort`)๋„ enum์œผ๋กœ ๊ด€๋ฆฌํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,27 @@ +package christmas; + +import christmas.controller.EventController; + +public class EventPlanner { + private final EventController eventController; + + public EventPlanner(EventController eventController) { + this.eventController = eventController; + } + + public void run(){ + startRequestInfo(); + startOrderProgram(); + runOrderProgram(); + } + + private void startRequestInfo(){ + eventController.requestInfo(); + } + + private void startOrderProgram(){eventController.startPrintingResult();} + + private void runOrderProgram(){ + eventController.runDecemberEvent(); + } +}
Java
P5: ์งˆ๋ฌธ๋“œ๋ฆฝ๋‹ˆ๋‹ค..! EventPlanner์™€ EventController์˜ ์—ญํ• ์ด ๋‹ค์†Œ ์ค‘์ฒฉ๋˜๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ์š”(๋‹ค๋ฅด๊ฒŒ ๋งํ•˜๋ฉด, ํ•œ ๊ฐ์ฒด๋กœ ํ•  ์ˆ˜ ์žˆ๋Š” ์—ญํ• ์„ ๋‘˜๋กœ ์ชผ๊ฐ  ๊ฒƒ ๊ฐ™์€๋ฐ์š”) ๋‚˜๋ˆ„์‹  ์ด์œ ๊ฐ€ ์–ด๋–ค๊ฑด์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,68 @@ +package christmas.domain; + +import christmas.view.OutputView; +import java.util.Map; + +public class Price { + + int totalPriceBeforeDiscount; + EventPrices eventPrices; + + + public Price(int totalPrice) { + this.totalPriceBeforeDiscount = totalPrice; + this.eventPrices = new EventPrices(); + + } + + public void printTotalPrice(){ + + System.out.println(totalPriceBeforeDiscount + "์›"); + } + + public void printChampagneEvent(){ + if(120000 <= totalPriceBeforeDiscount){ + OutputView.printChampagne(); + eventPrices.addChampagneBenefit(25000); + } else if (totalPriceBeforeDiscount < 120000) { + OutputView.printNone(); + } + } + + public void saleChristmasEvent(int christmasEventDiscount){ + if (christmasEventDiscount != 0){ + eventPrices.addChristBenefit(christmasEventDiscount); + } + } + + public void saleStarEvent(boolean starBoolean){ + if(starBoolean){ + eventPrices.addStarBenefit(1000); + } + } + + public void saleWeekdayAndWeekendEvent(Map<String, Integer> weeklyEvent){ + if(weeklyEvent.values() != null){ + eventPrices.addWeekdayAndWeekendBenefit(weeklyEvent); + } + } + + public void printBenefitListAndPrice(){ + eventPrices.calculateBenefitList(); + } + + public void printBenefitTotalPrice(){ + eventPrices.printTotalprice(); + } + + public void printDiscountedTotalPrice(){ + eventPrices.printDiscountedPrice(totalPriceBeforeDiscount); + } + + public void checkDecemberBadge(){ + eventPrices.printDecemberBadge(); + } + + + +}
Java
P5: ์ด ๋ถ€๋ถ„๋„, ๋ทฐ๋Š” ๋ถ„๋ฆฌํ•˜๋Š”๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ๋‹ค๋ฅธ ๋ถ€๋ถ„์—๋„ ์ฝ”๋ฉ˜ํŠธ ๋‚จ๊ฒผ์ง€๋งŒ, ์ด ๊ณณ์€ ์•„์˜ˆ System.out์„ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์–ด์„œ ํ•œ ๋ฒˆ ๋” ๋‚จ๊ฒจ๋ณด์•„์š”..! ๐Ÿ˜‡ ๊ทธ๋ฆฌ๊ณ  ์ด ๋ถ€๋ถ„ ๊ธˆ์•ก ํฌ๋งทํŒ…๋„ ์ถ”๊ฐ€๋˜๋ฉด ๋” ์ข‹๊ฒ ๋„ค์šฉ..! (๋‹ค๋ฅธ ๋ถ€๋ถ„์€ ๋˜์–ด์žˆ๋Š”๋ฐ ์—ฌ๊ธฐ๋งŒ ๋น ์ ธ์žˆ์–ด์„œ์š”)
@@ -0,0 +1,68 @@ +package christmas.domain; + +import christmas.view.OutputView; +import java.util.Map; + +public class Price { + + int totalPriceBeforeDiscount; + EventPrices eventPrices; + + + public Price(int totalPrice) { + this.totalPriceBeforeDiscount = totalPrice; + this.eventPrices = new EventPrices(); + + } + + public void printTotalPrice(){ + + System.out.println(totalPriceBeforeDiscount + "์›"); + } + + public void printChampagneEvent(){ + if(120000 <= totalPriceBeforeDiscount){ + OutputView.printChampagne(); + eventPrices.addChampagneBenefit(25000); + } else if (totalPriceBeforeDiscount < 120000) { + OutputView.printNone(); + } + } + + public void saleChristmasEvent(int christmasEventDiscount){ + if (christmasEventDiscount != 0){ + eventPrices.addChristBenefit(christmasEventDiscount); + } + } + + public void saleStarEvent(boolean starBoolean){ + if(starBoolean){ + eventPrices.addStarBenefit(1000); + } + } + + public void saleWeekdayAndWeekendEvent(Map<String, Integer> weeklyEvent){ + if(weeklyEvent.values() != null){ + eventPrices.addWeekdayAndWeekendBenefit(weeklyEvent); + } + } + + public void printBenefitListAndPrice(){ + eventPrices.calculateBenefitList(); + } + + public void printBenefitTotalPrice(){ + eventPrices.printTotalprice(); + } + + public void printDiscountedTotalPrice(){ + eventPrices.printDiscountedPrice(totalPriceBeforeDiscount); + } + + public void checkDecemberBadge(){ + eventPrices.printDecemberBadge(); + } + + + +}
Java
P3: ์—ฌ๊ธฐ์˜ if-else๋กœ์ง์ด... ๋ญ”๊ฐ€ ์ด์ƒํ•œ๊ฒŒ ์ˆจ์–ด์žˆ๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ์š” ๐Ÿ•ต๏ธโ€โ™‚๏ธ (์‚ฌ์šฉํ•˜์ง€ ์•Š๊ธฐ๋กœ ํ–ˆ๋˜ if-else๊ฐ€ ์žˆ๋Š” ๊ฒƒ์„ ์ œ์™ธํ•˜๊ณ ์„œ๋ผ๋„...)
@@ -0,0 +1,90 @@ +package christmas.domain; + +import christmas.constant.BenefitList; +import christmas.view.OutputView; +import java.text.DecimalFormat; +import java.util.HashMap; +import java.util.Map; + +public class EventPrices { + Map<String,Integer> benefitList; + int totalPrice; + + public EventPrices() { + + this.benefitList = new HashMap<>(); + this.totalPrice = 0; + } + + public void addChampagneBenefit(int discountPrice){ + benefitList.put("GIFT",discountPrice); + } +// + public void addChristBenefit(int discountPrice){ + benefitList.put("CHRISTMAS", discountPrice); + } + + public void addStarBenefit(int discountPrice){ + benefitList.put("STAR",discountPrice); + } + + public void addWeekdayAndWeekendBenefit(Map<String, Integer> weeklyEvent){ + if(weeklyEvent.containsKey("DESSERT") && weeklyEvent.get("DESSERT") != 0){ + benefitList.put("DESSERT",weeklyEvent.get("DESSERT")); + } else if (weeklyEvent.containsKey("MAIN") && weeklyEvent.get("MAIN") != 0) { + benefitList.put("MAIN",weeklyEvent.get("MAIN")); + } + } + + public void calculateBenefitList(){ + if(benefitList.isEmpty()){ + OutputView.printNone(); + return; + + } else if (benefitList != null) { + + for (Map.Entry<String, Integer> entry : benefitList.entrySet()){ + addTotalPrice(entry.getValue()); + printBenefits(entry.getKey(),entry.getValue()); + } + } + } + + private void printBenefits(String benefitName, int discountPrice){ + DecimalFormat format = new DecimalFormat("-###,###์›"); + String benefitPrint = BenefitList.getEventNameByValue(benefitName); + benefitPrint += format.format(discountPrice); + System.out.println(benefitPrint); + } + + private void addTotalPrice(int price){ + this.totalPrice += price; + } + + public void printTotalprice(){ + DecimalFormat format = new DecimalFormat("-###,###์›"); + System.out.println(format.format(totalPrice)); + } + + public void printDiscountedPrice(int totalPriceBeforeDiscount){ + DecimalFormat format = new DecimalFormat("-###,###์›"); + int discountedPrice = totalPriceBeforeDiscount - totalPrice; + System.out.println(format.format(discountedPrice)); + } + + public void printDecemberBadge(){ + if(totalPrice < 5000){ + OutputView.printNone(); + return; + }else if(totalPrice < 10000) { + OutputView.printStarBadge(); + return; + }else if(totalPrice < 20000){ + OutputView.printTreeBadge(); + return; + }else if(20000 <= totalPrice){ + OutputView.printSantaBadge(); + return; + } + } +}
Java
P2: if-else ๋ฌธ์—๋Š” return์ด ํ•„์š”ํ•˜์ง€ ์•Š์•„์š”..! ๋”๊ตฐ๋‹ค๋‚˜ ๋ฐ˜ํ™˜ํƒ€์ž…์ด void์ธ ์ƒํ™ฉ์—์„œ๋Š”์š”! ๋ฌผ๋ก  ๋ช…์‹œ์ ์ธ return์„ ์จ์„œ ํ—ท๊ฐˆ๋ฆด๋งŒํ•œ ์ฝ”๋“œ๋‚˜ ์‚ฌ์ด๋“œ์ดํŽ™ํŠธ๋ฅผ ๋ง‰๋Š” ๊ฒฝ์šฐ๋„ ์žˆ๋Š”๋ฐ, ์ง€๊ธˆ์€ ํ•ด๋‹น๋˜์ง€ ์•Š๋Š” ์ฝ”๋“œ ๊ฐ™์•„์„œ ๋ง์”€๋“œ๋ ค๋ณด์•˜์Šต๋‹ˆ๋‹ค ๐Ÿ˜‡
@@ -0,0 +1,25 @@ +package christmas.controller; + +import christmas.service.EventService; + +public class EventController { + private final EventService eventService; + + public EventController(EventService eventRepository) { + this.eventService = eventRepository; + } + + public void requestInfo() { + eventService.saveInfo(); + } + + public void startPrintingResult(){ + eventService.printFristLineAndMenus(); + } + + public void runDecemberEvent() { + eventService.startCalculateAndPrint(); + } + + +}
Java
EventPlanner EventController EventService๋กœ ๊ตฌ์กฐ๋ฅผ ๊ฐ€์ ธ๊ฐ€์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค. ์–ด๋–ค ์ด์ ์ด ์žˆ๋‹ค ์ƒ๊ฐ์ด ๋“ค์–ด์„œ ์ด๋ ‡๊ฒŒ ๊ตฌ์กฐ๋ฅผ ๊ฐ€์ ธ๊ฐ€์‹ ๊ฑธ๊นŒ์š”? ๋˜ํ•œ ๋ทฐ๋กœ์ง์ด ๋„๋ฉ”์ธ๊ณผ ๊ฐ•ํ•˜๊ฒŒ ๊ฒฐํ•ฉ๋œ๋‹ค ์ƒ๊ฐํ•˜๋Š”๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹ค๊นŒ์š”?
@@ -0,0 +1,33 @@ +public class Calculator { + public double calculate(String expression) { + String[] tokens = expression.split(" "); + double currentResult = Double.parseDouble(tokens[0]); + + for (int i = 1; i < tokens.length; i += 2) { + String operator = tokens[i]; + double number = Double.parseDouble(tokens[i + 1]); + + switch (operator) { + case "+": + currentResult += number; + break; + case "-": + currentResult -= number; + break; + case "*": + currentResult *= number; + break; + case "/": + if (number == 0) { + throw new ArithmeticException("0์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + currentResult /= number; + break; + default: + System.out.println("์ง€์›ํ•˜์ง€ ์•Š๋Š” ์—ฐ์‚ฐ์ž์ž…๋‹ˆ๋‹ค: " + operator); + return 0; + } + } + return currentResult; + } +}
Java
Enum์„ ์‚ฌ์šฉํ•ด์„œ switch๋ฌธ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๋ฐฉํ–ฅ์œผ๋กœ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด๋ด…์‹œ๋‹ค
@@ -0,0 +1,33 @@ +public class Calculator { + public double calculate(String expression) { + String[] tokens = expression.split(" "); + double currentResult = Double.parseDouble(tokens[0]); + + for (int i = 1; i < tokens.length; i += 2) { + String operator = tokens[i]; + double number = Double.parseDouble(tokens[i + 1]); + + switch (operator) { + case "+": + currentResult += number; + break; + case "-": + currentResult -= number; + break; + case "*": + currentResult *= number; + break; + case "/": + if (number == 0) { + throw new ArithmeticException("0์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + currentResult /= number; + break; + default: + System.out.println("์ง€์›ํ•˜์ง€ ์•Š๋Š” ์—ฐ์‚ฐ์ž์ž…๋‹ˆ๋‹ค: " + operator); + return 0; + } + } + return currentResult; + } +}
Java
Calculator ํด๋ž˜์Šค์˜ ์ฑ…์ž„์€ ๋ฌด์—‡์ธ๊ฐ€์š”. ํ•œ ํด๋ž˜์Šค์— ์—ฌ๋Ÿฌ ๊ฐœ์˜ ์ฑ…์ž„์ด ์žˆ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. SCP์— ๋Œ€ํ•ด์„œ ๊ณต๋ถ€ํ•ด๋ณด๊ณ  ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”
@@ -0,0 +1,34 @@ +public class Validator { + public boolean isValid(String expression) { + String[] tokens = expression.split(" "); + + if (tokens.length % 2 == 0) { + return false; + } + + if (!isNumeric(tokens[0])) { + return false; + } + + for (int i = 1; i < tokens.length; i += 2) { + if (!isOperator(tokens[i]) || !isNumeric(tokens[i + 1])) { + return false; + } + } + + return true; + } + + private boolean isNumeric(String str) { + try { + Double.parseDouble(str); + return true; + } catch (NumberFormatException e) { + return false; + } + } + + private boolean isOperator(String str) { + return str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/"); + } +}
Java
ํ•œ ๋ฉ”์†Œ๋“œ๊ฐ€ ๋งŽ์€ ์—ญํ• ์„ ํ•ด์ฃผ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ฐ๊ฐ์˜ if๋ฌธ์„ ์—ฌ๋Ÿฌ ๋ฉ”์†Œ๋“œ๋กœ ๋‚˜๋ˆ„์–ด๋ณด์„ธ์š”.
@@ -1,5 +1,22 @@ +import java.util.Scanner; + public class Main { public static void main(String[] args) { - System.out.println("1 + 1 = 2"); + Scanner scanner = new Scanner(System.in); + System.out.println("๊ณ„์‚ฐํ•  ์ˆ˜์‹์„ ์ž…๋ ฅํ•˜์„ธ์š” (์˜ˆ: 30 + 20 / 2 * 4):"); + String expression = scanner.nextLine(); + + Validator validator = new Validator(); + if (validator.isValid(expression)) { + Calculator calculator = new Calculator(); + try { + double result = calculator.calculate(expression); + System.out.println("๊ฒฐ๊ณผ: " + result); + } catch (ArithmeticException e) { + System.out.println("๊ณ„์‚ฐ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: " + e.getMessage()); + } + } else { + System.out.println("์ž˜๋ชป๋œ ์ˆ˜์‹ ํ˜•์‹์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."); + } } }
Java
Main ํด๋ž˜์Šค์— ๋„ˆ๋ฌด ๋งŽ์€ ์ฑ…์ž„์ด ์žˆ์Šต๋‹ˆ๋‹ค. SCP์— ๋Œ€ํ•ด์„œ ๊ณต๋ถ€ ํ•ด๋ณด๊ณ  ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š” * ์ฝ˜์†”์— ํ”„๋ฆฐํŠธํ•ด์ฃผ๋Š” ๊ฒƒ๋„ ํ•˜๋‚˜์˜ ์ฑ…์ž„์œผ๋กœ ๋ด…๋‹ˆ๋‹ค
@@ -18,6 +18,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; @Slf4j @RestController @@ -26,12 +27,24 @@ public class OrderController { private final OrderService orderService; private final BasketService basketService; + + /* + (C) OrderController๊ฐ€ ๊ด€์‹ฌ์žˆ๋Š” ๋ถ€๋ถ„์€ ์ฃผ๋ฌธ ์ •๋ณด๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ  ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด์ง€ ํŠน์ • ์„œ๋น„์Šค(SQS, SSE)๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ถ€๋ถ„์€ ์•„๋‹Œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + MessageService / OrderService / StoreService ๋“ฑ์œผ๋กœ Service๋ฅผ ๋ถ„๋ฆฌํ•˜์—ฌ์„œ ๊ทธ ์•ˆ์—์„œ SsqService, SseService ๋ฐ converter๋ฅผ ์กฐํ•ฉํ•˜์—ฌ + ํ•„์š”ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด ๊ด€์‹ฌ์‚ฌ์˜ ๋ถ„๋ฆฌ๊ฐ€ ๋” ์ ์ ˆํ•˜๊ฒŒ ์ด๋ฃจ์–ด ์งˆ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + */ private final SqsService sqsService; private final SseService sseService; private final SendingMessageConverter sendingMessageConverter; - private final ReceivingMessageConverter receivingMessageConverter; + private final ReceivingMessageConverter receivingMessageConverter; // (C) ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ์˜์กด์„ฑ์€ ์ง€์›Œ์ฃผ๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. - public OrderController(OrderService orderService, BasketService basketService, SqsService sqsService, SseService sseService, SendingMessageConverter sendingMessageConverter, ReceivingMessageConverter receivingMessageConverter) { + /* (C) ์—ฌ๊ธฐ๋„ lombok์˜ RequiredArgsConstructor๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค. */ + public OrderController(OrderService orderService, + BasketService basketService, + SqsService sqsService, + SseService sseService, + SendingMessageConverter sendingMessageConverter, + ReceivingMessageConverter receivingMessageConverter) { this.orderService = orderService; this.basketService = basketService; this.sqsService = sqsService; @@ -43,21 +56,32 @@ public OrderController(OrderService orderService, BasketService basketService, S @GetMapping @ResponseStatus(HttpStatus.OK) public List<OrderPartResponseDto> showOrderList(@RequestAttribute("cognitoUsername") String customerId) { - List<Order> orderList = orderService.getOrderList(customerId).orElseGet(ArrayList::new); - List<OrderPartResponseDto> orderPartInfoList = new ArrayList<>(); - orderList.forEach(order -> { - orderPartInfoList.add(new OrderPartResponseDto(order)); - }); - return orderPartInfoList; + + /* + (C) StreamAPI๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์•„๋ž˜์ฒ˜๋Ÿผ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์–ด ๋ณด์ž…๋‹ˆ๋‹ค. + + getOrderList๋Š” Optional์ด ์•„๋‹Œ List<Order> ํƒ€์ž…์„ ๋ฐ˜ํ™˜ํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค + */ + return orderService.getOrderList(customerId) + .orElseGet(ArrayList::new) + .stream() + .map(OrderPartResponseDto::new) + .collect(Collectors.toList()); } @PostMapping @ResponseStatus(HttpStatus.CREATED) + /* + (C) controller์—์„œ ํ•˜๋Š” ์ผ์ด ๊ฝค ๋งŽ์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์„œ๋น„์Šค๋กœ ๋กœ์ง์„ ๋นผ๋ณด์‹œ๋Š” ๊ฒƒ์„ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค. + */ public void createOrder(@RequestAttribute("cognitoUsername") String customerId, HttpServletResponse response) throws IOException { + /* + 1. (Q) ์—ฌ๊ธฐ๋Š” customerId๊ฐ€ ์™œ basketId๋กœ ์‚ฌ์šฉ๋˜๊ณ  ์žˆ๋‚˜์š”? + 2. (C) createOrder๋กœ order๋ฅผ ์ƒ์„ฑํ–ˆ๋‹ค๋ฉด, orderId๋ณด๋‹ค๋Š” order ์ž์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด ์‚ฌ์šฉ์„ฑ ์ธก๋ฉด์—์„œ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + */ String orderId = orderService.createOrder(customerId, customerId); Optional<Order> orderOptional = orderService.getOrder(orderId); - if(orderOptional.isEmpty()){ + if (orderOptional.isEmpty()) { throw new RuntimeException("Can't create order"); } Order order = orderOptional.get(); @@ -69,9 +93,10 @@ public void createOrder(@RequestAttribute("cognitoUsername") String customerId, @GetMapping("/{orderId}") @ResponseStatus(HttpStatus.OK) public SseEmitter showOrderInfo(@RequestAttribute("cognitoUsername") String customerId, - @PathVariable String orderId){ + @PathVariable String orderId) { SseEmitter sseEmitter = sseService.connect(customerId); sseService.showOrder(customerId, orderId); return sseEmitter; } + } \ No newline at end of file
Java
(C) ๋ถˆํ•„์š”ํ•œ IOException์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -11,6 +11,7 @@ import java.io.IOException; +// (Q) Custom deserializer๋ฅผ ๊ตฌํ˜„ํ•œ ์ด์œ ๊ฐ€ ๋ฌด์—‡์ธ๊ฐ€์š”? Jackson ๋“ฑ์˜ serializer๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์–ด๋ ค์šด ๋ถ€๋ถ„์ด ์žˆ๋‚˜์š”? public class StoreDeserializer extends StdDeserializer { public StoreDeserializer(){
Java
> ๋„ค ์‚ฌ์‹ค Menu ๋ฐ์ดํ„ฐ์™€๋Š” ๋‹ค๋ฅด๊ฒŒ Store ๋ฐ์ดํ„ฐ๋Š” Point๋ผ๋Š” spring์—์„œ ์ œ๊ณตํ•˜๋Š” ๊ฐ์ฒด๋ฅผ property๋กœ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋Ÿฐ๋ฐ objectMapper์˜ readValue()๋กœ๋Š” Store.class๋ฅผ ๋ฐ”๋กœ ์—ญ์ง๋ ฌํ™”์‹œํ‚ค์ง€ ๋ชปํ•˜๋Š”๋ฐ ๊ทธ๊ฑด ๋ฐ”๋กœ Point๋ฅผ objectMapper๊ฐ€ ํ•ด์„ํ•˜์ง€ ๋ชปํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋”๋ผ๊ณ ์š”. JSONObject.get()์„ ์‚ฌ์šฉํ•ด์„œ ํ•˜๋‚˜ํ•˜๋‚˜ ๊นŒ์„œ ์—ญ์ง๋ ฌํ™”ํ•ด๋„ ๋์ง€๋งŒ, convertStoreData() ๋ฉ”์„œ๋“œ๊ฐ€ ๊ธธ์–ด์ง€๋Š” ๊ฒŒ ๋ณด๊ธฐ ์‹ซ์–ด์„œ Custom deserializer๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ•œ๋ฐฉ์— ์ฒ˜๋ฆฌ๋˜๊ฒŒ๋” ๋ณด์ด๋„๋ก(?) ํ–ˆ์Šต๋‹ˆ๋‹ค. ์‚ฌ์‹ค Deserializer๋ฅผ ์–ด๋–ป๊ฒŒ ํ•ด์•ผํ•˜๋Š”์ง€ ์•„์ง ๊ฐ์„ ์ž˜ ๋ชป ์žก์•˜์Šต๋‹ˆ๋‹ค. ์–ด๋–ป๊ฒŒ ํ•˜๋Š”๊ฒŒ ์ข‹์„๊นŒ์š” point ํƒ€์ž…์˜ ๊ฐ์ฒด ๋˜ํ•œ spring boot default serializer(jackson)๋กœ๋„ ์ถฉ๋ถ„ํžˆ serialize/deserialize ๊ฐ€๋Šฅํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋ณ€์ˆ˜๋ช…์„ ๋™์ผํ•˜๊ฒŒ ์ฒ˜๋ฆฌํ•ด๋ณด์…จ์„๊นŒ์š”?
@@ -5,27 +5,32 @@ import org.springframework.web.bind.annotation.*; import java.util.ArrayList; +import java.util.Arrays; import java.util.EnumSet; import java.util.List; +import java.util.stream.Collectors; @RestController -@RequestMapping("/customer") +@RequestMapping("/customer") // (R) HomeController์—์„œ url prefix๊ฐ€ customer๋กœ ๋˜์–ด์žˆ๋Š” ๊ฒƒ์ด ์กฐ๊ธˆ ์ด์ƒํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. public class HomeController { @GetMapping @ResponseStatus(HttpStatus.OK) - public String home(){ + public String home() { return "Customer server is activated successfully"; - } + } // (Q) ์–ด๋–ค ์šฉ๋„์˜ ๋ฉ”์„œ๋“œ์ธ๊ฐ€์š”? @GetMapping("/main") @ResponseStatus(HttpStatus.OK) - public List<String> foods() { - List<String> foodKindList = new ArrayList<>(); - for (FoodKind foodKind : EnumSet.allOf(FoodKind.class)){ - foodKindList.add(foodKind.toString()); - } - return foodKindList; + public List<FoodKind> foods() { + /* + (C) ์—ฌ๊ธฐ๋„ Stream API๋ฅผ ์ž˜ ์‚ฌ์šฉํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + ๋‹จ์ˆœํžˆ ์Œ์‹ ์ข…๋ฅ˜๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด๋ผ๋ฉด, ์•„๋ž˜์™€ ๊ฐ™์ด ์‚ฌ์šฉํ•ด๋ณด์„ธ์š”. + (enum type์„ return ํ•˜๋”๋ผ๋„ string์œผ๋กœ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์œผ๋กœ ์•Œ๊ณ  ์žˆ๋Š”๋ฐ, ํ•œ๋ฒˆ ํ™•์ธํ•ด์ฃผ์„ธ์š”~!) + + + API์—์„œ set์„ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋ฌด์ž‘์œ„ ์ˆœ์„œ๋กœ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ์ˆœ์„œ๊ฐ€ ๋ฌด๊ด€ํ•œ ๊ฒฝ์šฐ์—๋งŒ set์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + */ + return Arrays.stream(FoodKind.values()).toList(); } }
Java
>HomeController์˜ home()์€ ํŠน๋ณ„ํ•œ ์ด์œ  ์—†์ด ์ดˆ๊ธฐ์— ์„œ๋ฒ„๊ฐ€ ์ž˜ ๋Œ์•„๊ฐ€๋Š”์ง€ ํ…Œ์ŠคํŠธ ํ•˜๋ ค๊ณ  ๋„ฃ์–ด๋†“์€ ํ…Œ์ŠคํŠธ ์šฉ๋„์˜ ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค. Customer, Restaurant, Rider ์„ธ๊ฐ€์ง€ ์„œ๋ฒ„๋ฅผ ๋„์šฐ๋‹ค๋ณด๋‹ˆ White Error ํŽ˜์ด์ง€๋กœ๋Š” ํ—ท๊ฐˆ๋ ค์„œ ์ž„์‹œ๋กœ ์ž‘์„ฑํ–ˆ๋˜ ์ฝ”๋“œ์ธ๋ฐ, ํ…Œ์ŠคํŠธ ์šฉ๋„๊ธฐ ๋•Œ๋ฌธ์— ์—†์–ด๋„ ๋ฌธ์ œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ํ•ด๋‹น ์ฝ”๋“œ์—๋Š” ์ฃผ์„์„ ๋„ฃ์–ด์•ผ ํ–ˆ์—ˆ๋„ค์š”. > customer, restaurant, rider ์„œ๋ฒ„ ๋ชจ๋‘ home controller๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š”๋ฐ, ์‚ฌ์‹ค ์ฃผ ์šฉ๋„๋Š” ์„œ๋ฒ„๊ฐ€ ๋Œ์•„๊ฐ€๋Š”์ง€ ๋ณด๋ ค๊ณ  ๋งŒ๋“ค์–ด๋‘” ๊ฒƒ์ž…๋‹ˆ๋‹ค. url prefix๋„ ์ปจํŠธ๋กค๋Ÿฌ๋ช…๊ณผ ์ผ์น˜ํ•˜์ง€ ์•Š๋Š” ๊ฒŒ ๊ทธ๊ฒƒ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. ํ…Œ์ŠคํŠธ ์šฉ๋„๋กœ ์ž‘์„ฑํ–ˆ๊ธฐ ๋•Œ๋ฌธ์ด์—์š”. ํ•ด๋‹น ํด๋ž˜์Šค๋Š” ์ง€์šฐ๋Š” ๊ฒŒ ๋‚˜์„๊นŒ์š”? ํ”ํžˆ ์ด๋Ÿฌํ•œ ์šฉ๋„์˜ controller๋ฅผ health check controller๋ผ๊ณ  ์ง€์นญํ•ฉ๋‹ˆ๋‹ค. ์šด์˜ ํ™˜๊ฒฝ์—์„œ ์„œ๋ฒ„๊ฐ€ ๋™์ž‘ํ•˜๋Š”์ง€ ์ฃผ๊ธฐ์ ์œผ๋กœ ํ•ด์ฃผ์–ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ๋„ค์ด๋ฐ๋งŒ health-check ์˜๋ฏธ๊ฐ€ ๋“œ๋Ÿฌ๋‚˜๊ฒŒ ํ•ด์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -18,6 +18,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; @Slf4j @RestController @@ -26,12 +27,24 @@ public class OrderController { private final OrderService orderService; private final BasketService basketService; + + /* + (C) OrderController๊ฐ€ ๊ด€์‹ฌ์žˆ๋Š” ๋ถ€๋ถ„์€ ์ฃผ๋ฌธ ์ •๋ณด๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ  ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด์ง€ ํŠน์ • ์„œ๋น„์Šค(SQS, SSE)๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ถ€๋ถ„์€ ์•„๋‹Œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + MessageService / OrderService / StoreService ๋“ฑ์œผ๋กœ Service๋ฅผ ๋ถ„๋ฆฌํ•˜์—ฌ์„œ ๊ทธ ์•ˆ์—์„œ SsqService, SseService ๋ฐ converter๋ฅผ ์กฐํ•ฉํ•˜์—ฌ + ํ•„์š”ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด ๊ด€์‹ฌ์‚ฌ์˜ ๋ถ„๋ฆฌ๊ฐ€ ๋” ์ ์ ˆํ•˜๊ฒŒ ์ด๋ฃจ์–ด ์งˆ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + */ private final SqsService sqsService; private final SseService sseService; private final SendingMessageConverter sendingMessageConverter; - private final ReceivingMessageConverter receivingMessageConverter; + private final ReceivingMessageConverter receivingMessageConverter; // (C) ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ์˜์กด์„ฑ์€ ์ง€์›Œ์ฃผ๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. - public OrderController(OrderService orderService, BasketService basketService, SqsService sqsService, SseService sseService, SendingMessageConverter sendingMessageConverter, ReceivingMessageConverter receivingMessageConverter) { + /* (C) ์—ฌ๊ธฐ๋„ lombok์˜ RequiredArgsConstructor๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค. */ + public OrderController(OrderService orderService, + BasketService basketService, + SqsService sqsService, + SseService sseService, + SendingMessageConverter sendingMessageConverter, + ReceivingMessageConverter receivingMessageConverter) { this.orderService = orderService; this.basketService = basketService; this.sqsService = sqsService; @@ -43,21 +56,32 @@ public OrderController(OrderService orderService, BasketService basketService, S @GetMapping @ResponseStatus(HttpStatus.OK) public List<OrderPartResponseDto> showOrderList(@RequestAttribute("cognitoUsername") String customerId) { - List<Order> orderList = orderService.getOrderList(customerId).orElseGet(ArrayList::new); - List<OrderPartResponseDto> orderPartInfoList = new ArrayList<>(); - orderList.forEach(order -> { - orderPartInfoList.add(new OrderPartResponseDto(order)); - }); - return orderPartInfoList; + + /* + (C) StreamAPI๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์•„๋ž˜์ฒ˜๋Ÿผ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์–ด ๋ณด์ž…๋‹ˆ๋‹ค. + + getOrderList๋Š” Optional์ด ์•„๋‹Œ List<Order> ํƒ€์ž…์„ ๋ฐ˜ํ™˜ํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค + */ + return orderService.getOrderList(customerId) + .orElseGet(ArrayList::new) + .stream() + .map(OrderPartResponseDto::new) + .collect(Collectors.toList()); } @PostMapping @ResponseStatus(HttpStatus.CREATED) + /* + (C) controller์—์„œ ํ•˜๋Š” ์ผ์ด ๊ฝค ๋งŽ์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์„œ๋น„์Šค๋กœ ๋กœ์ง์„ ๋นผ๋ณด์‹œ๋Š” ๊ฒƒ์„ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค. + */ public void createOrder(@RequestAttribute("cognitoUsername") String customerId, HttpServletResponse response) throws IOException { + /* + 1. (Q) ์—ฌ๊ธฐ๋Š” customerId๊ฐ€ ์™œ basketId๋กœ ์‚ฌ์šฉ๋˜๊ณ  ์žˆ๋‚˜์š”? + 2. (C) createOrder๋กœ order๋ฅผ ์ƒ์„ฑํ–ˆ๋‹ค๋ฉด, orderId๋ณด๋‹ค๋Š” order ์ž์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด ์‚ฌ์šฉ์„ฑ ์ธก๋ฉด์—์„œ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + */ String orderId = orderService.createOrder(customerId, customerId); Optional<Order> orderOptional = orderService.getOrder(orderId); - if(orderOptional.isEmpty()){ + if (orderOptional.isEmpty()) { throw new RuntimeException("Can't create order"); } Order order = orderOptional.get(); @@ -69,9 +93,10 @@ public void createOrder(@RequestAttribute("cognitoUsername") String customerId, @GetMapping("/{orderId}") @ResponseStatus(HttpStatus.OK) public SseEmitter showOrderInfo(@RequestAttribute("cognitoUsername") String customerId, - @PathVariable String orderId){ + @PathVariable String orderId) { SseEmitter sseEmitter = sseService.connect(customerId); sseService.showOrder(customerId, orderId); return sseEmitter; } + } \ No newline at end of file
Java
> Customer๋‹น Basket์€ ํ•˜๋‚˜๋งŒ ๊ฐ€์ง„๋‹ค๊ณ  ์ƒ๊ฐํ•ด์„œ CustomerId๋ฅผ ๋ฐ”๋กœ BasketId๋กœ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค. ๋ฌผ๋ก  ๋™์ผํ•œ ๊ฐ’์„ id๋กœ ์‚ฌ์šฉํ•˜์‹œ๋Š” ๊ฒƒ๋„ ๊ธฐ๋Šฅ ๋™์ž‘์— ๋ฌธ์ œ๊ฐ€ ์—†๊ฒ ์ง€๋งŒ, basketId์— customerId๋ฅผ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์€ ์ผ๋‹จ ์ฝ”๋“œ์˜ ์˜๋„ ํŒŒ์•…์ด ์–ด๋ ต๊ณ , ์ดํ›„ ๋ถ€์—ฌ๋˜๋Š” id๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฒ€์ƒ‰ํ• ํ…๋ฐ ๊ทธ ๋•Œ๋„ ์‹ค์ˆ˜๋ฅผ ์œ ๋ฐœํ•  ์—ฌ์ง€๊ฐ€ ์žˆ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์ฝ”๋“œ ์ˆ˜์ค€์—์„œ ์‹ค์ˆ˜๋ฅผ ์˜ˆ๋ฐฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ถ€๋ถ„์ด ์žˆ๋‹ค๋ฉด ํ•ญ์ƒ ๋ฐฉ์–ดํ•˜๋„๋ก ์ž‘์„ฑํ•˜๋Š” ๊ฒƒ์ด ์ข‹์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -18,6 +18,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; @Slf4j @RestController @@ -26,12 +27,24 @@ public class OrderController { private final OrderService orderService; private final BasketService basketService; + + /* + (C) OrderController๊ฐ€ ๊ด€์‹ฌ์žˆ๋Š” ๋ถ€๋ถ„์€ ์ฃผ๋ฌธ ์ •๋ณด๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ  ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด์ง€ ํŠน์ • ์„œ๋น„์Šค(SQS, SSE)๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ถ€๋ถ„์€ ์•„๋‹Œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + MessageService / OrderService / StoreService ๋“ฑ์œผ๋กœ Service๋ฅผ ๋ถ„๋ฆฌํ•˜์—ฌ์„œ ๊ทธ ์•ˆ์—์„œ SsqService, SseService ๋ฐ converter๋ฅผ ์กฐํ•ฉํ•˜์—ฌ + ํ•„์š”ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด ๊ด€์‹ฌ์‚ฌ์˜ ๋ถ„๋ฆฌ๊ฐ€ ๋” ์ ์ ˆํ•˜๊ฒŒ ์ด๋ฃจ์–ด ์งˆ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + */ private final SqsService sqsService; private final SseService sseService; private final SendingMessageConverter sendingMessageConverter; - private final ReceivingMessageConverter receivingMessageConverter; + private final ReceivingMessageConverter receivingMessageConverter; // (C) ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ์˜์กด์„ฑ์€ ์ง€์›Œ์ฃผ๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. - public OrderController(OrderService orderService, BasketService basketService, SqsService sqsService, SseService sseService, SendingMessageConverter sendingMessageConverter, ReceivingMessageConverter receivingMessageConverter) { + /* (C) ์—ฌ๊ธฐ๋„ lombok์˜ RequiredArgsConstructor๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค. */ + public OrderController(OrderService orderService, + BasketService basketService, + SqsService sqsService, + SseService sseService, + SendingMessageConverter sendingMessageConverter, + ReceivingMessageConverter receivingMessageConverter) { this.orderService = orderService; this.basketService = basketService; this.sqsService = sqsService; @@ -43,21 +56,32 @@ public OrderController(OrderService orderService, BasketService basketService, S @GetMapping @ResponseStatus(HttpStatus.OK) public List<OrderPartResponseDto> showOrderList(@RequestAttribute("cognitoUsername") String customerId) { - List<Order> orderList = orderService.getOrderList(customerId).orElseGet(ArrayList::new); - List<OrderPartResponseDto> orderPartInfoList = new ArrayList<>(); - orderList.forEach(order -> { - orderPartInfoList.add(new OrderPartResponseDto(order)); - }); - return orderPartInfoList; + + /* + (C) StreamAPI๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์•„๋ž˜์ฒ˜๋Ÿผ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์–ด ๋ณด์ž…๋‹ˆ๋‹ค. + + getOrderList๋Š” Optional์ด ์•„๋‹Œ List<Order> ํƒ€์ž…์„ ๋ฐ˜ํ™˜ํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค + */ + return orderService.getOrderList(customerId) + .orElseGet(ArrayList::new) + .stream() + .map(OrderPartResponseDto::new) + .collect(Collectors.toList()); } @PostMapping @ResponseStatus(HttpStatus.CREATED) + /* + (C) controller์—์„œ ํ•˜๋Š” ์ผ์ด ๊ฝค ๋งŽ์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ์„œ๋น„์Šค๋กœ ๋กœ์ง์„ ๋นผ๋ณด์‹œ๋Š” ๊ฒƒ์„ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค. + */ public void createOrder(@RequestAttribute("cognitoUsername") String customerId, HttpServletResponse response) throws IOException { + /* + 1. (Q) ์—ฌ๊ธฐ๋Š” customerId๊ฐ€ ์™œ basketId๋กœ ์‚ฌ์šฉ๋˜๊ณ  ์žˆ๋‚˜์š”? + 2. (C) createOrder๋กœ order๋ฅผ ์ƒ์„ฑํ–ˆ๋‹ค๋ฉด, orderId๋ณด๋‹ค๋Š” order ์ž์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด ์‚ฌ์šฉ์„ฑ ์ธก๋ฉด์—์„œ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + */ String orderId = orderService.createOrder(customerId, customerId); Optional<Order> orderOptional = orderService.getOrder(orderId); - if(orderOptional.isEmpty()){ + if (orderOptional.isEmpty()) { throw new RuntimeException("Can't create order"); } Order order = orderOptional.get(); @@ -69,9 +93,10 @@ public void createOrder(@RequestAttribute("cognitoUsername") String customerId, @GetMapping("/{orderId}") @ResponseStatus(HttpStatus.OK) public SseEmitter showOrderInfo(@RequestAttribute("cognitoUsername") String customerId, - @PathVariable String orderId){ + @PathVariable String orderId) { SseEmitter sseEmitter = sseService.connect(customerId); sseService.showOrder(customerId, orderId); return sseEmitter; } + } \ No newline at end of file
Java
> Repository์—์„œ ์Šต๊ด€์ ์œผ๋กœ create์ดํ›„ id๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋กœ์ง์„ ์‚ฌ์šฉํ•˜๋‹ค๋ณด๋‹ˆ ์ด๋ ‡๊ฒŒ ์ž‘์„ฑํ–ˆ๋Š”๋ฐ, ์ƒ๊ฐํ•ด๋ณด๋‹ˆ order ์ž์ฒด๋ฅผ ๊ฐ€์ ธ์˜ค๋ฉด getOrder()๋„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•„๋„ ๋˜๋‹ˆ ์ฟผ๋ฆฌ ํ•œ ๋ฒˆ์„ ์ ˆ์•ฝํ•˜๊ฒ ๊ตฐ์š”. ์ง€์ ํ•ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๋ง์”€ํ•ด์ฃผ์‹  ๋ถ€๋ถ„๋„ order ๊ฐ์ฒด๋กœ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์˜ ์žฅ์ ์œผ๋กœ ๋ณผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋‹ค๋งŒ ์ œ๊ฐ€ ๋ฆฌ๋ทฐ๋“œ๋ฆฐ ๊ด€์ ์€ ์กฐ๊ธˆ ๋‹ค๋ฅธ ๋ถ€๋ถ„์ž…๋‹ˆ๋‹ค. string ํƒ€์ž…์€ ๋ฒ”์šฉ์ ์ธ primitive ํƒ€์ž…์ด๊ธฐ ๋•Œ๋ฌธ์—, ํด๋ž˜์Šค ์ž์ฒด๋กœ์จ๋Š” ํฐ ์˜๋ฏธ๋ฅผ ๊ฐ–์ง€ ์•Š์Šต๋‹ˆ๋‹ค. (๋‹จ์ง€ string์˜ ์—ญํ• ์„ ํ•˜๋Š” ๊ธฐ๋Šฅ๋“ค์„ ์ œ๊ณตํ•  ๋ฟ์ด๊ฒ ์ฃ ) ํ•˜์ง€๋งŒ order ํƒ€์ž… ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด order๋งŒ์ด ๊ฐ–๊ณ  ์žˆ๋Š” ํด๋ž˜์Šค ์ž์ฒด์˜ ์˜๋ฏธ, ๊ทธ ํด๋ž˜์Šค๊ฐ€ ์ œ๊ณตํ•˜๋Š” ๊ธฐ๋Šฅ๋“ค๊ณผ ๋ถ€๊ฐ€ ๋กœ์ง ๋“ฑ์„ ์ฝ”๋“œ์—์„œ ํ‘œํ˜„๋ ฅ์žˆ๊ฒŒ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. (๊ฐœ์ธ์ ์œผ๋กœ) ์ €๋Š” ๊ทธ๋Ÿฌํ•œ ์ด์œ ๋กœ ์ตœ๋Œ€ํ•œ primitive type์„ ์„œ๋น„์Šค ์ฝ”๋“œ๋‚˜ ์ปจํŠธ๋กค๋Ÿฌ ์ฝ”๋“œ์—์„œ๋Š” ์ž˜ ์‚ฌ์šฉํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ด€๋ จํ•ด์„œ [๋””๋ฏธํ„ฐ ๋ฒ•์น™](https://prohannah.tistory.com/204)์— ๊ด€ํ•ด์„œ๋„ ์•Œ์•„๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋„ค์š”!
@@ -11,6 +11,7 @@ import java.io.IOException; +// (Q) Custom deserializer๋ฅผ ๊ตฌํ˜„ํ•œ ์ด์œ ๊ฐ€ ๋ฌด์—‡์ธ๊ฐ€์š”? Jackson ๋“ฑ์˜ serializer๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์–ด๋ ค์šด ๋ถ€๋ถ„์ด ์žˆ๋‚˜์š”? public class StoreDeserializer extends StdDeserializer { public StoreDeserializer(){
Java
๋„ค ๋™์ผํ•œ ๋ณ€์ˆ˜๋ช…์œผ๋กœ ์ฒ˜๋ฆฌํ–ˆ์ง€๋งŒ, custom deserializer๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์œผ๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•ฉ๋‹ˆ๋‹ค. _Cannot construct instance of `org.springframework.data.geo.Point` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)_ Point๋ผ๋Š” ๊ฐ์ฒด๋ฅผ objectMapper๊ฐ€ ๋ชจ๋ฅด๊ธฐ ๋•Œ๋ฌธ์— ๋ฐœ์ƒํ•œ ์ผ์ด๋ผ๊ณ  ํ•˜๋”๊ตฐ์š”. ์•„๋ž˜๋Š” chat GPT๋ฅผ ํ†ตํ•ด ์–ป์€ ๋‹ต๋ณ€์ž…๋‹ˆ๋‹ค. https://chat.openai.com/share/fe6258ed-93d6-446b-a39b-6b9c9d1ac0b1 ๋‹ค๋งŒ ์ œ๊ฐ€ ํ–ˆ๋˜ ๊ฒƒ์ฒ˜๋Ÿผ StoreSqsDto์˜ ๋ชจ๋“  property๋ฅผ custom deserialize ํ•  ํ•„์š” ์—†์ด Point๋งŒ custom์œผ๋กœ ๋“ฑ๋กํ•˜๋ฉด ๋˜๊ฒ ๊ตฐ์š”.
@@ -11,6 +11,7 @@ import java.io.IOException; +// (Q) Custom deserializer๋ฅผ ๊ตฌํ˜„ํ•œ ์ด์œ ๊ฐ€ ๋ฌด์—‡์ธ๊ฐ€์š”? Jackson ๋“ฑ์˜ serializer๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์–ด๋ ค์šด ๋ถ€๋ถ„์ด ์žˆ๋‚˜์š”? public class StoreDeserializer extends StdDeserializer { public StoreDeserializer(){
Java
@millwheel ์•„ Point๊ฐ€ ๊ธฐ๋ณธ ์ƒ์„ฑ์ž๊ฐ€ ์—†๊ตฐ์š”. ์ œ๊ฐ€ ์•Œ๊ณ ์žˆ๋Š” ์ผ๋ฐ˜์ ์ธ serializer์˜ deserialize ๋ฐฉ์‹์€, ๋จผ์ € ๊ธฐ๋ณธ ์ƒ์„ฑ์ž๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ณ  setter๋ฅผ ํ†ตํ•ด ๊ฐ์ฒด ํ•„๋“œ๋ฅผ settingํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ์•Œ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋Ÿฐ๋ฐ ๊ธฐ๋ณธ ์ƒ์„ฑ์ž๊ฐ€ ์—†๋‹ค๋ณด๋‹ˆ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๊ณผ์ •์—์„œ ์—๋Ÿฌ๊ฐ€ ๋‚˜๋Š” ๊ฒƒ ๊ฐ™๋„ค์š”~ ์‚ฌ์‹ค point ํด๋ž˜์Šค์™€ ๊ด€๋ จํ•ด์„œ๋„ ๋ฆฌ๋ทฐ ๋“œ๋ฆฌ๋ ค๊ณ  ํ–ˆ๋Š”๋ฐ, ์ดํ›„ ๊ด€๋ จ ๋ฆฌ๋ทฐ์—์„œ ๋” ์–˜๊ธฐํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค~
@@ -19,11 +19,16 @@ @RestController @Slf4j +/* + (C) foodKind๋Š” QueryParam์œผ๋กœ ๋ฐ›๋Š” ๊ฒƒ์ด ๋” restful ํ•ด๋ณด์ž…๋‹ˆ๋‹ค. + ๋˜ํ•œ showStoreInfo์—์„œ๋Š” foodKind๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์—, ๊ฐœ๋ณ„ ๋ฉ”์„œ๋“œ์—์„œ ๋งตํ•‘ํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„ ๋ณด์ž…๋‹ˆ๋‹ค. +*/ @RequestMapping("/customer/{foodKind}/store") public class StoreController { private final MemberService memberService; private final StoreService storeService; + /* (C) lombok์˜ @RequiredArgsConstructor๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. */ public StoreController(MemberService memberService, StoreService storeService) { this.memberService = memberService; this.storeService = storeService; @@ -33,11 +38,31 @@ public StoreController(MemberService memberService, StoreService storeService) { @ResponseStatus(HttpStatus.OK) public List<StorePartResponseDto> showStoreList(@RequestAttribute("cognitoUsername") String customerId, @PathVariable FoodKind foodKind, - HttpServletResponse response) throws IOException { + HttpServletResponse response /* ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” param์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. */) throws IOException { + /* + 1. (A) MemberService์— ์™œ coordinates๋ฅผ ํš๋“ํ•˜๋Š” ๋ฉ”์„œ๋“œ๊ฐ€ ์žˆ๋Š” ๊ฒƒ์ธ์ง€ ๋ฐ”๋กœ ์ดํ•ดํ•˜๊ธฐ๋Š” ์‚ด์ง ์–ด๋ ค์› ์Šต๋‹ˆ๋‹ค. + coordinates๋ณด๋‹ค๋Š” location์ด๋ผ๋Š” ๋‹จ์–ด๊ฐ€ ๋‹ค๋ฅธ ํด๋ž˜์Šค๋“ค์—์„œ ์‚ฌ์šฉํ•˜๋Š” ๋„๋ฉ”์ธ ์šฉ์–ด(Customer.location)์™€๋„ ํ†ต์ผ๋˜๊ณ  ๋” ์ดํ•ดํ•˜๊ธฐ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + + 2. (C) Optional ํƒ€์ž…์€ ํš๋“ํ•˜์ž๋งˆ์ž ํ•„์š”ํ•œ ํ›„์ฒ˜๋ฆฌ(orElseThrow, isEmpty ๋“ฑ)๋ฅผ ํ•ด์ฃผ์–ด์„œ + ์•„๋ž˜์˜ isEmpty์™€ ๊ฐ™์€ optional check ๋กœ์ง์ด ์—ฌ๋Ÿฌ ์ฝ”๋“œ์— ํผ์ง€์ง€ ์•Š๋„๋ก ํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. + MemberService.getCoordinates ๋‚ด์—์„œ orElseThrow ๋“ฑ์œผ๋กœ optional check & un-wrapํ•˜๊ณ , Point ํƒ€์ž…์œผ๋กœ ๋ฐ˜ํ™˜ํ•ด์ฃผ์„ธ์š”. + */ Optional<Point> coordinates = memberService.getCoordinates(customerId); if(coordinates.isEmpty()){ + /* + (R) NPE๋Š” ์ผ๋ฐ˜์ ์œผ๋กœ non-nullableํ•œ ๊ณณ์— null ๊ฐ’์ด ์„ธํŒ…๋˜์—ˆ์„ ๋•Œ ๋ฐœ์ƒํ•˜๋Š” exception์ž…๋‹ˆ๋‹ค. + Empty coordinates์— NPE๋ฅผ ๋˜์ง€๋ฉด ์˜๋ฏธ์˜ ํ˜ผ๋™์ด ์žˆ์„ ๊ฒƒ์œผ๋กœ ๋ณด์ž…๋‹ˆ๋‹ค. + ์ž๋ฐ” ์ŠคํŽ™์ธ NPE๋ณด๋‹ค๋Š”, ํ”„๋กœ์ ํŠธ์—์„œ empty์˜ ์˜๋ฏธ๋ฅผ ๊ฐ–๋Š” exception์„ customํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค. + empty๋„ ์–ด๋–ค ๋Œ€์ƒ์ด emptyํ•œ์ง€๋ฅผ ์„ธ๋ถ„ํ™”ํ•˜์—ฌ ๋‚˜ํƒ€๋‚ด๋ฉด ๋” ์œ ์˜๋ฏธํ•œ ์˜ˆ์™ธ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ฌ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + */ throw new NullPointerException("Customer has no location information."); } + + /* + (A) ์ฑ… clean code์—์„œ๋Š” collection์˜ ์ž๋ฃŒํ˜•์„ ๋ณ€์ˆ˜๋ช…์— ๋ถ™์ด์ง€ ๋ง ๊ฒƒ์„ ๊ถŒ์žฅํ•ฉ๋‹ˆ๋‹ค. + list -> set ๋“ฑ์œผ๋กœ collection ํƒ€์ž…์ด ๋ณ€๊ฒฝ๋˜๋ฉด storePartSet์œผ๋กœ ๋ณ€๊ฒฝํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ๋•Œ๋ฌธ์—, + storeParts, stores์™€ ๊ฐ™์€ ๋ณต์ˆ˜ํ˜•์œผ๋กœ ๋‚˜ํƒ€๋‚ด๊ธฐ๋ฅผ ๊ถŒ์žฅํ•ฉ๋‹ˆ๋‹ค. + */ List<StorePartResponseDto> storePartList = new ArrayList<>(); List<Store> storeList = storeService.getStoreListNearCustomer(coordinates.get(), foodKind); storeList.forEach(store -> { @@ -48,6 +73,10 @@ public List<StorePartResponseDto> showStoreList(@RequestAttribute("cognitoUserna @GetMapping("/{storeId}") @ResponseStatus(HttpStatus.OK) + /* + (R) Store์™€ ๊ฐ™์ด db table์— ์ €์žฅ๋˜๋Š” ์š”์†Œ๋“ค์€ ์ตœ๋Œ€ํ•œ ํด๋ผ์ด์–ธํŠธ ๋‹จ์—์„œ ๋ถ„๋ฆฌํ•˜์—ฌ ๊ฐ์ถฐ์ฃผ๋Š” ๊ฒƒ์ด ์ข‹์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. + ์ผ๋ฐ˜์ ์œผ๋กœ Store์— ๋Œ€์‘๋˜๋Š” DTO๋ฅผ ๋งŒ๋“ค์–ด์„œ ์‚ฌ์šฉํ•˜๋Š” ํŽธ์ž…๋‹ˆ๋‹ค. + */ public StoreResponseDto showStoreInfo (@RequestAttribute("storeEntity") Store store, @PathVariable String storeId){ return new StoreResponseDto(store);
Java
> Q) @RequiredArgConstructor๋ฅผ Entity์—์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ ์ž…๋ ฅ๋œ Property์˜ ์ˆœ์„œ๋ฅผ ๋ฐ”๊ฟจ์„ ๋•Œ ๋•Œ ๊ฐ™์€ ํƒ€์ž…์˜ property๋ผ๋ฉด ๋ฌธ์ œ๊ฐ€ ๋˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋”๋ผ๊ณ ์š”. ์ƒ์„ฑ์ž๋ฅผ ์ƒ์„ฑํ•  ๋•Œ ๋งค๊ฐœ๋ณ€์ˆ˜ ์ž…๋ ฅ ์ˆœ์„œ๋ฅผ ๋ฐ”๊พธ์ง€ ์•Š์•„๋„ ์ปดํŒŒ์ผ ๊ณผ์ •์—์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š์•„์„œ ์ž˜๋ชป๋œ ๊ฐ’์ด ๋“ค์–ด์™€๋„ ์บ์น˜ํ•  ์ˆ˜ ์—†์–ด์„œ ์•„์˜ˆ @RequiredArgConstructor๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ๋ง์ž๊ณ  ํ•˜๋Š” ๊ธ€๋„ ๋ดค์—ˆ์Šต๋‹ˆ๋‹ค. ๋ฌผ๋ก  Controller๋ผ์„œ ๊ฐ™์€ ํƒ€์ž…์˜ property๊ฐ€ ์—†์œผ๋‹ˆ๊นŒ ์—ฌ๊ธฐ์„  ๋ฌธ์ œ๊ฐ€ ์—†๊ฒ ์ง€๋งŒ, ์‹ค์ œ๋กœ @requiredargsconstructor๋ฅผ ํŽธ์˜์ƒ ๋งŽ์ด ์‚ฌ์šฉํ•˜๋‚˜์š”? Entity์—์„œ๋งŒ ์‚ฌ์šฉํ•˜์ง€ ์•Š์œผ๋ฉด ๋˜๋Š” ๊ฑด๊ฐ€์š”? ๋ง์”€ํ•˜์‹œ๋Š” ๋ฌธ์ œ๊ฐ€ ์–ด๋–ค ๋ฌธ์ œ์ธ์ง€ ์•Œ ์ˆ˜ ์žˆ์„๊นŒ์š”? --- > Q) Optional ์‚ฌ์šฉ์—์„œ ํ•ญ์ƒ ๊ณ ๋ฏผ์ด ๋˜์—ˆ๋Š”๋ฐ, Service ๋กœ์ง ๋‹จ์—์„œ orElseThrow()๋ฅผ ๋˜์ง€๋Š”๊ฒŒ ๋‚ซ๋‹ค๊ณ  ๋ณด์‹œ๋‚˜์š”? orElse(null)๊ณผ ๊ฐ™์€ ๋ฐฉ์‹์€ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”? exception์„ throwํ•˜๋Š”๊ฒŒ memory cost๊ฐ€ ๋งŽ์ด ๋“ค์–ด๊ฐ„๋‹ค๊ณ  ์•Œ๊ณ  ์žˆ์–ด์„œ ๋‹ค๋ฅธ ๋ฐฉ์‹์€ ์–ด๋–ค์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค. orElseThrow, orElse, orElseGet ๋“ฑ์œผ๋กœ optional์€ ๋ฐ›์€ ์ชฝ์—์„œ ์ตœ๋Œ€ํ•œ ๋น ๋ฅด๊ฒŒ ๋ฒ—๊ฒจ๋‚ด๋Š” ๊ฒƒ์ด ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. optional ์ฒดํฌ ๋กœ์ง์ด ๊ดœํžˆ ์—ฌ๊ธฐ์ €๊ธฐ ๋Œ์•„๋‹ค๋‹ˆ๋ฉด ํ•ด๋‹น ๋ฐ์ดํ„ฐ๊ฐ€ nullableํ•œ ์ƒํƒœ์ž„์„ ๊ณ„์† ๊ณ ๋ คํ•ด์•ผ ํ•˜๋Š”๋ฐ, ๊ทธ๋ ‡๊ฒŒ ํ•˜๊ธฐ๋ณด๋‹ค๋Š” empty์ด๋“  ์•„๋‹ˆ๋“  ๋นจ๋ฆฌ optional wrapping์„ ์ œ๊ฑฐํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. exception์ด memory๋ฅผ ๋งŽ์ด ์žก์•„๋จน๋Š”๋‹ค๋Š” ๊ฒƒ์€ ์•„๋งˆ ์Šฌ๋ž™์— ๊ณต์œ ๋œ ์งˆ๋ฌธ์—์„œ ๋ณธ ๊ฒƒ ๊ฐ™์€๋ฐ, ๋ฉ”๋ชจ๋ฆฌ ๋ฌธ์ œ๋กœ exception์„ ๋˜์ง€๋Š” ๊ฒƒ๊นŒ์ง€ ๊ณ ๋ คํ•ด์•ผํ•  ์ˆ˜์ค€์˜ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์ด๋ผ๋ฉด ์ฐจ๋ผ๋ฆฌ ํ•ด๋‹น ๊ธฐ๋Šฅ์„ ๋งˆ์ดํฌ๋กœ ์„œ๋น„์Šค๋กœ ๋ถ„๋ฆฌํ•ด์„œ golang์ด๋‚˜ rust, scala ๋“ฑ ํŠนํ™” ์–ธ์–ด๋กœ ์ ‘๊ทผํ•˜๋Š” ๊ฒƒ์ด ๋งž๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. exception throw๋Š” ์ž๋ฐ”์—์„œ best practice๋ผ๊ณ  ์ƒ๊ฐํ•ด์„œ ใ…Žใ…Ž ์ €๋Š” exception์„ ๋˜์ง€์ง€ ๋ชปํ•  ์ •๋„๊นŒ์ง€๋Š” ๋ณธ ์ ์ด ์—†๋Š” ๊ฒƒ ๊ฐ™๋„ค์š” --- > Q) showStoreInfo ๋ฉ”์„œ๋“œ์˜ @RequestAttribute์˜ Store ๊ฐ์ฒด๋Š” StoreCheckInterceptor๋กœ๋ถ€ํ„ฐ ๋„˜๊ฒจ๋ฐ›์€ ๊ฐ์ฒด์ž…๋‹ˆ๋‹ค. ํด๋ผ์ด์–ธํŠธ๋Š” pathvariable๋กœ storeId๋งŒ ๋˜์ ธ์ฃผ๊ณ  ์žˆ์–ด์š”. ์ธํ„ฐ์…‰ํ„ฐ๋กœ ๋ฐ›์€ Store์ธ๋ฐ๋„ DTO๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒŒ ์ข‹๋‹ค๊ณ  ๋ณด์„ธ์š”? ํ  ๊ทธ๋ ‡๊ตฐ์š”.. ์ €๋Š” ์ธํ„ฐ์…‰ํ„ฐ์—์„œ storeId๋ฅผ store๋กœ ๋ณ€ํ™˜ํ•ด์„œ controller์— ๋„˜๊ฒจ์ฃผ๋Š” ๋ถ€๋ถ„์ด ์–ด๋– ํ•œ ์ด์œ ๋กœ ์žˆ๋Š” ๊ฒƒ์ธ์ง€ ๊ถ๊ธˆํ•˜๊ธด ํ•ฉ๋‹ˆ๋‹ค ใ…Žใ…Ž storeId์˜ ์šฉ๋„๊ฐ€ ์ปจํŠธ๋กค๋Ÿฌ ๋‚ด์—์„œ ๋ณ€๊ฒฝ๋  ์ˆ˜๋„ ์žˆ์„ํ…๋ฐ, controller๊ฐ€ interceptor์— ๊ฐ•ํ•˜๊ฒŒ ๊ฒฐํ•ฉ๋œ ๋А๋‚Œ์ด ๋“œ๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ ๋‹ค๋ฅธ ๋ถ„๋“ค์€ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜๋Š”์ง€ ๋“ค์–ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋„ค์š”~
@@ -0,0 +1,45 @@ +package calculator.model; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; + +public enum OperatorType { + ADDITION("+", (a, b) -> a + b), + SUBTRACTION("-", (a, b) -> a - b), + MULTIPLICATION("*", (a, b) -> a * b), + DIVISION("/", (a, b) -> { + if (b == 0) { + throw new ArithmeticException("0์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + return a / b; + }); + + private static final Map<String, OperatorType> SYMBOL_MAP = new HashMap<>(); + + static { + for (OperatorType type : values()) { + SYMBOL_MAP.put(type.symbol, type); + } + } + + private final String symbol; + private final BiFunction<Integer, Integer, Integer> operation; + + OperatorType(String symbol, BiFunction<Integer, Integer, Integer> operation) { + this.symbol = symbol; + this.operation = operation; + } + + public static OperatorType fromString(String symbol) { + OperatorType type = SYMBOL_MAP.get(symbol); + if (type == null) { + throw new IllegalArgumentException("์ž˜๋ชป๋œ ์—ฐ์‚ฐ์ž์ž…๋‹ˆ๋‹ค."); + } + return type; + } + + public int apply(int a, int b) { + return operation.apply(a, b); + } +} \ No newline at end of file
Java
์ด๋ ‡๊ฒŒ ๋ฌธ์ž์—ด์„ ๋ฆฌํ„ดํ•ด์ค„ ํ•„์š”๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,17 @@ +package calculator.model; + +public class Operator { + + public int calculate(String[] values) { + int result = Integer.parseInt(values[0]); + + for (int i = 1; i < values.length; i += 2) { + String symbol = values[i]; + int nextNumber = Integer.parseInt(values[i + 1]); + OperatorType operatorType = OperatorType.fromString(symbol); + result = operatorType.apply(result, nextNumber); + } + + return result; + } +}
Java
Enum ์‚ฌ์šฉ๋ฒ•์„ ๋‹ค์‹œ ๊ณต๋ถ€ํ•ด์„œ ์ ์šฉํ•ด๋ด…์‹œ๋‹ค. Switch๋ฌธ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๋ฐฉ์‹์œผ๋กœ์š”.
@@ -0,0 +1,11 @@ +package calculator.view; + +import java.util.Scanner; + +public class InputView { + public String formulaInput() { + Scanner scanner = new Scanner(System.in); + System.out.print("์ˆ˜์‹์„ ์ž…๋ ฅํ•˜์„ธ์š” : "); + return scanner.nextLine(); + } +} \ No newline at end of file
Java
ํด๋ž˜์Šค์— ์—ญํ• ์ด ๋‘ ๊ฐ€์ง€ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค 1. ๋ฌธ์ž์—ด์„ ๋ฐ›๋Š”๋‹ค 2. ๋ฌธ์ž์—ด์„ ๋‚˜๋ˆˆ๋‹ค ํด๋ž˜์Šค์˜ ์ฑ…์ž„๊ณผ ์—ญํ• ์— ๋Œ€ํ•ด์„œ ์ƒ๊ฐํ•ด๋ด…์‹œ๋‹ค
@@ -0,0 +1,27 @@ +package calculator.controller; + +import calculator.model.Operator; +import calculator.util.FormulaParser; +import calculator.view.InputView; +import calculator.view.OutputView; + +public class CalculatorController { + private final Operator operator; + private final InputView inputView; + private final OutputView outputView; + private final FormulaParser formulaParser; + + public CalculatorController(Operator operator, InputView inputView, OutputView outputView, FormulaParser formulaParser) { + this.operator = operator; + this.inputView = inputView; + this.outputView = outputView; + this.formulaParser = formulaParser; + } + + public void calculatorRun() { + String formula = inputView.formulaInput(); + String[] values = formulaParser.parse(formula); + int result = operator.calculate(values); + outputView.resultOutput(result); + } +}
Java
์ด ๋ณ€์ˆ˜๊ฐ€ ์–ด๋–ค ์—ญํ• ์„ ํ•˜๋Š” ๋ณ€์ˆ˜์ธ์ง€ ๋ณ€์ˆ˜๋ช…๋งŒ ๋ณด๊ณ  ์•Œ ์ˆ˜ ์žˆ๊ฒŒ ๋งŒ๋“ค์–ด์ฃผ์„ธ์š”
@@ -0,0 +1,17 @@ +package calculator.model; + +public class Operator { + + public int calculate(String[] values) { + int result = Integer.parseInt(values[0]); + + for (int i = 1; i < values.length; i += 2) { + String symbol = values[i]; + int nextNumber = Integer.parseInt(values[i + 1]); + OperatorType operatorType = OperatorType.fromString(symbol); + result = operatorType.apply(result, nextNumber); + } + + return result; + } +}
Java
์ด๋ ‡๊ฒŒ ํ•ด์ค„ ๊ฑฐ๋ฉด ํ•„๋“œ์—์„œ ์ง์ ‘์ ์œผ๋กœ ์„ ์–ธํ•ด์ฃผ๋Š” ๊ฒƒ์ด ๋” ๊น”๋”ํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,45 @@ +package calculator.model; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; + +public enum OperatorType { + ADDITION("+", (a, b) -> a + b), + SUBTRACTION("-", (a, b) -> a - b), + MULTIPLICATION("*", (a, b) -> a * b), + DIVISION("/", (a, b) -> { + if (b == 0) { + throw new ArithmeticException("0์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + return a / b; + }); + + private static final Map<String, OperatorType> SYMBOL_MAP = new HashMap<>(); + + static { + for (OperatorType type : values()) { + SYMBOL_MAP.put(type.symbol, type); + } + } + + private final String symbol; + private final BiFunction<Integer, Integer, Integer> operation; + + OperatorType(String symbol, BiFunction<Integer, Integer, Integer> operation) { + this.symbol = symbol; + this.operation = operation; + } + + public static OperatorType fromString(String symbol) { + OperatorType type = SYMBOL_MAP.get(symbol); + if (type == null) { + throw new IllegalArgumentException("์ž˜๋ชป๋œ ์—ฐ์‚ฐ์ž์ž…๋‹ˆ๋‹ค."); + } + return type; + } + + public int apply(int a, int b) { + return operation.apply(a, b); + } +} \ No newline at end of file
Java
์ด ๋ฉ”์†Œ๋“œ๊ฐ€ static ๋ฉ”์†Œ๋“œ์—ฌ์•ผ๋งŒ ํ•˜๋Š” ์ด์œ ๊ฐ€ ์žˆ๋‚˜์š”?
@@ -0,0 +1,11 @@ +package calculator.view; + +import java.util.Scanner; + +public class InputView { + public String formulaInput() { + Scanner scanner = new Scanner(System.in); + System.out.print("์ˆ˜์‹์„ ์ž…๋ ฅํ•˜์„ธ์š” : "); + return scanner.nextLine(); + } +} \ No newline at end of file
Java
FormulaParser ํด๋ž˜์Šค์— ๋ฌธ์ž์—ด์„ ๋‚˜๋ˆ„๋Š” ์—ญํ• ์„ ๋ถ„ํ• ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,27 @@ +package calculator.controller; + +import calculator.model.Operator; +import calculator.util.FormulaParser; +import calculator.view.InputView; +import calculator.view.OutputView; + +public class CalculatorController { + private final Operator operator; + private final InputView inputView; + private final OutputView outputView; + private final FormulaParser formulaParser; + + public CalculatorController(Operator operator, InputView inputView, OutputView outputView, FormulaParser formulaParser) { + this.operator = operator; + this.inputView = inputView; + this.outputView = outputView; + this.formulaParser = formulaParser; + } + + public void calculatorRun() { + String formula = inputView.formulaInput(); + String[] values = formulaParser.parse(formula); + int result = operator.calculate(values); + outputView.resultOutput(result); + } +}
Java
calculatorRun์œผ๋กœ ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,45 @@ +package calculator.model; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; + +public enum OperatorType { + ADDITION("+", (a, b) -> a + b), + SUBTRACTION("-", (a, b) -> a - b), + MULTIPLICATION("*", (a, b) -> a * b), + DIVISION("/", (a, b) -> { + if (b == 0) { + throw new ArithmeticException("0์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + return a / b; + }); + + private static final Map<String, OperatorType> SYMBOL_MAP = new HashMap<>(); + + static { + for (OperatorType type : values()) { + SYMBOL_MAP.put(type.symbol, type); + } + } + + private final String symbol; + private final BiFunction<Integer, Integer, Integer> operation; + + OperatorType(String symbol, BiFunction<Integer, Integer, Integer> operation) { + this.symbol = symbol; + this.operation = operation; + } + + public static OperatorType fromString(String symbol) { + OperatorType type = SYMBOL_MAP.get(symbol); + if (type == null) { + throw new IllegalArgumentException("์ž˜๋ชป๋œ ์—ฐ์‚ฐ์ž์ž…๋‹ˆ๋‹ค."); + } + return type; + } + + public int apply(int a, int b) { + return operation.apply(a, b); + } +} \ No newline at end of file
Java
์ง€์ •๋œ ์—ฐ์‚ฐ์ž๋ฅผ ์ œ์™ธํ•œ ๋‹ค๋ฅธ ๊ธฐํ˜ธ๋ฅผ ์ž…๋ ฅํ–ˆ์„ ๊ฒฝ์šฐ์— ์ถœ๋ ฅํ•˜๋„๋ก ํ–ˆ์ง€๋งŒ ๊ณ„์‚ฐ๊ธฐ์˜ ๊ฒฝ์šฐ ๋”ฐ๋กœ ์—†์–ด๋„ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,17 @@ +package calculator.model; + +public class Operator { + + public int calculate(String[] values) { + int result = Integer.parseInt(values[0]); + + for (int i = 1; i < values.length; i += 2) { + String symbol = values[i]; + int nextNumber = Integer.parseInt(values[i + 1]); + OperatorType operatorType = OperatorType.fromString(symbol); + result = operatorType.apply(result, nextNumber); + } + + return result; + } +}
Java
OperatorType์˜ ๊ธฐ๋Šฅ์„ ์ˆ˜์ •ํ•˜๋ฉด์„œ Operator์˜ ๊ธฐ๋Šฅ๊ณผ ์ค‘๋ณต๋˜๊ธฐ์— ์‚ญ์ œํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,45 @@ +package calculator.model; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; + +public enum OperatorType { + ADDITION("+", (a, b) -> a + b), + SUBTRACTION("-", (a, b) -> a - b), + MULTIPLICATION("*", (a, b) -> a * b), + DIVISION("/", (a, b) -> { + if (b == 0) { + throw new ArithmeticException("0์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + return a / b; + }); + + private static final Map<String, OperatorType> SYMBOL_MAP = new HashMap<>(); + + static { + for (OperatorType type : values()) { + SYMBOL_MAP.put(type.symbol, type); + } + } + + private final String symbol; + private final BiFunction<Integer, Integer, Integer> operation; + + OperatorType(String symbol, BiFunction<Integer, Integer, Integer> operation) { + this.symbol = symbol; + this.operation = operation; + } + + public static OperatorType fromString(String symbol) { + OperatorType type = SYMBOL_MAP.get(symbol); + if (type == null) { + throw new IllegalArgumentException("์ž˜๋ชป๋œ ์—ฐ์‚ฐ์ž์ž…๋‹ˆ๋‹ค."); + } + return type; + } + + public int apply(int a, int b) { + return operation.apply(a, b); + } +} \ No newline at end of file
Java
๊ฐ์ฒด๋ฅผ ๋ณ€๊ฒฝํ•˜์ง€ ์•Š์•„์„œ ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•˜์ง€ ์•Š์•„๋„ ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๊ณ  static๋ฉ”์†Œ๋“œ๋กœ ์„ ์–ธํ•˜๋ฉด ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ์—†์ด ํ˜ธ์ถœ ํ•  ์ˆ˜ ์žˆ์–ด์„œ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,17 @@ +package calculator.model; + +public class Operator { + + public int calculate(String[] values) { + int result = Integer.parseInt(values[0]); + + for (int i = 1; i < values.length; i += 2) { + String symbol = values[i]; + int nextNumber = Integer.parseInt(values[i + 1]); + OperatorType operatorType = OperatorType.fromString(symbol); + result = operatorType.apply(result, nextNumber); + } + + return result; + } +}
Java
BiFunction ํ•„๋“œ๋ฅผ ํ™œ์šฉํ•˜์—ฌ Switch๋ฌธ ์—†์ด ์—ฐ์‚ฐ์„ ์ฒ˜๋ฆฌ ํ•  ์ˆ˜ ์žˆ๊ฒŒ ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,27 @@ +package calculator.controller; + +import calculator.model.Operator; +import calculator.util.FormulaParser; +import calculator.view.InputView; +import calculator.view.OutputView; + +public class CalculatorController { + private final Operator operator; + private final InputView inputView; + private final OutputView outputView; + private final FormulaParser formulaParser; + + public CalculatorController(Operator operator, InputView inputView, OutputView outputView, FormulaParser formulaParser) { + this.operator = operator; + this.inputView = inputView; + this.outputView = outputView; + this.formulaParser = formulaParser; + } + + public void calculatorRun() { + String formula = inputView.formulaInput(); + String[] values = formulaParser.parse(formula); + int result = operator.calculate(values); + outputView.resultOutput(result); + } +}
Java
values๋Š” ์–ด๋–ค ์šฉ๋„๋กœ ์‚ฌ์šฉ๋˜๋Š” ๋ณ€์ˆ˜์ธ๊ฐ€์š”
@@ -0,0 +1,17 @@ +package calculator.model; + +public class Operator { + + public int calculate(String[] values) { + int result = Integer.parseInt(values[0]); + + for (int i = 1; i < values.length; i += 2) { + String symbol = values[i]; + int nextNumber = Integer.parseInt(values[i + 1]); + OperatorType operatorType = OperatorType.fromString(symbol); + result = operatorType.apply(result, nextNumber); + } + + return result; + } +}
Java
์–ด๋–ค ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๋ฐ›์•„์˜ค๋Š” ๊ฑด๊ฐ€์š”. ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ๋ฉ”์†Œ๋“œ ๋‚ด์—์„œ ์–ด๋–ค ์—ญํ• ์„ ํ•˜๋Š”์ง€ ์•Œ ์ˆ˜ ์žˆ๋„๋ก ์ง€์–ด์ฃผ์„ธ์š”
@@ -0,0 +1,17 @@ +package calculator.model; + +public class Operator { + + public int calculate(String[] values) { + int result = Integer.parseInt(values[0]); + + for (int i = 1; i < values.length; i += 2) { + String symbol = values[i]; + int nextNumber = Integer.parseInt(values[i + 1]); + OperatorType operatorType = OperatorType.fromString(symbol); + result = operatorType.apply(result, nextNumber); + } + + return result; + } +}
Java
static ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด์•ผํ•  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,45 @@ +package calculator.model; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; + +public enum OperatorType { + ADDITION("+", (a, b) -> a + b), + SUBTRACTION("-", (a, b) -> a - b), + MULTIPLICATION("*", (a, b) -> a * b), + DIVISION("/", (a, b) -> { + if (b == 0) { + throw new ArithmeticException("0์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); + } + return a / b; + }); + + private static final Map<String, OperatorType> SYMBOL_MAP = new HashMap<>(); + + static { + for (OperatorType type : values()) { + SYMBOL_MAP.put(type.symbol, type); + } + } + + private final String symbol; + private final BiFunction<Integer, Integer, Integer> operation; + + OperatorType(String symbol, BiFunction<Integer, Integer, Integer> operation) { + this.symbol = symbol; + this.operation = operation; + } + + public static OperatorType fromString(String symbol) { + OperatorType type = SYMBOL_MAP.get(symbol); + if (type == null) { + throw new IllegalArgumentException("์ž˜๋ชป๋œ ์—ฐ์‚ฐ์ž์ž…๋‹ˆ๋‹ค."); + } + return type; + } + + public int apply(int a, int b) { + return operation.apply(a, b); + } +} \ No newline at end of file
Java
์ด๊ฑธ ํ•„๋“œ๋กœ ์„ ์–ธํ•œ ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”? ๋ฐ์ดํ„ฐ ์ฃผ๋„ ์„ค๊ณ„๊ฐ€ ์•„๋‹Œ ๋„๋ฉ”์ธ ์ฃผ๋„ ์„ค๊ณ„๋ฅผ ๊ณต๋ถ€ํ•ด๋ณด์„ธ
@@ -0,0 +1,17 @@ +package calculator.model; + +public class Operator { + + public int calculate(String[] values) { + int result = Integer.parseInt(values[0]); + + for (int i = 1; i < values.length; i += 2) { + String symbol = values[i]; + int nextNumber = Integer.parseInt(values[i + 1]); + OperatorType operatorType = OperatorType.fromString(symbol); + result = operatorType.apply(result, nextNumber); + } + + return result; + } +}
Java
ํ˜„์žฌ ํ‘ธ์‰ฌํ•œ ์ฝ”๋“œ์— ์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,17 @@ +package calculator.model; + +public class Operator { + + public int calculate(String[] values) { + int result = Integer.parseInt(values[0]); + + for (int i = 1; i < values.length; i += 2) { + String symbol = values[i]; + int nextNumber = Integer.parseInt(values[i + 1]); + OperatorType operatorType = OperatorType.fromString(symbol); + result = operatorType.apply(result, nextNumber); + } + + return result; + } +}
Java
values ๋งํ•œ ๊ฑฐ์—์š”
@@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Bucket + uuid = "F89D4C7C-1180-42EB-AF20-BEE64400FB01" + type = "1" + version = "2.0"> +</Bucket>
Unknown
์ด ํŒŒ์ผ์€ ๋ฌด์—‡์ธ๊ฐ€์š” . .? gitignore ๋กœ ์•ˆ์˜ฌ๋ฆฌ๋Š”๊ฒŒ ์ข‹์„๊ฒƒ๊ฐ€ํƒธ์š”
@@ -10,11 +10,11 @@ import UIKit class HomeViewController: UIViewController { private var feeds: [Feed] = [ - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]) + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]) ] private let feedCollectionView: UICollectionView = { @@ -79,13 +79,14 @@ extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSour return cell } + // Cell Spacing func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 30.0 } // Cell size func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { - return CGSize(width: view.bounds.width - 32.0, height: 524) + return CGSize(width: view.bounds.width - 32.0, height: 550) } }
Swift
550์˜ ์˜๋ฏธ๋Š” ๋ฌด์—‡์ธ๊ฐ€์š” ! ์˜๋ฏธ๊ฐ€ ์žˆ๋‹ค๋ฉด let์œผ๋กœ ๋ช…๋ช…ํ•ด์„œ ์ถ”ํ›„์— ์œ ์ง€๋ณด์ˆ˜ ๋•Œ ์•Œ์•„๋ณด๊ธฐ ์‰ฝ๊ฒŒํ•˜๋Š”๊ฒƒ์ด ์ข‹์„ ๋“ฏํ•ฉ๋‹ˆ๋‹ค ~
@@ -21,3 +21,25 @@ extension UICollectionViewCell { NSStringFromClass(self.classForCoder()).components(separatedBy: ".").last! } } + +extension UIImage { + + func applyBlur_usingClamp(radius: CGFloat) -> UIImage { + let context = CIContext() + guard let ciImage = CIImage(image: self), + let clampFilter = CIFilter(name: "CIAffineClamp"), + let blurFilter = CIFilter(name: "CIGaussianBlur") else { + return self + } + clampFilter.setValue(ciImage, forKey: kCIInputImageKey) + blurFilter.setValue(clampFilter.outputImage, forKey: kCIInputImageKey) + blurFilter.setValue(radius, forKey: kCIInputRadiusKey) + guard let output = blurFilter.outputImage, + let cgimg = context.createCGImage(output, from: ciImage.extent) else { + return self + } + + return UIImage(cgImage: cgimg) + } +} +
Swift
Swift๋Š” ์นด๋ฉœ์ผ€์ด์Šค ~ ๐Ÿซ
@@ -21,3 +21,25 @@ extension UICollectionViewCell { NSStringFromClass(self.classForCoder()).components(separatedBy: ".").last! } } + +extension UIImage { + + func applyBlur_usingClamp(radius: CGFloat) -> UIImage { + let context = CIContext() + guard let ciImage = CIImage(image: self), + let clampFilter = CIFilter(name: "CIAffineClamp"), + let blurFilter = CIFilter(name: "CIGaussianBlur") else { + return self + } + clampFilter.setValue(ciImage, forKey: kCIInputImageKey) + blurFilter.setValue(clampFilter.outputImage, forKey: kCIInputImageKey) + blurFilter.setValue(radius, forKey: kCIInputRadiusKey) + guard let output = blurFilter.outputImage, + let cgimg = context.createCGImage(output, from: ciImage.extent) else { + return self + } + + return UIImage(cgImage: cgimg) + } +} +
Swift
๊ณ„์† extension์ด ๋Š˜์–ด๋‚  ์˜ˆ์ •์ด๋ผ๋ฉด UIImage+.swift ๋กœ ๋ณ„๋„๋กœ ๋นผ๋ฉด์–ด๋–จ๊นŒ์šฅ
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
```suggestion private let feedUpperBarStackView: UIStackView = { ``` class๊ฐ€ StackView์ธ๊ฑด ๋ฐ”๋กœ ์•Œ์•„๋ณด๋ฉด ์ฝ๊ธฐ ํŽธํ• ๊ฑฐ๊ฐ™์•„์šฉ
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
```suggestion ``` ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ฒŒ๋˜์—ˆ๋‹ค๋ฉด ์‚ญ์ œ
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
์—ฌ๊ธฐ์— ํ•œ์ค„์”ฉ ๋„ฃ๋Š”๊ฑด ์šฐ๋””๋งŒ์˜ ์Šคํƒ€์ผ์ธ๊ฑด๊ฐ€์š”? ๊ทธ์ € ๊ถ๊ธˆ์“ฐ
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
property์ด๋ฆ„๊ณผ ์ฃผ์„์ด ๊ฐ™๋‹ค๋ฉด ๊ฐ ์ฃผ์„์ด ์‚ฌ๋ผ์ ธ๋„ ๋˜์ง€ ์•Š์„๊นŒ์š” ..?
@@ -10,11 +10,11 @@ import UIKit class HomeViewController: UIViewController { private var feeds: [Feed] = [ - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]) + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]) ] private let feedCollectionView: UICollectionView = { @@ -79,13 +79,14 @@ extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSour return cell } + // Cell Spacing func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 30.0 } // Cell size func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { - return CGSize(width: view.bounds.width - 32.0, height: 524) + return CGSize(width: view.bounds.width - 32.0, height: 550) } }
Swift
์˜๋ฏธ๋Š” ์—†์๋‹ˆ๋‹ค.. ๋ˆˆ์œผ๋กœ ๋Œ€๊ฐ• height ์Ÿ€์Šต๋‹ˆ๋‹ค let์œผ๋กœ ๋ณ€์ˆ˜ ์„ ์–ธํ•˜๋Š”๊ฒƒ์€ ํ•ด๋‹น func ๋‚ด๋ถ€์— ์„ ์–ธํ•˜๋Š” ๊ฒƒ์ด ์ข‹๊ฒ ์ฃ ?
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
์œ„์— ์ฃผ์„ ๋ง์”€์ด์‹ ๊ฐ€์š”?
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
์ฃผ์„์€ ์ €์—๊ฒŒ ์ผ์ข…์˜ ์˜์—ญ ํ‘œ์‹œ์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค ๊ตณ์ด ์กด์žฌํ•˜์ง€ ์•Š์•„๋„ ๋ ์ˆ˜๋„ ์žˆ์ง€๋งŒ ์—ฌ๊ธฐ ๋ญ”๊ฐ€๊ฐ€ ์žˆ๋‹ค๋ผ๋Š” ๋А๋‚Œ์ ์ธ ๋А๋‚Œ์ด๋ž„๊นŒ์š”
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
ํ‚ค์›Œ๋“œ๋ฅผ ์—ฌ๋Ÿฌ๊ฐœ ๋ถ™์—ฌ๋„ ๋˜๋Š”๊ตฐ์š”? ์ƒ๊ฐ๋„ ์•ˆํ•ด๋ดค์Šต๋‹ˆ๋‹ค
@@ -10,11 +10,11 @@ import UIKit class HomeViewController: UIViewController { private var feeds: [Feed] = [ - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), - Feed(username: "Woody", profileImage: "profileImage", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]) + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]), + Feed(username: "Woody", profileImage: "profileImage", image: "wooluck", author: "alice", title: "์šฐ๋Ÿญ๋จน๋‹ค ๋ฐ›์€ ์˜๊ฐ", hashTags: [HashTag(hashTag: "#Guitar"), HashTag(hashTag: "#Jazz")]) ] private let feedCollectionView: UICollectionView = { @@ -79,13 +79,14 @@ extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSour return cell } + // Cell Spacing func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 30.0 } // Cell size func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { - return CGSize(width: view.bounds.width - 32.0, height: 524) + return CGSize(width: view.bounds.width - 32.0, height: 550) } }
Swift
> ๋ˆˆ์œผ๋กœ ๋Œ€๊ฐ• height ์Ÿ€์Šต๋‹ˆ๋‹ค ๐Ÿค” ..????? > let์œผ๋กœ ๋ณ€์ˆ˜ ์„ ์–ธํ•˜๋Š”๊ฒƒ์€ ํ•ด๋‹น func ๋‚ด๋ถ€์— ์„ ์–ธํ•˜๋Š” ๊ฒƒ์ด ์ข‹๊ฒ ์ฃ ? ๋ฌผ๋ก ์ด์ฃ  !
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
L60๊ณผ ๊ฐ™์€ ๊ฐœํ–‰ ์ด์•ผ๊ธฐ๋“œ๋ฆฐ๊ฑฐ์˜€์–ด์š” !
@@ -20,27 +20,106 @@ class FeedCollectionViewCell: UICollectionViewCell { return stackView }() - // ์ƒ๋‹จ + // UpperBar private let feedUpperBar: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fill stackView.spacing = 8.0 stackView.translatesAutoresizingMaskIntoConstraints = false + return stackView }() + + // ContentView +// private let feedContentView: UIStackView = { +// +// let stackView = UIStackView() +// stackView.axis = .vertical +// stackView.alignment = .center +// stackView.translatesAutoresizingMaskIntoConstraints = false +// stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) +// stackView.layer.borderWidth = 1 +// +// return stackView +// }() - // ์ƒ๋‹จ ์•„๋ž˜ ํ”„๋ ˆ์ž„ - private let feedContentView: UIStackView = { + private let feedContentView: UIView = { - let stackView = UIStackView() - stackView.axis = .vertical - stackView.distribution = .fill - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) - stackView.layer.borderWidth = 1 - return stackView + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + uiView.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1) + uiView.layer.borderWidth = 1 + + return uiView + }() + + // feedContentViewUIView + private let feedContentViewUIView: UIView = { + + let uiView = UIView() + uiView.translatesAutoresizingMaskIntoConstraints = false + + return uiView + }() + + // feedContentViewImageView + private let feedContentViewImageView: UIImageView = { + + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.translatesAutoresizingMaskIntoConstraints = false + + return imageView + }() + + // feedContentViewTranslucenceView + private let feedContentViewTranslucenceView: UIView = { + + let uiView = UIView() + uiView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7) + uiView.translatesAutoresizingMaskIntoConstraints = false + return uiView + }() + + // feedContentViewTitleView + private let feedContentViewTitleView: UILabel = { + + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .left + return label + }() + + // feedContentViewAuthorView + private let feedContentViewAuthorView: UILabel = { + + let label = UILabel() + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // feedContentViewPauseOrPlayView + private let feedContentViewPauseOrPlayView: UIButton = { + + let button = UIButton() + let image = UIImage(systemName: "play.fill") + button.setImage(image, for: .normal) + button.tintColor = .white + button.setPreferredSymbolConfiguration(.init(pointSize: 30, weight: .regular, scale: .default), forImageIn: .normal) + button.translatesAutoresizingMaskIntoConstraints = false + + return button + }() + + // feedContentViewProgressBarView + private let feedContentViewProgressBarView: UISlider = { + + let progressBar = UISlider() + progressBar.translatesAutoresizingMaskIntoConstraints = false + return progressBar }() // username @@ -53,12 +132,14 @@ class FeedCollectionViewCell: UICollectionViewCell { return label }() + private let feedUpperBarHeight: CGFloat = 42 + // profileImage - private let profileImage: UIImageView = { + lazy var profileImage: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill - imageView.layer.cornerRadius = 15 + imageView.layer.cornerRadius = feedUpperBarHeight / 2 imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false @@ -83,14 +164,17 @@ class FeedCollectionViewCell: UICollectionViewCell { super.init(frame: frame) configureFeedView() - } // configure func configure(with feed: Feed) { username.text = feed.username profileImage.image = UIImage(named: feed.profileImage) + let image = UIImage(named: feed.image) + feedContentViewImageView.image = image?.applyBlur_usingClamp(radius: 5) + feedContentViewTitleView.text = feed.title + feedContentViewAuthorView.text = feed.author } required init?(coder: NSCoder) { @@ -103,10 +187,11 @@ private extension FeedCollectionViewCell { func configureFeedView() { // ์ „์ฒด contentView.addSubview(feedView) - + addItemsInfeedView() addItemsInFeedUpperBar() - + addItemsInFeedContentView() + applyConstraints() } @@ -120,48 +205,125 @@ private extension FeedCollectionViewCell { .forEach { feedUpperBar.addArrangedSubview($0) } } + func addItemsInFeedContentView() { + + // feedContentView + [ + feedContentViewUIView, + feedContentViewAuthorView, + feedContentViewPauseOrPlayView, + feedContentViewProgressBarView + ] + .forEach { feedContentView.addSubview($0) } + + // feedContentViewUIView + [ + feedContentViewImageView, + feedContentViewTranslucenceView, + feedContentViewTitleView, + ] + .forEach { feedContentViewUIView.addSubview($0) } + } + func applyConstraints() { - + + // ์ „์ฒด let feedViewContraints = [ feedView.leadingAnchor.constraint(equalTo: leadingAnchor), feedView.trailingAnchor.constraint(equalTo: trailingAnchor), feedView.topAnchor.constraint(equalTo: topAnchor), feedView.bottomAnchor.constraint(equalTo: bottomAnchor) ] + // UpperBar let feedUpperBarContraints = [ - feedUpperBar.heightAnchor.constraint(equalToConstant: 30.0), + feedUpperBar.heightAnchor.constraint(equalToConstant: feedUpperBarHeight), feedUpperBar.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] let profileImageConstraints = [ profileImage.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), - profileImage.widthAnchor.constraint(equalToConstant: 30) + profileImage.widthAnchor.constraint(equalToConstant: feedUpperBarHeight) ] let usernameConstraints = [ username.centerYAnchor.constraint(equalTo: feedUpperBar.centerYAnchor), ] let ellipsisButtonConstraints = [ - ellipsisButton.widthAnchor.constraint(equalToConstant: 30), - ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor), + ellipsisButton.widthAnchor.constraint(equalToConstant: feedUpperBarHeight), + ellipsisButton.heightAnchor.constraint(equalTo: feedUpperBar.heightAnchor) ] + // ContentView let feedContentViewConstraints = [ feedContentView.widthAnchor.constraint(equalTo: feedView.widthAnchor) ] + + // UIView + let feedContentViewUIViewConstraints = [ + feedContentViewUIView.widthAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.heightAnchor.constraint(equalTo: feedContentView.widthAnchor, constant: -16), + feedContentViewUIView.leftAnchor.constraint(equalTo: feedContentView.leftAnchor, constant: 8), + feedContentViewUIView.topAnchor.constraint(equalTo: feedContentView.topAnchor, constant: 8) + ] + + // image + let feedContentViewImageViewConstraints = [ + feedContentViewImageView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewImageView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // Translucence Filter + let feedContentViewTranslucenceViewConstraints = [ + feedContentViewTranslucenceView.widthAnchor.constraint(equalTo: feedContentViewUIView.widthAnchor), + feedContentViewTranslucenceView.heightAnchor.constraint(equalTo: feedContentViewUIView.heightAnchor) + ] + + // title + let feedContentViewTitleViewConstraints = [ + feedContentViewTitleView.centerXAnchor.constraint(equalTo: feedContentViewUIView.centerXAnchor), + feedContentViewTitleView.centerYAnchor.constraint(equalTo: feedContentViewUIView.centerYAnchor) + ] + + // author + let feedContentViewAuthorViewConstraints = [ + feedContentViewAuthorView.topAnchor.constraint(equalTo: feedContentViewUIView.bottomAnchor, constant: 8), + feedContentViewAuthorView.centerXAnchor.constraint(equalTo: feedContentView.centerXAnchor) + ] + + // playPauseButton + let feedContentViewPauseOrPlayViewConstraints = [ + feedContentViewPauseOrPlayView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewPauseOrPlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24) + ] + + // progressBar + let feedContentViewProgressBarViewConstraints = [ + feedContentViewProgressBarView.topAnchor.constraint(equalTo: feedContentViewAuthorView.bottomAnchor, constant: 8), + feedContentViewProgressBarView.leadingAnchor.constraint(equalTo: feedContentViewPauseOrPlayView.trailingAnchor, constant: 16), + feedContentViewProgressBarView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24) + ] [ + // FeedView feedViewContraints, + // UpperBar feedUpperBarContraints, profileImageConstraints, usernameConstraints, ellipsisButtonConstraints, + // Content - feedContentViewConstraints - feedViewContraints, + feedContentViewConstraints, + feedContentViewUIViewConstraints, + feedContentViewImageViewConstraints, + feedContentViewTranslucenceViewConstraints, + feedContentViewTitleViewConstraints, + feedContentViewAuthorViewConstraints, + feedContentViewPauseOrPlayViewConstraints, + feedContentViewProgressBarViewConstraints ].forEach { NSLayoutConstraint.activate($0) } } }
Swift
๊ฐœ์ธ์ ์ธ ์Šคํƒ€์ผ์ด๋„ค์š” ! ๐Ÿ™†
@@ -0,0 +1,29 @@ +import ItemCard from "@/components/ItemCard"; +import styled from "styled-components"; +import { flexCenter } from "@/styles/common"; +import { Product } from "@/types/products"; +import SeaOtterVideo from "@/components/SeaOtterVideo"; + +const ItemCardList = ({ products, isLoading }: { products: Product[]; isLoading: boolean }) => { + return ( + <ItemCardWrapper> + {products.length || isLoading ? ( + products.map((product) => <ItemCard key={Math.random() * 10000} product={product} />) + ) : ( + <> + <SeaOtterVideo /> + <h2>๐Ÿฆฆ ๋ˆˆ ์”ป๊ณ  ์ฐพ์•„๋ด๋„ ์ƒํ’ˆ์ด ์—†์–ด์š”.. ใ… ใ… </h2> + </> + )} + </ItemCardWrapper> + ); +}; + +export default ItemCardList; + +const ItemCardWrapper = styled.div` + display: flex; + gap: 14px; + flex-wrap: wrap; + ${flexCenter} +`;
Unknown
์—ฌ๊ธฐ์„œ product.id ๊ฐ€ key ๊ฐ’์ด ์•„๋‹ˆ๋ผ Math.random ์œผ๋กœ ์ฃผ์‹  ์ด์œ ๊ฐ€ ๋”ฐ๋กœ ์žˆ์œผ์‹ค๊นŒ์šฉ ??
@@ -0,0 +1,15 @@ +import * as S from "@/components/Header/style"; + +export const HeaderMain = ({ children }: React.PropsWithChildren) => { + return <S.Header>{children}</S.Header>; +}; + +export const Title = ({ text }: { text: string }) => { + return <S.Title>{text}</S.Title>; +}; + +const Header = Object.assign(HeaderMain, { + Title, +}); + +export default Header;
Unknown
๋„ˆ๋ฌด ์ข‹์•„์š”~!
@@ -0,0 +1,29 @@ +import ItemCard from "@/components/ItemCard"; +import styled from "styled-components"; +import { flexCenter } from "@/styles/common"; +import { Product } from "@/types/products"; +import SeaOtterVideo from "@/components/SeaOtterVideo"; + +const ItemCardList = ({ products, isLoading }: { products: Product[]; isLoading: boolean }) => { + return ( + <ItemCardWrapper> + {products.length || isLoading ? ( + products.map((product) => <ItemCard key={Math.random() * 10000} product={product} />) + ) : ( + <> + <SeaOtterVideo /> + <h2>๐Ÿฆฆ ๋ˆˆ ์”ป๊ณ  ์ฐพ์•„๋ด๋„ ์ƒํ’ˆ์ด ์—†์–ด์š”.. ใ… ใ… </h2> + </> + )} + </ItemCardWrapper> + ); +}; + +export default ItemCardList; + +const ItemCardWrapper = styled.div` + display: flex; + gap: 14px; + flex-wrap: wrap; + ${flexCenter} +`;
Unknown
์„œ๋ฒ„์—์„œ ๊ฐ„ํ—์ ์œผ๋กœ ์ค‘๋ณต๋œ key ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฌธ์ œ๊ฐ€ ์žˆ์–ด์„œ ํ•œ ๋ฒˆ์”ฉ ๋™์ผํ•œ key ๊ฐ’์œผ๋กœ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜๊ธฐ์— random ๊ฐ’์„ key ๋กœ ์„ค์ •ํ•ด์คฌ์–ด์š”!
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
๋„๋ฉ”์ธ์—์„œ view์— ์˜์กดํ•˜๋Š” ํ˜•ํƒœ๋ฅผ ๋„๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์‚ฌ์šฉ์ž ์ž…๋ ฅ ์ฒ˜๋ฆฌ์— ๋Œ€ํ•œ ๋ถ€๋ถ„์„ `MembershipManager` ์ฒ˜๋Ÿผ ์ปจํŠธ๋กค๋Ÿฌ๋กœ ๊บผ๋‚ด์–ด ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,88 @@ +package store.controller; + +import static store.constants.InputMessages.PRODUCTS_FILE_NAME; +import static store.constants.InputMessages.PROMOTIONS_FILE_NAME; + +import java.util.List; +import store.config.IoConfig; +import store.domain.Choice; +import store.domain.MembershipManager; +import store.domain.Product; +import store.domain.PromotionManager; +import store.domain.Receipt; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.InputView; +import store.io.OutputView; +import store.service.StoreService; + +public class StoreController { + + + private final InputView inputView; + private final OutputView outputView; + private StoreService service; + + public StoreController(IoConfig ioConfig) { + this.inputView = ioConfig.getInputView(); + this.outputView = ioConfig.getOutputView(); + } + + public void run() { + try { + storeOpen(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + + public void storeOpen() { + StoreHouse storeHouse = inputView.readProductsFileInput(PRODUCTS_FILE_NAME); + List<PromotionInfo> promotionInfos = inputView.readPromotionsFileInput(PROMOTIONS_FILE_NAME); + + PromotionManager promotionManager = new PromotionManager(promotionInfos, storeHouse, inputView); + MembershipManager membershipManager = new MembershipManager(storeHouse); + service = new StoreService(promotionManager, membershipManager); + + List<Product> allProduct = storeHouse.getProductList(); + processPurchase(allProduct, storeHouse, membershipManager); + } + + private void processPurchase(List<Product> allProduct, StoreHouse storeHouse, MembershipManager membershipManager) { + while (true) { + outputView.printProductList(allProduct); + Receipt receipt = getUserPurchase(storeHouse); + applyMembershipDiscount(receipt); + outputView.printReceipt(receipt, storeHouse, membershipManager); + if (inputView.readAdditionalPurchaseChoice().equals(Choice.N)) { + break; + } + } + } + + private Receipt getUserPurchase(StoreHouse storeHouse) { + while (true) { + List<Purchase> purchaseList = inputView.readProductNameAndQuantity(); + try { + return getReceipt(storeHouse, purchaseList); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private Receipt getReceipt(StoreHouse storeHouse, List<Purchase> purchaseList) { + Receipt receipt = service.purchase(purchaseList, storeHouse); + receipt.setPurchaseList(purchaseList); + return receipt; + } + + private void applyMembershipDiscount(Receipt receipt) { + Choice membershipDiscountApplicationChoice = inputView.readMembershipDiscountApplicationChoice(); + if (membershipDiscountApplicationChoice.equals(Choice.Y)) { + service.applyMembershipDiscount(receipt); + } + } + +}
Java
์ด ๋ฉ”์„œ๋“œ์—์„œ, ๊ตฌ๋งคํ•  ์ƒํ’ˆ๊ณผ ์ˆ˜๋Ÿ‰์„ ๋ฐ›์•„, Receipt๋ฅผ ๋งŒ๋“œ๋Š”๋ฐ ์ด ๊ณผ์ •์—์„œ, ํ”„๋กœ๋ชจ์…˜์— ๋Œ€ํ•œ ๊ธฐ๋Šฅ๋“ค์„ ์ฒ˜๋ฆฌํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋ฅผ ๋ถ„๋ฆฌํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”? ์‚ฌ์šฉ์ž๊ฐ€ ๊ตฌ๋งคํ•  ์ƒํ’ˆ๊ณผ ์ˆ˜๋Ÿ‰์„ ๋ฐ›์•„ ์ €์žฅํ•˜๊ณ , ์ด ์ €์žฅ๋œ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ํ”„๋กœ๋ชจ์…˜์„ ์ ์šฉํ•˜๋Š” ์ˆœ์„œ๋กœ์š”! ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด, ํ”„๋กœ๋ชจ์…˜ ์˜ˆ์™ธ์‚ฌํ•ญ์— ๋Œ€ํ•œ ์‚ฌ์šฉ์ž ์ž…๋ ฅ์„ ์ปจํŠธ๋กค๋Ÿฌ๋กœ ๋บ„ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค:)
@@ -0,0 +1,23 @@ +package store.constants; + +import static store.constants.StringConstants.NEW_LINE; +import static store.constants.StringConstants.ONE_SPACE; +import static store.constants.StringConstants.TAP; + +public class OutputMessages { + public static String WELCOME_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค." + NEW_LINE + "ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค." + NEW_LINE.repeat(2); + public static String PURCHASER_LIST_FORMAT = + "===========W ํŽธ์˜์ =============" + NEW_LINE + "์ƒํ’ˆ๋ช…" + TAP.repeat(2) + "์ˆ˜๋Ÿ‰" + TAP + "๊ธˆ์•ก" + NEW_LINE; + public static String FREEBIE_LIST_FORMAT = "===========์ฆ" + TAP + "์ •=============" + NEW_LINE; + public static String AMOUNT_INFORMATION_FORMAT = "==============================" + NEW_LINE; + + public static String TOTAL_PURCHASE_AMOUNT = "์ด๊ตฌ๋งค์•ก" + TAP.repeat(2); + public static String PROMOTION_DISCOUNT = "ํ–‰์‚ฌํ• ์ธ" + TAP.repeat(3); + public static String MEMBERSHIP_DISCOUNT = "๋ฉค๋ฒ„์‹ญํ• ์ธ" + TAP.repeat(3); + public static String TOTAL_PRICE = "๋‚ด์‹ค๋ˆ" + TAP.repeat(3) + ONE_SPACE; + + public static String CURRENCY_UNIT = "์›"; + public static String QUANTITY_UNIT = "๊ฐœ"; + public static String OUT_OF_STOCK = "์žฌ๊ณ  ์—†์Œ"; + +}
Java
์ด๋ ‡๊ฒŒ ์ž‘์€ ํ•˜๋“œ์ฝ”๋”ฉ ๋ฌธ์ž์—ด ๊ฐ™์€ ๊ฒฝ์šฐ์— ๋Œ€ํ•ด์„œ ํ•™๊ณผ ์„ ๋ฐฐ๋‹˜๊ป˜ ๋ฌผ์–ด๋ดค๋Š”๋ฐ, ์ด๋Ÿฐ ์ž‘์€ ๋ถ€๋ถ„(๋ฌธ์ž์—ด์„ ์กฐ๋ฆฝํ•ด์•ผํ•˜๋Š” ๋ถ€๋ถ„)์€ ๋งŽ์ง€ ์•Š์œผ๋ฉด ํด๋ž˜์Šค ๋‚ด์—์„œ ์„ ์–ธํ•˜๊ณ  ์“ด๋‹ค๋Š” ์˜๊ฒฌ์„ ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,88 @@ +package store.controller; + +import static store.constants.InputMessages.PRODUCTS_FILE_NAME; +import static store.constants.InputMessages.PROMOTIONS_FILE_NAME; + +import java.util.List; +import store.config.IoConfig; +import store.domain.Choice; +import store.domain.MembershipManager; +import store.domain.Product; +import store.domain.PromotionManager; +import store.domain.Receipt; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.InputView; +import store.io.OutputView; +import store.service.StoreService; + +public class StoreController { + + + private final InputView inputView; + private final OutputView outputView; + private StoreService service; + + public StoreController(IoConfig ioConfig) { + this.inputView = ioConfig.getInputView(); + this.outputView = ioConfig.getOutputView(); + } + + public void run() { + try { + storeOpen(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + + public void storeOpen() { + StoreHouse storeHouse = inputView.readProductsFileInput(PRODUCTS_FILE_NAME); + List<PromotionInfo> promotionInfos = inputView.readPromotionsFileInput(PROMOTIONS_FILE_NAME); + + PromotionManager promotionManager = new PromotionManager(promotionInfos, storeHouse, inputView); + MembershipManager membershipManager = new MembershipManager(storeHouse); + service = new StoreService(promotionManager, membershipManager); + + List<Product> allProduct = storeHouse.getProductList(); + processPurchase(allProduct, storeHouse, membershipManager); + } + + private void processPurchase(List<Product> allProduct, StoreHouse storeHouse, MembershipManager membershipManager) { + while (true) { + outputView.printProductList(allProduct); + Receipt receipt = getUserPurchase(storeHouse); + applyMembershipDiscount(receipt); + outputView.printReceipt(receipt, storeHouse, membershipManager); + if (inputView.readAdditionalPurchaseChoice().equals(Choice.N)) { + break; + } + } + } + + private Receipt getUserPurchase(StoreHouse storeHouse) { + while (true) { + List<Purchase> purchaseList = inputView.readProductNameAndQuantity(); + try { + return getReceipt(storeHouse, purchaseList); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private Receipt getReceipt(StoreHouse storeHouse, List<Purchase> purchaseList) { + Receipt receipt = service.purchase(purchaseList, storeHouse); + receipt.setPurchaseList(purchaseList); + return receipt; + } + + private void applyMembershipDiscount(Receipt receipt) { + Choice membershipDiscountApplicationChoice = inputView.readMembershipDiscountApplicationChoice(); + if (membershipDiscountApplicationChoice.equals(Choice.Y)) { + service.applyMembershipDiscount(receipt); + } + } + +}
Java
๋™์˜ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
๋„๋ฉ”์ธํด๋ž˜์Šค์˜ ์ฃผ์š”์ฑ…์ž„์€ '๋„๋ฉ”์ธ์„ ์ž˜ ํ‘œํ˜„ํ•ด๋‚ด๋Š” ๊ฒƒ'์ด๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. ํ•ด๋‹น ๋„๋ฉ”์ธ ํด๋ž˜์Šค๋Š” ๋งŽ์€ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์„ ํฌํ•จํ•˜๊ณ  ์žˆ์œผ๋ฏ€๋กœ, ๋‹จ์ผ์ฑ…์ž„์›์น™์ด ์œ„๋ฐฐ๋œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ์„œ๋น„์Šค๊ณ„์ธต์„ ๋„์ž…ํ•˜๊ฑฐ๋‚˜ ์ฑ…์ž„์„ ๋ถ„๋ฆฌํ•ด๋ณด๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,15 @@ +package store.constants; + +public class StringConstants { + public static final String COMMA = ","; + public static final String DASH = "-"; + public static final String NEW_LINE = "\n"; + public static final String TAP = "\t"; + public static final String OPEN_SQUARE_BRACKETS = "["; + public static final String CLOSE_SQUARE_BRACKETS = "]"; + public static final String EMPTY_STRING = ""; + public static final String ONE_SPACE = " "; + public static final String DATE_TIME_FORMATTER_PATTERN = "yyyy-MM-dd"; + public static final String NUMBER_FORMAT_WITH_COMMA = "%,d"; + +}
Java
๊ผผ๊ผผํ•œ ์ƒ์ˆ˜ ์ฒ˜๋ฆฌ! ๋ณผ ๋•Œ๋งˆ๋‹ค ๊ฐํƒ„์„ ์ž์•„๋ƒ…๋‹ˆ๋‹ค!
@@ -0,0 +1,88 @@ +package store.controller; + +import static store.constants.InputMessages.PRODUCTS_FILE_NAME; +import static store.constants.InputMessages.PROMOTIONS_FILE_NAME; + +import java.util.List; +import store.config.IoConfig; +import store.domain.Choice; +import store.domain.MembershipManager; +import store.domain.Product; +import store.domain.PromotionManager; +import store.domain.Receipt; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.InputView; +import store.io.OutputView; +import store.service.StoreService; + +public class StoreController { + + + private final InputView inputView; + private final OutputView outputView; + private StoreService service; + + public StoreController(IoConfig ioConfig) { + this.inputView = ioConfig.getInputView(); + this.outputView = ioConfig.getOutputView(); + } + + public void run() { + try { + storeOpen(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + + public void storeOpen() { + StoreHouse storeHouse = inputView.readProductsFileInput(PRODUCTS_FILE_NAME); + List<PromotionInfo> promotionInfos = inputView.readPromotionsFileInput(PROMOTIONS_FILE_NAME); + + PromotionManager promotionManager = new PromotionManager(promotionInfos, storeHouse, inputView); + MembershipManager membershipManager = new MembershipManager(storeHouse); + service = new StoreService(promotionManager, membershipManager); + + List<Product> allProduct = storeHouse.getProductList(); + processPurchase(allProduct, storeHouse, membershipManager); + } + + private void processPurchase(List<Product> allProduct, StoreHouse storeHouse, MembershipManager membershipManager) { + while (true) { + outputView.printProductList(allProduct); + Receipt receipt = getUserPurchase(storeHouse); + applyMembershipDiscount(receipt); + outputView.printReceipt(receipt, storeHouse, membershipManager); + if (inputView.readAdditionalPurchaseChoice().equals(Choice.N)) { + break; + } + } + } + + private Receipt getUserPurchase(StoreHouse storeHouse) { + while (true) { + List<Purchase> purchaseList = inputView.readProductNameAndQuantity(); + try { + return getReceipt(storeHouse, purchaseList); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private Receipt getReceipt(StoreHouse storeHouse, List<Purchase> purchaseList) { + Receipt receipt = service.purchase(purchaseList, storeHouse); + receipt.setPurchaseList(purchaseList); + return receipt; + } + + private void applyMembershipDiscount(Receipt receipt) { + Choice membershipDiscountApplicationChoice = inputView.readMembershipDiscountApplicationChoice(); + if (membershipDiscountApplicationChoice.equals(Choice.Y)) { + service.applyMembershipDiscount(receipt); + } + } + +}
Java
์—๋Ÿฌ ๋ฉ”์‹œ์ง€ ์ถœ๋ ฅ ๋ถ€๋ถ„๋„ OutputView ๋กœ ๋นผ์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
setQuantity์™€ setPromotionPeriods ๋ฉ”์„œ๋“œ๊ฐ€ ์ •์  ๋ฉ”์„œ๋“œ๋กœ ๋ณด์ด๋Š”๋ฐ ์ •์  ๋ฉ”์„œ๋“œ๋Š” ์ƒํƒœ ๋ณ€๊ฒฝ์— ์‚ฌ์šฉ๋˜๋ฉด ๊ฐ์ฒด์ง€ํ–ฅ์›์น™์— ๋งž์ง€ ์•Š์•„ ์•ˆ ์ข‹๋‹ค๊ณ  ์•Œ๊ณ ์žˆ์Šต๋‹ˆ๋‹ค Promotion ๊ฐ์ฒด๋ฅผ ์ธ์Šคํ„ด์Šคํ™”ํ•˜์—ฌ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
๋„๋ฉ”์ธ์—์„œ ๋ทฐ์— ์˜์กดํ•˜๋Š” ํ˜•ํƒœ๋Š” ์ข‹์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,60 @@ +package store.domain; + +import static camp.nextstep.edu.missionutils.DateTimes.now; + +import java.time.LocalDateTime; + +public enum Promotion { + + NULL(""), + SPARKLING_BUY_TWO_GET_ONE_FREE("ํƒ„์‚ฐ2+1"), + MD_RECOMMENDATION("MD์ถ”์ฒœ์ƒํ’ˆ"), + FLASH_SALE("๋ฐ˜์งํ• ์ธ"); + + private final String promotionName; + private int buyQuantity; + private int getQuantity; + private LocalDateTime startDateTime; + private LocalDateTime endDateTime; + + Promotion(String promotionName) { + this.promotionName = promotionName; + } + + static void setQuantity(Promotion promotionName, int buyQuantity, int getQuantity) { + promotionName.buyQuantity = buyQuantity; + promotionName.getQuantity = getQuantity; + } + + static void setPromotionPeriods(Promotion promotionName, LocalDateTime startDateTime, + LocalDateTime endDateTime) { + promotionName.startDateTime = startDateTime; + promotionName.endDateTime = endDateTime; + } + + public static boolean isPromotionValid(Promotion promotionName) { + LocalDateTime now = now(); + return !now.isBefore(promotionName.startDateTime) && !now.isAfter(promotionName.endDateTime); + } + + public String getPromotionName() { + return promotionName; + } + + public int getBuyQuantity() { + return buyQuantity; + } + + public int getGetQuantity() { + return getQuantity; + } + + public LocalDateTime getStartDateTime() { + return startDateTime; + } + + public LocalDateTime getEndDateTime() { + return endDateTime; + } + +}
Java
์ €๋Š” ํ”„๋กœ๋ชจ์…˜์ด ๋™์ ์œผ๋กœ ๊ฐ’์ด ๋ฐ”๋€” ์ˆ˜ ์žˆ๋‹ค๋Š” ์กฐ๊ฑด ๋•Œ๋ฌธ์— ํ”„๋กœ๋ชจ์…˜ ๊ฐ’์ด ๋ฐ”๋€๋‹ค๋ฉด ์ฝ”๋“œ๋ฅผ ์‹น ๋‹ค ๋ฐ”๊ฟ”์ค˜์•ผ ํ•ด์„œ enum์—๋Š” ๋งž์ง€ ์•Š๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค ์ง€์šฐ๋‹˜์€ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,48 @@ +package store.domain; + +import static store.constants.NumberConstants.SINGLE_PRODUCT_QUANTITY; + +import java.util.ArrayList; +import java.util.List; +import store.exception.ProductNotExistException; + +public class StoreHouse { + + private final List<Product> productList = new ArrayList<>(); + + + public void buy(Product product, int quantity) { + product.sell(quantity); + } + + public List<Product> findProductByName(String productName) { + List<Product> filteredProduct = productList.stream() + .filter(product -> product.getName().equals(productName)) + .toList(); + + if (filteredProduct.isEmpty()) { + throw new ProductNotExistException(); + } + + return filteredProduct; + } + + public boolean checkRegularPricePurchase(String productName) { + int count = (int) productList.stream() + .filter(product -> product.getName().equals(productName)) + .count(); + List<Product> products = findProductByName(productName); + Promotion promotionName = products.getFirst().getPromotionName(); + + return count == SINGLE_PRODUCT_QUANTITY && promotionName.equals(Promotion.NULL); + } + + public void addProduct(Product product) { + productList.add(product); + } + + public List<Product> getProductList() { + return productList; + } +} +
Java
์ด๋ฆ„์œผ๋กœ product๋ฅผ ์ฐพ์„๊ฑฐ๋ผ๋ฉด List<Product>๋ณด๋‹ค Map<String, Product>๋Š” ์–ด๋–จ๊นŒ์š”?
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
๋™์˜ํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,88 @@ +package store.controller; + +import static store.constants.InputMessages.PRODUCTS_FILE_NAME; +import static store.constants.InputMessages.PROMOTIONS_FILE_NAME; + +import java.util.List; +import store.config.IoConfig; +import store.domain.Choice; +import store.domain.MembershipManager; +import store.domain.Product; +import store.domain.PromotionManager; +import store.domain.Receipt; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.InputView; +import store.io.OutputView; +import store.service.StoreService; + +public class StoreController { + + + private final InputView inputView; + private final OutputView outputView; + private StoreService service; + + public StoreController(IoConfig ioConfig) { + this.inputView = ioConfig.getInputView(); + this.outputView = ioConfig.getOutputView(); + } + + public void run() { + try { + storeOpen(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + + public void storeOpen() { + StoreHouse storeHouse = inputView.readProductsFileInput(PRODUCTS_FILE_NAME); + List<PromotionInfo> promotionInfos = inputView.readPromotionsFileInput(PROMOTIONS_FILE_NAME); + + PromotionManager promotionManager = new PromotionManager(promotionInfos, storeHouse, inputView); + MembershipManager membershipManager = new MembershipManager(storeHouse); + service = new StoreService(promotionManager, membershipManager); + + List<Product> allProduct = storeHouse.getProductList(); + processPurchase(allProduct, storeHouse, membershipManager); + } + + private void processPurchase(List<Product> allProduct, StoreHouse storeHouse, MembershipManager membershipManager) { + while (true) { + outputView.printProductList(allProduct); + Receipt receipt = getUserPurchase(storeHouse); + applyMembershipDiscount(receipt); + outputView.printReceipt(receipt, storeHouse, membershipManager); + if (inputView.readAdditionalPurchaseChoice().equals(Choice.N)) { + break; + } + } + } + + private Receipt getUserPurchase(StoreHouse storeHouse) { + while (true) { + List<Purchase> purchaseList = inputView.readProductNameAndQuantity(); + try { + return getReceipt(storeHouse, purchaseList); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private Receipt getReceipt(StoreHouse storeHouse, List<Purchase> purchaseList) { + Receipt receipt = service.purchase(purchaseList, storeHouse); + receipt.setPurchaseList(purchaseList); + return receipt; + } + + private void applyMembershipDiscount(Receipt receipt) { + Choice membershipDiscountApplicationChoice = inputView.readMembershipDiscountApplicationChoice(); + if (membershipDiscountApplicationChoice.equals(Choice.Y)) { + service.applyMembershipDiscount(receipt); + } + } + +}
Java
๋™์˜ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,115 @@ +package store.io; + +import static store.constants.InputMessages.ADDITIONAL_PURCHASE_MESSAGE; +import static store.constants.InputMessages.FREEBIE_ADDITION_MESSAGE; +import static store.constants.InputMessages.INPUT_PRODUCT_NAME_AND_QUANTITY; +import static store.constants.InputMessages.MEMBERSHIP_DISCOUNT_CHOICE_MESSAGE; +import static store.constants.InputMessages.REGULAR_PRICE_BUY_MESSAGE; +import static store.constants.StringConstants.NEW_LINE; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import store.domain.Choice; +import store.domain.Product; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.parser.InputParser; +import store.io.parser.ProductsFileLineParser; +import store.io.parser.PromotionsFileLineParser; +import store.io.reader.FileReader; +import store.io.reader.Reader; +import store.io.writer.Writer; + +public class InputView { + + private final Reader reader; + private final Writer writer; + private final InputValidator validator; + + public InputView(Reader reader, Writer writer, InputValidator validator) { + this.reader = reader; + this.writer = writer; + this.validator = validator; + } + + public StoreHouse readProductsFileInput(String fileName) { + try { + return readProductsFile(fileName); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private StoreHouse readProductsFile(String fileName) throws IOException { + Reader reader = new FileReader(fileName); + reader.readLine(); + String line; + StoreHouse storeHouse = new StoreHouse(); + while ((line = reader.readLine()) != null) { + Product product = new ProductsFileLineParser(line).parseLine(); + storeHouse.addProduct(product); + } + return storeHouse; + } + + public List<PromotionInfo> readPromotionsFileInput(String fileName) { + try { + return readPromotionsFile(fileName); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private List<PromotionInfo> readPromotionsFile(String fileName) throws IOException { + Reader reader = new FileReader(fileName); + reader.readLine(); + String line; + List<PromotionInfo> promotionInfos = new ArrayList<>(); + while ((line = reader.readLine()) != null) { + promotionInfos.add(new PromotionsFileLineParser(line).parseLine()); + } + return promotionInfos; + } + + public List<Purchase> readProductNameAndQuantity() { + writer.write(INPUT_PRODUCT_NAME_AND_QUANTITY); + String inputProductAndQuantity = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(inputProductAndQuantity); + return new InputParser().parse(inputProductAndQuantity); + } + + public Choice readFreebieAdditionChoice(String productName) { + writer.write(String.format(FREEBIE_ADDITION_MESSAGE, productName)); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readRegularPricePaymentChoice(String productName, int quantity) { + writer.write(String.format(REGULAR_PRICE_BUY_MESSAGE, productName, quantity)); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readMembershipDiscountApplicationChoice() { + writer.write(MEMBERSHIP_DISCOUNT_CHOICE_MESSAGE); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readAdditionalPurchaseChoice() { + writer.write(ADDITIONAL_PURCHASE_MESSAGE); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } +}
Java
inputView๋Š” ์‚ฌ์šฉ์ž๋กœ๋ถ€ํ„ฐ ์ž…๋ ฅ์„ ๋ฐ›๋Š” UI ์—ญํ• ๋กœ, ํŒŒ์ผ์„ ์ฝ๊ณ  ๋ฐ์ดํ„ฐ๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ณผ์ •์€ parser๋กœ ๋นผ์ฃผ์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! (ํŒŒ์ผ ์ฝ๊ธฐ๋Š” FileReader๋กœ, ํ•ด๋‹น ํŒŒ์ผ์˜ ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ๋Š” parser๋กœ!) ์•„๋‹ˆ๋ฉด setup service๋ฅผ ๋งŒ๋“ค์–ด์„œ ๊ทธ๊ณณ์—์„œ setup์„ ์ง„ํ–‰ํ•˜๊ณ  controller์—์„œ ๋ถˆ๋Ÿฌ์˜ค๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ๊ทธ๋ฆฌ๊ณ  ํŒŒ์ผ ์ฝ๊ธฐ ๊ธฐ๋Šฅ์„ ์ค„ ๋‹จ์œ„๋กœ ์ฝ์–ด์™€ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์€ ๋ฐฉ๋ฒ•์ด์ง€๋งŒ, readAllLines (์ง€์šฐ๋‹˜๊ป˜์„œ ๋ฆฌ๋ทฐ ํ•ด์ฃผ์…จ๋˜!) ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ํ•œ๋ฒˆ์— ์ฝ์–ด์™€์„œ ์ฝ”๋“œ๋ฅผ ์ฝ์–ด์˜ค๋Š” ๋ถ€๋ถ„์„ ๋‹จ์ถ• ์‹œํ‚ฌ ์ˆ˜ ์žˆ๋‹ต๋‹ˆ๋‹ค!
@@ -0,0 +1,115 @@ +package store.io; + +import static store.constants.InputMessages.ADDITIONAL_PURCHASE_MESSAGE; +import static store.constants.InputMessages.FREEBIE_ADDITION_MESSAGE; +import static store.constants.InputMessages.INPUT_PRODUCT_NAME_AND_QUANTITY; +import static store.constants.InputMessages.MEMBERSHIP_DISCOUNT_CHOICE_MESSAGE; +import static store.constants.InputMessages.REGULAR_PRICE_BUY_MESSAGE; +import static store.constants.StringConstants.NEW_LINE; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import store.domain.Choice; +import store.domain.Product; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.parser.InputParser; +import store.io.parser.ProductsFileLineParser; +import store.io.parser.PromotionsFileLineParser; +import store.io.reader.FileReader; +import store.io.reader.Reader; +import store.io.writer.Writer; + +public class InputView { + + private final Reader reader; + private final Writer writer; + private final InputValidator validator; + + public InputView(Reader reader, Writer writer, InputValidator validator) { + this.reader = reader; + this.writer = writer; + this.validator = validator; + } + + public StoreHouse readProductsFileInput(String fileName) { + try { + return readProductsFile(fileName); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private StoreHouse readProductsFile(String fileName) throws IOException { + Reader reader = new FileReader(fileName); + reader.readLine(); + String line; + StoreHouse storeHouse = new StoreHouse(); + while ((line = reader.readLine()) != null) { + Product product = new ProductsFileLineParser(line).parseLine(); + storeHouse.addProduct(product); + } + return storeHouse; + } + + public List<PromotionInfo> readPromotionsFileInput(String fileName) { + try { + return readPromotionsFile(fileName); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private List<PromotionInfo> readPromotionsFile(String fileName) throws IOException { + Reader reader = new FileReader(fileName); + reader.readLine(); + String line; + List<PromotionInfo> promotionInfos = new ArrayList<>(); + while ((line = reader.readLine()) != null) { + promotionInfos.add(new PromotionsFileLineParser(line).parseLine()); + } + return promotionInfos; + } + + public List<Purchase> readProductNameAndQuantity() { + writer.write(INPUT_PRODUCT_NAME_AND_QUANTITY); + String inputProductAndQuantity = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(inputProductAndQuantity); + return new InputParser().parse(inputProductAndQuantity); + } + + public Choice readFreebieAdditionChoice(String productName) { + writer.write(String.format(FREEBIE_ADDITION_MESSAGE, productName)); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readRegularPricePaymentChoice(String productName, int quantity) { + writer.write(String.format(REGULAR_PRICE_BUY_MESSAGE, productName, quantity)); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readMembershipDiscountApplicationChoice() { + writer.write(MEMBERSHIP_DISCOUNT_CHOICE_MESSAGE); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readAdditionalPurchaseChoice() { + writer.write(ADDITIONAL_PURCHASE_MESSAGE); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } +}
Java
์ถ”๊ฐ€๋กœ validator์˜ empty input์„ ๊ฒ€์‚ฌํ•˜๋Š” ๋ฉ”์„œ๋“œ์˜ ๊ฒฝ์šฐ, parser์— ํฌํ•จ ์‹œํ‚ค๋Š” ๊ฒƒ์ด ์–ด๋–จ๊นŒ์š”? parser๋Š” ์ž…๋ ฅ ๊ฐ’์„ ํ•ด์„ํ•˜๊ณ , ์ ์ ˆํ•œ ํ˜•์‹์œผ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ์ฑ…์ž„์„ ๊ฐ€์ง€๋ฏ€๋กœ ์ž…๋ ฅ ๊ฐ’์˜ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ํ•˜๋Š” ๊ฒƒ๋„ ๊ทธ ์ฑ…์ž„์— ๋งž๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,88 @@ +package store.controller; + +import static store.constants.InputMessages.PRODUCTS_FILE_NAME; +import static store.constants.InputMessages.PROMOTIONS_FILE_NAME; + +import java.util.List; +import store.config.IoConfig; +import store.domain.Choice; +import store.domain.MembershipManager; +import store.domain.Product; +import store.domain.PromotionManager; +import store.domain.Receipt; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.InputView; +import store.io.OutputView; +import store.service.StoreService; + +public class StoreController { + + + private final InputView inputView; + private final OutputView outputView; + private StoreService service; + + public StoreController(IoConfig ioConfig) { + this.inputView = ioConfig.getInputView(); + this.outputView = ioConfig.getOutputView(); + } + + public void run() { + try { + storeOpen(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + + public void storeOpen() { + StoreHouse storeHouse = inputView.readProductsFileInput(PRODUCTS_FILE_NAME); + List<PromotionInfo> promotionInfos = inputView.readPromotionsFileInput(PROMOTIONS_FILE_NAME); + + PromotionManager promotionManager = new PromotionManager(promotionInfos, storeHouse, inputView); + MembershipManager membershipManager = new MembershipManager(storeHouse); + service = new StoreService(promotionManager, membershipManager); + + List<Product> allProduct = storeHouse.getProductList(); + processPurchase(allProduct, storeHouse, membershipManager); + } + + private void processPurchase(List<Product> allProduct, StoreHouse storeHouse, MembershipManager membershipManager) { + while (true) { + outputView.printProductList(allProduct); + Receipt receipt = getUserPurchase(storeHouse); + applyMembershipDiscount(receipt); + outputView.printReceipt(receipt, storeHouse, membershipManager); + if (inputView.readAdditionalPurchaseChoice().equals(Choice.N)) { + break; + } + } + } + + private Receipt getUserPurchase(StoreHouse storeHouse) { + while (true) { + List<Purchase> purchaseList = inputView.readProductNameAndQuantity(); + try { + return getReceipt(storeHouse, purchaseList); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private Receipt getReceipt(StoreHouse storeHouse, List<Purchase> purchaseList) { + Receipt receipt = service.purchase(purchaseList, storeHouse); + receipt.setPurchaseList(purchaseList); + return receipt; + } + + private void applyMembershipDiscount(Receipt receipt) { + Choice membershipDiscountApplicationChoice = inputView.readMembershipDiscountApplicationChoice(); + if (membershipDiscountApplicationChoice.equals(Choice.Y)) { + service.applyMembershipDiscount(receipt); + } + } + +}
Java
๋™์˜ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
๋™์˜ํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,23 @@ +package store.constants; + +import static store.constants.StringConstants.NEW_LINE; +import static store.constants.StringConstants.ONE_SPACE; +import static store.constants.StringConstants.TAP; + +public class OutputMessages { + public static String WELCOME_MESSAGE = "์•ˆ๋…•ํ•˜์„ธ์š”. WํŽธ์˜์ ์ž…๋‹ˆ๋‹ค." + NEW_LINE + "ํ˜„์žฌ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค." + NEW_LINE.repeat(2); + public static String PURCHASER_LIST_FORMAT = + "===========W ํŽธ์˜์ =============" + NEW_LINE + "์ƒํ’ˆ๋ช…" + TAP.repeat(2) + "์ˆ˜๋Ÿ‰" + TAP + "๊ธˆ์•ก" + NEW_LINE; + public static String FREEBIE_LIST_FORMAT = "===========์ฆ" + TAP + "์ •=============" + NEW_LINE; + public static String AMOUNT_INFORMATION_FORMAT = "==============================" + NEW_LINE; + + public static String TOTAL_PURCHASE_AMOUNT = "์ด๊ตฌ๋งค์•ก" + TAP.repeat(2); + public static String PROMOTION_DISCOUNT = "ํ–‰์‚ฌํ• ์ธ" + TAP.repeat(3); + public static String MEMBERSHIP_DISCOUNT = "๋ฉค๋ฒ„์‹ญํ• ์ธ" + TAP.repeat(3); + public static String TOTAL_PRICE = "๋‚ด์‹ค๋ˆ" + TAP.repeat(3) + ONE_SPACE; + + public static String CURRENCY_UNIT = "์›"; + public static String QUANTITY_UNIT = "๊ฐœ"; + public static String OUT_OF_STOCK = "์žฌ๊ณ  ์—†์Œ"; + +}
Java
์˜ค ๊ทธ๋ ‡๊ตฐ์š”. ์ฐธ๊ณ ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,15 @@ +package store.constants; + +public class StringConstants { + public static final String COMMA = ","; + public static final String DASH = "-"; + public static final String NEW_LINE = "\n"; + public static final String TAP = "\t"; + public static final String OPEN_SQUARE_BRACKETS = "["; + public static final String CLOSE_SQUARE_BRACKETS = "]"; + public static final String EMPTY_STRING = ""; + public static final String ONE_SPACE = " "; + public static final String DATE_TIME_FORMATTER_PATTERN = "yyyy-MM-dd"; + public static final String NUMBER_FORMAT_WITH_COMMA = "%,d"; + +}
Java
์นญ์ฐฌ,,, ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿฅน
@@ -0,0 +1,88 @@ +package store.controller; + +import static store.constants.InputMessages.PRODUCTS_FILE_NAME; +import static store.constants.InputMessages.PROMOTIONS_FILE_NAME; + +import java.util.List; +import store.config.IoConfig; +import store.domain.Choice; +import store.domain.MembershipManager; +import store.domain.Product; +import store.domain.PromotionManager; +import store.domain.Receipt; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.InputView; +import store.io.OutputView; +import store.service.StoreService; + +public class StoreController { + + + private final InputView inputView; + private final OutputView outputView; + private StoreService service; + + public StoreController(IoConfig ioConfig) { + this.inputView = ioConfig.getInputView(); + this.outputView = ioConfig.getOutputView(); + } + + public void run() { + try { + storeOpen(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + + public void storeOpen() { + StoreHouse storeHouse = inputView.readProductsFileInput(PRODUCTS_FILE_NAME); + List<PromotionInfo> promotionInfos = inputView.readPromotionsFileInput(PROMOTIONS_FILE_NAME); + + PromotionManager promotionManager = new PromotionManager(promotionInfos, storeHouse, inputView); + MembershipManager membershipManager = new MembershipManager(storeHouse); + service = new StoreService(promotionManager, membershipManager); + + List<Product> allProduct = storeHouse.getProductList(); + processPurchase(allProduct, storeHouse, membershipManager); + } + + private void processPurchase(List<Product> allProduct, StoreHouse storeHouse, MembershipManager membershipManager) { + while (true) { + outputView.printProductList(allProduct); + Receipt receipt = getUserPurchase(storeHouse); + applyMembershipDiscount(receipt); + outputView.printReceipt(receipt, storeHouse, membershipManager); + if (inputView.readAdditionalPurchaseChoice().equals(Choice.N)) { + break; + } + } + } + + private Receipt getUserPurchase(StoreHouse storeHouse) { + while (true) { + List<Purchase> purchaseList = inputView.readProductNameAndQuantity(); + try { + return getReceipt(storeHouse, purchaseList); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private Receipt getReceipt(StoreHouse storeHouse, List<Purchase> purchaseList) { + Receipt receipt = service.purchase(purchaseList, storeHouse); + receipt.setPurchaseList(purchaseList); + return receipt; + } + + private void applyMembershipDiscount(Receipt receipt) { + Choice membershipDiscountApplicationChoice = inputView.readMembershipDiscountApplicationChoice(); + if (membershipDiscountApplicationChoice.equals(Choice.Y)) { + service.applyMembershipDiscount(receipt); + } + } + +}
Java
๋†“์นœ ๋ถ€๋ถ„ ์งš์–ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :)
@@ -0,0 +1,88 @@ +package store.controller; + +import static store.constants.InputMessages.PRODUCTS_FILE_NAME; +import static store.constants.InputMessages.PROMOTIONS_FILE_NAME; + +import java.util.List; +import store.config.IoConfig; +import store.domain.Choice; +import store.domain.MembershipManager; +import store.domain.Product; +import store.domain.PromotionManager; +import store.domain.Receipt; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.InputView; +import store.io.OutputView; +import store.service.StoreService; + +public class StoreController { + + + private final InputView inputView; + private final OutputView outputView; + private StoreService service; + + public StoreController(IoConfig ioConfig) { + this.inputView = ioConfig.getInputView(); + this.outputView = ioConfig.getOutputView(); + } + + public void run() { + try { + storeOpen(); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + + public void storeOpen() { + StoreHouse storeHouse = inputView.readProductsFileInput(PRODUCTS_FILE_NAME); + List<PromotionInfo> promotionInfos = inputView.readPromotionsFileInput(PROMOTIONS_FILE_NAME); + + PromotionManager promotionManager = new PromotionManager(promotionInfos, storeHouse, inputView); + MembershipManager membershipManager = new MembershipManager(storeHouse); + service = new StoreService(promotionManager, membershipManager); + + List<Product> allProduct = storeHouse.getProductList(); + processPurchase(allProduct, storeHouse, membershipManager); + } + + private void processPurchase(List<Product> allProduct, StoreHouse storeHouse, MembershipManager membershipManager) { + while (true) { + outputView.printProductList(allProduct); + Receipt receipt = getUserPurchase(storeHouse); + applyMembershipDiscount(receipt); + outputView.printReceipt(receipt, storeHouse, membershipManager); + if (inputView.readAdditionalPurchaseChoice().equals(Choice.N)) { + break; + } + } + } + + private Receipt getUserPurchase(StoreHouse storeHouse) { + while (true) { + List<Purchase> purchaseList = inputView.readProductNameAndQuantity(); + try { + return getReceipt(storeHouse, purchaseList); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } + } + + private Receipt getReceipt(StoreHouse storeHouse, List<Purchase> purchaseList) { + Receipt receipt = service.purchase(purchaseList, storeHouse); + receipt.setPurchaseList(purchaseList); + return receipt; + } + + private void applyMembershipDiscount(Receipt receipt) { + Choice membershipDiscountApplicationChoice = inputView.readMembershipDiscountApplicationChoice(); + if (membershipDiscountApplicationChoice.equals(Choice.Y)) { + service.applyMembershipDiscount(receipt); + } + } + +}
Java
์ข‹์€ ์˜๊ฒฌ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ์‚ฌ์šฉ์ž๋กœ๋ถ€ํ„ฐ ์ž…๋ ฅ์„ ๋ฐ›๊ณ  ํ•œ๋ฒˆ์— ๋ชจ๋“  ๊ฑธ ์ฒ˜๋ฆฌํ•˜๋ ค๊ณ  ํ–ˆ๋˜ ๊ฒŒ ์‹ค์ˆ˜์˜€๋„ค์š”.. ์ฑ…์ž„ ๋ถ„๋ฆฌ๊ฐ€ ๋ถ€์กฑํ–ˆ๋˜ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๋ฆฌํŒฉํ† ๋ง์— ์ ์šฉํ•ด ๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค :)
@@ -0,0 +1,60 @@ +package store.domain; + +import static camp.nextstep.edu.missionutils.DateTimes.now; + +import java.time.LocalDateTime; + +public enum Promotion { + + NULL(""), + SPARKLING_BUY_TWO_GET_ONE_FREE("ํƒ„์‚ฐ2+1"), + MD_RECOMMENDATION("MD์ถ”์ฒœ์ƒํ’ˆ"), + FLASH_SALE("๋ฐ˜์งํ• ์ธ"); + + private final String promotionName; + private int buyQuantity; + private int getQuantity; + private LocalDateTime startDateTime; + private LocalDateTime endDateTime; + + Promotion(String promotionName) { + this.promotionName = promotionName; + } + + static void setQuantity(Promotion promotionName, int buyQuantity, int getQuantity) { + promotionName.buyQuantity = buyQuantity; + promotionName.getQuantity = getQuantity; + } + + static void setPromotionPeriods(Promotion promotionName, LocalDateTime startDateTime, + LocalDateTime endDateTime) { + promotionName.startDateTime = startDateTime; + promotionName.endDateTime = endDateTime; + } + + public static boolean isPromotionValid(Promotion promotionName) { + LocalDateTime now = now(); + return !now.isBefore(promotionName.startDateTime) && !now.isAfter(promotionName.endDateTime); + } + + public String getPromotionName() { + return promotionName; + } + + public int getBuyQuantity() { + return buyQuantity; + } + + public int getGetQuantity() { + return getQuantity; + } + + public LocalDateTime getStartDateTime() { + return startDateTime; + } + + public LocalDateTime getEndDateTime() { + return endDateTime; + } + +}
Java
์ข‹์€ ์˜๊ฒฌ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. @slay1379๋‹˜ ๋ฆฌ๋ทฐ์—๋„ ์งง๊ฒŒ ์ž‘์„ฑํ•˜๊ธด ํ–ˆ์ง€๋งŒ ์ถ”๊ฐ€๋กœ ๋ง์”€๋“œ๋ฆฌ์ž๋ฉด ํ˜„์žฌ null์„ ์ œ์™ธํ•˜๊ณ ๋Š” ์ฝ”๋“œ์—์„œ ์ง์ ‘ ์‚ฌ์šฉํ•˜๋Š” ๋ถ€๋ถ„์ด ์—†์ง€๋งŒ, ๋ณ€๋™ ๊ฐ€๋Šฅ์„ฑ์ด ๋†’๊ธฐ ๋•Œ๋ฌธ์— ๋ฌธ์ž์—ด ํƒ€์ž…์œผ๋กœ ๊ด€๋ฆฌํ•˜๋Š” ํŽธ์ด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. (๋ผ๊ณ  ์ž‘์„ฑํ•˜๊ณ  ๋‹ค์‹œ ์ƒ๊ฐํ•ด๋ณด๋‹ˆ ํ…Œ์ŠคํŠธ ์ฝ”๋“œ๊ฐ€ ์žˆ์—ˆ๋„ค์š”...! ^^;; ํ•˜ํ•˜)
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
์ข‹์€ ์˜๊ฒฌ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ์ด๋ฒˆ ๋ฏธ์…˜์—์„œ๋Š” ์ฑ…์ž„ ๋ถ„๋ฆฌ์— ๋ฏธํกํ–ˆ๋˜ ๊ฒƒ ๊ฐ™์•„์š”. PromotionManager์„ ์‚ฌ์‹ค์ƒ ์„œ๋น„์Šค์ฒ˜๋Ÿผ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์—ˆ๋˜ ๊ฒƒ ๊ฐ™๊ณ , ์˜๊ฒฌ ์ฐธ๊ณ ํ•ด์„œ ๋ฆฌํŒฉํ† ๋งํ•ด๋ณด๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค! ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :)
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
๋งž์Šต๋‹ˆ๋‹ค... ์ธ์ง€ํ•˜๊ณ  ์žˆ์œผ๋ฉด์„œ๋„ ๋‹น์žฅ ๋Œ์•„๊ฐ€๋Š” ๊ฒŒ ์šฐ์„ ์ด์—ˆ๊ธฐ์— ์“ฐ๋ ˆ๊ธฐ๋ฅผ ๋งŒ๋“ค์—ˆ๋„ค์š”ใ…‹ใ…‹ใ…‹ใ…œใ…œ ์ž…๋ ฅ ๋ฐ›๋Š” ๋ถ€๋ถ„์€ ์ „๋ถ€ ๋ฐ–์œผ๋กœ ๋นผ์„œ ๋ฆฌํŒฉํ† ๋งํ•  ์˜ˆ์ •์ž…๋‹ˆ๋‹ค! ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
๊ทธ๋ ‡๊ตฐ์š”..! ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๋” ๊ณต๋ถ€ํ•ด๋ณด๊ณ , ์ฐธ๊ณ ํ•ด์„œ ๋ฆฌํŒฉํ† ๋งํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
๋„ต ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :) ์ผ๋‹จ ๋Œ์•„๊ฐ€๊ฒŒ ๋งŒ๋“œ๋Š” ๊ฒŒ ๋ชฉ์ ์ด์—ˆ๊ธฐ์— ์ด๋Ÿฐ ๊ตฌ์กฐ๊ฐ€ ๋‚˜์™€๋ฒ„๋ ธ๋„ค์š”,, ใ…Žใ…Ž ์ž…๋ ฅ ๋ฐ›๋Š” ๋ถ€๋ถ„์€ ์ปจํŠธ๋กค๋Ÿฌ๋กœ ๋นผ์„œ ๋ฆฌํŒฉํ† ๋งํ•  ์˜ˆ์ •์ž…๋‹ˆ๋‹ค!
@@ -0,0 +1,48 @@ +package store.domain; + +import static store.constants.NumberConstants.SINGLE_PRODUCT_QUANTITY; + +import java.util.ArrayList; +import java.util.List; +import store.exception.ProductNotExistException; + +public class StoreHouse { + + private final List<Product> productList = new ArrayList<>(); + + + public void buy(Product product, int quantity) { + product.sell(quantity); + } + + public List<Product> findProductByName(String productName) { + List<Product> filteredProduct = productList.stream() + .filter(product -> product.getName().equals(productName)) + .toList(); + + if (filteredProduct.isEmpty()) { + throw new ProductNotExistException(); + } + + return filteredProduct; + } + + public boolean checkRegularPricePurchase(String productName) { + int count = (int) productList.stream() + .filter(product -> product.getName().equals(productName)) + .count(); + List<Product> products = findProductByName(productName); + Promotion promotionName = products.getFirst().getPromotionName(); + + return count == SINGLE_PRODUCT_QUANTITY && promotionName.equals(Promotion.NULL); + } + + public void addProduct(Product product) { + productList.add(product); + } + + public List<Product> getProductList() { + return productList; + } +} +
Java
์—‡ ๊ทธ ๋ฐฉ๋ฒ•๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์ง€๋งŒ, ๋™์ผํ•œ ์ด๋ฆ„์„ ๊ฐ€์ง„ ์ƒํ’ˆ์„ ๋ชจ๋‘ ๊ฐ€์ ธ์™€์„œ ๊ฐ ์ƒํ™ฉ์— ๋งž๊ฒŒ ์ฒ˜๋ฆฌํ•˜๋Š” ๋กœ์ง์—๋Š” List๊ฐ€ ๋” ์ ์ ˆํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ๋‹ค์–‘ํ•œ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ๊ณ ๋ฏผํ•ด ๋ณผ ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :)
@@ -0,0 +1,115 @@ +package store.io; + +import static store.constants.InputMessages.ADDITIONAL_PURCHASE_MESSAGE; +import static store.constants.InputMessages.FREEBIE_ADDITION_MESSAGE; +import static store.constants.InputMessages.INPUT_PRODUCT_NAME_AND_QUANTITY; +import static store.constants.InputMessages.MEMBERSHIP_DISCOUNT_CHOICE_MESSAGE; +import static store.constants.InputMessages.REGULAR_PRICE_BUY_MESSAGE; +import static store.constants.StringConstants.NEW_LINE; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import store.domain.Choice; +import store.domain.Product; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.parser.InputParser; +import store.io.parser.ProductsFileLineParser; +import store.io.parser.PromotionsFileLineParser; +import store.io.reader.FileReader; +import store.io.reader.Reader; +import store.io.writer.Writer; + +public class InputView { + + private final Reader reader; + private final Writer writer; + private final InputValidator validator; + + public InputView(Reader reader, Writer writer, InputValidator validator) { + this.reader = reader; + this.writer = writer; + this.validator = validator; + } + + public StoreHouse readProductsFileInput(String fileName) { + try { + return readProductsFile(fileName); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private StoreHouse readProductsFile(String fileName) throws IOException { + Reader reader = new FileReader(fileName); + reader.readLine(); + String line; + StoreHouse storeHouse = new StoreHouse(); + while ((line = reader.readLine()) != null) { + Product product = new ProductsFileLineParser(line).parseLine(); + storeHouse.addProduct(product); + } + return storeHouse; + } + + public List<PromotionInfo> readPromotionsFileInput(String fileName) { + try { + return readPromotionsFile(fileName); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private List<PromotionInfo> readPromotionsFile(String fileName) throws IOException { + Reader reader = new FileReader(fileName); + reader.readLine(); + String line; + List<PromotionInfo> promotionInfos = new ArrayList<>(); + while ((line = reader.readLine()) != null) { + promotionInfos.add(new PromotionsFileLineParser(line).parseLine()); + } + return promotionInfos; + } + + public List<Purchase> readProductNameAndQuantity() { + writer.write(INPUT_PRODUCT_NAME_AND_QUANTITY); + String inputProductAndQuantity = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(inputProductAndQuantity); + return new InputParser().parse(inputProductAndQuantity); + } + + public Choice readFreebieAdditionChoice(String productName) { + writer.write(String.format(FREEBIE_ADDITION_MESSAGE, productName)); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readRegularPricePaymentChoice(String productName, int quantity) { + writer.write(String.format(REGULAR_PRICE_BUY_MESSAGE, productName, quantity)); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readMembershipDiscountApplicationChoice() { + writer.write(MEMBERSHIP_DISCOUNT_CHOICE_MESSAGE); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readAdditionalPurchaseChoice() { + writer.write(ADDITIONAL_PURCHASE_MESSAGE); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } +}
Java
๋‹ค์–‘ํ•œ ์˜๊ฒฌ ์ œ์‹œํ•ด ์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!! ์ง€๊ธˆ ๋ณด๋‹ˆ ๊ทธ๋ ‡๋„ค์š”,, ํŒŒ์ผ์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ๋Š” ์—„์—ฐํžˆ ๋ทฐ์™€๋Š” ๋‹ค๋ฅธ ์ฑ…์ž„์ธ๋ฐ (๊ฐ’์„ ์ฝ์–ด๋“ค์ธ๋‹ค๋Š” ๋ถ€๋ถ„์— ๊ฝ‚ํ˜€) ์ด ๋ถ€๋ถ„์„ ๊ฐ„๊ณผํ–ˆ๋˜ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.์„œ๋น„์Šค๋กœ ๋ถ„๋ฆฌํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์ข‹์€ ๊ฒƒ ๊ฐ™์•„์š”! ํ•˜๋‚˜ ์˜๊ฒฌ์„ ์—ฌ์ญ™๊ณ  ์‹ถ์€ ๊ฒŒ ์žˆ๋Š”๋ฐ, **๋ทฐ์—์„œ ์ž…๋ ฅ๊ฐ’์— ๋Œ€ํ•œ ํŒŒ์‹ฑ์„ ํ•˜๋Š” ๊ฒƒ์— ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋Š”์ง€** ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค! ํ˜„์žฌ๋Š” ์ž…๋ ฅ ๋ฐ›๊ธฐ+๊ฒ€์ฆ+ํŒŒ์‹ฑ์„ ๋ชจ๋‘ ์ˆ˜ํ–‰ํ•˜๊ณ  ์žˆ์–ด ์ฑ…์ž„ ๋ถ„๋ฆฌ๊ฐ€ ์ž˜ ์ด๋ฃจ์–ด์ง€์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™๋‹ค๊ณ  ๋А๊ปด์ง‘๋‹ˆ๋‹ค... ๋ง์”€ํ•ด ์ฃผ์‹  ๊ฒƒ์ฒ˜๋Ÿผ ๋นˆ ๊ฐ’์„ ๊ฒ€์ฆํ•˜๋Š” ๋กœ์ง์„ parser๋กœ ํฌํ•จ์‹œํ‚จ๋‹ค๊ณ  ํ•˜๋ฉด, ๋ทฐ์—์„œ๋Š” ์ž…๋ ฅ์„ ๋ฐ›๋Š” ๊ธฐ๋Šฅ๋งŒ ์ˆ˜ํ–‰ํ•˜๊ณ  ์ปจํŠธ๋กค๋Ÿฌ๋‚˜ ์„œ๋น„์Šค์—์„œ ๊ฒ€์ฆ+ํŒŒ์‹ฑ์„ ์ง„ํ–‰ํ•˜๋Š” ํŽธ์ด ๋” ์ข‹์„๊นŒ์š”?
@@ -0,0 +1,138 @@ +name: CI + +on: + pull_request: + types: + - closed + +env: + IMAGE: ${{ vars.NCR_REGISTRY }}/follow-app + IMAGE_LATEST: ${{ vars.NCR_REGISTRY }}/follow-app:latest + +jobs: + lint-test: + name: lint and test + uses: ./.github/workflows/DRF-test.yaml + + send-discord-fail-message: + needs: lint-test + if: failure() + runs-on: ubuntu-latest + steps: + - name: Send Message to Discord + uses: "hugoalh/send-discord-webhook-ghaction@v5.0.0" + with: + key: ${{ secrets.DISCORD_WEBHOOK_KEY }} + payload: | + { + "content": "", + "embeds": [ + { + "title": "Test Failed", + "description": "workflow failed at DRF test stage.", + "color": "#b42323", + "footer": { + "text": "${{ github.event_name }}" + } + } + ], + "username": "Project Build Manager", + "avatar_url": "https://file.limeskin.kro.kr/curious_cat-small.png", + } + + build-and-push: + needs: lint-test + name: build and push + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Set up Docker buildx + uses: docker/setup-buildx-action@v2 + + - name: Login to NCR + uses: docker/login-action@v2 + with: + registry: ${{ vars.NCR_REGISTRY }} + username: ${{ secrets.NCR_ACCESS_KEY }} + password: ${{ secrets.NCR_SECRET_KEY }} + + - name: Get current timestamp + id: timestamp + run: echo "timestamp=$(date '+%s')" >> "$GITHUB_OUTPUT" + + - name: Build and Push + uses: docker/build-push-action@v4 + with: + context: follow_app + tags: ${{ env.IMAGE_LATEST }},"${{ env.IMAGE }}:${{ steps.timestamp.outputs.timestamp }}" + push: true + + health-check: + needs: build-and-push + name: health check + runs-on: ubuntu-latest + steps: + - name: Healthcheck Start + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.HOST }} + username: ${{ secrets.USERNAME }} + password: ${{ secrets.PASSWORD }} + script: | + cd follow_app + docker login \ + ${{ vars.NCR_REGISTRY }} \ + -u ${{ secrets.NCR_ACCESS_KEY }} \ + -p ${{ secrets.NCR_SECRET_KEY }} + docker pull ${{ env.IMAGE_LATEST }} + + send-discord-fail-health: + needs: health-check + if: failure() + runs-on: ubuntu-latest + steps: + - name: Send Message to Discord + uses: "hugoalh/send-discord-webhook-ghaction@v5.0.0" + with: + key: ${{ secrets.DISCORD_WEBHOOK_KEY }} + payload: | + { + "content": "", + "embeds": [ + { + "title": "Health Check Failed", + "description": "workflow failed at stage server health check.", + "color": "#b42323", + "footer": { + "text": "${{ github.event_name }}" + } + } + ], + "username": "Project Build Manager", + "avatar_url": "https://file.limeskin.kro.kr/curious_cat-small.png", + } + + deploy: + needs: health-check + name: deploy + runs-on: ubuntu-latest + steps: + - name: pull and run image + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.HOST }} + username: ${{ secrets.USERNAME }} + password: ${{ secrets.PASSWORD }} + script: | + docker login \ + ${{ vars.NCR_REGISTRY }} \ + -u ${{ secrets.NCR_ACCESS_KEY }} \ + -p ${{ secrets.NCR_SECRET_KEY }} + docker pull ${{ env.IMAGE_LATEST }} + docker stop follow-app + docker run -d --rm --name follow-app \ + --env-file .env \ + -p 8000:8000 \ + ${{ env.IMAGE_LATEST }} \ + /start
Unknown
๋‹ค๋ฅธ yaml ํŒŒ์ผ์— ์žˆ๋Š” workflow ๋ฅผ ๊ฐ€์ ธ์™€์„œ ์‚ฌ์šฉํ•˜์‹œ๋Š”๊ฑฐ ๊ฐ™์€๋ฐ, ์ž‘์—… ๋‚ด์— ์žˆ๋Š” ๋ณ€์ˆ˜๋„ ๋”ฐ๋กœ ๊บผ๋‚ด์„œ ์“ธ ์ˆ˜ ์žˆ๋‚˜์š” ??
@@ -0,0 +1,49 @@ +name: DRF Test + +on: + push: + workflow_call: + +jobs: + lint: + name: black check + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + with: + python-version: "3.11" + - name: install black + run: pip install black + - name: check black + run: black --check . + + drf-test: + needs: lint + name: test drf with docker + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: set env file + run: | + cat <<EOF > .env + # DB + POSTGRES_DB=postgres + POSTGRES_USER=postgres + POSTGRES_PASSWORD=postgres + POSTGRES_PORT=5432 + # DRF + DB_HOST=db + DJANGO_SECRET_KEY=just_test_secret_885f6d0c189dd4ccd619820b9f28f56bbe02be48d978f + RUN_MODE=local + DJANGO_ALLOWED_HOST=localhost + # NCP + NCP_ACCESS_KEY=${{ secrets.NCP_ACCESS_KEY }} + NCP_SECRET_KEY=${{ secrets.NCP_SECRET_KEY }} + EOF + + - name: test + run: | + docker compose up --build -d + docker compose run follow-app python manage.py test
Unknown
DB๊ด€๋ จ ๋ณ€์ˆ˜๋“ค๋„ secret์œผ๋กœ ์ถ”๊ฐ€ํ•ด์ฃผ์…”์„œ ์ฒ˜๋ฆฌํ•ด์ฃผ์‹œ๋ฉด ๋” ์ข‹์„๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค :)
@@ -0,0 +1,138 @@ +name: CI + +on: + pull_request: + types: + - closed + +env: + IMAGE: ${{ vars.NCR_REGISTRY }}/follow-app + IMAGE_LATEST: ${{ vars.NCR_REGISTRY }}/follow-app:latest + +jobs: + lint-test: + name: lint and test + uses: ./.github/workflows/DRF-test.yaml + + send-discord-fail-message: + needs: lint-test + if: failure() + runs-on: ubuntu-latest + steps: + - name: Send Message to Discord + uses: "hugoalh/send-discord-webhook-ghaction@v5.0.0" + with: + key: ${{ secrets.DISCORD_WEBHOOK_KEY }} + payload: | + { + "content": "", + "embeds": [ + { + "title": "Test Failed", + "description": "workflow failed at DRF test stage.", + "color": "#b42323", + "footer": { + "text": "${{ github.event_name }}" + } + } + ], + "username": "Project Build Manager", + "avatar_url": "https://file.limeskin.kro.kr/curious_cat-small.png", + } + + build-and-push: + needs: lint-test + name: build and push + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Set up Docker buildx + uses: docker/setup-buildx-action@v2 + + - name: Login to NCR + uses: docker/login-action@v2 + with: + registry: ${{ vars.NCR_REGISTRY }} + username: ${{ secrets.NCR_ACCESS_KEY }} + password: ${{ secrets.NCR_SECRET_KEY }} + + - name: Get current timestamp + id: timestamp + run: echo "timestamp=$(date '+%s')" >> "$GITHUB_OUTPUT" + + - name: Build and Push + uses: docker/build-push-action@v4 + with: + context: follow_app + tags: ${{ env.IMAGE_LATEST }},"${{ env.IMAGE }}:${{ steps.timestamp.outputs.timestamp }}" + push: true + + health-check: + needs: build-and-push + name: health check + runs-on: ubuntu-latest + steps: + - name: Healthcheck Start + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.HOST }} + username: ${{ secrets.USERNAME }} + password: ${{ secrets.PASSWORD }} + script: | + cd follow_app + docker login \ + ${{ vars.NCR_REGISTRY }} \ + -u ${{ secrets.NCR_ACCESS_KEY }} \ + -p ${{ secrets.NCR_SECRET_KEY }} + docker pull ${{ env.IMAGE_LATEST }} + + send-discord-fail-health: + needs: health-check + if: failure() + runs-on: ubuntu-latest + steps: + - name: Send Message to Discord + uses: "hugoalh/send-discord-webhook-ghaction@v5.0.0" + with: + key: ${{ secrets.DISCORD_WEBHOOK_KEY }} + payload: | + { + "content": "", + "embeds": [ + { + "title": "Health Check Failed", + "description": "workflow failed at stage server health check.", + "color": "#b42323", + "footer": { + "text": "${{ github.event_name }}" + } + } + ], + "username": "Project Build Manager", + "avatar_url": "https://file.limeskin.kro.kr/curious_cat-small.png", + } + + deploy: + needs: health-check + name: deploy + runs-on: ubuntu-latest + steps: + - name: pull and run image + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.HOST }} + username: ${{ secrets.USERNAME }} + password: ${{ secrets.PASSWORD }} + script: | + docker login \ + ${{ vars.NCR_REGISTRY }} \ + -u ${{ secrets.NCR_ACCESS_KEY }} \ + -p ${{ secrets.NCR_SECRET_KEY }} + docker pull ${{ env.IMAGE_LATEST }} + docker stop follow-app + docker run -d --rm --name follow-app \ + --env-file .env \ + -p 8000:8000 \ + ${{ env.IMAGE_LATEST }} \ + /start
Unknown
health-check๋Š” ์–ด๋–ค์‹์œผ๋กœ ํ™•์ธํ•˜๊ฒŒ ๋˜๋Š”๊ฑด์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,33 @@ +from django.core.management.base import BaseCommand +from django.contrib.auth.models import User +from tweet.models import Follow, Post + + +class Command(BaseCommand): + def handle(self, **options): + # if db has user script doesn't work + if User.objects.filter(username="user0").exists(): + print("๋ฐ์ดํ„ฐ๊ฐ€ ์ด๋ฏธ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค.") + exit(0) + + # create user data + for i in range(5): + user = User.objects.create_user(username=f"user{i}", password=f"user{i}") + # create post data + for j in range(3): + Post.objects.create(owner=user, content=f"{j}. post by user{i}") + + # set follow data + for i in range(5): + user = User.objects.get(username=f"user{i}") + a = (i + 1) % 5 + b = (i + 2) % 5 + c = (i + 4) % 5 + usera = User.objects.get(username=f"user{a}") + userb = User.objects.get(username=f"user{b}") + userc = User.objects.get(username=f"user{c}") + Follow.objects.create(user=user, follow=usera) + Follow.objects.create(user=user, follow=userb) + Follow.objects.create(user=user, follow=userc) + + print("๋ฐ์ดํ„ฐ ์ƒ์„ฑ ์™„๋ฃŒ")
Python
์ด๋Ÿฐ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค๋‹ˆ ๋งŽ์ด ๋ฐฐ์šฐ๊ณ  ๊ฐ‘๋‹ˆ๋‹ค ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,138 @@ +name: CI + +on: + pull_request: + types: + - closed + +env: + IMAGE: ${{ vars.NCR_REGISTRY }}/follow-app + IMAGE_LATEST: ${{ vars.NCR_REGISTRY }}/follow-app:latest + +jobs: + lint-test: + name: lint and test + uses: ./.github/workflows/DRF-test.yaml + + send-discord-fail-message: + needs: lint-test + if: failure() + runs-on: ubuntu-latest + steps: + - name: Send Message to Discord + uses: "hugoalh/send-discord-webhook-ghaction@v5.0.0" + with: + key: ${{ secrets.DISCORD_WEBHOOK_KEY }} + payload: | + { + "content": "", + "embeds": [ + { + "title": "Test Failed", + "description": "workflow failed at DRF test stage.", + "color": "#b42323", + "footer": { + "text": "${{ github.event_name }}" + } + } + ], + "username": "Project Build Manager", + "avatar_url": "https://file.limeskin.kro.kr/curious_cat-small.png", + } + + build-and-push: + needs: lint-test + name: build and push + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Set up Docker buildx + uses: docker/setup-buildx-action@v2 + + - name: Login to NCR + uses: docker/login-action@v2 + with: + registry: ${{ vars.NCR_REGISTRY }} + username: ${{ secrets.NCR_ACCESS_KEY }} + password: ${{ secrets.NCR_SECRET_KEY }} + + - name: Get current timestamp + id: timestamp + run: echo "timestamp=$(date '+%s')" >> "$GITHUB_OUTPUT" + + - name: Build and Push + uses: docker/build-push-action@v4 + with: + context: follow_app + tags: ${{ env.IMAGE_LATEST }},"${{ env.IMAGE }}:${{ steps.timestamp.outputs.timestamp }}" + push: true + + health-check: + needs: build-and-push + name: health check + runs-on: ubuntu-latest + steps: + - name: Healthcheck Start + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.HOST }} + username: ${{ secrets.USERNAME }} + password: ${{ secrets.PASSWORD }} + script: | + cd follow_app + docker login \ + ${{ vars.NCR_REGISTRY }} \ + -u ${{ secrets.NCR_ACCESS_KEY }} \ + -p ${{ secrets.NCR_SECRET_KEY }} + docker pull ${{ env.IMAGE_LATEST }} + + send-discord-fail-health: + needs: health-check + if: failure() + runs-on: ubuntu-latest + steps: + - name: Send Message to Discord + uses: "hugoalh/send-discord-webhook-ghaction@v5.0.0" + with: + key: ${{ secrets.DISCORD_WEBHOOK_KEY }} + payload: | + { + "content": "", + "embeds": [ + { + "title": "Health Check Failed", + "description": "workflow failed at stage server health check.", + "color": "#b42323", + "footer": { + "text": "${{ github.event_name }}" + } + } + ], + "username": "Project Build Manager", + "avatar_url": "https://file.limeskin.kro.kr/curious_cat-small.png", + } + + deploy: + needs: health-check + name: deploy + runs-on: ubuntu-latest + steps: + - name: pull and run image + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.HOST }} + username: ${{ secrets.USERNAME }} + password: ${{ secrets.PASSWORD }} + script: | + docker login \ + ${{ vars.NCR_REGISTRY }} \ + -u ${{ secrets.NCR_ACCESS_KEY }} \ + -p ${{ secrets.NCR_SECRET_KEY }} + docker pull ${{ env.IMAGE_LATEST }} + docker stop follow-app + docker run -d --rm --name follow-app \ + --env-file .env \ + -p 8000:8000 \ + ${{ env.IMAGE_LATEST }} \ + /start
Unknown
test๋งŒ ํ•˜๊ธฐ ์œ„ํ•ด ๋ถˆ๋Ÿฌ์˜ค๋Š” workflow๋ผ ๋ณ€์ˆ˜๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ƒ๊ฐ์€ ๋ชปํ–ˆ๋„ค์š”. job๋ผ๋ฆฌ์˜ ๋ณ€์ˆ˜ ๊ณต์œ  ๋ฐฉ๋ฒ•์œผ๋กœ ๊บผ๋‚ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™๊ธด ํ•œ๋ฐ ์‹œ๋„๋Š” ์•ˆํ•ด๋ดค์–ด์š”
@@ -0,0 +1,49 @@ +name: DRF Test + +on: + push: + workflow_call: + +jobs: + lint: + name: black check + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + with: + python-version: "3.11" + - name: install black + run: pip install black + - name: check black + run: black --check . + + drf-test: + needs: lint + name: test drf with docker + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: set env file + run: | + cat <<EOF > .env + # DB + POSTGRES_DB=postgres + POSTGRES_USER=postgres + POSTGRES_PASSWORD=postgres + POSTGRES_PORT=5432 + # DRF + DB_HOST=db + DJANGO_SECRET_KEY=just_test_secret_885f6d0c189dd4ccd619820b9f28f56bbe02be48d978f + RUN_MODE=local + DJANGO_ALLOWED_HOST=localhost + # NCP + NCP_ACCESS_KEY=${{ secrets.NCP_ACCESS_KEY }} + NCP_SECRET_KEY=${{ secrets.NCP_SECRET_KEY }} + EOF + + - name: test + run: | + docker compose up --build -d + docker compose run follow-app python manage.py test
Unknown
๋งž์•„์š” ๋‹ค๋งŒ ์ € ๋ถ€๋ถ„์ด ์ˆœ์ „ํžˆ ํ…Œ์ŠคํŠธ๋งŒ์„ ์œ„ํ•œ ๋ถ€๋ถ„์ด๋ผ ๊ดœ์ฐฎ์„ ๊ฑฐ๋ผ๊ณ  ์ƒ๊ฐํ–ˆ์–ด์š” ์›๋ž˜ test์šฉ envํŒŒ์ผ์„ git์— ๊ทธ๋Œ€๋กœ ์˜ฌ๋ ค์„œ actions์—์„œ ์‚ฌ์šฉํ–ˆ์—ˆ๋Š”๋ฐ ์ œ๊ฐ€ ์‹ค์ˆ˜๋กœ ncp key๋ฅผ ๋„ฃ์–ด์„œ ์˜ฌ๋ฆฌ๋Š” ๋ฐ”๋žŒ์— ๊ธ‰ํ•˜๊ฒŒ ์œ„์™€ ๊ฐ™์ด ๋ณ€๊ฒฝ๋œ ๊ฑฐ์—์š”. ์ €๋„ ์ €๋Ÿฐ์‹์œผ๋กœ ์ž‘์„ฑํ•˜๊ธฐ์—” ๋ณด๊ธฐ ์•Š์ข‹์•„ ๋ณด์—ฌ์„œ ์กฐ๊ธˆ ๋” ์„ธ๋ จ๋œ ๋ฐฉ์‹์œผ๋กœ ๋ณ€๊ฒฝํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,138 @@ +name: CI + +on: + pull_request: + types: + - closed + +env: + IMAGE: ${{ vars.NCR_REGISTRY }}/follow-app + IMAGE_LATEST: ${{ vars.NCR_REGISTRY }}/follow-app:latest + +jobs: + lint-test: + name: lint and test + uses: ./.github/workflows/DRF-test.yaml + + send-discord-fail-message: + needs: lint-test + if: failure() + runs-on: ubuntu-latest + steps: + - name: Send Message to Discord + uses: "hugoalh/send-discord-webhook-ghaction@v5.0.0" + with: + key: ${{ secrets.DISCORD_WEBHOOK_KEY }} + payload: | + { + "content": "", + "embeds": [ + { + "title": "Test Failed", + "description": "workflow failed at DRF test stage.", + "color": "#b42323", + "footer": { + "text": "${{ github.event_name }}" + } + } + ], + "username": "Project Build Manager", + "avatar_url": "https://file.limeskin.kro.kr/curious_cat-small.png", + } + + build-and-push: + needs: lint-test + name: build and push + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Set up Docker buildx + uses: docker/setup-buildx-action@v2 + + - name: Login to NCR + uses: docker/login-action@v2 + with: + registry: ${{ vars.NCR_REGISTRY }} + username: ${{ secrets.NCR_ACCESS_KEY }} + password: ${{ secrets.NCR_SECRET_KEY }} + + - name: Get current timestamp + id: timestamp + run: echo "timestamp=$(date '+%s')" >> "$GITHUB_OUTPUT" + + - name: Build and Push + uses: docker/build-push-action@v4 + with: + context: follow_app + tags: ${{ env.IMAGE_LATEST }},"${{ env.IMAGE }}:${{ steps.timestamp.outputs.timestamp }}" + push: true + + health-check: + needs: build-and-push + name: health check + runs-on: ubuntu-latest + steps: + - name: Healthcheck Start + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.HOST }} + username: ${{ secrets.USERNAME }} + password: ${{ secrets.PASSWORD }} + script: | + cd follow_app + docker login \ + ${{ vars.NCR_REGISTRY }} \ + -u ${{ secrets.NCR_ACCESS_KEY }} \ + -p ${{ secrets.NCR_SECRET_KEY }} + docker pull ${{ env.IMAGE_LATEST }} + + send-discord-fail-health: + needs: health-check + if: failure() + runs-on: ubuntu-latest + steps: + - name: Send Message to Discord + uses: "hugoalh/send-discord-webhook-ghaction@v5.0.0" + with: + key: ${{ secrets.DISCORD_WEBHOOK_KEY }} + payload: | + { + "content": "", + "embeds": [ + { + "title": "Health Check Failed", + "description": "workflow failed at stage server health check.", + "color": "#b42323", + "footer": { + "text": "${{ github.event_name }}" + } + } + ], + "username": "Project Build Manager", + "avatar_url": "https://file.limeskin.kro.kr/curious_cat-small.png", + } + + deploy: + needs: health-check + name: deploy + runs-on: ubuntu-latest + steps: + - name: pull and run image + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.HOST }} + username: ${{ secrets.USERNAME }} + password: ${{ secrets.PASSWORD }} + script: | + docker login \ + ${{ vars.NCR_REGISTRY }} \ + -u ${{ secrets.NCR_ACCESS_KEY }} \ + -p ${{ secrets.NCR_SECRET_KEY }} + docker pull ${{ env.IMAGE_LATEST }} + docker stop follow-app + docker run -d --rm --name follow-app \ + --env-file .env \ + -p 8000:8000 \ + ${{ env.IMAGE_LATEST }} \ + /start
Unknown
health-check๋ฅผ ํ™•์ธํ•˜๋Š” ๋ถ€๋ถ„์€ ์•„์ง ๋งŒ๋“ค์ง€ ์•Š์•˜์–ด์š” ๋Œ€์‹ ์— DRF test๋ฅผ ํ†ต๊ณผํ•˜๋ฉด ์ •์ƒ ๋™์ž‘์ธ ๊ฑฐ๋กœ ๊ฐ„์ฃผํ•˜๊ณ  ๋งŒ๋“ค๊ธด ํ–ˆ์–ด์š” ์‚ฌ์‹ค actions์—์„œ health-check๋ฅผ ๊ตฌํ˜„ํ•˜๊ธฐ ์กฐ๊ธˆ ๊นŒ๋‹ค๋กœ์›Œ์„œ k8s ์ ์šฉํ•˜๋ฉด์„œ health-check๋„ ๊ตฌํ˜„ ํ•  ๊ณ„ํš์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,41 @@ +import { useState, useCallback } from 'react'; +import APIError from '../../api/apiError'; + +interface UseFetchProps<TData> { + queryFn: () => Promise<TData>; + onError?: (error: APIError) => Promise<unknown> | unknown; +} + +interface UseFetchResult<TData> { + query: () => Promise<void>; + isLoading: boolean; + error: APIError | null; + data: TData; +} + +export default function useFetch<TData>({ + queryFn, + onError, +}: UseFetchProps<TData>): UseFetchResult<TData> { + const [isLoading, setLoading] = useState<boolean>(false); + const [error, setError] = useState<APIError | null>(null); + const [data, setData] = useState<TData>({} as TData); + + const query = useCallback(async () => { + setLoading(true); + setError(null); + + try { + const data = await queryFn(); + setData(data); + } catch (error) { + setError(error as APIError); + + if (onError) onError(error as APIError); + } finally { + setLoading(false); + } + }, [queryFn, onError]); + + return { query, isLoading, error, data }; +}
TypeScript
hooks ๋””๋ ‰ํ† ๋ฆฌ๋ฅผ components ๋””๋ ‰ํ† ๋ฆฌ ๋ฐ–์œผ๋กœ ์ด๋™์‹œ์ผœ์•ผ ํ•˜์ง€ ์•Š์„๊นŒ์š”~?
@@ -0,0 +1,80 @@ +import { useEffect, useRef, useState } from 'react'; +import { LowerArrow, UpperArrow } from './Arrows'; +import * as S from './style'; + +interface Option { + content: string; + value: string; +} + +interface DropdownProps { + size: S.Size; + options: Option[]; + defaultContent: string; + onSelect: (value: string) => void; +} + +const Dropdown = ({ + size, + options, + defaultContent, + onSelect, +}: DropdownProps) => { + const [curContent, setCurContent] = useState<string>(defaultContent); + const [isOpened, setIsOpened] = useState<boolean>(false); + const dropdownRef = useRef<HTMLDivElement>(null); + + const handleDropdownClick = () => { + setIsOpened((prev) => !prev); + }; + + const handleOptionSelect = (option: Option) => { + onSelect(option.value); + setCurContent(option.content); + setIsOpened(false); + }; + + const handleClickOutside = (event: MouseEvent) => { + if ( + dropdownRef.current && + !dropdownRef.current.contains(event.target as Node) + ) { + setIsOpened(false); + } + }; + + useEffect(() => { + document.addEventListener('mousedown', handleClickOutside); + return () => { + document.removeEventListener('mousedown', handleClickOutside); + }; + }, []); + + return ( + <S.Container ref={dropdownRef}> + <S.Dropdown size={size} onClick={handleDropdownClick}> + <S.DropdownText selectedOption={curContent}> + {curContent} + </S.DropdownText> + {isOpened ? <UpperArrow /> : <LowerArrow />} + </S.Dropdown> + {isOpened && ( + <S.OptionContainer size={size}> + {options.map((option, index) => { + return ( + <S.Option + key={`${option.content}_${index}`} + id={option.value} + onClick={() => handleOptionSelect(option)} + > + {option.content} + </S.Option> + ); + })} + </S.OptionContainer> + )} + </S.Container> + ); +}; + +export default Dropdown;
Unknown
select ํƒœ๊ทธ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ์ง์ ‘ ๋ฆฌ์ŠคํŠธ๋กœ ๋งŒ๋“œ๋Š” ์ •์„ฑ์ด ๋Œ€๋‹จํ•ด์š” :>
@@ -0,0 +1,90 @@ +import { useEffect, useState } from 'react'; +import { SortOrder, SortType } from '../../api/types'; +import { + INITIAL_PAGE_NUMBER, + INITIAL_PAGE_SIZE, + PAGE_SIZE, +} from '../../constants/paginationRules'; +import { Category, Product } from '../../types'; +import { productQueries } from './queries/product'; + +export interface UseProductsResult { + products: Product[]; + isLoading: boolean; + error: Error | null; + isLastPage: boolean; + page: number; + fetchNextPage: () => void; + setSort: (value: string) => void; + setCategory: (value: string) => void; +} + +export default function useProducts(): UseProductsResult { + const [products, setProducts] = useState<Product[]>([]); + const [isLastPage, setIsLastPage] = useState(false); + + const [page, setPage] = useState(INITIAL_PAGE_NUMBER); + const [sort, setSort] = useState<SortType>({ price: 'asc', id: 'asc' }); + const [category, setCategory] = useState<Category | ''>(''); + + const { + query: getProducts, + data: productsResponse, + isLoading, + error, + } = productQueries.useGetProducts({ + page, + category, + sort: Object.entries(sort).map(([field, order]) => `${field},${order}`), + size: page === INITIAL_PAGE_NUMBER ? INITIAL_PAGE_SIZE : PAGE_SIZE, + }); + + useEffect(() => { + if (!isLastPage) { + getProducts(); + } + }, [page, sort, category, isLastPage]); + + useEffect(() => { + setIsLastPage(false); + setPage(INITIAL_PAGE_NUMBER); + }, [category, sort]); + + useEffect(() => { + if (productsResponse) { + const { last, content } = productsResponse; + setIsLastPage(last); + setProducts((prevProducts) => + page === INITIAL_PAGE_NUMBER ? content : [...prevProducts, ...content] + ); + } + }, [productsResponse]); + + const fetchNextPage = () => { + if (isLastPage) return; + + // ์„œ๋ฒ„์˜ page size๊ฐ€ 4๋กœ ๊ณ ์ •๋˜์–ด + // page: 0, size: 20 ์š”์ฒญ ์ดํ›„์—” + // page: 5, size: 4 ๋กœ ์š”์ฒญํ•ด์•ผ ํ•จ + setPage((prevPage) => + prevPage !== INITIAL_PAGE_NUMBER + ? prevPage + 1 + : prevPage + INITIAL_PAGE_SIZE / PAGE_SIZE + ); + }; + + return { + products: products ?? [], + isLoading, + error, + page, + fetchNextPage, + setCategory: (value: string) => { + setCategory(value as Category); + }, + setSort: (value: string) => { + setSort((prev) => ({ ...prev, price: value as SortOrder })); + }, + isLastPage, + }; +}
TypeScript
๋ฆฌ๋ทฐ ๊ฐ€์ด๋“œ์— ๋”ฐ๋ผ ๋ฐ์ดํ„ฐ ํŽ˜์นญ ๋กœ์ง ๋ถ€๋ถ„์„ ์กฐ๊ธˆ ๋” ๊ฐœ์„ ํ•œ๋‹ค๋ฉด ์ข‹๊ฒ ๋Š”๋ฐ์š”, ์‚ฌ์‹ค ์ €๋„ ๋ชจ๋ฅด๊ฒ ์–ด์„œ ๊ฐ™์ด ๊ณ ๋ฏผํ•ด๋ณด์•„์š”~~
@@ -0,0 +1,519 @@ +import React, { Component } from 'react'; +import * as d3 from 'd3'; +import drawData from './Module/loadHandle'; +import FilterContainer from './Components/FilterContainer'; +import LoginModal from './Components/LoginModal'; +import DrawContainer from './Components/DrawContainer'; +import './less/App.less'; +import * as constants from './constants'; +import * as MakeSecret from './Module/simpleEncryption'; +import NearbyFactorDialog from './Components/NearbyFactorDialog'; +import DrawingSetTitleDescription from './Components/drawingSetTitleDescriptionModal'; + +class App extends Component { + constructor(props) { + super(props); + this.bound = undefined; + this.drawList = {}; + this.newToggleBox = constants.newToggleBox; + this.state = { + name: undefined, + drawingData: [], + map: undefined, + showFilter: false, + showModal: false, + activeFilter: 'active', + activeDraw: '', + MyInfoButton: false, + showDraw: false, + factors: [], + NearByFactorItems: [], + showDrawingSetTitleDescriptionModal: false, + drawingSetTitle: null, + drawingSetDescription: null, + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '', + legendToggle: false + // NearByFilteringItems: [] + }; + } + + componentDidMount = async () => { + const naver = window.naver; + const map = await new naver.maps.Map(d3.select('#map').node(), { + zoomControl: true, + zoomControlOptions: { + style: naver.maps.ZoomControlStyle.SMALL, + position: naver.maps.Position.TOP_RIGHT + }, + logoControl: true, + logoControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + scaleControl: true, + scaleControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + mapDataControl: true, + mapDataControlOptions: { + position: naver.maps.Position.BOTTOM_LEFT + } + }); + + this.setState({ map }); + this.bound = map.getBounds(); + this.mainPageLoad(map); + naver.maps.Event.addListener(map, 'idle', e => { + const { showDraw } = this.state; + this.bound = map.getBounds(); + // ๊ทธ๋ฆฌ๊ธฐ ๋ชจ๋“œ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ์—๋งŒ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ด + if (!showDraw) { + this.mainPageLoad(map); + this.deleteDraw(); + } + }); + const name = JSON.parse(localStorage.getItem('token')); + if (name) { + this.setState({ + name: MakeSecret.Decrypt(name) + }); + } + }; + + isDelete = false; + + handleUserNameOnChange = username => { + this.setState({ name: username }); + }; + + showDrawingSetTitleDescriptionModal = value => { + this.setState({ showDrawingSetTitleDescriptionModal: value }); + }; + + changeDrawingSetTitle = text => { + this.setState({ drawingSetTitle: text }); + }; + + changeDrawingSetDescription = text => { + this.setState({ drawingSetDescription: text }); + }; + + mainPageLoad = map => { + const { name, factors } = this.state; + const bound = this.bound; + const nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + drawData(name, bound, factors, false, this.drawList, map, nearbyData); + }; + + toggleAllDraw = () => { + const { showDraw, map } = this.state; + if (showDraw) { + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + this.isDelete = true; + } else { + if (this.isDelete) { + this.mainPageLoad(map); + this.isDelete = false; + } + } + }; + + deleteDraw = () => { + Object.entries(this.drawList).forEach(([key, value]) => { + const startPos = {}; + const endPos = {}; + // reference point + startPos.x = value._lineData[0].coord.x; + startPos.y = value._lineData[0].coord.y; + endPos.x = value._lineData[value._lineData.length - 1].coord.x; + endPos.y = value._lineData[value._lineData.length - 1].coord.y; + + if ( + (startPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < startPos.x + || startPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < startPos.y) + && (endPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < endPos.x + || endPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < endPos.y) + ) { + value.setMap(null); + delete this.drawList[key]; + } + }); + }; + + toggleLoginModal = () => { + const { showModal } = this.state; + this.setState({ showModal: !showModal }); + }; + + toggleDraw = () => { + const { showDraw } = this.state; + this.setState({ descriptionModalState: false }); + this.setState({ showDraw: !showDraw }); + }; + + toggleLegend = () => { + const { legendToggle } = this.state; + this.setState({ legendToggle: !legendToggle }); + }; + + showFilter = () => { + const { showFilter, activeFilter } = this.state; + if (activeFilter === 'active') { + this.setState({ + showFilter: !showFilter, + activeFilter: '' + }); + } else { + this.setState({ + showFilter: !showFilter, + activeFilter: 'active' + }); + } + }; + + showDraw = () => { + const { showDraw, drawingData, activeDraw } = this.state; + if (drawingData.length) { + const pressedConfirm = confirm( + '์ €์žฅํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ๊ทธ๋ฆฐ ์ •๋ณด๋Š” ๋ชจ๋‘ ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค!\n๊ทธ๋ž˜๋„ ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ์‹œ๊ฒ ์–ด์š”?' + ); + if (pressedConfirm) { + for (let index = 0; index < drawingData.length; index++) { + drawingData[index].figure.onRemove(); + } + this.setState({ drawingData: [] }); + this.setState({ descriptionModalState: false }); + } else if (!pressedConfirm) { + return; + } + } + + if (activeDraw === 'active') { + this.setState({ + showDraw: !showDraw, + activeDraw: '' + }); + } else { + this.setState({ + showDraw: !showDraw, + activeDraw: 'active' + }); + } + }; + + initDrawingListAfterSave = () => { + this.setState({ drawingData: [] }); + }; + + initUserName = () => { + this.setState({ name: undefined }); + }; + + myInfoToggle = () => { + const { MyInfoButton } = this.state; + this.setState({ MyInfoButton: !MyInfoButton }); + this.factorLoad(null, !MyInfoButton); + }; + + updateDrawingData = (shapeData, order = false, index) => { + const { drawingData } = this.state; + this.setState({ drawingData: [...drawingData, shapeData] }); + if (order) { + const newDrawingData = [...drawingData]; + newDrawingData.splice(index, 1); + this.setState({ drawingData: newDrawingData }); + } + }; + + mainToggle = (stateName, toggle) => { + this.setState({ [stateName]: !toggle }); + }; + + factorLoad = (category, toggle = false) => { + const { name, map } = this.state; + const bound = this.bound; + const factors = []; + let nearbyData; + + // ๊ธฐ์กด ์ง€๋„์— ์žˆ๋˜ ์ •๋ณด๋ฅผ ์ง€์›Œ์คŒ + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + // ์œ ์ € ํ˜ธ์žฌ ๋ณด๊ธฐ + if (toggle) { + const toggleObj = {}; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + toggleObj[key] = false; + }); + this.newToggleBox = toggleObj; + } + // ํ•„ํ„ฐ๋ง ํ•˜๊ธฐ + if (category) { + const toggleCategory = { + [category]: !this.newToggleBox[category] + }; + this.newToggleBox = { + ...this.newToggleBox, + ...toggleCategory + }; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + if (value) { + factors.push(key); + } + }); + this.setState({ + factors: factors + }); + nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + } + // TODO: + drawData(name, bound, factors, toggle, this.drawList, map, nearbyData); + }; + + handleChangeDescription = event => { + this.setState({ descriptionValue: event.target.value }); + }; + + handleChangeTitle = event => { + this.setState({ descriptionTitle: event.target.value }); + }; + + descriptionModal = () => { + const { + descriptionModalState, + descriptionValue, + descriptionTitle + } = this.state; + if (descriptionModalState) { + return ( + <div className="descriptionModal"> + <div className="descriptionHeader"> </div> + <textarea + placeholder="์ œ๋ชฉ์„ ์ง€์–ด์ฃผ์„ธ์š”:D" + className="descriptionInputTitle" + type="text" + value={descriptionTitle} + onChange={this.handleChangeTitle} + /> + <textarea + placeholder="ํ˜ธ์žฌ ๋‚ด์šฉ์„ ์ฑ„์›Œ์ฃผ์„ธ์š”:D" + className="descriptionInput" + type="text" + value={descriptionValue} + onChange={this.handleChangeDescription} + /> + <button + className="descriptionCloser" + type="button" + onClick={this.descriptionModalHide} + > + ๋‹ซ๊ธฐ + </button> + <button + className="descriptionSave" + type="button" + onClick={this.descriptionModalSave} + > + ์ €์žฅ + </button> + </div> + ); + } else { + return <div />; + } + }; + + descriptionModalHide = () => { + this.setState({ + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '' + }); + }; + + descriptionModalSave = () => { + const { descriptionValue, descriptionTitle, drawingData } = this.state; + this.setState({ descriptionModalState: false }); + const arrayOfShapes = drawingData; + arrayOfShapes[arrayOfShapes.length - 1].title = descriptionTitle; + arrayOfShapes[arrayOfShapes.length - 1].value = descriptionValue; + this.setState({ drawingData: arrayOfShapes }); + }; + + descriptionModalShow = () => { + this.setState({ descriptionModalState: true }); + }; + + render() { + const { + map, + name, + drawingData, + showFilter, + showDraw, + showModal, + activeFilter, + activeDraw, + MyInfoButton, + NearByFactorItems, + legendToggle, + showDrawingSetTitleDescriptionModal, + drawingSetTitle, + drawingSetDescription + } = this.state; + + this.toggleAllDraw(); + return ( + <div id="wrapper"> + <div id="map"> + <NearbyFactorDialog + mapLoad={map} + NearByFactorItems={NearByFactorItems} + /> + <div id="loginFavorContainer"> + <div + className="loginFavorBtn" + onClick={this.toggleLoginModal} + onKeyPress={this.toggleLoginModal} + role="button" + tabIndex="0" + > + {`My`} + </div> + <div + className={`loginFavorBtn ${activeFilter}`} + onClick={() => { + if (activeDraw === '') { + this.showFilter(); + } + }} + onKeyPress={() => this.showFilter} + role="button" + tabIndex="0" + > + {`ํ•„ํ„ฐ`} + </div> + <div + className={`loginFavorBtn ${activeDraw}`} + onClick={() => { + if (activeFilter === '') { + this.showDraw(); + this.descriptionModalHide(); + } + }} + onKeyPress={() => this.showDraw} + role="button" + tabIndex="0" + > + {`๊ทธ๋ฆฌ๊ธฐ`} + </div> + </div> + {showModal ? ( + <LoginModal + name={name} + toggleLoginModal={this.toggleLoginModal} + handleUserNameOnChange={this.handleUserNameOnChange} + initUserName={this.initUserName} + /> + ) : null} + <div className={!showFilter ? 'block' : 'none'}> + <FilterContainer + MyInfoButton={MyInfoButton} + myInfoToggle={this.myInfoToggle} + factorLoad={this.factorLoad} + showFilter={this.showFilter} + /> + </div> + <div className={showDraw ? 'block' : 'none'}> + <DrawContainer + handleToggle={this.showDraw} + mapLoad={map} + handleUserNameOnChange={this.handleUserNameOnChange} + drawingData={drawingData} + updateDrawingData={this.updateDrawingData} + toggleLoginModal={this.toggleLoginModal} + NearByFactorItems={NearByFactorItems} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + descriptionModalShow={this.descriptionModalShow} + descriptionModalHide={this.descriptionModalHide} + /> + </div> + {showDrawingSetTitleDescriptionModal ? ( + <DrawingSetTitleDescription + changeDrawingSetTitle={this.changeDrawingSetTitle} + changeDrawingSetDescription={ + this.changeDrawingSetDescription + } + drawingData={drawingData} + toggleLoginModal={this.toggleLoginModal} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + drawingSetTitle={drawingSetTitle} + drawingSetDescription={drawingSetDescription} + /> + ) : null} + <div + className="legend" + onClick={this.toggleLegend} + onKeyPress={this.toggleLegend} + role="button" + tabIndex="0" + /> + <div + className={ + 'colorList ' + (legendToggle ? 'invisible' : '') + } + > + {Object.keys(constants.newToggleBox).map( + (color, index) => { + return ( + <div className="eachColor" key={index}> + <div className="legendColorBox"> + <div className="colorCircle" /> + </div> + <div className="legendTextBox"> + {color} + </div> + </div> + ); + } + )} + </div> + </div> + <div> + <this.descriptionModal /> + </div> + </div> + ); + } +} + +export default App;
JavaScript
์ƒ์ˆ˜๋กœ ๋นผ๋†“๋Š”๊ฒŒ ์ข‹์„๋“ฏ. `server/categories.js`์—๋„ ์ •์˜๋˜์–ด์žˆ๊ณ  server๋‚˜ client๋‚˜ ๊ฐ™์ด ์“ฐ๊ฒŒ ๋ ํ…๋ฐ ์–ด๋–ป๊ฒŒ ์ฒ˜๋ฆฌํ• ์ง€ ์ •ํ•˜๋Š”๊ฒŒ ์ข‹์„๋“ฏ