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 ๊ตฌํํ์
จ๋ค์..! ๐
์ถ๊ฐ์ ์ผ๋ก ์ด๋ฏธ์ง๊ฐ ๋ก๋ฉ์ํ์ผ ๋, ํ๋ฉด์ด ์ ํ๋ค์..! ์คํ์ผ๋ ์ถ๊ฐ์ ์ผ๋ก ์ ์ฉํ๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค!
 |
@@ -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๋ ์ด๋ค ๋ชฉ์ ์ผ๋ก ๊ฑฐ์ณ๊ฐ๋๋ก ๊ตฌํํ์
จ๋์ง ๊ถ๊ธํฉ๋๋ค! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.