code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,79 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.core.context.SecurityContext; +import nextstep.security.core.context.SecurityContextHolder; +import nextstep.security.exception.AuthenticationException; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +public abstract class AbstractAuthProcessingFilter extends OncePerRequestFilter { + private final AuthenticationManager authenticationManager; + + protected AbstractAuthProcessingFilter(final AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + @Override + protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException { + if (!match(request)) { + filterChain.doFilter(request, response); + return; + } + + if (isAlreadyAuthenticated()) { + filterChain.doFilter(request, response); + return; + } + + Authentication authRequest = makeAuthentication(request); + + Authentication authentication = authenticate(authRequest); + + saveAuthentication(request, response, authentication); + + successAuthentication(request, response, filterChain); + + if (!shouldContinueFilterChain()) { + return; + } + + doFilter(request, response, filterChain); + } + + private static boolean isAlreadyAuthenticated() { + return SecurityContextHolder.getContext().getAuthentication() != null; + } + + private Authentication authenticate(final Authentication authRequest) { + Authentication authentication = this.authenticationManager.authenticate(authRequest); + if (!authentication.isAuthenticated()) { + throw new AuthenticationException(); + } + + return authentication; + } + + abstract boolean match(final HttpServletRequest request); + + private void saveAuthentication(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) { + SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); + securityContext.setAuthentication(authentication); + SecurityContextHolder.setContext(securityContext); + } + + abstract Authentication makeAuthentication(final HttpServletRequest request); + + protected abstract void successAuthentication(final HttpServletRequest request, final HttpServletResponse response, + final FilterChain filterChain) throws ServletException, IOException; + + protected boolean shouldContinueFilterChain() { + return true; + } +}
Java
๊ธฐ์กด์˜ ํžŒํŠธ ์ฝ”๋“œ๋ฅผ ๊ผญ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•˜์ง€ ์•Š์œผ์…”๋„ ๋˜๊ณ , ๋ฌธ์ œ๊ฐ€ ์žˆ๋‹ค๋ฉด ์ˆ˜์ •ํ•˜์…”๋„ ๋ฉ๋‹ˆ๋‹ค ใ…Žใ…Ž Filter์˜ ๊ตฌ์กฐ๋Š” ๋””์ž์ธํŒจํ„ด ์ค‘ ํ•˜๋‚˜์ธ ์—ฐ์‡„ ์ฑ…์ž„ ํŒจํ„ด์˜ ํ˜•ํƒœ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š”๋ฐ์š”. Filter๋Š” ๋‹ค๋ฅธ ํ•„ํ„ฐ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ๋ชจ๋ฅด๋Š” ์ƒํƒœ์—์„œ ์ž์‹ ์˜ ์—ญํ• ๋งŒ ์ˆ˜ํ–‰ํ•˜๊ณ , ๋ฌธ์ œ๊ฐ€ ์—†๋‹ค๋ฉด ๋ฐ˜๋“œ์‹œ ๋‹ค์Œ ํ•„ํ„ฐ๋กœ ์œ„์ž„ํ•˜๋Š” ๊ฒƒ์ด ์ •ํ•ด์ง„ ๊ทœ์น™์„ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๋งŒ์•ฝ ๊ตฌํ˜„ ๋ฐฉ์‹์— ๋”ฐ๋ผ doFilter() ํ˜ธ์ถœ ์—ฌ๋ถ€๊ฐ€ ๋‹ฌ๋ผ์ง„๋‹ค๋ฉด, ์„ค๊ณ„๋ฅผ ๋‹ค์‹œ ๊ณ ๋ฏผํ•ด๋ณผ ํ•„์š”๊ฐ€ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,79 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.authentication.UsernamePasswordAuthenticationToken; +import nextstep.security.core.context.SecurityContext; +import nextstep.security.core.context.SecurityContextHolder; +import nextstep.security.exception.AuthenticationException; +import nextstep.security.util.Base64Convertor; + +import java.io.IOException; + +public class BasicAuthFilter extends AbstractAuthProcessingFilter { + public static final String BASIC_HEADER_COLON = ":"; + public static final String BASIC_HEADER_COMMA = " "; + public static final String BASIC_HEADER_PREFIX = "Basic "; + public static final String AUTHORIZATION = "Authorization"; + + public BasicAuthFilter(final AuthenticationManager authenticationManager) { + super(authenticationManager); + } + + @Override + boolean match(final HttpServletRequest request) { + return existAuthorizationHeader(request); + } + + private boolean existAuthorizationHeader(final HttpServletRequest request) { + return request.getHeader(AUTHORIZATION) != null; + } + + @Override + public Authentication makeAuthentication(final HttpServletRequest request) { + String authorizationHeader = request.getHeader(AUTHORIZATION); + + if (isValidBasicAuthHeader(authorizationHeader)) { + throw new AuthenticationException(); + } + + String credentials = extractCredentials(authorizationHeader); + String[] usernameAndPassword = parseCredentials(credentials); + + return UsernamePasswordAuthenticationToken.unauthenticated(usernameAndPassword[0], usernameAndPassword[1]); + } + + private boolean isValidBasicAuthHeader(final String authorizationHeader) { + return authorizationHeader == null || !authorizationHeader.startsWith(BASIC_HEADER_PREFIX); + } + + private String extractCredentials(String authorizationHeader) { + String[] parts = authorizationHeader.split(BASIC_HEADER_COMMA); + if (parts.length != 2) { + throw new AuthenticationException(); + } + + return Base64Convertor.decode(parts[1]); + } + + private String[] parseCredentials(String decodedString) { + String[] usernameAndPassword = decodedString.split(BASIC_HEADER_COLON); + if (usernameAndPassword.length != 2) { + throw new AuthenticationException(); + } + + return usernameAndPassword; + } + + @Override + protected void successAuthentication(final HttpServletRequest request, final HttpServletResponse response, + final FilterChain filterChain) throws ServletException, IOException { + final SecurityContext context = SecurityContextHolder.getContext(); + final Authentication authentication = context.getAuthentication(); + authentication.getAuthorities().clear(); + } +}
Java
```suggestion authentication.getAuthorities().add(Role.ADMIN); filterChain.doFilter(request, response); ``` > SecurityContextRepository์˜ ๊ตฌํ˜„์ฒด๋ฅผ Filter์—์„œ ์ฃผ์ž…๋ฐ›์•„ ์ฒ˜๋ฆฌํ•˜๊ฒŒ ๊ตฌํ˜„ํ•ด์ฃผ์…จ๋„ค์š”! > ์Šคํ”„๋ง์€ ๋‹ค๋ฅธ Filter์—์„œ SecurityContextRepository์˜ ๋‚ด๋ถ€ ๊ตฌํ˜„์„ ๋ชฐ๋ผ๋„ SecurityContextHolder.getContext()๋ฅผ ํ†ตํ•ด ์ธ์ฆ ์ •๋ณด๋ฅผ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ์„ค๊ณ„๋˜์–ด ์žˆ๋Š”๋ฐ์š”. > ์ด๋ ‡๊ฒŒ ๊ตฌ์กฐ๋ฅผ ์„ค๊ณ„ํ•œ ์ด์œ ์— ๋Œ€ํ•ด ๊ณ ๋ฏผํ•ด๋ณด์‹œ๋ฉด ์ข‹๊ฒ ์Šต๋‹ˆ๋‹ค! > >> ์Œ.. ์ž˜๋ชป์งš์€๊ฑฐ ๊ฐ™๋„ค์š”.. >> security ์ฝ”๋“œ๋ฅผ ๋ณด๋ฉด ์ธ์ฆ ํ›„์— ๋ฐ”๋กœ ์ €์žฅ์„ ํ•˜๋Š”๋ฐ, filter ๋‚ด๋ถ€์—์„œ ๊ฐ SecurityContextRepository ๊ตฌํ˜„์ฒด์— ์˜์กดํ•˜๊ณ  ์žˆ๋„ค์š”! ์œ„ ์ฝ”๋ฉ˜ํŠธ์˜ ํ•ต์‹ฌ์€ `SecurityContextRepository๋ฅผ Filter์—์„œ ๋ชจ๋ฅด๋Š” ์ƒํƒœ๋กœ, SecurityContextHolder.getContext()๋ฅผ ํ™œ์šฉํ•œ๋‹ค.`์ธ๋ฐ์š”. SecurityContextRepository๋กœ ๊ด€๋ฆฌํ•˜๋Š” ์—ญํ• ์€ ์ƒˆ๋กœ์šด Filter๋ฅผ ๋งŒ๋“ค์–ด ์—ญํ• ์„ ์ „๋‹ฌํ•˜๊ณ , ์ด์™ธ Filter๋Š” SecurityContextRepository๋ฅผ ๋ชจ๋ฅด๋Š” ์ƒํƒœ๋กœ ๋งŒ๋“ค์–ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ์ถ”๊ฐ€ ํžŒํŠธ๊ฐ€ ํ•„์š”ํ•˜๋ฉด SecurityContextPersistenceFilter๋ฅผ ๊ฒ€์ƒ‰ํ•ด๋ณด์„ธ์š” :)
@@ -0,0 +1,79 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.authentication.UsernamePasswordAuthenticationToken; +import nextstep.security.core.context.SecurityContext; +import nextstep.security.core.context.SecurityContextHolder; +import nextstep.security.exception.AuthenticationException; +import nextstep.security.util.Base64Convertor; + +import java.io.IOException; + +public class BasicAuthFilter extends AbstractAuthProcessingFilter { + public static final String BASIC_HEADER_COLON = ":"; + public static final String BASIC_HEADER_COMMA = " "; + public static final String BASIC_HEADER_PREFIX = "Basic "; + public static final String AUTHORIZATION = "Authorization"; + + public BasicAuthFilter(final AuthenticationManager authenticationManager) { + super(authenticationManager); + } + + @Override + boolean match(final HttpServletRequest request) { + return existAuthorizationHeader(request); + } + + private boolean existAuthorizationHeader(final HttpServletRequest request) { + return request.getHeader(AUTHORIZATION) != null; + } + + @Override + public Authentication makeAuthentication(final HttpServletRequest request) { + String authorizationHeader = request.getHeader(AUTHORIZATION); + + if (isValidBasicAuthHeader(authorizationHeader)) { + throw new AuthenticationException(); + } + + String credentials = extractCredentials(authorizationHeader); + String[] usernameAndPassword = parseCredentials(credentials); + + return UsernamePasswordAuthenticationToken.unauthenticated(usernameAndPassword[0], usernameAndPassword[1]); + } + + private boolean isValidBasicAuthHeader(final String authorizationHeader) { + return authorizationHeader == null || !authorizationHeader.startsWith(BASIC_HEADER_PREFIX); + } + + private String extractCredentials(String authorizationHeader) { + String[] parts = authorizationHeader.split(BASIC_HEADER_COMMA); + if (parts.length != 2) { + throw new AuthenticationException(); + } + + return Base64Convertor.decode(parts[1]); + } + + private String[] parseCredentials(String decodedString) { + String[] usernameAndPassword = decodedString.split(BASIC_HEADER_COLON); + if (usernameAndPassword.length != 2) { + throw new AuthenticationException(); + } + + return usernameAndPassword; + } + + @Override + protected void successAuthentication(final HttpServletRequest request, final HttpServletResponse response, + final FilterChain filterChain) throws ServletException, IOException { + final SecurityContext context = SecurityContextHolder.getContext(); + final Authentication authentication = context.getAuthentication(); + authentication.getAuthorities().clear(); + } +}
Java
์•„! ๊ณฐ๊ณฐํžˆ ์ƒ๊ฐํ•ด๋ณด๋‹ˆ ์ธ์ฆ ์„ฑ๊ณต์‹œ filter์—์„œ๋Š” SecurityContextHolder์— ์ด๋ฏธ context๋ฅผ ์ €์žฅํ•˜์—ฌ ์–ด๋–ค ํ•„ํ„ฐ์—์„œ๋„ ์‚ฌ์šฉ๊ฐ€๋Šฅํ•˜๊ณ  repository๋Š” securiyContextHolderFilter์—์„œ ์‘๋‹ต์‹œ ์ €์žฅํ•ด์ฃผ๋ฉด ๋ ๊ฑฐ๊ฐ™์Šต๋‹ˆ๋‹ค! ์ธ์ฆํ•„ํ„ฐ๊ฐ€ repository๋ฅผ ์˜์กดํ•˜์ง€ ์•Š์•„๋„ ๋˜๊ฒ ๋„ค์š”!
@@ -1,25 +1,13 @@ -import logo from './logo.svg'; -import './App.css'; +import ReviewForm from "./Components/ReviewForm"; function App() { return ( <div className="App"> <header className="App-header"> - <img src={logo} className="App-logo" alt="logo" /> - <p> - Edit <code>src/App.js</code> and save to reload. - </p> - <a - className="App-link" - href="https://reactjs.org" - target="_blank" - rel="noopener noreferrer" - > - Learn React - </a> + <ReviewForm /> </header> </div> ); } -export default App; +export default App; \ No newline at end of file
JavaScript
๊ฒฝ๋กœ ./Components/DetailPage/ReviewForm ์š”๊ฑฐ ์•„๋‹Œ๊ฐ€์š” ?!
@@ -0,0 +1,52 @@ +import React from "react"; +import { useState } from "react"; + +const ReviewForm = () => { + const [received, setReceived] = useState(false); + const [year, setYear] = useState(""); + const [semester, setSemester] = useState(""); + const [review, setReview] = useState(""); + + const Submission = () => { + console.log({ received, year, semester, review}); + }; + + return ( + <div> + <h2>๋ฆฌ๋ทฐ์“ฐ๊ธฐ</h2> + <div> + <label> + <input + type="checkbox" + checked={received} + onChange={() => setReceived(!received)} + /> + ์ˆ˜ํ˜œ ์—ฌ๋ถ€ + </label> + + <input + type="number" + value={year} + onChange={(e) => setYear(e.target.value)} + placeholder="์‹ ์ฒญ ์—ฐ๋„๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”" + /> + + <select value={semester} onChange={(e) => setSemester(e.target.value)}> + <option value="">์‹ ์ฒญ ํ•™๊ธฐ</option> + <option value="1ํ•™๊ธฐ">1ํ•™๊ธฐ</option> + <option value="2ํ•™๊ธฐ">2ํ•™๊ธฐ</option> + </select> + + <textarea + value={review} + onChange={(e) => setReview(e.target.value)} + placeholder="๋ฆฌ๋ทฐ๋ฅผ ๋‚จ๊ฒจ์ฃผ์„ธ์š”" + /> + + <button onClick={Submission}>๋ฆฌ๋ทฐ ์ž‘์„ฑํ•˜๊ธฐ</button> + </div> + </div> + ); +}; + +export default ReviewForm; \ No newline at end of file
Unknown
ํ•จ์ˆ˜ ์ด๋ฆ„ ํŒŒ์Šค์นผ์ผ€์ด์Šค๋กœ ํ†ต์ผํ•˜์…จ๋‚˜์š”? ๐Ÿ™‚ (just ๊ถ๊ธˆ)
@@ -0,0 +1,52 @@ +import React from "react"; +import { useState } from "react"; + +const ReviewForm = () => { + const [received, setReceived] = useState(false); + const [year, setYear] = useState(""); + const [semester, setSemester] = useState(""); + const [review, setReview] = useState(""); + + const Submission = () => { + console.log({ received, year, semester, review}); + }; + + return ( + <div> + <h2>๋ฆฌ๋ทฐ์“ฐ๊ธฐ</h2> + <div> + <label> + <input + type="checkbox" + checked={received} + onChange={() => setReceived(!received)} + /> + ์ˆ˜ํ˜œ ์—ฌ๋ถ€ + </label> + + <input + type="number" + value={year} + onChange={(e) => setYear(e.target.value)} + placeholder="์‹ ์ฒญ ์—ฐ๋„๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”" + /> + + <select value={semester} onChange={(e) => setSemester(e.target.value)}> + <option value="">์‹ ์ฒญ ํ•™๊ธฐ</option> + <option value="1ํ•™๊ธฐ">1ํ•™๊ธฐ</option> + <option value="2ํ•™๊ธฐ">2ํ•™๊ธฐ</option> + </select> + + <textarea + value={review} + onChange={(e) => setReview(e.target.value)} + placeholder="๋ฆฌ๋ทฐ๋ฅผ ๋‚จ๊ฒจ์ฃผ์„ธ์š”" + /> + + <button onClick={Submission}>๋ฆฌ๋ทฐ ์ž‘์„ฑํ•˜๊ธฐ</button> + </div> + </div> + ); +}; + +export default ReviewForm; \ No newline at end of file
Unknown
ํ•จ์ˆ˜๋ช…์€ ๋ณดํŽธ์ ์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ์นด๋ฉœ์ผ€์ด์Šค๋กœ ์‚ฌ์šฉํ•ด๋ณด๋Š” ๊ฒƒ์€ ์–ด๋–จ๊นŒ์š”~?<br/> ์ถ”๊ฐ€๋กœ `handleSubmit`๊ณผ ๊ฐ™์ด handle prefix๋กœ ์ˆ˜์ •ํ•ด๋ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค~ cf. [๋ฆฌ์•กํŠธ ๊ณต์‹๋ฌธ์„œ](https://ko.react.dev/learn/adding-interactivity) <img width="396" alt="image" src="https://github.com/user-attachments/assets/efda3a60-12ff-4957-9e17-32377de6ce05" />
@@ -1,25 +1,13 @@ -import logo from './logo.svg'; -import './App.css'; +import ReviewForm from "./Components/ReviewForm"; function App() { return ( <div className="App"> <header className="App-header"> - <img src={logo} className="App-logo" alt="logo" /> - <p> - Edit <code>src/App.js</code> and save to reload. - </p> - <a - className="App-link" - href="https://reactjs.org" - target="_blank" - rel="noopener noreferrer" - > - Learn React - </a> + <ReviewForm /> </header> </div> ); } -export default App; +export default App; \ No newline at end of file
JavaScript
๋งž์•„์š”! ์ €๋Ÿฐ ์˜ค๋ฅ˜๊ฐ€ ์žˆ์—ˆ๋„ค์š”.. ๋‚˜์ค‘์— DetailPage ํด๋”๋ฅผ ์ถ”๊ฐ€ํ•˜๊ณ  ์ € ๋ถ€๋ถ„์„ ์ˆ˜์ • ์•ˆ ํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค ๋•๋ถ„์— ์•Œ๊ฒŒ ๋์–ด์š” ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!!
@@ -0,0 +1,52 @@ +import React from "react"; +import { useState } from "react"; + +const ReviewForm = () => { + const [received, setReceived] = useState(false); + const [year, setYear] = useState(""); + const [semester, setSemester] = useState(""); + const [review, setReview] = useState(""); + + const Submission = () => { + console.log({ received, year, semester, review}); + }; + + return ( + <div> + <h2>๋ฆฌ๋ทฐ์“ฐ๊ธฐ</h2> + <div> + <label> + <input + type="checkbox" + checked={received} + onChange={() => setReceived(!received)} + /> + ์ˆ˜ํ˜œ ์—ฌ๋ถ€ + </label> + + <input + type="number" + value={year} + onChange={(e) => setYear(e.target.value)} + placeholder="์‹ ์ฒญ ์—ฐ๋„๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”" + /> + + <select value={semester} onChange={(e) => setSemester(e.target.value)}> + <option value="">์‹ ์ฒญ ํ•™๊ธฐ</option> + <option value="1ํ•™๊ธฐ">1ํ•™๊ธฐ</option> + <option value="2ํ•™๊ธฐ">2ํ•™๊ธฐ</option> + </select> + + <textarea + value={review} + onChange={(e) => setReview(e.target.value)} + placeholder="๋ฆฌ๋ทฐ๋ฅผ ๋‚จ๊ฒจ์ฃผ์„ธ์š”" + /> + + <button onClick={Submission}>๋ฆฌ๋ทฐ ์ž‘์„ฑํ•˜๊ธฐ</button> + </div> + </div> + ); +}; + +export default ReviewForm; \ No newline at end of file
Unknown
์•ˆ๊ทธ๋ž˜๋„ ๋„ค์ด๋ฐ์ปจ๋ฒค์…˜์„ ์ž˜ ๋ชฐ๋ผ์„œ ์ด๋ฒˆ์ฃผ์— ๊ณต๋ถ€ํ•ด์˜ค๊ธฐ๋กœ ํ–ˆ์Šต๋‹ˆ๋‹ค...ใ…Žใ…Ž ๊ณต๋ถ€ํ•˜๊ณ  ์ฝ”๋“œ ์ˆ˜์ •ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค! ๋‘ ๋ถ„ ๋‹ค ๋ฆฌ๋ทฐํ•ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค:)
@@ -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์—๊ฒŒ ์ฑ…์ž„์„ ์ฃผ๋Š”๊ฒŒ ๋” ์ ํ•ฉํ•˜๊ฒ ๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“œ๋„ค์š”..!
@@ -0,0 +1,25 @@ +package nextstep.security.authentication; + +import nextstep.app.util.Base64Convertor; +import nextstep.security.authentication.exception.AuthenticationException; +import nextstep.security.user.UsernamePasswordAuthenticationToken; +import org.springframework.util.StringUtils; + +public class AuthenticationConverter { + + + public Authentication convert(String headerValue) { + if (!StringUtils.hasText(headerValue)) { + throw new AuthenticationException(); + } + + String credentials = headerValue.split(" ")[1]; + String decodedString = Base64Convertor.decode(credentials); + String[] usernameAndPassword = decodedString.split(":"); + if (usernameAndPassword.length != 2) { + throw new AuthenticationException(); + } + + return UsernamePasswordAuthenticationToken.unAuthorizedToken(usernameAndPassword[0], usernameAndPassword[1]); + } +}
Java
Convert์˜ ์ฑ…์ž„์„ ๋ถ„๋ฆฌํ•ด์ฃผ์…จ๊ตฐ์š” ๐Ÿ‘
@@ -0,0 +1,28 @@ +package nextstep.security.authentication; + +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.exception.AuthenticationException; +import nextstep.security.authentication.exception.MemberAccessDeniedException; + +import java.io.IOException; + +public class AuthenticationErrorHandler { + + protected AuthenticationErrorHandler() { + throw new UnsupportedOperationException(); + } + + public static void handleError(HttpServletResponse response, RuntimeException e) throws IOException { + if (e instanceof MemberAccessDeniedException) { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + return; + } + + if (e instanceof AuthenticationException) { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED); + return; + } + + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } +}
Java
error handle์˜ ์ฑ…์ž„๋„ ๋ถ„๋ฆฌํ•ด์ฃผ์…จ๊ตฐ์š” ๐Ÿ‘
@@ -0,0 +1,75 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationConverter; +import nextstep.security.authentication.AuthenticationErrorHandler; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.authentication.exception.AuthenticationException; +import nextstep.security.context.SecurityContextHolder; +import org.springframework.http.HttpMethod; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Objects; + +public class BasicAuthenticationFilter extends OncePerRequestFilter { + + private final AuthenticationManager authenticationManager; + private final AuthenticationConverter converter = new AuthenticationConverter(); + + private static final String AUTHORIZATION_HEADER = "Authorization"; + private static final String[] BASIC_AUTH_PATH = new String[]{"/members"}; + + public BasicAuthenticationFilter(AuthenticationManager authenticationManager) { + this.authenticationManager = Objects.requireNonNull(authenticationManager); + } + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + boolean isNotGetMethod = !HttpMethod.GET.name().equalsIgnoreCase(request.getMethod()); + boolean shouldNotFilterURI = Arrays.stream(BASIC_AUTH_PATH).noneMatch(it -> it.equalsIgnoreCase(request.getRequestURI())); + return isNotGetMethod || shouldNotFilterURI; + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws IOException, ServletException { + + try { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication != null) { + filterChain.doFilter(request, response); + return; + } + + authentication = authenticateByRequestHeader(request); + + SecurityContextHolder.getContext().setAuthentication(authentication); + + } catch (AuthenticationException e) { + AuthenticationErrorHandler.handleError(response, e); + return; + } + + filterChain.doFilter(request, response); + } + + private Authentication authenticateByRequestHeader(HttpServletRequest request) { + Authentication authentication = converter.convert(request.getHeader(AUTHORIZATION_HEADER)); + + Authentication result = authenticationManager.authenticate(authentication); + if (!result.isAuthenticated()) { + throw new AuthenticationException(); + } + + return result; + } +}
Java
OncePerRequestFilter ์ƒ์†์„ ์ž˜ ํ•ด์ฃผ์…จ์Šต๋‹ˆ๋‹ค! OncePerRequestFilter๋ฅผ ํ™œ์šฉํ•˜์‹  ์ด์œ ๋Š” ๋ฌด์—‡์ธ๊ฐ€์š”?
@@ -0,0 +1,76 @@ +package nextstep.security.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import nextstep.security.context.SecurityContext; +import nextstep.security.context.SecurityContextImpl; +import nextstep.security.context.SecurityContextRepository; +import nextstep.security.authentication.Authentication; +import nextstep.security.authentication.AuthenticationManager; +import nextstep.security.authentication.exception.AuthenticationException; +import nextstep.security.user.UsernamePasswordAuthenticationToken; +import org.springframework.http.HttpMethod; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; + +public class UserNamePasswordAuthFilter extends GenericFilterBean { + + private final AuthenticationManager authenticationManager; + private final SecurityContextRepository securityContextRepository; + + private static final String[] USER_NAME_PASSWORD_AUTH_PATH = new String[]{"/login"}; + + public UserNamePasswordAuthFilter(AuthenticationManager authenticationManager, SecurityContextRepository securityContextRepository) { + this.authenticationManager = Objects.requireNonNull(authenticationManager); + this.securityContextRepository = Objects.requireNonNull(securityContextRepository); + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + if (servletRequest instanceof HttpServletRequest request) { + boolean isNotPostMethod = !HttpMethod.POST.name().equalsIgnoreCase(request.getMethod()); + boolean isNotMatchedURI = Arrays.stream(USER_NAME_PASSWORD_AUTH_PATH).noneMatch(it -> it.equalsIgnoreCase(request.getRequestURI())); + if (isNotMatchedURI || isNotPostMethod) { + filterChain.doFilter(servletRequest, servletResponse); + return; + } + + try { + HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; + Authentication authentication = getAuthenticationByUserNamePassword(httpRequest); + + SecurityContext securityContext = new SecurityContextImpl(authentication); + securityContextRepository.saveContext(securityContext, httpRequest, (HttpServletResponse) servletResponse); + + } catch (AuthenticationException e) { + ((HttpServletResponse) servletResponse).sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage()); + return; + } + } + + ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_OK); + } + + private Authentication getAuthenticationByUserNamePassword(HttpServletRequest httpRequest) { + Map<String, String[]> parameterMap = httpRequest.getParameterMap(); + String username = parameterMap.get("username")[0]; + String password = parameterMap.get("password")[0]; + + UsernamePasswordAuthenticationToken authentication = UsernamePasswordAuthenticationToken.unAuthorizedToken(username, password); + + Authentication authenticate = authenticationManager.authenticate(authentication); + if (!authenticate.isAuthenticated()) { + throw new AuthenticationException(); + } + + return authenticate; + } +}
Java
๋ฏธ์…˜์„ ๋น ๋ฅด๊ฒŒ ์ž˜ ์ˆ˜ํ–‰ํ•ด์ฃผ์…”์„œ ์ถ”๊ฐ€์ ์œผ๋กœ ๊ณ ๋ฏผํ•ด๋ณผ ์ˆ˜ ์žˆ๋Š” ๋ถ€๋ถ„์„ ๋“œ๋ฆฝ๋‹ˆ๋‹ค! ์‹ค์ œ ์‹œํ๋ฆฌํ‹ฐ ์ฝ”๋“œ์—์„œ UsernamePasswordAuthenticationFilter์˜ ๊ฒฝ์šฐ AbstractAuthenticationProcessingFilter๋ฅผ ์ƒ์†๋ฐ›๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. **์‹œํ๋ฆฌํ‹ฐ์˜ ์ธ์ฆ ๊ด€๋ จ ํ•„ํ„ฐ๋ฅผ ์ž˜ ํŒŒ์•…ํ•ด๋ณด๊ธฐ ์œ„ํ•œ ๋ชฉ์ **์œผ๋กœ UserNamePasswordAuthFilter์™€ AbstractAuthenticationProcessingFilter๋ฅผ ๊ตฌ๋ถ„ํ•ด๋ณด๊ณ  ๋ฆฌํŒฉํ„ฐ๋ง ํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ์š”? ํ•จ๊ป˜ ๊ณ ๋ฏผํ•ด๋ณด๋ฉด ์ข‹์„ ๋‚ด์šฉ์œผ๋กœ ์‹ค์ œ ์‹œํ๋ฆฌํ‹ฐ ์ฝ”๋“œ์—์„œ๋Š” BasicAuthenticationFilter๋Š” AbstractAuthenticationProcessingFilter๋ฅผ ์ƒ์†๋ฐ›๊ณ  ์žˆ์ง€ ์•Š๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ด์œ ์— ๋Œ€ํ•ด์„œ ๊ณ ๋ฏผํ•ด๋ณด์‹œ๊ณ  ์„ธ์ค€๋‹˜์ด ๊ตฌํ˜„ํ•œ๋‹ค๋ฉด ์ด ๋ถ€๋ถ„์„ ํ•ฉ์ณ์„œ ๊ตฌํ˜„ํ•ด๋ณผ ๊ฒƒ ์ธ์ง€, ์•„๋‹ˆ๋ฉด ๊ธฐ์กด์ฒ˜๋Ÿผ ๋”ฐ๋กœ ๊ตฌํ˜„ํ•ด๋ณผ ๊ฒƒ ์ธ์ง€๋ฅผ ๊ณ ๋ฏผํ•ด๋ณด์‹œ๊ณ  ๊ทธ ์ด์œ ๋„ ํ•จ๊ป˜ ์ž‘์„ฑํ•ด๋ด์ฃผ์‹œ๋ฉด ์กฐ๊ธˆ ๋” ํญ๋„“์€ ํ•™์Šต์„ ํ•˜๋Š”๋ฐ ๋„์›€์ด ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค :)
@@ -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๊ณผ ๊ฐ™์€ ๋ช…๋ช…์ด ๋” ์ข‹์•˜์„๊นŒ์š”?
@@ -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
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. optional๋กœ ๋ฐ˜ํ™˜ํ–ˆ๋‹ค๋ฉด ํ˜ธ์ถœํ•˜๋Š” ๊ณณ์—์„œ ๋” ๊น”๋”ํ•˜๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ฒ ๋„ค์š”!
@@ -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
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.
@@ -1,7 +1,27 @@ package store; +import camp.nextstep.edu.missionutils.Console; +import store.controller.StoreController; +import store.model.repository.ProductRepository; +import store.model.repository.PromotionRepository; +import store.model.service.ReceiptCalculationService; +import store.model.service.StoreService; +import store.view.InputView; +import store.view.OutputView; + public class Application { public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + ProductRepository productRepository = new ProductRepository(); + PromotionRepository promotionRepository = new PromotionRepository(); + + StoreService storeService = new StoreService(productRepository, promotionRepository); + ReceiptCalculationService receiptCalculationService = new ReceiptCalculationService(); + + InputView inputView = new InputView(); + OutputView outputView = new OutputView(); + StoreController storeController = new StoreController(inputView, outputView, storeService, receiptCalculationService); + + storeController.run(); + Console.close(); } }
Java
Repository ๊ณ„์ธต์„ ์‚ฌ์šฉํ•˜๋ฉด ์–ป์„ ์ˆ˜ ์žˆ๋Š” ์žฅ์ ์ด ๋ฌด์—‡์ธ์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,24 @@ +package store.Message; + +public enum ErrorMessage { + + INVALID_FORMAT("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค."), + NON_EXISTENT_PRODUCT("์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."), + EXCEEDS_STOCK("์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + GENERIC_ERROR("์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค."), + FILE_ERROR("์ž˜๋ชป๋œ ๋ฐ์ดํ„ฐ ํŒŒ์ผ์ž…๋‹ˆ๋‹ค:"); + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return String.format("[ERROR] %s ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.", message); + } + + public String getMessage(String detail) { + return String.format("[ERROR] %s : %s", message, detail); + } +} \ 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,14 @@ +package store.constant; + +public class ReceiptLabels { + public static final String HEADER = "\n==============W ํŽธ์˜์ ================"; + public static final String GIFT_HEADER = "=============์ฆ\t์ •==============="; + public static final String FOOTER = "===================================="; + public static final String TOTAL_LABEL = "์ด๊ตฌ๋งค์•ก"; + public static final String EVENT_DISCOUNT_LABEL = "ํ–‰์‚ฌํ• ์ธ"; + public static final String MEMBERSHIP_DISCOUNT_LABEL = "๋ฉค๋ฒ„์‹ญํ• ์ธ"; + public static final String FINAL_AMOUNT_LABEL = "๋‚ด์‹ค๋ˆ"; + public static final String PRODUCT_NAME = "์ƒํ’ˆ๋ช…"; + public static final String COUNT = "์ˆ˜๋Ÿ‰"; + public static final String PRICE = "๊ธˆ์•ก"; +} \ No newline at end of file
Java
์ €๋„ ์ด ๋ถ€๋ถ„์ด ๊ฐ€์žฅ ํฐ ๊ณ ๋ฏผ์ธ๋ฐ, Enum์„ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ์ง€๋งŒ ๋งค๋ฒˆ .getMessage() ๋ฉ”์„œ๋“œ ์‚ฌ์šฉ์œผ๋กœ ๋กœ์ง์ด ๋ณต์žกํ•ด์ง€๋Š” ๋А๋‚Œ์ด ์žˆ์Šต๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ, ๊ทธ๋ž˜๋„ ํƒ€์ž…์„ ๋ณด์žฅํ•˜๊ธฐ ๋•Œ๋ฌธ์— Enum ์‚ฌ์šฉ์„ ๊ถŒ์žฅํ•œ๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ์ด์— ๋Œ€ํ•œ ์˜๊ฒฌ์„ ๋“ฃ๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค.
@@ -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
๋งค๋ฒˆ Y || N ๊ตฌ๋ถ„ํ•˜๊ธฐ ๋ณด๋‹ค๋Š” input์—์„œ boolean ๊ฐ’์œผ๋กœ ํŒ๋ณ„์—์„œ ๋„˜๊ฒจ์ฃผ๋Š” ๊ฑด ์–ด๋–จ๊นŒ์š”!?
@@ -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
2๋ฒˆ์งธ ๊ฐ’์— ์ˆซ์ž๊ฐ€ ์•„๋‹Œ ๋ฌธ์ž๊ฐ€ ์˜ฌ ๊ฒฝ์šฐ ์—๋Ÿฌ ์ฒ˜๋ฆฌ๋ฅผ ๋ชปํ•˜์ง€ ์•Š๋‚˜์šฉ!?
@@ -0,0 +1,34 @@ +package store.model.domain; + +import store.constant.ProductType; + +public class Product { + private final String name; + private final int price; + private final String promotion; + + public Product(String name, int price, String promotion) { + this.name = name; + this.price = price; + this.promotion = promotion; + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } + + public String getPromotion() { + return promotion; + } + + public ProductType isPromotion() { + if (promotion.equals("null")) { + return ProductType.REGULAR; + } + return ProductType.PROMOTION; + } +}
Java
"null" ๋„ ์ƒ์ˆ˜๋กœ ๋ถ„๋ฆฌํ•ด ํ”„๋กœ๋ชจ์…˜์ด ์—†์„ ๋•Œ ๋ผ๋Š” ๋ช…์นญ์„ ๊ฐ€์ง„ ์ด๋ฆ„์„ ๋ช…์‹œํ•˜๋Š” ๊ฒŒ ์ข‹์„ ๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,47 @@ +package store.model.service; + +import store.model.domain.ShoppingCartCheck; +import store.model.ReceiptTotals; +import store.constant.Discounts; + +import java.util.List; + +public class ReceiptCalculationService { + + public ReceiptTotals calculateTotals(List<ShoppingCartCheck> shoppingCartChecks, boolean isMembership) { + ReceiptTotals totals = new ReceiptTotals(); + + for (ShoppingCartCheck dto : shoppingCartChecks) { + int price = dto.getProductPrice() * dto.getRequestCount(); + totals.totalCount += dto.getRequestCount(); + totals.totalPrice += price; + totals.regularPrice += dto.getRegularCount() * dto.getProductPrice(); + } + + totals.giftPrice = calculateGiftDiscount(shoppingCartChecks); + totals.membershipPrice = calculateMembershipDiscount(totals.regularPrice, isMembership); + + return totals; + } + + private int calculateGiftDiscount(List<ShoppingCartCheck> shoppingCartChecks) { + int giftPrice = 0; + for (ShoppingCartCheck dto : shoppingCartChecks) { + if (dto.getFreeCount() > 0 && dto.isActivePromotion()) { + giftPrice -= dto.getProductPrice() * dto.getFreeCount(); + } + } + return giftPrice; + } + + private int calculateMembershipDiscount(int regularPrice, boolean isMembership) { + if (isMembership) { + double discountPrice = regularPrice * -Discounts.MEMBERSHIP_DISCOUNT_RATE; + if (Math.abs(discountPrice) > Discounts.MAX_MEMBERSHIP_DISCOUNT) { + return -Discounts.MAX_MEMBERSHIP_DISCOUNT; + } + return (int) discountPrice; + } + return 0; + } +} \ No newline at end of file
Java
์ด ๋ถ€๋ถ„๋„ ๋ฉ”์„œ๋“œ๋ฅผ ๋ถ„๋ฆฌํ•ด ์ธ๋ดํŠธ๋ฅผ ๊ฐ์†Œ์‹œํ‚ฌ ์ˆ˜ ์žˆ์„ ๊ฑฐ ๊ฐ™์•„์š”!
@@ -1,7 +1,27 @@ package store; +import camp.nextstep.edu.missionutils.Console; +import store.controller.StoreController; +import store.model.repository.ProductRepository; +import store.model.repository.PromotionRepository; +import store.model.service.ReceiptCalculationService; +import store.model.service.StoreService; +import store.view.InputView; +import store.view.OutputView; + public class Application { public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + ProductRepository productRepository = new ProductRepository(); + PromotionRepository promotionRepository = new PromotionRepository(); + + StoreService storeService = new StoreService(productRepository, promotionRepository); + ReceiptCalculationService receiptCalculationService = new ReceiptCalculationService(); + + InputView inputView = new InputView(); + OutputView outputView = new OutputView(); + StoreController storeController = new StoreController(inputView, outputView, storeService, receiptCalculationService); + + storeController.run(); + Console.close(); } }
Java
์˜์กด์„ฑ ์ฃผ์ž… ๋ฐ›๋Š” ๋ถ€๋ถ„์ด ๊ฝค ๋งŽ์•„์„œ ๋ณต์žก๋„๊ฐ€ ์กฐ๊ธˆ ๋†’์•„ ๋ณด์ด๋Š”๋ฐ ์ด์— ๋Œ€ํ•ด ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,24 @@ +package store.Message; + +public enum ErrorMessage { + + INVALID_FORMAT("์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์€ ํ˜•์‹์œผ๋กœ ์ž…๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค."), + NON_EXISTENT_PRODUCT("์กด์žฌํ•˜์ง€ ์•Š๋Š” ์ƒํ’ˆ์ž…๋‹ˆ๋‹ค."), + EXCEEDS_STOCK("์žฌ๊ณ  ์ˆ˜๋Ÿ‰์„ ์ดˆ๊ณผํ•˜์—ฌ ๊ตฌ๋งคํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."), + GENERIC_ERROR("์ž˜๋ชป๋œ ์ž…๋ ฅ์ž…๋‹ˆ๋‹ค."), + FILE_ERROR("์ž˜๋ชป๋œ ๋ฐ์ดํ„ฐ ํŒŒ์ผ์ž…๋‹ˆ๋‹ค:"); + + private final String message; + + ErrorMessage(String message) { + this.message = message; + } + + public String getMessage() { + return String.format("[ERROR] %s ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.", message); + } + + public String getMessage(String detail) { + return String.format("[ERROR] %s : %s", message, detail); + } +} \ No newline at end of file
Java
[ERROR] ์™€ "๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”." ๋„ ์ƒ์ˆ˜ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ์ข‹์•„ ๋ณด์ž…๋‹ˆ๋‹ค!
@@ -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,8 @@ +package store.config; + +public record ProductData(String name, + int price, + int quantity, + String promotion) { +} +
Java
record ์‚ฌ์šฉํ•˜์‹  ์  ์ธ์ƒ ๊นŠ์Šต๋‹ˆ๋‹ค :) ์ €๋„ IntelliJ์—์„œ record ์‚ฌ์šฉ์„ ์ถ”์ฒœํ•ด์„œ ๋ณ€ํ™˜ํ•˜๋ ค๋‹ค๊ฐ€ ๋ถ€์ž‘์šฉ์ด ์žˆ์„๊นŒ๋ด ์‹œ๋„ํ•˜์ง€ ์•Š์•˜๊ฑฐ๋“ ์š”, ํ˜น์‹œ record๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹์€ ์žฅ์ ๊ฐ™์€ ๊ฒƒ์„ ๋ง์”€ํ•ด์ฃผ์‹ค ์ˆ˜ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,9 @@ +package store.constant; + +public class InputMessages { + public static final String PURCHASE_PROMPT_MESSAGE = "\n๊ตฌ๋งคํ•˜์‹ค ์ƒํ’ˆ๋ช…๊ณผ ์ˆ˜๋Ÿ‰์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”. (์˜ˆ: [์‚ฌ์ด๋‹ค-2],[๊ฐ์ž์นฉ-1])"; + public static final String MEMBERSHIP_PROMPT_MESSAGE = "\n๋ฉค๋ฒ„์‹ญ ํ• ์ธ์„ ๋ฐ›์œผ์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)"; + public static final String ADDITIONAL_PURCHASE_PROMPT_MESSAGE = "\n๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋งคํ•˜๊ณ  ์‹ถ์€ ๋‹ค๋ฅธ ์ƒํ’ˆ์ด ์žˆ๋‚˜์š”? (Y/N)"; + public static final String ADDITIONAL_FREE_PROMPT_MESSAGE = "\nํ˜„์žฌ %s์€(๋Š”) 1๊ฐœ๋ฅผ ๋ฌด๋ฃŒ๋กœ ๋” ๋ฐ›์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ถ”๊ฐ€ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)%n"; + public static final String REGULAR_PRICE_PROMPT_MESSAGE = "\nํ˜„์žฌ %s %d๊ฐœ๋Š” ํ”„๋กœ๋ชจ์…˜ ํ• ์ธ์ด ์ ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜๋„ ๊ตฌ๋งคํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? (Y/N)%n"; +}
Java
์–ด๋–ค ๊ฒƒ์€ ๊ฐœํ–‰ ๋ฌธ์ž๊ฐ€ \n ์ด๊ณ , ์–ด๋–ค ๊ฒƒ์€ %n ์ธ๊ฒƒ์— ์ด์œ ๊ฐ€ ์žˆ๋‚˜์š”? %n์œผ๋กœ ํ†ต์ผํ–ˆ์œผ๋ฉด ์ข‹๊ฒ ๋‹ค๋Š” ์˜๊ฒฌ์ž…๋‹ˆ๋‹ค :)