code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -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,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๋ณด๋‹ค๋Š”
@@ -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
ํŒŒ์ผ์ž…์ถœ๋ ฅ ๋ฐฉ๋ฒ•์ด ์—ฌ๋Ÿฌ๊ฐœ ์žˆ๋Š”๊ฑธ๋กœ ์•„๋Š”๋ฐ ํ•ด๋‹น ๋ฐฉ๋ฒ•์„ ํƒํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค
@@ -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
์ €๋Š” ์ด ๋ฉ”์„œ๋“œ์˜ ๊ธฐ๋Šฅ์ด ํ•ด๋‹น ํด๋ž˜์Šค์— ์žˆ๋Š”๊ฒƒ๋ณด๋‹ค Product์— ์žˆ๋Š”๊ฒŒ ์ ์ ˆํ•œ๊ฑฐ ๊ฐ™๋‹ค๊ณ  ์ƒ๊ฐ์ด ๋“œ๋Š”๋ฐ ํ•ด๋‹น ํด๋ž˜์Šค์— ๋„ฃ์œผ์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค
@@ -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
์ฒ˜์Œ๋ณด๋Š” ํ˜•์‹์ธ๋ฐ ์–ด๋–ค ๊ธฐ๋Šฅ์„ ํ•˜๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,83 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.ErrorMessage.INVALID_ORDER_MESSAGE; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class Order { + + private final Map<String, Integer> orders; + + public Order(String orderInput) { + this.orders = new LinkedHashMap<>(); + validate(orderInput); + putToOrders(orderInput); + } + + private void putToOrders(String orderInput) { + List<String> orderParts = List.of(orderInput.split(",")); + for (String orderPart : orderParts) { + parseOrder(orderPart); + } + } + + private void parseOrder(String orderPart) { + String orderPartNoBracket = removeSquareBracket(orderPart); + List<String> productNameAndQuantity = List.of(orderPartNoBracket.split("-")); + String name = productNameAndQuantity.getFirst(); + String quantityPart = productNameAndQuantity.getLast(); + int quantity = Integer.parseInt(quantityPart); + orders.put(name, quantity); + } + + private void validate(String orderInput) { + List<String> splitComma = List.of(orderInput.split(",")); + for (String productNameAndQuantity : splitComma) { + checkSquareBracket(productNameAndQuantity); + checkSeparatedTwoPart(productNameAndQuantity); + } + } + + private void checkSquareBracket(String order) { + if (!isStartAndEndWithSquareBracket(order)) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private void checkSeparatedTwoPart(String order) { + String orderNoBracket = removeSquareBracket(order); + List<String> splitHyphen = List.of(orderNoBracket.split("-")); + if (splitHyphen.size() != 2) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + String quantity = splitHyphen.getLast(); + checkQuantityPart(quantity); + } + + private void checkQuantityPart(String quantityPart) { + try { + int quantity = Integer.parseInt(quantityPart); + if (quantity <= 0) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private boolean isStartAndEndWithSquareBracket(String order) { + return order.startsWith("[") && order.endsWith("]"); + } + + private String removeSquareBracket(String orderPart) { + return orderPart.replaceAll("[\\[\\]]", BLANK); + } + + public Map<String, Integer> getOrders() { + return Collections.unmodifiableMap(orders); + } +}
Java
order์— ๋„ฃ๋Š” ๋ถ€๋ถ„์ด parserOrder์— ์žˆ์–ด์„œ ์ด ๋ถ€๋ถ„์—์„œ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์ „๋‹ฌํ•ด์ฃผ๊ณ  putToOrders์—์„œ ์ง์ ‘ orders์— ๋„ฃ๋Š” ๋ฐฉ์‹์œผ๋กœ ๋ณ€๊ฒฝํ•˜๋ฉด ๋ฉ”์„œ๋“œ ์ด๋ฆ„์— ์ ํ•ฉํ•œ ๊ธฐ๋Šฅ์„ ํ• ๊ฑฐ๊ฐ™๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์–ด์„œ ์ž‘์„ฑํ•ด๋ด…๋‹ˆ๋‹ค.
@@ -0,0 +1,83 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.ErrorMessage.INVALID_ORDER_MESSAGE; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class Order { + + private final Map<String, Integer> orders; + + public Order(String orderInput) { + this.orders = new LinkedHashMap<>(); + validate(orderInput); + putToOrders(orderInput); + } + + private void putToOrders(String orderInput) { + List<String> orderParts = List.of(orderInput.split(",")); + for (String orderPart : orderParts) { + parseOrder(orderPart); + } + } + + private void parseOrder(String orderPart) { + String orderPartNoBracket = removeSquareBracket(orderPart); + List<String> productNameAndQuantity = List.of(orderPartNoBracket.split("-")); + String name = productNameAndQuantity.getFirst(); + String quantityPart = productNameAndQuantity.getLast(); + int quantity = Integer.parseInt(quantityPart); + orders.put(name, quantity); + } + + private void validate(String orderInput) { + List<String> splitComma = List.of(orderInput.split(",")); + for (String productNameAndQuantity : splitComma) { + checkSquareBracket(productNameAndQuantity); + checkSeparatedTwoPart(productNameAndQuantity); + } + } + + private void checkSquareBracket(String order) { + if (!isStartAndEndWithSquareBracket(order)) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private void checkSeparatedTwoPart(String order) { + String orderNoBracket = removeSquareBracket(order); + List<String> splitHyphen = List.of(orderNoBracket.split("-")); + if (splitHyphen.size() != 2) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + String quantity = splitHyphen.getLast(); + checkQuantityPart(quantity); + } + + private void checkQuantityPart(String quantityPart) { + try { + int quantity = Integer.parseInt(quantityPart); + if (quantity <= 0) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private boolean isStartAndEndWithSquareBracket(String order) { + return order.startsWith("[") && order.endsWith("]"); + } + + private String removeSquareBracket(String orderPart) { + return orderPart.replaceAll("[\\[\\]]", BLANK); + } + + public Map<String, Integer> getOrders() { + return Collections.unmodifiableMap(orders); + } +}
Java
splitํ•˜๋Š” ๋ถ€๋ถ„์˜ regex๋„ ์ƒ์ˆ˜ํ™”ํ•˜๋ฉด ์ข‹์„๊ฑฐ๊ฐ™๋‹ค๊ณ  ์ƒ๊ฐ๋“ญ๋‹ˆ๋‹ค
@@ -0,0 +1,120 @@ +package store.domain; + +import static store.util.Constant.MEMBERSHIP_DISCOUNT_LIMIT; +import static store.util.Constant.MEMBERSHIP_DISCOUNT_RATE; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +public class Receipt { + + private final Map<Product, Integer> purchaseHistory; + private final Map<Product, Integer> giveAwayHistory; + private int membershipApplicableAmount; + + public Receipt() { + purchaseHistory = new LinkedHashMap<>(); + giveAwayHistory = new LinkedHashMap<>(); + } + + public void addPurchaseHistory(Product product, int quantity) { + purchaseHistory.put(product, quantity); + } + + public void addGiveAwayHistory(Product product, Promotion promotion, int quantity) { + int bundle = promotion.getBuy() + promotion.getGet(); + int giveAwayQuantity = Math.min(quantity, product.getQuantity()) / bundle; + if (giveAwayQuantity != 0) { + giveAwayHistory.put(product, giveAwayQuantity); + } + } + + public void applyMembershipDiscount(Promotions promotions) { + for (Map.Entry<Product, Integer> purchaseInfo : purchaseHistory.entrySet()) { + Product product = purchaseInfo.getKey(); + int quantity = purchaseInfo.getValue(); + if (!hasGiveAway(product.getName())) { + membershipApplicableAmount += product.getPrice() * quantity; + continue; + } + int promotionApplicableQuantity = calculatePromotionApplicableQuantity(product, promotions); + membershipApplicableAmount += product.getPrice() * (quantity - promotionApplicableQuantity); + } + } + + private int calculatePromotionApplicableQuantity(Product product, Promotions promotions) { + int giveAwayQuantity = findGiveAwayQuantity(product.getName()); + Promotion promotion = promotions.findPromotion(product.getPromotionName()); + int bundle = promotion.calculateBundle(); + return bundle * giveAwayQuantity; + } + + private boolean hasGiveAway(String productName) { + for (Map.Entry<Product, Integer> giveAwayInfo : giveAwayHistory.entrySet()) { + Product product = giveAwayInfo.getKey(); + if (productName.equals(product.getName())) { + return true; + } + } + return false; + } + + private int findGiveAwayQuantity(String productName) { + for (Map.Entry<Product, Integer> giveAwayInfo : giveAwayHistory.entrySet()) { + Product product = giveAwayInfo.getKey(); + if (productName.equals(product.getName())) { + return giveAwayInfo.getValue(); + } + } + return 0; + } + + public int calculateTotalPurchaseAmount() { + int totalPurchaseAmount = 0; + for (Map.Entry<Product, Integer> giveAway : purchaseHistory.entrySet()) { + Product product = giveAway.getKey(); + int quantity = giveAway.getValue(); + totalPurchaseAmount += product.getPrice() * quantity; + } + return totalPurchaseAmount; + } + + public int calculateTotalQuantity() { + int totalQuantity = 0; + for (Integer quantity : purchaseHistory.values()) { + totalQuantity += quantity; + } + return totalQuantity; + } + + public int calculatePromotionDiscount() { + int promotionDiscount = 0; + for (Map.Entry<Product, Integer> giveAway : giveAwayHistory.entrySet()) { + Product product = giveAway.getKey(); + int quantity = giveAway.getValue(); + promotionDiscount += product.getPrice() * quantity; + } + return promotionDiscount; + } + + public int calculateMembershipDiscount() { + int membershipDiscount = (int) (membershipApplicableAmount * MEMBERSHIP_DISCOUNT_RATE); + return Math.min(MEMBERSHIP_DISCOUNT_LIMIT, membershipDiscount); + } + + public int calculatePayment() { + int totalPurchaseAmount = calculateTotalPurchaseAmount(); + int promotionDiscount = calculatePromotionDiscount(); + int membershipDiscount = calculateMembershipDiscount(); + return totalPurchaseAmount - promotionDiscount - membershipDiscount; + } + + public Map<Product, Integer> getPurchaseHistory() { + return Collections.unmodifiableMap(purchaseHistory); + } + + public Map<Product, Integer> getGiveAwayHistory() { + return Collections.unmodifiableMap(giveAwayHistory); + } +}
Java
inventory์—์„œ ๋น„์Šทํ•œ ์—ญํ• ์„ ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋ณธ๊ฑฐ ๊ฐ™์€๋ฐ ์ž๋ฃŒํ˜• ๋•Œ๋ฌธ์— ์ƒˆ๋กœ ๋งŒ๋“œ์‹ ๊ฑด๊ฐ€์š”..?
@@ -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
private๋กœ ์•ˆํ•˜์‹  ์ด์œ ๊ฐ€ ์žˆ๋‚˜์š”? controller์—์„œ๋Š” ์•„๋ฌด๋‚˜ ์ ‘๊ทผํ•˜์ง€ ๋ชปํ•˜๋„๋ก ์ ‘๊ทผ์ œํ•œ์ž๋ฅผ ์„ค์ •ํ•ด ๋†“๋Š”๊ฒŒ ์ข‹์•„๋ณด์ž…๋‹ˆ๋‹ค
@@ -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
Inventory์˜ ์—ญํ• ์ด ๋„ˆ๋ฌด ๋งŽ์•„๋ณด์—ฌ์š”. find๋‚˜ add ๊ฐ™์€ CRUD ๊ฐœ๋…์€ 3-way-architecture๋ฅผ ์ด์šฉํ•ด๋ณด์‹œ๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”
@@ -0,0 +1,83 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.ErrorMessage.INVALID_ORDER_MESSAGE; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class Order { + + private final Map<String, Integer> orders; + + public Order(String orderInput) { + this.orders = new LinkedHashMap<>(); + validate(orderInput); + putToOrders(orderInput); + } + + private void putToOrders(String orderInput) { + List<String> orderParts = List.of(orderInput.split(",")); + for (String orderPart : orderParts) { + parseOrder(orderPart); + } + } + + private void parseOrder(String orderPart) { + String orderPartNoBracket = removeSquareBracket(orderPart); + List<String> productNameAndQuantity = List.of(orderPartNoBracket.split("-")); + String name = productNameAndQuantity.getFirst(); + String quantityPart = productNameAndQuantity.getLast(); + int quantity = Integer.parseInt(quantityPart); + orders.put(name, quantity); + } + + private void validate(String orderInput) { + List<String> splitComma = List.of(orderInput.split(",")); + for (String productNameAndQuantity : splitComma) { + checkSquareBracket(productNameAndQuantity); + checkSeparatedTwoPart(productNameAndQuantity); + } + } + + private void checkSquareBracket(String order) { + if (!isStartAndEndWithSquareBracket(order)) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private void checkSeparatedTwoPart(String order) { + String orderNoBracket = removeSquareBracket(order); + List<String> splitHyphen = List.of(orderNoBracket.split("-")); + if (splitHyphen.size() != 2) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + String quantity = splitHyphen.getLast(); + checkQuantityPart(quantity); + } + + private void checkQuantityPart(String quantityPart) { + try { + int quantity = Integer.parseInt(quantityPart); + if (quantity <= 0) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private boolean isStartAndEndWithSquareBracket(String order) { + return order.startsWith("[") && order.endsWith("]"); + } + + private String removeSquareBracket(String orderPart) { + return orderPart.replaceAll("[\\[\\]]", BLANK); + } + + public Map<String, Integer> getOrders() { + return Collections.unmodifiableMap(orders); + } +}
Java
์ €๋„ ๋„๋ฉ”์ธ์—์„œ ๊ฒ€์ฆํ•˜๋Š” ๊ฒŒ ์žˆ๋Š”๊ฑธ ์ข‹์•„ํ•˜๋Š” ํŽธ์ธ๋ฐ ํ•ด๋‹น ์ œ๊ฐ€ ์ƒ๊ฐํ•˜๋Š” ์ด๋ฒˆ ํŽธ์˜์ ์—์„œ๋Š” orderCount๋ฅผ ๋ฏธ๋ฆฌ parseํ•˜๋Š” ๊ฒŒ ๋” ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,158 @@ +package store.service; + +import static store.util.Constant.ANSWER_NO; +import static store.util.Constant.ANSWER_YES; +import static store.util.Validator.validateAnswer; +import static store.view.InputView.readForAdditionalItem; +import static store.view.InputView.readForMembershipDiscount; +import static store.view.InputView.readForOutOfStock; + +import java.util.LinkedHashMap; +import java.util.Map; +import store.domain.Inventory; +import store.domain.Order; +import store.domain.Product; +import store.domain.Promotion; +import store.domain.Promotions; +import store.domain.Receipt; +import store.view.OutputView; + +public class PaymentService { + + private final Map<String, Integer> shoppingCart; + private final Receipt receipt; + + public PaymentService(Inventory inventory, Promotions promotions, Order order) { + shoppingCart = new LinkedHashMap<>(); + receipt = new Receipt(); + checkPromotionProduct(inventory, promotions, order); + updatePurchaseHistory(inventory); + updateGiveAwayHistory(inventory, promotions, order); + updateInventory(inventory, promotions); + checkMembershipDiscount(promotions); + } + + private void checkMembershipDiscount(Promotions promotions) { + String answer = inputForMembershipDiscount(); + if (answer.equals(ANSWER_YES)) { + receipt.applyMembershipDiscount(promotions); + } + } + + private void updateInventory(Inventory inventory, Promotions promotions) { + shoppingCart.forEach((productName, quantity) -> { + Product product = inventory.findProductWithPromotion(productName); + if (product != null && promotions.isPromotionApplicable(product)) { + inventory.reducePromotionStock(productName, quantity); + return; + } + inventory.reduceNotPromotionStock(productName, quantity); + }); + } + + private void updatePurchaseHistory(Inventory inventory) { + shoppingCart.forEach((productName, quantity) -> { + Product product = inventory.findProductWithPromotion(productName); + if (product == null) { + product = inventory.findProductWithoutPromotion(productName); + } + receipt.addPurchaseHistory(product, quantity); + }); + } + + private void updateGiveAwayHistory(Inventory inventory, Promotions promotions, Order order) { + shoppingCart.forEach((productName, quantity) -> { + Product product = inventory.findProductWithPromotion(productName); + if (product != null && promotions.isPromotionApplicable(product)) { + Promotion promotion = promotions.findPromotion(product.getPromotionName()); + receipt.addGiveAwayHistory(product, promotion, quantity); + } + }); + } + + private void checkPromotionProduct(Inventory inventory, Promotions promotions, Order order) { + Map<String, Integer> orders = order.getOrders(); + orders.forEach((productName, quantity) -> { + shoppingCart.put(productName, quantity); + Product product = inventory.findProductWithPromotion(productName); + if (product != null && promotions.isPromotionApplicable(product)) { + Promotion promotion = promotions.findPromotion(product.getPromotionName()); + checkBenefitOrOutOfStock(product, promotion, Map.entry(productName, quantity)); + } + }); + } + + private void checkBenefitOrOutOfStock(Product product, Promotion promotion, Map.Entry<String, Integer> order) { + String productName = order.getKey(); + int quantity = order.getValue(); + if (canApplyPromotionBenefit(product, promotion, Map.entry(productName, quantity))) { + if (inputForAdditionalItem(productName).equals(ANSWER_YES)) { + shoppingCart.put(productName, quantity + 1); + } + return; + } + checkOutOfStock(product, promotion, Map.entry(productName, quantity)); + } + + private boolean canApplyPromotionBenefit(Product product, Promotion promotion, Map.Entry<String, Integer> order) { + int bundle = promotion.calculateBundle(); + int quantity = order.getValue(); + if (quantity < product.getQuantity()) { + return quantity % bundle == bundle - 1; + } + return false; + } + + private void checkOutOfStock(Product product, Promotion promotion, Map.Entry<String, Integer> order) { + int bundle = promotion.calculateBundle(); + int shareOfOrder = order.getValue() / bundle; + int shareOfProduct = product.getQuantity() / bundle; + int shortageQuantity = order.getValue() - (Math.min(shareOfOrder, shareOfProduct) * bundle); + if (shortageQuantity != 0) { + String answer = inputForOutOfStock(order.getKey(), shortageQuantity); + if (answer.equals(ANSWER_NO)) { + shoppingCart.put(order.getKey(), order.getValue() - shortageQuantity); + } + } + } + + private String inputForOutOfStock(String productName, int shortageQuantity) { + while (true) { + try { + String answer = readForOutOfStock(productName, shortageQuantity); + validateAnswer(answer); + return answer; + } catch (IllegalArgumentException e) { + OutputView.printError(e.getMessage()); + } + } + } + + private String inputForAdditionalItem(String productName) { + while (true) { + try { + String answer = readForAdditionalItem(productName); + validateAnswer(answer); + return answer; + } catch (IllegalArgumentException e) { + OutputView.printError(e.getMessage()); + } + } + } + + private String inputForMembershipDiscount() { + while (true) { + try { + String answer = readForMembershipDiscount(); + validateAnswer(answer); + return answer; + } catch (IllegalArgumentException e) { + OutputView.printError(e.getMessage()); + } + } + } + + public Receipt getReceipt() { + return receipt; + } +}
Java
์ €๋Š” service์—์„œ input, output์„ ํ•˜๋Š” ๊ฑด ์—ญํ• ์— ์•ˆ๋งž๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. controller๊ฐ€ ์‚ฌ์šฉ์ž์—๊ฒŒ ์ž…๋ ฅ๊ณผ ์ถœ๋ ฅ์„ ๋‹ด๋‹นํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋Š”๋ฐ service์—์„œ ํ•˜๋Š” ์—ญํ• ์ด ์•„๋‹ˆ๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค
@@ -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
ํ•ด๋‹น ์ฝ”๋“œ๋Š” InputView์—์„œ ๋ฉ”์„œ๋“œ๋ฅผ ๋งŒ๋“ค์–ด์„œ ํ˜ธ์ถœํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ์ˆ˜ํ–‰ํ–ˆ์œผ๋ฉด ๋” ์ข‹์•˜์„ ๊ฒƒ ๊ฐ™๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์—ˆ์–ด์š”! import camp.nextstep.edu.missionutils.Console; ๋™์ผํ•œ import ๊ตฌ๋ฌธ์ด InputView์—๋„ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ด์—์š”!
@@ -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
์ผ๊ธ‰ ์ปฌ๋ ‰์…˜ ๋ฐฉ์‹์„ ์ด์šฉํ•˜์—ฌ Inventory ํด๋ž˜์Šค์—์„œ ์ƒํ’ˆ์˜ ์ˆ˜๋Ÿ‰ ๊ฐ์†Œ ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜์‹  ๊ฒƒ ๊ฐ™์•„์š”! ๊ฐ์ฒด๋ฅผ ๊ฐ์ฒด๋‹ต๊ฒŒ ํ™œ์šฉํ•˜๋ ค๋Š” ์ ‘๊ทผ์ด ๋‹๋ณด์ž…๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ํ•œ ๊ฐ€์ง€ ์•„์‰ฌ์šด ์ ์€ ํ˜„์žฌ ์ˆ˜๋Ÿ‰๋งŒํผ ๋ฐ˜๋ณต๋ฌธ์„ ํ†ตํ•ด reduceQuantity๋ฅผ ์—ฌ๋Ÿฌ ๋ฒˆ ํ˜ธ์ถœํ•˜๊ณ  ์žˆ๋‹ค๋Š” ์ ์ž…๋‹ˆ๋‹ค. ์ด ๋Œ€์‹ , ํ•ด๋‹น ์ƒํ’ˆ(Product)์— ์ฐจ๊ฐํ•  ์ˆ˜๋Ÿ‰์„ ํ•œ ๋ฒˆ์— ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ฐœ์„ ํ•˜๋ฉด ๋ถˆํ•„์š”ํ•œ ๋ฐ˜๋ณต๋ฌธ์„ ์ค„์ด๊ณ  ์„ฑ๋Šฅ๋„ ๊ฐœ์„ ๋  ๊ฒƒ ๊ฐ™์•„์š”! ``` private void reduceProduct(Product product, int quantity) { product.reduceQuantity(quantity); } ``` ์ด๋ ‡๊ฒŒ ๊ฐœ์„ ํ•˜๋ฉด ์ฝ”๋“œ๊ฐ€ ๋” ๊ฐ„๊ฒฐํ•ด์ง€๊ณ , Product ํด๋ž˜์Šค์—์„œ๋„ ์ˆ˜๋Ÿ‰์„ ํ•œ ๋ฒˆ์— ์ค„์ผ ์ˆ˜ ์žˆ์–ด ๋ช…ํ™•ํ•œ ์ฑ…์ž„ ๋ถ„๋ฆฌ๊ฐ€ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -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
๋ถˆ๋ณ€ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ์œ„ํ•œ ๋ฉ”์„œ๋“œ๋กœ ์•Œ๊ณ ์žˆ์–ด์š”! ์™ธ๋ถ€์—์„œ ์ˆ˜์ •์„ ๋ฐฉ์ง€ํ•˜๊ณ  ์•ˆ์ •์„ฑ์„ ๋ณด์žฅํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ ์•Œ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค! ์ €๋„ ์ผ๊ธ‰์ปฌ๋ ‰์…˜ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•ด์„œ ํ˜น์‹œ๋‚˜ ๋„์›€์ด ๋˜์…จ์œผ๋ฉด ํ•˜๋Š” ๋งˆ์Œ์— ๋‹ต๋ณ€ ๋‹ฌ์•„๋ด…๋‹ˆ๋‹ค!
@@ -0,0 +1,83 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.ErrorMessage.INVALID_ORDER_MESSAGE; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class Order { + + private final Map<String, Integer> orders; + + public Order(String orderInput) { + this.orders = new LinkedHashMap<>(); + validate(orderInput); + putToOrders(orderInput); + } + + private void putToOrders(String orderInput) { + List<String> orderParts = List.of(orderInput.split(",")); + for (String orderPart : orderParts) { + parseOrder(orderPart); + } + } + + private void parseOrder(String orderPart) { + String orderPartNoBracket = removeSquareBracket(orderPart); + List<String> productNameAndQuantity = List.of(orderPartNoBracket.split("-")); + String name = productNameAndQuantity.getFirst(); + String quantityPart = productNameAndQuantity.getLast(); + int quantity = Integer.parseInt(quantityPart); + orders.put(name, quantity); + } + + private void validate(String orderInput) { + List<String> splitComma = List.of(orderInput.split(",")); + for (String productNameAndQuantity : splitComma) { + checkSquareBracket(productNameAndQuantity); + checkSeparatedTwoPart(productNameAndQuantity); + } + } + + private void checkSquareBracket(String order) { + if (!isStartAndEndWithSquareBracket(order)) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private void checkSeparatedTwoPart(String order) { + String orderNoBracket = removeSquareBracket(order); + List<String> splitHyphen = List.of(orderNoBracket.split("-")); + if (splitHyphen.size() != 2) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + String quantity = splitHyphen.getLast(); + checkQuantityPart(quantity); + } + + private void checkQuantityPart(String quantityPart) { + try { + int quantity = Integer.parseInt(quantityPart); + if (quantity <= 0) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private boolean isStartAndEndWithSquareBracket(String order) { + return order.startsWith("[") && order.endsWith("]"); + } + + private String removeSquareBracket(String orderPart) { + return orderPart.replaceAll("[\\[\\]]", BLANK); + } + + public Map<String, Integer> getOrders() { + return Collections.unmodifiableMap(orders); + } +}
Java
์‰ผํ‘œ(,)์™€ ๊ฐ™์€ ์˜๋ฏธ ์žˆ๋Š” ๊ธฐํ˜ธ๋ฅผ ์ƒ์ˆ˜๋กœ์จ ๋ถ„๋ฆฌ๋ฅผ ํ•˜์‹œ๋ฉด ์œ ์ง€ ๋ณด์ˆ˜ ๊ด€์ ์—์„œ ๋” ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์—ˆ์–ด์š”!
@@ -0,0 +1,83 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.ErrorMessage.INVALID_ORDER_MESSAGE; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class Order { + + private final Map<String, Integer> orders; + + public Order(String orderInput) { + this.orders = new LinkedHashMap<>(); + validate(orderInput); + putToOrders(orderInput); + } + + private void putToOrders(String orderInput) { + List<String> orderParts = List.of(orderInput.split(",")); + for (String orderPart : orderParts) { + parseOrder(orderPart); + } + } + + private void parseOrder(String orderPart) { + String orderPartNoBracket = removeSquareBracket(orderPart); + List<String> productNameAndQuantity = List.of(orderPartNoBracket.split("-")); + String name = productNameAndQuantity.getFirst(); + String quantityPart = productNameAndQuantity.getLast(); + int quantity = Integer.parseInt(quantityPart); + orders.put(name, quantity); + } + + private void validate(String orderInput) { + List<String> splitComma = List.of(orderInput.split(",")); + for (String productNameAndQuantity : splitComma) { + checkSquareBracket(productNameAndQuantity); + checkSeparatedTwoPart(productNameAndQuantity); + } + } + + private void checkSquareBracket(String order) { + if (!isStartAndEndWithSquareBracket(order)) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private void checkSeparatedTwoPart(String order) { + String orderNoBracket = removeSquareBracket(order); + List<String> splitHyphen = List.of(orderNoBracket.split("-")); + if (splitHyphen.size() != 2) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + String quantity = splitHyphen.getLast(); + checkQuantityPart(quantity); + } + + private void checkQuantityPart(String quantityPart) { + try { + int quantity = Integer.parseInt(quantityPart); + if (quantity <= 0) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private boolean isStartAndEndWithSquareBracket(String order) { + return order.startsWith("[") && order.endsWith("]"); + } + + private String removeSquareBracket(String orderPart) { + return orderPart.replaceAll("[\\[\\]]", BLANK); + } + + public Map<String, Integer> getOrders() { + return Collections.unmodifiableMap(orders); + } +}
Java
split์„ ์‚ฌ์šฉํ•˜์…จ์ง€๋งŒ List๋ฅผ ์ด์šฉํ•˜์‹œ๊ธฐ ์œ„ํ—ค List.of๋ฅผ ์ด์šฉํ•˜์‹  ์ ์ด ๋‹๋ณด์ด๋„ค์š”!
@@ -0,0 +1,120 @@ +package store.domain; + +import static store.util.Constant.MEMBERSHIP_DISCOUNT_LIMIT; +import static store.util.Constant.MEMBERSHIP_DISCOUNT_RATE; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +public class Receipt { + + private final Map<Product, Integer> purchaseHistory; + private final Map<Product, Integer> giveAwayHistory; + private int membershipApplicableAmount; + + public Receipt() { + purchaseHistory = new LinkedHashMap<>(); + giveAwayHistory = new LinkedHashMap<>(); + } + + public void addPurchaseHistory(Product product, int quantity) { + purchaseHistory.put(product, quantity); + } + + public void addGiveAwayHistory(Product product, Promotion promotion, int quantity) { + int bundle = promotion.getBuy() + promotion.getGet(); + int giveAwayQuantity = Math.min(quantity, product.getQuantity()) / bundle; + if (giveAwayQuantity != 0) { + giveAwayHistory.put(product, giveAwayQuantity); + } + } + + public void applyMembershipDiscount(Promotions promotions) { + for (Map.Entry<Product, Integer> purchaseInfo : purchaseHistory.entrySet()) { + Product product = purchaseInfo.getKey(); + int quantity = purchaseInfo.getValue(); + if (!hasGiveAway(product.getName())) { + membershipApplicableAmount += product.getPrice() * quantity; + continue; + } + int promotionApplicableQuantity = calculatePromotionApplicableQuantity(product, promotions); + membershipApplicableAmount += product.getPrice() * (quantity - promotionApplicableQuantity); + } + } + + private int calculatePromotionApplicableQuantity(Product product, Promotions promotions) { + int giveAwayQuantity = findGiveAwayQuantity(product.getName()); + Promotion promotion = promotions.findPromotion(product.getPromotionName()); + int bundle = promotion.calculateBundle(); + return bundle * giveAwayQuantity; + } + + private boolean hasGiveAway(String productName) { + for (Map.Entry<Product, Integer> giveAwayInfo : giveAwayHistory.entrySet()) { + Product product = giveAwayInfo.getKey(); + if (productName.equals(product.getName())) { + return true; + } + } + return false; + } + + private int findGiveAwayQuantity(String productName) { + for (Map.Entry<Product, Integer> giveAwayInfo : giveAwayHistory.entrySet()) { + Product product = giveAwayInfo.getKey(); + if (productName.equals(product.getName())) { + return giveAwayInfo.getValue(); + } + } + return 0; + } + + public int calculateTotalPurchaseAmount() { + int totalPurchaseAmount = 0; + for (Map.Entry<Product, Integer> giveAway : purchaseHistory.entrySet()) { + Product product = giveAway.getKey(); + int quantity = giveAway.getValue(); + totalPurchaseAmount += product.getPrice() * quantity; + } + return totalPurchaseAmount; + } + + public int calculateTotalQuantity() { + int totalQuantity = 0; + for (Integer quantity : purchaseHistory.values()) { + totalQuantity += quantity; + } + return totalQuantity; + } + + public int calculatePromotionDiscount() { + int promotionDiscount = 0; + for (Map.Entry<Product, Integer> giveAway : giveAwayHistory.entrySet()) { + Product product = giveAway.getKey(); + int quantity = giveAway.getValue(); + promotionDiscount += product.getPrice() * quantity; + } + return promotionDiscount; + } + + public int calculateMembershipDiscount() { + int membershipDiscount = (int) (membershipApplicableAmount * MEMBERSHIP_DISCOUNT_RATE); + return Math.min(MEMBERSHIP_DISCOUNT_LIMIT, membershipDiscount); + } + + public int calculatePayment() { + int totalPurchaseAmount = calculateTotalPurchaseAmount(); + int promotionDiscount = calculatePromotionDiscount(); + int membershipDiscount = calculateMembershipDiscount(); + return totalPurchaseAmount - promotionDiscount - membershipDiscount; + } + + public Map<Product, Integer> getPurchaseHistory() { + return Collections.unmodifiableMap(purchaseHistory); + } + + public Map<Product, Integer> getGiveAwayHistory() { + return Collections.unmodifiableMap(giveAwayHistory); + } +}
Java
``` int promotionApplicableQuantity = calculatePromotionApplicableQuantity(product, promotions); membershipApplicableAmount += product.getPrice() * (quantity - promotionApplicableQuantity); ``` ํ•ด๋‹น ์ฝ”๋“œ๋ฅผ ๋ฉ”์„œ๋“œ ๋ถ„๋ฆฌํ•˜์…”์„œ ํ•œ ๋ผ์ธ์œผ๋กœ ์ฒ˜๋ฆฌ๊ฐ€ ๊ฐ€๋Šฅํ–ˆ์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,81 @@ +package store.view; + +import static store.util.Constant.BLANK; +import static store.util.ErrorMessage.ERROR_TAG; +import static store.util.Constant.RECEIPT_AMOUNT_INFO_TITLE; +import static store.util.Constant.RECEIPT_GIVEAWAY_TITLE; +import static store.util.Constant.RECEIPT_TITLE; +import static store.util.InformationMessage.INTRODUCE_PRODUCT_MESSAGE; +import static store.util.MessageTemplate.PRODUCT_INFO; +import static store.util.MessageTemplate.PRODUCT_INFO_ZERO_QUANTITY; +import static store.util.MessageTemplate.RECEIPT_DISCOUNT; +import static store.util.MessageTemplate.RECEIPT_GIVEAWAY_HISTORY; +import static store.util.MessageTemplate.RECEIPT_HEADER; +import static store.util.MessageTemplate.RECEIPT_PAYMENT; +import static store.util.MessageTemplate.RECEIPT_PURCHASE_HISTORY; +import static store.util.MessageTemplate.RECEIPT_TOTAL_PURCHASE_AMOUNT; + +import java.util.List; +import java.util.Map; +import store.domain.Inventory; +import store.domain.Product; +import store.domain.Receipt; + +public class OutputView extends View { + + private OutputView() {} + + public static void printInventory(Inventory inventory) { + printMessage(INTRODUCE_PRODUCT_MESSAGE); + printNewLine(); + List<Product> products = inventory.getProducts(); + for (Product product : products) { + printProductInfo(product); + } + } + + public static void printProductInfo(Product product) { + if (!product.isZeroQuantity()) { + printMessage(PRODUCT_INFO.format(product.getName(), product.getPrice(), product.getQuantity(), + product.getPromotionName())); + return; + } + printMessage( + PRODUCT_INFO_ZERO_QUANTITY.format(product.getName(), product.getPrice(), product.getPromotionName())); + } + + public static void displayReceipt(Receipt receipt) { + printMessage(RECEIPT_TITLE); + printMessage(RECEIPT_HEADER.format("์ƒํ’ˆ๋ช…", "์ˆ˜๋Ÿ‰", "๊ธˆ์•ก")); + displayPurchaseHistory(receipt); + displayGiveAwayHistory(receipt); + displayAmountInfo(receipt); + } + + private static void displayAmountInfo(Receipt receipt) { + printMessage(RECEIPT_AMOUNT_INFO_TITLE); + printMessage(RECEIPT_TOTAL_PURCHASE_AMOUNT.format("์ด๊ตฌ๋งค์•ก", receipt.calculateTotalQuantity(), + receipt.calculateTotalPurchaseAmount())); + printMessage(RECEIPT_DISCOUNT.format("ํ–‰์‚ฌํ• ์ธ", BLANK, receipt.calculatePromotionDiscount())); + printMessage(RECEIPT_DISCOUNT.format("๋ฉค๋ฒ„์‹ญํ• ์ธ", BLANK, receipt.calculateMembershipDiscount())); + printMessage(RECEIPT_PAYMENT.format("๋‚ด์‹ค๋ˆ", BLANK, receipt.calculatePayment())); + } + + private static void displayGiveAwayHistory(Receipt receipt) { + printMessage(RECEIPT_GIVEAWAY_TITLE); + receipt.getGiveAwayHistory().forEach((product, quantity) -> { + printMessage(RECEIPT_GIVEAWAY_HISTORY.format(product.getName(), quantity)); + }); + } + + private static void displayPurchaseHistory(Receipt receipt) { + Map<Product, Integer> purchaseHistory = receipt.getPurchaseHistory(); + purchaseHistory.forEach((product, quantity) -> { + printMessage(RECEIPT_PURCHASE_HISTORY.format(product.getName(), quantity, product.getPrice() * quantity)); + }); + } + + public static void printError(String errorMessage) { + printMessage(ERROR_TAG + errorMessage); + } +}
Java
์•ˆ๋…•ํ•˜์„ธ์š”! ํ˜น์‹œ ์•„๋ž˜์™€ ๊ฐ™์ด ํฌ๋งท์„ ์„ค์ •ํ•˜์…จ์„ ๋•Œ, ๋„์–ด์“ฐ๊ธฐ ๋•Œ๋ฌธ์— ์ถœ๋ ฅ์ด ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ์ •๋ ฌ์ด ๋˜์…จ๋‚˜์š”?? 4์ฃผ ์ฐจ ์ง„ํ–‰ํ•˜๋ฉด์„œ ์˜์ˆ˜์ฆ ์ถœ๋ ฅ ๋ถ€๋ถ„์„ ๋ณด๊ธฐ ์ข‹๊ฒŒ ์ •๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ์š”๊ตฌ์‚ฌํ•ญ์ด์—ˆ์–ด์„œ ๋งŽ์ด ์ฐพ์•„๋ดค์Šต๋‹ˆ๋‹ค! ๊ทธ ๊ณผ์ •์—์„œ ์•Œ๊ฒŒ ๋œ ์ ์€, ํ•œ๊ตญ์–ด๋Š” 2๊ธ€์ž๋กœ ์ทจ๊ธ‰๋˜์ง€๋งŒ, ๋„์–ด์“ฐ๊ธฐ์™€ ์˜์–ด๋Š” 1๊ธ€์ž๋กœ ์ทจ๊ธ‰๋œ๋‹ค๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ๋„์–ด์“ฐ๊ธฐ๋ฅผ ํ•œ๊ธ€์ฒ˜๋Ÿผ 2๊ธ€์ž ์—ญํ• ์„ ํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ์„๊นŒ ๊ณ ๋ฏผํ•˜๋‹ค๊ฐ€, \u3000 (์œ ๋‹ˆ์ฝ”๋“œ ๊ณต๋ฐฑ)์„ ์•Œ๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค! ์˜ˆ๋ฅผ ๋“ค์–ด, ์•„๋ž˜์™€ ๊ฐ™์ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค: `String name = String.format("%-14s", "์ด๊ตฌ๋งค์•ก").replace(" ", "\u3000");` ์ด ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜๋ฉด ํ•œ๊ธ€์ฒ˜๋Ÿผ ๋„์–ด์“ฐ๊ธฐ๋ฅผ 2๊ธ€์ž ์ทจ๊ธ‰ํ•  ์ˆ˜ ์žˆ์–ด์„œ ์ •๋ ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค! ๐Ÿ˜Š
@@ -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
์ผ๋ฐ˜์ ์œผ๋กœ do-while๋ณด๋‹ค๋Š” while๋ฌธ์„ ์‚ฌ์šฉํ•˜์—ฌ ์กฐ๊ฑด์„ ๋จผ์ € ํ™•์ธํ•˜๋Š” ๊ฒƒ์ด ๋” ๋ช…ํ™•ํ•˜๊ณ  ๊ฐ€๋…์„ฑ๋„ ํ–ฅ์ƒ๋œ๋‹ค๊ณ  ์•Œ๊ณ  ์žˆ์–ด์š”! while ๋ฌธ์„ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด, ์ฝ”๋“œ ํ๋ฆ„์ด ๋ช…ํ™•ํ•ด์ ธ์„œ ์œ ์ง€๋ณด์ˆ˜ํ•  ๋•Œ ๋” ์‰ฝ๊ฒŒ ์ดํ•ดํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๐Ÿ˜Š
@@ -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
ํ˜•๋ณ€ํ™˜์„ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ์‹์€ ์ž ์žฌ์ ์ธ ์˜ค๋ฅ˜๋ฅผ ์œ ๋ฐœํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, ๊ฐ€๋Šฅํ•œ ํ•œ ๊ตฌ์ฒด์ ์ธ ํƒ€์ž…์„ ์‚ฌ์šฉํ•˜์—ฌ ์•ˆ์ „ํ•˜๊ณ  ๊ฐ€๋…์„ฑ์ด ์ข‹์€ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋Š” ๊ฒƒ์ด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”! ์˜ˆ๋ฅผ ๋“ค์–ด, `List<Object>` ํƒ€์ž…์„ `List<String>, List<ProductInfo>` ๋ฐ”๊พธ์–ด ๊ตฌ์ฒด์ ์ธ ์ž๋ฃŒํ˜•์„ ์‚ฌ์šฉํ•˜๋ฉด ํ˜•๋ณ€ํ™˜์„ ํ”ผํ•  ์ˆ˜ ์žˆ์–ด์š” ```java private Product createProduct(List<String> productInfo) { String name = productInfo.get(0); int price = Integer.parseInt(productInfo.get(1)); int quantity = Integer.parseInt(productInfo.get(2)); String promotion = productInfo.get(3); return new Product(name, price, quantity, promotion); } ```
@@ -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
๋ฐ˜๋ณต๋˜๋Š” ์ฝ”๋“œ๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ๋ถ„๋ฆฌํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ˜Š
@@ -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
์ด ๋ถ€๋ถ„์€ ์ŠคํŠธ๋ฆผ์„ ์‚ฌ์šฉํ•˜์—ฌ ๋” ๊ฐ„๋‹จํ•˜๊ฒŒ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”! ```java public boolean hasProduct(String name) { return products.stream() .anyMatch(product -> name.equals(product.getName())); } ```
@@ -0,0 +1,83 @@ +package store.domain; + +import static store.util.Constant.BLANK; +import static store.util.ErrorMessage.INVALID_ORDER_MESSAGE; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class Order { + + private final Map<String, Integer> orders; + + public Order(String orderInput) { + this.orders = new LinkedHashMap<>(); + validate(orderInput); + putToOrders(orderInput); + } + + private void putToOrders(String orderInput) { + List<String> orderParts = List.of(orderInput.split(",")); + for (String orderPart : orderParts) { + parseOrder(orderPart); + } + } + + private void parseOrder(String orderPart) { + String orderPartNoBracket = removeSquareBracket(orderPart); + List<String> productNameAndQuantity = List.of(orderPartNoBracket.split("-")); + String name = productNameAndQuantity.getFirst(); + String quantityPart = productNameAndQuantity.getLast(); + int quantity = Integer.parseInt(quantityPart); + orders.put(name, quantity); + } + + private void validate(String orderInput) { + List<String> splitComma = List.of(orderInput.split(",")); + for (String productNameAndQuantity : splitComma) { + checkSquareBracket(productNameAndQuantity); + checkSeparatedTwoPart(productNameAndQuantity); + } + } + + private void checkSquareBracket(String order) { + if (!isStartAndEndWithSquareBracket(order)) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private void checkSeparatedTwoPart(String order) { + String orderNoBracket = removeSquareBracket(order); + List<String> splitHyphen = List.of(orderNoBracket.split("-")); + if (splitHyphen.size() != 2) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + String quantity = splitHyphen.getLast(); + checkQuantityPart(quantity); + } + + private void checkQuantityPart(String quantityPart) { + try { + int quantity = Integer.parseInt(quantityPart); + if (quantity <= 0) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } catch (NumberFormatException e) { + throw new IllegalArgumentException(INVALID_ORDER_MESSAGE); + } + } + + private boolean isStartAndEndWithSquareBracket(String order) { + return order.startsWith("[") && order.endsWith("]"); + } + + private String removeSquareBracket(String orderPart) { + return orderPart.replaceAll("[\\[\\]]", BLANK); + } + + public Map<String, Integer> getOrders() { + return Collections.unmodifiableMap(orders); + } +}
Java
์Œ,, ํ˜น์‹œ ์ด๋Ÿฌ๋ฉด [์ฝœ๋ผ[-3]] ์ด๋ ‡๊ฒŒ ์ž‘์„ฑ๋ผ๋„ ํ†ต๊ณผ๋  ๊ฑฐ ๊ฐ™์€๋ฐ ์•„๋‹Œ๊ฐ€์š” ??
@@ -0,0 +1,40 @@ +package store.domain; + +import java.time.LocalDateTime; + +public class Promotion { + + private final String name; + private final int buy; + private final int get; + private final LocalDateTime startDate; + private final LocalDateTime endDate; + + public Promotion(String name, int buy, int get, LocalDateTime startDate, LocalDateTime endDate) { + this.name = name; + this.buy = buy; + this.get = get; + this.startDate = startDate; + this.endDate = endDate; + } + + public boolean canApply(LocalDateTime now) { + return now.isAfter(startDate) && now.isBefore(endDate); + } + + public int calculateBundle() { + return buy + get; + } + + public String getName() { + return name; + } + + public int getBuy() { + return buy; + } + + public int getGet() { + return get; + } +}
Java
startDate์™€ endDate ๋Š” DateRange ๊ฐ™์€ ํด๋ž˜์Šค๋ฅผ ํ†ตํ•ด ๋”ฐ๋กœ ๋ถ„๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ๋‚˜์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,40 @@ +package store.domain; + +import java.time.LocalDateTime; + +public class Promotion { + + private final String name; + private final int buy; + private final int get; + private final LocalDateTime startDate; + private final LocalDateTime endDate; + + public Promotion(String name, int buy, int get, LocalDateTime startDate, LocalDateTime endDate) { + this.name = name; + this.buy = buy; + this.get = get; + this.startDate = startDate; + this.endDate = endDate; + } + + public boolean canApply(LocalDateTime now) { + return now.isAfter(startDate) && now.isBefore(endDate); + } + + public int calculateBundle() { + return buy + get; + } + + public String getName() { + return name; + } + + public int getBuy() { + return buy; + } + + public int getGet() { + return get; + } +}
Java
์ €๋„ ์‹ค์ˆ˜ํ•œ ๋ถ€๋ถ„์ธ๋ฐ, ์ด๋Ÿฌ๋ฉด ํ”„๋กœ๋ชจ์…˜ ์‹œ์ž‘์ผ, ์ข…๋ฃŒ์ผ์ด๋ฉด false ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋”๋ผ๊ตฌ์š” ใ…œใ…œ
@@ -0,0 +1,81 @@ +package store.view; + +import static store.util.Constant.BLANK; +import static store.util.ErrorMessage.ERROR_TAG; +import static store.util.Constant.RECEIPT_AMOUNT_INFO_TITLE; +import static store.util.Constant.RECEIPT_GIVEAWAY_TITLE; +import static store.util.Constant.RECEIPT_TITLE; +import static store.util.InformationMessage.INTRODUCE_PRODUCT_MESSAGE; +import static store.util.MessageTemplate.PRODUCT_INFO; +import static store.util.MessageTemplate.PRODUCT_INFO_ZERO_QUANTITY; +import static store.util.MessageTemplate.RECEIPT_DISCOUNT; +import static store.util.MessageTemplate.RECEIPT_GIVEAWAY_HISTORY; +import static store.util.MessageTemplate.RECEIPT_HEADER; +import static store.util.MessageTemplate.RECEIPT_PAYMENT; +import static store.util.MessageTemplate.RECEIPT_PURCHASE_HISTORY; +import static store.util.MessageTemplate.RECEIPT_TOTAL_PURCHASE_AMOUNT; + +import java.util.List; +import java.util.Map; +import store.domain.Inventory; +import store.domain.Product; +import store.domain.Receipt; + +public class OutputView extends View { + + private OutputView() {} + + public static void printInventory(Inventory inventory) { + printMessage(INTRODUCE_PRODUCT_MESSAGE); + printNewLine(); + List<Product> products = inventory.getProducts(); + for (Product product : products) { + printProductInfo(product); + } + } + + public static void printProductInfo(Product product) { + if (!product.isZeroQuantity()) { + printMessage(PRODUCT_INFO.format(product.getName(), product.getPrice(), product.getQuantity(), + product.getPromotionName())); + return; + } + printMessage( + PRODUCT_INFO_ZERO_QUANTITY.format(product.getName(), product.getPrice(), product.getPromotionName())); + } + + public static void displayReceipt(Receipt receipt) { + printMessage(RECEIPT_TITLE); + printMessage(RECEIPT_HEADER.format("์ƒํ’ˆ๋ช…", "์ˆ˜๋Ÿ‰", "๊ธˆ์•ก")); + displayPurchaseHistory(receipt); + displayGiveAwayHistory(receipt); + displayAmountInfo(receipt); + } + + private static void displayAmountInfo(Receipt receipt) { + printMessage(RECEIPT_AMOUNT_INFO_TITLE); + printMessage(RECEIPT_TOTAL_PURCHASE_AMOUNT.format("์ด๊ตฌ๋งค์•ก", receipt.calculateTotalQuantity(), + receipt.calculateTotalPurchaseAmount())); + printMessage(RECEIPT_DISCOUNT.format("ํ–‰์‚ฌํ• ์ธ", BLANK, receipt.calculatePromotionDiscount())); + printMessage(RECEIPT_DISCOUNT.format("๋ฉค๋ฒ„์‹ญํ• ์ธ", BLANK, receipt.calculateMembershipDiscount())); + printMessage(RECEIPT_PAYMENT.format("๋‚ด์‹ค๋ˆ", BLANK, receipt.calculatePayment())); + } + + private static void displayGiveAwayHistory(Receipt receipt) { + printMessage(RECEIPT_GIVEAWAY_TITLE); + receipt.getGiveAwayHistory().forEach((product, quantity) -> { + printMessage(RECEIPT_GIVEAWAY_HISTORY.format(product.getName(), quantity)); + }); + } + + private static void displayPurchaseHistory(Receipt receipt) { + Map<Product, Integer> purchaseHistory = receipt.getPurchaseHistory(); + purchaseHistory.forEach((product, quantity) -> { + printMessage(RECEIPT_PURCHASE_HISTORY.format(product.getName(), quantity, product.getPrice() * quantity)); + }); + } + + public static void printError(String errorMessage) { + printMessage(ERROR_TAG + errorMessage); + } +}
Java
์ด๋Ÿฌํ•œ ์ƒํ’ˆ๋ช…, ์ˆ˜๋Ÿ‰, ๊ธˆ์•ก, ์ด๊ตฌ๋งค์•ก, ํ–‰์‚ฌํ• ์ธ, ๋ฉค๋ฒ„์‹ญํ• ์ธ ๋“ฑ ์ƒ์ˆ˜๋กœ ๊ด€๋ฆฌํ•˜๋ฉด ๋” ์ข‹์„ ๊ฑฐ ๊ฐ™์•„์š”!
@@ -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
close๊นŒ์ง€ ์ƒ๊ฐ๋ชปํ–ˆ๋Š”๋ฐ ๊ผผ๊ผผํ•˜์‹ ๋ฐ์š”!
@@ -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
์—ฌ๊ธฐ์„œ ์ผ๊ธ‰์ปฌ๋ ‰์…˜์„ ์‚ฌ์šฉํ•˜์‹  ๊ฑฐ๋ผ๋ฉด, static์ด ์•„๋‹ˆ๋ผ final์ด ๋” ์ ์ ˆํ•ด ๋ณด์ด๋Š”๋ฐ 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
์ด ๋ถ€๋ถ„์€ ์™ธ๋ถ€ ํด๋ž˜์Šค์—์„œ ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ์•„๋‹Œ checkProductInventory์—์„œ๋งŒ ์‚ฌ์šฉํ•˜๊ธฐ ๋•Œ๋ฌธ์—, private์œผ๋กœ ๋‹ซ์•„๋‘ฌ๋„ ๋  ๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค
@@ -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๋Š” ์–ด๋–ค ๋ชฉ์ ์œผ๋กœ ๊ฑฐ์ณ๊ฐ€๋„๋ก ๊ตฌํ˜„ํ•˜์…จ๋Š”์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!