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๋ ๊ฐ์ด ์ฐ๊ฒ ๋ ํ
๋ฐ ์ด๋ป๊ฒ ์ฒ๋ฆฌํ ์ง ์ ํ๋๊ฒ ์ข์๋ฏ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.