code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,17 @@
+package lotto.domain
+
+object LottoTicketMachine {
+ fun issue(nums: List<Int>): LottoTicket {
+ require(nums.size == 6) {
+ "๋ก๋ ๊ฐ์๋ฅผ ์๋ชป ์
๋ ฅํ์ต๋๋ค"
+ }
+
+ val lottoBox = LottoBox()
+
+ val lottoNums = nums.map {
+ lottoBox.getLottoNum(it)
+ }.toList()
+
+ return LottoTicket(lottoNums)
+ }
+} | Kotlin | issue๋ผ๋ ๋ค์ด๋ฐ์ ๋ถ์ด์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,24 @@
+package lotto.domain
+
+class LottoBox {
+ private val lottoNums: MutableMap<Int, LottoNum>
+
+ init {
+ val intRange = 1..45
+
+ lottoNums = intRange
+ .map { LottoNum(it) }
+ .associateBy { it.num }
+ .toMutableMap()
+ }
+
+ fun getLottoNum(num: Int): LottoNum {
+ val lottoNum = lottoNums[num]
+ require(lottoNum != null) {
+ "๋ก๋ ์ซ์๋ ์ค๋ณตํด์ ์
๋ ฅํ ์ ์
์ต๋๋ค"
+ }
+
+ lottoNums.remove(lottoNum.num)
+ return lottoNum
+ }
+} | Kotlin | LottoBox๋ง ๋ดค์๋ lottoNum์ด null์ด๋ผ๊ณ ํด์ ์ค๋ณต๋ ์ซ์๋ฅผ ์
๋ ฅํ๋ค๊ณ ๋ณด์ฅํ ์ ์์๊น์? |
@@ -0,0 +1,28 @@
+package lotto.domain
+
+class LottoNum(num: Int) {
+ val num: Int
+
+ init {
+ require(num in 1..45) {
+ "๋ก๋ ์ซ์ ๋ฒ์๋ 1 ~ 45 ์
๋๋ค."
+ }
+
+ this.num = num
+ }
+
+ override fun equals(other: Any?): Boolean {
+ if (this === other) return true
+ if (javaClass != other?.javaClass) return false
+
+ other as LottoNum
+
+ if (num != other.num) return false
+
+ return true
+ }
+
+ override fun hashCode(): Int {
+ return num
+ }
+} | Kotlin | inline class๋ฅผ ํ์ฉํด๋ด๋ ์ข์ ๊ฒ ๊ฐ์์!! :)
> ๋ํผํด๋์ค๋ก inline class์ value class ๋ฅผ ์ฌ์ฉํ๋๊ฑฐ ๊ฐ์๋ฐ์!
์ ์ดํด๊ฐ ์๊ฐ์์~
๋ญ๊ฐ ์ข์ ๊ธฐ๋ฅ๊ฐ๊ธฐ๋ ํ๋ฐ, ์ค๋ฌด์์ ์ด๋ป๊ฒ, ์ด๋ค์ํฉ์ ์ฌ์ฉํ๋ฉด ์ข์์ง ์ง๋ฌธ๋๋ฆฝ๋๋ค!
์ฌ์ค ์ ๋ ์ ์ฌ์ฉํ๋ค๊ณ ๋ง์๋๋ฆฌ๊ธฐ๋ ์ด๋ ต์ง๋ง, ์ ๋ ์๋์ ๊ฐ์ ๊ธฐ์ค์ ์ถฉ์กฑ์ํค๋ ๊ฒฝ์ฐ ์ธ๋ผ์ธ ํด๋์ค๋ฅผ ์ฌ์ฉํ๊ณ ์์ด์
* ํด๋น ๋ํผํ์
์ด ์ฌ๋ฌ๊ณณ์์ ํธ์ถ๋๋๊ฐ?
* ํด๋น ํด๋์ค๊ฐ data class์ ํน์ง์ ๊ฐ์ง๊ณ ์๋๊ฐ?
์ค๋ฌด์์ ์ ์ฉ์ ํ์๊ฐ ์๋๊ณ ํ์๋ค๋ง๋ค ์๊ฒฌ์ด ๋ค๋ฅผ ์ ์์ผ๋ ํ ๋ด๋ถ์ ์ผ๋ก๋ ์ด์ผ๊ธฐ๋ฅผ ํด๋ณด๊ณ ์ปจ๋ฒค์
์ ์ก์๊ฐ๋ณด๋๊ฒ๋ ๋ฐฉ๋ฒ์ผ ๊ฒ ๊ฐ์์!
[์ด๋ฐ ๊ธ](https://github.com/Kotlin/KEEP/blob/master/notes/value-classes.md)๋ ์ฝ์ด๋ณด๋ฉด ๋์์ด ๋ ๊ฒ ๊ฐ์์!! :) |
@@ -0,0 +1,28 @@
+package lotto.domain
+
+class LottoNum(num: Int) {
+ val num: Int
+
+ init {
+ require(num in 1..45) {
+ "๋ก๋ ์ซ์ ๋ฒ์๋ 1 ~ 45 ์
๋๋ค."
+ }
+
+ this.num = num
+ }
+
+ override fun equals(other: Any?): Boolean {
+ if (this === other) return true
+ if (javaClass != other?.javaClass) return false
+
+ other as LottoNum
+
+ if (num != other.num) return false
+
+ return true
+ }
+
+ override fun hashCode(): Int {
+ return num
+ }
+} | Kotlin | ์ฌ๊ธฐ๋ ๋งค์ง๋๋ฒ๋ฅผ ์์ํํด๋ณด๋ฉด ์ด๋จ๊น์? |
@@ -1,14 +1,40 @@
-import React from "react";
-import "./PostList.scss";
+import React, { useEffect, useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import Posts from './components/Posts';
+import './PostList.scss';
const PostList = () => {
+ const [postData, setPostData] = useState([]);
-return(
- <div className="postList">
- <div>๋ก๊ทธ์ธ</div>
- </div>
-);
+ const navigate = useNavigate();
+ const goToWrite = () => {
+ navigate('/post-add');
+ };
+ useEffect(() => {
+ fetch('/data/postList.json', {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json;charset=utf-8',
+ },
+ })
+ .then(res => res.json())
+ .then(result => {
+ setPostData(result.data);
+ });
+ }, []);
+
+ if (postData.length === 0) return null;
+ return (
+ <div className="postList">
+ <div className="posts">
+ <Posts postData={postData} />
+ </div>
+ <div className="buttonPlace">
+ <button onClick={goToWrite}>๊ธ์ฐ๊ธฐ</button>
+ </div>
+ </div>
+ );
};
-export default PostList;
\ No newline at end of file
+export default PostList; | JavaScript | import ์์์๋ ์ ์ง๋ณด์ ๋ฐ ๊ฐ๋
์ฑ์ ์ํ ์ปจ๋ฒค์
์ด ์์ต๋๋ค.
์์ฝ๋์ ์ปจ๋ฒค์
์ ๊ฐ๋ตํ๊ฒ ์๋์ ๊ฐ๊ณ , ์ฐธ๊ณ ํด์ ์์ ํด ์ฃผ์ธ์!
- ๋ผ์ด๋ธ๋ฌ๋ฆฌ
- React ๊ด๋ จ ํจํค์ง
- ์ธ๋ถ ๋ผ์ด๋ธ๋ฌ๋ฆฌ
- ์ปดํฌ๋ํธ
- ๊ณตํต ์ปดํฌ๋ํธ โ ๋จผ ์ปดํฌ๋ํธ โ ๊ฐ๊น์ด ์ปดํฌ๋ํธ
- ํจ์, ๋ณ์ ๋ฐ ์ค์ ํ์ผ
- ์ฌ์ง ๋ฑ ๋ฏธ๋์ด ํ์ผ(`.png`)
- css ํ์ผ (.`scss`) |
@@ -0,0 +1,63 @@
+.postList {
+ margin: 0 auto;
+ display: flex;
+ width: 576px;
+ height: 80vh;
+ padding: 40px 24px;
+ flex-direction: column;
+ align-items: center;
+ border-radius: 16px;
+ border: 1px solid #e5e5e5;
+ background: white;
+
+ .posts {
+ width: 100%;
+ overflow-y: scroll;
+ flex: 1;
+ cursor: pointer;
+ }
+ & ::-webkit-scrollbar {
+ display: none;
+ }
+
+ .buttonPlace {
+ display: flex;
+ flex-direction: column;
+ width: 528px;
+ height: 56px;
+ margin-top: 28px;
+ align-items: flex-end;
+ gap: 8px;
+ align-self: stretch;
+
+ a {
+ text-decoration: none;
+ }
+
+ button {
+ display: flex;
+ width: 120px;
+ height: 56px;
+ padding: 0px 34px;
+ justify-content: center;
+ align-items: center;
+ border-radius: 6px;
+ background-color: #2d71f7;
+ color: #fff;
+ text-align: center;
+ font-feature-settings:
+ 'clig' off,
+ 'liga' off;
+ font-family: Apple SD Gothic Neo;
+ font-size: 16px;
+ font-style: normal;
+ font-weight: 800;
+ line-height: normal;
+
+ &:hover {
+ border-radius: 6px;
+ background: #083e7f;
+ }
+ }
+ }
+} | Unknown | ๋ถ๋ชจ ์ ํ์(`&`)๋ฅผ ์ฌ์ฉํด์ ํด๋น ์์์๋ง ์ ์ฉ๋๋ ์คํ์ผ์์ ์ข ๋ ๊น๋ํ๊ฒ ๋ช
์ํ ์ ์์ต๋๋ค!
```suggestion
.posts {
overflow-y: scroll;
flex: 1;
&::-webkit-scrollbar {
display: none;
}
}
``` |
@@ -1,7 +1,18 @@
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@100;300;400;500;700;900&display=swap');
-
* {
box-sizing: border-box;
font-family: 'Noto Sans KR', sans-serif;
-}
\ No newline at end of file
+}
+
+body {
+ width: 100vw;
+ height: 100vh;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+button {
+ cursor: pointer;
+} | Unknown | ๊ณต์ฉ ํ์ผ์ ์์ ํด์ ์ฌ๋ ค์ฃผ์
จ๋๋ฐ, ๊ณต์ฉ ํ์ผ์ ์์ ์
1. ํ์๊ณผ์ ์ถฉ๋ถํ ์์ ํ์
2. ํด๋น ํ์ผ๋ง ์์ ํ๋ ๋ด์ฉ์ PR
์ ์ฌ๋ ค์ฃผ์
์ผ ํฉ๋๋ค! |
@@ -1,9 +1,100 @@
-function Header(logo, searchBox) {
+import Input from './Input';
+import Button from './Button';
+import { handleSearch } from '../services/handleSeach';
+
+function Header({ logoSrc, logoAlt, onSearch }) {
const headerElement = document.createElement('header');
- headerElement.classList.add('header');
- headerElement.appendChild(logo);
- headerElement.appendChild(searchBox);
+ headerElement.innerHTML = `
+ <h1><img src="${logoSrc}" alt="${logoAlt}" loading="lazy"></h1>
+ <div class="search-box"></div>
+ `;
+
+ let page = 1;
+
+ const searchInput = Input({
+ id: 'search-input',
+ type: 'text',
+ placeholder: '๊ฒ์',
+ onKeyDown: async (event) => {
+ if (event.code === 'Enter') {
+ document.getElementById('more-movies').remove();
+ const sectionContainer = document.querySelector('.item-view');
+
+ sectionContainer.appendChild(
+ Button({
+ classNames: ['btn', 'primary', 'full-width'],
+ type: 'button',
+ id: 'more-movies',
+ name: '๋ ๋ณด๊ธฐ',
+ onClick: () => {
+ page += 1;
+ handleSearch(searchInput.value, page);
+ }
+ })
+ );
+
+ await onSearch(event.target.value, page);
+ }
+ }
+ });
+
+ const searchButton = Button({
+ classNames: ['search-button'],
+ name: '๊ฒ์',
+ type: 'button',
+ onClick: async () => {
+ document.getElementById('more-movies').remove();
+ const sectionContainer = document.querySelector('.item-view');
+
+ sectionContainer.appendChild(
+ Button({
+ classNames: ['btn', 'primary', 'full-width'],
+ type: 'button',
+ id: 'more-movies',
+ name: '๋ ๋ณด๊ธฐ',
+ onClick: () => {
+ page += 1;
+ handleSearch(searchInput.value, page);
+ }
+ })
+ );
+
+ const inputValue = document.getElementById('search-input').value;
+ await onSearch(inputValue, page);
+ }
+ });
+
+ const searchBox = headerElement.querySelector('.search-box');
+
+ searchBox.addEventListener('mouseenter', () => {
+ const width = document.querySelector('body').getBoundingClientRect().width;
+
+ if (width <= 390) {
+ const input = document.getElementById('search-input');
+ const logo = document.querySelector('header h1');
+
+ searchBox.classList.add('search-box-toggle');
+ input.classList.add('input-toggle');
+ logo.classList.add('logo-toggle');
+ }
+ });
+
+ searchBox.addEventListener('mouseleave', () => {
+ const width = document.querySelector('body').getBoundingClientRect().width;
+
+ if (width <= 390) {
+ const input = document.getElementById('search-input');
+ const logo = document.querySelector('header h1');
+
+ searchBox.classList.remove('search-box-toggle');
+ input.classList.remove('input-toggle');
+ logo.classList.remove('logo-toggle');
+ }
+ });
+
+ searchBox.appendChild(searchInput);
+ searchBox.appendChild(searchButton);
return headerElement;
} | JavaScript | ์ ๋ ์ด๋ฒคํธ์ ์ด๋ฆ์ด ์๋ฏธํ๋๊ฒ "ํ์์ ๋ฐ์" ์ด๋ผ๊ณ ์๊ฐํด์.
๊ฐ๋ น, `onChange` ๋ ์ค์ ๋ก change๊ฐ ์ผ์ด๋ฌ์ ๋์ด๊ณ , `onKeyDown` ์ ํค๋ฅผ ๋๋ ์ ๋ ์
๋๋ค.
`onSearch`๋ "๊ฒ์์ด ๋์์ ๋ ๋ฐ์" ์ธ๋ฐ, ์ด ์ปดํฌ๋ํธ์์ ์ค์ ๋ก "๊ฒ์"์ด๋ผ๋ ํ์๊ฐ ์ผ์ด๋ฌ๋ค๊ณ ํ ์ ์์๊น์?
์ง๊ธ์ "๊ฒ์"์ด๋ผ๋ ํ์๋ฅผ ๋ฐ์์ ์ฃผ์
ํด์ฃผ๊ณ , ์ด ์ปดํฌ๋ํธ ๋ด๋ถ์์ ์ผ์ด๋ ์ผ์ "์ํฐํค๋ฅผ ๋๋ ์" ์
๋๋ค.
์ฆ, ์ด๋ฒคํธ๋ "๊ฒ์ํ์ ๋ ๋ฐ์ํจ"์ ์ด์ผ๊ธฐํ๊ณ ์๋๋ฐ ๊ฒ์์ด๋ผ๋ ๊ธฐ๋ฅ์ ๋ฐ์์ ์ฃผ์
ํด์ค ์ ๋ฐ์ ์๋ ์ํฉ์ธ๊ฑฐ์ฃ . |
@@ -1,9 +1,100 @@
-function Header(logo, searchBox) {
+import Input from './Input';
+import Button from './Button';
+import { handleSearch } from '../services/handleSeach';
+
+function Header({ logoSrc, logoAlt, onSearch }) {
const headerElement = document.createElement('header');
- headerElement.classList.add('header');
- headerElement.appendChild(logo);
- headerElement.appendChild(searchBox);
+ headerElement.innerHTML = `
+ <h1><img src="${logoSrc}" alt="${logoAlt}" loading="lazy"></h1>
+ <div class="search-box"></div>
+ `;
+
+ let page = 1;
+
+ const searchInput = Input({
+ id: 'search-input',
+ type: 'text',
+ placeholder: '๊ฒ์',
+ onKeyDown: async (event) => {
+ if (event.code === 'Enter') {
+ document.getElementById('more-movies').remove();
+ const sectionContainer = document.querySelector('.item-view');
+
+ sectionContainer.appendChild(
+ Button({
+ classNames: ['btn', 'primary', 'full-width'],
+ type: 'button',
+ id: 'more-movies',
+ name: '๋ ๋ณด๊ธฐ',
+ onClick: () => {
+ page += 1;
+ handleSearch(searchInput.value, page);
+ }
+ })
+ );
+
+ await onSearch(event.target.value, page);
+ }
+ }
+ });
+
+ const searchButton = Button({
+ classNames: ['search-button'],
+ name: '๊ฒ์',
+ type: 'button',
+ onClick: async () => {
+ document.getElementById('more-movies').remove();
+ const sectionContainer = document.querySelector('.item-view');
+
+ sectionContainer.appendChild(
+ Button({
+ classNames: ['btn', 'primary', 'full-width'],
+ type: 'button',
+ id: 'more-movies',
+ name: '๋ ๋ณด๊ธฐ',
+ onClick: () => {
+ page += 1;
+ handleSearch(searchInput.value, page);
+ }
+ })
+ );
+
+ const inputValue = document.getElementById('search-input').value;
+ await onSearch(inputValue, page);
+ }
+ });
+
+ const searchBox = headerElement.querySelector('.search-box');
+
+ searchBox.addEventListener('mouseenter', () => {
+ const width = document.querySelector('body').getBoundingClientRect().width;
+
+ if (width <= 390) {
+ const input = document.getElementById('search-input');
+ const logo = document.querySelector('header h1');
+
+ searchBox.classList.add('search-box-toggle');
+ input.classList.add('input-toggle');
+ logo.classList.add('logo-toggle');
+ }
+ });
+
+ searchBox.addEventListener('mouseleave', () => {
+ const width = document.querySelector('body').getBoundingClientRect().width;
+
+ if (width <= 390) {
+ const input = document.getElementById('search-input');
+ const logo = document.querySelector('header h1');
+
+ searchBox.classList.remove('search-box-toggle');
+ input.classList.remove('input-toggle');
+ logo.classList.remove('logo-toggle');
+ }
+ });
+
+ searchBox.appendChild(searchInput);
+ searchBox.appendChild(searchButton);
return headerElement;
} | JavaScript | ์ด ๋ถ๋ถ๋ ๋์ผํฉ๋๋ค! |
@@ -1,9 +1,100 @@
-function Header(logo, searchBox) {
+import Input from './Input';
+import Button from './Button';
+import { handleSearch } from '../services/handleSeach';
+
+function Header({ logoSrc, logoAlt, onSearch }) {
const headerElement = document.createElement('header');
- headerElement.classList.add('header');
- headerElement.appendChild(logo);
- headerElement.appendChild(searchBox);
+ headerElement.innerHTML = `
+ <h1><img src="${logoSrc}" alt="${logoAlt}" loading="lazy"></h1>
+ <div class="search-box"></div>
+ `;
+
+ let page = 1;
+
+ const searchInput = Input({
+ id: 'search-input',
+ type: 'text',
+ placeholder: '๊ฒ์',
+ onKeyDown: async (event) => {
+ if (event.code === 'Enter') {
+ document.getElementById('more-movies').remove();
+ const sectionContainer = document.querySelector('.item-view');
+
+ sectionContainer.appendChild(
+ Button({
+ classNames: ['btn', 'primary', 'full-width'],
+ type: 'button',
+ id: 'more-movies',
+ name: '๋ ๋ณด๊ธฐ',
+ onClick: () => {
+ page += 1;
+ handleSearch(searchInput.value, page);
+ }
+ })
+ );
+
+ await onSearch(event.target.value, page);
+ }
+ }
+ });
+
+ const searchButton = Button({
+ classNames: ['search-button'],
+ name: '๊ฒ์',
+ type: 'button',
+ onClick: async () => {
+ document.getElementById('more-movies').remove();
+ const sectionContainer = document.querySelector('.item-view');
+
+ sectionContainer.appendChild(
+ Button({
+ classNames: ['btn', 'primary', 'full-width'],
+ type: 'button',
+ id: 'more-movies',
+ name: '๋ ๋ณด๊ธฐ',
+ onClick: () => {
+ page += 1;
+ handleSearch(searchInput.value, page);
+ }
+ })
+ );
+
+ const inputValue = document.getElementById('search-input').value;
+ await onSearch(inputValue, page);
+ }
+ });
+
+ const searchBox = headerElement.querySelector('.search-box');
+
+ searchBox.addEventListener('mouseenter', () => {
+ const width = document.querySelector('body').getBoundingClientRect().width;
+
+ if (width <= 390) {
+ const input = document.getElementById('search-input');
+ const logo = document.querySelector('header h1');
+
+ searchBox.classList.add('search-box-toggle');
+ input.classList.add('input-toggle');
+ logo.classList.add('logo-toggle');
+ }
+ });
+
+ searchBox.addEventListener('mouseleave', () => {
+ const width = document.querySelector('body').getBoundingClientRect().width;
+
+ if (width <= 390) {
+ const input = document.getElementById('search-input');
+ const logo = document.querySelector('header h1');
+
+ searchBox.classList.remove('search-box-toggle');
+ input.classList.remove('input-toggle');
+ logo.classList.remove('logo-toggle');
+ }
+ });
+
+ searchBox.appendChild(searchInput);
+ searchBox.appendChild(searchButton);
return headerElement;
} | JavaScript | ์ฌ๊ธฐ์ ์ฐ์ด๋ 390 ์ด๋ผ๋ ์ซ์๋ ์์๋ก ๋ง๋ค์ด์ ์ฌ์ฉํด์ฃผ๋ฉด ์ด๋จ๊น์!? |
@@ -1,9 +1,100 @@
-function Header(logo, searchBox) {
+import Input from './Input';
+import Button from './Button';
+import { handleSearch } from '../services/handleSeach';
+
+function Header({ logoSrc, logoAlt, onSearch }) {
const headerElement = document.createElement('header');
- headerElement.classList.add('header');
- headerElement.appendChild(logo);
- headerElement.appendChild(searchBox);
+ headerElement.innerHTML = `
+ <h1><img src="${logoSrc}" alt="${logoAlt}" loading="lazy"></h1>
+ <div class="search-box"></div>
+ `;
+
+ let page = 1;
+
+ const searchInput = Input({
+ id: 'search-input',
+ type: 'text',
+ placeholder: '๊ฒ์',
+ onKeyDown: async (event) => {
+ if (event.code === 'Enter') {
+ document.getElementById('more-movies').remove();
+ const sectionContainer = document.querySelector('.item-view');
+
+ sectionContainer.appendChild(
+ Button({
+ classNames: ['btn', 'primary', 'full-width'],
+ type: 'button',
+ id: 'more-movies',
+ name: '๋ ๋ณด๊ธฐ',
+ onClick: () => {
+ page += 1;
+ handleSearch(searchInput.value, page);
+ }
+ })
+ );
+
+ await onSearch(event.target.value, page);
+ }
+ }
+ });
+
+ const searchButton = Button({
+ classNames: ['search-button'],
+ name: '๊ฒ์',
+ type: 'button',
+ onClick: async () => {
+ document.getElementById('more-movies').remove();
+ const sectionContainer = document.querySelector('.item-view');
+
+ sectionContainer.appendChild(
+ Button({
+ classNames: ['btn', 'primary', 'full-width'],
+ type: 'button',
+ id: 'more-movies',
+ name: '๋ ๋ณด๊ธฐ',
+ onClick: () => {
+ page += 1;
+ handleSearch(searchInput.value, page);
+ }
+ })
+ );
+
+ const inputValue = document.getElementById('search-input').value;
+ await onSearch(inputValue, page);
+ }
+ });
+
+ const searchBox = headerElement.querySelector('.search-box');
+
+ searchBox.addEventListener('mouseenter', () => {
+ const width = document.querySelector('body').getBoundingClientRect().width;
+
+ if (width <= 390) {
+ const input = document.getElementById('search-input');
+ const logo = document.querySelector('header h1');
+
+ searchBox.classList.add('search-box-toggle');
+ input.classList.add('input-toggle');
+ logo.classList.add('logo-toggle');
+ }
+ });
+
+ searchBox.addEventListener('mouseleave', () => {
+ const width = document.querySelector('body').getBoundingClientRect().width;
+
+ if (width <= 390) {
+ const input = document.getElementById('search-input');
+ const logo = document.querySelector('header h1');
+
+ searchBox.classList.remove('search-box-toggle');
+ input.classList.remove('input-toggle');
+ logo.classList.remove('logo-toggle');
+ }
+ });
+
+ searchBox.appendChild(searchInput);
+ searchBox.appendChild(searchButton);
return headerElement;
} | JavaScript | ์ ๋ณด๋๊น ๋ก์ง์ด ๊ฑฐ์ ์ ์ฌํ๋ค์! |
@@ -0,0 +1,33 @@
+import handleMovie from '../services/handleMovie';
+import Button from './Button';
+
+function MainContent(initialPage) {
+ let page = initialPage;
+ const mainElement = document.createElement('main');
+ mainElement.id = 'main';
+
+ mainElement.innerHTML = `
+ <section class="item-view">
+ <h2>์ง๊ธ ์ธ๊ธฐ ์๋ ์ํ</h2>
+ <ul class="item-list"></ul>
+ </section>
+ `;
+
+ const sectionElement = mainElement.querySelector('.item-view');
+ sectionElement.appendChild(
+ Button({
+ classNames: ['btn', 'primary', 'full-width'],
+ type: 'button',
+ id: 'more-movies',
+ name: '๋ ๋ณด๊ธฐ',
+ onClick: () => {
+ page += 1;
+ handleMovie(page);
+ }
+ })
+ );
+
+ return mainElement;
+}
+
+export default MainContent; | JavaScript | ```suggestion
const mainElement = html(`
<main id="main">
<section class="item-view">
<h2>์ง๊ธ ์ธ๊ธฐ ์๋ ์ํ</h2>
<ul class="item-list"></ul>
</section>
<main>
`);
```
์ด๋ ๊ฒ ํํํ ์ ์๋๋ก ํจ์๋ฅผ ํ๋ ๋ง๋ค์ด์ฃผ์๋ฉด ์ด๋จ๊น์!? |
@@ -0,0 +1,33 @@
+import handleMovie from '../services/handleMovie';
+import Button from './Button';
+
+function MainContent(initialPage) {
+ let page = initialPage;
+ const mainElement = document.createElement('main');
+ mainElement.id = 'main';
+
+ mainElement.innerHTML = `
+ <section class="item-view">
+ <h2>์ง๊ธ ์ธ๊ธฐ ์๋ ์ํ</h2>
+ <ul class="item-list"></ul>
+ </section>
+ `;
+
+ const sectionElement = mainElement.querySelector('.item-view');
+ sectionElement.appendChild(
+ Button({
+ classNames: ['btn', 'primary', 'full-width'],
+ type: 'button',
+ id: 'more-movies',
+ name: '๋ ๋ณด๊ธฐ',
+ onClick: () => {
+ page += 1;
+ handleMovie(page);
+ }
+ })
+ );
+
+ return mainElement;
+}
+
+export default MainContent; | JavaScript | ์์์๋ html template์ผ๋ก ํํ๋๊ณ ์ฌ๊ธฐ์๋ ์ด๋ ๊ฒ ํํ๋๊ณ ์์ด์ ์ฝ๋๋ฅผ ์ฝ๋ ์ฌ๋ ์
์ฅ์์๋ ์กฐ๊ธ ํท๊ฐ๋ฆฌ์ง ์์๊น ์ถ์ด์! |
@@ -0,0 +1,47 @@
+import { BASE_URL } from '../constants/api';
+import { APIError } from '../apis/error';
+
+interface ApiClientType {
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE';
+ endpoint: string;
+ params?: Record<string, string>;
+ headers?: Record<string, string>;
+ body?: Record<string, any>;
+}
+
+class ApiClient {
+ static async request({ method, endpoint, params, headers = {}, body }: ApiClientType) {
+ const url = params
+ ? this.createUrlSearchParams({ baseUrl: `${BASE_URL}/${endpoint}`, params })
+ : `${BASE_URL}/${endpoint}`;
+
+ const options: RequestInit = {
+ method,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...headers
+ },
+ ...(body && { body: JSON.stringify(body) })
+ };
+
+ try {
+ const response = await fetch(url, options);
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new APIError(data.status_code, data.status_message);
+ }
+ return data;
+ } catch (error: any) {
+ throw new APIError(400, error.message || 'An unknown error occurred');
+ }
+ }
+
+ static createUrlSearchParams({ baseUrl, params }: { baseUrl: string; params: Record<string, string> }) {
+ const url = new URL(baseUrl);
+ url.search = new URLSearchParams(params).toString();
+ return url.toString();
+ }
+}
+
+export default ApiClient; | TypeScript | ์ํ.. ์ด ํ์ผ ๋๋ฌธ์ tsconfig๊ฐ ์๊ธด๊ฑฐ์๊ตฐ์ |
@@ -0,0 +1,47 @@
+import { BASE_URL } from '../constants/api';
+import { APIError } from '../apis/error';
+
+interface ApiClientType {
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE';
+ endpoint: string;
+ params?: Record<string, string>;
+ headers?: Record<string, string>;
+ body?: Record<string, any>;
+}
+
+class ApiClient {
+ static async request({ method, endpoint, params, headers = {}, body }: ApiClientType) {
+ const url = params
+ ? this.createUrlSearchParams({ baseUrl: `${BASE_URL}/${endpoint}`, params })
+ : `${BASE_URL}/${endpoint}`;
+
+ const options: RequestInit = {
+ method,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...headers
+ },
+ ...(body && { body: JSON.stringify(body) })
+ };
+
+ try {
+ const response = await fetch(url, options);
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new APIError(data.status_code, data.status_message);
+ }
+ return data;
+ } catch (error: any) {
+ throw new APIError(400, error.message || 'An unknown error occurred');
+ }
+ }
+
+ static createUrlSearchParams({ baseUrl, params }: { baseUrl: string; params: Record<string, string> }) {
+ const url = new URL(baseUrl);
+ url.search = new URLSearchParams(params).toString();
+ return url.toString();
+ }
+}
+
+export default ApiClient; | TypeScript | try ๊ตฌ๊ฐ์์ ์ค๋ฅ ๋ฐ์ -> catch๋ก ์ง์
-> ๋ฌด์กฐ๊ฑด status๋ 400์ผ๋ก ๊ณ ์ ํ์ฌ ๋ค์ error throw
์ด๋ ๊ฒ ๋ฉ๋๋ค.
์ ์๋ฏธํ ์๋ฌ ํ๋ก์ฐ์ผ๊น์~? |
@@ -0,0 +1,47 @@
+import { BASE_URL } from '../constants/api';
+import { APIError } from '../apis/error';
+
+interface ApiClientType {
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE';
+ endpoint: string;
+ params?: Record<string, string>;
+ headers?: Record<string, string>;
+ body?: Record<string, any>;
+}
+
+class ApiClient {
+ static async request({ method, endpoint, params, headers = {}, body }: ApiClientType) {
+ const url = params
+ ? this.createUrlSearchParams({ baseUrl: `${BASE_URL}/${endpoint}`, params })
+ : `${BASE_URL}/${endpoint}`;
+
+ const options: RequestInit = {
+ method,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...headers
+ },
+ ...(body && { body: JSON.stringify(body) })
+ };
+
+ try {
+ const response = await fetch(url, options);
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new APIError(data.status_code, data.status_message);
+ }
+ return data;
+ } catch (error: any) {
+ throw new APIError(400, error.message || 'An unknown error occurred');
+ }
+ }
+
+ static createUrlSearchParams({ baseUrl, params }: { baseUrl: string; params: Record<string, string> }) {
+ const url = new URL(baseUrl);
+ url.search = new URLSearchParams(params).toString();
+ return url.toString();
+ }
+}
+
+export default ApiClient; | TypeScript | ๊ทธ๋ฐ๋ฐ ์ด ํ์ผ์ด ์ domain ์ ํด๋นํ๋๊ฑธ๊น์~?
domain์ด๋ผ๊ณ ํ๊ธฐ์ ๋ง ๊ทธ๋๋ก ์ฌ์ด๋ ์ดํํธ(client)๋ฅผ ํํํ๊ฑฐ๋ผ์... ์ ํ ์ฐ๊ด์ด ์์ด๋ณด์ฌ์! |
@@ -0,0 +1,24 @@
+import getMovieList from '../apis/getMovieList';
+import ConfirmModal from '../components/modal/ConfirmModal';
+import { Modal } from '../components/modal/container/Modal';
+import { NOT_MORE_MOVIES_MESSAGE } from '../constants/message';
+import renderMovies from '../view/renderMovies';
+import renderSkeletonMovies from '../view/renderSkeletonMovies';
+
+export default async function handleMovie(page) {
+ try {
+ renderSkeletonMovies({ loading: true });
+ const movieList = await getMovieList(page);
+ renderSkeletonMovies({ loading: false });
+
+ if (movieList.results.length === 0) {
+ document.getElementById('more-movies').remove();
+ new Modal(document.querySelector('body'), ConfirmModal(NOT_MORE_MOVIES_MESSAGE));
+ }
+
+ renderMovies({ movieList: movieList.results, resetHTML: false });
+ } catch (error) {
+ renderSkeletonMovies({ loading: false });
+ new Modal(document.querySelector('body'), ConfirmModal(error.message));
+ }
+} | JavaScript | api์์ ๋ฐ์ํ ์๋ฌ ์ค์ message๋ง ์ฌ์ฉํ๊ณ ์๋๋ฐ, CustomError๋ฅผ ๋ง๋ค์ด์ ์ฐ๋ ์๋ฏธ๊ฐ ์๋๊ฑด๊ฐ ์ถ์ด์! |
@@ -0,0 +1,47 @@
+import { BASE_URL } from '../constants/api';
+import { APIError } from '../apis/error';
+
+interface ApiClientType {
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE';
+ endpoint: string;
+ params?: Record<string, string>;
+ headers?: Record<string, string>;
+ body?: Record<string, any>;
+}
+
+class ApiClient {
+ static async request({ method, endpoint, params, headers = {}, body }: ApiClientType) {
+ const url = params
+ ? this.createUrlSearchParams({ baseUrl: `${BASE_URL}/${endpoint}`, params })
+ : `${BASE_URL}/${endpoint}`;
+
+ const options: RequestInit = {
+ method,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...headers
+ },
+ ...(body && { body: JSON.stringify(body) })
+ };
+
+ try {
+ const response = await fetch(url, options);
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new APIError(data.status_code, data.status_message);
+ }
+ return data;
+ } catch (error: any) {
+ throw new APIError(400, error.message || 'An unknown error occurred');
+ }
+ }
+
+ static createUrlSearchParams({ baseUrl, params }: { baseUrl: string; params: Record<string, string> }) {
+ const url = new URL(baseUrl);
+ url.search = new URLSearchParams(params).toString();
+ return url.toString();
+ }
+}
+
+export default ApiClient; | TypeScript | domain์ด apis๋ฅผ ์ฐธ์กฐํ๋๊ฑด ์ด์ํด๋ณด์ฌ์! |
@@ -1,2 +1 @@
export const BASE_URL = 'https://api.themoviedb.org';
-export const IMAGE_BASE_URL = 'https://image.tmdb.org/t/p/w500'; | JavaScript | ์ด๋ฐ ์ ๋ณด๋ ์์ API๋ฅผ ์์ฒญํ๋ ์ชฝ์์ ๊ฐ์ง๊ณ ์์ผ๋ฉด ์ด๋จ๊น์? |
@@ -0,0 +1 @@
+export const NOT_MORE_MOVIES_MESSAGE = '๋์ด์ ์ํ๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค.'; | JavaScript | ์ด๋ฐ ์๋ฌ ๋ฉ์ธ์ง๋ ๋ฉ์ธ์ง๋ฅผ ์ฌ์ฉํ๋ ์ชฝ์์ ๊ฐ์ง๊ณ ์์ผ๋ฉด ์ด๋จ๊น์?
๋ค๋ฅธ ๊ตฌ๊ฐ์์๋ ์์ ์ฌ์ฉ๋ ๊ฒ ๊ฐ์ง ์์์์! |
@@ -0,0 +1,8 @@
+import "./css/reset.css";
+import "./css/common.css";
+import App from "./App";
+
+addEventListener("DOMContentLoaded", async () => {
+ const app = new App();
+ app.init();
+}); | JavaScript | ์ ํจ์๊ฐ ๋ฐ๋ก ์ฑ์ ๊ตฌ๋์ํค๋ Entry ํฌ์ธํธ๊ตฐ์!
`controller`๋ฅผ ์ด๊ธฐํํ๋ค? ๋ณด๋ค๋ `App`์ ์ด๊ธฐํํ๋ค๋ ๋๋์ด ์ด๋จ๊น์? |
@@ -0,0 +1,14 @@
+import { apiClient } from "./apiClient";
+import { BASE_URL } from "./constants";
+
+export const fetchPopularMovies = async ({ page = 1 }) => {
+ const param = new URLSearchParams({
+ api_key: process.env.TMDB_API_KEY,
+ language: "ko-KR",
+ page,
+ });
+
+ const response = await apiClient.get(`${BASE_URL}?${param}`);
+
+ return response.results;
+}; | JavaScript | ์ค ์ข์ต๋๋ค! |
@@ -0,0 +1,34 @@
+import { ApiError } from "./apiError";
+
+export const apiClient = {
+ get: async (url, headers = {}) => {
+ return apiClient.request("GET", url, null, headers);
+ },
+
+ request: async (method, url, body = null, headers = {}) => {
+ const options = {
+ method,
+ headers: {
+ "Content-Type": "application/json",
+ ...headers,
+ },
+ body: body && JSON.stringify(body),
+ };
+
+ try {
+ const response = await fetch(url, options);
+
+ if (!response.ok) {
+ throw new ApiError(response.status);
+ }
+
+ return await response.json();
+ } catch (error) {
+ if (error instanceof ApiError) {
+ ApiError.handle(error);
+ } else {
+ throw error;
+ }
+ }
+ },
+}; | JavaScript | `request()`์ `get()`์ ์ฐจ์ด๋ ๋ฌด์์ด๊ณ ๋๋ ์ด์ ๋ ๋ฌด์์ผ๊น์? |
@@ -0,0 +1,31 @@
+import { ERROR_MSG } from "./constants";
+
+export class ApiError extends Error {
+ constructor(message, details, status = -1) {
+ super(message);
+ this.details = details;
+ this.status = status;
+ }
+
+ static handle(error) {
+ let errMsg;
+ let errDetails;
+
+ switch (parseInt(error.message)) {
+ case 401:
+ errMsg = ERROR_MSG.INVALID_API_KEY.message;
+ errDetails = ERROR_MSG.INVALID_API_KEY.details;
+ break;
+ case 404:
+ errMsg = ERROR_MSG.INVALID_REQUEST.message;
+ errDetails = ERROR_MSG.INVALID_REQUEST.details;
+ break;
+ default:
+ errMsg = ERROR_MSG.DEFAULT.message;
+ errDetails = ERROR_MSG.DEFAULT.details;
+ break;
+ }
+
+ throw new ApiError(errMsg, errDetails, error.status);
+ }
+} | JavaScript | ์ค ์ข์ ์๋์
๋๋ค ๐ |
@@ -0,0 +1,16 @@
+import { mainTitle, mainMoreButton, movieCardsList } from "./index";
+
+export const mainSection = {
+ render() {
+ const element = document.createElement("section");
+ element.classList.add("item-view");
+
+ const title = mainTitle.render();
+ const itemList = movieCardsList.render();
+ const moreButton = mainMoreButton.render();
+
+ element.append(title, itemList, moreButton);
+
+ return element;
+ },
+}; | JavaScript | [append()](https://developer.mozilla.org/en-US/docs/Web/API/Element/append)๋ฅผ ํ์ฉํด๋ณด์ธ์! |
@@ -0,0 +1,46 @@
+describe("API ํ
์คํธ", () => {
+ it("์ํ ๋ชฉ๋ก API๋ฅผ ํธ์ถํ๋ฉด 20๊ฐ์ฉ ์ํ๋ฅผ ๋ฐ์์จ๋ค.", () => {
+ const baseUrl = "https://api.themoviedb.org/3/movie/popular";
+ const param = new URLSearchParams({
+ api_key: Cypress.env("TMDB_API_KEY"),
+ language: "ko-KR",
+ page: 1,
+ });
+
+ cy.request(`${baseUrl}?${param}`).then((response) => {
+ expect(response.status).to.eq(200);
+ expect(response.body.results).to.have.length(20);
+ });
+ });
+});
+
+describe("์ํ ๋ฆฌ๋ทฐ ์น ํ
์คํธ", () => {
+ beforeEach(() => {
+ cy.visit("http://localhost:8080");
+ });
+
+ it("์ํ ์นด๋๋ ์ธ๋ค์ผ, ๋ณ์ , ์ ๋ชฉ์ ๊ฐ๋๋ค.", () => {
+ cy.get(".item-card").each(($el) => {
+ cy.wrap($el).within(() => {
+ cy.get(".item-thumbnail").should("be.visible");
+ cy.get(".item-title").should("be.visible");
+ cy.get(".item-score").should("be.visible");
+ });
+ });
+ });
+
+ it("์ํ ๋ชฉ๋ก์ ํ ํ์ด์ง์ 20๊ฐ์ฉ ๋์จ๋ค.", () => {
+ cy.get(".item-list li").should("have.length", 20);
+ });
+
+ it("๋๋ณด๊ธฐ ๋ฒํผ์ ๋๋ฅด๋ฉด 20๊ฐ์ ์ํ๊ฐ ์ถ๊ฐ๋ก ์์ฑ๋๋ค.", () => {
+ cy.get(".show-more").click();
+ cy.get(".item-list li").should("have.length", 40);
+ });
+
+ it("์ํ ๋ชฉ๋ก์ ๋ถ๋ฌ์ค๋ ๋์ ์ค์ผ๋ ํค UI๋ฅผ ๋ณด์ฌ์ค๋ค.", () => {
+ cy.get(".skeleton-card").should("have.length", 20);
+ cy.wait(1000);
+ cy.get(".skeleton-card").should("have.length", 0);
+ });
+}); | JavaScript | ์คํธ?
`exist`๋ก ๊ฒ์ฌํ๋ฉด ๋ฌด์์ด ๋ค๋ฅผ๊น์? |
@@ -0,0 +1,46 @@
+describe("API ํ
์คํธ", () => {
+ it("์ํ ๋ชฉ๋ก API๋ฅผ ํธ์ถํ๋ฉด 20๊ฐ์ฉ ์ํ๋ฅผ ๋ฐ์์จ๋ค.", () => {
+ const baseUrl = "https://api.themoviedb.org/3/movie/popular";
+ const param = new URLSearchParams({
+ api_key: Cypress.env("TMDB_API_KEY"),
+ language: "ko-KR",
+ page: 1,
+ });
+
+ cy.request(`${baseUrl}?${param}`).then((response) => {
+ expect(response.status).to.eq(200);
+ expect(response.body.results).to.have.length(20);
+ });
+ });
+});
+
+describe("์ํ ๋ฆฌ๋ทฐ ์น ํ
์คํธ", () => {
+ beforeEach(() => {
+ cy.visit("http://localhost:8080");
+ });
+
+ it("์ํ ์นด๋๋ ์ธ๋ค์ผ, ๋ณ์ , ์ ๋ชฉ์ ๊ฐ๋๋ค.", () => {
+ cy.get(".item-card").each(($el) => {
+ cy.wrap($el).within(() => {
+ cy.get(".item-thumbnail").should("be.visible");
+ cy.get(".item-title").should("be.visible");
+ cy.get(".item-score").should("be.visible");
+ });
+ });
+ });
+
+ it("์ํ ๋ชฉ๋ก์ ํ ํ์ด์ง์ 20๊ฐ์ฉ ๋์จ๋ค.", () => {
+ cy.get(".item-list li").should("have.length", 20);
+ });
+
+ it("๋๋ณด๊ธฐ ๋ฒํผ์ ๋๋ฅด๋ฉด 20๊ฐ์ ์ํ๊ฐ ์ถ๊ฐ๋ก ์์ฑ๋๋ค.", () => {
+ cy.get(".show-more").click();
+ cy.get(".item-list li").should("have.length", 40);
+ });
+
+ it("์ํ ๋ชฉ๋ก์ ๋ถ๋ฌ์ค๋ ๋์ ์ค์ผ๋ ํค UI๋ฅผ ๋ณด์ฌ์ค๋ค.", () => {
+ cy.get(".skeleton-card").should("have.length", 20);
+ cy.wait(1000);
+ cy.get(".skeleton-card").should("have.length", 0);
+ });
+}); | JavaScript | 40์ผ๋ก ๊ฒ์ฌํ๋ ์ด์ ๋ ์ด๊ธฐ ๋ฆฌ์คํธ 20 + ์ถ๊ฐ ๋๋ณด๊ธฐ 20์ผ๊น์? |
@@ -0,0 +1,34 @@
+import { ApiError } from "./apiError";
+
+export const apiClient = {
+ get: async (url, headers = {}) => {
+ return apiClient.request("GET", url, null, headers);
+ },
+
+ request: async (method, url, body = null, headers = {}) => {
+ const options = {
+ method,
+ headers: {
+ "Content-Type": "application/json",
+ ...headers,
+ },
+ body: body && JSON.stringify(body),
+ };
+
+ try {
+ const response = await fetch(url, options);
+
+ if (!response.ok) {
+ throw new ApiError(response.status);
+ }
+
+ return await response.json();
+ } catch (error) {
+ if (error instanceof ApiError) {
+ ApiError.handle(error);
+ } else {
+ throw error;
+ }
+ }
+ },
+}; | JavaScript | `request()`๋ ๋งค๊ฐ๋ณ์๋ก ๋ฐ๋ method๋ฅผ ํตํด API ์์ฒญ์ ๋ณด๋ด๋ ํจ์์ด๊ณ , `get()`์ ํด๋น `request()` ํจ์์ `GET`์์ฒญ์ ๋ณด๋ด๋ ํจ์์
๋๋ค.
์ด๋ฒ ๊ณผ์ ์์ GET ์์ฒญ๋ง ์กด์ฌํ์ฌ ์ถ๊ฐํ์ง ์์์ง๋ง ์ถํ์ ๋ค๋ฅธ ๋ฉ์๋ ์์ฒญ์ ์ถ๊ฐํ ์ ์๊ฒ ์์ฑํ์์ต๋๋ค! |
@@ -0,0 +1,46 @@
+describe("API ํ
์คํธ", () => {
+ it("์ํ ๋ชฉ๋ก API๋ฅผ ํธ์ถํ๋ฉด 20๊ฐ์ฉ ์ํ๋ฅผ ๋ฐ์์จ๋ค.", () => {
+ const baseUrl = "https://api.themoviedb.org/3/movie/popular";
+ const param = new URLSearchParams({
+ api_key: Cypress.env("TMDB_API_KEY"),
+ language: "ko-KR",
+ page: 1,
+ });
+
+ cy.request(`${baseUrl}?${param}`).then((response) => {
+ expect(response.status).to.eq(200);
+ expect(response.body.results).to.have.length(20);
+ });
+ });
+});
+
+describe("์ํ ๋ฆฌ๋ทฐ ์น ํ
์คํธ", () => {
+ beforeEach(() => {
+ cy.visit("http://localhost:8080");
+ });
+
+ it("์ํ ์นด๋๋ ์ธ๋ค์ผ, ๋ณ์ , ์ ๋ชฉ์ ๊ฐ๋๋ค.", () => {
+ cy.get(".item-card").each(($el) => {
+ cy.wrap($el).within(() => {
+ cy.get(".item-thumbnail").should("be.visible");
+ cy.get(".item-title").should("be.visible");
+ cy.get(".item-score").should("be.visible");
+ });
+ });
+ });
+
+ it("์ํ ๋ชฉ๋ก์ ํ ํ์ด์ง์ 20๊ฐ์ฉ ๋์จ๋ค.", () => {
+ cy.get(".item-list li").should("have.length", 20);
+ });
+
+ it("๋๋ณด๊ธฐ ๋ฒํผ์ ๋๋ฅด๋ฉด 20๊ฐ์ ์ํ๊ฐ ์ถ๊ฐ๋ก ์์ฑ๋๋ค.", () => {
+ cy.get(".show-more").click();
+ cy.get(".item-list li").should("have.length", 40);
+ });
+
+ it("์ํ ๋ชฉ๋ก์ ๋ถ๋ฌ์ค๋ ๋์ ์ค์ผ๋ ํค UI๋ฅผ ๋ณด์ฌ์ค๋ค.", () => {
+ cy.get(".skeleton-card").should("have.length", 20);
+ cy.wait(1000);
+ cy.get(".skeleton-card").should("have.length", 0);
+ });
+}); | JavaScript | ์์ฑ๋ `movieCard`์๋ ์ธ๋ค์ผ, ๋ณ์ , ์ ๋ชฉ element๊ฐ `์กด์ฌ`ํ๋ค๋ ์๋ฏธ์์ ์ฌ์ฉํ ๊ฒ ๊ฐ์ต๋๋ค!
๋ค์ ์๊ฐํด๋ณด๋, ํด๋น element๊ฐ ์กด์ฌํ์ง๋ง ๋ณด์ฌ์ง์ง ์๊ฑฐ๋ ์ด๋ค css issue๊ฐ ์๊ธธ ์๋ ์๋ค๋ ์๊ฐ์ `be.visible`๋ก ๋์ฒดํ์์ต๋๋ค. |
@@ -0,0 +1,46 @@
+describe("API ํ
์คํธ", () => {
+ it("์ํ ๋ชฉ๋ก API๋ฅผ ํธ์ถํ๋ฉด 20๊ฐ์ฉ ์ํ๋ฅผ ๋ฐ์์จ๋ค.", () => {
+ const baseUrl = "https://api.themoviedb.org/3/movie/popular";
+ const param = new URLSearchParams({
+ api_key: Cypress.env("TMDB_API_KEY"),
+ language: "ko-KR",
+ page: 1,
+ });
+
+ cy.request(`${baseUrl}?${param}`).then((response) => {
+ expect(response.status).to.eq(200);
+ expect(response.body.results).to.have.length(20);
+ });
+ });
+});
+
+describe("์ํ ๋ฆฌ๋ทฐ ์น ํ
์คํธ", () => {
+ beforeEach(() => {
+ cy.visit("http://localhost:8080");
+ });
+
+ it("์ํ ์นด๋๋ ์ธ๋ค์ผ, ๋ณ์ , ์ ๋ชฉ์ ๊ฐ๋๋ค.", () => {
+ cy.get(".item-card").each(($el) => {
+ cy.wrap($el).within(() => {
+ cy.get(".item-thumbnail").should("be.visible");
+ cy.get(".item-title").should("be.visible");
+ cy.get(".item-score").should("be.visible");
+ });
+ });
+ });
+
+ it("์ํ ๋ชฉ๋ก์ ํ ํ์ด์ง์ 20๊ฐ์ฉ ๋์จ๋ค.", () => {
+ cy.get(".item-list li").should("have.length", 20);
+ });
+
+ it("๋๋ณด๊ธฐ ๋ฒํผ์ ๋๋ฅด๋ฉด 20๊ฐ์ ์ํ๊ฐ ์ถ๊ฐ๋ก ์์ฑ๋๋ค.", () => {
+ cy.get(".show-more").click();
+ cy.get(".item-list li").should("have.length", 40);
+ });
+
+ it("์ํ ๋ชฉ๋ก์ ๋ถ๋ฌ์ค๋ ๋์ ์ค์ผ๋ ํค UI๋ฅผ ๋ณด์ฌ์ค๋ค.", () => {
+ cy.get(".skeleton-card").should("have.length", 20);
+ cy.wait(1000);
+ cy.get(".skeleton-card").should("have.length", 0);
+ });
+}); | JavaScript | ๋ค ๋ง์ต๋๋ค! ์ด์ ํ
์คํธ์์ 20๊ฐ๊ฐ ๋ ๋๋ง์ด ๋์๊ณ ๋ฒํผ์ ํด๋ฆญํ ํ์, 20๊ฐ๊ฐ ๋ ์ถ๊ฐ๋์ด 40๊ฐ๋ฅผ ๊ฒ์ฌํ๊ฒ ํ์์ต๋๋ค.
์๋กญ๊ฒ ๋ ๋๋ง๋ 20๊ฐ์ ๋ํด์ ํ
์คํธ๋ฅผ ์งํํ๋ ๊ฒ์ด ๋ ์ฌ๋ฐ๋ฅธ ๊ฒ์ฌ์ผ๊น์?
+) ์ถ๊ฐ๋ก, ๋จ์ํ
์คํธ์์๋ ์ํ ๊ฐ์ ํตํด ๋์ถ๋๋ ๊ฐ์ ๊ฒ์ฌํ๋ ๊ณผ์ ์ด ํ
์คํธ์ ํต์ฌ์ด์๋ค๊ณ ์๊ฐ๋๋๋ฐ,
์ด๋ฒ์ e2e์์๋ ๊ฐ์ ์ด์ฉํ์ฌ ๊ฒ์ฌํ๋ ๋ฐฉํฅ๋ณด๋ค ๋ ๋๋ง๋๋ ์์์ ๊ฐ์๋ ์์ฑ ์ฌ๋ถ๋ฅผ ์ค์ฌ์ ์ผ๋ก ์ฝ๋๋ฅผ ์์ฑํ ๊ฒ ๊ฐ์ต๋๋ค.
๊ทธ๋ฐ ๊ณผ์ ์์ ๋จ์ ํ
์คํธ๋ ๊ฐ ์ค์ฌ, e2e๋ ์ ์ฒด์ ์ธ DOM ๋ ๋๋ง ์ค์ฌ ์ด๋ ๊ฒ ์์ฐ์ค๋ ์๊ฐ์ด ์ด์ด์ง๊ฒ ๋์๋๋ฐ ์ด๊ฒ ๋ง๋ ์๊ฐ์ผ๊น ์๊ตฌ์ฌ์ด ๋ค๊ธด ํฉ๋๋ค,,! |
@@ -1,11 +1,29 @@
import { useState } from "react";
+import Header from "./components/Header/Header";
+import Product from "./pages/Product";
+import GlobalStyles from "./styles/Global.style";
+import Toast from "./components/common/Toast/Toast";
+import { QuantityContext } from "./store/QuantityContext";
+import { createPortal } from "react-dom";
function App() {
- const [count, setCount] = useState(0);
-
+ const [quantity, setQuantity] = useState(0);
+ const [showToast, setShowToast] = useState(false);
+ const [toastMessage, setToastMessage] = useState("");
+ const handleError = (message: string) => {
+ setToastMessage(message);
+ setShowToast(true);
+ setTimeout(() => setShowToast(false), 3000);
+ };
return (
<>
- <h1>React Shopping Products</h1>
+ <GlobalStyles />
+ {showToast &&
+ createPortal(<Toast message={toastMessage} />, document.body)}
+ <QuantityContext.Provider value={{ quantity, setQuantity }}>
+ <Header />
+ <Product onError={handleError} />
+ </QuantityContext.Provider>
</>
);
} | Unknown | ์ฌ๊ธฐ ์ด `showToast` ์ํ๋ฅผ ํ ์คํธ ์ปดํฌ๋ํธ๊ฐ ์ฑ
์์ ๊ฐ์ง ์ ์์ง ์์๊น ์ถ์๋๋ฐ, ๊ทธ๋ ๋ค๋ฉด createPortal์ ์ฌ์ฉํ ์ ์๊ฒ ๋๋์..? createPortal์ ์ฌ์ฉํด๋ณด์ง ์์์ ์ ๋ชจ๋ฅด๊ฒ ์ง๋ง, ๋ฏธ๋ฆฌ ์ด์ด๋ ์ ์๋ค๋ฉด ๊ทธ์ชฝ์ผ๋ก ์ํ๋ฅผ ์ฎ๊ฒจ๋ด๋ ์ข์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,52 @@
+import { generateBasicToken } from "../util/auth";
+import { CART_ITEMS_ENDPOINT } from "./config";
+
+const USER_PASSWORD = import.meta.env.VITE_USER_PASSWORD;
+const USER_ID = import.meta.env.VITE_USER_ID;
+const token = generateBasicToken(USER_ID, USER_PASSWORD);
+
+export async function requestFetchCartItemList() {
+ const response = await fetch(`${CART_ITEMS_ENDPOINT}?size=2000`, {
+ method: "GET",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: token,
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to fetch cart item list");
+ }
+
+ const data = await response.json();
+ return data;
+}
+
+export async function requestAddCartItem(productId: number, quantity: number) {
+ const response = await fetch(`${CART_ITEMS_ENDPOINT}`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: token,
+ },
+ body: JSON.stringify({ productId, quantity }),
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to add cart item");
+ }
+}
+
+export async function requestDeleteCartItem(cartItemId: number | undefined) {
+ const response = await fetch(`${CART_ITEMS_ENDPOINT}/${cartItemId}`, {
+ method: "DELETE",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: token,
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to delete cart item");
+ }
+} | TypeScript | ํ์๋ ์๋์ง๋ง ๋ฐ๋ณต๋๋ fetch ๋ก์ง๋ค์ ์ถ์ํํด๋ณด์
๋ ์ข์ ๊ฒ ๊ฐ์์!ใ
ใ
|
@@ -0,0 +1,52 @@
+import { generateBasicToken } from "../util/auth";
+import { CART_ITEMS_ENDPOINT } from "./config";
+
+const USER_PASSWORD = import.meta.env.VITE_USER_PASSWORD;
+const USER_ID = import.meta.env.VITE_USER_ID;
+const token = generateBasicToken(USER_ID, USER_PASSWORD);
+
+export async function requestFetchCartItemList() {
+ const response = await fetch(`${CART_ITEMS_ENDPOINT}?size=2000`, {
+ method: "GET",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: token,
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to fetch cart item list");
+ }
+
+ const data = await response.json();
+ return data;
+}
+
+export async function requestAddCartItem(productId: number, quantity: number) {
+ const response = await fetch(`${CART_ITEMS_ENDPOINT}`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: token,
+ },
+ body: JSON.stringify({ productId, quantity }),
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to add cart item");
+ }
+}
+
+export async function requestDeleteCartItem(cartItemId: number | undefined) {
+ const response = await fetch(`${CART_ITEMS_ENDPOINT}/${cartItemId}`, {
+ method: "DELETE",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: token,
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error("Failed to delete cart item");
+ }
+} | TypeScript | chat GPTํํ
'์ด ์ฝ๋ ์ถ์ํ ํด๋ด'ํ๋ฉด ๊ธฐ๊ฐ๋งํ๊ฒ ํด์ฃผ๋๋ผ๊ตฌ์ |
@@ -0,0 +1,10 @@
+import { generateBasicToken } from "../util/auth";
+
+const API_URL = import.meta.env.VITE_API_URL;
+
+export const PRODUCTS_ENDPOINT = `${API_URL}/products`;
+export const CART_ITEMS_ENDPOINT = `${API_URL}/cart-items`;
+
+export const USER_PASSWORD = import.meta.env.VITE_USER_PASSWORD;
+export const USER_ID = import.meta.env.VITE_USER_ID;
+export const token = generateBasicToken(USER_ID, USER_PASSWORD); | TypeScript | api์์ฒญ์ ํ์ํ ๋ณ์๋ค์ด ์ ๋ชจ์ฌ์์ด ๊ด๋ฆฌํ๊ธฐ ํธํ ๊ฒ ๊ฐ๋ค์! ๐ |
@@ -0,0 +1,87 @@
+import { useContext, useEffect, useRef } from "react";
+import { QuantityContext } from "../../store/QuantityContext";
+import useProductList from "../../hooks/useProductList";
+import useCartItemList from "../../hooks/useCartItemList";
+import ProductItem from "../ProductItem/ProductItem";
+import * as S from "./ProductItemList.style";
+import { Category } from "../../interfaces/Product";
+import { Sorting } from "../../interfaces/Sorting";
+import useIntersectionObserver from "../../hooks/useIntersectionObserver";
+import Spinner from "../common/Spinner/Spinner";
+
+interface ProductItemListProp {
+ category: Category;
+ sortOption: Sorting;
+ onError: (error: string) => void;
+}
+
+function ProductItemList({
+ category,
+ sortOption,
+ onError,
+}: ProductItemListProp) {
+ const {
+ productList,
+ productListError,
+ productListLoading,
+ page,
+ fetchNextPage,
+ isLastPage,
+ setPage,
+ } = useProductList({
+ category,
+ sortOption,
+ });
+ const { cartItemList, isInCart, toggleCartItem, cartItemListError } =
+ useCartItemList();
+ const target = useRef(null);
+ const [observe, unobserve] = useIntersectionObserver(() => {
+ fetchNextPage();
+ });
+
+ useEffect(() => {
+ setPage(0);
+ }, [category, sortOption]);
+
+ useEffect(() => {
+ if (page === -1 || target.current === null) return;
+ observe(target.current);
+
+ const N = productList.length;
+
+ if (0 === N || isLastPage) {
+ unobserve(target.current);
+ }
+ }, [productList, page, observe, unobserve]);
+ const quantityContext = useContext(QuantityContext);
+ const setQuantity = quantityContext ? quantityContext.setQuantity : () => {};
+ setQuantity(cartItemList.length);
+
+ if (productListError) {
+ onError("์ํ ๋ชฉ๋ก ์กฐํ ์คํจ");
+ }
+ if (cartItemListError) {
+ onError("์ฅ๋ฐ๊ตฌ๋ ๋ชฉ๋ก ์กฐํ ์คํจ");
+ }
+
+ return (
+ <>
+ <S.ProductList>
+ {productList.map((product, idx) => {
+ return (
+ <ProductItem
+ key={`${idx}_${product.id}`}
+ product={product}
+ isInCart={isInCart(product.id)}
+ toggleCartItem={() => toggleCartItem(product)}
+ />
+ );
+ })}
+ </S.ProductList>
+ <div ref={target} style={{ height: "1px" }}></div>
+ {productListLoading && <Spinner />}
+ </>
+ );
+}
+
+export default ProductItemList; | Unknown | ํ์ด์ง๋ค์ด์
๊ด๋ จ ๋ก์ง๋ ์ปค์คํ
ํ
์ผ๋ก ๋ถ๋ฆฌํ๋ฉด ์ข์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,87 @@
+import { useContext, useEffect, useRef } from "react";
+import { QuantityContext } from "../../store/QuantityContext";
+import useProductList from "../../hooks/useProductList";
+import useCartItemList from "../../hooks/useCartItemList";
+import ProductItem from "../ProductItem/ProductItem";
+import * as S from "./ProductItemList.style";
+import { Category } from "../../interfaces/Product";
+import { Sorting } from "../../interfaces/Sorting";
+import useIntersectionObserver from "../../hooks/useIntersectionObserver";
+import Spinner from "../common/Spinner/Spinner";
+
+interface ProductItemListProp {
+ category: Category;
+ sortOption: Sorting;
+ onError: (error: string) => void;
+}
+
+function ProductItemList({
+ category,
+ sortOption,
+ onError,
+}: ProductItemListProp) {
+ const {
+ productList,
+ productListError,
+ productListLoading,
+ page,
+ fetchNextPage,
+ isLastPage,
+ setPage,
+ } = useProductList({
+ category,
+ sortOption,
+ });
+ const { cartItemList, isInCart, toggleCartItem, cartItemListError } =
+ useCartItemList();
+ const target = useRef(null);
+ const [observe, unobserve] = useIntersectionObserver(() => {
+ fetchNextPage();
+ });
+
+ useEffect(() => {
+ setPage(0);
+ }, [category, sortOption]);
+
+ useEffect(() => {
+ if (page === -1 || target.current === null) return;
+ observe(target.current);
+
+ const N = productList.length;
+
+ if (0 === N || isLastPage) {
+ unobserve(target.current);
+ }
+ }, [productList, page, observe, unobserve]);
+ const quantityContext = useContext(QuantityContext);
+ const setQuantity = quantityContext ? quantityContext.setQuantity : () => {};
+ setQuantity(cartItemList.length);
+
+ if (productListError) {
+ onError("์ํ ๋ชฉ๋ก ์กฐํ ์คํจ");
+ }
+ if (cartItemListError) {
+ onError("์ฅ๋ฐ๊ตฌ๋ ๋ชฉ๋ก ์กฐํ ์คํจ");
+ }
+
+ return (
+ <>
+ <S.ProductList>
+ {productList.map((product, idx) => {
+ return (
+ <ProductItem
+ key={`${idx}_${product.id}`}
+ product={product}
+ isInCart={isInCart(product.id)}
+ toggleCartItem={() => toggleCartItem(product)}
+ />
+ );
+ })}
+ </S.ProductList>
+ <div ref={target} style={{ height: "1px" }}></div>
+ {productListLoading && <Spinner />}
+ </>
+ );
+}
+
+export default ProductItemList; | Unknown | ์๋ฌด๋๋ ์ด๋ฒ ๋ฏธ์
์์ ๊ฐ์ฅ ๋ฉ์ธ์ด ๋๋(?) ์ปดํฌ๋ํธ์ธ ๊ฒ ๊ฐ์์. ๋น์ฆ๋์ค ๋ก์ง๊ณผ UI ๋ก์ง์ด ์ข ๋ ์ ๋ถ๋ฆฌ๋๋ฉด ๋์ฑ ์ฝ๊ธฐ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,13 @@
+package msa.customer.exception;
+
+public class DeliveryCustomerException extends RuntimeException {
+
+ public DeliveryCustomerException(String message) {
+ super(message);
+ }
+
+ public DeliveryCustomerException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+} | Java | (C) Exception์ ์๋น์ค์ `์ ์ฑ
์๋ฐ`์ ๋ํ๋ด๋ documentation์ ์ญํ ์ ํ๊ธฐ๋ ํฉ๋๋ค.
๋ฐ๋ผ์ Exception์ ํตํด ์๋น์ค ์ ์ฑ
์ ์๋ฐํ๋ ๊ฒฝ์ฐ, ์ ์ฑ
์ ๋ช
ํํ๊ฒ ๋ํ๋ผ ์ ์๋ ์์ฒด exception์ ์ ์ํ๊ณค ํ๋๋ฐ delivery application์ ์ ์ฉํด๋ณผ๋งํ exception ๋ช ๊ฐ๋ฅผ ๊ฐ๋ตํ๊ฒ ๊ตฌ์ฑํด๋ดค์ผ๋ ์ฐธ๊ณ ํด๋ณด์๊ณ Exception๋ค์ ์ ์ ์ํด์ฃผ์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค :) |
@@ -3,6 +3,7 @@
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import msa.customer.entity.store.Store;
+import msa.customer.exception.store.StoreEmptyException;
import msa.customer.service.store.StoreService;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
@@ -11,6 +12,7 @@
import java.util.Optional;
public class StoreCheckInterceptor implements HandlerInterceptor {
+
private final StoreService storeService;
public StoreCheckInterceptor(StoreService storeService) {
@@ -19,13 +21,14 @@ public StoreCheckInterceptor(StoreService storeService) {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
- String storeId = (String) pathVariables.get("storeId");
+ Map pathVariables = (Map)request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
+ String storeId = (String)pathVariables.get("storeId");
Optional<Store> storeOptional = storeService.getStore(storeId);
- if(storeOptional.isEmpty()){
- throw new NullPointerException("Store doesn't exist. " + storeId + " is not correct store id.");
+ if (storeOptional.isEmpty()) {
+ throw new StoreEmptyException(storeId);
}
request.setAttribute("storeEntity", storeOptional.get());
return true;
}
+
} | Java | (C) optional์ ๋ฒ๊ฒจ์ง ์ํ๋ก ์ค๋๊ฒ ์ข๊ฒ ์ง๋ง, ์ผ๋จ ํ์ฌ ์ํ๋ฅผ ๊ฐ์ ํ๊ณ custom exception์ throw ํ์ต๋๋ค |
@@ -6,6 +6,7 @@
import msa.restaurant.dto.store.StoreResponseDto;
import msa.restaurant.entity.store.Store;
import msa.restaurant.dto.store.StoreSqsDto;
+import msa.restaurant.exception.store.StoreCreationFailedException;
import msa.restaurant.service.member.MemberService;
import msa.restaurant.sqs.SendingMessageConverter;
import msa.restaurant.service.store.StoreService;
@@ -26,16 +27,19 @@ public class StoreController {
private final SendingMessageConverter sendingMessageConverter;
private final SqsService sqsService;
- public StoreController(StoreService storeService, SendingMessageConverter sendingMessageConverter, MemberService memberService, SqsService sqsService) {
+ public StoreController(StoreService storeService,
+ SendingMessageConverter sendingMessageConverter,
+ MemberService memberService,
+ SqsService sqsService) {
this.storeService = storeService;
this.sendingMessageConverter = sendingMessageConverter;
this.sqsService = sqsService;
}
@GetMapping
@ResponseStatus(HttpStatus.OK)
- public List<StorePartResponseDto> storeList (
- @RequestAttribute("cognitoUsername") String managerId) {
+ public List<StorePartResponseDto> storeList(
+ @RequestAttribute("cognitoUsername") String managerId) {
List<Store> storeList = storeService.getStoreList(managerId);
List<StorePartResponseDto> storeListDto = new ArrayList<>();
storeList.forEach(store -> {
@@ -46,12 +50,12 @@ public List<StorePartResponseDto> storeList (
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
- public void createStore (@RequestAttribute("cognitoUsername") String managerId,
- @RequestBody StoreRequestDto data) {
+ public void createStore(@RequestAttribute("cognitoUsername") String managerId,
+ @RequestBody StoreRequestDto data) {
String storeId = storeService.createStore(data, managerId);
Optional<Store> storeOptional = storeService.getStore(storeId);
- if (storeOptional.isEmpty()){
- throw new RuntimeException("Store creation failed.");
+ if (storeOptional.isEmpty()) {
+ throw new StoreCreationFailedException(storeId);
}
Store store = storeOptional.get();
StoreSqsDto storeSqsDto = new StoreSqsDto(store);
@@ -62,16 +66,16 @@ public void createStore (@RequestAttribute("cognitoUsername") String managerId,
@GetMapping("/{storeId}")
@ResponseStatus(HttpStatus.OK)
- public StoreResponseDto storeInfo (@RequestAttribute("cognitoUsername") String managerId,
- @RequestAttribute("store") Store store) {
+ public StoreResponseDto storeInfo(@RequestAttribute("cognitoUsername") String managerId,
+ @RequestAttribute("store") Store store) {
return new StoreResponseDto(store);
}
@PutMapping("/{storeId}")
@ResponseStatus(HttpStatus.OK)
public void updateStore(@RequestAttribute("cognitoUsername") String managerId,
@PathVariable String storeId,
- @RequestBody StoreRequestDto data) {
+ @RequestBody StoreRequestDto data) {
storeService.updateStore(storeId, data);
Optional<Store> storeOptional = storeService.getStore(storeId);
Store store = storeOptional.get();
@@ -85,9 +89,9 @@ public void updateStore(@RequestAttribute("cognitoUsername") String managerId,
@ResponseStatus(HttpStatus.CREATED)
public void changeStoreStatus(@RequestAttribute("cognitoUsername") String managerId,
@PathVariable String storeId,
- @RequestBody boolean open){
+ @RequestBody boolean open) {
String messageToChangeStatus;
- if (open){
+ if (open) {
storeService.openStore(storeId);
messageToChangeStatus = sendingMessageConverter.createMessageToOpenStore(storeId);
} else {
@@ -101,11 +105,12 @@ public void changeStoreStatus(@RequestAttribute("cognitoUsername") String manage
@DeleteMapping("/{storeId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteStore(@RequestAttribute("cognitoUsername") String managerId,
- @PathVariable String storeId) {
+ @PathVariable String storeId) {
storeService.deleteStore(storeId);
String messageToDeleteStore = sendingMessageConverter.createMessageToDeleteStore(storeId);
sqsService.sendToCustomer(messageToDeleteStore);
sqsService.sendToRider(messageToDeleteStore);
}
+
}
| Java | (C) ์ฌ๊ธฐ๋ StoreCreationFailedException์ ๋์ง์ง๋ง, storeService.createStore ๋ด๋ถ์์ exception ์ฒ๋ฆฌ๋ฅผ ํ๊ณ ๋์ค๋ ๊ฒ์ด ๋ ๋ฐ๋์งํด๋ณด์
๋๋ค. |
@@ -18,39 +18,30 @@ public OrderService(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
- public void createOrder(Order order){
+ public void createOrder(Order order) {
orderRepository.createOrder(order);
}
- public List<Order> getOrderList(String storeId){
+ public List<Order> getOrderList(String storeId) {
return orderRepository.readOrderList(storeId);
}
- public Optional<Order> getOrder(String orderId){
+ public Optional<Order> getOrder(String orderId) {
return orderRepository.readOrder(orderId);
}
- public OrderStatus changeOrderStatusToOrderAccept(String orderId, OrderStatus orderStatus){
- if(orderStatus.equals(OrderStatus.ORDER_REQUEST)){
- return orderRepository.updateOrderStatus(orderId, OrderStatus.ORDER_ACCEPT);
- } else {
- throw new IllegalStateException("The current order status is not changeable");
- }
- }
+ public OrderStatus changeOrderStatus(Order order, OrderStatus status, OrderStatusUpdatePolicy orderStatusUpdatePolicy) {
+ orderStatusUpdatePolicy.checkStatusUpdatable(status);
- public OrderStatus changeOrderStatusToFoodReady(String orderId, OrderStatus orderStatus){
- if (orderStatus.equals(OrderStatus.RIDER_ASSIGNED)) {
- return orderRepository.updateOrderStatus(orderId, OrderStatus.FOOD_READY);
- } else {
- throw new IllegalStateException("The current order status is not changeable");
- }
+ return orderRepository.updateOrderStatus(order.getOrderId(), status);
}
- public void assignRiderToOrder(String orderId, OrderStatus orderStatus, RiderPartDto riderPartDto){
+ public void assignRiderToOrder(String orderId, OrderStatus orderStatus, RiderPartDto riderPartDto) {
orderRepository.updateRiderInfo(orderId, orderStatus, riderPartDto);
}
- public void changeOrderStatusFromOtherServer(String orderId, OrderStatus orderStatus){
+ public void changeOrderStatusFromOtherServer(String orderId, OrderStatus orderStatus) {
orderRepository.updateOrderStatus(orderId, orderStatus);
}
+
} | Java | (C) changeOrderStatusTo~ ๋ฉ์๋์ ๋ด์ฉ์ด ๋๋ถ๋ถ ์ค๋ณต๋์ด์, ํด๋น ๋ฉ์๋๋ค์ changeOrderStatus๋ผ๋ ๋ฉ์๋๋ก ํตํฉํ์์ต๋๋ค.
์ฌ๊ธฐ์ ์๋ก์ด ํด๋์ค์ธ OrderStatusUpdatePolicy๊ฐ ๋ง๋ค์ด์ก๋๋ฐ, ~Policy๋ผ๋ ๋ช
์นญ์ ์๋น์ค ์ ์ฑ
์ ํํํ๊ธฐ ์ํด ๋ฒ์ฉ์ ์ผ๋ก ์ฌ์ฉํ๋ ํด๋์ค ๋ค์ด๋ฐ ์ค ํ๋์
๋๋ค.
delivery-application์๋ ์๋น์ค ์ด์์ ํ์ํ ์ฌ๋ฌ๊ฐ์ง ์ ์ฑ
๋ค์ ๊ฐ๊ณ ์์ํ
๋ฐ์, ์ด๋ฐ ์ ์ฑ
๋ค์ ํด๋์ค๋ก ๋๋ฌ๋ด์ง ์๊ณ ๋ฉ์๋๋ ๋ก์ง์ผ๋ก๋ง ๋ํ๋ด๋ฉด ์ ์ฑ
๋ค์ด ๋ถ์ฐ๋๊ณ , ์์์ ์ผ๋ก ํํ๋์ด์ ์ฐ๋ฆฌ ์๋น์ค๊ฐ ์ด๋ค ์ ์ฑ
๋ค์ ๊ฐ๊ณ ์๋์ง ๋ช
ํํ ํ์
ํ๊ธฐ ์ด๋ ต์ต๋๋ค. (์ด๋ ๊ฒ ๋๋ฉด ์๊ฐ์ด ์ง๋๋ฉด์ ์ฝ๋๊ฐ ์๋น์ค ์ ์ฑ
์ ๋ฐ๋ผ๊ฐ์ง ๋ชปํ๋ ์ํฉ๋ ์ข
์ข
์๊น๋๋ค)
DDD๋ฅผ ์์ง ์ฝ์ด๋ณด์ ์ง๋ ๋ชจ๋ฅด๊ฒ ์ง๋ง, [์์์ ์ธ ๊ฐ๋
์ ๋ช
ํํ๊ฒ](https://dhsim86.github.io/programming/2019/05/16/domain_driven_design_09-post.html)๋ผ๋ chapter๊ฐ ์๋๋ฐ ์๊ฐ๋์ค ๋ ๋งํฌ ํ๋ฒ ์ฝ์ด๋ณด์๊ณ , ํ์ฌ ์ฐ๋ฆฌ ์๋น์ค์ ์ฌ๊ธฐ์ ๊ธฐ ์จ์ด์๋ ์ ์ฑ
๋ค์ ์ด๋ค ๊ฒ๋ค์ด ์์์ง ์ฐพ์๋ณด์
์ ๋ช
ํํ๊ฒ ํด๋์ค๋ก ๋ํ๋ด๋ณด์ ๋ค๋ฉด ๋ง์ ๋์์ด ๋์ค ๊ฒ ๊ฐ์ต๋๋ค :) |
@@ -0,0 +1,13 @@
+package msa.customer.exception;
+
+public class DeliveryCustomerException extends RuntimeException {
+
+ public DeliveryCustomerException(String message) {
+ super(message);
+ }
+
+ public DeliveryCustomerException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+} | Java | ์ฐธ๊ณ ํ๊ฒ ์ต๋๋ค. |
@@ -0,0 +1,152 @@
+package nextstep.subway.acceptance;
+
+import static nextstep.subway.acceptance.FavoritesSteps.์ฆ๊ฒจ์ฐพ๊ธฐ_๊ถํ์ด_์์;
+import static nextstep.subway.acceptance.FavoritesSteps.์ฆ๊ฒจ์ฐพ๊ธฐ_๋ชฉ๋ก_์กฐํ_์์ฒญ;
+import static nextstep.subway.acceptance.FavoritesSteps.์ฆ๊ฒจ์ฐพ๊ธฐ_์ญ์ _์์ฒญ;
+import static nextstep.subway.acceptance.FavoritesSteps.์ฆ๊ฒจ์ฐพ๊ธฐ_์ญ์ ๋จ;
+import static nextstep.subway.acceptance.FavoritesSteps.์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์์ฒญ;
+import static nextstep.subway.acceptance.FavoritesSteps.์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ๋จ;
+import static nextstep.subway.acceptance.FavoritesSteps.์ฆ๊ฒจ์ฐพ๊ธฐ_์ ๋ณด_์กฐํ๋จ;
+import static nextstep.subway.acceptance.LineSteps.์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ _๊ตฌ๊ฐ_์์ฑ_์์ฒญ;
+import static nextstep.subway.acceptance.MemberSteps.๋ก๊ทธ์ธ_๋์ด_์์;
+import static nextstep.subway.acceptance.MemberSteps.ํ์_์์ฑ_์์ฒญ;
+import static nextstep.subway.acceptance.StationSteps.์งํ์ฒ ์ญ_์์ฑ_์์ฒญ;
+
+import io.restassured.response.ExtractableResponse;
+import io.restassured.response.Response;
+import java.util.HashMap;
+import java.util.Map;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+@DisplayName("์ฆ๊ฒจ์ฐพ๊ธฐ ๊ธฐ๋ฅ")
+public class FavoritesAcceptanceTest extends AcceptanceTest {
+
+ public static final String EMAIL = "email@email.com";
+ public static final String PASSWORD = "password";
+ public static final int AGE = 20;
+
+ private Long ๊ต๋์ญ;
+ private Long ๊ฐ๋จ์ญ;
+ private Long ์์ฌ์ญ;
+ private Long ๋จ๋ถํฐ๋ฏธ๋์ญ;
+ private Long ์ดํธ์ ;
+ private Long ์ ๋ถ๋น์ ;
+ private Long ์ผํธ์ ;
+ private String ๋ก๊ทธ์ธํ ํฐ;
+
+
+ /**
+ * ๊ต๋์ญ --- *2ํธ์ * --- ๊ฐ๋จ์ญ | | *3ํธ์ * *์ ๋ถ๋น์ * |
+ * | ๋จ๋ถํฐ๋ฏธ๋์ญ --- *3ํธ์ * --- ์์ฌ
+ */
+ @BeforeEach
+ public void setUp() {
+ super.setUp();
+
+ ๊ต๋์ญ = ์งํ์ฒ ์ญ_์์ฑ_์์ฒญ("๊ต๋์ญ").jsonPath().getLong("id");
+ ๊ฐ๋จ์ญ = ์งํ์ฒ ์ญ_์์ฑ_์์ฒญ("๊ฐ๋จ์ญ").jsonPath().getLong("id");
+ ์์ฌ์ญ = ์งํ์ฒ ์ญ_์์ฑ_์์ฒญ("์์ฌ์ญ").jsonPath().getLong("id");
+ ๋จ๋ถํฐ๋ฏธ๋์ญ = ์งํ์ฒ ์ญ_์์ฑ_์์ฒญ("๋จ๋ถํฐ๋ฏธ๋์ญ").jsonPath().getLong("id");
+
+ ์ดํธ์ = ์งํ์ฒ _๋
ธ์ _์์ฑ_์์ฒญ("2ํธ์ ", "green", ๊ต๋์ญ, ๊ฐ๋จ์ญ, 10);
+ ์ ๋ถ๋น์ = ์งํ์ฒ _๋
ธ์ _์์ฑ_์์ฒญ("์ ๋ถ๋น์ ", "red", ๊ฐ๋จ์ญ, ์์ฌ์ญ, 10);
+ ์ผํธ์ = ์งํ์ฒ _๋
ธ์ _์์ฑ_์์ฒญ("3ํธ์ ", "orange", ๊ต๋์ญ, ๋จ๋ถํฐ๋ฏธ๋์ญ, 2);
+
+ ์งํ์ฒ _๋
ธ์ ์_์งํ์ฒ _๊ตฌ๊ฐ_์์ฑ_์์ฒญ(์ผํธ์ , createSectionCreateParams(๋จ๋ถํฐ๋ฏธ๋์ญ, ์์ฌ์ญ, 3));
+
+ ํ์_์์ฑ_์์ฒญ(EMAIL, PASSWORD, AGE);
+ ๋ก๊ทธ์ธํ ํฐ = ๋ก๊ทธ์ธ_๋์ด_์์(EMAIL, PASSWORD);
+ }
+
+ @DisplayName("์ฆ๊ฒจ์ฐพ๊ธฐ ์ถ๊ฐ ํ๊ธฐ")
+ @Test
+ public void addFavorite() {
+ // when
+ ExtractableResponse<Response> response = ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์์ฒญ(๋ก๊ทธ์ธํ ํฐ, ๊ฐ๋จ์ญ, ์์ฌ์ญ);
+
+ // then
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ๋จ(response);
+ }
+
+ @DisplayName("์ฆ๊ฒจ์ฐพ๊ธฐ ์กฐํ ํ๊ธฐ")
+ @Test
+ public void getFavorites() {
+ // given
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์์ฒญ(๋ก๊ทธ์ธํ ํฐ, ๊ฐ๋จ์ญ, ์์ฌ์ญ);
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์์ฒญ(๋ก๊ทธ์ธํ ํฐ, ์์ฌ์ญ, ๊ต๋์ญ);
+
+ // when
+ ExtractableResponse<Response> response = ์ฆ๊ฒจ์ฐพ๊ธฐ_๋ชฉ๋ก_์กฐํ_์์ฒญ(๋ก๊ทธ์ธํ ํฐ);
+
+ // then
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_์ ๋ณด_์กฐํ๋จ(response, new Long[]{๊ฐ๋จ์ญ, ์์ฌ์ญ}, new Long[]{์์ฌ์ญ, ๊ต๋์ญ});
+ }
+
+ @DisplayName("์ฆ๊ฒจ์ฐพ๊ธฐ ์ญ์ ํ๊ธฐ")
+ @Test
+ public void deleteFavorites() {
+ // given
+ ExtractableResponse<Response> createResponse = ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์์ฒญ(๋ก๊ทธ์ธํ ํฐ, ๊ฐ๋จ์ญ, ์์ฌ์ญ);
+
+ // when
+ ExtractableResponse<Response> response = ์ฆ๊ฒจ์ฐพ๊ธฐ_์ญ์ _์์ฒญ(๋ก๊ทธ์ธํ ํฐ, createResponse);
+
+ // then
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_์ญ์ ๋จ(response);
+ }
+
+ @DisplayName("์ฆ๊ฒจ์ฐพ๊ธฐ ์ถ๊ฐ ํ๊ธฐ - ์ ํจํ์ง ์์ ํ ํฐ ์ผ ๊ฒฝ์ฐ")
+ @Test
+ public void addFavoriteWithInvalidToken() {
+ // when
+ ExtractableResponse<Response> response = ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์์ฒญ("invalid_token", ๊ฐ๋จ์ญ, ์์ฌ์ญ);
+
+ // then
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_๊ถํ์ด_์์(response);
+ }
+
+ @DisplayName("์ฆ๊ฒจ์ฐพ๊ธฐ ๋ชฉ๋ก์ ๊ด๋ฆฌํ๋ค.")
+ @Test
+ public void manageFavorites() {
+ // when ์ฆ๊ฒจ์ฐพ๊ธฐ ์์ฑ์ ์์ฒญ
+ ExtractableResponse<Response> ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์๋ต = ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์์ฒญ(๋ก๊ทธ์ธํ ํฐ, ๊ฐ๋จ์ญ, ์์ฌ์ญ);
+ // then ์ฆ๊ฒจ์ฐพ๊ธฐ ์์ฑ๋จ
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ๋จ(์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์๋ต);
+
+ // when ์ฆ๊ฒจ์ฐพ๊ธฐ ๋ชฉ๋ก ์กฐํ ์์ฒญ
+ ExtractableResponse<Response> ์ฆ๊ฒจ์ฐพ๊ธฐ_๋ชฉ๋ก_์กฐํ_์๋ต = ์ฆ๊ฒจ์ฐพ๊ธฐ_๋ชฉ๋ก_์กฐํ_์์ฒญ(๋ก๊ทธ์ธํ ํฐ);
+ // then ์ฆ๊ฒจ์ฐพ๊ธฐ ๋ชฉ๋ก ์กฐํ๋จ
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_์ ๋ณด_์กฐํ๋จ(์ฆ๊ฒจ์ฐพ๊ธฐ_๋ชฉ๋ก_์กฐํ_์๋ต, new Long[]{ ๊ฐ๋จ์ญ }, new Long[]{ ์์ฌ์ญ });
+
+ // when ์ฆ๊ฒจ์ฐพ๊ธฐ ์ญ์ ์์ฒญ
+ ExtractableResponse<Response> ์ฆ๊ฒจ์ฐพ๊ธฐ_์ญ์ _์๋ต = ์ฆ๊ฒจ์ฐพ๊ธฐ_์ญ์ _์์ฒญ(๋ก๊ทธ์ธํ ํฐ, ์ฆ๊ฒจ์ฐพ๊ธฐ_์์ฑ_์๋ต);
+ // then ์ฆ๊ฒจ์ฐพ๊ธฐ ์ญ์ ๋จ
+ ์ฆ๊ฒจ์ฐพ๊ธฐ_์ญ์ ๋จ(์ฆ๊ฒจ์ฐพ๊ธฐ_์ญ์ _์๋ต);
+ }
+
+
+ private Long ์งํ์ฒ _๋
ธ์ _์์ฑ_์์ฒญ(String name, String color, Long upStation, Long downStation,
+ int distance) {
+ Map<String, String> lineCreateParams;
+ lineCreateParams = new HashMap<>();
+ lineCreateParams.put("name", name);
+ lineCreateParams.put("color", color);
+ lineCreateParams.put("upStationId", upStation + "");
+ lineCreateParams.put("downStationId", downStation + "");
+ lineCreateParams.put("distance", distance + "");
+
+ return LineSteps.์งํ์ฒ _๋
ธ์ _์์ฑ_์์ฒญ(lineCreateParams).jsonPath().getLong("id");
+ }
+
+ private Map<String, String> createSectionCreateParams(Long upStationId, Long downStationId,
+ int distance) {
+ Map<String, String> params = new HashMap<>();
+ params.put("upStationId", upStationId + "");
+ params.put("downStationId", downStationId + "");
+ params.put("distance", distance + "");
+ return params;
+ }
+
+} | Java | `์ฆ๊ฒจ์ฐพ๊ธฐ ๋ชฉ๋ก์ ๊ด๋ฆฌํ๋ค` ์์ ์๋๋ฆฌ์ค ํ์์ผ๋ก ์ ์์ฑํด์ฃผ์
์
ํด๋น ํ
์คํธ๋ค์ ์์ฑํด์ฃผ์ง ์์๋ ๊ด์ฐฎ์ ๊ฒ ๊ฐ์์ ๐ |
@@ -0,0 +1,50 @@
+package nextstep.subway.applicaion;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import nextstep.member.application.MemberService;
+import nextstep.member.domain.LoginMember;
+import nextstep.member.domain.MemberRepository;
+import nextstep.subway.applicaion.dto.FavoriteRequest;
+import nextstep.subway.applicaion.dto.FavoriteResponse;
+import nextstep.subway.domain.Favorite;
+import nextstep.subway.domain.FavoriteRepository;
+import nextstep.subway.domain.Station;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+public class FavoriteService {
+ private final StationService stationService;
+ private final PathService pathService;
+ private final MemberRepository memberRepository;
+ private final FavoriteRepository favoriteRepository;
+
+ public FavoriteService(StationService stationService, PathService pathService,
+ MemberRepository memberRepository, FavoriteRepository favoriteRepository) {
+ this.stationService = stationService;
+ this.pathService = pathService;
+ this.memberRepository = memberRepository;
+ this.favoriteRepository = favoriteRepository;
+ }
+
+ public FavoriteResponse createFavorite(FavoriteRequest favoriteRequest, Long memberId) {
+ Station source = stationService.findById(favoriteRequest.getSource());
+ Station target = stationService.findById(favoriteRequest.getTarget());
+ pathService.findPath(source, target);
+ Favorite favorite = favoriteRepository.save(Favorite.of(memberId, source, target));
+ return FavoriteResponse.from(favorite);
+ }
+
+ @Transactional(readOnly = true)
+ public List<FavoriteResponse> findFavorites(Long memberId) {
+ List<Favorite> favorites = favoriteRepository.findAllByMemberId(memberId);
+ return favorites.stream().map(FavoriteResponse::from).collect(Collectors.toList());
+ }
+
+ public void deleteFavorite(Long favoriteId, Long memberId) {
+ Favorite favorite = favoriteRepository.getById(favoriteId);
+ favorite.hasPermission(memberId);
+ favoriteRepository.delete(favorite);
+ }
+} | Java | memberRepository ๋ฅผ ์ฌ์ฉํ๊ณ ์์ง ์๋๋ฐ์,
์ฆ๊ฒจ์ฐพ๊ธฐ ์์ฑ, ์กฐํ, ์ญ์ ์ ์ ์ํ memberId ์ธ์ง ํ์ธํ์ง ์์๋ ๋ ๊น์? ๐ |
@@ -22,10 +22,14 @@ public PathService(LineService lineService, StationService stationService) {
public PathResponse findPath(Long source, Long target) {
Station upStation = stationService.findById(source);
Station downStation = stationService.findById(target);
- List<Line> lines = lineService.findLines();
- SubwayMap subwayMap = new SubwayMap(lines);
- Path path = subwayMap.findPath(upStation, downStation);
+ Path path = findPath(upStation, downStation);
return PathResponse.of(path);
}
+
+ Path findPath(Station upStation, Station downStation) {
+ List<Line> lines = lineService.findLines();
+ SubwayMap subwayMap = new SubwayMap(lines);
+ return subwayMap.findPath(upStation, downStation);
+ }
} | Java | ์ ๊ทผ์ ์ด์๋ฅผ ์๋ตํ์ ์ด์ ๊ฐ ์์ผ์ ๊ฐ์? ๐ |
@@ -0,0 +1,39 @@
+package nextstep.subway.applicaion.dto;
+
+import nextstep.subway.domain.Favorite;
+
+public class FavoriteResponse {
+ private Long id;
+ private Long memberId;
+ private StationResponse source;
+ private StationResponse target;
+
+ private FavoriteResponse(Long id, Long memberId,
+ StationResponse source, StationResponse target) {
+ this.id = id;
+ this.memberId = memberId;
+ this.source = source;
+ this.target = target;
+ }
+
+ public static FavoriteResponse from(Favorite favorite) {
+ return new FavoriteResponse(favorite.getId(), favorite.getMemberId(),
+ StationResponse.of(favorite.getSource()), StationResponse.of(favorite.getTarget()));
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public Long getMemberId() {
+ return memberId;
+ }
+
+ public StationResponse getSource() {
+ return source;
+ }
+
+ public StationResponse getTarget() {
+ return target;
+ }
+} | Java | ์๊ตฌ์ฌํญ์ memberId ๋ ์๋ค์!
์๊ตฌ์ฌํญ์ ํ์ธํด์ฃผ์ธ์ ๐ |
@@ -0,0 +1,49 @@
+package nextstep.subway.ui;
+
+import java.net.URI;
+import java.util.List;
+import nextstep.auth.authorization.AuthenticationPrincipal;
+import nextstep.member.domain.LoginMember;
+import nextstep.subway.applicaion.FavoriteService;
+import nextstep.subway.applicaion.dto.FavoriteRequest;
+import nextstep.subway.applicaion.dto.FavoriteResponse;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/favorites")
+public class FavoriteController {
+
+ private final FavoriteService favoriteService;
+
+ public FavoriteController(FavoriteService favoriteService) {
+ this.favoriteService = favoriteService;
+ }
+
+ @PostMapping
+ public ResponseEntity<FavoriteResponse> createFavorite(
+ @AuthenticationPrincipal LoginMember loginMember,
+ @RequestBody FavoriteRequest favoriteRequest) {
+ FavoriteResponse favoriteResponse = favoriteService.createFavorite(favoriteRequest, loginMember.getId());
+ return ResponseEntity.created(URI.create("/favorites/" + favoriteResponse.getId())).body(favoriteResponse);
+ }
+
+ @GetMapping
+ public ResponseEntity<List<FavoriteResponse>> getFavorites(@AuthenticationPrincipal LoginMember loginMember) {
+ List<FavoriteResponse> favoriteResponses = favoriteService.findFavorites(loginMember.getId());
+ return ResponseEntity.ok(favoriteResponses);
+ }
+
+ @DeleteMapping("/{favoriteId}")
+ public ResponseEntity<Void> deleteFavorite(@AuthenticationPrincipal LoginMember loginMember, @PathVariable Long favoriteId) {
+ favoriteService.deleteFavorite(favoriteId, loginMember.getId());
+ return ResponseEntity.noContent().build();
+ }
+
+} | Java | ์ฆ๊ฒจ์ฐพ๊ธฐ ์์ฑ ํ ๋ฐํ๊ฐ์ ๋ํ ์๊ตฌ์ฌํญ์ ํ์ธํด์ฃผ์ธ์! ๐
 |
@@ -1,5 +1,6 @@
package nextstep.subway.domain;
+import java.util.Optional;
import org.jgrapht.GraphPath;
import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
import org.jgrapht.graph.SimpleDirectedWeightedGraph;
@@ -22,6 +23,11 @@ public Path findPath(Station source, Station target) {
DijkstraShortestPath<Station, SectionEdge> dijkstraShortestPath = new DijkstraShortestPath<>(graph);
GraphPath<Station, SectionEdge> result = dijkstraShortestPath.getPath(source, target);
+ Optional.ofNullable(result)
+ .orElseThrow(() -> {
+ throw new IllegalArgumentException("์ถ๋ฐ์ญ๊ณผ ๋์ฐฉ์ญ์ด ์ฐ๊ฒฐ๋์ด ์์ง ์์ต๋๋ค.");
+ });
+
List<Section> sections = result.getEdgeList().stream()
.map(it -> it.getSection())
.collect(Collectors.toList()); | Java | Optional ์ ์ฌ์ฉํ์ ์ด์ ๊ฐ ์์ผ์ ๊ฐ์?
์ด๋ ํ ์ด์ ์ด ์๋์? ๐
```suggestion
if (Objects.isNull(result)) {
throw new IllegalArgumentException("์ถ๋ฐ์ญ๊ณผ ๋์ฐฉ์ญ์ด ์ฐ๊ฒฐ๋์ด ์์ง ์์ต๋๋ค.");
}
``` |
@@ -1,4 +1,4 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
@@ -7,6 +7,7 @@
<title>react-shopping-products</title>
</head>
<body>
+ <div id="toast"></div>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body> | Unknown | ์๊ฒ๋ fileChanged์ ์ฌ๋ผ์์ ์ ๊ธฐํด์ ๋จ๊ฒจ๋ด ใ
ใ
|
@@ -0,0 +1,96 @@
+import objectToQueryString, { ObjectQueryParams } from '@/utils/objectToQueryString';
+import { generateBasicToken } from '../utils/auth';
+
+type Method = 'GET' | 'POST' | 'PATCH' | 'DELETE';
+
+type Body = ReadableStream | XMLHttpRequestBodyInit;
+type HeadersType = [string, string][] | Record<string, string> | Headers;
+
+const USER_ID = process.env.VITE_API_USER_ID || 'id';
+const USER_PASSWORD = process.env.VITE_API_USER_PASSWORD || 'password';
+
+type RequestProps = {
+ baseUrl: string;
+ endpoint: string;
+ headers?: HeadersType;
+ body?: Body | object | null;
+ queryParams?: ObjectQueryParams;
+};
+
+type FetcherProps = RequestProps & {
+ method: Method;
+};
+
+type Options = {
+ method: Method;
+ headers: HeadersType;
+ body?: Body | null;
+};
+
+export const requestGet = async <T>({
+ baseUrl,
+ endpoint,
+ headers = {},
+ queryParams,
+}: RequestProps): Promise<T> => {
+ const response = await fetcher({ method: 'GET', baseUrl, endpoint, headers, queryParams });
+ const data: T = await response.json();
+
+ return data;
+};
+
+export const requestPatch = ({
+ baseUrl,
+ endpoint,
+ headers = {},
+ body,
+ queryParams,
+}: RequestProps) => {
+ return fetcher({ method: 'PATCH', baseUrl, endpoint, headers, body, queryParams });
+};
+
+export const requestPost = ({
+ baseUrl,
+ endpoint,
+ headers = {},
+ body,
+ queryParams,
+}: RequestProps) => {
+ return fetcher({ method: 'POST', baseUrl, endpoint, headers, body, queryParams });
+};
+
+export const requestDelete = ({ baseUrl, endpoint, headers = {}, queryParams }: RequestProps) => {
+ return fetcher({ method: 'DELETE', baseUrl, endpoint, headers, queryParams });
+};
+
+const fetcher = ({ method, baseUrl, endpoint, headers, body, queryParams }: FetcherProps) => {
+ const token = generateBasicToken(USER_ID, USER_PASSWORD);
+ const options = {
+ method,
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: token,
+ ...headers,
+ },
+ body: body ? JSON.stringify(body) : null,
+ };
+
+ let url = `${baseUrl}${endpoint}`;
+
+ if (queryParams) url += `?${objectToQueryString(queryParams)}`;
+
+ return errorHandler(url, options, endpoint);
+};
+
+const errorHandler = async (url: string, options: Options, endpoint: string) => {
+ try {
+ const response = await fetch(url, options);
+
+ if (!response.ok) throw new Error('์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.');
+
+ return response;
+ } catch (error) {
+ console.error(`fail to fetch ${endpoint}\n error message: ${error}`);
+ throw new Error('๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ค๋ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.');
+ }
+}; | TypeScript | ์ด ํ์ผ์์ ๊ฐ request๋ฅผ ์ถ์ํํด์ค๊ฒ ์์ฃผ ์ธ์๊น์์ต๋๋ค!!!
๋ฐฐ์๊ฐ ์ด์ด์ด,, |
@@ -0,0 +1,96 @@
+import objectToQueryString, { ObjectQueryParams } from '@/utils/objectToQueryString';
+import { generateBasicToken } from '../utils/auth';
+
+type Method = 'GET' | 'POST' | 'PATCH' | 'DELETE';
+
+type Body = ReadableStream | XMLHttpRequestBodyInit;
+type HeadersType = [string, string][] | Record<string, string> | Headers;
+
+const USER_ID = process.env.VITE_API_USER_ID || 'id';
+const USER_PASSWORD = process.env.VITE_API_USER_PASSWORD || 'password';
+
+type RequestProps = {
+ baseUrl: string;
+ endpoint: string;
+ headers?: HeadersType;
+ body?: Body | object | null;
+ queryParams?: ObjectQueryParams;
+};
+
+type FetcherProps = RequestProps & {
+ method: Method;
+};
+
+type Options = {
+ method: Method;
+ headers: HeadersType;
+ body?: Body | null;
+};
+
+export const requestGet = async <T>({
+ baseUrl,
+ endpoint,
+ headers = {},
+ queryParams,
+}: RequestProps): Promise<T> => {
+ const response = await fetcher({ method: 'GET', baseUrl, endpoint, headers, queryParams });
+ const data: T = await response.json();
+
+ return data;
+};
+
+export const requestPatch = ({
+ baseUrl,
+ endpoint,
+ headers = {},
+ body,
+ queryParams,
+}: RequestProps) => {
+ return fetcher({ method: 'PATCH', baseUrl, endpoint, headers, body, queryParams });
+};
+
+export const requestPost = ({
+ baseUrl,
+ endpoint,
+ headers = {},
+ body,
+ queryParams,
+}: RequestProps) => {
+ return fetcher({ method: 'POST', baseUrl, endpoint, headers, body, queryParams });
+};
+
+export const requestDelete = ({ baseUrl, endpoint, headers = {}, queryParams }: RequestProps) => {
+ return fetcher({ method: 'DELETE', baseUrl, endpoint, headers, queryParams });
+};
+
+const fetcher = ({ method, baseUrl, endpoint, headers, body, queryParams }: FetcherProps) => {
+ const token = generateBasicToken(USER_ID, USER_PASSWORD);
+ const options = {
+ method,
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: token,
+ ...headers,
+ },
+ body: body ? JSON.stringify(body) : null,
+ };
+
+ let url = `${baseUrl}${endpoint}`;
+
+ if (queryParams) url += `?${objectToQueryString(queryParams)}`;
+
+ return errorHandler(url, options, endpoint);
+};
+
+const errorHandler = async (url: string, options: Options, endpoint: string) => {
+ try {
+ const response = await fetch(url, options);
+
+ if (!response.ok) throw new Error('์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.');
+
+ return response;
+ } catch (error) {
+ console.error(`fail to fetch ${endpoint}\n error message: ${error}`);
+ throw new Error('๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ค๋ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.');
+ }
+}; | TypeScript | ์ด๊ฑฐ ์ ์ํจ ใ
ใ
ใ
|
@@ -0,0 +1,96 @@
+import objectToQueryString, { ObjectQueryParams } from '@/utils/objectToQueryString';
+import { generateBasicToken } from '../utils/auth';
+
+type Method = 'GET' | 'POST' | 'PATCH' | 'DELETE';
+
+type Body = ReadableStream | XMLHttpRequestBodyInit;
+type HeadersType = [string, string][] | Record<string, string> | Headers;
+
+const USER_ID = process.env.VITE_API_USER_ID || 'id';
+const USER_PASSWORD = process.env.VITE_API_USER_PASSWORD || 'password';
+
+type RequestProps = {
+ baseUrl: string;
+ endpoint: string;
+ headers?: HeadersType;
+ body?: Body | object | null;
+ queryParams?: ObjectQueryParams;
+};
+
+type FetcherProps = RequestProps & {
+ method: Method;
+};
+
+type Options = {
+ method: Method;
+ headers: HeadersType;
+ body?: Body | null;
+};
+
+export const requestGet = async <T>({
+ baseUrl,
+ endpoint,
+ headers = {},
+ queryParams,
+}: RequestProps): Promise<T> => {
+ const response = await fetcher({ method: 'GET', baseUrl, endpoint, headers, queryParams });
+ const data: T = await response.json();
+
+ return data;
+};
+
+export const requestPatch = ({
+ baseUrl,
+ endpoint,
+ headers = {},
+ body,
+ queryParams,
+}: RequestProps) => {
+ return fetcher({ method: 'PATCH', baseUrl, endpoint, headers, body, queryParams });
+};
+
+export const requestPost = ({
+ baseUrl,
+ endpoint,
+ headers = {},
+ body,
+ queryParams,
+}: RequestProps) => {
+ return fetcher({ method: 'POST', baseUrl, endpoint, headers, body, queryParams });
+};
+
+export const requestDelete = ({ baseUrl, endpoint, headers = {}, queryParams }: RequestProps) => {
+ return fetcher({ method: 'DELETE', baseUrl, endpoint, headers, queryParams });
+};
+
+const fetcher = ({ method, baseUrl, endpoint, headers, body, queryParams }: FetcherProps) => {
+ const token = generateBasicToken(USER_ID, USER_PASSWORD);
+ const options = {
+ method,
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: token,
+ ...headers,
+ },
+ body: body ? JSON.stringify(body) : null,
+ };
+
+ let url = `${baseUrl}${endpoint}`;
+
+ if (queryParams) url += `?${objectToQueryString(queryParams)}`;
+
+ return errorHandler(url, options, endpoint);
+};
+
+const errorHandler = async (url: string, options: Options, endpoint: string) => {
+ try {
+ const response = await fetch(url, options);
+
+ if (!response.ok) throw new Error('์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.');
+
+ return response;
+ } catch (error) {
+ console.error(`fail to fetch ${endpoint}\n error message: ${error}`);
+ throw new Error('๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ค๋ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.');
+ }
+}; | TypeScript | ์ฌ๊ธฐ์ ๋์ง๋ ์ค๋ฅ ๋ฉ์์ง๊ฐ showToast์์ ๋ณด์ด๋ ๋ฉ์์ง์์๋ ํ์ฉ์ ์ํ๊ณ ์๋ ๊ฒ ๊ฐ์์
ํต์ผ์ํค๋ ๋ฐฉ์์ด๋ ์ฌ์ฉ์์๊ฒ ๋ณด์ด๋ ์ค๋ฅ ๋ฉ์์ง๋ฅผ ์ด๋ป๊ฒ ๊ด๋ฆฌํ ์ง๋ ๊ณ ๋ฏผํด๋ณด๋ฉด ์ข์ ๋ฏ์!
(๋๋ ํด์ผํจ ใ
) |
@@ -0,0 +1,75 @@
+import { CartItem } from '@/types/cartItem.type';
+import { BASE_URL } from '../baseUrl';
+import { requestGet, requestPost, requestDelete } from '../fetcher';
+import { ENDPOINT } from '../endpoints';
+
+type ResponseCartItemList = {
+ content: CartItem[];
+ pageable: {
+ sort: {
+ sorted: false;
+ unsorted: true;
+ empty: true;
+ };
+ pageNumber: 0;
+ pageSize: 20;
+ offset: 0;
+ paged: true;
+ unpaged: false;
+ };
+ last: true;
+ totalPages: 1;
+ totalElements: 6;
+ sort: {
+ sorted: false;
+ unsorted: true;
+ empty: true;
+ };
+ first: true;
+ number: 0;
+ numberOfElements: 6;
+ size: 20;
+ empty: false;
+};
+
+type QueryParams = {
+ page: number;
+ size: number;
+};
+
+export const requestCartItemList = async (
+ page: number = 0,
+ size: number = 20,
+): Promise<ResponseCartItemList> => {
+ const queryParams: QueryParams = {
+ page,
+ size,
+ };
+
+ return await requestGet<ResponseCartItemList>({
+ baseUrl: BASE_URL.SHOP,
+ endpoint: ENDPOINT.CART_ITEM,
+ queryParams,
+ });
+};
+
+export const requestAddCartItem = async (productId: number, quantity: number = 1) => {
+ await requestPost({
+ baseUrl: BASE_URL.SHOP,
+ endpoint: ENDPOINT.CART_ITEM,
+ body: {
+ productId,
+ quantity,
+ },
+ });
+};
+
+export const requestDeleteCartItem = async (cartItemId: number) => {
+ await requestDelete({
+ baseUrl: BASE_URL.SHOP,
+ endpoint: `${ENDPOINT.CART_ITEM}/${cartItemId}`,
+ body: {
+ id: cartItemId,
+ },
+ });
+}; | TypeScript | ์ฌ์ํ ์๊ฒฌ์ธ๋ฐ, ์ ๋ api ์๋ต์ด ์ธ์ ๋ ๋ฐ๋ ์ ์๋ค๊ณ ์๊ฐํด์ ์๋ฐ ํ์
์ type๋ณด๋ค interface๋ก ์ ์ธํ๋ ค๋ ํธ์ด๊ธด ํจ๋ค
๊ทธ๋ฌ๋ฉด pageable ๊ฐ์ด ์์ฐ๊ณ ๋ญ๊ฐ ๋ค๋ฅธ ์ ๋ณด๋ ์ค๋ณต๋๋ ์น๊ตฌ๋ค์ ์์จ์ค ์๋ ์์ด์ ์คํ๋ ค ๋ฆฌ๋ทฐ์ด์๊ฒ ์ธ ์น๊ตฌ๋ค๋ง interface์ ์ ์ธํด์ค ์ ์๋ค๋ ์ฅ์ ๋ ์๋ค๊ณ ์๊ฐํ์ด๋ค.
(interface์ ๋จ์ ์ ์์๊น ์๊ฐ๋ ๋๋๋ฐ ํจ ์ฐพ์๋ด์ผ๊ฒ ๋ค) |
@@ -0,0 +1,29 @@
+.container {
+ position: relative;
+}
+
+.cartIcon {
+ cursor: pointer;
+}
+
+.amountContainer {
+ position: absolute;
+ bottom: 0;
+ right: 0;
+ width: 19px;
+ height: 19px;
+ background: #fff;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ border-radius: 50%;
+}
+
+.amount {
+ color: black;
+ font-size: 10px;
+ font-weight: 700;
+ line-height: 12.19px;
+ text-align: left;
+ margin-top: 2px;
+} | Unknown | ์ด๊ฑฐ ๊ฐ ์ ์ธ ๊ถ๊ธ์ฆ์ธ๋ฐ ์ด๊ฑฐ ๋๊ฐ ํ์ํจ?! |
@@ -1,4 +1,4 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
@@ -7,6 +7,7 @@
<title>react-shopping-products</title>
</head>
<body>
+ <div id="toast"></div>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body> | Unknown | ์ ๋ ์ด๊ฒ ์ ๋์ง ๋ชจ๋ฅด๊ฒ ๋ค์.... ใ
.ใ
|
@@ -0,0 +1,96 @@
+import objectToQueryString, { ObjectQueryParams } from '@/utils/objectToQueryString';
+import { generateBasicToken } from '../utils/auth';
+
+type Method = 'GET' | 'POST' | 'PATCH' | 'DELETE';
+
+type Body = ReadableStream | XMLHttpRequestBodyInit;
+type HeadersType = [string, string][] | Record<string, string> | Headers;
+
+const USER_ID = process.env.VITE_API_USER_ID || 'id';
+const USER_PASSWORD = process.env.VITE_API_USER_PASSWORD || 'password';
+
+type RequestProps = {
+ baseUrl: string;
+ endpoint: string;
+ headers?: HeadersType;
+ body?: Body | object | null;
+ queryParams?: ObjectQueryParams;
+};
+
+type FetcherProps = RequestProps & {
+ method: Method;
+};
+
+type Options = {
+ method: Method;
+ headers: HeadersType;
+ body?: Body | null;
+};
+
+export const requestGet = async <T>({
+ baseUrl,
+ endpoint,
+ headers = {},
+ queryParams,
+}: RequestProps): Promise<T> => {
+ const response = await fetcher({ method: 'GET', baseUrl, endpoint, headers, queryParams });
+ const data: T = await response.json();
+
+ return data;
+};
+
+export const requestPatch = ({
+ baseUrl,
+ endpoint,
+ headers = {},
+ body,
+ queryParams,
+}: RequestProps) => {
+ return fetcher({ method: 'PATCH', baseUrl, endpoint, headers, body, queryParams });
+};
+
+export const requestPost = ({
+ baseUrl,
+ endpoint,
+ headers = {},
+ body,
+ queryParams,
+}: RequestProps) => {
+ return fetcher({ method: 'POST', baseUrl, endpoint, headers, body, queryParams });
+};
+
+export const requestDelete = ({ baseUrl, endpoint, headers = {}, queryParams }: RequestProps) => {
+ return fetcher({ method: 'DELETE', baseUrl, endpoint, headers, queryParams });
+};
+
+const fetcher = ({ method, baseUrl, endpoint, headers, body, queryParams }: FetcherProps) => {
+ const token = generateBasicToken(USER_ID, USER_PASSWORD);
+ const options = {
+ method,
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: token,
+ ...headers,
+ },
+ body: body ? JSON.stringify(body) : null,
+ };
+
+ let url = `${baseUrl}${endpoint}`;
+
+ if (queryParams) url += `?${objectToQueryString(queryParams)}`;
+
+ return errorHandler(url, options, endpoint);
+};
+
+const errorHandler = async (url: string, options: Options, endpoint: string) => {
+ try {
+ const response = await fetch(url, options);
+
+ if (!response.ok) throw new Error('์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.');
+
+ return response;
+ } catch (error) {
+ console.error(`fail to fetch ${endpoint}\n error message: ${error}`);
+ throw new Error('๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ค๋ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.');
+ }
+}; | TypeScript | ๋ง์์. ์ฌ์ค ์ด๋์ ๋์ง ์ค๋ฅ๊ฐ ์บ์น๋๊ณ ๊ทธ๋ฐ๊ฑธ ํ์ธ์ ์ํด์ ์๋ฌ ๋ฐ์ด๋๋ฆฌ์ ๋น์ทํ ์ค๊ณ๋ก ์ด๋ฅผ ํด๊ฒฐํ ์ ์์ง ์์๊น ์ถ์ต๋๋ค. ํ๋ฒ ์๋ํด๋ณผ๊ฒ์! |
@@ -0,0 +1,29 @@
+.container {
+ position: relative;
+}
+
+.cartIcon {
+ cursor: pointer;
+}
+
+.amountContainer {
+ position: absolute;
+ bottom: 0;
+ right: 0;
+ width: 19px;
+ height: 19px;
+ background: #fff;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ border-radius: 50%;
+}
+
+.amount {
+ color: black;
+ font-size: 10px;
+ font-weight: 700;
+ line-height: 12.19px;
+ text-align: left;
+ margin-top: 2px;
+} | Unknown | ๊ธ์ด์จ ๊ฒ ๊ฐ๋ค์. ํ์ ์์๋ฏ...! |
@@ -0,0 +1,99 @@
+## ์ฐ์ํ ํ
ํฌ์ฝ์ค ํ๋ฆฌ์ฝ์ค ํฌ๋ฆฌ์ค๋ง์ค ํ๋ก๋ชจ์
+
+### ์งํ๋ฐฉ์
+- ์์ ๋ฉ์์ง ์ถ๋ ฅ
+- ๋ฐฉ๋ฌธ ๋ ์ง ์
๋ ฅ
+- ์ฃผ๋ฌธ ๋ฉ๋ด์ ๊ฐ์ ์
๋ ฅ
+- ์
๋ ฅ ์์ผ ์ด๋ฒคํธ ๋ฉ์์ง ์ถ๋ ฅ
+- ์ด๋ฒคํธ ํํ ์ถ๋ ฅ
+ - ์ฃผ๋ฌธ ๋ฉ๋ด
+ - ํ ์ธ ์ ์ด ์ฃผ๋ฌธ ๊ธ์ก
+ - ์ฆ์ ๋ฉ๋ด ์ฌ๋ถ
+ - ํํ ๋ด์ญ ์ฌ๋ถ
+ - ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก
+ - 12์ ์ด๋ฒคํธ ๋ฐฐ์ง ์ฌ๋ถ
+
+### ์ฃผ์ ๊ตฌํ ์ฌํญ
+- [x] ์
๋ ฅ ๋ทฐ ๊ตฌํ
+- [x] ์ถ๋ ฅ ๋ทฐ ๊ตฌํ
+
+- [x] ๋ ์ง ์
๋ ฅ ๋ฐ ์ ์ฅ ๊ฐ์ฒด ๊ตฌํ
+- [x] ๋ ์ง ์
๋ ฅ ์ ๋ ์ง๊ด๋ จ ํด๋น ์ด๋ฒคํธ ํญ๋ชฉ ์ ์ฅ
+ - [x] ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ์ด ๊ธ์ก ํ ์ธ ํญ๋ชฉ
+ - [x] ํ์ผ/์ฃผ๋ง ๊ตฌ๋ถ ํ ์ธ ํ์
ํญ๋ณต
+ - [x] ๋ ์ง๋ ๋ฌ๋ ฅ์ ๋ณ์ ๋ฐ๋ผ ์คํ์
ํ ์ธ ํญ๋ชฉ
+- [x] ๋ ์ง ๊ด๋ จ ์ด๋ฒคํธ ๋ฐํ DTO ๋ฐํ
+
+- [x] ์ฃผ๋ฌธ ๋ฉ๋ด์ ๊ฐ์ ์
๋ ฅ ๋ฐ ์ ์ฅ ๊ฐ์ฒด ๊ตฌํ
+ - [x] ๊ฐ ๋ฉ๋ด๋ฅผ ๊ธฐ๋ณธ ๊ธ์ก๊ณผ ๋ฉ๋ด ๋ช
์ผ๋ก Enum ์ผ๋ก ๊ด๋ฆฌ
+ - [x] ์ฃผ๋ฌธํ ๋ฉ๋ด ์
๋ ฅ์ ๋ํ ์ ํจ์ฑ ๊ฒ์ฌ ์งํ ํ ์ ์ฅ ๊ฐ์ฒด์ ์ ์ฅ
+- [x] ์ฃผ๋ฌธ ๋ฉ๋ด ๋ด์ญ ๋ฐํ DTO ๋ฐํ
+
+- [x] ๋ ์ง ์ด๋ฒคํธ์ ์ฃผ๋ฌธ ๋ฉ๋ด DTO ๋ฅผ ํตํ ์ด๋ฒคํธ ํํ ์ ์ฉ
+- [x] ์ด๋ฒคํธ ์ ์ฉ DTO ๋ฐํ ๋ฐ ์ถ๋ ฅ
+ - [x] ํ ์ธ ์ ๊ธ์ก์ ์ถ๋ ฅ
+ - [x] ํ ์ธ ์ ๊ธ์ก์ ๋ฐ๋ฅธ ์ฆ์ ์ฌ๋ถ ์ถ๋ ฅ
+ - ์ฆ์ ์ฌ๋ถ๊ฐ ์๋ค๋ฉด '์์' ์ถ๋ ฅ
+ - [x] ํํ ๋ด์ญ ์ถ๋ ฅ
+ - ์ ์ฉ๋ ํํ ์๋ค๋ฉด '์์' ์ถ๋ ฅ
+ - [x] ํํ ๊ธ์ก ์ถ๋ ฅ
+ - [x] ์ฆ์ ํํ ๊ธ์ก์ ์ ์ธํ ํ ์ธ ํ ์์ ๊ธ์ก ์ถ๋ ฅ
+ - [x] ์ด ํํ ๊ธ์ก์ ๋ฐ๋ฅธ ์ด๋ฒคํธ ๋ฐฐ์ง ๋ถ์ฌ ์ฌ๋ถ ์ถ๋ ฅ
+ - ์ด๋ฒคํธ ๋ฐฐ์ง๊ฐ ์๋ค๋ฉด '์์' ์ถ๋ ฅ
+
+- ์ถ๊ฐ ๊ตฌํ ์ฌํญ
+ - ์ด๋ฒคํธ ๊ฒฐ๊ณผ ๋๋ฉ์ธ์ ์ ๋ณด๋ฅผ ์ถ๋ ฅ ๋ฌธ์์ด์ผ๋ก ๋ณ๊ฒฝํ์ฌ Builder DTO ์์ฑ/๋ฐํ
+ - ์๋ชป๋ ์
๋ ฅ์ ํตํ ๊ณผ์ ์ ์์ธ ๋ฉ์์ง ์ถ๋ ฅ ๋ฐ ์ฌ์
๋ ฅ
+ - ์ด ์ฃผ๋ฌธ ๋ฉ๋ด ๊ธ์ก์ด 10,000์ ์ดํ์ผ ๊ฒฝ์ฐ ๋ชจ๋ ํ ์ธ ๊ธ์ก 0์ผ๋ก ์ง์
+
+### ์์ธ ์ฒ๋ฆฌ
+- ๋ ์ง ์
๋ ฅ ์์ธ
+ - [x] ์๋ชป๋ ๋ ์ง ์
๋ ฅ์ ๊ฒฝ์ฐ
+ - [x] ๋ ์ง๊ฐ ์ ์ํ์ผ๋ก ๋ณ๊ฒฝ์ด ์๋ ๋
+- ๋ฉ๋ด ์
๋ ฅ ์์ธ
+ - [x] ๋ฉ๋ด ์
๋ ฅ ์ ์ ๊ทํํ์ ํจํด์ด ๋ค๋ฅผ ๊ฒฝ์ฐ (TextProcessor ์ฒ๋ฆฌ)
+ - [x] ์ค๋ณต ๋ฉ๋ด๋ช
์
๋ ฅ์ ๊ฒฝ์ฐ (TextProcessor ์ฒ๋ฆฌ)
+ - [x] ์๋ ๋ฉ๋ด๋ช
์
๋ ฅ์ ๊ฒฝ์ฐ
+ - [x] ์ฃผ๋ฌธ ๋ฉ๋ด์ ๊ฐ์๊ฐ 1๋ณด๋ค ์์ ๋
+ - [x] ์ฃผ๋ฌธ ๋ฉ๋ด๊ฐ 20๊ฐ๋ฅผ ๋์ ๋
+ - [x] ์๋ฃ๋ง ์ฃผ๋ฌธ ์ ์ฃผ๋ฌธ ๋ถ๊ฐ๋ฅ
+
+### ํด๋์ค ๊ตฌ์กฐ
+- InputView : ํ๋ฉด ์
๋ ฅ์ ๋ด๋นํ๋ ๋ทฐ
+ - InputViewMessage : ์
๋ ฅ์ ์ํ ๋ฉ์์ง๋ฅผ ๊ด๋ฆฌํ๋ Enum
+- OutputView : ํ๋ฉด ์ถ๋ ฅ์ ๋ด๋นํ๋ ๋ทฐ
+ - OutputViewMessage : ์ถ๋ ฅ์ ์ํ ๋ฉ์์ง๋ฅผ ๊ด๋ฆฌํ๋ Enum
+- PromotionRun : ๋ทฐ์ ์ปจํธ๋กค๋ฌ๋ฅผ ์ฐ๊ฒฐํ๋ ํด๋์ค๋ก ์์ฒญ ์ ๋ฌ
+- PromotionController : ๋น์ฆ๋์ค ๋ก์ง์ ์คํํ๊ธฐ ์ํด ์์ฒญ์ ์ ๋ฌํ๋ ์ปจํธ๋กค๋ฌ
+- PromotionService : ํ๋ก๋ชจ์
์ ํจ์ฑ ๊ฒ์ฆ์ ๊ฑฐ์น ๊ฐ์ฒด ์์ฑ๊ณผ ๋น์ฆ๋์ค ๋ก์ง์ ์คํํ ์๋น์ค
+- TextProcessor : ์
๋ ฅ๋ฐ์ ๋ฌธ์์ด์ ํน์ ํ์
์ผ๋ก ๋ฐํํ๊ธฐ ์ํ ์๋น์ค
+- OrderMenus : ์ฃผ๋ฌธ ๋ฉ๋ด์ ๊ฐ์ ์ ์ฅํ๋ ํด๋์ค
+ - MenuItem : ๋ฉ๋ด ์ด๋ฆ๊ณผ ๊ฐ๊ฒฉ, ๋ฉ๋ด ์ข
๋ฅ๋ฅผ ์ ์ฅํ๋ Enum
+ - MenuCategory : ๋ฉ๋ด ์ข
๋ฅ๋ฅผ ๊ตฌ๋ถํ๋ Enum
+- ReservationDateEvent : ๋ ์ง ๊ด๋ จ ์ด๋ฒคํธ ์ ์ฅ ํด๋์ค
+ - ReservationDate : ์
๋ ฅ๋ ๋ ์ง๋ฅผ ์ ์ฅํ๊ธฐ ์ํ ํด๋์ค
+ - ChristmasDiscount : ํฌ๋ฆฌ์ค๋ง์ค D-day ํ ์ธ ๊ด๋ฆฌ ํด๋์ค
+ - WeekDiscountType : ์ฃผ๋ง ํ ์ธ, ํ์ผ ํ ์ธ์ ๊ตฌ๋ถํ๋ Enum
+ - SpecialDayDiscount : ํน๋ณ ํ ์ธ ์ผ์๊ฐ ์ ์ฅ๋์ด ์๋ Enum
+- EventResult : ์ ์ฉ ์ค์ธ ๋ชจ๋ ์ด๋ฒคํธ๋ฅผ ์ ์ฅํ๋ ํด๋์ค
+ - DiscountDetail : ์ฃผ๋ฌธ ๊ธ์ก๊ณผ ํ ์ธ, ์์ ๊ธ์ก ๋ฑ์ ๋ณด๊ดํ ํด๋์ค
+ - GiftEvent : ์ฆ์ ์ํ ์ฌ๋ถ๋ฅผ ๊ด๋ฆฌํ๋ Enum
+ - RewardBadge : ์ด๋ฒคํธ ๋ฐฐ์ง๋ฅผ ๊ด๋ฆฌํ๋ Enum
+- PromotionException : ์ง์ ๋ Enum ์์ธ ๋ฉ์์ง๋ฅผ ํตํด ๊ฐ๋ฅผ ๋ด์ IllegalArgumentException ์์ฑ
+ - ExceptionMessage : ์์ธ ๋ฐ์ ๋ฉ์์ง๋ฅผ ๋ณด๊ดํ Enum Class
+- PromotionConverter : Service ์์ Domain to DTO ์ปจ๋ฒํฐ
+- EventResultTextFactory : EventResultDTO ๋ฐํ์ ์ํ ๋ฌธ์์ด ์กฐ์ ์๋น์ค
+ - EventResultText : EventResultDTO ์ ํ์ํ ๋ฌธ์์ด Enum
+- ํ
์คํธ : ํด๋์ค๋ณ ๋ฉ์๋ ๋จ์ ํ
์คํธ ์งํ
+
+### ์ด๋ฒ์ ํ๋ก์ ํธ๋ฅผ ์งํํ๋ฉด์ ๊ณ ๋ฏผํ ์์
+- ํด๋น ๊ธฐ๋ฅ์ ๊ตฌํํ๊ธฐ ์ํ ๊ตฌ์กฐ ์ค๊ณ
+ - ์ดํ ํ์ํ ํด๋์ค๋ค์ ์ถ๊ฐํ๋ฉฐ ์ค๊ณ ๋ณ๊ฒฝ
+- ๋์ผํ ์
๋ ฅ๊ณผ ์ถ๋ ฅ์ ํ๋ ๋ทฐ๋ ์ฑ๊ธํค์ผ๋ก ๊ตฌํ
+- ์
๋ ฅ์ ๋ํ ์ ํจ์ฑ ๊ฒ์ฌ์ ๊ฐ์ฒด ์์ฑ์ ๋ํ ์ ํจ์ฑ ๊ฒ์ฌ ๊ตฌ๋ถ์ ๋ํ ๊ณ ๋ฏผ
+- ์ด๋ฒคํธ ์ ์ฉ ์ ์ด๋ฒคํธ ๋ด์ญ๊ณผ ์ฃผ๋ฌธ ๋ด์ญ์ ์ฌ์ฉํด ๊ฐ์ ์ ์ฅํ๋ ๋ฐฉ๋ฒ์ Service ์์ ์งํํ ์ง ๊ฐ์ฒด ๋ด๋ถ์์ ์งํํ ์ง ๊ณ ๋ฏผ
+- ์ถ๋ ฅ์ ์ํ DTO ์์ฑ์ ๋ํ ๊ณ ๋ฏผ
+ - DTO ๋ฃฐ ์ถ๋ ฅํ๊ณ ํด๋น DTO ํตํด ๋ค์ ์ด๋ฒคํธ ๋ด์ญ ํ์ธํ๋๋ฐ ์์ด DTO ๊ฐ์ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ
+ - EventResultDTO ๋ทฐ์ ์ถ๋ ฅํ ๋ฌธ์์ด์ ๊ฐ์ง๊ณ ์์ DTO ์์ฑ ๋ฐฉ๋ฒ ๊ณ ๋ฏผ ํ Builder, EventResultTextFactory ์ฌ์ฉ
+- ์๋ชป๋ ์
๋ ฅ์ ๋ํ ๋ฉ์๋ ์ฌ์คํ ๋ก์ง์ ์ง๋์ฃผ [zangsu๋](https://github.com/zangsu) ์ฝ๋๋ฆฌ๋ทฐ๋ก ๋ฐฐ์ด Supplier ๋ฐ๋ณต ์ฌ์ฉ
+- ํ
์คํธ ์ฝ๋ mock ๊ฐ์ฒด์ ๋ํ ์ฌ์ฉ๋ฐฉ๋ฒ์ ๋ํ ๊ณ ๋ฏผ
\ No newline at end of file | Unknown | README์ ํด๋์ค์ด๋ฆ์ ์์ฑํ๊ธฐ๋ณด๋ค ์ด๋ค ์ญํ ์ ํด๋์ค์ธ์ง ์ ๋๋ง ์์ฑํ์๋๊ฒ ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! ์๋ฌด๋๋ ํด๋์ค์ด๋ฆ์ด๋ ๋ฉ์๋ ์ด๋ฆ์ ๊ฐ๋ณ์ฑ์ด ๋๋ค๋ณด๋ README๋ ์ฃผ๊ธฐ์ ์ผ๋ก ์
๋ฐ์ดํธํด์ผํด์ ๋ฒ๊ฑฐ๋ก์์ด ํฌ๊ฑฐ๋ ์ |
@@ -0,0 +1,20 @@
+package christmas.exception;
+
+public enum ExceptionMessage {
+ INVALID_INPUT_DATE("์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
+ INVALID_INPUT_ORDER("์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
+ INVALID_MENU_ITEM("ํด๋น ๋ฉ๋ด๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค."),
+ INVALID_WEEK_DISCOUNT_TYPE("์๋ชป๋ ์ฃผ๊ฐ ํ ์ธ ํ์
์
๋๋ค."),
+ ;
+
+ private static final String PREFIX = "[ERROR] ";
+ private final String errorMessage;
+
+ ExceptionMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ public String getErrorMessage() {
+ return PREFIX + errorMessage;
+ }
+} | Java | ์ถ๊ฐ๋ enum์ ๊ณ ๋ คํ์
์ ์ด๋ ๊ฒ ์์ฑํ ์๋๋ผ๊ณ ์๊ฐ์ ๋์ง๋ง, ๊ผผ๊ผผํ๊ณ ํ๊ณ ๋ค์๋ฉด ,;๋ณด๋ค ;๋ก ๋๋ด๋๊ฒ ๋ ์ข์ง ์์๊น์?? ๊ฐ์ธ์ ์ธ ์๊ฐ์
๋๋ค ใ
ใ
ใ
|
@@ -1,7 +1,20 @@
package christmas;
+
+import camp.nextstep.edu.missionutils.Console;
+import christmas.run.PromotionRun;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+
public class Application {
public static void main(String[] args) {
- // TODO: ํ๋ก๊ทธ๋จ ๊ตฌํ
+ try {
+ InputView inputView = SingletonView.getInputView();
+ OutputView outputView = SingletonView.getOutputView();
+ PromotionRun promotionRun = new PromotionRun(inputView, outputView);
+ promotionRun.runPromotion();
+ } finally {
+ Console.close();
+ }
}
} | Java | ๋ทฐ๋ฅผ ์ฑ๊ธํค์ผ๋ก ๊ด๋ฆฌํ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,20 @@
+package christmas.exception;
+
+public enum ExceptionMessage {
+ INVALID_INPUT_DATE("์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
+ INVALID_INPUT_ORDER("์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
+ INVALID_MENU_ITEM("ํด๋น ๋ฉ๋ด๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค."),
+ INVALID_WEEK_DISCOUNT_TYPE("์๋ชป๋ ์ฃผ๊ฐ ํ ์ธ ํ์
์
๋๋ค."),
+ ;
+
+ private static final String PREFIX = "[ERROR] ";
+ private final String errorMessage;
+
+ ExceptionMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ public String getErrorMessage() {
+ return PREFIX + errorMessage;
+ }
+} | Java | ์ถ๊ฐ์ ์ผ๋ก ์๊ตฌ์ฌํญ์ ์๋ฌ๋ฉ์์ง๋ "[ERROR] ์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."์ผ๋ก ํต์ผํ๋ผ๊ณ ๊ธฐ์ฌ๋์ด ์์ด ์ต์ข
์ฝ๋ฉํ
์คํธ๋ก ๊ฐ์๊ฒ ๋๋ฉด ๊ผผ๊ผผํ ๋ณด์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,33 @@
+package christmas.model.event;
+
+import christmas.model.date.ReservationDate;
+
+public class ChristmasDiscount {
+ private static final int FIRST_DAY = 1;
+ private static final int CHRISTMAS_DAY = 25;
+ private static final int BASIC_DISCOUNT = 1000;
+ private static final int PLUS_DISCOUNT = 100;
+ private static final int NONE_DISCOUNT = 0;
+
+ private final int discount;
+
+ public ChristmasDiscount(ReservationDate date) {
+ this.discount = initDiscountAmount(date);
+ }
+
+ private int initDiscountAmount(ReservationDate date) {
+ if (date.day() > CHRISTMAS_DAY) {
+ return NONE_DISCOUNT;
+ }
+
+ return BASIC_DISCOUNT + getPlusDiscount(date.day());
+ }
+
+ private int getPlusDiscount(int day) {
+ return (day - FIRST_DAY) * PLUS_DISCOUNT;
+ }
+
+ public int getDiscount() {
+ return discount;
+ }
+} | Java | ReservationDate์์ ์ค์ค๋ก ์์ ์ด ๊ฐ์ง ๊ฐ์๋ํด ๊ฒ์ฆํ๋๋ก ๋ฉ์๋๋ฅผ ๊ตฌํํ์๋ ๊ฒ์ด ๋ ๊ฐ์ฒด์งํฅ์ ์ธ ์ฝ๋๋ผ๊ณ ์๊ฐํฉ๋๋ค.
date.isChristmasDay() ์ ๊ฐ์ด ๋ง์ด์ฃ !! 'getter๋ฅผ ์ง์ํ๋ผ'๋ ์๋ฏธ๋ VO์๊ฒ๋ ๋์ผํ๊ฒ ์ ์ฉ๋ฉ๋๋ค.
๊ด๋ จ ๋ฌธ์๋ฅผ ์๋ ๋งํฌ๋ก ๋ฌ์๋๊ฒ์!
https://tecoble.techcourse.co.kr/post/2020-04-28-ask-instead-of-getter/ |
@@ -0,0 +1,62 @@
+package christmas.model.event;
+
+import christmas.model.event.dto.ReservationDateEventDTO;
+
+public class DiscountDetail {
+ private final int totalPriceBeforeDiscount;
+ private final int totalPriceAfterDiscount;
+ private final WeekDiscountType weekDiscountType;
+ private final int christmasDiscount;
+ private final int weekTypeDiscount;
+ private final int specialDiscount;
+
+ protected DiscountDetail(ReservationDateEventDTO dateEventDTO, int totalPriceBeforeDiscount, int weekTypeDiscount) {
+ this.totalPriceBeforeDiscount = totalPriceBeforeDiscount;
+ this.weekDiscountType = WeekDiscountType.checkWeekType(dateEventDTO.getDateWeek());
+ this.christmasDiscount = dateEventDTO.getChristmasDiscount();
+ this.specialDiscount = dateEventDTO.getSpecialDiscount();
+ this.weekTypeDiscount = weekTypeDiscount;
+ this.totalPriceAfterDiscount = initTotalPriceAfterDiscount();
+ }
+
+ protected DiscountDetail(ReservationDateEventDTO dateEventDTO, int totalPriceBeforeDiscount) {
+ this.totalPriceBeforeDiscount = totalPriceBeforeDiscount;
+ this.weekDiscountType = WeekDiscountType.checkWeekType(dateEventDTO.getDateWeek());
+ this.christmasDiscount = 0;
+ this.specialDiscount = 0;
+ this.weekTypeDiscount = 0;
+ this.totalPriceAfterDiscount = initTotalPriceAfterDiscount();
+ }
+
+ private int initTotalPriceAfterDiscount() {
+ return totalPriceBeforeDiscount - getTotalDiscount();
+ }
+
+ public int getTotalPriceBeforeDiscount() {
+ return totalPriceBeforeDiscount;
+ }
+
+ public int getTotalPriceAfterDiscount() {
+ return totalPriceAfterDiscount;
+ }
+
+ public int getChristmasDiscount() {
+ return christmasDiscount;
+ }
+
+ public int getSpecialDiscount() {
+ return specialDiscount;
+ }
+
+ public int getWeekTypeDiscount() {
+ return weekTypeDiscount;
+ }
+
+ public WeekDiscountType getWeekDiscountType() {
+ return weekDiscountType;
+ }
+
+ public int getTotalDiscount() {
+ return christmasDiscount + weekTypeDiscount + specialDiscount;
+ }
+} | Java | DiscountDetil์ ํ๋๋ก ์ด ๊ฐ๋ค์ ๊ตณ์ด ๊ฐ์ ธ์ผ ํ ์ด์ ๊ฐ ์์๊น์? ์ฌ์ฌ์ฉ์ ์ฌ์ง๊ฐ ์๋ค๋ฉด ๋ฉ์๋๋ฅผ ํตํด ๋ฉ์์ง๋ฅผ ์ ๋ฌํ๋ ๋ฐฉ์์ด ๋ ์ข๋ค๊ณ ์๊ฐํด์! |
@@ -0,0 +1,62 @@
+package christmas.model.event;
+
+import christmas.model.event.dto.ReservationDateEventDTO;
+
+public class DiscountDetail {
+ private final int totalPriceBeforeDiscount;
+ private final int totalPriceAfterDiscount;
+ private final WeekDiscountType weekDiscountType;
+ private final int christmasDiscount;
+ private final int weekTypeDiscount;
+ private final int specialDiscount;
+
+ protected DiscountDetail(ReservationDateEventDTO dateEventDTO, int totalPriceBeforeDiscount, int weekTypeDiscount) {
+ this.totalPriceBeforeDiscount = totalPriceBeforeDiscount;
+ this.weekDiscountType = WeekDiscountType.checkWeekType(dateEventDTO.getDateWeek());
+ this.christmasDiscount = dateEventDTO.getChristmasDiscount();
+ this.specialDiscount = dateEventDTO.getSpecialDiscount();
+ this.weekTypeDiscount = weekTypeDiscount;
+ this.totalPriceAfterDiscount = initTotalPriceAfterDiscount();
+ }
+
+ protected DiscountDetail(ReservationDateEventDTO dateEventDTO, int totalPriceBeforeDiscount) {
+ this.totalPriceBeforeDiscount = totalPriceBeforeDiscount;
+ this.weekDiscountType = WeekDiscountType.checkWeekType(dateEventDTO.getDateWeek());
+ this.christmasDiscount = 0;
+ this.specialDiscount = 0;
+ this.weekTypeDiscount = 0;
+ this.totalPriceAfterDiscount = initTotalPriceAfterDiscount();
+ }
+
+ private int initTotalPriceAfterDiscount() {
+ return totalPriceBeforeDiscount - getTotalDiscount();
+ }
+
+ public int getTotalPriceBeforeDiscount() {
+ return totalPriceBeforeDiscount;
+ }
+
+ public int getTotalPriceAfterDiscount() {
+ return totalPriceAfterDiscount;
+ }
+
+ public int getChristmasDiscount() {
+ return christmasDiscount;
+ }
+
+ public int getSpecialDiscount() {
+ return specialDiscount;
+ }
+
+ public int getWeekTypeDiscount() {
+ return weekTypeDiscount;
+ }
+
+ public WeekDiscountType getWeekDiscountType() {
+ return weekDiscountType;
+ }
+
+ public int getTotalDiscount() {
+ return christmasDiscount + weekTypeDiscount + specialDiscount;
+ }
+} | Java | ์ธ๋ถ ์์ฑ์ ๋ง๊ธฐ ์ํด ์์ฑ์๋ฅผ protected๋ก ๊ด๋ฆฌํ์ ๊ฒ์ผ๋ก ๋ณด์ด๋๋ฐ, private์ผ๋ก ์์ฑ์๋ฅผ ๋ง๊ณ ์ ์ ํฉํ ๋ฆฌ๋ฉ์๋ ์์ฑ์๋ฅผ ์ฌ์ฉํ๋ฉด ๋ ์๋ฐํ๊ฒ ์บก์ํํ ์ ์์ต๋๋ค! ๊ด๋ จ ์๋ฃ๋ฅผ ์๋ ๋งํฌ๋ก ๋ฌ์๋๊ฒ์!
https://hudi.blog/effective-java-static-factory-method/ |
@@ -0,0 +1,91 @@
+package christmas.model.event;
+
+import christmas.model.event.dto.ReservationDateEventDTO;
+import christmas.model.menu.MenuItem;
+
+import java.util.*;
+import java.util.stream.Stream;
+
+public class EventResult {
+ private static final int MIN_EVENT_AMOUNT = 10_000;
+ private static final int GIFT_AMOUNT = 120_000;
+
+ private final Map<MenuItem, Integer> orderMenus;
+ private final DiscountDetail discountDetail;
+ private final GiftMenu giftMenu;
+ private final RewardBadge rewardBadge;
+
+ public EventResult(ReservationDateEventDTO dateEventDTO, Map<MenuItem, Integer> orderMenus) {
+ this.orderMenus = orderMenus;
+ this.discountDetail = initDiscountDetail(dateEventDTO);
+ this.giftMenu = initGiftMenu();
+ this.rewardBadge = initRewardBadge();
+ }
+
+ private DiscountDetail initDiscountDetail(ReservationDateEventDTO dateEventDTO) {
+ int totalPriceBeforeDiscount = getTotalPriceBeforeDiscount();
+ if (totalPriceBeforeDiscount < MIN_EVENT_AMOUNT) {
+ return new DiscountDetail(dateEventDTO, totalPriceBeforeDiscount);
+ }
+ int weekDiscount = calculateWeekDiscount(dateEventDTO);
+
+ return new DiscountDetail(dateEventDTO, totalPriceBeforeDiscount, weekDiscount);
+ }
+
+ private GiftMenu initGiftMenu() {
+ if (discountDetail.getTotalPriceBeforeDiscount() < GIFT_AMOUNT) {
+ return GiftMenu.NONE;
+ }
+
+ return GiftMenu.CHAMPAGNE;
+ }
+
+ private RewardBadge initRewardBadge() {
+ int benefit = discountDetail.getTotalDiscount() + giftMenu.getGiftPrice();
+
+ return Arrays.stream(RewardBadge.values())
+ .filter(badge ->
+ benefit >= badge.getBenefit())
+ .max(Comparator.comparingInt(RewardBadge::getBenefit))
+ .orElse(RewardBadge.NONE);
+ }
+
+ private int getTotalPriceBeforeDiscount() {
+ return generateOrderMenuEntry(orderMenus)
+ .mapToInt(menu ->
+ menu.getKey().getItemPrice() * menu.getValue())
+ .sum();
+ }
+
+ private int calculateWeekDiscount(ReservationDateEventDTO dateEventDTO) {
+ WeekDiscountType type = WeekDiscountType.checkWeekType(dateEventDTO.getDateWeek());
+
+ return generateOrderMenuEntry(orderMenus)
+ .filter(menu ->
+ menu.getKey().getMenuCategory() == type.getDiscountCategory())
+ .mapToInt(menu ->
+ menu.getValue() * type.getDiscountPrice())
+ .sum();
+ }
+
+ private <K, V> Stream<Map.Entry<K, V>> generateOrderMenuEntry(Map<K, V> orderMenus) {
+ return orderMenus.entrySet()
+ .stream();
+ }
+
+ public Map<MenuItem, Integer> getOrderMenus() {
+ return Collections.unmodifiableMap(orderMenus);
+ }
+
+ public DiscountDetail getDiscountDetail() {
+ return discountDetail;
+ }
+
+ public GiftMenu getGiftMenu() {
+ return giftMenu;
+ }
+
+ public RewardBadge getRewardBadge() {
+ return rewardBadge;
+ }
+} | Java | ํ๋ ์๋ฅผ ์ค์ฌ ์์ง๋๋ฅผ ๋ฎ์ถ๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. ๋ฒ๊ทธ๊ฐ ๋ฐ์ํ๋ฉด ๋ฆฌํํ ๋งํ ๋ถ๋ถ์ด ๋ง์์ ธ์!! |
@@ -0,0 +1,91 @@
+package christmas.model.event;
+
+import christmas.model.event.dto.ReservationDateEventDTO;
+import christmas.model.menu.MenuItem;
+
+import java.util.*;
+import java.util.stream.Stream;
+
+public class EventResult {
+ private static final int MIN_EVENT_AMOUNT = 10_000;
+ private static final int GIFT_AMOUNT = 120_000;
+
+ private final Map<MenuItem, Integer> orderMenus;
+ private final DiscountDetail discountDetail;
+ private final GiftMenu giftMenu;
+ private final RewardBadge rewardBadge;
+
+ public EventResult(ReservationDateEventDTO dateEventDTO, Map<MenuItem, Integer> orderMenus) {
+ this.orderMenus = orderMenus;
+ this.discountDetail = initDiscountDetail(dateEventDTO);
+ this.giftMenu = initGiftMenu();
+ this.rewardBadge = initRewardBadge();
+ }
+
+ private DiscountDetail initDiscountDetail(ReservationDateEventDTO dateEventDTO) {
+ int totalPriceBeforeDiscount = getTotalPriceBeforeDiscount();
+ if (totalPriceBeforeDiscount < MIN_EVENT_AMOUNT) {
+ return new DiscountDetail(dateEventDTO, totalPriceBeforeDiscount);
+ }
+ int weekDiscount = calculateWeekDiscount(dateEventDTO);
+
+ return new DiscountDetail(dateEventDTO, totalPriceBeforeDiscount, weekDiscount);
+ }
+
+ private GiftMenu initGiftMenu() {
+ if (discountDetail.getTotalPriceBeforeDiscount() < GIFT_AMOUNT) {
+ return GiftMenu.NONE;
+ }
+
+ return GiftMenu.CHAMPAGNE;
+ }
+
+ private RewardBadge initRewardBadge() {
+ int benefit = discountDetail.getTotalDiscount() + giftMenu.getGiftPrice();
+
+ return Arrays.stream(RewardBadge.values())
+ .filter(badge ->
+ benefit >= badge.getBenefit())
+ .max(Comparator.comparingInt(RewardBadge::getBenefit))
+ .orElse(RewardBadge.NONE);
+ }
+
+ private int getTotalPriceBeforeDiscount() {
+ return generateOrderMenuEntry(orderMenus)
+ .mapToInt(menu ->
+ menu.getKey().getItemPrice() * menu.getValue())
+ .sum();
+ }
+
+ private int calculateWeekDiscount(ReservationDateEventDTO dateEventDTO) {
+ WeekDiscountType type = WeekDiscountType.checkWeekType(dateEventDTO.getDateWeek());
+
+ return generateOrderMenuEntry(orderMenus)
+ .filter(menu ->
+ menu.getKey().getMenuCategory() == type.getDiscountCategory())
+ .mapToInt(menu ->
+ menu.getValue() * type.getDiscountPrice())
+ .sum();
+ }
+
+ private <K, V> Stream<Map.Entry<K, V>> generateOrderMenuEntry(Map<K, V> orderMenus) {
+ return orderMenus.entrySet()
+ .stream();
+ }
+
+ public Map<MenuItem, Integer> getOrderMenus() {
+ return Collections.unmodifiableMap(orderMenus);
+ }
+
+ public DiscountDetail getDiscountDetail() {
+ return discountDetail;
+ }
+
+ public GiftMenu getGiftMenu() {
+ return giftMenu;
+ }
+
+ public RewardBadge getRewardBadge() {
+ return rewardBadge;
+ }
+} | Java | ์ด ๋ถ๋ถ๋ getter๋ก ๊บผ๋ด์์ ๊ฒ์ฆํ๊ธฐ๋ณด๋ค ๊ฐ์ฒด ๋ด๋ถ์์ ์ค์ค๋ก๊ฒ์ฆํ๋๋ก ํ๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค |
@@ -0,0 +1,28 @@
+package christmas.model.event;
+
+public enum SpecialDayDiscount {
+ THIRD_DAY(3, 1000),
+ TENTH_DAY(10, 1000),
+ SEVENTEENTH_DAY(17, 1000),
+ TWENTY_FOURTH_DAY(24, 1000),
+ TWENTY_FIFTH_DAY(25, 1000),
+ THIRTY_FIRST_DAY(31, 1000),
+ OTHER_DAY(0, 0),
+ ;
+
+ private final int day;
+ private final int discountPrice;
+
+ SpecialDayDiscount(int day, int discountPrice) {
+ this.day = day;
+ this.discountPrice = discountPrice;
+ }
+
+ public int getDay() {
+ return day;
+ }
+
+ public int getDiscountPrice() {
+ return discountPrice;
+ }
+} | Java | 1000์์ด๋ผ๋ ๋์ผํ ํ ์ธ๊ธ์ก์ ๊ฐ์ง๊ณ ์์ผ๋ List๋ก ๊ด๋ฆฌํ๋ ๋ฐฉ๋ฒ๋ ๊ด์ฐฎ์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,55 @@
+package christmas.model.menu;
+
+import christmas.exception.ExceptionMessage;
+import christmas.exception.PromotionException;
+
+import java.util.Arrays;
+
+public enum MenuItem {
+ APPETIZER_MUSHROOM_SOUP("์์ก์ด์ํ", 6_000, MenuCategory.APPETIZER),
+ APPETIZER_TAPAS("ํํ์ค", 5_500, MenuCategory.APPETIZER),
+ APPETIZER_CAESAR_SALAD("์์ ์๋ฌ๋", 8_000, MenuCategory.APPETIZER),
+
+ MAIN_T_BONE_STEAK("ํฐ๋ณธ์คํ
์ดํฌ", 55_000, MenuCategory.MAIN_COURSE),
+ MAIN_BBQ_RIB("๋ฐ๋นํ๋ฆฝ", 54_000, MenuCategory.MAIN_COURSE),
+ MAIN_SEAFOOD_PASTA("ํด์ฐ๋ฌผํ์คํ", 35_000, MenuCategory.MAIN_COURSE),
+ MAIN_CHRISTMAS_PASTA("ํฌ๋ฆฌ์ค๋ง์คํ์คํ", 25_000, MenuCategory.MAIN_COURSE),
+
+ DESSERT_CHOCO_CAKE("์ด์ฝ์ผ์ดํฌ", 15_000, MenuCategory.DESSERT),
+ DESSERT_ICE_CREAM("์์ด์คํฌ๋ฆผ", 5_000, MenuCategory.DESSERT),
+
+ BEVERAGE_ZERO_COLA("์ ๋ก์ฝ๋ผ", 3_000, MenuCategory.BEVERAGE),
+ BEVERAGE_RED_WINE("๋ ๋์์ธ", 60_000, MenuCategory.BEVERAGE),
+ BEVERAGE_CHAMPAGNE("์ดํ์ธ", 25_000, MenuCategory.BEVERAGE),
+ ;
+
+ private final String itemName;
+ private final int itemPrice;
+ private final MenuCategory menuCategory;
+
+ MenuItem(String itemName, int itemPrice, MenuCategory menuCategory) {
+ this.itemName = itemName;
+ this.itemPrice = itemPrice;
+ this.menuCategory = menuCategory;
+ }
+
+ public static MenuItem findMenuItemByName(String itemName, ExceptionMessage message) {
+ return Arrays.stream(MenuItem.values())
+ .filter(menu -> menu.getItemName().equals(itemName))
+ .findFirst()
+ .orElseThrow(() ->
+ new PromotionException(message));
+ }
+
+ public String getItemName() {
+ return itemName;
+ }
+
+ public int getItemPrice() {
+ return itemPrice;
+ }
+
+ public MenuCategory getMenuCategory() {
+ return menuCategory;
+ }
+} | Java | MenuCategory, MenuItem์์ ์ค๋ณต๋๋ ์์๋ค์ด ์๋๋ฐ ํ๋๋ก ๋ฌถ์ด๋ ๋ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,79 @@
+package christmas.model.menu;
+
+import christmas.exception.ExceptionMessage;
+import christmas.exception.PromotionException;
+
+import java.util.*;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class OrderMenus {
+ private static final int MIN_ORDER_MENU_NUMBER = 1;
+ private static final int MAX_ORDER_MENUS_NUMBER = 20;
+
+ private final Map<MenuItem, Integer> orderMenus;
+
+ public OrderMenus(Map<String, Integer> orderMenus) {
+ this.orderMenus = validateOrderMenusByNames(orderMenus);
+ validateOrderMenus();
+ }
+
+ private Map<MenuItem, Integer> validateOrderMenusByNames(Map<String, Integer> orderMenus) {
+ return generateOrderMenuValues(orderMenus)
+ .collect(Collectors.toUnmodifiableMap(
+ entry -> MenuItem.findMenuItemByName(entry.getKey(), ExceptionMessage.INVALID_INPUT_ORDER),
+ Map.Entry::getValue
+ ));
+ }
+
+ private void validateOrderMenus() {
+ validateOrderNumbers();
+ validateTotalOrderNumbers();
+ validateOrderAllBeverage();
+ }
+
+ private void validateOrderNumbers() {
+ generateOrderMenuValues(orderMenus)
+ .filter(menu ->
+ menu.getValue() < MIN_ORDER_MENU_NUMBER)
+ .findAny()
+ .ifPresent(menuName -> throwInvalidOrderException());
+ }
+
+ private void validateTotalOrderNumbers() {
+ int orderNumber = generateOrderMenuValues(orderMenus)
+ .mapToInt(Map.Entry::getValue)
+ .sum();
+
+ if (orderNumber > MAX_ORDER_MENUS_NUMBER) {
+ throwInvalidOrderException();
+ }
+ }
+
+ private void validateOrderAllBeverage() {
+ boolean allBeverage = generateOrderMenuValues(orderMenus)
+ .allMatch(orderMenu ->
+ orderMenu.getKey().getMenuCategory() == MenuCategory.BEVERAGE);
+
+ if (allBeverage) {
+ throwInvalidOrderException();
+ }
+ }
+
+ private <K, V> Stream<Map.Entry<K, V>> generateOrderMenuValues(Map<K, V> orderMenus) {
+ return orderMenus.entrySet()
+ .stream();
+ }
+
+ private void throwInvalidOrderException() {
+ throw new PromotionException(ExceptionMessage.INVALID_INPUT_ORDER);
+ }
+
+ public Map<String, Integer> getOrderMenus() {
+ Map<String, Integer> menuNames = new HashMap<>();
+ orderMenus.forEach((menuItem, quantity) ->
+ menuNames.put(menuItem.getItemName(), quantity));
+
+ return Collections.unmodifiableMap(menuNames);
+ }
+} | Java | Integer๋ ์์๊ฐ์ ํฌ์ฅํ๋ ๊ฒ์ ์ด๋จ๊น์?? |
@@ -0,0 +1,76 @@
+package christmas.run;
+
+import christmas.controller.PromotionController;
+import christmas.exception.PromotionException;
+import christmas.model.event.dto.EventResultDTO;
+import christmas.model.event.dto.ReservationDateEventDTO;
+import christmas.model.menu.dto.OrderMenusDTO;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+
+import java.util.function.Supplier;
+
+public class PromotionRun {
+ private final PromotionController controller = new PromotionController();
+ private final InputView inputView;
+ private final OutputView outputView;
+
+ public PromotionRun(InputView inputView, OutputView outputView) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ }
+
+ public void runPromotion() {
+ ReservationDateEventDTO dateEventDto = inputCorrectReservationDate();
+ OrderMenusDTO orderMenusDto = inputCorrectOrderMenus();
+ displayEventPreview(dateEventDto);
+
+ EventResultDTO responseDto = applyEventsAndGenerateResult(dateEventDto, orderMenusDto);
+ outputEventResult(responseDto);
+ }
+
+ private ReservationDateEventDTO inputCorrectReservationDate() {
+ outputView.displayStartPromotion();
+
+ return getCorrectResult(this::generateDateEvent);
+ }
+
+ private OrderMenusDTO inputCorrectOrderMenus() {
+ return getCorrectResult(this::receiveMenus);
+ }
+
+ private ReservationDateEventDTO generateDateEvent() {
+ String inputDate = inputView.inputDate();
+
+ return controller.generateEvent(inputDate);
+ }
+
+ private OrderMenusDTO receiveMenus() {
+ String inputMenus = inputView.inputOrderMenus();
+
+ return controller.receiveOrderMenus(inputMenus);
+ }
+
+ private void displayEventPreview(ReservationDateEventDTO dateEventDto) {
+ outputView.displayPreviewEvent(dateEventDto.getDay());
+ }
+
+ private EventResultDTO applyEventsAndGenerateResult(ReservationDateEventDTO dateEventDTO,
+ OrderMenusDTO orderMenusDto) {
+ return controller.applyEvents(dateEventDTO, orderMenusDto);
+ }
+
+ private void outputEventResult(EventResultDTO responseDto) {
+ outputView.outputEventResult(responseDto);
+ }
+
+ private <T> T getCorrectResult(Supplier<T> supplier) {
+ while (true) {
+ try {
+ return supplier.get();
+ } catch (PromotionException e) {
+ outputView.displayException(e);
+ }
+ }
+ }
+} | Java | ํ๋์ฃผ์
๋ณด๋ค ์์ฑ์ ์ฃผ์
์ด ์ ์ง๋ณด์ ๊ด์ ์์ ๋ ์ข์ ๊ฒ ๊ฐ์์.!! |
@@ -0,0 +1,76 @@
+package christmas.run;
+
+import christmas.controller.PromotionController;
+import christmas.exception.PromotionException;
+import christmas.model.event.dto.EventResultDTO;
+import christmas.model.event.dto.ReservationDateEventDTO;
+import christmas.model.menu.dto.OrderMenusDTO;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+
+import java.util.function.Supplier;
+
+public class PromotionRun {
+ private final PromotionController controller = new PromotionController();
+ private final InputView inputView;
+ private final OutputView outputView;
+
+ public PromotionRun(InputView inputView, OutputView outputView) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ }
+
+ public void runPromotion() {
+ ReservationDateEventDTO dateEventDto = inputCorrectReservationDate();
+ OrderMenusDTO orderMenusDto = inputCorrectOrderMenus();
+ displayEventPreview(dateEventDto);
+
+ EventResultDTO responseDto = applyEventsAndGenerateResult(dateEventDto, orderMenusDto);
+ outputEventResult(responseDto);
+ }
+
+ private ReservationDateEventDTO inputCorrectReservationDate() {
+ outputView.displayStartPromotion();
+
+ return getCorrectResult(this::generateDateEvent);
+ }
+
+ private OrderMenusDTO inputCorrectOrderMenus() {
+ return getCorrectResult(this::receiveMenus);
+ }
+
+ private ReservationDateEventDTO generateDateEvent() {
+ String inputDate = inputView.inputDate();
+
+ return controller.generateEvent(inputDate);
+ }
+
+ private OrderMenusDTO receiveMenus() {
+ String inputMenus = inputView.inputOrderMenus();
+
+ return controller.receiveOrderMenus(inputMenus);
+ }
+
+ private void displayEventPreview(ReservationDateEventDTO dateEventDto) {
+ outputView.displayPreviewEvent(dateEventDto.getDay());
+ }
+
+ private EventResultDTO applyEventsAndGenerateResult(ReservationDateEventDTO dateEventDTO,
+ OrderMenusDTO orderMenusDto) {
+ return controller.applyEvents(dateEventDTO, orderMenusDto);
+ }
+
+ private void outputEventResult(EventResultDTO responseDto) {
+ outputView.outputEventResult(responseDto);
+ }
+
+ private <T> T getCorrectResult(Supplier<T> supplier) {
+ while (true) {
+ try {
+ return supplier.get();
+ } catch (PromotionException e) {
+ outputView.displayException(e);
+ }
+ }
+ }
+} | Java | ์ ๋๋ฆญ์ ์ฌ์ฉํ์ ๋ถ๋ถ์ด ์ธ์๊น์ต๋๋ค.! |
@@ -0,0 +1,27 @@
+package christmas.util;
+
+enum EventResultText {
+ ORDER_OUTPUT_REGEX("%s %d%s"),
+ EMPTY_TEXT(""),
+ SPACE(" "),
+ MENU_NUMBER("๊ฐ"),
+ MENU_PRICE_UNIT("์"),
+ CHRISTMAS_D_DAY_DISCOUNT("ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ"),
+ SPECIAL_DISCOUNT("ํน๋ณ ํ ์ธ"),
+ GIFT_EVENT("์ฆ์ ์ด๋ฒคํธ"),
+ NONE_BENEFIT("์์"),
+ DISCOUNT_PRICE("-"),
+ BENEFIT_SEPARATOR(": "),
+ NEW_LINE("\n"),
+ ;
+
+ private final String text;
+
+ EventResultText(String text) {
+ this.text = text;
+ }
+
+ public String getText() {
+ return text;
+ }
+} | Java | ์ฐ๊ด์ฑ์ด ์๋ ์์๋ค์ static final๋ก ๊ด๋ฆฌํ๋ ๊ฒ์ด ๋ ๊ฐ๋
์ฑ ์ธก๋ฉด์์ ์ข๋ค๊ณ ์๊ฐํด์ ! |
@@ -0,0 +1,99 @@
+## ์ฐ์ํ ํ
ํฌ์ฝ์ค ํ๋ฆฌ์ฝ์ค ํฌ๋ฆฌ์ค๋ง์ค ํ๋ก๋ชจ์
+
+### ์งํ๋ฐฉ์
+- ์์ ๋ฉ์์ง ์ถ๋ ฅ
+- ๋ฐฉ๋ฌธ ๋ ์ง ์
๋ ฅ
+- ์ฃผ๋ฌธ ๋ฉ๋ด์ ๊ฐ์ ์
๋ ฅ
+- ์
๋ ฅ ์์ผ ์ด๋ฒคํธ ๋ฉ์์ง ์ถ๋ ฅ
+- ์ด๋ฒคํธ ํํ ์ถ๋ ฅ
+ - ์ฃผ๋ฌธ ๋ฉ๋ด
+ - ํ ์ธ ์ ์ด ์ฃผ๋ฌธ ๊ธ์ก
+ - ์ฆ์ ๋ฉ๋ด ์ฌ๋ถ
+ - ํํ ๋ด์ญ ์ฌ๋ถ
+ - ํ ์ธ ํ ์์ ๊ฒฐ์ ๊ธ์ก
+ - 12์ ์ด๋ฒคํธ ๋ฐฐ์ง ์ฌ๋ถ
+
+### ์ฃผ์ ๊ตฌํ ์ฌํญ
+- [x] ์
๋ ฅ ๋ทฐ ๊ตฌํ
+- [x] ์ถ๋ ฅ ๋ทฐ ๊ตฌํ
+
+- [x] ๋ ์ง ์
๋ ฅ ๋ฐ ์ ์ฅ ๊ฐ์ฒด ๊ตฌํ
+- [x] ๋ ์ง ์
๋ ฅ ์ ๋ ์ง๊ด๋ จ ํด๋น ์ด๋ฒคํธ ํญ๋ชฉ ์ ์ฅ
+ - [x] ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ์ด ๊ธ์ก ํ ์ธ ํญ๋ชฉ
+ - [x] ํ์ผ/์ฃผ๋ง ๊ตฌ๋ถ ํ ์ธ ํ์
ํญ๋ณต
+ - [x] ๋ ์ง๋ ๋ฌ๋ ฅ์ ๋ณ์ ๋ฐ๋ผ ์คํ์
ํ ์ธ ํญ๋ชฉ
+- [x] ๋ ์ง ๊ด๋ จ ์ด๋ฒคํธ ๋ฐํ DTO ๋ฐํ
+
+- [x] ์ฃผ๋ฌธ ๋ฉ๋ด์ ๊ฐ์ ์
๋ ฅ ๋ฐ ์ ์ฅ ๊ฐ์ฒด ๊ตฌํ
+ - [x] ๊ฐ ๋ฉ๋ด๋ฅผ ๊ธฐ๋ณธ ๊ธ์ก๊ณผ ๋ฉ๋ด ๋ช
์ผ๋ก Enum ์ผ๋ก ๊ด๋ฆฌ
+ - [x] ์ฃผ๋ฌธํ ๋ฉ๋ด ์
๋ ฅ์ ๋ํ ์ ํจ์ฑ ๊ฒ์ฌ ์งํ ํ ์ ์ฅ ๊ฐ์ฒด์ ์ ์ฅ
+- [x] ์ฃผ๋ฌธ ๋ฉ๋ด ๋ด์ญ ๋ฐํ DTO ๋ฐํ
+
+- [x] ๋ ์ง ์ด๋ฒคํธ์ ์ฃผ๋ฌธ ๋ฉ๋ด DTO ๋ฅผ ํตํ ์ด๋ฒคํธ ํํ ์ ์ฉ
+- [x] ์ด๋ฒคํธ ์ ์ฉ DTO ๋ฐํ ๋ฐ ์ถ๋ ฅ
+ - [x] ํ ์ธ ์ ๊ธ์ก์ ์ถ๋ ฅ
+ - [x] ํ ์ธ ์ ๊ธ์ก์ ๋ฐ๋ฅธ ์ฆ์ ์ฌ๋ถ ์ถ๋ ฅ
+ - ์ฆ์ ์ฌ๋ถ๊ฐ ์๋ค๋ฉด '์์' ์ถ๋ ฅ
+ - [x] ํํ ๋ด์ญ ์ถ๋ ฅ
+ - ์ ์ฉ๋ ํํ ์๋ค๋ฉด '์์' ์ถ๋ ฅ
+ - [x] ํํ ๊ธ์ก ์ถ๋ ฅ
+ - [x] ์ฆ์ ํํ ๊ธ์ก์ ์ ์ธํ ํ ์ธ ํ ์์ ๊ธ์ก ์ถ๋ ฅ
+ - [x] ์ด ํํ ๊ธ์ก์ ๋ฐ๋ฅธ ์ด๋ฒคํธ ๋ฐฐ์ง ๋ถ์ฌ ์ฌ๋ถ ์ถ๋ ฅ
+ - ์ด๋ฒคํธ ๋ฐฐ์ง๊ฐ ์๋ค๋ฉด '์์' ์ถ๋ ฅ
+
+- ์ถ๊ฐ ๊ตฌํ ์ฌํญ
+ - ์ด๋ฒคํธ ๊ฒฐ๊ณผ ๋๋ฉ์ธ์ ์ ๋ณด๋ฅผ ์ถ๋ ฅ ๋ฌธ์์ด์ผ๋ก ๋ณ๊ฒฝํ์ฌ Builder DTO ์์ฑ/๋ฐํ
+ - ์๋ชป๋ ์
๋ ฅ์ ํตํ ๊ณผ์ ์ ์์ธ ๋ฉ์์ง ์ถ๋ ฅ ๋ฐ ์ฌ์
๋ ฅ
+ - ์ด ์ฃผ๋ฌธ ๋ฉ๋ด ๊ธ์ก์ด 10,000์ ์ดํ์ผ ๊ฒฝ์ฐ ๋ชจ๋ ํ ์ธ ๊ธ์ก 0์ผ๋ก ์ง์
+
+### ์์ธ ์ฒ๋ฆฌ
+- ๋ ์ง ์
๋ ฅ ์์ธ
+ - [x] ์๋ชป๋ ๋ ์ง ์
๋ ฅ์ ๊ฒฝ์ฐ
+ - [x] ๋ ์ง๊ฐ ์ ์ํ์ผ๋ก ๋ณ๊ฒฝ์ด ์๋ ๋
+- ๋ฉ๋ด ์
๋ ฅ ์์ธ
+ - [x] ๋ฉ๋ด ์
๋ ฅ ์ ์ ๊ทํํ์ ํจํด์ด ๋ค๋ฅผ ๊ฒฝ์ฐ (TextProcessor ์ฒ๋ฆฌ)
+ - [x] ์ค๋ณต ๋ฉ๋ด๋ช
์
๋ ฅ์ ๊ฒฝ์ฐ (TextProcessor ์ฒ๋ฆฌ)
+ - [x] ์๋ ๋ฉ๋ด๋ช
์
๋ ฅ์ ๊ฒฝ์ฐ
+ - [x] ์ฃผ๋ฌธ ๋ฉ๋ด์ ๊ฐ์๊ฐ 1๋ณด๋ค ์์ ๋
+ - [x] ์ฃผ๋ฌธ ๋ฉ๋ด๊ฐ 20๊ฐ๋ฅผ ๋์ ๋
+ - [x] ์๋ฃ๋ง ์ฃผ๋ฌธ ์ ์ฃผ๋ฌธ ๋ถ๊ฐ๋ฅ
+
+### ํด๋์ค ๊ตฌ์กฐ
+- InputView : ํ๋ฉด ์
๋ ฅ์ ๋ด๋นํ๋ ๋ทฐ
+ - InputViewMessage : ์
๋ ฅ์ ์ํ ๋ฉ์์ง๋ฅผ ๊ด๋ฆฌํ๋ Enum
+- OutputView : ํ๋ฉด ์ถ๋ ฅ์ ๋ด๋นํ๋ ๋ทฐ
+ - OutputViewMessage : ์ถ๋ ฅ์ ์ํ ๋ฉ์์ง๋ฅผ ๊ด๋ฆฌํ๋ Enum
+- PromotionRun : ๋ทฐ์ ์ปจํธ๋กค๋ฌ๋ฅผ ์ฐ๊ฒฐํ๋ ํด๋์ค๋ก ์์ฒญ ์ ๋ฌ
+- PromotionController : ๋น์ฆ๋์ค ๋ก์ง์ ์คํํ๊ธฐ ์ํด ์์ฒญ์ ์ ๋ฌํ๋ ์ปจํธ๋กค๋ฌ
+- PromotionService : ํ๋ก๋ชจ์
์ ํจ์ฑ ๊ฒ์ฆ์ ๊ฑฐ์น ๊ฐ์ฒด ์์ฑ๊ณผ ๋น์ฆ๋์ค ๋ก์ง์ ์คํํ ์๋น์ค
+- TextProcessor : ์
๋ ฅ๋ฐ์ ๋ฌธ์์ด์ ํน์ ํ์
์ผ๋ก ๋ฐํํ๊ธฐ ์ํ ์๋น์ค
+- OrderMenus : ์ฃผ๋ฌธ ๋ฉ๋ด์ ๊ฐ์ ์ ์ฅํ๋ ํด๋์ค
+ - MenuItem : ๋ฉ๋ด ์ด๋ฆ๊ณผ ๊ฐ๊ฒฉ, ๋ฉ๋ด ์ข
๋ฅ๋ฅผ ์ ์ฅํ๋ Enum
+ - MenuCategory : ๋ฉ๋ด ์ข
๋ฅ๋ฅผ ๊ตฌ๋ถํ๋ Enum
+- ReservationDateEvent : ๋ ์ง ๊ด๋ จ ์ด๋ฒคํธ ์ ์ฅ ํด๋์ค
+ - ReservationDate : ์
๋ ฅ๋ ๋ ์ง๋ฅผ ์ ์ฅํ๊ธฐ ์ํ ํด๋์ค
+ - ChristmasDiscount : ํฌ๋ฆฌ์ค๋ง์ค D-day ํ ์ธ ๊ด๋ฆฌ ํด๋์ค
+ - WeekDiscountType : ์ฃผ๋ง ํ ์ธ, ํ์ผ ํ ์ธ์ ๊ตฌ๋ถํ๋ Enum
+ - SpecialDayDiscount : ํน๋ณ ํ ์ธ ์ผ์๊ฐ ์ ์ฅ๋์ด ์๋ Enum
+- EventResult : ์ ์ฉ ์ค์ธ ๋ชจ๋ ์ด๋ฒคํธ๋ฅผ ์ ์ฅํ๋ ํด๋์ค
+ - DiscountDetail : ์ฃผ๋ฌธ ๊ธ์ก๊ณผ ํ ์ธ, ์์ ๊ธ์ก ๋ฑ์ ๋ณด๊ดํ ํด๋์ค
+ - GiftEvent : ์ฆ์ ์ํ ์ฌ๋ถ๋ฅผ ๊ด๋ฆฌํ๋ Enum
+ - RewardBadge : ์ด๋ฒคํธ ๋ฐฐ์ง๋ฅผ ๊ด๋ฆฌํ๋ Enum
+- PromotionException : ์ง์ ๋ Enum ์์ธ ๋ฉ์์ง๋ฅผ ํตํด ๊ฐ๋ฅผ ๋ด์ IllegalArgumentException ์์ฑ
+ - ExceptionMessage : ์์ธ ๋ฐ์ ๋ฉ์์ง๋ฅผ ๋ณด๊ดํ Enum Class
+- PromotionConverter : Service ์์ Domain to DTO ์ปจ๋ฒํฐ
+- EventResultTextFactory : EventResultDTO ๋ฐํ์ ์ํ ๋ฌธ์์ด ์กฐ์ ์๋น์ค
+ - EventResultText : EventResultDTO ์ ํ์ํ ๋ฌธ์์ด Enum
+- ํ
์คํธ : ํด๋์ค๋ณ ๋ฉ์๋ ๋จ์ ํ
์คํธ ์งํ
+
+### ์ด๋ฒ์ ํ๋ก์ ํธ๋ฅผ ์งํํ๋ฉด์ ๊ณ ๋ฏผํ ์์
+- ํด๋น ๊ธฐ๋ฅ์ ๊ตฌํํ๊ธฐ ์ํ ๊ตฌ์กฐ ์ค๊ณ
+ - ์ดํ ํ์ํ ํด๋์ค๋ค์ ์ถ๊ฐํ๋ฉฐ ์ค๊ณ ๋ณ๊ฒฝ
+- ๋์ผํ ์
๋ ฅ๊ณผ ์ถ๋ ฅ์ ํ๋ ๋ทฐ๋ ์ฑ๊ธํค์ผ๋ก ๊ตฌํ
+- ์
๋ ฅ์ ๋ํ ์ ํจ์ฑ ๊ฒ์ฌ์ ๊ฐ์ฒด ์์ฑ์ ๋ํ ์ ํจ์ฑ ๊ฒ์ฌ ๊ตฌ๋ถ์ ๋ํ ๊ณ ๋ฏผ
+- ์ด๋ฒคํธ ์ ์ฉ ์ ์ด๋ฒคํธ ๋ด์ญ๊ณผ ์ฃผ๋ฌธ ๋ด์ญ์ ์ฌ์ฉํด ๊ฐ์ ์ ์ฅํ๋ ๋ฐฉ๋ฒ์ Service ์์ ์งํํ ์ง ๊ฐ์ฒด ๋ด๋ถ์์ ์งํํ ์ง ๊ณ ๋ฏผ
+- ์ถ๋ ฅ์ ์ํ DTO ์์ฑ์ ๋ํ ๊ณ ๋ฏผ
+ - DTO ๋ฃฐ ์ถ๋ ฅํ๊ณ ํด๋น DTO ํตํด ๋ค์ ์ด๋ฒคํธ ๋ด์ญ ํ์ธํ๋๋ฐ ์์ด DTO ๊ฐ์ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ
+ - EventResultDTO ๋ทฐ์ ์ถ๋ ฅํ ๋ฌธ์์ด์ ๊ฐ์ง๊ณ ์์ DTO ์์ฑ ๋ฐฉ๋ฒ ๊ณ ๋ฏผ ํ Builder, EventResultTextFactory ์ฌ์ฉ
+- ์๋ชป๋ ์
๋ ฅ์ ๋ํ ๋ฉ์๋ ์ฌ์คํ ๋ก์ง์ ์ง๋์ฃผ [zangsu๋](https://github.com/zangsu) ์ฝ๋๋ฆฌ๋ทฐ๋ก ๋ฐฐ์ด Supplier ๋ฐ๋ณต ์ฌ์ฉ
+- ํ
์คํธ ์ฝ๋ mock ๊ฐ์ฒด์ ๋ํ ์ฌ์ฉ๋ฐฉ๋ฒ์ ๋ํ ๊ณ ๋ฏผ
\ No newline at end of file | Unknown | ์ ์ข์ ์๊ฐ์ด๋ค์. ์ดํ ๊ด๋ฆฌ์๋ ์๊ฐํ์ง ์์๋ ๊ฒ ๊ฐ์ต๋๋ค |
@@ -1,7 +1,20 @@
package christmas;
+
+import camp.nextstep.edu.missionutils.Console;
+import christmas.run.PromotionRun;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+
public class Application {
public static void main(String[] args) {
- // TODO: ํ๋ก๊ทธ๋จ ๊ตฌํ
+ try {
+ InputView inputView = SingletonView.getInputView();
+ OutputView outputView = SingletonView.getOutputView();
+ PromotionRun promotionRun = new PromotionRun(inputView, outputView);
+ promotionRun.runPromotion();
+ } finally {
+ Console.close();
+ }
}
} | Java | ํ๋ฒ๋ง ์์ฑ๋๋ฉด ๋๊ณ ์๋ก์ด ๊ฐ์ฒด๋ฅผ ์์ฑํ ํ์๊ฐ ์๊ฒ ๋ค ์ถ์ด ์ ์ฉํ๋๋ฐ ์ปจํธ๋กค๋ฌ, ์๋น์ค ๋ชจ๋ ์ ์ฉํด์ผํ๋ ์ถ๋ค๊ฐ ๋ทฐ๋ง ์์ฑํ๊ฒ ๋์์ต๋๋ค.. |
@@ -0,0 +1,20 @@
+package christmas.exception;
+
+public enum ExceptionMessage {
+ INVALID_INPUT_DATE("์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
+ INVALID_INPUT_ORDER("์ ํจํ์ง ์์ ์ฃผ๋ฌธ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
+ INVALID_MENU_ITEM("ํด๋น ๋ฉ๋ด๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค."),
+ INVALID_WEEK_DISCOUNT_TYPE("์๋ชป๋ ์ฃผ๊ฐ ํ ์ธ ํ์
์
๋๋ค."),
+ ;
+
+ private static final String PREFIX = "[ERROR] ";
+ private final String errorMessage;
+
+ ExceptionMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ public String getErrorMessage() {
+ return PREFIX + errorMessage;
+ }
+} | Java | ์ ํด๋น ์์ธ๋ ์ด๋ฏธ ์ฒ๋ฆฌ๋ ๊ฒฐ๊ณผ DTO ๋ค์ ๊ฐ์ง๊ณ ๋ฐ์๋๋ ์์ธ๋ผ์ ์ ์์ ์ด๋ผ๋ฉด ํฐ์ง์ง ์๋ ์์ธ ์
๋๋ค. ์ผ๋จ ์ ์๊ฐ์ผ๋ก๋ ๋ฌด์จ ์ง์ ํด๋ ์
๋ ฅ์ ๋ํด ํด๋น ์์ธ๋ ํฐ์ง์ง๋ ์์ ๊ฑฐ๋ผ ์๊ฐํ๋๋ฐ ํด๋น ๊ธฐ๋ฅ์์๋ง ํฐ์ง๋ ์์ธ๋ฅผ ๊ตฌ๋ถํ๊ธฐ ์ํด์ ์ฌ์ฉํ์ต๋๋ค! |
@@ -0,0 +1,33 @@
+package christmas.model.event;
+
+import christmas.model.date.ReservationDate;
+
+public class ChristmasDiscount {
+ private static final int FIRST_DAY = 1;
+ private static final int CHRISTMAS_DAY = 25;
+ private static final int BASIC_DISCOUNT = 1000;
+ private static final int PLUS_DISCOUNT = 100;
+ private static final int NONE_DISCOUNT = 0;
+
+ private final int discount;
+
+ public ChristmasDiscount(ReservationDate date) {
+ this.discount = initDiscountAmount(date);
+ }
+
+ private int initDiscountAmount(ReservationDate date) {
+ if (date.day() > CHRISTMAS_DAY) {
+ return NONE_DISCOUNT;
+ }
+
+ return BASIC_DISCOUNT + getPlusDiscount(date.day());
+ }
+
+ private int getPlusDiscount(int day) {
+ return (day - FIRST_DAY) * PLUS_DISCOUNT;
+ }
+
+ public int getDiscount() {
+ return discount;
+ }
+} | Java | ์์ฝ ์ผ์ ๊ฐ์ฒด๋ ์์ฝ๋ ์ผ์์ ๋ํด์๋ง ๊ฐ์ ๊ฐ์ง๊ณ ์์ด ํ ์ธ์ ์ ์ฉํ๊ธฐ ์ํ ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ํด๋น ํ ์ธ ๊ฐ์ฒด๊ฐ ์ํํด์ผ ํ๋ค๊ณ ์๊ฐํด์ ๋ฃ์๋๋ฐ ๊ณ ๋ฏผ์ด ๋๋ค์.. |
@@ -0,0 +1,62 @@
+package christmas.model.event;
+
+import christmas.model.event.dto.ReservationDateEventDTO;
+
+public class DiscountDetail {
+ private final int totalPriceBeforeDiscount;
+ private final int totalPriceAfterDiscount;
+ private final WeekDiscountType weekDiscountType;
+ private final int christmasDiscount;
+ private final int weekTypeDiscount;
+ private final int specialDiscount;
+
+ protected DiscountDetail(ReservationDateEventDTO dateEventDTO, int totalPriceBeforeDiscount, int weekTypeDiscount) {
+ this.totalPriceBeforeDiscount = totalPriceBeforeDiscount;
+ this.weekDiscountType = WeekDiscountType.checkWeekType(dateEventDTO.getDateWeek());
+ this.christmasDiscount = dateEventDTO.getChristmasDiscount();
+ this.specialDiscount = dateEventDTO.getSpecialDiscount();
+ this.weekTypeDiscount = weekTypeDiscount;
+ this.totalPriceAfterDiscount = initTotalPriceAfterDiscount();
+ }
+
+ protected DiscountDetail(ReservationDateEventDTO dateEventDTO, int totalPriceBeforeDiscount) {
+ this.totalPriceBeforeDiscount = totalPriceBeforeDiscount;
+ this.weekDiscountType = WeekDiscountType.checkWeekType(dateEventDTO.getDateWeek());
+ this.christmasDiscount = 0;
+ this.specialDiscount = 0;
+ this.weekTypeDiscount = 0;
+ this.totalPriceAfterDiscount = initTotalPriceAfterDiscount();
+ }
+
+ private int initTotalPriceAfterDiscount() {
+ return totalPriceBeforeDiscount - getTotalDiscount();
+ }
+
+ public int getTotalPriceBeforeDiscount() {
+ return totalPriceBeforeDiscount;
+ }
+
+ public int getTotalPriceAfterDiscount() {
+ return totalPriceAfterDiscount;
+ }
+
+ public int getChristmasDiscount() {
+ return christmasDiscount;
+ }
+
+ public int getSpecialDiscount() {
+ return specialDiscount;
+ }
+
+ public int getWeekTypeDiscount() {
+ return weekTypeDiscount;
+ }
+
+ public WeekDiscountType getWeekDiscountType() {
+ return weekDiscountType;
+ }
+
+ public int getTotalDiscount() {
+ return christmasDiscount + weekTypeDiscount + specialDiscount;
+ }
+} | Java | ๊ฐ์ฒด๊ฐ ๊ฐ์ง๊ณ ์๋ ์ํ์ ๊ฐ์ฒด๋ฅผ ํํํ๋ ค ํ๋ค๋ณด๋ ์ด๋ ๊ฒ ๋์๋๋ฐ ์์ง๋ ๋ฉ์๋๋ก ๋ฉ์์ง๋ฅผ ์ ๋ฌํ๋ ๋ฐฉ๋ฒ์ ์์ง ๋ฏ์ ๊ฒ ๊ฐ์ต๋๋ค.. ์ค๊ฐ์ค๊ฐ ์ธ์งํ๋ คํด๋ ๋์น๋ ๋ถ๋ถ์ด ๋ง๋ค์.. |
@@ -0,0 +1,62 @@
+package christmas.model.event;
+
+import christmas.model.event.dto.ReservationDateEventDTO;
+
+public class DiscountDetail {
+ private final int totalPriceBeforeDiscount;
+ private final int totalPriceAfterDiscount;
+ private final WeekDiscountType weekDiscountType;
+ private final int christmasDiscount;
+ private final int weekTypeDiscount;
+ private final int specialDiscount;
+
+ protected DiscountDetail(ReservationDateEventDTO dateEventDTO, int totalPriceBeforeDiscount, int weekTypeDiscount) {
+ this.totalPriceBeforeDiscount = totalPriceBeforeDiscount;
+ this.weekDiscountType = WeekDiscountType.checkWeekType(dateEventDTO.getDateWeek());
+ this.christmasDiscount = dateEventDTO.getChristmasDiscount();
+ this.specialDiscount = dateEventDTO.getSpecialDiscount();
+ this.weekTypeDiscount = weekTypeDiscount;
+ this.totalPriceAfterDiscount = initTotalPriceAfterDiscount();
+ }
+
+ protected DiscountDetail(ReservationDateEventDTO dateEventDTO, int totalPriceBeforeDiscount) {
+ this.totalPriceBeforeDiscount = totalPriceBeforeDiscount;
+ this.weekDiscountType = WeekDiscountType.checkWeekType(dateEventDTO.getDateWeek());
+ this.christmasDiscount = 0;
+ this.specialDiscount = 0;
+ this.weekTypeDiscount = 0;
+ this.totalPriceAfterDiscount = initTotalPriceAfterDiscount();
+ }
+
+ private int initTotalPriceAfterDiscount() {
+ return totalPriceBeforeDiscount - getTotalDiscount();
+ }
+
+ public int getTotalPriceBeforeDiscount() {
+ return totalPriceBeforeDiscount;
+ }
+
+ public int getTotalPriceAfterDiscount() {
+ return totalPriceAfterDiscount;
+ }
+
+ public int getChristmasDiscount() {
+ return christmasDiscount;
+ }
+
+ public int getSpecialDiscount() {
+ return specialDiscount;
+ }
+
+ public int getWeekTypeDiscount() {
+ return weekTypeDiscount;
+ }
+
+ public WeekDiscountType getWeekDiscountType() {
+ return weekDiscountType;
+ }
+
+ public int getTotalDiscount() {
+ return christmasDiscount + weekTypeDiscount + specialDiscount;
+ }
+} | Java | ์ฌ๋ฌ ๊ฐ์ฒด๋ฅผ ์์ฑํ๊ณ static์ผ๋ก ๊ฐ์ฒด๋ฅผ ์์ฑํ๋ ๋ฐฉ๋ฒ๋ณด๋ค๋ ์ ๋ ๊ฐ์ธ์ ์ผ๋ก ํด๋น ๊ธฐ๋ฅ์ ํ ์ธ์ด ์์ ๊ฒฝ์ฐ์ ๊ฐ์ฒด๋ฅผ ์ค๋ฒ๋ก๋ฉ์ ํตํด ์์ฑํ๋๊ฒ ์ข๋ค๊ณ ์๊ฐ๋ฉ๋๋ค |
@@ -0,0 +1,91 @@
+package christmas.model.event;
+
+import christmas.model.event.dto.ReservationDateEventDTO;
+import christmas.model.menu.MenuItem;
+
+import java.util.*;
+import java.util.stream.Stream;
+
+public class EventResult {
+ private static final int MIN_EVENT_AMOUNT = 10_000;
+ private static final int GIFT_AMOUNT = 120_000;
+
+ private final Map<MenuItem, Integer> orderMenus;
+ private final DiscountDetail discountDetail;
+ private final GiftMenu giftMenu;
+ private final RewardBadge rewardBadge;
+
+ public EventResult(ReservationDateEventDTO dateEventDTO, Map<MenuItem, Integer> orderMenus) {
+ this.orderMenus = orderMenus;
+ this.discountDetail = initDiscountDetail(dateEventDTO);
+ this.giftMenu = initGiftMenu();
+ this.rewardBadge = initRewardBadge();
+ }
+
+ private DiscountDetail initDiscountDetail(ReservationDateEventDTO dateEventDTO) {
+ int totalPriceBeforeDiscount = getTotalPriceBeforeDiscount();
+ if (totalPriceBeforeDiscount < MIN_EVENT_AMOUNT) {
+ return new DiscountDetail(dateEventDTO, totalPriceBeforeDiscount);
+ }
+ int weekDiscount = calculateWeekDiscount(dateEventDTO);
+
+ return new DiscountDetail(dateEventDTO, totalPriceBeforeDiscount, weekDiscount);
+ }
+
+ private GiftMenu initGiftMenu() {
+ if (discountDetail.getTotalPriceBeforeDiscount() < GIFT_AMOUNT) {
+ return GiftMenu.NONE;
+ }
+
+ return GiftMenu.CHAMPAGNE;
+ }
+
+ private RewardBadge initRewardBadge() {
+ int benefit = discountDetail.getTotalDiscount() + giftMenu.getGiftPrice();
+
+ return Arrays.stream(RewardBadge.values())
+ .filter(badge ->
+ benefit >= badge.getBenefit())
+ .max(Comparator.comparingInt(RewardBadge::getBenefit))
+ .orElse(RewardBadge.NONE);
+ }
+
+ private int getTotalPriceBeforeDiscount() {
+ return generateOrderMenuEntry(orderMenus)
+ .mapToInt(menu ->
+ menu.getKey().getItemPrice() * menu.getValue())
+ .sum();
+ }
+
+ private int calculateWeekDiscount(ReservationDateEventDTO dateEventDTO) {
+ WeekDiscountType type = WeekDiscountType.checkWeekType(dateEventDTO.getDateWeek());
+
+ return generateOrderMenuEntry(orderMenus)
+ .filter(menu ->
+ menu.getKey().getMenuCategory() == type.getDiscountCategory())
+ .mapToInt(menu ->
+ menu.getValue() * type.getDiscountPrice())
+ .sum();
+ }
+
+ private <K, V> Stream<Map.Entry<K, V>> generateOrderMenuEntry(Map<K, V> orderMenus) {
+ return orderMenus.entrySet()
+ .stream();
+ }
+
+ public Map<MenuItem, Integer> getOrderMenus() {
+ return Collections.unmodifiableMap(orderMenus);
+ }
+
+ public DiscountDetail getDiscountDetail() {
+ return discountDetail;
+ }
+
+ public GiftMenu getGiftMenu() {
+ return giftMenu;
+ }
+
+ public RewardBadge getRewardBadge() {
+ return rewardBadge;
+ }
+} | Java | ๊ทธ ๋ถ๋ถ์ @Dongwoongkim ๋์ ์ฝ๋๋ฅผ ๋ณด๊ณ ํ์คํ ๊ทธ๋ ๋ค๊ณ ๋๊ปด์ก๋ ๊ฒ ๊ฐ์ต๋๋ค. ํด๋น ๊ฐ์ฒด ์์ ์์ด์ผํ๋ค๊ณ ๋ฐ๋ผ๋ณด๋ ๊ทธ๋ ๊ฒ ์๊ฐ์ ๋ชปํ๋ ๊ฒ ๊ฐ์์.. EventResult๋ฅผ ํ๋ผ๋ฏธํฐ๋ก ๊ฐ์ฒด๋ฅผ ์์ฑํ๋ ๋ฐฉ๋ฒ์ด ์ ๋ ๋ ์ฌ๋ฐ๋ฅธ ๊ฒ ๊ฐ์ต๋๋ค |
@@ -0,0 +1,28 @@
+package christmas.model.event;
+
+public enum SpecialDayDiscount {
+ THIRD_DAY(3, 1000),
+ TENTH_DAY(10, 1000),
+ SEVENTEENTH_DAY(17, 1000),
+ TWENTY_FOURTH_DAY(24, 1000),
+ TWENTY_FIFTH_DAY(25, 1000),
+ THIRTY_FIRST_DAY(31, 1000),
+ OTHER_DAY(0, 0),
+ ;
+
+ private final int day;
+ private final int discountPrice;
+
+ SpecialDayDiscount(int day, int discountPrice) {
+ this.day = day;
+ this.discountPrice = discountPrice;
+ }
+
+ public int getDay() {
+ return day;
+ }
+
+ public int getDiscountPrice() {
+ return discountPrice;
+ }
+} | Java | ์ข์ ์๊ฐ์
๋๋ค! enum์ ์๋ฃ๊ตฌ์กฐ๋ฅผ ๋ฃ์ ์๊ฐ์ ๋ชปํ๋ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,79 @@
+package christmas.model.menu;
+
+import christmas.exception.ExceptionMessage;
+import christmas.exception.PromotionException;
+
+import java.util.*;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class OrderMenus {
+ private static final int MIN_ORDER_MENU_NUMBER = 1;
+ private static final int MAX_ORDER_MENUS_NUMBER = 20;
+
+ private final Map<MenuItem, Integer> orderMenus;
+
+ public OrderMenus(Map<String, Integer> orderMenus) {
+ this.orderMenus = validateOrderMenusByNames(orderMenus);
+ validateOrderMenus();
+ }
+
+ private Map<MenuItem, Integer> validateOrderMenusByNames(Map<String, Integer> orderMenus) {
+ return generateOrderMenuValues(orderMenus)
+ .collect(Collectors.toUnmodifiableMap(
+ entry -> MenuItem.findMenuItemByName(entry.getKey(), ExceptionMessage.INVALID_INPUT_ORDER),
+ Map.Entry::getValue
+ ));
+ }
+
+ private void validateOrderMenus() {
+ validateOrderNumbers();
+ validateTotalOrderNumbers();
+ validateOrderAllBeverage();
+ }
+
+ private void validateOrderNumbers() {
+ generateOrderMenuValues(orderMenus)
+ .filter(menu ->
+ menu.getValue() < MIN_ORDER_MENU_NUMBER)
+ .findAny()
+ .ifPresent(menuName -> throwInvalidOrderException());
+ }
+
+ private void validateTotalOrderNumbers() {
+ int orderNumber = generateOrderMenuValues(orderMenus)
+ .mapToInt(Map.Entry::getValue)
+ .sum();
+
+ if (orderNumber > MAX_ORDER_MENUS_NUMBER) {
+ throwInvalidOrderException();
+ }
+ }
+
+ private void validateOrderAllBeverage() {
+ boolean allBeverage = generateOrderMenuValues(orderMenus)
+ .allMatch(orderMenu ->
+ orderMenu.getKey().getMenuCategory() == MenuCategory.BEVERAGE);
+
+ if (allBeverage) {
+ throwInvalidOrderException();
+ }
+ }
+
+ private <K, V> Stream<Map.Entry<K, V>> generateOrderMenuValues(Map<K, V> orderMenus) {
+ return orderMenus.entrySet()
+ .stream();
+ }
+
+ private void throwInvalidOrderException() {
+ throw new PromotionException(ExceptionMessage.INVALID_INPUT_ORDER);
+ }
+
+ public Map<String, Integer> getOrderMenus() {
+ Map<String, Integer> menuNames = new HashMap<>();
+ orderMenus.forEach((menuItem, quantity) ->
+ menuNames.put(menuItem.getItemName(), quantity));
+
+ return Collections.unmodifiableMap(menuNames);
+ }
+} | Java | ๊ฐ์๋ง์ ๊ฐ์ง๊ณ ์๋ ๊ฐ์ฒด๋ค ๋ณด๋ ํด๋์ค๊ฐ ๋ง์์ ธ ๋ฌด๊ฑฐ์์ง ๊ฒ ๊ฐ์ ์ฌ์ฉํ์ง ์์๋๋ฐ ๋ญ๊ฐ ๋ ๋์์ง๋ ๊ณ ๋ฏผ์ด ๋๋ค์.. |
@@ -0,0 +1,76 @@
+package christmas.run;
+
+import christmas.controller.PromotionController;
+import christmas.exception.PromotionException;
+import christmas.model.event.dto.EventResultDTO;
+import christmas.model.event.dto.ReservationDateEventDTO;
+import christmas.model.menu.dto.OrderMenusDTO;
+import christmas.view.InputView;
+import christmas.view.OutputView;
+
+import java.util.function.Supplier;
+
+public class PromotionRun {
+ private final PromotionController controller = new PromotionController();
+ private final InputView inputView;
+ private final OutputView outputView;
+
+ public PromotionRun(InputView inputView, OutputView outputView) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ }
+
+ public void runPromotion() {
+ ReservationDateEventDTO dateEventDto = inputCorrectReservationDate();
+ OrderMenusDTO orderMenusDto = inputCorrectOrderMenus();
+ displayEventPreview(dateEventDto);
+
+ EventResultDTO responseDto = applyEventsAndGenerateResult(dateEventDto, orderMenusDto);
+ outputEventResult(responseDto);
+ }
+
+ private ReservationDateEventDTO inputCorrectReservationDate() {
+ outputView.displayStartPromotion();
+
+ return getCorrectResult(this::generateDateEvent);
+ }
+
+ private OrderMenusDTO inputCorrectOrderMenus() {
+ return getCorrectResult(this::receiveMenus);
+ }
+
+ private ReservationDateEventDTO generateDateEvent() {
+ String inputDate = inputView.inputDate();
+
+ return controller.generateEvent(inputDate);
+ }
+
+ private OrderMenusDTO receiveMenus() {
+ String inputMenus = inputView.inputOrderMenus();
+
+ return controller.receiveOrderMenus(inputMenus);
+ }
+
+ private void displayEventPreview(ReservationDateEventDTO dateEventDto) {
+ outputView.displayPreviewEvent(dateEventDto.getDay());
+ }
+
+ private EventResultDTO applyEventsAndGenerateResult(ReservationDateEventDTO dateEventDTO,
+ OrderMenusDTO orderMenusDto) {
+ return controller.applyEvents(dateEventDTO, orderMenusDto);
+ }
+
+ private void outputEventResult(EventResultDTO responseDto) {
+ outputView.outputEventResult(responseDto);
+ }
+
+ private <T> T getCorrectResult(Supplier<T> supplier) {
+ while (true) {
+ try {
+ return supplier.get();
+ } catch (PromotionException e) {
+ outputView.displayException(e);
+ }
+ }
+ }
+} | Java | ํด๋น ๋ถ๋ถ์ ์ ๋ ์ด์ ์ฝ๋๋ฆฌ๋ทฐ๋ฅผ ํตํด ๋ฐฐ์ด ๊ตฌํ ๋ฐฉ๋ฒ์ธ๋ฐ ์ข์ ๋ฐฉ๋ฒ์ธ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,27 @@
+package christmas.util;
+
+enum EventResultText {
+ ORDER_OUTPUT_REGEX("%s %d%s"),
+ EMPTY_TEXT(""),
+ SPACE(" "),
+ MENU_NUMBER("๊ฐ"),
+ MENU_PRICE_UNIT("์"),
+ CHRISTMAS_D_DAY_DISCOUNT("ํฌ๋ฆฌ์ค๋ง์ค ๋๋ฐ์ด ํ ์ธ"),
+ SPECIAL_DISCOUNT("ํน๋ณ ํ ์ธ"),
+ GIFT_EVENT("์ฆ์ ์ด๋ฒคํธ"),
+ NONE_BENEFIT("์์"),
+ DISCOUNT_PRICE("-"),
+ BENEFIT_SEPARATOR(": "),
+ NEW_LINE("\n"),
+ ;
+
+ private final String text;
+
+ EventResultText(String text) {
+ this.text = text;
+ }
+
+ public String getText() {
+ return text;
+ }
+} | Java | ๊ฒฐ๊ณผ ๋ฌธ์์ด์ ์ถ๋ ฅํด์ฃผ๊ธฐ ์ํ ์์๋ค์ ๋ฌถ์ด ๋ Enum ์
๋๋ค. ๋ค๋ฅธ ๊ณณ์์ ์ฌ์ฉ๋์ง๋ ์์ ๊ฒ ๊ฐ์ default๋ก enum์ ์ฌ์ฉํ์ด์ |
@@ -0,0 +1,62 @@
+package christmas.model.event;
+
+import christmas.model.event.dto.ReservationDateEventDTO;
+
+public class DiscountDetail {
+ private final int totalPriceBeforeDiscount;
+ private final int totalPriceAfterDiscount;
+ private final WeekDiscountType weekDiscountType;
+ private final int christmasDiscount;
+ private final int weekTypeDiscount;
+ private final int specialDiscount;
+
+ protected DiscountDetail(ReservationDateEventDTO dateEventDTO, int totalPriceBeforeDiscount, int weekTypeDiscount) {
+ this.totalPriceBeforeDiscount = totalPriceBeforeDiscount;
+ this.weekDiscountType = WeekDiscountType.checkWeekType(dateEventDTO.getDateWeek());
+ this.christmasDiscount = dateEventDTO.getChristmasDiscount();
+ this.specialDiscount = dateEventDTO.getSpecialDiscount();
+ this.weekTypeDiscount = weekTypeDiscount;
+ this.totalPriceAfterDiscount = initTotalPriceAfterDiscount();
+ }
+
+ protected DiscountDetail(ReservationDateEventDTO dateEventDTO, int totalPriceBeforeDiscount) {
+ this.totalPriceBeforeDiscount = totalPriceBeforeDiscount;
+ this.weekDiscountType = WeekDiscountType.checkWeekType(dateEventDTO.getDateWeek());
+ this.christmasDiscount = 0;
+ this.specialDiscount = 0;
+ this.weekTypeDiscount = 0;
+ this.totalPriceAfterDiscount = initTotalPriceAfterDiscount();
+ }
+
+ private int initTotalPriceAfterDiscount() {
+ return totalPriceBeforeDiscount - getTotalDiscount();
+ }
+
+ public int getTotalPriceBeforeDiscount() {
+ return totalPriceBeforeDiscount;
+ }
+
+ public int getTotalPriceAfterDiscount() {
+ return totalPriceAfterDiscount;
+ }
+
+ public int getChristmasDiscount() {
+ return christmasDiscount;
+ }
+
+ public int getSpecialDiscount() {
+ return specialDiscount;
+ }
+
+ public int getWeekTypeDiscount() {
+ return weekTypeDiscount;
+ }
+
+ public WeekDiscountType getWeekDiscountType() {
+ return weekDiscountType;
+ }
+
+ public int getTotalDiscount() {
+ return christmasDiscount + weekTypeDiscount + specialDiscount;
+ }
+} | Java | ํ๋๋ก ๊ฐ์ง๊ณ ์๋๊ฒ ์ฌ๋ฌ๋ฒ ํธ์ถ ๋ ๊ฒฝ์ฐ ๋ฐ์ดํฐ๋ง ๊ฐ์ง๊ณ ์ค๋ ๊ฒ์ด ์ข๋ค ์๊ฐํด์ ํด๋น ๋ฐฉ์์ผ๋ก ์ฌ์ฉํ๋ ๊ฒ์ด ์ข๋ค ์๊ฐํ๋๋ฐ ๋ช๋ช ํ๋๋ ๋ฉ์๋๋ก ํด๋น ํ๋๋ง์ ๊ฐ์ง๊ณ ๋ฐํํ ์ ์์ ๊ฒ ๊ฐ๋ค์ |
@@ -0,0 +1,105 @@
+package christmas.model.event.dto;
+
+public class EventResultDTO {
+ private final String orderMenus;
+ private final String totalPriceBeforeDiscount;
+ private final String giftMenu;
+ private final String benefitHistory;
+ private final String totalBenefit;
+ private final String totalPriceAfterDiscount;
+ private final String rewardBadge;
+
+ private EventResultDTO(Builder builder) {
+ this.orderMenus = builder.orderMenus;
+ this.totalPriceBeforeDiscount = builder.totalPriceBeforeDiscount;
+ this.giftMenu = builder.giftMenu;
+ this.benefitHistory = builder.benefitHistory;
+ this.totalBenefit = builder.totalBenefit;
+ this.totalPriceAfterDiscount = builder.totalPriceAfterDiscount;
+ this.rewardBadge = builder.rewardBadge;
+ }
+
+ public static class Builder {
+ private String orderMenus;
+ private String totalPriceBeforeDiscount;
+ private String giftMenu;
+ private String benefitHistory;
+ private String totalBenefit;
+ private String totalPriceAfterDiscount;
+ private String rewardBadge;
+
+ public Builder() {
+ }
+
+ public Builder orderMenus(String orderMenus) {
+ this.orderMenus = orderMenus;
+ return this;
+ }
+
+ public Builder totalPriceBeforeDiscount(String totalPriceBeforeDiscount) {
+ this.totalPriceBeforeDiscount = totalPriceBeforeDiscount;
+ return this;
+ }
+
+ public Builder giftMenu(String giftMenu) {
+ this.giftMenu = giftMenu;
+ return this;
+ }
+
+ public Builder benefitHistory(String benefitHistory) {
+ this.benefitHistory = benefitHistory;
+ return this;
+ }
+
+ public Builder totalBenefit(String totalBenefit) {
+ this.totalBenefit = totalBenefit;
+ return this;
+ }
+
+ public Builder totalPriceAfterDiscount(String totalPriceAfterDiscount) {
+ this.totalPriceAfterDiscount = totalPriceAfterDiscount;
+ return this;
+ }
+
+ public Builder rewardBadge(String rewardBadge) {
+ this.rewardBadge = rewardBadge;
+ return this;
+ }
+
+ public EventResultDTO build() {
+ return new EventResultDTO(this);
+ }
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public String getOrderMenus() {
+ return orderMenus;
+ }
+
+ public String getTotalPriceBeforeDiscount() {
+ return totalPriceBeforeDiscount;
+ }
+
+ public String getGiftMenu() {
+ return giftMenu;
+ }
+
+ public String getBenefitHistory() {
+ return benefitHistory;
+ }
+
+ public String getTotalBenefit() {
+ return totalBenefit;
+ }
+
+ public String getTotalPriceAfterDiscount() {
+ return totalPriceAfterDiscount;
+ }
+
+ public String getRewardBadge() {
+ return rewardBadge;
+ }
+} | Java | ๋น๋ ํด๋์ค๋ฅผ ์ฌ์ฉํ์ฌ ์ธ์คํด์ค๋ฅผ ์์ฑํ๋ฉด null ์ธ ๊ฐ์ด ์ฌ ์ ๋ ์์ํ
๋ฐ ์ ๋ถ ๋ค ํ์ํด์ด๋ ๋ณ์๋ค์ธ๋ฐ ์์ฑ์๋ฅผ ์ด์ฉํ์ง ์๊ณ ๋น๋ํด๋์ค๋ฅผ ํ์ฉํ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,55 @@
+package christmas.model.menu;
+
+import christmas.exception.ExceptionMessage;
+import christmas.exception.PromotionException;
+
+import java.util.Arrays;
+
+public enum MenuItem {
+ APPETIZER_MUSHROOM_SOUP("์์ก์ด์ํ", 6_000, MenuCategory.APPETIZER),
+ APPETIZER_TAPAS("ํํ์ค", 5_500, MenuCategory.APPETIZER),
+ APPETIZER_CAESAR_SALAD("์์ ์๋ฌ๋", 8_000, MenuCategory.APPETIZER),
+
+ MAIN_T_BONE_STEAK("ํฐ๋ณธ์คํ
์ดํฌ", 55_000, MenuCategory.MAIN_COURSE),
+ MAIN_BBQ_RIB("๋ฐ๋นํ๋ฆฝ", 54_000, MenuCategory.MAIN_COURSE),
+ MAIN_SEAFOOD_PASTA("ํด์ฐ๋ฌผํ์คํ", 35_000, MenuCategory.MAIN_COURSE),
+ MAIN_CHRISTMAS_PASTA("ํฌ๋ฆฌ์ค๋ง์คํ์คํ", 25_000, MenuCategory.MAIN_COURSE),
+
+ DESSERT_CHOCO_CAKE("์ด์ฝ์ผ์ดํฌ", 15_000, MenuCategory.DESSERT),
+ DESSERT_ICE_CREAM("์์ด์คํฌ๋ฆผ", 5_000, MenuCategory.DESSERT),
+
+ BEVERAGE_ZERO_COLA("์ ๋ก์ฝ๋ผ", 3_000, MenuCategory.BEVERAGE),
+ BEVERAGE_RED_WINE("๋ ๋์์ธ", 60_000, MenuCategory.BEVERAGE),
+ BEVERAGE_CHAMPAGNE("์ดํ์ธ", 25_000, MenuCategory.BEVERAGE),
+ ;
+
+ private final String itemName;
+ private final int itemPrice;
+ private final MenuCategory menuCategory;
+
+ MenuItem(String itemName, int itemPrice, MenuCategory menuCategory) {
+ this.itemName = itemName;
+ this.itemPrice = itemPrice;
+ this.menuCategory = menuCategory;
+ }
+
+ public static MenuItem findMenuItemByName(String itemName, ExceptionMessage message) {
+ return Arrays.stream(MenuItem.values())
+ .filter(menu -> menu.getItemName().equals(itemName))
+ .findFirst()
+ .orElseThrow(() ->
+ new PromotionException(message));
+ }
+
+ public String getItemName() {
+ return itemName;
+ }
+
+ public int getItemPrice() {
+ return itemPrice;
+ }
+
+ public MenuCategory getMenuCategory() {
+ return menuCategory;
+ }
+} | Java | ๋ฉ๋ด ์์ดํ
CRUD API ๋ฅผ ๋ง๋ค๋ enum ์ผ๋ก ํ๊ฒ ๋๋ฉด ์ถ๊ฐ์ ๋ํด ํ์ฅ์ฑ์ด ๋จ์ด์ง๋๊ฒ์ด ์๋๊ฐ ์๊ฐ์ด๋ญ๋๋ค! |
@@ -0,0 +1,57 @@
+package christmas.model.event;
+
+import christmas.model.date.ReservationDate;
+
+import java.util.Arrays;
+
+public class ReservationDateEvent {
+ private static final int WEEK = 7;
+ private static final int FRIDAY = 2;
+ private static final int SATURDAY = 3;
+
+ private final ReservationDate reservationDate;
+ private final ChristmasDiscount christmasDiscount;
+ private final WeekDiscountType discountDateWeek;
+ private final SpecialDayDiscount specialDiscountDate;
+
+ public ReservationDateEvent(int day) {
+ this.reservationDate = new ReservationDate(day);
+ this.christmasDiscount = new ChristmasDiscount(reservationDate);
+ this.discountDateWeek = initDiscountDateWeek(reservationDate);
+ this.specialDiscountDate = initSpecialDiscountDate(reservationDate);
+ }
+
+ private WeekDiscountType initDiscountDateWeek(ReservationDate reservationDate) {
+ if (reservationDate.day() % WEEK == FRIDAY ||
+ reservationDate.day() % WEEK == SATURDAY) {
+
+ return WeekDiscountType.WEEKEND;
+ }
+
+ return WeekDiscountType.WEEKDAY;
+ }
+
+ private SpecialDayDiscount initSpecialDiscountDate(ReservationDate reservationDate) {
+ return Arrays.stream(SpecialDayDiscount.values())
+ .filter(specialDay ->
+ reservationDate.day() == specialDay.getDay())
+ .findFirst()
+ .orElse(SpecialDayDiscount.OTHER_DAY);
+ }
+
+ public ReservationDate getReservationDate() {
+ return reservationDate;
+ }
+
+ public ChristmasDiscount getChristmasDiscount() {
+ return christmasDiscount;
+ }
+
+ public WeekDiscountType getDiscountDateWeek() {
+ return discountDateWeek;
+ }
+
+ public SpecialDayDiscount getSpecialDiscountDate() {
+ return specialDiscountDate;
+ }
+} | Java | ์ด๋ ๊ฒ ๋๋ฉด ์ด๋ฒคํธ๊ฐ ์๋ฐฑ๊ฐ๊ฐ ๋๋ฉด ์๋ฐฑ๊ฐ๋ฅผ ์ง์ ๋ค ๊ตฌํํด์ค์ผ ๋์ ๋นํจ์จ์ ์ธ๊ฒ ๊ฐ์ต๋๋ค!
๋ชจ๋ ํ ์ธ์ ์ ์ฉํ๋ ๊ฒ์ด๋ inteface Discount ๋ฅผ ๋ง๋ค์ด
```
Discount ๋ฅผ ๊ตฌํํ ReservationDate implements Discount
ChristmasDiscount implements Discount ........
```
์ด๋ ๊ฒ ๋ง๋ค์ด์ List<DIscount> discountList ์ด๋ฐ์์ผ๋ก ๋ง๋ค์ด์ ๊ณตํตํจ์ ๋ถ๋ถ๋ง ๋ก์ง์ ๋ฃ์ด์ฃผ์๋ฉด ๊ด๋ฆฌ๊ฐ ์ฌ์ธ๊ฒ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,58 @@
+package christmas.domain;
+
+import java.time.DayOfWeek;
+import java.time.LocalDate;
+
+public class Date {
+ public static final String DATE_RE_READ_REQUEST_MESSAGE = "์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final LocalDate CHRISTMAS_DAY = LocalDate.of(2023, 12, 25);
+ private static final int YEAR = 2023;
+ private static final int MONTH = 12;
+ private static final int DATE_MIN_NUMBER = 1;
+ private static final int DATE_MAX_NUMBER = 31;
+
+ private final int dayNumber;
+
+ public Date(int dayNumber) {
+ validateRange(dayNumber);
+ this.dayNumber = dayNumber;
+ }
+
+ private void validateRange(int dayNumber) {
+ if ((dayNumber < DATE_MIN_NUMBER) || (dayNumber > DATE_MAX_NUMBER)) {
+ throw new IllegalArgumentException(DATE_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ public boolean isDDayDiscountActive() {
+ LocalDate localDate = LocalDate.of(YEAR, MONTH, dayNumber);
+
+ return localDate.isBefore(CHRISTMAS_DAY.plusDays(1));
+ }
+
+ public boolean isWeekdayDiscountActive() {
+ LocalDate localDate = LocalDate.of(YEAR, MONTH, dayNumber);
+ DayOfWeek day = localDate.getDayOfWeek();
+
+ return (day.equals(DayOfWeek.MONDAY) || day.equals(DayOfWeek.TUESDAY) || day.equals(DayOfWeek.WEDNESDAY)
+ || day.equals(DayOfWeek.THURSDAY) || day.equals(DayOfWeek.SUNDAY));
+ }
+
+ public boolean isWeekendDiscountActive() {
+ LocalDate localDate = LocalDate.of(YEAR, MONTH, dayNumber);
+ DayOfWeek day = localDate.getDayOfWeek();
+
+ return (day.equals(DayOfWeek.FRIDAY) || day.equals(DayOfWeek.SATURDAY));
+ }
+
+ public boolean isSpecialDiscountActive() {
+ LocalDate localDate = LocalDate.of(YEAR, MONTH, dayNumber);
+ DayOfWeek day = localDate.getDayOfWeek();
+
+ return (day.equals(DayOfWeek.SUNDAY) || localDate.equals(CHRISTMAS_DAY));
+ }
+
+ public int getDayNumber() {
+ return dayNumber;
+ }
+}
\ No newline at end of file | Java | (์ด๋ฐ ๋ฐฉ๋ฒ๋ ์์ด์!)
```suggestion
try {
LocalDate.of(YEAR, MONTH, dayNumber);
} catch (NumberFormatException exception) {
throw new IllegalArgumentException(DATE_RE_READ_REQUEST_MESSAGE);
}
```
์ด๋ฐ์์ผ๋ก LocalDate๋ฅผ ํ์ฉํ๋ ๋ฐฉ๋ฒ๋ ์์ต๋๋ค! |
@@ -0,0 +1,100 @@
+package christmas.domain;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class EventProcess {
+ private static final int MINIMUM_TOTAL_ORDER_PRICE_FOR_GIFT = 120000;
+ private static final int MINIMUM_TOTAL_ORDER_PRICE_FOR_ALL_EVENT = 10000;
+ private static final int D_DAY_DISCOUNT_AMOUNT_PER_DAY = 100;
+ private static final int D_DAY_DISCOUNT_DEFAULT_AMOUNT = 1000;
+ private static final int FIRST_DAY_NUMBER = 1;
+ private static final int WEEKDAY_DESSERT_DISCOUNT_AMOUNT = 2023;
+ private static final int WEEKEND_MAIN_DISCOUNT_AMOUNT = 2023;
+ private static final int SPECIAL_DISCOUNT_AMOUNT = 1000;
+
+ public EventResult takeAllBenefit(Date date, Order order) {
+ Map<BenefitType, Integer> allBenefit = new HashMap<>();
+ allBenefit.put(BenefitType.GIFT, takeGift(order));
+ allBenefit.put(BenefitType.D_DAY, takeDDayDiscount(date));
+ allBenefit.put(BenefitType.WEEKDAY, takeWeekdayDiscount(date, order));
+ allBenefit.put(BenefitType.WEEKEND, takeWeekendDiscount(date, order));
+ allBenefit.put(BenefitType.SPECIAL, takeSpecialDiscount(date));
+
+ cancelAllBenefitIfMeetCondition(order, allBenefit);
+
+ return new EventResult(allBenefit);
+ }
+
+ private int takeGift(Order order) {
+ if (order.calculateTotalOrderPrice() >= MINIMUM_TOTAL_ORDER_PRICE_FOR_GIFT) {
+ return Menu.CHAMPAGNE.getPrice();
+ }
+
+ return 0;
+ }
+
+ private int takeDDayDiscount(Date date) {
+ if (date.isDDayDiscountActive()) {
+ return D_DAY_DISCOUNT_DEFAULT_AMOUNT
+ + (calculateDifferenceBetweenFirstDay(date) * D_DAY_DISCOUNT_AMOUNT_PER_DAY);
+ }
+
+ return 0;
+ }
+
+ private int calculateDifferenceBetweenFirstDay(Date date) {
+ return date.getDayNumber() - FIRST_DAY_NUMBER;
+ }
+
+ private int takeWeekdayDiscount(Date date, Order order) {
+ int discount = 0;
+
+ for (OrderedMenu orderedMenu : order.getOrder()) {
+ Menu menu = Menu.decideMenu(orderedMenu.getMenuName());
+ if (date.isWeekdayDiscountActive() && MenuType.decideMenuType(menu) == MenuType.DESSERT) {
+ discount += orderedMenu.getQuantity() * WEEKDAY_DESSERT_DISCOUNT_AMOUNT;
+ }
+ }
+
+ return discount;
+ }
+
+ private int takeWeekendDiscount(Date date, Order order) {
+ int discount = 0;
+
+ for (OrderedMenu orderedMenu : order.getOrder()) {
+ Menu menu = Menu.decideMenu(orderedMenu.getMenuName());
+ if (date.isWeekendDiscountActive() && MenuType.decideMenuType(menu) == MenuType.MAIN) {
+ discount += orderedMenu.getQuantity() * WEEKEND_MAIN_DISCOUNT_AMOUNT;
+ }
+ }
+
+ return discount;
+ }
+
+ private int takeSpecialDiscount(Date date) {
+ if (date.isSpecialDiscountActive()) {
+ return SPECIAL_DISCOUNT_AMOUNT;
+ }
+
+ return 0;
+ }
+
+ private Map<BenefitType, Integer> cancelAllBenefitIfMeetCondition(Order order,
+ Map<BenefitType, Integer> allBenefit) {
+ if (isInsufficientTotalOrderPriceForEvent(order)) {
+ allBenefit.replace(BenefitType.GIFT, 0);
+ allBenefit.replace(BenefitType.D_DAY, 0);
+ allBenefit.replace(BenefitType.WEEKDAY, 0);
+ allBenefit.replace(BenefitType.WEEKEND, 0);
+ allBenefit.replace(BenefitType.SPECIAL, 0);
+ }
+
+ return allBenefit;
+ }
+
+ private boolean isInsufficientTotalOrderPriceForEvent(Order order) {
+ return order.calculateTotalOrderPrice() < MINIMUM_TOTAL_ORDER_PRICE_FOR_ALL_EVENT;
+ }
+}
\ No newline at end of file | Java | (๊ฐ์ธ์ ์ธ ์๊ฐ์
๋๋ค!)
ํ ์ธ์ ์ ์ฉํ๊ณ ์กฐ๊ฑด์ ๋ง์ง ์์ผ๋ฉด ๋๋๋ฆฌ๋ ๋ฐฉ๋ฒ๋ณด๋ค๋ ์ฒ์๋ถํฐ ์กฐ๊ฑด์ ๋ง์กฑํ์ง ์์ผ๋ฉด ํ ์ธ์ ์ ์ฉํ์ง ์๋ ๊ฒ๋ ํ๋์ ๋ฐฉ๋ฒ์ผ ๊ฒ ๊ฐ์์!
```suggestion
if (this.isInsufficientTotalOrderPriceForEvent(order)) {
return EnumSet.allOf(BenefitType.class)
.stream()
.collect(collectingAndThen(
toMap(Function.identity(), (benefit) -> 0),
EventResult::new)
);
}
```
์ ์ฝ๋์์ stream์ ํ์ฉํ๋๋ฐ BenefitType์ ๋ชจ๋ ์์๋ฅผ ๊ฐ์ ธ์จ๋ค์ 0์ผ๋ก ์ด๊ธฐํํ๊ณ ๋์จ ๊ฒฐ๊ณผ๋ฌผ์ EventResult๋ก ๋ํํ๋ ์ฝ๋์
๋๋ค :) |
@@ -0,0 +1,100 @@
+package christmas.domain;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class EventProcess {
+ private static final int MINIMUM_TOTAL_ORDER_PRICE_FOR_GIFT = 120000;
+ private static final int MINIMUM_TOTAL_ORDER_PRICE_FOR_ALL_EVENT = 10000;
+ private static final int D_DAY_DISCOUNT_AMOUNT_PER_DAY = 100;
+ private static final int D_DAY_DISCOUNT_DEFAULT_AMOUNT = 1000;
+ private static final int FIRST_DAY_NUMBER = 1;
+ private static final int WEEKDAY_DESSERT_DISCOUNT_AMOUNT = 2023;
+ private static final int WEEKEND_MAIN_DISCOUNT_AMOUNT = 2023;
+ private static final int SPECIAL_DISCOUNT_AMOUNT = 1000;
+
+ public EventResult takeAllBenefit(Date date, Order order) {
+ Map<BenefitType, Integer> allBenefit = new HashMap<>();
+ allBenefit.put(BenefitType.GIFT, takeGift(order));
+ allBenefit.put(BenefitType.D_DAY, takeDDayDiscount(date));
+ allBenefit.put(BenefitType.WEEKDAY, takeWeekdayDiscount(date, order));
+ allBenefit.put(BenefitType.WEEKEND, takeWeekendDiscount(date, order));
+ allBenefit.put(BenefitType.SPECIAL, takeSpecialDiscount(date));
+
+ cancelAllBenefitIfMeetCondition(order, allBenefit);
+
+ return new EventResult(allBenefit);
+ }
+
+ private int takeGift(Order order) {
+ if (order.calculateTotalOrderPrice() >= MINIMUM_TOTAL_ORDER_PRICE_FOR_GIFT) {
+ return Menu.CHAMPAGNE.getPrice();
+ }
+
+ return 0;
+ }
+
+ private int takeDDayDiscount(Date date) {
+ if (date.isDDayDiscountActive()) {
+ return D_DAY_DISCOUNT_DEFAULT_AMOUNT
+ + (calculateDifferenceBetweenFirstDay(date) * D_DAY_DISCOUNT_AMOUNT_PER_DAY);
+ }
+
+ return 0;
+ }
+
+ private int calculateDifferenceBetweenFirstDay(Date date) {
+ return date.getDayNumber() - FIRST_DAY_NUMBER;
+ }
+
+ private int takeWeekdayDiscount(Date date, Order order) {
+ int discount = 0;
+
+ for (OrderedMenu orderedMenu : order.getOrder()) {
+ Menu menu = Menu.decideMenu(orderedMenu.getMenuName());
+ if (date.isWeekdayDiscountActive() && MenuType.decideMenuType(menu) == MenuType.DESSERT) {
+ discount += orderedMenu.getQuantity() * WEEKDAY_DESSERT_DISCOUNT_AMOUNT;
+ }
+ }
+
+ return discount;
+ }
+
+ private int takeWeekendDiscount(Date date, Order order) {
+ int discount = 0;
+
+ for (OrderedMenu orderedMenu : order.getOrder()) {
+ Menu menu = Menu.decideMenu(orderedMenu.getMenuName());
+ if (date.isWeekendDiscountActive() && MenuType.decideMenuType(menu) == MenuType.MAIN) {
+ discount += orderedMenu.getQuantity() * WEEKEND_MAIN_DISCOUNT_AMOUNT;
+ }
+ }
+
+ return discount;
+ }
+
+ private int takeSpecialDiscount(Date date) {
+ if (date.isSpecialDiscountActive()) {
+ return SPECIAL_DISCOUNT_AMOUNT;
+ }
+
+ return 0;
+ }
+
+ private Map<BenefitType, Integer> cancelAllBenefitIfMeetCondition(Order order,
+ Map<BenefitType, Integer> allBenefit) {
+ if (isInsufficientTotalOrderPriceForEvent(order)) {
+ allBenefit.replace(BenefitType.GIFT, 0);
+ allBenefit.replace(BenefitType.D_DAY, 0);
+ allBenefit.replace(BenefitType.WEEKDAY, 0);
+ allBenefit.replace(BenefitType.WEEKEND, 0);
+ allBenefit.replace(BenefitType.SPECIAL, 0);
+ }
+
+ return allBenefit;
+ }
+
+ private boolean isInsufficientTotalOrderPriceForEvent(Order order) {
+ return order.calculateTotalOrderPrice() < MINIMUM_TOTAL_ORDER_PRICE_FOR_ALL_EVENT;
+ }
+}
\ No newline at end of file | Java | (๊ฐ์ธ์ ์ธ ์๊ฐ์
๋๋ค!)
```suggestion
return new EventResult(new HashMap<>() {{
this.put(BenefitType.GIFT, takeGift(order));
this.put(BenefitType.D_DAY, takeDDayDiscount(date));
this.put(BenefitType.WEEKDAY, takeWeekdayDiscount(date, order));
this.put(BenefitType.WEEKEND, takeWeekendDiscount(date, order));
this.put(BenefitType.SPECIAL, takeSpecialDiscount(date));
}});
```
์ด๋ฐ์์ผ๋ก ์์ฑ๊ณผ ๋์์ HashMap์ ์์๋ฅผ ์ด๊ธฐํ ํ๋ ๋ฐฉ๋ฒ๋ ์์ด์ :) |
@@ -0,0 +1,100 @@
+package christmas.domain;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class EventProcess {
+ private static final int MINIMUM_TOTAL_ORDER_PRICE_FOR_GIFT = 120000;
+ private static final int MINIMUM_TOTAL_ORDER_PRICE_FOR_ALL_EVENT = 10000;
+ private static final int D_DAY_DISCOUNT_AMOUNT_PER_DAY = 100;
+ private static final int D_DAY_DISCOUNT_DEFAULT_AMOUNT = 1000;
+ private static final int FIRST_DAY_NUMBER = 1;
+ private static final int WEEKDAY_DESSERT_DISCOUNT_AMOUNT = 2023;
+ private static final int WEEKEND_MAIN_DISCOUNT_AMOUNT = 2023;
+ private static final int SPECIAL_DISCOUNT_AMOUNT = 1000;
+
+ public EventResult takeAllBenefit(Date date, Order order) {
+ Map<BenefitType, Integer> allBenefit = new HashMap<>();
+ allBenefit.put(BenefitType.GIFT, takeGift(order));
+ allBenefit.put(BenefitType.D_DAY, takeDDayDiscount(date));
+ allBenefit.put(BenefitType.WEEKDAY, takeWeekdayDiscount(date, order));
+ allBenefit.put(BenefitType.WEEKEND, takeWeekendDiscount(date, order));
+ allBenefit.put(BenefitType.SPECIAL, takeSpecialDiscount(date));
+
+ cancelAllBenefitIfMeetCondition(order, allBenefit);
+
+ return new EventResult(allBenefit);
+ }
+
+ private int takeGift(Order order) {
+ if (order.calculateTotalOrderPrice() >= MINIMUM_TOTAL_ORDER_PRICE_FOR_GIFT) {
+ return Menu.CHAMPAGNE.getPrice();
+ }
+
+ return 0;
+ }
+
+ private int takeDDayDiscount(Date date) {
+ if (date.isDDayDiscountActive()) {
+ return D_DAY_DISCOUNT_DEFAULT_AMOUNT
+ + (calculateDifferenceBetweenFirstDay(date) * D_DAY_DISCOUNT_AMOUNT_PER_DAY);
+ }
+
+ return 0;
+ }
+
+ private int calculateDifferenceBetweenFirstDay(Date date) {
+ return date.getDayNumber() - FIRST_DAY_NUMBER;
+ }
+
+ private int takeWeekdayDiscount(Date date, Order order) {
+ int discount = 0;
+
+ for (OrderedMenu orderedMenu : order.getOrder()) {
+ Menu menu = Menu.decideMenu(orderedMenu.getMenuName());
+ if (date.isWeekdayDiscountActive() && MenuType.decideMenuType(menu) == MenuType.DESSERT) {
+ discount += orderedMenu.getQuantity() * WEEKDAY_DESSERT_DISCOUNT_AMOUNT;
+ }
+ }
+
+ return discount;
+ }
+
+ private int takeWeekendDiscount(Date date, Order order) {
+ int discount = 0;
+
+ for (OrderedMenu orderedMenu : order.getOrder()) {
+ Menu menu = Menu.decideMenu(orderedMenu.getMenuName());
+ if (date.isWeekendDiscountActive() && MenuType.decideMenuType(menu) == MenuType.MAIN) {
+ discount += orderedMenu.getQuantity() * WEEKEND_MAIN_DISCOUNT_AMOUNT;
+ }
+ }
+
+ return discount;
+ }
+
+ private int takeSpecialDiscount(Date date) {
+ if (date.isSpecialDiscountActive()) {
+ return SPECIAL_DISCOUNT_AMOUNT;
+ }
+
+ return 0;
+ }
+
+ private Map<BenefitType, Integer> cancelAllBenefitIfMeetCondition(Order order,
+ Map<BenefitType, Integer> allBenefit) {
+ if (isInsufficientTotalOrderPriceForEvent(order)) {
+ allBenefit.replace(BenefitType.GIFT, 0);
+ allBenefit.replace(BenefitType.D_DAY, 0);
+ allBenefit.replace(BenefitType.WEEKDAY, 0);
+ allBenefit.replace(BenefitType.WEEKEND, 0);
+ allBenefit.replace(BenefitType.SPECIAL, 0);
+ }
+
+ return allBenefit;
+ }
+
+ private boolean isInsufficientTotalOrderPriceForEvent(Order order) {
+ return order.calculateTotalOrderPrice() < MINIMUM_TOTAL_ORDER_PRICE_FOR_ALL_EVENT;
+ }
+}
\ No newline at end of file | Java | (๊ฐ์ธ์ ์ธ ์๊ฐ์
๋๋ค!)
ํ ์ธ ๊ธ์ก์ ๊ณ์ฐํ๊ธฐ ์ ์ ์ฃผ๋ง์ด๋ฉด 0์์ ๋ฐํํ๋ ๋ฐฉ๋ฒ๋ ๊ด์ฐฎ์ ๊ฒ ๊ฐ์์!
```suggestion
if (date.isWeekendDiscountActive()) {
return 0;
}
return order.getOrder()
.stream()
.filter(orderedMenu -> DESSERT.equals(MenuType.decideMenuType(Menu.decideMenu(orderedMenu.getMenuName()))))
.mapToInt(orderMenu -> orderMenu.getQuantity() * WEEKDAY_DESSERT_DISCOUNT_AMOUNT)
.sum();
``` |
@@ -0,0 +1,85 @@
+package christmas.domain;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+public class EventResult {
+ private static final String NON_BADGE = "์์";
+ private static final String STAR_BADGE = "๋ณ";
+ private static final String TREE_BADGE = "ํธ๋ฆฌ";
+ private static final String SANTA_BADGE = "์ฐํ";
+ private static final int STAR_BADGE_MINIMUM_AMOUNT = 5000;
+ private static final int STAR_BADGE_MAXIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MINIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MAXIMUM_AMOUNT = 20000;
+ private static final int SANTA_BADGE_MINIMUM_AMOUNT = 20000;
+
+ private final Map<BenefitType, Integer> allBenefit;
+
+ public EventResult(Map<BenefitType, Integer> allBenefit) {
+ this.allBenefit = allBenefit;
+ }
+
+ public int calculateTotalBenefitAmount() {
+ int totalBenefitAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalBenefitAmount += allBenefit.get(benefitType);
+ }
+
+ return totalBenefitAmount;
+ }
+
+ public int calculateTotalDiscountAmount() {
+ int totalDiscountAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalDiscountAmount += allBenefit.get(benefitType);
+ }
+ if (allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice()) {
+ totalDiscountAmount -= Menu.CHAMPAGNE.getPrice();
+ }
+
+ return totalDiscountAmount;
+ }
+
+ public boolean isReceivedGiftBenefit() {
+ return allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice();
+ }
+
+ public List<BenefitType> checkWhichBenefitExist() {
+ List<BenefitType> existingBenefit = new ArrayList<>();
+ BenefitType[] benefitTypes = BenefitType.values();
+
+ for (BenefitType benefitType : benefitTypes) {
+ if (allBenefit.get(benefitType) != 0) {
+ existingBenefit.add(benefitType);
+ }
+ }
+
+ return existingBenefit;
+ }
+
+ public String decideEventBadge() {
+ int totalBenefitAmount = calculateTotalBenefitAmount();
+
+ if ((totalBenefitAmount >= STAR_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < STAR_BADGE_MAXIMUM_AMOUNT)) {
+ return STAR_BADGE;
+ }
+ if ((totalBenefitAmount >= TREE_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < TREE_BADGE_MAXIMUM_AMOUNT)) {
+ return TREE_BADGE;
+ }
+ if ((totalBenefitAmount >= SANTA_BADGE_MINIMUM_AMOUNT)) {
+ return SANTA_BADGE;
+ }
+ return NON_BADGE;
+ }
+
+ public Map<BenefitType, Integer> getAllBenefit() {
+ return Collections.unmodifiableMap(allBenefit);
+ }
+}
\ No newline at end of file | Java | (์ถ์ฒ๋๋ ค์!)
EventResult์ badge๊ด๋ จ ์ฝ๋๋ enum์ผ๋ก ๋ถ๋ฆฌํ๋ฉด ์ข์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,52 @@
+package christmas.ui;
+
+import static christmas.domain.Date.DATE_RE_READ_REQUEST_MESSAGE;
+import static christmas.domain.OrderedMenu.ORDER_RE_READ_REQUEST_MESSAGE;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Converter {
+ private static final String ORDER_DELIMITER = ",";
+ private static final String NAME_AND_AMOUNT_DELIMITER = "-";
+
+ public static int convertDateNumeric(String Input) {
+ try {
+ return Integer.parseInt(Input);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(DATE_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ public static List<String> separateOrder(String order) {
+ return new ArrayList<>(List.of(order.split(ORDER_DELIMITER)));
+ }
+
+ public static List<String> separateNameAndAmount(String orderedMenu) {
+ validateAppropriateDelimiter(orderedMenu);
+ List<String> separatedNameAndAmount = new ArrayList<>(List.of(orderedMenu.split(NAME_AND_AMOUNT_DELIMITER)));
+ validateAppropriateForm(separatedNameAndAmount);
+
+ return separatedNameAndAmount;
+ }
+
+ private static void validateAppropriateDelimiter(String orderedMenu) {
+ if (!orderedMenu.contains(NAME_AND_AMOUNT_DELIMITER)) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ private static void validateAppropriateForm(List<String> separatedNameAndAmount) {
+ if (separatedNameAndAmount.size() != 2) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ public static int convertAmountNumeric(String input) {
+ try {
+ return Integer.parseInt(input);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(ORDER_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+}
\ No newline at end of file | Java | (์ด๋ ๊ฒ๋ ๊ฐ๋ฅํด์!)
ArrayList๋ก ๋ค์ ๊ฐ์ธ์ง ์์๋ ์ถฉ๋ถํ ๊ฒ ๊ฐ์์ :)
```suggestion
return List.of(order.split(ORDER_DELIMITER));
``` |
@@ -0,0 +1,63 @@
+package christmas.ui;
+
+import camp.nextstep.edu.missionutils.Console;
+import christmas.domain.Date;
+import christmas.domain.Order;
+import christmas.domain.OrderedMenu;
+import java.util.ArrayList;
+import java.util.List;
+
+public class InputView {
+ private static final String OPENING_MESSAGE = "์๋
ํ์ธ์! ์ฐํ
์ฝ ์๋น 12์ ์ด๋ฒคํธ ํ๋๋์
๋๋ค.";
+ private static final String DATE_REQUEST_MESSAGE = "12์ ์ค ์๋น ์์ ๋ฐฉ๋ฌธ ๋ ์ง๋ ์ธ์ ์ธ๊ฐ์? (์ซ์๋ง ์
๋ ฅํด ์ฃผ์ธ์!)";
+ private static final String ORDER_REQUEST_MESSAGE
+ = "์ฃผ๋ฌธํ์ค ๋ฉ๋ด๋ฅผ ๋ฉ๋ด์ ๊ฐ์๋ฅผ ์๋ ค ์ฃผ์ธ์. (e.g. ํด์ฐ๋ฌผํ์คํ-2,๋ ๋์์ธ-1,์ด์ฝ์ผ์ดํฌ-1)";
+
+ public static void notifyProgramStarted() {
+ System.out.println(OPENING_MESSAGE);
+ }
+
+ public static Date inputDate() {
+ try {
+ return readDate();
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorMessage(e);
+ return inputDate();
+ }
+ }
+
+ private static Date readDate() {
+ System.out.println(DATE_REQUEST_MESSAGE);
+
+ String input = Console.readLine();
+ int dayNumber = Converter.convertDateNumeric(input);
+
+ return new Date(dayNumber);
+ }
+
+ public static Order inputOrder() {
+ try {
+ return new Order(readOrder());
+ } catch (IllegalArgumentException e) {
+ OutputView.printErrorMessage(e);
+ return inputOrder();
+ }
+ }
+
+ private static List<OrderedMenu> readOrder() {
+ System.out.println(ORDER_REQUEST_MESSAGE);
+
+ String input = Console.readLine();
+ List<String> separatedOrder = Converter.separateOrder(input);
+ List<OrderedMenu> order = new ArrayList<>();
+
+ for (String orderedMenu : separatedOrder) {
+ List<String> separatedNameAndAmount = Converter.separateNameAndAmount(orderedMenu);
+ String name = separatedNameAndAmount.get(0);
+ int amount = Converter.convertAmountNumeric(separatedNameAndAmount.get(1));
+ order.add(new OrderedMenu(name, amount));
+ }
+
+ return order;
+ }
+}
\ No newline at end of file | Java | (์ด๋ ๊ฒ ๋ฐ๊ฟ ์ ์์ด์!)
```suggestion
private static List<OrderedMenu> readOrder() {
System.out.println(ORDER_REQUEST_MESSAGE);
String input = Console.readLine();
List<String> separatedOrder = Converter.separateOrder(input);
return separatedOrder.stream()
.map(InputView::convertNameToOrderedMenu)
.toList();
}
private static OrderedMenu convertNameToOrderedMenu(String orderMenu) {
List<String> separatedNameAndAmount = Converter.separateNameAndAmount(orderMenu);
String name = separatedNameAndAmount.get(0);
int amount = Converter.convertAmountNumeric(separatedNameAndAmount.get(1));
return new OrderedMenu(name, amount);
}
``` |
@@ -0,0 +1,60 @@
+package christmas.domain;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+class EventProcessTest {
+ @DisplayName("์ด๋ฒคํธ์ ์ถฉ๋ถํ ์ ์ฒด ์ฃผ๋ฌธ ๊ธ์ก์ผ๋ก ์ ์ฒด ํํ ๋์ถ")
+ @Test
+ void takeAllBenefitWithSufficientTotalOrderPrice() {
+ Date dateInput = new Date(3);
+ Order orderInput = new Order(setUpSufficientTotalOrderPriceOrder());
+ EventProcess eventProcess = new EventProcess();
+ EventResult eventResult = eventProcess.takeAllBenefit(dateInput, orderInput);
+ Map<BenefitType, Integer> result = eventResult.getAllBenefit();
+
+ assertThat(result.get(BenefitType.GIFT)).isEqualTo(25000);
+ assertThat(result.get(BenefitType.D_DAY)).isEqualTo(1200);
+ assertThat(result.get(BenefitType.WEEKDAY)).isEqualTo(2023);
+ assertThat(result.get(BenefitType.WEEKEND)).isEqualTo(0);
+ assertThat(result.get(BenefitType.SPECIAL)).isEqualTo(1000);
+ }
+
+ private List<OrderedMenu> setUpSufficientTotalOrderPriceOrder() {
+ List<OrderedMenu> orderedMenus = new ArrayList<>();
+ orderedMenus.add(new OrderedMenu("ํด์ฐ๋ฌผํ์คํ", 2));
+ orderedMenus.add(new OrderedMenu("๋ ๋์์ธ", 1));
+ orderedMenus.add(new OrderedMenu("์ด์ฝ์ผ์ดํฌ", 1));
+
+ return orderedMenus;
+ }
+
+ @DisplayName("์ด๋ฒคํธ์ ์ถฉ๋ถํ์ง ์์ ์ ์ฒด ์ฃผ๋ฌธ ๊ธ์ก์ผ๋ก ์ ์ฒด ํํ ๋์ถ")
+ @Test
+ void takeAllBenefitWithInSufficientTotalOrderPrice() {
+ Date dateInput = new Date(26);
+ Order orderInput = new Order(setUpInSufficientTotalOrderPriceOrder());
+ EventProcess eventProcess = new EventProcess();
+ EventResult eventResult = eventProcess.takeAllBenefit(dateInput, orderInput);
+ Map<BenefitType, Integer> result = eventResult.getAllBenefit();
+
+ assertThat(result.get(BenefitType.GIFT)).isEqualTo(0);
+ assertThat(result.get(BenefitType.D_DAY)).isEqualTo(0);
+ assertThat(result.get(BenefitType.WEEKDAY)).isEqualTo(0);
+ assertThat(result.get(BenefitType.WEEKEND)).isEqualTo(0);
+ assertThat(result.get(BenefitType.SPECIAL)).isEqualTo(0);
+ }
+
+ private List<OrderedMenu> setUpInSufficientTotalOrderPriceOrder() {
+ List<OrderedMenu> orderedMenus = new ArrayList<>();
+ orderedMenus.add(new OrderedMenu("ํํ์ค", 1));
+ orderedMenus.add(new OrderedMenu("์ ๋ก์ฝ๋ผ", 1));
+
+ return orderedMenus;
+ }
+}
\ No newline at end of file | Java | (์ถ์ฒ๋๋ ค์)
assertThat๋ง ์ฌ์ฉํ๋ฉด 21๋ฒ์งธ ์ค์์ ์คํจํ์ ๋ ๋ฐ์ 22~25๋ฒ ๋ผ์ธ๊น์ง ๊ฒ์ฆํ์ง ์์ต๋๋ค!
๋ฐ๋ฉด assertAll์ ์ฌ์ฉํ๋ฉด ๋ชจ๋ assertThat์ ์คํ์ํค๊ธฐ ๋๋ฌธ์ ๋ฌด์์ด ์คํจํ๋์ง ํ์คํ๊ฒ ์ฐพ์ ์ ์๋ ์ฅ์ ์ด ์์ต๋๋ค!
```suggestion
assertAll(
() -> assertThat(result.get(BenefitType.GIFT)).isEqualTo(25000),
() -> assertThat(result.get(BenefitType.D_DAY)).isEqualTo(1200),
() -> assertThat(result.get(BenefitType.WEEKDAY)).isEqualTo(2023),
() -> assertThat(result.get(BenefitType.WEEKEND)).isEqualTo(0),
() -> assertThat(result.get(BenefitType.SPECIAL)).isEqualTo(1000)
);
``` |
@@ -0,0 +1,23 @@
+package christmas.domain;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+class MenuTest {
+ @DisplayName("์ฃผ์ด์ง ์ด๋ฆ์ ํ ๋๋ก ๋ฉ๋ด๋ฅผ ํ๋จํ ์ ์๋ค.")
+ @Test
+ void decideMenu() {
+ String inputTapas = "ํํ์ค";
+ String inputSeafoodPasta = "ํด์ฐ๋ฌผํ์คํ";
+ String inputRedWine = "๋ ๋์์ธ";
+ Menu inputTapasResult = Menu.decideMenu(inputTapas);
+ Menu inputSeafoodPastaResult = Menu.decideMenu(inputSeafoodPasta);
+ Menu inputRedWineResult = Menu.decideMenu(inputRedWine);
+
+ assertThat(inputTapasResult).isEqualTo(Menu.TAPAS);
+ assertThat(inputSeafoodPastaResult).isEqualTo(Menu.SEAFOOD_PASTA);
+ assertThat(inputRedWineResult).isEqualTo(Menu.RED_WINE);
+ }
+}
\ No newline at end of file | Java | (๊ฐ์ธ์ ์ธ ์๊ฐ์
๋๋ค!)
ํ
์คํธ์ฝ๋๋ฅผ ๋๋ฌ๋ณด๋ ๋๋ถ๋ถ ํดํผ์ผ์ด์ค๋ง ์๋๋ผ๊ตฌ์!
์คํจ์ ๋ํ ๊ฒ์ฆ ํ
์คํธ ์ฝ๋๋ ์ฐ์ตํด๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,58 @@
+package christmas.domain;
+
+import java.time.DayOfWeek;
+import java.time.LocalDate;
+
+public class Date {
+ public static final String DATE_RE_READ_REQUEST_MESSAGE = "์ ํจํ์ง ์์ ๋ ์ง์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.";
+ private static final LocalDate CHRISTMAS_DAY = LocalDate.of(2023, 12, 25);
+ private static final int YEAR = 2023;
+ private static final int MONTH = 12;
+ private static final int DATE_MIN_NUMBER = 1;
+ private static final int DATE_MAX_NUMBER = 31;
+
+ private final int dayNumber;
+
+ public Date(int dayNumber) {
+ validateRange(dayNumber);
+ this.dayNumber = dayNumber;
+ }
+
+ private void validateRange(int dayNumber) {
+ if ((dayNumber < DATE_MIN_NUMBER) || (dayNumber > DATE_MAX_NUMBER)) {
+ throw new IllegalArgumentException(DATE_RE_READ_REQUEST_MESSAGE);
+ }
+ }
+
+ public boolean isDDayDiscountActive() {
+ LocalDate localDate = LocalDate.of(YEAR, MONTH, dayNumber);
+
+ return localDate.isBefore(CHRISTMAS_DAY.plusDays(1));
+ }
+
+ public boolean isWeekdayDiscountActive() {
+ LocalDate localDate = LocalDate.of(YEAR, MONTH, dayNumber);
+ DayOfWeek day = localDate.getDayOfWeek();
+
+ return (day.equals(DayOfWeek.MONDAY) || day.equals(DayOfWeek.TUESDAY) || day.equals(DayOfWeek.WEDNESDAY)
+ || day.equals(DayOfWeek.THURSDAY) || day.equals(DayOfWeek.SUNDAY));
+ }
+
+ public boolean isWeekendDiscountActive() {
+ LocalDate localDate = LocalDate.of(YEAR, MONTH, dayNumber);
+ DayOfWeek day = localDate.getDayOfWeek();
+
+ return (day.equals(DayOfWeek.FRIDAY) || day.equals(DayOfWeek.SATURDAY));
+ }
+
+ public boolean isSpecialDiscountActive() {
+ LocalDate localDate = LocalDate.of(YEAR, MONTH, dayNumber);
+ DayOfWeek day = localDate.getDayOfWeek();
+
+ return (day.equals(DayOfWeek.SUNDAY) || localDate.equals(CHRISTMAS_DAY));
+ }
+
+ public int getDayNumber() {
+ return dayNumber;
+ }
+}
\ No newline at end of file | Java | ์ค,, ์ด๋ฒ์ LocalDate๋ฅผ ์ฒ์ ์ฌ์ฉํด๋ด์ ์ต์ํ์ง ์์๋๋ฐ์ ์ด๋ฐ ๋ฐฉ๋ฒ๋ ์์๊ตฐ์,, ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,100 @@
+package christmas.domain;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class EventProcess {
+ private static final int MINIMUM_TOTAL_ORDER_PRICE_FOR_GIFT = 120000;
+ private static final int MINIMUM_TOTAL_ORDER_PRICE_FOR_ALL_EVENT = 10000;
+ private static final int D_DAY_DISCOUNT_AMOUNT_PER_DAY = 100;
+ private static final int D_DAY_DISCOUNT_DEFAULT_AMOUNT = 1000;
+ private static final int FIRST_DAY_NUMBER = 1;
+ private static final int WEEKDAY_DESSERT_DISCOUNT_AMOUNT = 2023;
+ private static final int WEEKEND_MAIN_DISCOUNT_AMOUNT = 2023;
+ private static final int SPECIAL_DISCOUNT_AMOUNT = 1000;
+
+ public EventResult takeAllBenefit(Date date, Order order) {
+ Map<BenefitType, Integer> allBenefit = new HashMap<>();
+ allBenefit.put(BenefitType.GIFT, takeGift(order));
+ allBenefit.put(BenefitType.D_DAY, takeDDayDiscount(date));
+ allBenefit.put(BenefitType.WEEKDAY, takeWeekdayDiscount(date, order));
+ allBenefit.put(BenefitType.WEEKEND, takeWeekendDiscount(date, order));
+ allBenefit.put(BenefitType.SPECIAL, takeSpecialDiscount(date));
+
+ cancelAllBenefitIfMeetCondition(order, allBenefit);
+
+ return new EventResult(allBenefit);
+ }
+
+ private int takeGift(Order order) {
+ if (order.calculateTotalOrderPrice() >= MINIMUM_TOTAL_ORDER_PRICE_FOR_GIFT) {
+ return Menu.CHAMPAGNE.getPrice();
+ }
+
+ return 0;
+ }
+
+ private int takeDDayDiscount(Date date) {
+ if (date.isDDayDiscountActive()) {
+ return D_DAY_DISCOUNT_DEFAULT_AMOUNT
+ + (calculateDifferenceBetweenFirstDay(date) * D_DAY_DISCOUNT_AMOUNT_PER_DAY);
+ }
+
+ return 0;
+ }
+
+ private int calculateDifferenceBetweenFirstDay(Date date) {
+ return date.getDayNumber() - FIRST_DAY_NUMBER;
+ }
+
+ private int takeWeekdayDiscount(Date date, Order order) {
+ int discount = 0;
+
+ for (OrderedMenu orderedMenu : order.getOrder()) {
+ Menu menu = Menu.decideMenu(orderedMenu.getMenuName());
+ if (date.isWeekdayDiscountActive() && MenuType.decideMenuType(menu) == MenuType.DESSERT) {
+ discount += orderedMenu.getQuantity() * WEEKDAY_DESSERT_DISCOUNT_AMOUNT;
+ }
+ }
+
+ return discount;
+ }
+
+ private int takeWeekendDiscount(Date date, Order order) {
+ int discount = 0;
+
+ for (OrderedMenu orderedMenu : order.getOrder()) {
+ Menu menu = Menu.decideMenu(orderedMenu.getMenuName());
+ if (date.isWeekendDiscountActive() && MenuType.decideMenuType(menu) == MenuType.MAIN) {
+ discount += orderedMenu.getQuantity() * WEEKEND_MAIN_DISCOUNT_AMOUNT;
+ }
+ }
+
+ return discount;
+ }
+
+ private int takeSpecialDiscount(Date date) {
+ if (date.isSpecialDiscountActive()) {
+ return SPECIAL_DISCOUNT_AMOUNT;
+ }
+
+ return 0;
+ }
+
+ private Map<BenefitType, Integer> cancelAllBenefitIfMeetCondition(Order order,
+ Map<BenefitType, Integer> allBenefit) {
+ if (isInsufficientTotalOrderPriceForEvent(order)) {
+ allBenefit.replace(BenefitType.GIFT, 0);
+ allBenefit.replace(BenefitType.D_DAY, 0);
+ allBenefit.replace(BenefitType.WEEKDAY, 0);
+ allBenefit.replace(BenefitType.WEEKEND, 0);
+ allBenefit.replace(BenefitType.SPECIAL, 0);
+ }
+
+ return allBenefit;
+ }
+
+ private boolean isInsufficientTotalOrderPriceForEvent(Order order) {
+ return order.calculateTotalOrderPrice() < MINIMUM_TOTAL_ORDER_PRICE_FOR_ALL_EVENT;
+ }
+}
\ No newline at end of file | Java | ๋ฏธ์
๋์์ ์๊ฐ์ด ์ด๋ฐํ์ด์ stream๊ณต๋ถ๋ฅผ ํ์ง ๋ชปํ๋๋ฐ์, ์์ผ๋ก ๊ณต๋ถํด์ ์ถ์ฒํด์ฃผ์ ๋ฐฉ๋ฒ ์ดํดํด๋ณด๋๋ก ํ ๊ฒ์ ๊ฐ์ฌํฉ๋๋ค!! |
@@ -0,0 +1,100 @@
+package christmas.domain;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class EventProcess {
+ private static final int MINIMUM_TOTAL_ORDER_PRICE_FOR_GIFT = 120000;
+ private static final int MINIMUM_TOTAL_ORDER_PRICE_FOR_ALL_EVENT = 10000;
+ private static final int D_DAY_DISCOUNT_AMOUNT_PER_DAY = 100;
+ private static final int D_DAY_DISCOUNT_DEFAULT_AMOUNT = 1000;
+ private static final int FIRST_DAY_NUMBER = 1;
+ private static final int WEEKDAY_DESSERT_DISCOUNT_AMOUNT = 2023;
+ private static final int WEEKEND_MAIN_DISCOUNT_AMOUNT = 2023;
+ private static final int SPECIAL_DISCOUNT_AMOUNT = 1000;
+
+ public EventResult takeAllBenefit(Date date, Order order) {
+ Map<BenefitType, Integer> allBenefit = new HashMap<>();
+ allBenefit.put(BenefitType.GIFT, takeGift(order));
+ allBenefit.put(BenefitType.D_DAY, takeDDayDiscount(date));
+ allBenefit.put(BenefitType.WEEKDAY, takeWeekdayDiscount(date, order));
+ allBenefit.put(BenefitType.WEEKEND, takeWeekendDiscount(date, order));
+ allBenefit.put(BenefitType.SPECIAL, takeSpecialDiscount(date));
+
+ cancelAllBenefitIfMeetCondition(order, allBenefit);
+
+ return new EventResult(allBenefit);
+ }
+
+ private int takeGift(Order order) {
+ if (order.calculateTotalOrderPrice() >= MINIMUM_TOTAL_ORDER_PRICE_FOR_GIFT) {
+ return Menu.CHAMPAGNE.getPrice();
+ }
+
+ return 0;
+ }
+
+ private int takeDDayDiscount(Date date) {
+ if (date.isDDayDiscountActive()) {
+ return D_DAY_DISCOUNT_DEFAULT_AMOUNT
+ + (calculateDifferenceBetweenFirstDay(date) * D_DAY_DISCOUNT_AMOUNT_PER_DAY);
+ }
+
+ return 0;
+ }
+
+ private int calculateDifferenceBetweenFirstDay(Date date) {
+ return date.getDayNumber() - FIRST_DAY_NUMBER;
+ }
+
+ private int takeWeekdayDiscount(Date date, Order order) {
+ int discount = 0;
+
+ for (OrderedMenu orderedMenu : order.getOrder()) {
+ Menu menu = Menu.decideMenu(orderedMenu.getMenuName());
+ if (date.isWeekdayDiscountActive() && MenuType.decideMenuType(menu) == MenuType.DESSERT) {
+ discount += orderedMenu.getQuantity() * WEEKDAY_DESSERT_DISCOUNT_AMOUNT;
+ }
+ }
+
+ return discount;
+ }
+
+ private int takeWeekendDiscount(Date date, Order order) {
+ int discount = 0;
+
+ for (OrderedMenu orderedMenu : order.getOrder()) {
+ Menu menu = Menu.decideMenu(orderedMenu.getMenuName());
+ if (date.isWeekendDiscountActive() && MenuType.decideMenuType(menu) == MenuType.MAIN) {
+ discount += orderedMenu.getQuantity() * WEEKEND_MAIN_DISCOUNT_AMOUNT;
+ }
+ }
+
+ return discount;
+ }
+
+ private int takeSpecialDiscount(Date date) {
+ if (date.isSpecialDiscountActive()) {
+ return SPECIAL_DISCOUNT_AMOUNT;
+ }
+
+ return 0;
+ }
+
+ private Map<BenefitType, Integer> cancelAllBenefitIfMeetCondition(Order order,
+ Map<BenefitType, Integer> allBenefit) {
+ if (isInsufficientTotalOrderPriceForEvent(order)) {
+ allBenefit.replace(BenefitType.GIFT, 0);
+ allBenefit.replace(BenefitType.D_DAY, 0);
+ allBenefit.replace(BenefitType.WEEKDAY, 0);
+ allBenefit.replace(BenefitType.WEEKEND, 0);
+ allBenefit.replace(BenefitType.SPECIAL, 0);
+ }
+
+ return allBenefit;
+ }
+
+ private boolean isInsufficientTotalOrderPriceForEvent(Order order) {
+ return order.calculateTotalOrderPrice() < MINIMUM_TOTAL_ORDER_PRICE_FOR_ALL_EVENT;
+ }
+}
\ No newline at end of file | Java | ํจ์ฌ ๊น๋ํ๋ค์,, ๊ฐ์ฌํฉ๋๋ค!! |
@@ -0,0 +1,85 @@
+package christmas.domain;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+public class EventResult {
+ private static final String NON_BADGE = "์์";
+ private static final String STAR_BADGE = "๋ณ";
+ private static final String TREE_BADGE = "ํธ๋ฆฌ";
+ private static final String SANTA_BADGE = "์ฐํ";
+ private static final int STAR_BADGE_MINIMUM_AMOUNT = 5000;
+ private static final int STAR_BADGE_MAXIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MINIMUM_AMOUNT = 10000;
+ private static final int TREE_BADGE_MAXIMUM_AMOUNT = 20000;
+ private static final int SANTA_BADGE_MINIMUM_AMOUNT = 20000;
+
+ private final Map<BenefitType, Integer> allBenefit;
+
+ public EventResult(Map<BenefitType, Integer> allBenefit) {
+ this.allBenefit = allBenefit;
+ }
+
+ public int calculateTotalBenefitAmount() {
+ int totalBenefitAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalBenefitAmount += allBenefit.get(benefitType);
+ }
+
+ return totalBenefitAmount;
+ }
+
+ public int calculateTotalDiscountAmount() {
+ int totalDiscountAmount = 0;
+ List<BenefitType> benefitTypes = List.of(BenefitType.values());
+
+ for (BenefitType benefitType : benefitTypes) {
+ totalDiscountAmount += allBenefit.get(benefitType);
+ }
+ if (allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice()) {
+ totalDiscountAmount -= Menu.CHAMPAGNE.getPrice();
+ }
+
+ return totalDiscountAmount;
+ }
+
+ public boolean isReceivedGiftBenefit() {
+ return allBenefit.get(BenefitType.GIFT) == Menu.CHAMPAGNE.getPrice();
+ }
+
+ public List<BenefitType> checkWhichBenefitExist() {
+ List<BenefitType> existingBenefit = new ArrayList<>();
+ BenefitType[] benefitTypes = BenefitType.values();
+
+ for (BenefitType benefitType : benefitTypes) {
+ if (allBenefit.get(benefitType) != 0) {
+ existingBenefit.add(benefitType);
+ }
+ }
+
+ return existingBenefit;
+ }
+
+ public String decideEventBadge() {
+ int totalBenefitAmount = calculateTotalBenefitAmount();
+
+ if ((totalBenefitAmount >= STAR_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < STAR_BADGE_MAXIMUM_AMOUNT)) {
+ return STAR_BADGE;
+ }
+ if ((totalBenefitAmount >= TREE_BADGE_MINIMUM_AMOUNT) && (totalBenefitAmount < TREE_BADGE_MAXIMUM_AMOUNT)) {
+ return TREE_BADGE;
+ }
+ if ((totalBenefitAmount >= SANTA_BADGE_MINIMUM_AMOUNT)) {
+ return SANTA_BADGE;
+ }
+ return NON_BADGE;
+ }
+
+ public Map<BenefitType, Integer> getAllBenefit() {
+ return Collections.unmodifiableMap(allBenefit);
+ }
+}
\ No newline at end of file | Java | ์ถ๋ ฅ ํค๋๋ค์ enum์ผ๋ก ๊ด๋ฆฌํ ์ง badge๋ฅผ enum์ผ๋ก ๊ด๋ฆฌํ ์ง ๊ณ ๋ฏผํ๋ค๊ฐ ์ถ๋ ฅ ํค๋๋ค๋ง enum์ผ๋ก ๊ด๋ฆฌํ๋๋ฐ์, ๋ฆฌ๋ทฐ ๋จ๊ฒจ๋๋ฆฐ ๊ฒ์ ๋ต๋ณ ์ฃผ์ ํ๋ฒ๋ง ์ฌ์ฉํ๋ ๋ฌธ์์ด์ ๊ตณ์ด enum์ผ๋ก ๊ด๋ฆฌ ํ์ง ์์๋ ๋ ๊ฒ ๊ฐ๋ค๋ ๋ง์์ ๊ณต๊ณต๊ฐํด์ ๋ฐ๋๋ก badge๋ ๊ผญ enum์ผ๋ก ํ๋ ๊ฒ์ด ์ข์์ ๊ฒ์ด๋ผ๋ ์๊ฐ๋ ๋๋ค์. ๊ฐ์ฌํด์ |
@@ -0,0 +1,60 @@
+package christmas.domain;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+class EventProcessTest {
+ @DisplayName("์ด๋ฒคํธ์ ์ถฉ๋ถํ ์ ์ฒด ์ฃผ๋ฌธ ๊ธ์ก์ผ๋ก ์ ์ฒด ํํ ๋์ถ")
+ @Test
+ void takeAllBenefitWithSufficientTotalOrderPrice() {
+ Date dateInput = new Date(3);
+ Order orderInput = new Order(setUpSufficientTotalOrderPriceOrder());
+ EventProcess eventProcess = new EventProcess();
+ EventResult eventResult = eventProcess.takeAllBenefit(dateInput, orderInput);
+ Map<BenefitType, Integer> result = eventResult.getAllBenefit();
+
+ assertThat(result.get(BenefitType.GIFT)).isEqualTo(25000);
+ assertThat(result.get(BenefitType.D_DAY)).isEqualTo(1200);
+ assertThat(result.get(BenefitType.WEEKDAY)).isEqualTo(2023);
+ assertThat(result.get(BenefitType.WEEKEND)).isEqualTo(0);
+ assertThat(result.get(BenefitType.SPECIAL)).isEqualTo(1000);
+ }
+
+ private List<OrderedMenu> setUpSufficientTotalOrderPriceOrder() {
+ List<OrderedMenu> orderedMenus = new ArrayList<>();
+ orderedMenus.add(new OrderedMenu("ํด์ฐ๋ฌผํ์คํ", 2));
+ orderedMenus.add(new OrderedMenu("๋ ๋์์ธ", 1));
+ orderedMenus.add(new OrderedMenu("์ด์ฝ์ผ์ดํฌ", 1));
+
+ return orderedMenus;
+ }
+
+ @DisplayName("์ด๋ฒคํธ์ ์ถฉ๋ถํ์ง ์์ ์ ์ฒด ์ฃผ๋ฌธ ๊ธ์ก์ผ๋ก ์ ์ฒด ํํ ๋์ถ")
+ @Test
+ void takeAllBenefitWithInSufficientTotalOrderPrice() {
+ Date dateInput = new Date(26);
+ Order orderInput = new Order(setUpInSufficientTotalOrderPriceOrder());
+ EventProcess eventProcess = new EventProcess();
+ EventResult eventResult = eventProcess.takeAllBenefit(dateInput, orderInput);
+ Map<BenefitType, Integer> result = eventResult.getAllBenefit();
+
+ assertThat(result.get(BenefitType.GIFT)).isEqualTo(0);
+ assertThat(result.get(BenefitType.D_DAY)).isEqualTo(0);
+ assertThat(result.get(BenefitType.WEEKDAY)).isEqualTo(0);
+ assertThat(result.get(BenefitType.WEEKEND)).isEqualTo(0);
+ assertThat(result.get(BenefitType.SPECIAL)).isEqualTo(0);
+ }
+
+ private List<OrderedMenu> setUpInSufficientTotalOrderPriceOrder() {
+ List<OrderedMenu> orderedMenus = new ArrayList<>();
+ orderedMenus.add(new OrderedMenu("ํํ์ค", 1));
+ orderedMenus.add(new OrderedMenu("์ ๋ก์ฝ๋ผ", 1));
+
+ return orderedMenus;
+ }
+}
\ No newline at end of file | Java | ์,, ํ์คํ๊ฒ ํ
์คํธ ํ ์ ์๊ฒ ๋ค์ ๊ฐ์ฌํฉ๋๋ค!! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.