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 ์ด์—ฌ์„œ ํ˜ผ๋™์ด ์žˆ์–ด ๋ณด์—ฌ์š”! ๐Ÿ˜Š