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