code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,56 @@ +package store.domain; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import store.domain.exception.ProductErrorCode; +import store.domain.exception.ProductException; + +public class BuyProducts { + + private final List<Product> products; + + public BuyProducts(Map<String, String> splitProducts, Promotions promotions, Products products) { + this.products = createBuyProducts(splitProducts, promotions); + validateExistence(products); + validateQuantity(products); + } + + public List<Product> products() { + return Collections.unmodifiableList(products); + } + + private List<Product> createBuyProducts(Map<String, String> splitProducts, Promotions promotions) { + List<Product> products = new ArrayList<>(); + + for (Entry<String, String> entry : splitProducts.entrySet()) { + Product product = new Product( + entry.getKey(), + ProductInfo.findPriceByName(entry.getKey()), + entry.getValue(), + promotions.getPromotionByType(PromotionInfo.findPromotionByName(entry.getKey()))); + products.add(product); + } + + return products; + } + + private void validateExistence(Products inventoryProducts) { + for (Product buyProduct : products) { + if (!inventoryProducts.getProducts().contains(buyProduct)) { + throw new ProductException(ProductErrorCode.NOT_FOUND_PRODUCT_NAME); + } + } + } + + private void validateQuantity(Products inventoryProducts) { + for (Product buyProduct : products) { + int availableQuantity = inventoryProducts.countProductsByName(buyProduct.getName()); + if (availableQuantity < buyProduct.getQuantity()) { + throw new ProductException(ProductErrorCode.OVER_QUANTITY); + } + } + } +}
Java
๋‹จ์ˆœํžˆ getProductsํ›„ contains๋ฅผ ์ง์ ‘์ ์œผ๋กœ ํ•˜๊ธฐ๋ณด๋‹จ Products์— public ๋ฉ”์„œ๋“œ๋ฅผ ๋”ฐ๋กœ ๋‘๋Š” ๊ฒƒ์€ ์–ด๋–ค๊ฐ€์š”?
@@ -0,0 +1,79 @@ +package store.domain; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map.Entry; +import store.domain.vo.MemberShip; +import store.domain.vo.ProductQuantity; +import store.view.dto.response.BuyProductResponse; +import store.view.dto.response.FreeProductResponse; +import store.view.dto.response.ProductCalculateResponse; + +public class CustomerReceipt { + + private final Receipt receipt; + private final MemberShip memberShipDiscount; + + public CustomerReceipt(Receipt receipt, MemberShip memberShipDiscount) { + this.receipt = receipt; + this.memberShipDiscount = memberShipDiscount; + } + + public List<BuyProductResponse> showBuyProducts() { + List<BuyProductResponse> products = new ArrayList<>(); + for (Entry<Product, ProductQuantity> entry : receipt.getReceipt().entrySet()) { + products.add(new BuyProductResponse(entry.getKey().getName(), entry.getKey().getQuantity(), + entry.getKey().getQuantity() * entry.getKey().getPrice())); + } + return Collections.unmodifiableList(products); + } + + public List<FreeProductResponse> showFreeProductInfo() { + List<FreeProductResponse> freeProductResponses = new ArrayList<>(); + for (Entry<Product, ProductQuantity> entry : receipt.getReceipt().entrySet()) { + freeProductResponses.add( + new FreeProductResponse(entry.getKey().getName(), entry.getValue().getQuantity()) + ); + } + return Collections.unmodifiableList(freeProductResponses); + } + + public ProductCalculateResponse showCalculateInfo() { + return new ProductCalculateResponse( + productsAllQuantity(), + productsAllPrice(), + promotionPrice(), + memberShipDiscount.getDisCountPrice(), + totalPrice() + ); + } + + private int totalPrice() { + return productsAllPrice() - promotionPrice() - memberShipDiscount.getDisCountPrice(); + } + + private int productsAllPrice() { + return receipt.getReceipt() + .keySet() + .stream() + .mapToInt(product -> product.getPrice() * product.getQuantity()) + .sum(); + } + + private int promotionPrice() { + return receipt.getReceipt() + .entrySet() + .stream() + .mapToInt(entry -> entry.getKey().getPrice() * entry.getValue().getQuantity()) + .sum(); + } + + private int productsAllQuantity() { + return receipt.getReceipt() + .keySet() + .stream() + .mapToInt(Product::getQuantity) + .sum(); + } +}
Java
์—”ํŠธ๋ฆฌ๋ฅผ ์ง์ ‘์ ์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ์ด ๋–จ์–ด์ง„๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. getKey(), getValue()๊ณผ ๊ฐ™์ด ํ‚ค์™€ ๊ฐ’์œผ๋กœ ๋‚˜ํƒ€๋‚ด๋Š” ๋ฉ”์„œ๋“œ๋Š” ์ฝ”๋“œ๋ฅผ ์ฝ๋Š” ์‚ฌ๋žŒ์—๊ฒŒ key๋Š” ๋ฌด์—‡์ด์ง€๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๊ฒŒ ๋˜์–ด ๋”ฐ๋กœ ๋งŒ๋“œ๋Š”๊ฒŒ ์ข‹์„๊ฒƒ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,169 @@ +# 1. ํ•ต์‹ฌ ํ•œ ์ค„ ์ •์˜ + +์‚ฌ์šฉ์ž์˜ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ๋ชฉ๋ก ๋ฐ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก์„ ํ™•์ธํ•˜๊ณ , ๊ฒฐ์ œ ๋‹จ๊ณ„๋กœ ์ „ํ™˜ํ•œ๋‹ค. + +# 2. ์‚ฌ์šฉ์ž ๊ด€์ ์—์„œ ๊ธฐ๋Šฅ ๋ฆฌ์ŠคํŒ… (์„ธ๋ถ€ ๊ธฐ๋Šฅ ์ •์˜) + +- [ ] CartItem + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ์ •๋ณด๋ฅผ ๋ณด์—ฌ์ค€๋‹ค + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ์„ ์„ ํƒ/ํ•ด์ œํ•œ๋‹ค. + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ์„ ์ œ๊ฑฐํ•œ๋‹ค. + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ์ˆ˜๋Ÿ‰์„ ๋ณ€๊ฒฝํ•œ๋‹ค. +- [ ] CartItemList + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ๋ชฉ๋ก์„ ๋ณด์—ฌ์ค€๋‹ค. + - [ ] ์ „์ฒด ์„ ํƒ +- [ ] CartAmount + - [ ] ์ฃผ๋ฌธ๊ธˆ์•ก, ๋ฐฐ์†ก๋น„, ์ด ๊ฒฐ์ œ ๊ธˆ์•ก์„ ๋ณด์—ฌ์ค€๋‹ค. +- [ ] ShopHeader + - [ ] SHOP์„ ๋ณด์—ฌ์ค€๋‹ค +- [ ] BackHeader + - [ ] ๋’ค๋กœ๊ฐ€๊ธฐ ์•„์ด์ฝ˜ ํด๋ฆญ ์‹œ ๋’ค๋กœ๊ฐ„๋‹ค. + - [ ] ๋’ค๋กœ๊ฐ€๊ธฐ ์•„์ด์ฝ˜์„ ๋ณด์—ฌ์ค€๋‹ค. +- [ ] OrderConfirmButton (button ๊ธฐ๋ณธ ์š”์†Œ๋ฅผ ํ™œ์šฉ) + - [ ] ์ฃผ๋ฌธํ™•์ธ ๋ฒ„ํ†ค์„ ํด๋ฆญํ•˜๋ฉด ์ฃผ๋ฌธํ™•์ธ ํŽ˜์ด์ง€๋กœ ์ด๋™ํ•œ๋‹ค. +- [ ] BuyButton (button ๊ธฐ๋ณธ ์š”์†Œ๋ฅผ ํ™œ์šฉ) + - [ ] disabled ์ฒ˜๋ฆฌ๊ฐ€ ๋˜์–ด ์žˆ๋‹ค. +- [ ] OrderSummary + - [ ] ์ด๊ฒฐ์ œ๊ธˆ์•ก์„ ๋ณด์—ฌ์ค€๋‹ค. + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ์ข…๋ฅ˜, ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ๊ฐœ์ˆ˜๋ฅผ ๋ณด์—ฌ์ค€๋‹ค. + +# 3. ๊ตฌํ˜„์„ ์–ด๋–ป๊ฒŒ ํ• ์ง€ ๋ฆฌ์ŠคํŒ… + +- [ ] ์ƒํƒœ + + - atom + + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ๋ฐฐ์—ด + + - [ ] key: 'cartItems' + - [ ] returnType: CartItem[] + + - [ ] ์„ ํƒ์—ฌ๋ถ€ ๋ฐฐ์—ด + + - [ ] key: selectedCartItemIds + - [ ] returnType: number[] + + - selector + + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ๋ฐฐ์—ด(๊ทธ๋Ÿฐ๋ฐ ์„ ํƒ ์—ฌ๋ถ€๊ฐ€ ๋”ํ•ด์ง„) + + - [ ] key: cartItemsWithIsSelected + - [ ] returnType: CartItemWithIsSelected[] + - dependency: cartItems, selectedCartItemIds + + - [ ] ์ฃผ๋ฌธ ๊ธˆ์•ก + + - [ ] key: orderAmount + - [ ] returnType: number + - dependency: cartItemsWithIsSelected + + - [ ] ๋ฐฐ์†ก๋น„ + + - [ ] key: deliveryCost + - [ ] returnType: number + - dependency: orderAmount + + - [ ] ์ด ๊ฒฐ์ œ ๊ธˆ์•ก + + - [ ] key: totalOrderAmount + - [ ] returnType: number + - dependency: deliveryCost, orderAmount + + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ์ข…๋ฅ˜ ์ˆ˜ + + - [ ] key: uniqueCartItemsCount + - [ ] returnType: number + - dependency: cartItems + + - [ ] ์„ ํƒ๋œ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ์ข…๋ฅ˜ ์ˆ˜ + + - [ ] key: selectedUniqueCartItemsCount + - [ ] returnType: number + - dependency: selectedCartItemIds + + - [ ] ์„ ํƒ๋œ ์ด ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ๊ฐœ์ˆ˜ + + - [ ] key: selectedCartItemsCount + - [ ] returnType: number + - dependency: cartItemsWithIsSelected + +- [ ] api + + - [ ] cartItems get + - [ ] cartItems/[id] patch + - [ ] cartItems/[id] delete + +- [ ] UI + + - [ ] CartItem + - [ ] prop: cartItem + - [ ] CartItemList + - [ ] CartAmount + - [ ] Header + - [ ] prop: hasBackButton, text + - [ ] shop header: `text = shop` + - [ ] back header: `hasBackButton = true` + - [ ] Button + - [ ] prop: text, onclick, disabled + - [ ] OrderSummary + +- [ ] ์Šคํ† ๋ฆฌ์ง€ + - ์„ธ์…˜ ์Šคํ† ๋ฆฌ์ง€ ํ™œ์šฉ + - ๊ด€๋ฆฌ ๋Œ€์ƒ: ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ์„ ํƒ์—ฌ๋ถ€ + - ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ: `number[]` + +# 4. ๊ตฌํ˜„ ์ˆœ์„œ + +1. CartList + +- [x] atom ์ •์˜ (cartItemsState, selectedCartItemIds) +- [x] selector ์ •์˜ (cartItemsWithIsSelected) +- [x] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ๋ชฉ๋ก ๋ถˆ๋Ÿฌ์˜ค๊ธฐ (api fetching) +- [x] CartItem + - [x] cartItems/[id] patch (๊ฐœ์ˆ˜ ์ˆ˜์ •) + - [x] cartItems/[id] delete (์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ์‚ญ์ œ) + - [x] UI ๊ตฌํ˜„(prop: cartItem) +- [x] empty case ๋Œ€์‘ +- [x] atom & select ์„ธ๋ถ€ ๊ตฌํ˜„(api, session storage ์—ฐ๊ฒฐ) & ์ ์šฉ +- [x] ์ „์ฒด ์„ ํƒ ๊ธฐ๋Šฅ ๊ตฌํ˜„ + +1. CartAmount + +- [x] selector ์ •์˜ (orderAmount, deliveryCost, totalOrderAmount) +- [x] UI ๊ตฌํ˜„ + +3. CartTitle + +- [x] selector ์ •์˜ (uniqueCartItemsCount) +- [x] UI ๊ตฌํ˜„ + +1. Header, Footer + +2. OrderSummary + +- [x] selector ์ •์˜ (selectedUniqueCartItemsCount, selectedCartItemsCount, totalOrderAmount) +- [x] UI ๊ตฌํ˜„ + +1. UX ์ตœ์ ํ™” + +- [x] ErrorBoundary, Suspense + +### test + +1. CartList + +- rawCartItemsState + - [x] ์ดˆ๊ธฐ๊ฐ’์ด ์ž˜ ์„ธํŒ…๋˜๋Š”์ง€ +- selectedCartItemIdsState + - [x] ์ดˆ๊ธฐ๊ฐ’์ด ์ž˜ ์„ธํŒ…๋˜๋Š”์ง€ + - [x] set์ด ๋ฐœ์ƒํ•  ๋•Œ putInSelectedCartItemIds์ด ํ˜ธ์ถœ๋˜๋Š”์ง€ +- useCartItemControl + - [x] remove (1. delete api ์š”์ฒญ 2. ์ƒํƒœ ๋ณ€๊ฒฝ) + - [x] updateQuantity (1. patch api ์š”์ฒญ 2. ์ƒํƒœ ๋ณ€๊ฒฝ) + - [x] toggleSelection (์ƒํƒœ ๋ณ€๊ฒฝ) + +### ๋‚จ์€๊ฑฐ + +- [x] useCartItemControl ํ…Œ์ŠคํŠธ +- [x] OrderSummary ์ปดํฌ๋„ŒํŠธ ๊ฐœ๋ฐœ ๋ฐ ๋ผ์šฐํŠธ ์ฒ˜๋ฆฌ +- [x] ErrorBoundary
Unknown
ํ˜น์‹œ ์ฒดํฌ๋ฆฌ์ŠคํŠธ๋Š” ์ผ๋ถ€๋Ÿฌ ์ฒดํฌ ์•ˆํ•˜์‹ ๊ฑธ๊นŒ์š”?! ๐Ÿซ
@@ -0,0 +1,10 @@ +์ผ๊ด€์„ฑ์„ ์œ ์ง€ํ•˜๊ธฐ ์œ„ํ•œ ๊ทœ์น™ + +### recoil + +1. ๋ฆฌ๋ Œ๋”๋ฅผ ์ด‰๋ฐœํ•˜๋Š” ๋ฐ์ดํ„ฐ์— ํ•ด๋‹นํ•˜๋Š” ๊ฒฝ์šฐ ์ด๋ฆ„์— State๋ฅผ ๋ถ™์ธ๋‹ค. + 1. atom์€ ๋ฌด์กฐ๊ฑด State๋ฅผ ๋ถ™์ธ๋‹ค. + 2. selector๋Š” ๋‚ด๋ถ€์ ์œผ๋กœ ํ•˜๋‚˜ ์ด์ƒ์˜ atom์„ ์ด์šฉํ•˜๋Š” ๊ฒฝ์šฐ State๋ฅผ ๋ถ™์ธ๋‹ค. +2. selector์˜ ์šฉ๋„๋Š” ์„ธ ๊ฐ€์ง€์ด๋‹ค. + 1. atom ํŒŒ์ƒ ์ƒํƒœ + 2. ๋น„๋™๊ธฐ ๋ฐ์ดํ„ฐ ํŒจ์นญ
Unknown
๊ทœ์น™๊นŒ์ง€ ๋””ํ…Œ์ผ.. ๐Ÿ‘
@@ -1,10 +1,24 @@ import "./App.css"; +import { RecoilRoot } from "recoil"; +import { BrowserRouter, Route, Routes } from "react-router-dom"; + +import CartPage from "./pages/CartPage"; +import { PATH } from "./constants/path"; +import OrderSummaryPage from "./pages/OrderSummaryPage"; +import { ErrorBoundary } from "react-error-boundary"; function App() { return ( - <> - <h1>react-shopping-cart</h1> - </> + <BrowserRouter> + <RecoilRoot> + <ErrorBoundary fallbackRender={({ error }) => error.message}> + <Routes> + <Route path={PATH.cart} element={<CartPage />} /> + <Route path={PATH.orderSummary} element={<OrderSummaryPage />} /> + </Routes> + </ErrorBoundary> + </RecoilRoot> + </BrowserRouter> ); }
Unknown
[crerateBrowserRouter](https://reactrouter.com/en/main/routers/create-browser-router)๋„ ์ถ”ํ›„์— ํ•œ ๋ฒˆ ์จ๋ณด์‹œ๋Š”๊ฑฐ ์ถ”์ฒœ๋“œ๋ฆฝ๋‹ˆ๋‹ค :) ๐Ÿซ
@@ -0,0 +1,31 @@ +import styled from "styled-components"; + +export interface IButtonProps extends React.HTMLAttributes<HTMLButtonElement> { + disabled?: boolean; +} + +export default function Button({ children, ...attributes }: IButtonProps) { + return <S.Button {...attributes}>{children}</S.Button>; +} + +const S = { + Button: styled.button` + position: fixed; + bottom: 0; + max-width: 429px; + + height: 64px; + font-size: 16px; + font-weight: 700; + text-align: center; + width: 100%; + + background-color: black; + color: white; + border: none; + cursor: pointer; + &:disabled { + background-color: rgba(190, 190, 190, 1); + } + `, +};
Unknown
์Šคํƒ€์ผ์„ ์œ„ํ•œ ๋ฒ„ํŠผ ์ปดํฌ๋„ŒํŠธ๋กœ ํ™•์ธ๋˜๋Š”๋ฐ, ์ด๋ฅผ ํด๋”๋กœ ๊ตฌ์กฐํ™”์‹œํ‚ค๋ฉด ๋ฒ„ํŠผ์˜ ์—ญํ• ์„ ํŒŒ์•…ํ•˜๋Š”๋ฐ ๋”์šฑ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ๐Ÿซ
@@ -0,0 +1,91 @@ +import { useRecoilValue } from "recoil"; +import styled from "styled-components"; +import { deliveryCostState, orderAmountState, totalOrderAmountState } from "../recoil/cartAmount"; +import { ReactComponent as InfoIcon } from "../assets/info-icon.svg"; + +export interface ICartAmountProps {} + +export default function CartAmount() { + const orderAmount = useRecoilValue(orderAmountState); + const deliveryCost = useRecoilValue(deliveryCostState); + const totalOrderAmount = useRecoilValue(totalOrderAmountState); + + return ( + <S.CartAmountContainer> + <S.CartAmountNoti> + <S.InfoIcon /> + <S.CartAmountNotiText> + ์ด ์ฃผ๋ฌธ ๊ธˆ์•ก์ด 100,000์› ์ด์ƒ์ผ ๊ฒฝ์šฐ ๋ฌด๋ฃŒ ๋ฐฐ์†ก๋ฉ๋‹ˆ๋‹ค. + </S.CartAmountNotiText> + </S.CartAmountNoti> + + <S.UpperCartAmountInfoWrapper> + <S.CartAmountInfo> + <S.AmountText>์ฃผ๋ฌธ ๊ธˆ์•ก</S.AmountText>{" "} + <S.Amount>{orderAmount.toLocaleString()}์›</S.Amount> + </S.CartAmountInfo> + <S.CartAmountInfo> + <S.AmountText>๋ฐฐ์†ก๋น„</S.AmountText> <S.Amount>{deliveryCost.toLocaleString()}์›</S.Amount> + </S.CartAmountInfo> + </S.UpperCartAmountInfoWrapper> + <S.LowerCartAmountInfoWrapper> + <S.CartAmountInfo> + <S.AmountText>์ด ์ฃผ๋ฌธ ๊ธˆ์•ก</S.AmountText>{" "} + <S.Amount>{totalOrderAmount.toLocaleString()}์›</S.Amount> + </S.CartAmountInfo> + </S.LowerCartAmountInfoWrapper> + </S.CartAmountContainer> + ); +} + +const S = { + CartAmountContainer: styled.div` + display: flex; + flex-direction: column; + gap: 12px; + `, + + CartAmountNoti: styled.p` + font-size: 14px; + color: #888; + margin-bottom: 20px; + display: flex; + align-items: center; + gap: 4px; + `, + + UpperCartAmountInfoWrapper: styled.div` + border-top: 1px solid rgba(0, 0, 0, 0.1); + `, + + LowerCartAmountInfoWrapper: styled.div` + border-top: 1px solid rgba(0, 0, 0, 0.1); + `, + + CartAmountInfo: styled.div` + display: flex; + justify-content: space-between; + align-items: center; + padding-top: 12px; + `, + + AmountText: styled.span` + font-size: 16px; + font-weight: 700; + `, + + Amount: styled.span` + font-size: 24px; + font-weight: 700; + `, + InfoIcon: styled(InfoIcon)` + width: 16px; + height: 16px; + `, + CartAmountNotiText: styled.span` + font-size: 12px; + font-weight: 500; + line-height: 15px; + color: rgba(10, 13, 19, 1); + `, +};
Unknown
์‚ฌ์šฉ๋˜์ง€ ์•Š๋Š” Props์ธ๊ฐ€์š”?! ๐Ÿ‘€
@@ -0,0 +1,82 @@ +import { useSetRecoilState } from "recoil"; +import CartItemView from "./CartItemView"; +import styled from "styled-components"; +import { selectedCartItemIdsState } from "../recoil/selectedCartItemIds"; +import { CartItem } from "../types/cartItems"; +import { useCartItemControl } from "../hooks/useCartItemControl"; + +export interface ICartItemList { + cartItems: CartItem[]; +} + +export default function CartItemList({ cartItems }: ICartItemList) { + const cartItemControl = useCartItemControl(); + const setSelectedCartItemIds = useSetRecoilState(selectedCartItemIdsState); + const isAllSelected = cartItems.every(({ isSelected }) => isSelected); + + const handleSelectAllChange = () => { + if (isAllSelected) { + setSelectedCartItemIds([]); + } else { + setSelectedCartItemIds(cartItems.map(({ id }) => id)); + } + }; + + return ( + <S.CartItemListContainer> + <S.SelectAll> + <S.Checkbox + id="select-all-checkbox" + type="checkbox" + checked={isAllSelected} + onChange={handleSelectAllChange} + /> + <S.SelectAllLabel htmlFor="select-all-checkbox">์ „์ฒด์„ ํƒ</S.SelectAllLabel> + </S.SelectAll> + <S.CartItemList> + {cartItems.map((cartItem) => ( + <CartItemView + key={cartItem.product.id} + cartItem={cartItem} + cartItemControl={cartItemControl} + /> + ))} + </S.CartItemList> + </S.CartItemListContainer> + ); +} + +const S = { + CartItemListContainer: styled.div` + display: flex; + flex-direction: column; + gap: 20px; + + margin: 36px 0 52px 0; + `, + + CartItemList: styled.div` + display: flex; + flex-direction: column; + gap: 20px; + `, + + SelectAll: styled.div` + display: flex; + align-items: center; + gap: 8px; + `, + + Checkbox: styled.input` + accent-color: black; + margin: 0; + width: 24px; + height: 24px; + `, + + SelectAllLabel: styled.label` + font-size: 12px; + font-weight: 500; + line-height: 15px; + `, +};
Unknown
(๋‹จ์ˆœ ๊ถ๊ธˆ) cartItem.id๊ฐ€ ์•„๋‹ˆ๋ผ product.id๋กœ ์„ค์ •ํ•ด์ฃผ์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,145 @@ +import { CartItem } from "../types/cartItems"; +import styled from "styled-components"; +import { UseCartItemsReturn } from "../hooks/useCartItemControl"; + +export interface CartItemViewProps { + cartItem: CartItem; + cartItemControl: UseCartItemsReturn; +} + +export default function CartItemView({ cartItem, cartItemControl }: CartItemViewProps) { + const { remove, updateQuantity, toggleSelection } = cartItemControl; + const cartItemId = cartItem.id; + + const handleCheckboxChange = () => { + toggleSelection(cartItemId); + }; + + const handleRemoveButtonClick = () => { + remove(cartItemId); + }; + + const handleIncreaseButtonClick = () => { + updateQuantity(cartItemId, cartItem.quantity + 1); + }; + + const handleDecreaseButtonClick = () => { + updateQuantity(cartItemId, cartItem.quantity - 1); + }; + + return ( + <S.CartItemContainer> + <S.TopWrapper> + <S.Checkbox type="checkbox" checked={cartItem.isSelected} onChange={handleCheckboxChange} /> + <S.RemoveButton onClick={handleRemoveButtonClick}>์‚ญ์ œ</S.RemoveButton> + </S.TopWrapper> + + <S.ProductOuterWrapper> + <S.ProductImage src={cartItem.product.imageUrl} alt="Product Image" /> + <S.ProductInnerWrapper> + <S.ProductInfo> + <S.ProductName>{cartItem.product.name}</S.ProductName> + <S.ProductPrice>{cartItem.product.price.toLocaleString()}์›</S.ProductPrice> + </S.ProductInfo> + <S.CartItemCountControl> + <S.CountButton onClick={handleDecreaseButtonClick}>-</S.CountButton> + <S.Count>{cartItem.quantity}</S.Count> + <S.CountButton onClick={handleIncreaseButtonClick}>+</S.CountButton> + </S.CartItemCountControl> + </S.ProductInnerWrapper> + </S.ProductOuterWrapper> + </S.CartItemContainer> + ); +} + +const S = { + CartItemContainer: styled.div` + display: flex; + flex-direction: column; + gap: 12px; + border-top: 1px solid #d9d9d9; + padding-top: 12px; + `, + + TopWrapper: styled.div` + display: flex; + justify-content: space-between; + align-items: center; + `, + + Checkbox: styled.input` + accent-color: black; + margin: 0; + width: 24px; + height: 24px; + `, + + RemoveButton: styled.button` + width: 40px; + height: 24px; + background-color: rgba(255, 255, 255, 1); + border: 1px solid rgba(0, 0, 0, 0.1); + border-radius: 4px; + font-size: 12px; + font-weight: 500; + line-height: 15px; + color: rgba(10, 13, 19, 1); + `, + + ProductOuterWrapper: styled.div` + display: flex; + gap: 24px; + `, + + ProductImage: styled.img` + width: 112px; + height: 112px; + border-radius: 10px; + `, + + ProductInnerWrapper: styled.div` + display: flex; + flex-direction: column; + gap: 24px; + margin: 9.5px 0; + `, + + CartItemCountControl: styled.div` + display: flex; + gap: 4px; + align-items: center; + `, + + ProductInfo: styled.div` + display: flex; + flex-direction: column; + gap: 4px; + `, + + ProductName: styled.div` + font-size: 12px; + font-weight: 500; + line-height: 15px; + `, + + ProductPrice: styled.div` + font-size: 24px; + font-weight: 700; + line-height: 34.75px; + `, + + CountButton: styled.button` + width: 24px; + height: 24px; + line-height: 10px; + border: 1px solid rgba(0, 0, 0, 0.1); + background-color: white; + border-radius: 8px; + `, + + Count: styled.div` + font-size: 12px; + width: 20px; + text-align: center; + `, +};
Unknown
์—ฌ๊ธฐ์„œ Return interface๋ฅผ ๋ณ„๋„๋กœ export ํ•ด์ค˜๋„ ์ข‹์ง€๋งŒ, [ReturnType](https://www.typescriptlang.org/ko/docs/handbook/utility-types.html#returntypetype)์ด๋ผ๋Š” ์œ ํ‹ธํ•จ์ˆ˜๋„ ์‚ฌ์šฉํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ์ด๋ ‡๊ฒŒ ์‚ฌ์šฉํ•˜๋ฉด ๋ณ„๋„์˜ interface๋ฅผ ๋งŒ๋“ค ํ•„์š” ์—†์ง€ ์•Š์„๊นŒ ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค! :)
@@ -0,0 +1,91 @@ +import { RecoilRoot, useRecoilState } from "recoil"; + +import { act } from "react"; +import { renderHook } from "@testing-library/react"; +import { updateCartItemQuantity } from "../api/cartItems"; +import { useCartItemControl } from "./useCartItemControl"; + +jest.mock("recoil", () => ({ + ...jest.requireActual("recoil"), + useRecoilState: jest.fn(), +})); +jest.mock("../api/cartItems"); +jest.mock("../utils/sessionStorage"); + +describe("useCartItemControl", () => { + // describe("remove", () => { + // const mockCartItems = [{ id: 1 }, { id: 2 }, { id: 3 }]; + // const mockRemovingCartItemId = 1; + // const mockRemovedCartItems = [{ id: 2 }, { id: 3 }]; + + // it("1. delete api ์š”์ฒญ 2. ์ƒํƒœ ๋ณ€๊ฒฝ", async () => { + // const mockDeleteCartItemRequest = removeCartItem as jest.Mock; + // const setRawCartItems = jest.fn(); + + // (useRecoilState as jest.Mock).mockImplementation(() => [mockCartItems, setRawCartItems]); + + // const { result } = renderHook(() => useCartItemControl(), { + // wrapper: RecoilRoot, + // }); + + // await act(async () => result.current.remove(mockRemovingCartItemId)); + + // expect(mockDeleteCartItemRequest).toHaveBeenCalledWith(mockRemovingCartItemId); + // expect(setRawCartItems).toHaveBeenCalledWith(mockRemovedCartItems); + // }); + // }); + + describe("updateQuantity", () => { + const mockUpdatingCartItemId = 1; + const updatingQuantity = 2; + const mockCartItems = [{ id: 1, quantity: 1 }]; + it("1. patch api ์š”์ฒญ 2. ์ƒํƒœ ๋ณ€๊ฒฝ", async () => { + const mockUpdateCartItemQuantity = updateCartItemQuantity as jest.Mock; + const setRawCartItems = jest.fn(); + + (useRecoilState as jest.Mock).mockImplementation(() => [ + mockCartItems, + setRawCartItems, + ]); + + const { result } = renderHook(() => useCartItemControl(), { + wrapper: RecoilRoot, + }); + + await act(async () => + result.current.updateQuantity(mockUpdatingCartItemId, updatingQuantity) + ); + + expect(mockUpdateCartItemQuantity).toHaveBeenCalledWith( + mockUpdatingCartItemId, + updatingQuantity + ); + expect(setRawCartItems).toHaveBeenCalledWith([{ id: 1, quantity: 2 }]); + }); + }); + + /** + * TODO: ์ƒํƒœ ๋ณ€๊ฒฝ์— ๋Œ€ํ•œ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ์ž‘์„ฑ ์š”๋ง (๋ชจํ‚นํ•œ setSelectedCartItemIds์˜ ๋‚ด๋ถ€ callback์—์„œ ๋ฌธ์ œ ๋ฐœ์ƒ) + describe("toggleSelection", () => { + const mockCartItemId = 1; + const mockSelectedCartItemIds = [1, 2]; + const mockPutInSelectedCartItemIds = putInSelectedCartItemIds as jest.Mock; + const mockSetSelectedCartItemIds = jest.fn(); + + it("1. ์Šคํ† ๋ฆฌ์ง€ ๋™๊ธฐํ™” 2. ์ƒํƒœ ๋ณ€๊ฒฝ", () => { + (useRecoilState as jest.Mock).mockImplementation(() => [ + mockSelectedCartItemIds, + mockSetSelectedCartItemIds, + ]); + + const { result } = renderHook(() => useCartItemControl(), { + wrapper: RecoilRoot, + }); + + act(() => result.current.toggleSelection(mockCartItemId)); + + expect(mockPutInSelectedCartItemIds).toHaveBeenCalledWith([2]); + }); + }); + */ +});
TypeScript
์—ฌ๊ธฐ ์ฃผ์„์€ ์ผ๋ถ€๋Ÿฌ ๋‚จ๊ฒจ๋‘์‹ ๊ฑธ๊นŒ์š”?! ๐Ÿซ
@@ -0,0 +1,91 @@ +import { RecoilRoot, useRecoilState } from "recoil"; + +import { act } from "react"; +import { renderHook } from "@testing-library/react"; +import { updateCartItemQuantity } from "../api/cartItems"; +import { useCartItemControl } from "./useCartItemControl"; + +jest.mock("recoil", () => ({ + ...jest.requireActual("recoil"), + useRecoilState: jest.fn(), +})); +jest.mock("../api/cartItems"); +jest.mock("../utils/sessionStorage"); + +describe("useCartItemControl", () => { + // describe("remove", () => { + // const mockCartItems = [{ id: 1 }, { id: 2 }, { id: 3 }]; + // const mockRemovingCartItemId = 1; + // const mockRemovedCartItems = [{ id: 2 }, { id: 3 }]; + + // it("1. delete api ์š”์ฒญ 2. ์ƒํƒœ ๋ณ€๊ฒฝ", async () => { + // const mockDeleteCartItemRequest = removeCartItem as jest.Mock; + // const setRawCartItems = jest.fn(); + + // (useRecoilState as jest.Mock).mockImplementation(() => [mockCartItems, setRawCartItems]); + + // const { result } = renderHook(() => useCartItemControl(), { + // wrapper: RecoilRoot, + // }); + + // await act(async () => result.current.remove(mockRemovingCartItemId)); + + // expect(mockDeleteCartItemRequest).toHaveBeenCalledWith(mockRemovingCartItemId); + // expect(setRawCartItems).toHaveBeenCalledWith(mockRemovedCartItems); + // }); + // }); + + describe("updateQuantity", () => { + const mockUpdatingCartItemId = 1; + const updatingQuantity = 2; + const mockCartItems = [{ id: 1, quantity: 1 }]; + it("1. patch api ์š”์ฒญ 2. ์ƒํƒœ ๋ณ€๊ฒฝ", async () => { + const mockUpdateCartItemQuantity = updateCartItemQuantity as jest.Mock; + const setRawCartItems = jest.fn(); + + (useRecoilState as jest.Mock).mockImplementation(() => [ + mockCartItems, + setRawCartItems, + ]); + + const { result } = renderHook(() => useCartItemControl(), { + wrapper: RecoilRoot, + }); + + await act(async () => + result.current.updateQuantity(mockUpdatingCartItemId, updatingQuantity) + ); + + expect(mockUpdateCartItemQuantity).toHaveBeenCalledWith( + mockUpdatingCartItemId, + updatingQuantity + ); + expect(setRawCartItems).toHaveBeenCalledWith([{ id: 1, quantity: 2 }]); + }); + }); + + /** + * TODO: ์ƒํƒœ ๋ณ€๊ฒฝ์— ๋Œ€ํ•œ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ์ž‘์„ฑ ์š”๋ง (๋ชจํ‚นํ•œ setSelectedCartItemIds์˜ ๋‚ด๋ถ€ callback์—์„œ ๋ฌธ์ œ ๋ฐœ์ƒ) + describe("toggleSelection", () => { + const mockCartItemId = 1; + const mockSelectedCartItemIds = [1, 2]; + const mockPutInSelectedCartItemIds = putInSelectedCartItemIds as jest.Mock; + const mockSetSelectedCartItemIds = jest.fn(); + + it("1. ์Šคํ† ๋ฆฌ์ง€ ๋™๊ธฐํ™” 2. ์ƒํƒœ ๋ณ€๊ฒฝ", () => { + (useRecoilState as jest.Mock).mockImplementation(() => [ + mockSelectedCartItemIds, + mockSetSelectedCartItemIds, + ]); + + const { result } = renderHook(() => useCartItemControl(), { + wrapper: RecoilRoot, + }); + + act(() => result.current.toggleSelection(mockCartItemId)); + + expect(mockPutInSelectedCartItemIds).toHaveBeenCalledWith([2]); + }); + }); + */ +});
TypeScript
๋ช…์„ธ๊ฐ€ ์กฐ๊ธˆ ๋” ๋ช…ํ™•ํ–ˆ์œผ๋ฉด ์ข‹๊ฒ ์–ด์š”! ์–ด๋–ค patch api๋ฅผ ์š”์ฒญํ–ˆ๊ณ  ์–ด๋–ป๊ฒŒ ์ƒํƒœ๊ฐ€ ๋ณ€๊ฒฝ๋˜์—ˆ๋Š”์ง€ ๊ตฌ์ฒด์ ์œผ๋กœ ๋ช…์‹œํ•˜๋ฉด ๋” ์ข‹์€ ๋ช…์„ธ๊ฐ€ ๋  ๋“ฏ ํ•ฉ๋‹ˆ๋‹ค :)
@@ -0,0 +1,22 @@ +import Header from "../components/Header"; +import styled from "styled-components"; +import CartContent from "../components/CartContent"; +import { Suspense } from "react"; + +export default function CartPage() { + return ( + <S.Container> + <Header hasBackButton={false} title="SHOP" /> + <Suspense fallback={<div>Loading...</div>}> + <CartContent /> + </Suspense> + </S.Container> + ); +} + +const S = { + Container: styled.div` + width: 429px; + border: 1px solid #808080; + `, +};
Unknown
Suspense ๊ตฌํ˜„ํ•˜์…จ๋„ค์š”..! ๐Ÿ‘ ์ถ”๊ฐ€์ ์œผ๋กœ ์ด๋ฏธ์ง€๊ฐ€ ๋กœ๋”ฉ์ƒํƒœ์ผ ๋•Œ, ํ™”๋ฉด์ด ์ ‘ํžˆ๋„ค์š”..! ์Šคํƒ€์ผ๋„ ์ถ”๊ฐ€์ ์œผ๋กœ ์ ์šฉํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ![image](https://github.com/cys4585/react-shopping-cart/assets/106071687/5c0b6fa9-7f24-4c18-8f66-f800db48bcaa)
@@ -0,0 +1,169 @@ +# 1. ํ•ต์‹ฌ ํ•œ ์ค„ ์ •์˜ + +์‚ฌ์šฉ์ž์˜ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ๋ชฉ๋ก ๋ฐ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก์„ ํ™•์ธํ•˜๊ณ , ๊ฒฐ์ œ ๋‹จ๊ณ„๋กœ ์ „ํ™˜ํ•œ๋‹ค. + +# 2. ์‚ฌ์šฉ์ž ๊ด€์ ์—์„œ ๊ธฐ๋Šฅ ๋ฆฌ์ŠคํŒ… (์„ธ๋ถ€ ๊ธฐ๋Šฅ ์ •์˜) + +- [ ] CartItem + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ์ •๋ณด๋ฅผ ๋ณด์—ฌ์ค€๋‹ค + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ์„ ์„ ํƒ/ํ•ด์ œํ•œ๋‹ค. + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ์„ ์ œ๊ฑฐํ•œ๋‹ค. + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ์ˆ˜๋Ÿ‰์„ ๋ณ€๊ฒฝํ•œ๋‹ค. +- [ ] CartItemList + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ๋ชฉ๋ก์„ ๋ณด์—ฌ์ค€๋‹ค. + - [ ] ์ „์ฒด ์„ ํƒ +- [ ] CartAmount + - [ ] ์ฃผ๋ฌธ๊ธˆ์•ก, ๋ฐฐ์†ก๋น„, ์ด ๊ฒฐ์ œ ๊ธˆ์•ก์„ ๋ณด์—ฌ์ค€๋‹ค. +- [ ] ShopHeader + - [ ] SHOP์„ ๋ณด์—ฌ์ค€๋‹ค +- [ ] BackHeader + - [ ] ๋’ค๋กœ๊ฐ€๊ธฐ ์•„์ด์ฝ˜ ํด๋ฆญ ์‹œ ๋’ค๋กœ๊ฐ„๋‹ค. + - [ ] ๋’ค๋กœ๊ฐ€๊ธฐ ์•„์ด์ฝ˜์„ ๋ณด์—ฌ์ค€๋‹ค. +- [ ] OrderConfirmButton (button ๊ธฐ๋ณธ ์š”์†Œ๋ฅผ ํ™œ์šฉ) + - [ ] ์ฃผ๋ฌธํ™•์ธ ๋ฒ„ํ†ค์„ ํด๋ฆญํ•˜๋ฉด ์ฃผ๋ฌธํ™•์ธ ํŽ˜์ด์ง€๋กœ ์ด๋™ํ•œ๋‹ค. +- [ ] BuyButton (button ๊ธฐ๋ณธ ์š”์†Œ๋ฅผ ํ™œ์šฉ) + - [ ] disabled ์ฒ˜๋ฆฌ๊ฐ€ ๋˜์–ด ์žˆ๋‹ค. +- [ ] OrderSummary + - [ ] ์ด๊ฒฐ์ œ๊ธˆ์•ก์„ ๋ณด์—ฌ์ค€๋‹ค. + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ์ข…๋ฅ˜, ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ๊ฐœ์ˆ˜๋ฅผ ๋ณด์—ฌ์ค€๋‹ค. + +# 3. ๊ตฌํ˜„์„ ์–ด๋–ป๊ฒŒ ํ• ์ง€ ๋ฆฌ์ŠคํŒ… + +- [ ] ์ƒํƒœ + + - atom + + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ๋ฐฐ์—ด + + - [ ] key: 'cartItems' + - [ ] returnType: CartItem[] + + - [ ] ์„ ํƒ์—ฌ๋ถ€ ๋ฐฐ์—ด + + - [ ] key: selectedCartItemIds + - [ ] returnType: number[] + + - selector + + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ๋ฐฐ์—ด(๊ทธ๋Ÿฐ๋ฐ ์„ ํƒ ์—ฌ๋ถ€๊ฐ€ ๋”ํ•ด์ง„) + + - [ ] key: cartItemsWithIsSelected + - [ ] returnType: CartItemWithIsSelected[] + - dependency: cartItems, selectedCartItemIds + + - [ ] ์ฃผ๋ฌธ ๊ธˆ์•ก + + - [ ] key: orderAmount + - [ ] returnType: number + - dependency: cartItemsWithIsSelected + + - [ ] ๋ฐฐ์†ก๋น„ + + - [ ] key: deliveryCost + - [ ] returnType: number + - dependency: orderAmount + + - [ ] ์ด ๊ฒฐ์ œ ๊ธˆ์•ก + + - [ ] key: totalOrderAmount + - [ ] returnType: number + - dependency: deliveryCost, orderAmount + + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ์ข…๋ฅ˜ ์ˆ˜ + + - [ ] key: uniqueCartItemsCount + - [ ] returnType: number + - dependency: cartItems + + - [ ] ์„ ํƒ๋œ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ์ข…๋ฅ˜ ์ˆ˜ + + - [ ] key: selectedUniqueCartItemsCount + - [ ] returnType: number + - dependency: selectedCartItemIds + + - [ ] ์„ ํƒ๋œ ์ด ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ๊ฐœ์ˆ˜ + + - [ ] key: selectedCartItemsCount + - [ ] returnType: number + - dependency: cartItemsWithIsSelected + +- [ ] api + + - [ ] cartItems get + - [ ] cartItems/[id] patch + - [ ] cartItems/[id] delete + +- [ ] UI + + - [ ] CartItem + - [ ] prop: cartItem + - [ ] CartItemList + - [ ] CartAmount + - [ ] Header + - [ ] prop: hasBackButton, text + - [ ] shop header: `text = shop` + - [ ] back header: `hasBackButton = true` + - [ ] Button + - [ ] prop: text, onclick, disabled + - [ ] OrderSummary + +- [ ] ์Šคํ† ๋ฆฌ์ง€ + - ์„ธ์…˜ ์Šคํ† ๋ฆฌ์ง€ ํ™œ์šฉ + - ๊ด€๋ฆฌ ๋Œ€์ƒ: ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ์„ ํƒ์—ฌ๋ถ€ + - ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ: `number[]` + +# 4. ๊ตฌํ˜„ ์ˆœ์„œ + +1. CartList + +- [x] atom ์ •์˜ (cartItemsState, selectedCartItemIds) +- [x] selector ์ •์˜ (cartItemsWithIsSelected) +- [x] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ๋ชฉ๋ก ๋ถˆ๋Ÿฌ์˜ค๊ธฐ (api fetching) +- [x] CartItem + - [x] cartItems/[id] patch (๊ฐœ์ˆ˜ ์ˆ˜์ •) + - [x] cartItems/[id] delete (์žฅ๋ฐ”๊ตฌ๋‹ˆ ์ƒํ’ˆ ์‚ญ์ œ) + - [x] UI ๊ตฌํ˜„(prop: cartItem) +- [x] empty case ๋Œ€์‘ +- [x] atom & select ์„ธ๋ถ€ ๊ตฌํ˜„(api, session storage ์—ฐ๊ฒฐ) & ์ ์šฉ +- [x] ์ „์ฒด ์„ ํƒ ๊ธฐ๋Šฅ ๊ตฌํ˜„ + +1. CartAmount + +- [x] selector ์ •์˜ (orderAmount, deliveryCost, totalOrderAmount) +- [x] UI ๊ตฌํ˜„ + +3. CartTitle + +- [x] selector ์ •์˜ (uniqueCartItemsCount) +- [x] UI ๊ตฌํ˜„ + +1. Header, Footer + +2. OrderSummary + +- [x] selector ์ •์˜ (selectedUniqueCartItemsCount, selectedCartItemsCount, totalOrderAmount) +- [x] UI ๊ตฌํ˜„ + +1. UX ์ตœ์ ํ™” + +- [x] ErrorBoundary, Suspense + +### test + +1. CartList + +- rawCartItemsState + - [x] ์ดˆ๊ธฐ๊ฐ’์ด ์ž˜ ์„ธํŒ…๋˜๋Š”์ง€ +- selectedCartItemIdsState + - [x] ์ดˆ๊ธฐ๊ฐ’์ด ์ž˜ ์„ธํŒ…๋˜๋Š”์ง€ + - [x] set์ด ๋ฐœ์ƒํ•  ๋•Œ putInSelectedCartItemIds์ด ํ˜ธ์ถœ๋˜๋Š”์ง€ +- useCartItemControl + - [x] remove (1. delete api ์š”์ฒญ 2. ์ƒํƒœ ๋ณ€๊ฒฝ) + - [x] updateQuantity (1. patch api ์š”์ฒญ 2. ์ƒํƒœ ๋ณ€๊ฒฝ) + - [x] toggleSelection (์ƒํƒœ ๋ณ€๊ฒฝ) + +### ๋‚จ์€๊ฑฐ + +- [x] useCartItemControl ํ…Œ์ŠคํŠธ +- [x] OrderSummary ์ปดํฌ๋„ŒํŠธ ๊ฐœ๋ฐœ ๋ฐ ๋ผ์šฐํŠธ ์ฒ˜๋ฆฌ +- [x] ErrorBoundary
Unknown
์•„๋‹™๋‹ˆ๋‹ค...ใ…Ž ์ฒดํฌ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ชฉ๋ก์ฒ˜๋Ÿผ ์‚ฌ์šฉํ–ˆ๋„ค์š”. ๋ช…๋ฐฑํ•œ ๋ˆ„๋ฝ์ž…๋‹ˆ๋‹คใ…œใ…œใ…œ
@@ -1,10 +1,24 @@ import "./App.css"; +import { RecoilRoot } from "recoil"; +import { BrowserRouter, Route, Routes } from "react-router-dom"; + +import CartPage from "./pages/CartPage"; +import { PATH } from "./constants/path"; +import OrderSummaryPage from "./pages/OrderSummaryPage"; +import { ErrorBoundary } from "react-error-boundary"; function App() { return ( - <> - <h1>react-shopping-cart</h1> - </> + <BrowserRouter> + <RecoilRoot> + <ErrorBoundary fallbackRender={({ error }) => error.message}> + <Routes> + <Route path={PATH.cart} element={<CartPage />} /> + <Route path={PATH.orderSummary} element={<OrderSummaryPage />} /> + </Routes> + </ErrorBoundary> + </RecoilRoot> + </BrowserRouter> ); }
Unknown
BrowserRouter์™€ ๋น„๊ตํ•ด์„œ ๋Œ€ํ‘œ์ ์ธ ์ฐจ์ด๊ฐ€ ์–ด๋–ค ๊ฒŒ ์žˆ์„๊นŒ์š”??? ๋‹ค์Œ์— ํ•œ ๋ฒˆ ์‹œ๋„ํ•ด ๋ณด๋„๋ก ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,31 @@ +import styled from "styled-components"; + +export interface IButtonProps extends React.HTMLAttributes<HTMLButtonElement> { + disabled?: boolean; +} + +export default function Button({ children, ...attributes }: IButtonProps) { + return <S.Button {...attributes}>{children}</S.Button>; +} + +const S = { + Button: styled.button` + position: fixed; + bottom: 0; + max-width: 429px; + + height: 64px; + font-size: 16px; + font-weight: 700; + text-align: center; + width: 100%; + + background-color: black; + color: white; + border: none; + cursor: pointer; + &:disabled { + background-color: rgba(190, 190, 190, 1); + } + `, +};
Unknown
์˜ค... ๋„ˆ๋ฌด ์ข‹์„ ๊ฒƒ ๊ฐ™๋„ค์š”!! ํ˜น์‹œ ํด๋”๋„ค์ด๋ฐ์— ๋Œ€ํ•œ ์˜๊ฒฌ๋„ ์žˆ์œผ์‹ค๊นŒ์š”~? `components/styled` ..?
@@ -0,0 +1,91 @@ +import { useRecoilValue } from "recoil"; +import styled from "styled-components"; +import { deliveryCostState, orderAmountState, totalOrderAmountState } from "../recoil/cartAmount"; +import { ReactComponent as InfoIcon } from "../assets/info-icon.svg"; + +export interface ICartAmountProps {} + +export default function CartAmount() { + const orderAmount = useRecoilValue(orderAmountState); + const deliveryCost = useRecoilValue(deliveryCostState); + const totalOrderAmount = useRecoilValue(totalOrderAmountState); + + return ( + <S.CartAmountContainer> + <S.CartAmountNoti> + <S.InfoIcon /> + <S.CartAmountNotiText> + ์ด ์ฃผ๋ฌธ ๊ธˆ์•ก์ด 100,000์› ์ด์ƒ์ผ ๊ฒฝ์šฐ ๋ฌด๋ฃŒ ๋ฐฐ์†ก๋ฉ๋‹ˆ๋‹ค. + </S.CartAmountNotiText> + </S.CartAmountNoti> + + <S.UpperCartAmountInfoWrapper> + <S.CartAmountInfo> + <S.AmountText>์ฃผ๋ฌธ ๊ธˆ์•ก</S.AmountText>{" "} + <S.Amount>{orderAmount.toLocaleString()}์›</S.Amount> + </S.CartAmountInfo> + <S.CartAmountInfo> + <S.AmountText>๋ฐฐ์†ก๋น„</S.AmountText> <S.Amount>{deliveryCost.toLocaleString()}์›</S.Amount> + </S.CartAmountInfo> + </S.UpperCartAmountInfoWrapper> + <S.LowerCartAmountInfoWrapper> + <S.CartAmountInfo> + <S.AmountText>์ด ์ฃผ๋ฌธ ๊ธˆ์•ก</S.AmountText>{" "} + <S.Amount>{totalOrderAmount.toLocaleString()}์›</S.Amount> + </S.CartAmountInfo> + </S.LowerCartAmountInfoWrapper> + </S.CartAmountContainer> + ); +} + +const S = { + CartAmountContainer: styled.div` + display: flex; + flex-direction: column; + gap: 12px; + `, + + CartAmountNoti: styled.p` + font-size: 14px; + color: #888; + margin-bottom: 20px; + display: flex; + align-items: center; + gap: 4px; + `, + + UpperCartAmountInfoWrapper: styled.div` + border-top: 1px solid rgba(0, 0, 0, 0.1); + `, + + LowerCartAmountInfoWrapper: styled.div` + border-top: 1px solid rgba(0, 0, 0, 0.1); + `, + + CartAmountInfo: styled.div` + display: flex; + justify-content: space-between; + align-items: center; + padding-top: 12px; + `, + + AmountText: styled.span` + font-size: 16px; + font-weight: 700; + `, + + Amount: styled.span` + font-size: 24px; + font-weight: 700; + `, + InfoIcon: styled(InfoIcon)` + width: 16px; + height: 16px; + `, + CartAmountNotiText: styled.span` + font-size: 12px; + font-weight: 500; + line-height: 15px; + color: rgba(10, 13, 19, 1); + `, +};
Unknown
์ฒ˜์Œ์— ๊ตฌ์กฐ๋ฅผ ์ž๋™ ์™„์„ฑํ•ด์ฃผ๋Š” ๋ฌด์Šจ ๋‹จ์ถ• ๋ช…๋ น์–ด๊ฐ€ ์žˆ์—ˆ๋Š”๋ฐ, ๊ฑ”๊ฐ€ ๋งŒ๋“ค์–ด์คฌ๊ณ  ๊ทธ๊ฑธ ์ง€์šฐ์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค... ๋‹ค๋ฅธ ๋งŽ์€ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๊ทธ๋ ‡๋„ค์š”...ใ…Ž
@@ -0,0 +1,82 @@ +import { useSetRecoilState } from "recoil"; +import CartItemView from "./CartItemView"; +import styled from "styled-components"; +import { selectedCartItemIdsState } from "../recoil/selectedCartItemIds"; +import { CartItem } from "../types/cartItems"; +import { useCartItemControl } from "../hooks/useCartItemControl"; + +export interface ICartItemList { + cartItems: CartItem[]; +} + +export default function CartItemList({ cartItems }: ICartItemList) { + const cartItemControl = useCartItemControl(); + const setSelectedCartItemIds = useSetRecoilState(selectedCartItemIdsState); + const isAllSelected = cartItems.every(({ isSelected }) => isSelected); + + const handleSelectAllChange = () => { + if (isAllSelected) { + setSelectedCartItemIds([]); + } else { + setSelectedCartItemIds(cartItems.map(({ id }) => id)); + } + }; + + return ( + <S.CartItemListContainer> + <S.SelectAll> + <S.Checkbox + id="select-all-checkbox" + type="checkbox" + checked={isAllSelected} + onChange={handleSelectAllChange} + /> + <S.SelectAllLabel htmlFor="select-all-checkbox">์ „์ฒด์„ ํƒ</S.SelectAllLabel> + </S.SelectAll> + <S.CartItemList> + {cartItems.map((cartItem) => ( + <CartItemView + key={cartItem.product.id} + cartItem={cartItem} + cartItemControl={cartItemControl} + /> + ))} + </S.CartItemList> + </S.CartItemListContainer> + ); +} + +const S = { + CartItemListContainer: styled.div` + display: flex; + flex-direction: column; + gap: 20px; + + margin: 36px 0 52px 0; + `, + + CartItemList: styled.div` + display: flex; + flex-direction: column; + gap: 20px; + `, + + SelectAll: styled.div` + display: flex; + align-items: center; + gap: 8px; + `, + + Checkbox: styled.input` + accent-color: black; + margin: 0; + width: 24px; + height: 24px; + `, + + SelectAllLabel: styled.label` + font-size: 12px; + font-weight: 500; + line-height: 15px; + `, +};
Unknown
์—‡..ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ ์—†์Šต๋‹ˆ๋‹ค. ์ˆœ๊ฐ„ ์—๋Ÿฌ ๋œฐ ๊ฑฐ๋ผ ์ƒ๊ฐํ•˜๊ณ  ์•„์ฐ”ํ–ˆ๋„ค์š”. ํ•˜์ง€๋งŒ, `cartItem.id`๊ฐ€ ๋งž๋Š” ํ‘œํ˜„์ด๊ณ , ์‹ค์ˆ˜๋กœ `product.id`๋กœ ํ•œ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,145 @@ +import { CartItem } from "../types/cartItems"; +import styled from "styled-components"; +import { UseCartItemsReturn } from "../hooks/useCartItemControl"; + +export interface CartItemViewProps { + cartItem: CartItem; + cartItemControl: UseCartItemsReturn; +} + +export default function CartItemView({ cartItem, cartItemControl }: CartItemViewProps) { + const { remove, updateQuantity, toggleSelection } = cartItemControl; + const cartItemId = cartItem.id; + + const handleCheckboxChange = () => { + toggleSelection(cartItemId); + }; + + const handleRemoveButtonClick = () => { + remove(cartItemId); + }; + + const handleIncreaseButtonClick = () => { + updateQuantity(cartItemId, cartItem.quantity + 1); + }; + + const handleDecreaseButtonClick = () => { + updateQuantity(cartItemId, cartItem.quantity - 1); + }; + + return ( + <S.CartItemContainer> + <S.TopWrapper> + <S.Checkbox type="checkbox" checked={cartItem.isSelected} onChange={handleCheckboxChange} /> + <S.RemoveButton onClick={handleRemoveButtonClick}>์‚ญ์ œ</S.RemoveButton> + </S.TopWrapper> + + <S.ProductOuterWrapper> + <S.ProductImage src={cartItem.product.imageUrl} alt="Product Image" /> + <S.ProductInnerWrapper> + <S.ProductInfo> + <S.ProductName>{cartItem.product.name}</S.ProductName> + <S.ProductPrice>{cartItem.product.price.toLocaleString()}์›</S.ProductPrice> + </S.ProductInfo> + <S.CartItemCountControl> + <S.CountButton onClick={handleDecreaseButtonClick}>-</S.CountButton> + <S.Count>{cartItem.quantity}</S.Count> + <S.CountButton onClick={handleIncreaseButtonClick}>+</S.CountButton> + </S.CartItemCountControl> + </S.ProductInnerWrapper> + </S.ProductOuterWrapper> + </S.CartItemContainer> + ); +} + +const S = { + CartItemContainer: styled.div` + display: flex; + flex-direction: column; + gap: 12px; + border-top: 1px solid #d9d9d9; + padding-top: 12px; + `, + + TopWrapper: styled.div` + display: flex; + justify-content: space-between; + align-items: center; + `, + + Checkbox: styled.input` + accent-color: black; + margin: 0; + width: 24px; + height: 24px; + `, + + RemoveButton: styled.button` + width: 40px; + height: 24px; + background-color: rgba(255, 255, 255, 1); + border: 1px solid rgba(0, 0, 0, 0.1); + border-radius: 4px; + font-size: 12px; + font-weight: 500; + line-height: 15px; + color: rgba(10, 13, 19, 1); + `, + + ProductOuterWrapper: styled.div` + display: flex; + gap: 24px; + `, + + ProductImage: styled.img` + width: 112px; + height: 112px; + border-radius: 10px; + `, + + ProductInnerWrapper: styled.div` + display: flex; + flex-direction: column; + gap: 24px; + margin: 9.5px 0; + `, + + CartItemCountControl: styled.div` + display: flex; + gap: 4px; + align-items: center; + `, + + ProductInfo: styled.div` + display: flex; + flex-direction: column; + gap: 4px; + `, + + ProductName: styled.div` + font-size: 12px; + font-weight: 500; + line-height: 15px; + `, + + ProductPrice: styled.div` + font-size: 24px; + font-weight: 700; + line-height: 34.75px; + `, + + CountButton: styled.button` + width: 24px; + height: 24px; + line-height: 10px; + border: 1px solid rgba(0, 0, 0, 0.1); + background-color: white; + border-radius: 8px; + `, + + Count: styled.div` + font-size: 12px; + width: 20px; + text-align: center; + `, +};
Unknown
~~์œผ์Œ... ์–ด๋–ค ์‹์œผ๋กœ ์จ์•ผ ์ข‹์„์ง€ ๊ฐ์ด ์˜ค์งˆ ์•Š๋„ค์š”... ํ˜ธ์˜ฅ์‹œ ์งค๋ง‰ํ•œ ์˜ˆ์‹œ๋ฅผ ๋“ค์–ด์ฃผ์‹ค ์ˆ˜ ์žˆ์œผ์‹ค๊นŒ์š”?~~ ์˜คํ˜ธ~ ์ข‹๋„ค์š”. ๊ฟ€ ํŒ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค. ํ•œ ๊ฐ€์ง€ ์ด์•ผ๊ธฐ ๋‚˜๋ˆ ๋ณด๊ณ  ์‹ถ์€ ๋ถ€๋ถ„์ด ์žˆ์Šต๋‹ˆ๋‹ค! ์–ด๋–ค ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค ๋•Œ ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๋งŒ๋“ค์–ด๋‘๋ฉด ๊ตฌ์กฐ๊ฐ€ ๋จธ๋ฆฌ์— ์ž˜ ๋“ค์–ด์˜ค๋Š” ๊ฒƒ ๊ฐ™๋‹ค๊ณ  ์ƒ๊ฐํ•ด์š”. ์ด๋Ÿฐ ์ธก๋ฉด์—์„œ ๋ฐ˜ํ™˜ ํƒ€์ž…์„ ๋ณ„๋„๋กœ ๋งŒ๋“œ๋Š” ๊ฒŒ ์ข‹๋‹ค๊ณ  ์ƒ๊ฐ์„ ํ–ˆ๋Š”๋ฐ, ๋‚™ํƒ€์˜ ์˜๊ฒฌ์„ ๋“ค์–ด๋ณด๊ณ  ์‹ถ๋„ค์š”!!
@@ -0,0 +1,91 @@ +import { RecoilRoot, useRecoilState } from "recoil"; + +import { act } from "react"; +import { renderHook } from "@testing-library/react"; +import { updateCartItemQuantity } from "../api/cartItems"; +import { useCartItemControl } from "./useCartItemControl"; + +jest.mock("recoil", () => ({ + ...jest.requireActual("recoil"), + useRecoilState: jest.fn(), +})); +jest.mock("../api/cartItems"); +jest.mock("../utils/sessionStorage"); + +describe("useCartItemControl", () => { + // describe("remove", () => { + // const mockCartItems = [{ id: 1 }, { id: 2 }, { id: 3 }]; + // const mockRemovingCartItemId = 1; + // const mockRemovedCartItems = [{ id: 2 }, { id: 3 }]; + + // it("1. delete api ์š”์ฒญ 2. ์ƒํƒœ ๋ณ€๊ฒฝ", async () => { + // const mockDeleteCartItemRequest = removeCartItem as jest.Mock; + // const setRawCartItems = jest.fn(); + + // (useRecoilState as jest.Mock).mockImplementation(() => [mockCartItems, setRawCartItems]); + + // const { result } = renderHook(() => useCartItemControl(), { + // wrapper: RecoilRoot, + // }); + + // await act(async () => result.current.remove(mockRemovingCartItemId)); + + // expect(mockDeleteCartItemRequest).toHaveBeenCalledWith(mockRemovingCartItemId); + // expect(setRawCartItems).toHaveBeenCalledWith(mockRemovedCartItems); + // }); + // }); + + describe("updateQuantity", () => { + const mockUpdatingCartItemId = 1; + const updatingQuantity = 2; + const mockCartItems = [{ id: 1, quantity: 1 }]; + it("1. patch api ์š”์ฒญ 2. ์ƒํƒœ ๋ณ€๊ฒฝ", async () => { + const mockUpdateCartItemQuantity = updateCartItemQuantity as jest.Mock; + const setRawCartItems = jest.fn(); + + (useRecoilState as jest.Mock).mockImplementation(() => [ + mockCartItems, + setRawCartItems, + ]); + + const { result } = renderHook(() => useCartItemControl(), { + wrapper: RecoilRoot, + }); + + await act(async () => + result.current.updateQuantity(mockUpdatingCartItemId, updatingQuantity) + ); + + expect(mockUpdateCartItemQuantity).toHaveBeenCalledWith( + mockUpdatingCartItemId, + updatingQuantity + ); + expect(setRawCartItems).toHaveBeenCalledWith([{ id: 1, quantity: 2 }]); + }); + }); + + /** + * TODO: ์ƒํƒœ ๋ณ€๊ฒฝ์— ๋Œ€ํ•œ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ์ž‘์„ฑ ์š”๋ง (๋ชจํ‚นํ•œ setSelectedCartItemIds์˜ ๋‚ด๋ถ€ callback์—์„œ ๋ฌธ์ œ ๋ฐœ์ƒ) + describe("toggleSelection", () => { + const mockCartItemId = 1; + const mockSelectedCartItemIds = [1, 2]; + const mockPutInSelectedCartItemIds = putInSelectedCartItemIds as jest.Mock; + const mockSetSelectedCartItemIds = jest.fn(); + + it("1. ์Šคํ† ๋ฆฌ์ง€ ๋™๊ธฐํ™” 2. ์ƒํƒœ ๋ณ€๊ฒฝ", () => { + (useRecoilState as jest.Mock).mockImplementation(() => [ + mockSelectedCartItemIds, + mockSetSelectedCartItemIds, + ]); + + const { result } = renderHook(() => useCartItemControl(), { + wrapper: RecoilRoot, + }); + + act(() => result.current.toggleSelection(mockCartItemId)); + + expect(mockPutInSelectedCartItemIds).toHaveBeenCalledWith([2]); + }); + }); + */ +});
TypeScript
ํ…Œ์ŠคํŠธ ์ฝ”๋“œ ์ž‘์„ฑ ์ค‘ ํฌ๊ธฐํ•œ ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค! ๋ชจํ‚นํ•œ setSelectedCartItemIds์˜ ๋‚ด๋ถ€ callback์—์„œ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•˜๊ณ  ์žˆ๋Š”๋ฐ, ํ•ด๊ฒฐ์„ ๋ชปํ•ด์„œ ์ฃผ์„์œผ๋กœ ์ฒ˜๋ฆฌํ–ˆ์–ด์š”. ์•„์‰ฌ์›Œ์„œ ์ง€์šฐ์ง„ ์•Š๊ณ  ๋ƒ…๋’€์Šต๋‹ˆ๋‹ค...
@@ -0,0 +1,22 @@ +import Header from "../components/Header"; +import styled from "styled-components"; +import CartContent from "../components/CartContent"; +import { Suspense } from "react"; + +export default function CartPage() { + return ( + <S.Container> + <Header hasBackButton={false} title="SHOP" /> + <Suspense fallback={<div>Loading...</div>}> + <CartContent /> + </Suspense> + </S.Container> + ); +} + +const S = { + Container: styled.div` + width: 429px; + border: 1px solid #808080; + `, +};
Unknown
์ •ํ™•ํžˆ ๊ฐ™์€ ๋ถ€๋ถ„์— ํ”ผํ„ฐ์—๊ฒŒ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ๋ฐ›์•˜์–ด์š”! ๋‚™ํƒ€ ๋‚ ์นด๋กœ์›€์ด ๊ฑฐ์˜ ๋ญ ํ˜„์ง์ž”๋ฐ์š”? ๐Ÿ‘ "์ „์ฒด ๋ ˆ์ด์•„์›ƒ์ด ์œ ์ง€๋˜๋„๋ก ์Šคํƒ€์ผ๋ง์„ ํ•ด์ฃผ๋ฉด, CLS(Cumulative Layout Shift)๋ฅผ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ"์ด๋ผ๋Š” ํ”ผํ„ฐ์˜ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ๊ณต์œ ํ•ด๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,31 @@ +import styled from "styled-components"; + +export interface IButtonProps extends React.HTMLAttributes<HTMLButtonElement> { + disabled?: boolean; +} + +export default function Button({ children, ...attributes }: IButtonProps) { + return <S.Button {...attributes}>{children}</S.Button>; +} + +const S = { + Button: styled.button` + position: fixed; + bottom: 0; + max-width: 429px; + + height: 64px; + font-size: 16px; + font-weight: 700; + text-align: center; + width: 100%; + + background-color: black; + color: white; + border: none; + cursor: pointer; + &:disabled { + background-color: rgba(190, 190, 190, 1); + } + `, +};
Unknown
ps. ์ €๋Š” ๊ฐœ์ธ์ ์œผ๋กœ `common` ์ด๋ผ๋Š” ํด๋”๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค...!
@@ -0,0 +1,91 @@ +import { useRecoilValue } from "recoil"; +import styled from "styled-components"; +import { deliveryCostState, orderAmountState, totalOrderAmountState } from "../recoil/cartAmount"; +import { ReactComponent as InfoIcon } from "../assets/info-icon.svg"; + +export interface ICartAmountProps {} + +export default function CartAmount() { + const orderAmount = useRecoilValue(orderAmountState); + const deliveryCost = useRecoilValue(deliveryCostState); + const totalOrderAmount = useRecoilValue(totalOrderAmountState); + + return ( + <S.CartAmountContainer> + <S.CartAmountNoti> + <S.InfoIcon /> + <S.CartAmountNotiText> + ์ด ์ฃผ๋ฌธ ๊ธˆ์•ก์ด 100,000์› ์ด์ƒ์ผ ๊ฒฝ์šฐ ๋ฌด๋ฃŒ ๋ฐฐ์†ก๋ฉ๋‹ˆ๋‹ค. + </S.CartAmountNotiText> + </S.CartAmountNoti> + + <S.UpperCartAmountInfoWrapper> + <S.CartAmountInfo> + <S.AmountText>์ฃผ๋ฌธ ๊ธˆ์•ก</S.AmountText>{" "} + <S.Amount>{orderAmount.toLocaleString()}์›</S.Amount> + </S.CartAmountInfo> + <S.CartAmountInfo> + <S.AmountText>๋ฐฐ์†ก๋น„</S.AmountText> <S.Amount>{deliveryCost.toLocaleString()}์›</S.Amount> + </S.CartAmountInfo> + </S.UpperCartAmountInfoWrapper> + <S.LowerCartAmountInfoWrapper> + <S.CartAmountInfo> + <S.AmountText>์ด ์ฃผ๋ฌธ ๊ธˆ์•ก</S.AmountText>{" "} + <S.Amount>{totalOrderAmount.toLocaleString()}์›</S.Amount> + </S.CartAmountInfo> + </S.LowerCartAmountInfoWrapper> + </S.CartAmountContainer> + ); +} + +const S = { + CartAmountContainer: styled.div` + display: flex; + flex-direction: column; + gap: 12px; + `, + + CartAmountNoti: styled.p` + font-size: 14px; + color: #888; + margin-bottom: 20px; + display: flex; + align-items: center; + gap: 4px; + `, + + UpperCartAmountInfoWrapper: styled.div` + border-top: 1px solid rgba(0, 0, 0, 0.1); + `, + + LowerCartAmountInfoWrapper: styled.div` + border-top: 1px solid rgba(0, 0, 0, 0.1); + `, + + CartAmountInfo: styled.div` + display: flex; + justify-content: space-between; + align-items: center; + padding-top: 12px; + `, + + AmountText: styled.span` + font-size: 16px; + font-weight: 700; + `, + + Amount: styled.span` + font-size: 24px; + font-weight: 700; + `, + InfoIcon: styled(InfoIcon)` + width: 16px; + height: 16px; + `, + CartAmountNotiText: styled.span` + font-size: 12px; + font-weight: 500; + line-height: 15px; + color: rgba(10, 13, 19, 1); + `, +};
Unknown
S-dot ์ปจ๋ฒค์…˜ ์ข‹๋„ค์š”๐Ÿ‘ ๋‹ค์Œ์— ์ €๋„ ์จ๋ด์•ผ๊ฒ ์–ด์š”!
@@ -0,0 +1,21 @@ +import { useNavigate } from "react-router-dom"; +import { PATH } from "../constants/path"; +import Button from "./Button"; +import { useRecoilValue } from "recoil"; +import { selectedCartItemIdsState } from "../recoil/selectedCartItemIds"; + +export default function CartButton() { + const navigate = useNavigate(); + const selectedCartItemIds = useRecoilValue(selectedCartItemIdsState); + const isDisabled = selectedCartItemIds.length === 0; + + const handleOrderConfirmButtonClick = () => { + navigate(PATH.orderSummary); + }; + + return ( + <Button disabled={isDisabled} onClick={handleOrderConfirmButtonClick}> + ์ฃผ๋ฌธ ํ™•์ธ + </Button> + ); +}
Unknown
๋ฒ„ํŠผ ์ปดํฌ๋„ŒํŠธ์—์„œ disabled, onClick์„ ๋ฐ›์„ ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ค˜๋„ ์ข‹์•˜์„ ๊ฒƒ ๊ฐ™์•„์š”! ๊ทธ๋Ÿผ `CartButton` ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ณ„๋„๋กœ ๋งŒ๋“ค์ง€ ์•Š๊ณ  `Button` ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ฐ”๋กœ ์žฌ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!ใ…Žใ…Ž (์•„๋‹ˆ๋ฉด ํ˜น์‹œ ๋ณ„๋„๋กœ ์ด๋ ‡๊ฒŒ ๋งŒ๋“ค์–ด์ฃผ์‹  ์—ฐ์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š”?)
@@ -0,0 +1,50 @@ +import styled from "styled-components"; +import { cartItemsState } from "../recoil/cartItems"; +import { useRecoilValue } from "recoil"; +import CartTitle from "./CartTitle"; +import CartItemList from "./CartItemList"; +import CartAmount from "./CartAmount"; +import CartButton from "./CartButton"; + +export default function CartContent() { + const cartItems = useRecoilValue(cartItemsState); + + const ๋‚ด์šฉ๋ฌผ = + cartItems.length === 0 ? ( + <S.EmptyMessage>์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ๋‹ด์€ ์ƒํ’ˆ์ด ์—†์Šต๋‹ˆ๋‹ค.</S.EmptyMessage> + ) : ( + <> + <CartItemList cartItems={cartItems} /> + <CartAmount /> + </> + ); + + return ( + <> + <S.Content> + <CartTitle /> + {๋‚ด์šฉ๋ฌผ} + </S.Content> + <CartButton /> + </> + ); +} + +const S = { + EmptyMessage: styled.div` + position: fixed; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + font-size: 16px; + font-weight: 400; + line-height: 16px; + color: rgba(10, 13, 19, 1); + width: fit-content; + margin: 0 auto; + `, + Content: styled.div` + padding: 36px 24px 100px 24px; + min-height: 100vh; + `, +};
Unknown
์˜ค! ํ•œ๊ตญ์–ด๋กœ ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•ด์ฃผ์‹  ์ด์œ ๊ฐ€ ์žˆ์œผ์‹ค๊นŒ์š”? ๋ณดํ†ต ๋ณ€์ˆ˜๋Š” ์˜์–ด๋กœ ์„ ์–ธํ•˜๋Š”๋ฐ ์—ฌ๊ธฐ ํ•œ๊ตญ๋ง์ด๋ผ ์กฐ๊ธˆ ๋‚ฎ์„ค๊ณ  ์‹ ๊ธฐํ•˜๋„ค์š”!
@@ -0,0 +1,49 @@ +import { useRecoilState, useSetRecoilState } from "recoil"; +import { removeCartItem, updateCartItemQuantity } from "../api/cartItems"; +import { CartItemId } from "../types/cartItems"; +import { rawCartItemsState } from "../recoil/rawCartItems"; +import { selectedCartItemIdsState } from "../recoil/selectedCartItemIds"; + +export interface UseCartItemsReturn { + remove: (cartItemId: CartItemId) => void; + updateQuantity: (cartItemId: CartItemId, quantity: number) => void; + toggleSelection: (cartItemId: CartItemId) => void; +} + +export const useCartItemControl = (): UseCartItemsReturn => { + const [rawCartItems, setRawCartItems] = useRecoilState(rawCartItemsState); + const setSelectedCartItemIds = useSetRecoilState(selectedCartItemIdsState); + + const remove = async (cartItemId: CartItemId) => { + await removeCartItem(cartItemId); + + setSelectedCartItemIds((prev) => prev.filter((id) => id !== cartItemId)); + + const filteredCartItems = rawCartItems.filter((cartItem) => cartItem.id !== cartItemId); + setRawCartItems(filteredCartItems); + }; + + const updateQuantity = async (cartItemId: CartItemId, quantity: number) => { + if (quantity < 1) return; + + await updateCartItemQuantity(cartItemId, quantity); + + const updatedCartItems = rawCartItems.map((cartItem) => + cartItem.id === cartItemId ? { ...cartItem, quantity } : cartItem + ); + setRawCartItems(updatedCartItems); + }; + + const toggleSelection = (cartItemId: CartItemId) => { + setSelectedCartItemIds((prev) => { + const isSelected = prev.includes(cartItemId); + return isSelected ? prev.filter((id) => id !== cartItemId) : [...prev, cartItemId]; + }); + }; + + return { + remove, + updateQuantity, + toggleSelection, + }; +};
TypeScript
๋ณ„๋„์˜ hook์œผ๋กœ ๋ถ„๋ฆฌํ•ด์ฃผ์…จ๊ตฐ์š”! ์ƒ๊ฐํ•ด๋ณด์ง€ ๋ชปํ–ˆ๋˜ ๋ฐฉ๋ฒ•์ธ๋ฐ, ์ด๋ ‡๊ฒŒ ๋ชจ์•„๋‘๋‹ˆ ๊ต‰์žฅํžˆ ๊ด€์‹ฌ์‚ฌ ๋ถ„๋ฆฌ๊ฐ€ ์ž˜ ์ด๋ฃจ์–ด์กŒ๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์—ˆ์–ด์š”๐Ÿ‘๐Ÿ‘๐Ÿ‘
@@ -1,10 +1,24 @@ import "./App.css"; +import { RecoilRoot } from "recoil"; +import { BrowserRouter, Route, Routes } from "react-router-dom"; + +import CartPage from "./pages/CartPage"; +import { PATH } from "./constants/path"; +import OrderSummaryPage from "./pages/OrderSummaryPage"; +import { ErrorBoundary } from "react-error-boundary"; function App() { return ( - <> - <h1>react-shopping-cart</h1> - </> + <BrowserRouter> + <RecoilRoot> + <ErrorBoundary fallbackRender={({ error }) => error.message}> + <Routes> + <Route path={PATH.cart} element={<CartPage />} /> + <Route path={PATH.orderSummary} element={<OrderSummaryPage />} /> + </Routes> + </ErrorBoundary> + </RecoilRoot> + </BrowserRouter> ); }
Unknown
์ œ๊ฐ€ ์œ ์˜๋ฏธํ•œ ์ฐจ์ด์— ๋Œ€ํ•ด์„œ๋Š” ์•Œ์•„๋ณด์ง€ ๋ชปํ•ด์„œ ๋‹ต๋ณ€์„ ์„ฃ๋ถˆ๋ฆฌ ๋“œ๋ฆด ์ˆ˜๊ฐ€ ์—†๋„ค์š”..! ๋‹ค๋งŒ, ์กฐ๊ธˆ ๋” ์ตœ์‹  ๋ฌธ๋ฒ•์ด๋‹ค ๋ณด๋‹ˆ ์ตœ์‹  ๋ฌธ๋ฒ•์— ๋งž์ถฐ์„œ ์ ์šฉํ•ด๋ด๋„ ๊ดœ์ฐฎ์ง€ ์•Š์„๊นŒ ์‹ถ์—ˆ์Šต๋‹ˆ๋‹ค! [ํ•ด๋‹น ๋ธ”๋กœ๊ทธ](https://velog.io/@kimbyeonghwa/createBrowserRouter-vs-BrowserRouter)์—์„œ๋Š” ๋ชจ๋“ˆํ™”๊ฐ€ ๊ฐ€๋Šฅํ•œ ์ ์„ ๊ผฝ์•˜๋„ค์š”! ์ €๋„ ๋ชจ๋“ˆํ™”๊ฐ€ ๊ฐ€๋Šฅํ•œ ์ ์ด ๊ฐ€์žฅ ์ด์ ์ด ํฌ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์–ด์š”! https://github.com/Largopie/react-shopping-cart/blob/step1/src/router.tsx ๊ฐœ์ธ์ ์œผ๋กœ๋Š” ์ด์™€ ๊ฐ™์ด ๋ชจ๋“ˆํ™”ํ•ด์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์–ด์„œ ์ฝ”๋“œ๋ฅผ ๋ณด๋‹ค ์ง๊ด€์ ์œผ๋กœ ํŒŒ์•…ํ•  ์ˆ˜ ์žˆ์—ˆ๋˜ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ++ ๊ณต์‹๋ฌธ์„œ์—์„œ๋„ ๊ถŒ์žฅํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋„ค์š”! > This is the recommended router for all React Router web projects. It uses the [DOM History API](https://developer.mozilla.org/en-US/docs/Web/API/History) to update the URL and manage the history stack.
@@ -0,0 +1,31 @@ +import styled from "styled-components"; + +export interface IButtonProps extends React.HTMLAttributes<HTMLButtonElement> { + disabled?: boolean; +} + +export default function Button({ children, ...attributes }: IButtonProps) { + return <S.Button {...attributes}>{children}</S.Button>; +} + +const S = { + Button: styled.button` + position: fixed; + bottom: 0; + max-width: 429px; + + height: 64px; + font-size: 16px; + font-weight: 700; + text-align: center; + width: 100%; + + background-color: black; + color: white; + border: none; + cursor: pointer; + &:disabled { + background-color: rgba(190, 190, 190, 1); + } + `, +};
Unknown
์ €๋„ ๊ณต์šฉ์ ์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ์ปดํฌ๋„ŒํŠธ๋Š” ๋ณดํ†ต `common` ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค! ๐Ÿ™Œ ๋‹จ์ง€ ์Šคํƒ€์ผ์„ ์œ„ํ•ด์„œ ์‚ฌ์šฉํ•˜๋Š” ์ฝ”๋“œ๋ผ๋ฉด styled๋ผ๊ณ  ๋ถ™์—ฌ๋„ ๊ดœ์ฐฎ์„ ๊ฒƒ ๊ฐ™๋„ค์š”!
@@ -0,0 +1,35 @@ +package christmas.domain.discount; + +import christmas.domain.discount.dto.DiscountResponseDto; +import christmas.domain.order.OrderRequestDto; + +import java.time.LocalDate; + +public class ChristmasDiscounter implements Discounter{ + + private final LocalDate START_DATE = LocalDate.of(2023,12,1); + private final LocalDate END_DATE = LocalDate.of(2023,12,25); + + private final String DISCOUNT_NAME = "ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด ํ• ์ธ"; + + @Override + public DiscountResponseDto discount(OrderRequestDto orderRequest) { + + LocalDate orderDate = orderRequest.getOrderDate(); + int totalDiscount = 0; + + if (isValidDateRange(orderDate)) { + totalDiscount = calculateDiscountPrice(orderDate); + } + + return new DiscountResponseDto(totalDiscount, DISCOUNT_NAME); + } + + private boolean isValidDateRange(LocalDate orderDate) { + return !orderDate.isAfter(END_DATE) && !orderDate.isBefore(START_DATE); + } + + private int calculateDiscountPrice(LocalDate orderDate) { + return (orderDate.getDayOfMonth() -1 ) * 100 + 1000; + } +}
Java
100๊ณผ 1000๋„ ์ƒ์ˆ˜ํ™”ํ•˜๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”??!
@@ -0,0 +1,45 @@ +package christmas.domain.discount; + +import christmas.domain.discount.dto.DiscountResponseDto; +import christmas.domain.discount.dto.FreeBieResponseDto; +import christmas.domain.menu.DrinkMenu; +import christmas.domain.menu.Menu; +import christmas.domain.order.OrderRequestDto; + +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; + +public class FreeBieDiscounter implements Discounter { + + private final String DISCOUNT_NAME = "์ฆ์ • ํ• ์ธ"; + private final Menu FREEBIE_MENU = DrinkMenu.CHAMPAGNE; + private final int FREEBIE_MIN_PRICE = 120_000; + + @Override + public DiscountResponseDto discount(OrderRequestDto orderRequest) { + + List<Menu> menus = orderRequest.getMenus(); + LocalDate orderDate = orderRequest.getOrderDate(); + + if (isFreeBie(menus, orderDate)) { + return new FreeBieResponseDto(Optional.of(FREEBIE_MENU), DISCOUNT_NAME); + } + + return new FreeBieResponseDto(Optional.empty(), DISCOUNT_NAME); + } + + private boolean isFreeBie(List<Menu> menus, LocalDate orderDate) { + int totalPrice = 0; + + if (orderDate.getMonth().getValue() != 12 || orderDate.getYear() != 2023) { + return false; + } + + for (Menu menu : menus) { + totalPrice += menu.getPrice(); + } + + return totalPrice >= FREEBIE_MIN_PRICE; + } +}
Java
2023๋…„ 12์›”์—๋งŒ ์ ์šฉ๋˜๋Š” ์ด๋ฒคํŠธ๋ผ๋Š”๊ฒŒ ๋ˆˆ์— ๋„๋Š” ๊ฒƒ ๊ฐ™์•„์š”! ์ €๋Š” ์ƒ๊ฐ๋ชปํ•œ ๋ถ€๋ถ„์ธ๋ฐ ์„ธ์„ธํ•˜๊ฒŒ ์ž˜ ํ•˜์‹  ๊ฒƒ ๊ฐ™๋„ค์š”!!
@@ -0,0 +1,33 @@ +package christmas.domain.discount.dto; + +import christmas.domain.menu.Menu; + +import java.util.Optional; + +public class FreeBieResponseDto extends DiscountResponseDto{ + + private final Optional<Menu> freeBieMenu; + + public FreeBieResponseDto(Optional<Menu> freeBieMenu, String discountName) { + super(freeBieMenu.orElse(new FreeMenu()).getPrice(), discountName); + this.freeBieMenu = freeBieMenu; + } + + public Optional<Menu> getFreeBieMenu() { + return freeBieMenu; + } + + static private class FreeMenu implements Menu { + + + @Override + public int getPrice() { + return 0; + } + + @Override + public String getName() { + return null; + } + } +}
Java
์˜ค.. ์ด๋Ÿฐ ํ˜•ํƒœ๋Š” ์ฒ˜์Œ๋ณด๋„ค์š”!
@@ -0,0 +1,84 @@ +package christmas.domain.order; + +import christmas.domain.discount.Discounter; +import christmas.domain.discount.dto.DiscountResponseDto; +import christmas.domain.discount.dto.FreeBieResponseDto; +import christmas.domain.menu.DrinkMenu; +import christmas.domain.menu.Menu; + +import java.util.ArrayList; +import java.util.List; + +public class OrderImpl implements Order{ + + private final List<Discounter> discounters; + + public OrderImpl(List<Discounter> discounters) { + this.discounters = discounters; + } + + @Override + public OrderResponseDto order(OrderRequestDto orderRequestDto) { + assertValidOrder(orderRequestDto.getMenus()); + + List<DiscountResponseDto> discountResult = getDiscountResponses(orderRequestDto); + int discountPrice = getDiscountPrice(discountResult); + int priceBeforeDiscount = getPriceBeforeDiscount(orderRequestDto.getMenus()); + int priceAfterDiscount = priceBeforeDiscount - discountPrice; + + OrderResponseDto result = new OrderResponseDto(); + result.setDiscountResults(discountResult); + result.setDiscountPrice(discountPrice); + result.setPriceAfterDiscount(priceAfterDiscount); + result.setPriceBeforeDiscount(priceBeforeDiscount); + + + return result; + } + + private void assertValidOrder(List<Menu> menus) { + boolean validCheck = false; + + for (Menu menu : menus) { + if (!(menu instanceof DrinkMenu)) { + validCheck = true; + break; + } + } + + if (!validCheck) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + } + + + private List<DiscountResponseDto> getDiscountResponses(OrderRequestDto orderRequestDto){ + List<DiscountResponseDto> result = new ArrayList<>(); + + for (Discounter discounter : discounters) { + result.add(discounter.discount(orderRequestDto)); + } + return result; + } + + + //์ฆ์ •์€ ๋”ฐ๋กœ ์ฒ˜๋ฆฌ ํ•„์š”. + private int getDiscountPrice(List<DiscountResponseDto> discounts) { + int discountPrice = 0; + for (DiscountResponseDto discount : discounts) { + discountPrice += discount.getTotalDiscount(); + } + + return discountPrice; + } + + private int getPriceBeforeDiscount(List<Menu> menus) { + int priceBeforeDiscount = 0; + + for (Menu menu : menus) { + priceBeforeDiscount += menu.getPrice(); + } + + return priceBeforeDiscount; + } +}
Java
๋ฉ”์„œ๋“œ๊ฐ€ ์Œ๋ฃŒ๋กœ๋งŒ ์ด๋ฃจ์–ด์กŒ๋Š”์ง€ ํ…Œ์ŠคํŠธํ•˜๋Š” ๊ฒƒ ๊ฐ™์•„์š”! ๋ฉ”์„œ๋“œ๋ช…์„ ๋ชจ๋‘ ์Œ๋ฃŒ์ธ์ง€ ์ฒดํฌํ•˜๋Š” ๋ฉ”์„œ๋“œ๋ผ๋Š” ๊ฑธ ์•Œ ์ˆ˜ ์žˆ๊ฒŒ ํ•˜๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”? ValidOrder๋Š” ์ „์ฒด์ ์ธ ์œ ํšจ์„ฑ์— ๋Œ€ํ•ด์„œ ์ƒ๊ฐํ•˜๊ฒŒ๋  ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,43 @@ +package christmas.domain.user; + +import java.util.Optional; + +public enum Badge { + STAR(5_000, "๋ณ„"), + TREE(10_000, "ํŠธ๋ฆฌ"), + SANTA(20_000, "์‚ฐํƒ€"); + + private final int minPrice; + private final String message; + + Badge(int minPrice, String message) { + this.minPrice = minPrice; + this.message = message; + } + + public int getMinPrice() { + return minPrice; + } + + public String getMessage() { + return message; + } + + public static Optional<Badge> findByPrice(int discountPrice) { + Badge result = null; + + for (Badge badge : Badge.values()) { + if (result == null && badge.getMinPrice() <= discountPrice) { + result = badge; + } + else if (badge.getMinPrice() <= discountPrice && badge.getMinPrice() >= result.getMinPrice() ) { + result = badge; + } + } + + if (result == null) { + return Optional.empty(); + } + return Optional.of(result); + } +}
Java
message ๋ณด๋‹ค๋Š” badgeType ๊ฐ™์€ ํ•„๋“œ๋ช…์ด ๋” ๋‚˜์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,28 @@ +package christmas.domain.user; + +import christmas.domain.order.Order; +import christmas.domain.order.OrderRequestDto; +import christmas.domain.order.OrderResponseDto; + +import java.util.Optional; + +public class User { + + private Optional<Badge> badge; + private final Order order; + + public User(Order order) { + this.order = order; + } + + public OrderResponseDto order(OrderRequestDto request) { + OrderResponseDto response = order.order(request); + this.badge = Badge.findByPrice(response.getDiscountPrice()); + + return response; + } + + public Optional<Badge> getBadge() { + return badge; + } +}
Java
์œ„์—์„œ๋„ ๋‚˜์™”์ง€๋งŒ Optional์€ ์ €๋Š” ์ฒ˜์Œ ๋ณด๋Š” ๊ฒƒ ๊ฐ™์•„์š”! ์ž๋ฐ”๊ฐ€ ์•„์ง ์„œํˆด๋Ÿฌ์„œ..ใ…Ž ๋•๋ถ„์— ์ƒˆ๋กœ์šด ๋ถ€๋ถ„์— ๋Œ€ํ•ด ๊ณต๋ถ€ํ•˜๊ณ  ๊ฐˆ ์ˆ˜ ์žˆ๊ฒ ๋„ค์š”!!
@@ -0,0 +1,81 @@ +package christmas.presentation; + +import camp.nextstep.edu.missionutils.Console; +import christmas.domain.menu.Menu; +import christmas.domain.order.OrderErrorMessage; + +import java.time.LocalDate; +import java.util.*; + +public class InputView { + + public LocalDate inputDate() throws IllegalArgumentException { + + try { + System.out.println("12์›” ์ค‘ ์‹๋‹น ์˜ˆ์ƒ ๋ฐฉ๋ฌธ ๋‚ ์งœ๋Š” ์–ธ์ œ์ธ๊ฐ€์š”? (์ˆซ์ž๋งŒ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”!)"); + int date = Integer.parseInt(Console.readLine()); + + if (date < 1 || date > 31) { + throw new IllegalArgumentException(ViewErrorMessage.INVALID_DATE_FORMAT.getMessage()); + } + + return LocalDate.of(2023,12,date); + } catch (NumberFormatException ex) { + throw new IllegalArgumentException(ViewErrorMessage.INVALID_DATE_FORMAT.getMessage()); + } + } + + public Map<String, Integer> inputMenus() throws IllegalArgumentException { + System.out.println("์ฃผ๋ฌธํ•˜์‹ค ๋ฉ”๋‰ด๋ฅผ ๋ฉ”๋‰ด์™€ ๊ฐœ์ˆ˜๋ฅผ ์•Œ๋ ค ์ฃผ์„ธ์š”. (e.g. ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€-2,๋ ˆ๋“œ์™€์ธ-1,์ดˆ์ฝ”์ผ€์ดํฌ-1)"); + String userInput = Console.readLine(); + try { + Map<String, Integer> result = parsingMenus(userInput); + if (result.keySet().size() == 0) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + + return result; + } catch (IllegalArgumentException ex) { + throw ex; + } + } + + + + private Map<String, Integer> parsingMenus(String userOrder) throws IllegalArgumentException { + Map<String,Integer> menus = new HashMap<>(); + Set<String> orderMenu = new HashSet<>(); + + List<String> splitMenus = List.of(userOrder.split(",")); + for (String splitMenu : splitMenus) { + Map<String, Integer> tmpResult = parsingMenu(splitMenu); + String tmpMenuName = tmpResult.keySet().iterator().next(); + + if (orderMenu.contains(tmpMenuName)) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + orderMenu.add(tmpMenuName); + menus.put(tmpMenuName, tmpResult.get(tmpMenuName)); + } + return menus; + } + + private Map<String, Integer> parsingMenu(String menu) { + Map<String, Integer> parsingResult = new HashMap<>(); + int i = menu.lastIndexOf("-"); + + if (i == -1) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + + try { + parsingResult.put(menu.substring(0,i), Integer.parseInt(menu.substring(i + 1))); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } catch (Exception ex) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + + return parsingResult; + } +}
Java
์ €๋Š” view์—์„œ๋Š” ์ˆซ์ž๊ฐ€ ๋“ค์–ด์™”๋Š”์ง€๋งŒ ์ฒดํฌํ•˜๊ณ  1~31์ผ์— ํ•ด๋‹นํ•˜๋Š”์ง€๋Š” ๋„๋ฉ”์ธ ๊ฐ์ฒด์—์„œ ์ฒดํฌํ–ˆ์–ด์š”! ์ €๋Š” ์ด ๋ถ€๋ถ„์— ๋Œ€ํ•ด์„œ ์–ด๋””์—์„œ ๊ตฌํ˜„ํ• ์ง€ ๊ณ ๋ฏผํ–ˆ๋Š”๋ฐ view์—์„œ ์ฒดํฌํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -0,0 +1,81 @@ +package christmas.presentation; + +import camp.nextstep.edu.missionutils.Console; +import christmas.domain.menu.Menu; +import christmas.domain.order.OrderErrorMessage; + +import java.time.LocalDate; +import java.util.*; + +public class InputView { + + public LocalDate inputDate() throws IllegalArgumentException { + + try { + System.out.println("12์›” ์ค‘ ์‹๋‹น ์˜ˆ์ƒ ๋ฐฉ๋ฌธ ๋‚ ์งœ๋Š” ์–ธ์ œ์ธ๊ฐ€์š”? (์ˆซ์ž๋งŒ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”!)"); + int date = Integer.parseInt(Console.readLine()); + + if (date < 1 || date > 31) { + throw new IllegalArgumentException(ViewErrorMessage.INVALID_DATE_FORMAT.getMessage()); + } + + return LocalDate.of(2023,12,date); + } catch (NumberFormatException ex) { + throw new IllegalArgumentException(ViewErrorMessage.INVALID_DATE_FORMAT.getMessage()); + } + } + + public Map<String, Integer> inputMenus() throws IllegalArgumentException { + System.out.println("์ฃผ๋ฌธํ•˜์‹ค ๋ฉ”๋‰ด๋ฅผ ๋ฉ”๋‰ด์™€ ๊ฐœ์ˆ˜๋ฅผ ์•Œ๋ ค ์ฃผ์„ธ์š”. (e.g. ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€-2,๋ ˆ๋“œ์™€์ธ-1,์ดˆ์ฝ”์ผ€์ดํฌ-1)"); + String userInput = Console.readLine(); + try { + Map<String, Integer> result = parsingMenus(userInput); + if (result.keySet().size() == 0) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + + return result; + } catch (IllegalArgumentException ex) { + throw ex; + } + } + + + + private Map<String, Integer> parsingMenus(String userOrder) throws IllegalArgumentException { + Map<String,Integer> menus = new HashMap<>(); + Set<String> orderMenu = new HashSet<>(); + + List<String> splitMenus = List.of(userOrder.split(",")); + for (String splitMenu : splitMenus) { + Map<String, Integer> tmpResult = parsingMenu(splitMenu); + String tmpMenuName = tmpResult.keySet().iterator().next(); + + if (orderMenu.contains(tmpMenuName)) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + orderMenu.add(tmpMenuName); + menus.put(tmpMenuName, tmpResult.get(tmpMenuName)); + } + return menus; + } + + private Map<String, Integer> parsingMenu(String menu) { + Map<String, Integer> parsingResult = new HashMap<>(); + int i = menu.lastIndexOf("-"); + + if (i == -1) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + + try { + parsingResult.put(menu.substring(0,i), Integer.parseInt(menu.substring(i + 1))); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } catch (Exception ex) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + + return parsingResult; + } +}
Java
์œ„์—์„œ๋ž‘ ๊ฐ™์€ ๋งฅ๋ฝ์ธ๋ฐ View์—์„œ๋Š” ์ž…๋ ฅ์„ ๋ฐ›๊ณ , utils ๊ฐ™์€ ๋ถ€๋ถ„์—์„œ ์ž…๋ ฅ๊ฐ’ ํ˜•ํƒœ๋ฅผ ๋ฐ”๊พธ์–ด์ฃผ๋Š” ์—ญํ• ์„ ํ•ด์•ผํ•œ๋‹ค๊ณ  ์ €๋Š” ์ƒ๊ฐํ–ˆ์–ด์š”! Inputview ๋‚ด์—์„œ ํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ด์š”!
@@ -0,0 +1,116 @@ +package christmas.presentation; + +import christmas.domain.discount.Discounter; +import christmas.domain.discount.dto.DiscountResponseDto; +import christmas.domain.discount.dto.FreeBieResponseDto; +import christmas.domain.menu.Menu; +import christmas.domain.order.OrderResponseDto; +import christmas.domain.user.User; + +import java.sql.SQLOutput; +import java.text.NumberFormat; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class OutputView { + + private final NumberFormat numberFormat = NumberFormat.getInstance(); + + + public void printStart() { + System.out.println("์•ˆ๋…•ํ•˜์„ธ์š”! ์šฐํ…Œ์ฝ” ์‹๋‹น 12์›” ์ด๋ฒคํŠธ ํ”Œ๋ž˜๋„ˆ์ž…๋‹ˆ๋‹ค."); + } + + public void printOrderResult(OrderResponseDto orderResponseDto) { + System.out.println("<ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก>"); + System.out.println(numberToString(orderResponseDto.getPriceBeforeDiscount()) + "์›"); + System.out.println(); + System.out.println("<์ฆ์ • ๋ฉ”๋‰ด>"); + printFreebie(orderResponseDto); + System.out.println("<ํ˜œํƒ ๋‚ด์—ญ>"); + printDiscount(orderResponseDto); + System.out.println("<์ดํ˜œํƒ ๊ธˆ์•ก>"); + System.out.println("-" + numberToString(orderResponseDto.getDiscountPrice()) + "์›"); + System.out.println("<ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก>"); + System.out.println(numberToString(orderResponseDto.getPriceAfterDiscount())+"์›"); + System.out.println(); + } + + public void printBadge(User user) { + System.out.println("<12์›” ์ด๋ฒคํŠธ ๋ฐฐ์ง€>"); + if (user.getBadge().isEmpty()) { + System.out.println("์—†์Œ"); + return; + } + System.out.println(user.getBadge().get().getMessage()); + } + + public void printOrderDate(LocalDate date) { + System.out.println(date.getMonthValue() +"์›” " + date.getDayOfMonth() +"์ผ์— ์šฐํ…Œ์ฝ” ์‹๋‹น์—์„œ ๋ฐ›์„ ์ด๋ฒคํŠธ ํ˜œํƒ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!"); + System.out.println(); + } + + private void printDiscount(OrderResponseDto orderResponseDto) { + boolean noneFlag = true; + for (DiscountResponseDto tmp : orderResponseDto.getDiscountResults()) { + if (tmp.getTotalDiscount() == 0) { + continue; + } + noneFlag = false; + System.out.println(tmp.getDiscountName() + ": -" + numberToString(tmp.getTotalDiscount()) + "์›"); + } + + if (noneFlag) { + System.out.println("์—†์Œ"); + } + + System.out.println(); + } + + private void printFreebie(OrderResponseDto orderResponseDto) { + for (DiscountResponseDto discount : orderResponseDto.getDiscountResults()) { + if (discount instanceof FreeBieResponseDto freeBieResponseDto) { + printFreebie(freeBieResponseDto); + } + } + System.out.println(); + } + + private void printFreebie(FreeBieResponseDto freeBie) { + if (freeBie.getFreeBieMenu().isEmpty()) { + System.out.println("์—†์Œ"); + return; + } + + System.out.println(freeBie.getFreeBieMenu().get().getName()+ " 1๊ฐœ"); + } + + + public void printOrder(List<Menu> menus) { + System.out.println("<์ฃผ๋ฌธ ๋ฉ”๋‰ด>"); + printFoods(menus); + System.out.println(); + } + + private void printFoods(List<Menu> menus) { + Map<String, Integer> foods = new HashMap<>(); + + for (Menu menu : menus) { + if (foods.containsKey(menu.getName())) { + foods.put(menu.getName(), foods.get(menu.getName()) + 1); + continue; + } + foods.put(menu.getName(), 1); + } + + for (String name : foods.keySet()) { + System.out.println(name + ' ' + foods.get(name) + '๊ฐœ'); + } + } + + private String numberToString(int num) { + return numberFormat.format(num); + } +}
Java
์ด ๋ฉ”์„œ๋“œ์—์„œ ์ถœ๋ ฅ์— ๋Œ€ํ•œ ์ „์ฒด์ ์ธ ๋ถ€๋ถ„์˜ ์—ญํ• ์„ ๋งก๊ณ  ์žˆ๋Š” ๊ฒƒ ๊ฐ™์•„์š”! ๊ฐ๊ฐ ํŒŒํŠธ๋ณ„๋กœ ๋‚˜๋ˆ„๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”? ํ• ์ธ ์ „ ์ด ์ฃผ๋ฌธ ๊ธˆ์•ก, ์ฆ์ • ๋ฉ”๋‰ด, ํ˜œํƒ ๋‚ด์—ญ, ์ดํ˜œํƒ ๊ธˆ์•ก, ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก ์œผ๋กœ์š”!
@@ -0,0 +1,35 @@ +package christmas.domain.discount; + +import christmas.domain.discount.dto.DiscountResponseDto; +import christmas.domain.order.OrderRequestDto; + +import java.time.LocalDate; + +public class ChristmasDiscounter implements Discounter{ + + private final LocalDate START_DATE = LocalDate.of(2023,12,1); + private final LocalDate END_DATE = LocalDate.of(2023,12,25); + + private final String DISCOUNT_NAME = "ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด ํ• ์ธ"; + + @Override + public DiscountResponseDto discount(OrderRequestDto orderRequest) { + + LocalDate orderDate = orderRequest.getOrderDate(); + int totalDiscount = 0; + + if (isValidDateRange(orderDate)) { + totalDiscount = calculateDiscountPrice(orderDate); + } + + return new DiscountResponseDto(totalDiscount, DISCOUNT_NAME); + } + + private boolean isValidDateRange(LocalDate orderDate) { + return !orderDate.isAfter(END_DATE) && !orderDate.isBefore(START_DATE); + } + + private int calculateDiscountPrice(LocalDate orderDate) { + return (orderDate.getDayOfMonth() -1 ) * 100 + 1000; + } +}
Java
์ƒ์ˆ˜ํ™”์— ๊ด€ํ•ด์„œ ํฌ๊ฒŒ ์ƒ๊ฐํ•˜์ง€ ์•Š์•˜์—ˆ๋„ค์š”. ์ƒ์ˆ˜ํ™”ํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,45 @@ +package christmas.domain.discount; + +import christmas.domain.discount.dto.DiscountResponseDto; +import christmas.domain.discount.dto.FreeBieResponseDto; +import christmas.domain.menu.DrinkMenu; +import christmas.domain.menu.Menu; +import christmas.domain.order.OrderRequestDto; + +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; + +public class FreeBieDiscounter implements Discounter { + + private final String DISCOUNT_NAME = "์ฆ์ • ํ• ์ธ"; + private final Menu FREEBIE_MENU = DrinkMenu.CHAMPAGNE; + private final int FREEBIE_MIN_PRICE = 120_000; + + @Override + public DiscountResponseDto discount(OrderRequestDto orderRequest) { + + List<Menu> menus = orderRequest.getMenus(); + LocalDate orderDate = orderRequest.getOrderDate(); + + if (isFreeBie(menus, orderDate)) { + return new FreeBieResponseDto(Optional.of(FREEBIE_MENU), DISCOUNT_NAME); + } + + return new FreeBieResponseDto(Optional.empty(), DISCOUNT_NAME); + } + + private boolean isFreeBie(List<Menu> menus, LocalDate orderDate) { + int totalPrice = 0; + + if (orderDate.getMonth().getValue() != 12 || orderDate.getYear() != 2023) { + return false; + } + + for (Menu menu : menus) { + totalPrice += menu.getPrice(); + } + + return totalPrice >= FREEBIE_MIN_PRICE; + } +}
Java
๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,33 @@ +package christmas.domain.discount.dto; + +import christmas.domain.menu.Menu; + +import java.util.Optional; + +public class FreeBieResponseDto extends DiscountResponseDto{ + + private final Optional<Menu> freeBieMenu; + + public FreeBieResponseDto(Optional<Menu> freeBieMenu, String discountName) { + super(freeBieMenu.orElse(new FreeMenu()).getPrice(), discountName); + this.freeBieMenu = freeBieMenu; + } + + public Optional<Menu> getFreeBieMenu() { + return freeBieMenu; + } + + static private class FreeMenu implements Menu { + + + @Override + public int getPrice() { + return 0; + } + + @Override + public String getName() { + return null; + } + } +}
Java
์ฆ์ •ํ’ˆ์„ ์–ด๋–ป๊ฒŒ ์ฒ˜๋ฆฌํ•  ์ง€์— ๋Œ€ํ•ด ๋งŽ์ด ๊ณ ๋ฏผํ–ˆ์Šต๋‹ˆ๋‹ค ใ…Žใ…Ž.. ์ข€ ๋” ์ข‹์€ ๋ฐฉ๋ฒ•์ด ์žˆ์„ ๊ฒƒ ๊ฐ™์€๋ฐ, ์ €๋Š” ์•ˆ ๋– ์˜ค๋ฅด๋„ค์š” ใ… ใ… 
@@ -0,0 +1,84 @@ +package christmas.domain.order; + +import christmas.domain.discount.Discounter; +import christmas.domain.discount.dto.DiscountResponseDto; +import christmas.domain.discount.dto.FreeBieResponseDto; +import christmas.domain.menu.DrinkMenu; +import christmas.domain.menu.Menu; + +import java.util.ArrayList; +import java.util.List; + +public class OrderImpl implements Order{ + + private final List<Discounter> discounters; + + public OrderImpl(List<Discounter> discounters) { + this.discounters = discounters; + } + + @Override + public OrderResponseDto order(OrderRequestDto orderRequestDto) { + assertValidOrder(orderRequestDto.getMenus()); + + List<DiscountResponseDto> discountResult = getDiscountResponses(orderRequestDto); + int discountPrice = getDiscountPrice(discountResult); + int priceBeforeDiscount = getPriceBeforeDiscount(orderRequestDto.getMenus()); + int priceAfterDiscount = priceBeforeDiscount - discountPrice; + + OrderResponseDto result = new OrderResponseDto(); + result.setDiscountResults(discountResult); + result.setDiscountPrice(discountPrice); + result.setPriceAfterDiscount(priceAfterDiscount); + result.setPriceBeforeDiscount(priceBeforeDiscount); + + + return result; + } + + private void assertValidOrder(List<Menu> menus) { + boolean validCheck = false; + + for (Menu menu : menus) { + if (!(menu instanceof DrinkMenu)) { + validCheck = true; + break; + } + } + + if (!validCheck) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + } + + + private List<DiscountResponseDto> getDiscountResponses(OrderRequestDto orderRequestDto){ + List<DiscountResponseDto> result = new ArrayList<>(); + + for (Discounter discounter : discounters) { + result.add(discounter.discount(orderRequestDto)); + } + return result; + } + + + //์ฆ์ •์€ ๋”ฐ๋กœ ์ฒ˜๋ฆฌ ํ•„์š”. + private int getDiscountPrice(List<DiscountResponseDto> discounts) { + int discountPrice = 0; + for (DiscountResponseDto discount : discounts) { + discountPrice += discount.getTotalDiscount(); + } + + return discountPrice; + } + + private int getPriceBeforeDiscount(List<Menu> menus) { + int priceBeforeDiscount = 0; + + for (Menu menu : menus) { + priceBeforeDiscount += menu.getPrice(); + } + + return priceBeforeDiscount; + } +}
Java
์˜ค! ๊ทธ๋ ‡๋„ค์š”. ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,43 @@ +package christmas.domain.user; + +import java.util.Optional; + +public enum Badge { + STAR(5_000, "๋ณ„"), + TREE(10_000, "ํŠธ๋ฆฌ"), + SANTA(20_000, "์‚ฐํƒ€"); + + private final int minPrice; + private final String message; + + Badge(int minPrice, String message) { + this.minPrice = minPrice; + this.message = message; + } + + public int getMinPrice() { + return minPrice; + } + + public String getMessage() { + return message; + } + + public static Optional<Badge> findByPrice(int discountPrice) { + Badge result = null; + + for (Badge badge : Badge.values()) { + if (result == null && badge.getMinPrice() <= discountPrice) { + result = badge; + } + else if (badge.getMinPrice() <= discountPrice && badge.getMinPrice() >= result.getMinPrice() ) { + result = badge; + } + } + + if (result == null) { + return Optional.empty(); + } + return Optional.of(result); + } +}
Java
์•— ๊ทธ๋ ‡๊ตฐ์š”. ๊ทธ๋ƒฅ message๋กœ๋งŒ ์žˆ์œผ๋ฉด ํ—ท๊ฐˆ๋ฆฌ๊ฒ ๋„ค์š”.
@@ -0,0 +1,28 @@ +package christmas.domain.user; + +import christmas.domain.order.Order; +import christmas.domain.order.OrderRequestDto; +import christmas.domain.order.OrderResponseDto; + +import java.util.Optional; + +public class User { + + private Optional<Badge> badge; + private final Order order; + + public User(Order order) { + this.order = order; + } + + public OrderResponseDto order(OrderRequestDto request) { + OrderResponseDto response = order.order(request); + this.badge = Badge.findByPrice(response.getDiscountPrice()); + + return response; + } + + public Optional<Badge> getBadge() { + return badge; + } +}
Java
Optional์„ ์ƒ๊ฐ๋ณด๋‹ค ๋งŽ์ด ์“ฐ๊ณ , ์ถ”์ฒœํ•ด์ฃผ๋”๋ผ๊ณ ์š”. ์ดํŽ™ํ‹ฐ๋ธŒ ์ž๋ฐ”๋‚˜ ์ข‹์€ ์ฝ”๋“œ, ๋‚˜์œ ์ฝ”๋“œ ๋“ฑ ๋‹ค์–‘ํ•œ ๊ณณ์—์„œ ๋‚˜์˜ต๋‹ˆ๋‹ค!
@@ -0,0 +1,81 @@ +package christmas.presentation; + +import camp.nextstep.edu.missionutils.Console; +import christmas.domain.menu.Menu; +import christmas.domain.order.OrderErrorMessage; + +import java.time.LocalDate; +import java.util.*; + +public class InputView { + + public LocalDate inputDate() throws IllegalArgumentException { + + try { + System.out.println("12์›” ์ค‘ ์‹๋‹น ์˜ˆ์ƒ ๋ฐฉ๋ฌธ ๋‚ ์งœ๋Š” ์–ธ์ œ์ธ๊ฐ€์š”? (์ˆซ์ž๋งŒ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”!)"); + int date = Integer.parseInt(Console.readLine()); + + if (date < 1 || date > 31) { + throw new IllegalArgumentException(ViewErrorMessage.INVALID_DATE_FORMAT.getMessage()); + } + + return LocalDate.of(2023,12,date); + } catch (NumberFormatException ex) { + throw new IllegalArgumentException(ViewErrorMessage.INVALID_DATE_FORMAT.getMessage()); + } + } + + public Map<String, Integer> inputMenus() throws IllegalArgumentException { + System.out.println("์ฃผ๋ฌธํ•˜์‹ค ๋ฉ”๋‰ด๋ฅผ ๋ฉ”๋‰ด์™€ ๊ฐœ์ˆ˜๋ฅผ ์•Œ๋ ค ์ฃผ์„ธ์š”. (e.g. ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€-2,๋ ˆ๋“œ์™€์ธ-1,์ดˆ์ฝ”์ผ€์ดํฌ-1)"); + String userInput = Console.readLine(); + try { + Map<String, Integer> result = parsingMenus(userInput); + if (result.keySet().size() == 0) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + + return result; + } catch (IllegalArgumentException ex) { + throw ex; + } + } + + + + private Map<String, Integer> parsingMenus(String userOrder) throws IllegalArgumentException { + Map<String,Integer> menus = new HashMap<>(); + Set<String> orderMenu = new HashSet<>(); + + List<String> splitMenus = List.of(userOrder.split(",")); + for (String splitMenu : splitMenus) { + Map<String, Integer> tmpResult = parsingMenu(splitMenu); + String tmpMenuName = tmpResult.keySet().iterator().next(); + + if (orderMenu.contains(tmpMenuName)) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + orderMenu.add(tmpMenuName); + menus.put(tmpMenuName, tmpResult.get(tmpMenuName)); + } + return menus; + } + + private Map<String, Integer> parsingMenu(String menu) { + Map<String, Integer> parsingResult = new HashMap<>(); + int i = menu.lastIndexOf("-"); + + if (i == -1) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + + try { + parsingResult.put(menu.substring(0,i), Integer.parseInt(menu.substring(i + 1))); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } catch (Exception ex) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + + return parsingResult; + } +}
Java
์Œ... ์ €๋„ ์ด์ œ ๋ณด๋‹ˆ ๋„๋ฉ”์ธ ๊ฐ์ฒด์—์„œ ์ฒดํฌํ•˜๋Š” ๊ฒƒ์ด ๋งž๋Š” ๊ฒƒ ๊ฐ™๋„ค์š”. ๋งŒ์•ฝ ์š”๊ตฌ์‚ฌํ•ญ์ด ๋ณ€๊ฒฝ๋˜์–ด์„œ 11์›”๋งŒ ์ฃผ๋ฌธ์ด ๊ฐ€๋Šฅํ•˜๋‹ค๋ฉด, ์ด ๋ถ€๋ถ„์€ ๋„๋ฉ”์ธ์— ํ•ด๋‹นํ•˜๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,81 @@ +package christmas.presentation; + +import camp.nextstep.edu.missionutils.Console; +import christmas.domain.menu.Menu; +import christmas.domain.order.OrderErrorMessage; + +import java.time.LocalDate; +import java.util.*; + +public class InputView { + + public LocalDate inputDate() throws IllegalArgumentException { + + try { + System.out.println("12์›” ์ค‘ ์‹๋‹น ์˜ˆ์ƒ ๋ฐฉ๋ฌธ ๋‚ ์งœ๋Š” ์–ธ์ œ์ธ๊ฐ€์š”? (์ˆซ์ž๋งŒ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”!)"); + int date = Integer.parseInt(Console.readLine()); + + if (date < 1 || date > 31) { + throw new IllegalArgumentException(ViewErrorMessage.INVALID_DATE_FORMAT.getMessage()); + } + + return LocalDate.of(2023,12,date); + } catch (NumberFormatException ex) { + throw new IllegalArgumentException(ViewErrorMessage.INVALID_DATE_FORMAT.getMessage()); + } + } + + public Map<String, Integer> inputMenus() throws IllegalArgumentException { + System.out.println("์ฃผ๋ฌธํ•˜์‹ค ๋ฉ”๋‰ด๋ฅผ ๋ฉ”๋‰ด์™€ ๊ฐœ์ˆ˜๋ฅผ ์•Œ๋ ค ์ฃผ์„ธ์š”. (e.g. ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€-2,๋ ˆ๋“œ์™€์ธ-1,์ดˆ์ฝ”์ผ€์ดํฌ-1)"); + String userInput = Console.readLine(); + try { + Map<String, Integer> result = parsingMenus(userInput); + if (result.keySet().size() == 0) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + + return result; + } catch (IllegalArgumentException ex) { + throw ex; + } + } + + + + private Map<String, Integer> parsingMenus(String userOrder) throws IllegalArgumentException { + Map<String,Integer> menus = new HashMap<>(); + Set<String> orderMenu = new HashSet<>(); + + List<String> splitMenus = List.of(userOrder.split(",")); + for (String splitMenu : splitMenus) { + Map<String, Integer> tmpResult = parsingMenu(splitMenu); + String tmpMenuName = tmpResult.keySet().iterator().next(); + + if (orderMenu.contains(tmpMenuName)) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + orderMenu.add(tmpMenuName); + menus.put(tmpMenuName, tmpResult.get(tmpMenuName)); + } + return menus; + } + + private Map<String, Integer> parsingMenu(String menu) { + Map<String, Integer> parsingResult = new HashMap<>(); + int i = menu.lastIndexOf("-"); + + if (i == -1) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + + try { + parsingResult.put(menu.substring(0,i), Integer.parseInt(menu.substring(i + 1))); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } catch (Exception ex) { + throw new IllegalArgumentException(OrderErrorMessage.INVALID_ORDER.getMessage()); + } + + return parsingResult; + } +}
Java
์ฝค๋งˆ๋กœ ๋ฉ”๋‰ด๋ฅผ ๊ตฌ๋ถ„ํ•˜๊ฑฐ๋‚˜ <๋ฉ”๋‰ด ์ด๋ฆ„>-1 ์ด๋Ÿฐ ์‹์œผ๋กœ ์ž…๋ ฅ์ด ๋œ๋‹ค๋Š” ๊ฒƒ์€ InputView๋งŒ ์•Œ๊ณ  ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ์ด ๋ถ€๋ถ„์„ ๋‹ค๋ฅธ ๊ฐ์ฒด์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ฒŒ๋” ๊ฐ€๊ณตํ•˜๋Š” ๊ฒƒ๋„ InputView์˜ ์—ญํ• ์ด๋ผ๊ณ  ์ƒ๊ฐํ•ด์„œ ์ด๋ ‡๊ฒŒ ์ฒ˜๋ฆฌ ํ–ˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,116 @@ +package christmas.presentation; + +import christmas.domain.discount.Discounter; +import christmas.domain.discount.dto.DiscountResponseDto; +import christmas.domain.discount.dto.FreeBieResponseDto; +import christmas.domain.menu.Menu; +import christmas.domain.order.OrderResponseDto; +import christmas.domain.user.User; + +import java.sql.SQLOutput; +import java.text.NumberFormat; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class OutputView { + + private final NumberFormat numberFormat = NumberFormat.getInstance(); + + + public void printStart() { + System.out.println("์•ˆ๋…•ํ•˜์„ธ์š”! ์šฐํ…Œ์ฝ” ์‹๋‹น 12์›” ์ด๋ฒคํŠธ ํ”Œ๋ž˜๋„ˆ์ž…๋‹ˆ๋‹ค."); + } + + public void printOrderResult(OrderResponseDto orderResponseDto) { + System.out.println("<ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก>"); + System.out.println(numberToString(orderResponseDto.getPriceBeforeDiscount()) + "์›"); + System.out.println(); + System.out.println("<์ฆ์ • ๋ฉ”๋‰ด>"); + printFreebie(orderResponseDto); + System.out.println("<ํ˜œํƒ ๋‚ด์—ญ>"); + printDiscount(orderResponseDto); + System.out.println("<์ดํ˜œํƒ ๊ธˆ์•ก>"); + System.out.println("-" + numberToString(orderResponseDto.getDiscountPrice()) + "์›"); + System.out.println("<ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก>"); + System.out.println(numberToString(orderResponseDto.getPriceAfterDiscount())+"์›"); + System.out.println(); + } + + public void printBadge(User user) { + System.out.println("<12์›” ์ด๋ฒคํŠธ ๋ฐฐ์ง€>"); + if (user.getBadge().isEmpty()) { + System.out.println("์—†์Œ"); + return; + } + System.out.println(user.getBadge().get().getMessage()); + } + + public void printOrderDate(LocalDate date) { + System.out.println(date.getMonthValue() +"์›” " + date.getDayOfMonth() +"์ผ์— ์šฐํ…Œ์ฝ” ์‹๋‹น์—์„œ ๋ฐ›์„ ์ด๋ฒคํŠธ ํ˜œํƒ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!"); + System.out.println(); + } + + private void printDiscount(OrderResponseDto orderResponseDto) { + boolean noneFlag = true; + for (DiscountResponseDto tmp : orderResponseDto.getDiscountResults()) { + if (tmp.getTotalDiscount() == 0) { + continue; + } + noneFlag = false; + System.out.println(tmp.getDiscountName() + ": -" + numberToString(tmp.getTotalDiscount()) + "์›"); + } + + if (noneFlag) { + System.out.println("์—†์Œ"); + } + + System.out.println(); + } + + private void printFreebie(OrderResponseDto orderResponseDto) { + for (DiscountResponseDto discount : orderResponseDto.getDiscountResults()) { + if (discount instanceof FreeBieResponseDto freeBieResponseDto) { + printFreebie(freeBieResponseDto); + } + } + System.out.println(); + } + + private void printFreebie(FreeBieResponseDto freeBie) { + if (freeBie.getFreeBieMenu().isEmpty()) { + System.out.println("์—†์Œ"); + return; + } + + System.out.println(freeBie.getFreeBieMenu().get().getName()+ " 1๊ฐœ"); + } + + + public void printOrder(List<Menu> menus) { + System.out.println("<์ฃผ๋ฌธ ๋ฉ”๋‰ด>"); + printFoods(menus); + System.out.println(); + } + + private void printFoods(List<Menu> menus) { + Map<String, Integer> foods = new HashMap<>(); + + for (Menu menu : menus) { + if (foods.containsKey(menu.getName())) { + foods.put(menu.getName(), foods.get(menu.getName()) + 1); + continue; + } + foods.put(menu.getName(), 1); + } + + for (String name : foods.keySet()) { + System.out.println(name + ' ' + foods.get(name) + '๊ฐœ'); + } + } + + private String numberToString(int num) { + return numberFormat.format(num); + } +}
Java
์ €๋Š” OrderResponseDto์— ๋ชจ๋“  ์ •๋ณด๊ฐ€ ๋“ค์–ด์žˆ์–ด์„œ ์ด๋ ‡๊ฒŒ ํ–ˆ์—ˆ์Šต๋‹ˆ๋‹ค. ๋Œ€์‹  private method๋ฅผ ์ด์šฉํ•˜์—ฌ ์„ธ๋ถ€์ ์œผ๋กœ ๋‚˜๋ˆด์Šต๋‹ˆ๋‹ค! ํ…Œ์ŠคํŠธ๋‚˜ ๊ธฐ๋Šฅ ๋ณ€๊ฒฝ ๋“ฑ ๊ณ ๋ คํ•˜๋ฉด private์ด ์•„๋‹Œ public์œผ๋กœ ํ•ด์„œ ์™ธ๋ถ€์—์„œ ํ˜ธ์ถœํ•˜๋„๋ก ํ•˜๋Š” ๊ฒƒ๋„ ์ข‹์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ํ”ผ๋“œ๋ฐฑ ์ •๋ง ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,162 @@ +package store.controller; + +import static store.controller.PromotionController.getValidInput; + +import java.text.NumberFormat; +import java.util.List; +import store.model.Receipt; +import store.view.InputView; +import store.view.OutputView; +import store.view.error.ErrorException; +import store.view.error.InputErrorType; + +public class FrontController { + + private static final String newline = System.getProperty("line.separator"); + + private final InputView inputView; + private final OutputView outputView; + private final ProductController productController; + private final PromotionController promotionController; + + public FrontController(InputView inputView, OutputView outputView, + ProductController productController, PromotionController promotionController) { + this.inputView = inputView; + this.outputView = outputView; + this.productController = productController; + this.promotionController = promotionController; + + } + + public void runFrontController() { + run(); + retry(); + } + + private void display() { + promotionController.displayAllTheProducts(); + } + + private void retry() { + while (true) { + try { + boolean continuePurchase = getValidInput(inputView::readContinuePurchase, this::isValidPositive); + if (!continuePurchase) { + throw new IllegalArgumentException(); + } + run(); + } catch (IllegalArgumentException e) { + return; + } + } + } + + private void run() { + MembershipController membershipController = new MembershipController(inputView); + boolean skipStartMessage = false; + + while (true) { + try { + if (!skipStartMessage) { + outputView.startMessage(); + display(); + } + + Receipt receipt = promotionController.process(); + membershipController.execute(receipt); + printTotalReceipt(receipt); + return; + } catch (ErrorException e) { + System.out.println(e.getMessage()); + /* + if (e.getMessage().contains(InputErrorType.NEED_PRODUCT_COUNT_WITHIN_STOCK.getMessage()) || + e.getMessage().contains(InputErrorType.NEED_EXISTING_PRODUCT.getMessage())) { + skipStartMessage = true; + }*/ + if(!e.getMessage().isEmpty()){ + skipStartMessage = true; + } + new FrontController(inputView, outputView, productController, promotionController); + } + } + } + + private boolean isValidPositive(String input) { + if (input.equals("Y")) { + return true; + } + if (input.equals("N")) { + return false; + } + throw new ErrorException(InputErrorType.NEED_AVAILABLE_INPUT); + } + + private void printTotalReceipt(Receipt receipt) { + outputView.printReceiptStart(); + printProductDetails(receipt); + printBonusProductDetails(receipt); + outputView.printDividingLine(); + receipt.printFinalReceipt(); + } + + + private void printProductDetails(Receipt receipt) { + List<String> productDetails = receipt.getProductDetails(); + int groupSize = 3; + StringBuilder output = new StringBuilder(); + + NumberFormat numberFormat = NumberFormat.getInstance(); + + for (int i = 0; i < productDetails.size(); i++) { + String detail = productDetails.get(i); + + if ((i + 1) % groupSize == 0) { + try { + int number = Integer.parseInt(detail); + output.append(numberFormat.format(number)); + } catch (NumberFormatException e) { + output.append(detail); + } + output.append(newline); + } + + if ((i + 1) % groupSize != 0 && i != productDetails.size() - 1) { + output.append(detail).append(" "); + } + } + + System.out.print(output); + } + + + private void printBonusProductDetails(Receipt receipt) { + List<String> bonusProductDetails = receipt.getBonusProductDetails(); + int groupSize = 2; + StringBuilder output = new StringBuilder(); + + NumberFormat numberFormat = NumberFormat.getInstance(); + + for (int i = 0; i < bonusProductDetails.size(); i++) { + String detail = bonusProductDetails.get(i); + + if ((i + 1) % groupSize == 0) { + try { + int number = Integer.parseInt(detail); + output.append(numberFormat.format(number)); + } catch (NumberFormatException e) { + output.append(detail); + } + output.append(newline); + } + + if ((i + 1) % groupSize != 0 && i != bonusProductDetails.size() - 1) { + output.append(detail).append(" "); + } + } + if(!output.isEmpty()){ + outputView.startPrintBonusProduct(); + } + + System.out.print(output); + } +}
Java
์ œ๊ฐ€ ์ €๋ฒˆ์—๋Š” ์žฌ๊ท€ ํ•จ์ˆ˜๊ฐ€ ์•ˆ์ข‹์ง€ ์•Š์„๊นŒ๋ผ๋Š” ์‹์œผ๋กœ ์–˜๊ธฐ๋ฅผ ํ•˜์˜€์ง€๋งŒ ์ž‘๋…„ 3์ฃผ์ฐจ ํ”ผ๋“œ๋ฐฑ์„ ๋ณด๋‹ˆ ์žฌ๊ท€ํ•จ์ˆ˜๋กœ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๋‚ด์šฉ์ด ์žˆ๋”๊ตฐ์š”... ์ฝ”๋“œ๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค๋ฉด ์žฌ๊ท€๋„ ์ข‹์€ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,162 @@ +package store.controller; + +import static store.controller.PromotionController.getValidInput; + +import java.text.NumberFormat; +import java.util.List; +import store.model.Receipt; +import store.view.InputView; +import store.view.OutputView; +import store.view.error.ErrorException; +import store.view.error.InputErrorType; + +public class FrontController { + + private static final String newline = System.getProperty("line.separator"); + + private final InputView inputView; + private final OutputView outputView; + private final ProductController productController; + private final PromotionController promotionController; + + public FrontController(InputView inputView, OutputView outputView, + ProductController productController, PromotionController promotionController) { + this.inputView = inputView; + this.outputView = outputView; + this.productController = productController; + this.promotionController = promotionController; + + } + + public void runFrontController() { + run(); + retry(); + } + + private void display() { + promotionController.displayAllTheProducts(); + } + + private void retry() { + while (true) { + try { + boolean continuePurchase = getValidInput(inputView::readContinuePurchase, this::isValidPositive); + if (!continuePurchase) { + throw new IllegalArgumentException(); + } + run(); + } catch (IllegalArgumentException e) { + return; + } + } + } + + private void run() { + MembershipController membershipController = new MembershipController(inputView); + boolean skipStartMessage = false; + + while (true) { + try { + if (!skipStartMessage) { + outputView.startMessage(); + display(); + } + + Receipt receipt = promotionController.process(); + membershipController.execute(receipt); + printTotalReceipt(receipt); + return; + } catch (ErrorException e) { + System.out.println(e.getMessage()); + /* + if (e.getMessage().contains(InputErrorType.NEED_PRODUCT_COUNT_WITHIN_STOCK.getMessage()) || + e.getMessage().contains(InputErrorType.NEED_EXISTING_PRODUCT.getMessage())) { + skipStartMessage = true; + }*/ + if(!e.getMessage().isEmpty()){ + skipStartMessage = true; + } + new FrontController(inputView, outputView, productController, promotionController); + } + } + } + + private boolean isValidPositive(String input) { + if (input.equals("Y")) { + return true; + } + if (input.equals("N")) { + return false; + } + throw new ErrorException(InputErrorType.NEED_AVAILABLE_INPUT); + } + + private void printTotalReceipt(Receipt receipt) { + outputView.printReceiptStart(); + printProductDetails(receipt); + printBonusProductDetails(receipt); + outputView.printDividingLine(); + receipt.printFinalReceipt(); + } + + + private void printProductDetails(Receipt receipt) { + List<String> productDetails = receipt.getProductDetails(); + int groupSize = 3; + StringBuilder output = new StringBuilder(); + + NumberFormat numberFormat = NumberFormat.getInstance(); + + for (int i = 0; i < productDetails.size(); i++) { + String detail = productDetails.get(i); + + if ((i + 1) % groupSize == 0) { + try { + int number = Integer.parseInt(detail); + output.append(numberFormat.format(number)); + } catch (NumberFormatException e) { + output.append(detail); + } + output.append(newline); + } + + if ((i + 1) % groupSize != 0 && i != productDetails.size() - 1) { + output.append(detail).append(" "); + } + } + + System.out.print(output); + } + + + private void printBonusProductDetails(Receipt receipt) { + List<String> bonusProductDetails = receipt.getBonusProductDetails(); + int groupSize = 2; + StringBuilder output = new StringBuilder(); + + NumberFormat numberFormat = NumberFormat.getInstance(); + + for (int i = 0; i < bonusProductDetails.size(); i++) { + String detail = bonusProductDetails.get(i); + + if ((i + 1) % groupSize == 0) { + try { + int number = Integer.parseInt(detail); + output.append(numberFormat.format(number)); + } catch (NumberFormatException e) { + output.append(detail); + } + output.append(newline); + } + + if ((i + 1) % groupSize != 0 && i != bonusProductDetails.size() - 1) { + output.append(detail).append(" "); + } + } + if(!output.isEmpty()){ + outputView.startPrintBonusProduct(); + } + + System.out.print(output); + } +}
Java
์ €๋„ ๋ชฐ๋ž๋˜ ๋‚ด์šฉ์ด์ง€๋งŒ String format๊ณผ %-8s(8์นธ๋งŒํผ ์™ผ์ชฝ์ •๋ ฌ ์ด๋Ÿฐ์‹์œผ๋กœ ์‚ฌ์šฉํ•ด์„œ ์ •๋ ฌ์„ ์‹œ๋„ํ•˜๋”๊ตฐ์š”
@@ -0,0 +1,306 @@ +package store.controller; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.time.LocalDateTime; +import java.util.List; +import java.util.function.Function; +import java.util.function.Supplier; +import store.model.Product; +import store.model.ProductStock; +import store.model.Promotion; +import store.model.Promotions; +import store.model.PurchaseDetail; +import store.model.PurchasedProducts; +import store.model.Receipt; +import store.view.InputView; +import store.view.error.ErrorException; +import store.view.error.InputErrorType; + +public class PromotionController { + + private final InputView inputView; + private final ProductStock productStock; + private final Promotions promotions; + private final ProductController productController; + + + public void displayAllTheProducts() { + productStock.display(); + } + + public PromotionController(InputView inputView, ProductController productController) { + this.inputView = inputView; + this.productStock = new ProductStock(); + this.promotions = new Promotions(); + this.productController = productController; + } + + public Receipt process() throws ErrorException { + List<String> items = getValidInput(inputView::readItem, productController::extractValidProducts); + LocalDateTime localDateTime = DateTimes.now(); + + PurchasedProducts purchasedProducts = new PurchasedProducts(items); + productController.checkProductInConvenience(purchasedProducts, productStock); + productController.checkProductQuantityAvailable(purchasedProducts, productStock); + + + Receipt receipt = new Receipt(purchasedProducts, productStock, new PurchaseDetail()); + + + for (Product purchasedProduct : purchasedProducts.getProducts()) { + String productName = purchasedProduct.getValueOfTheField("name"); + Product promotable = productStock.getSameFieldProductWithPromotion(productName, "name", true); + Product nonPromotable = productStock.getSameFieldProductWithPromotion(productName, "name", false); + + + int purchaseQuantity = purchasedProduct.parseQuantity(); + + //ํ”„๋กœ๋ชจ์…˜์ด ์—†๋Š” ๊ฒฝ์šฐ + if (promotable == null) { + nonPromotable.decreaseQuantity(purchaseQuantity); + receipt.updateReceipt(purchasedProduct, 0, 0); + continue; + } + + //์•„๋ž˜๋กœ ๋‹ค ํ”„๋กœ๋ชจ์…˜์ด ์žˆ๋Š” ๊ฒฝ์šฐ + + int promotionalProductQuantity = promotable.parseQuantity(); + + // ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๊ฐ€ 0์ธ ๊ฒฝ์šฐ + if (promotionalProductQuantity == 0) { + nonPromotable.decreaseQuantity(purchaseQuantity); + receipt.updateReceipt(purchasedProduct, 0, 0); + continue; + } + + // ์•„๋ž˜ ๋‹ค ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ ๊ฐ€ 0์ด ์•„๋‹Œ ๊ฒฝ์šฐ + + String promotion = promotable.getValueOfTheField("promotion"); + Promotion matchedPromotion = promotions.getMatchedPromotion(promotion, "name"); + + //ํ–‰์‚ฌ ๊ธฐ๊ฐ„์ด ์•„๋‹Œ ๊ฒฝ์šฐ + if (!matchedPromotion.isInPromotionPeriod(localDateTime)) { + nonPromotable.decreaseQuantity(purchaseQuantity); + receipt.updateReceipt(purchasedProduct, 0, 0); + continue; + } + + //์•„๋ž˜ ๋‹ค ํ–‰์‚ฌ ๊ธฐ๊ฐ„์ธ ๊ฒฝ์šฐ + + int promotionBonusQuantity = Integer.parseInt(matchedPromotion.getValueOfTheField("get")); + int promotionMinQuantity = Integer.parseInt(matchedPromotion.getValueOfTheField("buy")); + int promotionAcquiredQuantity = promotionMinQuantity + promotionBonusQuantity; + + //ํ”„๋กœ๋ชจ์…˜ ์ตœ์†Œ ๊ฐœ์ˆ˜ > ๊ตฌ๋งค ๊ฐœ์ˆ˜ + if (promotionMinQuantity > purchaseQuantity) { + nonPromotable.decreaseQuantity(purchaseQuantity); + receipt.updateReceipt(purchasedProduct, 0, 0); + continue; + } + + // ํ”„๋กœ๋ชจ์…˜ ์ตœ์†Œ ๊ตฌ๋งค ๊ฐœ์ˆ˜<= ๊ตฌ๋งค ๊ฐœ์ˆ˜< ํ”„๋กœ๋ชจ์…˜ ํ•ด๋‹น ๊ฐœ์ˆ˜ + if (promotionAcquiredQuantity > purchaseQuantity) { + + if(promotionalProductQuantity<promotionMinQuantity){ + nonPromotable.decreaseQuantity(purchaseQuantity); + receipt.updateReceipt(purchasedProduct, 0,0); + continue; + } + if(promotionalProductQuantity==promotionMinQuantity){ + boolean purchaseFullPrice = getValidInput( + () -> inputView.readPurchaseFullPrice(productName, promotionalProductQuantity), + this::isValidPositive + ); + + if(!purchaseFullPrice){ + purchasedProduct.decreaseQuantity(promotionalProductQuantity); + receipt.updateReceipt(purchasedProduct,0,0); + continue; + } + promotable.decreaseQuantity(promotionalProductQuantity); + int currentQuantity = purchaseQuantity-promotionalProductQuantity; + nonPromotable.decreaseQuantity(currentQuantity); + receipt.updateReceipt(purchasedProduct, 0,0); + continue; + } + boolean addItem = getValidInput( + () -> inputView.readAddItem(productName, promotionBonusQuantity), + this::isValidPositive + ); + + // ์ฆ์ • ์ƒํ’ˆ ์ถ”๊ฐ€ ๊ตฌ๋งค ์•ˆ ํ•  ๊ฒฝ์šฐ + if (!addItem) { + promotable.decreaseQuantity(purchaseQuantity); + receipt.updateReceipt(purchasedProduct, 0, 0); + continue; + } + //์ฆ์ • ์ƒํ’ˆ ์ถ”๊ฐ€ ๊ตฌ๋งคํ•  ๊ฒฝ์šฐ + purchasedProduct.addQuantity(); + } + + // ์•„๋ž˜ ๋‹ค ๊ตฌ๋งค ๊ฐœ์ˆ˜>= ํ”„๋กœ๋ชจ์…˜ ํ•ด๋‹น ๊ฐœ์ˆ˜ + + // ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ < ํ”„๋กœ๋ชจ์…˜ ํ•ด๋‹น ๊ฐœ์ˆ˜ + if (promotionalProductQuantity < promotionAcquiredQuantity) { + int finalPurchaseQuantity = purchasedProduct.parseQuantity(); + int nonPromotableQuantity = finalPurchaseQuantity - promotionalProductQuantity; + + boolean purchaseFullPrice = getValidInput( + () -> inputView.readPurchaseFullPrice(productName, finalPurchaseQuantity), + this::isValidPositive + ); + + //ํ”„๋กœ๋ชจ์…˜ ์—†๋Š” ๊ฑฐ๋ฅผ ์ •๊ฐ€๋กœ ๊ตฌ๋งค ์•ˆ ํ•˜๊ธฐ + if (!purchaseFullPrice) { + purchasedProduct.decreaseQuantity(finalPurchaseQuantity); + receipt.updateReceipt(purchasedProduct, 0, 0); + continue; + } + + //ํ”„๋กœ๋ชจ์…˜ ์—†๋Š” ๊ฑฐ๋ฅผ ์ •๊ฐ€๋กœ ๊ตฌ๋งคํ•˜๊ธฐ + promotable.decreaseQuantity(promotionalProductQuantity); + nonPromotable.decreaseQuantity(nonPromotableQuantity); + receipt.updateReceipt(purchasedProduct, 0, 0); + continue; + } + + // ์•„๋ž˜๋กœ ๋‹ค ํ”„๋กœ๋ชจ์…˜ ์žฌ๊ณ >= ํ”„๋กœ๋ชจ์…˜ ํ•ด๋‹น ๊ฐœ์ˆ˜, ๊ตฌ๋งค ๊ฐœ์ˆ˜>= ํ”„๋กœ๋ชจ์…˜ ํ•ด๋‹น ๊ฐœ์ˆ˜ + + int promotableQuantity = + (promotionalProductQuantity / promotionAcquiredQuantity) * promotionAcquiredQuantity; + + purchaseQuantity = purchasedProduct.parseQuantity(); + int nonPromotableQuantity = purchaseQuantity - promotableQuantity; + + + + + + + + // ํ”„๋กœ๋ชจ์…˜ ๋ฐ›์„ ์ˆ˜ ์žˆ๋Š” ๊ฐœ์ˆ˜>= ๊ตฌ๋งค ๊ฐœ์ˆ˜ + if (promotableQuantity >= purchaseQuantity) { + + if(purchaseQuantity%promotionAcquiredQuantity == 0){ + promotable.decreaseQuantity(purchaseQuantity); + receipt.updateReceipt(purchasedProduct, purchaseQuantity, purchaseQuantity / promotionAcquiredQuantity); + continue; + } + int currentNonPromotableQuantity = purchaseQuantity%promotionAcquiredQuantity; + + if (promotionMinQuantity == 1 && currentNonPromotableQuantity == 1) { + boolean addItem = getValidInput( + () -> inputView.readAddItem(productName, 1), + this::isValidPositive + ); + + if (addItem) { + purchasedProduct.addQuantity(); + purchaseQuantity++; + promotable.decreaseQuantity(purchaseQuantity); + receipt.updateReceipt(purchasedProduct, purchaseQuantity, purchaseQuantity / 2); + } else { + promotable.decreaseQuantity(purchaseQuantity - 1); + nonPromotable.decreaseQuantity(1); + receipt.updateReceipt(purchasedProduct, purchaseQuantity - 1, (purchaseQuantity - 1) / 2); + } + continue; + } + + + // ํ”„๋กœ๋ชจ์…˜ ์กฐ๊ฑด์„ ์ถฉ์กฑํ•˜์ง€ ์•Š๋Š” ์ˆ˜๋Ÿ‰์ด ์žˆ๋Š” ๊ฒฝ์šฐ + if (currentNonPromotableQuantity > 0) { + int additionalItemsForPromotion = promotionAcquiredQuantity - currentNonPromotableQuantity; + + int finalAdditionalItemsForPromotion = additionalItemsForPromotion; + boolean addItems = getValidInput( + () -> inputView.readAddItem(productName, finalAdditionalItemsForPromotion), + this::isValidPositive + ); + + if (addItems) { + // ์ถ”๊ฐ€ ๊ตฌ๋งค๋กœ ํ”„๋กœ๋ชจ์…˜ ์กฐ๊ฑด ์ถฉ์กฑ + purchasedProduct.decreaseQuantity(-finalAdditionalItemsForPromotion); + purchaseQuantity += additionalItemsForPromotion; + promotable.decreaseQuantity(purchaseQuantity); + receipt.updateReceipt(purchasedProduct, purchaseQuantity, purchaseQuantity / promotionAcquiredQuantity); + } else { + // ์ถ”๊ฐ€ ๊ตฌ๋งค ๊ฑฐ๋ถ€, ์ผ๋ถ€๋งŒ ํ”„๋กœ๋ชจ์…˜ ์ ์šฉ + int promotionAppliedQuantity = purchaseQuantity - currentNonPromotableQuantity; + promotable.decreaseQuantity(promotionAppliedQuantity); + nonPromotable.decreaseQuantity(currentNonPromotableQuantity); + receipt.updateReceipt(purchasedProduct, promotionAppliedQuantity, promotionAppliedQuantity / promotionAcquiredQuantity); + } + } else { + // ๋ชจ๋“  ์ˆ˜๋Ÿ‰์ด ํ”„๋กœ๋ชจ์…˜ ์กฐ๊ฑด์„ ์ถฉ์กฑ + promotable.decreaseQuantity(purchaseQuantity); + receipt.updateReceipt(purchasedProduct, purchaseQuantity, purchaseQuantity / promotionAcquiredQuantity); + } + continue; + } + + + + + + + + + //์•„๋ž˜๋กœ ๋‹ค ํ”„๋กœ๋ชจ์…˜ ๋ฐ›์„ ์ˆ˜ ์žˆ๋Š” ๊ฐœ์ˆ˜< ๊ตฌ๋งค ๊ฐœ์ˆ˜ + //========================================= + + boolean purchaseFullPrice = getValidInput( + () -> inputView.readPurchaseFullPrice(productName, nonPromotableQuantity), + this::isValidPositive + ); + if (!purchaseFullPrice) { + purchasedProduct.decreaseQuantity(nonPromotableQuantity); + int finalPurchaseQuantity = purchasedProduct.parseQuantity(); + promotable.decreaseQuantity(finalPurchaseQuantity); + receipt.updateReceipt(purchasedProduct, promotableQuantity, + promotableQuantity / promotionAcquiredQuantity); + continue; + } + promotable.decreaseQuantity(promotableQuantity); + purchaseFullPrice(promotable, nonPromotableQuantity, nonPromotable); + + receipt.updateReceipt(purchasedProduct, promotableQuantity, promotableQuantity / promotionAcquiredQuantity); + + } + + return receipt; + } + + private void purchaseFullPrice(Product promotableProductInStock, int nonPromotableQuantity, + Product nonPromotableProductInStock) { + int remainingQuantityInStock = Integer.parseInt(promotableProductInStock.getValueOfTheField("quantity")); + int decreaseInNonPromotableQuantity = nonPromotableQuantity - remainingQuantityInStock; + + promotableProductInStock.decreaseQuantity(remainingQuantityInStock); + nonPromotableProductInStock.decreaseQuantity(decreaseInNonPromotableQuantity); + } + + + private boolean isValidPositive(String input) { + if (input.equals("Y")) { + return true; + } + if (input.equals("N")) { + return false; + } + throw new ErrorException(InputErrorType.NEED_AVAILABLE_INPUT); + } + + + public static <T> T getValidInput(Supplier<String> inputSupplier, Function<String, T> converter) { + while (true) { + String input = inputSupplier.get(); + try { + return converter.apply(input); + } catch (ErrorException e) { + System.out.println(e.getMessage()); + } + } + } + +}
Java
enum์„ ์‚ฌ์šฉํ•ด์„œ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋Š” ๋ถ€๋ถ„์ž…๋‹ˆ๋‹ค!
@@ -1,7 +1,26 @@ package store; + +import store.controller.FrontController; +import store.controller.ProductController; +import store.controller.PromotionController; +import store.view.InputView; +import store.view.OutputView; + + public class Application { + + public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + InputView inputView = new InputView(); + OutputView outputView = new OutputView(); + ProductController productController = new ProductController(); + PromotionController promotionController = new PromotionController(inputView, productController); + + FrontController frontController = new FrontController(inputView, outputView, productController, + promotionController); + frontController.runFrontController(); + } + }
Java
ํด๋ž˜์Šค๋ช…์œผ๋กœ ์˜๋ฏธ๋ฅผ ์•Œ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ๋ฉ”์†Œ๋“œ๋ช…์— ํ‘œํ˜„์•ˆํ•ด๋„ ๋  ๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,53 @@ +package christmas.Domain; + +import christmas.Constant.December; +import christmas.Constant.DiscountPrice; +import java.util.HashMap; +import java.util.Map; + +public class Discount { + + public Map<String, Integer> applyDiscount(int visitDay, int dessertCount, int mainCount) { + Map<String, Integer> appliedDiscount = new HashMap<>(); + calculateChristmasDiscount(visitDay, appliedDiscount); + calculateWeekendDiscount(visitDay, mainCount, appliedDiscount); + calculateSpecialDiscount(visitDay, appliedDiscount); + calculateWeekdayDiscount(visitDay, dessertCount, appliedDiscount); + return appliedDiscount; + } + + private void calculateChristmasDiscount(int visitDay, Map<String, Integer> appliedDiscount) { + if (December.FIRST_DAY.getDay() <= visitDay && visitDay <= December.CHRISTMAS.getDay()) { + appliedDiscount.put("ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด ํ• ์ธ", + ((visitDay - December.FIRST_DAY.getDay()) * DiscountPrice.DAILY_INCREASE.getPrice()) + + DiscountPrice.DEFAULT_DISCOUNT.getPrice()); + } + } + + private void calculateWeekendDiscount(int visitDay, int mainCount, + Map<String, Integer> appliedDiscount) { + if (getDayOfWeek(visitDay) == December.FRIDAY.getDay() + || getDayOfWeek(visitDay) == December.SATURDAY.getDay()) { + appliedDiscount.put("์ฃผ๋ง ํ• ์ธ", DiscountPrice.WEEKEND_DISCOUNT.getPrice() * mainCount); + } + } + + private void calculateSpecialDiscount(int visitDay, Map<String, Integer> appliedDiscount) { + if (getDayOfWeek(visitDay) == December.SUNDAY.getDay() + || visitDay == December.CHRISTMAS.getDay()) { + appliedDiscount.put("ํŠน๋ณ„ ํ• ์ธ", DiscountPrice.SPECIAL_DISCOUNT.getPrice()); + } + } + + private void calculateWeekdayDiscount(int visitDay, int dessertCount, + Map<String, Integer> appliedDiscount) { + if (December.SUNDAY.getDay() <= getDayOfWeek(visitDay) + && getDayOfWeek(visitDay) <= December.THURSDAY.getDay()) { + appliedDiscount.put("ํ‰์ผ ํ• ์ธ", DiscountPrice.WEEKDAY_DISCOUNT.getPrice() * dessertCount); + } + } + + private static int getDayOfWeek(int visitDay) { + return visitDay % December.WEEK_DAYS.getDay(); + } +}
Java
์ œ๊ฐ€ Enum ๊ณผ ํ•จ์ˆ˜ํ˜•์„ ํ™œ์šฉํ•˜์ง€๋Š” ์•Š์•˜์ง€๋งŒ ๋‹ค๋ฅธ๋ถ„์ด ํ™œ์šฉํ•˜์‹  ๊ฒƒ์„ ๋ดค์–ด์„œ ๊ณต์œ ํ•ด๋“œ๋ฆฝ๋‹ˆ๋‹ค! [์ด ๋งํฌ](https://github.com/june-777/java-christmas-6-june-777/pull/1/files#diff-7bfcb10ed508aaf21090292db65f13df60f023b14552f1338a16fe10023b9948)์—์„œ EventType ๋ถ€๋ถ„์„ ํ™•์ธํ•ด๋ณด์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค! <img width="850" alt="image" src="https://github.com/Firedrago95/java-christmas-6-Firedrago95/assets/78288539/dc123cfb-535e-4223-8328-cfe3d4597608">
@@ -0,0 +1,97 @@ +package christmas.Controller; + +import christmas.Domain.PromotionService; +import christmas.Util.Parser; +import christmas.View.InputView; +import christmas.View.OutputView; + + +public class PromotionController { + + private PromotionService promotionService; + + public void run() { + setPromotion(); + printOrderList(); + printTotalPrice(); + if (hasNoEvent()) { + printNoEvent(); + return; + } + printEligibleGift(); + printAppliedDiscount(); + printTotalBenefit(); + printTotalPayment(); + printChristmasBadge(); + } + + private void setPromotion() { + setUpService(); + setDate(); + setOrder(); + } + + private void setUpService() { + promotionService = new PromotionService(); + } + + private void setDate() { + try { + int visitDay = InputView.requestVisitDay(); + promotionService.createDate(visitDay); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + setDate(); + } + } + + private void setOrder() { + try { + String orders = InputView.requestOrder(); + promotionService.createOrder(Parser.convertStringToMap(orders)); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + setOrder(); + } + } + + private void printOrderList() { + OutputView.printOrder(promotionService.getOrderList()); + } + + private void printTotalPrice() { + OutputView.printTotalPrice(promotionService.getTotalPrice()); + } + + private void printNoEvent() { + OutputView.printNoEvent(promotionService.getTotalPrice()); + } + + private boolean hasNoEvent() { + boolean isEventOn = promotionService.isEventOn(); + if (!isEventOn) { + return true; + } + return false; + } + + private void printEligibleGift() { + OutputView.printGift(promotionService.hasGift()); + } + + private void printAppliedDiscount() { + OutputView.printDiscount(promotionService.getDiscount(), promotionService.hasGift()); + } + + private void printTotalBenefit() { + OutputView.printTotalBenefit(promotionService.getTotalBenefit()); + } + + private void printTotalPayment() { + OutputView.printTotalPayment(promotionService.getTotalPayment()); + } + + private void printChristmasBadge() { + OutputView.printBadge(promotionService.getChristmasBadge()); + } +}
Java
์„œ๋น„์Šค ๊ณ„์ธต์€ ํ•œ๋ฒˆ ์„ค์ •๋˜๊ณ  ๋‚œ ๋’ค๋กœ ๋ณ€๊ฒฝ๋˜์ง€ ์•Š์œผ๋‹ˆ๊นŒ Controller ์ƒ์„ฑ์ž๋ฅผ ํ†ตํ•ด์„œ ์ฃผ์ž… ๋ฐ›๋Š” ๋ฐฉ๋ฒ•๋„ ๊ดœ์ฐฎ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!๐Ÿ˜
@@ -0,0 +1,97 @@ +package christmas.Controller; + +import christmas.Domain.PromotionService; +import christmas.Util.Parser; +import christmas.View.InputView; +import christmas.View.OutputView; + + +public class PromotionController { + + private PromotionService promotionService; + + public void run() { + setPromotion(); + printOrderList(); + printTotalPrice(); + if (hasNoEvent()) { + printNoEvent(); + return; + } + printEligibleGift(); + printAppliedDiscount(); + printTotalBenefit(); + printTotalPayment(); + printChristmasBadge(); + } + + private void setPromotion() { + setUpService(); + setDate(); + setOrder(); + } + + private void setUpService() { + promotionService = new PromotionService(); + } + + private void setDate() { + try { + int visitDay = InputView.requestVisitDay(); + promotionService.createDate(visitDay); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + setDate(); + } + } + + private void setOrder() { + try { + String orders = InputView.requestOrder(); + promotionService.createOrder(Parser.convertStringToMap(orders)); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + setOrder(); + } + } + + private void printOrderList() { + OutputView.printOrder(promotionService.getOrderList()); + } + + private void printTotalPrice() { + OutputView.printTotalPrice(promotionService.getTotalPrice()); + } + + private void printNoEvent() { + OutputView.printNoEvent(promotionService.getTotalPrice()); + } + + private boolean hasNoEvent() { + boolean isEventOn = promotionService.isEventOn(); + if (!isEventOn) { + return true; + } + return false; + } + + private void printEligibleGift() { + OutputView.printGift(promotionService.hasGift()); + } + + private void printAppliedDiscount() { + OutputView.printDiscount(promotionService.getDiscount(), promotionService.hasGift()); + } + + private void printTotalBenefit() { + OutputView.printTotalBenefit(promotionService.getTotalBenefit()); + } + + private void printTotalPayment() { + OutputView.printTotalPayment(promotionService.getTotalPayment()); + } + + private void printChristmasBadge() { + OutputView.printBadge(promotionService.getChristmasBadge()); + } +}
Java
์ €๋„ ์ž˜ ํ™œ์šฉํ•˜์ง€๋Š” ๋ชปํ•˜์ง€๋งŒ ํ•จ์ˆ˜ํ˜• ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ํ™œ์šฉํ•ด๋ณด์‹œ๋ฉด ํ•˜๋‚˜์˜ `try-catch` ๋ฌธ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋”๋ผ๊ณ ์š”! ๊ฐ™์€ ์ง€์›์ž์ด์‹  ํ˜„์ค€๋‹˜์ด [์ •๋ฆฌํ•ด์ฃผ์‹  ๊ธ€](https://hstory0208.tistory.com/entry/Java-%ED%95%A8%EC%88%98%ED%98%95-%EC%9D%B8%ED%84%B0%ED%8E%98%EC%9D%B4%EC%8A%A4%EB%9E%80-%ED%99%9C%EC%9A%A9-%EB%B0%A9%EB%B2%95%EC%97%90-%EB%8C%80%ED%95%B4-%EC%95%8C%EC%95%84%EB%B3%B4%EC%9E%90)์ด ์žˆ์–ด์„œ ๊ณต์œ ํ•ด๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,28 @@ +package christmas.View; + +import camp.nextstep.edu.missionutils.Console; +import christmas.Domain.Date; + +public class InputView { + + public static final String REQUEST_ORDER = + "์ฃผ๋ฌธํ•˜์‹ค ๋ฉ”๋‰ด๋ฅผ ๋ฉ”๋‰ด์™€ ๊ฐœ์ˆ˜๋ฅผ ์•Œ๋ ค ์ฃผ์„ธ์š”. (e.g. ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€-2,๋ ˆ๋“œ์™€์ธ-1,์ดˆ์ฝ”์ผ€์ดํฌ-1)"; + private static final String REQUEST_VISIT_DAY = + "12์›” ์ค‘ ์‹๋‹น ์˜ˆ์ƒ ๋ฐฉ๋ฌธ ๋‚ ์งœ๋Š” ์–ธ์ œ์ธ๊ฐ€์š”? (์ˆซ์ž๋งŒ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”!)"; + + public static int requestVisitDay() { + try { + System.out.println(REQUEST_VISIT_DAY); + return Integer.parseInt(Console.readLine()); + } catch (NumberFormatException e) { + System.out.println(Date.INVALID_RANGE); + return requestVisitDay(); + } + } + + public static String requestOrder() { + System.out.println(REQUEST_ORDER); + return Console.readLine(); + } + +}
Java
์ ‘๊ทผ ์ œ์–ด์ž๊ฐ€ ๋‹ค๋ฅธ ํŠน๋ณ„ํ•œ ์ด์œ ๊ฐ€ ์žˆ์œผ์‹œ๋‚˜์š”??๐Ÿง
@@ -0,0 +1,28 @@ +package christmas.View; + +import camp.nextstep.edu.missionutils.Console; +import christmas.Domain.Date; + +public class InputView { + + public static final String REQUEST_ORDER = + "์ฃผ๋ฌธํ•˜์‹ค ๋ฉ”๋‰ด๋ฅผ ๋ฉ”๋‰ด์™€ ๊ฐœ์ˆ˜๋ฅผ ์•Œ๋ ค ์ฃผ์„ธ์š”. (e.g. ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€-2,๋ ˆ๋“œ์™€์ธ-1,์ดˆ์ฝ”์ผ€์ดํฌ-1)"; + private static final String REQUEST_VISIT_DAY = + "12์›” ์ค‘ ์‹๋‹น ์˜ˆ์ƒ ๋ฐฉ๋ฌธ ๋‚ ์งœ๋Š” ์–ธ์ œ์ธ๊ฐ€์š”? (์ˆซ์ž๋งŒ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”!)"; + + public static int requestVisitDay() { + try { + System.out.println(REQUEST_VISIT_DAY); + return Integer.parseInt(Console.readLine()); + } catch (NumberFormatException e) { + System.out.println(Date.INVALID_RANGE); + return requestVisitDay(); + } + } + + public static String requestOrder() { + System.out.println(REQUEST_ORDER); + return Console.readLine(); + } + +}
Java
๊ฐœ์ธ์ ์ธ ์ƒ๊ฐ์ด์ง€๋งŒ ์ด๋Ÿฌ๋ฉด `IllegalArgumentException` ์ด ์•„๋‹Œ `NumberFormatException` ๊ฐ€ ๋ฐœ์ƒํ•  ๊ฒƒ ๊ฐ™์•„์š”. ๋ฌผ๋ก  `NumberFormatException`๊ฐ€ `IllegalArgumentException` ์˜ ์ž์‹ ์˜ˆ์™ธ์ด์ง€๋งŒ ๊ทธ๋ž˜๋„ ์š”๊ตฌ์‚ฌํ•ญ์— ๋ช…์‹œ์ ์œผ๋กœ `IllegalArgumentException` ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๋ผ๊ณ  ๋˜์–ด ์žˆ์œผ๋‹ˆ๊นŒ ์ง€๊ฒจ์ฃผ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!(์ง€๊ทนํžˆ ๊ฐœ์ธ์ ์ธ ์˜๊ฒฌ์ž…๋‹ˆ๋‹ค!โ˜บ๏ธ)
@@ -0,0 +1,97 @@ +package christmas.Controller; + +import christmas.Domain.PromotionService; +import christmas.Util.Parser; +import christmas.View.InputView; +import christmas.View.OutputView; + + +public class PromotionController { + + private PromotionService promotionService; + + public void run() { + setPromotion(); + printOrderList(); + printTotalPrice(); + if (hasNoEvent()) { + printNoEvent(); + return; + } + printEligibleGift(); + printAppliedDiscount(); + printTotalBenefit(); + printTotalPayment(); + printChristmasBadge(); + } + + private void setPromotion() { + setUpService(); + setDate(); + setOrder(); + } + + private void setUpService() { + promotionService = new PromotionService(); + } + + private void setDate() { + try { + int visitDay = InputView.requestVisitDay(); + promotionService.createDate(visitDay); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + setDate(); + } + } + + private void setOrder() { + try { + String orders = InputView.requestOrder(); + promotionService.createOrder(Parser.convertStringToMap(orders)); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + setOrder(); + } + } + + private void printOrderList() { + OutputView.printOrder(promotionService.getOrderList()); + } + + private void printTotalPrice() { + OutputView.printTotalPrice(promotionService.getTotalPrice()); + } + + private void printNoEvent() { + OutputView.printNoEvent(promotionService.getTotalPrice()); + } + + private boolean hasNoEvent() { + boolean isEventOn = promotionService.isEventOn(); + if (!isEventOn) { + return true; + } + return false; + } + + private void printEligibleGift() { + OutputView.printGift(promotionService.hasGift()); + } + + private void printAppliedDiscount() { + OutputView.printDiscount(promotionService.getDiscount(), promotionService.hasGift()); + } + + private void printTotalBenefit() { + OutputView.printTotalBenefit(promotionService.getTotalBenefit()); + } + + private void printTotalPayment() { + OutputView.printTotalPayment(promotionService.getTotalPayment()); + } + + private void printChristmasBadge() { + OutputView.printBadge(promotionService.getChristmasBadge()); + } +}
Java
```suggestion private boolean hasNoEvent() { return !promotionService.isEventOn(); } ``` ๊ฐ„๋‹จํ•˜๊ฒŒ ๋ฐ”๊ฟ”์ค„ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”!โ˜บ๏ธ
@@ -0,0 +1,54 @@ +package christmas.Util.Validator; + +import christmas.Domain.Menu; +import java.util.Map; + +public class OrderValidator { + + public static final String INVALID_ORDER = "[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ์ฃผ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."; + public static final int MAX_ORDER = 20; + public static final int MIN_ORDER_QUANTITY = 1; + + public static void validateOrder(Map<String, Integer> order) throws IllegalArgumentException { + validateMenu(order); + validateAllBeverage(order); + validateNumber(order); + validateNumberRange(order); + } + + private static void validateMenu(Map<String, Integer> order) throws IllegalArgumentException { + boolean isContain = order.keySet().stream() + .allMatch(Menu::hasContain); + if (!isContain) { + throw new IllegalArgumentException(INVALID_ORDER); + } + } + + private static void validateAllBeverage(Map<String, Integer> order) + throws IllegalArgumentException { + boolean allBeverage = order.keySet().stream() + .allMatch(Menu::isBeverage); + if (allBeverage) { + throw new IllegalArgumentException(INVALID_ORDER); + } + } + + private static void validateNumber(Map<String, Integer> order) throws IllegalArgumentException { + int menuCount = order.values().stream() + .mapToInt(Integer::intValue) + .sum(); + if (menuCount > MAX_ORDER) { + throw new IllegalArgumentException(INVALID_ORDER); + } + } + + private static void validateNumberRange(Map<String, Integer> order) + throws IllegalArgumentException { + boolean allQuantitiesValid = order.values().stream() + .allMatch(quantity -> quantity >= MIN_ORDER_QUANTITY); + if (!allQuantitiesValid) { + throw new IllegalArgumentException(INVALID_ORDER); + } + } + +}
Java
์™€,, `allMatch` ๋ฅผ ํ™œ์šฉํ•ด์„œ ์ •๋ง ๊น”๋”ํ•˜๊ฒŒ ํ•ด์ฃผ์…จ๋„ค์š”! ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค!๐Ÿ‘
@@ -0,0 +1,117 @@ +package christmas.View; + +import christmas.Domain.Menu; +import java.util.Map; + +public class OutputView { + + public static final String ORDER_LIST_MESSAGE = "<์ฃผ๋ฌธ ๋ฉ”๋‰ด>"; + public static final String TOTAL_PRICE_MESSAGE = "<ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก>"; + public static final String GIFT_MESSAGE = "<์ฆ์ • ๋ฉ”๋‰ด>"; + public static final String CHAMPAGNE = "์ƒดํŽ˜์ธ 1๊ฐœ"; + public static final String BENEFIT_LIST_MESSAGE = "<ํ˜œํƒ ๋‚ด์—ญ>"; + public static final String CHAMPAGNE_AMOUNT_MESSAGE = "์ฆ์ • ์ด๋ฒคํŠธ: -25,000์›"; + public static final String BENEFIT_AMOUNT_MESSAGE = "<์ดํ˜œํƒ ๊ธˆ์•ก>"; + public static final String ZERO_AMOUNT = "0์›"; + public static final String TOTAL_PAYMENT_MESSAGE = "<ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก>"; + public static final String BADGE_MESSAGE = "<12์›” ์ด๋ฒคํŠธ ๋ฐฐ์ง€>"; + public static final String CURRENCY = "์›"; + public static final String NOTHING = "์—†์Œ"; + public static final int ZERO = 0; + + public static void printOrder(Map<Menu, Integer> order) { + System.out.println(ORDER_LIST_MESSAGE); + order.forEach( + (menu, quantity) -> System.out.println(menu.getName() + " " + quantity + "๊ฐœ")); + System.out.println(); + } + + public static void printTotalPrice(int totalPrice) { + System.out.println(TOTAL_PRICE_MESSAGE); + System.out.println(convertFormatted(totalPrice) + CURRENCY); + System.out.println(); + } + + public static void printGift(boolean isEligibleForGift) { + if (!isEligibleForGift) { + System.out.println(GIFT_MESSAGE); + printNothing(); + return; + } + System.out.println(GIFT_MESSAGE); + System.out.println(CHAMPAGNE); + System.out.println(); + } + + public static void printNoEvent(int totalPrice) { + System.out.println(GIFT_MESSAGE); + printNothing(); + System.out.println(BENEFIT_LIST_MESSAGE); + printNothing(); + System.out.println(BENEFIT_AMOUNT_MESSAGE); + System.out.println(ZERO_AMOUNT); + System.out.println(); + System.out.println(TOTAL_PAYMENT_MESSAGE); + System.out.println(totalPrice + CURRENCY); + System.out.println(); + System.out.println(BADGE_MESSAGE); + printNothing(); + } + + public static void printDiscount(Map<String, Integer> appliedDiscount, boolean isEligibleGift) { + System.out.println(BENEFIT_LIST_MESSAGE); + if (sumTotalDiscount(appliedDiscount) == ZERO && !isEligibleGift) { + printNothing(); + return; + } + printDiscountList(appliedDiscount); + printGiftAmount(isEligibleGift); + } + + private static void printDiscountList(Map<String, Integer> appliedDiscount) { + for (Map.Entry<String, Integer> discount : appliedDiscount.entrySet()) { + if (discount.getValue() != ZERO) { + System.out.println( + discount.getKey() + ": " + "-" + convertFormatted(discount.getValue()) + + CURRENCY); + } + } + } + + private static int sumTotalDiscount(Map<String, Integer> appliedDiscount) { + return appliedDiscount.values().stream().mapToInt(Integer::intValue).sum(); + } + + private static void printGiftAmount(boolean isEligibleGift) { + if (isEligibleGift) { + System.out.println(CHAMPAGNE_AMOUNT_MESSAGE); + } + System.out.println(); + } + + public static void printTotalBenefit(int totalBenefit) { + System.out.println(BENEFIT_AMOUNT_MESSAGE); + System.out.println("-" + convertFormatted(totalBenefit) + CURRENCY); + System.out.println(); + } + + public static void printTotalPayment(int totalPayment) { + System.out.println(TOTAL_PAYMENT_MESSAGE); + System.out.println(convertFormatted(totalPayment) + CURRENCY); + System.out.println(); + } + + public static void printBadge(String badge) { + System.out.println(BADGE_MESSAGE); + System.out.println(badge); + } + + private static void printNothing() { + System.out.println(NOTHING); + System.out.println(); + } + + private static String convertFormatted(int number) { + return String.format("%,d", number); + } +}
Java
์™€,, ์ €๋Š” DecimalFormat ์„ ํ™œ์šฉํ–ˆ์—ˆ๋Š”๋ฐ ์ด๋ ‡๊ฒŒ ๊ฐ„๋‹จํ•˜๊ฒŒ ํ•  ์ˆ˜ ์žˆ์—ˆ๊ตฐ์š”! ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค!
@@ -0,0 +1,53 @@ +package christmas.Domain; + +import christmas.Constant.December; +import christmas.Constant.DiscountPrice; +import java.util.HashMap; +import java.util.Map; + +public class Discount { + + public Map<String, Integer> applyDiscount(int visitDay, int dessertCount, int mainCount) { + Map<String, Integer> appliedDiscount = new HashMap<>(); + calculateChristmasDiscount(visitDay, appliedDiscount); + calculateWeekendDiscount(visitDay, mainCount, appliedDiscount); + calculateSpecialDiscount(visitDay, appliedDiscount); + calculateWeekdayDiscount(visitDay, dessertCount, appliedDiscount); + return appliedDiscount; + } + + private void calculateChristmasDiscount(int visitDay, Map<String, Integer> appliedDiscount) { + if (December.FIRST_DAY.getDay() <= visitDay && visitDay <= December.CHRISTMAS.getDay()) { + appliedDiscount.put("ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด ํ• ์ธ", + ((visitDay - December.FIRST_DAY.getDay()) * DiscountPrice.DAILY_INCREASE.getPrice()) + + DiscountPrice.DEFAULT_DISCOUNT.getPrice()); + } + } + + private void calculateWeekendDiscount(int visitDay, int mainCount, + Map<String, Integer> appliedDiscount) { + if (getDayOfWeek(visitDay) == December.FRIDAY.getDay() + || getDayOfWeek(visitDay) == December.SATURDAY.getDay()) { + appliedDiscount.put("์ฃผ๋ง ํ• ์ธ", DiscountPrice.WEEKEND_DISCOUNT.getPrice() * mainCount); + } + } + + private void calculateSpecialDiscount(int visitDay, Map<String, Integer> appliedDiscount) { + if (getDayOfWeek(visitDay) == December.SUNDAY.getDay() + || visitDay == December.CHRISTMAS.getDay()) { + appliedDiscount.put("ํŠน๋ณ„ ํ• ์ธ", DiscountPrice.SPECIAL_DISCOUNT.getPrice()); + } + } + + private void calculateWeekdayDiscount(int visitDay, int dessertCount, + Map<String, Integer> appliedDiscount) { + if (December.SUNDAY.getDay() <= getDayOfWeek(visitDay) + && getDayOfWeek(visitDay) <= December.THURSDAY.getDay()) { + appliedDiscount.put("ํ‰์ผ ํ• ์ธ", DiscountPrice.WEEKDAY_DISCOUNT.getPrice() * dessertCount); + } + } + + private static int getDayOfWeek(int visitDay) { + return visitDay % December.WEEK_DAYS.getDay(); + } +}
Java
์ œ๊ฐ€ ์ฐพ๋˜๊ฑด๋ฐ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,146 @@ +import pickle +import pandas as pd +import numpy as np +import re +from openai import OpenAI +import os +from tqdm import tqdm +import time + +def clean(answer): + ''' + ์ฃผ์–ด์ง„ ๋‹ต๋ณ€์„ ์ „์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜ + Args: + answer (str) : FAQ์˜ ๋‹ต๋ณ€ ๋ฐ์ดํ„ฐ + Returns: + answer (str) : ์ „์ฒ˜๋ฆฌ๋œ ๋‹ต๋ณ€ ๋ฐ์ดํ„ฐ + related (list) : ๊ด€๋ จ ๋„์›€๋ง ๋ชฉ๋ก + ''' + + #๋ถˆํ•„์š”ํ•œ ๋ณ„์  ์ œ๊ฑฐ + other = '\n\n\n์œ„ ๋„์›€๋ง์ด ๋„์›€์ด ๋˜์—ˆ๋‚˜์š”?\n\n\n๋ณ„์ 1์ \n\n๋ณ„์ 2์ \n\n๋ณ„์ 3์ \n\n๋ณ„์ 4์ \n\n๋ณ„์ 5์ \n\n\n\n์†Œ์ค‘ํ•œ ์˜๊ฒฌ์„ ๋‚จ๊ฒจ์ฃผ์‹œ๋ฉด ๋ณด์™„ํ•˜๋„๋ก ๋…ธ๋ ฅํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.\n\n๋ณด๋‚ด๊ธฐ\n\n\n\n' + answer = answer.replace(other, ' ') + answer = answer.replace('๋„์›€๋ง ๋‹ซ๊ธฐ', '') + + #๊ด€๋ จ ๋„์›€๋ง์€ ๋”ฐ๋กœ ์ €์žฅ + if '๊ด€๋ จ ๋„์›€๋ง/ํ‚ค์›Œ๋“œ' in answer: + a = answer.split('๊ด€๋ จ ๋„์›€๋ง/ํ‚ค์›Œ๋“œ') + answer = a[0] + related = a[1] + related=related.strip().split('\n') + + else: + related = np.nan + + #์ „์ฒ˜๋ฆฌ + answer = re.sub('\s{2,}', '\n', answer) #๋นˆ์นธ์ด ๊ธด ๊ฒฝ์šฐ ์ค„์ด๊ธฐ + answer = answer.replace('\xa0','\n') #\xa0๋ฅผ \n์œผ๋กœ ํ†ต์ผ + answer = answer.replace("\'",'') #๋ณผ๋“œ ํ‘œ์‹œ ์ œ๊ฑฐ + + return answer, related + +def get_category(text): + ''' + ์งˆ๋ฌธ์˜ ์นดํ…Œ๊ณ ๋ฆฌ๋ฅผ ์ถ”์ถœํ•˜๋Š” ํ•จ์ˆ˜ + Args: + text (str) : FAQ์˜ ์งˆ๋ฌธ ๋ฐ์ดํ„ฐ + Returns: + extracted_text (str) : ์งˆ๋ฌธ์ด ์†ํ•˜๋Š” ์นดํ…Œ๊ณ ๋ฆฌ (์—†๋‹ค๋ฉด np.nan ๋ฐ˜ํ™˜) + ''' + pattern = r'^\[(.*?)\]' #[]ํ‘œ์‹œ๋กœ ์‹œ์ž‘ํ•˜๋Š” ๊ฒฝ์šฐ ์นดํ…Œ๊ณ ๋ฆฌ๋กœ ์ธ์‹ + matches = re.findall(pattern, text) + if matches: + extracted_text = matches[0] #์ฒซ ์นดํ…Œ๊ณ ๋ฆฌ๋งŒ ๋ฐ˜ํ™˜ + return extracted_text + else: + return np.nan + + +def chunk_string(long_string, chunk_size=500): + ''' + ๊ธด ๋ฌธ์ž์—ด์„ ์งง๊ฒŒ ๋‚˜๋ˆ„๋Š” ํ•จ์ˆ˜ + Args: + long_string (str) : ๊ธด ๋ฌธ์ž์—ด + chunk_size (int) : ์›ํ•˜๋Š” ๋ฌธ์ž์—ด ๊ธธ์ด + Returns: + chunks (list) : ๋‚˜๋ˆ ์ง„ ์งง์€ ๋ฌธ์ž์—ด์˜ ๋ฆฌ์ŠคํŠธ + ''' + chunks = [] + current_chunk = '' + last_line = '' + previous_line = '' + + for line in long_string.split('\n'): + # ์ฃผ์–ด์ง„ chunk_size๋ฅผ ์ดˆ๊ณผํ•˜์ง€ ์•Š๋Š” ํ•œ ๊ณ„์†ํ•ด์„œ ํ˜„์žฌ chunk์— ์ƒˆ๋กœ์šด ์ค„ ์ถ”๊ฐ€ + if len(current_chunk) + len(line) <= chunk_size: + current_chunk += line + '\n' + last_line = line + '\n' + # ํ˜„์žฌ ์ฒญํฌ์— ์ค„์„ ์ถ”๊ฐ€ํ•˜๋ฉด chunk_size๋ฅผ ์ดˆ๊ณผํ•˜๊ฒŒ ๋˜๋ฉด ํ˜„์žฌ ์ฒญํฌ ์™„์„ฑ + else: + #์ด์ „ chunk์˜ ๋งˆ์ง€๋ง‰ ์ค„๋„ overlap๋˜๊ฒŒ ์•ž์— ํฌํ•จ + chunks.append((previous_line+current_chunk).rstrip('\n')) + previous_line = last_line + current_chunk = line + '\n' + + # ๋งˆ์ง€๋ง‰์œผ๋กœ ๋‚จ์€ chunk ์ฒ˜๋ฆฌ + if current_chunk: + chunks.append((previous_line+current_chunk).rstrip('\n')) + + return chunks + +def embed(text, wait_time=0.1): + ''' + ํ…์ŠคํŠธ๋ฅผ ์ž„๋ฒ ๋”ฉํ•˜๋Š” ํ•จ์ˆ˜ + Args: + text (str): ์ž„๋ฒ ๋”ฉํ•  ํ…์ŠคํŠธ + wait_time (float): ์š”์ฒญ ์‚ฌ์ด์˜ ๊ฐ„๊ฒฉ + Returns: + embedding (list): ํ…์ŠคํŠธ์˜ ์ž„๋ฒ ๋”ฉ + ''' + response = client.embeddings.create(input = text, model='text-embedding-3-small') + time.sleep(wait_time) + embedding = response.data[0].embedding + return embedding + +if __name__=="__main__": + + #FAQ ๋ฐ์ดํ„ฐ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ + with open('final_result.pkl', 'rb') as file: + loaded_data = pickle.load(file) + + df = pd.DataFrame(loaded_data.items()) + df.columns = ['Question','Answer'] + + #์งˆ๋ฌธ์˜ ์นดํ…Œ๊ณ ๋ฆฌ ์ •๋ณด ์ถ”์ถœ + df['Category'] = df['Question'].apply(get_category) + + #๋‹ต๋ณ€ ๋ฐ์ดํ„ฐ ์ „์ฒ˜๋ฆฌ ๋ฐ ๊ด€๋ จ ์งˆ๋ฌธ ์ •๋ณด ์ถ”์ถœ + df['Related'] = np.nan + df[['Answer', 'Related']] = df['Answer'].apply(clean).apply(pd.Series) + + #์ž„๋ฒ ๋”ฉ ์„ค์ • + api_key = input('Input API KEY: ') + os.environ["OPENAI_API_KEY"] = api_key + client = OpenAI() + + #์งˆ๋ฌธ ์ž„๋ฒ ๋”ฉ + tqdm.pandas(desc='Embedding Questions') + df['Question Vector'] = df['Question'].progress_apply(embed) + + #๋‹ต๋ณ€ chunking + df['Answer']=df['Answer'].apply(chunk_string) + df = df.explode('Answer') + df = df.reset_index() + df = df.rename(columns={'index': 'Question Index'}) + + #๋‹ต๋ณ€ ์ž„๋ฒ ๋”ฉ + tqdm.pandas(desc='Embedding Answers') + df['Answer Vector'] = df['Answer'].progress_apply(embed) + + #์งˆ๋ฌธ-๋‹ต๋ณ€ ์Œ ์ž„๋ฒ ๋”ฉ + df['QA'] = df['Question'] + ' ' + df['Answer'] + tqdm.pandas(desc='Embedding Question-Answer Pairs') + df['QA Vector'] = df['QA'].progress_apply(embed) + + #์ตœ์ข… ๋ฒกํ„ฐ DB ์ €์žฅ + df.to_pickle('vectordb.df') \ No newline at end of file
Python
ํŒŒ์ผ๋ช…์— ๋™์‚ฌ
@@ -0,0 +1,146 @@ +import pickle +import pandas as pd +import numpy as np +import re +from openai import OpenAI +import os +from tqdm import tqdm +import time + +def clean(answer): + ''' + ์ฃผ์–ด์ง„ ๋‹ต๋ณ€์„ ์ „์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜ + Args: + answer (str) : FAQ์˜ ๋‹ต๋ณ€ ๋ฐ์ดํ„ฐ + Returns: + answer (str) : ์ „์ฒ˜๋ฆฌ๋œ ๋‹ต๋ณ€ ๋ฐ์ดํ„ฐ + related (list) : ๊ด€๋ จ ๋„์›€๋ง ๋ชฉ๋ก + ''' + + #๋ถˆํ•„์š”ํ•œ ๋ณ„์  ์ œ๊ฑฐ + other = '\n\n\n์œ„ ๋„์›€๋ง์ด ๋„์›€์ด ๋˜์—ˆ๋‚˜์š”?\n\n\n๋ณ„์ 1์ \n\n๋ณ„์ 2์ \n\n๋ณ„์ 3์ \n\n๋ณ„์ 4์ \n\n๋ณ„์ 5์ \n\n\n\n์†Œ์ค‘ํ•œ ์˜๊ฒฌ์„ ๋‚จ๊ฒจ์ฃผ์‹œ๋ฉด ๋ณด์™„ํ•˜๋„๋ก ๋…ธ๋ ฅํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.\n\n๋ณด๋‚ด๊ธฐ\n\n\n\n' + answer = answer.replace(other, ' ') + answer = answer.replace('๋„์›€๋ง ๋‹ซ๊ธฐ', '') + + #๊ด€๋ จ ๋„์›€๋ง์€ ๋”ฐ๋กœ ์ €์žฅ + if '๊ด€๋ จ ๋„์›€๋ง/ํ‚ค์›Œ๋“œ' in answer: + a = answer.split('๊ด€๋ จ ๋„์›€๋ง/ํ‚ค์›Œ๋“œ') + answer = a[0] + related = a[1] + related=related.strip().split('\n') + + else: + related = np.nan + + #์ „์ฒ˜๋ฆฌ + answer = re.sub('\s{2,}', '\n', answer) #๋นˆ์นธ์ด ๊ธด ๊ฒฝ์šฐ ์ค„์ด๊ธฐ + answer = answer.replace('\xa0','\n') #\xa0๋ฅผ \n์œผ๋กœ ํ†ต์ผ + answer = answer.replace("\'",'') #๋ณผ๋“œ ํ‘œ์‹œ ์ œ๊ฑฐ + + return answer, related + +def get_category(text): + ''' + ์งˆ๋ฌธ์˜ ์นดํ…Œ๊ณ ๋ฆฌ๋ฅผ ์ถ”์ถœํ•˜๋Š” ํ•จ์ˆ˜ + Args: + text (str) : FAQ์˜ ์งˆ๋ฌธ ๋ฐ์ดํ„ฐ + Returns: + extracted_text (str) : ์งˆ๋ฌธ์ด ์†ํ•˜๋Š” ์นดํ…Œ๊ณ ๋ฆฌ (์—†๋‹ค๋ฉด np.nan ๋ฐ˜ํ™˜) + ''' + pattern = r'^\[(.*?)\]' #[]ํ‘œ์‹œ๋กœ ์‹œ์ž‘ํ•˜๋Š” ๊ฒฝ์šฐ ์นดํ…Œ๊ณ ๋ฆฌ๋กœ ์ธ์‹ + matches = re.findall(pattern, text) + if matches: + extracted_text = matches[0] #์ฒซ ์นดํ…Œ๊ณ ๋ฆฌ๋งŒ ๋ฐ˜ํ™˜ + return extracted_text + else: + return np.nan + + +def chunk_string(long_string, chunk_size=500): + ''' + ๊ธด ๋ฌธ์ž์—ด์„ ์งง๊ฒŒ ๋‚˜๋ˆ„๋Š” ํ•จ์ˆ˜ + Args: + long_string (str) : ๊ธด ๋ฌธ์ž์—ด + chunk_size (int) : ์›ํ•˜๋Š” ๋ฌธ์ž์—ด ๊ธธ์ด + Returns: + chunks (list) : ๋‚˜๋ˆ ์ง„ ์งง์€ ๋ฌธ์ž์—ด์˜ ๋ฆฌ์ŠคํŠธ + ''' + chunks = [] + current_chunk = '' + last_line = '' + previous_line = '' + + for line in long_string.split('\n'): + # ์ฃผ์–ด์ง„ chunk_size๋ฅผ ์ดˆ๊ณผํ•˜์ง€ ์•Š๋Š” ํ•œ ๊ณ„์†ํ•ด์„œ ํ˜„์žฌ chunk์— ์ƒˆ๋กœ์šด ์ค„ ์ถ”๊ฐ€ + if len(current_chunk) + len(line) <= chunk_size: + current_chunk += line + '\n' + last_line = line + '\n' + # ํ˜„์žฌ ์ฒญํฌ์— ์ค„์„ ์ถ”๊ฐ€ํ•˜๋ฉด chunk_size๋ฅผ ์ดˆ๊ณผํ•˜๊ฒŒ ๋˜๋ฉด ํ˜„์žฌ ์ฒญํฌ ์™„์„ฑ + else: + #์ด์ „ chunk์˜ ๋งˆ์ง€๋ง‰ ์ค„๋„ overlap๋˜๊ฒŒ ์•ž์— ํฌํ•จ + chunks.append((previous_line+current_chunk).rstrip('\n')) + previous_line = last_line + current_chunk = line + '\n' + + # ๋งˆ์ง€๋ง‰์œผ๋กœ ๋‚จ์€ chunk ์ฒ˜๋ฆฌ + if current_chunk: + chunks.append((previous_line+current_chunk).rstrip('\n')) + + return chunks + +def embed(text, wait_time=0.1): + ''' + ํ…์ŠคํŠธ๋ฅผ ์ž„๋ฒ ๋”ฉํ•˜๋Š” ํ•จ์ˆ˜ + Args: + text (str): ์ž„๋ฒ ๋”ฉํ•  ํ…์ŠคํŠธ + wait_time (float): ์š”์ฒญ ์‚ฌ์ด์˜ ๊ฐ„๊ฒฉ + Returns: + embedding (list): ํ…์ŠคํŠธ์˜ ์ž„๋ฒ ๋”ฉ + ''' + response = client.embeddings.create(input = text, model='text-embedding-3-small') + time.sleep(wait_time) + embedding = response.data[0].embedding + return embedding + +if __name__=="__main__": + + #FAQ ๋ฐ์ดํ„ฐ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ + with open('final_result.pkl', 'rb') as file: + loaded_data = pickle.load(file) + + df = pd.DataFrame(loaded_data.items()) + df.columns = ['Question','Answer'] + + #์งˆ๋ฌธ์˜ ์นดํ…Œ๊ณ ๋ฆฌ ์ •๋ณด ์ถ”์ถœ + df['Category'] = df['Question'].apply(get_category) + + #๋‹ต๋ณ€ ๋ฐ์ดํ„ฐ ์ „์ฒ˜๋ฆฌ ๋ฐ ๊ด€๋ จ ์งˆ๋ฌธ ์ •๋ณด ์ถ”์ถœ + df['Related'] = np.nan + df[['Answer', 'Related']] = df['Answer'].apply(clean).apply(pd.Series) + + #์ž„๋ฒ ๋”ฉ ์„ค์ • + api_key = input('Input API KEY: ') + os.environ["OPENAI_API_KEY"] = api_key + client = OpenAI() + + #์งˆ๋ฌธ ์ž„๋ฒ ๋”ฉ + tqdm.pandas(desc='Embedding Questions') + df['Question Vector'] = df['Question'].progress_apply(embed) + + #๋‹ต๋ณ€ chunking + df['Answer']=df['Answer'].apply(chunk_string) + df = df.explode('Answer') + df = df.reset_index() + df = df.rename(columns={'index': 'Question Index'}) + + #๋‹ต๋ณ€ ์ž„๋ฒ ๋”ฉ + tqdm.pandas(desc='Embedding Answers') + df['Answer Vector'] = df['Answer'].progress_apply(embed) + + #์งˆ๋ฌธ-๋‹ต๋ณ€ ์Œ ์ž„๋ฒ ๋”ฉ + df['QA'] = df['Question'] + ' ' + df['Answer'] + tqdm.pandas(desc='Embedding Question-Answer Pairs') + df['QA Vector'] = df['QA'].progress_apply(embed) + + #์ตœ์ข… ๋ฒกํ„ฐ DB ์ €์žฅ + df.to_pickle('vectordb.df') \ No newline at end of file
Python
์ฃผ์„์€ ์ข‹์œผ๋‚˜ ํƒ€์ดํ•‘๋„
@@ -0,0 +1,146 @@ +import pickle +import pandas as pd +import numpy as np +import re +from openai import OpenAI +import os +from tqdm import tqdm +import time + +def clean(answer): + ''' + ์ฃผ์–ด์ง„ ๋‹ต๋ณ€์„ ์ „์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜ + Args: + answer (str) : FAQ์˜ ๋‹ต๋ณ€ ๋ฐ์ดํ„ฐ + Returns: + answer (str) : ์ „์ฒ˜๋ฆฌ๋œ ๋‹ต๋ณ€ ๋ฐ์ดํ„ฐ + related (list) : ๊ด€๋ จ ๋„์›€๋ง ๋ชฉ๋ก + ''' + + #๋ถˆํ•„์š”ํ•œ ๋ณ„์  ์ œ๊ฑฐ + other = '\n\n\n์œ„ ๋„์›€๋ง์ด ๋„์›€์ด ๋˜์—ˆ๋‚˜์š”?\n\n\n๋ณ„์ 1์ \n\n๋ณ„์ 2์ \n\n๋ณ„์ 3์ \n\n๋ณ„์ 4์ \n\n๋ณ„์ 5์ \n\n\n\n์†Œ์ค‘ํ•œ ์˜๊ฒฌ์„ ๋‚จ๊ฒจ์ฃผ์‹œ๋ฉด ๋ณด์™„ํ•˜๋„๋ก ๋…ธ๋ ฅํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.\n\n๋ณด๋‚ด๊ธฐ\n\n\n\n' + answer = answer.replace(other, ' ') + answer = answer.replace('๋„์›€๋ง ๋‹ซ๊ธฐ', '') + + #๊ด€๋ จ ๋„์›€๋ง์€ ๋”ฐ๋กœ ์ €์žฅ + if '๊ด€๋ จ ๋„์›€๋ง/ํ‚ค์›Œ๋“œ' in answer: + a = answer.split('๊ด€๋ จ ๋„์›€๋ง/ํ‚ค์›Œ๋“œ') + answer = a[0] + related = a[1] + related=related.strip().split('\n') + + else: + related = np.nan + + #์ „์ฒ˜๋ฆฌ + answer = re.sub('\s{2,}', '\n', answer) #๋นˆ์นธ์ด ๊ธด ๊ฒฝ์šฐ ์ค„์ด๊ธฐ + answer = answer.replace('\xa0','\n') #\xa0๋ฅผ \n์œผ๋กœ ํ†ต์ผ + answer = answer.replace("\'",'') #๋ณผ๋“œ ํ‘œ์‹œ ์ œ๊ฑฐ + + return answer, related + +def get_category(text): + ''' + ์งˆ๋ฌธ์˜ ์นดํ…Œ๊ณ ๋ฆฌ๋ฅผ ์ถ”์ถœํ•˜๋Š” ํ•จ์ˆ˜ + Args: + text (str) : FAQ์˜ ์งˆ๋ฌธ ๋ฐ์ดํ„ฐ + Returns: + extracted_text (str) : ์งˆ๋ฌธ์ด ์†ํ•˜๋Š” ์นดํ…Œ๊ณ ๋ฆฌ (์—†๋‹ค๋ฉด np.nan ๋ฐ˜ํ™˜) + ''' + pattern = r'^\[(.*?)\]' #[]ํ‘œ์‹œ๋กœ ์‹œ์ž‘ํ•˜๋Š” ๊ฒฝ์šฐ ์นดํ…Œ๊ณ ๋ฆฌ๋กœ ์ธ์‹ + matches = re.findall(pattern, text) + if matches: + extracted_text = matches[0] #์ฒซ ์นดํ…Œ๊ณ ๋ฆฌ๋งŒ ๋ฐ˜ํ™˜ + return extracted_text + else: + return np.nan + + +def chunk_string(long_string, chunk_size=500): + ''' + ๊ธด ๋ฌธ์ž์—ด์„ ์งง๊ฒŒ ๋‚˜๋ˆ„๋Š” ํ•จ์ˆ˜ + Args: + long_string (str) : ๊ธด ๋ฌธ์ž์—ด + chunk_size (int) : ์›ํ•˜๋Š” ๋ฌธ์ž์—ด ๊ธธ์ด + Returns: + chunks (list) : ๋‚˜๋ˆ ์ง„ ์งง์€ ๋ฌธ์ž์—ด์˜ ๋ฆฌ์ŠคํŠธ + ''' + chunks = [] + current_chunk = '' + last_line = '' + previous_line = '' + + for line in long_string.split('\n'): + # ์ฃผ์–ด์ง„ chunk_size๋ฅผ ์ดˆ๊ณผํ•˜์ง€ ์•Š๋Š” ํ•œ ๊ณ„์†ํ•ด์„œ ํ˜„์žฌ chunk์— ์ƒˆ๋กœ์šด ์ค„ ์ถ”๊ฐ€ + if len(current_chunk) + len(line) <= chunk_size: + current_chunk += line + '\n' + last_line = line + '\n' + # ํ˜„์žฌ ์ฒญํฌ์— ์ค„์„ ์ถ”๊ฐ€ํ•˜๋ฉด chunk_size๋ฅผ ์ดˆ๊ณผํ•˜๊ฒŒ ๋˜๋ฉด ํ˜„์žฌ ์ฒญํฌ ์™„์„ฑ + else: + #์ด์ „ chunk์˜ ๋งˆ์ง€๋ง‰ ์ค„๋„ overlap๋˜๊ฒŒ ์•ž์— ํฌํ•จ + chunks.append((previous_line+current_chunk).rstrip('\n')) + previous_line = last_line + current_chunk = line + '\n' + + # ๋งˆ์ง€๋ง‰์œผ๋กœ ๋‚จ์€ chunk ์ฒ˜๋ฆฌ + if current_chunk: + chunks.append((previous_line+current_chunk).rstrip('\n')) + + return chunks + +def embed(text, wait_time=0.1): + ''' + ํ…์ŠคํŠธ๋ฅผ ์ž„๋ฒ ๋”ฉํ•˜๋Š” ํ•จ์ˆ˜ + Args: + text (str): ์ž„๋ฒ ๋”ฉํ•  ํ…์ŠคํŠธ + wait_time (float): ์š”์ฒญ ์‚ฌ์ด์˜ ๊ฐ„๊ฒฉ + Returns: + embedding (list): ํ…์ŠคํŠธ์˜ ์ž„๋ฒ ๋”ฉ + ''' + response = client.embeddings.create(input = text, model='text-embedding-3-small') + time.sleep(wait_time) + embedding = response.data[0].embedding + return embedding + +if __name__=="__main__": + + #FAQ ๋ฐ์ดํ„ฐ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ + with open('final_result.pkl', 'rb') as file: + loaded_data = pickle.load(file) + + df = pd.DataFrame(loaded_data.items()) + df.columns = ['Question','Answer'] + + #์งˆ๋ฌธ์˜ ์นดํ…Œ๊ณ ๋ฆฌ ์ •๋ณด ์ถ”์ถœ + df['Category'] = df['Question'].apply(get_category) + + #๋‹ต๋ณ€ ๋ฐ์ดํ„ฐ ์ „์ฒ˜๋ฆฌ ๋ฐ ๊ด€๋ จ ์งˆ๋ฌธ ์ •๋ณด ์ถ”์ถœ + df['Related'] = np.nan + df[['Answer', 'Related']] = df['Answer'].apply(clean).apply(pd.Series) + + #์ž„๋ฒ ๋”ฉ ์„ค์ • + api_key = input('Input API KEY: ') + os.environ["OPENAI_API_KEY"] = api_key + client = OpenAI() + + #์งˆ๋ฌธ ์ž„๋ฒ ๋”ฉ + tqdm.pandas(desc='Embedding Questions') + df['Question Vector'] = df['Question'].progress_apply(embed) + + #๋‹ต๋ณ€ chunking + df['Answer']=df['Answer'].apply(chunk_string) + df = df.explode('Answer') + df = df.reset_index() + df = df.rename(columns={'index': 'Question Index'}) + + #๋‹ต๋ณ€ ์ž„๋ฒ ๋”ฉ + tqdm.pandas(desc='Embedding Answers') + df['Answer Vector'] = df['Answer'].progress_apply(embed) + + #์งˆ๋ฌธ-๋‹ต๋ณ€ ์Œ ์ž„๋ฒ ๋”ฉ + df['QA'] = df['Question'] + ' ' + df['Answer'] + tqdm.pandas(desc='Embedding Question-Answer Pairs') + df['QA Vector'] = df['QA'].progress_apply(embed) + + #์ตœ์ข… ๋ฒกํ„ฐ DB ์ €์žฅ + df.to_pickle('vectordb.df') \ No newline at end of file
Python
์š”๊ฑฐ๋„ ๋ฐ–์œผ๋กœ
@@ -0,0 +1,146 @@ +import pickle +import pandas as pd +import numpy as np +import re +from openai import OpenAI +import os +from tqdm import tqdm +import time + +def clean(answer): + ''' + ์ฃผ์–ด์ง„ ๋‹ต๋ณ€์„ ์ „์ฒ˜๋ฆฌํ•˜๋Š” ํ•จ์ˆ˜ + Args: + answer (str) : FAQ์˜ ๋‹ต๋ณ€ ๋ฐ์ดํ„ฐ + Returns: + answer (str) : ์ „์ฒ˜๋ฆฌ๋œ ๋‹ต๋ณ€ ๋ฐ์ดํ„ฐ + related (list) : ๊ด€๋ จ ๋„์›€๋ง ๋ชฉ๋ก + ''' + + #๋ถˆํ•„์š”ํ•œ ๋ณ„์  ์ œ๊ฑฐ + other = '\n\n\n์œ„ ๋„์›€๋ง์ด ๋„์›€์ด ๋˜์—ˆ๋‚˜์š”?\n\n\n๋ณ„์ 1์ \n\n๋ณ„์ 2์ \n\n๋ณ„์ 3์ \n\n๋ณ„์ 4์ \n\n๋ณ„์ 5์ \n\n\n\n์†Œ์ค‘ํ•œ ์˜๊ฒฌ์„ ๋‚จ๊ฒจ์ฃผ์‹œ๋ฉด ๋ณด์™„ํ•˜๋„๋ก ๋…ธ๋ ฅํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.\n\n๋ณด๋‚ด๊ธฐ\n\n\n\n' + answer = answer.replace(other, ' ') + answer = answer.replace('๋„์›€๋ง ๋‹ซ๊ธฐ', '') + + #๊ด€๋ จ ๋„์›€๋ง์€ ๋”ฐ๋กœ ์ €์žฅ + if '๊ด€๋ จ ๋„์›€๋ง/ํ‚ค์›Œ๋“œ' in answer: + a = answer.split('๊ด€๋ จ ๋„์›€๋ง/ํ‚ค์›Œ๋“œ') + answer = a[0] + related = a[1] + related=related.strip().split('\n') + + else: + related = np.nan + + #์ „์ฒ˜๋ฆฌ + answer = re.sub('\s{2,}', '\n', answer) #๋นˆ์นธ์ด ๊ธด ๊ฒฝ์šฐ ์ค„์ด๊ธฐ + answer = answer.replace('\xa0','\n') #\xa0๋ฅผ \n์œผ๋กœ ํ†ต์ผ + answer = answer.replace("\'",'') #๋ณผ๋“œ ํ‘œ์‹œ ์ œ๊ฑฐ + + return answer, related + +def get_category(text): + ''' + ์งˆ๋ฌธ์˜ ์นดํ…Œ๊ณ ๋ฆฌ๋ฅผ ์ถ”์ถœํ•˜๋Š” ํ•จ์ˆ˜ + Args: + text (str) : FAQ์˜ ์งˆ๋ฌธ ๋ฐ์ดํ„ฐ + Returns: + extracted_text (str) : ์งˆ๋ฌธ์ด ์†ํ•˜๋Š” ์นดํ…Œ๊ณ ๋ฆฌ (์—†๋‹ค๋ฉด np.nan ๋ฐ˜ํ™˜) + ''' + pattern = r'^\[(.*?)\]' #[]ํ‘œ์‹œ๋กœ ์‹œ์ž‘ํ•˜๋Š” ๊ฒฝ์šฐ ์นดํ…Œ๊ณ ๋ฆฌ๋กœ ์ธ์‹ + matches = re.findall(pattern, text) + if matches: + extracted_text = matches[0] #์ฒซ ์นดํ…Œ๊ณ ๋ฆฌ๋งŒ ๋ฐ˜ํ™˜ + return extracted_text + else: + return np.nan + + +def chunk_string(long_string, chunk_size=500): + ''' + ๊ธด ๋ฌธ์ž์—ด์„ ์งง๊ฒŒ ๋‚˜๋ˆ„๋Š” ํ•จ์ˆ˜ + Args: + long_string (str) : ๊ธด ๋ฌธ์ž์—ด + chunk_size (int) : ์›ํ•˜๋Š” ๋ฌธ์ž์—ด ๊ธธ์ด + Returns: + chunks (list) : ๋‚˜๋ˆ ์ง„ ์งง์€ ๋ฌธ์ž์—ด์˜ ๋ฆฌ์ŠคํŠธ + ''' + chunks = [] + current_chunk = '' + last_line = '' + previous_line = '' + + for line in long_string.split('\n'): + # ์ฃผ์–ด์ง„ chunk_size๋ฅผ ์ดˆ๊ณผํ•˜์ง€ ์•Š๋Š” ํ•œ ๊ณ„์†ํ•ด์„œ ํ˜„์žฌ chunk์— ์ƒˆ๋กœ์šด ์ค„ ์ถ”๊ฐ€ + if len(current_chunk) + len(line) <= chunk_size: + current_chunk += line + '\n' + last_line = line + '\n' + # ํ˜„์žฌ ์ฒญํฌ์— ์ค„์„ ์ถ”๊ฐ€ํ•˜๋ฉด chunk_size๋ฅผ ์ดˆ๊ณผํ•˜๊ฒŒ ๋˜๋ฉด ํ˜„์žฌ ์ฒญํฌ ์™„์„ฑ + else: + #์ด์ „ chunk์˜ ๋งˆ์ง€๋ง‰ ์ค„๋„ overlap๋˜๊ฒŒ ์•ž์— ํฌํ•จ + chunks.append((previous_line+current_chunk).rstrip('\n')) + previous_line = last_line + current_chunk = line + '\n' + + # ๋งˆ์ง€๋ง‰์œผ๋กœ ๋‚จ์€ chunk ์ฒ˜๋ฆฌ + if current_chunk: + chunks.append((previous_line+current_chunk).rstrip('\n')) + + return chunks + +def embed(text, wait_time=0.1): + ''' + ํ…์ŠคํŠธ๋ฅผ ์ž„๋ฒ ๋”ฉํ•˜๋Š” ํ•จ์ˆ˜ + Args: + text (str): ์ž„๋ฒ ๋”ฉํ•  ํ…์ŠคํŠธ + wait_time (float): ์š”์ฒญ ์‚ฌ์ด์˜ ๊ฐ„๊ฒฉ + Returns: + embedding (list): ํ…์ŠคํŠธ์˜ ์ž„๋ฒ ๋”ฉ + ''' + response = client.embeddings.create(input = text, model='text-embedding-3-small') + time.sleep(wait_time) + embedding = response.data[0].embedding + return embedding + +if __name__=="__main__": + + #FAQ ๋ฐ์ดํ„ฐ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ + with open('final_result.pkl', 'rb') as file: + loaded_data = pickle.load(file) + + df = pd.DataFrame(loaded_data.items()) + df.columns = ['Question','Answer'] + + #์งˆ๋ฌธ์˜ ์นดํ…Œ๊ณ ๋ฆฌ ์ •๋ณด ์ถ”์ถœ + df['Category'] = df['Question'].apply(get_category) + + #๋‹ต๋ณ€ ๋ฐ์ดํ„ฐ ์ „์ฒ˜๋ฆฌ ๋ฐ ๊ด€๋ จ ์งˆ๋ฌธ ์ •๋ณด ์ถ”์ถœ + df['Related'] = np.nan + df[['Answer', 'Related']] = df['Answer'].apply(clean).apply(pd.Series) + + #์ž„๋ฒ ๋”ฉ ์„ค์ • + api_key = input('Input API KEY: ') + os.environ["OPENAI_API_KEY"] = api_key + client = OpenAI() + + #์งˆ๋ฌธ ์ž„๋ฒ ๋”ฉ + tqdm.pandas(desc='Embedding Questions') + df['Question Vector'] = df['Question'].progress_apply(embed) + + #๋‹ต๋ณ€ chunking + df['Answer']=df['Answer'].apply(chunk_string) + df = df.explode('Answer') + df = df.reset_index() + df = df.rename(columns={'index': 'Question Index'}) + + #๋‹ต๋ณ€ ์ž„๋ฒ ๋”ฉ + tqdm.pandas(desc='Embedding Answers') + df['Answer Vector'] = df['Answer'].progress_apply(embed) + + #์งˆ๋ฌธ-๋‹ต๋ณ€ ์Œ ์ž„๋ฒ ๋”ฉ + df['QA'] = df['Question'] + ' ' + df['Answer'] + tqdm.pandas(desc='Embedding Question-Answer Pairs') + df['QA Vector'] = df['QA'].progress_apply(embed) + + #์ตœ์ข… ๋ฒกํ„ฐ DB ์ €์žฅ + df.to_pickle('vectordb.df') \ No newline at end of file
Python
๋Š์–ด์„œ ํ•˜๋Š”๊ฒŒ ๋‚˜์„ ๊ฒƒ ๊ฐ™๋‹ค
@@ -0,0 +1,135 @@ +import pandas as pd +import os +from openai import OpenAI +from sklearn.metrics.pairwise import cosine_similarity + + +def embed(text): + ''' + ํ…์ŠคํŠธ๋ฅผ ์ž„๋ฒ ๋”ฉํ•˜๋Š” ํ•จ์ˆ˜ + Args: + text (str) : ์ž„๋ฒ ๋”ฉํ•  ํ…์ŠคํŠธ + Returns: + embedding (list) : ํ…์ŠคํŠธ์˜ ์ž„๋ฒ ๋”ฉ + ''' + + response = client.embeddings.create(input = text, model='text-embedding-3-small') + embedding = response.data[0].embedding + return embedding + +def find_context(question,k,min_score): + ''' + ์œ ์ €์˜ ์งˆ๋ฌธ์„ ๋Œ€๋‹ตํ•˜๊ธฐ ์œ„ํ•œ ๋ฌธ๋งฅ์„ ์ฐพ๋Š” ํ•จ์ˆ˜ + Args: + question (str) : ์œ ์ €์˜ ์งˆ๋ฌธ + k (int) : ์ฐพ์„ ๋ฌธ๋งฅ์˜ ์ˆ˜ + min_score (float) : ์ตœ์†Œ ์œ ์‚ฌ๋„ ์ ์ˆ˜ + Returns: + context (str) : ์ƒ์œ„ k ๊ฐœ์˜ ๋ฌธ๋งฅ. ์ถฉ๋ถ„ํžˆ ์œ ์‚ฌํ•œ ๋ฌธ๋งฅ์ด ์—†๋‹ค๋ฉด '๊ด€๋ จ ์—†๋Š” ์งˆ๋ฌธ'์ž„์„ ๋ฐ˜ํ™˜ + ''' + + user_vector = embed(question) + + cosine_similarities = cosine_similarity(df['QA Vector'].tolist(), [user_vector]) + + #๊ฐ€์žฅ ๋†’์€ ์œ ์‚ฌ๋„๊ฐ€ ์ตœ์†Œ ์š”๊ตฌ ์ ์ˆ˜ ๋ฏธ๋งŒ์ด๋ผ๋ฉด, '๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ ์Šคํ† ์–ด์™€ ๊ด€๋ จ ์—†๋Š” ์งˆ๋ฌธ'์ž„์„ ๋ฐ˜ํ™˜ + if max(cosine_similarities) < min_score: + context = '\n This question is unrelated to ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด' + return context + + top_indices = cosine_similarities.flatten().argsort()[-k:][::-1] + + #์ƒ์œ„ k๊ฐœ์˜ ๋ฌธ๋งฅ์„ ํ•˜๋‚˜์˜ str๋กœ ํ•ฉ์น˜๊ธฐ + context = '' + for i in range(k): + context += f'\n Context {i+1} \n' + context += df['QA'].iloc[top_indices[i]] + + return context + +def generate_question(message,history): + ''' + ์ง€๊ธˆ๊นŒ์ง€์˜ ๋Œ€ํ™”์™€ ์ƒˆ๋กœ์šด ์œ ์ € ์งˆ๋ฌธ์„ ๋ฐ”ํƒ•์œผ๋กœ (๋ฌธ๋งฅ ๊ฒ€์ƒ‰์— ์‚ฌ์šฉํ• ) ๋…๋ฆฝ์ ์ธ ์งˆ๋ฌธ์„ ์ƒ์„ฑํ•˜๋Š” ํ•จ์ˆ˜ + Args: + message (str) : ์œ ์ €์˜ ์ƒˆ ์งˆ๋ฌธ + history (str) : ์ง€๊ธˆ๊นŒ์ง€์˜ ๋Œ€ํ™” ๋‚ด์šฉ (์œ ์ €์˜ ์งˆ๋ฌธ๊ณผ ์ฑ—๋ด‡์˜ ๋‹ต๋ณ€) + Returns: + question (str) : ์ƒ์„ฑ๋œ ๋…๋ฆฝ์ ์ธ ์งˆ๋ฌธ + ''' + + prompt = f'''Create a standalone question based on the chat history and the follow-up question. Return only the standalone question in Korean and no other explanation. + Chat History: {history} + Follow-up Question: {message} + ''' + + #GPT๋ฅผ ํ†ตํ•ด ์ƒˆ๋กœ์šด ์งˆ๋ฌธ ์ƒ์„ฑ + response = client.chat.completions.create( + model="gpt-3.5-turbo", + messages=[{"role": "user", "content": prompt}] + ) + + question = response.choices[0].message.content + + return question + +def chatbot(): + + #๋Œ€ํ™” ์‹œ์ž‘ + intro = "์ €๋Š” ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด ์ฑ—๋ด‡์ž…๋‹ˆ๋‹ค. ๊ถ๊ธˆํ•œ ์ ์„ ์งˆ๋ฌธํ•ด์ฃผ์„ธ์š”! (๋ฉˆ์ถ”๋ ค๋ฉด quit์„ ์ ์–ด์ฃผ์„ธ์š”)\n" + print('์ฑ—๋ด‡:', intro) + + #๋Œ€ํ™” ๋‚ด์—ญ ๊ธฐ๋ก ์‹œ์ž‘ (์‹ค์ œ ์œ ์ € ์งˆ๋ฌธ ๋ฐ ์ฑ—๋ด‡ ๋‹ต๋ณ€๋งŒ ์ €์žฅ) + history = 'assistant: ' + intro + + #GPT ๋‹ต๋ณ€ ์ง€์‹œ prompt + messages = [ + {"role": "system", "content": '''You are a helpful assistant that answers questions related to ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด. + For every Question, you will be given some Context that provides relevant information about ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด. + You are only allowed to answer based on the given Context. + If the Question is unrelated to ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด, answer with '์ €๋Š” ์Šค๋งˆํŠธ ์Šคํ† ์–ด FAQ๋ฅผ ์œ„ํ•œ ์ฑ—๋ด‡์ž…๋‹ˆ๋‹ค. ์Šค๋งˆํŠธ ์Šคํ† ์–ด์— ๋Œ€ํ•œ ์งˆ๋ฌธ์„ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.' + Always answer in Korean.'''}, + ] + + while True: + # ์งˆ๋ฌธ ์ž…๋ ฅ + message = input("์œ ์ €: ") + + # ์œ ์ €๊ฐ€ quit์„ ์ž…๋ ฅํ•˜๋ฉด ์ค‘๋‹จ + if message.lower() == "quit": + break + + # ์ง€๊ธˆ๊นŒ์ง€ ์งˆ๋ฌธ์ด ๋‘ ๊ฐœ ์ด์ƒ ์žˆ์—ˆ๋‹ค๋ฉด, ๋Œ€ํ™” ๋‚ด์—ญ์„ ๋ฐ”ํƒ•์œผ๋กœ ๋…๋ฆฝ์ ์ธ ์งˆ๋ฌธ์„ ๋จผ์ € ์ƒ์„ฑํ•œ ๋’ค ์ง„ํ–‰ + if len(messages)>2: + message = generate_question(message, history) + + #๋‹ต๋ณ€์— ํ™œ์šฉํ•  ๋ฌธ๋งฅ ๊ฒ€์ƒ‰ + context = find_context(message,3,0.4) + + #GPT์—๊ฒŒ ์งˆ๋ฌธ ๋ฐ ๋ฌธ๋งฅ ์ œ๊ณต + messages.append({"role": "user", "content": f"Question: {message} {context}"}) + history += f'user: {message} /n ' + + response = client.chat.completions.create( + model="gpt-3.5-turbo", + messages=messages + ) + + # ๋‹ต๋ณ€ ์ถœ๋ ฅ + chat_message = response.choices[0].message.content + print(f"\n์ฑ—๋ด‡: {chat_message}\n") + messages.append({"role": "assistant", "content": chat_message}) + history += f'assistant: {chat_message} /n ' + + +if __name__ == "__main__": + + #OpenAI API ์„ค์ • + api_key = input('Input API KEY: ') + os.environ["OPENAI_API_KEY"] = api_key + client = OpenAI() + + #Vector DB ๋ถˆ๋Ÿฌ์˜ค๊ธฐ + df = pd.read_pickle('chatbot/vectordb.df') + + #์ฑ—๋ด‡ ์‹คํ–‰ + chatbot()
Python
๋ฐ–์œผ๋กœ
@@ -0,0 +1,135 @@ +import pandas as pd +import os +from openai import OpenAI +from sklearn.metrics.pairwise import cosine_similarity + + +def embed(text): + ''' + ํ…์ŠคํŠธ๋ฅผ ์ž„๋ฒ ๋”ฉํ•˜๋Š” ํ•จ์ˆ˜ + Args: + text (str) : ์ž„๋ฒ ๋”ฉํ•  ํ…์ŠคํŠธ + Returns: + embedding (list) : ํ…์ŠคํŠธ์˜ ์ž„๋ฒ ๋”ฉ + ''' + + response = client.embeddings.create(input = text, model='text-embedding-3-small') + embedding = response.data[0].embedding + return embedding + +def find_context(question,k,min_score): + ''' + ์œ ์ €์˜ ์งˆ๋ฌธ์„ ๋Œ€๋‹ตํ•˜๊ธฐ ์œ„ํ•œ ๋ฌธ๋งฅ์„ ์ฐพ๋Š” ํ•จ์ˆ˜ + Args: + question (str) : ์œ ์ €์˜ ์งˆ๋ฌธ + k (int) : ์ฐพ์„ ๋ฌธ๋งฅ์˜ ์ˆ˜ + min_score (float) : ์ตœ์†Œ ์œ ์‚ฌ๋„ ์ ์ˆ˜ + Returns: + context (str) : ์ƒ์œ„ k ๊ฐœ์˜ ๋ฌธ๋งฅ. ์ถฉ๋ถ„ํžˆ ์œ ์‚ฌํ•œ ๋ฌธ๋งฅ์ด ์—†๋‹ค๋ฉด '๊ด€๋ จ ์—†๋Š” ์งˆ๋ฌธ'์ž„์„ ๋ฐ˜ํ™˜ + ''' + + user_vector = embed(question) + + cosine_similarities = cosine_similarity(df['QA Vector'].tolist(), [user_vector]) + + #๊ฐ€์žฅ ๋†’์€ ์œ ์‚ฌ๋„๊ฐ€ ์ตœ์†Œ ์š”๊ตฌ ์ ์ˆ˜ ๋ฏธ๋งŒ์ด๋ผ๋ฉด, '๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ ์Šคํ† ์–ด์™€ ๊ด€๋ จ ์—†๋Š” ์งˆ๋ฌธ'์ž„์„ ๋ฐ˜ํ™˜ + if max(cosine_similarities) < min_score: + context = '\n This question is unrelated to ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด' + return context + + top_indices = cosine_similarities.flatten().argsort()[-k:][::-1] + + #์ƒ์œ„ k๊ฐœ์˜ ๋ฌธ๋งฅ์„ ํ•˜๋‚˜์˜ str๋กœ ํ•ฉ์น˜๊ธฐ + context = '' + for i in range(k): + context += f'\n Context {i+1} \n' + context += df['QA'].iloc[top_indices[i]] + + return context + +def generate_question(message,history): + ''' + ์ง€๊ธˆ๊นŒ์ง€์˜ ๋Œ€ํ™”์™€ ์ƒˆ๋กœ์šด ์œ ์ € ์งˆ๋ฌธ์„ ๋ฐ”ํƒ•์œผ๋กœ (๋ฌธ๋งฅ ๊ฒ€์ƒ‰์— ์‚ฌ์šฉํ• ) ๋…๋ฆฝ์ ์ธ ์งˆ๋ฌธ์„ ์ƒ์„ฑํ•˜๋Š” ํ•จ์ˆ˜ + Args: + message (str) : ์œ ์ €์˜ ์ƒˆ ์งˆ๋ฌธ + history (str) : ์ง€๊ธˆ๊นŒ์ง€์˜ ๋Œ€ํ™” ๋‚ด์šฉ (์œ ์ €์˜ ์งˆ๋ฌธ๊ณผ ์ฑ—๋ด‡์˜ ๋‹ต๋ณ€) + Returns: + question (str) : ์ƒ์„ฑ๋œ ๋…๋ฆฝ์ ์ธ ์งˆ๋ฌธ + ''' + + prompt = f'''Create a standalone question based on the chat history and the follow-up question. Return only the standalone question in Korean and no other explanation. + Chat History: {history} + Follow-up Question: {message} + ''' + + #GPT๋ฅผ ํ†ตํ•ด ์ƒˆ๋กœ์šด ์งˆ๋ฌธ ์ƒ์„ฑ + response = client.chat.completions.create( + model="gpt-3.5-turbo", + messages=[{"role": "user", "content": prompt}] + ) + + question = response.choices[0].message.content + + return question + +def chatbot(): + + #๋Œ€ํ™” ์‹œ์ž‘ + intro = "์ €๋Š” ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด ์ฑ—๋ด‡์ž…๋‹ˆ๋‹ค. ๊ถ๊ธˆํ•œ ์ ์„ ์งˆ๋ฌธํ•ด์ฃผ์„ธ์š”! (๋ฉˆ์ถ”๋ ค๋ฉด quit์„ ์ ์–ด์ฃผ์„ธ์š”)\n" + print('์ฑ—๋ด‡:', intro) + + #๋Œ€ํ™” ๋‚ด์—ญ ๊ธฐ๋ก ์‹œ์ž‘ (์‹ค์ œ ์œ ์ € ์งˆ๋ฌธ ๋ฐ ์ฑ—๋ด‡ ๋‹ต๋ณ€๋งŒ ์ €์žฅ) + history = 'assistant: ' + intro + + #GPT ๋‹ต๋ณ€ ์ง€์‹œ prompt + messages = [ + {"role": "system", "content": '''You are a helpful assistant that answers questions related to ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด. + For every Question, you will be given some Context that provides relevant information about ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด. + You are only allowed to answer based on the given Context. + If the Question is unrelated to ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด, answer with '์ €๋Š” ์Šค๋งˆํŠธ ์Šคํ† ์–ด FAQ๋ฅผ ์œ„ํ•œ ์ฑ—๋ด‡์ž…๋‹ˆ๋‹ค. ์Šค๋งˆํŠธ ์Šคํ† ์–ด์— ๋Œ€ํ•œ ์งˆ๋ฌธ์„ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.' + Always answer in Korean.'''}, + ] + + while True: + # ์งˆ๋ฌธ ์ž…๋ ฅ + message = input("์œ ์ €: ") + + # ์œ ์ €๊ฐ€ quit์„ ์ž…๋ ฅํ•˜๋ฉด ์ค‘๋‹จ + if message.lower() == "quit": + break + + # ์ง€๊ธˆ๊นŒ์ง€ ์งˆ๋ฌธ์ด ๋‘ ๊ฐœ ์ด์ƒ ์žˆ์—ˆ๋‹ค๋ฉด, ๋Œ€ํ™” ๋‚ด์—ญ์„ ๋ฐ”ํƒ•์œผ๋กœ ๋…๋ฆฝ์ ์ธ ์งˆ๋ฌธ์„ ๋จผ์ € ์ƒ์„ฑํ•œ ๋’ค ์ง„ํ–‰ + if len(messages)>2: + message = generate_question(message, history) + + #๋‹ต๋ณ€์— ํ™œ์šฉํ•  ๋ฌธ๋งฅ ๊ฒ€์ƒ‰ + context = find_context(message,3,0.4) + + #GPT์—๊ฒŒ ์งˆ๋ฌธ ๋ฐ ๋ฌธ๋งฅ ์ œ๊ณต + messages.append({"role": "user", "content": f"Question: {message} {context}"}) + history += f'user: {message} /n ' + + response = client.chat.completions.create( + model="gpt-3.5-turbo", + messages=messages + ) + + # ๋‹ต๋ณ€ ์ถœ๋ ฅ + chat_message = response.choices[0].message.content + print(f"\n์ฑ—๋ด‡: {chat_message}\n") + messages.append({"role": "assistant", "content": chat_message}) + history += f'assistant: {chat_message} /n ' + + +if __name__ == "__main__": + + #OpenAI API ์„ค์ • + api_key = input('Input API KEY: ') + os.environ["OPENAI_API_KEY"] = api_key + client = OpenAI() + + #Vector DB ๋ถˆ๋Ÿฌ์˜ค๊ธฐ + df = pd.read_pickle('chatbot/vectordb.df') + + #์ฑ—๋ด‡ ์‹คํ–‰ + chatbot()
Python
ํ˜ธ์ถœํ• ๋•Œ ์ด๋ฆ„๊นŒ์ง€
@@ -0,0 +1,135 @@ +import pandas as pd +import os +from openai import OpenAI +from sklearn.metrics.pairwise import cosine_similarity + + +def embed(text): + ''' + ํ…์ŠคํŠธ๋ฅผ ์ž„๋ฒ ๋”ฉํ•˜๋Š” ํ•จ์ˆ˜ + Args: + text (str) : ์ž„๋ฒ ๋”ฉํ•  ํ…์ŠคํŠธ + Returns: + embedding (list) : ํ…์ŠคํŠธ์˜ ์ž„๋ฒ ๋”ฉ + ''' + + response = client.embeddings.create(input = text, model='text-embedding-3-small') + embedding = response.data[0].embedding + return embedding + +def find_context(question,k,min_score): + ''' + ์œ ์ €์˜ ์งˆ๋ฌธ์„ ๋Œ€๋‹ตํ•˜๊ธฐ ์œ„ํ•œ ๋ฌธ๋งฅ์„ ์ฐพ๋Š” ํ•จ์ˆ˜ + Args: + question (str) : ์œ ์ €์˜ ์งˆ๋ฌธ + k (int) : ์ฐพ์„ ๋ฌธ๋งฅ์˜ ์ˆ˜ + min_score (float) : ์ตœ์†Œ ์œ ์‚ฌ๋„ ์ ์ˆ˜ + Returns: + context (str) : ์ƒ์œ„ k ๊ฐœ์˜ ๋ฌธ๋งฅ. ์ถฉ๋ถ„ํžˆ ์œ ์‚ฌํ•œ ๋ฌธ๋งฅ์ด ์—†๋‹ค๋ฉด '๊ด€๋ จ ์—†๋Š” ์งˆ๋ฌธ'์ž„์„ ๋ฐ˜ํ™˜ + ''' + + user_vector = embed(question) + + cosine_similarities = cosine_similarity(df['QA Vector'].tolist(), [user_vector]) + + #๊ฐ€์žฅ ๋†’์€ ์œ ์‚ฌ๋„๊ฐ€ ์ตœ์†Œ ์š”๊ตฌ ์ ์ˆ˜ ๋ฏธ๋งŒ์ด๋ผ๋ฉด, '๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ ์Šคํ† ์–ด์™€ ๊ด€๋ จ ์—†๋Š” ์งˆ๋ฌธ'์ž„์„ ๋ฐ˜ํ™˜ + if max(cosine_similarities) < min_score: + context = '\n This question is unrelated to ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด' + return context + + top_indices = cosine_similarities.flatten().argsort()[-k:][::-1] + + #์ƒ์œ„ k๊ฐœ์˜ ๋ฌธ๋งฅ์„ ํ•˜๋‚˜์˜ str๋กœ ํ•ฉ์น˜๊ธฐ + context = '' + for i in range(k): + context += f'\n Context {i+1} \n' + context += df['QA'].iloc[top_indices[i]] + + return context + +def generate_question(message,history): + ''' + ์ง€๊ธˆ๊นŒ์ง€์˜ ๋Œ€ํ™”์™€ ์ƒˆ๋กœ์šด ์œ ์ € ์งˆ๋ฌธ์„ ๋ฐ”ํƒ•์œผ๋กœ (๋ฌธ๋งฅ ๊ฒ€์ƒ‰์— ์‚ฌ์šฉํ• ) ๋…๋ฆฝ์ ์ธ ์งˆ๋ฌธ์„ ์ƒ์„ฑํ•˜๋Š” ํ•จ์ˆ˜ + Args: + message (str) : ์œ ์ €์˜ ์ƒˆ ์งˆ๋ฌธ + history (str) : ์ง€๊ธˆ๊นŒ์ง€์˜ ๋Œ€ํ™” ๋‚ด์šฉ (์œ ์ €์˜ ์งˆ๋ฌธ๊ณผ ์ฑ—๋ด‡์˜ ๋‹ต๋ณ€) + Returns: + question (str) : ์ƒ์„ฑ๋œ ๋…๋ฆฝ์ ์ธ ์งˆ๋ฌธ + ''' + + prompt = f'''Create a standalone question based on the chat history and the follow-up question. Return only the standalone question in Korean and no other explanation. + Chat History: {history} + Follow-up Question: {message} + ''' + + #GPT๋ฅผ ํ†ตํ•ด ์ƒˆ๋กœ์šด ์งˆ๋ฌธ ์ƒ์„ฑ + response = client.chat.completions.create( + model="gpt-3.5-turbo", + messages=[{"role": "user", "content": prompt}] + ) + + question = response.choices[0].message.content + + return question + +def chatbot(): + + #๋Œ€ํ™” ์‹œ์ž‘ + intro = "์ €๋Š” ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด ์ฑ—๋ด‡์ž…๋‹ˆ๋‹ค. ๊ถ๊ธˆํ•œ ์ ์„ ์งˆ๋ฌธํ•ด์ฃผ์„ธ์š”! (๋ฉˆ์ถ”๋ ค๋ฉด quit์„ ์ ์–ด์ฃผ์„ธ์š”)\n" + print('์ฑ—๋ด‡:', intro) + + #๋Œ€ํ™” ๋‚ด์—ญ ๊ธฐ๋ก ์‹œ์ž‘ (์‹ค์ œ ์œ ์ € ์งˆ๋ฌธ ๋ฐ ์ฑ—๋ด‡ ๋‹ต๋ณ€๋งŒ ์ €์žฅ) + history = 'assistant: ' + intro + + #GPT ๋‹ต๋ณ€ ์ง€์‹œ prompt + messages = [ + {"role": "system", "content": '''You are a helpful assistant that answers questions related to ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด. + For every Question, you will be given some Context that provides relevant information about ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด. + You are only allowed to answer based on the given Context. + If the Question is unrelated to ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด, answer with '์ €๋Š” ์Šค๋งˆํŠธ ์Šคํ† ์–ด FAQ๋ฅผ ์œ„ํ•œ ์ฑ—๋ด‡์ž…๋‹ˆ๋‹ค. ์Šค๋งˆํŠธ ์Šคํ† ์–ด์— ๋Œ€ํ•œ ์งˆ๋ฌธ์„ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.' + Always answer in Korean.'''}, + ] + + while True: + # ์งˆ๋ฌธ ์ž…๋ ฅ + message = input("์œ ์ €: ") + + # ์œ ์ €๊ฐ€ quit์„ ์ž…๋ ฅํ•˜๋ฉด ์ค‘๋‹จ + if message.lower() == "quit": + break + + # ์ง€๊ธˆ๊นŒ์ง€ ์งˆ๋ฌธ์ด ๋‘ ๊ฐœ ์ด์ƒ ์žˆ์—ˆ๋‹ค๋ฉด, ๋Œ€ํ™” ๋‚ด์—ญ์„ ๋ฐ”ํƒ•์œผ๋กœ ๋…๋ฆฝ์ ์ธ ์งˆ๋ฌธ์„ ๋จผ์ € ์ƒ์„ฑํ•œ ๋’ค ์ง„ํ–‰ + if len(messages)>2: + message = generate_question(message, history) + + #๋‹ต๋ณ€์— ํ™œ์šฉํ•  ๋ฌธ๋งฅ ๊ฒ€์ƒ‰ + context = find_context(message,3,0.4) + + #GPT์—๊ฒŒ ์งˆ๋ฌธ ๋ฐ ๋ฌธ๋งฅ ์ œ๊ณต + messages.append({"role": "user", "content": f"Question: {message} {context}"}) + history += f'user: {message} /n ' + + response = client.chat.completions.create( + model="gpt-3.5-turbo", + messages=messages + ) + + # ๋‹ต๋ณ€ ์ถœ๋ ฅ + chat_message = response.choices[0].message.content + print(f"\n์ฑ—๋ด‡: {chat_message}\n") + messages.append({"role": "assistant", "content": chat_message}) + history += f'assistant: {chat_message} /n ' + + +if __name__ == "__main__": + + #OpenAI API ์„ค์ • + api_key = input('Input API KEY: ') + os.environ["OPENAI_API_KEY"] = api_key + client = OpenAI() + + #Vector DB ๋ถˆ๋Ÿฌ์˜ค๊ธฐ + df = pd.read_pickle('chatbot/vectordb.df') + + #์ฑ—๋ด‡ ์‹คํ–‰ + chatbot()
Python
๋„์–ด์“ฐ๊ธฐ
@@ -0,0 +1,135 @@ +import pandas as pd +import os +from openai import OpenAI +from sklearn.metrics.pairwise import cosine_similarity + + +def embed(text): + ''' + ํ…์ŠคํŠธ๋ฅผ ์ž„๋ฒ ๋”ฉํ•˜๋Š” ํ•จ์ˆ˜ + Args: + text (str) : ์ž„๋ฒ ๋”ฉํ•  ํ…์ŠคํŠธ + Returns: + embedding (list) : ํ…์ŠคํŠธ์˜ ์ž„๋ฒ ๋”ฉ + ''' + + response = client.embeddings.create(input = text, model='text-embedding-3-small') + embedding = response.data[0].embedding + return embedding + +def find_context(question,k,min_score): + ''' + ์œ ์ €์˜ ์งˆ๋ฌธ์„ ๋Œ€๋‹ตํ•˜๊ธฐ ์œ„ํ•œ ๋ฌธ๋งฅ์„ ์ฐพ๋Š” ํ•จ์ˆ˜ + Args: + question (str) : ์œ ์ €์˜ ์งˆ๋ฌธ + k (int) : ์ฐพ์„ ๋ฌธ๋งฅ์˜ ์ˆ˜ + min_score (float) : ์ตœ์†Œ ์œ ์‚ฌ๋„ ์ ์ˆ˜ + Returns: + context (str) : ์ƒ์œ„ k ๊ฐœ์˜ ๋ฌธ๋งฅ. ์ถฉ๋ถ„ํžˆ ์œ ์‚ฌํ•œ ๋ฌธ๋งฅ์ด ์—†๋‹ค๋ฉด '๊ด€๋ จ ์—†๋Š” ์งˆ๋ฌธ'์ž„์„ ๋ฐ˜ํ™˜ + ''' + + user_vector = embed(question) + + cosine_similarities = cosine_similarity(df['QA Vector'].tolist(), [user_vector]) + + #๊ฐ€์žฅ ๋†’์€ ์œ ์‚ฌ๋„๊ฐ€ ์ตœ์†Œ ์š”๊ตฌ ์ ์ˆ˜ ๋ฏธ๋งŒ์ด๋ผ๋ฉด, '๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ ์Šคํ† ์–ด์™€ ๊ด€๋ จ ์—†๋Š” ์งˆ๋ฌธ'์ž„์„ ๋ฐ˜ํ™˜ + if max(cosine_similarities) < min_score: + context = '\n This question is unrelated to ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด' + return context + + top_indices = cosine_similarities.flatten().argsort()[-k:][::-1] + + #์ƒ์œ„ k๊ฐœ์˜ ๋ฌธ๋งฅ์„ ํ•˜๋‚˜์˜ str๋กœ ํ•ฉ์น˜๊ธฐ + context = '' + for i in range(k): + context += f'\n Context {i+1} \n' + context += df['QA'].iloc[top_indices[i]] + + return context + +def generate_question(message,history): + ''' + ์ง€๊ธˆ๊นŒ์ง€์˜ ๋Œ€ํ™”์™€ ์ƒˆ๋กœ์šด ์œ ์ € ์งˆ๋ฌธ์„ ๋ฐ”ํƒ•์œผ๋กœ (๋ฌธ๋งฅ ๊ฒ€์ƒ‰์— ์‚ฌ์šฉํ• ) ๋…๋ฆฝ์ ์ธ ์งˆ๋ฌธ์„ ์ƒ์„ฑํ•˜๋Š” ํ•จ์ˆ˜ + Args: + message (str) : ์œ ์ €์˜ ์ƒˆ ์งˆ๋ฌธ + history (str) : ์ง€๊ธˆ๊นŒ์ง€์˜ ๋Œ€ํ™” ๋‚ด์šฉ (์œ ์ €์˜ ์งˆ๋ฌธ๊ณผ ์ฑ—๋ด‡์˜ ๋‹ต๋ณ€) + Returns: + question (str) : ์ƒ์„ฑ๋œ ๋…๋ฆฝ์ ์ธ ์งˆ๋ฌธ + ''' + + prompt = f'''Create a standalone question based on the chat history and the follow-up question. Return only the standalone question in Korean and no other explanation. + Chat History: {history} + Follow-up Question: {message} + ''' + + #GPT๋ฅผ ํ†ตํ•ด ์ƒˆ๋กœ์šด ์งˆ๋ฌธ ์ƒ์„ฑ + response = client.chat.completions.create( + model="gpt-3.5-turbo", + messages=[{"role": "user", "content": prompt}] + ) + + question = response.choices[0].message.content + + return question + +def chatbot(): + + #๋Œ€ํ™” ์‹œ์ž‘ + intro = "์ €๋Š” ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด ์ฑ—๋ด‡์ž…๋‹ˆ๋‹ค. ๊ถ๊ธˆํ•œ ์ ์„ ์งˆ๋ฌธํ•ด์ฃผ์„ธ์š”! (๋ฉˆ์ถ”๋ ค๋ฉด quit์„ ์ ์–ด์ฃผ์„ธ์š”)\n" + print('์ฑ—๋ด‡:', intro) + + #๋Œ€ํ™” ๋‚ด์—ญ ๊ธฐ๋ก ์‹œ์ž‘ (์‹ค์ œ ์œ ์ € ์งˆ๋ฌธ ๋ฐ ์ฑ—๋ด‡ ๋‹ต๋ณ€๋งŒ ์ €์žฅ) + history = 'assistant: ' + intro + + #GPT ๋‹ต๋ณ€ ์ง€์‹œ prompt + messages = [ + {"role": "system", "content": '''You are a helpful assistant that answers questions related to ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด. + For every Question, you will be given some Context that provides relevant information about ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด. + You are only allowed to answer based on the given Context. + If the Question is unrelated to ๋„ค์ด๋ฒ„ ์Šค๋งˆํŠธ์Šคํ† ์–ด, answer with '์ €๋Š” ์Šค๋งˆํŠธ ์Šคํ† ์–ด FAQ๋ฅผ ์œ„ํ•œ ์ฑ—๋ด‡์ž…๋‹ˆ๋‹ค. ์Šค๋งˆํŠธ ์Šคํ† ์–ด์— ๋Œ€ํ•œ ์งˆ๋ฌธ์„ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.' + Always answer in Korean.'''}, + ] + + while True: + # ์งˆ๋ฌธ ์ž…๋ ฅ + message = input("์œ ์ €: ") + + # ์œ ์ €๊ฐ€ quit์„ ์ž…๋ ฅํ•˜๋ฉด ์ค‘๋‹จ + if message.lower() == "quit": + break + + # ์ง€๊ธˆ๊นŒ์ง€ ์งˆ๋ฌธ์ด ๋‘ ๊ฐœ ์ด์ƒ ์žˆ์—ˆ๋‹ค๋ฉด, ๋Œ€ํ™” ๋‚ด์—ญ์„ ๋ฐ”ํƒ•์œผ๋กœ ๋…๋ฆฝ์ ์ธ ์งˆ๋ฌธ์„ ๋จผ์ € ์ƒ์„ฑํ•œ ๋’ค ์ง„ํ–‰ + if len(messages)>2: + message = generate_question(message, history) + + #๋‹ต๋ณ€์— ํ™œ์šฉํ•  ๋ฌธ๋งฅ ๊ฒ€์ƒ‰ + context = find_context(message,3,0.4) + + #GPT์—๊ฒŒ ์งˆ๋ฌธ ๋ฐ ๋ฌธ๋งฅ ์ œ๊ณต + messages.append({"role": "user", "content": f"Question: {message} {context}"}) + history += f'user: {message} /n ' + + response = client.chat.completions.create( + model="gpt-3.5-turbo", + messages=messages + ) + + # ๋‹ต๋ณ€ ์ถœ๋ ฅ + chat_message = response.choices[0].message.content + print(f"\n์ฑ—๋ด‡: {chat_message}\n") + messages.append({"role": "assistant", "content": chat_message}) + history += f'assistant: {chat_message} /n ' + + +if __name__ == "__main__": + + #OpenAI API ์„ค์ • + api_key = input('Input API KEY: ') + os.environ["OPENAI_API_KEY"] = api_key + client = OpenAI() + + #Vector DB ๋ถˆ๋Ÿฌ์˜ค๊ธฐ + df = pd.read_pickle('chatbot/vectordb.df') + + #์ฑ—๋ด‡ ์‹คํ–‰ + chatbot()
Python
ํžˆ์Šคํ† ๋ฆฌ๋ฅผ ๋‹ค๋ฅธ ์ž๋ฃŒํ˜• ์“ฐ๋Š”๊ฒŒ ๋‚˜์„๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค str๋ณด๋‹ค๋Š”
@@ -1,7 +1,20 @@ package christmas; +import christmas.domain.EventController; +import christmas.global.config.Dependency; +import christmas.global.view.output.OutputView; + +import static christmas.global.exception.CommonExceptionMessage.EXCEPTION_PREFIX; + public class Application { public static void main(String[] args) { // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + try { + EventController eventController = Dependency.eventController(); + eventController.play(); + } catch (Exception e) { + OutputView.println(EXCEPTION_PREFIX.get() + e.getMessage()); + throw e; + } } }
Java
์ž˜๋ชป๋œ ์ž…๋ ฅ์„ ๋ชจ๋‘ ์˜ˆ์™ธ ํด๋ž˜์Šค๋กœ ๋งŒ๋“ค์–ด์„œ Application ๋‚ด์—์„œ catch๋˜๋Š”๊ฒŒ ํฅ๋ฏธ๋กญ๊ณ  ํšจ์œจ์ ์ธ ๊ฒƒ ๊ฐ™๋„ค์š”! ์ž˜ ๋ฐฐ์šฐ๊ณ  ๊ฐ‘๋‹ˆ๋‹ค
@@ -0,0 +1,114 @@ +package christmas.domain.order; + +import christmas.domain.order.enums.food.Food; +import christmas.domain.order.enums.food.FoodCategory; + +import java.util.*; + +import static christmas.global.exception.OrderExceptionMessage.INVALID_ORDERS; +import static christmas.domain.order.enums.OrderNumberDefinition.MAX_ORDER_QUANTITY; + +public class Orders { + private static final String SEPARATOR = ","; + private static final String HYPHEN = "-"; + + private Map<Food, Integer> orderMap; + + private static final Orders instance = new Orders(); + + private Orders() {} + + public static Orders getInstance() { + return instance; + } + + + public void takeOrders(String orders) { + orderMap = separateByFood(orders); + } + + private Map<Food, Integer> separateByFood(String orders) { + Map<Food, Integer> foodMap = new EnumMap<>(Food.class); + List<String> orderList = Arrays.stream(orders.split(SEPARATOR)) + .toList(); + + orderList.stream() + .map(String::trim) + .forEach(o -> sortByFoods(foodMap, o)); + validateOrdersQuantityIsInRange(foodMap); + validateOrdersConsistOfDrinkOnly(foodMap); + return foodMap; + } + + + + public void sortByFoods(Map<Food, Integer> foodMap, String inputOrder) { + String[] order = inputOrder.split(HYPHEN); + Food food = Food.findByFood(order[0]); + int foodCount = Integer.parseInt(order[1]); + + validateOrderQuantityIsPositive(foodCount); + int count = foodMap.getOrDefault(food, 0); + validateDuplicateMenu(count); + count += foodCount; + foodMap.put(food, count); + } + + private void validateOrderQuantityIsPositive(int count) { + if(count < 1) { + throw new IllegalArgumentException(INVALID_ORDERS.get()); + } + } + + + private void validateDuplicateMenu(int count) { + if(count != 0) { + throw new IllegalArgumentException(INVALID_ORDERS.get()); + } + } + + private void validateOrdersQuantityIsInRange(Map<Food, Integer> foodMap) { + int totalQuantity = 0; + for (Integer value : foodMap.values()) { + totalQuantity += value; + } + if(totalQuantity > MAX_ORDER_QUANTITY.get()) { + throw new IllegalArgumentException(INVALID_ORDERS.get()); + } + } + + private void validateOrdersConsistOfDrinkOnly(Map<Food, Integer> foodMap) { + int notDrinkCount = 0; + for (Food food : foodMap.keySet()) { + notDrinkCount = countNotDrinkCategory(notDrinkCount, food); + } + if(notDrinkCount == 0) { + throw new IllegalArgumentException(INVALID_ORDERS.get()); + } + } + + private int countNotDrinkCategory(int notDrinkCount, Food food) { + if(!food.getFoodCategory().equals(FoodCategory.DRINK)) { + notDrinkCount += 1; + } + return notDrinkCount; + } + + public Map<FoodCategory, Integer> sortByFoodCategory() { + return Food.sortByFoodCategory(orderMap); + } + + public String generateOrderedMenu() { + return Food.generateOrderedMenu(orderMap); + + } + + public int calculateTotalPrice() { + return Food.calculateTotalPrice(orderMap); + } + + + public Map<Food, Integer> getOrderMap() { + return orderMap; + } +}
Java
์ค‘๋ณต๊ฒ€์ฆ์˜ ๋กœ์ง์„ ์˜จ์ „ํžˆ validateDuplicateMenu ๋ฉ”์„œ๋“œ๋กœ ๋„˜๊ธฐ๋Š” ๊ฒƒ๋„ ์ข‹์ง€ ์•Š์„๊นŒ ์ƒ๊ฐํ•ด๋ด…๋‹ˆ๋‹ค!
@@ -0,0 +1,32 @@ +package christmas.domain.sale.enums; + +import christmas.domain.calendar.enums.Week; +import christmas.domain.order.enums.food.FoodCategory; + +import java.util.Arrays; + +import static christmas.domain.calendar.enums.Week.WEEKDAY; +import static christmas.domain.calendar.enums.Week.WEEKEND; +import static christmas.domain.order.enums.food.FoodCategory.DESSERT; +import static christmas.domain.order.enums.food.FoodCategory.MAIN_DISH; + +public enum SaleTarget { + MAIN_FOR_SALE(WEEKEND, MAIN_DISH), + DESSERT_FOR_SALE(WEEKDAY, DESSERT); + + private final Week week; + private final FoodCategory foodCategory; + + SaleTarget(Week week, FoodCategory foodCategory) { + this.week = week; + this.foodCategory = foodCategory; + } + + public static FoodCategory findByDay(Week week) { + return Arrays.stream(SaleTarget.values()) + .filter(target -> target.week.equals(week)) + .findFirst() + .map(saleTarget -> saleTarget.foodCategory) + .get(); + } +}
Java
SaleTarget์ด๋ผ๋Š” enum์œผ๋กœ ํ‰์ผ๊ณผ ์ฃผ๋ง์˜ ํ• ์ธ์„ ์ฒ˜๋ฆฌํ•˜์‹  ๋ถ€๋ถ„์ด ๊ต‰์žฅํžˆ ํฅ๋ฏธ๋กœ์šด๋ฐ ์ผ๋ฐ˜ ํด๋ž˜์Šค๊ฐ€ ์•„๋‹ˆ๋ผ enum์œผ๋กœ ํ•˜์‹  ์ด์œ ๊ฐ€ ๋ฌด์—‡์ธ๊ฐ€์š”?
@@ -0,0 +1,114 @@ +package christmas.domain.order; + +import christmas.domain.order.enums.food.Food; +import christmas.domain.order.enums.food.FoodCategory; + +import java.util.*; + +import static christmas.global.exception.OrderExceptionMessage.INVALID_ORDERS; +import static christmas.domain.order.enums.OrderNumberDefinition.MAX_ORDER_QUANTITY; + +public class Orders { + private static final String SEPARATOR = ","; + private static final String HYPHEN = "-"; + + private Map<Food, Integer> orderMap; + + private static final Orders instance = new Orders(); + + private Orders() {} + + public static Orders getInstance() { + return instance; + } + + + public void takeOrders(String orders) { + orderMap = separateByFood(orders); + } + + private Map<Food, Integer> separateByFood(String orders) { + Map<Food, Integer> foodMap = new EnumMap<>(Food.class); + List<String> orderList = Arrays.stream(orders.split(SEPARATOR)) + .toList(); + + orderList.stream() + .map(String::trim) + .forEach(o -> sortByFoods(foodMap, o)); + validateOrdersQuantityIsInRange(foodMap); + validateOrdersConsistOfDrinkOnly(foodMap); + return foodMap; + } + + + + public void sortByFoods(Map<Food, Integer> foodMap, String inputOrder) { + String[] order = inputOrder.split(HYPHEN); + Food food = Food.findByFood(order[0]); + int foodCount = Integer.parseInt(order[1]); + + validateOrderQuantityIsPositive(foodCount); + int count = foodMap.getOrDefault(food, 0); + validateDuplicateMenu(count); + count += foodCount; + foodMap.put(food, count); + } + + private void validateOrderQuantityIsPositive(int count) { + if(count < 1) { + throw new IllegalArgumentException(INVALID_ORDERS.get()); + } + } + + + private void validateDuplicateMenu(int count) { + if(count != 0) { + throw new IllegalArgumentException(INVALID_ORDERS.get()); + } + } + + private void validateOrdersQuantityIsInRange(Map<Food, Integer> foodMap) { + int totalQuantity = 0; + for (Integer value : foodMap.values()) { + totalQuantity += value; + } + if(totalQuantity > MAX_ORDER_QUANTITY.get()) { + throw new IllegalArgumentException(INVALID_ORDERS.get()); + } + } + + private void validateOrdersConsistOfDrinkOnly(Map<Food, Integer> foodMap) { + int notDrinkCount = 0; + for (Food food : foodMap.keySet()) { + notDrinkCount = countNotDrinkCategory(notDrinkCount, food); + } + if(notDrinkCount == 0) { + throw new IllegalArgumentException(INVALID_ORDERS.get()); + } + } + + private int countNotDrinkCategory(int notDrinkCount, Food food) { + if(!food.getFoodCategory().equals(FoodCategory.DRINK)) { + notDrinkCount += 1; + } + return notDrinkCount; + } + + public Map<FoodCategory, Integer> sortByFoodCategory() { + return Food.sortByFoodCategory(orderMap); + } + + public String generateOrderedMenu() { + return Food.generateOrderedMenu(orderMap); + + } + + public int calculateTotalPrice() { + return Food.calculateTotalPrice(orderMap); + } + + + public Map<Food, Integer> getOrderMap() { + return orderMap; + } +}
Java
์ฃผ๋ฌธํ•œ ๋ฉ”๋‰ด ๋ชฉ๋ก์„ ์ƒ์„ฑํ•˜๊ธฐ ์œ„ํ•ด Food.generateOrderedMenu๋ฅผ ํ˜ธ์ถœํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค. ์ถœ๋ ฅ ํ˜•์‹์— ๋ณ€ํ™” ์ƒ๊ธฐ๋ฉด Food enum์ด ์˜ํ–ฅ์„ ๋ฐ›๋Š” ๋Œ€์‹  Orders๊ฐ€ ์˜ํ–ฅ์„ ๋ฐ›๋Š” ๊ฒƒ์ด ๋” ์ž์—ฐ์Šค๋Ÿฝ์ง€ ์•Š์„๊นŒ ํ•˜๋Š” ์ƒ๊ฐ์—์„œ ์งˆ๋ฌธ๋“œ๋ฆฝ๋‹ˆ๋‹ค!
@@ -0,0 +1,25 @@ +package christmas.domain.calendar.dto; + +import static christmas.global.exception.DateExceptionMessage.INVALID_DATE; + +public record DateDto(String date) { + + public DateDto { + validateDateIsNotNull(date); + validateDateIsNumber(date); + } + + private void validateDateIsNotNull(String date) { + if (date == null) { + throw new IllegalArgumentException(INVALID_DATE.get()); + } + } + + private void validateDateIsNumber(String date) { + try { + Integer.parseInt(date); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_DATE.get()); + } + } +}
Java
์ฝ”๋“œ ์ฝ๋‹ค๊ฐ€ record์— ๋Œ€ํ•ด ์ƒˆ๋กญ๊ฒŒ ์•Œ๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ •๋ง ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค ๐Ÿฅน
@@ -0,0 +1,94 @@ +package christmas.domain.sale; + +import christmas.domain.calendar.EventCalendar; +import christmas.domain.calendar.enums.Week; +import christmas.domain.order.Orders; +import christmas.domain.order.enums.food.FoodCategory; +import christmas.domain.sale.enums.BenefitCategory; +import christmas.domain.sale.enums.SaleTarget; + +import java.util.EnumMap; +import java.util.Map; + +import static christmas.domain.sale.enums.BenefitCategory.*; + +public class SaleDetails { + private static final int MINIMUM_TOTAL_PRICE = 10_000; + private static final int SALE_PER_MENU = 2_023; + private static final int STAR_DATE_SALE = 1_000; + + + private final Orders orders; + private final EventCalendar eventCalendar; + private final ChristmasDDaySale christmasDDaySale; + + + public SaleDetails(Orders orders, EventCalendar eventCalendar, ChristmasDDaySale christmasDDaySale) { + this.orders = orders; + this.eventCalendar = eventCalendar; + this.christmasDDaySale = christmasDDaySale; + } + + public int calculateTotalPrice() { + return orders.calculateTotalPrice(); + } + + public int calculateTotalSaleAmount() { + Map<BenefitCategory, Integer> benefitCategoryMap = categorizeSaleAmount(); + + if (!checkTotalPriceMoreThanTenThousand()) return 0; + + int totalSale = 0; + for (BenefitCategory benefitCategory : benefitCategoryMap.keySet()) { + int saleAmount = benefitCategoryMap.getOrDefault(benefitCategory, 0); + totalSale += saleAmount; + } + return totalSale; + } + + private boolean checkTotalPriceMoreThanTenThousand() { + int totalPrice = calculateTotalPrice(); + if (totalPrice < MINIMUM_TOTAL_PRICE) { + return false; + } + return true; + } + + public Map<BenefitCategory, Integer> categorizeSaleAmount() { + Map<BenefitCategory, Integer> benefitCategoryMap = new EnumMap<>(BenefitCategory.class); + + calculateWeekSalePrice(benefitCategoryMap); + calculateChristmasDdayEventSale(benefitCategoryMap); + calculateStarDateSalePrice(benefitCategoryMap); + + return benefitCategoryMap; + } + + private void calculateWeekSalePrice(Map<BenefitCategory, Integer> benefitCategoryMap) { + Map<FoodCategory, Integer> foodCategoryMap = orders.sortByFoodCategory(); + + Week week = eventCalendar.checkWeekOrWeekend(); + FoodCategory saleTarget = SaleTarget.findByDay(week); + + int saleCount = foodCategoryMap.getOrDefault(saleTarget, 0); + int saleAmount = saleCount * SALE_PER_MENU; + + benefitCategoryMap.put(week.getBenefitCategory(), saleAmount); + } + + private void calculateChristmasDdayEventSale(Map<BenefitCategory, Integer> benefitCategoryMap) { + int date = eventCalendar.getDate(); + int christmasDdaySaleAmount = christmasDDaySale.calculateSale(date); + + benefitCategoryMap.put(CHRISTMAS_DDAY_SALE, christmasDdaySaleAmount); + } + + private void calculateStarDateSalePrice(Map<BenefitCategory, Integer> benefitCategoryMap) { + int starDateSalePrice = 0; + boolean isStarDate = eventCalendar.checkStarDate(); + if(isStarDate) { + starDateSalePrice += STAR_DATE_SALE; + } + benefitCategoryMap.put(SPECIAL_SALE, starDateSalePrice); + } +}
Java
christmasDDaySale ์ฒ˜๋Ÿผ starDateSale๋กœ ๊ด€๋ฆฌํ•˜๋ฉด ๋” ์ผ๊ด€์„ฑ ์žˆ์–ด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค :>
@@ -0,0 +1,38 @@ +package christmas.domain.calendar.enums; + +import christmas.domain.sale.enums.BenefitCategory; + +import java.time.DayOfWeek; +import java.time.LocalDate; + +import static christmas.domain.sale.enums.BenefitCategory.WEEKDAY_SALE; +import static christmas.domain.sale.enums.BenefitCategory.WEEKEND_SALE; +import static christmas.domain.calendar.enums.YearMonthDateDefinition.*; + +public enum Week { + WEEKDAY(WEEKDAY_SALE), + WEEKEND(WEEKEND_SALE); + + + private final BenefitCategory benefitCategory; + + Week(BenefitCategory benefitCategory) { + this.benefitCategory = benefitCategory; + } + + public static Week determineWeek(int date) { + LocalDate localDate = LocalDate.of(YEAR.get(), MONTH.get(), date); + DayOfWeek dayOfWeek = localDate.getDayOfWeek(); + int week = dayOfWeek.getValue(); + + if (week >= WEEKEND_START.get() && week <= WEEKEND_END.get()) { + return WEEKEND; + } + return WEEKDAY; + } + + + public BenefitCategory getBenefitCategory() { + return benefitCategory; + } +}
Java
enum ํด๋ž˜์Šค์˜ ํ™œ์šฉ๋„๊ฐ€ ๊ต‰์žฅํžˆ ๋†’์œผ์‹  ๊ฒƒ ๊ฐ™์•„์š”! enum ์‚ฌ์šฉ๋ฒ• ๋งŽ์ด ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค ใ…Žใ…Ž
@@ -0,0 +1,49 @@ +package christmas.domain; + +import christmas.global.view.io.EventCalendarView; +import christmas.global.view.io.OrdersView; +import christmas.global.view.io.BenefitDetailsView; +import christmas.global.view.output.OutputView; + +import static christmas.global.view.message.OrderDynamicMessage.SHOW_EVENT; + +public class EventController { + private final EventCalendarView eventCalendarView; + private final OrdersView ordersView; + private final BenefitDetailsView benefitDetailsView; + + public EventController(EventCalendarView eventCalendarView, OrdersView ordersView, BenefitDetailsView benefitDetailsView) { + this.eventCalendarView = eventCalendarView; + this.ordersView = ordersView; + this.benefitDetailsView = benefitDetailsView; + } + + public void play() { + takeReservation(); + showOrderedMenus(); + showEventPreview(); + } + public void takeReservation() { + int date = inputVisitDate(); + + inputOrders(); + OutputView.println(SHOW_EVENT.get(date)); + } + + public int inputVisitDate() { + return eventCalendarView.inputVisitDate(); + } + + public void inputOrders() { + ordersView.inputOrders(); + } + + public void showOrderedMenus() { + ordersView.showOrderMenus(); + } + + public void showEventPreview() { + benefitDetailsView.showEventPreview(); + } + +}
Java
P5: ํŒจํ‚ค์ง•์ด ๋ฌ˜ํ•œ ๊ฒƒ์ด์–ด์š” ใ…‹ใ…‹ใ…‹ ์–ด๋–ค ๋ชฉ์ ์œผ๋กœ ํŒจํ‚ค์ง•์„ ํ•˜์…จ๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹น ๐Ÿค” (docs/README.md์— ์ถ”๊ฐ€ํ•ด์ฃผ์…”๋„ ์ข‹์•˜์„ ๊ฒƒ ๊ฐ™๊ณ ์š”?!)
@@ -0,0 +1,29 @@ +package christmas.global.view.io; + +import christmas.domain.calendar.EventCalendar; +import christmas.domain.calendar.dto.DateDto; +import christmas.global.view.input.InputView; +import christmas.global.view.output.OutputView; + +import static christmas.global.view.message.OrderStaticMessage.EXPECTED_VISIT_DATE; +import static christmas.global.view.message.OrderStaticMessage.START_MESSAGE; + +public class EventCalendarView implements InteractionRepeatable{ + private final EventCalendar eventCalendar; + + public EventCalendarView(EventCalendar eventCalendar) { + this.eventCalendar = eventCalendar; + } + + public int inputVisitDate() { + OutputView.println(START_MESSAGE.get()); + OutputView.println(EXPECTED_VISIT_DATE.get()); + + return supplyInteraction(() -> { + String input = InputView.input(); + DateDto dateDto = new DateDto(input); + + return eventCalendar.takeReservation(dateDto.date()); + }); + } +}
Java
P2: ์ด ๋ทฐ์˜ ์—ญํ• ์ด ์–ด๋–ค ๊ฑด์ง€ ๋ช…ํ™•ํžˆ ํ•ด์•ผํ•  ๊ฒƒ ๊ฐ™์•„์š”. ๐Ÿค” ์ง€๊ธˆ์€ ๋ทฐ ๊ณ„์ธต๋„ ์—ฌ๋Ÿฌ ๋‹จ๊ณ„๋กœ ์ถ”์ƒํ™” ๋˜์–ด์žˆ๊ณ , ์ปจํŠธ๋กค๋Ÿฌ์—์„œ ๋ฐ›...์„๊ฒƒ๋งŒ ๊ฐ™์€ DTO๋„ ๋„์ž…์ด ๋˜์–ด์žˆ๋Š”๋ฐ, ์ •์ž‘ ํ˜ธ์ถœํ•œ ์ชฝ์œผ๋กœ ๋Œ์•„๊ฐ€๋Š” ๊ฑด `int` ํƒ€์ž…์˜ ๊ฐ’ ํ•˜๋‚˜๋ž€ ๋ง์ด์ฃ . '์ „์†ก๋˜์ง€ ์•Š๋Š” ์ „์†ก๊ฐ์ฒด(DTO)๋Š” ์™œ ์กด์žฌํ•˜๋Š” ๊ฑฐ์ง€?....' ์ด๋Ÿฐ ์ƒ๊ฐ์ด ์ถฉ๋ถ„ํžˆ ๋“ค ์ˆ˜ ์žˆ๋Š” ์ฝ”๋“œ์ธ ๊ฒƒ ๊ฐ™๊ฑฐ๋“ ์š”. - ์™œ `InputView`์™€ `EventCalendarView`๊ฐ€ ๋‚˜๋‰˜์—ˆ๋Š”๊ฐ€ - ์™œ DateDto๋ฅผ ๋„์ž…ํ–ˆ๋Š”๊ฐ€ - ์™œ ๋ฐ˜ํ™˜๊ฐ’์„ `View`๊ฐ€ ์•„๋‹Œ `eventCalendar`๊ฐ€ ๋งŒ๋“ค์–ด ๋ฐ˜ํ™˜ํ•˜๋Š”๊ฐ€ - ์™œ ๊ทธ ๋ฐ˜ํ™˜ ํƒ€์ž…์ด `int`์ธ๊ฐ€ (์ถ”์ƒํ™”๋œ ๋ทฐ ๊ณ„์ธต์ด ๋‹จ์ˆœ ์›์‹œ ํƒ€์ž…์„ ๋ฐ˜ํ™˜ํ•˜๋Š”๊ฒŒ ์ ์ ˆํ•œ๊ฐ€?) - ์—ฌ๋Ÿฌ ํด๋ž˜์Šค๋กœ ๋‚˜๋‰˜์ง€ ์•Š์•˜์–ด๋„, InputView๋งŒ ์žˆ์–ด๋„ ์–ด์ƒ‰ํ•˜์ง€ ์•Š๊ฒŒ ๊ตฌํ˜„ ๊ฐ€๋Šฅํ•˜์ง€ ์•Š์„๊นŒ? ์š”๋Ÿฐ ๋ถ€๋ถ„๋“ค์„ ๊ณ ๋ฏผํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š” ๋‹ค๋ฅด๊ฒŒ ๋งํ•˜๋ฉด, ๊ณ„์ธต์ด ๋‚˜๋ˆ ์ง„ ๋ชฉ์ ์ด ๋“œ๋Ÿฌ๋‚˜๋ฉด ์ข‹๊ฒ ์–ด์š”. ๋ชฉ์ ์„ ๋“œ๋Ÿฌ๋‚ด๊ธฐ ์–ด๋ ต๋‹ค๋ฉด, ์•„์˜ˆ ๊ณ„์ธต์„ ๋‚˜๋ˆ„์ง€ ์•Š๋Š” ๊ฒƒ๋„ ์ข‹๊ณ ์š”. ์‹œ๊ฐ„ ๋‚  ๋•Œ ํ•œ๋ฒˆ ์ƒ๊ฐํ•ด๋ด ์ฃผ์„ธ์š”...! ๐Ÿ˜„
@@ -0,0 +1,49 @@ +package christmas.domain; + +import christmas.global.view.io.EventCalendarView; +import christmas.global.view.io.OrdersView; +import christmas.global.view.io.BenefitDetailsView; +import christmas.global.view.output.OutputView; + +import static christmas.global.view.message.OrderDynamicMessage.SHOW_EVENT; + +public class EventController { + private final EventCalendarView eventCalendarView; + private final OrdersView ordersView; + private final BenefitDetailsView benefitDetailsView; + + public EventController(EventCalendarView eventCalendarView, OrdersView ordersView, BenefitDetailsView benefitDetailsView) { + this.eventCalendarView = eventCalendarView; + this.ordersView = ordersView; + this.benefitDetailsView = benefitDetailsView; + } + + public void play() { + takeReservation(); + showOrderedMenus(); + showEventPreview(); + } + public void takeReservation() { + int date = inputVisitDate(); + + inputOrders(); + OutputView.println(SHOW_EVENT.get(date)); + } + + public int inputVisitDate() { + return eventCalendarView.inputVisitDate(); + } + + public void inputOrders() { + ordersView.inputOrders(); + } + + public void showOrderedMenus() { + ordersView.showOrderMenus(); + } + + public void showEventPreview() { + benefitDetailsView.showEventPreview(); + } + +}
Java
P4: 30๋ผ์ธ์˜ ์ฝ”๋“œ๋Š” ๋ทฐ ๊ฐ์ฒด๋กœ ์ด์ „ํ• ์ˆ˜ ์žˆ์„ ๊ฑฐ ๊ฐ™์•„์š”..! ์—‡ ๊ทผ๋ฐ ์ด๋ฒคํŠธ ์•ˆ๋‚ด ๋ฌธ๊ตฌ ์ถœ๋ ฅ ์ฝ”๋“œ๊ฐ€ `takeReservation()` ์•ˆ์—.... ๐Ÿ˜ญ
@@ -0,0 +1,114 @@ +package christmas.domain.order; + +import christmas.domain.order.enums.food.Food; +import christmas.domain.order.enums.food.FoodCategory; + +import java.util.*; + +import static christmas.global.exception.OrderExceptionMessage.INVALID_ORDERS; +import static christmas.domain.order.enums.OrderNumberDefinition.MAX_ORDER_QUANTITY; + +public class Orders { + private static final String SEPARATOR = ","; + private static final String HYPHEN = "-"; + + private Map<Food, Integer> orderMap; + + private static final Orders instance = new Orders(); + + private Orders() {} + + public static Orders getInstance() { + return instance; + } + + + public void takeOrders(String orders) { + orderMap = separateByFood(orders); + } + + private Map<Food, Integer> separateByFood(String orders) { + Map<Food, Integer> foodMap = new EnumMap<>(Food.class); + List<String> orderList = Arrays.stream(orders.split(SEPARATOR)) + .toList(); + + orderList.stream() + .map(String::trim) + .forEach(o -> sortByFoods(foodMap, o)); + validateOrdersQuantityIsInRange(foodMap); + validateOrdersConsistOfDrinkOnly(foodMap); + return foodMap; + } + + + + public void sortByFoods(Map<Food, Integer> foodMap, String inputOrder) { + String[] order = inputOrder.split(HYPHEN); + Food food = Food.findByFood(order[0]); + int foodCount = Integer.parseInt(order[1]); + + validateOrderQuantityIsPositive(foodCount); + int count = foodMap.getOrDefault(food, 0); + validateDuplicateMenu(count); + count += foodCount; + foodMap.put(food, count); + } + + private void validateOrderQuantityIsPositive(int count) { + if(count < 1) { + throw new IllegalArgumentException(INVALID_ORDERS.get()); + } + } + + + private void validateDuplicateMenu(int count) { + if(count != 0) { + throw new IllegalArgumentException(INVALID_ORDERS.get()); + } + } + + private void validateOrdersQuantityIsInRange(Map<Food, Integer> foodMap) { + int totalQuantity = 0; + for (Integer value : foodMap.values()) { + totalQuantity += value; + } + if(totalQuantity > MAX_ORDER_QUANTITY.get()) { + throw new IllegalArgumentException(INVALID_ORDERS.get()); + } + } + + private void validateOrdersConsistOfDrinkOnly(Map<Food, Integer> foodMap) { + int notDrinkCount = 0; + for (Food food : foodMap.keySet()) { + notDrinkCount = countNotDrinkCategory(notDrinkCount, food); + } + if(notDrinkCount == 0) { + throw new IllegalArgumentException(INVALID_ORDERS.get()); + } + } + + private int countNotDrinkCategory(int notDrinkCount, Food food) { + if(!food.getFoodCategory().equals(FoodCategory.DRINK)) { + notDrinkCount += 1; + } + return notDrinkCount; + } + + public Map<FoodCategory, Integer> sortByFoodCategory() { + return Food.sortByFoodCategory(orderMap); + } + + public String generateOrderedMenu() { + return Food.generateOrderedMenu(orderMap); + + } + + public int calculateTotalPrice() { + return Food.calculateTotalPrice(orderMap); + } + + + public Map<Food, Integer> getOrderMap() { + return orderMap; + } +}
Java
P5: orderMap์„ ๋ž˜ํ•‘ํ•œ ์ปฌ๋ ‰์…˜๋„ ํ˜น์‹œ ๊ณ ๋ คํ•ด๋ณด์‹œ๋ฉด ์–ด๋–จ๊นŒ์š”? ๐Ÿ˜‡
@@ -0,0 +1,92 @@ +package christmas.domain.order.enums.food; + +import java.util.*; + +import static christmas.global.exception.OrderExceptionMessage.INVALID_ORDERS; + +public enum Food { + ์–‘์†ก์ด์ˆ˜ํ”„(FoodCategory.APPETIZER,"์–‘์†ก์ด์ˆ˜ํ”„", 6000), + ํƒ€ํŒŒ์Šค(FoodCategory.APPETIZER, "ํƒ€ํŒŒ์Šค", 5500), + ์‹œ์ €์ƒ๋Ÿฌ๋“œ(FoodCategory.APPETIZER, "์‹œ์ €์ƒ๋Ÿฌ๋“œ", 8000), + + ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ(FoodCategory.MAIN_DISH, "ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 55000), + ๋ฐ”๋น„ํ๋ฆฝ(FoodCategory.MAIN_DISH, "๋ฐ”๋น„ํ๋ฆฝ", 54000), + ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€(FoodCategory.MAIN_DISH, "ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€",35000), + ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€(FoodCategory.MAIN_DISH, "ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€",25000), + + ์ดˆ์ฝ”์ผ€์ดํฌ(FoodCategory.DESSERT, "์ดˆ์ฝ”์ผ€์ดํฌ",15000), + ์•„์ด์Šคํฌ๋ฆผ(FoodCategory.DESSERT, "์•„์ด์Šคํฌ๋ฆผ",5000), + + ์ œ๋กœ์ฝœ๋ผ(FoodCategory.DRINK, "์ œ๋กœ์ฝœ๋ผ",3000), + ๋ ˆ๋“œ์™€์ธ(FoodCategory.DRINK, "๋ ˆ๋“œ์™€์ธ",60000), + ์ƒดํŽ˜์ธ(FoodCategory.DRINK, "์ƒดํŽ˜์ธ",25000); + + private final FoodCategory foodCategory; + private final String food; + private final int price; + + Food(FoodCategory foodCategory, String food, int price) { + this.foodCategory = foodCategory; + this.food = food; + this.price = price; + } + + + public static Food findByFood(String food) { + return Arrays.stream(Food.values()) + .filter(f -> f.food.equals(food)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException(INVALID_ORDERS.get())); + } + + public static Map<FoodCategory, Integer> sortByFoodCategory(Map<Food, Integer> foodMap) { + Map<FoodCategory, Integer> foodCategoryMap = new EnumMap<>(FoodCategory.class); + + for (Food food : foodMap.keySet()) { + FoodCategory foodCategory = food.foodCategory; + int count = foodCategoryMap.getOrDefault(foodCategory, 0); + count += foodMap.get(food); + + foodCategoryMap.put(foodCategory, count); + } + + return foodCategoryMap; + } + + public static int calculateTotalPrice(Map<Food, Integer> foodMap) { + int totalPrice = 0; + + for (Food food : foodMap.keySet()) { + int price = food.price; + int foodCount = foodMap.get(food); + totalPrice += price * foodCount; + } + + return totalPrice; + } + + public static String generateOrderedMenu(Map<Food, Integer> foodMap) { + StringBuilder menu = new StringBuilder(); + + for (Food food : foodMap.keySet()) { + String foodName = food.food; + int count = foodMap.get(food); + String order = String.format("%s %s๊ฐœ\n",foodName, count); + menu.append(order); + } + return menu.toString(); + + } + + public FoodCategory getFoodCategory() { + return foodCategory; + } + + public String getFood() { + return food; + } + + public int getPrice() { + return price; + } +}
Java
P3: `generateOrderedMenu()`์— ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ํ†ต์งธ๋กœ ๋งต์„ ๋„˜๊ฒจ์ฃผ์ง€ ์•Š๊ณ , ๋ฐ–์—์„œ ๋งต์„ ์ˆœํšŒํ•˜๋ฉด์„œ `Food`์—๋Š” `getOrderedFoodName(food:Food)` ๊ฐ™์€ ๋ฉ”์„œ๋“œ๋งŒ ํ˜ธ์ถœํ•ด์„œ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ›์•„๋ณด๊ฒŒ ํ•˜๋ฉด ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ˜‡ ๐Ÿ‘
@@ -0,0 +1,75 @@ +package christmas.global.view.io; + +import christmas.domain.badge.Enum.EventBadge; +import christmas.domain.sale.BenefitDetails; +import christmas.domain.sale.enums.Giveaway; +import christmas.global.view.output.OutputView; + +import static christmas.global.view.message.PriceMessage.getDiscountPriceMessage; +import static christmas.global.view.message.PriceMessage.getPriceMessage; +import static christmas.global.view.message.TitleMessage.*; + +public class BenefitDetailsView implements InteractionRepeatable{ + private final BenefitDetails benefitDetails; + + public BenefitDetailsView(BenefitDetails benefitDetails) { + this.benefitDetails = benefitDetails; + } + + public void showEventPreview() { + calculateTotalPrice(); + showResult(); + } + + public void calculateTotalPrice() { + benefitDetails.calculateTotalPrice(); + benefitDetails.calculateTotalSaleAmount(); + + int totalPrice = benefitDetails.getTotalPrice(); + + OutputView.println(BEFORE_SALE_PRICE.get()); + OutputView.println(getPriceMessage(totalPrice)); + } + + public void showResult() { + showFreeGift(); + showTotalBenefitDetails(); + int totalBenefitAmount = showTotalBenefitAmount(); + showFinalTotalPrice(); + showBadge(totalBenefitAmount); + } + + private void showFreeGift() { + Giveaway giveaway = benefitDetails.calculateFreeGiftPrice(); + + OutputView.println(GIVEAWAY_MENU.get()); + OutputView.println(giveaway.getProduct()); + OutputView.printNextLine(); + } + + private void showTotalBenefitDetails() { + OutputView.println(BENEFIT.get()); + String benefitDetails = this.benefitDetails.getTotalBenefitMessage(); + OutputView.println(benefitDetails); + } + + private int showTotalBenefitAmount() { + int totalBenefitAmount = benefitDetails.calculateTotalBenefitAmount(); + OutputView.println(TOTAL_BENEFIT_AMOUNT.get()); + OutputView.println(getDiscountPriceMessage(totalBenefitAmount)); + + return totalBenefitAmount; + } + + private void showFinalTotalPrice() { + OutputView.println(AFTER_SALE_PRICE.get()); + int totalFinalPrice = this.benefitDetails.calculateFinalPrice(); + OutputView.println(getPriceMessage(totalFinalPrice)); + } + + private void showBadge(int totalBenefitAmount) { + String badge = EventBadge.getBadge(totalBenefitAmount); + OutputView.println(EVENT_BADGE.get()); + OutputView.println(badge); + } +}
Java
P5: 25๋ผ์ธ์˜ `calculateTotalPrice()`๊ฐ€ -> `BenefitDetails#calculateTotalPrice()` -> `SaleDetails#calculateTotalPrice()` -> `Orders#calculateTotalPrice(foodMap)` -> `Food.calculateTotalPrice(foodMap)` ์ด๋Ÿฐ์‹์œผ๋กœ ํ˜ธ์ถœ์ด ๋˜๋Š”๋ฐ์š”. BenefitDetails์™€ SaleDetails๋Š” ์–ด๋–ค ๋ชฉ์ ์œผ๋กœ ๊ฑฐ์ณ๊ฐ€๋„๋ก ๊ตฌํ˜„ํ•˜์…จ๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,75 @@ +package christmas.global.view.io; + +import christmas.domain.badge.Enum.EventBadge; +import christmas.domain.sale.BenefitDetails; +import christmas.domain.sale.enums.Giveaway; +import christmas.global.view.output.OutputView; + +import static christmas.global.view.message.PriceMessage.getDiscountPriceMessage; +import static christmas.global.view.message.PriceMessage.getPriceMessage; +import static christmas.global.view.message.TitleMessage.*; + +public class BenefitDetailsView implements InteractionRepeatable{ + private final BenefitDetails benefitDetails; + + public BenefitDetailsView(BenefitDetails benefitDetails) { + this.benefitDetails = benefitDetails; + } + + public void showEventPreview() { + calculateTotalPrice(); + showResult(); + } + + public void calculateTotalPrice() { + benefitDetails.calculateTotalPrice(); + benefitDetails.calculateTotalSaleAmount(); + + int totalPrice = benefitDetails.getTotalPrice(); + + OutputView.println(BEFORE_SALE_PRICE.get()); + OutputView.println(getPriceMessage(totalPrice)); + } + + public void showResult() { + showFreeGift(); + showTotalBenefitDetails(); + int totalBenefitAmount = showTotalBenefitAmount(); + showFinalTotalPrice(); + showBadge(totalBenefitAmount); + } + + private void showFreeGift() { + Giveaway giveaway = benefitDetails.calculateFreeGiftPrice(); + + OutputView.println(GIVEAWAY_MENU.get()); + OutputView.println(giveaway.getProduct()); + OutputView.printNextLine(); + } + + private void showTotalBenefitDetails() { + OutputView.println(BENEFIT.get()); + String benefitDetails = this.benefitDetails.getTotalBenefitMessage(); + OutputView.println(benefitDetails); + } + + private int showTotalBenefitAmount() { + int totalBenefitAmount = benefitDetails.calculateTotalBenefitAmount(); + OutputView.println(TOTAL_BENEFIT_AMOUNT.get()); + OutputView.println(getDiscountPriceMessage(totalBenefitAmount)); + + return totalBenefitAmount; + } + + private void showFinalTotalPrice() { + OutputView.println(AFTER_SALE_PRICE.get()); + int totalFinalPrice = this.benefitDetails.calculateFinalPrice(); + OutputView.println(getPriceMessage(totalFinalPrice)); + } + + private void showBadge(int totalBenefitAmount) { + String badge = EventBadge.getBadge(totalBenefitAmount); + OutputView.println(EVENT_BADGE.get()); + OutputView.println(badge); + } +}
Java
P5: benefitDetails๋ฅผ ํ•„๋“œ๋กœ ๋‘๊ณ , ์ด๋ ‡๊ฒŒ showResult() ์•ˆ์—์„œ ์‚ฌ์šฉํ•˜๋‹ˆ ์ฝ”๋“œ๊ฐ€ ๊น”๋”ํ•ด์ง€๊ณ  ์ข‹๋„ค์š” ๐Ÿ˜‡ ๐Ÿ‘
@@ -0,0 +1,39 @@ +package christmas.domain.badge.Enum; + +import static christmas.global.exception.CommonExceptionMessage.UNEXPECTED_EXCEPTION; + +public enum EventBadge { + NONE("์—†์Œ", 0) + ,STAR("๋ณ„", 5_000) + ,TREE("ํŠธ๋ฆฌ", 10_000) + ,SANTA("์‚ฐํƒ€", 20_000) + ; + + private final String badge; + private final int benefitPrice; + + EventBadge(String badge, int benefitPrice) { + this.badge = badge; + this.benefitPrice = benefitPrice; + } + + public static String getBadge(int benefitPrice) { + validateBenefitPrice(benefitPrice); + if(benefitPrice >= SANTA.benefitPrice) { + return SANTA.badge; + } + if(benefitPrice >= TREE.benefitPrice) { + return TREE.badge; + } + if(benefitPrice >= STAR.benefitPrice) { + return STAR.badge; + } + return NONE.badge; + } + + public static void validateBenefitPrice(int benefitPrice) { + if (benefitPrice < 0) { + throw new IllegalStateException(UNEXPECTED_EXCEPTION.get()); + } + } +}
Java
P4: ์ •์ ๋ฉ”์„œ๋“œ์—์„œ ์œ ํšจ์„ฑ ๊ฒ€์ฆ์„ ํ•œ๋ฒˆ ๋” ๊ฑฐ์น˜๋Š” ๊ฒƒ ์ •๋ง ๊ผผ๊ผผํ•˜๊ณ  ์ข‹๋„ค์š” ๐Ÿ‘ P4: 22~31๋ผ์ธ์˜ ๋‹ค์ค‘ if ๋ฌธ์€ enum์˜ ๊ธฐ๋Šฅ์„ ํ™œ์šฉํ•ด์„œ ํ•ด๊ฒฐ ํ•  ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ์š”? ๐Ÿ˜‡
@@ -0,0 +1,38 @@ +package christmas.global.config; + +import christmas.domain.EventController; +import christmas.domain.calendar.EventCalendar; +import christmas.domain.order.Orders; +import christmas.domain.sale.BenefitDetails; +import christmas.domain.sale.ChristmasDDaySale; +import christmas.domain.sale.SaleDetails; +import christmas.global.view.io.BenefitDetailsView; +import christmas.global.view.io.EventCalendarView; +import christmas.global.view.io.OrdersView; + +public class Dependency { + public static EventController eventController() { + return new EventController(eventCalendarView(), ordersView(), benefitDetailsView()); + } + + public static BenefitDetailsView benefitDetailsView() { + return new BenefitDetailsView(benefitDetails()); + } + + public static OrdersView ordersView() { + return new OrdersView(Orders.getInstance()); + } + + public static EventCalendarView eventCalendarView() { + return new EventCalendarView(EventCalendar.getInstance()); + } + + public static BenefitDetails benefitDetails() { + return new BenefitDetails(saleDetails()); + } + + public static SaleDetails saleDetails() { + return new SaleDetails(Orders.getInstance(), EventCalendar.getInstance(), ChristmasDDaySale.getInstance()); + } + +}
Java
P3: ์—ฐ๊ด€๊ด€๊ณ„ ์ •๋ณด๊ฐ€ ์™„์ „ํžˆ ๋ถ„๋ฆฌ๋˜์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™์•„์š”..! ์ฝ”๋“œ ์•ˆ์—์„œ๋งŒ ๋ถ„๋ฆฌํ• ๊ฑฐ๋ผ๋ฉด Application์ชฝ์˜ ๋ฉ”์„œ๋“œ๋กœ๋งŒ ๋ถ„๋ฆฌํ•ด๋„ ์ถฉ๋ถ„ํ• ๊ฑฐ ๊ฐ™๊ณ , ์ง€๊ธˆ์ฒ˜๋Ÿผ Dependency ํŒŒ์ผ์„ ์•„์˜ˆ ๋”ฐ๋กœ ๋บ„ ๊ฑฐ๋ผ๋ฉด, Orders๊ฐ€ ์ž์‹ ์˜ ์ธ์Šคํ„ด์Šค๊ฐ€ ๋ฌด์—‡์ธ์ง€ ์ „ํ˜€ ์•Œ์ง€ ๋ชปํ•˜๊ฒŒ ๋ฐ–์—์„œ ์ฃผ์ž…ํ•˜๋„๋ก ๋งŒ๋“ค์–ด์ฃผ๋Š”๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -1,7 +1,16 @@ package christmas; +import christmas.config.Dependency; + public class Application { public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + + try { + EventPlanner eventPlanner = Dependency.eventPlannner(); + eventPlanner.run(); + } catch (Exception e) { + System.out.println(); + throw e; + } } }
Java
P5: ์š”๊ตฌ์‚ฌํ•ญ์ด ๋‹ค ๊ตฌํ˜„๋˜์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ˜ญ ...
@@ -1,7 +1,16 @@ package christmas; +import christmas.config.Dependency; + public class Application { public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + + try { + EventPlanner eventPlanner = Dependency.eventPlannner(); + eventPlanner.run(); + } catch (Exception e) { + System.out.println(); + throw e; + } } }
Java
P5: ์ง„์งœ ์‚ฌ์†Œํ•œ ๊ฑด๋ฐ์š”. ์ด ๊ณต๋ฐฑ ์ถœ๋ ฅ์˜ ์˜๋ฏธ...๋Š” ๋ญ˜๊นŒ์š”?... ๐Ÿค” ...
@@ -0,0 +1,42 @@ +package christmas.domain; + +import christmas.constant.Calendar; +import christmas.constant.FoodName; +import christmas.validator.DateValidator; +import christmas.view.InputView; +import christmas.view.OutputView; + +public class Date { + int date; + + public void saveDate(){ + String input = InputView.inputDate(); + this.date = DateValidator.validateDate(input); + } + + + + public int calculateChristmasEvent() { + if(25 < date){ + return 0; + }else if(1 <= date && date <= 25){ + return 900 + date * 100 ; + //christmas ์ด๋ฒคํŠธ ํ• ์ธ ๊ฐ’ ๊ตฌํ•˜๋Š” ์‹ + } + return 0; + } + + public boolean checkStarEvent(){ + return Calendar.isStarByDate(this.date); + } + + public String checkSaleSort(){ + return Calendar.getSaleSortByDate(this.date); + } + + public void printStartResultLine(){ + OutputView.printResultStart(date); + } + + +}
Java
P2: `Date`๊ฐ€ ๋‹จ์ˆœ ๊ฐ’ํƒ€์ž…์€ ์•„๋‹ˆ๊ณ  ์ž๊ธฐ๋งŒ์˜ ์—ญํ• ์„ ๊ฐ€์ง„ ๊ฐ์ฒด๋กœ ๋ณด์—ฌ์ง€๋Š”๋ฐ์š”! ๊ทธ๋ ‡๋‹ค๋ฉด ์—ฌ๊ธฐ์„œ ๋ทฐ๋ฅผ ํ˜ธ์ถœํ•˜๊ฒŒ ๋˜๋ฉด, ๋ทฐ์™€ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์ด ๊ฐ•ํ•˜๊ฒŒ ์—ฐ๊ด€๋œ๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์–ด์š”. ์šฐํ…Œ์ฝ” ์š”๊ตฌ์‚ฌํ•ญ์— ์žˆ์—ˆ๋“ฏ์ด ๋ทฐ๋ฅผ ๋ถ„๋ฆฌํ•ด์ฃผ๋ ค๋ฉด, ์Šนํ›ˆ๋‹˜๊ป˜์„œ ๊ตฌํ˜„ํ•ด๋†“์œผ์‹  ์ปจํŠธ๋กค๋Ÿฌ๋‚˜, `EventPlanner`๋‚˜, ์•„๋‹ˆ๋ฉด ์„œ๋น„์Šค ๋ณด๋‹ค ์•ž์„œ์žˆ๋Š” ์–ด๋–ค ์ œ3์˜ ๊ฐ์ฒด์—์„œ, ๋ทฐ๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ณ  ๊ฐ’๋งŒ `Date`์ชฝ์œผ๋กœ ๋„˜๊ฒจ์ฃผ๋ฉด ๋  ๊ฒƒ ๊ฐ™์•„์š”..!
@@ -0,0 +1,33 @@ +package christmas.validator; + +import jdk.jshell.spi.ExecutionControl.RunException; + +public class DateValidator { + + public static int validateDate(String input) { + validateInputType(input); + + try { + if (input == null) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + int date = Integer.parseInt(input); + + if (date < 1 || date > 31) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + + return date; + + } catch (NumberFormatException e) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ ํ˜•์‹์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } + + private static void validateInputType(String input) { + if (!(input instanceof String)) { + throw new IllegalArgumentException("[ERROR] ์œ ํšจํ•˜์ง€ ์•Š์€ ๋‚ ์งœ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."); + } + } +} \ No newline at end of file
Java
P5: ํƒ€์ž…๊นŒ์ง€ ๊ฒ€์ฆํ•˜์‹œ๋ ค๊ณ  ๋…ธ๋ ฅํ•˜์‹  ๋ถ€๋ถ„์ด ๋ณด์—ฌ์„œ ์ •๋ง ์ข‹์€ ๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ˜‡ ๐Ÿ‘ ๊ทธ๋Ÿฐ๋ฐ ์›์ฒœ input์˜ ํƒ€์ž…์€ ๋ฌด์กฐ๊ฑด String์ด ๋  ์ˆ˜ ๋ฐ–์— ์—†์–ด์š”! ์ผ๋ถ€๋Ÿฌ ์•ž์—์„œ ํƒ€์ž…์„ ๋ณ€ํ™˜ํ•˜์ง€ ์•Š๋Š” ์ด์ƒ์€์š”(๋งŒ์•ฝ ๊ทธ๋ ‡๋‹ค๋ฉด, ์˜๋„์— ๋”ฐ๋ผ ๋ฐ”๋€ ๊ฒƒ์ด๋‹ˆ ์˜ˆ์™ธ์ ์ธ ์ƒํ™ฉ์ด ์•„๋‹ˆ๊ฒ ์ฃ ..!) ๊ทธ๋ž˜์„œ ์ด ๋ถ€๋ถ„์˜ ์ฝ”๋“œ๋Š” ์ œ๊ฑฐํ•ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค..!
@@ -0,0 +1,60 @@ +package christmas.constant; + +import java.util.Arrays; +import java.util.stream.Stream; + +public enum FoodName { + MUSHROOM_SOUP("์–‘์†ก์ด์ˆ˜ํ”„",6000,"APPITIZER"), + TAPAS("ํƒ€ํŒŒ์Šค", 6000,"APPITIZER"), + CEASAR_SALAD("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 6000,"APPITIZER"), + T_BONE_STAKE("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 6000,"MAIN"), + BARBECUE_RIBS("๋ฐ”๋ฒ ํ๋ฆฝ", 6000,"MAIN"), + SEAFOOD_PASTA("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 6000,"MAIN"), + CHRISTMAS_PASTA("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 6000,"MAIN"), + CHOCOLATE_CAKE("์ดˆ์ฝ”์ผ€์ดํฌ", 6000,"DESSERT"), + ICE_CREAM("์•„์ด์Šคํฌ๋ฆผ", 6000,"DESSERT"), + ZERO_COLA("์ œ๋กœ์ฝœ๋ผ", 6000,"DRINK"), + RED_WINE("๋ ˆ๋“œ์™€์ธ", 6000,"DRINK"), + CHAMPAGNE("์ƒดํŽ˜์ธ", 6000,"DRINK"); + + private final String name; + private final int price; + private final String sort; + + FoodName(String name, int price, String sort) {this.name = name; this.price = price; + this.sort = sort; + } + + private String getName() { + return name; + } + + private int getPrice() { + return price; + } + + private String getSort() {return sort;} + + public static String[] getAllFoodNames() { + return Arrays.stream(FoodName.values()) + .map(FoodName::getName) + .toArray(String[]::new); + } + + public static int getPriceByName(String name) { + return Stream.of(values()) + .filter(foodName -> foodName.getName().equals(name)) + .findFirst() + .map(FoodName::getPrice) + .orElse(0); + } + + public static boolean isNameAndSortMatch(String name, String sort) { + return Arrays.stream(values()) + .filter(foodName -> foodName.getSort().equals(sort)) + .anyMatch(foodName -> foodName.getName().equals(name)); + } + + + +}
Java
P4: enum์œผ๋กœ ๋ฉ”๋‰ด๋ฅผ ๊ตฌํ˜„ํ•˜์‹  ๋ถ€๋ถ„ ์ •๋ง ์ข‹์€ ๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ‘ ๊ทธ๋Ÿฐ๋ฐ ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ์ •์ƒ๋™์ž‘ ํ•˜์ง€ ์•Š๋Š” ์ด์œ  ์ค‘ ์ผ๋ถ€๊ฐ€ ์—ฌ๊ธฐ ์ˆจ์–ด์žˆ์—ˆ๊ตฐ์š” ๊ฐ€๊ฒฉ์ด ์ „๋ถ€ 6000์›... ๐Ÿ˜ญ ํ•œ๊ฐ€์ง€๋งŒ ์˜๊ฒฌ์„ ๋‚ด๋ณด์ž๋ฉด, ์Œ์‹์˜ ์นดํ…Œ๊ณ ๋ฆฌ(`sort`)๋„ enum์œผ๋กœ ๊ด€๋ฆฌํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฑฐ ๊ฐ™์•„์š”!
@@ -0,0 +1,27 @@ +package christmas; + +import christmas.controller.EventController; + +public class EventPlanner { + private final EventController eventController; + + public EventPlanner(EventController eventController) { + this.eventController = eventController; + } + + public void run(){ + startRequestInfo(); + startOrderProgram(); + runOrderProgram(); + } + + private void startRequestInfo(){ + eventController.requestInfo(); + } + + private void startOrderProgram(){eventController.startPrintingResult();} + + private void runOrderProgram(){ + eventController.runDecemberEvent(); + } +}
Java
P5: ์งˆ๋ฌธ๋“œ๋ฆฝ๋‹ˆ๋‹ค..! EventPlanner์™€ EventController์˜ ์—ญํ• ์ด ๋‹ค์†Œ ์ค‘์ฒฉ๋˜๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ์š”(๋‹ค๋ฅด๊ฒŒ ๋งํ•˜๋ฉด, ํ•œ ๊ฐ์ฒด๋กœ ํ•  ์ˆ˜ ์žˆ๋Š” ์—ญํ• ์„ ๋‘˜๋กœ ์ชผ๊ฐ  ๊ฒƒ ๊ฐ™์€๋ฐ์š”) ๋‚˜๋ˆ„์‹  ์ด์œ ๊ฐ€ ์–ด๋–ค๊ฑด์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,68 @@ +package christmas.domain; + +import christmas.view.OutputView; +import java.util.Map; + +public class Price { + + int totalPriceBeforeDiscount; + EventPrices eventPrices; + + + public Price(int totalPrice) { + this.totalPriceBeforeDiscount = totalPrice; + this.eventPrices = new EventPrices(); + + } + + public void printTotalPrice(){ + + System.out.println(totalPriceBeforeDiscount + "์›"); + } + + public void printChampagneEvent(){ + if(120000 <= totalPriceBeforeDiscount){ + OutputView.printChampagne(); + eventPrices.addChampagneBenefit(25000); + } else if (totalPriceBeforeDiscount < 120000) { + OutputView.printNone(); + } + } + + public void saleChristmasEvent(int christmasEventDiscount){ + if (christmasEventDiscount != 0){ + eventPrices.addChristBenefit(christmasEventDiscount); + } + } + + public void saleStarEvent(boolean starBoolean){ + if(starBoolean){ + eventPrices.addStarBenefit(1000); + } + } + + public void saleWeekdayAndWeekendEvent(Map<String, Integer> weeklyEvent){ + if(weeklyEvent.values() != null){ + eventPrices.addWeekdayAndWeekendBenefit(weeklyEvent); + } + } + + public void printBenefitListAndPrice(){ + eventPrices.calculateBenefitList(); + } + + public void printBenefitTotalPrice(){ + eventPrices.printTotalprice(); + } + + public void printDiscountedTotalPrice(){ + eventPrices.printDiscountedPrice(totalPriceBeforeDiscount); + } + + public void checkDecemberBadge(){ + eventPrices.printDecemberBadge(); + } + + + +}
Java
P5: ์ด ๋ถ€๋ถ„๋„, ๋ทฐ๋Š” ๋ถ„๋ฆฌํ•˜๋Š”๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ๋‹ค๋ฅธ ๋ถ€๋ถ„์—๋„ ์ฝ”๋ฉ˜ํŠธ ๋‚จ๊ฒผ์ง€๋งŒ, ์ด ๊ณณ์€ ์•„์˜ˆ System.out์„ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์–ด์„œ ํ•œ ๋ฒˆ ๋” ๋‚จ๊ฒจ๋ณด์•„์š”..! ๐Ÿ˜‡ ๊ทธ๋ฆฌ๊ณ  ์ด ๋ถ€๋ถ„ ๊ธˆ์•ก ํฌ๋งทํŒ…๋„ ์ถ”๊ฐ€๋˜๋ฉด ๋” ์ข‹๊ฒ ๋„ค์šฉ..! (๋‹ค๋ฅธ ๋ถ€๋ถ„์€ ๋˜์–ด์žˆ๋Š”๋ฐ ์—ฌ๊ธฐ๋งŒ ๋น ์ ธ์žˆ์–ด์„œ์š”)
@@ -0,0 +1,68 @@ +package christmas.domain; + +import christmas.view.OutputView; +import java.util.Map; + +public class Price { + + int totalPriceBeforeDiscount; + EventPrices eventPrices; + + + public Price(int totalPrice) { + this.totalPriceBeforeDiscount = totalPrice; + this.eventPrices = new EventPrices(); + + } + + public void printTotalPrice(){ + + System.out.println(totalPriceBeforeDiscount + "์›"); + } + + public void printChampagneEvent(){ + if(120000 <= totalPriceBeforeDiscount){ + OutputView.printChampagne(); + eventPrices.addChampagneBenefit(25000); + } else if (totalPriceBeforeDiscount < 120000) { + OutputView.printNone(); + } + } + + public void saleChristmasEvent(int christmasEventDiscount){ + if (christmasEventDiscount != 0){ + eventPrices.addChristBenefit(christmasEventDiscount); + } + } + + public void saleStarEvent(boolean starBoolean){ + if(starBoolean){ + eventPrices.addStarBenefit(1000); + } + } + + public void saleWeekdayAndWeekendEvent(Map<String, Integer> weeklyEvent){ + if(weeklyEvent.values() != null){ + eventPrices.addWeekdayAndWeekendBenefit(weeklyEvent); + } + } + + public void printBenefitListAndPrice(){ + eventPrices.calculateBenefitList(); + } + + public void printBenefitTotalPrice(){ + eventPrices.printTotalprice(); + } + + public void printDiscountedTotalPrice(){ + eventPrices.printDiscountedPrice(totalPriceBeforeDiscount); + } + + public void checkDecemberBadge(){ + eventPrices.printDecemberBadge(); + } + + + +}
Java
P3: ์—ฌ๊ธฐ์˜ if-else๋กœ์ง์ด... ๋ญ”๊ฐ€ ์ด์ƒํ•œ๊ฒŒ ์ˆจ์–ด์žˆ๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ์š” ๐Ÿ•ต๏ธโ€โ™‚๏ธ (์‚ฌ์šฉํ•˜์ง€ ์•Š๊ธฐ๋กœ ํ–ˆ๋˜ if-else๊ฐ€ ์žˆ๋Š” ๊ฒƒ์„ ์ œ์™ธํ•˜๊ณ ์„œ๋ผ๋„...)
@@ -0,0 +1,90 @@ +package christmas.domain; + +import christmas.constant.BenefitList; +import christmas.view.OutputView; +import java.text.DecimalFormat; +import java.util.HashMap; +import java.util.Map; + +public class EventPrices { + Map<String,Integer> benefitList; + int totalPrice; + + public EventPrices() { + + this.benefitList = new HashMap<>(); + this.totalPrice = 0; + } + + public void addChampagneBenefit(int discountPrice){ + benefitList.put("GIFT",discountPrice); + } +// + public void addChristBenefit(int discountPrice){ + benefitList.put("CHRISTMAS", discountPrice); + } + + public void addStarBenefit(int discountPrice){ + benefitList.put("STAR",discountPrice); + } + + public void addWeekdayAndWeekendBenefit(Map<String, Integer> weeklyEvent){ + if(weeklyEvent.containsKey("DESSERT") && weeklyEvent.get("DESSERT") != 0){ + benefitList.put("DESSERT",weeklyEvent.get("DESSERT")); + } else if (weeklyEvent.containsKey("MAIN") && weeklyEvent.get("MAIN") != 0) { + benefitList.put("MAIN",weeklyEvent.get("MAIN")); + } + } + + public void calculateBenefitList(){ + if(benefitList.isEmpty()){ + OutputView.printNone(); + return; + + } else if (benefitList != null) { + + for (Map.Entry<String, Integer> entry : benefitList.entrySet()){ + addTotalPrice(entry.getValue()); + printBenefits(entry.getKey(),entry.getValue()); + } + } + } + + private void printBenefits(String benefitName, int discountPrice){ + DecimalFormat format = new DecimalFormat("-###,###์›"); + String benefitPrint = BenefitList.getEventNameByValue(benefitName); + benefitPrint += format.format(discountPrice); + System.out.println(benefitPrint); + } + + private void addTotalPrice(int price){ + this.totalPrice += price; + } + + public void printTotalprice(){ + DecimalFormat format = new DecimalFormat("-###,###์›"); + System.out.println(format.format(totalPrice)); + } + + public void printDiscountedPrice(int totalPriceBeforeDiscount){ + DecimalFormat format = new DecimalFormat("-###,###์›"); + int discountedPrice = totalPriceBeforeDiscount - totalPrice; + System.out.println(format.format(discountedPrice)); + } + + public void printDecemberBadge(){ + if(totalPrice < 5000){ + OutputView.printNone(); + return; + }else if(totalPrice < 10000) { + OutputView.printStarBadge(); + return; + }else if(totalPrice < 20000){ + OutputView.printTreeBadge(); + return; + }else if(20000 <= totalPrice){ + OutputView.printSantaBadge(); + return; + } + } +}
Java
P2: if-else ๋ฌธ์—๋Š” return์ด ํ•„์š”ํ•˜์ง€ ์•Š์•„์š”..! ๋”๊ตฐ๋‹ค๋‚˜ ๋ฐ˜ํ™˜ํƒ€์ž…์ด void์ธ ์ƒํ™ฉ์—์„œ๋Š”์š”! ๋ฌผ๋ก  ๋ช…์‹œ์ ์ธ return์„ ์จ์„œ ํ—ท๊ฐˆ๋ฆด๋งŒํ•œ ์ฝ”๋“œ๋‚˜ ์‚ฌ์ด๋“œ์ดํŽ™ํŠธ๋ฅผ ๋ง‰๋Š” ๊ฒฝ์šฐ๋„ ์žˆ๋Š”๋ฐ, ์ง€๊ธˆ์€ ํ•ด๋‹น๋˜์ง€ ์•Š๋Š” ์ฝ”๋“œ ๊ฐ™์•„์„œ ๋ง์”€๋“œ๋ ค๋ณด์•˜์Šต๋‹ˆ๋‹ค ๐Ÿ˜‡
@@ -0,0 +1,25 @@ +package christmas.controller; + +import christmas.service.EventService; + +public class EventController { + private final EventService eventService; + + public EventController(EventService eventRepository) { + this.eventService = eventRepository; + } + + public void requestInfo() { + eventService.saveInfo(); + } + + public void startPrintingResult(){ + eventService.printFristLineAndMenus(); + } + + public void runDecemberEvent() { + eventService.startCalculateAndPrint(); + } + + +}
Java
EventPlanner EventController EventService๋กœ ๊ตฌ์กฐ๋ฅผ ๊ฐ€์ ธ๊ฐ€์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค. ์–ด๋–ค ์ด์ ์ด ์žˆ๋‹ค ์ƒ๊ฐ์ด ๋“ค์–ด์„œ ์ด๋ ‡๊ฒŒ ๊ตฌ์กฐ๋ฅผ ๊ฐ€์ ธ๊ฐ€์‹ ๊ฑธ๊นŒ์š”? ๋˜ํ•œ ๋ทฐ๋กœ์ง์ด ๋„๋ฉ”์ธ๊ณผ ๊ฐ•ํ•˜๊ฒŒ ๊ฒฐํ•ฉ๋œ๋‹ค ์ƒ๊ฐํ•˜๋Š”๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹ค๊นŒ์š”?
@@ -0,0 +1,28 @@ +# ๊ธฐ๋Šฅ ์š”๊ตฌ ์‚ฌํ•ญ + +1. ์ƒํ’ˆ ๋ชฉ๋ก ์กฐํšŒ + + - [x] API๋ฅผ ํ†ตํ•ด ์ƒํ’ˆ ๋ชฉ๋ก์„ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋‹ค. + - [x] ๋งจ ์ฒ˜์Œ API ํ˜ธ์ถœ ์‹œ 20๊ฐœ์˜ ๋ชฉ๋ก์„ ๋ถˆ๋Ÿฌ์˜จ๋‹ค. + - [x] ์ด ํ›„ ์ถ”๊ฐ€ API ํ˜ธ์ถœ ์‹œ 4๊ฐœ์˜ ๋ชฉ๋ก์„ ๋ถˆ๋Ÿฌ์˜จ๋‹ค. + - [x] ๋ฌดํ•œ ์Šคํฌ๋กค์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. + +2. ์ƒํ’ˆ ์ •๋ ฌ ๋ฐ ํ•„ํ„ฐ๋ง + + - [x] ์ƒํ’ˆ ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„ ํ•„ํ„ฐ๋ง์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. + - [x] ์ƒํ’ˆ์„ ์ •๋ ฌ ํ•  ์ˆ˜ ์žˆ๋‹ค. (๋‚ฎ์€ ๊ฐ€๊ฒฉ ์ˆœ, ๋†’์€ ๊ฐ€๊ฒฉ ์ˆœ) + +3. ์ƒํ’ˆ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๋‹ด๊ธฐ + + - [x] ์‚ฌ์šฉ์ž๊ฐ€ ๋‹ด๊ธฐ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด, API๋ฅผ ํ†ตํ•ด ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ์ถ”๊ฐ€ ๋  ์ˆ˜ ์žˆ๋‹ค. + - [x] ์ด ๋•Œ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ๋‹ด๊ธด ์ƒํ’ˆ '์ข…๋ฅ˜'์˜ ๊ฐฏ์ˆ˜๋กœ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์•„์ด์ฝ˜์— ์ˆซ์ž๋ฅผ ํ‘œ์‹œํ•œ๋‹ค. + - [x] ์žฅ๋ฐ”๊ตฌ๋‹ˆ์—์„œ ๋นผ๊ธฐ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด, ์žฅ๋ฐ”๊ตฌ๋‹ˆ์—์„œ ํ•ด๋‹น ์•„์ดํ…œ์ด ์ œ๊ฑฐ๋˜๊ณ  ์ƒํ’ˆ ๋ชฉ๋ก ํŽ˜์ด์ง€์˜ ๋‹ด๊ธฐ ๋ฒ„ํŠผ์€ ํ™œ์„ฑํ™”๋œ๋‹ค. + +4. ํ…Œ์ŠคํŠธ + + - [x] API ์š”์ฒญ ์‹œ MSW ์„œ๋ฒ„๋ฅผ ๋ชจํ‚นํ•œ๋‹ค. + - [x] API ์š”์ฒญ ์ƒํƒœ์— ๋”ฐ๋ฅธ ๋ณ€ํ™”(๋กœ๋”ฉ์ƒํƒœ ํ‘œ์‹œ, ์—๋Ÿฌ๋ฉ”์„ธ์ง€ ํ‘œ์‹œ)๋ฅผ ๊ฒ€์ฆํ•œ๋‹ค. + +5. ์—๋Ÿฌ + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๋‹ด๊ธฐ/๋นผ๊ธฐ ์š”์ฒญ ์ค‘ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•œ ๊ฒฝ์šฐ, ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ์‚ฌ์šฉ์ž์—๊ฒŒ ์•Œ๋ ค์ฃผ๋Š” UI๋ฅผ ํ‘œ์‹œํ•œ๋‹ค. + - [x] ์ƒํ’ˆ๋ชฉ๋ก์„ ๋ถˆ๋Ÿฌ์˜ค๋Š” ์ค‘ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ๊ฒฝ์šฐ, ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ์‚ฌ์šฉ์ž์—๊ฒŒ ์•Œ๋ ค์ฃผ๋Š” UI๋ฅผ ํ‘œ์‹œํ•œ๋‹ค.
Unknown
์‚ฌ์†Œํ•˜์ง€๋งŒ, ์—ฌ๊ธฐ ๋งˆ์ง€๋ง‰ ๋ถ€๋ถ„ ์ฒดํฌ๋ฆฌ์ŠคํŠธ๊ฐ€ ๋น ์ ธ์žˆ๋„ค์š”! ์•„์ง ๊ตฌํ˜„ ๋ชปํ•œ ๋ถ€๋ถ„์ผ๊นŒ์š”?!
@@ -4,17 +4,21 @@ "version": "0.0.0", "type": "module", "scripts": { - "dev": "vite", + "dev": "vite --host", "build": "tsc && vite build", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "preview": "vite preview", "test": "vitest" }, "dependencies": { + "@tanstack/react-query": "^5.40.1", + "lv2-modal-component": "^0.0.20", "react": "^18.2.0", - "react-dom": "^18.2.0" + "react-dom": "^18.2.0", + "styled-components": "^6.1.11" }, "devDependencies": { + "@tanstack/eslint-plugin-query": "^5.35.6", "@testing-library/react": "^15.0.7", "@types/jest": "^29.5.12", "@types/node": "^20.12.11", @@ -24,9 +28,12 @@ "@typescript-eslint/parser": "^7.2.0", "@vitejs/plugin-react-swc": "^3.5.0", "eslint": "^8.57.0", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-prettier": "^5.1.3", "eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-react-refresh": "^0.4.6", "msw": "^2.3.0", + "prettier": "^3.2.5", "ts-node": "^10.9.2", "typescript": "^5.2.2", "vite": "^5.2.0",
Unknown
์ œ์ด๋“œ๋Š” styled-components๋ฅผ ์‚ฌ์šฉํ•œ ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”? ์ œ์ด๋“œ์˜ ์˜๊ฒฌ์ด ๊ถ๊ธˆํ•˜๋„ค์š”! ๐Ÿซ
@@ -0,0 +1,28 @@ +# ๊ธฐ๋Šฅ ์š”๊ตฌ ์‚ฌํ•ญ + +1. ์ƒํ’ˆ ๋ชฉ๋ก ์กฐํšŒ + + - [x] API๋ฅผ ํ†ตํ•ด ์ƒํ’ˆ ๋ชฉ๋ก์„ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋‹ค. + - [x] ๋งจ ์ฒ˜์Œ API ํ˜ธ์ถœ ์‹œ 20๊ฐœ์˜ ๋ชฉ๋ก์„ ๋ถˆ๋Ÿฌ์˜จ๋‹ค. + - [x] ์ด ํ›„ ์ถ”๊ฐ€ API ํ˜ธ์ถœ ์‹œ 4๊ฐœ์˜ ๋ชฉ๋ก์„ ๋ถˆ๋Ÿฌ์˜จ๋‹ค. + - [x] ๋ฌดํ•œ ์Šคํฌ๋กค์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. + +2. ์ƒํ’ˆ ์ •๋ ฌ ๋ฐ ํ•„ํ„ฐ๋ง + + - [x] ์ƒํ’ˆ ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„ ํ•„ํ„ฐ๋ง์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. + - [x] ์ƒํ’ˆ์„ ์ •๋ ฌ ํ•  ์ˆ˜ ์žˆ๋‹ค. (๋‚ฎ์€ ๊ฐ€๊ฒฉ ์ˆœ, ๋†’์€ ๊ฐ€๊ฒฉ ์ˆœ) + +3. ์ƒํ’ˆ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๋‹ด๊ธฐ + + - [x] ์‚ฌ์šฉ์ž๊ฐ€ ๋‹ด๊ธฐ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด, API๋ฅผ ํ†ตํ•ด ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ์ถ”๊ฐ€ ๋  ์ˆ˜ ์žˆ๋‹ค. + - [x] ์ด ๋•Œ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ๋‹ด๊ธด ์ƒํ’ˆ '์ข…๋ฅ˜'์˜ ๊ฐฏ์ˆ˜๋กœ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์•„์ด์ฝ˜์— ์ˆซ์ž๋ฅผ ํ‘œ์‹œํ•œ๋‹ค. + - [x] ์žฅ๋ฐ”๊ตฌ๋‹ˆ์—์„œ ๋นผ๊ธฐ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด, ์žฅ๋ฐ”๊ตฌ๋‹ˆ์—์„œ ํ•ด๋‹น ์•„์ดํ…œ์ด ์ œ๊ฑฐ๋˜๊ณ  ์ƒํ’ˆ ๋ชฉ๋ก ํŽ˜์ด์ง€์˜ ๋‹ด๊ธฐ ๋ฒ„ํŠผ์€ ํ™œ์„ฑํ™”๋œ๋‹ค. + +4. ํ…Œ์ŠคํŠธ + + - [x] API ์š”์ฒญ ์‹œ MSW ์„œ๋ฒ„๋ฅผ ๋ชจํ‚นํ•œ๋‹ค. + - [x] API ์š”์ฒญ ์ƒํƒœ์— ๋”ฐ๋ฅธ ๋ณ€ํ™”(๋กœ๋”ฉ์ƒํƒœ ํ‘œ์‹œ, ์—๋Ÿฌ๋ฉ”์„ธ์ง€ ํ‘œ์‹œ)๋ฅผ ๊ฒ€์ฆํ•œ๋‹ค. + +5. ์—๋Ÿฌ + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๋‹ด๊ธฐ/๋นผ๊ธฐ ์š”์ฒญ ์ค‘ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•œ ๊ฒฝ์šฐ, ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ์‚ฌ์šฉ์ž์—๊ฒŒ ์•Œ๋ ค์ฃผ๋Š” UI๋ฅผ ํ‘œ์‹œํ•œ๋‹ค. + - [x] ์ƒํ’ˆ๋ชฉ๋ก์„ ๋ถˆ๋Ÿฌ์˜ค๋Š” ์ค‘ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ๊ฒฝ์šฐ, ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ์‚ฌ์šฉ์ž์—๊ฒŒ ์•Œ๋ ค์ฃผ๋Š” UI๋ฅผ ํ‘œ์‹œํ•œ๋‹ค.
Unknown
++ README์— ์ž‘์„ฑํ•˜๊ธฐ๋ณด๋‹ค, REQUIREMENTS์— ์ž‘์„ฑํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”?
@@ -4,17 +4,21 @@ "version": "0.0.0", "type": "module", "scripts": { - "dev": "vite", + "dev": "vite --host", "build": "tsc && vite build", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "preview": "vite preview", "test": "vitest" }, "dependencies": { + "@tanstack/react-query": "^5.40.1", + "lv2-modal-component": "^0.0.20", "react": "^18.2.0", - "react-dom": "^18.2.0" + "react-dom": "^18.2.0", + "styled-components": "^6.1.11" }, "devDependencies": { + "@tanstack/eslint-plugin-query": "^5.35.6", "@testing-library/react": "^15.0.7", "@types/jest": "^29.5.12", "@types/node": "^20.12.11", @@ -24,9 +28,12 @@ "@typescript-eslint/parser": "^7.2.0", "@vitejs/plugin-react-swc": "^3.5.0", "eslint": "^8.57.0", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-prettier": "^5.1.3", "eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-react-refresh": "^0.4.6", "msw": "^2.3.0", + "prettier": "^3.2.5", "ts-node": "^10.9.2", "typescript": "^5.2.2", "vite": "^5.2.0",
Unknown
styled-component์™€ emotion ์˜ ์„ ํƒ ์‚ฌ์‹ค ์ €๋Š” ๋‘˜ ๋‹ค์‚ฌ์šฉํ•ด๋ณด๊ณ  emotion์„ ๋” ์„ ํ˜ธํ•˜์ง€๋งŒ, ์ด๋ฒˆ ๋ฏธ์…˜์—์„œ๋Š” ์ด ๋‘˜์˜ ์„ ํƒ์— ๋Œ€ํ•ด์„  ํฌ๋ฃจ์˜ ์˜๊ฒฌ์„ ๋”ฐ๋ž์Šต๋‹ˆ๋‹ค. emotion์„ ์ข€ ๋” ์„ ํ˜ธํ•˜๋Š” ์ด์œ : styled-component๋ฅผ ๋‹ค๋ฅธํŒŒ์ผ์— ๊ณ„์† ๋งŒ๋“ค์–ด ์ค„ ํ•„์š” ์—†์Œ ๋™์ ์ธ css๋ฅผ ์‚ฌ์šฉํ•˜๊ณ ์‹ถ์„ ๋•Œ ์ข€ ๋” ํŽธํ•˜๋‹ค๊ณ  ๋А๊ผˆ์Œ ์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,28 @@ +# ๊ธฐ๋Šฅ ์š”๊ตฌ ์‚ฌํ•ญ + +1. ์ƒํ’ˆ ๋ชฉ๋ก ์กฐํšŒ + + - [x] API๋ฅผ ํ†ตํ•ด ์ƒํ’ˆ ๋ชฉ๋ก์„ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋‹ค. + - [x] ๋งจ ์ฒ˜์Œ API ํ˜ธ์ถœ ์‹œ 20๊ฐœ์˜ ๋ชฉ๋ก์„ ๋ถˆ๋Ÿฌ์˜จ๋‹ค. + - [x] ์ด ํ›„ ์ถ”๊ฐ€ API ํ˜ธ์ถœ ์‹œ 4๊ฐœ์˜ ๋ชฉ๋ก์„ ๋ถˆ๋Ÿฌ์˜จ๋‹ค. + - [x] ๋ฌดํ•œ ์Šคํฌ๋กค์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. + +2. ์ƒํ’ˆ ์ •๋ ฌ ๋ฐ ํ•„ํ„ฐ๋ง + + - [x] ์ƒํ’ˆ ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„ ํ•„ํ„ฐ๋ง์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. + - [x] ์ƒํ’ˆ์„ ์ •๋ ฌ ํ•  ์ˆ˜ ์žˆ๋‹ค. (๋‚ฎ์€ ๊ฐ€๊ฒฉ ์ˆœ, ๋†’์€ ๊ฐ€๊ฒฉ ์ˆœ) + +3. ์ƒํ’ˆ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๋‹ด๊ธฐ + + - [x] ์‚ฌ์šฉ์ž๊ฐ€ ๋‹ด๊ธฐ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด, API๋ฅผ ํ†ตํ•ด ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ์ถ”๊ฐ€ ๋  ์ˆ˜ ์žˆ๋‹ค. + - [x] ์ด ๋•Œ ์žฅ๋ฐ”๊ตฌ๋‹ˆ์— ๋‹ด๊ธด ์ƒํ’ˆ '์ข…๋ฅ˜'์˜ ๊ฐฏ์ˆ˜๋กœ ์žฅ๋ฐ”๊ตฌ๋‹ˆ ์•„์ด์ฝ˜์— ์ˆซ์ž๋ฅผ ํ‘œ์‹œํ•œ๋‹ค. + - [x] ์žฅ๋ฐ”๊ตฌ๋‹ˆ์—์„œ ๋นผ๊ธฐ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด, ์žฅ๋ฐ”๊ตฌ๋‹ˆ์—์„œ ํ•ด๋‹น ์•„์ดํ…œ์ด ์ œ๊ฑฐ๋˜๊ณ  ์ƒํ’ˆ ๋ชฉ๋ก ํŽ˜์ด์ง€์˜ ๋‹ด๊ธฐ ๋ฒ„ํŠผ์€ ํ™œ์„ฑํ™”๋œ๋‹ค. + +4. ํ…Œ์ŠคํŠธ + + - [x] API ์š”์ฒญ ์‹œ MSW ์„œ๋ฒ„๋ฅผ ๋ชจํ‚นํ•œ๋‹ค. + - [x] API ์š”์ฒญ ์ƒํƒœ์— ๋”ฐ๋ฅธ ๋ณ€ํ™”(๋กœ๋”ฉ์ƒํƒœ ํ‘œ์‹œ, ์—๋Ÿฌ๋ฉ”์„ธ์ง€ ํ‘œ์‹œ)๋ฅผ ๊ฒ€์ฆํ•œ๋‹ค. + +5. ์—๋Ÿฌ + - [ ] ์žฅ๋ฐ”๊ตฌ๋‹ˆ ๋‹ด๊ธฐ/๋นผ๊ธฐ ์š”์ฒญ ์ค‘ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•œ ๊ฒฝ์šฐ, ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ์‚ฌ์šฉ์ž์—๊ฒŒ ์•Œ๋ ค์ฃผ๋Š” UI๋ฅผ ํ‘œ์‹œํ•œ๋‹ค. + - [x] ์ƒํ’ˆ๋ชฉ๋ก์„ ๋ถˆ๋Ÿฌ์˜ค๋Š” ์ค‘ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ๊ฒฝ์šฐ, ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ์‚ฌ์šฉ์ž์—๊ฒŒ ์•Œ๋ ค์ฃผ๋Š” UI๋ฅผ ํ‘œ์‹œํ•œ๋‹ค.
Unknown
์š”๊ตฌ์‚ฌํ•ญ์ด๋ผ์„œ REQUIREMENTS๋กœ ๋ช…๋ช…ํ–ˆ์Šต๋‹ˆ๋‹ค. README์—๋Š” ํ”„๋กœ์ ํŠธ ๋‚ด์šฉ์—๋Œ€ํ•œ ์†Œ๊ฐœ ๋“ฑ์„ ์“ฐ๋Š” ํŽธ์ธ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,86 @@ +package store.controller; + +import static store.util.Constant.ANSWER_NO; +import static store.util.InformationMessage.WELCOME_MESSAGE; +import static store.util.Validator.validateAnswer; +import static store.view.InputView.readForAdditionalPurchase; +import static store.view.OutputView.displayReceipt; + +import camp.nextstep.edu.missionutils.Console; +import java.io.IOException; +import store.service.PaymentService; +import store.domain.Inventory; +import store.domain.Order; +import store.domain.Promotions; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + + private final Inventory inventory; + private final Promotions promotions; + + public StoreController() { + inventory = prepareInventory(); + promotions = preparePromotions(); + } + + public void run() { + do { + OutputView.printMessage(WELCOME_MESSAGE); + OutputView.printInventory(inventory); + Order order = inputOrder(inventory); + PaymentService paymentService = new PaymentService(inventory, promotions, order); + displayReceipt(paymentService.getReceipt()); + } while (!inputAdditionalPurchase().equals(ANSWER_NO)); + closeConsole(); + } + + Inventory prepareInventory() { + Inventory inventory; + try { + inventory = new Inventory(); + return inventory; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + Promotions preparePromotions() { + Promotions promotions; + try { + promotions = new Promotions(); + return promotions; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + Order inputOrder(Inventory inventory) { + while (true) { + try { + Order order = new Order(InputView.readOrder()); + inventory.checkOrder(order); + return order; + } catch (IllegalArgumentException e) { + OutputView.printError(e.getMessage()); + } + } + } + + String inputAdditionalPurchase() { + while (true) { + try { + String answer = readForAdditionalPurchase(); + validateAnswer(answer); + return answer; + } catch (IllegalArgumentException e) { + OutputView.printError(e.getMessage()); + } + } + } + + void closeConsole() { + Console.close(); + } +}
Java
์ด๋ถ€๋ถ„ ๊น”๋”ํ•œ๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,86 @@ +package store.controller; + +import static store.util.Constant.ANSWER_NO; +import static store.util.InformationMessage.WELCOME_MESSAGE; +import static store.util.Validator.validateAnswer; +import static store.view.InputView.readForAdditionalPurchase; +import static store.view.OutputView.displayReceipt; + +import camp.nextstep.edu.missionutils.Console; +import java.io.IOException; +import store.service.PaymentService; +import store.domain.Inventory; +import store.domain.Order; +import store.domain.Promotions; +import store.view.InputView; +import store.view.OutputView; + +public class StoreController { + + private final Inventory inventory; + private final Promotions promotions; + + public StoreController() { + inventory = prepareInventory(); + promotions = preparePromotions(); + } + + public void run() { + do { + OutputView.printMessage(WELCOME_MESSAGE); + OutputView.printInventory(inventory); + Order order = inputOrder(inventory); + PaymentService paymentService = new PaymentService(inventory, promotions, order); + displayReceipt(paymentService.getReceipt()); + } while (!inputAdditionalPurchase().equals(ANSWER_NO)); + closeConsole(); + } + + Inventory prepareInventory() { + Inventory inventory; + try { + inventory = new Inventory(); + return inventory; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + Promotions preparePromotions() { + Promotions promotions; + try { + promotions = new Promotions(); + return promotions; + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + Order inputOrder(Inventory inventory) { + while (true) { + try { + Order order = new Order(InputView.readOrder()); + inventory.checkOrder(order); + return order; + } catch (IllegalArgumentException e) { + OutputView.printError(e.getMessage()); + } + } + } + + String inputAdditionalPurchase() { + while (true) { + try { + String answer = readForAdditionalPurchase(); + validateAnswer(answer); + return answer; + } catch (IllegalArgumentException e) { + OutputView.printError(e.getMessage()); + } + } + } + + void closeConsole() { + Console.close(); + } +}
Java
๋”ฐ๋กœ static์„ ์–ธ์„ ์•ˆํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,162 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.Constant.PRODUCTS_FILE_NAME; +import static store.util.ErrorMessage.INSUFFICIENT_INVENTORY_MESSAGE; +import static store.util.ErrorMessage.PRODUCT_NOT_FOUND_MESSAGE; +import static store.util.Parser.parseProductInfo; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public class Inventory { + + private static List<Product> products; + + public Inventory() throws IOException { + products = new ArrayList<>(); + loadFromFile(); + } + + private void loadFromFile() throws IOException { + BufferedReader br = new BufferedReader(new FileReader(PRODUCTS_FILE_NAME)); + String line; + br.readLine(); + while ((line = br.readLine()) != null) { + List<Object> productInfo = parseProductInfo(line); + addIfNoProductWithoutPromotion(productInfo); + products.add(createProduct(productInfo)); + } + br.close(); + } + + private void addIfNoProductWithoutPromotion(List<Object> productInfo) { + if (!products.isEmpty()) { + Product lastAddProduct = products.getLast(); + if (hasNoProductWithoutPromotion(lastAddProduct, productInfo)) { + products.add(createProductWithoutPromotion(lastAddProduct)); + } + } + } + + private boolean hasNoProductWithoutPromotion(Product lastAddProduct, List<Object> productInfo) { + String addProductName = (String) productInfo.getFirst(); + if (!lastAddProduct.getName().equals(addProductName)) { + return lastAddProduct.hasPromotion(); + } + return false; + } + + private Product createProductWithoutPromotion(Product lastAddProduct) { + return new Product(lastAddProduct.getName(), lastAddProduct.getPrice(), 0, BLANK); + } + + private Product createProduct(List<Object> productInfo) { + String name = (String) productInfo.getFirst(); + int price = (int) productInfo.get(1); + int quantity = (int) productInfo.get(2); + String promotion = (String) productInfo.getLast(); + return new Product(name, price, quantity, promotion); + } + + public void reducePromotionStock(String productName, int quantity) { + Product product = findProductWithPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithoutPromotion = findProductWithoutPromotion(productName); + reduceProduct(productWithoutPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + public void reduceNotPromotionStock(String productName, int quantity) { + Product product = findProductWithoutPromotion(productName); + int subtractValue = product.getQuantity() - quantity; + if (subtractValue < 0) { + product.reduceQuantityToZero(); + Product productWithPromotion = findProductWithPromotion(productName); + reduceProduct(productWithPromotion, Math.abs(subtractValue)); + return; + } + reduceProduct(product, quantity); + } + + private void reduceProduct(Product product, int quantity) { + for (int i = 0; i < quantity; i++) { + product.reduceQuantity(); + } + } + + public void checkOrder(Order order) { + Map<String, Integer> orderInfo = order.getOrders(); + orderInfo.forEach((name, quantity) -> { + checkProductInInventory(name); + checkPurchaseQuantity(name, quantity); + }); + } + + private void checkProductInInventory(String name) { + if (!hasProduct(name)) { + throw new IllegalArgumentException(PRODUCT_NOT_FOUND_MESSAGE); + } + } + + public boolean hasProduct(String name) { + for (Product product : products) { + if (name.equals(product.getName())) { + return true; + } + } + return false; + } + + private void checkPurchaseQuantity(String name, int quantity) { + if (isQuantityExceedingInventory(name, quantity)) { + throw new IllegalArgumentException(INSUFFICIENT_INVENTORY_MESSAGE); + } + } + + private boolean isQuantityExceedingInventory(String name, int quantity) { + int totalQuantity = findTotalQuantity(name); + return totalQuantity < quantity; + } + + private int findTotalQuantity(String name) { + int totalQuantity = 0; + for (Product product : products) { + if (name.equals(product.getName())) { + totalQuantity += product.getQuantity(); + } + } + return totalQuantity; + } + + public Product findProductWithPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && product.hasPromotion()) { + return product; + } + } + return null; + } + + public Product findProductWithoutPromotion(String name) { + for (Product product : products) { + if (name.equals(product.getName()) && !product.hasPromotion()) { + return product; + } + } + return null; + } + + public List<Product> getProducts() { + return Collections.unmodifiableList(products); + } +}
Java
ํŒŒ์ผ์ž…์ถœ๋ ฅ ๋ฐฉ๋ฒ•์ด ์—ฌ๋Ÿฌ๊ฐœ ์žˆ๋Š”๊ฑธ๋กœ ์•„๋Š”๋ฐ ํ•ด๋‹น ๋ฐฉ๋ฒ•์„ ํƒํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค