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์ผ๋ก ํต์ผํ์ผ๋ฉด ์ข๊ฒ ๋ค๋ ์๊ฒฌ์
๋๋ค :) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.