code stringlengths 41 34.3k | lang stringclasses 8
values | review stringlengths 1 4.74k |
|---|---|---|
@@ -0,0 +1,66 @@
+import {useAtomValue} from 'jotai';
+import useGetList from '../../hooks/useGetList';
+import useInfiniteScroll from '../../hooks/useInfiniteScroll';
+import * as S from './styles';
+import MovieItem from '../MovieItem';
+import SkeletonMovieList from '../skeleton/MovieList';
+import {searchTextAtom} from '../../jotai/atoms';
+
+interface MovieListProps {
+ openModal: (movieId: number) => void;
+}
+
+const MovieList = ({openModal}: MovieListProps) => {
+ const {movies, hasNextPage, fetchNextPage, isLoading, isFetchingNextPage} = useGetList();
+ const searchText = useAtomValue(searchTextAtom);
+
+ const lastElementRef = useInfiniteScroll({
+ fetchNextPage,
+ isLoading,
+ isLastPage: !hasNextPage,
+ });
+
+ const handleItemClick = (event: React.MouseEvent<HTMLUListElement>) => {
+ event.preventDefault();
+
+ const listItem = (event.target as HTMLElement).closest('li');
+ if (!listItem) return;
+
+ const id = Number(listItem.id);
+ const selectedItem = movies.find(item => item.id === id);
+
+ if (selectedItem) openModal(id);
+ };
+
+ return (
+ <S.MovieList onClick={handleItemClick}>
+ {isLoading ? (
+ <SkeletonMovieList />
+ ) : (
+ movies.map((movie, index) => {
+ const isLastMovie = index === movies.length - 1;
+
+ return (
+ <div
+ key={movie.id}
+ ref={isLastMovie ? lastElementRef : null} // ๋ง์ง๋ง ์์์ ref ์ฐ๊ฒฐ
+ >
+ <MovieItem
+ key={movie.id}
+ id={movie.id}
+ title={movie.title}
+ poster_path={movie.poster_path}
+ vote_average={movie.vote_average}
+ />
+ </div>
+ );
+ })
+ )}
+ {isFetchingNextPage && <SkeletonMovieList />}
+
+ {searchText && movies.length === 0 && <S.Message>๊ฒ์ ๊ฒฐ๊ณผ๊ฐ ์์ต๋๋ค.</S.Message>}
+ </S.MovieList>
+ );
+};
+
+export default MovieList; | Unknown | ์คํธ ์ด๋ ๊ฒ ๋ง์ง๋ง ์์์ ref๋ฅผ ๋ฃ๋ ๋ฐฉ๋ฒ๋ ์๊ตฐ์..! ์ด๋ ๊ฒ ํ๋ฉด ํ์คํ ๋ง์ง๋ง ์์๊น์ง ๋๋ฌํ์ ๋ ์๋ก์ด API๋ฅผ ํธ์ถํ ์ ์์ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,66 @@
+import {useAtomValue} from 'jotai';
+import useGetList from '../../hooks/useGetList';
+import useInfiniteScroll from '../../hooks/useInfiniteScroll';
+import * as S from './styles';
+import MovieItem from '../MovieItem';
+import SkeletonMovieList from '../skeleton/MovieList';
+import {searchTextAtom} from '../../jotai/atoms';
+
+interface MovieListProps {
+ openModal: (movieId: number) => void;
+}
+
+const MovieList = ({openModal}: MovieListProps) => {
+ const {movies, hasNextPage, fetchNextPage, isLoading, isFetchingNextPage} = useGetList();
+ const searchText = useAtomValue(searchTextAtom);
+
+ const lastElementRef = useInfiniteScroll({
+ fetchNextPage,
+ isLoading,
+ isLastPage: !hasNextPage,
+ });
+
+ const handleItemClick = (event: React.MouseEvent<HTMLUListElement>) => {
+ event.preventDefault();
+
+ const listItem = (event.target as HTMLElement).closest('li');
+ if (!listItem) return;
+
+ const id = Number(listItem.id);
+ const selectedItem = movies.find(item => item.id === id);
+
+ if (selectedItem) openModal(id);
+ };
+
+ return (
+ <S.MovieList onClick={handleItemClick}>
+ {isLoading ? (
+ <SkeletonMovieList />
+ ) : (
+ movies.map((movie, index) => {
+ const isLastMovie = index === movies.length - 1;
+
+ return (
+ <div
+ key={movie.id}
+ ref={isLastMovie ? lastElementRef : null} // ๋ง์ง๋ง ์์์ ref ์ฐ๊ฒฐ
+ >
+ <MovieItem
+ key={movie.id}
+ id={movie.id}
+ title={movie.title}
+ poster_path={movie.poster_path}
+ vote_average={movie.vote_average}
+ />
+ </div>
+ );
+ })
+ )}
+ {isFetchingNextPage && <SkeletonMovieList />}
+
+ {searchText && movies.length === 0 && <S.Message>๊ฒ์ ๊ฒฐ๊ณผ๊ฐ ์์ต๋๋ค.</S.Message>}
+ </S.MovieList>
+ );
+};
+
+export default MovieList; | Unknown | ์ด ๋ถ๋ถ์ ์๋ก์ด ์ปดํฌ๋ํธ๋ก ๋ถ๋ฆฌํด๋ณด๋ ๊ฑด ์ด๋จ๊น์? ref๋ฅผ MovieItem์ ์ง์ ๋๊ฒจ์ฃผ๋ ๋ฐฉ๋ฒ์ผ๋ก๋ ํด๋ณผ ์ ์์ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,24 @@
+import {IMAGE_BASE_URL} from '../../constants/movie';
+import filledStar from '../../assets/star_filled.png';
+import {Movie} from '../../types/movie';
+import * as S from './styles';
+import {toOneDecimalPlace} from '../../utils/number';
+
+export type MovieItemProps = Pick<Movie, 'id' | 'title' | 'poster_path' | 'vote_average'>;
+
+const MovieItem = ({id, title, poster_path, vote_average}: MovieItemProps) => (
+ <S.MovieItem id={String(id)}>
+ <a href="#">
+ <S.MovieContent>
+ <S.Thumbnail src={`${IMAGE_BASE_URL}${poster_path}`} loading="lazy" alt={`${title}-ํฌ์คํฐ`} />
+ <S.Title>{title}</S.Title>
+ <S.ScoreContainer>
+ <S.Score>{toOneDecimalPlace(vote_average)}</S.Score>
+ <S.StarImg src={filledStar} alt="" />
+ </S.ScoreContainer>
+ </S.MovieContent>
+ </a>
+ </S.MovieItem>
+);
+
+export default MovieItem; | Unknown | ์ค Pick์ ์ฌ์ฉํ๊ตฐ์! ์ฌ๋ฆฌ๋ Pick๊ณผ Omit์ ์ฌ์ฉ ๊ธฐ์ค์ด ์์๊น์? ์ ๋ Omit์ ์ฃผ๋ก ์ฌ์ฉํ๋ ํธ์ด๋ผ์์!
๊ทธ๋ฆฌ๊ณ MovieItemProps๋ ๋ค๋ฅธ ๊ณณ์์ ์ฌ์ฉ๋์ง ์๊ธฐ ๋๋ฌธ์ export๊ฐ ์์ด๋ ๋ ๊ฒ ๊ฐ์ด๋ค! |
@@ -0,0 +1,24 @@
+import {IMAGE_BASE_URL} from '../../constants/movie';
+import filledStar from '../../assets/star_filled.png';
+import {Movie} from '../../types/movie';
+import * as S from './styles';
+import {toOneDecimalPlace} from '../../utils/number';
+
+export type MovieItemProps = Pick<Movie, 'id' | 'title' | 'poster_path' | 'vote_average'>;
+
+const MovieItem = ({id, title, poster_path, vote_average}: MovieItemProps) => (
+ <S.MovieItem id={String(id)}>
+ <a href="#">
+ <S.MovieContent>
+ <S.Thumbnail src={`${IMAGE_BASE_URL}${poster_path}`} loading="lazy" alt={`${title}-ํฌ์คํฐ`} />
+ <S.Title>{title}</S.Title>
+ <S.ScoreContainer>
+ <S.Score>{toOneDecimalPlace(vote_average)}</S.Score>
+ <S.StarImg src={filledStar} alt="" />
+ </S.ScoreContainer>
+ </S.MovieContent>
+ </a>
+ </S.MovieItem>
+);
+
+export default MovieItem; | Unknown | id๋ liํ๊ทธ์ id์ธ ๊ฑธ๊น์? idํ๊ทธ๋ฅผ ๋ฃ์ด์ค ์ด์ ๊ฐ ๊ถ๊ธํด์! |
@@ -0,0 +1,66 @@
+import {useAtomValue} from 'jotai';
+import useGetList from '../../hooks/useGetList';
+import useInfiniteScroll from '../../hooks/useInfiniteScroll';
+import * as S from './styles';
+import MovieItem from '../MovieItem';
+import SkeletonMovieList from '../skeleton/MovieList';
+import {searchTextAtom} from '../../jotai/atoms';
+
+interface MovieListProps {
+ openModal: (movieId: number) => void;
+}
+
+const MovieList = ({openModal}: MovieListProps) => {
+ const {movies, hasNextPage, fetchNextPage, isLoading, isFetchingNextPage} = useGetList();
+ const searchText = useAtomValue(searchTextAtom);
+
+ const lastElementRef = useInfiniteScroll({
+ fetchNextPage,
+ isLoading,
+ isLastPage: !hasNextPage,
+ });
+
+ const handleItemClick = (event: React.MouseEvent<HTMLUListElement>) => {
+ event.preventDefault();
+
+ const listItem = (event.target as HTMLElement).closest('li');
+ if (!listItem) return;
+
+ const id = Number(listItem.id);
+ const selectedItem = movies.find(item => item.id === id);
+
+ if (selectedItem) openModal(id);
+ };
+
+ return (
+ <S.MovieList onClick={handleItemClick}>
+ {isLoading ? (
+ <SkeletonMovieList />
+ ) : (
+ movies.map((movie, index) => {
+ const isLastMovie = index === movies.length - 1;
+
+ return (
+ <div
+ key={movie.id}
+ ref={isLastMovie ? lastElementRef : null} // ๋ง์ง๋ง ์์์ ref ์ฐ๊ฒฐ
+ >
+ <MovieItem
+ key={movie.id}
+ id={movie.id}
+ title={movie.title}
+ poster_path={movie.poster_path}
+ vote_average={movie.vote_average}
+ />
+ </div>
+ );
+ })
+ )}
+ {isFetchingNextPage && <SkeletonMovieList />}
+
+ {searchText && movies.length === 0 && <S.Message>๊ฒ์ ๊ฒฐ๊ณผ๊ฐ ์์ต๋๋ค.</S.Message>}
+ </S.MovieList>
+ );
+};
+
+export default MovieList; | Unknown | infiniteQuery์์ ์๋ก์ด ๋ฐฐ์ด์ ๊ธฐ์กด ๋ฐฐ์ด์ ๋ฃ์ด์ฃผ๊ณ ์๊ธฐ ๋๋ฌธ์ ์ด ๋ถ๋ถ์ ์์ด๋ ๋ ๊ฒ ๊ฐ์์~! |
@@ -0,0 +1,30 @@
+import styled from '@emotion/styled';
+import searchImg from '../../assets/search_button.png';
+
+export const Search = styled.section`
+ display: flex;
+ height: 3rem;
+
+ background: #fff;
+ padding: 8px;
+ border-radius: 4px;
+
+ button {
+ width: 14px;
+ border: 0;
+ text-indent: -1000rem;
+ background: url(${searchImg}) no-repeat center center;
+ background-size: contain;
+ }
+`;
+
+export const SearchInput = styled.input`
+ font-size: 13px;
+
+ border: 0;
+
+ &:focus {
+ outline: none;
+ border: none;
+ }
+`; | TypeScript | form์ผ๋ก๋ ์ฒ๋ฆฌํด๋ณผ ์ ์์ ๊ฒ ๊ฐ์๋ฐ ์ฌ๋ฆฌ๋ ์ด๋ค ๋ฐฉ๋ฒ์ด ๋ ํธํ ๊น์? |
@@ -0,0 +1,17 @@
+import React, {useRef} from 'react';
+
+import * as S from './styles.ts';
+import useModalClose from '../../../hooks/useModalClose.ts';
+
+interface ModalBackgroundProps {
+ closeModal: (() => void) | null;
+ children?: React.ReactNode;
+}
+
+const ModalBackground = ({children, closeModal}: ModalBackgroundProps) => {
+ const modalBackgroundRef = useRef<HTMLDivElement>(null);
+ useModalClose({closeModal, modalBackgroundRef});
+
+ return <S.ModalBackground ref={modalBackgroundRef}>{children}</S.ModalBackground>;
+};
+export default ModalBackground; | Unknown | React.FC๋ฅผ ์ฌ์ฉํ ์ด์ ๊ฐ ์์๊น์?! |
@@ -0,0 +1,81 @@
+import {BASE_URL, POPULAR_MOVIE_URL, SEARCH_URL} from '../constants/movie';
+import {MovieDetail, MovieList} from '../types/movie';
+import {createApiErrorMessage} from '../utils/error';
+
+export const getMovieList = async ({pageParam = 1}: {pageParam?: number}) => {
+ const params = {
+ api_key: import.meta.env.VITE_TMDB_TOKEN,
+ language: 'ko-KR',
+ page: String(pageParam),
+ };
+ const endpoint = `${POPULAR_MOVIE_URL}?${new URLSearchParams(params).toString()}`;
+
+ const response = await fetch(endpoint, {
+ method: 'GET',
+ headers: {
+ Authorization: `Bearer ${import.meta.env.VITE_TMDB_TOKEN}`,
+ accept: 'application/json',
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error(createApiErrorMessage(response.status));
+ }
+
+ const data = await response.json();
+ return data as MovieList;
+};
+
+interface GetSearchedMovieListParam {
+ pageParam?: number;
+ title: string;
+}
+
+export const getSearchedMovieList = async ({pageParam = 1, title}: GetSearchedMovieListParam) => {
+ const params = {
+ api_key: import.meta.env.VITE_TMDB_TOKEN,
+ query: title, // ๊ฒ์์ด
+ language: 'ko-KR',
+ page: String(pageParam),
+ };
+
+ const endpoint = `${SEARCH_URL}?${new URLSearchParams(params).toString()}`;
+
+ const response = await fetch(endpoint, {
+ method: 'GET',
+ headers: {
+ Authorization: `Bearer ${import.meta.env.VITE_TMDB_TOKEN}`,
+ accept: 'application/json',
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error(createApiErrorMessage(response.status));
+ }
+
+ const data = await response.json();
+ return data as MovieList;
+};
+
+export const getMovieDetail = async (movieId: number) => {
+ const params = {
+ api_key: import.meta.env.VITE_TMDB_TOKEN,
+ language: 'ko-KR',
+ };
+ const endpoint = `${BASE_URL}/movie/${movieId}?${new URLSearchParams(params).toString()}`;
+
+ const response = await fetch(endpoint, {
+ method: 'GET',
+ headers: {
+ Authorization: `Bearer ${import.meta.env.VITE_TMDB_TOKEN}`,
+ accept: 'application/json',
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error(createApiErrorMessage(response.status));
+ }
+
+ const data = await response.json();
+ return data as MovieDetail;
+}; | TypeScript | ์๋ฒ์์ ๋ฐ์ดํฐ๋ฅผ ํธ์ถํ๋ ์ง์ฐ ์๊ฐ์ด ์๊ธฐ ๋๋ฌธ์ delay๋ฅผ ๊ฑธ์ง ์์๋ ์ข์ ๊ฒ ๊ฐ์์! ์ ๋ ๊ตฌํํ ๋ ๋คํธ์ํฌ ์๋๋ performance์์ CPU๋ฅผ ์ ์ดํ๋ฉด์ ํ
์คํธํ๋ต๋๋ค๐ |
@@ -0,0 +1,59 @@
+import React, {Component, ReactNode} from 'react';
+
+import {TOAST_ERROR} from '../../../constants/error';
+
+export interface FallbackProps {
+ error: Error;
+ resetErrorBoundary: () => void;
+}
+
+interface ErrorBoundaryProps {
+ fallback: React.ComponentType<FallbackProps>;
+ children: ReactNode;
+ resetQueryError?: () => void;
+}
+
+interface ErrorBoundaryState {
+ hasError: boolean;
+ error: Error | null;
+}
+
+class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
+ constructor(props: ErrorBoundaryProps) {
+ super(props);
+ this.state = {hasError: false, error: null};
+ }
+
+ static getDerivedStateFromError(error: Error): ErrorBoundaryState {
+ // ์๋ฌ๊ฐ ๋ฐ์ํ๋ฉด ์ํ๋ฅผ ์
๋ฐ์ดํธํ์ฌ fallback์ ํ์
+ return {hasError: true, error};
+ }
+
+ componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
+ // ์๋ฌ๋ฅผ ๋ก๊น
+ console.error('ErrorBoundary caught an error', error, errorInfo);
+ }
+
+ resetErrorBoundary = () => {
+ const {resetQueryError} = this.props;
+ if (resetQueryError) resetQueryError();
+ this.setState({hasError: false, error: null});
+ };
+
+ render() {
+ const {hasError, error} = this.state;
+ const {children, fallback: FallbackComponent} = this.props;
+
+ // ์๋ฌ ๋ฉ์ธ์ง์ TOAST_ERROR ํฌํจํ๋ฉด fallback ๋์์์ ์ ์ธ
+ const isHandleError = !error?.message.includes(TOAST_ERROR);
+
+ // ์๋ฌ๊ฐ ๋ฐ์ํ์ ๋ fallback ์ปดํฌ๋ํธ๋ก ๋์ฒด
+ if (hasError && error && isHandleError) {
+ return <FallbackComponent error={error} resetErrorBoundary={this.resetErrorBoundary} />;
+ }
+
+ return children;
+ }
+}
+
+export default ErrorBoundary; | Unknown | ์คํ ํ ์คํธ ๊ตฌํ๋ ๊ถ๊ธํด์ง๋ค์๐คฉ ๊ธฐ๋ํด๋ด๋....์ข์๊น์....?ใ
ใ
ใ
ใ
ใ
ใ
|
@@ -0,0 +1,66 @@
+import {useAtomValue} from 'jotai';
+import useGetList from '../../hooks/useGetList';
+import useInfiniteScroll from '../../hooks/useInfiniteScroll';
+import * as S from './styles';
+import MovieItem from '../MovieItem';
+import SkeletonMovieList from '../skeleton/MovieList';
+import {searchTextAtom} from '../../jotai/atoms';
+
+interface MovieListProps {
+ openModal: (movieId: number) => void;
+}
+
+const MovieList = ({openModal}: MovieListProps) => {
+ const {movies, hasNextPage, fetchNextPage, isLoading, isFetchingNextPage} = useGetList();
+ const searchText = useAtomValue(searchTextAtom);
+
+ const lastElementRef = useInfiniteScroll({
+ fetchNextPage,
+ isLoading,
+ isLastPage: !hasNextPage,
+ });
+
+ const handleItemClick = (event: React.MouseEvent<HTMLUListElement>) => {
+ event.preventDefault();
+
+ const listItem = (event.target as HTMLElement).closest('li');
+ if (!listItem) return;
+
+ const id = Number(listItem.id);
+ const selectedItem = movies.find(item => item.id === id);
+
+ if (selectedItem) openModal(id);
+ };
+
+ return (
+ <S.MovieList onClick={handleItemClick}>
+ {isLoading ? (
+ <SkeletonMovieList />
+ ) : (
+ movies.map((movie, index) => {
+ const isLastMovie = index === movies.length - 1;
+
+ return (
+ <div
+ key={movie.id}
+ ref={isLastMovie ? lastElementRef : null} // ๋ง์ง๋ง ์์์ ref ์ฐ๊ฒฐ
+ >
+ <MovieItem
+ key={movie.id}
+ id={movie.id}
+ title={movie.title}
+ poster_path={movie.poster_path}
+ vote_average={movie.vote_average}
+ />
+ </div>
+ );
+ })
+ )}
+ {isFetchingNextPage && <SkeletonMovieList />}
+
+ {searchText && movies.length === 0 && <S.Message>๊ฒ์ ๊ฒฐ๊ณผ๊ฐ ์์ต๋๋ค.</S.Message>}
+ </S.MovieList>
+ );
+};
+
+export default MovieList; | Unknown | ์ ์ด ๋ถ๋ถ๋๋ฌธ์ ์ํ๊ฐ 2๋ฒ ๋ณด์๋ ๊ฑฐ๋ค์๐ ๋๋ถ์ ์์์ฐจ๋ ธ์ด์! |
@@ -1,5 +1,22 @@
+import MovieListContainer from './components/MovieListContainer';
+import Header from './components/Header';
+import QueryErrorBoundary from './components/common/QueryResetErrorboundary';
+
function App() {
- return <div>hi</div>;
+ return (
+ <div style={AppStyle}>
+ <QueryErrorBoundary>
+ <Header />
+ <main>
+ <MovieListContainer />
+ </main>
+ </QueryErrorBoundary>
+ </div>
+ );
}
+const AppStyle = {
+ paddingBottom: '48px',
+};
+
export default App; | Unknown | ์ฌ์ค ์๋ ์ฝ๋๋ฅผ ๊ฐ์ ธ์์ต๋๋คใ
ใ
ใ
ใ
|
@@ -0,0 +1,56 @@
+import * as S from './styles';
+import Portal from '../common/Portal';
+import ModalBackground from '../common/ModalBackground';
+import useGetMovieDetail from '../../hooks/useGetMovieDetail';
+import {IMAGE_BASE_URL} from '../../constants/movie';
+import {toOneDecimalPlace} from '../../utils/number';
+import filledStar from '../../assets/star_filled.png';
+import MyRating from '../MyRating';
+
+interface DetailModalProps {
+ selectedMovieId: number;
+ closeModal: () => void;
+}
+
+const DetailModal = ({selectedMovieId, closeModal}: DetailModalProps) => {
+ const {data} = useGetMovieDetail(selectedMovieId);
+
+ const {poster_path, vote_average, title, overview, genres} = data;
+
+ return (
+ <Portal>
+ <ModalBackground closeModal={closeModal}>
+ <S.ModalContainer>
+ <S.Header>
+ <h2>{title}</h2>
+ <button type="button" onClick={closeModal}>
+ ๋ซ๊ธฐ
+ </button>
+ </S.Header>
+
+ <S.Content>
+ <S.Poster src={`${IMAGE_BASE_URL}${poster_path}`} alt={`${title} ํฌ์คํฐ`} />
+
+ <S.RightContent>
+ <S.ShortInfo>
+ <S.Genres>{genres.map(genre => genre.name).join(', ')}</S.Genres>
+ <S.Rate>
+ <span>{toOneDecimalPlace(vote_average)}</span>
+ <img src={filledStar} alt="" />
+ </S.Rate>
+ </S.ShortInfo>
+
+ <S.Overview>{overview}</S.Overview>
+
+ <S.MyRatingWrapper>
+ <MyRating movieId={selectedMovieId} />
+ </S.MyRatingWrapper>
+ </S.RightContent>
+ </S.Content>
+ </S.ModalContainer>
+ </ModalBackground>
+ </Portal>
+ );
+};
+
+export default DetailModal; | Unknown | ์ฌ์ค ์ ๋ 1์ด ์ธ์ ๋ฆฌ์ ์งง์ ๋ก๋ฉ ์๊ฐ์ด๋ผ๋ฉด ์ค์ผ๋ ํค์ ๊ฑฐ๋ ๊ฒ ์คํ๋ ค ์ ์ ์๋ค๊ณ ์๊ฐํด์ ์ ํธํ์ง ์๋ ํธ์ธ๋ฐ, ๋ชจ๋ฌ์ 1์ด๋์ ๋ก๋ฉ์ด์ง๋ง ํ๋ฉด ์ ํ์ด ๋ฐ๋ก ์ผ์ด๋ ๊ฒ์ ๊ธฐ๋ํ๊ณ ํด๋ฆญํ๋ ๊ฑฐ๋๊น ๋ชจ๋ฌ์ ๋ฐ๋ก ๋์ฐ๋ ๋ก๋ฉ UI๋ฅผ ๋ณด์ฌ์ฃผ๋ ๊ฒ ํจ์ฌ ์์ฐ์ค๋ฌ์ธ ๊ฒ ๊ฐ๋ค์!
๊ฐ๋ฐํ๋ฉด์ ๋๋ ๋ ๊ฒ๋ง ๊ณ์ ๋๋ฌ์ ๋๋ฆฐ ์ค๋ ๋ชจ๋ฅด๊ณ ์์๋ค์...ใ
ใ
ใ
ใ
ใ
|
@@ -0,0 +1,81 @@
+import {BASE_URL, POPULAR_MOVIE_URL, SEARCH_URL} from '../constants/movie';
+import {MovieDetail, MovieList} from '../types/movie';
+import {createApiErrorMessage} from '../utils/error';
+
+export const getMovieList = async ({pageParam = 1}: {pageParam?: number}) => {
+ const params = {
+ api_key: import.meta.env.VITE_TMDB_TOKEN,
+ language: 'ko-KR',
+ page: String(pageParam),
+ };
+ const endpoint = `${POPULAR_MOVIE_URL}?${new URLSearchParams(params).toString()}`;
+
+ const response = await fetch(endpoint, {
+ method: 'GET',
+ headers: {
+ Authorization: `Bearer ${import.meta.env.VITE_TMDB_TOKEN}`,
+ accept: 'application/json',
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error(createApiErrorMessage(response.status));
+ }
+
+ const data = await response.json();
+ return data as MovieList;
+};
+
+interface GetSearchedMovieListParam {
+ pageParam?: number;
+ title: string;
+}
+
+export const getSearchedMovieList = async ({pageParam = 1, title}: GetSearchedMovieListParam) => {
+ const params = {
+ api_key: import.meta.env.VITE_TMDB_TOKEN,
+ query: title, // ๊ฒ์์ด
+ language: 'ko-KR',
+ page: String(pageParam),
+ };
+
+ const endpoint = `${SEARCH_URL}?${new URLSearchParams(params).toString()}`;
+
+ const response = await fetch(endpoint, {
+ method: 'GET',
+ headers: {
+ Authorization: `Bearer ${import.meta.env.VITE_TMDB_TOKEN}`,
+ accept: 'application/json',
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error(createApiErrorMessage(response.status));
+ }
+
+ const data = await response.json();
+ return data as MovieList;
+};
+
+export const getMovieDetail = async (movieId: number) => {
+ const params = {
+ api_key: import.meta.env.VITE_TMDB_TOKEN,
+ language: 'ko-KR',
+ };
+ const endpoint = `${BASE_URL}/movie/${movieId}?${new URLSearchParams(params).toString()}`;
+
+ const response = await fetch(endpoint, {
+ method: 'GET',
+ headers: {
+ Authorization: `Bearer ${import.meta.env.VITE_TMDB_TOKEN}`,
+ accept: 'application/json',
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error(createApiErrorMessage(response.status));
+ }
+
+ const data = await response.json();
+ return data as MovieDetail;
+}; | TypeScript | ์ด ๋ถ๋ถ์ ํ๋ก์ ํธ ํ ๋ ๊ณ์ ์จ์์ ๊ทธ๋ฐ๊ฐ ๋ณ ์๊ฐ ์์ด ์ผ์ด์...ใ
(ํฐ ๋ฌธ์ ๊ฐ ์์๋ค๋ฉด ๋๊ตฐ๊ฐ ์ง์ ํด์คฌ๊ฒ ์ง ํ๋ ์์ผํจ) ๋น์ฅ ๋๋ ์๊ฐ์ ์ผ๋ฐ์ ์ธ ๊ฒฝ์ฐ์๋ ๋จ์ธ์ ํด๋ ๋ฌธ์ ๋ ์์ ๊ฒ ๊ฐ๋ค๋ ์๊ฐ์
๋๋ค. ํ์ง๋ง ์๋ฒ๊ฐ ๊นจ์ ธ์ ์ด์ํ ๊ฐ์ ๋ณด๋ด์ฃผ๋ ๊ฒฝ์ฐ์๋ ๋๋ฒ๊น
ํ๊ธฐ ์ด๋ ค์ธ ์๋ ์์ ๊ฒ ๊ฐ์์.
ํ์
์ถ๋ก ์ as๊ฐ ์ ์ด์ ์ด๊ฑธ๋ก ์ถ๋ก ํด๋ผ! ๋ผ๊ณ ๋ช
๋ นํ๋ ๊ฑฐ๋๊น ๋ฌธ์ ์์ด ๋๋ ๊ฒ ๊ฐ์ต๋๋ค. ์ค์ ๋ก ๋ฆฌ์กํธ ์ฟผ๋ฆฌ ์ฝ๋๋ฅผ ์ธ ๋ ์ ๋ค๋ฆญ์ผ๋ก ๋ฆฌํด ํ์
์ ๋ช
์ํด์ฃผ์ง ์์๋ ์์์ data ํ์
์ ์ถ๋ก ํด์ฃผ๋๋ผ๊ณ ์.
๋ง์ฝ ๊ณ ์ณ๋ณธ๋ค๋ฉด Promise์ ์ ๋ค๋ฆญ์ผ๋ก ํ์
์ ๊ฑธ์ด์ค ๊ฒ ๊ฐ์ต๋๋ค~! |
@@ -0,0 +1,47 @@
+package nextstep.security.authorization.manager;
+
+import nextstep.security.authentication.Authentication;
+import nextstep.security.authentication.AuthenticationException;
+import nextstep.security.authorization.AuthorizationDecision;
+import nextstep.security.authorization.ForbiddenException;
+import nextstep.security.authorization.Secured;
+import org.aopalliance.intercept.MethodInvocation;
+import org.springframework.core.annotation.AnnotationUtils;
+
+import java.lang.reflect.Method;
+import java.util.Collection;
+import java.util.Set;
+
+public class SecuredAuthorizationManager implements AuthorizationManager<MethodInvocation> {
+
+ private final AuthorizationManager<Collection<String>> authorizationManager;
+
+ public SecuredAuthorizationManager() {
+ this.authorizationManager = new AuthoritiesAuthorizationManager();
+ }
+
+ @Override
+ public AuthorizationDecision check(Authentication authentication, MethodInvocation invocation) {
+ Method method = invocation.getMethod();
+
+ if (authentication == null) {
+ throw new ForbiddenException();
+ }
+
+ if (method.isAnnotationPresent(Secured.class)) {
+ Secured secured = getSecured(method);
+ return this.authorizationManager.check(authentication, Set.of(secured.value()));
+ }
+
+ return AuthorizationDecision.ACCESS_DENIED;
+ }
+
+ private Secured getSecured(Method method) {
+ Secured secured = AnnotationUtils.findAnnotation(method, Secured.class);
+ if (secured == null) {
+ throw new IllegalStateException();
+ }
+
+ return secured;
+ }
+} | Java | ```suggestion
if (authentication == null) {
return AuthorizationDecision.ACCESS_DENIED;
}
```
๊ถํ์ ๋ฐ๋ฅธ ์์ธ ์ฒ๋ฆฌ๋ Interceptor์ ์ญํ ๋ก ๋๊ฒจ์ฃผ๋ฉด ์ด๋จ๊น์? |
@@ -0,0 +1,28 @@
+package nextstep.security.authorization.manager;
+
+import jakarta.servlet.http.HttpServletRequest;
+import nextstep.security.authentication.Authentication;
+import nextstep.security.authorization.AuthorizationDecision;
+import nextstep.security.authorization.access.RequestMatcherEntry;
+
+import java.util.List;
+
+public class RequestMatcherDelegatingAuthorizationManager implements AuthorizationManager<HttpServletRequest> {
+
+ private final List<RequestMatcherEntry<AuthorizationManager<HttpServletRequest>>> mappings;
+
+ public RequestMatcherDelegatingAuthorizationManager(List<RequestMatcherEntry<AuthorizationManager<HttpServletRequest>>> mappings) {
+ this.mappings = mappings;
+ }
+
+ @Override
+ public AuthorizationDecision check(Authentication authentication, HttpServletRequest httpServletRequest) {
+ for (RequestMatcherEntry<AuthorizationManager<HttpServletRequest>> entry : mappings) {
+ if (entry.getMatcher().matches(httpServletRequest)) {
+ return entry.getManager().check(authentication, httpServletRequest);
+ }
+ }
+
+ return AuthorizationDecision.ACCESS_DENIED;
+ }
+} | Java | AuthorizationManager์ ๋ํ ์ถ์ํ๋ฅผ ์ ํด์ฃผ์
จ๋ค์ ๐ |
@@ -1,13 +1,21 @@
package nextstep.app;
+import jakarta.servlet.http.HttpServletRequest;
import nextstep.app.domain.Member;
import nextstep.app.domain.MemberRepository;
import nextstep.security.authentication.AuthenticationException;
import nextstep.security.authentication.BasicAuthenticationFilter;
import nextstep.security.authentication.UsernamePasswordAuthenticationFilter;
-import nextstep.security.authorization.CheckAuthenticationFilter;
-import nextstep.security.authorization.SecuredAspect;
+import nextstep.security.authorization.AuthorizationFilter;
import nextstep.security.authorization.SecuredMethodInterceptor;
+import nextstep.security.authorization.manager.AuthenticatedAuthorizationManager;
+import nextstep.security.authorization.manager.AuthorityAuthorizationManager;
+import nextstep.security.authorization.manager.AuthorizationManager;
+import nextstep.security.authorization.manager.RequestMatcherDelegatingAuthorizationManager;
+import nextstep.security.authorization.manager.SecuredAuthorizationManager;
+import nextstep.security.authorization.access.AnyRequestMatcher;
+import nextstep.security.authorization.access.MvcRequestMatcher;
+import nextstep.security.authorization.access.RequestMatcherEntry;
import nextstep.security.config.DefaultSecurityFilterChain;
import nextstep.security.config.DelegatingFilterProxy;
import nextstep.security.config.FilterChainProxy;
@@ -18,7 +26,9 @@
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.http.HttpMethod;
+import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@@ -42,23 +52,14 @@ public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilte
return new FilterChainProxy(securityFilterChains);
}
- @Bean
- public SecuredMethodInterceptor securedMethodInterceptor() {
- return new SecuredMethodInterceptor();
- }
-// @Bean
-// public SecuredAspect securedAspect() {
-// return new SecuredAspect();
-// }
-
@Bean
public SecurityFilterChain securityFilterChain() {
return new DefaultSecurityFilterChain(
List.of(
new SecurityContextHolderFilter(),
new UsernamePasswordAuthenticationFilter(userDetailsService()),
new BasicAuthenticationFilter(userDetailsService()),
- new CheckAuthenticationFilter()
+ new AuthorizationFilter(requestAuthorizationManager())
)
);
}
@@ -87,4 +88,36 @@ public Set<String> getAuthorities() {
};
};
}
+
+ @Bean
+ public SecuredMethodInterceptor securedMethodInterceptor() {
+ return new SecuredMethodInterceptor(
+ new SecuredAuthorizationManager()
+ );
+ }
+
+ @Bean
+ public RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager() {
+ List<RequestMatcherEntry<AuthorizationManager<HttpServletRequest>>> mappings = new ArrayList<>();
+
+ mappings.add(new RequestMatcherEntry<>(
+ new MvcRequestMatcher(HttpMethod.GET, "/members/me"),
+ AuthenticatedAuthorizationManager.authenticated())
+ );
+
+ mappings.add(new RequestMatcherEntry<>(
+ new MvcRequestMatcher(HttpMethod.GET, "/members"),
+ AuthorityAuthorizationManager.hasAuthority("ADMIN")));
+
+ mappings.add(new RequestMatcherEntry<>(
+ new MvcRequestMatcher(HttpMethod.GET, "/search"),
+ AuthorityAuthorizationManager.permitAll())
+ );
+ mappings.add(new RequestMatcherEntry<>(
+ new AnyRequestMatcher(),
+ AuthorityAuthorizationManager.permitAll())
+ );
+
+ return new RequestMatcherDelegatingAuthorizationManager(mappings);
+ }
} | Java | `๊ทธ ์ธ ๋ชจ๋ ์์ฒญ์ ๊ถํ์ ์ ํํ๊ธฐ ์ํด DenyAllAuthorizationManager๋ก ์ฒ๋ฆฌ`
ํด๋น ์๊ตฌ์ฌํญ์ด ๋ฐ์ ์๋์ด ์๋ ๊ฒ ๊ฐ๋ค์! |
@@ -1,13 +1,21 @@
package nextstep.app;
+import jakarta.servlet.http.HttpServletRequest;
import nextstep.app.domain.Member;
import nextstep.app.domain.MemberRepository;
import nextstep.security.authentication.AuthenticationException;
import nextstep.security.authentication.BasicAuthenticationFilter;
import nextstep.security.authentication.UsernamePasswordAuthenticationFilter;
-import nextstep.security.authorization.CheckAuthenticationFilter;
-import nextstep.security.authorization.SecuredAspect;
+import nextstep.security.authorization.AuthorizationFilter;
import nextstep.security.authorization.SecuredMethodInterceptor;
+import nextstep.security.authorization.manager.AuthenticatedAuthorizationManager;
+import nextstep.security.authorization.manager.AuthorityAuthorizationManager;
+import nextstep.security.authorization.manager.AuthorizationManager;
+import nextstep.security.authorization.manager.RequestMatcherDelegatingAuthorizationManager;
+import nextstep.security.authorization.manager.SecuredAuthorizationManager;
+import nextstep.security.authorization.access.AnyRequestMatcher;
+import nextstep.security.authorization.access.MvcRequestMatcher;
+import nextstep.security.authorization.access.RequestMatcherEntry;
import nextstep.security.config.DefaultSecurityFilterChain;
import nextstep.security.config.DelegatingFilterProxy;
import nextstep.security.config.FilterChainProxy;
@@ -18,7 +26,9 @@
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.http.HttpMethod;
+import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@@ -42,23 +52,14 @@ public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilte
return new FilterChainProxy(securityFilterChains);
}
- @Bean
- public SecuredMethodInterceptor securedMethodInterceptor() {
- return new SecuredMethodInterceptor();
- }
-// @Bean
-// public SecuredAspect securedAspect() {
-// return new SecuredAspect();
-// }
-
@Bean
public SecurityFilterChain securityFilterChain() {
return new DefaultSecurityFilterChain(
List.of(
new SecurityContextHolderFilter(),
new UsernamePasswordAuthenticationFilter(userDetailsService()),
new BasicAuthenticationFilter(userDetailsService()),
- new CheckAuthenticationFilter()
+ new AuthorizationFilter(requestAuthorizationManager())
)
);
}
@@ -87,4 +88,36 @@ public Set<String> getAuthorities() {
};
};
}
+
+ @Bean
+ public SecuredMethodInterceptor securedMethodInterceptor() {
+ return new SecuredMethodInterceptor(
+ new SecuredAuthorizationManager()
+ );
+ }
+
+ @Bean
+ public RequestMatcherDelegatingAuthorizationManager requestAuthorizationManager() {
+ List<RequestMatcherEntry<AuthorizationManager<HttpServletRequest>>> mappings = new ArrayList<>();
+
+ mappings.add(new RequestMatcherEntry<>(
+ new MvcRequestMatcher(HttpMethod.GET, "/members/me"),
+ AuthenticatedAuthorizationManager.authenticated())
+ );
+
+ mappings.add(new RequestMatcherEntry<>(
+ new MvcRequestMatcher(HttpMethod.GET, "/members"),
+ AuthorityAuthorizationManager.hasAuthority("ADMIN")));
+
+ mappings.add(new RequestMatcherEntry<>(
+ new MvcRequestMatcher(HttpMethod.GET, "/search"),
+ AuthorityAuthorizationManager.permitAll())
+ );
+ mappings.add(new RequestMatcherEntry<>(
+ new AnyRequestMatcher(),
+ AuthorityAuthorizationManager.permitAll())
+ );
+
+ return new RequestMatcherDelegatingAuthorizationManager(mappings);
+ }
} | Java | ๋ช
ํํ ์ญํ ์ ๊ตฌ๋ถํ๊ธฐ ์ํด AuthenticatedAuthorizationManager์ HasAuthorityAuthorizationManager๋ฅผ ๋ถ๋ฆฌํด์ ๊ตฌํํด๋ด๋ ์ข๊ฒ ๋ค์! |
@@ -1,13 +1,19 @@
package nextstep.app;
+import jakarta.servlet.http.HttpServletRequest;
import nextstep.app.domain.Member;
import nextstep.app.domain.MemberRepository;
import nextstep.security.authentication.AuthenticationException;
import nextstep.security.authentication.BasicAuthenticationFilter;
import nextstep.security.authentication.UsernamePasswordAuthenticationFilter;
-import nextstep.security.authorization.CheckAuthenticationFilter;
-import nextstep.security.authorization.SecuredAspect;
+import nextstep.security.authorization.AuthorizationFilter;
import nextstep.security.authorization.SecuredMethodInterceptor;
+import nextstep.security.authorization.manager.AuthenticatedAuthorizationManager;
+import nextstep.security.authorization.manager.AuthorizationManager;
+import nextstep.security.authorization.manager.DenyAllAuthorizationManager;
+import nextstep.security.authorization.manager.HasAuthorityAuthorizationManager;
+import nextstep.security.authorization.manager.PermitAllAuthorizationManager;
+import nextstep.security.authorization.manager.RequestAuthorizationManager;
import nextstep.security.config.DefaultSecurityFilterChain;
import nextstep.security.config.DelegatingFilterProxy;
import nextstep.security.config.FilterChainProxy;
@@ -22,6 +28,10 @@
import java.util.List;
import java.util.Set;
+import static nextstep.security.authorization.matcher.RequestMatcherEntry.createDefaultMatcher;
+import static nextstep.security.authorization.matcher.RequestMatcherEntry.createMvcMatcher;
+import static org.springframework.http.HttpMethod.GET;
+
@EnableAspectJAutoProxy
@Configuration
public class SecurityConfig {
@@ -46,19 +56,20 @@ public FilterChainProxy filterChainProxy(List<SecurityFilterChain> securityFilte
public SecuredMethodInterceptor securedMethodInterceptor() {
return new SecuredMethodInterceptor();
}
-// @Bean
-// public SecuredAspect securedAspect() {
-// return new SecuredAspect();
-// }
@Bean
public SecurityFilterChain securityFilterChain() {
+ final AuthorizationManager<HttpServletRequest> authorizationManager = new RequestAuthorizationManager(List.of(
+ createMvcMatcher(GET, "/members", new HasAuthorityAuthorizationManager<>("ADMIN")),
+ createMvcMatcher(GET, "/members/me", new AuthenticatedAuthorizationManager<>()),
+ createMvcMatcher(GET, "/search", new PermitAllAuthorizationManager<>())
+ ), createDefaultMatcher(new DenyAllAuthorizationManager<>()));
return new DefaultSecurityFilterChain(
List.of(
new SecurityContextHolderFilter(),
new UsernamePasswordAuthenticationFilter(userDetailsService()),
new BasicAuthenticationFilter(userDetailsService()),
- new CheckAuthenticationFilter()
+ new AuthorizationFilter(authorizationManager)
)
);
} | Java | config์ ์ ์ถ๊ฐํด์ฃผ์
จ๋ค์ ๐
์๋ฐ ์ปจ๋ฒค์
์ ํด๋์ค ๋ค์ด๋ฐ์ ๋ช
์ฌ๋ฅผ ํ์ฉํ๊ธฐ ๋๋ฌธ์ `Has`๋ณด๋ค๋ ์กฐ๊ธ ๋ ์ ์ ํ ๋ค์ด๋ฐ์ด ๋ค์ด๊ฐ๋ฉด ์ข์ ๊ฒ ๊ฐ์์.
https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html |
@@ -0,0 +1,8 @@
+package nextstep.security.authorization.manager;
+
+import nextstep.security.authentication.Authentication;
+
+@FunctionalInterface
+public interface AuthorizationManager<T> {
+ AuthorizationDecision check(Authentication authentication, T target);
+} | Java | ์ต๊ทผ spring security ๋ฒ์ ์์๋ `check`๋ ์ฌ์ค deprecated๋์๋๋ฐ์. ์ผ๋ฐ์ ์ผ๋ก๋ ์ ์์๋ค์ํผ ๋๋ถ๋ถ์ ์คํ์์ค๋ ๊ฒฐ๊ตญ ์ถ์ํ๋ฅผ ๋ฐ๋ผ๋ณด๊ณ ์งํํ๋ คํ๋ฉฐ `AuthorizationDecision`์ด spring security ๋ด์์๋ ํด๋์ค ๊ตฌํ์ฒด๋ก ๋์ด์๊ณ , ๋ฒ์ ์ด ์ฌ๋ผ๊ฐ๋ ๊ณผ์ ์์ ์ด๋ถ๋ถ ๋ํ ์ถ์ํ๋์์ด์.
์ต๊ทผ ๋ฒ์ ์์๋ ๊ทธ๋์ ๊ตฌํ์ฒด๋ฅผ ๋ฐํํ๋ `AuthorizationDecision`์ ์ฌ์ฉํ๊ธฐ๋ณด๋ค๋ ์ด๋ฅผ ์ฌ์ฉํ๋ default ๋ฉ์๋์ธ `authorize` ์ฌ์ฉ์ ๊ถ์ฅํ๊ณ ์์ต๋๋ค.
https://github.com/franticticktick/spring-security/blob/main/core/src/main/java/org/springframework/security/authorization/AuthorizationManager.java
https://github.com/spring-projects/spring-security/pull/14712
https://github.com/spring-projects/spring-security/pull/14846 |
@@ -0,0 +1,8 @@
+package nextstep.security.authorization.manager;
+
+import nextstep.security.authentication.Authentication;
+
+@FunctionalInterface
+public interface AuthorizationManager<T> {
+ AuthorizationDecision check(Authentication authentication, T target);
+} | Java | ์ ํ ์๊ตฌ์ฌํญ์๋ `verify`๋ ์๋๋ฐ์. ์ ์๋์ `verfiy`๋ ์ด๋ค ์ํฉ์์ ์ฌ์ฉํ๋ฉด ์ข์๋งํ๋ค๊ณ ์๊ฐํ์๋์? |
@@ -0,0 +1,19 @@
+package nextstep.security.authorization.manager;
+
+public enum AuthorizationDecision {
+ GRANTED(true), NOT_GRANTED(false);
+
+ private final boolean granted;
+
+ AuthorizationDecision(boolean granted) {
+ this.granted = granted;
+ }
+
+ public static AuthorizationDecision of(boolean granted) {
+ return granted ? GRANTED : NOT_GRANTED;
+ }
+
+ public boolean isGranted() {
+ return this.granted;
+ }
+} | Java | `AuthorizationManager.check`๋ฅผ ์ด์ด์ ์ด์ผ๊ธฐํ๋ฉด, enum์ ์ฌ์ฉํ๊ธฐ์ ์ ์ ํ์ง ๊ณ ๋ คํด๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ์์.
๋ฌผ๋ก ํ์ฌ๋ granted ์กฐ๊ฑด์ด true์ false๋ฐ์ ์๋ ์ํฉ์ด๊ธด ํ์ง๋ง ํ์ฅ์ฑ์ ๊ณ ๋ คํด๋ณธ๋ค๋ฉด interface๋ก ๊ตฌ์ฑํ๋ ๊ฒ์ด ๋ง์ง ์์๊น์? ๊ถํ์ด true์ธ์ง, false์ธ์ง ๋ด์๋ ์๋ ์์ง๋ง ์ด๋ค ๊ถํ์ธ์ง๋ ๋ณด์ ํ ์ํฉ์ด ์กด์ฌํ์ง ์์๊น์? |
@@ -0,0 +1,20 @@
+package nextstep.security.authorization.matcher;
+
+import jakarta.servlet.http.HttpServletRequest;
+
+public class AnyRequestMatcher implements RequestMatcher {
+ private AnyRequestMatcher() {}
+
+ public static AnyRequestMatcher getInstance() {
+ return SingletonHolder.INSTANCE;
+ }
+
+ @Override
+ public boolean matches(HttpServletRequest request) {
+ return true;
+ }
+
+ private final static class SingletonHolder {
+ private static final AnyRequestMatcher INSTANCE = new AnyRequestMatcher();
+ }
+} | Java | ์ฑ๊ธํค์ผ๋ก ์ ๊ตฌ์ฑํด์ฃผ์
จ๋ค์ ๐ |
@@ -0,0 +1,35 @@
+package nextstep.security.authorization.matcher;
+
+import jakarta.servlet.http.HttpServletRequest;
+import org.springframework.http.HttpMethod;
+
+import java.util.regex.Pattern;
+
+public class MvcRequestMatcher implements RequestMatcher {
+ private final HttpMethod method;
+ private final Pattern pattern;
+
+ public MvcRequestMatcher(HttpMethod method, String pattern) {
+ this.method = method;
+ this.pattern = compile(pattern);
+ }
+
+ private Pattern compile(String regex) {
+ return regex == null || regex.isBlank()
+ ? null
+ : Pattern.compile(regex);
+ }
+
+ @Override
+ public boolean matches(HttpServletRequest request) {
+ return matchMethod(request) && matchPattern(request);
+ }
+
+ private boolean matchMethod(HttpServletRequest request) {
+ return method == null || method.name().equals(request.getMethod());
+ }
+
+ private boolean matchPattern(HttpServletRequest request) {
+ return pattern == null || pattern.matcher(request.getRequestURI()).matches();
+ }
+} | Java | ```suggestion
if (regex == null || regex.isBlank()) {
return null;
}
return Pattern.compile(regex);
```
๊ฐ์ธ์ ์ผ๋ก๋ ์ผํญ์ฐ์ฐ์๋ณด๋ค๋ if๋ฌธ์ผ๋ก early return ํด์ฃผ๋ ๊ฒ์ด ํ์ค ํ์ค์ ์ฝ์ ๋ ์ปจํ
์คํธ๋ฅผ ์ธ์๋์ง ์์๋ ๋์ด์ ์ฝ๊ธฐ ํธํ ์ฝ๋๋ก ๋ง๋ค์ด์ค๋ค๊ณ ์๊ฐํฉ๋๋ค :) |
@@ -0,0 +1,32 @@
+package nextstep.security.authorization.manager;
+
+import nextstep.security.authentication.Authentication;
+import nextstep.security.authorization.Secured;
+import org.aopalliance.intercept.MethodInvocation;
+
+import java.lang.reflect.Method;
+
+public class SecuredAuthorizationManager implements AuthorizationManager<MethodInvocation> {
+ private SecuredAuthorizationManager() {}
+
+ public static SecuredAuthorizationManager getInstance() {
+ return SingletonHolder.INSTANCE;
+ }
+
+ @Override
+ public AuthorizationDecision check(Authentication authentication, MethodInvocation target) {
+ return AuthorizationDecision.of(hasAuthority(authentication, target.getMethod()));
+ }
+
+ private boolean hasAuthority(Authentication authentication, Method method) {
+ return authentication != null
+ && authentication.isAuthenticated()
+ && method.isAnnotationPresent(Secured.class)
+ && authentication.getAuthorities()
+ .contains(method.getAnnotation(Secured.class).value());
+ }
+
+ private static final class SingletonHolder {
+ private static final SecuredAuthorizationManager INSTANCE = new SecuredAuthorizationManager();
+ }
+} | Java | `@Secured` ์ด๋
ธํ
์ด์
์ด ์๋ ๋ฉ์๋๋ฅผ ํ๋ ๊ฒฝ์ฐ์๋ ์ธ๊ฐ ๊ฐ์ด true์ธ `AuthorizationDecision`์ ๋ฐํํ๋ ๊ฒ์ด ๋ง์์ง ๊ณ ๋ฏผํด๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ์์.
`AuthorizationDecision`์ด true์ธ ๊ฐ์ฒด๋ฅผ ๋ฐํํ๋ค๋ ๊ฒ์ "์ธ๊ฐ"๋์๋ค๋ ๊ฒ์ธ๋ฐ `@Secured`์ด๋
ธํ
์ด์
์ด ์๋ ๊ฒ์ ์ธ๊ฐ์ ํ๋ก์ธ์ค๊ฐ ํ์์์ง ์๋์? |
@@ -0,0 +1,48 @@
+package nextstep.security.authorization.manager;
+
+import jakarta.servlet.http.HttpServletRequest;
+import nextstep.security.authentication.Authentication;
+import nextstep.security.authorization.matcher.RequestMatcherEntry;
+
+import java.util.List;
+
+public class RequestAuthorizationManager implements AuthorizationManager<HttpServletRequest> {
+ private final List<RequestMatcherEntry<AuthorizationManager<HttpServletRequest>>> entries;
+ private final RequestMatcherEntry<AuthorizationManager<HttpServletRequest>> defaultEntry;
+
+ public RequestAuthorizationManager(
+ List<RequestMatcherEntry<AuthorizationManager<HttpServletRequest>>> entries,
+ RequestMatcherEntry<AuthorizationManager<HttpServletRequest>> defaultEntry
+ ) {
+ this.entries = entries;
+ this.defaultEntry = defaultEntry;
+ }
+
+ @Override
+ public AuthorizationDecision check(Authentication authentication, HttpServletRequest target) {
+ final boolean isGranted = noneMatch(target)
+ ? check(authentication, target, defaultEntry)
+ : allMatch(authentication, target);
+ return AuthorizationDecision.of(isGranted);
+ }
+
+ private boolean noneMatch(HttpServletRequest request) {
+ return entries.stream().noneMatch(
+ entry -> entry.requestMatcher().matches(request)
+ );
+ }
+
+ private boolean allMatch(Authentication authentication, HttpServletRequest request) {
+ return entries.stream().allMatch(
+ entry -> check(authentication, request, entry)
+ );
+ }
+
+ private boolean check(
+ Authentication authentication, HttpServletRequest request,
+ RequestMatcherEntry<AuthorizationManager<HttpServletRequest>> matcherEntry
+ ) {
+ return !matcherEntry.requestMatcher().matches(request)
+ || matcherEntry.entry().check(authentication, request).isGranted();
+ }
+} | Java | spring security์์๋ ์ฑ๋ฅ์ ๋ฌธ์ ๋ก stream๋ฌธ์ ์ง์ํฉ๋๋ค.
https://github.com/spring-projects/spring-security/issues/7154 |
@@ -0,0 +1,36 @@
+package nextstep;
+
+import nextstep.app.domain.Member;
+
+import java.util.Base64;
+import java.util.Set;
+
+public final class Fixture {
+ public static final Member TEST_ADMIN_MEMBER = new Member(
+ "a@a.com", "password",
+ "a", "",
+ Set.of("USER", "ADMIN")
+ );
+ public static final Member TEST_USER_MEMBER = new Member(
+ "b@b.com", "password",
+ "b", "",
+ Set.of("USER")
+ );
+ public static final String TEST_ADMIN_TOKEN = createToken(TEST_ADMIN_MEMBER);
+ public static final String TEST_USER_TOKEN = createToken(TEST_USER_MEMBER);
+
+ private Fixture() {}
+
+ private static String createToken(final Member member) {
+ return createToken(member.getEmail(), member.getPassword());
+ }
+
+ public static String createToken(
+ final String principal,
+ final String credential
+ ) {
+ return "Basic " + Base64.getEncoder().encodeToString(
+ (principal + ":" + credential).getBytes()
+ );
+ }
+} | Java | `Fixture` ๐
(๋ฐ์ํ์ง ์์ผ์
๋ ๋ฉ๋๋ค) ์ ๋ ํน์ ๋๋ฉ์ธ ๊ฐ์ฒด์ Fixture ๋ฅผ ํ์ฉํด์ผํ๋ ๊ฒฝ์ฐ๊ฐ ์์ผ๋ฉด enum์ผ๋ก ์์ฑํ์ฌ ํ์ฉํ๋ ํธ์ด๊ธดํฉ๋๋ค. enum์์ ์ ๊ณตํ๋ ๋ฉ์๋๋ฅผ ํ์ฉํ ํ์๊ฐ ์์ ๋๊ฐ ๊ฐํน ์๋๋ผ๊ตฌ์. |
@@ -0,0 +1,79 @@
+package nextstep.security.authorization.manager;
+
+import nextstep.security.authentication.Authentication;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.util.Set;
+
+import static nextstep.security.authorization.manager.AuthorizationDecision.GRANTED;
+import static nextstep.security.authorization.manager.AuthorizationDecision.NOT_GRANTED;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertAll;
+
+class HasAuthorityAuthorizationManagerTest {
+ private final AuthorizationManager<String> manager = new HasAuthorityAuthorizationManager<>(
+ "ADMIN", "USER"
+ );
+
+ @DisplayName("์ ์ ๊ฐ ์ธ์ฆ๋์ง ์์๋ค๋ฉด ์ธ๊ฐ๋ฐ์ง ๋ชปํ๋ค.")
+ @Test
+ void notAuthenticated() {
+ assertAll(
+ () -> assertThat(manager.check(
+ null, null
+ )).isEqualTo(NOT_GRANTED),
+ () -> assertThat(manager.check(
+ createAuthentication(false), null
+ )).isEqualTo(NOT_GRANTED)
+ );
+ }
+
+ @DisplayName("์ธ์ฆ๋ ์ ์ ๊ฐ Authority ๋ฅผ ๊ฐ์ก๋ค๋ฉด ์ธ๊ฐ๋ฐ๋๋ค.")
+ @Test
+ void noAuthority() {
+ assertAll(
+ () -> assertThat(manager.check(
+ createAuthentication(true, "ADMIN"), null)
+ ).isEqualTo(GRANTED),
+ () -> assertThat(manager.check(
+ createAuthentication(true, "USER"), null)
+ ).isEqualTo(GRANTED)
+ );
+ }
+
+ @DisplayName("์ธ์ฆ๋ ์ ์ ๊ฐ Authority ๋ฅผ ๊ฐ์ง์ง ๋ชปํ๋ค๋ฉด ์ธ๊ฐ๋ฐ์ง ๋ชปํ๋ค.")
+ @Test
+ void hasAuthority() {
+ assertThat(manager.check(
+ createAuthentication(true, "ANONYMOUS"), null)
+ ).isEqualTo(NOT_GRANTED);
+ }
+
+ private Authentication createAuthentication(
+ boolean isAuthenticated,
+ String... authorities
+ ) {
+ return new Authentication() {
+ @Override
+ public Set<String> getAuthorities() {
+ return Set.of(authorities);
+ }
+
+ @Override
+ public Object getCredentials() {
+ return "PASSWORD";
+ }
+
+ @Override
+ public Object getPrincipal() {
+ return "USERNAME";
+ }
+
+ @Override
+ public boolean isAuthenticated() {
+ return isAuthenticated;
+ }
+ };
+ }
+} | Java | ์ธ์ฆ๋ ์ ์ ์ ๋ํ ํ
์คํธ๋ฅผ ์งํํ ๋ "ADMIN"๊ณผ "USER"๋ ๊ฒฐ๊ตญ ๋ค๋ฅธ ํ
์คํธ ์ผ์ด์ค์ ํด๋นํด์. "ADMIN"์ ๋ํ ๊ฒฐ๊ณผ๋ "USER"์ ๋ํ ๊ฒฐ๊ณผ๊ฐ ๋ค๋ฅผ ์ ์๋๋ฐ, ์ด์ ๋ํ ํผ๋๋ฐฑ์ ํ๋์ ํ
์คํธ์์ ๋ชฐ์์ ์งํํ๊ธฐ๋ณด๋ค๋ ๊ฐ ์ผ์ด์ค์ ๋ง๊ฒ ํ
์คํธ์ ๋ํ ํผ๋๋ฐฑ์ ๋ฐ์์ผ ์ด๋ค ์ผ์ด์ค๋ฅผ ๋ณด์์ผํ ์ง ๋ช
ํํ๊ฒ ํ์
์ด ๋ ์ ์์ต๋๋ค.
ํ ํ
์คํธ์ ํ ์ผ์ด์ค๋ง ๋ฃ์ผ๋ผ๊ฐ ๋ช
ํํ ์ ๋ต์ ์๋์ง๋ง ์ด๋ค ํผ๋๋ฐฑ์ ์ค์ ์๋์ ๊ด์ ์์๋ ๊ฐ๊ฐ์ ๋ค๋ฅธ ์ผ์ด์ค๋ ์๋ก ๋ค๋ฅธ ํ
์คํธ์ ํด๋นํ๋ค๊ณ ๋ณผ ์ ์์ ๊ฒ ๊ฐ์์ :)
https://martinfowler.com/bliki/SpecificationByExample.html |
@@ -0,0 +1,176 @@
+package store.controller;
+
+import store.infrastructure.constant.Message;
+import store.service.OrderParser;
+import store.domain.vo.Name;
+import store.domain.vo.Order;
+import store.domain.vo.Quantity;
+import store.service.*;
+import store.service.dto.request.ApplyPromotionRequest;
+import store.service.dto.response.PromotionCommandResponse;
+import store.service.dto.response.PromotionQueryResponse;
+import store.domain.vo.PromotionOption;
+import store.service.strategy.PromotionStrategy;
+import store.service.strategy.provider.PromotionStrategyProvider;
+import store.validator.OrderValidator;
+import store.view.InputView;
+import store.view.OutputView;
+import store.view.dto.calculate.ReceiptCalculateRequest;
+import store.view.dto.gift.ReceiptGiftViewRequest;
+import store.view.dto.order.ReceiptOrderViewRequest;
+import store.view.dto.product.ProductViewRequest;
+
+import java.util.List;
+
+public class StoreController {
+ private final StoreFileInputService storeFileInputService;
+ private final ProductService productService;
+ private final PromotionService promotionService;
+ private final OrderValidator orderValidator;
+ private final OrderParser orderParser;
+ private final ReceiptService receiptService;
+ private final InputView inputView;
+ private final OutputView outputView;
+
+ public StoreController(
+ StoreFileInputService storeFileInputService,
+ ProductService productService,
+ PromotionService promotionService,
+ OrderValidator orderValidator,
+ OrderParser orderParser,
+ ReceiptService receiptService,
+ InputView inputView,
+ OutputView outputView
+ ) {
+ this.storeFileInputService = storeFileInputService;
+ this.productService = productService;
+ this.promotionService = promotionService;
+ this.orderValidator = orderValidator;
+ this.orderParser = orderParser;
+ this.receiptService = receiptService;
+ this.inputView = inputView;
+ this.outputView = outputView;
+ }
+
+ public void run() {
+ storeFileInputService.loadAndSave();
+ while (true) {
+ printInfo();
+ receiveOrder();
+ handleDiscount();
+ applyOrder();
+ printReceipt();
+ resetOrder();
+ if (!isContinue()) break;
+ }
+ }
+
+ private boolean isContinue() {
+ return inputView.readAdditionalPurchase();
+ }
+
+ private void printInfo() {
+ outputView.printWelcome();
+ outputView.printProducts(new ProductViewRequest(productService.getAllProductInfo()));
+ }
+
+ private void printReceipt() {
+ printReceiptOrder();
+ printReceiptGift();
+ printReceiptCalculate();
+ }
+
+ private void printReceiptOrder() {
+ outputView.printReceiptTitle(Message.STORE_NAME);
+ outputView.printReceiptOrderContent(new ReceiptOrderViewRequest(receiptService.getOrderResult()));
+ }
+
+ private void printReceiptGift() {
+ outputView.printReceiptTitle("์ฆ ์ ");
+ outputView.printReceiptGiftContent(new ReceiptGiftViewRequest(receiptService.getPromotionResult()));
+ }
+
+ private void printReceiptCalculate() {
+ outputView.printReceiptTitle();
+ outputView.printReceiptCalculateContent(
+ new ReceiptCalculateRequest(
+ receiptService.getOrderResult().size(),
+ receiptService.getTotalOrderPrice(),
+ receiptService.getTotalPromotionDiscount(),
+ receiptService.getMembershipDiscount(),
+ receiptService.getPayPrice()
+ ));
+ }
+
+ private void receiveOrder() {
+ while (true) {
+ try {
+ List<Order> orders = orderParser.from(inputView.readItem());
+ orderValidator.validate(orders);
+ receiptService.setOrder(orders);
+ break;
+ } catch (IllegalArgumentException e) {
+ outputView.printMessage(e.getMessage());
+ }
+ }
+ }
+
+ private void handleDiscount() {
+ handlePromotion();
+ handleMembership();
+ }
+
+ private void handlePromotion() {
+ List<Order> orders = receiptService.getAllOrder();
+ for (Order order : orders) {
+ if (promotionService.isExistApplicablePromotion(order.productName())) {
+ PromotionQueryResponse queryResult = promotionService.query(order);
+ PromotionCommandResponse response = getPromotionResult(order, queryResult);
+ receiptService.setOrder(response.order());
+ receiptService.addPromotionDiscount(order.productName(), response.giftQuantity());
+ }
+ }
+ }
+
+ private PromotionCommandResponse getPromotionResult(Order order, PromotionQueryResponse queryResponse) {
+ if (queryResponse.option().equals(PromotionOption.NONE)) {
+ return new PromotionCommandResponse(order, queryResponse.giftQuantity());
+ }
+ PromotionStrategy strategy = getStrategy(order, queryResponse);
+
+ ApplyPromotionRequest request = new ApplyPromotionRequest(order, strategy);
+ return promotionService.command(request);
+ }
+
+ private PromotionStrategy getStrategy(Order order, PromotionQueryResponse queryResponse) {
+ if (queryResponse.option().equals(PromotionOption.ADD_FREE)) {
+ return getAddFreeStrategy(order.productName());
+ }
+ return getRegularPurchaseStrategy(order.productName(), queryResponse.notAppliedQuantity());
+ }
+
+ private PromotionStrategy getAddFreeStrategy(Name productName) {
+ final boolean answer = inputView.readAddFreeAnswer(productName.value());
+ return PromotionStrategyProvider.from(PromotionOption.ADD_FREE, answer);
+ }
+
+ private PromotionStrategy getRegularPurchaseStrategy(Name productName, Quantity excluded) {
+ final boolean answer = inputView.readPaidRegularPriceAnswer(productName.value(), excluded.value());
+ return PromotionStrategyProvider.from(PromotionOption.REGULAR_PURCHASE, answer);
+ }
+
+ private void handleMembership() {
+ final boolean apply = inputView.readMembershipAnswer();
+ if (apply) {
+ receiptService.setMembershipDiscount();
+ }
+ }
+
+ private void applyOrder() {
+ productService.applyReceiptInventory();
+ }
+
+ private void resetOrder() {
+ receiptService.reset();
+ }
+} | Java | ์ ๋ ๋ฐ๋ณต๋ฌธ์์ break ๋ฌธ์ ์ฌ์ฉํ๋ ๊ฒ์ ์ง์ํฉ๋๋ค! ํ์ฌ๋ ๋ง์ง๋ง์ ์์ด์ ์ฝ๊ธฐ ์ฝ์ง๋ง ์ค๊ฐ์ ์์ผ๋ฉด ์ฝ๋ ๋ก์ง์ ์ดํดํ๊ธฐ ํ๋ค๊ธฐ ๋๋ฌธ์
๋๋ค! ์ฌ๊ธฐ์ break ๋ณด๋ค๋ do-while์ ์ฌ์ฉํ๋๊ฒ ์ด๋จ์ง ์กฐ์ฌ์ค๋ฝ๊ฒ ์๊ฒฌ ๋จ๊น๋๋ค ๐ |
@@ -0,0 +1,176 @@
+package store.controller;
+
+import store.infrastructure.constant.Message;
+import store.service.OrderParser;
+import store.domain.vo.Name;
+import store.domain.vo.Order;
+import store.domain.vo.Quantity;
+import store.service.*;
+import store.service.dto.request.ApplyPromotionRequest;
+import store.service.dto.response.PromotionCommandResponse;
+import store.service.dto.response.PromotionQueryResponse;
+import store.domain.vo.PromotionOption;
+import store.service.strategy.PromotionStrategy;
+import store.service.strategy.provider.PromotionStrategyProvider;
+import store.validator.OrderValidator;
+import store.view.InputView;
+import store.view.OutputView;
+import store.view.dto.calculate.ReceiptCalculateRequest;
+import store.view.dto.gift.ReceiptGiftViewRequest;
+import store.view.dto.order.ReceiptOrderViewRequest;
+import store.view.dto.product.ProductViewRequest;
+
+import java.util.List;
+
+public class StoreController {
+ private final StoreFileInputService storeFileInputService;
+ private final ProductService productService;
+ private final PromotionService promotionService;
+ private final OrderValidator orderValidator;
+ private final OrderParser orderParser;
+ private final ReceiptService receiptService;
+ private final InputView inputView;
+ private final OutputView outputView;
+
+ public StoreController(
+ StoreFileInputService storeFileInputService,
+ ProductService productService,
+ PromotionService promotionService,
+ OrderValidator orderValidator,
+ OrderParser orderParser,
+ ReceiptService receiptService,
+ InputView inputView,
+ OutputView outputView
+ ) {
+ this.storeFileInputService = storeFileInputService;
+ this.productService = productService;
+ this.promotionService = promotionService;
+ this.orderValidator = orderValidator;
+ this.orderParser = orderParser;
+ this.receiptService = receiptService;
+ this.inputView = inputView;
+ this.outputView = outputView;
+ }
+
+ public void run() {
+ storeFileInputService.loadAndSave();
+ while (true) {
+ printInfo();
+ receiveOrder();
+ handleDiscount();
+ applyOrder();
+ printReceipt();
+ resetOrder();
+ if (!isContinue()) break;
+ }
+ }
+
+ private boolean isContinue() {
+ return inputView.readAdditionalPurchase();
+ }
+
+ private void printInfo() {
+ outputView.printWelcome();
+ outputView.printProducts(new ProductViewRequest(productService.getAllProductInfo()));
+ }
+
+ private void printReceipt() {
+ printReceiptOrder();
+ printReceiptGift();
+ printReceiptCalculate();
+ }
+
+ private void printReceiptOrder() {
+ outputView.printReceiptTitle(Message.STORE_NAME);
+ outputView.printReceiptOrderContent(new ReceiptOrderViewRequest(receiptService.getOrderResult()));
+ }
+
+ private void printReceiptGift() {
+ outputView.printReceiptTitle("์ฆ ์ ");
+ outputView.printReceiptGiftContent(new ReceiptGiftViewRequest(receiptService.getPromotionResult()));
+ }
+
+ private void printReceiptCalculate() {
+ outputView.printReceiptTitle();
+ outputView.printReceiptCalculateContent(
+ new ReceiptCalculateRequest(
+ receiptService.getOrderResult().size(),
+ receiptService.getTotalOrderPrice(),
+ receiptService.getTotalPromotionDiscount(),
+ receiptService.getMembershipDiscount(),
+ receiptService.getPayPrice()
+ ));
+ }
+
+ private void receiveOrder() {
+ while (true) {
+ try {
+ List<Order> orders = orderParser.from(inputView.readItem());
+ orderValidator.validate(orders);
+ receiptService.setOrder(orders);
+ break;
+ } catch (IllegalArgumentException e) {
+ outputView.printMessage(e.getMessage());
+ }
+ }
+ }
+
+ private void handleDiscount() {
+ handlePromotion();
+ handleMembership();
+ }
+
+ private void handlePromotion() {
+ List<Order> orders = receiptService.getAllOrder();
+ for (Order order : orders) {
+ if (promotionService.isExistApplicablePromotion(order.productName())) {
+ PromotionQueryResponse queryResult = promotionService.query(order);
+ PromotionCommandResponse response = getPromotionResult(order, queryResult);
+ receiptService.setOrder(response.order());
+ receiptService.addPromotionDiscount(order.productName(), response.giftQuantity());
+ }
+ }
+ }
+
+ private PromotionCommandResponse getPromotionResult(Order order, PromotionQueryResponse queryResponse) {
+ if (queryResponse.option().equals(PromotionOption.NONE)) {
+ return new PromotionCommandResponse(order, queryResponse.giftQuantity());
+ }
+ PromotionStrategy strategy = getStrategy(order, queryResponse);
+
+ ApplyPromotionRequest request = new ApplyPromotionRequest(order, strategy);
+ return promotionService.command(request);
+ }
+
+ private PromotionStrategy getStrategy(Order order, PromotionQueryResponse queryResponse) {
+ if (queryResponse.option().equals(PromotionOption.ADD_FREE)) {
+ return getAddFreeStrategy(order.productName());
+ }
+ return getRegularPurchaseStrategy(order.productName(), queryResponse.notAppliedQuantity());
+ }
+
+ private PromotionStrategy getAddFreeStrategy(Name productName) {
+ final boolean answer = inputView.readAddFreeAnswer(productName.value());
+ return PromotionStrategyProvider.from(PromotionOption.ADD_FREE, answer);
+ }
+
+ private PromotionStrategy getRegularPurchaseStrategy(Name productName, Quantity excluded) {
+ final boolean answer = inputView.readPaidRegularPriceAnswer(productName.value(), excluded.value());
+ return PromotionStrategyProvider.from(PromotionOption.REGULAR_PURCHASE, answer);
+ }
+
+ private void handleMembership() {
+ final boolean apply = inputView.readMembershipAnswer();
+ if (apply) {
+ receiptService.setMembershipDiscount();
+ }
+ }
+
+ private void applyOrder() {
+ productService.applyReceiptInventory();
+ }
+
+ private void resetOrder() {
+ receiptService.reset();
+ }
+} | Java | ์ ๋ ์ปจํธ๋กค๋ฌ์ ๋ทฐ์ ๊ฐ ์ญํ ์ด ์ปจํธ๋กค๋ฌ์ ๋ทฐ์๊ฒ ์ถ๋ ฅํ ์ ๋ณด๋ฅผ ์ ๊ณตํ๊ณ ๋ทฐ๋ ์ปจํธ๋กค๋ฌ์์ ์ ๊ณต๋ฐ์ ์ ๋ณด๋ฅผ ํตํด ์ถ๋ ฅํด์ผํ๋ค๊ณ ์๊ฐํฉ๋๋ค. ํ์ง๋ง ์ง๊ธ์ฒ๋ผ ๋จ์ ํ๋ ์ฝ๋ฉ์ ๋ฌธ์๋ ์ฃผ๋ ๊ฒฝ์ฐ์๋ ์ฐจ๋ผ๋ฆฌ view ๋ด์์ ์์ํ๋ฅผ ํ์ฌ ๊ด๋ฆฌํ๋๊ฒ ๋ ์ข์๋ณด์ด๋๋ฐ ์ด๋ป๊ฒ ์๊ฐํ์๋์? ์ด๋ ๊ฒ ์ค๊ณ๋ฅผ ํ ์๋๊ฐ ์์๊น์? |
@@ -0,0 +1,176 @@
+package store.controller;
+
+import store.infrastructure.constant.Message;
+import store.service.OrderParser;
+import store.domain.vo.Name;
+import store.domain.vo.Order;
+import store.domain.vo.Quantity;
+import store.service.*;
+import store.service.dto.request.ApplyPromotionRequest;
+import store.service.dto.response.PromotionCommandResponse;
+import store.service.dto.response.PromotionQueryResponse;
+import store.domain.vo.PromotionOption;
+import store.service.strategy.PromotionStrategy;
+import store.service.strategy.provider.PromotionStrategyProvider;
+import store.validator.OrderValidator;
+import store.view.InputView;
+import store.view.OutputView;
+import store.view.dto.calculate.ReceiptCalculateRequest;
+import store.view.dto.gift.ReceiptGiftViewRequest;
+import store.view.dto.order.ReceiptOrderViewRequest;
+import store.view.dto.product.ProductViewRequest;
+
+import java.util.List;
+
+public class StoreController {
+ private final StoreFileInputService storeFileInputService;
+ private final ProductService productService;
+ private final PromotionService promotionService;
+ private final OrderValidator orderValidator;
+ private final OrderParser orderParser;
+ private final ReceiptService receiptService;
+ private final InputView inputView;
+ private final OutputView outputView;
+
+ public StoreController(
+ StoreFileInputService storeFileInputService,
+ ProductService productService,
+ PromotionService promotionService,
+ OrderValidator orderValidator,
+ OrderParser orderParser,
+ ReceiptService receiptService,
+ InputView inputView,
+ OutputView outputView
+ ) {
+ this.storeFileInputService = storeFileInputService;
+ this.productService = productService;
+ this.promotionService = promotionService;
+ this.orderValidator = orderValidator;
+ this.orderParser = orderParser;
+ this.receiptService = receiptService;
+ this.inputView = inputView;
+ this.outputView = outputView;
+ }
+
+ public void run() {
+ storeFileInputService.loadAndSave();
+ while (true) {
+ printInfo();
+ receiveOrder();
+ handleDiscount();
+ applyOrder();
+ printReceipt();
+ resetOrder();
+ if (!isContinue()) break;
+ }
+ }
+
+ private boolean isContinue() {
+ return inputView.readAdditionalPurchase();
+ }
+
+ private void printInfo() {
+ outputView.printWelcome();
+ outputView.printProducts(new ProductViewRequest(productService.getAllProductInfo()));
+ }
+
+ private void printReceipt() {
+ printReceiptOrder();
+ printReceiptGift();
+ printReceiptCalculate();
+ }
+
+ private void printReceiptOrder() {
+ outputView.printReceiptTitle(Message.STORE_NAME);
+ outputView.printReceiptOrderContent(new ReceiptOrderViewRequest(receiptService.getOrderResult()));
+ }
+
+ private void printReceiptGift() {
+ outputView.printReceiptTitle("์ฆ ์ ");
+ outputView.printReceiptGiftContent(new ReceiptGiftViewRequest(receiptService.getPromotionResult()));
+ }
+
+ private void printReceiptCalculate() {
+ outputView.printReceiptTitle();
+ outputView.printReceiptCalculateContent(
+ new ReceiptCalculateRequest(
+ receiptService.getOrderResult().size(),
+ receiptService.getTotalOrderPrice(),
+ receiptService.getTotalPromotionDiscount(),
+ receiptService.getMembershipDiscount(),
+ receiptService.getPayPrice()
+ ));
+ }
+
+ private void receiveOrder() {
+ while (true) {
+ try {
+ List<Order> orders = orderParser.from(inputView.readItem());
+ orderValidator.validate(orders);
+ receiptService.setOrder(orders);
+ break;
+ } catch (IllegalArgumentException e) {
+ outputView.printMessage(e.getMessage());
+ }
+ }
+ }
+
+ private void handleDiscount() {
+ handlePromotion();
+ handleMembership();
+ }
+
+ private void handlePromotion() {
+ List<Order> orders = receiptService.getAllOrder();
+ for (Order order : orders) {
+ if (promotionService.isExistApplicablePromotion(order.productName())) {
+ PromotionQueryResponse queryResult = promotionService.query(order);
+ PromotionCommandResponse response = getPromotionResult(order, queryResult);
+ receiptService.setOrder(response.order());
+ receiptService.addPromotionDiscount(order.productName(), response.giftQuantity());
+ }
+ }
+ }
+
+ private PromotionCommandResponse getPromotionResult(Order order, PromotionQueryResponse queryResponse) {
+ if (queryResponse.option().equals(PromotionOption.NONE)) {
+ return new PromotionCommandResponse(order, queryResponse.giftQuantity());
+ }
+ PromotionStrategy strategy = getStrategy(order, queryResponse);
+
+ ApplyPromotionRequest request = new ApplyPromotionRequest(order, strategy);
+ return promotionService.command(request);
+ }
+
+ private PromotionStrategy getStrategy(Order order, PromotionQueryResponse queryResponse) {
+ if (queryResponse.option().equals(PromotionOption.ADD_FREE)) {
+ return getAddFreeStrategy(order.productName());
+ }
+ return getRegularPurchaseStrategy(order.productName(), queryResponse.notAppliedQuantity());
+ }
+
+ private PromotionStrategy getAddFreeStrategy(Name productName) {
+ final boolean answer = inputView.readAddFreeAnswer(productName.value());
+ return PromotionStrategyProvider.from(PromotionOption.ADD_FREE, answer);
+ }
+
+ private PromotionStrategy getRegularPurchaseStrategy(Name productName, Quantity excluded) {
+ final boolean answer = inputView.readPaidRegularPriceAnswer(productName.value(), excluded.value());
+ return PromotionStrategyProvider.from(PromotionOption.REGULAR_PURCHASE, answer);
+ }
+
+ private void handleMembership() {
+ final boolean apply = inputView.readMembershipAnswer();
+ if (apply) {
+ receiptService.setMembershipDiscount();
+ }
+ }
+
+ private void applyOrder() {
+ productService.applyReceiptInventory();
+ }
+
+ private void resetOrder() {
+ receiptService.reset();
+ }
+} | Java | break ๋์ returnํ๋ ๋ฐฉ๋ฒ๋ ์์ต๋๋ค!๐ |
@@ -0,0 +1,176 @@
+package store.controller;
+
+import store.infrastructure.constant.Message;
+import store.service.OrderParser;
+import store.domain.vo.Name;
+import store.domain.vo.Order;
+import store.domain.vo.Quantity;
+import store.service.*;
+import store.service.dto.request.ApplyPromotionRequest;
+import store.service.dto.response.PromotionCommandResponse;
+import store.service.dto.response.PromotionQueryResponse;
+import store.domain.vo.PromotionOption;
+import store.service.strategy.PromotionStrategy;
+import store.service.strategy.provider.PromotionStrategyProvider;
+import store.validator.OrderValidator;
+import store.view.InputView;
+import store.view.OutputView;
+import store.view.dto.calculate.ReceiptCalculateRequest;
+import store.view.dto.gift.ReceiptGiftViewRequest;
+import store.view.dto.order.ReceiptOrderViewRequest;
+import store.view.dto.product.ProductViewRequest;
+
+import java.util.List;
+
+public class StoreController {
+ private final StoreFileInputService storeFileInputService;
+ private final ProductService productService;
+ private final PromotionService promotionService;
+ private final OrderValidator orderValidator;
+ private final OrderParser orderParser;
+ private final ReceiptService receiptService;
+ private final InputView inputView;
+ private final OutputView outputView;
+
+ public StoreController(
+ StoreFileInputService storeFileInputService,
+ ProductService productService,
+ PromotionService promotionService,
+ OrderValidator orderValidator,
+ OrderParser orderParser,
+ ReceiptService receiptService,
+ InputView inputView,
+ OutputView outputView
+ ) {
+ this.storeFileInputService = storeFileInputService;
+ this.productService = productService;
+ this.promotionService = promotionService;
+ this.orderValidator = orderValidator;
+ this.orderParser = orderParser;
+ this.receiptService = receiptService;
+ this.inputView = inputView;
+ this.outputView = outputView;
+ }
+
+ public void run() {
+ storeFileInputService.loadAndSave();
+ while (true) {
+ printInfo();
+ receiveOrder();
+ handleDiscount();
+ applyOrder();
+ printReceipt();
+ resetOrder();
+ if (!isContinue()) break;
+ }
+ }
+
+ private boolean isContinue() {
+ return inputView.readAdditionalPurchase();
+ }
+
+ private void printInfo() {
+ outputView.printWelcome();
+ outputView.printProducts(new ProductViewRequest(productService.getAllProductInfo()));
+ }
+
+ private void printReceipt() {
+ printReceiptOrder();
+ printReceiptGift();
+ printReceiptCalculate();
+ }
+
+ private void printReceiptOrder() {
+ outputView.printReceiptTitle(Message.STORE_NAME);
+ outputView.printReceiptOrderContent(new ReceiptOrderViewRequest(receiptService.getOrderResult()));
+ }
+
+ private void printReceiptGift() {
+ outputView.printReceiptTitle("์ฆ ์ ");
+ outputView.printReceiptGiftContent(new ReceiptGiftViewRequest(receiptService.getPromotionResult()));
+ }
+
+ private void printReceiptCalculate() {
+ outputView.printReceiptTitle();
+ outputView.printReceiptCalculateContent(
+ new ReceiptCalculateRequest(
+ receiptService.getOrderResult().size(),
+ receiptService.getTotalOrderPrice(),
+ receiptService.getTotalPromotionDiscount(),
+ receiptService.getMembershipDiscount(),
+ receiptService.getPayPrice()
+ ));
+ }
+
+ private void receiveOrder() {
+ while (true) {
+ try {
+ List<Order> orders = orderParser.from(inputView.readItem());
+ orderValidator.validate(orders);
+ receiptService.setOrder(orders);
+ break;
+ } catch (IllegalArgumentException e) {
+ outputView.printMessage(e.getMessage());
+ }
+ }
+ }
+
+ private void handleDiscount() {
+ handlePromotion();
+ handleMembership();
+ }
+
+ private void handlePromotion() {
+ List<Order> orders = receiptService.getAllOrder();
+ for (Order order : orders) {
+ if (promotionService.isExistApplicablePromotion(order.productName())) {
+ PromotionQueryResponse queryResult = promotionService.query(order);
+ PromotionCommandResponse response = getPromotionResult(order, queryResult);
+ receiptService.setOrder(response.order());
+ receiptService.addPromotionDiscount(order.productName(), response.giftQuantity());
+ }
+ }
+ }
+
+ private PromotionCommandResponse getPromotionResult(Order order, PromotionQueryResponse queryResponse) {
+ if (queryResponse.option().equals(PromotionOption.NONE)) {
+ return new PromotionCommandResponse(order, queryResponse.giftQuantity());
+ }
+ PromotionStrategy strategy = getStrategy(order, queryResponse);
+
+ ApplyPromotionRequest request = new ApplyPromotionRequest(order, strategy);
+ return promotionService.command(request);
+ }
+
+ private PromotionStrategy getStrategy(Order order, PromotionQueryResponse queryResponse) {
+ if (queryResponse.option().equals(PromotionOption.ADD_FREE)) {
+ return getAddFreeStrategy(order.productName());
+ }
+ return getRegularPurchaseStrategy(order.productName(), queryResponse.notAppliedQuantity());
+ }
+
+ private PromotionStrategy getAddFreeStrategy(Name productName) {
+ final boolean answer = inputView.readAddFreeAnswer(productName.value());
+ return PromotionStrategyProvider.from(PromotionOption.ADD_FREE, answer);
+ }
+
+ private PromotionStrategy getRegularPurchaseStrategy(Name productName, Quantity excluded) {
+ final boolean answer = inputView.readPaidRegularPriceAnswer(productName.value(), excluded.value());
+ return PromotionStrategyProvider.from(PromotionOption.REGULAR_PURCHASE, answer);
+ }
+
+ private void handleMembership() {
+ final boolean apply = inputView.readMembershipAnswer();
+ if (apply) {
+ receiptService.setMembershipDiscount();
+ }
+ }
+
+ private void applyOrder() {
+ productService.applyReceiptInventory();
+ }
+
+ private void resetOrder() {
+ receiptService.reset();
+ }
+} | Java | ์ด ๋ถ๋ถ์ ๋ฏผ์ ๋์ ๋ง์์ฒ๋ผ ์๋น์ค๋ก ๋๋๋๊ฒ ์ข์๋ณด์
๋๋ค! ์ปจํธ๋กค๋ฌ๋ ๋ทฐ์ ์๋น์ค ๋ก์ง์ ์ด์ด์ฃผ๊ณ ํ๋ฆ๋ง ๋ด๋นํ๋ ์ญํ ์ ๋ด๋นํ๋๊ฒ ์ข์๋ณด์
๋๋ค ใ
ใ
|
@@ -0,0 +1,31 @@
+package store.domain.vo;
+
+public record Name(String value) {
+ public static final int MAX_LEN = 10;
+
+ public Name(String value) {
+ validateName(value.trim());
+ this.value = value.trim();
+ }
+
+ private void validateName(String name) {
+ if (name == null || name.isEmpty()) {
+ throw new IllegalArgumentException("[ERROR] ์ํ๋ช
์ ๊ณต๋ฐฑ์ผ๋ก ์ค์ ํ ์ ์์ต๋๋ค.");
+ }
+
+ if (name.length() > MAX_LEN) {
+ throw new IllegalArgumentException("[ERROR] ์ํ ๋ช
์ ์ต๋ 10์๊น์ง ์ค์ ํ ์ ์์ต๋๋ค.");
+ }
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o instanceof String) {
+ return o.equals(value);
+ }
+ if (o instanceof Name) {
+ return ((Name) o).value().equals(value);
+ }
+ return false;
+ }
+} | Java | vo ๊ฐ์ฒด๋ก ๊ฐ๋ฅํ ๊ฐ์ ๋ํ ๊ฒ์ฆ์ ๋ด๋ถ์์ ๋ด๋นํ๋ ๋ชจ์ต์ด ์ ๋ง ์ธ์ ๊น๋ค์! ํ์ง๋ง Quantity์ฒ๋ผ ๊ณ์ฐ ๊ณผ์ ์ด ๋ณต์กํด์ง ์ ์๊ณ ๊ณ์ฐํ ๋๋ง๋ค ์๋ก์ด ๊ฐ์ฒด๊ฐ ์์ฑ์ด ๋์ด์ผํ๋ค๋ ๋จ์ ์ด ์กด์ฌํ๋๊ฑฐ๋ก ๋ณด์ด๋๋ฐ ๋ณธ์ธ๋ง์ ์ ์ฉ ๊ธฐ์ค์ด ์์๊น์?? ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,128 @@
+package store.infrastructure.config;
+
+import store.controller.StoreController;
+import store.repository.inventory.InventoryRepository;
+import store.repository.inventory.InventoryRepositoryImpl;
+import store.repository.order.OrderRepository;
+import store.repository.order.OrderRepositoryImpl;
+import store.repository.product.ProductRepository;
+import store.repository.product.ProductRepositoryImpl;
+import store.repository.promotion.PromotionRepository;
+import store.repository.promotion.PromotionRepositoryImpl;
+import store.service.*;
+import store.validator.OrderValidator;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class AppConfig {
+ private ProductRepository productRepository;
+ private InventoryRepository inventoryRepository;
+ private OrderRepository orderRepository;
+ private PromotionRepository promotionRepository;
+
+ private ProductRepository productRepository() {
+ return new ProductRepositoryImpl();
+ }
+
+ private InventoryRepository inventoryRepository() {
+ return new InventoryRepositoryImpl();
+ }
+
+ private OrderRepository orderRepository() {
+ return new OrderRepositoryImpl();
+ }
+
+ private PromotionRepository promotionRepository() {
+ return new PromotionRepositoryImpl();
+ }
+
+ public ProductRepository getProductRepository() {
+ if (this.productRepository == null) {
+ this.productRepository = productRepository();
+ }
+ return this.productRepository;
+ }
+
+ public InventoryRepository getInventoryRepository() {
+ if (this.inventoryRepository == null) {
+ this.inventoryRepository = inventoryRepository();
+ }
+ return this.inventoryRepository;
+ }
+
+ public OrderRepository getOrderRepository() {
+ if (this.orderRepository == null) {
+ this.orderRepository = orderRepository();
+ }
+ return this.orderRepository;
+ }
+
+ public PromotionRepository getPromotionRepository() {
+ if (this.promotionRepository == null) {
+ this.promotionRepository = promotionRepository();
+ }
+ return this.promotionRepository;
+ }
+
+ public StoreFileInputService getStoreFileInputService() {
+ return new StoreFileInputService(
+ getProductRepository(),
+ getPromotionRepository(),
+ getInventoryRepository()
+ );
+ }
+
+ public ProductService getProductService() {
+ return new ProductService(
+ getOrderRepository(),
+ getProductRepository(),
+ getInventoryRepository()
+ );
+ }
+
+ public PromotionService getPromotionService() {
+ return new PromotionService(
+ getProductRepository(),
+ getInventoryRepository()
+ );
+ }
+
+ public OrderValidator getOrderValidator() {
+ return new OrderValidator(
+ getProductRepository(),
+ getInventoryRepository()
+ );
+ }
+
+ public OrderParser getOrderParser() {
+ return new OrderParser();
+ }
+
+ public ReceiptService getDiscountService() {
+ return new ReceiptService(
+ getOrderRepository(),
+ getProductRepository()
+ );
+ }
+
+ public InputView getInputView() {
+ return new InputView();
+ }
+
+ public OutputView getOutputView() {
+ return new OutputView();
+ }
+
+ public StoreController controller() {
+ return new StoreController(
+ getStoreFileInputService(),
+ getProductService(),
+ getPromotionService(),
+ getOrderValidator(),
+ getOrderParser(),
+ getDiscountService(),
+ getInputView(),
+ getOutputView()
+ );
+ }
+} | Java | ์ฐ์ ๋จ ๊ฐ์ฒด ํ๋๋ง ์์ฑ์ด ๋๋๋กํ๊ธฐ ์ํด์ ์ด๋ ๊ฒ ์ค๊ณ๋ฅผ ํ์
จ๊ตฐ์! ์ ํด๊ฒฐํ์ง ๋ชปํ์๋๋ฐ ํ๋ ๋ฐฐ์๊ฐ๋๋ค ๐ |
@@ -0,0 +1,128 @@
+package store.infrastructure.config;
+
+import store.controller.StoreController;
+import store.repository.inventory.InventoryRepository;
+import store.repository.inventory.InventoryRepositoryImpl;
+import store.repository.order.OrderRepository;
+import store.repository.order.OrderRepositoryImpl;
+import store.repository.product.ProductRepository;
+import store.repository.product.ProductRepositoryImpl;
+import store.repository.promotion.PromotionRepository;
+import store.repository.promotion.PromotionRepositoryImpl;
+import store.service.*;
+import store.validator.OrderValidator;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class AppConfig {
+ private ProductRepository productRepository;
+ private InventoryRepository inventoryRepository;
+ private OrderRepository orderRepository;
+ private PromotionRepository promotionRepository;
+
+ private ProductRepository productRepository() {
+ return new ProductRepositoryImpl();
+ }
+
+ private InventoryRepository inventoryRepository() {
+ return new InventoryRepositoryImpl();
+ }
+
+ private OrderRepository orderRepository() {
+ return new OrderRepositoryImpl();
+ }
+
+ private PromotionRepository promotionRepository() {
+ return new PromotionRepositoryImpl();
+ }
+
+ public ProductRepository getProductRepository() {
+ if (this.productRepository == null) {
+ this.productRepository = productRepository();
+ }
+ return this.productRepository;
+ }
+
+ public InventoryRepository getInventoryRepository() {
+ if (this.inventoryRepository == null) {
+ this.inventoryRepository = inventoryRepository();
+ }
+ return this.inventoryRepository;
+ }
+
+ public OrderRepository getOrderRepository() {
+ if (this.orderRepository == null) {
+ this.orderRepository = orderRepository();
+ }
+ return this.orderRepository;
+ }
+
+ public PromotionRepository getPromotionRepository() {
+ if (this.promotionRepository == null) {
+ this.promotionRepository = promotionRepository();
+ }
+ return this.promotionRepository;
+ }
+
+ public StoreFileInputService getStoreFileInputService() {
+ return new StoreFileInputService(
+ getProductRepository(),
+ getPromotionRepository(),
+ getInventoryRepository()
+ );
+ }
+
+ public ProductService getProductService() {
+ return new ProductService(
+ getOrderRepository(),
+ getProductRepository(),
+ getInventoryRepository()
+ );
+ }
+
+ public PromotionService getPromotionService() {
+ return new PromotionService(
+ getProductRepository(),
+ getInventoryRepository()
+ );
+ }
+
+ public OrderValidator getOrderValidator() {
+ return new OrderValidator(
+ getProductRepository(),
+ getInventoryRepository()
+ );
+ }
+
+ public OrderParser getOrderParser() {
+ return new OrderParser();
+ }
+
+ public ReceiptService getDiscountService() {
+ return new ReceiptService(
+ getOrderRepository(),
+ getProductRepository()
+ );
+ }
+
+ public InputView getInputView() {
+ return new InputView();
+ }
+
+ public OutputView getOutputView() {
+ return new OutputView();
+ }
+
+ public StoreController controller() {
+ return new StoreController(
+ getStoreFileInputService(),
+ getProductService(),
+ getPromotionService(),
+ getOrderValidator(),
+ getOrderParser(),
+ getDiscountService(),
+ getInputView(),
+ getOutputView()
+ );
+ }
+} | Java | public ๋ฉ์๋์ private ๋ฉ์๋ ์์ ๋ฐฐ์น์ ๊ธฐ์ค์ด ์์ผ์ ๊ฐ์? ์ ํฌํจ ๋ค๋ฅธ ๋ถ๋ค์ public์ ์์๋๊ณ private์ ์๋ ๋๋๋ฐ ๋ฐ๋์ฌ์ ์ด๋ ๊ฒ ์ ํํ์ ์ด์ ๊ฐ ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,6 @@
+package store.infrastructure.constant;
+
+public class Membership {
+ public static final int DISCOUNT_RATE = 30;
+ public static final int MAX = 8_000;
+} | Java | ๋ฏผ์ ๋์ ์์ํ ๊ธฐ์ค์ด ๊ถ๊ธํฉ๋๋ค! ์ด๋ค ๊ฑธ ENUM์ผ๋ก ๊ณตํต์ผ๋ก ๋ฌถ๊ณ ์ด๋ค ๊ฑธ ๋ด๋ถ๋ก ๊ด๋ฆฌํ์๋์? ๋ํ ์ด๋ค๊ฑด ํ๋์ฝ๋ฉ๋ ์ํ๋ก ๊ทธ๋๋ก ๋์๋์?? |
@@ -0,0 +1,54 @@
+package store.domain.vo;
+
+import store.infrastructure.constant.ExceptionMessage;
+import store.infrastructure.exception.CustomException;
+
+public record Price(int value) implements Comparable<Price> {
+ public static final int MIN = 10;
+ public static final int MAX = 1_000_000;
+
+ public Price {
+ validatePrice(value);
+ }
+
+ public static Price from(String input) {
+ try {
+ return new Price(Integer.parseInt(input.trim()));
+ } catch (NumberFormatException e) {
+ throw new CustomException(ExceptionMessage.WRONG_INTEGER_FORMAT.message());
+ }
+ }
+
+ private void validatePrice(int value) {
+ if (value < MIN || value > MAX) {
+ throw new CustomException(ExceptionMessage.WRONG_PRICE_RANGE.message());
+ }
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o instanceof Integer) {
+ return (Integer) o == value;
+ }
+ if (o instanceof Price) {
+ return ((Price) o).value == value;
+ }
+ return false;
+ }
+
+ @Override
+ public int compareTo(Price other) {
+ return value - other.value;
+ }
+
+ public int multiply(Quantity quantity) {
+ return quantity.value() * value;
+ }
+
+ public int multiply(int other) {
+ if (other <= 0) {
+ throw new IllegalStateException("0 ์ดํ์ ์ซ์๋ ๊ฐ๊ฒฉ์ ๊ณฑํ ์ ์์ต๋๋ค.");
+ }
+ return other * value;
+ }
+} | Java | ์ ์ ํฉํ ๋ฆฌ ๋ฉ์๋ ํจํด์ ๋ณดํต ์์ฑ์๋ฅผ private๋ก ๋ง๊ณ ๋ฉ์๋ ๋ช
๊ณผ ํ๋ผ๋ฏธํฐ๋ฅผ ํตํด ๊ทธ ์๋ฏธ๋ฅผ ์ ๋ฌํ๋ ๊ฒ์ผ๋ก ์๊ณ ์์ต๋๋ค! ์ด๋ ๊ฒ ์์ฑ์์ ์ ์ ํฉํ ๋ฆฌ ๋ฉ์๋ ํจํด์ ๋ ๋ค ์ฌ์ฉํ์ ์ด์ ๊ฐ ์์ผ์ค๊น์?? ์ ํํ ๊ธฐ์ค์ด ๊ถ๊ธํฉ๋๋ค! |
@@ -0,0 +1,176 @@
+package store.controller;
+
+import store.infrastructure.constant.Message;
+import store.service.OrderParser;
+import store.domain.vo.Name;
+import store.domain.vo.Order;
+import store.domain.vo.Quantity;
+import store.service.*;
+import store.service.dto.request.ApplyPromotionRequest;
+import store.service.dto.response.PromotionCommandResponse;
+import store.service.dto.response.PromotionQueryResponse;
+import store.domain.vo.PromotionOption;
+import store.service.strategy.PromotionStrategy;
+import store.service.strategy.provider.PromotionStrategyProvider;
+import store.validator.OrderValidator;
+import store.view.InputView;
+import store.view.OutputView;
+import store.view.dto.calculate.ReceiptCalculateRequest;
+import store.view.dto.gift.ReceiptGiftViewRequest;
+import store.view.dto.order.ReceiptOrderViewRequest;
+import store.view.dto.product.ProductViewRequest;
+
+import java.util.List;
+
+public class StoreController {
+ private final StoreFileInputService storeFileInputService;
+ private final ProductService productService;
+ private final PromotionService promotionService;
+ private final OrderValidator orderValidator;
+ private final OrderParser orderParser;
+ private final ReceiptService receiptService;
+ private final InputView inputView;
+ private final OutputView outputView;
+
+ public StoreController(
+ StoreFileInputService storeFileInputService,
+ ProductService productService,
+ PromotionService promotionService,
+ OrderValidator orderValidator,
+ OrderParser orderParser,
+ ReceiptService receiptService,
+ InputView inputView,
+ OutputView outputView
+ ) {
+ this.storeFileInputService = storeFileInputService;
+ this.productService = productService;
+ this.promotionService = promotionService;
+ this.orderValidator = orderValidator;
+ this.orderParser = orderParser;
+ this.receiptService = receiptService;
+ this.inputView = inputView;
+ this.outputView = outputView;
+ }
+
+ public void run() {
+ storeFileInputService.loadAndSave();
+ while (true) {
+ printInfo();
+ receiveOrder();
+ handleDiscount();
+ applyOrder();
+ printReceipt();
+ resetOrder();
+ if (!isContinue()) break;
+ }
+ }
+
+ private boolean isContinue() {
+ return inputView.readAdditionalPurchase();
+ }
+
+ private void printInfo() {
+ outputView.printWelcome();
+ outputView.printProducts(new ProductViewRequest(productService.getAllProductInfo()));
+ }
+
+ private void printReceipt() {
+ printReceiptOrder();
+ printReceiptGift();
+ printReceiptCalculate();
+ }
+
+ private void printReceiptOrder() {
+ outputView.printReceiptTitle(Message.STORE_NAME);
+ outputView.printReceiptOrderContent(new ReceiptOrderViewRequest(receiptService.getOrderResult()));
+ }
+
+ private void printReceiptGift() {
+ outputView.printReceiptTitle("์ฆ ์ ");
+ outputView.printReceiptGiftContent(new ReceiptGiftViewRequest(receiptService.getPromotionResult()));
+ }
+
+ private void printReceiptCalculate() {
+ outputView.printReceiptTitle();
+ outputView.printReceiptCalculateContent(
+ new ReceiptCalculateRequest(
+ receiptService.getOrderResult().size(),
+ receiptService.getTotalOrderPrice(),
+ receiptService.getTotalPromotionDiscount(),
+ receiptService.getMembershipDiscount(),
+ receiptService.getPayPrice()
+ ));
+ }
+
+ private void receiveOrder() {
+ while (true) {
+ try {
+ List<Order> orders = orderParser.from(inputView.readItem());
+ orderValidator.validate(orders);
+ receiptService.setOrder(orders);
+ break;
+ } catch (IllegalArgumentException e) {
+ outputView.printMessage(e.getMessage());
+ }
+ }
+ }
+
+ private void handleDiscount() {
+ handlePromotion();
+ handleMembership();
+ }
+
+ private void handlePromotion() {
+ List<Order> orders = receiptService.getAllOrder();
+ for (Order order : orders) {
+ if (promotionService.isExistApplicablePromotion(order.productName())) {
+ PromotionQueryResponse queryResult = promotionService.query(order);
+ PromotionCommandResponse response = getPromotionResult(order, queryResult);
+ receiptService.setOrder(response.order());
+ receiptService.addPromotionDiscount(order.productName(), response.giftQuantity());
+ }
+ }
+ }
+
+ private PromotionCommandResponse getPromotionResult(Order order, PromotionQueryResponse queryResponse) {
+ if (queryResponse.option().equals(PromotionOption.NONE)) {
+ return new PromotionCommandResponse(order, queryResponse.giftQuantity());
+ }
+ PromotionStrategy strategy = getStrategy(order, queryResponse);
+
+ ApplyPromotionRequest request = new ApplyPromotionRequest(order, strategy);
+ return promotionService.command(request);
+ }
+
+ private PromotionStrategy getStrategy(Order order, PromotionQueryResponse queryResponse) {
+ if (queryResponse.option().equals(PromotionOption.ADD_FREE)) {
+ return getAddFreeStrategy(order.productName());
+ }
+ return getRegularPurchaseStrategy(order.productName(), queryResponse.notAppliedQuantity());
+ }
+
+ private PromotionStrategy getAddFreeStrategy(Name productName) {
+ final boolean answer = inputView.readAddFreeAnswer(productName.value());
+ return PromotionStrategyProvider.from(PromotionOption.ADD_FREE, answer);
+ }
+
+ private PromotionStrategy getRegularPurchaseStrategy(Name productName, Quantity excluded) {
+ final boolean answer = inputView.readPaidRegularPriceAnswer(productName.value(), excluded.value());
+ return PromotionStrategyProvider.from(PromotionOption.REGULAR_PURCHASE, answer);
+ }
+
+ private void handleMembership() {
+ final boolean apply = inputView.readMembershipAnswer();
+ if (apply) {
+ receiptService.setMembershipDiscount();
+ }
+ }
+
+ private void applyOrder() {
+ productService.applyReceiptInventory();
+ }
+
+ private void resetOrder() {
+ receiptService.reset();
+ }
+} | Java | `do-while`์ ์๊ฐํ์ง ๋ชปํ๋๋ฐ, ์ข์ ๋ฐฉ๋ฒ์ธ ๊ฒ ๊ฐ์์!
๊ฐ์ฌํฉ๋๋ค |
@@ -0,0 +1,31 @@
+package store.domain.vo;
+
+public record Name(String value) {
+ public static final int MAX_LEN = 10;
+
+ public Name(String value) {
+ validateName(value.trim());
+ this.value = value.trim();
+ }
+
+ private void validateName(String name) {
+ if (name == null || name.isEmpty()) {
+ throw new IllegalArgumentException("[ERROR] ์ํ๋ช
์ ๊ณต๋ฐฑ์ผ๋ก ์ค์ ํ ์ ์์ต๋๋ค.");
+ }
+
+ if (name.length() > MAX_LEN) {
+ throw new IllegalArgumentException("[ERROR] ์ํ ๋ช
์ ์ต๋ 10์๊น์ง ์ค์ ํ ์ ์์ต๋๋ค.");
+ }
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o instanceof String) {
+ return o.equals(value);
+ }
+ if (o instanceof Name) {
+ return ((Name) o).value().equals(value);
+ }
+ return false;
+ }
+} | Java | ์ฐ์ ์ข์ ์ง๋ฌธ ๋จ๊ฒจ์ฃผ์
์ ๊ฐ์ฌ๋๋ฆฝ๋๋ค!
์ ๋ ์ฌํ๋์ด ๋ง์ํด์ฃผ์ ๊ฒ์ฒ๋ผ `vo ๊ฐ์ฒด`๋ฅผ ์ฌ์ฉํ๋ฉด์ **๊ฐ์ฒด๋ฅผ ๋งค๋ฒ ์๋ก ์์ฑํด์ผ ํ๋ค๋ ์ **, **์ฐ์ฐ ๊ณผ์ ์ด ๋ณต์กํด์ง ์ ์๋ค๋ ์ **์์ ๊ณ ๋ฏผ์ ๋ง์ด ํ์๋๋ฐ์,
์๋ ๋ ํญ๋ชฉ์ด ๊ฐ์ ธ๋ค์ฃผ๋ ์ด์ ์ด ๋ ํฌ๋ค๊ณ ์๊ฐ๋๋ ๋ถ๋ถ์๋ `vo ๊ฐ์ฒด`๋ฅผ ๋์
ํ์ต๋๋ค.
```
1. ๊ฒ์ฆ ์์น๋ฅผ ํ ๊ณณ์ผ๋ก(๊ฐ์ฒด ๋ด๋ถ๋ก) ํต์ผ์ํฌ ์ ์๋ค.
2. ๋ถ๋ณ์ฑ์ ๋ณด์ฅํ์ฌ ์์ ์ ์ผ๋ก ๊ฐ์ ๊ด๋ฆฌํ ์ ์๋ค.
```
์๋ฅผ๋ค์ด `์ํ๋ช
`์ ๊ฒฝ์ฐ์๋ ์ถ๋ ฅ ํฌ๋งท์ ์ํฅ์ ์ค ์ ์๊ธฐ ๋๋ฌธ์, `์ํ๋ช
๊ธธ์ด ์ ํ`์ด ํ์ํ๋ค๊ณ ์๊ฐํ์ด์.
์ด๋ฌํ `์ํ๋ช
์ ๋ํ ๊ฒ์ฆ ์๊ตฌ์ฌํญ`์ ์ธ์ ๋ ์ง ๋ณ๋๋ ์ ์๊ธฐ ๋๋ฌธ์, **validation ๊ณผ์ **์ ์ธ๋ถ์ ๋๋ ๊ฒ๋ณด๋ค๋ **๊ฐ ์์ฒด๋ฅผ ๊ฐ์ฒด๋ก ๊ด๋ฆฌํด์ ๊ด๋ฆฌ ์ง์ ์ ํต์ผ์ํค๊ณ ์** ํ์ต๋๋ค.
๋ํ, ์ํ๋ช
์ **์๋น์ค๊ฐ ๋์ํ๋ ๋์์๋ ๋ณ๋๋ ์ผ์ด ์๊ธฐ** ๋๋ฌธ์, `๋ถ๋ณ์ฑ`์ ๋ณด์ฅํ๋ค๋ ์ธก๋ฉด์์๋ ๋ณ๋์ ๊ฐ์ฒด๋ก ๊ด๋ฆฌํ๋ ๊ฒ์ด ์์ ์ ์ผ ๊ฒ์ด๋ผ๊ณ ์๊ฐํ์ต๋๋ค |
@@ -0,0 +1,54 @@
+package store.domain.vo;
+
+import store.infrastructure.constant.ExceptionMessage;
+import store.infrastructure.exception.CustomException;
+
+public record Price(int value) implements Comparable<Price> {
+ public static final int MIN = 10;
+ public static final int MAX = 1_000_000;
+
+ public Price {
+ validatePrice(value);
+ }
+
+ public static Price from(String input) {
+ try {
+ return new Price(Integer.parseInt(input.trim()));
+ } catch (NumberFormatException e) {
+ throw new CustomException(ExceptionMessage.WRONG_INTEGER_FORMAT.message());
+ }
+ }
+
+ private void validatePrice(int value) {
+ if (value < MIN || value > MAX) {
+ throw new CustomException(ExceptionMessage.WRONG_PRICE_RANGE.message());
+ }
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o instanceof Integer) {
+ return (Integer) o == value;
+ }
+ if (o instanceof Price) {
+ return ((Price) o).value == value;
+ }
+ return false;
+ }
+
+ @Override
+ public int compareTo(Price other) {
+ return value - other.value;
+ }
+
+ public int multiply(Quantity quantity) {
+ return quantity.value() * value;
+ }
+
+ public int multiply(int other) {
+ if (other <= 0) {
+ throw new IllegalStateException("0 ์ดํ์ ์ซ์๋ ๊ฐ๊ฒฉ์ ๊ณฑํ ์ ์์ต๋๋ค.");
+ }
+ return other * value;
+ }
+} | Java | ์ผ๋จ `record`์ ๊ฒฝ์ฐ `private` ์์ฑ์๋ฅผ ์ ์ธํ๋๋ผ๋, ์๋์ ๊ฐ์ด ์ง์ ์์ฑํ๋ ๊ฒ์ ๋ง์ ์ ์๋ค๊ณ ์๊ณ ์์ต๋๋ค!
```java
Price price = new Price(1000);
```
๋ฌด์๋ณด๋ค ์ ๊ฐ ์๋ํ๋ ๊ฒ์ **์ ์ ๊ฐ ๋ฟ๋ง ์๋๋ผ, ์ ์๋ฅผ ๋ด๋ String ๊ฐ์ฒด๋ก๋ `Price ๊ฐ์ฒด`๋ฅผ ์์ฑํ ์ ์๋๋ก ํ๋ ๊ฒ**์ด์์ต๋๋ค.
- ์ฆ, **int ์๋ฃํ**์ผ๋ก๋ง `Price ๊ฐ์ฒด`๋ฅผ ์์ฑํ๋ ๊ฒ์ด ์๋, **String ์๋ฃํ**์ผ๋ก๋ `Price ๊ฐ์ฒด`๋ฅผ ์์ฑํ ์ ์๋๋ก ์๋ํ์ต๋๋ค! |
@@ -0,0 +1,128 @@
+package store.infrastructure.config;
+
+import store.controller.StoreController;
+import store.repository.inventory.InventoryRepository;
+import store.repository.inventory.InventoryRepositoryImpl;
+import store.repository.order.OrderRepository;
+import store.repository.order.OrderRepositoryImpl;
+import store.repository.product.ProductRepository;
+import store.repository.product.ProductRepositoryImpl;
+import store.repository.promotion.PromotionRepository;
+import store.repository.promotion.PromotionRepositoryImpl;
+import store.service.*;
+import store.validator.OrderValidator;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class AppConfig {
+ private ProductRepository productRepository;
+ private InventoryRepository inventoryRepository;
+ private OrderRepository orderRepository;
+ private PromotionRepository promotionRepository;
+
+ private ProductRepository productRepository() {
+ return new ProductRepositoryImpl();
+ }
+
+ private InventoryRepository inventoryRepository() {
+ return new InventoryRepositoryImpl();
+ }
+
+ private OrderRepository orderRepository() {
+ return new OrderRepositoryImpl();
+ }
+
+ private PromotionRepository promotionRepository() {
+ return new PromotionRepositoryImpl();
+ }
+
+ public ProductRepository getProductRepository() {
+ if (this.productRepository == null) {
+ this.productRepository = productRepository();
+ }
+ return this.productRepository;
+ }
+
+ public InventoryRepository getInventoryRepository() {
+ if (this.inventoryRepository == null) {
+ this.inventoryRepository = inventoryRepository();
+ }
+ return this.inventoryRepository;
+ }
+
+ public OrderRepository getOrderRepository() {
+ if (this.orderRepository == null) {
+ this.orderRepository = orderRepository();
+ }
+ return this.orderRepository;
+ }
+
+ public PromotionRepository getPromotionRepository() {
+ if (this.promotionRepository == null) {
+ this.promotionRepository = promotionRepository();
+ }
+ return this.promotionRepository;
+ }
+
+ public StoreFileInputService getStoreFileInputService() {
+ return new StoreFileInputService(
+ getProductRepository(),
+ getPromotionRepository(),
+ getInventoryRepository()
+ );
+ }
+
+ public ProductService getProductService() {
+ return new ProductService(
+ getOrderRepository(),
+ getProductRepository(),
+ getInventoryRepository()
+ );
+ }
+
+ public PromotionService getPromotionService() {
+ return new PromotionService(
+ getProductRepository(),
+ getInventoryRepository()
+ );
+ }
+
+ public OrderValidator getOrderValidator() {
+ return new OrderValidator(
+ getProductRepository(),
+ getInventoryRepository()
+ );
+ }
+
+ public OrderParser getOrderParser() {
+ return new OrderParser();
+ }
+
+ public ReceiptService getDiscountService() {
+ return new ReceiptService(
+ getOrderRepository(),
+ getProductRepository()
+ );
+ }
+
+ public InputView getInputView() {
+ return new InputView();
+ }
+
+ public OutputView getOutputView() {
+ return new OutputView();
+ }
+
+ public StoreController controller() {
+ return new StoreController(
+ getStoreFileInputService(),
+ getProductService(),
+ getPromotionService(),
+ getOrderValidator(),
+ getOrderParser(),
+ getDiscountService(),
+ getInputView(),
+ getOutputView()
+ );
+ }
+} | Java | ์ ๋ค ๋ง์ต๋๋ค! ์ ๋ ๋ณดํต **์๋จ์ public ๋ฉ์๋**๋ฅผ ๋ฐฐ์นํ๊ณ , **ํธ์ถ ์์์ ๋ฐ๋ผ์ private ๋ฉ์๋๋ฅผ ํ๋จ**์ ๋ฐฐ์นํ๋๋ฐ์, `AppConfig` ํด๋์ค์ ๊ฒฝ์ฐ์๋ ๋ชฉ์ ์ ๋ง๊ฒ ์กฐ๊ธ ๋ค๋ฅด๊ฒ ๋ฐฐ์น๋ฅผ ํ์ต๋๋ค.
`AppConfig` ํด๋์ค๋ **ํ์ฌ ์๊ตฌ์ฌํญ์ ๋ง๋ ๊ตฌํ์ฒด**์ ๋ฐ๋ผ์ **์์กด์ฑ์ ๊ด๋ฆฌ**ํ๋ ์ญํ ์ ํฉ๋๋ค.
- ๊ฐ์ธ์ ์ผ๋ก `์์กด ๊ด๊ณ`๋ณด๋ค๋ `๊ตฌํ์ฒด`๊ฐ ๋ณ๊ฒฝ๋๋ ๊ฒฝ์ฐ๊ฐ ๋ ๋น๋ฒํ ๊ฒ์ด๋ผ๊ณ ์๊ฐํ๊ณ , **๊ตฌํ์ฒด๋ฅผ ๋ฐํํ๋ ๋ฉ์๋๋ฅผ ์๋จ์ผ๋ก** ์ฌ๋ฆฌ๋ ๊ฒ์ด ๋ ๋์ ๋ ๊ฒ์ด๋ผ๊ณ ์๊ฐํ์ต๋๋ค.
- ๊ทธ๋ฆฌ๊ณ ํ์ฌ ์๋น์ค์์๋ `์ด๋ค ๊ตฌํ์ฒด์ ์ํด ๋์ํ๋์ง`๋ฅผ ๋จผ์ ๋ณด์ฌ์ฃผ๋๊ฒ ๋ ์ข๋ค๊ณ ์๊ฐํด์, ๋ ํ์งํ ๋ฆฌ ๊ตฌํ์ฒด๋ฅผ ๋ฐํํ๋ ๋ฉ์๋๋ฅผ ๋งจ ์์ ๋ฐฐ์น์์ผฐ๋ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,6 @@
+package store.infrastructure.constant;
+
+public class Membership {
+ public static final int DISCOUNT_RATE = 30;
+ public static final int MAX = 8_000;
+} | Java | ์ข์ ์ง๋ฌธ์ธ ๊ฒ ๊ฐ์ต๋๋ค!
### 1. ์์ํ ์ฌ๋ถ ๊ฒฐ์
> ์ ๋ ์ฐ์ ๋ช ๊ฐ์ง ๋ถ๋ฅ ๊ธฐ์ค์ผ๋ก **์์ํ๋ฅผ ๊ฒฐ์ **ํฉ๋๋ค.
- ์ฒซ ๋ฒ์งธ ๋ถ๋ฅ ๊ธฐ์ค์ `์๋น์ค ์๊ตฌ์ฌํญ๊ณผ์ ๋ฐ์ ๋`์ธ ๊ฒ ๊ฐ์ต๋๋ค.
**์๋น์ค ์๊ตฌ์ฌํญ**์ ๋ณ๋ ๊ฐ๋ฅ์ฑ์ด ํฐ ๋ถ๋ถ์ด๋ผ๊ณ ์๊ฐํด์, **_์ด์ ๋ฐ์ ํ๊ฒ ์ฐ๊ด๋ ๊ฐ๋ค์ ๋ฐ๋ก ์์๋ก ๊ด๋ฆฌํ๋ ๊ฒ_** ์ด ์ข๋ค๊ณ ์๊ฐํด์.
๐๐ป ์๋ฅผ๋ค์ด `๋ฉค๋ฒ์ญ ํ ์ธ์จ`์ด๋ `์ต๋ ํ ์ธ ๊ฐ๋ฅ ๊ธ์ก`์ ์๋น์ค ์๊ตฌ์ฌํญ๊ณผ ๋ฐ์ ํ ์ฐ๊ด์ด ์์ผ๋ฏ๋ก ์์๋ก ๊ด๋ฆฌํฉ๋๋ค.
- ๋ ๋ฒ์งธ๋ `์๋ฏธ๊ฐ ํํ๋์ง ์๋ ๊ฐ`์
๋๋ค.
**์๋ฏธ๋ฅผ ํฌํจํ์ง ์๋ ๊ฐ**์ ๊ทธ๋๋ก ์ฌ์ฉํ๋ฉด, ์ฝ๋๋ฅผ ์ดํดํ๋๋ฐ ์์ด์๋ ์ด๋ ค์์ด ์๋ค๊ณ ์๊ฐํด์.
๐๐ป ์๋ฅผ๋ค์ด ์ฝค๋ง(`,`), ๋์(`-`) ๋ฑ๊ณผ ๊ฐ์ ๋ฌธ์๋ ๋ฌธ์ ์์ฒด๋ก ์๋ฏธ๊ฐ ํํ๋์ง ์์ต๋๋ค. ๋์์ ์ด ๊ฐ๋ค์ `์
์ถ๋ ฅ ์๊ตฌ์ฌํญ`๊ณผ๋ ๋ฐ์ ํ ์ฐ๊ด์ด ์๊ธฐ ๋๋ฌธ์, ์์ํ๋ฅผ ๊ฒฐ์ ํ์ต๋๋ค.
### 2. ์์ ์์น
> ๊ทธ๋ฆฌ๊ณ ์ด๋ ๊ฒ ์์ํํ ๊ฐ๋ค์ `๋ณ๋์ ํด๋์ค์์ ๊ด๋ฆฌ`ํ ๊ฒ์ธ์ง, `๊ด๋ จ ํด๋์ค ๋ด๋ถ์์ ๊ด๋ฆฌ`ํ ๊ฒ์ธ์ง๋ ๋ง์ด ๊ณ ๋ฏผํ๊ฒ ๋๋๋ฐ์,
- ์ฐ์ ๊ฐ ๊ทธ ์์ฒด์ ์กฐ๊ฑด์ ๋ํ ์์ ๊ฐ _(ex. price์ ์ต๋, ์ต์ ๊ฐ)_ ๋ค์ ๋ณดํต `vo ๊ฐ์ฒด` ๋ด๋ถ์์ ๊ด๋ฆฌํฉ๋๋ค.
๐๐ป ๊ฐ์ ๋ํ `๊ฒ์ฆ ์กฐ๊ฑด`๊ณผ `๊ฒ์ฆ ๊ณผ์ `์ ๋ชจ๋ vo ๊ฐ์ฒด ๋ด๋ถ์์ ๊ด๋ฆฌํ๋ ๊ฒ์ด **์์ง๋** ์ธก๋ฉด์์ ์ข๋ค๊ณ ์๊ฐํ๊ธฐ ๋๋ฌธ์ด์์.
- ๊ทธ ์ธ์ ์๋น์ค ์๊ตฌ์ฌํญ ๊ด๋ จ ์์ ๊ฐ๋ค์ ๋๋ฉ์ธ ์ธ๋ถ์ ํด๋์ค๋ก ๋ฌถ์ด์ ๊ด๋ฆฌํฉ๋๋ค.
๐๐ป ์๋ฅผ๋ค์ด `๋ฉค๋ฒ์ญ ํ ์ธ์จ` ๋ฐ `์ต๋ ํ ์ธ ๊ธ์ก`์ ๊ฒฝ์ฐ, ๊ฐ ์์ฒด๋ณด๋ค๋ `์๋น์ค ๋ก์ง์ ์ฒ๋ฆฌํ๋ ๊ณผ์ `์ ์ ํ์ ๋๋ ์ญํ ์ ๊ฐ๊น๋ค๊ณ ์๊ฐํ์ต๋๋ค.
ํนํ, ๋ฉค๋ฒ์ญ๊ณผ ๊ฐ์ด **์๋น์ค ๋ก์ง์ ์ฒ๋ฆฌํ๋ ๊ณผ์ ์ ํ์ํ ์์ ๊ฐ๋ค**์ ๋๋ฉ์ธ ๊ฐ์ฒด ๋ด๋ถ์์ ๊ด๋ฆฌํ๊ธฐ๋ณด๋ค๋, ์๋น์ค ๊ณ์ธต๊ณผ ๋์ผํ ๋ ๋ฒจ์์(= `infrastructure`) ๊ด๋ฆฌํ๋ ๊ฒ์ด ๋ ์ง๊ด์ ์ด๋ผ๊ณ ์๊ฐํ์ด์.
### ์ ๋ฆฌ
์ค๋ช
์ด ๋๋ฌด ์ฅํฉํด์ง ๊ฒ ๊ฐ์๋ฐ.. ์ ๋ฆฌํ์๋ฉด
- ์๋น์ค ๋ก์ง ์ฒ๋ฆฌ ๊ณผ์ ์ ํ์ํ ๊ฐ๋ค์ ๋ณดํต ์ธ๋ถ์ ํด๋์ค๋ก ๋ถ๋ฆฌํด์ ๊ด๋ฆฌํ๋ ํธ์ด๊ณ ,
- ๋๋ฉ์ธ ๊ฐ์ฒด ๊ฐ๊ณผ ๋ฐ์ ํ ๊ฐ๋ค์ ๋๋ฉ์ธ ๊ฐ์ฒด ๋ด๋ถ์์ ๊ด๋ฆฌํ๋ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,176 @@
+package store.controller;
+
+import store.infrastructure.constant.Message;
+import store.service.OrderParser;
+import store.domain.vo.Name;
+import store.domain.vo.Order;
+import store.domain.vo.Quantity;
+import store.service.*;
+import store.service.dto.request.ApplyPromotionRequest;
+import store.service.dto.response.PromotionCommandResponse;
+import store.service.dto.response.PromotionQueryResponse;
+import store.domain.vo.PromotionOption;
+import store.service.strategy.PromotionStrategy;
+import store.service.strategy.provider.PromotionStrategyProvider;
+import store.validator.OrderValidator;
+import store.view.InputView;
+import store.view.OutputView;
+import store.view.dto.calculate.ReceiptCalculateRequest;
+import store.view.dto.gift.ReceiptGiftViewRequest;
+import store.view.dto.order.ReceiptOrderViewRequest;
+import store.view.dto.product.ProductViewRequest;
+
+import java.util.List;
+
+public class StoreController {
+ private final StoreFileInputService storeFileInputService;
+ private final ProductService productService;
+ private final PromotionService promotionService;
+ private final OrderValidator orderValidator;
+ private final OrderParser orderParser;
+ private final ReceiptService receiptService;
+ private final InputView inputView;
+ private final OutputView outputView;
+
+ public StoreController(
+ StoreFileInputService storeFileInputService,
+ ProductService productService,
+ PromotionService promotionService,
+ OrderValidator orderValidator,
+ OrderParser orderParser,
+ ReceiptService receiptService,
+ InputView inputView,
+ OutputView outputView
+ ) {
+ this.storeFileInputService = storeFileInputService;
+ this.productService = productService;
+ this.promotionService = promotionService;
+ this.orderValidator = orderValidator;
+ this.orderParser = orderParser;
+ this.receiptService = receiptService;
+ this.inputView = inputView;
+ this.outputView = outputView;
+ }
+
+ public void run() {
+ storeFileInputService.loadAndSave();
+ while (true) {
+ printInfo();
+ receiveOrder();
+ handleDiscount();
+ applyOrder();
+ printReceipt();
+ resetOrder();
+ if (!isContinue()) break;
+ }
+ }
+
+ private boolean isContinue() {
+ return inputView.readAdditionalPurchase();
+ }
+
+ private void printInfo() {
+ outputView.printWelcome();
+ outputView.printProducts(new ProductViewRequest(productService.getAllProductInfo()));
+ }
+
+ private void printReceipt() {
+ printReceiptOrder();
+ printReceiptGift();
+ printReceiptCalculate();
+ }
+
+ private void printReceiptOrder() {
+ outputView.printReceiptTitle(Message.STORE_NAME);
+ outputView.printReceiptOrderContent(new ReceiptOrderViewRequest(receiptService.getOrderResult()));
+ }
+
+ private void printReceiptGift() {
+ outputView.printReceiptTitle("์ฆ ์ ");
+ outputView.printReceiptGiftContent(new ReceiptGiftViewRequest(receiptService.getPromotionResult()));
+ }
+
+ private void printReceiptCalculate() {
+ outputView.printReceiptTitle();
+ outputView.printReceiptCalculateContent(
+ new ReceiptCalculateRequest(
+ receiptService.getOrderResult().size(),
+ receiptService.getTotalOrderPrice(),
+ receiptService.getTotalPromotionDiscount(),
+ receiptService.getMembershipDiscount(),
+ receiptService.getPayPrice()
+ ));
+ }
+
+ private void receiveOrder() {
+ while (true) {
+ try {
+ List<Order> orders = orderParser.from(inputView.readItem());
+ orderValidator.validate(orders);
+ receiptService.setOrder(orders);
+ break;
+ } catch (IllegalArgumentException e) {
+ outputView.printMessage(e.getMessage());
+ }
+ }
+ }
+
+ private void handleDiscount() {
+ handlePromotion();
+ handleMembership();
+ }
+
+ private void handlePromotion() {
+ List<Order> orders = receiptService.getAllOrder();
+ for (Order order : orders) {
+ if (promotionService.isExistApplicablePromotion(order.productName())) {
+ PromotionQueryResponse queryResult = promotionService.query(order);
+ PromotionCommandResponse response = getPromotionResult(order, queryResult);
+ receiptService.setOrder(response.order());
+ receiptService.addPromotionDiscount(order.productName(), response.giftQuantity());
+ }
+ }
+ }
+
+ private PromotionCommandResponse getPromotionResult(Order order, PromotionQueryResponse queryResponse) {
+ if (queryResponse.option().equals(PromotionOption.NONE)) {
+ return new PromotionCommandResponse(order, queryResponse.giftQuantity());
+ }
+ PromotionStrategy strategy = getStrategy(order, queryResponse);
+
+ ApplyPromotionRequest request = new ApplyPromotionRequest(order, strategy);
+ return promotionService.command(request);
+ }
+
+ private PromotionStrategy getStrategy(Order order, PromotionQueryResponse queryResponse) {
+ if (queryResponse.option().equals(PromotionOption.ADD_FREE)) {
+ return getAddFreeStrategy(order.productName());
+ }
+ return getRegularPurchaseStrategy(order.productName(), queryResponse.notAppliedQuantity());
+ }
+
+ private PromotionStrategy getAddFreeStrategy(Name productName) {
+ final boolean answer = inputView.readAddFreeAnswer(productName.value());
+ return PromotionStrategyProvider.from(PromotionOption.ADD_FREE, answer);
+ }
+
+ private PromotionStrategy getRegularPurchaseStrategy(Name productName, Quantity excluded) {
+ final boolean answer = inputView.readPaidRegularPriceAnswer(productName.value(), excluded.value());
+ return PromotionStrategyProvider.from(PromotionOption.REGULAR_PURCHASE, answer);
+ }
+
+ private void handleMembership() {
+ final boolean apply = inputView.readMembershipAnswer();
+ if (apply) {
+ receiptService.setMembershipDiscount();
+ }
+ }
+
+ private void applyOrder() {
+ productService.applyReceiptInventory();
+ }
+
+ private void resetOrder() {
+ receiptService.reset();
+ }
+} | Java | ํด๋น ์ฝ๋๋ฅผ ์์ฑํ ๋น์ `์์์ฆ ์ถ๋ ฅ์ ์ด๋ป๊ฒ ํํํ ๊ฒ์ธ์ง`๋ฅผ ์ปจํธ๋กค๋ฌ๊ฐ ๊ฒฐ์ ํ ์ฑ
์์ด ์๋ค๊ณ ์๊ฐํ์์ต๋๋ค.
๊ทธ๋ฐ๋ฐ ์ฌํ๋ ์๊ฒฌ์ ํ์ธํด๋ณด๋, ์ด ๋ถ๋ถ์ view์๊ฒ ์ฑ
์์ ์ฃผ๋๊ฒ ๋ ์ ํฉํ๊ฒ ๋ค๋ ์๊ฐ์ด ๋๋ค์..! |
@@ -4,7 +4,14 @@
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
-import org.springframework.web.bind.annotation.*;
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.ResponseStatus;
+import org.springframework.web.bind.annotation.RestController;
import roomit.main.domain.business.dto.CustomBusinessDetails;
import roomit.main.domain.business.dto.request.BusinessRegisterRequest;
import roomit.main.domain.business.dto.request.BusinessUpdateRequest;
@@ -13,38 +20,39 @@
@RestController
+@RequestMapping("/api/v1/business")
@RequiredArgsConstructor
public class BusinessController {
private final BusinessService businessService;
//์ฌ์
์ ํ์ ๊ฐ์
@ResponseStatus(HttpStatus.CREATED)
- @PostMapping("/api/v1/business/signup")
- public void signup(@RequestBody @Valid BusinessRegisterRequest request) {
+ @PostMapping("/signup")
+ public void signUp(@RequestBody @Valid BusinessRegisterRequest request) {
businessService.signUpBusiness(request);
}
//์ฌ์
์ ์ ๋ณด ์์
@ResponseStatus(HttpStatus.NO_CONTENT)
- @PutMapping("api/v1/business")
- public void businessModify(@RequestBody @Valid BusinessUpdateRequest businessUpdateRequest
- ,@AuthenticationPrincipal CustomBusinessDetails customBusinessDetails){
+ @PutMapping
+ public void businessModify(@RequestBody @Valid BusinessUpdateRequest businessUpdateRequest,
+ @AuthenticationPrincipal CustomBusinessDetails customBusinessDetails){
businessService.updateBusinessInfo(customBusinessDetails.getId(), businessUpdateRequest);
}
//์ฌ์
์ ์ ๋ณด ์กฐํ
@ResponseStatus(HttpStatus.OK)
- @GetMapping("api/v1/business")
+ @GetMapping
public BusinessResponse businessRead(@AuthenticationPrincipal CustomBusinessDetails customBusinessDetails){
return businessService.readBusinessInfo(customBusinessDetails.getId());
}
//์ฌ์
์ ํํด
@ResponseStatus(HttpStatus.NO_CONTENT)
- @DeleteMapping("api/v1/business")
+ @DeleteMapping
public void businessDelete(@AuthenticationPrincipal CustomBusinessDetails customBusinessDetails){
businessService.deleteBusiness(customBusinessDetails.getId());
} | Java | ์ฌ์ํ๊ฑฐ๊ธด ํ๋ฐ, ์ฌ์ค ์ด๋ฐ ๊ฒฝ์ฐ์ ๊ทธ๋ฅ `@PutMapping` ์ ์จ๋ ๋ฉ๋๋ค. |
@@ -1,15 +1,40 @@
package roomit.main.domain.business.repository;
+import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import roomit.main.domain.business.entity.Business;
-import java.util.Optional;
-
public interface BusinessRepository extends JpaRepository<Business, Long> {
- @Query(value = "SELECT b FROM Business b WHERE b.businessEmail.value=:email")
- Optional<Business> findByBusinessEmail(String email);
-
+ @Query(value = "SELECT b FROM Business b WHERE b.businessEmail.value=:businessEmail")
+ Optional<Business> findByBusinessEmail(String businessEmail);
+
+ @Query("""
+ SELECT CASE WHEN EXISTS (
+ SELECT 1
+ FROM Business b
+ WHERE b.businessName.value = :businessName
+ ) THEN TRUE ELSE FALSE END
+ """)
+ Boolean existsByBusinessName(String businessName);
+
+ @Query("""
+ SELECT CASE WHEN EXISTS (
+ SELECT 1
+ FROM Business b
+ WHERE b.businessEmail.value = :businessEmail
+ ) THEN TRUE ELSE FALSE END
+ """)
+ Boolean existsByBusinessEmail(String businessEmail);
+
+ @Query("""
+ SELECT CASE WHEN EXISTS (
+ SELECT 1
+ FROM Business b
+ WHERE b.businessNum.value = :businessNum
+ ) THEN TRUE ELSE FALSE END
+ """)
+ Boolean existsByBusinessNum(String businessNum);
}
| Java | ์กด์ฌ ์ฌ๋ถ๋ฅผ ํ์ธํ๋ ๊ฑด๊ฐ์?
์ด ๊ฒฝ์ฐ, `EXIST` ์ ๊ฑธ๋ฉด ์ข์ต๋๋ค.
ํ ๊ฐ ๊ฒ์์ด ๋๋ ์๊ฐ ์ฟผ๋ฆฌ๋ฅผ ์ข
๋ฃ์์ผ ๋ฒ๋ฆฌ๊ฑฐ๋ ์.
```java
@Query("""
SELECT CASE WHEN EXISTS (
SELECT 1
FROM Business b
WHERE b.businessId = :senderId AND b.businessName = :senderName
) THEN TRUE ELSE FALSE END
""")
boolean existsByIdAndBusinessName(Long senderId, String senderName);
``` |
@@ -1,15 +1,40 @@
package roomit.main.domain.business.repository;
+import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import roomit.main.domain.business.entity.Business;
-import java.util.Optional;
-
public interface BusinessRepository extends JpaRepository<Business, Long> {
- @Query(value = "SELECT b FROM Business b WHERE b.businessEmail.value=:email")
- Optional<Business> findByBusinessEmail(String email);
-
+ @Query(value = "SELECT b FROM Business b WHERE b.businessEmail.value=:businessEmail")
+ Optional<Business> findByBusinessEmail(String businessEmail);
+
+ @Query("""
+ SELECT CASE WHEN EXISTS (
+ SELECT 1
+ FROM Business b
+ WHERE b.businessName.value = :businessName
+ ) THEN TRUE ELSE FALSE END
+ """)
+ Boolean existsByBusinessName(String businessName);
+
+ @Query("""
+ SELECT CASE WHEN EXISTS (
+ SELECT 1
+ FROM Business b
+ WHERE b.businessEmail.value = :businessEmail
+ ) THEN TRUE ELSE FALSE END
+ """)
+ Boolean existsByBusinessEmail(String businessEmail);
+
+ @Query("""
+ SELECT CASE WHEN EXISTS (
+ SELECT 1
+ FROM Business b
+ WHERE b.businessNum.value = :businessNum
+ ) THEN TRUE ELSE FALSE END
+ """)
+ Boolean existsByBusinessNum(String businessNum);
}
| Java | ์ด๊ฒ๋ง primitive ๋ค์. |
@@ -0,0 +1,23 @@
+package roomit.main.domain.chat.chatmessage.service;
+
+import lombok.RequiredArgsConstructor;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+import roomit.main.domain.chat.chatroom.repository.ChatRoomRepository;
+
+import java.util.List;
+
+@Component
+@RequiredArgsConstructor
+public class ChatMessageBatchProcessor {
+ private final ChatService chatService;
+ private final ChatRoomRepository chatRoomRepository;
+
+ @Scheduled(fixedRate = 30000) // 1๋ถ๋ง๋ค ์คํ
+ public void flushMessages() {
+ List<Long> roomIds = chatRoomRepository.findAllRoomIds(); // Room ID ๋์ ์กฐํ
+ for (Long roomId : roomIds) {
+ chatService.flushMessagesToDatabase(roomId);
+ }
+ }
+} | Java | roomId ์ ์๊ฐ ๋๋ ์์ด ๋ง์ ์ ์์ง ์์๊น์? |
@@ -0,0 +1,56 @@
+package store.config;
+
+import java.util.Map;
+import store.controller.ConvenienceController;
+import store.convenience.Convenience;
+import store.domain.Product;
+import store.domain.Promotion;
+import store.reader.StoreFileReader;
+import store.repository.ProductRepository;
+import store.repository.PromotionRepository;
+import store.service.ConvenienceService;
+import store.service.ProductService;
+import store.service.PromotionService;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class ConvenienceFactory {
+
+ public static Convenience createConvenience() {
+ return new Convenience(convenienceController(), outputView(), inputView());
+ }
+
+ public static ConvenienceController convenienceController() {
+ return new ConvenienceController(convenienceService());
+ }
+
+ public static ConvenienceService convenienceService() {
+ return new ConvenienceService(productService(), promotionService());
+ }
+
+ public static OutputView outputView() {
+ return new OutputView();
+ }
+
+ public static InputView inputView() {
+ return new InputView();
+ }
+
+ public static ProductRepository productRepository() {
+ Map<String, Promotion> promotions = StoreFileReader.promotions();
+ Map<String, Product> products = StoreFileReader.product(promotions);
+ return new ProductRepository(products);
+ }
+
+ public static ProductService productService() {
+ return new ProductService(productRepository());
+ }
+
+ public static PromotionService promotionService() {
+ return new PromotionService(promotionRepository());
+ }
+
+ public static PromotionRepository promotionRepository() {
+ return new PromotionRepository(StoreFileReader.promotions());
+ }
+} | Java | ์ ๋ 2์ฃผ์ฐจ์ Factory๋ฅผ ์ฌ์ฉํ์๋๋ฐ ํ์คํ ์์กด์ฑ ์ฃผ์
ํ๊ธฐ์๋ ์ด๊ฒ๋งํผ ์ข์๊ฒ ์๋ ๊ฒ ๊ฐ์์ |
@@ -0,0 +1,56 @@
+package store.config;
+
+import java.util.Map;
+import store.controller.ConvenienceController;
+import store.convenience.Convenience;
+import store.domain.Product;
+import store.domain.Promotion;
+import store.reader.StoreFileReader;
+import store.repository.ProductRepository;
+import store.repository.PromotionRepository;
+import store.service.ConvenienceService;
+import store.service.ProductService;
+import store.service.PromotionService;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class ConvenienceFactory {
+
+ public static Convenience createConvenience() {
+ return new Convenience(convenienceController(), outputView(), inputView());
+ }
+
+ public static ConvenienceController convenienceController() {
+ return new ConvenienceController(convenienceService());
+ }
+
+ public static ConvenienceService convenienceService() {
+ return new ConvenienceService(productService(), promotionService());
+ }
+
+ public static OutputView outputView() {
+ return new OutputView();
+ }
+
+ public static InputView inputView() {
+ return new InputView();
+ }
+
+ public static ProductRepository productRepository() {
+ Map<String, Promotion> promotions = StoreFileReader.promotions();
+ Map<String, Product> products = StoreFileReader.product(promotions);
+ return new ProductRepository(products);
+ }
+
+ public static ProductService productService() {
+ return new ProductService(productRepository());
+ }
+
+ public static PromotionService promotionService() {
+ return new PromotionService(promotionRepository());
+ }
+
+ public static PromotionRepository promotionRepository() {
+ return new PromotionRepository(StoreFileReader.promotions());
+ }
+} | Java | IO์์
์ ๊ฒฝ์ฐ ์ฌ๋ฌ ๊ฐ์ ์ธ์คํด์ค๊ฐ ํ๋ฒ์ ์ ๊ทผํ๋ค๋ฉด ๋ฌธ์ ๊ฐ ์๊ธธ์ ์๋ค๊ณ ์๊ฐํฉ๋๋ค. getInstance๋ฉ์๋๋ฅผ ํตํด ์ฑ๊ธํค ์ ์งํด๋ณด๋๊ฒ์ ์ด๋จ๊น์? |
@@ -0,0 +1,56 @@
+package store.config;
+
+import java.util.Map;
+import store.controller.ConvenienceController;
+import store.convenience.Convenience;
+import store.domain.Product;
+import store.domain.Promotion;
+import store.reader.StoreFileReader;
+import store.repository.ProductRepository;
+import store.repository.PromotionRepository;
+import store.service.ConvenienceService;
+import store.service.ProductService;
+import store.service.PromotionService;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class ConvenienceFactory {
+
+ public static Convenience createConvenience() {
+ return new Convenience(convenienceController(), outputView(), inputView());
+ }
+
+ public static ConvenienceController convenienceController() {
+ return new ConvenienceController(convenienceService());
+ }
+
+ public static ConvenienceService convenienceService() {
+ return new ConvenienceService(productService(), promotionService());
+ }
+
+ public static OutputView outputView() {
+ return new OutputView();
+ }
+
+ public static InputView inputView() {
+ return new InputView();
+ }
+
+ public static ProductRepository productRepository() {
+ Map<String, Promotion> promotions = StoreFileReader.promotions();
+ Map<String, Product> products = StoreFileReader.product(promotions);
+ return new ProductRepository(products);
+ }
+
+ public static ProductService productService() {
+ return new ProductService(productRepository());
+ }
+
+ public static PromotionService promotionService() {
+ return new PromotionService(promotionRepository());
+ }
+
+ public static PromotionRepository promotionRepository() {
+ return new PromotionRepository(StoreFileReader.promotions());
+ }
+} | Java | Factory์ ์ฅ์ ์ ์์กด์ฑ ์ฃผ์
์ด๋ผ๊ณ ์๊ฐํฉ๋๋ค. ์ธํฐํ์ด์ค๋ฅผ ํตํด ํด๋์ค๊ฐ ๊ฒฐํฉ๋๋ฅผ ์ค์ฌ๋ณด๋ ๊ฒ์ ์ด๋จ๊น์? |
@@ -0,0 +1,56 @@
+package store.config;
+
+import java.util.Map;
+import store.controller.ConvenienceController;
+import store.convenience.Convenience;
+import store.domain.Product;
+import store.domain.Promotion;
+import store.reader.StoreFileReader;
+import store.repository.ProductRepository;
+import store.repository.PromotionRepository;
+import store.service.ConvenienceService;
+import store.service.ProductService;
+import store.service.PromotionService;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class ConvenienceFactory {
+
+ public static Convenience createConvenience() {
+ return new Convenience(convenienceController(), outputView(), inputView());
+ }
+
+ public static ConvenienceController convenienceController() {
+ return new ConvenienceController(convenienceService());
+ }
+
+ public static ConvenienceService convenienceService() {
+ return new ConvenienceService(productService(), promotionService());
+ }
+
+ public static OutputView outputView() {
+ return new OutputView();
+ }
+
+ public static InputView inputView() {
+ return new InputView();
+ }
+
+ public static ProductRepository productRepository() {
+ Map<String, Promotion> promotions = StoreFileReader.promotions();
+ Map<String, Product> products = StoreFileReader.product(promotions);
+ return new ProductRepository(products);
+ }
+
+ public static ProductService productService() {
+ return new ProductService(productRepository());
+ }
+
+ public static PromotionService promotionService() {
+ return new PromotionService(promotionRepository());
+ }
+
+ public static PromotionRepository promotionRepository() {
+ return new PromotionRepository(StoreFileReader.promotions());
+ }
+} | Java | staitc ๋ฉ์๋๋ฅผ ํตํด ์ธ์คํด์ค๋ฅผ ์์ฑํ์ง ์๋ ํํ๋ก ๋ง๋์
จ๋๋ฐ private์์ฑ์๋ฅผ ํตํด ๊ธฐ๋ณธ ์์ฑ์๋ฅผ ์์ฑํ๋ ๊ฒ์ ๋ง๋๋ค๋ฉด ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,19 @@
+package store.config;
+
+public enum ErrorMessage {
+
+ PRODUCT_NOT_EXIST("์กด์ฌํ์ง ์๋ ์ํ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
+ PRODUCT_QUANTITY_NOT_ENOUGH("์ฌ๊ณ ์๋์ ์ด๊ณผํ์ฌ ๊ตฌ๋งคํ ์ ์์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
+ PRODUCT_WRONG_INPUT("์ฌ๋ฐ๋ฅด์ง ์์ ํ์์ผ๋ก ์
๋ ฅํ์ต๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์."),
+ WRONG_INPUT("์๋ชป๋ ์
๋ ฅ์
๋๋ค. ๋ค์ ์
๋ ฅํด ์ฃผ์ธ์.");
+
+ private final String message;
+
+ ErrorMessage(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return "[ERROR] " + message;
+ }
+} | Java | "[ERROR] "๋ผ๋ ๊ฒ์ ํ๋์ ๋ฃ์ด ์์๋ก ๋ง๋ ๋ค๋ฉด ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค.
```
private static final String ERROR_PREFIX = "[ERROR] ";
``` |
@@ -0,0 +1,35 @@
+package store.controller;
+
+import java.util.List;
+import java.util.Map;
+import store.domain.Product;
+import store.domain.Promotion;
+import store.domain.Receipt;
+import store.domain.ShortageQuantity;
+import store.domain.request.PurchaseRequest;
+import store.service.ConvenienceService;
+
+public class ConvenienceController {
+
+ private final ConvenienceService convenienceService;
+
+ public ConvenienceController(ConvenienceService convenienceService) {
+ this.convenienceService = convenienceService;
+ }
+
+ public Receipt sell(List<PurchaseRequest> purchaseRequests, String membership) {
+ return convenienceService.sell(purchaseRequests, membership);
+ }
+
+ public void setPromotion(Map<String, Promotion> promotions) {
+ convenienceService.setPromotion(promotions);
+ }
+
+ public Map<String, Product> getProducts() {
+ return convenienceService.getProducts();
+ }
+
+ public List<ShortageQuantity> getShortageQuantityForPromotion(List<PurchaseRequest> purchases) {
+ return convenienceService.getShortageQuantityForPromotion(purchases);
+ }
+} | Java | ์คํ๋ง์์ ์ฌ์ฉํ๋ Controller, Service, Repository๋ฅผ ์ฌ์ฉํ๋ฉด์ ๊ฐ๊ฐ์ ์
๋ ฅ์ด ๋ฐ๋ก ๋ค์ด์ค๋ ๊ฒ์ฒ๋ผ ์์ฑํ์ ๊ฒ ๋๊ฒ ์ ์ ํ๊ฒ ๋๊ปด์ง๋ค์ ํ์ง๋ง ์ปจํธ๋กค๋ฌ๋ ์
๋ ฅ์ ๋ฐ์ ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ํ๋ ์ญํ ๋ ์๋๋ฐ ๊ทธ ์ญํ ์ด Convenience๋ก ๋์ด๊ฐ๊ฒ ์์ฌ์์ด ์์ต๋๋ค.
Supplier๋ฅผ ํ์ฉํ์ฌ ์ ํจ์ฑ ๊ฒ์ฌ ์คํจ์ ์ฌ์
๋ ฅ์ ๋ฐ๋๋ก ์ ๋ํ๋ ๊ฒ์ ์ด๋จ๊น์? |
@@ -0,0 +1,35 @@
+package store.controller;
+
+import java.util.List;
+import java.util.Map;
+import store.domain.Product;
+import store.domain.Promotion;
+import store.domain.Receipt;
+import store.domain.ShortageQuantity;
+import store.domain.request.PurchaseRequest;
+import store.service.ConvenienceService;
+
+public class ConvenienceController {
+
+ private final ConvenienceService convenienceService;
+
+ public ConvenienceController(ConvenienceService convenienceService) {
+ this.convenienceService = convenienceService;
+ }
+
+ public Receipt sell(List<PurchaseRequest> purchaseRequests, String membership) {
+ return convenienceService.sell(purchaseRequests, membership);
+ }
+
+ public void setPromotion(Map<String, Promotion> promotions) {
+ convenienceService.setPromotion(promotions);
+ }
+
+ public Map<String, Product> getProducts() {
+ return convenienceService.getProducts();
+ }
+
+ public List<ShortageQuantity> getShortageQuantityForPromotion(List<PurchaseRequest> purchases) {
+ return convenienceService.getShortageQuantityForPromotion(purchases);
+ }
+} | Java | ์ปจํธ๋กค๋ฌ์ ์ญํ ์ด ๋๋ฌด ์์ด์ ์์ฌ์์ ๋จ๊ฒจ๋ด์. ์ปจํธ๋กค๋ฌ์์ ์ด๋ค ์ฒ๋ฆฌ๋ ํ์ง ์์์ฑ ์๋น์ค์ ๋ฉ์๋๋ฅผ ํธ์ถํด์ ๊ทธ๋ ์ต๋๋ค. |
@@ -0,0 +1,72 @@
+package store.convenience;
+
+import static store.domain.Agree.YES;
+
+import java.util.List;
+import java.util.Map;
+import java.util.function.Supplier;
+import store.controller.ConvenienceController;
+import store.domain.Product;
+import store.domain.Receipt;
+import store.domain.ShortageQuantity;
+import store.domain.request.PurchaseRequest;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class Convenience {
+ private final ConvenienceController convenienceController;
+ private final OutputView outputView;
+ private final InputView inputView;
+
+ public Convenience(ConvenienceController convenienceController, OutputView outputView, InputView inputView) {
+ this.convenienceController = convenienceController;
+ this.outputView = outputView;
+ this.inputView = inputView;
+ }
+
+ public void operating() {
+ repurchase(this::operate);
+ }
+
+ public void repurchase(Supplier<String> supplier) {
+ while (supplier.get().equals(YES.getValue())) {}
+ }
+
+ private String operate() {
+ Map<String, Product> products = convenienceController.getProducts();
+ outputView.printProducts(products);
+
+ List<PurchaseRequest> purchases = inputView.inputProductAndQuantity(products);
+
+ List<ShortageQuantity> shortageQuantityForPromotion = convenienceController.getShortageQuantityForPromotion(
+ purchases);
+
+ for (ShortageQuantity shortageQuantity : shortageQuantityForPromotion) {
+ addShortageQuantity(shortageQuantity);
+
+ if (!shortageQuantity.isPromotion()) {
+ String notPromotion = inputView.getNotPromotion(shortageQuantity);
+ if (notPromotion.equals("N")) {
+ return "Y";
+ }
+ }
+ }
+
+ String membership = inputView.inputMembership();
+ Receipt receipt = convenienceController.sell(purchases, membership);
+
+ outputView.printReceipt(receipt);
+ return inputView.inputRePurchase();
+ }
+
+ private void addShortageQuantity(ShortageQuantity shortageQuantity) {
+ if (shortageQuantity.isPromotion()) {
+ String promotion = inputView.getPromotion(shortageQuantity);
+ if (promotion.equals("Y")) {
+ shortageQuantity.getPurchaseRequest().add(shortageQuantity.getQuantity());
+ }
+ }
+ }
+
+
+} | Java | ์ค์ ์๋ฒ์์ ์ด์๋๋ฏ์ด Controller, Service, Repository๋ฅผ ์์ฑํ๊ณ ์ค์ง์ ์ธ ํ๋ฆ์ Convenience๋ก ๊ด๋ฆฌํ๋ ๊ฒ์ด ์ด์ฉ๋ฉด ์ด ๋ถ๋ถ์ด ํ๋ก ํธ๊ณ ๋๋จธ์ง๊ฐ ๋ฐฑ์๋๊ฐ์ ๊ต์ฅํ ํฅ๋ฏธ๋ก์ ์ต๋๋ค. |
@@ -0,0 +1,72 @@
+package store.convenience;
+
+import static store.domain.Agree.YES;
+
+import java.util.List;
+import java.util.Map;
+import java.util.function.Supplier;
+import store.controller.ConvenienceController;
+import store.domain.Product;
+import store.domain.Receipt;
+import store.domain.ShortageQuantity;
+import store.domain.request.PurchaseRequest;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class Convenience {
+ private final ConvenienceController convenienceController;
+ private final OutputView outputView;
+ private final InputView inputView;
+
+ public Convenience(ConvenienceController convenienceController, OutputView outputView, InputView inputView) {
+ this.convenienceController = convenienceController;
+ this.outputView = outputView;
+ this.inputView = inputView;
+ }
+
+ public void operating() {
+ repurchase(this::operate);
+ }
+
+ public void repurchase(Supplier<String> supplier) {
+ while (supplier.get().equals(YES.getValue())) {}
+ }
+
+ private String operate() {
+ Map<String, Product> products = convenienceController.getProducts();
+ outputView.printProducts(products);
+
+ List<PurchaseRequest> purchases = inputView.inputProductAndQuantity(products);
+
+ List<ShortageQuantity> shortageQuantityForPromotion = convenienceController.getShortageQuantityForPromotion(
+ purchases);
+
+ for (ShortageQuantity shortageQuantity : shortageQuantityForPromotion) {
+ addShortageQuantity(shortageQuantity);
+
+ if (!shortageQuantity.isPromotion()) {
+ String notPromotion = inputView.getNotPromotion(shortageQuantity);
+ if (notPromotion.equals("N")) {
+ return "Y";
+ }
+ }
+ }
+
+ String membership = inputView.inputMembership();
+ Receipt receipt = convenienceController.sell(purchases, membership);
+
+ outputView.printReceipt(receipt);
+ return inputView.inputRePurchase();
+ }
+
+ private void addShortageQuantity(ShortageQuantity shortageQuantity) {
+ if (shortageQuantity.isPromotion()) {
+ String promotion = inputView.getPromotion(shortageQuantity);
+ if (promotion.equals("Y")) {
+ shortageQuantity.getPurchaseRequest().add(shortageQuantity.getQuantity());
+ }
+ }
+ }
+
+
+} | Java | Supplier๋ฅผ ์์ฑํ์ ๋ถ๋ค์ค์ ๊ฐ์ฅ ์์ฐ์ค๋ฝ๊ฒ ์ฌ์ฉํ์ ์์์ธ๊ฒ ๊ฐ์ต๋๋ค. ๊ต์ฅํ ์ฌ๋ฏธ์๋ค์ |
@@ -0,0 +1,72 @@
+package store.convenience;
+
+import static store.domain.Agree.YES;
+
+import java.util.List;
+import java.util.Map;
+import java.util.function.Supplier;
+import store.controller.ConvenienceController;
+import store.domain.Product;
+import store.domain.Receipt;
+import store.domain.ShortageQuantity;
+import store.domain.request.PurchaseRequest;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class Convenience {
+ private final ConvenienceController convenienceController;
+ private final OutputView outputView;
+ private final InputView inputView;
+
+ public Convenience(ConvenienceController convenienceController, OutputView outputView, InputView inputView) {
+ this.convenienceController = convenienceController;
+ this.outputView = outputView;
+ this.inputView = inputView;
+ }
+
+ public void operating() {
+ repurchase(this::operate);
+ }
+
+ public void repurchase(Supplier<String> supplier) {
+ while (supplier.get().equals(YES.getValue())) {}
+ }
+
+ private String operate() {
+ Map<String, Product> products = convenienceController.getProducts();
+ outputView.printProducts(products);
+
+ List<PurchaseRequest> purchases = inputView.inputProductAndQuantity(products);
+
+ List<ShortageQuantity> shortageQuantityForPromotion = convenienceController.getShortageQuantityForPromotion(
+ purchases);
+
+ for (ShortageQuantity shortageQuantity : shortageQuantityForPromotion) {
+ addShortageQuantity(shortageQuantity);
+
+ if (!shortageQuantity.isPromotion()) {
+ String notPromotion = inputView.getNotPromotion(shortageQuantity);
+ if (notPromotion.equals("N")) {
+ return "Y";
+ }
+ }
+ }
+
+ String membership = inputView.inputMembership();
+ Receipt receipt = convenienceController.sell(purchases, membership);
+
+ outputView.printReceipt(receipt);
+ return inputView.inputRePurchase();
+ }
+
+ private void addShortageQuantity(ShortageQuantity shortageQuantity) {
+ if (shortageQuantity.isPromotion()) {
+ String promotion = inputView.getPromotion(shortageQuantity);
+ if (promotion.equals("Y")) {
+ shortageQuantity.getPurchaseRequest().add(shortageQuantity.getQuantity());
+ }
+ }
+ }
+
+
+} | Java | N์ด๋ Y์ธ ๋ฌธ์์ด๋ณด๋ค boolean์ ์ฌ์ฉํ์ผ๋ฉด ์ด๋จ๊น๋ผ๋ ์๊ฐ์ด ๋ค์ด์ |
@@ -0,0 +1,72 @@
+package store.convenience;
+
+import static store.domain.Agree.YES;
+
+import java.util.List;
+import java.util.Map;
+import java.util.function.Supplier;
+import store.controller.ConvenienceController;
+import store.domain.Product;
+import store.domain.Receipt;
+import store.domain.ShortageQuantity;
+import store.domain.request.PurchaseRequest;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class Convenience {
+ private final ConvenienceController convenienceController;
+ private final OutputView outputView;
+ private final InputView inputView;
+
+ public Convenience(ConvenienceController convenienceController, OutputView outputView, InputView inputView) {
+ this.convenienceController = convenienceController;
+ this.outputView = outputView;
+ this.inputView = inputView;
+ }
+
+ public void operating() {
+ repurchase(this::operate);
+ }
+
+ public void repurchase(Supplier<String> supplier) {
+ while (supplier.get().equals(YES.getValue())) {}
+ }
+
+ private String operate() {
+ Map<String, Product> products = convenienceController.getProducts();
+ outputView.printProducts(products);
+
+ List<PurchaseRequest> purchases = inputView.inputProductAndQuantity(products);
+
+ List<ShortageQuantity> shortageQuantityForPromotion = convenienceController.getShortageQuantityForPromotion(
+ purchases);
+
+ for (ShortageQuantity shortageQuantity : shortageQuantityForPromotion) {
+ addShortageQuantity(shortageQuantity);
+
+ if (!shortageQuantity.isPromotion()) {
+ String notPromotion = inputView.getNotPromotion(shortageQuantity);
+ if (notPromotion.equals("N")) {
+ return "Y";
+ }
+ }
+ }
+
+ String membership = inputView.inputMembership();
+ Receipt receipt = convenienceController.sell(purchases, membership);
+
+ outputView.printReceipt(receipt);
+ return inputView.inputRePurchase();
+ }
+
+ private void addShortageQuantity(ShortageQuantity shortageQuantity) {
+ if (shortageQuantity.isPromotion()) {
+ String promotion = inputView.getPromotion(shortageQuantity);
+ if (promotion.equals("Y")) {
+ shortageQuantity.getPurchaseRequest().add(shortageQuantity.getQuantity());
+ }
+ }
+ }
+
+
+} | Java | enum์ผ๋ก Agree๋ฅผ ๋ง๋์
จ๋๋ฐ ํด๋น ํด๋์ค๋ฅผ ํตํด ๊ตฌ๋ณํ๊ฑฐ๋ "Y"๊ฐ์ ๊ฐ์ enum์์ ๊ฐ์ ธ์ ์์์ฒ๋ผ ์ฒ๋ฆฌํ๋ ๊ฒ์ ์ด๋จ๊น์?
Agree์์ ๋ฐ๋ก ๋ฉ์๋๋ฅผ ๋ง๋๋ ๊ฒ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,74 @@
+package store.domain;
+
+public class Product {
+ private final String name;
+ private final int price;
+ private int quantity;
+ private int promotionQuantity;
+ private Promotion promotion;
+
+ public Product(String name, int price, int promotionQuantity, Promotion promotion) {
+ this.name = name;
+ this.price = price;
+ this.promotionQuantity = promotionQuantity;
+ this.promotion = promotion;
+ }
+
+ public Product(String name, int price, int quantity) {
+ this.name = name;
+ this.price = price;
+ this.quantity = quantity;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ public int getPromotionQuantity() {
+ return promotionQuantity;
+ }
+
+ public Promotion getPromotion() {
+ return promotion;
+ }
+
+ public boolean existsPromotion() {
+ return promotion != null;
+ }
+
+ @Override
+ public String toString() {
+ return "Product{" +
+ "name='" + name + '\'' +
+ ", price=" + price +
+ ", quantity=" + quantity +
+ ", promotionQuantity=" + promotionQuantity +
+ ", promotion=" + promotion +
+ '}';
+ }
+
+ public void add(int quantity) {
+ this.quantity += quantity;
+ }
+
+
+ public int getShortageQuantityForPromotion(int purchaseQuantity) {
+ if (promotionQuantity < purchaseQuantity) {
+ return promotionQuantity % (promotion.getBuy() + promotion.getGet());
+ }
+
+ int shortage = purchaseQuantity % (promotion.getBuy() + promotion.getGet());
+ if (shortage == 0) {
+ return 0;
+ }
+ return (promotion.getBuy() + promotion.getGet()) - shortage;
+ }
+} | Java | ์ ์ ๊ฐ์ฅ ๋น์ทํ๊ฒ Product์ ํ๋๊ฐ ๊ตฌ์ฑ๋ ์ฌ๋์ ๋ด์ ์ ๊ธฐํ๋ค์. name๊ณผ price๋ ๋ณ๊ฒฝ๋์ง ์์ final๋ก ์ ์ผ์ ๊ฒ ๊ผผ๊ผผํจ์ด ๋ณด์
๋๋ค. |
@@ -0,0 +1,46 @@
+package store.domain;
+
+import java.time.LocalDate;
+
+public class Promotion {
+ private final String name;
+ private final int buy;
+ private final int get;
+ private final LocalDate startDate;
+ private final LocalDate endDate;
+
+ public Promotion(String name, int buy, int get, LocalDate startDate, LocalDate endDate) {
+ this.name = name;
+ this.buy = buy;
+ this.get = get;
+ this.startDate = startDate;
+ this.endDate = endDate;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getBuy() {
+ return buy;
+ }
+
+ public int getGet() {
+ return get;
+ }
+
+ @Override
+ public String toString() {
+ return "Promotion{" +
+ "name='" + name + '\'' +
+ ", buy=" + buy +
+ ", get=" + get +
+ ", startDate=" + startDate +
+ ", endDate=" + endDate +
+ '}';
+ }
+
+ public boolean isRangePromotion(LocalDate now) {
+ return now.isAfter(startDate) && now.isBefore(endDate);
+ }
+} | Java | ์ด๊ฑด ๋๋ฒ๊น
์ ์ํด ๋ฃ์ ๊ฒ์ผ๊น์? |
@@ -0,0 +1,46 @@
+package store.domain;
+
+import java.time.LocalDate;
+
+public class Promotion {
+ private final String name;
+ private final int buy;
+ private final int get;
+ private final LocalDate startDate;
+ private final LocalDate endDate;
+
+ public Promotion(String name, int buy, int get, LocalDate startDate, LocalDate endDate) {
+ this.name = name;
+ this.buy = buy;
+ this.get = get;
+ this.startDate = startDate;
+ this.endDate = endDate;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getBuy() {
+ return buy;
+ }
+
+ public int getGet() {
+ return get;
+ }
+
+ @Override
+ public String toString() {
+ return "Promotion{" +
+ "name='" + name + '\'' +
+ ", buy=" + buy +
+ ", get=" + get +
+ ", startDate=" + startDate +
+ ", endDate=" + endDate +
+ '}';
+ }
+
+ public boolean isRangePromotion(LocalDate now) {
+ return now.isAfter(startDate) && now.isBefore(endDate);
+ }
+} | Java | ์ ๋ Buy์ Get์ ๋ฐ๋ก ๋ง๋ค์์์ง๋ง ์๊ตฌ์ฌํญ์ N+1์ด๋ผ๋ ๊ธ์ ๋ด์ get์ ํญ์ 1์ด๊ฒ ๊ตฌ๋ ์๊ฐํ๊ณ ๋์ค์ ์ฐ์ฐ์ ํฐ ๋์์ด ๋์ง์์๋๊ฒ ๊ฐ์ต๋๋ค |
@@ -0,0 +1,46 @@
+package store.domain;
+
+import java.time.LocalDate;
+
+public class Promotion {
+ private final String name;
+ private final int buy;
+ private final int get;
+ private final LocalDate startDate;
+ private final LocalDate endDate;
+
+ public Promotion(String name, int buy, int get, LocalDate startDate, LocalDate endDate) {
+ this.name = name;
+ this.buy = buy;
+ this.get = get;
+ this.startDate = startDate;
+ this.endDate = endDate;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getBuy() {
+ return buy;
+ }
+
+ public int getGet() {
+ return get;
+ }
+
+ @Override
+ public String toString() {
+ return "Promotion{" +
+ "name='" + name + '\'' +
+ ", buy=" + buy +
+ ", get=" + get +
+ ", startDate=" + startDate +
+ ", endDate=" + endDate +
+ '}';
+ }
+
+ public boolean isRangePromotion(LocalDate now) {
+ return now.isAfter(startDate) && now.isBefore(endDate);
+ }
+} | Java | ์์๋ ์ง ์ด์ ๋๋ ๋ ์ง์ดํ ์ฆ ์์๊ณผ ๋์ ํฌํจํ๋ ๊ฒ์ผ๋ก ์๊ตฌ์ฌํญ์ ์๊ณ ์๋๋ฐ isAfter๊ณผ isBefore์ ๋์ผํ ๋ ์ง๋ฅผ ๋ง๋๋ฉด false๋ก ๋์จ๋ค๊ณ ์๊ณ ์์ต๋๋ค. |
@@ -0,0 +1,32 @@
+package store.domain.request;
+
+public class PurchaseRequest {
+ private final String name;
+ private int quantity;
+
+
+ public PurchaseRequest(String name, int quantity) {
+ this.name = name;
+ this.quantity = quantity;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getQuantity() {
+ return quantity;
+ }
+
+ @Override
+ public String toString() {
+ return "Purchase{" +
+ "name='" + name + '\'' +
+ ", quantity=" + quantity +
+ '}';
+ }
+
+ public void add(int quantity) {
+ this.quantity += quantity;
+ }
+} | Java | request์ ๊ฒฝ์ฐ view์ ํจํค์ง์์ ์กด์ฌํด์ผํ๋ค๊ณ ์๊ฐํฉ๋๋ค. Domain์ ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ๋ ์ ์ฅ์์ธ๋ฐ domain๊ณผ dto์ค์ dto์ ๋ ๊ฐ๊น์ด ํด๋์ค์ธ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -15,29 +15,35 @@ public class StoreFileReader {
public static final String PRODUCTS_DATA = "src/main/resources/products.md";
public static final String PROMOTIONS_DATA = "src/main/resources/promotions.md";
- public Map<String, Product> product(Map<String, Promotion> promotions) {
- Map<String, Product> products = new LinkedHashMap<>();
- try (BufferedReader br = new BufferedReader(
- new InputStreamReader(new FileInputStream(PRODUCTS_DATA)))) {
- String line = br.readLine();
- while ((line = br.readLine()) != null) {
- String[] product = line.split(",");
- String productName = product[0];
- if (products.containsKey(productName)) { // ๋๋ฒ์งธ๋ก ๋ค์ด์ค๋ ๊ฑด ๋ฌด์กฐ๊ฑด ์ผ๋ฐ ์ฌ๊ณ
- Product p = products.get(productName);
- int quantity = Integer.parseInt(product[2]);
- p.add(quantity);
- }
- products.computeIfAbsent(productName, (k) -> convertProduct(product, promotions));
-
- }
+ public static Map<String, Product> product(Map<String, Promotion> promotions) {
+ try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(PRODUCTS_DATA)))) {
+ return getProductMap(promotions, br);
} catch (IOException e) {
throw new RuntimeException("Failed to read the file.", e);
}
+ }
+
+ private static Map<String, Product> getProductMap(Map<String, Promotion> promotions, BufferedReader br)
+ throws IOException {
+ Map<String, Product> products = new LinkedHashMap<>();
+ String line = br.readLine();
+ while ((line = br.readLine()) != null) {
+ String[] product = line.split(",");
+ String productName = product[0];
+ addProduct(products, productName, product);
+ products.computeIfAbsent(productName, (k) -> convertProduct(product, promotions));
+ }
return products;
}
- private Product convertProduct(String[] product, Map<String, Promotion> promotions) {
+ private static void addProduct(Map<String, Product> products, String productName, String[] product) {
+ if (products.containsKey(productName)) {
+ Product p = products.get(productName);
+ p.add(Integer.parseInt(product[2]));
+ }
+ }
+
+ private static Product convertProduct(String[] product, Map<String, Promotion> promotions) {
String name = product[0];
int price = Integer.parseInt(product[1]);
int quantity = Integer.parseInt(product[2]);
@@ -52,23 +58,28 @@ private static boolean isPromotion(String[] product) {
return !product[3].equals("null");
}
- public Map<String, Promotion> promotions() {
- Map<String, Promotion> promotions = new LinkedHashMap<>();
+ public static Map<String, Promotion> promotions() {
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(PROMOTIONS_DATA)))) {
- String line = br.readLine();
- while ((line = br.readLine()) != null) {
- String[] promotion = line.split(",");
- String promotionName = promotion[0];
- promotions.put(promotionName, convertPromotion(promotion));
- }
+ return getPromotionMap(br);
} catch (IOException e) {
throw new RuntimeException("Failed to read the file.", e);
}
+
+ }
+
+ private static Map<String, Promotion> getPromotionMap(BufferedReader br) throws IOException {
+ Map<String, Promotion> promotions = new LinkedHashMap<>();
+ String line = br.readLine();
+ while ((line = br.readLine()) != null) {
+ String[] promotion = line.split(",");
+ String promotionName = promotion[0];
+ promotions.put(promotionName, convertPromotion(promotion));
+ }
return promotions;
}
- private Promotion convertPromotion(String[] promotion) {
+ private static Promotion convertPromotion(String[] promotion) {
return new Promotion(promotion[0], Integer.parseInt(promotion[1]), Integer.parseInt(promotion[2]),
LocalDate.parse(promotion[3]), LocalDate.parse(promotion[4]));
} | Java | ์๋ฌ ๋ฉ์ธ์ง๋ฅผ ์์ํ ์ํค๋ ๊ฒ์ ์ด๋จ๊น์? ์๋๋ฉด ์ปค์คํ
์์ธ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -15,29 +15,35 @@ public class StoreFileReader {
public static final String PRODUCTS_DATA = "src/main/resources/products.md";
public static final String PROMOTIONS_DATA = "src/main/resources/promotions.md";
- public Map<String, Product> product(Map<String, Promotion> promotions) {
- Map<String, Product> products = new LinkedHashMap<>();
- try (BufferedReader br = new BufferedReader(
- new InputStreamReader(new FileInputStream(PRODUCTS_DATA)))) {
- String line = br.readLine();
- while ((line = br.readLine()) != null) {
- String[] product = line.split(",");
- String productName = product[0];
- if (products.containsKey(productName)) { // ๋๋ฒ์งธ๋ก ๋ค์ด์ค๋ ๊ฑด ๋ฌด์กฐ๊ฑด ์ผ๋ฐ ์ฌ๊ณ
- Product p = products.get(productName);
- int quantity = Integer.parseInt(product[2]);
- p.add(quantity);
- }
- products.computeIfAbsent(productName, (k) -> convertProduct(product, promotions));
-
- }
+ public static Map<String, Product> product(Map<String, Promotion> promotions) {
+ try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(PRODUCTS_DATA)))) {
+ return getProductMap(promotions, br);
} catch (IOException e) {
throw new RuntimeException("Failed to read the file.", e);
}
+ }
+
+ private static Map<String, Product> getProductMap(Map<String, Promotion> promotions, BufferedReader br)
+ throws IOException {
+ Map<String, Product> products = new LinkedHashMap<>();
+ String line = br.readLine();
+ while ((line = br.readLine()) != null) {
+ String[] product = line.split(",");
+ String productName = product[0];
+ addProduct(products, productName, product);
+ products.computeIfAbsent(productName, (k) -> convertProduct(product, promotions));
+ }
return products;
}
- private Product convertProduct(String[] product, Map<String, Promotion> promotions) {
+ private static void addProduct(Map<String, Product> products, String productName, String[] product) {
+ if (products.containsKey(productName)) {
+ Product p = products.get(productName);
+ p.add(Integer.parseInt(product[2]));
+ }
+ }
+
+ private static Product convertProduct(String[] product, Map<String, Promotion> promotions) {
String name = product[0];
int price = Integer.parseInt(product[1]);
int quantity = Integer.parseInt(product[2]);
@@ -52,23 +58,28 @@ private static boolean isPromotion(String[] product) {
return !product[3].equals("null");
}
- public Map<String, Promotion> promotions() {
- Map<String, Promotion> promotions = new LinkedHashMap<>();
+ public static Map<String, Promotion> promotions() {
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(PROMOTIONS_DATA)))) {
- String line = br.readLine();
- while ((line = br.readLine()) != null) {
- String[] promotion = line.split(",");
- String promotionName = promotion[0];
- promotions.put(promotionName, convertPromotion(promotion));
- }
+ return getPromotionMap(br);
} catch (IOException e) {
throw new RuntimeException("Failed to read the file.", e);
}
+
+ }
+
+ private static Map<String, Promotion> getPromotionMap(BufferedReader br) throws IOException {
+ Map<String, Promotion> promotions = new LinkedHashMap<>();
+ String line = br.readLine();
+ while ((line = br.readLine()) != null) {
+ String[] promotion = line.split(",");
+ String promotionName = promotion[0];
+ promotions.put(promotionName, convertPromotion(promotion));
+ }
return promotions;
}
- private Promotion convertPromotion(String[] promotion) {
+ private static Promotion convertPromotion(String[] promotion) {
return new Promotion(promotion[0], Integer.parseInt(promotion[1]), Integer.parseInt(promotion[2]),
LocalDate.parse(promotion[3]), LocalDate.parse(promotion[4]));
} | Java | ,์ ๊ฒฝ์ฐ ๊ตฌ๋ถ์๋ฅผ ์์๋ก ๊ทธ๋ฆฌ๊ณ product[0]์ ๊ฒฝ์ฐ์๋ ๋ค๋ฅธ ์ฝ๋๋ฅผ ๋ณด๋ฉด product[NAME_IDX]๋ผ๊ณ ๋ช
๋ช
ํ์ฌ ๊ฐ๋
์ฑ์ ๋์ด๊ธฐ๋ ํ๋๋ฐ ์ด๋ฐ ๊ฒ๋ ์์ผ๋ ์ฐธ๊ณ ํ์๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -15,29 +15,35 @@ public class StoreFileReader {
public static final String PRODUCTS_DATA = "src/main/resources/products.md";
public static final String PROMOTIONS_DATA = "src/main/resources/promotions.md";
- public Map<String, Product> product(Map<String, Promotion> promotions) {
- Map<String, Product> products = new LinkedHashMap<>();
- try (BufferedReader br = new BufferedReader(
- new InputStreamReader(new FileInputStream(PRODUCTS_DATA)))) {
- String line = br.readLine();
- while ((line = br.readLine()) != null) {
- String[] product = line.split(",");
- String productName = product[0];
- if (products.containsKey(productName)) { // ๋๋ฒ์งธ๋ก ๋ค์ด์ค๋ ๊ฑด ๋ฌด์กฐ๊ฑด ์ผ๋ฐ ์ฌ๊ณ
- Product p = products.get(productName);
- int quantity = Integer.parseInt(product[2]);
- p.add(quantity);
- }
- products.computeIfAbsent(productName, (k) -> convertProduct(product, promotions));
-
- }
+ public static Map<String, Product> product(Map<String, Promotion> promotions) {
+ try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(PRODUCTS_DATA)))) {
+ return getProductMap(promotions, br);
} catch (IOException e) {
throw new RuntimeException("Failed to read the file.", e);
}
+ }
+
+ private static Map<String, Product> getProductMap(Map<String, Promotion> promotions, BufferedReader br)
+ throws IOException {
+ Map<String, Product> products = new LinkedHashMap<>();
+ String line = br.readLine();
+ while ((line = br.readLine()) != null) {
+ String[] product = line.split(",");
+ String productName = product[0];
+ addProduct(products, productName, product);
+ products.computeIfAbsent(productName, (k) -> convertProduct(product, promotions));
+ }
return products;
}
- private Product convertProduct(String[] product, Map<String, Promotion> promotions) {
+ private static void addProduct(Map<String, Product> products, String productName, String[] product) {
+ if (products.containsKey(productName)) {
+ Product p = products.get(productName);
+ p.add(Integer.parseInt(product[2]));
+ }
+ }
+
+ private static Product convertProduct(String[] product, Map<String, Promotion> promotions) {
String name = product[0];
int price = Integer.parseInt(product[1]);
int quantity = Integer.parseInt(product[2]);
@@ -52,23 +58,28 @@ private static boolean isPromotion(String[] product) {
return !product[3].equals("null");
}
- public Map<String, Promotion> promotions() {
- Map<String, Promotion> promotions = new LinkedHashMap<>();
+ public static Map<String, Promotion> promotions() {
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(PROMOTIONS_DATA)))) {
- String line = br.readLine();
- while ((line = br.readLine()) != null) {
- String[] promotion = line.split(",");
- String promotionName = promotion[0];
- promotions.put(promotionName, convertPromotion(promotion));
- }
+ return getPromotionMap(br);
} catch (IOException e) {
throw new RuntimeException("Failed to read the file.", e);
}
+
+ }
+
+ private static Map<String, Promotion> getPromotionMap(BufferedReader br) throws IOException {
+ Map<String, Promotion> promotions = new LinkedHashMap<>();
+ String line = br.readLine();
+ while ((line = br.readLine()) != null) {
+ String[] promotion = line.split(",");
+ String promotionName = promotion[0];
+ promotions.put(promotionName, convertPromotion(promotion));
+ }
return promotions;
}
- private Promotion convertPromotion(String[] promotion) {
+ private static Promotion convertPromotion(String[] promotion) {
return new Promotion(promotion[0], Integer.parseInt(promotion[1]), Integer.parseInt(promotion[2]),
LocalDate.parse(promotion[3]), LocalDate.parse(promotion[4]));
} | Java | null๋ ์์ํ ์ํค๋ฉด ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -15,29 +15,35 @@ public class StoreFileReader {
public static final String PRODUCTS_DATA = "src/main/resources/products.md";
public static final String PROMOTIONS_DATA = "src/main/resources/promotions.md";
- public Map<String, Product> product(Map<String, Promotion> promotions) {
- Map<String, Product> products = new LinkedHashMap<>();
- try (BufferedReader br = new BufferedReader(
- new InputStreamReader(new FileInputStream(PRODUCTS_DATA)))) {
- String line = br.readLine();
- while ((line = br.readLine()) != null) {
- String[] product = line.split(",");
- String productName = product[0];
- if (products.containsKey(productName)) { // ๋๋ฒ์งธ๋ก ๋ค์ด์ค๋ ๊ฑด ๋ฌด์กฐ๊ฑด ์ผ๋ฐ ์ฌ๊ณ
- Product p = products.get(productName);
- int quantity = Integer.parseInt(product[2]);
- p.add(quantity);
- }
- products.computeIfAbsent(productName, (k) -> convertProduct(product, promotions));
-
- }
+ public static Map<String, Product> product(Map<String, Promotion> promotions) {
+ try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(PRODUCTS_DATA)))) {
+ return getProductMap(promotions, br);
} catch (IOException e) {
throw new RuntimeException("Failed to read the file.", e);
}
+ }
+
+ private static Map<String, Product> getProductMap(Map<String, Promotion> promotions, BufferedReader br)
+ throws IOException {
+ Map<String, Product> products = new LinkedHashMap<>();
+ String line = br.readLine();
+ while ((line = br.readLine()) != null) {
+ String[] product = line.split(",");
+ String productName = product[0];
+ addProduct(products, productName, product);
+ products.computeIfAbsent(productName, (k) -> convertProduct(product, promotions));
+ }
return products;
}
- private Product convertProduct(String[] product, Map<String, Promotion> promotions) {
+ private static void addProduct(Map<String, Product> products, String productName, String[] product) {
+ if (products.containsKey(productName)) {
+ Product p = products.get(productName);
+ p.add(Integer.parseInt(product[2]));
+ }
+ }
+
+ private static Product convertProduct(String[] product, Map<String, Promotion> promotions) {
String name = product[0];
int price = Integer.parseInt(product[1]);
int quantity = Integer.parseInt(product[2]);
@@ -52,23 +58,28 @@ private static boolean isPromotion(String[] product) {
return !product[3].equals("null");
}
- public Map<String, Promotion> promotions() {
- Map<String, Promotion> promotions = new LinkedHashMap<>();
+ public static Map<String, Promotion> promotions() {
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(PROMOTIONS_DATA)))) {
- String line = br.readLine();
- while ((line = br.readLine()) != null) {
- String[] promotion = line.split(",");
- String promotionName = promotion[0];
- promotions.put(promotionName, convertPromotion(promotion));
- }
+ return getPromotionMap(br);
} catch (IOException e) {
throw new RuntimeException("Failed to read the file.", e);
}
+
+ }
+
+ private static Map<String, Promotion> getPromotionMap(BufferedReader br) throws IOException {
+ Map<String, Promotion> promotions = new LinkedHashMap<>();
+ String line = br.readLine();
+ while ((line = br.readLine()) != null) {
+ String[] promotion = line.split(",");
+ String promotionName = promotion[0];
+ promotions.put(promotionName, convertPromotion(promotion));
+ }
return promotions;
}
- private Promotion convertPromotion(String[] promotion) {
+ private static Promotion convertPromotion(String[] promotion) {
return new Promotion(promotion[0], Integer.parseInt(promotion[1]), Integer.parseInt(promotion[2]),
LocalDate.parse(promotion[3]), LocalDate.parse(promotion[4]));
} | Java | - ์ธ๋ฑ์ค ๋ฒํธ์ ์์ํ๊ฐ ์ด๋ฃจ์ด์ง๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค.
- null๊ณผ ๊ฐ์ ๊ฒ๋ค์ EMPTY์ ๊ฐ์ด ์๋ฏธ๊ฐ ์๋๋ก ์์ํ๋ฅผ ์งํํ๋ฉด ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค.
- Map์ผ๋ก ๋ฃ๋ ๊ณผ์ ์ ๋น์ฆ๋์ค ๋ก์ง์ด๋ ๋ฐ์ดํฐ ์ ์ฅ ๋ก์ง์ ๊ฑด๋๋ ๊ฒ ๊ฐ์ต๋๋ค. List๋ฅผ ํตํด request ๋ฐ์ดํฐ ํ์์ผ๋ก ๋ง๋ ํ ๋น์ฆ๋์ค ๋ก์ง์ ๋ด๋นํ๋ service๋ ๋ฐ์ดํฐ๋ฅผ ์ง์ ๊ฑด๋๋ repository์์ ์ฒ๋ฆฌํ๋ ๊ฒ์ด ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,11 @@
+package store.repository;
+
+import java.util.Map;
+import store.domain.Product;
+
+public record ProductRepository(Map<String, Product> products) {
+
+ public Product findProduct(String name) {
+ return products.get(name);
+ }
+} | Java | StoreFileReader์์ ๋จผ์ ๋ง๋ Map์ ์ฌ๊ธฐ์ ๋ง๋ค์์ผ๋ฉด ์ข๊ฒ ์ต๋๋ค. ์ ํฌ๊ฐ Controller๋ Service์์ ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ์ ์ฅ ๋ฐฉ์์ ๊ฑด๋ค์ง ์๋ ์ด์ ์ ๊ฐ์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,52 @@
+package store.service;
+
+import java.util.List;
+import java.util.Map;
+import store.domain.Product;
+import store.domain.Promotion;
+import store.domain.Purchase;
+import store.domain.Receipt;
+import store.domain.ShortageQuantity;
+import store.domain.request.PurchaseRequest;
+
+public class ConvenienceService {
+ private final ProductService productService;
+ private final PromotionService promotionService;
+
+ public ConvenienceService(ProductService productService, PromotionService promotionService) {
+ this.productService = productService;
+ this.promotionService = promotionService;
+ }
+
+ public Receipt sell(List<PurchaseRequest> purchaseRequests, String membership) {
+ return calculate(purchaseRequests, membership, productService.getProducts());
+ }
+
+ private Receipt calculate(List<PurchaseRequest> purchaseRequests, String membership, Map<String, Product> products) {
+ List<Purchase> purchases = purchaseRequests.stream()
+ .filter(purchaseRequest -> products.containsKey(purchaseRequest.getName()))
+ .map(purchaseRequest -> {
+ Product product = products.get(purchaseRequest.getName());
+ return new Purchase(
+ purchaseRequest.getName(),
+ purchaseRequest.getQuantity(),
+ product.getPrice(),
+ 0);
+ }).toList();
+ return new Receipt(purchases, membership);
+ }
+
+
+ public void setPromotion(Map<String, Promotion> promotions) {
+ promotionService.setPromotion(promotions);
+ }
+
+ public Map<String, Product> getProducts() {
+ return productService.getProducts();
+ }
+
+ public List<ShortageQuantity> getShortageQuantityForPromotion(List<PurchaseRequest> purchases) {
+ return productService.getShortageQuantityForPromotion(purchases);
+ }
+
+} | Java | ๋ฉ์๋๋ฅผ ๋ฐ๋ก ๋ฝ์๋ด๋ฉด ๋ ์ข์๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,52 @@
+package store.service;
+
+import java.util.List;
+import java.util.Map;
+import store.domain.Product;
+import store.domain.Promotion;
+import store.domain.Purchase;
+import store.domain.Receipt;
+import store.domain.ShortageQuantity;
+import store.domain.request.PurchaseRequest;
+
+public class ConvenienceService {
+ private final ProductService productService;
+ private final PromotionService promotionService;
+
+ public ConvenienceService(ProductService productService, PromotionService promotionService) {
+ this.productService = productService;
+ this.promotionService = promotionService;
+ }
+
+ public Receipt sell(List<PurchaseRequest> purchaseRequests, String membership) {
+ return calculate(purchaseRequests, membership, productService.getProducts());
+ }
+
+ private Receipt calculate(List<PurchaseRequest> purchaseRequests, String membership, Map<String, Product> products) {
+ List<Purchase> purchases = purchaseRequests.stream()
+ .filter(purchaseRequest -> products.containsKey(purchaseRequest.getName()))
+ .map(purchaseRequest -> {
+ Product product = products.get(purchaseRequest.getName());
+ return new Purchase(
+ purchaseRequest.getName(),
+ purchaseRequest.getQuantity(),
+ product.getPrice(),
+ 0);
+ }).toList();
+ return new Receipt(purchases, membership);
+ }
+
+
+ public void setPromotion(Map<String, Promotion> promotions) {
+ promotionService.setPromotion(promotions);
+ }
+
+ public Map<String, Product> getProducts() {
+ return productService.getProducts();
+ }
+
+ public List<ShortageQuantity> getShortageQuantityForPromotion(List<PurchaseRequest> purchases) {
+ return productService.getShortageQuantityForPromotion(purchases);
+ }
+
+} | Java | ํด๋น ์ ํ์ด ์๋ ๊ฒฝ์ฐ filter๋ก ์ฒ๋ฆฌํ์๋๋ฐ ๊ธฐ์กด์ ์กด์ฌํ์ง ์์ ์ ํ์ ๊ฒฝ์ฐ ์๋ฌ๋ ๋ฌด์ํ๊ณ ๋์ด๊ฐ๋ ๊ฒ์ผ๊น์? |
@@ -0,0 +1,57 @@
+package store.service;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import store.domain.Product;
+import store.domain.ShortageQuantity;
+import store.domain.request.PurchaseRequest;
+import store.repository.ProductRepository;
+
+public class ProductService {
+
+ private final ProductRepository productRepository;
+
+ public ProductService(ProductRepository productRepository) {
+ this.productRepository = productRepository;
+ }
+
+ public Product findProduct(String name) {
+ return productRepository.findProduct(name);
+ }
+
+ public Map<String, Product> getProducts() {
+ return productRepository.products();
+ }
+
+ public List<ShortageQuantity> getShortageQuantityForPromotion(List<PurchaseRequest> purchases) {
+ return getShortageQuantities(purchases);
+ }
+
+ private List<ShortageQuantity> getShortageQuantities(List<PurchaseRequest> purchases) {
+ return purchases.stream()
+ .map(purchase -> {
+ Product product = findProduct(purchase.getName());
+
+ if (!product.existsPromotion()) {
+ return null;
+ }
+
+ int quantityRequested = purchase.getQuantity();
+ int shortageQuantity = product.getShortageQuantityForPromotion(quantityRequested);
+
+ if (shortageQuantity <= 0) {
+ return null;
+ }
+
+ boolean isSufficient = product.getPromotionQuantity() >= quantityRequested + shortageQuantity;
+ int actualShortageQuantity = isSufficient
+ ? shortageQuantity
+ : quantityRequested + shortageQuantity - product.getPromotionQuantity();
+
+ return new ShortageQuantity(purchase, product.getName(), actualShortageQuantity, isSufficient);
+ })
+ .filter(Objects::nonNull)
+ .toList();
+ }
+} | Java | Map์ ์ง์ ๊บผ๋ด์ฃผ๋ ๊ฒ์ ๋ฐ์ดํฐ๋ฅผ ๋ ํฌ์งํ ๋ฆฌ๋ฅผ ํตํ์ง ์๊ณ ์ง์ ๋ฐ์ดํฐ๋ฅผ ๋ณ๊ฒฝํ ์ ์๋ค๊ณ ์๊ฐํฉ๋๋ค. collections.unmodifiablemap์ ์ฌ์ฉํ์ฌ ๋ณ๊ฒฝํ ์ ์๋๋ก ๋ง๋ค๊ฑฐ๋ ์ด ๋ฉ์๋๋ก ๊บผ๋ธ Map์์ ์ฌ์ฉํ ๊ธฐ๋ฅ๋ค์ repository์์ ์ง์ ๊ฑด๋๋ ๊ฒ์ด ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,11 @@
+package store.repository;
+
+import java.util.Map;
+import store.domain.Product;
+
+public record ProductRepository(Map<String, Product> products) {
+
+ public Product findProduct(String name) {
+ return products.get(name);
+ }
+} | Java | repository๋ ์ ๋ณด๋ฅผ ์ ์ฅํ๋ ๊ฒ์ด ์๋ ์ ๋ณด ์ ์ฅ์์์ ์ ๋ณด๋ฅผ ๊บผ๋ด์ค๋ ๊ฒ์ผ๋ก ์๊ณ ์์ต๋๋ค. ์ด ํด๋์ค๋ ์ ๋ณด๋ฅผ ์ ์ฅํ๋ฉด ์๋ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,57 @@
+package store.service;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import store.domain.Product;
+import store.domain.ShortageQuantity;
+import store.domain.request.PurchaseRequest;
+import store.repository.ProductRepository;
+
+public class ProductService {
+
+ private final ProductRepository productRepository;
+
+ public ProductService(ProductRepository productRepository) {
+ this.productRepository = productRepository;
+ }
+
+ public Product findProduct(String name) {
+ return productRepository.findProduct(name);
+ }
+
+ public Map<String, Product> getProducts() {
+ return productRepository.products();
+ }
+
+ public List<ShortageQuantity> getShortageQuantityForPromotion(List<PurchaseRequest> purchases) {
+ return getShortageQuantities(purchases);
+ }
+
+ private List<ShortageQuantity> getShortageQuantities(List<PurchaseRequest> purchases) {
+ return purchases.stream()
+ .map(purchase -> {
+ Product product = findProduct(purchase.getName());
+
+ if (!product.existsPromotion()) {
+ return null;
+ }
+
+ int quantityRequested = purchase.getQuantity();
+ int shortageQuantity = product.getShortageQuantityForPromotion(quantityRequested);
+
+ if (shortageQuantity <= 0) {
+ return null;
+ }
+
+ boolean isSufficient = product.getPromotionQuantity() >= quantityRequested + shortageQuantity;
+ int actualShortageQuantity = isSufficient
+ ? shortageQuantity
+ : quantityRequested + shortageQuantity - product.getPromotionQuantity();
+
+ return new ShortageQuantity(purchase, product.getName(), actualShortageQuantity, isSufficient);
+ })
+ .filter(Objects::nonNull)
+ .toList();
+ }
+} | Java | ๋ฉ์๋๋ฅผ ๋ฐ๋ก ๋ฝ์๋ด๋ ๊ฒ์ด ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค... |
@@ -0,0 +1,18 @@
+package store.service;
+
+import java.util.Map;
+import store.domain.Promotion;
+import store.repository.PromotionRepository;
+
+public class PromotionService {
+
+ private final PromotionRepository promotionRepository;
+
+ public PromotionService(PromotionRepository promotionRepository) {
+ this.promotionRepository = promotionRepository;
+ }
+
+ public void setPromotion(Map<String, Promotion> promotions) {
+ promotionRepository.setPromotion(promotions);
+ }
+} | Java | ๊ฐ ๊ณ์ธต์์ ์ญํ ์ด ์ ๋๋ก ๋ถ๋ฐฐ๋์ง์์ ๋ฐ์ํ๋ ์๋ฏธ์๋ ๋ฉ์๋๊ฐ ๋ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,138 @@
+package store.view;
+
+import static store.config.ErrorMessage.PRODUCT_NOT_EXIST;
+import static store.config.ErrorMessage.PRODUCT_QUANTITY_NOT_ENOUGH;
+import static store.domain.Agree.NO;
+import static store.domain.Agree.YES;
+
+import camp.nextstep.edu.missionutils.Console;
+import camp.nextstep.edu.missionutils.DateTimes;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import store.config.ErrorMessage;
+import store.domain.Product;
+import store.domain.Promotion;
+import store.domain.ShortageQuantity;
+import store.domain.request.PurchaseRequest;
+
+public class InputView {
+
+ public List<PurchaseRequest> inputProductAndQuantity(Map<String, Product> products) {
+ return RetryOnInvalidInput.retryOnException(() -> getPurchaseRequests(products));
+ }
+
+ private List<PurchaseRequest> getPurchaseRequests(Map<String, Product> products) {
+ System.out.println("๊ตฌ๋งคํ์ค ์ํ๋ช
๊ณผ ์๋์ ์
๋ ฅํด ์ฃผ์ธ์. (์: [์ฌ์ด๋ค-2],[๊ฐ์์นฉ-1])");
+ try {
+ String[] purchaseProduct = extractProduct(Console.readLine());
+ return Arrays.stream(purchaseProduct)
+ .map(product -> product.split("-"))
+ .map(product -> convertToPurchaseRequest(product, products))
+ .toList();
+ } catch (NoSuchElementException e) {
+ throw new NoSuchElementException(e.getMessage(), e);
+ } catch (Exception e) {
+ throw new IllegalArgumentException(e.getMessage(), e);
+ }
+ }
+
+ private static String[] extractProduct(String input) {
+ return input.replaceAll("[\\[\\]]", "").split(",");
+ }
+
+ public PurchaseRequest convertToPurchaseRequest(String[] request, Map<String, Product> products) {
+ String name = request[0];
+ int quantity = Integer.parseInt(request[1]);
+
+ Product product = products.get(name);
+ validateProduct(product, quantity);
+
+ Promotion promotion = product.getPromotion();
+ validatePromotion(promotion, product, quantity);
+
+ return new PurchaseRequest(name, quantity);
+ }
+
+ private static void validatePromotion(Promotion promotion, Product product, int quantity) {
+ if (existsPromotion(promotion)) {
+ if (product.getPromotionQuantity() + product.getQuantity() < quantity) {
+ throw new IllegalStateException(PRODUCT_QUANTITY_NOT_ENOUGH.getMessage());
+ }
+ }
+ }
+
+ private void validateProduct(Product product, int quantity) {
+ if (isNotFound(product)) {
+ throw new IllegalStateException(PRODUCT_NOT_EXIST.getMessage());
+ }
+ if (notEnoughProduct(product, quantity)) {
+ throw new IllegalStateException(PRODUCT_QUANTITY_NOT_ENOUGH.getMessage());
+ }
+ }
+
+ private static boolean notEnoughProduct(Product product, int quantity) {
+ return product.getQuantity() < quantity;
+ }
+
+ private static boolean existsPromotion(Promotion promotion) {
+ return promotion != null && promotion.isRangePromotion(DateTimes.now().toLocalDate());
+ }
+
+ private boolean isNotFound(Product product) {
+ return product == null;
+ }
+
+ public String inputMembership() {
+ return RetryOnInvalidInput.retryOnException(this::getMemberShip);
+ }
+
+ public String inputRePurchase() {
+ return RetryOnInvalidInput.retryOnException(this::getRePurchase);
+ }
+
+ private String getMemberShip() {
+ System.out.println("๋ฉค๋ฒ์ญ ํ ์ธ์ ๋ฐ์ผ์๊ฒ ์ต๋๊น? (Y/N)");
+ return agree(Console.readLine());
+ }
+
+ private String getRePurchase() {
+ System.out.println("๊ฐ์ฌํฉ๋๋ค. ๊ตฌ๋งคํ๊ณ ์ถ์ ๋ค๋ฅธ ์ํ์ด ์๋์? (Y/N)");
+ return agree(Console.readLine());
+ }
+
+ public String getNotPromotion(ShortageQuantity shortageQuantity) {
+ return RetryOnInvalidInput.retryOnException(() -> inputNotPromotion(shortageQuantity));
+ }
+
+ public String inputNotPromotion(ShortageQuantity shortageQuantity) {
+ System.out.println("ํ์ฌ " +
+ shortageQuantity.getName() +
+ " " +
+ shortageQuantity.getQuantity() +
+ "๊ฐ๋ ํ๋ก๋ชจ์
ํ ์ธ์ด ์ ์ฉ๋์ง ์์ต๋๋ค. ๊ทธ๋๋ ๊ตฌ๋งคํ์๊ฒ ์ต๋๊น? (Y/N)");
+ return agree(Console.readLine());
+ }
+
+ private static String agree(String agree) {
+ if (!agree.equals(YES.getValue()) && !agree.equals(NO.getValue())) {
+ throw new IllegalArgumentException(ErrorMessage.WRONG_INPUT.getMessage());
+ }
+ return agree;
+ }
+
+ public String getPromotion(ShortageQuantity shortageQuantity) {
+ return RetryOnInvalidInput.retryOnException(() -> inputPromotion(shortageQuantity));
+ }
+
+
+ private String inputPromotion(ShortageQuantity shortageQuantity) {
+ System.out.println("ํ์ฌ " +
+ shortageQuantity.getName() +
+ "์(๋) " +
+ shortageQuantity.getQuantity() +
+ "๊ฐ๋ฅผ ๋ฌด๋ฃ๋ก ๋ ๋ฐ์ ์ ์์ต๋๋ค. ์ถ๊ฐํ์๊ฒ ์ต๋๊น? (Y/N)");
+ return agree(Console.readLine());
+ }
+} | Java | ์ฌ์ด๋ค,2๊ฐ์์นฉ-1 ๊ณผ ๊ฐ์ ๊ฒฝ์ฐ ๊ฑธ๋ฌ๋ผ ๊ฒ์ฌ๊ฐ ์์ด๋ณด์
๋๋ค. |
@@ -0,0 +1,86 @@
+package store.view;
+
+import java.util.Map;
+import store.domain.Product;
+import store.domain.Purchase;
+import store.domain.Receipt;
+
+public class OutputView {
+
+ public void printProducts(Map<String, Product> products) {
+ printStart();
+ for (Product product : products.values()) {
+ if(product.existsPromotion()) {
+ System.out.println("- " + getName(product) + " " + getPrice(product) + " " + getPromotionQuantity(product) + " " + getPromotion(product));
+ }
+ System.out.println("- " + getName(product) + " " + getPrice(product) + " " + getQuantity(product));
+ }
+ System.out.println();
+ }
+
+ private static String getName(Product product) {
+ return product.getName();
+ }
+
+ private static String getPromotion(Product product) {
+ return product.getPromotion() == null ? "" : product.getPromotion().getName();
+ }
+
+ private static String getPromotionQuantity(Product product) {
+ return product.getPromotionQuantity() == 0 ? "์ฌ๊ณ ์์" : (product.getPromotionQuantity() + "๊ฐ");
+ }
+
+ private static String getQuantity(Product product) {
+ return product.getQuantity() == 0 ? "์ฌ๊ณ ์์" : (product.getQuantity() + "๊ฐ");
+ }
+
+ private static String getPrice(Product product) {
+ return String.format("%,d์", product.getPrice());
+ }
+
+ private void printStart() {
+ System.out.println("์๋
ํ์ธ์. Wํธ์์ ์
๋๋ค.");
+ System.out.println("ํ์ฌ ๋ณด์ ํ๊ณ ์๋ ์ํ์
๋๋ค.");
+ System.out.println();
+ }
+
+ public void printReceipt(Receipt receipt) {
+ System.out.println("==============W ํธ์์ ================");
+ printProduct(receipt);
+ printPromotion(receipt);
+ printResult(receipt);
+ }
+
+ private static void printProduct(Receipt receipt) {
+ System.out.println("์ํ๋ช
์๋ ๊ธ์ก");
+ StringBuilder product = new StringBuilder();
+ for (Purchase purchase : receipt.getPurchases()) {
+ product.append(purchase.getName())
+ .append(" ")
+ .append(purchase.getQuantity())
+ .append(" ")
+ .append(purchase.getPrice() * purchase.getQuantity())
+ .append("\n");
+ }
+ System.out.println(product);
+ }
+
+ private static void printPromotion(Receipt receipt) {
+ System.out.println("=============์ฆ ์ ===============");
+ for (Purchase purchase : receipt.getPurchases()) {
+ if (purchase.getPromotionQuantity() != 0) {
+ System.out.println(purchase.getName() + " " + purchase.getPromotionQuantity());
+ }
+ }
+ }
+
+ private static void printResult(Receipt receipt) {
+ System.out.println("====================================");
+ System.out.format("์ด๊ตฌ๋งค์ก %d %,d์\n", receipt.getTotalCount(), receipt.getTotalMoney());
+ System.out.format("ํ์ฌํ ์ธ %,d์\n", receipt.getPromotionDiscount());
+ System.out.format("๋ฉค๋ฒ์ญํ ์ธ %,d์\n", receipt.getMembershipDiscount());
+ System.out.format("๋ด์ค๋ %,d์\n",
+ receipt.getTotalMoney() - receipt.getMembershipDiscount() - receipt.getPromotionDiscount());
+ System.out.println();
+ }
+} | Java | ํ์์ ๊ฒฝ์ฐ ์์๋ก ์ฒ๋ฆฌํ๋ ๊ฒ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค. |
@@ -0,0 +1,56 @@
+package store.config;
+
+import java.util.Map;
+import store.controller.ConvenienceController;
+import store.convenience.Convenience;
+import store.domain.Product;
+import store.domain.Promotion;
+import store.reader.StoreFileReader;
+import store.repository.ProductRepository;
+import store.repository.PromotionRepository;
+import store.service.ConvenienceService;
+import store.service.ProductService;
+import store.service.PromotionService;
+import store.view.InputView;
+import store.view.OutputView;
+
+public class ConvenienceFactory {
+
+ public static Convenience createConvenience() {
+ return new Convenience(convenienceController(), outputView(), inputView());
+ }
+
+ public static ConvenienceController convenienceController() {
+ return new ConvenienceController(convenienceService());
+ }
+
+ public static ConvenienceService convenienceService() {
+ return new ConvenienceService(productService(), promotionService());
+ }
+
+ public static OutputView outputView() {
+ return new OutputView();
+ }
+
+ public static InputView inputView() {
+ return new InputView();
+ }
+
+ public static ProductRepository productRepository() {
+ Map<String, Promotion> promotions = StoreFileReader.promotions();
+ Map<String, Product> products = StoreFileReader.product(promotions);
+ return new ProductRepository(products);
+ }
+
+ public static ProductService productService() {
+ return new ProductService(productRepository());
+ }
+
+ public static PromotionService promotionService() {
+ return new PromotionService(promotionRepository());
+ }
+
+ public static PromotionRepository promotionRepository() {
+ return new PromotionRepository(StoreFileReader.promotions());
+ }
+} | Java | ๋์ณค๋ ๋ถ๋ถ์ด๋ค์ ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,134 @@
+import axios, {
+ AxiosError,
+ AxiosInstance,
+ AxiosRequestConfig,
+ AxiosResponse,
+ InternalAxiosRequestConfig,
+} from 'axios';
+import { BASE_URL } from '@constants/constants';
+import {
+ getAuthToken,
+ removeAuthToken,
+ removeRole,
+ setAuthToken,
+} from '@utils/auth';
+import { toast } from 'react-toastify';
+
+// Default Instance
+const defaultInstance: AxiosInstance = axios.create({
+ baseURL: BASE_URL,
+ timeout: 5000,
+ headers: {
+ accept: 'application/json',
+ 'Content-Type': 'application/json',
+ },
+ withCredentials: true,
+});
+
+// Auth Instance
+const authInstance: AxiosInstance = axios.create({
+ baseURL: BASE_URL,
+ timeout: 5000,
+ headers: {
+ accept: 'application/json',
+ 'Content-Type': 'application/json',
+ },
+ withCredentials: true,
+});
+
+/*
+ AccessToken ๋ง๋ฃ ์
+ ํ ํฐ ์ฌ๋ฐ๊ธ ์์ฒญ(reissue) ->
+ ์๋ฒ์์ refreshToken ๊ฒ์ฌ ->
+ ์ฌ๋ฐ๋ฅธ ํ ํฐ์ด๋ฉด AccessToken ์ฌ๋ฐ๊ธ , ๊ทธ๋ ์ง ์์ ํ ํฐ์ด๋ฉด ๋ก๊ทธ์์ ์ํ๋ก ๋ณ๊ฒฝ
+*/
+
+// response interceptor (ํ ํฐ ๊ฐฑ์ )
+authInstance.interceptors.response.use(
+ (response: AxiosResponse) => response,
+ // ์๋ฌ ์ฒ๋ฆฌ ํจ์
+ async (error: AxiosError) => {
+ // 401 Unauthorized ์๋ฌ ์ token ๊ฐฑ์ ํ๊ธฐ
+ if (error.response && error.response.status === 401) {
+ try {
+ const response = await defaultInstance.post('/reissue');
+
+ // reissue ์์ฒญ ์ฑ๊ณต ์
+ if (response.status === 200) {
+ const token = response.headers.authorization;
+ setAuthToken(token);
+
+ const originalRequest = error.config as AxiosRequestConfig;
+ if (originalRequest.headers) {
+ originalRequest.headers.Authorization = `Bearer ${token}`;
+ }
+ return await authInstance(originalRequest); // ์คํจํ๋ ์์ฒญ ์ฌ์๋
+ }
+ } catch (refreshError) {
+ // reissue ์์ฒญ ์คํจ ์
+ const reissueError = refreshError as AxiosError;
+ if (reissueError.response?.status === 401) {
+ // ๋ก๊ทธ์์
+ removeAuthToken();
+ removeRole();
+ window.location.replace('/start');
+ }
+ }
+ }
+ return Promise.reject(error);
+ },
+);
+
+// request interceptor
+authInstance.interceptors.request.use(
+ (config: InternalAxiosRequestConfig) => {
+ const accessToken = getAuthToken();
+ if (config.headers && accessToken) {
+ config.headers.Authorization = `Bearer ${accessToken}`;
+ }
+ return config;
+ },
+ (error) => {
+ return Promise.reject(error);
+ },
+);
+
+// response interceptor
+const responseInterceptor = (response: AxiosResponse) => response;
+
+// error handling
+export const onError = (message: string): void => {
+ toast.error(message);
+};
+
+const errorInterceptor = (error: AxiosError) => {
+ if (error.response) {
+ const { message, code } = error.response.data as {
+ code: string;
+ message: string;
+ };
+ if (
+ // ํน์ ์ฝ๋(B004, B005, B006)์์๋ toast๋ฅผ ๋์ฐ์ง ์์
+ error.response.status === 401 ||
+ (error.response.status === 409 && ['B004', 'B005', 'B006'].includes(code))
+ ) {
+ return Promise.reject(error);
+ }
+
+ onError(message || '์์ฒญ ์ฒ๋ฆฌ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.');
+ }
+
+ if (!error.response) {
+ onError('๋คํธ์ํฌ ์ฐ๊ฒฐ์ ํ์ธํด์ฃผ์ธ์.');
+ }
+
+ return Promise.reject(error);
+};
+
+defaultInstance.interceptors.response.use(
+ responseInterceptor,
+ errorInterceptor,
+);
+authInstance.interceptors.response.use(responseInterceptor, errorInterceptor);
+
+export { defaultInstance, authInstance }; | TypeScript | 1. ์๋ฌ์ฒ๋ฆฌ
- 1-1 ๊ณตํต์๋ฌ์ฒ๋ฆฌ ์๋ฌ ์๋ต์ ๋ํด ๋ช
ํํ๊ฒ ๋ฉ์ธ์ง๋ฅผ ์ ๋ฌํ๋ฉด ์ข์ต๋๋ค.
```js
const errorInterceptor = (error: AxiosError) => {
if (error.response) {
const { status } = error.response;
switch (status) {
case 401: {
onError('์ธ์ฆ์ด ๋ง๋ฃ๋์์ต๋๋ค.');
break;
}
case 403: {
onError('์ ๊ทผ ๊ถํ์ด ์์ต๋๋ค.');
break;
}
case 404: {
onError('์์ฒญํ์ ์ ๋ณด๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค.');
break;
}
case 500: {
onError('์๋ฒ ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.');
break;
}
default: {
onError('์ ์ ์๋ ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.');
}
}
}
// ๋คํธ์ํฌ ์๋ฌ
if (!error.response) {
onError('๋คํธ์ํฌ ์ฐ๊ฒฐ์ ํ์ธํด์ฃผ์ธ์.');
}
return Promise.reject(error);
};
``` |
@@ -0,0 +1,57 @@
+import {
+ DetailReview,
+ PostReviewRequestBody,
+ PutReviewRequestBody,
+ Review,
+} from '@typings/types';
+import { authInstance, defaultInstance } from '.';
+
+// ์์ธํ์ด์ง ๋ฆฌ๋ทฐ ์ ์ฒด ๋ชฉ๋ก ์กฐํ(๋น๋ก๊ทธ์ธ)
+export const getAllReview = async (
+ workplaceId: number,
+ nextCursor?: number,
+): Promise<{ data: DetailReview[]; nextCursor: number }> => {
+ const response = await defaultInstance.get(
+ `/api/v1/review/workplace/${workplaceId}`,
+ {
+ params: nextCursor ? { lastId: nextCursor } : {},
+ },
+ );
+ return response.data;
+};
+
+// ๋ด๊ฐ ์์ฑํ ๋ฆฌ๋ทฐ ์กฐํ - ๋ก๊ทธ์ธ
+export const getMyReview = async (): Promise<Review[]> => {
+ const response = await authInstance.get('/api/v1/review/me');
+ return response.data;
+};
+
+// ๋ฆฌ๋ทฐ ์์ฑ
+export const postReview = async (
+ data: PostReviewRequestBody,
+): Promise<void> => {
+ await authInstance.post('/api/v1/review/register', data);
+};
+
+// ๋ฆฌ๋ทฐ ์์
+export const putEditReview = async (
+ reviewId: number,
+ workplaceName: string,
+ data: PutReviewRequestBody,
+): Promise<Review> => {
+ const response = await authInstance.put(
+ `/api/v1/review/update/${reviewId}?workplaceName=${workplaceName}`,
+ data,
+ );
+ return response.data;
+};
+
+// ๋ฆฌ๋ทฐ ์ญ์
+export const deleteReview = async (
+ reviewId: number,
+ workplaceName: string,
+): Promise<void> => {
+ await authInstance.delete(
+ `/api/v1/review/${reviewId}?workplaceName=${workplaceName}`,
+ );
+}; | TypeScript | - 1-2 ๊ฐ๋ณ ์๋ฌ ์ฒ๋ฆฌ์ ๊ฒฝ์ฐ ์๋์ ๊ฐ์ด ์ฒ๋ฆฌํ๋ฉด ๋ฉ๋๋ค.
```js
export const postReview = async (data: ReviewData): Promise<Review> => {
try {
const response = await authInstance.post('/api/v1/review', data);
return response.data;
} catch (error) {
// ๋ฆฌ๋ทฐ ์์ฑ ์ ํน๋ณํ ์ฒ๋ฆฌํด์ผ ํ๋ ์๋ฌ๋ง ์ฌ๊ธฐ์ ์ฒ๋ฆฌ
if (error.response?.status === 400) {
throw new Error('๋ฆฌ๋ทฐ ๋ด์ฉ์ ํ์ธํด์ฃผ์ธ์.');
}
// ๋๋จธ์ง๋ ๊ณตํต ์๋ฌ ์ฒ๋ฆฌ๋ก ์ ํ
throw error;
}
};
``` |
@@ -0,0 +1,134 @@
+import axios, {
+ AxiosError,
+ AxiosInstance,
+ AxiosRequestConfig,
+ AxiosResponse,
+ InternalAxiosRequestConfig,
+} from 'axios';
+import { BASE_URL } from '@constants/constants';
+import {
+ getAuthToken,
+ removeAuthToken,
+ removeRole,
+ setAuthToken,
+} from '@utils/auth';
+import { toast } from 'react-toastify';
+
+// Default Instance
+const defaultInstance: AxiosInstance = axios.create({
+ baseURL: BASE_URL,
+ timeout: 5000,
+ headers: {
+ accept: 'application/json',
+ 'Content-Type': 'application/json',
+ },
+ withCredentials: true,
+});
+
+// Auth Instance
+const authInstance: AxiosInstance = axios.create({
+ baseURL: BASE_URL,
+ timeout: 5000,
+ headers: {
+ accept: 'application/json',
+ 'Content-Type': 'application/json',
+ },
+ withCredentials: true,
+});
+
+/*
+ AccessToken ๋ง๋ฃ ์
+ ํ ํฐ ์ฌ๋ฐ๊ธ ์์ฒญ(reissue) ->
+ ์๋ฒ์์ refreshToken ๊ฒ์ฌ ->
+ ์ฌ๋ฐ๋ฅธ ํ ํฐ์ด๋ฉด AccessToken ์ฌ๋ฐ๊ธ , ๊ทธ๋ ์ง ์์ ํ ํฐ์ด๋ฉด ๋ก๊ทธ์์ ์ํ๋ก ๋ณ๊ฒฝ
+*/
+
+// response interceptor (ํ ํฐ ๊ฐฑ์ )
+authInstance.interceptors.response.use(
+ (response: AxiosResponse) => response,
+ // ์๋ฌ ์ฒ๋ฆฌ ํจ์
+ async (error: AxiosError) => {
+ // 401 Unauthorized ์๋ฌ ์ token ๊ฐฑ์ ํ๊ธฐ
+ if (error.response && error.response.status === 401) {
+ try {
+ const response = await defaultInstance.post('/reissue');
+
+ // reissue ์์ฒญ ์ฑ๊ณต ์
+ if (response.status === 200) {
+ const token = response.headers.authorization;
+ setAuthToken(token);
+
+ const originalRequest = error.config as AxiosRequestConfig;
+ if (originalRequest.headers) {
+ originalRequest.headers.Authorization = `Bearer ${token}`;
+ }
+ return await authInstance(originalRequest); // ์คํจํ๋ ์์ฒญ ์ฌ์๋
+ }
+ } catch (refreshError) {
+ // reissue ์์ฒญ ์คํจ ์
+ const reissueError = refreshError as AxiosError;
+ if (reissueError.response?.status === 401) {
+ // ๋ก๊ทธ์์
+ removeAuthToken();
+ removeRole();
+ window.location.replace('/start');
+ }
+ }
+ }
+ return Promise.reject(error);
+ },
+);
+
+// request interceptor
+authInstance.interceptors.request.use(
+ (config: InternalAxiosRequestConfig) => {
+ const accessToken = getAuthToken();
+ if (config.headers && accessToken) {
+ config.headers.Authorization = `Bearer ${accessToken}`;
+ }
+ return config;
+ },
+ (error) => {
+ return Promise.reject(error);
+ },
+);
+
+// response interceptor
+const responseInterceptor = (response: AxiosResponse) => response;
+
+// error handling
+export const onError = (message: string): void => {
+ toast.error(message);
+};
+
+const errorInterceptor = (error: AxiosError) => {
+ if (error.response) {
+ const { message, code } = error.response.data as {
+ code: string;
+ message: string;
+ };
+ if (
+ // ํน์ ์ฝ๋(B004, B005, B006)์์๋ toast๋ฅผ ๋์ฐ์ง ์์
+ error.response.status === 401 ||
+ (error.response.status === 409 && ['B004', 'B005', 'B006'].includes(code))
+ ) {
+ return Promise.reject(error);
+ }
+
+ onError(message || '์์ฒญ ์ฒ๋ฆฌ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.');
+ }
+
+ if (!error.response) {
+ onError('๋คํธ์ํฌ ์ฐ๊ฒฐ์ ํ์ธํด์ฃผ์ธ์.');
+ }
+
+ return Promise.reject(error);
+};
+
+defaultInstance.interceptors.response.use(
+ responseInterceptor,
+ errorInterceptor,
+);
+authInstance.interceptors.response.use(responseInterceptor, errorInterceptor);
+
+export { defaultInstance, authInstance }; | TypeScript | - ์ค์ ์์ํ
```js
export const AXIOS_CONFIG = {
TIMEOUT: 2000,
HEADERS: {
ACCEPT: 'application/json',
CONTENT_TYPE: 'application/json',
},
} as const;
// src/apis/index.ts
const defaultInstance = axios.create({
baseURL: ENV.API_BASE_URL,
timeout: AXIOS_CONFIG.TIMEOUT,
headers: {
accept: AXIOS_CONFIG.HEADERS.ACCEPT,
'Content-Type': AXIOS_CONFIG.HEADERS.CONTENT_TYPE,
},
});
``` |
@@ -0,0 +1,134 @@
+import axios, {
+ AxiosError,
+ AxiosInstance,
+ AxiosRequestConfig,
+ AxiosResponse,
+ InternalAxiosRequestConfig,
+} from 'axios';
+import { BASE_URL } from '@constants/constants';
+import {
+ getAuthToken,
+ removeAuthToken,
+ removeRole,
+ setAuthToken,
+} from '@utils/auth';
+import { toast } from 'react-toastify';
+
+// Default Instance
+const defaultInstance: AxiosInstance = axios.create({
+ baseURL: BASE_URL,
+ timeout: 5000,
+ headers: {
+ accept: 'application/json',
+ 'Content-Type': 'application/json',
+ },
+ withCredentials: true,
+});
+
+// Auth Instance
+const authInstance: AxiosInstance = axios.create({
+ baseURL: BASE_URL,
+ timeout: 5000,
+ headers: {
+ accept: 'application/json',
+ 'Content-Type': 'application/json',
+ },
+ withCredentials: true,
+});
+
+/*
+ AccessToken ๋ง๋ฃ ์
+ ํ ํฐ ์ฌ๋ฐ๊ธ ์์ฒญ(reissue) ->
+ ์๋ฒ์์ refreshToken ๊ฒ์ฌ ->
+ ์ฌ๋ฐ๋ฅธ ํ ํฐ์ด๋ฉด AccessToken ์ฌ๋ฐ๊ธ , ๊ทธ๋ ์ง ์์ ํ ํฐ์ด๋ฉด ๋ก๊ทธ์์ ์ํ๋ก ๋ณ๊ฒฝ
+*/
+
+// response interceptor (ํ ํฐ ๊ฐฑ์ )
+authInstance.interceptors.response.use(
+ (response: AxiosResponse) => response,
+ // ์๋ฌ ์ฒ๋ฆฌ ํจ์
+ async (error: AxiosError) => {
+ // 401 Unauthorized ์๋ฌ ์ token ๊ฐฑ์ ํ๊ธฐ
+ if (error.response && error.response.status === 401) {
+ try {
+ const response = await defaultInstance.post('/reissue');
+
+ // reissue ์์ฒญ ์ฑ๊ณต ์
+ if (response.status === 200) {
+ const token = response.headers.authorization;
+ setAuthToken(token);
+
+ const originalRequest = error.config as AxiosRequestConfig;
+ if (originalRequest.headers) {
+ originalRequest.headers.Authorization = `Bearer ${token}`;
+ }
+ return await authInstance(originalRequest); // ์คํจํ๋ ์์ฒญ ์ฌ์๋
+ }
+ } catch (refreshError) {
+ // reissue ์์ฒญ ์คํจ ์
+ const reissueError = refreshError as AxiosError;
+ if (reissueError.response?.status === 401) {
+ // ๋ก๊ทธ์์
+ removeAuthToken();
+ removeRole();
+ window.location.replace('/start');
+ }
+ }
+ }
+ return Promise.reject(error);
+ },
+);
+
+// request interceptor
+authInstance.interceptors.request.use(
+ (config: InternalAxiosRequestConfig) => {
+ const accessToken = getAuthToken();
+ if (config.headers && accessToken) {
+ config.headers.Authorization = `Bearer ${accessToken}`;
+ }
+ return config;
+ },
+ (error) => {
+ return Promise.reject(error);
+ },
+);
+
+// response interceptor
+const responseInterceptor = (response: AxiosResponse) => response;
+
+// error handling
+export const onError = (message: string): void => {
+ toast.error(message);
+};
+
+const errorInterceptor = (error: AxiosError) => {
+ if (error.response) {
+ const { message, code } = error.response.data as {
+ code: string;
+ message: string;
+ };
+ if (
+ // ํน์ ์ฝ๋(B004, B005, B006)์์๋ toast๋ฅผ ๋์ฐ์ง ์์
+ error.response.status === 401 ||
+ (error.response.status === 409 && ['B004', 'B005', 'B006'].includes(code))
+ ) {
+ return Promise.reject(error);
+ }
+
+ onError(message || '์์ฒญ ์ฒ๋ฆฌ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.');
+ }
+
+ if (!error.response) {
+ onError('๋คํธ์ํฌ ์ฐ๊ฒฐ์ ํ์ธํด์ฃผ์ธ์.');
+ }
+
+ return Promise.reject(error);
+};
+
+defaultInstance.interceptors.response.use(
+ responseInterceptor,
+ errorInterceptor,
+);
+authInstance.interceptors.response.use(responseInterceptor, errorInterceptor);
+
+export { defaultInstance, authInstance }; | TypeScript | - ๊ฐ์ ์ ์
```js
export class AuthService {
private static isRefreshing = false;
private static refreshSubscribers: Array<(token: string) => void> = [];
static async refreshToken() {
if (this.isRefreshing) {
return new Promise(resolve => {
this.refreshSubscribers.push(resolve);
});
}
this.isRefreshing = true;
try {
const response = await authInstance.post('/reissue');
const newToken = response.headers.authorization;
this.refreshSubscribers.forEach(cb => cb(newToken));
this.refreshSubscribers = [];
return newToken;
} finally {
this.isRefreshing = false;
}
}
}
``` |
@@ -0,0 +1,36 @@
+interface InputProps {
+ label: string;
+ placeholder?: string;
+ defaultValue?: string | number;
+ value?: string;
+ onChangeFunction?: (e: React.ChangeEvent<HTMLInputElement>) => void;
+ maxLength?: number;
+ name?: string;
+}
+
+const CommonInput = ({
+ label,
+ placeholder,
+ defaultValue,
+ value,
+ onChangeFunction,
+ maxLength,
+ name,
+}: InputProps) => {
+ return (
+ <div className='mx-auto flex w-custom flex-col gap-1.5'>
+ <p className='w-[100%] text-sm font-normal'>{label}</p>
+ <input
+ className='main-input'
+ placeholder={placeholder}
+ defaultValue={defaultValue}
+ value={value}
+ onChange={onChangeFunction}
+ maxLength={maxLength}
+ name={name}
+ />
+ </div>
+ );
+};
+
+export default CommonInput; | Unknown | - ๊ฒ์ ์ ์
```js
// src/components/common/Input/types.ts
export interface BaseInputProps extends React.InputHTMLAttributes<HTMLInputElement> {
label: string;
}
// src/components/common/Input/Input.tsx
import { BaseInputProps } from './types';
const Input = ({ label, className, ...props }: BaseInputProps) => {
return (
<div className='input-wrapper'>
<label className='input-label'>{label}</label>
<input className={clsx('input-base', className)} {...props} />
</div>
);
};
``` |
@@ -0,0 +1,77 @@
+package store.util;
+
+import store.domain.Product;
+import store.domain.Promotion;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.time.LocalDateTime;
+import java.util.*;
+
+public class ProductLoader {
+
+ private static final String FILE_PATH = "./src/main/resources/products.md";
+
+ public static List<Product> loadProducts() {
+ Map<String, Promotion> promotions = PromotionLoader.loadPromotion();
+ Map<String, List<String[]>> groupedLines = getGroups();
+ return getProducts(groupedLines, promotions);
+ }
+
+ private static List<Product> getProducts(Map<String, List<String[]>> groupedLines, Map<String, Promotion> promotions) {
+ List<Product> products = new ArrayList<>();
+
+ for (Map.Entry<String, List<String[]>> entry : groupedLines.entrySet()) {
+ String name = entry.getKey();
+ Product product = createProduct(name, entry.getValue(), promotions);
+ products.add(product);
+ }
+
+ return products;
+ }
+
+ private static Product createProduct(String name, List<String[]> valuesList, Map<String, Promotion> promotions) {
+ int price = 0;
+ int promotionQuantity = 0;
+ int commonQuantity = 0;
+ Promotion promotion = createDefaultPromotion();
+
+ for (String[] values : valuesList) {
+ price = Integer.parseInt(values[1]);
+ int quantity = Integer.parseInt(values[2]);
+ String promotionName = values[3];
+
+ if ("null".equals(promotionName)) {
+ commonQuantity += quantity;
+ } else {
+ promotionQuantity += quantity;
+ promotion = promotions.getOrDefault(promotionName, promotions.get(promotionName));
+ }
+ }
+
+ return new Product(name, price, promotionQuantity, commonQuantity, promotion);
+ }
+
+ private static Promotion createDefaultPromotion() {
+ return new Promotion("", Integer.MAX_VALUE, 0, LocalDateTime.MIN, LocalDateTime.MIN);
+ }
+
+ private static Map<String, List<String[]>> getGroups() {
+ Map<String, List<String[]>> groupedLines = new HashMap<>();
+
+ try (BufferedReader br = new BufferedReader(new FileReader(FILE_PATH))) {
+ br.readLine(); // Skip header
+ String line;
+ while ((line = br.readLine()) != null) {
+ String[] values = line.split(",");
+ String name = values[0];
+ groupedLines.computeIfAbsent(name, k -> new ArrayList<>()).add(values);
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ return groupedLines;
+ }
+
+} | Java | util ํด๋์ค๋ผ๋ฉด ๊ธฐ๋ณธ ์์ฑ์ private์ผ๋ก ํด์ ์ธ์คํด์ค ์์ฑ์ ๋ง์๋ ์ข์๊ฒ ๊ฐ์์. |
@@ -0,0 +1,37 @@
+package store.util;
+
+import store.domain.Promotion;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.time.LocalDateTime;
+import java.util.HashMap;
+import java.util.Map;
+
+public class PromotionLoader {
+
+ private static final String FILE_PATH = "./src/main/resources/promotions.md";
+
+ public static Map<String, Promotion> loadPromotion() {
+ Map<String, Promotion> promotions = new HashMap<>();
+ try (BufferedReader br = new BufferedReader(new FileReader(FILE_PATH))) {
+ br.readLine(); // ์ฒซ๋ฒ์จฐ ํค๋ ์๋ต
+ String line;
+ while ((line = br.readLine()) != null) {
+ String[] values = line.split(",");
+ String name = values[0];
+ int buy = Integer.parseInt(values[1]);
+ int get = Integer.parseInt(values[2]);
+ LocalDateTime startDate = LocalDateTime.parse(values[3]+ "T00:00:00");
+ LocalDateTime endDate = LocalDateTime.parse(values[4] + "T00:00:00");
+ Promotion promotion = new Promotion(name, buy, get, startDate, endDate);
+ promotions.put(name, promotion);
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ return promotions;
+ }
+
+} | Java | `ClassLoader.getResource()`๋ก ๊ฐ์ ธ์์ผ ๋น๋๋ ์ํฐํฉํธ์์๋ ์ ๋๋ก resource๋ฅผ ๊ฐ์ ธ์ฌ ์ ์์ต๋๋ค |
@@ -0,0 +1,104 @@
+package store.service;
+
+import camp.nextstep.edu.missionutils.DateTimes;
+import store.controller.dto.OrderStateDTO;
+import store.controller.dto.StateContextDTO;
+import store.domain.*;
+import store.repository.OrderRepository;
+import store.repository.ProductRepository;
+import store.view.dto.RequestOrder;
+import store.view.dto.RequestOrderProduct;
+import store.view.dto.ResponseOrder;
+
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
+public class OrderService {
+
+ private final OrderRepository orderRepository;
+ private final ProductRepository productRepository;
+
+ public OrderService(OrderRepository orderRepository, ProductRepository productRepository) {
+ this.orderRepository = orderRepository;
+ this.productRepository = productRepository;
+ }
+
+ public OrderStateDTO createOrder(RequestOrder requestOrder) {
+ List<OrderProduct> orderProducts = new ArrayList<>();
+ List<StateContextDTO> stateContexts = new ArrayList<>();
+ OrderState orderState = OrderState.SUCCESS;
+ LocalDateTime now = DateTimes.now();
+ for (RequestOrderProduct requestOrderProduct : requestOrder.orderProducts()) {
+ Product product = productRepository.findByName(requestOrderProduct.name());
+ ApplyResult applyResult = product.applyResult(requestOrderProduct.quantity(), now);
+ OrderProduct orderProduct = createOrderProduct(product, applyResult, now);
+ OrderProductState orderProductState = orderProduct.getState();
+ orderState = calcaulteOrderState(orderProductState);
+ orderProducts.add(orderProduct);
+ stateContexts.add(new StateContextDTO(orderProductState.getState(), product.getName(), getQuantity(applyResult, orderProductState)));
+ }
+ Order order = new Order(orderProducts, orderState);
+ orderRepository.save(order);
+ return new OrderStateDTO(orderState.getState(), stateContexts);
+ }
+
+ private OrderProduct createOrderProduct(Product product, ApplyResult applyResult, LocalDateTime now) {
+ OrderProductState orderProductState = getOrderProductState(applyResult);
+
+ return new OrderProduct(
+ product,
+ applyResult.promotionQuantity(),
+ applyResult.commonQuantity(),
+ applyResult.pendingQuantity(),
+ applyResult.giftQuantity(),
+ orderProductState
+ );
+ }
+
+ private OrderProductState getOrderProductState(ApplyResult applyResult) {
+ if(applyResult.pendingQuantity() == 0) {
+ return OrderProductState.SOLVE;
+ }
+ if(applyResult.giftQuantity() == 0) {
+ return OrderProductState.EXCLUSION;
+ }
+ return OrderProductState.GIFT;
+ }
+
+ private int getQuantity(ApplyResult applyResult, OrderProductState orderProductState) {
+ if(orderProductState == OrderProductState.GIFT) {
+ return applyResult.giftQuantity();
+ }
+ return applyResult.pendingQuantity();
+ }
+
+ private OrderState calcaulteOrderState(OrderProductState orderProductState) {
+ if(orderProductState == OrderProductState.SOLVE) {
+ return OrderState.SUCCESS;
+ }
+ return OrderState.PENDING;
+ }
+
+ public void solvePending(Command command, String name) {
+ Optional<Order> order = orderRepository.find();
+ if (order.isEmpty()) {
+ throw new IllegalStateException("Order not found");
+ }
+ order.get().solvePending(name, command);
+ }
+
+ public void determinedMembership(Command command) {
+ Order order = orderRepository.find().get();
+ if (command.isYes()) {
+ order.activeMembership();
+ }
+ }
+
+ public ResponseOrder getOrderReceipt() {
+ Order order = orderRepository.find().get();
+ OrderReceipt receipt = order.getReceipt();
+ return ResponseOrder.from(receipt);
+ }
+} | Java | ์ธ๋ถ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ ํ๋ฒ ๊ฐ์ธ์ ํ์ฉ์ ํ๋ฉด ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค.
์๋น์ค๋ ๋น์ฆ๋์ค๊ฐ ์์ฑ๋๋ ๊ณณ์ด๋ค๋ณด๋๊น ์กฐ๊ธ ๋ ๊ทธ๋ฐ ์๊ฐ์ด ๋ค์์ด์. |
@@ -0,0 +1,80 @@
+package store.controller;
+
+import store.controller.dto.OrderStateDTO;
+import store.controller.dto.StateContextDTO;
+import store.domain.Command;
+import store.service.OrderService;
+import store.service.ProductService;
+import store.view.InputView;
+import store.view.OutputView;
+import store.view.dto.RequestOrder;
+import store.view.dto.ResponseOrder;
+import store.view.dto.ResponseProducts;
+
+import java.util.function.Supplier;
+
+public class OrderController {
+ private final OrderService orderService;
+ private final ProductService productService;
+ private final InputView inputView;
+ private final OutputView outputView;
+
+ public OrderController(OrderService orderService, ProductService productService, InputView inputView, OutputView outputView) {
+ this.orderService = orderService;
+ this.productService = productService;
+ this.inputView = inputView;
+ this.outputView = outputView;
+ }
+
+ public void createOrder() {
+ Command retryCommand;
+ do {
+ printProductInfo();
+ OrderStateDTO orderStateDTO = getOrderStateDTO();
+ checkOrderState(orderStateDTO);
+ Command command = inputCommand(inputView::askMemberShipDiscount);
+ orderService.determinedMembership(command);
+ getReceipt();
+ retryCommand = inputCommand(inputView::askAdditionalPurchase);
+ } while (retryCommand.isYes());
+ }
+
+ private void checkOrderState(OrderStateDTO orderState) {
+ if(orderState.state().equals("PENDING")) {
+ for (StateContextDTO stateContext : orderState.stateContexts()) {
+ Command command = inputCommand(() -> inputView.askReviewPending(stateContext));
+ orderService.solvePending(command, stateContext.name());
+ }
+ }
+ }
+
+ private void printProductInfo() {
+ ResponseProducts products = productService.findAll();
+ outputView.printProducts(products);
+ }
+
+ private OrderStateDTO getOrderStateDTO() {
+ try {
+ RequestOrder requestOrder = inputView.askItem();
+ return orderService.createOrder(requestOrder);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return getOrderStateDTO();
+ }
+ }
+
+ private Command inputCommand(Supplier<String> supplier) {
+ try {
+ String input = supplier.get();
+ return Command.find(input);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return inputCommand(supplier);
+ }
+ }
+
+ public void getReceipt() {
+ ResponseOrder orderReceipt = orderService.getOrderReceipt();
+ outputView.printOrder(orderReceipt);
+ }
+} | Java | ๊ณ ์ ๋์ด์๋ ์ํ๋ enum์ผ๋ก ํํํ๋ฉด ์๋๊ฐ ๋ช
ํํด์ง ์ ์์ ๊ฒ ๊ฐ์์. |
@@ -0,0 +1,80 @@
+package store.controller;
+
+import store.controller.dto.OrderStateDTO;
+import store.controller.dto.StateContextDTO;
+import store.domain.Command;
+import store.service.OrderService;
+import store.service.ProductService;
+import store.view.InputView;
+import store.view.OutputView;
+import store.view.dto.RequestOrder;
+import store.view.dto.ResponseOrder;
+import store.view.dto.ResponseProducts;
+
+import java.util.function.Supplier;
+
+public class OrderController {
+ private final OrderService orderService;
+ private final ProductService productService;
+ private final InputView inputView;
+ private final OutputView outputView;
+
+ public OrderController(OrderService orderService, ProductService productService, InputView inputView, OutputView outputView) {
+ this.orderService = orderService;
+ this.productService = productService;
+ this.inputView = inputView;
+ this.outputView = outputView;
+ }
+
+ public void createOrder() {
+ Command retryCommand;
+ do {
+ printProductInfo();
+ OrderStateDTO orderStateDTO = getOrderStateDTO();
+ checkOrderState(orderStateDTO);
+ Command command = inputCommand(inputView::askMemberShipDiscount);
+ orderService.determinedMembership(command);
+ getReceipt();
+ retryCommand = inputCommand(inputView::askAdditionalPurchase);
+ } while (retryCommand.isYes());
+ }
+
+ private void checkOrderState(OrderStateDTO orderState) {
+ if(orderState.state().equals("PENDING")) {
+ for (StateContextDTO stateContext : orderState.stateContexts()) {
+ Command command = inputCommand(() -> inputView.askReviewPending(stateContext));
+ orderService.solvePending(command, stateContext.name());
+ }
+ }
+ }
+
+ private void printProductInfo() {
+ ResponseProducts products = productService.findAll();
+ outputView.printProducts(products);
+ }
+
+ private OrderStateDTO getOrderStateDTO() {
+ try {
+ RequestOrder requestOrder = inputView.askItem();
+ return orderService.createOrder(requestOrder);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return getOrderStateDTO();
+ }
+ }
+
+ private Command inputCommand(Supplier<String> supplier) {
+ try {
+ String input = supplier.get();
+ return Command.find(input);
+ } catch (IllegalArgumentException e) {
+ outputView.printError(e.getMessage());
+ return inputCommand(supplier);
+ }
+ }
+
+ public void getReceipt() {
+ ResponseOrder orderReceipt = orderService.getOrderReceipt();
+ outputView.printOrder(orderReceipt);
+ }
+} | Java | ํน์ ์์กด์ฑ์ ๋ฐฉํฅ์ ๋ํด์ ๊ณ ๋ฏผํด๋ณด์
จ๋์?
๋ฌผ๋ก ์ง๊ธ์ ๊ณ์ธต์ด ๊ตฌ์กฐ์ ์ผ๋ก ๋ช
ํํ๊ฒ ๋๋์ด์ ธ์๋ ๊ฒ์ ์๋์ง๋ง(`interface`๋ฅผ ์ด์ฉํด์)
DTO๋ฅผ ์ฌ์ฉํ์ ๊ฒ์ผ๋ก ๋ณด์์ ๊ณ์ธต์ ๋ถ๋ฆฌํ๋ ค๊ณ ์๋ํ์์ง ์์๋ ์ถ์ด์.
๋ง์ฝ ๊ทธ๋ ๋ค๊ณ ํ๋ฉด, '๋ถ๋ฆฌ๋ ์ปจํธ๋กค๋ฌ๊ฐ ๋ทฐ๋ฅผ ๋ฐ๋ผ๋ณด๊ณ ์๋(`import store.view....`) ์์กด์ฑ์ ๋ฐฉํฅ์ด ๋ฐ๋์งํ๊ฐ?'๋ฅผ ๊ณ ๋ฏผํด๋ด๋ ์ข์ ๊ฒ ๊ฐ์์.
์ ์๊ฐ์๋ ๋ทฐ์ ์ปจํธ๋กค๋ฌ์ ์ฝ๋๋ฅผ ๋ถ๋ฆฌํ ๋๋ ๋ทฐ์ ๋ณ๊ฒฝ์ฌํญ์ผ๋ก๋ถํฐ ์ปจํธ๋กค๋ฌ๊ฐ ์ํฅ์ ๋ฐ์ง ์๊ฒ ํ๋ ค๋ ์๋๊ฐ ์๋ ๊ฑฐ๋ผ๊ตฌ ์๊ฐ์ ํ๊ณ ์๊ฑฐ๋ ์. (๊ผญ ๋ทฐ์ ์ปจํธ๋กค๋ฌ๊ฐ ์๋๋ผ ํ๋๋ผ๋ ๊ณ์ธต์ ๋ถ๋ฆฌํ ๋๋...)
๊ทธ๋ฐ๋ฐ ๊ทธ๋ ๊ฒ ํด์ ๋ถ๋ฆฌํ ์ปจํธ๋กค๋ฌ๊ฐ ๋ค์ ๋ทฐ๋ฅผ ์์กดํ๊ฒ ๋๋ฉด, ๊ฒฐ๊ตญ ๋ถ๋ฆฌํ ์๋ฏธ๊ฐ ํฌ์๋๋ ๊ฒ์ด ์๋๊ฐ ํ๋ ์๊ฐ์ด ๋ค์ด์.
๋ชจํธํ ์ด์ผ๊ธฐ๋ค์ ๐
์ง๊ธ ์ํฉ์์ ๊ผญ ์ง์ผ์ผ ํ๋ ๋ด์ฉ์ด๋ผ๊ณ ์๊ฐํ์ง ์์ง๋ง, ๊ณ์ธต ๋ถ๋ฆฌ๋ฅผ ์ผ๋์ ๋๊ณ ์ฝ๋ฉ์ ํ์
จ๋ ๊ฒ ๊ฐ์ ๋จ๊ฒจ๋ณด์์. |
@@ -0,0 +1,122 @@
+package store.config;
+
+import store.model.domain.Product;
+import store.constant.ProductType;
+import store.model.domain.Promotion;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.time.LocalDate;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public class DataInitializer {
+ public static final String REGULAR = "null";
+
+ private static DataInitializer instance;
+
+ private DataInitializer() {
+ }
+
+ public static DataInitializer getInstance() {
+ if (instance == null) {
+ instance = new DataInitializer();
+ }
+ return instance;
+ }
+
+ public ProductsData loadProducts(String filePath) throws IOException {
+ Map<ProductType, Map<String, Product>> info = new LinkedHashMap<>();
+ Map<ProductType, Map<String, Integer>> stock = new HashMap<>();
+
+ try (BufferedReader br = readFile(filePath)) {
+ processProduct(br, info, stock);
+ }
+
+ return new ProductsData(info, stock);
+ }
+
+ public Map<String, Promotion> loadPromotions(String filePath) throws IOException {
+ Map<String, Promotion> promotions = new LinkedHashMap<>();
+
+ try (BufferedReader br = readFile(filePath)) {
+ processPromotion(br, promotions);
+ }
+
+ return promotions;
+ }
+
+ private BufferedReader readFile(String filePath) throws IOException {
+ return new BufferedReader(new FileReader(filePath));
+ }
+
+ private void processProduct(BufferedReader br,
+ Map<ProductType, Map<String, Product>> info,
+ Map<ProductType, Map<String, Integer>> stock) throws IOException {
+ Map<String, Product> regularProducts = new LinkedHashMap<>();
+ Map<String, Product> promotionProducts = new LinkedHashMap<>();
+ Map<String, Integer> regularStocks = new HashMap<>();
+ Map<String, Integer> promotionStocks = new HashMap<>();
+
+ br.readLine(); // ํค๋ ์๋ต
+ String line;
+ while ((line = br.readLine()) != null) {
+ ProductData productData = parseProduct(line);
+ addProduct(productData, regularProducts, promotionProducts, regularStocks, promotionStocks);
+ }
+
+ info.put(ProductType.REGULAR, regularProducts);
+ info.put(ProductType.PROMOTION, promotionProducts);
+ stock.put(ProductType.REGULAR, regularStocks);
+ stock.put(ProductType.PROMOTION, promotionStocks);
+ }
+
+ private ProductData parseProduct(String line) {
+ String[] data = line.split(",");
+ String name = data[0];
+ int price = Integer.parseInt(data[1]);
+ int quantity = Integer.parseInt(data[2]);
+ String promotion = data[3];
+ return new ProductData(name, price, quantity, promotion);
+ }
+
+ private void addProduct(ProductData productData,
+ Map<String, Product> regularProducts,
+ Map<String, Product> promotionProducts,
+ Map<String, Integer> regularStocks,
+ Map<String, Integer> promotionStocks) {
+ Product product = new Product(productData.name(), productData.price(), productData.promotion());
+
+ if (productData.promotion().equals(REGULAR)) {
+ regularProducts.put(productData.name(), product);
+ regularStocks.put(productData.name(), productData.quantity());
+ return;
+ }
+
+ regularProducts.computeIfAbsent(productData.name(), n -> new Product(n, productData.price(), REGULAR));
+ regularStocks.putIfAbsent(productData.name(), 0);
+ promotionProducts.put(productData.name(), product);
+ promotionStocks.put(productData.name(), productData.quantity());
+ }
+
+ private void processPromotion(BufferedReader br, Map<String, Promotion> promotions) throws IOException {
+ br.readLine(); // ํค๋ ์๋ต
+ String line;
+ while ((line = br.readLine()) != null) {
+ Promotion promotion = parsePromotion(line);
+ promotions.put(promotion.getName(), promotion);
+ }
+ }
+
+ private Promotion parsePromotion(String line) {
+ String[] data = line.split(",");
+ String name = data[0];
+ int buy = Integer.parseInt(data[1]);
+ int get = Integer.parseInt(data[2]);
+ LocalDate startDate = LocalDate.parse(data[3]);
+ LocalDate endDate = LocalDate.parse(data[4]);
+ return new Promotion(name, buy, get, startDate, endDate);
+ }
+}
\ No newline at end of file | Java | DataInitializer์ ํ๋ก๋ชจ์
ํ์ฑ๊ณผ, ์ํ ํ์ฑ ๋ ๋ถ๋ถ์ด ์์ฌ ์๋ ๋๋์ด ๋ค์ด์.
์ด ๋ถ๋ถ์์๋ mdํ์ผ์ ์ฝ๋ ์ญํ ๋ง ํ๊ณ ํ๋ก๋ชจ์
์ด๋ ์ํ์ผ๋ก ๋ณํํ๋ ๊ฒ์ ๋ค๋ฅธ ๋ถ๋ถ์ผ๋ก ๋ถ๋ฆฌํ๋ ๊ฒ๋ ์ถ์ฒ๋๋ ค์! |
@@ -0,0 +1,122 @@
+package store.config;
+
+import store.model.domain.Product;
+import store.constant.ProductType;
+import store.model.domain.Promotion;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.time.LocalDate;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public class DataInitializer {
+ public static final String REGULAR = "null";
+
+ private static DataInitializer instance;
+
+ private DataInitializer() {
+ }
+
+ public static DataInitializer getInstance() {
+ if (instance == null) {
+ instance = new DataInitializer();
+ }
+ return instance;
+ }
+
+ public ProductsData loadProducts(String filePath) throws IOException {
+ Map<ProductType, Map<String, Product>> info = new LinkedHashMap<>();
+ Map<ProductType, Map<String, Integer>> stock = new HashMap<>();
+
+ try (BufferedReader br = readFile(filePath)) {
+ processProduct(br, info, stock);
+ }
+
+ return new ProductsData(info, stock);
+ }
+
+ public Map<String, Promotion> loadPromotions(String filePath) throws IOException {
+ Map<String, Promotion> promotions = new LinkedHashMap<>();
+
+ try (BufferedReader br = readFile(filePath)) {
+ processPromotion(br, promotions);
+ }
+
+ return promotions;
+ }
+
+ private BufferedReader readFile(String filePath) throws IOException {
+ return new BufferedReader(new FileReader(filePath));
+ }
+
+ private void processProduct(BufferedReader br,
+ Map<ProductType, Map<String, Product>> info,
+ Map<ProductType, Map<String, Integer>> stock) throws IOException {
+ Map<String, Product> regularProducts = new LinkedHashMap<>();
+ Map<String, Product> promotionProducts = new LinkedHashMap<>();
+ Map<String, Integer> regularStocks = new HashMap<>();
+ Map<String, Integer> promotionStocks = new HashMap<>();
+
+ br.readLine(); // ํค๋ ์๋ต
+ String line;
+ while ((line = br.readLine()) != null) {
+ ProductData productData = parseProduct(line);
+ addProduct(productData, regularProducts, promotionProducts, regularStocks, promotionStocks);
+ }
+
+ info.put(ProductType.REGULAR, regularProducts);
+ info.put(ProductType.PROMOTION, promotionProducts);
+ stock.put(ProductType.REGULAR, regularStocks);
+ stock.put(ProductType.PROMOTION, promotionStocks);
+ }
+
+ private ProductData parseProduct(String line) {
+ String[] data = line.split(",");
+ String name = data[0];
+ int price = Integer.parseInt(data[1]);
+ int quantity = Integer.parseInt(data[2]);
+ String promotion = data[3];
+ return new ProductData(name, price, quantity, promotion);
+ }
+
+ private void addProduct(ProductData productData,
+ Map<String, Product> regularProducts,
+ Map<String, Product> promotionProducts,
+ Map<String, Integer> regularStocks,
+ Map<String, Integer> promotionStocks) {
+ Product product = new Product(productData.name(), productData.price(), productData.promotion());
+
+ if (productData.promotion().equals(REGULAR)) {
+ regularProducts.put(productData.name(), product);
+ regularStocks.put(productData.name(), productData.quantity());
+ return;
+ }
+
+ regularProducts.computeIfAbsent(productData.name(), n -> new Product(n, productData.price(), REGULAR));
+ regularStocks.putIfAbsent(productData.name(), 0);
+ promotionProducts.put(productData.name(), product);
+ promotionStocks.put(productData.name(), productData.quantity());
+ }
+
+ private void processPromotion(BufferedReader br, Map<String, Promotion> promotions) throws IOException {
+ br.readLine(); // ํค๋ ์๋ต
+ String line;
+ while ((line = br.readLine()) != null) {
+ Promotion promotion = parsePromotion(line);
+ promotions.put(promotion.getName(), promotion);
+ }
+ }
+
+ private Promotion parsePromotion(String line) {
+ String[] data = line.split(",");
+ String name = data[0];
+ int buy = Integer.parseInt(data[1]);
+ int get = Integer.parseInt(data[2]);
+ LocalDate startDate = LocalDate.parse(data[3]);
+ LocalDate endDate = LocalDate.parse(data[4]);
+ return new Promotion(name, buy, get, startDate, endDate);
+ }
+}
\ No newline at end of file | Java | DataInitializer์๋ ์ํ๊ฐ ๋ฐ๋ก ์๋๋ฐ ์ฑ๊ธํค์ผ๋ก ๊ด๋ฆฌํ์๋ ์ด์ ๊ฐ ์์๊น์? |
@@ -0,0 +1,118 @@
+package store.controller;
+
+import store.Message.ErrorMessage;
+import store.model.domain.ShoppingCartCheck;
+import store.model.ReceiptTotals;
+import store.model.service.StoreService;
+import store.model.service.ReceiptCalculationService;
+import store.util.StringParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.util.List;
+import java.util.Map;
+
+public class StoreController {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final StoreService storeService;
+ private final ReceiptCalculationService receiptCalculationService;
+
+ public StoreController(InputView inputView, OutputView outputView, StoreService storeService, ReceiptCalculationService receiptCalculationService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.storeService = storeService;
+ this.receiptCalculationService = receiptCalculationService;
+ }
+
+ public void run() {
+ do {
+ initializeView();
+ Map<String, Integer> shoppingCart = askPurchase();
+ List<ShoppingCartCheck> shoppingCartChecks = processShoppingCart(shoppingCart);
+ boolean isMembership = processMembership();
+
+ ReceiptTotals totals = receiptCalculationService.calculateTotals(shoppingCartChecks, isMembership);
+ outputView.printReceipt(shoppingCartChecks, totals);
+
+ storeService.reduceProductStocks(shoppingCartChecks);
+ } while (askAdditionalPurchase());
+ }
+
+ private void initializeView() {
+ outputView.printHelloMessage();
+ outputView.printProducts(storeService.getAllProductDtos());
+ }
+
+ private Map<String, Integer> askPurchase() {
+ while (true) {
+ try {
+ String item = inputView.readItem();
+ Map<String, Integer> shoppingCart = StringParser.parseToMap(item);
+ storeService.checkStock(shoppingCart);
+ return shoppingCart;
+ } catch (IllegalArgumentException | IllegalStateException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private List<ShoppingCartCheck> processShoppingCart(Map<String, Integer> shoppingCart) {
+ List<ShoppingCartCheck> shoppingCartChecks = storeService.checkShoppingCart(shoppingCart);
+ shoppingCartChecks.forEach(this::processPromotionForItem);
+ return shoppingCartChecks;
+ }
+
+ private void processPromotionForItem(ShoppingCartCheck item) {
+ while (item.isCanReceiveAdditionalFree()) {
+ String decision = inputView.readPromotionDecision(item.getProductName());
+ if (decision.equals("Y")) {
+ item.acceptFree();
+ return;
+ }
+ if (decision.equals("N")) {
+ return;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+
+ while (item.isActivePromotion() && item.getFullPriceCount() > 0) {
+ String decision = inputView.readFullPriceDecision(item.getProductName(), item.getFullPriceCount());
+ if (decision.equals("Y")) {
+ return;
+ }
+ if (decision.equals("N")) {
+ item.rejectFullPrice();
+ return;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+ }
+
+ private boolean processMembership() {
+ while (true) {
+ String decision = inputView.readMembershipDecision();
+ if (decision.equals("Y")) {
+ return true;
+ }
+ if (decision.equals("N")) {
+ return false;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+ }
+
+ private boolean askAdditionalPurchase() {
+ while (true) {
+ String decision = inputView.readAdditionalPurchaseDecision();
+ if (decision.equals("Y")) {
+ System.out.println();
+ return true;
+ }
+ if (decision.equals("N")) {
+ return false;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+ }
+}
\ No newline at end of file | Java | do-while๋ฌธ์ผ๋ก ๋ฐ๋ณต๋ฌธ์ ๋๋ฆฌ๋๊น ๊ฐ๋
์ฑ์ด ๋ ์ข์ ๊ฒ ๊ฐ์ต๋๋ค ๐ |
@@ -0,0 +1,118 @@
+package store.controller;
+
+import store.Message.ErrorMessage;
+import store.model.domain.ShoppingCartCheck;
+import store.model.ReceiptTotals;
+import store.model.service.StoreService;
+import store.model.service.ReceiptCalculationService;
+import store.util.StringParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.util.List;
+import java.util.Map;
+
+public class StoreController {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final StoreService storeService;
+ private final ReceiptCalculationService receiptCalculationService;
+
+ public StoreController(InputView inputView, OutputView outputView, StoreService storeService, ReceiptCalculationService receiptCalculationService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.storeService = storeService;
+ this.receiptCalculationService = receiptCalculationService;
+ }
+
+ public void run() {
+ do {
+ initializeView();
+ Map<String, Integer> shoppingCart = askPurchase();
+ List<ShoppingCartCheck> shoppingCartChecks = processShoppingCart(shoppingCart);
+ boolean isMembership = processMembership();
+
+ ReceiptTotals totals = receiptCalculationService.calculateTotals(shoppingCartChecks, isMembership);
+ outputView.printReceipt(shoppingCartChecks, totals);
+
+ storeService.reduceProductStocks(shoppingCartChecks);
+ } while (askAdditionalPurchase());
+ }
+
+ private void initializeView() {
+ outputView.printHelloMessage();
+ outputView.printProducts(storeService.getAllProductDtos());
+ }
+
+ private Map<String, Integer> askPurchase() {
+ while (true) {
+ try {
+ String item = inputView.readItem();
+ Map<String, Integer> shoppingCart = StringParser.parseToMap(item);
+ storeService.checkStock(shoppingCart);
+ return shoppingCart;
+ } catch (IllegalArgumentException | IllegalStateException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private List<ShoppingCartCheck> processShoppingCart(Map<String, Integer> shoppingCart) {
+ List<ShoppingCartCheck> shoppingCartChecks = storeService.checkShoppingCart(shoppingCart);
+ shoppingCartChecks.forEach(this::processPromotionForItem);
+ return shoppingCartChecks;
+ }
+
+ private void processPromotionForItem(ShoppingCartCheck item) {
+ while (item.isCanReceiveAdditionalFree()) {
+ String decision = inputView.readPromotionDecision(item.getProductName());
+ if (decision.equals("Y")) {
+ item.acceptFree();
+ return;
+ }
+ if (decision.equals("N")) {
+ return;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+
+ while (item.isActivePromotion() && item.getFullPriceCount() > 0) {
+ String decision = inputView.readFullPriceDecision(item.getProductName(), item.getFullPriceCount());
+ if (decision.equals("Y")) {
+ return;
+ }
+ if (decision.equals("N")) {
+ item.rejectFullPrice();
+ return;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+ }
+
+ private boolean processMembership() {
+ while (true) {
+ String decision = inputView.readMembershipDecision();
+ if (decision.equals("Y")) {
+ return true;
+ }
+ if (decision.equals("N")) {
+ return false;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+ }
+
+ private boolean askAdditionalPurchase() {
+ while (true) {
+ String decision = inputView.readAdditionalPurchaseDecision();
+ if (decision.equals("Y")) {
+ System.out.println();
+ return true;
+ }
+ if (decision.equals("N")) {
+ return false;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+ }
+}
\ No newline at end of file | Java | ํด๋น ํจ์์ while๋ฌธ ๋๊ฐ๊ฐ ๋๊ณ ์๋๋ฐ ๋ถ๋ฆฌ์์ผ์ ๋ฏธ์
์๊ตฌ์ฌํญ๋ ์ถฉ์กฑํ๊ณ ์ฑ
์ ๋ถ๋ฆฌ๋ ๋ ์ํ ์ ์์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,87 @@
+package store.view;
+
+import store.dto.ProductWithStockDto;
+import store.model.domain.ShoppingCartCheck;
+import store.model.ReceiptTotals;
+import store.constant.OutputFormats;
+import store.constant.OutputMessages;
+import store.constant.ReceiptLabels;
+
+import java.util.List;
+
+public class OutputView {
+ private static final String REGULAR = "null";
+
+ public void printHelloMessage() {
+ System.out.println(OutputMessages.WELCOME_MESSAGE);
+ }
+
+ public void printProducts(List<ProductWithStockDto> products) {
+ System.out.println(OutputMessages.CURRENT_PRODUCTS_MESSAGE);
+ products.forEach(this::printProduct);
+ }
+
+ public void printReceipt(List<ShoppingCartCheck> shoppingCartChecks, ReceiptTotals totals) {
+ printReceiptHeader();
+ printReceiptItems(shoppingCartChecks);
+ printReceiptGiftItems(shoppingCartChecks);
+ printReceiptTotals(totals);
+ }
+
+ private void printProduct(ProductWithStockDto product) {
+ String promotion = product.promotion();
+ if (promotion.equals(REGULAR)) {
+ promotion = OutputMessages.EMPTY_STRING;
+ }
+ if (product.stock() == 0) {
+ System.out.printf(OutputFormats.PRODUCT_OUT_OF_STOCK_FORMAT, product.name(), product.price(), OutputMessages.NO_STOCK, promotion);
+ return;
+ }
+ System.out.printf(OutputFormats.PRODUCT_IN_STOCK_FORMAT, product.name(), product.price(), product.stock(), promotion);
+ }
+
+ private void printReceiptHeader() {
+ System.out.println(ReceiptLabels.HEADER);
+ System.out.printf(OutputFormats.HEADER_FORMAT, ReceiptLabels.PRODUCT_NAME, ReceiptLabels.COUNT, ReceiptLabels.PRICE);
+ }
+
+ private void printReceiptItems(List<ShoppingCartCheck> shoppingCartChecks) {
+ for (ShoppingCartCheck dto : shoppingCartChecks) {
+ int price = dto.getProductPrice() * dto.getRequestCount();
+ System.out.printf(OutputFormats.ITEM_FORMAT, dto.getProductName(), dto.getRequestCount(), price);
+ }
+ }
+
+ private void printReceiptGiftItems(List<ShoppingCartCheck> shoppingCartChecks) {
+ List<ShoppingCartCheck> giftItems = shoppingCartChecks.stream()
+ .filter(dto -> dto.getFreeCount() > 0)
+ .filter(ShoppingCartCheck::isActivePromotion)
+ .toList();
+
+ if (!giftItems.isEmpty()) {
+ System.out.println(ReceiptLabels.GIFT_HEADER);
+ for (ShoppingCartCheck dto : giftItems) {
+ System.out.printf(OutputFormats.GIFT_ITEM_FORMAT, dto.getProductName(), dto.getFreeCount());
+ }
+ }
+ }
+
+ private void printReceiptTotals(ReceiptTotals totals) {
+ System.out.println(ReceiptLabels.FOOTER);
+ System.out.printf(OutputFormats.ITEM_FORMAT, ReceiptLabels.TOTAL_LABEL, totals.totalCount, totals.totalPrice);
+
+ String giftPriceDisplay = formatDiscount(totals.giftPrice);
+ System.out.printf(OutputFormats.DISCOUNT_FORMAT, ReceiptLabels.EVENT_DISCOUNT_LABEL, giftPriceDisplay);
+
+ String membershipPriceDisplay = formatDiscount(totals.membershipPrice);
+ System.out.printf(OutputFormats.DISCOUNT_FORMAT, ReceiptLabels.MEMBERSHIP_DISCOUNT_LABEL, membershipPriceDisplay);
+
+ int finalAmount = totals.totalPrice + totals.giftPrice + totals.membershipPrice;
+ System.out.printf(OutputFormats.TOTAL_FORMAT, ReceiptLabels.FINAL_AMOUNT_LABEL, finalAmount);
+ }
+
+ private String formatDiscount(int discount) {
+ if (discount == 0) return "-0";
+ return String.format("%,d", discount);
+ }
+}
\ No newline at end of file | Java | ์ถ์ํ๊ฐ ์์์ฆ ์ถ๋ ฅ์ ๋จ๊ณ์ ๋ง์ถ์ด ์ ๋์ด์๋ ๊ฒ ๊ฐ์์. ๐ |
@@ -0,0 +1,27 @@
+package store.util;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.Stream;
+
+public class StringParser {
+
+ private StringParser() {
+ }
+
+ public static Map<String, Integer> parseToMap(String input) {
+ Map<String, Integer> result = new HashMap<>();
+
+ Stream.of(input.split(","))
+ .forEach(item -> {
+ item = item.replaceAll("[\\[\\]]", "");
+ String[] nameAndQuantity = item.split("-");
+ if (nameAndQuantity.length != 2) {
+ throw new IllegalArgumentException("์ํ๋ช
๊ณผ ์๋์ ์ ํํ ์
๋ ฅํด ์ฃผ์ธ์.");
+ }
+ result.put(nameAndQuantity[0], Integer.valueOf(nameAndQuantity[1]));
+ });
+
+ return result;
+ }
+}
\ No newline at end of file | Java | key - value ์์ด ๋ง๋์ง ๊ฒ์ฌํ๋ ๋ถ๋ถ ๋ํ ํ๋์ ๋ฉ์๋๋ก ๋ถ๋ฆฌํ ์ ์์ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,70 @@
+package store.model.repository;
+
+import store.Message.ErrorMessage;
+import store.config.DataInitializer;
+import store.config.ProductsData;
+import store.model.domain.Product;
+import store.constant.ProductType;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+public class ProductRepository {
+ public static final String DEFAULT_PRODUCT_FILE_PATH = "src/main/resources/products.md";
+
+ private final Map<ProductType, Map<String, Product>> info = new LinkedHashMap<>();
+ private final Map<ProductType, Map<String, Integer>> stock = new HashMap<>();
+
+ public ProductRepository(String filePath) {
+ DataInitializer initializer = DataInitializer.getInstance();
+ try {
+ ProductsData productsData = initializer.loadProducts(filePath);
+ this.info.putAll(productsData.info());
+ this.stock.putAll(productsData.stock());
+ } catch (IOException e) {
+ throw new RuntimeException(ErrorMessage.FILE_ERROR.getMessage(filePath));
+ }
+ }
+
+ public ProductRepository() {
+ this(DEFAULT_PRODUCT_FILE_PATH);
+ }
+
+ public List<Product> findAllInfo() {
+ return info.values().stream()
+ .flatMap(innerMap -> innerMap.values().stream())
+ .toList();
+ }
+
+ public Product findInfo(String name, ProductType productType) {
+ Map<String, Product> typeInfo = info.get(productType);
+ return typeInfo.getOrDefault(name, null);
+ }
+
+ public int findStock(String name, ProductType productType) {
+ Map<String, Integer> typeStock = stock.get(productType);
+ return typeStock.getOrDefault(name, 0);
+ }
+
+ public boolean reduceStock(String name, ProductType productType, int quantity) {
+ Map<String, Integer> typeStocks = stock.get(productType);
+ checkStock(name, typeStocks);
+
+ int currentStock = typeStocks.get(name);
+ if (currentStock < quantity) {
+ return false;
+ }
+
+ typeStocks.put(name, currentStock - quantity);
+ return true;
+ }
+
+ private static void checkStock(String name, Map<String, Integer> stock) {
+ if (stock == null || !stock.containsKey(name)) {
+ throw new IllegalStateException(ErrorMessage.NON_EXISTENT_PRODUCT.getMessage());
+ }
+ }
+}
\ No newline at end of file | Java | info๋ผ๋ ๋ค์ด๋ฐ์์ ์ด๋ค ์ ๋ณด๊ฐ ๋ค์ด์๋์ง ์ง๊ด์ ์ผ๋ก ๋ค๊ฐ์ค์ง ์๋ ๊ฒ ๊ฐ์ต๋๋ค! |
@@ -0,0 +1,70 @@
+package store.model.repository;
+
+import store.Message.ErrorMessage;
+import store.config.DataInitializer;
+import store.config.ProductsData;
+import store.model.domain.Product;
+import store.constant.ProductType;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+public class ProductRepository {
+ public static final String DEFAULT_PRODUCT_FILE_PATH = "src/main/resources/products.md";
+
+ private final Map<ProductType, Map<String, Product>> info = new LinkedHashMap<>();
+ private final Map<ProductType, Map<String, Integer>> stock = new HashMap<>();
+
+ public ProductRepository(String filePath) {
+ DataInitializer initializer = DataInitializer.getInstance();
+ try {
+ ProductsData productsData = initializer.loadProducts(filePath);
+ this.info.putAll(productsData.info());
+ this.stock.putAll(productsData.stock());
+ } catch (IOException e) {
+ throw new RuntimeException(ErrorMessage.FILE_ERROR.getMessage(filePath));
+ }
+ }
+
+ public ProductRepository() {
+ this(DEFAULT_PRODUCT_FILE_PATH);
+ }
+
+ public List<Product> findAllInfo() {
+ return info.values().stream()
+ .flatMap(innerMap -> innerMap.values().stream())
+ .toList();
+ }
+
+ public Product findInfo(String name, ProductType productType) {
+ Map<String, Product> typeInfo = info.get(productType);
+ return typeInfo.getOrDefault(name, null);
+ }
+
+ public int findStock(String name, ProductType productType) {
+ Map<String, Integer> typeStock = stock.get(productType);
+ return typeStock.getOrDefault(name, 0);
+ }
+
+ public boolean reduceStock(String name, ProductType productType, int quantity) {
+ Map<String, Integer> typeStocks = stock.get(productType);
+ checkStock(name, typeStocks);
+
+ int currentStock = typeStocks.get(name);
+ if (currentStock < quantity) {
+ return false;
+ }
+
+ typeStocks.put(name, currentStock - quantity);
+ return true;
+ }
+
+ private static void checkStock(String name, Map<String, Integer> stock) {
+ if (stock == null || !stock.containsKey(name)) {
+ throw new IllegalStateException(ErrorMessage.NON_EXISTENT_PRODUCT.getMessage());
+ }
+ }
+}
\ No newline at end of file | Java | ์ ๋ ์ด๋ฒ์๋ ์ฌ์ฉํ์ง ์์์ง๋ง Repository๋ฅผ ๊ตฌํํ์
์ ์๊ฒฌ ํ๋ ๋๋ฆฌ๋ฉด `Optional<Product>` ๋ก ๋ฆฌํดํ๋ ๊ฒ๋ ์ข์ผ์
จ์ ๊ฒ ๊ฐ์ต๋๋ค ๐ |
@@ -0,0 +1,118 @@
+package store.controller;
+
+import store.Message.ErrorMessage;
+import store.model.domain.ShoppingCartCheck;
+import store.model.ReceiptTotals;
+import store.model.service.StoreService;
+import store.model.service.ReceiptCalculationService;
+import store.util.StringParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.util.List;
+import java.util.Map;
+
+public class StoreController {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final StoreService storeService;
+ private final ReceiptCalculationService receiptCalculationService;
+
+ public StoreController(InputView inputView, OutputView outputView, StoreService storeService, ReceiptCalculationService receiptCalculationService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.storeService = storeService;
+ this.receiptCalculationService = receiptCalculationService;
+ }
+
+ public void run() {
+ do {
+ initializeView();
+ Map<String, Integer> shoppingCart = askPurchase();
+ List<ShoppingCartCheck> shoppingCartChecks = processShoppingCart(shoppingCart);
+ boolean isMembership = processMembership();
+
+ ReceiptTotals totals = receiptCalculationService.calculateTotals(shoppingCartChecks, isMembership);
+ outputView.printReceipt(shoppingCartChecks, totals);
+
+ storeService.reduceProductStocks(shoppingCartChecks);
+ } while (askAdditionalPurchase());
+ }
+
+ private void initializeView() {
+ outputView.printHelloMessage();
+ outputView.printProducts(storeService.getAllProductDtos());
+ }
+
+ private Map<String, Integer> askPurchase() {
+ while (true) {
+ try {
+ String item = inputView.readItem();
+ Map<String, Integer> shoppingCart = StringParser.parseToMap(item);
+ storeService.checkStock(shoppingCart);
+ return shoppingCart;
+ } catch (IllegalArgumentException | IllegalStateException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private List<ShoppingCartCheck> processShoppingCart(Map<String, Integer> shoppingCart) {
+ List<ShoppingCartCheck> shoppingCartChecks = storeService.checkShoppingCart(shoppingCart);
+ shoppingCartChecks.forEach(this::processPromotionForItem);
+ return shoppingCartChecks;
+ }
+
+ private void processPromotionForItem(ShoppingCartCheck item) {
+ while (item.isCanReceiveAdditionalFree()) {
+ String decision = inputView.readPromotionDecision(item.getProductName());
+ if (decision.equals("Y")) {
+ item.acceptFree();
+ return;
+ }
+ if (decision.equals("N")) {
+ return;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+
+ while (item.isActivePromotion() && item.getFullPriceCount() > 0) {
+ String decision = inputView.readFullPriceDecision(item.getProductName(), item.getFullPriceCount());
+ if (decision.equals("Y")) {
+ return;
+ }
+ if (decision.equals("N")) {
+ item.rejectFullPrice();
+ return;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+ }
+
+ private boolean processMembership() {
+ while (true) {
+ String decision = inputView.readMembershipDecision();
+ if (decision.equals("Y")) {
+ return true;
+ }
+ if (decision.equals("N")) {
+ return false;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+ }
+
+ private boolean askAdditionalPurchase() {
+ while (true) {
+ String decision = inputView.readAdditionalPurchaseDecision();
+ if (decision.equals("Y")) {
+ System.out.println();
+ return true;
+ }
+ if (decision.equals("N")) {
+ return false;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+ }
+}
\ No newline at end of file | Java | ์... ์ด๊ฑฐ ๋ฆฌํฉํ ๋งํ๊ณ ํธ์๋ฅผ ์ํ๋ค์. 10์ค๋ณด๋ค ๋๋ฌด ๊ธธ์ด์ ๋์ ํ ๋์๋ ๋ถ๋ถ์ธ๋ฐ! |
@@ -0,0 +1,118 @@
+package store.controller;
+
+import store.Message.ErrorMessage;
+import store.model.domain.ShoppingCartCheck;
+import store.model.ReceiptTotals;
+import store.model.service.StoreService;
+import store.model.service.ReceiptCalculationService;
+import store.util.StringParser;
+import store.view.InputView;
+import store.view.OutputView;
+
+import java.util.List;
+import java.util.Map;
+
+public class StoreController {
+ private final InputView inputView;
+ private final OutputView outputView;
+ private final StoreService storeService;
+ private final ReceiptCalculationService receiptCalculationService;
+
+ public StoreController(InputView inputView, OutputView outputView, StoreService storeService, ReceiptCalculationService receiptCalculationService) {
+ this.inputView = inputView;
+ this.outputView = outputView;
+ this.storeService = storeService;
+ this.receiptCalculationService = receiptCalculationService;
+ }
+
+ public void run() {
+ do {
+ initializeView();
+ Map<String, Integer> shoppingCart = askPurchase();
+ List<ShoppingCartCheck> shoppingCartChecks = processShoppingCart(shoppingCart);
+ boolean isMembership = processMembership();
+
+ ReceiptTotals totals = receiptCalculationService.calculateTotals(shoppingCartChecks, isMembership);
+ outputView.printReceipt(shoppingCartChecks, totals);
+
+ storeService.reduceProductStocks(shoppingCartChecks);
+ } while (askAdditionalPurchase());
+ }
+
+ private void initializeView() {
+ outputView.printHelloMessage();
+ outputView.printProducts(storeService.getAllProductDtos());
+ }
+
+ private Map<String, Integer> askPurchase() {
+ while (true) {
+ try {
+ String item = inputView.readItem();
+ Map<String, Integer> shoppingCart = StringParser.parseToMap(item);
+ storeService.checkStock(shoppingCart);
+ return shoppingCart;
+ } catch (IllegalArgumentException | IllegalStateException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+ }
+
+ private List<ShoppingCartCheck> processShoppingCart(Map<String, Integer> shoppingCart) {
+ List<ShoppingCartCheck> shoppingCartChecks = storeService.checkShoppingCart(shoppingCart);
+ shoppingCartChecks.forEach(this::processPromotionForItem);
+ return shoppingCartChecks;
+ }
+
+ private void processPromotionForItem(ShoppingCartCheck item) {
+ while (item.isCanReceiveAdditionalFree()) {
+ String decision = inputView.readPromotionDecision(item.getProductName());
+ if (decision.equals("Y")) {
+ item.acceptFree();
+ return;
+ }
+ if (decision.equals("N")) {
+ return;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+
+ while (item.isActivePromotion() && item.getFullPriceCount() > 0) {
+ String decision = inputView.readFullPriceDecision(item.getProductName(), item.getFullPriceCount());
+ if (decision.equals("Y")) {
+ return;
+ }
+ if (decision.equals("N")) {
+ item.rejectFullPrice();
+ return;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+ }
+
+ private boolean processMembership() {
+ while (true) {
+ String decision = inputView.readMembershipDecision();
+ if (decision.equals("Y")) {
+ return true;
+ }
+ if (decision.equals("N")) {
+ return false;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+ }
+
+ private boolean askAdditionalPurchase() {
+ while (true) {
+ String decision = inputView.readAdditionalPurchaseDecision();
+ if (decision.equals("Y")) {
+ System.out.println();
+ return true;
+ }
+ if (decision.equals("N")) {
+ return false;
+ }
+ System.out.println(ErrorMessage.GENERIC_ERROR.getMessage());
+ }
+ }
+}
\ No newline at end of file | Java | ๊ฐ์ฌํฉ๋๋ค! |
@@ -0,0 +1,122 @@
+package store.config;
+
+import store.model.domain.Product;
+import store.constant.ProductType;
+import store.model.domain.Promotion;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.time.LocalDate;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public class DataInitializer {
+ public static final String REGULAR = "null";
+
+ private static DataInitializer instance;
+
+ private DataInitializer() {
+ }
+
+ public static DataInitializer getInstance() {
+ if (instance == null) {
+ instance = new DataInitializer();
+ }
+ return instance;
+ }
+
+ public ProductsData loadProducts(String filePath) throws IOException {
+ Map<ProductType, Map<String, Product>> info = new LinkedHashMap<>();
+ Map<ProductType, Map<String, Integer>> stock = new HashMap<>();
+
+ try (BufferedReader br = readFile(filePath)) {
+ processProduct(br, info, stock);
+ }
+
+ return new ProductsData(info, stock);
+ }
+
+ public Map<String, Promotion> loadPromotions(String filePath) throws IOException {
+ Map<String, Promotion> promotions = new LinkedHashMap<>();
+
+ try (BufferedReader br = readFile(filePath)) {
+ processPromotion(br, promotions);
+ }
+
+ return promotions;
+ }
+
+ private BufferedReader readFile(String filePath) throws IOException {
+ return new BufferedReader(new FileReader(filePath));
+ }
+
+ private void processProduct(BufferedReader br,
+ Map<ProductType, Map<String, Product>> info,
+ Map<ProductType, Map<String, Integer>> stock) throws IOException {
+ Map<String, Product> regularProducts = new LinkedHashMap<>();
+ Map<String, Product> promotionProducts = new LinkedHashMap<>();
+ Map<String, Integer> regularStocks = new HashMap<>();
+ Map<String, Integer> promotionStocks = new HashMap<>();
+
+ br.readLine(); // ํค๋ ์๋ต
+ String line;
+ while ((line = br.readLine()) != null) {
+ ProductData productData = parseProduct(line);
+ addProduct(productData, regularProducts, promotionProducts, regularStocks, promotionStocks);
+ }
+
+ info.put(ProductType.REGULAR, regularProducts);
+ info.put(ProductType.PROMOTION, promotionProducts);
+ stock.put(ProductType.REGULAR, regularStocks);
+ stock.put(ProductType.PROMOTION, promotionStocks);
+ }
+
+ private ProductData parseProduct(String line) {
+ String[] data = line.split(",");
+ String name = data[0];
+ int price = Integer.parseInt(data[1]);
+ int quantity = Integer.parseInt(data[2]);
+ String promotion = data[3];
+ return new ProductData(name, price, quantity, promotion);
+ }
+
+ private void addProduct(ProductData productData,
+ Map<String, Product> regularProducts,
+ Map<String, Product> promotionProducts,
+ Map<String, Integer> regularStocks,
+ Map<String, Integer> promotionStocks) {
+ Product product = new Product(productData.name(), productData.price(), productData.promotion());
+
+ if (productData.promotion().equals(REGULAR)) {
+ regularProducts.put(productData.name(), product);
+ regularStocks.put(productData.name(), productData.quantity());
+ return;
+ }
+
+ regularProducts.computeIfAbsent(productData.name(), n -> new Product(n, productData.price(), REGULAR));
+ regularStocks.putIfAbsent(productData.name(), 0);
+ promotionProducts.put(productData.name(), product);
+ promotionStocks.put(productData.name(), productData.quantity());
+ }
+
+ private void processPromotion(BufferedReader br, Map<String, Promotion> promotions) throws IOException {
+ br.readLine(); // ํค๋ ์๋ต
+ String line;
+ while ((line = br.readLine()) != null) {
+ Promotion promotion = parsePromotion(line);
+ promotions.put(promotion.getName(), promotion);
+ }
+ }
+
+ private Promotion parsePromotion(String line) {
+ String[] data = line.split(",");
+ String name = data[0];
+ int buy = Integer.parseInt(data[1]);
+ int get = Integer.parseInt(data[2]);
+ LocalDate startDate = LocalDate.parse(data[3]);
+ LocalDate endDate = LocalDate.parse(data[4]);
+ return new Promotion(name, buy, get, startDate, endDate);
+ }
+}
\ No newline at end of file | Java | ๊ฐ์ฌํฉ๋๋ค. ๋ฐ์ดํฐ ๋ฆฌ๋์ ํ๋ก์ธ์? ์ด๋์
๋ผ์ด์ ๋ก ๊ตฌ๋ถํ ์ ์์ ๊ฒ ๊ฐ์์! |
@@ -0,0 +1,122 @@
+package store.config;
+
+import store.model.domain.Product;
+import store.constant.ProductType;
+import store.model.domain.Promotion;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.time.LocalDate;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public class DataInitializer {
+ public static final String REGULAR = "null";
+
+ private static DataInitializer instance;
+
+ private DataInitializer() {
+ }
+
+ public static DataInitializer getInstance() {
+ if (instance == null) {
+ instance = new DataInitializer();
+ }
+ return instance;
+ }
+
+ public ProductsData loadProducts(String filePath) throws IOException {
+ Map<ProductType, Map<String, Product>> info = new LinkedHashMap<>();
+ Map<ProductType, Map<String, Integer>> stock = new HashMap<>();
+
+ try (BufferedReader br = readFile(filePath)) {
+ processProduct(br, info, stock);
+ }
+
+ return new ProductsData(info, stock);
+ }
+
+ public Map<String, Promotion> loadPromotions(String filePath) throws IOException {
+ Map<String, Promotion> promotions = new LinkedHashMap<>();
+
+ try (BufferedReader br = readFile(filePath)) {
+ processPromotion(br, promotions);
+ }
+
+ return promotions;
+ }
+
+ private BufferedReader readFile(String filePath) throws IOException {
+ return new BufferedReader(new FileReader(filePath));
+ }
+
+ private void processProduct(BufferedReader br,
+ Map<ProductType, Map<String, Product>> info,
+ Map<ProductType, Map<String, Integer>> stock) throws IOException {
+ Map<String, Product> regularProducts = new LinkedHashMap<>();
+ Map<String, Product> promotionProducts = new LinkedHashMap<>();
+ Map<String, Integer> regularStocks = new HashMap<>();
+ Map<String, Integer> promotionStocks = new HashMap<>();
+
+ br.readLine(); // ํค๋ ์๋ต
+ String line;
+ while ((line = br.readLine()) != null) {
+ ProductData productData = parseProduct(line);
+ addProduct(productData, regularProducts, promotionProducts, regularStocks, promotionStocks);
+ }
+
+ info.put(ProductType.REGULAR, regularProducts);
+ info.put(ProductType.PROMOTION, promotionProducts);
+ stock.put(ProductType.REGULAR, regularStocks);
+ stock.put(ProductType.PROMOTION, promotionStocks);
+ }
+
+ private ProductData parseProduct(String line) {
+ String[] data = line.split(",");
+ String name = data[0];
+ int price = Integer.parseInt(data[1]);
+ int quantity = Integer.parseInt(data[2]);
+ String promotion = data[3];
+ return new ProductData(name, price, quantity, promotion);
+ }
+
+ private void addProduct(ProductData productData,
+ Map<String, Product> regularProducts,
+ Map<String, Product> promotionProducts,
+ Map<String, Integer> regularStocks,
+ Map<String, Integer> promotionStocks) {
+ Product product = new Product(productData.name(), productData.price(), productData.promotion());
+
+ if (productData.promotion().equals(REGULAR)) {
+ regularProducts.put(productData.name(), product);
+ regularStocks.put(productData.name(), productData.quantity());
+ return;
+ }
+
+ regularProducts.computeIfAbsent(productData.name(), n -> new Product(n, productData.price(), REGULAR));
+ regularStocks.putIfAbsent(productData.name(), 0);
+ promotionProducts.put(productData.name(), product);
+ promotionStocks.put(productData.name(), productData.quantity());
+ }
+
+ private void processPromotion(BufferedReader br, Map<String, Promotion> promotions) throws IOException {
+ br.readLine(); // ํค๋ ์๋ต
+ String line;
+ while ((line = br.readLine()) != null) {
+ Promotion promotion = parsePromotion(line);
+ promotions.put(promotion.getName(), promotion);
+ }
+ }
+
+ private Promotion parsePromotion(String line) {
+ String[] data = line.split(",");
+ String name = data[0];
+ int buy = Integer.parseInt(data[1]);
+ int get = Integer.parseInt(data[2]);
+ LocalDate startDate = LocalDate.parse(data[3]);
+ LocalDate endDate = LocalDate.parse(data[4]);
+ return new Promotion(name, buy, get, startDate, endDate);
+ }
+}
\ No newline at end of file | Java | ํ์ผ์ ์ฝ๋ ํด๋์ค์ด๊ธฐ ๋๋ฌธ์ ์์ ์ฌ์ฉ์ ๋ฌธ์ ๊ฐ ์์๊น ๊ฑฑ์ ๋์ด ์ฑ๊ธํค์ผ๋ก ๋ง๋ค์์ต๋๋ค.
์ง๋ฌธ์ ๋ํด ์๊ฐํด๋ณด๋ ์์ ํด์ ๋ฅผ ๋ช
ํํ ๊ด๋ฆฌํ๋ ๊ฒ์ด ๋ ์ข์์ ๊ฒ ๊ฐ๋ค๋ ์๊ฐ์ด ๋ค๊ธฐ๋ ํ๋ค์ |
@@ -0,0 +1,27 @@
+package store.util;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.Stream;
+
+public class StringParser {
+
+ private StringParser() {
+ }
+
+ public static Map<String, Integer> parseToMap(String input) {
+ Map<String, Integer> result = new HashMap<>();
+
+ Stream.of(input.split(","))
+ .forEach(item -> {
+ item = item.replaceAll("[\\[\\]]", "");
+ String[] nameAndQuantity = item.split("-");
+ if (nameAndQuantity.length != 2) {
+ throw new IllegalArgumentException("์ํ๋ช
๊ณผ ์๋์ ์ ํํ ์
๋ ฅํด ์ฃผ์ธ์.");
+ }
+ result.put(nameAndQuantity[0], Integer.valueOf(nameAndQuantity[1]));
+ });
+
+ return result;
+ }
+}
\ No newline at end of file | Java | ์ ๊ฐ ๋ด๋ ๋ถํธํ ์ฝ๋๋ค์ ใ
ใ
. ๊ฐ์ฌํฉ๋๋ค |
@@ -0,0 +1,70 @@
+package store.model.repository;
+
+import store.Message.ErrorMessage;
+import store.config.DataInitializer;
+import store.config.ProductsData;
+import store.model.domain.Product;
+import store.constant.ProductType;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+public class ProductRepository {
+ public static final String DEFAULT_PRODUCT_FILE_PATH = "src/main/resources/products.md";
+
+ private final Map<ProductType, Map<String, Product>> info = new LinkedHashMap<>();
+ private final Map<ProductType, Map<String, Integer>> stock = new HashMap<>();
+
+ public ProductRepository(String filePath) {
+ DataInitializer initializer = DataInitializer.getInstance();
+ try {
+ ProductsData productsData = initializer.loadProducts(filePath);
+ this.info.putAll(productsData.info());
+ this.stock.putAll(productsData.stock());
+ } catch (IOException e) {
+ throw new RuntimeException(ErrorMessage.FILE_ERROR.getMessage(filePath));
+ }
+ }
+
+ public ProductRepository() {
+ this(DEFAULT_PRODUCT_FILE_PATH);
+ }
+
+ public List<Product> findAllInfo() {
+ return info.values().stream()
+ .flatMap(innerMap -> innerMap.values().stream())
+ .toList();
+ }
+
+ public Product findInfo(String name, ProductType productType) {
+ Map<String, Product> typeInfo = info.get(productType);
+ return typeInfo.getOrDefault(name, null);
+ }
+
+ public int findStock(String name, ProductType productType) {
+ Map<String, Integer> typeStock = stock.get(productType);
+ return typeStock.getOrDefault(name, 0);
+ }
+
+ public boolean reduceStock(String name, ProductType productType, int quantity) {
+ Map<String, Integer> typeStocks = stock.get(productType);
+ checkStock(name, typeStocks);
+
+ int currentStock = typeStocks.get(name);
+ if (currentStock < quantity) {
+ return false;
+ }
+
+ typeStocks.put(name, currentStock - quantity);
+ return true;
+ }
+
+ private static void checkStock(String name, Map<String, Integer> stock) {
+ if (stock == null || !stock.containsKey(name)) {
+ throw new IllegalStateException(ErrorMessage.NON_EXISTENT_PRODUCT.getMessage());
+ }
+ }
+}
\ No newline at end of file | Java | productInfo ์์ง๋ง ProductRepository ๋ด๋ถ๋ผ์ info๋ก ๋ณ๊ฒฝํ์ต๋๋ค. ํน์ description๊ณผ ๊ฐ์ ๋ช
๋ช
์ด ๋ ์ข์์๊น์? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.