code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,25 @@
+package christmas.view;
+
+enum Notice {
+ WELCOME("์๋
ํ์ธ์! ์ฐํ
์ฝ ์๋น 12์ ์ด๋ฒคํธ ํ๋๋์
๋๋ค."),
+ ASK_DATE_OF_VISIT("12์ ์ค ์๋น ์์ ๋ฐฉ๋ฌธ ๋ ์ง๋ ์ธ์ ์ธ๊ฐ์? (์ซ์๋ง ์
๋ ฅํด ์ฃผ์ธ์!)"),
+ ASK_MENU_AND_COUNT("์ฃผ๋ฌธํ์ค ๋ฉ๋ด๋ฅผ ๋ฉ๋ด์ ๊ฐ์๋ฅผ ์๋ ค ์ฃผ์ธ์. (e.g. ํด์ฐ๋ฌผํ์คํ-2,๋ ๋์์ธ-1,์ด์ฝ์ผ์ดํฌ-1)"),
+ PREVIEW("12์ %s์ผ์ ์ฐํ
์ฝ ์๋น์์ ๋ฐ์ ์ด๋ฒคํธ ํํ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!%n"),
+ ORDER_MENU("\n<์ฃผ๋ฌธ ๋ฉ๋ด>"),
+ TOTAL_ORDER_AMOUNT("\n<ํ ์ธ ์ ์ด์ฃผ๋ฌธ ๊ธ์ก>"),
+ GIFT_MENU("\n<์ฆ์ ๋ฉ๋ด>"),
+ BENEFIT_LIST("\n<ํํ ๋ด์ญ>"),
+ TOTAL_BENEFIT_AMOUNT("\n<์ดํํ ๊ธ์ก>"),
+ TOTAL_PAYMENT_AMOUNT("\n<ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก>"),
+ EVENT_BADGE("\n<12์ ์ด๋ฒคํธ ๋ฐฐ์ง>");
+
+ private final String message;
+
+ Notice(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+} | Java | ์ ๋ @ddrongy๋์ ์๊ฒฌ์ ๋์ํฉ๋๋ค!,๊ทธ๋ ๋ค๋ฉด 1์๋ก ๋ฐ๋์์๋, (2024๋
1์)
System Constraint๋ ์๋์ผ๋ก ๋ฐ๋๋๋ก(LocalDate..?) ์ค์ ํ๋ ๋ฐฉํฅ์ผ๋ก ์์ ๋ ํ์ํ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,76 @@
+package christmas.controller;
+
+import christmas.domain.Badge;
+import christmas.domain.Benefits;
+import christmas.domain.Convertor;
+import christmas.domain.Date;
+import christmas.domain.EventManager;
+import christmas.domain.Orders;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+
+public class EventController {
+ public void start() {
+ OutputView.printWelcome();
+ Date date = createDate();
+ Orders orders = createOrders();
+ int totalOrderAmount = createTotalOrderAmount(orders);
+ OutputView.printGift(orders.hasGift());
+ Benefits benefits = createBenefits(orders, date);
+ int totalBenefitAmount = createTotalBenefitAmount(benefits);
+ createPaymentAmount(orders, totalOrderAmount, totalBenefitAmount);
+ createBadge(benefits, totalBenefitAmount);
+ }
+
+ private Date createDate() {
+ while (true) {
+ try {
+ Date date = new Date(InputView.readDate());
+ OutputView.printPreview(date);
+ return date;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e);
+ }
+ }
+ }
+
+ private Orders createOrders() {
+ while (true) {
+ try {
+ Orders orders = Convertor.toOrders(InputView.readOrder());
+ OutputView.printOrders(orders);
+ return orders;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e);
+ }
+ }
+ }
+
+ private int createTotalOrderAmount(Orders orders) {
+ int totalOrderAmount = orders.calculateTotalAmount();
+ OutputView.printTotalOrderAmount(totalOrderAmount);
+ return totalOrderAmount;
+ }
+
+ private Benefits createBenefits(Orders orders, Date date) {
+ Benefits benefits = EventManager.toBenefits(orders, date);
+ OutputView.printBenefitDetail(benefits);
+ return benefits;
+ }
+
+ private int createTotalBenefitAmount(Benefits benefits) {
+ int totalBenefitAmount = benefits.calculateTotalBenefitAmount();
+ OutputView.printTotalBenefitAmount(totalBenefitAmount);
+ return totalBenefitAmount;
+ }
+
+ private void createPaymentAmount(Orders orders, int totalOrderAmount, int totalBenefitAmount) {
+ int paymentAmount = orders.calculatePaymentAmount(totalOrderAmount, totalBenefitAmount);
+ OutputView.printPaymentAmount(paymentAmount);
+ }
+
+ private void createBadge(Benefits benefits, int totalBenefitAmount) {
+ Badge badge = benefits.toEventBadge(totalBenefitAmount);
+ OutputView.printEventBadge(badge);
+ }
+} | Java | ๋ชจ๋ ๊ฒ์ฆ์ InputView์์ ๋ฐ๋๋ค๋ฉด ์น์ฐ๋ ๋ง์๋๋ก ํ๋๊ฒ ๋ง๋ค๊ณ ์๊ฐํฉ๋๋ค! ํ์ง๋ง ๋ ์ง๊ฐ 1 - 31์ผ ์ค ํ๋์ฌ์ผ ํ๋ค๋ ๊ฒ์ ๋ํ ๊ฒ์ฆ์ VIew๊ฐ ์๋๋ผ Domain ์์ ์ด๋ค์ง๊ธฐ ๋๋ฌธ์ ๊ฒฐ๊ณผ์ ์ผ๋ก View์ Domain ์์ชฝ์์ ๊ฒ์ฆ์ด ์ด๋ค์ ธ์ผ ํฉ๋๋ค. ๋ฐ๋ผ์ ์์ชฝ์ ํต๋ก ์ญํ ์ ํ๋ controller์์ ์งํํ๋ ๊ฒ์ด ๋ง๋ค๊ณ ํ๋จํ์ต๋๋ค~ |
@@ -0,0 +1,76 @@
+package christmas.controller;
+
+import christmas.domain.Badge;
+import christmas.domain.Benefits;
+import christmas.domain.Convertor;
+import christmas.domain.Date;
+import christmas.domain.EventManager;
+import christmas.domain.Orders;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+
+public class EventController {
+ public void start() {
+ OutputView.printWelcome();
+ Date date = createDate();
+ Orders orders = createOrders();
+ int totalOrderAmount = createTotalOrderAmount(orders);
+ OutputView.printGift(orders.hasGift());
+ Benefits benefits = createBenefits(orders, date);
+ int totalBenefitAmount = createTotalBenefitAmount(benefits);
+ createPaymentAmount(orders, totalOrderAmount, totalBenefitAmount);
+ createBadge(benefits, totalBenefitAmount);
+ }
+
+ private Date createDate() {
+ while (true) {
+ try {
+ Date date = new Date(InputView.readDate());
+ OutputView.printPreview(date);
+ return date;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e);
+ }
+ }
+ }
+
+ private Orders createOrders() {
+ while (true) {
+ try {
+ Orders orders = Convertor.toOrders(InputView.readOrder());
+ OutputView.printOrders(orders);
+ return orders;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e);
+ }
+ }
+ }
+
+ private int createTotalOrderAmount(Orders orders) {
+ int totalOrderAmount = orders.calculateTotalAmount();
+ OutputView.printTotalOrderAmount(totalOrderAmount);
+ return totalOrderAmount;
+ }
+
+ private Benefits createBenefits(Orders orders, Date date) {
+ Benefits benefits = EventManager.toBenefits(orders, date);
+ OutputView.printBenefitDetail(benefits);
+ return benefits;
+ }
+
+ private int createTotalBenefitAmount(Benefits benefits) {
+ int totalBenefitAmount = benefits.calculateTotalBenefitAmount();
+ OutputView.printTotalBenefitAmount(totalBenefitAmount);
+ return totalBenefitAmount;
+ }
+
+ private void createPaymentAmount(Orders orders, int totalOrderAmount, int totalBenefitAmount) {
+ int paymentAmount = orders.calculatePaymentAmount(totalOrderAmount, totalBenefitAmount);
+ OutputView.printPaymentAmount(paymentAmount);
+ }
+
+ private void createBadge(Benefits benefits, int totalBenefitAmount) {
+ Badge badge = benefits.toEventBadge(totalBenefitAmount);
+ OutputView.printEventBadge(badge);
+ }
+} | Java | e๋ผ๊ณ ์ฌ์ฉํ๋ ๊ฒ์ ์๋ฐ๋ฅผ ์ฌ์ฉํ๋ ์ฌ๋๋ค๋ผ๋ฆฌ์ ์ฝ์์ธ๊ฑฐ ๊ฐ์๋ฐ ์ด๋ถ๋ถ์ ํ๋ฒ ๋ํ๋ฅผ ๋๋ ๋ณด๋ฉด ์ข์๊ฑฐ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,76 @@
+package christmas.controller;
+
+import christmas.domain.Badge;
+import christmas.domain.Benefits;
+import christmas.domain.Convertor;
+import christmas.domain.Date;
+import christmas.domain.EventManager;
+import christmas.domain.Orders;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+
+public class EventController {
+ public void start() {
+ OutputView.printWelcome();
+ Date date = createDate();
+ Orders orders = createOrders();
+ int totalOrderAmount = createTotalOrderAmount(orders);
+ OutputView.printGift(orders.hasGift());
+ Benefits benefits = createBenefits(orders, date);
+ int totalBenefitAmount = createTotalBenefitAmount(benefits);
+ createPaymentAmount(orders, totalOrderAmount, totalBenefitAmount);
+ createBadge(benefits, totalBenefitAmount);
+ }
+
+ private Date createDate() {
+ while (true) {
+ try {
+ Date date = new Date(InputView.readDate());
+ OutputView.printPreview(date);
+ return date;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e);
+ }
+ }
+ }
+
+ private Orders createOrders() {
+ while (true) {
+ try {
+ Orders orders = Convertor.toOrders(InputView.readOrder());
+ OutputView.printOrders(orders);
+ return orders;
+ } catch (IllegalArgumentException e) {
+ OutputView.printError(e);
+ }
+ }
+ }
+
+ private int createTotalOrderAmount(Orders orders) {
+ int totalOrderAmount = orders.calculateTotalAmount();
+ OutputView.printTotalOrderAmount(totalOrderAmount);
+ return totalOrderAmount;
+ }
+
+ private Benefits createBenefits(Orders orders, Date date) {
+ Benefits benefits = EventManager.toBenefits(orders, date);
+ OutputView.printBenefitDetail(benefits);
+ return benefits;
+ }
+
+ private int createTotalBenefitAmount(Benefits benefits) {
+ int totalBenefitAmount = benefits.calculateTotalBenefitAmount();
+ OutputView.printTotalBenefitAmount(totalBenefitAmount);
+ return totalBenefitAmount;
+ }
+
+ private void createPaymentAmount(Orders orders, int totalOrderAmount, int totalBenefitAmount) {
+ int paymentAmount = orders.calculatePaymentAmount(totalOrderAmount, totalBenefitAmount);
+ OutputView.printPaymentAmount(paymentAmount);
+ }
+
+ private void createBadge(Benefits benefits, int totalBenefitAmount) {
+ Badge badge = benefits.toEventBadge(totalBenefitAmount);
+ OutputView.printEventBadge(badge);
+ }
+} | Java | > ์ ์ฒด์ ์ผ๋ก create๋ผ๋ ๋ฉ์๋๋ช
์ ์ฌ์ฉํ๋๋ฐ create๊ฐ ๊ฐ์ฒด ์์ฑ์ ๋๋์ ์ฃผ๋๊ฑฐ๊ฐ์์ ๋ค๋ฅธ ์ด๋ฆ์ผ๋ก ๋ฉ์๋๋ช
์ ์์ฑํด๋ณด๋๊ฑด ์ด๋จ๊น์ ?
์ค์ ๋ก ํด๋น ๋ฉ์๋๊ฐ ๊ฐ์ฒด๋ฅผ ์์ฑํด์ ๋ฆฌํดํ๋ ๊ธฐ๋ฅ์ ํ๊ณ ์์ด์ create ๋ผ๊ณ ๋ช
๋ช
ํ๋๋ฐ ํน์ ๋ค๋ฅธ ์ข์ ์ด๋ฆ์ด ์์๊น์~? |
@@ -0,0 +1,24 @@
+package christmas.domain;
+
+public enum Badge {
+ STAR("๋ณ", 5_000),
+ TREE("ํธ๋ฆฌ", 10_000),
+ SANTA("์ฐํ", 20_000),
+ NONE("์์", 0);
+
+ private final String type;
+ private final int amount;
+
+ Badge(String type, int amount) {
+ this.type = type;
+ this.amount = amount;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public int getAmount() {
+ return amount;
+ }
+} | Java | ์ธํ
๋ฆฌ์ ์ด ์๋ ์์ฑ๊ธฐ๋ฅ์ผ๋ก ๋ง๋ ๊ฑด๋ฐ ์ด ๋ถ๋ถ์ ๋ํด์๋ ์๊ฐํด๋ณด์ง ๋ชปํ๋ค์ ใ
ใ
private๋ก ์ง์ ํ๋๊ฒ ๋ง๋๊ฑฐ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,37 @@
+import CONSTANTS from '../constants/constants.js';
+import ERROR from '../constants/error.js';
+
+class NumbersValidator {
+ static validateNumbers(numbers) {
+ const validators = [
+ this.#validateEmpty,
+ this.#validateNegative,
+ this.#validateNaN,
+ this.#validateLength,
+ this.#validateDuplicated,
+ ];
+ validators.forEach(validator => validator(numbers));
+ }
+
+ static #validateLength(numbers) {
+ if (numbers.length !== CONSTANTS.number.numberSize) throw new Error(ERROR.numbers.length);
+ }
+
+ static #validateNaN(numbers) {
+ if (Number.isNaN(Number(numbers))) throw new Error(ERROR.numbers.notANumber);
+ }
+
+ static #validateNegative(numbers) {
+ if (Number(numbers) < CONSTANTS.number.zero) throw new Error(ERROR.numbers.negative);
+ }
+
+ static #validateDuplicated(numbers) {
+ if (numbers.length !== new Set(numbers).size) throw new Error(ERROR.numbers.duplicated);
+ }
+
+ static #validateEmpty(numbers) {
+ if (numbers.length === CONSTANTS.number.zero) throw new Error(ERROR.numbers.empty);
+ }
+}
+
+export default NumbersValidator; | JavaScript | ๊ฐ ๋งค์๋๋ค์ ๋ฐ๋ก ํธ์ถ์ํค์ง ์๊ณ ๋ฐฐ์ด์ ๋ง๋ค์ด์ forEach ๋ฉ์๋๋ก ํ๋์ฉ ํธ์ถ์ํจ ์ด์ ๊ฐ ๊ถ๊ธํด์! |
@@ -0,0 +1,20 @@
+import { Console } from '@woowacourse/mission-utils';
+import MESSAGE from '../constants/message.js';
+import NumbersValidator from '../validators/NumbersValidator.js';
+import RestartValidator from '../validators/RestartValidator.js';
+
+const InputView = {
+ async readNumbers() {
+ const numbers = await Console.readLineAsync(MESSAGE.read.numbers);
+ NumbersValidator.validateNumbers(numbers);
+ return [...numbers].map(Number);
+ },
+
+ async readRestart() {
+ const restart = await Console.readLineAsync(MESSAGE.read.restart);
+ RestartValidator.validateRestart(restart);
+ return Number(restart);
+ },
+};
+
+export default InputView; | JavaScript | ๋ฐ์ดํฐ๋ฅผ ๋ฐ์ ์ถ๋ ฅํ๋ view์ ์ญํ ์ ์๊ฐํ์ ๋ ์ ํจ์ฑ ๊ฒ์ฌ๋จ๊ณ๊ฐ view์ ์๋๊ฒ ๋ง๋์ง ๊ถ๊ธ์ฆ์ด ๋๋๋ฐ ์ด๋ ๊ฒ ์์ฑํ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋น :) |
@@ -0,0 +1,42 @@
+import CONSTANTS from '../constants/constants.js';
+import MESSAGE from '../constants/message.js';
+
+class Hint {
+ #numbers;
+
+ #computerNumbers;
+
+ constructor(numbers, computerNumbers) {
+ this.#numbers = numbers;
+ this.#computerNumbers = computerNumbers;
+ }
+
+ calculateStrikeCount() {
+ return this.#numbers.reduce(
+ (count, digit, index) => (digit === this.#computerNumbers[index] ? count + 1 : count),
+ 0,
+ );
+ }
+
+ calculateBallCount(strikeCount) {
+ return (
+ this.#numbers.reduce(
+ (count, digit) => (this.#computerNumbers.includes(digit) ? count + 1 : count),
+ 0,
+ ) - strikeCount
+ );
+ }
+
+ generateHintMessage(strikeCount, ballCount) {
+ const hintMessage = [];
+ if (ballCount !== CONSTANTS.number.zero) hintMessage.push(`${ballCount}${MESSAGE.print.ball}`);
+ if (strikeCount !== CONSTANTS.number.zero)
+ hintMessage.push(`${strikeCount}${MESSAGE.print.strike}`);
+ if (ballCount === CONSTANTS.number.zero && strikeCount === CONSTANTS.number.zero)
+ hintMessage.push(MESSAGE.print.nothing);
+
+ return hintMessage;
+ }
+}
+
+export default Hint; | JavaScript | ์ฒ์์ Hint ํด๋์ค๋ช
์ ์๋ฌธ์ด ๋ค์๋๋ฐ ๊ฒ์์ด๋๊น ์ผ๋ง๋ ๋ง์ท๋์ง ์๋ ค์ฃผ๋ ์ญํ ์ด๋ผ ์ ์ ํ ์ ์๊ฒ ๋ค์! ๐๐ป |
@@ -0,0 +1,20 @@
+import { Console } from '@woowacourse/mission-utils';
+import MESSAGE from '../constants/message.js';
+import NumbersValidator from '../validators/NumbersValidator.js';
+import RestartValidator from '../validators/RestartValidator.js';
+
+const InputView = {
+ async readNumbers() {
+ const numbers = await Console.readLineAsync(MESSAGE.read.numbers);
+ NumbersValidator.validateNumbers(numbers);
+ return [...numbers].map(Number);
+ },
+
+ async readRestart() {
+ const restart = await Console.readLineAsync(MESSAGE.read.restart);
+ RestartValidator.validateRestart(restart);
+ return Number(restart);
+ },
+};
+
+export default InputView; | JavaScript | ์ด ๋ถ๋ถ์ ๋ํด์ ์ ๋ ๊ณ ๋ฏผ์ ๋ง์ด ํด๋ดค๋๋ฐ ํ๋ก ํธ(InputVIew)์ ๋ฐฑ์๋(model)์ ์ญํ ์ด ์๋ค๊ณ ๊ฐ์ ํ์ ๋, view์ model ๋ ๋ค ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ์งํํ๋ ๊ฒ์ด ๋ง๋ค๊ณ ํ๋จํ์ฌ ์์ฑํ๊ฒ ๋์์ต๋๋ค. |
@@ -0,0 +1,37 @@
+import CONSTANTS from '../constants/constants.js';
+import ERROR from '../constants/error.js';
+
+class NumbersValidator {
+ static validateNumbers(numbers) {
+ const validators = [
+ this.#validateEmpty,
+ this.#validateNegative,
+ this.#validateNaN,
+ this.#validateLength,
+ this.#validateDuplicated,
+ ];
+ validators.forEach(validator => validator(numbers));
+ }
+
+ static #validateLength(numbers) {
+ if (numbers.length !== CONSTANTS.number.numberSize) throw new Error(ERROR.numbers.length);
+ }
+
+ static #validateNaN(numbers) {
+ if (Number.isNaN(Number(numbers))) throw new Error(ERROR.numbers.notANumber);
+ }
+
+ static #validateNegative(numbers) {
+ if (Number(numbers) < CONSTANTS.number.zero) throw new Error(ERROR.numbers.negative);
+ }
+
+ static #validateDuplicated(numbers) {
+ if (numbers.length !== new Set(numbers).size) throw new Error(ERROR.numbers.duplicated);
+ }
+
+ static #validateEmpty(numbers) {
+ if (numbers.length === CONSTANTS.number.zero) throw new Error(ERROR.numbers.empty);
+ }
+}
+
+export default NumbersValidator; | JavaScript | ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ๋ชจ๋ ์ํํ๊ธฐ ์ํด์ ํ๋์ ๋ฉ์๋๋ฅผ ํธ์ถํจ์ผ๋ก์ ๊ฐ ์ ํจ์ฑ ๊ฒ์ฌ๊ฐ ์ํ๋๋๋ก ์์ฑํด๋ณด์์ต๋๋ค! |
@@ -0,0 +1,38 @@
+# ๊ธฐ๋ฅ ๊ตฌํ ์ฒดํฌ๋ฆฌ์คํธ
+
+## ๊ธฐ๋ฅ ๋ชฉ๋ก
+
+### ์ฌ์ฉ์์ ์
๋ ฅ
+
+- [x] ์ธ ์๋ฆฌ ์ซ์๋ฅผ ์
๋ ฅํ๋ค.
+ - [x] ์ซ์๊ฐ ์๋ ๊ฒฝ์ฐ ์์ธ ์ฒ๋ฆฌ (1 ~ 9) - ์ ๊ท ํํ์
+ - [x] ์ซ์๊ฐ 3๊ฐ๊ฐ ์๋ ๊ฒฝ์ฐ ์์ธ ์ฒ๋ฆฌ
+ - [x] ์ค๋ณต๋๋ ์ซ์๊ฐ ์กด์ฌํ๋ ๊ฒฝ์ฐ ์์ธ ์ฒ๋ฆฌ
+
+### ์ปดํจํฐ์ ์ ์์ฑ
+
+- [x] 3๊ฐ์ ์ซ์ ์์ฑ (์ง์ ๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ด์ฉ)
+ - [x] ์ค๋ณต๋ ์ซ์๊ฐ ๋ฐ์ํ ๊ฒฝ์ฐ ์ฌ์์ฑ
+
+### ์ฌ์ฉ์๊ฐ ์
๋ ฅํ ์์ ์ปดํจํฐ๊ฐ ์์ฑํ ์ ๋น๊ต
+
+- [x] ๊ฐ ์๋ฆฌ ์ซ์ ๋น๊ตํ๊ธฐ
+ - [x] ์ซ์๊ฐ ๋๊ฐ๋ค๋ฉด ์คํธ๋ผ์ดํฌ +1
+ - [x] ๋ค๋ฅธ ์์น์ ์๋ค๋ฉด ๋ณผ +1
+
+### ๊ฒฐ๊ณผ
+
+- [x] ๋ณผ, ์คํธ๋ผ์ดํฌ, ๋ซ์ฑ ์ถ๋ ฅ
+- [x] 3์คํธ๋ผ์ดํฌ์ธ ๊ฒฝ์ฐ ๊ฒ์ ์ข
๋ฃ
+
+### ์ฌ์์ ํ์ธ
+
+- [x] ์ฌ์์ ์
๋ ฅ ์ซ์๋ฅผ ์
๋ ฅํ๋ค.
+ - [x] ์ซ์๊ฐ ์๋ ๊ฒฝ์ฐ ์์ธ ์ฒ๋ฆฌ
+ - [x] 1(์ฌ์์), 2(์ข
๋ฃ)๊ฐ ์๋ ๊ฒฝ์ฐ ์์ธ ์ฒ๋ฆฌ
+- [x] 1์ ์
๋ ฅ๋ฐ์ ๊ฒฝ์ฐ ์ฌ์์
+- [x] 2๋ฅผ ์
๋ ฅ๋ฐ์ ๊ฒฝ์ฐ ์ข
๋ฃ
+
+## ๋ชฉํ
+
+1. ๊ฐ์ฒด๋ฅผ ๊ฐ์ฒด์ค๋ฝ๊ฒ ์ฌ์ฉํ์!!!
\ No newline at end of file | Unknown | ๋ฆฌ๋ทฐ ์์์ ์์ ๋ฆฌ๋๋ฏธ์ ๊ฐ ํด๋์ค๋ณ ์ญํ ์ ๋ํด ๊ธฐ์ฌํด์ฃผ์๋ฉด ์ฝ๋ ํ์
์ ๋ ๋์์ด ๋ ๊ฑฐ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,58 @@
+package baseball.controller;
+
+import baseball.domain.Computer;
+import baseball.domain.Referee;
+import baseball.domain.Result;
+import baseball.util.GameProgress;
+import baseball.view.InputView;
+import baseball.view.OutputView;
+import java.util.List;
+
+public class GameController {
+
+ private final Computer computer;
+ private final Referee referee;
+ private GameProgress gameProgress;
+
+ public GameController() {
+ this.computer = new Computer();
+ this.referee = new Referee();
+ this.gameProgress = GameProgress.START;
+ }
+
+ public void play() {
+ playOrEnd();
+ }
+
+ private void playOrEnd() {
+ OutputView.printStart();
+ while (!GameProgress.isQuit(gameProgress)) {
+ List<Integer> computerNumbers = computer.generateRandomNumbers();
+ playUntilThreeStrikes(computerNumbers);
+ selectRetry();
+ }
+ }
+
+ private void selectRetry() {
+ OutputView.printRetryOrEnd();
+ gameProgress = GameProgress.judgeEnd(InputView.readNumber());
+ }
+
+ private void playUntilThreeStrikes(List<Integer> computerNumbers) {
+ while (!GameProgress.isQuit(gameProgress)) {
+ OutputView.printInputNumbers();
+ Result result = referee.judge(InputView.readNumbers(), computerNumbers);
+ OutputView.printResult(result.announceResult());
+ judgeRetry(result);
+ }
+ }
+
+ private void judgeRetry(Result result) {
+ if (!result.isThreeStrikes()) {
+ gameProgress = GameProgress.RETRY;
+ return;
+ }
+ OutputView.printGameEnd();
+ gameProgress = GameProgress.QUIT;
+ }
+} | Java | ํ๋ ์ด ๋ฉ์๋๊ฐ ๋จ์ํ playOrEnd๋ฅผ ํธ์ถํ๊ณ ์๋๋ฐ play๋ playOrEnd์ค ํ๋๋ฅผ ์์ ๊ณ ํฉ์ณ๋ ๋ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,58 @@
+package baseball.controller;
+
+import baseball.domain.Computer;
+import baseball.domain.Referee;
+import baseball.domain.Result;
+import baseball.util.GameProgress;
+import baseball.view.InputView;
+import baseball.view.OutputView;
+import java.util.List;
+
+public class GameController {
+
+ private final Computer computer;
+ private final Referee referee;
+ private GameProgress gameProgress;
+
+ public GameController() {
+ this.computer = new Computer();
+ this.referee = new Referee();
+ this.gameProgress = GameProgress.START;
+ }
+
+ public void play() {
+ playOrEnd();
+ }
+
+ private void playOrEnd() {
+ OutputView.printStart();
+ while (!GameProgress.isQuit(gameProgress)) {
+ List<Integer> computerNumbers = computer.generateRandomNumbers();
+ playUntilThreeStrikes(computerNumbers);
+ selectRetry();
+ }
+ }
+
+ private void selectRetry() {
+ OutputView.printRetryOrEnd();
+ gameProgress = GameProgress.judgeEnd(InputView.readNumber());
+ }
+
+ private void playUntilThreeStrikes(List<Integer> computerNumbers) {
+ while (!GameProgress.isQuit(gameProgress)) {
+ OutputView.printInputNumbers();
+ Result result = referee.judge(InputView.readNumbers(), computerNumbers);
+ OutputView.printResult(result.announceResult());
+ judgeRetry(result);
+ }
+ }
+
+ private void judgeRetry(Result result) {
+ if (!result.isThreeStrikes()) {
+ gameProgress = GameProgress.RETRY;
+ return;
+ }
+ OutputView.printGameEnd();
+ gameProgress = GameProgress.QUIT;
+ }
+} | Java | while์ ์กฐ๊ฑด๋ฌธ์ ๊ธ์ ๋ฌธ์ผ๋ก ํ๋ ๊ฒ์ด ๊ฐ๋
์ฑ์ ๋ ๋์์ด ๋๋ค๊ณ ํ๋๋ผ๊ตฌ์.
```suggestion
while (GameProgress.isRetry(gameProgress)) {
```
์ด๋ ๊ฒ ๋ฐ๊ฟ๋ณด์๋ ๊ฒ๋ ํ๋ฒ ์ ์๋๋ ค๋ด
๋๋ค! |
@@ -0,0 +1,23 @@
+package baseball.domain;
+
+import camp.nextstep.edu.missionutils.Randoms;
+import java.util.ArrayList;
+import java.util.List;
+
+public class Computer {
+
+ private static final int NUMBERS_LENGTH = 3;
+ private static final int START_RANGE_NUMBER = 1;
+ private static final int END_RANGE_NUMBER = 9;
+
+ public List<Integer> generateRandomNumbers() {
+ List<Integer> computer = new ArrayList<>();
+ while (computer.size() < NUMBERS_LENGTH) {
+ int randomNumber = Randoms.pickNumberInRange(START_RANGE_NUMBER, END_RANGE_NUMBER);
+ if (!computer.contains(randomNumber)) {
+ computer.add(randomNumber);
+ }
+ }
+ return computer;
+ }
+} | Java | ์ ์ ๋ฉ์๋๋ฅผ ์ ์ธํ์ ๊ธฐ์ค์ ์ดํด๋ณด๋ฉด Computer๋ ์ ํธ ๊ธฐ๋ฅ + ์ํ๊ฐ์ ๊ฐ์ง์ง ์๊ธฐ ๋๋ฌธ์ ์ ์ ๋ฉ์๋๋ก ์ ์ธํด๋ ๋๋ค๊ณ ์๊ฐํ๋๋ฐ ์ด๋ ์ ๊ฐ์? |
@@ -0,0 +1,17 @@
+package baseball.domain;
+
+import java.util.List;
+
+public class Referee {
+
+ public Result judge(List<Integer> userNumbers, List<Integer> computerNumbers) {
+ Result result = new Result();
+ for (int i = 0; i < userNumbers.size(); i++) {
+ if (result.isStrike(userNumbers, computerNumbers, i)) {
+ continue;
+ }
+ result.countBall(userNumbers, computerNumbers, i);
+ }
+ return result;
+ }
+} | Java | ์ปดํจํฐ์ ๋ง์ฐฌ๊ฐ์ง๋ก ๋ ํผ๋ฆฌ๋ ์ ์ ๋ฉ์๋๋ก ์ ์ธํด๋ ๊ด์ฐฎ์ง ์์๊น ํ๋ ์๊ฐ์
๋๋ค! |
@@ -0,0 +1,19 @@
+package baseball.util;
+
+public enum GameProgress {
+
+ START, RETRY, QUIT;
+
+ private static final int RETRY_NUMBER = 1;
+
+ public static boolean isQuit(GameProgress gameProgress) {
+ return gameProgress == QUIT;
+ }
+
+ public static GameProgress judgeEnd(int number) {
+ if (number == RETRY_NUMBER) {
+ return START;
+ }
+ return QUIT;
+ }
+} | Java | ํ๋ก๊ทธ๋จ์ ํ์ฅ์ฑ์ ๊ณ ๋ คํ์
์ enum์ผ๋ก ๋ง๋์ ๊ฑฐ ๋ง์ผ์ค๊น์? ์ ๋ ์ฒ์์ ์ข
๋ฃ ๋ฉ๋ด๋ฅผ enum์ผ๋ก ๋ง๋๋ ค๊ณ ํ๋ค๊ฐ ๊ฒฝ์ฐ์ ์๊ฐ 2๊ฐ์ง์ฌ์ class๋ก ๋ง๋ค์์ต๋๋ค. ๋ง์ฝ ๊ฒฝ์ฐ์ ์๊ฐ ๋ ๋ง์๋ค๋ฉด ์ ๋ enum์ผ๋ก ๋ง๋ค์์ ๊ฒ ๊ฐ๋ค์! |
@@ -0,0 +1,19 @@
+package baseball.util;
+
+public enum GameProgress {
+
+ START, RETRY, QUIT;
+
+ private static final int RETRY_NUMBER = 1;
+
+ public static boolean isQuit(GameProgress gameProgress) {
+ return gameProgress == QUIT;
+ }
+
+ public static GameProgress judgeEnd(int number) {
+ if (number == RETRY_NUMBER) {
+ return START;
+ }
+ return QUIT;
+ }
+} | Java | ๋ฐ๋ก ์์๋ฅผ ์ ์ธํ์๊ธฐ ๋ณด๋ค RETRY(1), QUIT(2); ์ด๋ฐ ์์ผ๋ก ๊ฐ์ ์ง์ ํด์ฃผ์๋๊ฑด ์ด๋ ์ ์ง ์ ์๋๋ ค๋ด
๋๋ค! |
@@ -0,0 +1,34 @@
+package baseball.view;
+
+import baseball.util.Validator;
+import camp.nextstep.edu.missionutils.Console;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class InputView {
+
+ public static final String DELIMITER = "";
+
+ public static List<Integer> readNumbers() {
+ String input = input();
+ Validator.validateNumbersPattern(input);
+
+ List<Integer> numbers = Stream.of(input.split(DELIMITER))
+ .map(Integer::parseInt)
+ .distinct()
+ .collect(Collectors.toList());
+ Validator.validateDuplication(numbers);
+ return numbers;
+ }
+
+ public static int readNumber() {
+ String input = input();
+ Validator.validateNumberPattern(input);
+ return Integer.parseInt(input);
+ }
+
+ private static String input() {
+ return Console.readLine();
+ }
+} | Java | view๊ฐ inputd์ domain์์ ์ฌ์ฉ๋ ํํ๋ก ๊ฐ๊ณตํด์ ๋๊ฒจ์ฃผ๋ ๊ฒ์ด ๋ง๋ ๊ฑธ๊น์??? ์ ๋ ํ๋ฆฌ์ฝ์ค๋ฅผ ํ๋ฉด์ ํญ์ ์๊ตฌ์ฌ ๊ฐ์ ธ์๋ ๋ถ๋ถ์ด๋ผ์ ๋ ์ด์ฑ์นด ๋ค์ ๋ง๋ค๊ธฐ์์๋ ์๋ํ์ ๋ํ String ๊ฐ์ผ๋ก๋ง ๋๊ฒจ์คฌ์๋๋ฐ์. ์ด ๋ถ๋ถ ๋ชฉ์์ผ์ ๊ผญ ์๊ธฐ ๋๋ ๋ดค์ผ๋ฉด ์ข๊ฒ ์ต๋๋ค! |
@@ -0,0 +1,65 @@
+package baseball.domain;
+
+import java.util.List;
+
+public class Result {
+
+ private static final int DEFAULT_NUMBER = 0;
+ private static final int END_NUMBER = 3;
+
+ private int ball;
+ private int strike;
+
+ public Result() {
+ this.ball = DEFAULT_NUMBER;
+ this.strike = DEFAULT_NUMBER;
+ }
+
+ public boolean isStrike(List<Integer> userNumbers, List<Integer> computerNumbers, int index) {
+ if (userNumbers.get(index).equals(computerNumbers.get(index))) {
+ strike++;
+ return true;
+ }
+ return false;
+ }
+
+ public void countBall(List<Integer> userNumbers, List<Integer> computerNumbers, int index) {
+ if (computerNumbers.contains(userNumbers.get(index))) {
+ ball++;
+ }
+ }
+
+ public boolean isThreeStrikes() {
+ return strike == END_NUMBER;
+ }
+
+ public String announceResult() {
+ if (ball == DEFAULT_NUMBER && strike == DEFAULT_NUMBER) {
+ return Message.NOTHING.getMessage();
+ }
+ if (ball == DEFAULT_NUMBER) {
+ return String.format(Message.STRIKE.getMessage(), strike);
+ }
+ if (strike == DEFAULT_NUMBER) {
+ return String.format(Message.BALL.getMessage(), ball);
+ }
+ return String.format(Message.BALL_AND_STRIKE.getMessage(), ball, strike);
+ }
+
+ private enum Message {
+ NOTHING("๋ซ์ฑ"),
+ BALL("%d๋ณผ"),
+ STRIKE("%d์คํธ๋ผ์ดํฌ"),
+ BALL_AND_STRIKE("%d๋ณผ %d์คํธ๋ผ์ดํฌ");
+
+ private final String message;
+
+ Message(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+ }
+} | Java | ํด๋น ์ถ๋ ฅ์ ๋ํ ์ฑ
์์ OutputView์ ๋๊ฒจ์ฃผ์๋๊ฑด ์ด๋ ์ ๊ฐ์? |
@@ -0,0 +1,32 @@
+package baseball.util;
+
+import java.util.List;
+import java.util.regex.Pattern;
+
+public class Validator {
+
+ private static final String DUPLICATION_MESSAGE = "์ค๋ณต๋ ์ซ์๊ฐ ์กด์ฌํฉ๋๋ค. ๋ค์ ์
๋ ฅํด์ฃผ์ธ์.";
+ private static final String NUMBERS_PATTERN_MESSAGE = "1๋ถํฐ 9๊น์ง์ ์ซ์ ์ค 3๊ฐ์ง ์ซ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์.";
+ private static final String NUMBER_PATTERN_MESSAGE = "์ฌ์์์ ์ํ๋ฉด 1, ์ข
๋ฃ๋ฅผ ์ํ๋ฉด 2๋ฅผ ์
๋ ฅํด์ฃผ์ธ์.";
+ private static final Pattern REGEX_NUMBERS = Pattern.compile("^[1-9]{3}$");
+ private static final Pattern REGEX_NUMBER = Pattern.compile("^[1-2]{1}$");
+ private static final int NUMBERS_LENGTH = 3;
+
+ public static void validateDuplication(List<Integer> input) {
+ if (input.size() < NUMBERS_LENGTH) {
+ throw new IllegalArgumentException(DUPLICATION_MESSAGE);
+ }
+ }
+
+ public static void validateNumbersPattern(String input) {
+ if (!REGEX_NUMBERS.matcher(input).matches()) {
+ throw new IllegalArgumentException(NUMBERS_PATTERN_MESSAGE);
+ }
+ }
+
+ public static void validateNumberPattern(String input) {
+ if (!REGEX_NUMBER.matcher(input).matches()) {
+ throw new IllegalArgumentException(NUMBER_PATTERN_MESSAGE);
+ }
+ }
+} | Java | ์ ๊ท์ ํํ์ด ๋งค์ฐ ๊น๋ํ๋ค์! ๋ฐฐ์ฐ๊ณ ๊ฐ๋๋ค. |
@@ -0,0 +1,58 @@
+package baseball.controller;
+
+import baseball.domain.Computer;
+import baseball.domain.Referee;
+import baseball.domain.Result;
+import baseball.util.GameProgress;
+import baseball.view.InputView;
+import baseball.view.OutputView;
+import java.util.List;
+
+public class GameController {
+
+ private final Computer computer;
+ private final Referee referee;
+ private GameProgress gameProgress;
+
+ public GameController() {
+ this.computer = new Computer();
+ this.referee = new Referee();
+ this.gameProgress = GameProgress.START;
+ }
+
+ public void play() {
+ playOrEnd();
+ }
+
+ private void playOrEnd() {
+ OutputView.printStart();
+ while (!GameProgress.isQuit(gameProgress)) {
+ List<Integer> computerNumbers = computer.generateRandomNumbers();
+ playUntilThreeStrikes(computerNumbers);
+ selectRetry();
+ }
+ }
+
+ private void selectRetry() {
+ OutputView.printRetryOrEnd();
+ gameProgress = GameProgress.judgeEnd(InputView.readNumber());
+ }
+
+ private void playUntilThreeStrikes(List<Integer> computerNumbers) {
+ while (!GameProgress.isQuit(gameProgress)) {
+ OutputView.printInputNumbers();
+ Result result = referee.judge(InputView.readNumbers(), computerNumbers);
+ OutputView.printResult(result.announceResult());
+ judgeRetry(result);
+ }
+ }
+
+ private void judgeRetry(Result result) {
+ if (!result.isThreeStrikes()) {
+ gameProgress = GameProgress.RETRY;
+ return;
+ }
+ OutputView.printGameEnd();
+ gameProgress = GameProgress.QUIT;
+ }
+} | Java | ํจ์๋ช
์ ThreeStrike์ฒ๋ผ ์ฐ์น ์กฐ๊ฑด์ ๋ํด ์ง์ ์ ์ผ๋ก ๋ํ๋ด๋ ๊ฒ๋ณด๋ค playUntilWin ๊ฐ์ ๋ฐฉ์์ผ๋ก ์์ฑํ๋๊ฑด ์ด๋จ๊น์?? |
@@ -0,0 +1,65 @@
+package baseball.domain;
+
+import java.util.List;
+
+public class Result {
+
+ private static final int DEFAULT_NUMBER = 0;
+ private static final int END_NUMBER = 3;
+
+ private int ball;
+ private int strike;
+
+ public Result() {
+ this.ball = DEFAULT_NUMBER;
+ this.strike = DEFAULT_NUMBER;
+ }
+
+ public boolean isStrike(List<Integer> userNumbers, List<Integer> computerNumbers, int index) {
+ if (userNumbers.get(index).equals(computerNumbers.get(index))) {
+ strike++;
+ return true;
+ }
+ return false;
+ }
+
+ public void countBall(List<Integer> userNumbers, List<Integer> computerNumbers, int index) {
+ if (computerNumbers.contains(userNumbers.get(index))) {
+ ball++;
+ }
+ }
+
+ public boolean isThreeStrikes() {
+ return strike == END_NUMBER;
+ }
+
+ public String announceResult() {
+ if (ball == DEFAULT_NUMBER && strike == DEFAULT_NUMBER) {
+ return Message.NOTHING.getMessage();
+ }
+ if (ball == DEFAULT_NUMBER) {
+ return String.format(Message.STRIKE.getMessage(), strike);
+ }
+ if (strike == DEFAULT_NUMBER) {
+ return String.format(Message.BALL.getMessage(), ball);
+ }
+ return String.format(Message.BALL_AND_STRIKE.getMessage(), ball, strike);
+ }
+
+ private enum Message {
+ NOTHING("๋ซ์ฑ"),
+ BALL("%d๋ณผ"),
+ STRIKE("%d์คํธ๋ผ์ดํฌ"),
+ BALL_AND_STRIKE("%d๋ณผ %d์คํธ๋ผ์ดํฌ");
+
+ private final String message;
+
+ Message(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+ }
+} | Java | isStrike์ ํต์ผํ์ฌ isBall๋ก ์ํ ์ด์ ๊ฐ ๋ฐ๋ก ์๋์ !? |
@@ -0,0 +1,65 @@
+package baseball.domain;
+
+import java.util.List;
+
+public class Result {
+
+ private static final int DEFAULT_NUMBER = 0;
+ private static final int END_NUMBER = 3;
+
+ private int ball;
+ private int strike;
+
+ public Result() {
+ this.ball = DEFAULT_NUMBER;
+ this.strike = DEFAULT_NUMBER;
+ }
+
+ public boolean isStrike(List<Integer> userNumbers, List<Integer> computerNumbers, int index) {
+ if (userNumbers.get(index).equals(computerNumbers.get(index))) {
+ strike++;
+ return true;
+ }
+ return false;
+ }
+
+ public void countBall(List<Integer> userNumbers, List<Integer> computerNumbers, int index) {
+ if (computerNumbers.contains(userNumbers.get(index))) {
+ ball++;
+ }
+ }
+
+ public boolean isThreeStrikes() {
+ return strike == END_NUMBER;
+ }
+
+ public String announceResult() {
+ if (ball == DEFAULT_NUMBER && strike == DEFAULT_NUMBER) {
+ return Message.NOTHING.getMessage();
+ }
+ if (ball == DEFAULT_NUMBER) {
+ return String.format(Message.STRIKE.getMessage(), strike);
+ }
+ if (strike == DEFAULT_NUMBER) {
+ return String.format(Message.BALL.getMessage(), ball);
+ }
+ return String.format(Message.BALL_AND_STRIKE.getMessage(), ball, strike);
+ }
+
+ private enum Message {
+ NOTHING("๋ซ์ฑ"),
+ BALL("%d๋ณผ"),
+ STRIKE("%d์คํธ๋ผ์ดํฌ"),
+ BALL_AND_STRIKE("%d๋ณผ %d์คํธ๋ผ์ดํฌ");
+
+ private final String message;
+
+ Message(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+ }
+} | Java | ์ค .. ์ด๋ฐฉ์์ผ๋ก ํ๋๊ฑฐ ์ข์๊ฑฐ ๊ฐ๋ค์
๊ทผ๋ฐ ์๋ ์กฐ๊ฑด์๋ else if ๋ก ๋ํ๋ด๋ ์ข์๊ฑฐ๊ฐ์์ ! |
@@ -29,7 +29,7 @@ public void initialize() {
beanFactory.initialize();
}
- public Collection<Object> controllers() {
+ public Collection<Object> getControllers() {
return beanFactory.beansAnnotatedWith(Controller.class);
}
} | Java | ํผ๋๋ฐฑ ๋ฐ์ ์ ํด์ฃผ์
จ๋ค์ ๐ |
@@ -1,6 +1,5 @@
package next.controller;
-import core.annotation.Inject;
import core.annotation.web.Controller;
import core.annotation.web.RequestMapping;
import core.annotation.web.RequestMethod;
@@ -22,14 +21,8 @@
public class ApiQnaController extends AbstractNewController {
private static final Logger logger = LoggerFactory.getLogger( ApiQnaController.class );
- private final QuestionDao questionDao;
- private final AnswerDao answerDao;
-
- @Inject
- public ApiQnaController(QuestionDao questionDao, AnswerDao answerDao) {
- this.questionDao = questionDao;
- this.answerDao = answerDao;
- }
+ private final QuestionDao questionDao = QuestionDao.getInstance();
+ private final AnswerDao answerDao = AnswerDao.getInstance();
@RequestMapping(value = "/api/qna/list", method = RequestMethod.GET)
public ModelAndView questions(HttpServletRequest req, HttpServletResponse resp) throws Exception { | Java | BeanFactory, getInstantiateSingletons NPE ๋ฐ์ ๋ฌธ์ ๋ก getInstance() ํธ์ถ๋ก ์์ ํ์ ๊ฑฐ ๋ง์๊น์?
์์ธ์ด ๋ฌด์์ด์๋์?
์ด์ ์ฝ๋(์์ฑ์ inject) ๋ฐฉ์์ผ๋ก ๋ฌธ์ ๋ฅผ ํด๊ฒฐํด๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ์์.
MyConfiguration ํด๋์ค์์ ๋ฑ๋กํ DataSource๋ ๋น์ผ๋ก ๋ฑ๋กํ์ผ๋ JdbcTemplate์์ ์ฌ์ฉํด๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ๊ตฌ์! |
@@ -0,0 +1,19 @@
+import { ShoppingCartIcon } from "../../assets";
+import { BaseButton } from "./BaseButton";
+import { StyledCartButtonImg, StyledCartCount, StyledContainer } from "./CartButton.styled";
+
+interface CartButtonProps {
+ quantity: number;
+ onClick: () => void;
+}
+
+export const CartButton = ({ quantity, onClick }: CartButtonProps) => {
+ return (
+ <BaseButton onClick={onClick}>
+ <StyledContainer>
+ <StyledCartButtonImg src={ShoppingCartIcon} />
+ {quantity && <StyledCartCount>{quantity}</StyledCartCount>}
+ </StyledContainer>
+ </BaseButton>
+ );
+}; | Unknown | ์ ํ๋ฆฌ์ผ์ด์
์ด ์ฒ์ ์คํ๋์ ๋ fetchํ ์ดํ์๋, ๋ด๊ธฐ/๋นผ๊ธฐ ๋ฒํผ์ ๋๋ฌ๋ productCount๊ฐ ๋ณ๊ฒฝ๋์ง ์๊ธฐ ๋๋ฌธ์ ์ค์๊ฐ์ผ๋ก ๊ฐ์๋ฅผ ์
๋ฐ์ดํธํ์ง ๋ชปํ๋ ๊ฒ์ผ๋ก ์ดํดํ์ด์. prop์ผ๋ก `productCount`๊ฐ๊ณผ `updateProductCount` ํจ์๋ฅผ ๋ง๋ค์ด CartActionButton๋ก ๋๊ฒจ์ฃผ๊ณ , CartActionButton์์๋ action์ด ์ผ์ด๋๋ฉด `updateProductCount`์ ๋ฐ๋ ๊ฐ์๋ฅผ CartButton์ผ๋ก ์ ๋ฌํ๋ฉด ์
๋ฐ์ดํธํ ์ ์์ ๊ฒ ๊ฐ์์!๐ |
@@ -0,0 +1,37 @@
+import { Suspense, useState } from "react";
+import { useSearchParams } from "react-router-dom";
+
+import { InputSection } from "./components/InputSection";
+import { ListSection } from "./components/ListSection/ListSection";
+
+export const SearchPage = () => {
+ const [, setSearchParams] = useSearchParams();
+
+ const [keyword, setKeyword] = useState<string>("");
+
+ const handleKeywordChange = (keyword: string) => {
+ setKeyword(keyword);
+ };
+
+ const handleSearch = (keyword: string) => {
+ console.log("๊ฒ์์ด: ", keyword);
+ setSearchParams({ keyword });
+ };
+
+ return (
+ <main>
+ <InputSection
+ keyword={keyword}
+ onKeywordChange={handleKeywordChange}
+ onInputSubmit={handleSearch}
+ />
+ {keyword ? (
+ <Suspense fallback={<p>๊ฒ์์ค...</p>}>
+ <ListSection />
+ </Suspense>
+ ) : (
+ <p>๊ฒ์์ด๋ฅผ ์
๋ ฅํด์ฃผ์ธ์</p>
+ )}
+ </main>
+ );
+}; | Unknown | url์ ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ๋ฅผ ์ด์ฉํด ๊ฒ์์ด ํค์๋๋ฅผ ๊ด๋ฆฌํ๋๋ก ์ค์ ํ ๊ฒ์, url์ ์ ๋ฌํ๋ฉฐ ๊ฒ์ ๊ฒฐ๊ณผ๋ ํจ๊ป ์ ๋ฌํ ์ ์๋๋ก ํ๊ธฐ ์ํจ์ด์์. ๊ทธ๋ฐ๋ฐ ํ์ฌ๋ ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ๋ฅผ ๊ฒ์์ด์ ๊ธฐ๋ณธ๊ฐ์ผ๋ก ๋ด๋ ค๋ฐ์ง ๋ชปํ๋ ๋ฌธ์ ๊ฐ ๋ฐ์ํ์ด์.
TODO: ์์นํ๋ผ๋ฏธํฐ ๊ฐ์ ํค์๋ ์ด๊ธฐ๊ฐ์ผ๋ก ์ค์
```suggestion
const [searchParams, setSearchParams] = useSearchParams();
const [keyword, setKeyword] = useState<string>(searchParams.get("keyword") || "");
``` |
@@ -0,0 +1,30 @@
+import { useLazyLoadQuery } from "react-relay";
+import { useSearchParams } from "react-router-dom";
+
+import { graphql } from "relay-runtime";
+
+import { ListSectionRepositorySearchQuery } from "./__generated__/ListSectionRepositorySearchQuery.graphql";
+
+import { RepositoryPagination } from "./RepositoryPagination";
+
+export const ListSection = () => {
+ const [searchParams] = useSearchParams();
+ const keyword = searchParams.get("keyword") || "";
+
+ const data = useLazyLoadQuery<ListSectionRepositorySearchQuery>(
+ graphql`
+ query ListSectionRepositorySearchQuery($keyword: String!) {
+ ...RepositoryPagination @arguments(keyword: $keyword)
+ }
+ `,
+ {
+ keyword,
+ }
+ );
+
+ return (
+ <ul>
+ <RepositoryPagination data={data} />
+ </ul>
+ );
+}; | Unknown | TODO: List Section ๋ด์์ ํค์๋๋ฅผ ์ง์ ๊ฐ์ ธ์ค์ง ๋ง๊ณ , Search Page์์ props๋ก ํค์๋๋ฅผ ์ฃผ์
๋ฐ๋๋ก ๋ณ๊ฒฝ |
@@ -0,0 +1,87 @@
+import { graphql, useFragment, useMutation } from "react-relay";
+
+import { RepositoryItem_repository$key } from "./__generated__/RepositoryItem_repository.graphql";
+import { RepositoryItemAddStarMutation } from "./__generated__/RepositoryItemAddStarMutation.graphql";
+import { RepositoryItemRemoveStarMutation } from "./__generated__/RepositoryItemRemoveStarMutation.graphql";
+
+import { StarButton } from "./StarButton";
+
+type RepositoryItemProps = {
+ repository: RepositoryItem_repository$key;
+};
+
+const RepositoryStarAddMutation = graphql`
+ mutation RepositoryItemAddStarMutation($id: ID!) {
+ addStar(input: { starrableId: $id }) {
+ starrable {
+ id
+ viewerHasStarred
+ }
+ }
+ }
+`;
+
+const RepositoryStarRemoveMutation = graphql`
+ mutation RepositoryItemRemoveStarMutation($id: ID!) {
+ removeStar(input: { starrableId: $id }) {
+ starrable {
+ id
+ viewerHasStarred
+ }
+ }
+ }
+`;
+
+export const RepositoryItem = (props: RepositoryItemProps) => {
+ const payload = useFragment(
+ graphql`
+ fragment RepositoryItem_repository on Repository {
+ id
+ name
+ url
+ description
+ stargazerCount
+ viewerHasStarred
+ }
+ `,
+ props.repository
+ );
+
+ const [add, isAdding] = useMutation<RepositoryItemAddStarMutation>(
+ RepositoryStarAddMutation
+ );
+
+ const [remove, isRemoving] = useMutation<RepositoryItemRemoveStarMutation>(
+ RepositoryStarRemoveMutation
+ );
+
+ if (!payload) {
+ return null;
+ }
+
+ const { id, url, name, description, stargazerCount, viewerHasStarred } =
+ payload;
+
+ const isLoading = isAdding || isRemoving;
+
+ return (
+ <li>
+ <a href={url} target="_blank" rel="noreferrer">
+ {name}
+ </a>
+ <p>{description}</p>
+ <p>โญ๏ธ {stargazerCount}</p>
+
+ {isLoading ? (
+ <div>...</div>
+ ) : (
+ <StarButton
+ repositoryId={id}
+ isStarred={viewerHasStarred}
+ onAddStar={() => add({ variables: { id } })}
+ onRemoveStar={() => remove({ variables: { id } })}
+ />
+ )}
+ </li>
+ );
+}; | Unknown | TODO: add, remove์ ๋ํ ๋ณ์๊ฐ์ StarButton ๋ด์์ ๋๊ฒจ๋ฐ๋๋ก ๋ณ๊ฒฝ |
@@ -0,0 +1,77 @@
+import React, { useState } from "react";
+import styled from "styled-components";
+import { Star as StarIcon } from "lucide-react";
+
+interface StarRatingProps {
+ totalStars?: number;
+ initialRating?: number;
+ onRatingChange?: (rating: number) => void;
+}
+
+const BackgroundContainer = styled.div`
+ background-color: #f7f7f7;
+ width: 807.73px;
+ height: 251.63px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+`;
+
+const StarContainer = styled.div`
+ display: flex;
+ gap: 4px;
+`;
+
+const StyledStar = styled.div<{ filled: boolean }>`
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ svg {
+ width: 94.96px;
+ height: 99.25px;
+ color: ${(props) => (props.filled ? "#facc15" : "#d1d5db")};
+ }
+`;
+
+const StarRating: React.FC<StarRatingProps> = ({
+ totalStars = 5,
+ initialRating = 0,
+ onRatingChange,
+}) => {
+ const [rating, setRating] = useState(initialRating);
+
+ const handleRating = (index: number) => {
+ let newRating = rating;
+ if (index + 1 === rating) {
+ newRating = index;
+ } else if (index < rating) {
+ newRating = index;
+ } else {
+ newRating = index + 1;
+ }
+
+ setRating(newRating);
+ if (onRatingChange) {
+ onRatingChange(newRating);
+ }
+ };
+
+ return (
+ <BackgroundContainer>
+ <StarContainer>
+ {Array.from({ length: totalStars }, (_, index) => (
+ <StyledStar
+ key={index}
+ filled={index < rating}
+ onClick={() => handleRating(index)}
+ >
+ <StarIcon fill={index < rating ? "#facc15" : "none"} stroke="#facc15" />
+ </StyledStar>
+ ))}
+ </StarContainer>
+ </BackgroundContainer>
+ );
+};
+
+export default StarRating; | Unknown | filled ์์ชฝ์ String์ผ๋ก ๊ฐ์ธ์ฃผ์ธ์ |
@@ -0,0 +1,77 @@
+import React, { useState } from "react";
+import styled from "styled-components";
+import { Star as StarIcon } from "lucide-react";
+
+interface StarRatingProps {
+ totalStars?: number;
+ initialRating?: number;
+ onRatingChange?: (rating: number) => void;
+}
+
+const BackgroundContainer = styled.div`
+ background-color: #f7f7f7;
+ width: 807.73px;
+ height: 251.63px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+`;
+
+const StarContainer = styled.div`
+ display: flex;
+ gap: 4px;
+`;
+
+const StyledStar = styled.div<{ filled: boolean }>`
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ svg {
+ width: 94.96px;
+ height: 99.25px;
+ color: ${(props) => (props.filled ? "#facc15" : "#d1d5db")};
+ }
+`;
+
+const StarRating: React.FC<StarRatingProps> = ({
+ totalStars = 5,
+ initialRating = 0,
+ onRatingChange,
+}) => {
+ const [rating, setRating] = useState(initialRating);
+
+ const handleRating = (index: number) => {
+ let newRating = rating;
+ if (index + 1 === rating) {
+ newRating = index;
+ } else if (index < rating) {
+ newRating = index;
+ } else {
+ newRating = index + 1;
+ }
+
+ setRating(newRating);
+ if (onRatingChange) {
+ onRatingChange(newRating);
+ }
+ };
+
+ return (
+ <BackgroundContainer>
+ <StarContainer>
+ {Array.from({ length: totalStars }, (_, index) => (
+ <StyledStar
+ key={index}
+ filled={index < rating}
+ onClick={() => handleRating(index)}
+ >
+ <StarIcon fill={index < rating ? "#facc15" : "none"} stroke="#facc15" />
+ </StyledStar>
+ ))}
+ </StarContainer>
+ </BackgroundContainer>
+ );
+};
+
+export default StarRating; | Unknown | ์ ๊ฐ ํ๊ธฐ ํ์ด์ง ๋ง๋ค๋ฉด์ ์ด ๋ถ๋ถ ์์ ํด์ ํ๊บผ๋ฒ์ PR ์ฌ๋ฆฌ๊ฒ ์ต๋๋ค |
@@ -0,0 +1,67 @@
+import { Button, Form, Input, Select, Space } from 'antd';
+import { REVIEW_CYCLE_FORM_NAMES, REVIEW_CYCLE_RULES } from './constants';
+import useMembers from '@apis/review/useMembers';
+import { ReviewCycleRequest } from '@apis/review/type';
+import { ReviewCycle } from '@apis/review/entities';
+
+interface Props {
+ onFinish: (values: ReviewCycleRequest) => void;
+ onReset: () => void;
+ initialValues?: {
+ name: ReviewCycle['name'];
+ reviewees: number[];
+ title: ReviewCycle['question']['title'];
+ description: ReviewCycle['question']['description'];
+ };
+ confirmButtonProps?: { text: string };
+ deleteButtonProps?: { text: string; handleClick: () => void };
+}
+
+export default function ReviewCycleForm({
+ onFinish,
+ onReset,
+ initialValues,
+ confirmButtonProps = { text: 'ํ์ธ' },
+ deleteButtonProps,
+}: Props) {
+ const { members, isLoading } = useMembers();
+
+ return (
+ <Form labelAlign="right" onFinish={onFinish} onReset={onReset} initialValues={initialValues}>
+ <Form.Item label="๋ฆฌ๋ทฐ ์ ์ฑ
์ด๋ฆ" name={REVIEW_CYCLE_FORM_NAMES.name} rules={REVIEW_CYCLE_RULES.reviewCycleName}>
+ <Input />
+ </Form.Item>
+
+ <Form.Item label="๋ฆฌ๋ทฐ ๋ฐ๋ ์ฌ๋" name={REVIEW_CYCLE_FORM_NAMES.reviewees} rules={REVIEW_CYCLE_RULES.reviewees}>
+ <Select
+ mode="multiple"
+ loading={isLoading}
+ placeholder="๋ฆฌ๋ทฐ ๋ฐ๋ ์ฌ๋์ ์ ํํด์ฃผ์ธ์."
+ optionFilterProp="label"
+ options={members?.map(m => ({ key: m.entityId, label: m.name, value: m.entityId }))}
+ />
+ </Form.Item>
+
+ <Form.Item label="์ง๋ฌธ" name={REVIEW_CYCLE_FORM_NAMES.question.title} rules={REVIEW_CYCLE_RULES.questionTitle}>
+ <Input />
+ </Form.Item>
+
+ <Form.Item
+ label="์ง๋ฌธ ์ค๋ช
"
+ name={REVIEW_CYCLE_FORM_NAMES.question.description}
+ rules={REVIEW_CYCLE_RULES.questionDescription}
+ >
+ <Input />
+ </Form.Item>
+ <Form.Item style={{ textAlign: 'right' }}>
+ <Space size={10}>
+ <Button htmlType="reset">์ทจ์</Button>
+ {deleteButtonProps && <Button onClick={deleteButtonProps.handleClick}>{deleteButtonProps.text}</Button>}
+ <Button type="primary" htmlType="submit">
+ {confirmButtonProps.text}
+ </Button>
+ </Space>
+ </Form.Item>
+ </Form>
+ );
+} | Unknown | ์๊ธฐ `form`์ ์์ด๋ ๋ ๊ฒ ๊ฐ์์~ |
@@ -0,0 +1,67 @@
+import { Button, Form, Input, Select, Space } from 'antd';
+import { REVIEW_CYCLE_FORM_NAMES, REVIEW_CYCLE_RULES } from './constants';
+import useMembers from '@apis/review/useMembers';
+import { ReviewCycleRequest } from '@apis/review/type';
+import { ReviewCycle } from '@apis/review/entities';
+
+interface Props {
+ onFinish: (values: ReviewCycleRequest) => void;
+ onReset: () => void;
+ initialValues?: {
+ name: ReviewCycle['name'];
+ reviewees: number[];
+ title: ReviewCycle['question']['title'];
+ description: ReviewCycle['question']['description'];
+ };
+ confirmButtonProps?: { text: string };
+ deleteButtonProps?: { text: string; handleClick: () => void };
+}
+
+export default function ReviewCycleForm({
+ onFinish,
+ onReset,
+ initialValues,
+ confirmButtonProps = { text: 'ํ์ธ' },
+ deleteButtonProps,
+}: Props) {
+ const { members, isLoading } = useMembers();
+
+ return (
+ <Form labelAlign="right" onFinish={onFinish} onReset={onReset} initialValues={initialValues}>
+ <Form.Item label="๋ฆฌ๋ทฐ ์ ์ฑ
์ด๋ฆ" name={REVIEW_CYCLE_FORM_NAMES.name} rules={REVIEW_CYCLE_RULES.reviewCycleName}>
+ <Input />
+ </Form.Item>
+
+ <Form.Item label="๋ฆฌ๋ทฐ ๋ฐ๋ ์ฌ๋" name={REVIEW_CYCLE_FORM_NAMES.reviewees} rules={REVIEW_CYCLE_RULES.reviewees}>
+ <Select
+ mode="multiple"
+ loading={isLoading}
+ placeholder="๋ฆฌ๋ทฐ ๋ฐ๋ ์ฌ๋์ ์ ํํด์ฃผ์ธ์."
+ optionFilterProp="label"
+ options={members?.map(m => ({ key: m.entityId, label: m.name, value: m.entityId }))}
+ />
+ </Form.Item>
+
+ <Form.Item label="์ง๋ฌธ" name={REVIEW_CYCLE_FORM_NAMES.question.title} rules={REVIEW_CYCLE_RULES.questionTitle}>
+ <Input />
+ </Form.Item>
+
+ <Form.Item
+ label="์ง๋ฌธ ์ค๋ช
"
+ name={REVIEW_CYCLE_FORM_NAMES.question.description}
+ rules={REVIEW_CYCLE_RULES.questionDescription}
+ >
+ <Input />
+ </Form.Item>
+ <Form.Item style={{ textAlign: 'right' }}>
+ <Space size={10}>
+ <Button htmlType="reset">์ทจ์</Button>
+ {deleteButtonProps && <Button onClick={deleteButtonProps.handleClick}>{deleteButtonProps.text}</Button>}
+ <Button type="primary" htmlType="submit">
+ {confirmButtonProps.text}
+ </Button>
+ </Space>
+ </Form.Item>
+ </Form>
+ );
+} | Unknown | ์ค ์ด๋ฐ ๋ฐฉ์์ผ๋ก ํ์ดํ ํ๋ฉด `initialValues`์ ๋ํ ํ์
์ ๋ฐ๋ก ๋ง๋ค์ด์ฃผ์ง ์์๋ ๋๊ณ ์ข๋ค์ ๐ |
@@ -0,0 +1,17 @@
+import { Rule } from 'antd/lib/form';
+
+export const REVIEW_CYCLE_FORM_NAMES = {
+ name: 'name',
+ reviewees: 'reviewees',
+ question: {
+ title: 'title',
+ description: 'description',
+ },
+} as const;
+
+export const REVIEW_CYCLE_RULES: Record<string, Rule[]> = {
+ reviewCycleName: [{ required: true, message: '๋ฆฌ๋ทฐ ์ ์ฑ
์ด๋ฆ์ ์
๋ ฅํ์ธ์.' }],
+ reviewees: [{ required: true, message: '๋ฆฌ๋ทฐ ๋ฐ๋ ์ฌ๋์ ์ ํํ์ธ์.' }],
+ questionTitle: [{ required: true, message: '์ง๋ฌธ ์ ๋ชฉ์ ์
๋ ฅํ์ธ์.' }],
+ questionDescription: [{ required: true, message: '์ง๋ฌธ ์ค๋ช
์ ์
๋ ฅํ์ธ์.' }],
+}; | TypeScript | ์๊ธฐ ์์๋ ๋ฐ๋ก ๋นผ์ ์ด์ ๊ฐ ๋ญ๊น์?
`Form.Item`์ `name` ์ธ์๋ ์ฌ์ฉ๋์ง ์๋ ๊ฒ ๊ฐ์๋ฐ `label`์ฒ๋ผ ๋ฐ๋ก ๋ฃ์ด๋ ์ข์๋ณด์ฌ์!
์๋๋ฉด label, name, rule์ ํ๋๋ก ๋ฌถ์ด๋ ์ข์ ๊ฒ ๊ฐ๊ตฌ์! ๊ฐ๋ณ๊ฒ ๋๋ ์๊ฐ ๋จ๊ฒจ๋ด
๋๋ค~ |
@@ -0,0 +1,90 @@
+import { API_PATH } from '@apis/constants';
+import { useQuery } from '@apis/common/useQuery';
+import { ReviewCycle } from './entities';
+import { ReviewCycleRequest, ReviewCycleResponse } from './type';
+import { useDelete, usePost, usePut } from '@apis/common/useMutation';
+import { get } from 'lodash';
+
+export function useGetReviewCycles() {
+ const {
+ data,
+ isLoading,
+ mutate: refetchReviewCycle,
+ } = useQuery<{ reviewCycles: ReviewCycle[] }>(API_PATH.REVIEW_CYCLES);
+
+ return {
+ reviewCycles: data?.reviewCycles,
+ isLoading,
+ refetchReviewCycle,
+ };
+}
+
+export function useCreateReviewCycle({
+ onSuccess,
+ onError,
+}: {
+ onSuccess: () => void;
+ onError: (message: string) => void;
+}) {
+ const { trigger, isMutating } = usePost<ReviewCycleRequest, ReviewCycleResponse>({
+ endpoint: API_PATH.REVIEW_CYCLES,
+ onSuccess: onSuccess,
+ onError: err => {
+ const errorMessage = get(err, 'response.data.error.message', '๋ฆฌ๋ทฐ ์ฌ์ดํด ์์ฑ์ ์คํจํ์ต๋๋ค.');
+ onError(errorMessage);
+ },
+ });
+
+ return {
+ createReviewCycle: (reviewCycle: ReviewCycleRequest) => trigger(reviewCycle),
+ isMutating,
+ };
+}
+
+export function useUpdateReviewCycle({
+ entityId,
+ onSuccess,
+ onError,
+}: {
+ entityId?: number;
+ onSuccess: () => void;
+ onError: (message: string) => void;
+}) {
+ const { trigger, isMutating } = usePut<ReviewCycleRequest, ReviewCycleResponse>({
+ endpoint: entityId ? `${API_PATH.REVIEW_CYCLES}/${entityId}` : null,
+ onSuccess: onSuccess,
+ onError: err => {
+ const errorMessage = get(err, 'response.data.error.message', '๋ฆฌ๋ทฐ ์ฌ์ดํด ์์ ์ ์คํจํ์ต๋๋ค.');
+ onError(errorMessage);
+ },
+ });
+
+ return {
+ updateReviewCycle: (reviewCycle: ReviewCycleRequest) => trigger(reviewCycle),
+ isMutating,
+ };
+}
+
+export function useDeleteReviewCycle({
+ entityId,
+ onSuccess,
+ onError,
+}: {
+ entityId: number;
+ onSuccess: () => void;
+ onError: (message: string) => void;
+}) {
+ const { trigger, isMutating } = useDelete({
+ endpoint: `${API_PATH.REVIEW_CYCLES}/${entityId}`,
+ onSuccess,
+ onError: err => {
+ const errorMessage = get(err, 'response.data.error.message', '๋ฆฌ๋ทฐ ์ฌ์ดํด ์ญ์ ์ ์คํจํ์ต๋๋ค.');
+ onError(errorMessage);
+ },
+ });
+
+ return {
+ deleteReviewCycle: trigger,
+ isMutating,
+ };
+} | TypeScript | [์ง๋ฌธ]
`trigger`๋ฅผ ๋ฐ๋ก ๋๊ธฐ์ง ์๊ณ ํจ์๋ก ๋๊ฒจ์ฃผ๋ ์ด์ ๋ ํ์
์ ๊ณ ์ ์ํค๊ธฐ ์ํจ์ผ๊น์? |
@@ -0,0 +1,37 @@
+import useModal from 'hooks/useModal';
+import { Headline4 } from 'styles/typography';
+import ReviewCycleForm from '../ReviewCycleForm';
+import { message } from 'antd';
+import { useCreateReviewCycle, useGetReviewCycles } from '@apis/review/useReviewCycles';
+
+function useReviewCycleCreateModal() {
+ const modal = useModal();
+
+ const { refetchReviewCycle } = useGetReviewCycles();
+ const { createReviewCycle } = useCreateReviewCycle({
+ onSuccess: () => {
+ message.success('์๋ก์ด ๋ฆฌ๋ทฐ ์ ์ฑ
์ ์์ฑํ์ด์.');
+ modal.close();
+ refetchReviewCycle();
+ },
+ onError: message.error,
+ });
+
+ function render() {
+ return modal.render({
+ title: <Headline4>์๋ก์ด ๋ฆฌ๋ทฐ ์ ์ฑ
๋ง๋ค๊ธฐ</Headline4>,
+ visible: modal.visible,
+ children: (
+ <ReviewCycleForm onFinish={createReviewCycle} onReset={modal.close} confirmButtonProps={{ text: '์์ฑํ๊ธฐ' }} />
+ ),
+ });
+ }
+
+ return {
+ render,
+ open: modal.open,
+ close: modal.close,
+ };
+}
+
+export default useReviewCycleCreateModal; | Unknown | ์๋ฐ ์์ผ๋ก ๊ธฐ์กด `modal`์ ํ์ฅํ๋ ํ
์ผ๋ก ๋ง๋ค์ด๋ ์ข์ ๊ฒ ๊ฐ์์~
```suggestion
return {
...modal,
render,
};
``` |
@@ -0,0 +1,25 @@
+import { DeleteOutlined } from '@ant-design/icons';
+import { useDeleteReviewCycle, useGetReviewCycles } from '@apis/review/useReviewCycles';
+import { message } from 'antd';
+
+function DeleteButton({ entityId }: { entityId: number }) {
+ const { refetchReviewCycle } = useGetReviewCycles();
+ const { deleteReviewCycle } = useDeleteReviewCycle({
+ entityId,
+ onSuccess: refetchReviewCycle,
+ onError: message.error,
+ });
+
+ return (
+ <button
+ onClick={e => {
+ e.stopPropagation();
+ deleteReviewCycle();
+ }}
+ >
+ <DeleteOutlined />
+ </button>
+ );
+}
+
+export default DeleteButton; | Unknown | [์ง๋ฌธ]
`e.stopPropagation()`์ ์๋๊ฐ ๋ฌด์์ธ๊ฐ์? |
@@ -0,0 +1,10 @@
+import { Member, ReviewCycle } from './entities';
+
+export type ReviewCycleRequest = {
+ name: ReviewCycle['name'];
+ reviewees: Member['entityId'][];
+ title: string;
+ description: string;
+};
+
+export type ReviewCycleResponse = Pick<ReviewCycle, 'entityId'>; | TypeScript | [์ ์]
์ด๊ฒ๊ณผ entities์ ํ์
์ ์ผ๋ถ ๊ณตํต์ผ๋ก ์ฌ์ฉํด๋ณผ ์๋ ์์ผ๋ ค๋์? ๊ฐ์ ๋งฅ๋ฝ์ ๋ด๊ณ ์๋ ํ์
์ธ๋ฐ ๋งฅ๋ฝ์ด ์์ ๋ถ๋ฆฌ๋์ด์ ๋์ค์ ์ ์ง๋ณด์ํ ๋ ์ฃผ์ํด์ผ๊ฒ ๋ค๋ ์๊ฐ์ด ๋๋ค์ |
@@ -0,0 +1,67 @@
+import { Button, Form, Input, Select, Space } from 'antd';
+import { REVIEW_CYCLE_FORM_NAMES, REVIEW_CYCLE_RULES } from './constants';
+import useMembers from '@apis/review/useMembers';
+import { ReviewCycleRequest } from '@apis/review/type';
+import { ReviewCycle } from '@apis/review/entities';
+
+interface Props {
+ onFinish: (values: ReviewCycleRequest) => void;
+ onReset: () => void;
+ initialValues?: {
+ name: ReviewCycle['name'];
+ reviewees: number[];
+ title: ReviewCycle['question']['title'];
+ description: ReviewCycle['question']['description'];
+ };
+ confirmButtonProps?: { text: string };
+ deleteButtonProps?: { text: string; handleClick: () => void };
+}
+
+export default function ReviewCycleForm({
+ onFinish,
+ onReset,
+ initialValues,
+ confirmButtonProps = { text: 'ํ์ธ' },
+ deleteButtonProps,
+}: Props) {
+ const { members, isLoading } = useMembers();
+
+ return (
+ <Form labelAlign="right" onFinish={onFinish} onReset={onReset} initialValues={initialValues}>
+ <Form.Item label="๋ฆฌ๋ทฐ ์ ์ฑ
์ด๋ฆ" name={REVIEW_CYCLE_FORM_NAMES.name} rules={REVIEW_CYCLE_RULES.reviewCycleName}>
+ <Input />
+ </Form.Item>
+
+ <Form.Item label="๋ฆฌ๋ทฐ ๋ฐ๋ ์ฌ๋" name={REVIEW_CYCLE_FORM_NAMES.reviewees} rules={REVIEW_CYCLE_RULES.reviewees}>
+ <Select
+ mode="multiple"
+ loading={isLoading}
+ placeholder="๋ฆฌ๋ทฐ ๋ฐ๋ ์ฌ๋์ ์ ํํด์ฃผ์ธ์."
+ optionFilterProp="label"
+ options={members?.map(m => ({ key: m.entityId, label: m.name, value: m.entityId }))}
+ />
+ </Form.Item>
+
+ <Form.Item label="์ง๋ฌธ" name={REVIEW_CYCLE_FORM_NAMES.question.title} rules={REVIEW_CYCLE_RULES.questionTitle}>
+ <Input />
+ </Form.Item>
+
+ <Form.Item
+ label="์ง๋ฌธ ์ค๋ช
"
+ name={REVIEW_CYCLE_FORM_NAMES.question.description}
+ rules={REVIEW_CYCLE_RULES.questionDescription}
+ >
+ <Input />
+ </Form.Item>
+ <Form.Item style={{ textAlign: 'right' }}>
+ <Space size={10}>
+ <Button htmlType="reset">์ทจ์</Button>
+ {deleteButtonProps && <Button onClick={deleteButtonProps.handleClick}>{deleteButtonProps.text}</Button>}
+ <Button type="primary" htmlType="submit">
+ {confirmButtonProps.text}
+ </Button>
+ </Space>
+ </Form.Item>
+ </Form>
+ );
+} | Unknown | [์ ๊ทน]
ui๋ฅผ ๋ ๋๋งํ๊ธฐ ์ํ buttonProps๊ฐ ๊ฐ์ฒดํํ๋ก ๋ด๋ ค๊ฐ๋ฉด ๋์ค์ ์ ์ง๋ณด์์ฐจ์์์ ์ด๋ ค์์ด ์์ ๊ฒ ๊ฐ์๋ฐ ๋ฐฉ๋ฒ์ด ์์ผ๋ ค๋์??
confirmButtonProps๋ deleteButtonProps๋ Form์ด๋ผ๋ ๋งฅ๋ฝ์์๋ ์์ ๋ค์ด๊ฐ๋ ๋ ๊ฒ ๊ฐ๋ค๊ณ ํ๋จํ ์๋ ์์ผ๋ ์ค์ ๋ ๋ํ๋ ์ชฝ์์๋ prop์ ๊บผ๋ด์ฐ๋ ์ฐจ์์ ๋ถ๊ณผํด์ ์ด๋ป๊ฒ๋ ๋ถ๋ฆฌ๊ฐ ๋๋ฉด ์ข๊ฒ ๋ค๋ ์๊ฐ์ด ๋ค์ด์. |
@@ -0,0 +1,28 @@
+import { faker } from '@faker-js/faker';
+import { personList } from '@mocks/auth/data';
+import { v4 as uuidv4 } from 'uuid';
+
+const personCount = personList.length;
+
+export const reviewCycleList = Array.from({ length: 10 }, (_, i) => ({
+ entityId: uuidv4(),
+ name: faker.lorem.words(),
+ creator: personList[Math.floor(Math.random() * personCount)],
+ reviewees: shuffleArray(personList).slice(0, Math.floor(Math.random() * personCount) + 1),
+ question: {
+ title: faker.lorem.words(),
+ description: faker.lorem.sentence(),
+ },
+ updatedAt: faker.date.past().toISOString(),
+}));
+
+function shuffleArray<T>(array: T[]) {
+ const result = [...array];
+
+ for (let i = result.length - 1; i > 0; i--) {
+ const j = Math.floor(Math.random() * (i + 1));
+ [result[i], result[j]] = [result[j], result[i]];
+ }
+
+ return result;
+} | TypeScript | `faker` ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ ์ ํ ์ ์ฐ์๋ค์ ๐ |
@@ -0,0 +1,25 @@
+import { DeleteOutlined } from '@ant-design/icons';
+import { useDeleteReviewCycle, useGetReviewCycles } from '@apis/review/useReviewCycles';
+import { message } from 'antd';
+
+function DeleteButton({ entityId }: { entityId: number }) {
+ const { refetchReviewCycle } = useGetReviewCycles();
+ const { deleteReviewCycle } = useDeleteReviewCycle({
+ entityId,
+ onSuccess: refetchReviewCycle,
+ onError: message.error,
+ });
+
+ return (
+ <button
+ onClick={e => {
+ e.stopPropagation();
+ deleteReviewCycle();
+ }}
+ >
+ <DeleteOutlined />
+ </button>
+ );
+}
+
+export default DeleteButton; | Unknown | [์ ๊ทน]
๋ฒํผ์ธ๋ฐ ๋ฒํผ์ด ์๋ ์ปดํฌ๋ํธ๊ฐ ๋ ๊ฒ ๊ฐ์์.
์์ด์ฝ์ ํด๋ฆญ์ด๋ฒคํธ๋ฅผ ๋ค๋ ๊ฒ์ ๋ํด์๋ ์ด๋ป๊ฒ ์๊ฐํ์๋์ฉ? role=button์ด ๋๋๋ก ํด์ผํ๋ ํ๋ ํ๋จ์ด ๋๋ค์ |
@@ -0,0 +1,163 @@
+import { Person, personIDMap, personMap } from './../auth/data';
+import { API_PATH } from '@apis/constants';
+import { personList } from '@mocks/auth/data';
+import { HttpResponse, http } from 'msw';
+import { reviewCycleList } from './data';
+import { ReviewCycleRequest } from '@apis/review/type';
+import { JWTPayload, JWTVerifyResult, jwtVerify } from 'jose';
+import { v4 as uuidv4 } from 'uuid';
+import { validateAccessToken } from '@mocks/utils';
+import { secretKey } from '@mocks/constants';
+
+export const reviewHandlers = [
+ http.get(API_PATH.MEMBERS, async ({ request }) => {
+ const res = await validateAccessToken(request);
+
+ if (res) {
+ return res;
+ }
+
+ return HttpResponse.json({
+ members: personList.map(m => ({
+ entityId: m.entityId,
+ name: m.name,
+ })),
+ });
+ }),
+
+ http.get(API_PATH.REVIEW_CYCLES, async ({ request }) => {
+ const res = await validateAccessToken(request);
+
+ if (res) {
+ return res;
+ }
+
+ const formatted = reviewCycleList.map(r => ({
+ entityId: r.entityId,
+ name: r.name,
+ creator: r.creator.name,
+ reviewees: r.reviewees.map(m => ({ entityId: m.entityId, name: m.name })),
+ question: {
+ title: r.question.title,
+ description: r.question.description,
+ },
+ updatedAt: r.updatedAt,
+ }));
+
+ return HttpResponse.json({
+ reviewCycles: formatted,
+ });
+ }),
+
+ http.post<never, ReviewCycleRequest>(API_PATH.REVIEW_CYCLES, async ({ request }) => {
+ const res = await validateAccessToken(request);
+
+ if (res) {
+ return res;
+ }
+
+ const accessToken = request.headers.get('Authorization')?.split(' ')[1];
+ const verified = accessToken && (await jwtVerify(accessToken, secretKey));
+ const email = (verified as JWTVerifyResult<JWTPayload>).payload.email;
+
+ const req = await request.json();
+ const reviewees = req.reviewees.map(id => personIDMap.get(id) ?? ({} as Person));
+
+ reviewCycleList.push({
+ entityId: uuidv4(),
+ name: req.name,
+ creator: personMap.get(email as string) ?? ({} as Person),
+ reviewees: reviewees,
+ question: {
+ title: req.title,
+ description: req.description,
+ },
+ updatedAt: new Date().toISOString(),
+ });
+
+ return HttpResponse.json(
+ {
+ reviewCycle: reviewCycleList[reviewCycleList.length - 1],
+ },
+ {
+ status: 201,
+ },
+ );
+ }),
+
+ http.delete<{ entityId: string }>(`${API_PATH.REVIEW_CYCLES}/:entityId`, async ({ request, params }) => {
+ const res = await validateAccessToken(request);
+
+ if (res) {
+ return res;
+ }
+
+ const index = reviewCycleList.splice(
+ reviewCycleList.findIndex(r => r.entityId === params.entityId),
+ 1,
+ );
+
+ if (index.length === 0) {
+ return HttpResponse.json(
+ {
+ error: { message: '๋ฆฌ๋ทฐ ์ฌ์ดํด์ด ์กด์ฌํ์ง ์์ต๋๋ค' },
+ },
+ {
+ status: 404,
+ },
+ );
+ }
+
+ return HttpResponse.json({
+ status: 200,
+ });
+ }),
+
+ http.put<{ entityId: string }, ReviewCycleRequest>(
+ `${API_PATH.REVIEW_CYCLES}/:entityId`,
+ async ({ request, params }) => {
+ const res = await validateAccessToken(request);
+
+ if (res) {
+ return res;
+ }
+
+ const index = reviewCycleList.findIndex(r => r.entityId === params.entityId);
+
+ if (index === -1) {
+ return HttpResponse.json(
+ {
+ error: { message: '๋ฆฌ๋ทฐ ์ฌ์ดํด์ด ์กด์ฌํ์ง ์์ต๋๋ค' },
+ },
+ {
+ status: 404,
+ },
+ );
+ }
+
+ const req = await request.json();
+ const prev = reviewCycleList[index];
+
+ reviewCycleList[index] = {
+ entityId: params.entityId,
+ name: req.name,
+ creator: prev.creator,
+ reviewees: req.reviewees.map(id => personIDMap.get(id) ?? ({} as Person)),
+ question: {
+ title: req.title,
+ description: req.description,
+ },
+ updatedAt: new Date().toISOString(),
+ };
+
+ return HttpResponse.json(
+ {
+ entityId: params.entityId,
+ },
+ {
+ status: 200,
+ },
+ );
+ },
+ ),
+]; | TypeScript | ์ฌ๊ธฐ๋ ์ค์ฝํ๊ฐ ๋์ผ๋ `r`๋ณด๋ค๋ `reviewCycle`์ผ๋ก ๋ค์ด๋ฐ ํ๋ ๊ฒ์ด ์ข์ ๊ฒ ๊ฐ์์~ |
@@ -0,0 +1,43 @@
+import { Button } from 'antd';
+import { RoundContent } from 'components/common/RoundContent';
+import useReviewCycleCreateModal from './ReviewCycleModals/useReviewCycleCreateModal';
+import ReviewCycleTable from './ReviewCycleTable';
+import useReviewCycleUpdateModal from './ReviewCycleModals/useReviewCycleUpdateModal';
+import useSelectedReviewCycle from './useSelectedReviewCycle';
+
+function ReviewCycles() {
+ const { selectedReviewCycle } = useSelectedReviewCycle();
+
+ const reviewCycleCreateModal = useReviewCycleCreateModal();
+ const reviewCycleUpdateModal = useReviewCycleUpdateModal({
+ entityId: selectedReviewCycle?.entityId,
+ });
+
+ function openReviewCycleCreateModal() {
+ reviewCycleCreateModal.open();
+ }
+
+ function openReviewCycleUpdateModal() {
+ reviewCycleUpdateModal.open();
+ }
+
+ return (
+ <RoundContent>
+ <RoundContent.Header
+ title="๋ฆฌ๋ทฐ ์ ์ฑ
๋ชฉ๋ก"
+ rightArea={
+ <Button type="primary" size="large" onClick={openReviewCycleCreateModal}>
+ ๋ฆฌ๋ทฐ ์ ์ฑ
์์ฑ
+ </Button>
+ }
+ />
+ <RoundContent.Body>
+ <ReviewCycleTable onRowClick={openReviewCycleUpdateModal} />
+ </RoundContent.Body>
+ {reviewCycleCreateModal.render()}
+ {reviewCycleUpdateModal.render()}
+ </RoundContent>
+ );
+}
+
+export default ReviewCycles; | Unknown | [์ ๊ทน]
์ธ์คํด์ค๋ camelcase๊ฐ ๋๋ฉด ์ข๊ฒ ์ต๋๋ค! |
@@ -0,0 +1,163 @@
+import { Person, personIDMap, personMap } from './../auth/data';
+import { API_PATH } from '@apis/constants';
+import { personList } from '@mocks/auth/data';
+import { HttpResponse, http } from 'msw';
+import { reviewCycleList } from './data';
+import { ReviewCycleRequest } from '@apis/review/type';
+import { JWTPayload, JWTVerifyResult, jwtVerify } from 'jose';
+import { v4 as uuidv4 } from 'uuid';
+import { validateAccessToken } from '@mocks/utils';
+import { secretKey } from '@mocks/constants';
+
+export const reviewHandlers = [
+ http.get(API_PATH.MEMBERS, async ({ request }) => {
+ const res = await validateAccessToken(request);
+
+ if (res) {
+ return res;
+ }
+
+ return HttpResponse.json({
+ members: personList.map(m => ({
+ entityId: m.entityId,
+ name: m.name,
+ })),
+ });
+ }),
+
+ http.get(API_PATH.REVIEW_CYCLES, async ({ request }) => {
+ const res = await validateAccessToken(request);
+
+ if (res) {
+ return res;
+ }
+
+ const formatted = reviewCycleList.map(r => ({
+ entityId: r.entityId,
+ name: r.name,
+ creator: r.creator.name,
+ reviewees: r.reviewees.map(m => ({ entityId: m.entityId, name: m.name })),
+ question: {
+ title: r.question.title,
+ description: r.question.description,
+ },
+ updatedAt: r.updatedAt,
+ }));
+
+ return HttpResponse.json({
+ reviewCycles: formatted,
+ });
+ }),
+
+ http.post<never, ReviewCycleRequest>(API_PATH.REVIEW_CYCLES, async ({ request }) => {
+ const res = await validateAccessToken(request);
+
+ if (res) {
+ return res;
+ }
+
+ const accessToken = request.headers.get('Authorization')?.split(' ')[1];
+ const verified = accessToken && (await jwtVerify(accessToken, secretKey));
+ const email = (verified as JWTVerifyResult<JWTPayload>).payload.email;
+
+ const req = await request.json();
+ const reviewees = req.reviewees.map(id => personIDMap.get(id) ?? ({} as Person));
+
+ reviewCycleList.push({
+ entityId: uuidv4(),
+ name: req.name,
+ creator: personMap.get(email as string) ?? ({} as Person),
+ reviewees: reviewees,
+ question: {
+ title: req.title,
+ description: req.description,
+ },
+ updatedAt: new Date().toISOString(),
+ });
+
+ return HttpResponse.json(
+ {
+ reviewCycle: reviewCycleList[reviewCycleList.length - 1],
+ },
+ {
+ status: 201,
+ },
+ );
+ }),
+
+ http.delete<{ entityId: string }>(`${API_PATH.REVIEW_CYCLES}/:entityId`, async ({ request, params }) => {
+ const res = await validateAccessToken(request);
+
+ if (res) {
+ return res;
+ }
+
+ const index = reviewCycleList.splice(
+ reviewCycleList.findIndex(r => r.entityId === params.entityId),
+ 1,
+ );
+
+ if (index.length === 0) {
+ return HttpResponse.json(
+ {
+ error: { message: '๋ฆฌ๋ทฐ ์ฌ์ดํด์ด ์กด์ฌํ์ง ์์ต๋๋ค' },
+ },
+ {
+ status: 404,
+ },
+ );
+ }
+
+ return HttpResponse.json({
+ status: 200,
+ });
+ }),
+
+ http.put<{ entityId: string }, ReviewCycleRequest>(
+ `${API_PATH.REVIEW_CYCLES}/:entityId`,
+ async ({ request, params }) => {
+ const res = await validateAccessToken(request);
+
+ if (res) {
+ return res;
+ }
+
+ const index = reviewCycleList.findIndex(r => r.entityId === params.entityId);
+
+ if (index === -1) {
+ return HttpResponse.json(
+ {
+ error: { message: '๋ฆฌ๋ทฐ ์ฌ์ดํด์ด ์กด์ฌํ์ง ์์ต๋๋ค' },
+ },
+ {
+ status: 404,
+ },
+ );
+ }
+
+ const req = await request.json();
+ const prev = reviewCycleList[index];
+
+ reviewCycleList[index] = {
+ entityId: params.entityId,
+ name: req.name,
+ creator: prev.creator,
+ reviewees: req.reviewees.map(id => personIDMap.get(id) ?? ({} as Person)),
+ question: {
+ title: req.title,
+ description: req.description,
+ },
+ updatedAt: new Date().toISOString(),
+ };
+
+ return HttpResponse.json(
+ {
+ entityId: params.entityId,
+ },
+ {
+ status: 200,
+ },
+ );
+ },
+ ),
+]; | TypeScript | `r`์ด ์ค๋ณต ๋ณ์๋ผ ์ฌ๊ธฐ๋ `m`์ด ๋์๊ตฐ์..
`r`์ `reviewCycle`๋ก ๋ฐ๊พธ๋ฉด ์ฌ๊ธฐ๋ `r`์ด์ด๋ ๊ด์ฐฎ์๋ณด์
๋๋ค. ํน์ ์ข ๋ ๋ช
ํํ `reviewee`์ด๋ ์ข๊ฒ ๊ตฌ์!
์ทจํฅ ์ฐจ์ด์ผ ์ ์๊ฒ ์ง๋ง ๊ฐ์ธ์ ์ผ๋ก๋ ํ ์ค ์ ๋์ ์ค์ฝํ์ผ ๋๋ ์ถ์ฝ ๋ณ์ ์ฌ์ฉํด๋ ํฌ๊ฒ ๊ฐ๋
์ฑ์ ํด์น์ง ์์ ๊ด์ฐฎ๋ค๊ณ ์๊ฐํด์~ |
@@ -0,0 +1,163 @@
+import { Person, personIDMap, personMap } from './../auth/data';
+import { API_PATH } from '@apis/constants';
+import { personList } from '@mocks/auth/data';
+import { HttpResponse, http } from 'msw';
+import { reviewCycleList } from './data';
+import { ReviewCycleRequest } from '@apis/review/type';
+import { JWTPayload, JWTVerifyResult, jwtVerify } from 'jose';
+import { v4 as uuidv4 } from 'uuid';
+import { validateAccessToken } from '@mocks/utils';
+import { secretKey } from '@mocks/constants';
+
+export const reviewHandlers = [
+ http.get(API_PATH.MEMBERS, async ({ request }) => {
+ const res = await validateAccessToken(request);
+
+ if (res) {
+ return res;
+ }
+
+ return HttpResponse.json({
+ members: personList.map(m => ({
+ entityId: m.entityId,
+ name: m.name,
+ })),
+ });
+ }),
+
+ http.get(API_PATH.REVIEW_CYCLES, async ({ request }) => {
+ const res = await validateAccessToken(request);
+
+ if (res) {
+ return res;
+ }
+
+ const formatted = reviewCycleList.map(r => ({
+ entityId: r.entityId,
+ name: r.name,
+ creator: r.creator.name,
+ reviewees: r.reviewees.map(m => ({ entityId: m.entityId, name: m.name })),
+ question: {
+ title: r.question.title,
+ description: r.question.description,
+ },
+ updatedAt: r.updatedAt,
+ }));
+
+ return HttpResponse.json({
+ reviewCycles: formatted,
+ });
+ }),
+
+ http.post<never, ReviewCycleRequest>(API_PATH.REVIEW_CYCLES, async ({ request }) => {
+ const res = await validateAccessToken(request);
+
+ if (res) {
+ return res;
+ }
+
+ const accessToken = request.headers.get('Authorization')?.split(' ')[1];
+ const verified = accessToken && (await jwtVerify(accessToken, secretKey));
+ const email = (verified as JWTVerifyResult<JWTPayload>).payload.email;
+
+ const req = await request.json();
+ const reviewees = req.reviewees.map(id => personIDMap.get(id) ?? ({} as Person));
+
+ reviewCycleList.push({
+ entityId: uuidv4(),
+ name: req.name,
+ creator: personMap.get(email as string) ?? ({} as Person),
+ reviewees: reviewees,
+ question: {
+ title: req.title,
+ description: req.description,
+ },
+ updatedAt: new Date().toISOString(),
+ });
+
+ return HttpResponse.json(
+ {
+ reviewCycle: reviewCycleList[reviewCycleList.length - 1],
+ },
+ {
+ status: 201,
+ },
+ );
+ }),
+
+ http.delete<{ entityId: string }>(`${API_PATH.REVIEW_CYCLES}/:entityId`, async ({ request, params }) => {
+ const res = await validateAccessToken(request);
+
+ if (res) {
+ return res;
+ }
+
+ const index = reviewCycleList.splice(
+ reviewCycleList.findIndex(r => r.entityId === params.entityId),
+ 1,
+ );
+
+ if (index.length === 0) {
+ return HttpResponse.json(
+ {
+ error: { message: '๋ฆฌ๋ทฐ ์ฌ์ดํด์ด ์กด์ฌํ์ง ์์ต๋๋ค' },
+ },
+ {
+ status: 404,
+ },
+ );
+ }
+
+ return HttpResponse.json({
+ status: 200,
+ });
+ }),
+
+ http.put<{ entityId: string }, ReviewCycleRequest>(
+ `${API_PATH.REVIEW_CYCLES}/:entityId`,
+ async ({ request, params }) => {
+ const res = await validateAccessToken(request);
+
+ if (res) {
+ return res;
+ }
+
+ const index = reviewCycleList.findIndex(r => r.entityId === params.entityId);
+
+ if (index === -1) {
+ return HttpResponse.json(
+ {
+ error: { message: '๋ฆฌ๋ทฐ ์ฌ์ดํด์ด ์กด์ฌํ์ง ์์ต๋๋ค' },
+ },
+ {
+ status: 404,
+ },
+ );
+ }
+
+ const req = await request.json();
+ const prev = reviewCycleList[index];
+
+ reviewCycleList[index] = {
+ entityId: params.entityId,
+ name: req.name,
+ creator: prev.creator,
+ reviewees: req.reviewees.map(id => personIDMap.get(id) ?? ({} as Person)),
+ question: {
+ title: req.title,
+ description: req.description,
+ },
+ updatedAt: new Date().toISOString(),
+ };
+
+ return HttpResponse.json(
+ {
+ entityId: params.entityId,
+ },
+ {
+ status: 200,
+ },
+ );
+ },
+ ),
+]; | TypeScript | [์ ์]
์๋๋ก `push`๋ฅผ ํ๋ฉด ๋งจ ๋ค์ ๋ค์ด๊ฐ๊ฒ ๋ผ์ ์ต์ ์์ผ๋ก ๋ณด์ด์ง ์๊ฒ ๋๋๋ผ๊ตฌ์~
์ ๋ ฌ์ ํ ๋ฒ ํด ์ฃผ๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,10 @@
+import { Member, ReviewCycle } from './entities';
+
+export type ReviewCycleRequest = {
+ name: ReviewCycle['name'];
+ reviewees: Member['entityId'][];
+ title: string;
+ description: string;
+};
+
+export type ReviewCycleResponse = Pick<ReviewCycle, 'entityId'>; | TypeScript | ์ ์๋์ฒ๋ผ ํ์ดํํ๋ฉด ๊ฐ์ ๋งฅ๋ฝ์์ด ์ ๋๋ฌ๋๋ ค๋์?
```ts
export type ReviewCycleRequest = {
name: ReviewCycle['name'];
reviewees: Member['entityId'][];
title: string;
description: string;
};
export type ReviewCycleResponse = Pick<ReviewCycle, 'entityId'>;
``` |
@@ -0,0 +1,90 @@
+import { API_PATH } from '@apis/constants';
+import { useQuery } from '@apis/common/useQuery';
+import { ReviewCycle } from './entities';
+import { ReviewCycleRequest, ReviewCycleResponse } from './type';
+import { useDelete, usePost, usePut } from '@apis/common/useMutation';
+import { get } from 'lodash';
+
+export function useGetReviewCycles() {
+ const {
+ data,
+ isLoading,
+ mutate: refetchReviewCycle,
+ } = useQuery<{ reviewCycles: ReviewCycle[] }>(API_PATH.REVIEW_CYCLES);
+
+ return {
+ reviewCycles: data?.reviewCycles,
+ isLoading,
+ refetchReviewCycle,
+ };
+}
+
+export function useCreateReviewCycle({
+ onSuccess,
+ onError,
+}: {
+ onSuccess: () => void;
+ onError: (message: string) => void;
+}) {
+ const { trigger, isMutating } = usePost<ReviewCycleRequest, ReviewCycleResponse>({
+ endpoint: API_PATH.REVIEW_CYCLES,
+ onSuccess: onSuccess,
+ onError: err => {
+ const errorMessage = get(err, 'response.data.error.message', '๋ฆฌ๋ทฐ ์ฌ์ดํด ์์ฑ์ ์คํจํ์ต๋๋ค.');
+ onError(errorMessage);
+ },
+ });
+
+ return {
+ createReviewCycle: (reviewCycle: ReviewCycleRequest) => trigger(reviewCycle),
+ isMutating,
+ };
+}
+
+export function useUpdateReviewCycle({
+ entityId,
+ onSuccess,
+ onError,
+}: {
+ entityId?: number;
+ onSuccess: () => void;
+ onError: (message: string) => void;
+}) {
+ const { trigger, isMutating } = usePut<ReviewCycleRequest, ReviewCycleResponse>({
+ endpoint: entityId ? `${API_PATH.REVIEW_CYCLES}/${entityId}` : null,
+ onSuccess: onSuccess,
+ onError: err => {
+ const errorMessage = get(err, 'response.data.error.message', '๋ฆฌ๋ทฐ ์ฌ์ดํด ์์ ์ ์คํจํ์ต๋๋ค.');
+ onError(errorMessage);
+ },
+ });
+
+ return {
+ updateReviewCycle: (reviewCycle: ReviewCycleRequest) => trigger(reviewCycle),
+ isMutating,
+ };
+}
+
+export function useDeleteReviewCycle({
+ entityId,
+ onSuccess,
+ onError,
+}: {
+ entityId: number;
+ onSuccess: () => void;
+ onError: (message: string) => void;
+}) {
+ const { trigger, isMutating } = useDelete({
+ endpoint: `${API_PATH.REVIEW_CYCLES}/${entityId}`,
+ onSuccess,
+ onError: err => {
+ const errorMessage = get(err, 'response.data.error.message', '๋ฆฌ๋ทฐ ์ฌ์ดํด ์ญ์ ์ ์คํจํ์ต๋๋ค.');
+ onError(errorMessage);
+ },
+ });
+
+ return {
+ deleteReviewCycle: trigger,
+ isMutating,
+ };
+} | TypeScript | ์ด ๋ถ๋ถ์ SWR ๊ธฐ๋ฐ์ ์ธํฐํ์ด์ค(trigger)๋ฅผ ๊ฐ์ถ๊ณ ์ธํฐํ์ด์ค๋ฅผ ํต์ผํ๊ธฐ ์ํ ๋ชฉ์ ์ด์์ด์. ์ถํ์ SWR์ tanstack-query ๋ฑ ๋ค๋ฅธ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ก ๋ณ๊ฒฝํ๋๋ผ๋ ๋์ผํ๊ฒ createReviewCycle ์ธํฐํ์ด์ค๋ฅผ ์ฌ์ฉํ๋๋ก ํด์ ์ฌ์ฉ์ฒ์์๋ ์ฝ๋๋ฅผ ์์ ํ ํ์๊ฐ ์๋๋ก ํ๊ณ ์ ํ์ต๋๋ค. |
@@ -0,0 +1,17 @@
+import { Rule } from 'antd/lib/form';
+
+export const REVIEW_CYCLE_FORM_NAMES = {
+ name: 'name',
+ reviewees: 'reviewees',
+ question: {
+ title: 'title',
+ description: 'description',
+ },
+} as const;
+
+export const REVIEW_CYCLE_RULES: Record<string, Rule[]> = {
+ reviewCycleName: [{ required: true, message: '๋ฆฌ๋ทฐ ์ ์ฑ
์ด๋ฆ์ ์
๋ ฅํ์ธ์.' }],
+ reviewees: [{ required: true, message: '๋ฆฌ๋ทฐ ๋ฐ๋ ์ฌ๋์ ์ ํํ์ธ์.' }],
+ questionTitle: [{ required: true, message: '์ง๋ฌธ ์ ๋ชฉ์ ์
๋ ฅํ์ธ์.' }],
+ questionDescription: [{ required: true, message: '์ง๋ฌธ ์ค๋ช
์ ์
๋ ฅํ์ธ์.' }],
+}; | TypeScript | ํด๋น form์ ์์๊ฐ ์ด๋ป๊ฒ ๊ตฌ์ฑ๋์ด ์๋์ง ํ๋์ ํ์
ํ๊ธฐ ์ฝ์ง ์์๊น ํ์๋๋ฐ, ํ๋์ ๊ฐ์ฒด๋ก ๋ฌถ๋๊ฒ ๋์์ผ๋ ค๋ ์ถ๊ตฐ์! |
@@ -0,0 +1,25 @@
+import { DeleteOutlined } from '@ant-design/icons';
+import { useDeleteReviewCycle, useGetReviewCycles } from '@apis/review/useReviewCycles';
+import { message } from 'antd';
+
+function DeleteButton({ entityId }: { entityId: number }) {
+ const { refetchReviewCycle } = useGetReviewCycles();
+ const { deleteReviewCycle } = useDeleteReviewCycle({
+ entityId,
+ onSuccess: refetchReviewCycle,
+ onError: message.error,
+ });
+
+ return (
+ <button
+ onClick={e => {
+ e.stopPropagation();
+ deleteReviewCycle();
+ }}
+ >
+ <DeleteOutlined />
+ </button>
+ );
+}
+
+export default DeleteButton; | Unknown | ํ์ฌ ํ
์ด๋ธ onRowClick ์ ๋ฆฌ๋ทฐ ์ฌ์ดํด ์์ ๋ชจ๋ฌ์ด ์ด๋ฆฌ๋๋ก ์ด๋ฒคํธ๋ฅผ ๋ฑ๋กํด๋์๋๋ฐ์, ์ญ์ ๋ฒํผ ์์๋ ์ด๋ฒคํธ ์ ํ๋ฅผ ๋ง๋๋ก ํ์ต๋๋ค. |
@@ -0,0 +1,25 @@
+import { DeleteOutlined } from '@ant-design/icons';
+import { useDeleteReviewCycle, useGetReviewCycles } from '@apis/review/useReviewCycles';
+import { message } from 'antd';
+
+function DeleteButton({ entityId }: { entityId: number }) {
+ const { refetchReviewCycle } = useGetReviewCycles();
+ const { deleteReviewCycle } = useDeleteReviewCycle({
+ entityId,
+ onSuccess: refetchReviewCycle,
+ onError: message.error,
+ });
+
+ return (
+ <button
+ onClick={e => {
+ e.stopPropagation();
+ deleteReviewCycle();
+ }}
+ >
+ <DeleteOutlined />
+ </button>
+ );
+}
+
+export default DeleteButton; | Unknown | ๋ต button์ผ๋ก ๊ฐ์ธ๋๊ฒ ์ข๊ฒ ๊ตฐ์.
> ๋ฐ์ํ์ต๋๋ค! [refactor: ์ญ์ ๋ฒํผ ๊ตฌ์กฐ ๋ณ๊ฒฝ](https://github.com/lemonbase-labs/journee-on-boarding-project/pull/7/commits/2201091e80c11c71bb97c3cf131410067cb04478) |
@@ -0,0 +1,67 @@
+import { Button, Form, Input, Select, Space } from 'antd';
+import { REVIEW_CYCLE_FORM_NAMES, REVIEW_CYCLE_RULES } from './constants';
+import useMembers from '@apis/review/useMembers';
+import { ReviewCycleRequest } from '@apis/review/type';
+import { ReviewCycle } from '@apis/review/entities';
+
+interface Props {
+ onFinish: (values: ReviewCycleRequest) => void;
+ onReset: () => void;
+ initialValues?: {
+ name: ReviewCycle['name'];
+ reviewees: number[];
+ title: ReviewCycle['question']['title'];
+ description: ReviewCycle['question']['description'];
+ };
+ confirmButtonProps?: { text: string };
+ deleteButtonProps?: { text: string; handleClick: () => void };
+}
+
+export default function ReviewCycleForm({
+ onFinish,
+ onReset,
+ initialValues,
+ confirmButtonProps = { text: 'ํ์ธ' },
+ deleteButtonProps,
+}: Props) {
+ const { members, isLoading } = useMembers();
+
+ return (
+ <Form labelAlign="right" onFinish={onFinish} onReset={onReset} initialValues={initialValues}>
+ <Form.Item label="๋ฆฌ๋ทฐ ์ ์ฑ
์ด๋ฆ" name={REVIEW_CYCLE_FORM_NAMES.name} rules={REVIEW_CYCLE_RULES.reviewCycleName}>
+ <Input />
+ </Form.Item>
+
+ <Form.Item label="๋ฆฌ๋ทฐ ๋ฐ๋ ์ฌ๋" name={REVIEW_CYCLE_FORM_NAMES.reviewees} rules={REVIEW_CYCLE_RULES.reviewees}>
+ <Select
+ mode="multiple"
+ loading={isLoading}
+ placeholder="๋ฆฌ๋ทฐ ๋ฐ๋ ์ฌ๋์ ์ ํํด์ฃผ์ธ์."
+ optionFilterProp="label"
+ options={members?.map(m => ({ key: m.entityId, label: m.name, value: m.entityId }))}
+ />
+ </Form.Item>
+
+ <Form.Item label="์ง๋ฌธ" name={REVIEW_CYCLE_FORM_NAMES.question.title} rules={REVIEW_CYCLE_RULES.questionTitle}>
+ <Input />
+ </Form.Item>
+
+ <Form.Item
+ label="์ง๋ฌธ ์ค๋ช
"
+ name={REVIEW_CYCLE_FORM_NAMES.question.description}
+ rules={REVIEW_CYCLE_RULES.questionDescription}
+ >
+ <Input />
+ </Form.Item>
+ <Form.Item style={{ textAlign: 'right' }}>
+ <Space size={10}>
+ <Button htmlType="reset">์ทจ์</Button>
+ {deleteButtonProps && <Button onClick={deleteButtonProps.handleClick}>{deleteButtonProps.text}</Button>}
+ <Button type="primary" htmlType="submit">
+ {confirmButtonProps.text}
+ </Button>
+ </Space>
+ </Form.Item>
+ </Form>
+ );
+} | Unknown | ์ํ.. ์ ๋ ์ง๊ด์ ์ด๋ผ๊ณ ์๊ฐํ๋๋ฐ, ์ ์ง๋ณด์ ์ฐจ์์์ ์ด๋ค ์ด๋ ค์์ธ์ง ํน์ ์ด๋ป๊ฒ ๋ถ๋ฆฌ๋์ด์ผ ํ๋์ง ์ข ๋ ์ค๋ช
ํด์ฃผ์ค ์ ์์๊น์?
์ค์ ๋ก ํ์ฌ ๋ ๋ชฌ๋ฒ ์ด์ค ๋ชจ๋ฌ ํ
์ธ useBasicModal๋ ๋น์ทํ ํจํด์ผ๋ก ์ฌ์ฉํ๊ณ ์๋๋ฐ, ์ ๋ ์ ์ง๋ณด์ ์ฐจ์์์ ์ด๋ ค์์ด ์์ด์ ๊ฐ์ ํด์ผ ํ๋ค๊ณ ์๊ฐํ์ง ์์์ด์์! |
@@ -0,0 +1,43 @@
+import { Button } from 'antd';
+import { RoundContent } from 'components/common/RoundContent';
+import useReviewCycleCreateModal from './ReviewCycleModals/useReviewCycleCreateModal';
+import ReviewCycleTable from './ReviewCycleTable';
+import useReviewCycleUpdateModal from './ReviewCycleModals/useReviewCycleUpdateModal';
+import useSelectedReviewCycle from './useSelectedReviewCycle';
+
+function ReviewCycles() {
+ const { selectedReviewCycle } = useSelectedReviewCycle();
+
+ const reviewCycleCreateModal = useReviewCycleCreateModal();
+ const reviewCycleUpdateModal = useReviewCycleUpdateModal({
+ entityId: selectedReviewCycle?.entityId,
+ });
+
+ function openReviewCycleCreateModal() {
+ reviewCycleCreateModal.open();
+ }
+
+ function openReviewCycleUpdateModal() {
+ reviewCycleUpdateModal.open();
+ }
+
+ return (
+ <RoundContent>
+ <RoundContent.Header
+ title="๋ฆฌ๋ทฐ ์ ์ฑ
๋ชฉ๋ก"
+ rightArea={
+ <Button type="primary" size="large" onClick={openReviewCycleCreateModal}>
+ ๋ฆฌ๋ทฐ ์ ์ฑ
์์ฑ
+ </Button>
+ }
+ />
+ <RoundContent.Body>
+ <ReviewCycleTable onRowClick={openReviewCycleUpdateModal} />
+ </RoundContent.Body>
+ {reviewCycleCreateModal.render()}
+ {reviewCycleUpdateModal.render()}
+ </RoundContent>
+ );
+}
+
+export default ReviewCycles; | Unknown | ๋ค!! ๋ฐ์ํ์ต๋๋ค!
[refactor: ์ธ์คํด์ค camelcase๋ก ์์ ](https://github.com/lemonbase-labs/journee-on-boarding-project/pull/7/commits/3a4fecb79aa6c1a53951900d79c308af0a87d940) |
@@ -0,0 +1,90 @@
+import { API_PATH } from '@apis/constants';
+import { useQuery } from '@apis/common/useQuery';
+import { ReviewCycle } from './entities';
+import { ReviewCycleRequest, ReviewCycleResponse } from './type';
+import { useDelete, usePost, usePut } from '@apis/common/useMutation';
+import { get } from 'lodash';
+
+export function useGetReviewCycles() {
+ const {
+ data,
+ isLoading,
+ mutate: refetchReviewCycle,
+ } = useQuery<{ reviewCycles: ReviewCycle[] }>(API_PATH.REVIEW_CYCLES);
+
+ return {
+ reviewCycles: data?.reviewCycles,
+ isLoading,
+ refetchReviewCycle,
+ };
+}
+
+export function useCreateReviewCycle({
+ onSuccess,
+ onError,
+}: {
+ onSuccess: () => void;
+ onError: (message: string) => void;
+}) {
+ const { trigger, isMutating } = usePost<ReviewCycleRequest, ReviewCycleResponse>({
+ endpoint: API_PATH.REVIEW_CYCLES,
+ onSuccess: onSuccess,
+ onError: err => {
+ const errorMessage = get(err, 'response.data.error.message', '๋ฆฌ๋ทฐ ์ฌ์ดํด ์์ฑ์ ์คํจํ์ต๋๋ค.');
+ onError(errorMessage);
+ },
+ });
+
+ return {
+ createReviewCycle: (reviewCycle: ReviewCycleRequest) => trigger(reviewCycle),
+ isMutating,
+ };
+}
+
+export function useUpdateReviewCycle({
+ entityId,
+ onSuccess,
+ onError,
+}: {
+ entityId?: number;
+ onSuccess: () => void;
+ onError: (message: string) => void;
+}) {
+ const { trigger, isMutating } = usePut<ReviewCycleRequest, ReviewCycleResponse>({
+ endpoint: entityId ? `${API_PATH.REVIEW_CYCLES}/${entityId}` : null,
+ onSuccess: onSuccess,
+ onError: err => {
+ const errorMessage = get(err, 'response.data.error.message', '๋ฆฌ๋ทฐ ์ฌ์ดํด ์์ ์ ์คํจํ์ต๋๋ค.');
+ onError(errorMessage);
+ },
+ });
+
+ return {
+ updateReviewCycle: (reviewCycle: ReviewCycleRequest) => trigger(reviewCycle),
+ isMutating,
+ };
+}
+
+export function useDeleteReviewCycle({
+ entityId,
+ onSuccess,
+ onError,
+}: {
+ entityId: number;
+ onSuccess: () => void;
+ onError: (message: string) => void;
+}) {
+ const { trigger, isMutating } = useDelete({
+ endpoint: `${API_PATH.REVIEW_CYCLES}/${entityId}`,
+ onSuccess,
+ onError: err => {
+ const errorMessage = get(err, 'response.data.error.message', '๋ฆฌ๋ทฐ ์ฌ์ดํด ์ญ์ ์ ์คํจํ์ต๋๋ค.');
+ onError(errorMessage);
+ },
+ });
+
+ return {
+ deleteReviewCycle: trigger,
+ isMutating,
+ };
+} | TypeScript | ์คํธ ์ธํฐํ์ด์ค ํต์ผ ๋ชฉ์ ! ์ดํดํ์ต๋๋ค~
๊ณ ๋ ๋ค๋ฉด ๊ฐ์ ํ์ผ [L87](https://github.com/lemonbase-labs/journee-on-boarding-project/pull/7/files#diff-3ab91e36eb619267b0f18915f2e642a8452aece2c4e8220b0bce854dc2e8d68eR87)์ `deleteReviewCycle: trigger`๋ ์ ์ฒ๋ฆฌ๊ฐ ๋๋ฝ๋ ๊ฒ ๊ฐ์ ๊ฐ์ด ๋ฐ์ํ๋ฉด ์ข์ ๊ฒ ๊ฐ์์~ |
@@ -0,0 +1,86 @@
+package nextstep.subway.application;
+
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import nextstep.subway.domain.Line;
+import nextstep.subway.domain.LineRepository;
+import nextstep.subway.domain.Station;
+import nextstep.subway.domain.StationRepository;
+import nextstep.subway.dto.LineCreateRequest;
+import nextstep.subway.dto.LineResponse;
+import nextstep.subway.dto.LineUpdateRequest;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+@Transactional(readOnly = true)
+public class LineService {
+ private final LineRepository lineRepository;
+
+ private final StationRepository stationRepository;
+
+ public LineService(LineRepository lineRepository, StationRepository stationRepository) {
+ this.lineRepository = lineRepository;
+ this.stationRepository = stationRepository;
+ }
+
+ @Transactional
+ public LineResponse saveLine(LineCreateRequest lineCreateRequest) {
+ Line persistLine = lineRepository.save(lineCreateRequest.toLine());
+ addStations(persistLine, lineCreateRequest);
+ return LineResponse.of(persistLine);
+ }
+
+ public LineResponse findLine(Long id) {
+ Optional<Line> line = lineRepository.findById(id);
+ return LineResponse.of(line.get());
+ }
+
+ public List<LineResponse> findAllLines() {
+ return lineRepository.findAll().stream()
+ .map(LineResponse::of)
+ .collect(Collectors.toList());
+ }
+
+ @Transactional
+ public LineResponse updateLine(Long id, LineUpdateRequest lineUpdateRequest) {
+ Line line = lineRepository.findById(id).get();
+ line.updateLine(lineUpdateRequest);
+ return LineResponse.of(line);
+ }
+
+ @Transactional
+ public void deleteLineById(Long id) {
+ Optional<Line> line = lineRepository.findById(id);
+ if (line.isPresent()) {
+ line.get().clearRelatedLines();
+ lineRepository.delete(line.get());
+ }
+ }
+
+ private void addStations(Line persistLine, LineCreateRequest lineCreateRequest) {
+ addUpLine(persistLine, lineCreateRequest);
+ addDownLine(persistLine, lineCreateRequest);
+ }
+
+ private void addUpLine(Line line, LineCreateRequest lineCreateRequest) {
+ if (lineCreateRequest.hasUpStationsId()) {
+ Station station = getStation(lineCreateRequest.getUpStationId());
+ line.addStation(station);
+ }
+ }
+
+ private void addDownLine(Line line, LineCreateRequest lineCreateRequest) {
+ if (lineCreateRequest.hasDownStationsId()) {
+ Station station = getStation(lineCreateRequest.getDownStationId());
+ line.addStation(station);
+ }
+ }
+
+ private Station getStation(Long stationId) {
+ return stationRepository.findById(stationId)
+ .orElseThrow(() -> new NoSuchElementException("id(" + stationId + ")์ ํด๋นํ๋ ์ญ์ด ์์ต๋๋ค."));
+ }
+} | Java | deleteById ๊ตฌํ์ฒด๋ฅผ ๋ณด์๋ฉด ์กฐํ ํ์ ๊ฐ์ด ์์ ๊ฒฝ์ฐ์๋ง ์ญ์ ํ๊ณ ์์ต๋๋ค.
์ด๋ฐ ๋ถ๋ถ๋ค์ ์ ํ๋ฆฌ์ผ์ด์
์์ ์ง์ ์์ฑํ๊ธฐ๋ณด๋ค๋ Infrastructre layer์์ ๋ด๋นํ๋ ๊ฒ์ด ์ข๋ค๊ณ ์๊ฐํ๋๋ฐ
์ด๋ป๊ฒ ์๊ฐํ์๋์?
```java
@Transactional
@Override
public void deleteById(ID id) {
Assert.notNull(id, ID_MUST_NOT_BE_NULL);
delete(findById(id).orElseThrow(() -> new EmptyResultDataAccessException(
String.format("No %s entity with id %s exists!", entityInformation.getJavaType(), id), 1)));
} |
@@ -0,0 +1,86 @@
+package nextstep.subway.application;
+
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import nextstep.subway.domain.Line;
+import nextstep.subway.domain.LineRepository;
+import nextstep.subway.domain.Station;
+import nextstep.subway.domain.StationRepository;
+import nextstep.subway.dto.LineCreateRequest;
+import nextstep.subway.dto.LineResponse;
+import nextstep.subway.dto.LineUpdateRequest;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+@Transactional(readOnly = true)
+public class LineService {
+ private final LineRepository lineRepository;
+
+ private final StationRepository stationRepository;
+
+ public LineService(LineRepository lineRepository, StationRepository stationRepository) {
+ this.lineRepository = lineRepository;
+ this.stationRepository = stationRepository;
+ }
+
+ @Transactional
+ public LineResponse saveLine(LineCreateRequest lineCreateRequest) {
+ Line persistLine = lineRepository.save(lineCreateRequest.toLine());
+ addStations(persistLine, lineCreateRequest);
+ return LineResponse.of(persistLine);
+ }
+
+ public LineResponse findLine(Long id) {
+ Optional<Line> line = lineRepository.findById(id);
+ return LineResponse.of(line.get());
+ }
+
+ public List<LineResponse> findAllLines() {
+ return lineRepository.findAll().stream()
+ .map(LineResponse::of)
+ .collect(Collectors.toList());
+ }
+
+ @Transactional
+ public LineResponse updateLine(Long id, LineUpdateRequest lineUpdateRequest) {
+ Line line = lineRepository.findById(id).get();
+ line.updateLine(lineUpdateRequest);
+ return LineResponse.of(line);
+ }
+
+ @Transactional
+ public void deleteLineById(Long id) {
+ Optional<Line> line = lineRepository.findById(id);
+ if (line.isPresent()) {
+ line.get().clearRelatedLines();
+ lineRepository.delete(line.get());
+ }
+ }
+
+ private void addStations(Line persistLine, LineCreateRequest lineCreateRequest) {
+ addUpLine(persistLine, lineCreateRequest);
+ addDownLine(persistLine, lineCreateRequest);
+ }
+
+ private void addUpLine(Line line, LineCreateRequest lineCreateRequest) {
+ if (lineCreateRequest.hasUpStationsId()) {
+ Station station = getStation(lineCreateRequest.getUpStationId());
+ line.addStation(station);
+ }
+ }
+
+ private void addDownLine(Line line, LineCreateRequest lineCreateRequest) {
+ if (lineCreateRequest.hasDownStationsId()) {
+ Station station = getStation(lineCreateRequest.getDownStationId());
+ line.addStation(station);
+ }
+ }
+
+ private Station getStation(Long stationId) {
+ return stationRepository.findById(stationId)
+ .orElseThrow(() -> new NoSuchElementException("id(" + stationId + ")์ ํด๋นํ๋ ์ญ์ด ์์ต๋๋ค."));
+ }
+} | Java | ๋ฉ์๋ ๋ณ์๋ก ํ ๋นํ์ ์ด์ ๊ฐ ์์ผ์ ๊ฐ์?
``` java
findAll().stream()
.map(LineResponse::of)
.collect(Collectors.toList());
``` |
@@ -1,16 +1,35 @@
package nextstep.subway.domain;
-import javax.persistence.*;
+import java.util.Objects;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
@Entity
public class Station extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
+
@Column(unique = true)
private String name;
- public Station() {
+ @ManyToOne
+ @JoinColumn(name = "line_id")
+ private Line line;
+
+ private Integer distance;
+
+ protected Station() {
+ }
+
+ Station(Long id, String name) {
+ this.id = id;
+ this.name = name;
}
public Station(String name) {
@@ -24,4 +43,61 @@ public Long getId() {
public String getName() {
return name;
}
+
+ public Integer getDistance() {
+ return distance;
+ }
+
+ public Line getLine() {
+ return line;
+ }
+
+ public void setLine(Line line) {
+ if (Objects.nonNull(this.line)) {
+ this.line.getStations().removeStation(this);
+ }
+ this.line = line;
+ if (!line.getStations().containsStation(this)) {
+ line.getStations().addStation(this);
+ }
+ }
+
+ public void clearLine() {
+ this.line = null;
+ }
+
+ public void clearRelatedStation() {
+ if (line != null) {
+ this.line.getStations().removeStation(this);
+ }
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ Station station = (Station) o;
+
+ return id.equals(station.id);
+ }
+
+ @Override
+ public int hashCode() {
+ return id.hashCode();
+ }
+
+ @Override
+ public String toString() {
+ return "Station{" +
+ "id=" + id +
+ ", name='" + name + '\'' +
+ ", line=" + line +
+ ", distance=" + distance +
+ '}';
+ }
} | Java | ์ญ์ด Line์ ๊ฐ์ง๋๊ฒ ๋ง์๊น์?
ํ๋์ ์ญ์ด ์ฌ๋ฌ ๋
ธ์ ์ ์ํ๋ฉด ์ด๋ป๊ฒ ๋๋์.
์๋ฅผ ๋ค์ด ๊ฐ๋จ์ญ์ 2ํธ์ ๊ณผ ์ ๋ถ๋น์ ๋๊ฐ์ง๊ฐ ์์ด์. |
@@ -0,0 +1,156 @@
+package nextstep.subway.acceptance;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import io.restassured.RestAssured;
+import io.restassured.response.ExtractableResponse;
+import io.restassured.response.Response;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.server.LocalServerPort;
+import org.springframework.http.HttpStatus;
+import org.springframework.test.context.jdbc.Sql;
+
+@Sql("classpath:testdb/truncate.sql")
+@DisplayName("์งํ์ฒ ๋
ธ์ ๊ด๋ จ ๊ธฐ๋ฅ")
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+class LineAcceptanceTest extends AcceptanceTest {
+ private final static String API_URL_LINES = "/lines";
+ private final static String COLOR_RED = "bg-red-400";
+ private final static String LINE_NUMBER_1 = "1ํธ์ ";
+ private final static String LINE_NUMBER_2 = "2ํธ์ ";
+ @LocalServerPort
+ int port;
+
+ @BeforeEach
+ public void setUp() {
+ if (RestAssured.port == RestAssured.UNDEFINED_PORT) {
+ RestAssured.port = port;
+ }
+ }
+
+
+ /**
+ * When ์งํ์ฒ ๋
ธ์ ์ ์์ฑํ๋ฉด
+ * Then ์งํ์ฒ ๋
ธ์ ๋ชฉ๋ก ์กฐํ ์ ์์ฑํ ๋
ธ์ ์ ์ฐพ์ ์ ์๋ค
+ */
+ @DisplayName("์งํ์ฒ ๋
ธ์ ์์ฑ")
+ @Test
+ void createLine() {
+ // when
+ registerLine(LINE_NUMBER_2);
+
+ // then
+ List<String> lineNames = findLines().jsonPath().getList("name", String.class);
+ assertThat(lineNames).contains(LINE_NUMBER_2);
+
+ }
+
+ /**
+ * Given 2๊ฐ์ ์งํ์ฒ ๋
ธ์ ์ ์์ฑํ๊ณ
+ * When ์งํ์ฒ ๋
ธ์ ๋ชฉ๋ก์ ์กฐํํ๋ฉด
+ * Then ์งํ์ฒ ๋
ธ์ ๋ชฉ๋ก ์กฐํ ์ 2๊ฐ์ ๋
ธ์ ์ ์กฐํํ ์ ์๋ค.
+ */
+ @DisplayName("์งํ์ฒ ๋
ธ์ ๋ชฉ๋ก ์กฐํ")
+ @Test
+ void getLines() {
+ // given
+ registerLine(LINE_NUMBER_1);
+ registerLine(LINE_NUMBER_2);
+
+ // when
+ List<String> lineNames = findLines().jsonPath().getList("name", String.class);
+
+ // then
+ assertThat(lineNames).contains(LINE_NUMBER_1, LINE_NUMBER_2);
+ }
+
+ /**
+ * Given ์งํ์ฒ ๋
ธ์ ์ ์์ฑํ๊ณ
+ * When ์์ฑํ ์งํ์ฒ ๋
ธ์ ์ ์กฐํํ๋ฉด
+ * Then ์์ฑํ ์งํ์ฒ ๋
ธ์ ์ ์ ๋ณด๋ฅผ ์๋ต๋ฐ์ ์ ์๋ค.
+ */
+ @DisplayName("์งํ์ฒ ๋
ธ์ ์กฐํ")
+ @Test
+ void getLine() {
+ // given
+ String lineId = registerLine(LINE_NUMBER_2).jsonPath().getString("id");
+
+ // when
+ ExtractableResponse<Response> response = findLine(lineId);
+
+ // then
+ assertThat(response.statusCode()).isEqualTo(HttpStatus.OK.value());
+ }
+
+ /**
+ * Given ์งํ์ฒ ๋
ธ์ ์ ์์ฑํ๊ณ
+ * When ์์ฑํ ์งํ์ฒ ๋
ธ์ ์ ์์ ํ๋ฉด
+ * Then ํด๋น ์งํ์ฒ ๋
ธ์ ์ ๋ณด๋ ์์ ๋๋ค
+ */
+
+ @DisplayName("์งํ์ฒ ๋
ธ์ ์์ ")
+ @Test
+ void updateLine() {
+ // given
+ String lineId = registerLine(LINE_NUMBER_2).jsonPath().getString("id");
+
+ // when
+ modifyLine(lineId, COLOR_RED);
+
+ // then
+ String actual = findLine(lineId).jsonPath().getString("color");
+ assertThat(actual).isEqualTo(COLOR_RED);
+ }
+
+ /**
+ * Given ์งํ์ฒ ๋
ธ์ ์ ์์ฑํ๊ณ
+ * When ์์ฑํ ์งํ์ฒ ๋
ธ์ ์ ์ญ์ ํ๋ฉด
+ * Then ํด๋น ์งํ์ฒ ๋
ธ์ ์ ๋ณด๋ ์ญ์ ๋๋ค
+ */
+ @DisplayName("์งํ์ฒ ๋
ธ์ ์ญ์ ")
+ @Test
+ void deleteLine() {
+ // given
+ String lineId = registerLine(LINE_NUMBER_2).jsonPath().getString("id");
+
+ // when
+ removeLine(lineId);
+ List<String> lineNames = findLines().jsonPath().getList("name", String.class);
+
+ // then
+ assertThat(lineNames.isEmpty() || !lineNames.contains(LINE_NUMBER_2)).isTrue();
+ }
+
+ private ExtractableResponse<Response> registerLine(String lineName) {
+ Map<String, Object> lineMap = new HashMap<>();
+ lineMap.put("name", lineName);
+ lineMap.put("color", "red");
+ lineMap.put("distance", 2);
+ return sendPost(lineMap, API_URL_LINES);
+ }
+
+ private ExtractableResponse<Response> findLines() {
+ return sendGet(API_URL_LINES);
+ }
+
+ private ExtractableResponse<Response> findLine(String lineId) {
+ return sendGet(API_URL_LINES + "/{id}", lineId);
+ }
+
+ private ExtractableResponse<Response> modifyLine(String lineId, String color) {
+ Map<String, Object> lineMap = new HashMap<>();
+ lineMap.put("name", "redred");
+ lineMap.put("color", color);
+ return sendPut(lineMap, API_URL_LINES + "/{id}", lineId);
+ }
+
+ private ExtractableResponse<Response> removeLine(String lineId) {
+ return sendDelete(API_URL_LINES + "/{id}", lineId);
+ }
+} | Java | ๋
ธ์ ์์ฑ ์ ์ํ์ข
์ ์ญ๊ณผ ํํ์ข
์ ์ญ์ ๋ฑ๋กํฉ๋๋ค.
๋ฐ๋ผ์ ์ด๋ฒ ๋จ๊ณ์์๋ ์งํ์ฒ ๋
ธ์ ์ ์ญ์ ๋งตํํ๋ ๊ธฐ๋ฅ์ ์์ง ์์ง๋ง ๋
ธ์ ์กฐํ์ ํฌํจ๋ ์ญ ๋ชฉ๋ก์ด ํจ๊ป ์๋ต๋ฉ๋๋ค.
statusCode ์ฝ๋ ๋ฟ๋ง ์๋๋ผ ์ค์ ์๋ต์๋ํด์ ํ
์คํธ ํ ์ ์์ผ๋ฉด ์ข์๊ฒ ๊ฐ์์. |
@@ -0,0 +1,156 @@
+package nextstep.subway.acceptance;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import io.restassured.RestAssured;
+import io.restassured.response.ExtractableResponse;
+import io.restassured.response.Response;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.server.LocalServerPort;
+import org.springframework.http.HttpStatus;
+import org.springframework.test.context.jdbc.Sql;
+
+@Sql("classpath:testdb/truncate.sql")
+@DisplayName("์งํ์ฒ ๋
ธ์ ๊ด๋ จ ๊ธฐ๋ฅ")
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+class LineAcceptanceTest extends AcceptanceTest {
+ private final static String API_URL_LINES = "/lines";
+ private final static String COLOR_RED = "bg-red-400";
+ private final static String LINE_NUMBER_1 = "1ํธ์ ";
+ private final static String LINE_NUMBER_2 = "2ํธ์ ";
+ @LocalServerPort
+ int port;
+
+ @BeforeEach
+ public void setUp() {
+ if (RestAssured.port == RestAssured.UNDEFINED_PORT) {
+ RestAssured.port = port;
+ }
+ }
+
+
+ /**
+ * When ์งํ์ฒ ๋
ธ์ ์ ์์ฑํ๋ฉด
+ * Then ์งํ์ฒ ๋
ธ์ ๋ชฉ๋ก ์กฐํ ์ ์์ฑํ ๋
ธ์ ์ ์ฐพ์ ์ ์๋ค
+ */
+ @DisplayName("์งํ์ฒ ๋
ธ์ ์์ฑ")
+ @Test
+ void createLine() {
+ // when
+ registerLine(LINE_NUMBER_2);
+
+ // then
+ List<String> lineNames = findLines().jsonPath().getList("name", String.class);
+ assertThat(lineNames).contains(LINE_NUMBER_2);
+
+ }
+
+ /**
+ * Given 2๊ฐ์ ์งํ์ฒ ๋
ธ์ ์ ์์ฑํ๊ณ
+ * When ์งํ์ฒ ๋
ธ์ ๋ชฉ๋ก์ ์กฐํํ๋ฉด
+ * Then ์งํ์ฒ ๋
ธ์ ๋ชฉ๋ก ์กฐํ ์ 2๊ฐ์ ๋
ธ์ ์ ์กฐํํ ์ ์๋ค.
+ */
+ @DisplayName("์งํ์ฒ ๋
ธ์ ๋ชฉ๋ก ์กฐํ")
+ @Test
+ void getLines() {
+ // given
+ registerLine(LINE_NUMBER_1);
+ registerLine(LINE_NUMBER_2);
+
+ // when
+ List<String> lineNames = findLines().jsonPath().getList("name", String.class);
+
+ // then
+ assertThat(lineNames).contains(LINE_NUMBER_1, LINE_NUMBER_2);
+ }
+
+ /**
+ * Given ์งํ์ฒ ๋
ธ์ ์ ์์ฑํ๊ณ
+ * When ์์ฑํ ์งํ์ฒ ๋
ธ์ ์ ์กฐํํ๋ฉด
+ * Then ์์ฑํ ์งํ์ฒ ๋
ธ์ ์ ์ ๋ณด๋ฅผ ์๋ต๋ฐ์ ์ ์๋ค.
+ */
+ @DisplayName("์งํ์ฒ ๋
ธ์ ์กฐํ")
+ @Test
+ void getLine() {
+ // given
+ String lineId = registerLine(LINE_NUMBER_2).jsonPath().getString("id");
+
+ // when
+ ExtractableResponse<Response> response = findLine(lineId);
+
+ // then
+ assertThat(response.statusCode()).isEqualTo(HttpStatus.OK.value());
+ }
+
+ /**
+ * Given ์งํ์ฒ ๋
ธ์ ์ ์์ฑํ๊ณ
+ * When ์์ฑํ ์งํ์ฒ ๋
ธ์ ์ ์์ ํ๋ฉด
+ * Then ํด๋น ์งํ์ฒ ๋
ธ์ ์ ๋ณด๋ ์์ ๋๋ค
+ */
+
+ @DisplayName("์งํ์ฒ ๋
ธ์ ์์ ")
+ @Test
+ void updateLine() {
+ // given
+ String lineId = registerLine(LINE_NUMBER_2).jsonPath().getString("id");
+
+ // when
+ modifyLine(lineId, COLOR_RED);
+
+ // then
+ String actual = findLine(lineId).jsonPath().getString("color");
+ assertThat(actual).isEqualTo(COLOR_RED);
+ }
+
+ /**
+ * Given ์งํ์ฒ ๋
ธ์ ์ ์์ฑํ๊ณ
+ * When ์์ฑํ ์งํ์ฒ ๋
ธ์ ์ ์ญ์ ํ๋ฉด
+ * Then ํด๋น ์งํ์ฒ ๋
ธ์ ์ ๋ณด๋ ์ญ์ ๋๋ค
+ */
+ @DisplayName("์งํ์ฒ ๋
ธ์ ์ญ์ ")
+ @Test
+ void deleteLine() {
+ // given
+ String lineId = registerLine(LINE_NUMBER_2).jsonPath().getString("id");
+
+ // when
+ removeLine(lineId);
+ List<String> lineNames = findLines().jsonPath().getList("name", String.class);
+
+ // then
+ assertThat(lineNames.isEmpty() || !lineNames.contains(LINE_NUMBER_2)).isTrue();
+ }
+
+ private ExtractableResponse<Response> registerLine(String lineName) {
+ Map<String, Object> lineMap = new HashMap<>();
+ lineMap.put("name", lineName);
+ lineMap.put("color", "red");
+ lineMap.put("distance", 2);
+ return sendPost(lineMap, API_URL_LINES);
+ }
+
+ private ExtractableResponse<Response> findLines() {
+ return sendGet(API_URL_LINES);
+ }
+
+ private ExtractableResponse<Response> findLine(String lineId) {
+ return sendGet(API_URL_LINES + "/{id}", lineId);
+ }
+
+ private ExtractableResponse<Response> modifyLine(String lineId, String color) {
+ Map<String, Object> lineMap = new HashMap<>();
+ lineMap.put("name", "redred");
+ lineMap.put("color", color);
+ return sendPut(lineMap, API_URL_LINES + "/{id}", lineId);
+ }
+
+ private ExtractableResponse<Response> removeLine(String lineId) {
+ return sendDelete(API_URL_LINES + "/{id}", lineId);
+ }
+} | Java | ์ฑํ ํฝ์ค์ฒ ๋ฐ ๋ฐ์ดํฐ ์ง์ ์ญ์ ํด์ฃผ์
จ์ด์.
๋ค๋ง ์์ฑํด์ผ ํ ๋ฐ์ดํฐ๊ฐ ๋ง๊ฑฐ๋, ์ฐ๊ด ๊ด๊ณ ๋งตํ์ด ์์ผ๋ฉด ์ด๋ป๊ฒ ๋ ์ง ๊ณ ๋ฏผํด๋ณด์๋ฉด ์ข์ ๊ฒ๊ฐ์์. |
@@ -0,0 +1,156 @@
+package nextstep.subway.acceptance;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import io.restassured.RestAssured;
+import io.restassured.response.ExtractableResponse;
+import io.restassured.response.Response;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.server.LocalServerPort;
+import org.springframework.http.HttpStatus;
+import org.springframework.test.context.jdbc.Sql;
+
+@Sql("classpath:testdb/truncate.sql")
+@DisplayName("์งํ์ฒ ๋
ธ์ ๊ด๋ จ ๊ธฐ๋ฅ")
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+class LineAcceptanceTest extends AcceptanceTest {
+ private final static String API_URL_LINES = "/lines";
+ private final static String COLOR_RED = "bg-red-400";
+ private final static String LINE_NUMBER_1 = "1ํธ์ ";
+ private final static String LINE_NUMBER_2 = "2ํธ์ ";
+ @LocalServerPort
+ int port;
+
+ @BeforeEach
+ public void setUp() {
+ if (RestAssured.port == RestAssured.UNDEFINED_PORT) {
+ RestAssured.port = port;
+ }
+ }
+
+
+ /**
+ * When ์งํ์ฒ ๋
ธ์ ์ ์์ฑํ๋ฉด
+ * Then ์งํ์ฒ ๋
ธ์ ๋ชฉ๋ก ์กฐํ ์ ์์ฑํ ๋
ธ์ ์ ์ฐพ์ ์ ์๋ค
+ */
+ @DisplayName("์งํ์ฒ ๋
ธ์ ์์ฑ")
+ @Test
+ void createLine() {
+ // when
+ registerLine(LINE_NUMBER_2);
+
+ // then
+ List<String> lineNames = findLines().jsonPath().getList("name", String.class);
+ assertThat(lineNames).contains(LINE_NUMBER_2);
+
+ }
+
+ /**
+ * Given 2๊ฐ์ ์งํ์ฒ ๋
ธ์ ์ ์์ฑํ๊ณ
+ * When ์งํ์ฒ ๋
ธ์ ๋ชฉ๋ก์ ์กฐํํ๋ฉด
+ * Then ์งํ์ฒ ๋
ธ์ ๋ชฉ๋ก ์กฐํ ์ 2๊ฐ์ ๋
ธ์ ์ ์กฐํํ ์ ์๋ค.
+ */
+ @DisplayName("์งํ์ฒ ๋
ธ์ ๋ชฉ๋ก ์กฐํ")
+ @Test
+ void getLines() {
+ // given
+ registerLine(LINE_NUMBER_1);
+ registerLine(LINE_NUMBER_2);
+
+ // when
+ List<String> lineNames = findLines().jsonPath().getList("name", String.class);
+
+ // then
+ assertThat(lineNames).contains(LINE_NUMBER_1, LINE_NUMBER_2);
+ }
+
+ /**
+ * Given ์งํ์ฒ ๋
ธ์ ์ ์์ฑํ๊ณ
+ * When ์์ฑํ ์งํ์ฒ ๋
ธ์ ์ ์กฐํํ๋ฉด
+ * Then ์์ฑํ ์งํ์ฒ ๋
ธ์ ์ ์ ๋ณด๋ฅผ ์๋ต๋ฐ์ ์ ์๋ค.
+ */
+ @DisplayName("์งํ์ฒ ๋
ธ์ ์กฐํ")
+ @Test
+ void getLine() {
+ // given
+ String lineId = registerLine(LINE_NUMBER_2).jsonPath().getString("id");
+
+ // when
+ ExtractableResponse<Response> response = findLine(lineId);
+
+ // then
+ assertThat(response.statusCode()).isEqualTo(HttpStatus.OK.value());
+ }
+
+ /**
+ * Given ์งํ์ฒ ๋
ธ์ ์ ์์ฑํ๊ณ
+ * When ์์ฑํ ์งํ์ฒ ๋
ธ์ ์ ์์ ํ๋ฉด
+ * Then ํด๋น ์งํ์ฒ ๋
ธ์ ์ ๋ณด๋ ์์ ๋๋ค
+ */
+
+ @DisplayName("์งํ์ฒ ๋
ธ์ ์์ ")
+ @Test
+ void updateLine() {
+ // given
+ String lineId = registerLine(LINE_NUMBER_2).jsonPath().getString("id");
+
+ // when
+ modifyLine(lineId, COLOR_RED);
+
+ // then
+ String actual = findLine(lineId).jsonPath().getString("color");
+ assertThat(actual).isEqualTo(COLOR_RED);
+ }
+
+ /**
+ * Given ์งํ์ฒ ๋
ธ์ ์ ์์ฑํ๊ณ
+ * When ์์ฑํ ์งํ์ฒ ๋
ธ์ ์ ์ญ์ ํ๋ฉด
+ * Then ํด๋น ์งํ์ฒ ๋
ธ์ ์ ๋ณด๋ ์ญ์ ๋๋ค
+ */
+ @DisplayName("์งํ์ฒ ๋
ธ์ ์ญ์ ")
+ @Test
+ void deleteLine() {
+ // given
+ String lineId = registerLine(LINE_NUMBER_2).jsonPath().getString("id");
+
+ // when
+ removeLine(lineId);
+ List<String> lineNames = findLines().jsonPath().getList("name", String.class);
+
+ // then
+ assertThat(lineNames.isEmpty() || !lineNames.contains(LINE_NUMBER_2)).isTrue();
+ }
+
+ private ExtractableResponse<Response> registerLine(String lineName) {
+ Map<String, Object> lineMap = new HashMap<>();
+ lineMap.put("name", lineName);
+ lineMap.put("color", "red");
+ lineMap.put("distance", 2);
+ return sendPost(lineMap, API_URL_LINES);
+ }
+
+ private ExtractableResponse<Response> findLines() {
+ return sendGet(API_URL_LINES);
+ }
+
+ private ExtractableResponse<Response> findLine(String lineId) {
+ return sendGet(API_URL_LINES + "/{id}", lineId);
+ }
+
+ private ExtractableResponse<Response> modifyLine(String lineId, String color) {
+ Map<String, Object> lineMap = new HashMap<>();
+ lineMap.put("name", "redred");
+ lineMap.put("color", color);
+ return sendPut(lineMap, API_URL_LINES + "/{id}", lineId);
+ }
+
+ private ExtractableResponse<Response> removeLine(String lineId) {
+ return sendDelete(API_URL_LINES + "/{id}", lineId);
+ }
+} | Java | ๋
ธ์ ์์ฑ ์ ์ํ์ข
์ ์ญ๊ณผ ํํ์ข
์ ์ญ์ ๋ฑ๋กํฉ๋๋ค.
ํด๋น ์๊ตฌ์ฌํญ์ด ๊ตฌํ๋์ง ์์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,86 @@
+package nextstep.subway.application;
+
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import nextstep.subway.domain.Line;
+import nextstep.subway.domain.LineRepository;
+import nextstep.subway.domain.Station;
+import nextstep.subway.domain.StationRepository;
+import nextstep.subway.dto.LineCreateRequest;
+import nextstep.subway.dto.LineResponse;
+import nextstep.subway.dto.LineUpdateRequest;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+@Transactional(readOnly = true)
+public class LineService {
+ private final LineRepository lineRepository;
+
+ private final StationRepository stationRepository;
+
+ public LineService(LineRepository lineRepository, StationRepository stationRepository) {
+ this.lineRepository = lineRepository;
+ this.stationRepository = stationRepository;
+ }
+
+ @Transactional
+ public LineResponse saveLine(LineCreateRequest lineCreateRequest) {
+ Line persistLine = lineRepository.save(lineCreateRequest.toLine());
+ addStations(persistLine, lineCreateRequest);
+ return LineResponse.of(persistLine);
+ }
+
+ public LineResponse findLine(Long id) {
+ Optional<Line> line = lineRepository.findById(id);
+ return LineResponse.of(line.get());
+ }
+
+ public List<LineResponse> findAllLines() {
+ return lineRepository.findAll().stream()
+ .map(LineResponse::of)
+ .collect(Collectors.toList());
+ }
+
+ @Transactional
+ public LineResponse updateLine(Long id, LineUpdateRequest lineUpdateRequest) {
+ Line line = lineRepository.findById(id).get();
+ line.updateLine(lineUpdateRequest);
+ return LineResponse.of(line);
+ }
+
+ @Transactional
+ public void deleteLineById(Long id) {
+ Optional<Line> line = lineRepository.findById(id);
+ if (line.isPresent()) {
+ line.get().clearRelatedLines();
+ lineRepository.delete(line.get());
+ }
+ }
+
+ private void addStations(Line persistLine, LineCreateRequest lineCreateRequest) {
+ addUpLine(persistLine, lineCreateRequest);
+ addDownLine(persistLine, lineCreateRequest);
+ }
+
+ private void addUpLine(Line line, LineCreateRequest lineCreateRequest) {
+ if (lineCreateRequest.hasUpStationsId()) {
+ Station station = getStation(lineCreateRequest.getUpStationId());
+ line.addStation(station);
+ }
+ }
+
+ private void addDownLine(Line line, LineCreateRequest lineCreateRequest) {
+ if (lineCreateRequest.hasDownStationsId()) {
+ Station station = getStation(lineCreateRequest.getDownStationId());
+ line.addStation(station);
+ }
+ }
+
+ private Station getStation(Long stationId) {
+ return stationRepository.findById(stationId)
+ .orElseThrow(() -> new NoSuchElementException("id(" + stationId + ")์ ํด๋นํ๋ ์ญ์ด ์์ต๋๋ค."));
+ }
+} | Java | id๋ก ๋ผ์ธ์ ์ฐพ์ ์ฐ๊ด๊ด๊ณ๋ฅผ ์ ๊ฑฐํ๋ ๋ก์ง์ ๋ฃ๊ณ ์ ํ๋๋ฐ์,
๋ผ์ธ์ด ์์ ๊ฒฝ์ฐ์๋ง ์ฒ๋ฆฌํ๋ ค๋ค ๋ณด๋ ๋ฐฉ์ด์ฝ๋ ์ฐจ์์ผ๋ก ๋ฃ์์ต๋๋ค.
์ด ๊ฒฝ์ฐ์๋ deleteById ๋ณด๋ค๋ delete ๋ฉ์๋๊ฐ ๋ ์ ํฉํด ๋ณด์ด๋ค์. ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,86 @@
+package nextstep.subway.application;
+
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import nextstep.subway.domain.Line;
+import nextstep.subway.domain.LineRepository;
+import nextstep.subway.domain.Station;
+import nextstep.subway.domain.StationRepository;
+import nextstep.subway.dto.LineCreateRequest;
+import nextstep.subway.dto.LineResponse;
+import nextstep.subway.dto.LineUpdateRequest;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+@Transactional(readOnly = true)
+public class LineService {
+ private final LineRepository lineRepository;
+
+ private final StationRepository stationRepository;
+
+ public LineService(LineRepository lineRepository, StationRepository stationRepository) {
+ this.lineRepository = lineRepository;
+ this.stationRepository = stationRepository;
+ }
+
+ @Transactional
+ public LineResponse saveLine(LineCreateRequest lineCreateRequest) {
+ Line persistLine = lineRepository.save(lineCreateRequest.toLine());
+ addStations(persistLine, lineCreateRequest);
+ return LineResponse.of(persistLine);
+ }
+
+ public LineResponse findLine(Long id) {
+ Optional<Line> line = lineRepository.findById(id);
+ return LineResponse.of(line.get());
+ }
+
+ public List<LineResponse> findAllLines() {
+ return lineRepository.findAll().stream()
+ .map(LineResponse::of)
+ .collect(Collectors.toList());
+ }
+
+ @Transactional
+ public LineResponse updateLine(Long id, LineUpdateRequest lineUpdateRequest) {
+ Line line = lineRepository.findById(id).get();
+ line.updateLine(lineUpdateRequest);
+ return LineResponse.of(line);
+ }
+
+ @Transactional
+ public void deleteLineById(Long id) {
+ Optional<Line> line = lineRepository.findById(id);
+ if (line.isPresent()) {
+ line.get().clearRelatedLines();
+ lineRepository.delete(line.get());
+ }
+ }
+
+ private void addStations(Line persistLine, LineCreateRequest lineCreateRequest) {
+ addUpLine(persistLine, lineCreateRequest);
+ addDownLine(persistLine, lineCreateRequest);
+ }
+
+ private void addUpLine(Line line, LineCreateRequest lineCreateRequest) {
+ if (lineCreateRequest.hasUpStationsId()) {
+ Station station = getStation(lineCreateRequest.getUpStationId());
+ line.addStation(station);
+ }
+ }
+
+ private void addDownLine(Line line, LineCreateRequest lineCreateRequest) {
+ if (lineCreateRequest.hasDownStationsId()) {
+ Station station = getStation(lineCreateRequest.getDownStationId());
+ line.addStation(station);
+ }
+ }
+
+ private Station getStation(Long stationId) {
+ return stationRepository.findById(stationId)
+ .orElseThrow(() -> new NoSuchElementException("id(" + stationId + ")์ ํด๋นํ๋ ์ญ์ด ์์ต๋๋ค."));
+ }
+} | Java | ๋ฆฌํฉํ ๋ง ๋จ๊ณ์์ ๋ฏธ์ฒ ์์ ํ์ง ๋ชปํ ๊ฒ ๊ฐ์ต๋๋ค... |
@@ -0,0 +1,63 @@
+package christmas.controller;
+
+import christmas.domain.PromotionService;
+import christmas.domain.order.Day;
+import christmas.domain.order.Order;
+import christmas.dto.response.DiscountPreviewResponse;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+
+import java.util.function.Supplier;
+
+public class PromotionController {
+
+ private PromotionController() {
+
+ }
+
+ public static PromotionController create() {
+ return new PromotionController();
+ }
+
+
+ public void run() {
+ printIntroductionMessage();
+
+ Day day = readWithExceptionHandling(PromotionController::readDay);
+ Order order = readWithExceptionHandling(PromotionController::readOrder);
+ PromotionService promotionService = PromotionService.create(order, day);
+ closeRead();
+
+ printDiscountPreviewMessage(promotionService);
+ }
+
+ private static void printIntroductionMessage() {
+ OutputView.printIntroductionMessage();
+ }
+
+ private static <T> T readWithExceptionHandling(Supplier<T> reader) {
+ while (true) {
+ try {
+ return reader.get();
+ } catch (IllegalArgumentException exception) {
+ System.out.println(exception.getMessage());
+ }
+ }
+ }
+
+ private static Day readDay() throws IllegalArgumentException {
+ return Day.create(InputView.readEstimatedVisitingDate());
+ }
+
+ private static Order readOrder() throws IllegalArgumentException {
+ return Order.create(InputView.readOrder());
+ }
+
+ private static void closeRead() {
+ InputView.closeRead();
+ }
+
+ private static void printDiscountPreviewMessage(PromotionService promotionService) {
+ OutputView.printDiscountPreviewMessage(DiscountPreviewResponse.from(promotionService));
+ }
+} | Java | static ๋ฉ์๋๊ฐ ์๋๊ฐ ๋นจ๋ผ์ง๋ค๋ ์ฅ์ ์ด ์์ง๋ง ๊ฐ์ฒด์งํฅ์์ ๋ฉ์ด์ง๊ธฐ ๋๋ฌธ์ ์ง์ํด์ผํ๋ค๊ณ ์๊ฐํฉ๋๋ค!
ํน์ Controller ๋ด ๋ฉ์๋๋ค์ ๋ชจ๋ static ๋ฉ์๋๋ก ์ ์ธํ์ ์ด์ ๊ฐ ์์ผ์ค๊น์?? |
@@ -0,0 +1,40 @@
+package christmas.domain.order;
+
+import christmas.validator.OrderValidator;
+
+import java.util.Objects;
+
+public class Day {
+
+ private final Integer day;
+
+ private Day(Integer day) {
+ validate(day);
+ this.day = day;
+ }
+
+ public static Day create(Integer day) {
+ return new Day(day);
+ }
+
+ private void validate(Integer day) {
+ OrderValidator.validateIsDateInRange(day);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Day day1 = (Day) o;
+ return Objects.equals(day, day1.day);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(day);
+ }
+
+ public Integer getPrimitiveDay() {
+ return day;
+ }
+} | Java | Day ๊ฐ์ฒด์ ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ OrderValidator์์ ์งํํ๊ฒ ๋๋ฉด ๋๋ฉ์ธ ๋ด๋ถ ์ํ ๋ฐ์ดํฐ์ ์บก์ํ๊ฐ ๊นจ์ง ๋ฟ๋๋ฌ ์ ํจ์ฑ ๊ฒ์ฌ์ ์์ด ๋ง์์ง๋ฉด OrderValidator ๊ฐ์ฒด๊ฐ ๋น๋ํด์ง๋ค๋ ๋จ์ ์ด ์๋ค๊ณ ์๊ฐํฉ๋๋ค.
Day ๊ฐ์ฒด ๋ด๋ถ์์ ์งํํ๋ ๊ฒ์ ์ด๋ค๊ฐ์?? |
@@ -0,0 +1,74 @@
+package christmas.domain.order;
+
+import christmas.domain.order.menu.Menu;
+import christmas.domain.order.menu.Quantity;
+import christmas.dto.request.OrderRequest;
+import christmas.dto.response.OrderResponse;
+import christmas.util.InputUtil;
+import christmas.validator.OrderValidator;
+
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+public class Order {
+
+ Map<Menu, Quantity> Order;
+
+ private Order(List<OrderRequest> orderRequests) {
+ Map<Menu, Quantity> order = InputUtil.parseOrderRequests(orderRequests);
+ validate(order);
+ this.Order = new EnumMap<>(order);
+ }
+
+ public static Order create(List<OrderRequest> orderRequests) {
+ return new Order(orderRequests);
+ }
+
+ private void validate(Map<Menu, Quantity> order) {
+ OrderValidator.validateHasOnlyDrink(order);
+ OrderValidator.validateIsTotalQuantityValid(order);
+ }
+
+ public List<OrderResponse> findOrderResponses() {
+ return Order
+ .entrySet()
+ .stream()
+ .map(entry -> OrderResponse.of(entry.getKey(), entry.getValue()))
+ .toList();
+ }
+
+ public int calculateInitialPrice() {
+ return Order
+ .entrySet()
+ .stream()
+ .mapToInt(entry -> getMenuPrice(entry) * getEachQuantity(entry))
+ .sum();
+ }
+
+ private int getMenuPrice(Map.Entry<Menu, Quantity> entry) {
+ return entry.getKey().getPrice();
+ }
+
+ private Integer getEachQuantity(Map.Entry<Menu, Quantity> entry) {
+ return entry.getValue().getPrimitiveQuantity();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Order order = (Order) o;
+ return Objects.equals(getOrder(), order.getOrder());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getOrder());
+ }
+
+ public Map<Menu, Quantity> getOrder() {
+ return new EnumMap<>(Order);
+ }
+} | Java | ์ ๊ทผ์ ์ด์๋ฅผ default๋ก ์ ์ธํ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,70 @@
+package christmas.domain.order.menu;
+
+import java.util.Arrays;
+import java.util.Map;
+
+public enum Menu {
+
+ // ๊ธฐํ
+ NONE("์์", 0, MenuType.NONE),
+
+ // ์ํผํ์ด์
+ MUSHROOM_SOUP("์์ก์ด ์คํ", 6_000, MenuType.APPETIZER),
+ TAPAS("ํํ์ค", 5_500, MenuType.APPETIZER),
+ CAESAR_SALAD("์์ ์๋ฌ๋", 8_000, MenuType.APPETIZER),
+
+ // ๋ฉ์ธ
+ T_BONE_STEAK("ํฐ๋ณธ์คํ
์ดํฌ", 55_000, MenuType.MAIN),
+ BBQ_RIBS("๋ฐ๋นํ๋ฆฝ", 54_000, MenuType.MAIN),
+ SEAFOOD_PASTA("ํด์ฐ๋ฌผํ์คํ", 35_000, MenuType.MAIN),
+ CHRISTMAS_PASTA("ํฌ๋ฆฌ์ค๋ง์คํ์คํ", 25_000, MenuType.MAIN),
+
+ // ๋์ ํธ
+ CHOCOLATE_CAKE("์ด์ฝ์ผ์ดํฌ", 15_000, MenuType.DESSERT),
+ ICE_CREAM("์์ด์คํฌ๋ฆผ", 5_000, MenuType.DESSERT),
+
+ // ์๋ฃ
+ ZERO_COKE("์ ๋ก์ฝ๋ผ", 3_000, MenuType.DRINK),
+ RED_WINE("๋ ๋์์ธ", 60_000, MenuType.DRINK),
+ CHAMPAGNE("์ดํ์ธ", 25_000, MenuType.DRINK);
+
+ private final String name;
+ private final int price;
+ private final MenuType type;
+
+ Menu(String name, int price, MenuType type) {
+ this.name = name;
+ this.price = price;
+ this.type = type;
+ }
+
+ public static Menu findByName(String name) {
+ return Arrays.stream(values())
+ .filter(menu -> menu.name.equals(name))
+ .findAny()
+ .orElse(Menu.NONE);
+ }
+
+ public static boolean isGiftMenu(Menu menu) {
+ return getGiftMenus()
+ .keySet()
+ .stream()
+ .anyMatch(giftMenu -> giftMenu.equals(menu));
+ }
+
+ public static Map<Menu, Quantity> getGiftMenus() {
+ return Map.of(Menu.CHAMPAGNE, Quantity.create(1));
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public MenuType getType() {
+ return type;
+ }
+} | Java | ์ ๊ฒฝ์ฐ 1์ ์ํด ์ด๋ฒคํธ์ ์ด๋ฒคํธ๊ฐ ๋ณ๊ฒฝ๋ ์ ์๋ค ๊ฐ์ ํด Menu ์ธํฐํ์ด์ค๋ฅผ ์ ์ธํ ๋ค ์ํผํ์ด์ , ๋ฉ์ธ, ๋์ ํธ, ์๋ฃ๋ณ๋ก ENUM ๊ฐ์ฒด๋ฅผ ๊ฐ๊ฐ ๋ฐ๋ก ์ ์ธํ์ต๋๋ค!
์ฐธ๊ณ ํ์๋ฉด ์ข์ ๊ฒ ๊ฐ์์!
``` java
public interface Menu {
int discount(int day);
String getName();
int getPrice();
}
```
``` java
public enum Appetizer implements Menu {
MUSHROOM_SOUP("์์ก์ด์ํ", 6000),
TAPAS("ํํ์ค", 5500),
CAESAR_SALAD("์์ ์๋ฌ๋", 8000);
private final String name;
private final int price;
Appetizer(String name, int price) {
this.name = name;
this.price = price;
}
@Override
public int discount(int day) {
return 0;
}
@Override
public String getName() {
return name;
}
@Override
public int getPrice() {
return price;
}
}
``` |
@@ -0,0 +1,40 @@
+package christmas.domain.order.menu;
+
+import christmas.validator.OrderValidator;
+
+import java.util.Objects;
+
+public class Quantity {
+
+ private final Integer quantity;
+
+ private Quantity(Integer quantity) {
+ validate(quantity);
+ this.quantity = quantity;
+ }
+
+ public static Quantity create(Integer quantity) {
+ return new Quantity(quantity);
+ }
+
+ private void validate(Integer quantity) {
+ OrderValidator.validateIsEachQuantityGreaterThanCondition(quantity);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Quantity quantity1 = (Quantity) o;
+ return Objects.equals(quantity, quantity1.quantity);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(quantity);
+ }
+
+ public Integer getPrimitiveQuantity() {
+ return quantity;
+ }
+} | Java | int๊ฐ ์๋ Integer๋ก ์ ์ธํด์ฃผ์๋ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค!๐ค |
@@ -0,0 +1,18 @@
+package christmas.domain.discount;
+
+import christmas.domain.order.Day;
+import christmas.domain.order.Order;
+
+public interface Discount {
+
+ public void calculateDiscountAmount(Order order, Day day);
+
+ public void checkIsAvailableDiscount(Order order, Day day);
+
+ public String getName();
+
+ public int getDiscountAmount();
+
+ public boolean getIsAvailable();
+
+} | Java | ๋คํ์ฑ์ ์ด์ฉํ๋ ์ ๋ง ์ข์ ๋ฐฉ๋ฒ์ด๋ค์ ๋ฐฐ์ฐ๊ณ ๊ฐ๋๋ค! |
@@ -0,0 +1,119 @@
+package christmas.validator;
+
+import christmas.domain.order.menu.Menu;
+import christmas.dto.request.OrderRequest;
+import christmas.util.InputUtil;
+import christmas.exception.ErrorMessage;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.regex.Pattern;
+
+public class InputValidator {
+
+ private InputValidator() {
+
+ }
+
+ /*
+ ์๋น ์์ ๋ฐฉ๋ฌธ ๋ ์ง ์
๋ ฅ๊ฐ ๊ฒ์ฆ
+ */
+ public static void validateEstimatedVisitingDateInput(String input) {
+ validateIsBlank(input);
+ validateIsDigit(input);
+ }
+
+ /*
+ ์ฃผ๋ฌธ ๋ฉ๋ด ๋ฐ ๊ฐ์ ์
๋ ฅ๊ฐ ์ ์ฒด ๊ฒ์ฆ
+ */
+ public static void validateOrder(String input) {
+ validateOrderInput(input);
+ validateOrderRequest(input);
+ }
+
+ /*
+ ์ฃผ๋ฌธ ๋ฉ๋ด ๋ฐ ๊ฐ์ ์
๋ ฅ๊ฐ ๋ถ๋ฆฌ ์ ๊ฒ์ฆ
+ */
+ private static void validateOrderInput(String input) {
+ validateIsBlank(input);
+ validateIsRightFormat(input);
+ }
+
+ private static void validateIsRightFormat(String input) {
+ if (!isRightFormat(input)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+ }
+
+ private static boolean isRightFormat(String input) {
+ String regex = ErrorMessage.ORDER_INPUT_REGEX.getMessage();
+ return Pattern.compile(regex)
+ .matcher(input)
+ .matches();
+ }
+
+ /*
+ ์ฃผ๋ฌธ ๋ฉ๋ด ๋ฐ ๊ฐ์ ์
๋ ฅ๊ฐ ๋ถ๋ฆฌ ํ ๊ฒ์ฆ
+ */
+ private static void validateOrderRequest(String input) {
+ List<OrderRequest> orderRequests = InputUtil.parseOrder(input);
+ validateIsExistingMenu(orderRequests);
+ validateHasDuplicatedMenu(orderRequests);
+ }
+
+ private static void validateIsExistingMenu(List<OrderRequest> orderRequests) {
+ if (!isExistingMenu(orderRequests)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+ }
+
+ private static boolean isExistingMenu(List<OrderRequest> orderRequests) {
+ List<String> menuNames = getMenuNames();
+ return orderRequests.stream()
+ .map(OrderRequest::getMenuName)
+ .allMatch(menuNames::contains);
+ }
+
+ private static List<String> getMenuNames() {
+ return Arrays.stream(Menu.values())
+ .map(Menu::getName)
+ .toList();
+ }
+
+ private static void validateHasDuplicatedMenu(List<OrderRequest> orderRequests) {
+ if (hasDuplicatedMenu(orderRequests)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+ }
+
+ private static boolean hasDuplicatedMenu(List<OrderRequest> orderRequests) {
+ return orderRequests.stream()
+ .map(OrderRequest::getMenuName)
+ .distinct()
+ .count() != orderRequests.size();
+ }
+
+ /*
+ ๊ณตํต ๊ฒ์ฆ
+ */
+ private static void validateIsBlank(String input) {
+ if (input.isBlank()) {
+ throw new IllegalArgumentException(ErrorMessage.INPUT_IS_BLANK.getMessage());
+ }
+ }
+
+ private static void validateIsDigit(String input) {
+ if (!isDigit(input)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_DATE.getMessage());
+ }
+ }
+
+ private static boolean isDigit(String input) {
+ try {
+ Integer.parseInt(input);
+ return true;
+ } catch (NumberFormatException e) {
+ return false;
+ }
+ }
+} | Java | ํ์ฌ InputValidator ๊ฐ์ฒด์์ ์ฌ์ฉ๋๋ ๋ฉ์๋๋ค์ ๋๋ถ๋ถ ํน์ ๋๋ฉ์ธ์ ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ์ํด ์ฌ์ฉ๋๊ณ ์๋๋ฐ ์ธ์คํด์ค ๋ฉ์๋๋ก ์ฌ์ฉํ๋๊ฑด ์ด๋ ์ ๊ฐ์?? |
@@ -0,0 +1,40 @@
+package christmas.domain.order.menu;
+
+import christmas.validator.OrderValidator;
+
+import java.util.Objects;
+
+public class Quantity {
+
+ private final Integer quantity;
+
+ private Quantity(Integer quantity) {
+ validate(quantity);
+ this.quantity = quantity;
+ }
+
+ public static Quantity create(Integer quantity) {
+ return new Quantity(quantity);
+ }
+
+ private void validate(Integer quantity) {
+ OrderValidator.validateIsEachQuantityGreaterThanCondition(quantity);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Quantity quantity1 = (Quantity) o;
+ return Objects.equals(quantity, quantity1.quantity);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(quantity);
+ }
+
+ public Integer getPrimitiveQuantity() {
+ return quantity;
+ }
+} | Java | ํฐ ์๋ฏธ๊ฐ ์๋ ๊ฒ์ ์๋๊ณ , null ์ฒ๋ฆฌ์ ๋๋นํ์ฌ Integer๋ฅผ ์ฌ์ฉํ๊ฒ ๋์์ต๋๋ค. ์ฌ์ค ์
๋ ฅ๊ฐ ๊ฒ์ฆ ๋ก์ง์ด ์ด๋ฏธ ์์ด์ null์ด ๋ค์ด๊ฐ ์ผ์ ์์ ๊ฒ ๊ฐ๊ธฐ๋ ํ๋ค์! |
@@ -0,0 +1,119 @@
+package christmas.validator;
+
+import christmas.domain.order.menu.Menu;
+import christmas.dto.request.OrderRequest;
+import christmas.util.InputUtil;
+import christmas.exception.ErrorMessage;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.regex.Pattern;
+
+public class InputValidator {
+
+ private InputValidator() {
+
+ }
+
+ /*
+ ์๋น ์์ ๋ฐฉ๋ฌธ ๋ ์ง ์
๋ ฅ๊ฐ ๊ฒ์ฆ
+ */
+ public static void validateEstimatedVisitingDateInput(String input) {
+ validateIsBlank(input);
+ validateIsDigit(input);
+ }
+
+ /*
+ ์ฃผ๋ฌธ ๋ฉ๋ด ๋ฐ ๊ฐ์ ์
๋ ฅ๊ฐ ์ ์ฒด ๊ฒ์ฆ
+ */
+ public static void validateOrder(String input) {
+ validateOrderInput(input);
+ validateOrderRequest(input);
+ }
+
+ /*
+ ์ฃผ๋ฌธ ๋ฉ๋ด ๋ฐ ๊ฐ์ ์
๋ ฅ๊ฐ ๋ถ๋ฆฌ ์ ๊ฒ์ฆ
+ */
+ private static void validateOrderInput(String input) {
+ validateIsBlank(input);
+ validateIsRightFormat(input);
+ }
+
+ private static void validateIsRightFormat(String input) {
+ if (!isRightFormat(input)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+ }
+
+ private static boolean isRightFormat(String input) {
+ String regex = ErrorMessage.ORDER_INPUT_REGEX.getMessage();
+ return Pattern.compile(regex)
+ .matcher(input)
+ .matches();
+ }
+
+ /*
+ ์ฃผ๋ฌธ ๋ฉ๋ด ๋ฐ ๊ฐ์ ์
๋ ฅ๊ฐ ๋ถ๋ฆฌ ํ ๊ฒ์ฆ
+ */
+ private static void validateOrderRequest(String input) {
+ List<OrderRequest> orderRequests = InputUtil.parseOrder(input);
+ validateIsExistingMenu(orderRequests);
+ validateHasDuplicatedMenu(orderRequests);
+ }
+
+ private static void validateIsExistingMenu(List<OrderRequest> orderRequests) {
+ if (!isExistingMenu(orderRequests)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+ }
+
+ private static boolean isExistingMenu(List<OrderRequest> orderRequests) {
+ List<String> menuNames = getMenuNames();
+ return orderRequests.stream()
+ .map(OrderRequest::getMenuName)
+ .allMatch(menuNames::contains);
+ }
+
+ private static List<String> getMenuNames() {
+ return Arrays.stream(Menu.values())
+ .map(Menu::getName)
+ .toList();
+ }
+
+ private static void validateHasDuplicatedMenu(List<OrderRequest> orderRequests) {
+ if (hasDuplicatedMenu(orderRequests)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_ORDER.getMessage());
+ }
+ }
+
+ private static boolean hasDuplicatedMenu(List<OrderRequest> orderRequests) {
+ return orderRequests.stream()
+ .map(OrderRequest::getMenuName)
+ .distinct()
+ .count() != orderRequests.size();
+ }
+
+ /*
+ ๊ณตํต ๊ฒ์ฆ
+ */
+ private static void validateIsBlank(String input) {
+ if (input.isBlank()) {
+ throw new IllegalArgumentException(ErrorMessage.INPUT_IS_BLANK.getMessage());
+ }
+ }
+
+ private static void validateIsDigit(String input) {
+ if (!isDigit(input)) {
+ throw new IllegalArgumentException(ErrorMessage.INVALID_DATE.getMessage());
+ }
+ }
+
+ private static boolean isDigit(String input) {
+ try {
+ Integer.parseInt(input);
+ return true;
+ } catch (NumberFormatException e) {
+ return false;
+ }
+ }
+} | Java | ์ฌํ ํฌ๊ฒ ์๊ฐ์ ์ ํ๋ ๋ถ๋ถ์ธ๋ฐ, ์๋ฌด๋๋ static์ ๋ถ์ฌ์ ์๋ฌด๋ฐ์๋ ์ธ ์ ์๊ฒ ํ๋ ๊ฒ๋ณด๋ค๋ ํ์ํ ๊ณณ์์๋ง ๋ถ๋ฌ์์ ์ฌ์ฉํ๋ ํธ์ด ์ฅ์ ์ด ์๊ฒ ๋ค์! ์ข์ ์๊ฒฌ ๊ฐ์ฌํฉ๋๋ค ๐ |
@@ -0,0 +1,63 @@
+package christmas.controller;
+
+import christmas.domain.PromotionService;
+import christmas.domain.order.Day;
+import christmas.domain.order.Order;
+import christmas.dto.response.DiscountPreviewResponse;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+
+import java.util.function.Supplier;
+
+public class PromotionController {
+
+ private PromotionController() {
+
+ }
+
+ public static PromotionController create() {
+ return new PromotionController();
+ }
+
+
+ public void run() {
+ printIntroductionMessage();
+
+ Day day = readWithExceptionHandling(PromotionController::readDay);
+ Order order = readWithExceptionHandling(PromotionController::readOrder);
+ PromotionService promotionService = PromotionService.create(order, day);
+ closeRead();
+
+ printDiscountPreviewMessage(promotionService);
+ }
+
+ private static void printIntroductionMessage() {
+ OutputView.printIntroductionMessage();
+ }
+
+ private static <T> T readWithExceptionHandling(Supplier<T> reader) {
+ while (true) {
+ try {
+ return reader.get();
+ } catch (IllegalArgumentException exception) {
+ System.out.println(exception.getMessage());
+ }
+ }
+ }
+
+ private static Day readDay() throws IllegalArgumentException {
+ return Day.create(InputView.readEstimatedVisitingDate());
+ }
+
+ private static Order readOrder() throws IllegalArgumentException {
+ return Order.create(InputView.readOrder());
+ }
+
+ private static void closeRead() {
+ InputView.closeRead();
+ }
+
+ private static void printDiscountPreviewMessage(PromotionService promotionService) {
+ OutputView.printDiscountPreviewMessage(DiscountPreviewResponse.from(promotionService));
+ }
+} | Java | ์...! ์ ๊ฐ ์ธํ
๋ฆฌ์ ์ด์ ๋ฉ์๋ ๋ถ๋ฆฌ ๋จ์ถํค์ธ option + command + v๋ฅผ ์์ฃผ ์ฌ์ฉํ๋๋ฐ, ๊ทธ ๊ณผ์ ์์ ์๋์ผ๋ก static ๋ฉ์๋๋ก ์ ์ธ๋ ๊ฒ ๊ฐ์ต๋๋ค. ์ ๋ถ ์ง์์ผ๊ฒ ๋ค์ ๐ |
@@ -0,0 +1,40 @@
+package christmas.domain.order;
+
+import christmas.validator.OrderValidator;
+
+import java.util.Objects;
+
+public class Day {
+
+ private final Integer day;
+
+ private Day(Integer day) {
+ validate(day);
+ this.day = day;
+ }
+
+ public static Day create(Integer day) {
+ return new Day(day);
+ }
+
+ private void validate(Integer day) {
+ OrderValidator.validateIsDateInRange(day);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Day day1 = (Day) o;
+ return Objects.equals(day, day1.day);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(day);
+ }
+
+ public Integer getPrimitiveDay() {
+ return day;
+ }
+} | Java | ๊ฐ VO์์ ์ด๋ฃจ์ด์ง๋ ๊ฒ์ฆ์ ํ ๊ตฐ๋ฐ์์ ๋ชจ์ ๊ด๋ฆฌํ๋ฉด ํธ๋ฆฌํ ๊ฒ์ด๋ผ ์๊ฐํ์๋๋ฐ, ๋ง์์ฃผ์ ๊ฒ์ฒ๋ผ ์บก์ํ๊ฐ ๊นจ์ง๋ ๋ฌธ์ ๋ ์์ ๋ฟ๋๋ฌ OrderValidator ๊ฐ์ฒด๊ฐ ๋น๋ํด์ง๋ค๋ฉด ๊ฒฐ๊ตญ์ ๋ก์ง์ ๋ถ๋ฆฌํด์ผํ ๊ฒ์ด๊ณ ์ด๋ฌ๋ฉด ํ ๊ณณ์์ ๊ด๋ฆฌํ ์ ์๋ค๋ ์ฅ์ ๋ํ ์ฌ๋ผ์ง ๊ฒ ๊ฐ์ต๋๋ค.
๊ฒฐ๊ตญ์๋ ์ ์ผ ๊ด๋ จ์ฑ์ด ๊น์ VO ๋ด๋ถ์์ ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ํ๋ ๊ฒ์ด ๋ง๊ฒ ๋ค์! ์ข์ ์กฐ์ธ ๊ฐ์ฌํฉ๋๋ค ๐ |
@@ -0,0 +1,74 @@
+package christmas.domain.order;
+
+import christmas.domain.order.menu.Menu;
+import christmas.domain.order.menu.Quantity;
+import christmas.dto.request.OrderRequest;
+import christmas.dto.response.OrderResponse;
+import christmas.util.InputUtil;
+import christmas.validator.OrderValidator;
+
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+public class Order {
+
+ Map<Menu, Quantity> Order;
+
+ private Order(List<OrderRequest> orderRequests) {
+ Map<Menu, Quantity> order = InputUtil.parseOrderRequests(orderRequests);
+ validate(order);
+ this.Order = new EnumMap<>(order);
+ }
+
+ public static Order create(List<OrderRequest> orderRequests) {
+ return new Order(orderRequests);
+ }
+
+ private void validate(Map<Menu, Quantity> order) {
+ OrderValidator.validateHasOnlyDrink(order);
+ OrderValidator.validateIsTotalQuantityValid(order);
+ }
+
+ public List<OrderResponse> findOrderResponses() {
+ return Order
+ .entrySet()
+ .stream()
+ .map(entry -> OrderResponse.of(entry.getKey(), entry.getValue()))
+ .toList();
+ }
+
+ public int calculateInitialPrice() {
+ return Order
+ .entrySet()
+ .stream()
+ .mapToInt(entry -> getMenuPrice(entry) * getEachQuantity(entry))
+ .sum();
+ }
+
+ private int getMenuPrice(Map.Entry<Menu, Quantity> entry) {
+ return entry.getKey().getPrice();
+ }
+
+ private Integer getEachQuantity(Map.Entry<Menu, Quantity> entry) {
+ return entry.getValue().getPrimitiveQuantity();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Order order = (Order) o;
+ return Objects.equals(getOrder(), order.getOrder());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getOrder());
+ }
+
+ public Map<Menu, Quantity> getOrder() {
+ return new EnumMap<>(Order);
+ }
+} | Java | ์ ๋ ์ง๊ธ ๋ดค๋ค์ใ
ใ
ใ
ใ
private ์ ์ธํด์ผ ๋๋๋ฐ ๊น๋จน์ ๊ฒ ๊ฐ์ต๋๋ค ๐คฃ |
@@ -0,0 +1,70 @@
+package christmas.domain.order.menu;
+
+import java.util.Arrays;
+import java.util.Map;
+
+public enum Menu {
+
+ // ๊ธฐํ
+ NONE("์์", 0, MenuType.NONE),
+
+ // ์ํผํ์ด์
+ MUSHROOM_SOUP("์์ก์ด ์คํ", 6_000, MenuType.APPETIZER),
+ TAPAS("ํํ์ค", 5_500, MenuType.APPETIZER),
+ CAESAR_SALAD("์์ ์๋ฌ๋", 8_000, MenuType.APPETIZER),
+
+ // ๋ฉ์ธ
+ T_BONE_STEAK("ํฐ๋ณธ์คํ
์ดํฌ", 55_000, MenuType.MAIN),
+ BBQ_RIBS("๋ฐ๋นํ๋ฆฝ", 54_000, MenuType.MAIN),
+ SEAFOOD_PASTA("ํด์ฐ๋ฌผํ์คํ", 35_000, MenuType.MAIN),
+ CHRISTMAS_PASTA("ํฌ๋ฆฌ์ค๋ง์คํ์คํ", 25_000, MenuType.MAIN),
+
+ // ๋์ ํธ
+ CHOCOLATE_CAKE("์ด์ฝ์ผ์ดํฌ", 15_000, MenuType.DESSERT),
+ ICE_CREAM("์์ด์คํฌ๋ฆผ", 5_000, MenuType.DESSERT),
+
+ // ์๋ฃ
+ ZERO_COKE("์ ๋ก์ฝ๋ผ", 3_000, MenuType.DRINK),
+ RED_WINE("๋ ๋์์ธ", 60_000, MenuType.DRINK),
+ CHAMPAGNE("์ดํ์ธ", 25_000, MenuType.DRINK);
+
+ private final String name;
+ private final int price;
+ private final MenuType type;
+
+ Menu(String name, int price, MenuType type) {
+ this.name = name;
+ this.price = price;
+ this.type = type;
+ }
+
+ public static Menu findByName(String name) {
+ return Arrays.stream(values())
+ .filter(menu -> menu.name.equals(name))
+ .findAny()
+ .orElse(Menu.NONE);
+ }
+
+ public static boolean isGiftMenu(Menu menu) {
+ return getGiftMenus()
+ .keySet()
+ .stream()
+ .anyMatch(giftMenu -> giftMenu.equals(menu));
+ }
+
+ public static Map<Menu, Quantity> getGiftMenus() {
+ return Map.of(Menu.CHAMPAGNE, Quantity.create(1));
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public MenuType getType() {
+ return type;
+ }
+} | Java | ๋ฉ๋ด Enum์๋ ์ด๋ฐ ์์ผ๋ก ์ธํฐํ์ด์ค๋ฅผ ์ ์ฉํ ์ ์๋๋ฐ ์๊ฐํ์ง ๋ชปํ๋ค์! ์ฐธ๊ณ ํ๊ฒ ์ต๋๋ค...! |
@@ -0,0 +1,31 @@
+package christmas.model.badge.enums;
+
+import java.util.Arrays;
+
+public enum BadgeInfo {
+
+ SANTA_BADGE("์ฐํ", 20_000),
+ TREE_BADGE("ํธ๋ฆฌ", 10_000),
+ START_BADGE("๋ณ", 5_000),
+ NON_BADGE("์์", 0);
+
+ private final String name;
+
+ private final int price;
+
+ BadgeInfo(String name, int price) {
+ this.name = name;
+ this.price = price;
+ }
+
+ public static BadgeInfo findBadgeByPrice(int totalPrice) {
+ return Arrays.stream(values())
+ .filter(badge -> totalPrice >= badge.price)
+ .findFirst()
+ .orElse(NON_BADGE);
+ }
+
+ public String getName() {
+ return name;
+ }
+} | Java | ์ค์๋ฅผ ๋ฏธ์
์ด ๋๋๊ณ ๋ฐ๊ฒฌํ์ต๋๋ค ^^..
START -> STAR |
@@ -0,0 +1,32 @@
+package christmas.model.discount;
+
+
+import static christmas.exception.ErrorType.INVALID_ORDER_AMOUNT;
+import static christmas.model.discount.enums.DiscountAmount.CAN_GIVEAWAY_DISCOUNT;
+import static christmas.model.discount.enums.DiscountAmount.NON_DISCOUNT;
+
+import christmas.model.order.enums.MenuInfo;
+
+public class GiveawayDiscount implements Discount {
+
+ private final int totalOrderAmount;
+
+ public GiveawayDiscount(int totalOrderAmount) {
+ validateOrderAmount(totalOrderAmount);
+ this.totalOrderAmount = totalOrderAmount;
+ }
+
+ private void validateOrderAmount(int totalOrderAmount) {
+ if (totalOrderAmount < NON_DISCOUNT.getDiscount()) {
+ throw new IllegalArgumentException(INVALID_ORDER_AMOUNT.getMessage());
+ }
+ }
+
+ @Override
+ public int calculateDiscount() {
+ if (totalOrderAmount >= CAN_GIVEAWAY_DISCOUNT.getDiscount()) {
+ return MenuInfo.CHRISTMAS_PASTA.getPrice();
+ }
+ return NON_DISCOUNT.getDiscount();
+ }
+} | Java | ์ค์๋ฅผ ๋ฏธ์
์ด ๋๋๊ณ ๋ฐ๊ฒฌํ์ต๋๋ค ^^..
ํ์คํ -> ์ดํ์ธ (๊ฐ๊ฒฉ์ด ๋๊ฐ์์ ๋์น์ฑ์ง ๋ชปํ๋ค์ (__)) |
@@ -0,0 +1,61 @@
+package christmas.model.order.enums;
+
+import static christmas.exception.ErrorType.INVALID_MENU_NOT_EXIST;
+
+import java.util.Arrays;
+
+public enum MenuInfo {
+
+ MUSHROOM_SOUP("์์ก์ด์ํ", 6_000, Category.APPETIZER),
+ TAPAS("ํํ์ค", 5_500, Category.APPETIZER),
+ CAESAR_SALAD("์์ ์๋ฌ๋", 8_000, Category.APPETIZER),
+
+ T_BONE_STEAK("ํฐ๋ณธ์คํ
์ดํฌ", 55_000, Category.MAIN_COURSE),
+ BARBECUE_RIBS("๋ฐ๋นํ๋ฆฝ", 54_000, Category.MAIN_COURSE),
+ SEAFOOD_PASTA("ํด์ฐ๋ฌผํ์คํ", 35_000, Category.MAIN_COURSE),
+ CHRISTMAS_PASTA("ํฌ๋ฆฌ์ค๋ง์คํ์คํ", 25_000, Category.MAIN_COURSE),
+
+ CHOCOLATE_CAKE("์ด์ฝ์ผ์ดํฌ", 15_000, Category.DESSERT),
+ ICE_CREAM("์์ด์คํฌ๋ฆผ", 5_000, Category.DESSERT),
+
+ ZERO_COLA("์ ๋ก์ฝ๋ผ", 3_000, Category.BEVERAGE),
+ RED_WINE("๋ ๋์์ธ", 60_000, Category.BEVERAGE),
+ CHAMPAGNE("์ดํ์ธ", 25_000, Category.BEVERAGE);
+
+ private final String name;
+
+ private final int price;
+
+ private final Category category;
+
+ MenuInfo(String name, int price, Category category) {
+ this.name = name;
+ this.price = price;
+ this.category = category;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public Category getCategory() {
+ return category;
+ }
+
+ public static boolean isExistMenu(String name) {
+ return Arrays.stream(MenuInfo.values())
+ .map(MenuInfo::getName)
+ .anyMatch(existMenu -> existMenu.equals(name));
+ }
+
+ public static MenuInfo findByMenuName(String name) {
+ return Arrays.stream(MenuInfo.values())
+ .filter(menuInfo -> menuInfo.getName().equals(name))
+ .findFirst()
+ .orElseThrow(() -> new IllegalArgumentException(INVALID_MENU_NOT_EXIST.getMessage()));
+ }
+} | Java | ๋ฉ๋ด ์ข
๋ฅ๋ณ ์ฃผ๋ฌธ ์๋์ ์ ์ฅํ๋ Map์ ๋ง๋๋ ๋ฉ์๋๊ฐ ์์ด๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,54 @@
+package christmas.model.calendar;
+
+import static christmas.model.calendar.enums.CalendarDate.CHRISTMAS;
+import static christmas.model.calendar.enums.CalendarDate.EVENT_MONTH;
+import static christmas.model.calendar.enums.CalendarDate.EVENT_YEAR;
+import static christmas.model.calendar.enums.CalendarDate.FRIDAY;
+import static christmas.model.calendar.enums.CalendarDate.SATURDAY;
+import static christmas.model.calendar.enums.CalendarDate.SUNDAY;
+
+import java.time.LocalDate;
+
+public abstract class EventCalendar implements Calendar {
+
+ protected final LocalDate eventDate;
+
+ public EventCalendar(int visitDay) {
+ validate(visitDay);
+ this.eventDate = LocalDate.of(EVENT_YEAR.getNumber(), EVENT_MONTH.getNumber(), visitDay);
+ }
+
+ protected abstract void validateDayRange(int visitDay);
+
+ @Override
+ public boolean isWeekend() {
+ int visitDay = getDayOfWeek();
+ return visitDay == FRIDAY.getNumber() || visitDay == SATURDAY.getNumber();
+ }
+
+ @Override
+ public boolean isSpecialDay() {
+ return isChristmas() || isSunday();
+ }
+
+ @Override
+ public int getDayOfMonth() {
+ return eventDate.getDayOfMonth();
+ }
+
+ private void validate(int visitDay) {
+ validateDayRange(visitDay);
+ }
+
+ private boolean isChristmas() {
+ return getDayOfMonth() == CHRISTMAS.getNumber();
+ }
+
+ private boolean isSunday() {
+ return getDayOfWeek() == SUNDAY.getNumber();
+ }
+
+ private int getDayOfWeek() {
+ return eventDate.getDayOfWeek().getValue();
+ }
+} | Java | `DayOfWeek`๋ `enum` ํ์
์ด๊ธฐ์ ๋ค์๊ณผ ๊ฐ์ด ์ง์ ์ ์ธ ๋๋ฑ์ฑ ๋น๊ต๋ ๊ฐ๋ฅํ๋ฉฐ, ์ด ๊ฒฝ์ฐ๊ฐ ๊ฐ๋
์ฑ๋ ๋ ์ข์์ง ๊ฒ ๊ฐ์ต๋๋ค!
```suggestion
DayOfWeek week = eventDate.getDayOfWeek();
return week == DayOfWeek.FRIDAY || week == DayOfWeek.SATURDAY;
``` |
@@ -0,0 +1,14 @@
+package christmas.model.calendar;
+
+import static christmas.model.calendar.enums.CalendarDate.CHRISTMAS;
+
+public class CalendarFactory {
+
+ public static Calendar createCalendar(int day) {
+ if (day <= CHRISTMAS.getNumber()) {
+ return new ChristmasEventCalendar(day);
+ }
+
+ return new GeneralEventCalendar(day);
+ }
+} | Java | ์ํ, ์
๋ ฅ ๋ ์ง๊ฐ ํฌ๋ฆฌ์ค๋ง์ค ์ดํ์ธ์ง์ ์ฌ๋ถ์ ๋ฐ๋ผ ๊ฐ๊ฐ ๋ค๋ฅธ `Calendar` ํด๋์ค๋ฅผ ์ฌ์ฉํ๋๋ก ํ์
จ๋ค์.
์ด๋ ๊ฒ๋ ๊ตฌํ์ ํ ์ ์์๊ตฐ์! |
@@ -0,0 +1,31 @@
+package christmas.model.badge.enums;
+
+import java.util.Arrays;
+
+public enum BadgeInfo {
+
+ SANTA_BADGE("์ฐํ", 20_000),
+ TREE_BADGE("ํธ๋ฆฌ", 10_000),
+ START_BADGE("๋ณ", 5_000),
+ NON_BADGE("์์", 0);
+
+ private final String name;
+
+ private final int price;
+
+ BadgeInfo(String name, int price) {
+ this.name = name;
+ this.price = price;
+ }
+
+ public static BadgeInfo findBadgeByPrice(int totalPrice) {
+ return Arrays.stream(values())
+ .filter(badge -> totalPrice >= badge.price)
+ .findFirst()
+ .orElse(NON_BADGE);
+ }
+
+ public String getName() {
+ return name;
+ }
+} | Java | ๋ฑ์ง๋ฅผ ์ป์ ์ ์๋ ํํ๊ฐ ๊ธ์ก๋ง ์ค์ ํด ๋๊ณ , `enum`์ ์์๋ฅผ ํ์ฉํ์
จ๋ค์!
`enum`์ ์์์ ์ํฅ์ ๋ฐ๋ ๋ก์ง์ ์์ฑํ๋ ๊ฒ์ด ์ณ์๊ฐ ์ ๋ํ ํ์ ์ด ์์ด ์ด๋ ๊ฒ ๊ตฌํํ์ง ๋ชปํ๋๋ฐ, ์ด๋ ๊ฒ ๊ตฌํํ๋ ๊ฒ์ด ํจ์ฌ ๊ฐ๊ฒฐํ๊ณ ์ข์์ ๊ฒ๋ ๊ฐ๊ตฐ์! |
@@ -0,0 +1,20 @@
+package christmas.model.badge;
+
+import christmas.model.badge.enums.BadgeInfo;
+
+public class Badge {
+
+ private final BadgeInfo badgeInfo;
+
+ public Badge(int totalDiscountAmount) {
+ this.badgeInfo = selectBadge(totalDiscountAmount);
+ }
+
+ public String getBadgeName() {
+ return badgeInfo.getName();
+ }
+
+ private BadgeInfo selectBadge(int totalDiscountAmount) {
+ return BadgeInfo.findBadgeByPrice(totalDiscountAmount);
+ }
+} | Java | ํด๋น ํด๋์ค๋ ์ด๋ป๊ฒ ๋ณด๋ฉด `BadgeInfo`๋ฅผ ๋ํํ๊ณ ์๋ ๋ํ ํด๋์ค์ฒ๋ผ ๋ณด์ด๋๋ฐ์.
์ด ํด๋์ค๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์๋ ์ด๋ค ์ด์ ์ด ์์ ์ ์์๊น์? |
@@ -0,0 +1,15 @@
+package christmas.model.order.enums;
+
+public enum Category {
+
+ APPETIZER("์ํผํ์ด์ "),
+ MAIN_COURSE("๋ฉ์ธ"),
+ DESSERT("๋์ ํธ"),
+ BEVERAGE("์๋ฃ");
+
+ private final String category;
+
+ Category(String category) {
+ this.category = category;
+ }
+} | Java | ํด๋น ํ๋๋ ํ์ฅ์ฑ์ ์ํ ํ๋์ธ๊ฐ์? |
@@ -0,0 +1,51 @@
+package christmas.model.order;
+
+import static christmas.exception.ErrorType.INVALID_MENU_NAME;
+
+import christmas.model.order.enums.Category;
+import christmas.model.order.enums.MenuInfo;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+public class OrderMenu {
+
+ private final Map<MenuName, MenuQuantity> orderMenu;
+
+ public OrderMenu() {
+ this.orderMenu = new HashMap<>();
+ }
+
+ public Map<MenuName, MenuQuantity> getOrderMenu() {
+ return Collections.unmodifiableMap(orderMenu);
+ }
+
+ public int getMenuQuantity(MenuName menuName) {
+ return orderMenu.get(menuName).getQuantity();
+ }
+
+ public boolean containMainMenu(MenuName menuName) {
+ String menu = menuName.getName();
+ return MenuInfo.findByMenuName(menu).getCategory() == Category.MAIN_COURSE;
+ }
+
+ public boolean containDesertMenu(MenuName menuName) {
+ String menu = menuName.getName();
+ return MenuInfo.findByMenuName(menu).getCategory() == Category.DESSERT;
+ }
+
+ public void addMenu(MenuName menuName, MenuQuantity menuQuantity) {
+ validate(menuName);
+ orderMenu.put(menuName, menuQuantity);
+ }
+
+ private void validate(MenuName menuName) {
+ validateDuplicateMenuName(menuName);
+ }
+
+ private void validateDuplicateMenuName(MenuName menuName) {
+ if (orderMenu.containsKey(menuName)) {
+ throw new IllegalArgumentException(INVALID_MENU_NAME.getMessage());
+ }
+ }
+} | Java | ์ด๋ฆ์ `MainMenu`๋ฅผ ํฌํจํ๋์ง๋ฅผ ํ๋จํ๋ ๋ฉ์๋์ฒ๋ผ ๋๊ปด์ง๋๋ฐ, ์๋์ ๋ก์ง์ ์
๋ ฅ๋ฐ์ ๋ฉ๋ด๊ฐ ๋ฉ์ธ๋ฉ๋ด์ธ์ง๋ฅผ ํ๋จํ๋ค์.
`contain~`๋ณด๋ค `is~`์ ๋ค์ด๋ฐ์ด ์กฐ๊ธ ๋ ์ ์ ํ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,64 @@
+package christmas.model.result;
+
+import static christmas.model.discount.enums.DiscountAmount.NON_DISCOUNT;
+
+public class DiscountResult {
+
+ private int christmasDiscount;
+
+ private int weeksDaysDiscount;
+
+ private int weekendDiscount;
+
+ private int specialDiscount;
+
+ private int giveawayDiscount;
+
+ public DiscountResult() {
+ this.christmasDiscount = NON_DISCOUNT.getDiscount();
+ this.weeksDaysDiscount = NON_DISCOUNT.getDiscount();
+ this.weekendDiscount = NON_DISCOUNT.getDiscount();
+ this.specialDiscount = NON_DISCOUNT.getDiscount();
+ this.giveawayDiscount = NON_DISCOUNT.getDiscount();
+ }
+
+ public void updateChristmasDiscount(int christmasDiscount) {
+ this.christmasDiscount = christmasDiscount;
+ }
+
+ public void updateWeeksDaysDiscount(int weeksDaysDiscount) {
+ this.weeksDaysDiscount = weeksDaysDiscount;
+ }
+
+ public void updateWeekendDiscount(int weekendDiscount) {
+ this.weekendDiscount = weekendDiscount;
+ }
+
+ public void updateSpecialDiscount(int specialDiscount) {
+ this.specialDiscount = specialDiscount;
+ }
+
+ public void updateGiveawayDiscount(int giveawayDiscount) {
+ this.giveawayDiscount = giveawayDiscount;
+ }
+
+ public int getChristmasDiscount() {
+ return christmasDiscount;
+ }
+
+ public int getWeeksDaysDiscount() {
+ return weeksDaysDiscount;
+ }
+
+ public int getWeekendDiscount() {
+ return weekendDiscount;
+ }
+
+ public int getSpecialDiscount() {
+ return specialDiscount;
+ }
+
+ public int getGiveawayDiscount() {
+ return giveawayDiscount;
+ }
+} | Java | ์ํ, ์ฒ์์ ๋ชจ๋ ํ ์ธ ์ ์ฉ์ 0์ผ๋ก ๋๊ณ ํ ์ธ์ ์ ์ฉํ ์ ์์ ๋ ๋ด๋ถ์ ๊ฐ๋ค์ ์๋ก ์
๋ฐ์ดํธ ํด์ฃผ๋๊ตฐ์!
์ ์๋ ๋ค๋ฅธ ์ ๊ทผ์ด๋ผ์ ์ ๋ง ์ฌ๋ฏธ์๊ฒ ์ฝ์์ต๋๋ค! |
@@ -0,0 +1,81 @@
+package christmas.model.order;
+
+import static christmas.exception.ErrorType.INVALID_MAX_MENU_QUANTITY;
+import static christmas.exception.ErrorType.INVALID_MENU_ONLY_DRINK;
+import static christmas.utils.Constants.MAX_ORDER_QUANTITY;
+import static christmas.utils.Constants.MIN_ORDER_MENU;
+
+import christmas.model.order.enums.Category;
+import christmas.model.order.enums.MenuInfo;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class OrderDetail {
+
+ private final OrderMenu orderMenu;
+
+ public OrderDetail(OrderMenu orderMenu) {
+ validate(orderMenu);
+ this.orderMenu = orderMenu;
+ }
+
+ public Map<String, Integer> getOrderMenuName() {
+ Map<String, Integer> details = new HashMap<>();
+ for (Map.Entry<MenuName, MenuQuantity> entry : orderMenu.getOrderMenu().entrySet()) {
+ String menuName = entry.getKey().getName();
+ int quantity = entry.getValue().getQuantity();
+ details.put(menuName, quantity);
+ }
+
+ return Collections.unmodifiableMap(details);
+ }
+
+ public int getQuantityByMenu(MenuName menuName) {
+ return orderMenu.getMenuQuantity(menuName);
+ }
+
+ public List<MenuName> getMainMenu() {
+ return orderMenu.getOrderMenu().keySet().stream()
+ .filter(orderMenu::containMainMenu)
+ .toList();
+ }
+
+ public List<MenuName> getDesertMenu() {
+ return orderMenu.getOrderMenu().keySet().stream()
+ .filter(orderMenu::containDesertMenu)
+ .toList();
+ }
+
+ private void validate(OrderMenu orderMenu) {
+ if (orderMenu.getOrderMenu().size() == MIN_ORDER_MENU) {
+ validateOnlyBeverage(orderMenu);
+ }
+
+ validateMaxQuantity(calculateTotalQuantity(orderMenu));
+ }
+
+ private void validateOnlyBeverage(OrderMenu orderMenu) {
+ MenuName menuName = orderMenu.getOrderMenu().keySet().stream()
+ .findFirst()
+ .orElseThrow();
+
+ String name = menuName.getName();
+ if (MenuInfo.findByMenuName(name).getCategory() == Category.BEVERAGE) {
+ throw new IllegalArgumentException(INVALID_MENU_ONLY_DRINK.getMessage());
+ }
+ }
+
+ private void validateMaxQuantity(int totalQuantity) {
+ if (totalQuantity > MAX_ORDER_QUANTITY) {
+ throw new IllegalArgumentException(INVALID_MAX_MENU_QUANTITY.getMessage());
+ }
+ }
+
+ private int calculateTotalQuantity(OrderMenu orderMenu) {
+ return orderMenu.getOrderMenu().values().stream()
+ .mapToInt(MenuQuantity::getQuantity)
+ .sum();
+ }
+} | Java | ์ด ์ฝ๋์ ํ๋ฆ์ ์ดํดํด ๋ณด๊ณ ์ ์ ๋ง ์ด์ฌํ ๋
ธ๋ ฅํ๋๋ฐ ์คํจํ์ต๋๋ค...ใ
ใ
์ฃผ๋ฌธ ๋ชฉ๋ก์ ์ฒซ ๋ฒ์งธ ๋ฉ๋ด๋ง ์นดํ
๊ณ ๋ฆฌ๋ฅผ ํ์ธํ๋ ๊ฒ์ผ๋ก ํด์์ ํ๋๋ฐ ์ด๊ฒ ์ด๋ป๊ฒ ์๋ฃ๋ง ์ฃผ๋ฌธํ ๊ฒฝ์ฐ๋ฅผ ํ๋ณํ ์ ์๋ ์ง ๋ชจ๋ฅด๊ฒ ์ด์...
๊ด์ฐฎ์ผ์๋ค๋ฉด ํธํ์ค ๋ ์ค๋ช
ํ๋ฒ๋ง ๋ถํ๋๋ฆฝ๋๋ค..! |
@@ -0,0 +1,30 @@
+package christmas.model.calendar;
+
+import static christmas.exception.ErrorType.INVALID_DAY_OUT_OF_RANGE;
+import static christmas.model.calendar.enums.CalendarDate.CHRISTMAS;
+import static christmas.model.calendar.enums.CalendarDate.EVENT_MONTH;
+import static christmas.model.calendar.enums.CalendarDate.EVENT_YEAR;
+import static christmas.model.calendar.enums.CalendarDate.FRIDAY;
+import static christmas.model.calendar.enums.CalendarDate.SATURDAY;
+import static christmas.model.calendar.enums.CalendarDate.START_DAY;
+import static christmas.model.calendar.enums.CalendarDate.SUNDAY;
+
+import java.time.LocalDate;
+
+public class ChristmasEventCalendar extends EventCalendar {
+
+ public ChristmasEventCalendar(int visitDay) {
+ super(visitDay);
+ }
+
+ protected void validateDayRange(int visitDay) {
+ if (visitDay < START_DAY.getNumber() || visitDay > CHRISTMAS.getNumber()) {
+ throw new IllegalArgumentException(INVALID_DAY_OUT_OF_RANGE.getMessage());
+ }
+ }
+
+ public int calculateVisitDayFromStart() {
+ int visitDay = getDayOfMonth();
+ return visitDay - START_DAY.getNumber();
+ }
+} | Java | ์กฐ๊ฑด๋ฌธ์ด ๊ธธ์ด์ง๋ค๋ฉด ๋ฉ์๋๋ก ๋ฐ๋ก ๋นผ๋๋ ๊ฒ๋ ์ข์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,20 @@
+package christmas.model.badge;
+
+import christmas.model.badge.enums.BadgeInfo;
+
+public class Badge {
+
+ private final BadgeInfo badgeInfo;
+
+ public Badge(int totalDiscountAmount) {
+ this.badgeInfo = selectBadge(totalDiscountAmount);
+ }
+
+ public String getBadgeName() {
+ return badgeInfo.getName();
+ }
+
+ private BadgeInfo selectBadge(int totalDiscountAmount) {
+ return BadgeInfo.findBadgeByPrice(totalDiscountAmount);
+ }
+} | Java | ์ ๋ ๊ฐ์ ์๊ฒฌ์
๋๋ค !
`Badge` ํด๋์ค์์ ์ด๋ค์ง๋ ๋ชจ๋ ๋ก์ง์ `BadgeInfo`์์๋ ๋์ผํ๊ธฐ ์ํํ ์ ์๊ณ
๊ทธ๋ ๊ฒ ํ๋ค๋ฉด ํด๋์ค ๋ช
์ Info ๋ฅผ ์ถ๊ฐํ์ง ์์๋ ๋ผ์ ๋์ฑ ๊น๋ํ ์ฝ๋๊ฐ ๋ ๊ฒ ๊ฐ์์ ! |
@@ -0,0 +1,54 @@
+package christmas.model.calendar;
+
+import static christmas.model.calendar.enums.CalendarDate.CHRISTMAS;
+import static christmas.model.calendar.enums.CalendarDate.EVENT_MONTH;
+import static christmas.model.calendar.enums.CalendarDate.EVENT_YEAR;
+import static christmas.model.calendar.enums.CalendarDate.FRIDAY;
+import static christmas.model.calendar.enums.CalendarDate.SATURDAY;
+import static christmas.model.calendar.enums.CalendarDate.SUNDAY;
+
+import java.time.LocalDate;
+
+public abstract class EventCalendar implements Calendar {
+
+ protected final LocalDate eventDate;
+
+ public EventCalendar(int visitDay) {
+ validate(visitDay);
+ this.eventDate = LocalDate.of(EVENT_YEAR.getNumber(), EVENT_MONTH.getNumber(), visitDay);
+ }
+
+ protected abstract void validateDayRange(int visitDay);
+
+ @Override
+ public boolean isWeekend() {
+ int visitDay = getDayOfWeek();
+ return visitDay == FRIDAY.getNumber() || visitDay == SATURDAY.getNumber();
+ }
+
+ @Override
+ public boolean isSpecialDay() {
+ return isChristmas() || isSunday();
+ }
+
+ @Override
+ public int getDayOfMonth() {
+ return eventDate.getDayOfMonth();
+ }
+
+ private void validate(int visitDay) {
+ validateDayRange(visitDay);
+ }
+
+ private boolean isChristmas() {
+ return getDayOfMonth() == CHRISTMAS.getNumber();
+ }
+
+ private boolean isSunday() {
+ return getDayOfWeek() == SUNDAY.getNumber();
+ }
+
+ private int getDayOfWeek() {
+ return eventDate.getDayOfWeek().getValue();
+ }
+} | Java | LocalDate๋ฅผ ํ์ฉํ๋ ๋ฐฉ๋ฒ๋ ์์๊ตฐ์ ..!
๋ ๋ค์ํญ ํ์ฉ์ ํ ์ ์์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,45 @@
+package christmas.model.discount;
+
+import static christmas.model.discount.enums.DiscountAmount.DESERT_DISCOUNT;
+import static christmas.model.discount.enums.DiscountAmount.NON_DISCOUNT;
+import static christmas.utils.Constants.MIN_ORDER_MENU;
+
+import christmas.model.calendar.Calendar;
+import christmas.model.order.MenuName;
+import christmas.model.order.OrderDetail;
+import java.util.List;
+
+public class WeekdaysDiscount implements Discount {
+
+ private final Calendar calendar;
+
+ private final OrderDetail orderDetail;
+
+ public WeekdaysDiscount(Calendar calendar, OrderDetail orderDetail) {
+ this.calendar = calendar;
+ this.orderDetail = orderDetail;
+ }
+
+ @Override
+ public int calculateDiscount() {
+ if (!calendar.isWeekend()) {
+ return desertDiscountPrice();
+ }
+ return NON_DISCOUNT.getDiscount();
+ }
+
+ private int desertDiscountPrice() {
+ List<MenuName> desertMenu = orderDetail.getDesertMenu();
+ int totalPrice = NON_DISCOUNT.getDiscount();
+ if (desertMenu.size() < MIN_ORDER_MENU) {
+ return totalPrice;
+ }
+
+ for (MenuName menuName : desertMenu) {
+ int quantityByMenu = orderDetail.getQuantityByMenu(menuName);
+ totalPrice += (quantityByMenu * DESERT_DISCOUNT.getDiscount());
+ }
+
+ return totalPrice;
+ }
+} | Java | `orderDetail.getDesertMenu()` ์์ ๋์ ํธ ๋ฉ๋ด๊ฐ ์๋ค๋ฉด ๋น ์ปฌ๋ ์
์ด ๋ฐํ๋๊ธฐ ๋๋ฌธ์
์ด ๊ฒ์ฆ ๋ก์ง์ด ์์ด๋ ๊ด์ฐฎ์ง ์์๊น? ๋ผ๋ ์๊ฐ์ด ๋ค์ด์! |
@@ -0,0 +1,45 @@
+package christmas.model.discount;
+
+import static christmas.model.discount.enums.DiscountAmount.MAIN_COURSE_DISCOUNT;
+import static christmas.model.discount.enums.DiscountAmount.NON_DISCOUNT;
+import static christmas.utils.Constants.MIN_ORDER_MENU;
+
+import christmas.model.calendar.Calendar;
+import christmas.model.order.MenuName;
+import christmas.model.order.OrderDetail;
+import java.util.List;
+
+public class WeekendDiscount implements Discount {
+
+ private final Calendar calendar;
+
+ private final OrderDetail orderDetail;
+
+ public WeekendDiscount(Calendar calendar, OrderDetail orderDetail) {
+ this.calendar = calendar;
+ this.orderDetail = orderDetail;
+ }
+
+ @Override
+ public int calculateDiscount() {
+ if (calendar.isWeekend()) {
+ return mainCourseDiscountPrice();
+ }
+ return NON_DISCOUNT.getDiscount();
+ }
+
+ private int mainCourseDiscountPrice() {
+ List<MenuName> mainMenu = orderDetail.getMainMenu();
+ int totalPrice = NON_DISCOUNT.getDiscount();
+ if (mainMenu.size() < MIN_ORDER_MENU) {
+ return totalPrice;
+ }
+
+ for (MenuName menuName : mainMenu) {
+ int quantityByMenu = orderDetail.getQuantityByMenu(menuName);
+ totalPrice += (quantityByMenu * MAIN_COURSE_DISCOUNT.getDiscount());
+ }
+
+ return totalPrice;
+ }
+} | Java | ~~~java
mainMenus.strem()
.mapToInt(menu -> orderDetail.getQuantityByMenu(menuName))
.sum()
~~~
๊ณผ ๊ฐ์ด ์คํธ๋ฆผ์ ํ์ฉํด ๋ณด๋ ๊ฒ๋ ์ข์๋ณด์ฌ์! |
@@ -0,0 +1,83 @@
+package christmas.model.discount.facade;
+
+import static christmas.model.discount.enums.DiscountAmount.CAN_DISCOUNT_AMOUNT;
+import static christmas.model.discount.enums.DiscountAmount.NON_DISCOUNT;
+
+import christmas.model.discount.GiveawayDiscount;
+import christmas.model.result.DiscountResult;
+import christmas.model.calendar.Calendar;
+import christmas.model.calendar.ChristmasEventCalendar;
+import christmas.model.discount.ChristmasDiscount;
+import christmas.model.discount.SpecialDiscount;
+import christmas.model.discount.WeekdaysDiscount;
+import christmas.model.discount.WeekendDiscount;
+import christmas.model.order.OrderDetail;
+import christmas.utils.Payment;
+
+public class DiscountFacade {
+
+ private final Calendar calendar;
+
+ private final OrderDetail orderDetail;
+
+ public DiscountFacade(Calendar calendar, OrderDetail orderDetail) {
+ this.calendar = calendar;
+ this.orderDetail = orderDetail;
+ }
+
+ public int calculateTotalDiscount(Payment payment, DiscountResult discountResult) {
+ if (!canDiscount(payment)) {
+ return NON_DISCOUNT.getDiscount();
+ }
+
+ if (includeChristmasDiscount()) {
+ ChristmasDiscount christmasDiscount = new ChristmasDiscount(calendar);
+ int christmasAmount = christmasDiscount.calculateDiscount();
+ discountResult.updateChristmasDiscount(christmasAmount);
+ return christmasAmount + basicDiscount(payment, discountResult);
+ }
+ return basicDiscount(payment, discountResult);
+ }
+
+ private boolean canDiscount(Payment payment) {
+ return payment.beforeDiscountPayment(orderDetail) >= CAN_DISCOUNT_AMOUNT.getDiscount();
+ }
+
+ private int basicDiscount(Payment payment, DiscountResult discountResult) {
+ int weekendAmount = calculateWeekendDiscount();
+ int weekdaysAmount = calculateWeekdaysDiscount();
+ int specialAmount = calculateSpecialDiscount();
+ int giveawayAmount = calculateGiveawayDiscount(payment);
+
+ discountResult.updateWeekendDiscount(weekendAmount);
+ discountResult.updateWeeksDaysDiscount(weekdaysAmount);
+ discountResult.updateSpecialDiscount(calculateSpecialDiscount());
+ discountResult.updateGiveawayDiscount(giveawayAmount);
+
+ return weekendAmount + weekdaysAmount + specialAmount + giveawayAmount;
+ }
+
+ private int calculateWeekendDiscount() {
+ WeekendDiscount weekendDiscount = new WeekendDiscount(calendar, orderDetail);
+ return weekendDiscount.calculateDiscount();
+ }
+
+ private int calculateWeekdaysDiscount() {
+ WeekdaysDiscount weekdaysDiscount = new WeekdaysDiscount(calendar, orderDetail);
+ return weekdaysDiscount.calculateDiscount();
+ }
+
+ private int calculateSpecialDiscount() {
+ SpecialDiscount specialDiscount = new SpecialDiscount(calendar);
+ return specialDiscount.calculateDiscount();
+ }
+
+ private int calculateGiveawayDiscount(Payment payment) {
+ GiveawayDiscount giveawayDiscount = new GiveawayDiscount(payment.beforeDiscountPayment(orderDetail));
+ return giveawayDiscount.calculateDiscount();
+ }
+
+ private boolean includeChristmasDiscount() {
+ return calendar instanceof ChristmasEventCalendar;
+ }
+} | Java | ํ ์ธ ํํ๋ค์ ๋ชจ๋ `Discount`๋ก ์ถ์ํ ํด๋์
จ๊ธฐ ๋๋ฌธ์
~~~java
List<Discount> discounts = List.of(
new WeekendDiscount(calendar, orderDetail),
new WeekdaysDiscount(calendar, orderDetail),
new SpecialDiscount(calendar)
);
int discountAmount = discounts.stream()
.mapToInt(Discount::calculateDiscount)
.sum()
~~~
์ฒ๋ผ ํ์ฉํ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค !
์ ๋ ๊ทธ๊ฒ ์ถ์ํ์ ๋ ๋ค๋ฅธ ์ฅ์ ์ด๋ผ๊ณ ์๊ฐํด์! |
@@ -0,0 +1,81 @@
+package christmas.model.order;
+
+import static christmas.exception.ErrorType.INVALID_MAX_MENU_QUANTITY;
+import static christmas.exception.ErrorType.INVALID_MENU_ONLY_DRINK;
+import static christmas.utils.Constants.MAX_ORDER_QUANTITY;
+import static christmas.utils.Constants.MIN_ORDER_MENU;
+
+import christmas.model.order.enums.Category;
+import christmas.model.order.enums.MenuInfo;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class OrderDetail {
+
+ private final OrderMenu orderMenu;
+
+ public OrderDetail(OrderMenu orderMenu) {
+ validate(orderMenu);
+ this.orderMenu = orderMenu;
+ }
+
+ public Map<String, Integer> getOrderMenuName() {
+ Map<String, Integer> details = new HashMap<>();
+ for (Map.Entry<MenuName, MenuQuantity> entry : orderMenu.getOrderMenu().entrySet()) {
+ String menuName = entry.getKey().getName();
+ int quantity = entry.getValue().getQuantity();
+ details.put(menuName, quantity);
+ }
+
+ return Collections.unmodifiableMap(details);
+ }
+
+ public int getQuantityByMenu(MenuName menuName) {
+ return orderMenu.getMenuQuantity(menuName);
+ }
+
+ public List<MenuName> getMainMenu() {
+ return orderMenu.getOrderMenu().keySet().stream()
+ .filter(orderMenu::containMainMenu)
+ .toList();
+ }
+
+ public List<MenuName> getDesertMenu() {
+ return orderMenu.getOrderMenu().keySet().stream()
+ .filter(orderMenu::containDesertMenu)
+ .toList();
+ }
+
+ private void validate(OrderMenu orderMenu) {
+ if (orderMenu.getOrderMenu().size() == MIN_ORDER_MENU) {
+ validateOnlyBeverage(orderMenu);
+ }
+
+ validateMaxQuantity(calculateTotalQuantity(orderMenu));
+ }
+
+ private void validateOnlyBeverage(OrderMenu orderMenu) {
+ MenuName menuName = orderMenu.getOrderMenu().keySet().stream()
+ .findFirst()
+ .orElseThrow();
+
+ String name = menuName.getName();
+ if (MenuInfo.findByMenuName(name).getCategory() == Category.BEVERAGE) {
+ throw new IllegalArgumentException(INVALID_MENU_ONLY_DRINK.getMessage());
+ }
+ }
+
+ private void validateMaxQuantity(int totalQuantity) {
+ if (totalQuantity > MAX_ORDER_QUANTITY) {
+ throw new IllegalArgumentException(INVALID_MAX_MENU_QUANTITY.getMessage());
+ }
+ }
+
+ private int calculateTotalQuantity(OrderMenu orderMenu) {
+ return orderMenu.getOrderMenu().values().stream()
+ .mapToInt(MenuQuantity::getQuantity)
+ .sum();
+ }
+} | Java | ์ด๋ฏธ `OrderMenu`๊ฐ ์ผ๊ธ ์ปฌ๋ ์
์ ์ญํ ์ ํ๊ณ ์๋๋ฐ ๊ตณ์ด ํ๋ฒ ๋ ๊ฐ์ธ์ผ ํ๋?? ๋ผ๋ ์๊ฐ์ด ๋ญ๋๋ค..
๊ฐ์ ์ญํ ์ `OrderMenu`๊ฐ ์ํํด๋ ๋ฌธ๋งฅ์ ์ ํ ์ด์ํ์ง ์์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,54 @@
+package christmas.model.calendar;
+
+import static christmas.model.calendar.enums.CalendarDate.CHRISTMAS;
+import static christmas.model.calendar.enums.CalendarDate.EVENT_MONTH;
+import static christmas.model.calendar.enums.CalendarDate.EVENT_YEAR;
+import static christmas.model.calendar.enums.CalendarDate.FRIDAY;
+import static christmas.model.calendar.enums.CalendarDate.SATURDAY;
+import static christmas.model.calendar.enums.CalendarDate.SUNDAY;
+
+import java.time.LocalDate;
+
+public abstract class EventCalendar implements Calendar {
+
+ protected final LocalDate eventDate;
+
+ public EventCalendar(int visitDay) {
+ validate(visitDay);
+ this.eventDate = LocalDate.of(EVENT_YEAR.getNumber(), EVENT_MONTH.getNumber(), visitDay);
+ }
+
+ protected abstract void validateDayRange(int visitDay);
+
+ @Override
+ public boolean isWeekend() {
+ int visitDay = getDayOfWeek();
+ return visitDay == FRIDAY.getNumber() || visitDay == SATURDAY.getNumber();
+ }
+
+ @Override
+ public boolean isSpecialDay() {
+ return isChristmas() || isSunday();
+ }
+
+ @Override
+ public int getDayOfMonth() {
+ return eventDate.getDayOfMonth();
+ }
+
+ private void validate(int visitDay) {
+ validateDayRange(visitDay);
+ }
+
+ private boolean isChristmas() {
+ return getDayOfMonth() == CHRISTMAS.getNumber();
+ }
+
+ private boolean isSunday() {
+ return getDayOfWeek() == SUNDAY.getNumber();
+ }
+
+ private int getDayOfWeek() {
+ return eventDate.getDayOfWeek().getValue();
+ }
+} | Java | ๊ฐ์ฌํฉ๋๋ค :) |
@@ -0,0 +1,20 @@
+package christmas.model.badge;
+
+import christmas.model.badge.enums.BadgeInfo;
+
+public class Badge {
+
+ private final BadgeInfo badgeInfo;
+
+ public Badge(int totalDiscountAmount) {
+ this.badgeInfo = selectBadge(totalDiscountAmount);
+ }
+
+ public String getBadgeName() {
+ return badgeInfo.getName();
+ }
+
+ private BadgeInfo selectBadge(int totalDiscountAmount) {
+ return BadgeInfo.findBadgeByPrice(totalDiscountAmount);
+ }
+} | Java | ๊ฐ์ฌํฉ๋๋ค. ๊ฐ์ฒด์๊ฒ ๋ฉ์ธ์ง๋ฅผ ๋์ ธ์ ์บก์ํ ์ํค๋ ค๊ณ ์๋ํ์๋๋ฐ, ์๋นํ ๋ถํ์ํ๋ค๊ณ ์๊ฐ๋๋ค์ ใ
ใ
|
@@ -0,0 +1,15 @@
+package christmas.model.order.enums;
+
+public enum Category {
+
+ APPETIZER("์ํผํ์ด์ "),
+ MAIN_COURSE("๋ฉ์ธ"),
+ DESSERT("๋์ ํธ"),
+ BEVERAGE("์๋ฃ");
+
+ private final String category;
+
+ Category(String category) {
+ this.category = category;
+ }
+} | Java | ๋ค ๋ง์ต๋๋ค! |
@@ -0,0 +1,81 @@
+package christmas.model.order;
+
+import static christmas.exception.ErrorType.INVALID_MAX_MENU_QUANTITY;
+import static christmas.exception.ErrorType.INVALID_MENU_ONLY_DRINK;
+import static christmas.utils.Constants.MAX_ORDER_QUANTITY;
+import static christmas.utils.Constants.MIN_ORDER_MENU;
+
+import christmas.model.order.enums.Category;
+import christmas.model.order.enums.MenuInfo;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class OrderDetail {
+
+ private final OrderMenu orderMenu;
+
+ public OrderDetail(OrderMenu orderMenu) {
+ validate(orderMenu);
+ this.orderMenu = orderMenu;
+ }
+
+ public Map<String, Integer> getOrderMenuName() {
+ Map<String, Integer> details = new HashMap<>();
+ for (Map.Entry<MenuName, MenuQuantity> entry : orderMenu.getOrderMenu().entrySet()) {
+ String menuName = entry.getKey().getName();
+ int quantity = entry.getValue().getQuantity();
+ details.put(menuName, quantity);
+ }
+
+ return Collections.unmodifiableMap(details);
+ }
+
+ public int getQuantityByMenu(MenuName menuName) {
+ return orderMenu.getMenuQuantity(menuName);
+ }
+
+ public List<MenuName> getMainMenu() {
+ return orderMenu.getOrderMenu().keySet().stream()
+ .filter(orderMenu::containMainMenu)
+ .toList();
+ }
+
+ public List<MenuName> getDesertMenu() {
+ return orderMenu.getOrderMenu().keySet().stream()
+ .filter(orderMenu::containDesertMenu)
+ .toList();
+ }
+
+ private void validate(OrderMenu orderMenu) {
+ if (orderMenu.getOrderMenu().size() == MIN_ORDER_MENU) {
+ validateOnlyBeverage(orderMenu);
+ }
+
+ validateMaxQuantity(calculateTotalQuantity(orderMenu));
+ }
+
+ private void validateOnlyBeverage(OrderMenu orderMenu) {
+ MenuName menuName = orderMenu.getOrderMenu().keySet().stream()
+ .findFirst()
+ .orElseThrow();
+
+ String name = menuName.getName();
+ if (MenuInfo.findByMenuName(name).getCategory() == Category.BEVERAGE) {
+ throw new IllegalArgumentException(INVALID_MENU_ONLY_DRINK.getMessage());
+ }
+ }
+
+ private void validateMaxQuantity(int totalQuantity) {
+ if (totalQuantity > MAX_ORDER_QUANTITY) {
+ throw new IllegalArgumentException(INVALID_MAX_MENU_QUANTITY.getMessage());
+ }
+ }
+
+ private int calculateTotalQuantity(OrderMenu orderMenu) {
+ return orderMenu.getOrderMenu().values().stream()
+ .mapToInt(MenuQuantity::getQuantity)
+ .sum();
+ }
+} | Java | ์๋จ์ validate๋ฅผ ๋ณด์๋ฉด ์ดํดํ์ค ์ ์์๊ฑฐ์์..! |
@@ -0,0 +1,18 @@
+package subway.config;
+
+import lombok.extern.slf4j.*;
+import org.springframework.http.*;
+import org.springframework.web.bind.annotation.*;
+
+@Slf4j
+@RestControllerAdvice
+public class GlobalExceptionHandler {
+
+ @ExceptionHandler(RuntimeException.class)
+ public ResponseEntity<ErrorResponse> runtimeException(final RuntimeException e) {
+
+ log.error("error: ", e);
+ return ResponseEntity.badRequest()
+ .body(new ErrorResponse(e.getMessage()));
+ }
+} | Java | ์๋ฌ ๊ณตํต ์ฒ๋ฆฌ๋ฅผ ์ ํด์ฃผ์
จ๋ค์! ๐
์์ธ์ข
๋ฅ์ ๋ฐ๋ผ ๋ก๊น
๋ ๋ฒจ์ ์ ์ ํ๊ฒ ๋ถ๋ฆฌํด์ ๋ก๊ทธ๋ฅผ ๋จ๊ธฐ๋ ๊ฒ๋ ์ข์ ๊ฑฐ ๊ฐ์๋ฐ ์ด๋ป๊ฒ ์๊ฐํ์๋์?
logging level ๊ด๋ จํด์๋ ์๋ ๋ด์ฉ์ ์ฐธ๊ณ ํด ์ฃผ์๋ฉด ๊ฐ์ฌํ๊ฒ ์ต๋๋ค.
์) log.error("Unexpected exception occurred: {}", e.getMessage(), e);
โ DEBUG : ๊ฐ๋ฐ๋จ๊ณ์์๋ถํฐ ํ์ฑํ.ํ๋ก์ธ์ค์์ฒ๋ฆฌ์์/ํ๋ฆ์๋ถ์ํ๋๋ฐ ๋์์ด ๋๋ ์ ๋ณด ๋ฑ
โ INFO : ๋๋ฒ๊น
์ ๋ณด์ธ์ ํ๋ก์ธ์ค์ค์ / ๊ธฐ๋์ ๊ด๋ จํ ์ ๋ณด ๋ฑ
โ WARN : ์ค๋ฅ์ํฉ์ ์๋์ง๋ง, ์ถํํ์ธ์ด ํ์ํ ์ ๋ณด ๋ฑ
โ ERROR : ์ค๋ฅ๊ฐ ๋ฐ์ํ์ํฉ .์ฆ์ ๋์์ด ํ์ํ ์์์
โ FATAL : ๋งค์ฐ ์ฌ๊ฐํ์ํฉ. ์ฆ์ ๋์์ด ํ์ํจ |
@@ -1,13 +1,13 @@
package subway.line;
import lombok.*;
+import subway.*;
+import subway.line.section.*;
import javax.persistence.*;
@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
-@AllArgsConstructor(access = AccessLevel.PRIVATE)
-@Builder
@Getter
public class Line {
@@ -21,13 +21,27 @@ public class Line {
private String color;
@Embedded
- @Builder.Default
- private LineStations lineStations = new LineStations();
+ private Sections sections;
+
+ @Builder
+ private Line(
+ final Long id,
+ final String name,
+ final String color,
+ final Section section
+ ) {
+
+ section.changeLine(this);
+ this.id = id;
+ this.name = name;
+ this.color = color;
+ this.sections = new Sections(section);
+ }
- public Line addLineStation(final LineStation lineStation) {
+ public Line addSection(final Section section) {
- this.lineStations.add(lineStation);
- lineStation.changeLine(this);
+ this.sections.add(section);
+ section.changeLine(this);
return this;
}
@@ -37,4 +51,10 @@ public Line change(final String name, final String color) {
return this;
}
+ public Line removeSection(final Station downStation) {
+
+ this.sections.remove(downStation);
+ return this;
+ }
+
} | Java | `@Embedded ์ ์ด์ฉํด ๋๋ฉ์ธ ๋ก์ง์ ์ ๋ถ๋ฆฌํด ์ฃผ์
จ๊ตฐ์! ๐ |
@@ -0,0 +1,49 @@
+package subway.line.section;
+
+import lombok.*;
+import org.springframework.stereotype.*;
+import org.springframework.transaction.annotation.*;
+import subway.*;
+import subway.line.*;
+
+@Service
+@Transactional
+@RequiredArgsConstructor
+public class SectionService {
+
+ private final StationService stationService;
+ private final LineService lineService;
+
+ public void addSection(final Long lineId, final SectionAddRequest request) {
+
+ final var line = lineService.getById(lineId);
+
+ final var upStation = stationService.getById(request.getUpStationId());
+ final var downStation = stationService.getById(request.getDownStationId());
+
+ line.addSection(createSection(request, line, upStation, downStation));
+ }
+
+ private static Section createSection(
+ final SectionAddRequest request,
+ final Line line,
+ final Station upStationId,
+ final Station downStationId
+ ) {
+
+ return Section.builder()
+ .line(line)
+ .upStation(upStationId)
+ .downStation(downStationId)
+ .distance(request.getDistance())
+ .build();
+ }
+
+ public void removeSection(final Long lineId, final Long stationId) {
+
+ final var line = lineService.getById(lineId);
+ final var station = stationService.getById(stationId);
+
+ line.removeSection(station);
+ }
+} | Java | ํด๋น ํจ์๋ SectionService ์์๋ง ์ฌ์ฉํ๋ ๊ฒ์ผ๋ก ๋ณด์ฌ์ง๋๋ฐ static ์ผ๋ก ์ ์ธํ ์ด์ ๊ฐ ์์๊น์? ๐ |
@@ -0,0 +1,81 @@
+package subway.line.section;
+
+import lombok.*;
+import subway.*;
+
+import javax.persistence.*;
+import java.util.*;
+
+@Embeddable
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public class Sections {
+
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "line", cascade = CascadeType.ALL, orphanRemoval = true)
+ private List<Section> values = new ArrayList<>();
+
+ public Sections(final Section section) {
+ final ArrayList<Section> sections = new ArrayList<>();
+ sections.add(section);
+ this.values = sections;
+ }
+
+ public Sections add(final Section section) {
+
+ validationLastStation(section.getUpStation());
+
+ if (this.anyMatchStation(section.getDownStation())) {
+ throw new DuplicateSectionStationException();
+ }
+
+ this.values.add(section);
+ return this;
+ }
+
+ private void validationLastStation(final Station section) {
+ if (!this.isLastStation(section)) {
+ throw new NotLastDownStationException();
+ }
+ }
+
+ public Sections remove(final Station downStation) {
+ validationLastStation(downStation);
+ if(isOnlyOne()) {
+ throw new OnlyOneSectionException();
+ }
+
+ this.values.removeIf(section -> section.isDownStation(downStation));
+ return this;
+ }
+
+ private boolean isOnlyOne() {
+ return this.values.size() == 1;
+ }
+
+ public List<Section> getValues() {
+
+ return List.copyOf(this.values);
+ }
+
+ public boolean isLastStation(final Station station) {
+
+ return getLastSection()
+ .map(section -> section.isDownStation(station))
+ .orElse(false);
+ }
+
+ private Optional<Section> getLastSection() {
+ if(this.values.isEmpty()) {
+ return Optional.empty();
+ }
+ return Optional.of(this.values.get(lastIndex()));
+ }
+
+ private int lastIndex() {
+ return this.values.size() - 1;
+ }
+
+ public boolean anyMatchStation(final Station station) {
+ return this.values.stream()
+ .anyMatch(section -> section.anyMatchStation(station));
+ }
+} | Java | ๋งค๊ฐ๋ณ์ ํ์
์ Station ์ธ๋ฐ ๋ณ์ ๋ช
์ section ์ด์ฌ์ ํผ๋์ด ์์ด ๋ณด์ฌ์! ๐ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.