diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 000000000..5c056a748 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,62 @@ +name: Deploy Advanced to GitHub Pages + +on: + push: + branches: + - main + workflow_dispatch: + +permissions: + contents: read + pages: write + id-token: write + +concurrency: + group: "pages" + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup pnpm + uses: pnpm/action-setup@v4 + with: + version: 8 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'pnpm' + + - name: Install dependencies + run: pnpm install + + - name: Build advanced + run: pnpm run build:advanced + env: + GITHUB_PAGES: 'true' + + - name: Setup Pages + uses: actions/configure-pages@v4 + + - name: Upload artifact + uses: actions/upload-pages-artifact@v3 + with: + path: './dist' + + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + needs: build + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 + diff --git a/package.json b/package.json index 17b18de25..b7e8c7065 100644 --- a/package.json +++ b/package.json @@ -13,9 +13,11 @@ "test:advanced": "vitest src/advanced", "test:ui": "vitest --ui", "build": "tsc -b && vite build", + "build:advanced": "GITHUB_PAGES=true vite build && cp dist/index.advanced.html dist/index.html", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0" }, "dependencies": { + "jotai": "^2.15.2", "react": "^19.1.1", "react-dom": "^19.1.1" }, @@ -23,6 +25,7 @@ "@testing-library/jest-dom": "^6.6.4", "@testing-library/react": "^16.3.0", "@testing-library/user-event": "^14.6.1", + "@types/node": "^24.10.1", "@types/react": "^19.1.9", "@types/react-dom": "^19.1.7", "@typescript-eslint/eslint-plugin": "^8.38.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2dddaf85f..ba2de1cf1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,6 +8,9 @@ importers: .: dependencies: + jotai: + specifier: ^2.15.2 + version: 2.15.2(@types/react@19.1.9)(react@19.1.1) react: specifier: ^19.1.1 version: 19.1.1 @@ -24,6 +27,9 @@ importers: '@testing-library/user-event': specifier: ^14.6.1 version: 14.6.1(@testing-library/dom@10.4.0) + '@types/node': + specifier: ^24.10.1 + version: 24.10.1 '@types/react': specifier: ^19.1.9 version: 19.1.9 @@ -38,7 +44,7 @@ importers: version: 8.38.0(eslint@9.32.0)(typescript@5.9.2) '@vitejs/plugin-react-swc': specifier: ^3.11.0 - version: 3.11.0(vite@7.0.6) + version: 3.11.0(vite@7.0.6(@types/node@24.10.1)) '@vitest/ui': specifier: ^3.2.4 version: 3.2.4(vitest@3.2.4) @@ -59,10 +65,10 @@ importers: version: 5.9.2 vite: specifier: ^7.0.6 - version: 7.0.6 + version: 7.0.6(@types/node@24.10.1) vitest: specifier: ^3.2.4 - version: 3.2.4(@vitest/ui@3.2.4)(jsdom@26.1.0) + version: 3.2.4(@types/node@24.10.1)(@vitest/ui@3.2.4)(jsdom@26.1.0) packages: @@ -583,6 +589,9 @@ packages: '@types/json-schema@7.0.15': resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} + '@types/node@24.10.1': + resolution: {integrity: sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==} + '@types/react-dom@19.1.7': resolution: {integrity: sha512-i5ZzwYpqjmrKenzkoLM2Ibzt6mAsM7pxB6BCIouEVVmgiqaMj1TjaK7hnA36hbW5aZv20kx7Lw6hWzPWg0Rurw==} peerDependencies: @@ -1056,6 +1065,24 @@ packages: isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + jotai@2.15.2: + resolution: {integrity: sha512-El86CCfXNMEOytp20NPfppqGGmcp6H6kIA+tJHdmASEUURJCYW4fh8nTHEnB8rUXEFAY1pm8PdHPwnrcPGwdEg==} + engines: {node: '>=12.20.0'} + peerDependencies: + '@babel/core': '>=7.0.0' + '@babel/template': '>=7.0.0' + '@types/react': '>=17.0.0' + react: '>=17.0.0' + peerDependenciesMeta: + '@babel/core': + optional: true + '@babel/template': + optional: true + '@types/react': + optional: true + react: + optional: true + js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -1382,6 +1409,9 @@ packages: engines: {node: '>=14.17'} hasBin: true + undici-types@7.16.0: + resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==} + uri-js@4.4.1: resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} @@ -1886,6 +1916,10 @@ snapshots: '@types/json-schema@7.0.15': {} + '@types/node@24.10.1': + dependencies: + undici-types: 7.16.0 + '@types/react-dom@19.1.7(@types/react@19.1.9)': dependencies: '@types/react': 19.1.9 @@ -1987,11 +2021,11 @@ snapshots: '@typescript-eslint/types': 8.38.0 eslint-visitor-keys: 4.2.1 - '@vitejs/plugin-react-swc@3.11.0(vite@7.0.6)': + '@vitejs/plugin-react-swc@3.11.0(vite@7.0.6(@types/node@24.10.1))': dependencies: '@rolldown/pluginutils': 1.0.0-beta.27 '@swc/core': 1.13.3 - vite: 7.0.6 + vite: 7.0.6(@types/node@24.10.1) transitivePeerDependencies: - '@swc/helpers' @@ -2003,13 +2037,13 @@ snapshots: chai: 5.2.1 tinyrainbow: 2.0.0 - '@vitest/mocker@3.2.4(vite@7.0.6)': + '@vitest/mocker@3.2.4(vite@7.0.6(@types/node@24.10.1))': dependencies: '@vitest/spy': 3.2.4 estree-walker: 3.0.3 magic-string: 0.30.17 optionalDependencies: - vite: 7.0.6 + vite: 7.0.6(@types/node@24.10.1) '@vitest/pretty-format@3.2.4': dependencies: @@ -2040,7 +2074,7 @@ snapshots: sirv: 3.0.1 tinyglobby: 0.2.14 tinyrainbow: 2.0.0 - vitest: 3.2.4(@vitest/ui@3.2.4)(jsdom@26.1.0) + vitest: 3.2.4(@types/node@24.10.1)(@vitest/ui@3.2.4)(jsdom@26.1.0) '@vitest/utils@3.2.4': dependencies: @@ -2413,6 +2447,11 @@ snapshots: isexe@2.0.0: {} + jotai@2.15.2(@types/react@19.1.9)(react@19.1.1): + optionalDependencies: + '@types/react': 19.1.9 + react: 19.1.1 + js-tokens@4.0.0: {} js-tokens@9.0.1: {} @@ -2716,17 +2755,19 @@ snapshots: typescript@5.9.2: {} + undici-types@7.16.0: {} + uri-js@4.4.1: dependencies: punycode: 2.3.1 - vite-node@3.2.4: + vite-node@3.2.4(@types/node@24.10.1): dependencies: cac: 6.7.14 debug: 4.4.1 es-module-lexer: 1.7.0 pathe: 2.0.3 - vite: 7.0.6 + vite: 7.0.6(@types/node@24.10.1) transitivePeerDependencies: - '@types/node' - jiti @@ -2741,7 +2782,7 @@ snapshots: - tsx - yaml - vite@7.0.6: + vite@7.0.6(@types/node@24.10.1): dependencies: esbuild: 0.25.8 fdir: 6.4.6(picomatch@4.0.3) @@ -2750,13 +2791,14 @@ snapshots: rollup: 4.46.2 tinyglobby: 0.2.14 optionalDependencies: + '@types/node': 24.10.1 fsevents: 2.3.3 - vitest@3.2.4(@vitest/ui@3.2.4)(jsdom@26.1.0): + vitest@3.2.4(@types/node@24.10.1)(@vitest/ui@3.2.4)(jsdom@26.1.0): dependencies: '@types/chai': 5.2.2 '@vitest/expect': 3.2.4 - '@vitest/mocker': 3.2.4(vite@7.0.6) + '@vitest/mocker': 3.2.4(vite@7.0.6(@types/node@24.10.1)) '@vitest/pretty-format': 3.2.4 '@vitest/runner': 3.2.4 '@vitest/snapshot': 3.2.4 @@ -2774,10 +2816,11 @@ snapshots: tinyglobby: 0.2.14 tinypool: 1.1.1 tinyrainbow: 2.0.0 - vite: 7.0.6 - vite-node: 3.2.4 + vite: 7.0.6(@types/node@24.10.1) + vite-node: 3.2.4(@types/node@24.10.1) why-is-node-running: 2.3.0 optionalDependencies: + '@types/node': 24.10.1 '@vitest/ui': 3.2.4(vitest@3.2.4) jsdom: 26.1.0 transitivePeerDependencies: diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 0ba406491..befd353a5 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,5 +1,8 @@ +packages: + - "." + ignoredBuiltDependencies: - esbuild onlyBuiltDependencies: - - '@swc/core' + - "@swc/core" diff --git a/src/advanced/App.tsx b/src/advanced/App.tsx index a4369fe1d..7fbd9b8ef 100644 --- a/src/advanced/App.tsx +++ b/src/advanced/App.tsx @@ -1,1124 +1,45 @@ -import { useState, useCallback, useEffect } from 'react'; -import { CartItem, Coupon, Product } from '../types'; +import { useState } from "react"; +import AdminPage from "./components/AdminPage"; -interface ProductWithUI extends Product { - description?: string; - isRecommended?: boolean; -} - -interface Notification { - id: string; - message: string; - type: 'error' | 'success' | 'warning'; -} - -// 초기 데이터 -const initialProducts: ProductWithUI[] = [ - { - id: 'p1', - name: '상품1', - price: 10000, - stock: 20, - discounts: [ - { quantity: 10, rate: 0.1 }, - { quantity: 20, rate: 0.2 } - ], - description: '최고급 품질의 프리미엄 상품입니다.' - }, - { - id: 'p2', - name: '상품2', - price: 20000, - stock: 20, - discounts: [ - { quantity: 10, rate: 0.15 } - ], - description: '다양한 기능을 갖춘 실용적인 상품입니다.', - isRecommended: true - }, - { - id: 'p3', - name: '상품3', - price: 30000, - stock: 20, - discounts: [ - { quantity: 10, rate: 0.2 }, - { quantity: 30, rate: 0.25 } - ], - description: '대용량과 고성능을 자랑하는 상품입니다.' - } -]; - -const initialCoupons: Coupon[] = [ - { - name: '5000원 할인', - code: 'AMOUNT5000', - discountType: 'amount', - discountValue: 5000 - }, - { - name: '10% 할인', - code: 'PERCENT10', - discountType: 'percentage', - discountValue: 10 - } -]; +import { useSearch } from "./hooks/useSearch"; +import { Notifications } from "./components/Notifications"; +import { Header } from "./components/header"; +import { SearchBar } from "./components/header/SearchBar"; +import { ToggleButton } from "./components/header/ToggleButton"; +import { CartIcon } from "./components/header/CartIcon"; +import CartPage from "./components/CartPage"; const App = () => { - - const [products, setProducts] = useState(() => { - const saved = localStorage.getItem('products'); - if (saved) { - try { - return JSON.parse(saved); - } catch { - return initialProducts; - } - } - return initialProducts; - }); - - const [cart, setCart] = useState(() => { - const saved = localStorage.getItem('cart'); - if (saved) { - try { - return JSON.parse(saved); - } catch { - return []; - } - } - return []; - }); - - const [coupons, setCoupons] = useState(() => { - const saved = localStorage.getItem('coupons'); - if (saved) { - try { - return JSON.parse(saved); - } catch { - return initialCoupons; - } - } - return initialCoupons; - }); - - const [selectedCoupon, setSelectedCoupon] = useState(null); + const { searchTerm, debouncedSearchTerm, setSearchTerm } = useSearch(500); const [isAdmin, setIsAdmin] = useState(false); - const [notifications, setNotifications] = useState([]); - const [showCouponForm, setShowCouponForm] = useState(false); - const [activeTab, setActiveTab] = useState<'products' | 'coupons'>('products'); - const [showProductForm, setShowProductForm] = useState(false); - const [searchTerm, setSearchTerm] = useState(''); - const [debouncedSearchTerm, setDebouncedSearchTerm] = useState(''); - - // Admin - const [editingProduct, setEditingProduct] = useState(null); - const [productForm, setProductForm] = useState({ - name: '', - price: 0, - stock: 0, - description: '', - discounts: [] as Array<{ quantity: number; rate: number }> - }); - - const [couponForm, setCouponForm] = useState({ - name: '', - code: '', - discountType: 'amount' as 'amount' | 'percentage', - discountValue: 0 - }); - - - const formatPrice = (price: number, productId?: string): string => { - if (productId) { - const product = products.find(p => p.id === productId); - if (product && getRemainingStock(product) <= 0) { - return 'SOLD OUT'; - } - } - - if (isAdmin) { - return `${price.toLocaleString()}원`; - } - - return `₩${price.toLocaleString()}`; - }; - - const getMaxApplicableDiscount = (item: CartItem): number => { - const { discounts } = item.product; - const { quantity } = item; - - const baseDiscount = discounts.reduce((maxDiscount, discount) => { - return quantity >= discount.quantity && discount.rate > maxDiscount - ? discount.rate - : maxDiscount; - }, 0); - - const hasBulkPurchase = cart.some(cartItem => cartItem.quantity >= 10); - if (hasBulkPurchase) { - return Math.min(baseDiscount + 0.05, 0.5); // 대량 구매 시 추가 5% 할인 - } - - return baseDiscount; - }; - - const calculateItemTotal = (item: CartItem): number => { - const { price } = item.product; - const { quantity } = item; - const discount = getMaxApplicableDiscount(item); - - return Math.round(price * quantity * (1 - discount)); - }; - - const calculateCartTotal = (): { - totalBeforeDiscount: number; - totalAfterDiscount: number; - } => { - let totalBeforeDiscount = 0; - let totalAfterDiscount = 0; - - cart.forEach(item => { - const itemPrice = item.product.price * item.quantity; - totalBeforeDiscount += itemPrice; - totalAfterDiscount += calculateItemTotal(item); - }); - - if (selectedCoupon) { - if (selectedCoupon.discountType === 'amount') { - totalAfterDiscount = Math.max(0, totalAfterDiscount - selectedCoupon.discountValue); - } else { - totalAfterDiscount = Math.round(totalAfterDiscount * (1 - selectedCoupon.discountValue / 100)); - } - } - - return { - totalBeforeDiscount: Math.round(totalBeforeDiscount), - totalAfterDiscount: Math.round(totalAfterDiscount) - }; - }; - - const getRemainingStock = (product: Product): number => { - const cartItem = cart.find(item => item.product.id === product.id); - const remaining = product.stock - (cartItem?.quantity || 0); - - return remaining; - }; - - const addNotification = useCallback((message: string, type: 'error' | 'success' | 'warning' = 'success') => { - const id = Date.now().toString(); - setNotifications(prev => [...prev, { id, message, type }]); - - setTimeout(() => { - setNotifications(prev => prev.filter(n => n.id !== id)); - }, 3000); - }, []); - - const [totalItemCount, setTotalItemCount] = useState(0); - - - useEffect(() => { - const count = cart.reduce((sum, item) => sum + item.quantity, 0); - setTotalItemCount(count); - }, [cart]); - - useEffect(() => { - localStorage.setItem('products', JSON.stringify(products)); - }, [products]); - - useEffect(() => { - localStorage.setItem('coupons', JSON.stringify(coupons)); - }, [coupons]); - - useEffect(() => { - if (cart.length > 0) { - localStorage.setItem('cart', JSON.stringify(cart)); - } else { - localStorage.removeItem('cart'); - } - }, [cart]); - - useEffect(() => { - const timer = setTimeout(() => { - setDebouncedSearchTerm(searchTerm); - }, 500); - return () => clearTimeout(timer); - }, [searchTerm]); - - const addToCart = useCallback((product: ProductWithUI) => { - const remainingStock = getRemainingStock(product); - if (remainingStock <= 0) { - addNotification('재고가 부족합니다!', 'error'); - return; - } - - setCart(prevCart => { - const existingItem = prevCart.find(item => item.product.id === product.id); - - if (existingItem) { - const newQuantity = existingItem.quantity + 1; - - if (newQuantity > product.stock) { - addNotification(`재고는 ${product.stock}개까지만 있습니다.`, 'error'); - return prevCart; - } - - return prevCart.map(item => - item.product.id === product.id - ? { ...item, quantity: newQuantity } - : item - ); - } - - return [...prevCart, { product, quantity: 1 }]; - }); - - addNotification('장바구니에 담았습니다', 'success'); - }, [cart, addNotification, getRemainingStock]); - - const removeFromCart = useCallback((productId: string) => { - setCart(prevCart => prevCart.filter(item => item.product.id !== productId)); - }, []); - - const updateQuantity = useCallback((productId: string, newQuantity: number) => { - if (newQuantity <= 0) { - removeFromCart(productId); - return; - } - - const product = products.find(p => p.id === productId); - if (!product) return; - - const maxStock = product.stock; - if (newQuantity > maxStock) { - addNotification(`재고는 ${maxStock}개까지만 있습니다.`, 'error'); - return; - } - - setCart(prevCart => - prevCart.map(item => - item.product.id === productId - ? { ...item, quantity: newQuantity } - : item - ) - ); - }, [products, removeFromCart, addNotification, getRemainingStock]); - - const applyCoupon = useCallback((coupon: Coupon) => { - const currentTotal = calculateCartTotal().totalAfterDiscount; - - if (currentTotal < 10000 && coupon.discountType === 'percentage') { - addNotification('percentage 쿠폰은 10,000원 이상 구매 시 사용 가능합니다.', 'error'); - return; - } - - setSelectedCoupon(coupon); - addNotification('쿠폰이 적용되었습니다.', 'success'); - }, [addNotification, calculateCartTotal]); - - const completeOrder = useCallback(() => { - const orderNumber = `ORD-${Date.now()}`; - addNotification(`주문이 완료되었습니다. 주문번호: ${orderNumber}`, 'success'); - setCart([]); - setSelectedCoupon(null); - }, [addNotification]); - - const addProduct = useCallback((newProduct: Omit) => { - const product: ProductWithUI = { - ...newProduct, - id: `p${Date.now()}` - }; - setProducts(prev => [...prev, product]); - addNotification('상품이 추가되었습니다.', 'success'); - }, [addNotification]); - - const updateProduct = useCallback((productId: string, updates: Partial) => { - setProducts(prev => - prev.map(product => - product.id === productId - ? { ...product, ...updates } - : product - ) - ); - addNotification('상품이 수정되었습니다.', 'success'); - }, [addNotification]); - - const deleteProduct = useCallback((productId: string) => { - setProducts(prev => prev.filter(p => p.id !== productId)); - addNotification('상품이 삭제되었습니다.', 'success'); - }, [addNotification]); - - const addCoupon = useCallback((newCoupon: Coupon) => { - const existingCoupon = coupons.find(c => c.code === newCoupon.code); - if (existingCoupon) { - addNotification('이미 존재하는 쿠폰 코드입니다.', 'error'); - return; - } - setCoupons(prev => [...prev, newCoupon]); - addNotification('쿠폰이 추가되었습니다.', 'success'); - }, [coupons, addNotification]); - - const deleteCoupon = useCallback((couponCode: string) => { - setCoupons(prev => prev.filter(c => c.code !== couponCode)); - if (selectedCoupon?.code === couponCode) { - setSelectedCoupon(null); - } - addNotification('쿠폰이 삭제되었습니다.', 'success'); - }, [selectedCoupon, addNotification]); - - const handleProductSubmit = (e: React.FormEvent) => { - e.preventDefault(); - if (editingProduct && editingProduct !== 'new') { - updateProduct(editingProduct, productForm); - setEditingProduct(null); - } else { - addProduct({ - ...productForm, - discounts: productForm.discounts - }); - } - setProductForm({ name: '', price: 0, stock: 0, description: '', discounts: [] }); - setEditingProduct(null); - setShowProductForm(false); - }; - - const handleCouponSubmit = (e: React.FormEvent) => { - e.preventDefault(); - addCoupon(couponForm); - setCouponForm({ - name: '', - code: '', - discountType: 'amount', - discountValue: 0 - }); - setShowCouponForm(false); - }; - - const startEditProduct = (product: ProductWithUI) => { - setEditingProduct(product.id); - setProductForm({ - name: product.name, - price: product.price, - stock: product.stock, - description: product.description || '', - discounts: product.discounts || [] - }); - setShowProductForm(true); - }; - - const totals = calculateCartTotal(); - - const filteredProducts = debouncedSearchTerm - ? products.filter(product => - product.name.toLowerCase().includes(debouncedSearchTerm.toLowerCase()) || - (product.description && product.description.toLowerCase().includes(debouncedSearchTerm.toLowerCase())) - ) - : products; return (
- {notifications.length > 0 && ( -
- {notifications.map(notif => ( -
- {notif.message} - -
- ))} -
- )} -
-
-
-
-

SHOP

- {/* 검색창 - 안티패턴: 검색 로직이 컴포넌트에 직접 포함 */} - {!isAdmin && ( -
- setSearchTerm(e.target.value)} - placeholder="상품 검색..." - className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" - /> -
- )} + +
+
- -
-
-
- + ) + } + rightSide={ + + } + />
{isAdmin ? ( -
-
-

관리자 대시보드

-

상품과 쿠폰을 관리할 수 있습니다

-
-
- -
- - {activeTab === 'products' ? ( -
-
-
-

상품 목록

- -
-
- -
- - - - - - - - - - - - {(activeTab === 'products' ? products : products).map(product => ( - - - - - - - - ))} - -
상품명가격재고설명작업
{product.name}{formatPrice(product.price, product.id)} - 10 ? 'bg-green-100 text-green-800' : - product.stock > 0 ? 'bg-yellow-100 text-yellow-800' : - 'bg-red-100 text-red-800' - }`}> - {product.stock}개 - - {product.description || '-'} - - -
-
- {showProductForm && ( -
-
-

- {editingProduct === 'new' ? '새 상품 추가' : '상품 수정'} -

-
-
- - setProductForm({ ...productForm, name: e.target.value })} - className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border" - required - /> -
-
- - setProductForm({ ...productForm, description: e.target.value })} - className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border" - /> -
-
- - { - const value = e.target.value; - if (value === '' || /^\d+$/.test(value)) { - setProductForm({ ...productForm, price: value === '' ? 0 : parseInt(value) }); - } - }} - onBlur={(e) => { - const value = e.target.value; - if (value === '') { - setProductForm({ ...productForm, price: 0 }); - } else if (parseInt(value) < 0) { - addNotification('가격은 0보다 커야 합니다', 'error'); - setProductForm({ ...productForm, price: 0 }); - } - }} - className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border" - placeholder="숫자만 입력" - required - /> -
-
- - { - const value = e.target.value; - if (value === '' || /^\d+$/.test(value)) { - setProductForm({ ...productForm, stock: value === '' ? 0 : parseInt(value) }); - } - }} - onBlur={(e) => { - const value = e.target.value; - if (value === '') { - setProductForm({ ...productForm, stock: 0 }); - } else if (parseInt(value) < 0) { - addNotification('재고는 0보다 커야 합니다', 'error'); - setProductForm({ ...productForm, stock: 0 }); - } else if (parseInt(value) > 9999) { - addNotification('재고는 9999개를 초과할 수 없습니다', 'error'); - setProductForm({ ...productForm, stock: 9999 }); - } - }} - className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border" - placeholder="숫자만 입력" - required - /> -
-
-
- -
- {productForm.discounts.map((discount, index) => ( -
- { - const newDiscounts = [...productForm.discounts]; - newDiscounts[index].quantity = parseInt(e.target.value) || 0; - setProductForm({ ...productForm, discounts: newDiscounts }); - }} - className="w-20 px-2 py-1 border rounded" - min="1" - placeholder="수량" - /> - 개 이상 구매 시 - { - const newDiscounts = [...productForm.discounts]; - newDiscounts[index].rate = (parseInt(e.target.value) || 0) / 100; - setProductForm({ ...productForm, discounts: newDiscounts }); - }} - className="w-16 px-2 py-1 border rounded" - min="0" - max="100" - placeholder="%" - /> - % 할인 - -
- ))} - -
-
- -
- - -
-
-
- )} -
- ) : ( -
-
-

쿠폰 관리

-
-
-
- {coupons.map(coupon => ( -
-
-
-

{coupon.name}

-

{coupon.code}

-
- - {coupon.discountType === 'amount' - ? `${coupon.discountValue.toLocaleString()}원 할인` - : `${coupon.discountValue}% 할인`} - -
-
- -
-
- ))} - -
- -
-
- - {showCouponForm && ( -
-
-

새 쿠폰 생성

-
-
- - setCouponForm({ ...couponForm, name: e.target.value })} - className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border text-sm" - placeholder="신규 가입 쿠폰" - required - /> -
-
- - setCouponForm({ ...couponForm, code: e.target.value.toUpperCase() })} - className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border text-sm font-mono" - placeholder="WELCOME2024" - required - /> -
-
- - -
-
- - { - const value = e.target.value; - if (value === '' || /^\d+$/.test(value)) { - setCouponForm({ ...couponForm, discountValue: value === '' ? 0 : parseInt(value) }); - } - }} - onBlur={(e) => { - const value = parseInt(e.target.value) || 0; - if (couponForm.discountType === 'percentage') { - if (value > 100) { - addNotification('할인율은 100%를 초과할 수 없습니다', 'error'); - setCouponForm({ ...couponForm, discountValue: 100 }); - } else if (value < 0) { - setCouponForm({ ...couponForm, discountValue: 0 }); - } - } else { - if (value > 100000) { - addNotification('할인 금액은 100,000원을 초과할 수 없습니다', 'error'); - setCouponForm({ ...couponForm, discountValue: 100000 }); - } else if (value < 0) { - setCouponForm({ ...couponForm, discountValue: 0 }); - } - } - }} - className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border text-sm" - placeholder={couponForm.discountType === 'amount' ? '5000' : '10'} - required - /> -
-
-
- - -
-
-
- )} -
-
- )} -
+ ) : ( -
-
- {/* 상품 목록 */} -
-
-

전체 상품

-
- 총 {products.length}개 상품 -
-
- {filteredProducts.length === 0 ? ( -
-

"{debouncedSearchTerm}"에 대한 검색 결과가 없습니다.

-
- ) : ( -
- {filteredProducts.map(product => { - const remainingStock = getRemainingStock(product); - - return ( -
- {/* 상품 이미지 영역 (placeholder) */} -
-
- - - -
- {product.isRecommended && ( - - BEST - - )} - {product.discounts.length > 0 && ( - - ~{Math.max(...product.discounts.map(d => d.rate)) * 100}% - - )} -
- - {/* 상품 정보 */} -
-

{product.name}

- {product.description && ( -

{product.description}

- )} - - {/* 가격 정보 */} -
-

{formatPrice(product.price, product.id)}

- {product.discounts.length > 0 && ( -

- {product.discounts[0].quantity}개 이상 구매시 할인 {product.discounts[0].rate * 100}% -

- )} -
- - {/* 재고 상태 */} -
- {remainingStock <= 5 && remainingStock > 0 && ( -

품절임박! {remainingStock}개 남음

- )} - {remainingStock > 5 && ( -

재고 {remainingStock}개

- )} -
- - {/* 장바구니 버튼 */} - -
-
- ); - })} -
- )} -
-
- -
-
-
-

- - - - 장바구니 -

- {cart.length === 0 ? ( -
- - - -

장바구니가 비어있습니다

-
- ) : ( -
- {cart.map(item => { - const itemTotal = calculateItemTotal(item); - const originalPrice = item.product.price * item.quantity; - const hasDiscount = itemTotal < originalPrice; - const discountRate = hasDiscount ? Math.round((1 - itemTotal / originalPrice) * 100) : 0; - - return ( -
-
-

{item.product.name}

- -
-
-
- - {item.quantity} - -
-
- {hasDiscount && ( - -{discountRate}% - )} -

- {Math.round(itemTotal).toLocaleString()}원 -

-
-
-
- ); - })} -
- )} -
- - {cart.length > 0 && ( - <> -
-
-

쿠폰 할인

- -
- {coupons.length > 0 && ( - - )} -
- -
-

결제 정보

-
-
- 상품 금액 - {totals.totalBeforeDiscount.toLocaleString()}원 -
- {totals.totalBeforeDiscount - totals.totalAfterDiscount > 0 && ( -
- 할인 금액 - -{(totals.totalBeforeDiscount - totals.totalAfterDiscount).toLocaleString()}원 -
- )} -
- 결제 예정 금액 - {totals.totalAfterDiscount.toLocaleString()}원 -
-
- - - -
-

* 실제 결제는 이루어지지 않습니다

-
-
- - )} -
-
-
+ )}
); }; -export default App; \ No newline at end of file +export default App; diff --git a/src/advanced/__tests__/origin.test.tsx b/src/advanced/__tests__/origin.test.tsx index 3f5c3d55e..19998b6aa 100644 --- a/src/advanced/__tests__/origin.test.tsx +++ b/src/advanced/__tests__/origin.test.tsx @@ -1,528 +1,573 @@ // @ts-nocheck -import { render, screen, fireEvent, within, waitFor } from '@testing-library/react'; -import { vi } from 'vitest'; -import App from '../App'; -import '../../setupTests'; +import { + render, + screen, + fireEvent, + within, + waitFor, +} from "@testing-library/react"; +import { vi } from "vitest"; +import App from "../App"; +import "../../setupTests"; +import { Provider } from "jotai"; -describe('쇼핑몰 앱 통합 테스트', () => { +const renderWithProvider = (ui: React.ReactElement) => { + return render({ui}); +}; + +describe("쇼핑몰 앱 통합 테스트", () => { beforeEach(() => { // localStorage 초기화 localStorage.clear(); // console 경고 무시 - vi.spyOn(console, 'warn').mockImplementation(() => {}); - vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(console, "warn").mockImplementation(() => {}); + vi.spyOn(console, "log").mockImplementation(() => {}); }); afterEach(() => { vi.restoreAllMocks(); }); - describe('고객 쇼핑 플로우', () => { - test('상품을 검색하고 장바구니에 추가할 수 있다', async () => { + describe("고객 쇼핑 플로우", () => { + test("상품을 검색하고 장바구니에 추가할 수 있다", async () => { render(); - + // 검색창에 "프리미엄" 입력 - const searchInput = screen.getByPlaceholderText('상품 검색...'); - fireEvent.change(searchInput, { target: { value: '프리미엄' } }); - + const searchInput = screen.getByPlaceholderText("상품 검색..."); + fireEvent.change(searchInput, { target: { value: "프리미엄" } }); + // 디바운스 대기 - await waitFor(() => { - expect(screen.getByText('최고급 품질의 프리미엄 상품입니다.')).toBeInTheDocument(); - }, { timeout: 600 }); - + await waitFor( + () => { + expect( + screen.getByText("최고급 품질의 프리미엄 상품입니다.") + ).toBeInTheDocument(); + }, + { timeout: 600 } + ); + // 검색된 상품을 장바구니에 추가 (첫 번째 버튼 선택) - const addButtons = screen.getAllByText('장바구니 담기'); + const addButtons = screen.getAllByText("장바구니 담기"); fireEvent.click(addButtons[0]); - + // 알림 메시지 확인 await waitFor(() => { - expect(screen.getByText('장바구니에 담았습니다')).toBeInTheDocument(); + expect(screen.getByText("장바구니에 담았습니다")).toBeInTheDocument(); }); - + // 장바구니에 추가됨 확인 (장바구니 섹션에서) - const cartSection = screen.getByText('장바구니').closest('section'); - expect(within(cartSection).getByText('상품1')).toBeInTheDocument(); + const cartSection = screen.getByText("장바구니").closest("section"); + expect(within(cartSection).getByText("상품1")).toBeInTheDocument(); }); - test('장바구니에서 수량을 조절하고 할인을 확인할 수 있다', () => { + test("장바구니에서 수량을 조절하고 할인을 확인할 수 있다", () => { render(); - + // 상품1을 장바구니에 추가 - const product1 = screen.getAllByText('장바구니 담기')[0]; + const product1 = screen.getAllByText("장바구니 담기")[0]; fireEvent.click(product1); - + // 수량을 10개로 증가 (10% 할인 적용) - const cartSection = screen.getByText('장바구니').closest('section'); - const plusButton = within(cartSection).getByText('+'); - + const cartSection = screen.getByText("장바구니").closest("section"); + const plusButton = within(cartSection).getByText("+"); + for (let i = 0; i < 9; i++) { fireEvent.click(plusButton); } - + // 10% 할인 적용 확인 - 15% (대량 구매 시 추가 5% 포함) - expect(screen.getByText('-15%')).toBeInTheDocument(); + expect(screen.getByText("-15%")).toBeInTheDocument(); }); - test('쿠폰을 선택하고 적용할 수 있다', () => { + test("쿠폰을 선택하고 적용할 수 있다", () => { render(); - + // 상품 추가 - const addButton = screen.getAllByText('장바구니 담기')[0]; + const addButton = screen.getAllByText("장바구니 담기")[0]; fireEvent.click(addButton); - + // 쿠폰 선택 - const couponSelect = screen.getByRole('combobox'); - fireEvent.change(couponSelect, { target: { value: 'AMOUNT5000' } }); - + const couponSelect = screen.getByRole("combobox"); + fireEvent.change(couponSelect, { target: { value: "AMOUNT5000" } }); + // 결제 정보에서 할인 금액 확인 - const paymentSection = screen.getByText('결제 정보').closest('section'); - const discountRow = within(paymentSection).getByText('할인 금액').closest('div'); - expect(within(discountRow).getByText('-5,000원')).toBeInTheDocument(); + const paymentSection = screen.getByText("결제 정보").closest("section"); + const discountRow = within(paymentSection) + .getByText("할인 금액") + .closest("div"); + expect(within(discountRow).getByText("-5,000원")).toBeInTheDocument(); }); - test('품절 임박 상품에 경고가 표시된다', async () => { + test("품절 임박 상품에 경고가 표시된다", async () => { render(); - + // 관리자 모드로 전환 - fireEvent.click(screen.getByText('관리자 페이지로')); - + fireEvent.click(screen.getByText("관리자 페이지로")); + // 상품 수정 - const editButton = screen.getAllByText('수정')[0]; + const editButton = screen.getAllByText("수정")[0]; fireEvent.click(editButton); - + // 재고를 5개로 변경 - const stockInputs = screen.getAllByPlaceholderText('숫자만 입력'); + const stockInputs = screen.getAllByPlaceholderText("숫자만 입력"); const stockInput = stockInputs[1]; // 재고 입력 필드는 두 번째 - fireEvent.change(stockInput, { target: { value: '5' } }); + fireEvent.change(stockInput, { target: { value: "5" } }); fireEvent.blur(stockInput); - + // 수정 완료 버튼 클릭 - const editButtons = screen.getAllByText('수정'); + const editButtons = screen.getAllByText("수정"); const completeEditButton = editButtons[editButtons.length - 1]; // 마지막 수정 버튼 (완료 버튼) fireEvent.click(completeEditButton); - + // 쇼핑몰로 돌아가기 - fireEvent.click(screen.getByText('쇼핑몰로 돌아가기')); - + fireEvent.click(screen.getByText("쇼핑몰로 돌아가기")); + // 품절임박 메시지 확인 - 재고가 5개 이하면 품절임박 표시 await waitFor(() => { - expect(screen.getByText('품절임박! 5개 남음')).toBeInTheDocument(); + expect(screen.getByText("품절임박! 5개 남음")).toBeInTheDocument(); }); }); - test('주문을 완료할 수 있다', () => { + test("주문을 완료할 수 있다", () => { render(); - + // 상품 추가 - fireEvent.click(screen.getAllByText('장바구니 담기')[0]); - + fireEvent.click(screen.getAllByText("장바구니 담기")[0]); + // 결제하기 버튼 클릭 const orderButton = screen.getByText(/원 결제하기/); fireEvent.click(orderButton); - + // 주문 완료 알림 확인 expect(screen.getByText(/주문이 완료되었습니다/)).toBeInTheDocument(); - + // 장바구니가 비어있는지 확인 - expect(screen.getByText('장바구니가 비어있습니다')).toBeInTheDocument(); + expect(screen.getByText("장바구니가 비어있습니다")).toBeInTheDocument(); }); - test('장바구니에서 상품을 삭제할 수 있다', () => { + test("장바구니에서 상품을 삭제할 수 있다", () => { render(); - + // 상품 2개 추가 - fireEvent.click(screen.getAllByText('장바구니 담기')[0]); - fireEvent.click(screen.getAllByText('장바구니 담기')[1]); - + fireEvent.click(screen.getAllByText("장바구니 담기")[0]); + fireEvent.click(screen.getAllByText("장바구니 담기")[1]); + // 장바구니 섹션 확인 - const cartSection = screen.getByText('장바구니').closest('section'); - expect(within(cartSection).getByText('상품1')).toBeInTheDocument(); - expect(within(cartSection).getByText('상품2')).toBeInTheDocument(); - + const cartSection = screen.getByText("장바구니").closest("section"); + expect(within(cartSection).getByText("상품1")).toBeInTheDocument(); + expect(within(cartSection).getByText("상품2")).toBeInTheDocument(); + // 첫 번째 상품 삭제 (X 버튼) - const deleteButtons = within(cartSection).getAllByRole('button').filter( - button => button.querySelector('svg') - ); + const deleteButtons = within(cartSection) + .getAllByRole("button") + .filter((button) => button.querySelector("svg")); fireEvent.click(deleteButtons[0]); - + // 상품1이 삭제되고 상품2만 남음 - expect(within(cartSection).queryByText('상품1')).not.toBeInTheDocument(); - expect(within(cartSection).getByText('상품2')).toBeInTheDocument(); + expect(within(cartSection).queryByText("상품1")).not.toBeInTheDocument(); + expect(within(cartSection).getByText("상품2")).toBeInTheDocument(); }); - test('재고를 초과하여 구매할 수 없다', async () => { + test("재고를 초과하여 구매할 수 없다", async () => { render(); - + // 상품1 장바구니에 추가 - fireEvent.click(screen.getAllByText('장바구니 담기')[0]); - + fireEvent.click(screen.getAllByText("장바구니 담기")[0]); + // 수량을 재고(20개) 이상으로 증가 시도 - const cartSection = screen.getByText('장바구니').closest('section'); - const plusButton = within(cartSection).getByText('+'); - + const cartSection = screen.getByText("장바구니").closest("section"); + const plusButton = within(cartSection).getByText("+"); + // 19번 클릭하여 총 20개로 만듦 for (let i = 0; i < 19; i++) { fireEvent.click(plusButton); } - + // 한 번 더 클릭 시도 (21개가 되려고 함) fireEvent.click(plusButton); - + // 수량이 20개에서 멈춰있어야 함 - expect(within(cartSection).getByText('20')).toBeInTheDocument(); - + expect(within(cartSection).getByText("20")).toBeInTheDocument(); + // 재고 부족 메시지 확인 await waitFor(() => { - expect(screen.getByText(/재고는.*개까지만 있습니다/)).toBeInTheDocument(); + expect( + screen.getByText(/재고는.*개까지만 있습니다/) + ).toBeInTheDocument(); }); }); - test('장바구니에서 수량을 감소시킬 수 있다', () => { + test("장바구니에서 수량을 감소시킬 수 있다", () => { render(); - + // 상품 추가 - fireEvent.click(screen.getAllByText('장바구니 담기')[0]); - - const cartSection = screen.getByText('장바구니').closest('section'); - const plusButton = within(cartSection).getByText('+'); - const minusButton = within(cartSection).getByText('−'); // U+2212 마이너스 기호 - + fireEvent.click(screen.getAllByText("장바구니 담기")[0]); + + const cartSection = screen.getByText("장바구니").closest("section"); + const plusButton = within(cartSection).getByText("+"); + const minusButton = within(cartSection).getByText("−"); // U+2212 마이너스 기호 + // 수량 3개로 증가 fireEvent.click(plusButton); fireEvent.click(plusButton); - expect(within(cartSection).getByText('3')).toBeInTheDocument(); - + expect(within(cartSection).getByText("3")).toBeInTheDocument(); + // 수량 감소 fireEvent.click(minusButton); - expect(within(cartSection).getByText('2')).toBeInTheDocument(); - + expect(within(cartSection).getByText("2")).toBeInTheDocument(); + // 1개로 더 감소 fireEvent.click(minusButton); - expect(within(cartSection).getByText('1')).toBeInTheDocument(); - + expect(within(cartSection).getByText("1")).toBeInTheDocument(); + // 1개에서 한 번 더 감소하면 장바구니에서 제거될 수도 있음 fireEvent.click(minusButton); // 장바구니가 비었는지 확인 - const emptyMessage = screen.queryByText('장바구니가 비어있습니다'); + const emptyMessage = screen.queryByText("장바구니가 비어있습니다"); if (emptyMessage) { expect(emptyMessage).toBeInTheDocument(); } else { // 또는 수량이 1에서 멈춤 - expect(within(cartSection).getByText('1')).toBeInTheDocument(); + expect(within(cartSection).getByText("1")).toBeInTheDocument(); } }); - test('20개 이상 구매 시 최대 할인이 적용된다', async () => { + test("20개 이상 구매 시 최대 할인이 적용된다", async () => { render(); - + // 관리자 모드로 전환하여 상품1의 재고를 늘림 - fireEvent.click(screen.getByText('관리자 페이지로')); - fireEvent.click(screen.getAllByText('수정')[0]); - - const stockInput = screen.getAllByPlaceholderText('숫자만 입력')[1]; - fireEvent.change(stockInput, { target: { value: '30' } }); - - const editButtons = screen.getAllByText('수정'); + fireEvent.click(screen.getByText("관리자 페이지로")); + fireEvent.click(screen.getAllByText("수정")[0]); + + const stockInput = screen.getAllByPlaceholderText("숫자만 입력")[1]; + fireEvent.change(stockInput, { target: { value: "30" } }); + + const editButtons = screen.getAllByText("수정"); fireEvent.click(editButtons[editButtons.length - 1]); - + // 쇼핑몰로 돌아가기 - fireEvent.click(screen.getByText('쇼핑몰로 돌아가기')); - + fireEvent.click(screen.getByText("쇼핑몰로 돌아가기")); + // 상품1을 장바구니에 추가 - fireEvent.click(screen.getAllByText('장바구니 담기')[0]); - + fireEvent.click(screen.getAllByText("장바구니 담기")[0]); + // 수량을 20개로 증가 - const cartSection = screen.getByText('장바구니').closest('section'); - const plusButton = within(cartSection).getByText('+'); - + const cartSection = screen.getByText("장바구니").closest("section"); + const plusButton = within(cartSection).getByText("+"); + for (let i = 0; i < 19; i++) { fireEvent.click(plusButton); } - + // 25% 할인 적용 확인 (또는 대량 구매 시 30%) await waitFor(() => { - const discount25 = screen.queryByText('-25%'); - const discount30 = screen.queryByText('-30%'); + const discount25 = screen.queryByText("-25%"); + const discount30 = screen.queryByText("-30%"); expect(discount25 || discount30).toBeTruthy(); }); }); }); - describe('관리자 기능', () => { + describe("관리자 기능", () => { beforeEach(() => { render(); // 관리자 모드로 전환 - fireEvent.click(screen.getByText('관리자 페이지로')); + fireEvent.click(screen.getByText("관리자 페이지로")); }); - test('새 상품을 추가할 수 있다', () => { + test("새 상품을 추가할 수 있다", () => { // 새 상품 추가 버튼 클릭 - fireEvent.click(screen.getByText('새 상품 추가')); - + fireEvent.click(screen.getByText("새 상품 추가")); + // 폼 입력 - 상품명 입력 - const labels = screen.getAllByText('상품명'); - const nameLabel = labels.find(el => el.tagName === 'LABEL'); - const nameInput = nameLabel.closest('div').querySelector('input'); - fireEvent.change(nameInput, { target: { value: '테스트 상품' } }); - - const priceInput = screen.getAllByPlaceholderText('숫자만 입력')[0]; - fireEvent.change(priceInput, { target: { value: '25000' } }); - - const stockInput = screen.getAllByPlaceholderText('숫자만 입력')[1]; - fireEvent.change(stockInput, { target: { value: '50' } }); - - const descLabels = screen.getAllByText('설명'); - const descLabel = descLabels.find(el => el.tagName === 'LABEL'); - const descInput = descLabel.closest('div').querySelector('input'); - fireEvent.change(descInput, { target: { value: '테스트 설명' } }); - + const labels = screen.getAllByText("상품명"); + const nameLabel = labels.find((el) => el.tagName === "LABEL"); + const nameInput = nameLabel.closest("div").querySelector("input"); + fireEvent.change(nameInput, { target: { value: "테스트 상품" } }); + + const priceInput = screen.getAllByPlaceholderText("숫자만 입력")[0]; + fireEvent.change(priceInput, { target: { value: "25000" } }); + + const stockInput = screen.getAllByPlaceholderText("숫자만 입력")[1]; + fireEvent.change(stockInput, { target: { value: "50" } }); + + const descLabels = screen.getAllByText("설명"); + const descLabel = descLabels.find((el) => el.tagName === "LABEL"); + const descInput = descLabel.closest("div").querySelector("input"); + fireEvent.change(descInput, { target: { value: "테스트 설명" } }); + // 저장 - fireEvent.click(screen.getByText('추가')); - + fireEvent.click(screen.getByText("추가")); + // 추가된 상품 확인 - expect(screen.getByText('테스트 상품')).toBeInTheDocument(); - expect(screen.getByText('25,000원')).toBeInTheDocument(); + expect(screen.getByText("테스트 상품")).toBeInTheDocument(); + expect(screen.getByText("25,000원")).toBeInTheDocument(); }); - test('쿠폰 탭으로 전환하고 새 쿠폰을 추가할 수 있다', () => { + test("쿠폰 탭으로 전환하고 새 쿠폰을 추가할 수 있다", () => { // 쿠폰 관리 탭으로 전환 - fireEvent.click(screen.getByText('쿠폰 관리')); - + fireEvent.click(screen.getByText("쿠폰 관리")); + // 새 쿠폰 추가 버튼 클릭 - const addCouponButton = screen.getByText('새 쿠폰 추가'); + const addCouponButton = screen.getByText("새 쿠폰 추가"); fireEvent.click(addCouponButton); - + // 쿠폰 정보 입력 - fireEvent.change(screen.getByPlaceholderText('신규 가입 쿠폰'), { target: { value: '테스트 쿠폰' } }); - fireEvent.change(screen.getByPlaceholderText('WELCOME2024'), { target: { value: 'TEST2024' } }); - - const discountInput = screen.getByPlaceholderText('5000'); - fireEvent.change(discountInput, { target: { value: '7000' } }); - + fireEvent.change(screen.getByPlaceholderText("신규 가입 쿠폰"), { + target: { value: "테스트 쿠폰" }, + }); + fireEvent.change(screen.getByPlaceholderText("WELCOME2024"), { + target: { value: "TEST2024" }, + }); + + const discountInput = screen.getByPlaceholderText("5000"); + fireEvent.change(discountInput, { target: { value: "7000" } }); + // 쿠폰 생성 - fireEvent.click(screen.getByText('쿠폰 생성')); - + fireEvent.click(screen.getByText("쿠폰 생성")); + // 생성된 쿠폰 확인 - expect(screen.getByText('테스트 쿠폰')).toBeInTheDocument(); - expect(screen.getByText('TEST2024')).toBeInTheDocument(); - expect(screen.getByText('7,000원 할인')).toBeInTheDocument(); + expect(screen.getByText("테스트 쿠폰")).toBeInTheDocument(); + expect(screen.getByText("TEST2024")).toBeInTheDocument(); + expect(screen.getByText("7,000원 할인")).toBeInTheDocument(); }); - test('상품의 가격 입력 시 숫자만 허용된다', async () => { + test("상품의 가격 입력 시 숫자만 허용된다", async () => { // 상품 수정 - fireEvent.click(screen.getAllByText('수정')[0]); - - const priceInput = screen.getAllByPlaceholderText('숫자만 입력')[0]; - + fireEvent.click(screen.getAllByText("수정")[0]); + + const priceInput = screen.getAllByPlaceholderText("숫자만 입력")[0]; + // 문자와 숫자 혼합 입력 시도 - 숫자만 남음 - fireEvent.change(priceInput, { target: { value: 'abc123def' } }); - expect(priceInput.value).toBe('10000'); // 유효하지 않은 입력은 무시됨 - + fireEvent.change(priceInput, { target: { value: "abc123def" } }); + expect(priceInput.value).toBe("10000"); // 유효하지 않은 입력은 무시됨 + // 숫자만 입력 - fireEvent.change(priceInput, { target: { value: '123' } }); - expect(priceInput.value).toBe('123'); - + fireEvent.change(priceInput, { target: { value: "123" } }); + expect(priceInput.value).toBe("123"); + // 음수 입력 시도 - regex가 매치되지 않아 값이 변경되지 않음 - fireEvent.change(priceInput, { target: { value: '-100' } }); - expect(priceInput.value).toBe('123'); // 이전 값 유지 - + fireEvent.change(priceInput, { target: { value: "-100" } }); + expect(priceInput.value).toBe("123"); // 이전 값 유지 + // 유효한 음수 입력하기 위해 먼저 1 입력 후 앞에 - 추가는 불가능 // 대신 blur 이벤트를 통해 음수 검증을 테스트 // parseInt()는 실제로 음수를 파싱할 수 있으므로 다른 방법으로 테스트 - + // 공백 입력 시도 - fireEvent.change(priceInput, { target: { value: ' ' } }); - expect(priceInput.value).toBe('123'); // 유효하지 않은 입력은 무시됨 + fireEvent.change(priceInput, { target: { value: " " } }); + expect(priceInput.value).toBe("123"); // 유효하지 않은 입력은 무시됨 }); - test('쿠폰 할인율 검증이 작동한다', async () => { + test("쿠폰 할인율 검증이 작동한다", async () => { // 쿠폰 관리 탭으로 전환 - fireEvent.click(screen.getByText('쿠폰 관리')); - + fireEvent.click(screen.getByText("쿠폰 관리")); + // 새 쿠폰 추가 - fireEvent.click(screen.getByText('새 쿠폰 추가')); - + fireEvent.click(screen.getByText("새 쿠폰 추가")); + // 퍼센트 타입으로 변경 - 쿠폰 폼 내의 select 찾기 - const couponFormSelects = screen.getAllByRole('combobox'); + const couponFormSelects = screen.getAllByRole("combobox"); const typeSelect = couponFormSelects[couponFormSelects.length - 1]; // 마지막 select가 타입 선택 - fireEvent.change(typeSelect, { target: { value: 'percentage' } }); - + fireEvent.change(typeSelect, { target: { value: "percentage" } }); + // 100% 초과 할인율 입력 - const discountInput = screen.getByPlaceholderText('10'); - fireEvent.change(discountInput, { target: { value: '150' } }); + const discountInput = screen.getByPlaceholderText("10"); + fireEvent.change(discountInput, { target: { value: "150" } }); fireEvent.blur(discountInput); - + // 에러 메시지 확인 await waitFor(() => { - expect(screen.getByText('할인율은 100%를 초과할 수 없습니다')).toBeInTheDocument(); + expect( + screen.getByText("할인율은 100%를 초과할 수 없습니다") + ).toBeInTheDocument(); }); }); - test('상품을 삭제할 수 있다', () => { + test("상품을 삭제할 수 있다", () => { // 초기 상품명들 확인 (테이블에서) - const productTable = screen.getByRole('table'); - expect(within(productTable).getByText('상품1')).toBeInTheDocument(); - + const productTable = screen.getByRole("table"); + expect(within(productTable).getByText("상품1")).toBeInTheDocument(); + // 삭제 버튼들 찾기 - const deleteButtons = within(productTable).getAllByRole('button').filter( - button => button.textContent === '삭제' - ); - + const deleteButtons = within(productTable) + .getAllByRole("button") + .filter((button) => button.textContent === "삭제"); + // 첫 번째 상품 삭제 fireEvent.click(deleteButtons[0]); - + // 상품1이 삭제되었는지 확인 - expect(within(productTable).queryByText('상품1')).not.toBeInTheDocument(); - expect(within(productTable).getByText('상품2')).toBeInTheDocument(); + expect(within(productTable).queryByText("상품1")).not.toBeInTheDocument(); + expect(within(productTable).getByText("상품2")).toBeInTheDocument(); }); - test('쿠폰을 삭제할 수 있다', () => { + test("쿠폰을 삭제할 수 있다", () => { // 쿠폰 관리 탭으로 전환 - fireEvent.click(screen.getByText('쿠폰 관리')); - + fireEvent.click(screen.getByText("쿠폰 관리")); + // 초기 쿠폰들 확인 (h3 제목에서) - const couponTitles = screen.getAllByRole('heading', { level: 3 }); - const coupon5000 = couponTitles.find(el => el.textContent === '5000원 할인'); - const coupon10 = couponTitles.find(el => el.textContent === '10% 할인'); + const couponTitles = screen.getAllByRole("heading", { level: 3 }); + const coupon5000 = couponTitles.find( + (el) => el.textContent === "5000원 할인" + ); + const coupon10 = couponTitles.find((el) => el.textContent === "10% 할인"); expect(coupon5000).toBeInTheDocument(); expect(coupon10).toBeInTheDocument(); - + // 삭제 버튼 찾기 (SVG 아이콘을 포함한 버튼) - const deleteButtons = screen.getAllByRole('button').filter(button => { - return button.querySelector('svg') && - button.querySelector('path[d*="M19 7l"]'); // 삭제 아이콘 path + const deleteButtons = screen.getAllByRole("button").filter((button) => { + return ( + button.querySelector("svg") && + button.querySelector('path[d*="M19 7l"]') + ); // 삭제 아이콘 path }); - + // 첫 번째 쿠폰 삭제 fireEvent.click(deleteButtons[0]); - + // 쿠폰이 삭제되었는지 확인 - expect(screen.queryByText('5000원 할인')).not.toBeInTheDocument(); + expect(screen.queryByText("5000원 할인")).not.toBeInTheDocument(); }); - }); - describe('로컬스토리지 동기화', () => { - test('상품, 장바구니, 쿠폰이 localStorage에 저장된다', () => { + describe("로컬스토리지 동기화", () => { + test("상품, 장바구니, 쿠폰이 localStorage에 저장된다", () => { render(); - + // 상품을 장바구니에 추가 - fireEvent.click(screen.getAllByText('장바구니 담기')[0]); - + fireEvent.click(screen.getAllByText("장바구니 담기")[0]); + // localStorage 확인 - expect(localStorage.getItem('cart')).toBeTruthy(); - expect(JSON.parse(localStorage.getItem('cart'))).toHaveLength(1); - + expect(localStorage.getItem("cart")).toBeTruthy(); + expect(JSON.parse(localStorage.getItem("cart"))).toHaveLength(1); + // 관리자 모드로 전환하여 새 상품 추가 - fireEvent.click(screen.getByText('관리자 페이지로')); - fireEvent.click(screen.getByText('새 상품 추가')); - - const labels = screen.getAllByText('상품명'); - const nameLabel = labels.find(el => el.tagName === 'LABEL'); - const nameInput = nameLabel.closest('div').querySelector('input'); - fireEvent.change(nameInput, { target: { value: '저장 테스트' } }); - - const priceInput = screen.getAllByPlaceholderText('숫자만 입력')[0]; - fireEvent.change(priceInput, { target: { value: '10000' } }); - - const stockInput = screen.getAllByPlaceholderText('숫자만 입력')[1]; - fireEvent.change(stockInput, { target: { value: '10' } }); - - fireEvent.click(screen.getByText('추가')); - + fireEvent.click(screen.getByText("관리자 페이지로")); + fireEvent.click(screen.getByText("새 상품 추가")); + + const labels = screen.getAllByText("상품명"); + const nameLabel = labels.find((el) => el.tagName === "LABEL"); + const nameInput = nameLabel.closest("div").querySelector("input"); + fireEvent.change(nameInput, { target: { value: "저장 테스트" } }); + + const priceInput = screen.getAllByPlaceholderText("숫자만 입력")[0]; + fireEvent.change(priceInput, { target: { value: "10000" } }); + + const stockInput = screen.getAllByPlaceholderText("숫자만 입력")[1]; + fireEvent.change(stockInput, { target: { value: "10" } }); + + fireEvent.click(screen.getByText("추가")); + // localStorage에 products가 저장되었는지 확인 - expect(localStorage.getItem('products')).toBeTruthy(); - const products = JSON.parse(localStorage.getItem('products')); - expect(products.some(p => p.name === '저장 테스트')).toBe(true); + expect(localStorage.getItem("products")).toBeTruthy(); + const products = JSON.parse(localStorage.getItem("products")); + expect(products.some((p) => p.name === "저장 테스트")).toBe(true); }); - test('페이지 새로고침 후에도 데이터가 유지된다', () => { + test("페이지 새로고침 후에도 데이터가 유지된다", () => { const { unmount } = render(); - + // 장바구니에 상품 추가 - fireEvent.click(screen.getAllByText('장바구니 담기')[0]); - fireEvent.click(screen.getAllByText('장바구니 담기')[1]); - + fireEvent.click(screen.getAllByText("장바구니 담기")[0]); + fireEvent.click(screen.getAllByText("장바구니 담기")[1]); + // 컴포넌트 unmount unmount(); - + // 다시 mount render(); - + // 장바구니 아이템이 유지되는지 확인 - const cartSection = screen.getByText('장바구니').closest('section'); - expect(within(cartSection).getByText('상품1')).toBeInTheDocument(); - expect(within(cartSection).getByText('상품2')).toBeInTheDocument(); + const cartSection = screen.getByText("장바구니").closest("section"); + expect(within(cartSection).getByText("상품1")).toBeInTheDocument(); + expect(within(cartSection).getByText("상품2")).toBeInTheDocument(); }); }); - describe('UI 상태 관리', () => { - test('할인이 있을 때 할인율이 표시된다', async () => { + describe("UI 상태 관리", () => { + test("할인이 있을 때 할인율이 표시된다", async () => { render(); - + // 상품을 10개 담아서 할인 발생 - const addButton = screen.getAllByText('장바구니 담기')[0]; + const addButton = screen.getAllByText("장바구니 담기")[0]; for (let i = 0; i < 10; i++) { fireEvent.click(addButton); } - + // 할인율 표시 확인 - 대량 구매로 15% 할인 await waitFor(() => { - expect(screen.getByText('-15%')).toBeInTheDocument(); + expect(screen.getByText("-15%")).toBeInTheDocument(); }); }); - test('장바구니 아이템 개수가 헤더에 표시된다', () => { + test("장바구니 아이템 개수가 헤더에 표시된다", () => { render(); - + // 상품 추가 - fireEvent.click(screen.getAllByText('장바구니 담기')[0]); - fireEvent.click(screen.getAllByText('장바구니 담기')[0]); - fireEvent.click(screen.getAllByText('장바구니 담기')[1]); - + fireEvent.click(screen.getAllByText("장바구니 담기")[0]); + fireEvent.click(screen.getAllByText("장바구니 담기")[0]); + fireEvent.click(screen.getAllByText("장바구니 담기")[1]); + // 헤더의 장바구니 아이콘 옆 숫자 확인 - const cartCount = screen.getByText('3'); + const cartCount = screen.getByText("3"); expect(cartCount).toBeInTheDocument(); }); - test('검색을 초기화할 수 있다', async () => { + test("검색을 초기화할 수 있다", async () => { render(); - + // 검색어 입력 - const searchInput = screen.getByPlaceholderText('상품 검색...'); - fireEvent.change(searchInput, { target: { value: '프리미엄' } }); - + const searchInput = screen.getByPlaceholderText("상품 검색..."); + fireEvent.change(searchInput, { target: { value: "프리미엄" } }); + // 검색 결과 확인 await waitFor(() => { - expect(screen.getByText('최고급 품질의 프리미엄 상품입니다.')).toBeInTheDocument(); + expect( + screen.getByText("최고급 품질의 프리미엄 상품입니다.") + ).toBeInTheDocument(); // 다른 상품들은 보이지 않음 - expect(screen.queryByText('다양한 기능을 갖춘 실용적인 상품입니다.')).not.toBeInTheDocument(); + expect( + screen.queryByText("다양한 기능을 갖춘 실용적인 상품입니다.") + ).not.toBeInTheDocument(); }); - + // 검색어 초기화 - fireEvent.change(searchInput, { target: { value: '' } }); - + fireEvent.change(searchInput, { target: { value: "" } }); + // 모든 상품이 다시 표시됨 await waitFor(() => { - expect(screen.getByText('최고급 품질의 프리미엄 상품입니다.')).toBeInTheDocument(); - expect(screen.getByText('다양한 기능을 갖춘 실용적인 상품입니다.')).toBeInTheDocument(); - expect(screen.getByText('대용량과 고성능을 자랑하는 상품입니다.')).toBeInTheDocument(); + expect( + screen.getByText("최고급 품질의 프리미엄 상품입니다.") + ).toBeInTheDocument(); + expect( + screen.getByText("다양한 기능을 갖춘 실용적인 상품입니다.") + ).toBeInTheDocument(); + expect( + screen.getByText("대용량과 고성능을 자랑하는 상품입니다.") + ).toBeInTheDocument(); }); }); - test('알림 메시지가 자동으로 사라진다', async () => { - render(); - + test("알림 메시지가 자동으로 사라진다", async () => { + renderWithProvider(); + // 상품 추가하여 알림 발생 - fireEvent.click(screen.getAllByText('장바구니 담기')[0]); - + fireEvent.click(screen.getAllByText("장바구니 담기")[0]); + // 알림 메시지 확인 - expect(screen.getByText('장바구니에 담았습니다')).toBeInTheDocument(); - + const notification = await screen.findByText("장바구니에 담았습니다"); + expect(notification).toBeInTheDocument(); + // 3초 후 알림이 사라짐 - await waitFor(() => { - expect(screen.queryByText('장바구니에 담았습니다')).not.toBeInTheDocument(); - }, { timeout: 4000 }); + await waitFor( + () => { + expect( + screen.queryByText("장바구니에 담았습니다") + ).not.toBeInTheDocument(); + }, + { timeout: 4000 } + ); }); }); -}); \ No newline at end of file +}); diff --git a/src/advanced/atoms/cart.ts b/src/advanced/atoms/cart.ts new file mode 100644 index 000000000..4f7433f91 --- /dev/null +++ b/src/advanced/atoms/cart.ts @@ -0,0 +1,11 @@ +import { atom } from "jotai"; +import { atomWithStorage } from "jotai/utils"; +import { CartItem } from "../../types"; + +export const cartAtom = atomWithStorage("cart", []); + +// useEffect를 사용하지 않고 장바구니 아이템 개수를 계산하는 atom +export const totalItemCountAtom = atom((get) => { + const cart = get(cartAtom); + return cart.reduce((sum, item) => sum + item.quantity, 0); +}); diff --git a/src/advanced/atoms/coupons.ts b/src/advanced/atoms/coupons.ts new file mode 100644 index 000000000..6d18a3c61 --- /dev/null +++ b/src/advanced/atoms/coupons.ts @@ -0,0 +1,8 @@ +import { atomWithStorage } from "jotai/utils"; +import { Coupon } from "../../types"; +import { initialCoupons } from "../constants"; +import { atom } from "jotai"; + +export const couponsAtom = atomWithStorage("coupons", initialCoupons); + +export const selectedCouponAtom = atom(null); diff --git a/src/advanced/atoms/notifications.ts b/src/advanced/atoms/notifications.ts new file mode 100644 index 000000000..1e1eb424c --- /dev/null +++ b/src/advanced/atoms/notifications.ts @@ -0,0 +1,9 @@ +import { atom } from "jotai"; + +export interface NotificationType { + id: string; + message: string; + type: "error" | "success" | "warning"; +} + +export const notificationsAtom = atom([]); diff --git a/src/advanced/atoms/products.ts b/src/advanced/atoms/products.ts new file mode 100644 index 000000000..a9805424c --- /dev/null +++ b/src/advanced/atoms/products.ts @@ -0,0 +1,8 @@ +import { atomWithStorage } from "jotai/utils"; +import { ProductWithUI } from "../hooks/useProducts"; +import { initialProducts } from "../constants"; + +export const productsAtom = atomWithStorage( + "products", + initialProducts +); diff --git a/src/advanced/components/AdminPage.tsx b/src/advanced/components/AdminPage.tsx new file mode 100644 index 000000000..e088bd1b3 --- /dev/null +++ b/src/advanced/components/AdminPage.tsx @@ -0,0 +1,163 @@ +import { useState } from "react"; +import { useProducts, type ProductWithUI } from "../hooks/useProducts"; +import { ProductList } from "./admin/ProductList"; +import { useProductForm } from "../hooks/useProductForm"; +import { ProductForm } from "./admin/ProductForm"; +import { CouponList } from "./admin/CouponList"; +import { useCouponForm } from "../hooks/useCouponForm"; +import { CouponForm } from "./admin/CouponForm"; +import { useNotification } from "../hooks/useNotification"; +import { useCoupons } from "../hooks/useCoupons"; + +const AdminPage = () => { + const { addProduct, updateProduct } = useProducts(); + const { + productForm, + setProductForm, + editingProduct, + setEditingProduct, + showProductForm, + setShowProductForm, + updateProductForm, + resetProductForm, + } = useProductForm(); + const { addNotification } = useNotification(); + const { + couponForm, + updateCouponForm, + resetCouponForm, + toggleCouponForm, + showCouponForm, + } = useCouponForm(); + const { addCoupon, isDuplicateCoupon } = useCoupons(); + const [activeTab, setActiveTab] = useState<"products" | "coupons">( + "products" + ); + + const startEditProduct = (product: ProductWithUI) => { + setEditingProduct(product.id); + setProductForm({ + name: product.name, + price: product.price, + stock: product.stock, + description: product.description || "", + discounts: product.discounts || [], + }); + setShowProductForm(true); + }; + + const handleNewProduct = () => { + resetProductForm(); + setEditingProduct("new"); + setShowProductForm(true); + }; + + const handleProductSubmit = (e: React.FormEvent) => { + e.preventDefault(); + if (editingProduct && editingProduct !== "new") { + updateProduct(editingProduct, productForm); + addNotification("상품이 수정되었습니다.", "success"); + } else { + addProduct({ + ...productForm, + discounts: productForm.discounts, + }); + addNotification("상품이 추가되었습니다.", "success"); + } + resetProductForm(); + }; + + const handleCouponSubmit = (e: React.FormEvent) => { + e.preventDefault(); + if (isDuplicateCoupon(couponForm)) { + addNotification("이미 존재하는 쿠폰 코드입니다.", "error"); + return; + } + addCoupon(couponForm); + addNotification("쿠폰이 추가되었습니다.", "success"); + resetCouponForm(); + toggleCouponForm(); + }; + + return ( +
+
+

관리자 대시보드

+

상품과 쿠폰을 관리할 수 있습니다

+
+
+ +
+ + {activeTab === "products" ? ( +
+
+
+

상품 목록

+ +
+
+ + + {showProductForm && ( + + )} +
+ ) : ( +
+
+

쿠폰 관리

+
+
+ + + {showCouponForm && ( +
+ +
+ )} +
+
+ )} +
+ ); +}; + +export default AdminPage; diff --git a/src/advanced/components/CartPage.tsx b/src/advanced/components/CartPage.tsx new file mode 100644 index 000000000..3b7fceab9 --- /dev/null +++ b/src/advanced/components/CartPage.tsx @@ -0,0 +1,76 @@ +import { useCallback } from "react"; +import { useProducts } from "../hooks/useProducts"; +import { ProductCard } from "./cart/ProductCard"; +import { ShoppingCart } from "./cart/ShoppingCart"; +import { SelectCoupon } from "./cart/SelectCoupon"; +import { PaymentInfo } from "./cart/PaymentInfo"; +import { useNotification } from "../hooks/useNotification"; +import { useCart } from "../hooks/useCart"; +import { useCoupons } from "../hooks/useCoupons"; + +interface CartPageProps { + debouncedSearchTerm: string; +} + +const CartPage = ({ debouncedSearchTerm }: CartPageProps) => { + const { addNotification } = useNotification(); + const { cart, setCart } = useCart(); + const { coupons, setSelectedCoupon } = useCoupons(); + const { products, filterProductsBySearchTerm } = useProducts(); + + const filteredProducts = filterProductsBySearchTerm(debouncedSearchTerm); + + const completeOrder = useCallback(() => { + const orderNumber = `ORD-${Date.now()}`; + addNotification( + `주문이 완료되었습니다. 주문번호: ${orderNumber}`, + "success" + ); + setCart([]); + setSelectedCoupon(null); + }, [addNotification]); + + return ( +
+
+ {/* 상품 목록 */} +
+
+

전체 상품

+
+ 총 {products.length}개 상품 +
+
+ {filteredProducts.length === 0 ? ( +
+

+ "{debouncedSearchTerm}"에 대한 검색 결과가 없습니다. +

+
+ ) : ( +
+ {filteredProducts.map((product) => { + return ; + })} +
+ )} +
+
+ +
+
+ + + {cart.length > 0 && ( + <> + {coupons.length > 0 && } + + + )} +
+
+
+ ); +}; + +export default CartPage; diff --git a/src/advanced/components/Notifications.tsx b/src/advanced/components/Notifications.tsx new file mode 100644 index 000000000..4e9babe95 --- /dev/null +++ b/src/advanced/components/Notifications.tsx @@ -0,0 +1,47 @@ +import { useAtomValue } from "jotai"; +import { useNotification } from "../hooks/useNotification"; +import { notificationsAtom } from "../atoms/notifications"; + +export const Notifications = () => { + const notifications = useAtomValue(notificationsAtom); + const { clearNotification } = useNotification(); + + if (notifications.length === 0) return null; + + return ( +
+ {notifications.map((notif) => ( +
+ {notif.message} + +
+ ))} +
+ ); +}; diff --git a/src/advanced/components/admin/CouponForm.tsx b/src/advanced/components/admin/CouponForm.tsx new file mode 100644 index 000000000..a421d744e --- /dev/null +++ b/src/advanced/components/admin/CouponForm.tsx @@ -0,0 +1,159 @@ +import { CouponFormType } from "../../hooks/useCouponForm"; +import { useNotification } from "../../hooks/useNotification"; +interface CouponFormProps { + couponForm: { + name: string; + code: string; + discountType: "amount" | "percentage"; + discountValue: number; + }; + updateCouponForm: (updates: Partial) => void; + handleCouponSubmit: (e: React.FormEvent) => void; + toggleCouponForm: () => void; +} + +export const CouponForm = ({ + couponForm, + updateCouponForm, + handleCouponSubmit, + toggleCouponForm, +}: CouponFormProps) => { + const { addNotification } = useNotification(); + return ( +
+
+

새 쿠폰 생성

+
+
+ + + updateCouponForm({ + ...couponForm, + name: e.target.value, + }) + } + className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border text-sm" + placeholder="신규 가입 쿠폰" + required + /> +
+
+ + + updateCouponForm({ + ...couponForm, + code: e.target.value.toUpperCase(), + }) + } + className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border text-sm font-mono" + placeholder="WELCOME2024" + required + /> +
+
+ + +
+
+ + { + const value = e.target.value; + if (value === "" || /^\d+$/.test(value)) { + updateCouponForm({ + ...couponForm, + discountValue: value === "" ? 0 : parseInt(value), + }); + } + }} + onBlur={(e) => { + const value = parseInt(e.target.value) || 0; + if (couponForm.discountType === "percentage") { + if (value > 100) { + addNotification( + "할인율은 100%를 초과할 수 없습니다", + "error" + ); + updateCouponForm({ + ...couponForm, + discountValue: 100, + }); + } else if (value < 0) { + updateCouponForm({ + ...couponForm, + discountValue: 0, + }); + } + } else { + if (value > 100000) { + addNotification( + "할인 금액은 100,000원을 초과할 수 없습니다", + "error" + ); + updateCouponForm({ + ...couponForm, + discountValue: 100000, + }); + } else if (value < 0) { + updateCouponForm({ + ...couponForm, + discountValue: 0, + }); + } + } + }} + className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border text-sm" + placeholder={couponForm.discountType === "amount" ? "5000" : "10"} + required + /> +
+
+
+ + +
+
+
+ ); +}; diff --git a/src/advanced/components/admin/CouponList.tsx b/src/advanced/components/admin/CouponList.tsx new file mode 100644 index 000000000..295b744fd --- /dev/null +++ b/src/advanced/components/admin/CouponList.tsx @@ -0,0 +1,87 @@ +import { useEffect } from "react"; +import { useCoupons } from "../../hooks/useCoupons"; +import { useNotification } from "../../hooks/useNotification"; + +export const CouponList = ({ + toggleCouponForm, +}: { + toggleCouponForm: () => void; +}) => { + const { coupons, deleteCoupon } = useCoupons(); + const { addNotification } = useNotification(); + const handleDeleteCoupon = (couponCode: string) => { + deleteCoupon(couponCode); + addNotification("쿠폰이 삭제되었습니다.", "success"); + }; + + useEffect(() => { + localStorage.setItem("coupons", JSON.stringify(coupons)); + }, [coupons]); + + return ( +
+ {coupons.map((coupon) => ( +
+
+
+

{coupon.name}

+

+ {coupon.code} +

+
+ + {coupon.discountType === "amount" + ? `${coupon.discountValue.toLocaleString()}원 할인` + : `${coupon.discountValue}% 할인`} + +
+
+ +
+
+ ))} + +
+ +
+
+ ); +}; diff --git a/src/advanced/components/admin/ProductForm.tsx b/src/advanced/components/admin/ProductForm.tsx new file mode 100644 index 000000000..d2595c6c0 --- /dev/null +++ b/src/advanced/components/admin/ProductForm.tsx @@ -0,0 +1,233 @@ +import { useNotification } from "../../hooks/useNotification"; +import { type ProductFormType } from "../../hooks/useProductForm"; + +interface ProductFormProps { + productForm: ProductFormType; + editingProduct: string | null; + updateProductForm: (updates: Partial) => void; + resetProductForm: () => void; + handleProductSubmit: (e: React.FormEvent) => void; +} +export const ProductForm = ({ + productForm, + editingProduct, + updateProductForm, + resetProductForm, + handleProductSubmit, +}: ProductFormProps) => { + const { addNotification } = useNotification(); + return ( +
+
+

+ {editingProduct === "new" ? "새 상품 추가" : "상품 수정"} +

+
+
+ + + updateProductForm({ + name: e.target.value, + }) + } + className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border" + required + /> +
+
+ + + updateProductForm({ + description: e.target.value, + }) + } + className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border" + /> +
+
+ + { + const value = e.target.value; + if (value === "" || /^\d+$/.test(value)) { + updateProductForm({ + price: value === "" ? 0 : parseInt(value), + }); + } + }} + onBlur={(e) => { + const value = e.target.value; + if (value === "") { + updateProductForm({ price: 0 }); + } else if (parseInt(value) < 0) { + updateProductForm({ price: 0 }); + addNotification("가격은 0보다 커야 합니다", "error"); + } + }} + className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border" + placeholder="숫자만 입력" + required + /> +
+
+ + { + const value = e.target.value; + if (value === "" || /^\d+$/.test(value)) { + updateProductForm({ + stock: value === "" ? 0 : parseInt(value), + }); + } + }} + onBlur={(e) => { + const value = e.target.value; + if (value === "") { + updateProductForm({ stock: 0 }); + } else if (parseInt(value) < 0) { + addNotification("재고는 0보다 커야 합니다", "error"); + updateProductForm({ stock: 0 }); + } else if (parseInt(value) > 9999) { + addNotification( + "재고는 9999개를 초과할 수 없습니다", + "error" + ); + updateProductForm({ stock: 9999 }); + } + }} + className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border" + placeholder="숫자만 입력" + required + /> +
+
+
+ +
+ {productForm.discounts.map((discount, index) => ( +
+ { + const newDiscounts = [...productForm.discounts]; + newDiscounts[index].quantity = + parseInt(e.target.value) || 0; + updateProductForm({ + discounts: newDiscounts, + }); + }} + className="w-20 px-2 py-1 border rounded" + min="1" + placeholder="수량" + /> + 개 이상 구매 시 + { + const newDiscounts = [...productForm.discounts]; + newDiscounts[index].rate = + (parseInt(e.target.value) || 0) / 100; + updateProductForm({ + discounts: newDiscounts, + }); + }} + className="w-16 px-2 py-1 border rounded" + min="0" + max="100" + placeholder="%" + /> + % 할인 + +
+ ))} + +
+
+ +
+ + +
+
+
+ ); +}; diff --git a/src/advanced/components/admin/ProductList.tsx b/src/advanced/components/admin/ProductList.tsx new file mode 100644 index 000000000..104566325 --- /dev/null +++ b/src/advanced/components/admin/ProductList.tsx @@ -0,0 +1,89 @@ +import { useEffect } from "react"; +import { ProductWithUI, useProducts } from "../../hooks/useProducts"; +import { formatPriceWon } from "../../utils/formatters"; +import { useNotification } from "../../hooks/useNotification"; + +interface ProductListProps { + startEditProduct: (product: ProductWithUI) => void; +} + +export const ProductList = ({ startEditProduct }: ProductListProps) => { + const { products, deleteProduct } = useProducts(); + const { addNotification } = useNotification(); + const handleDelete = (productId: string) => { + deleteProduct(productId); + addNotification("상품이 삭제되었습니다.", "success"); + }; + + useEffect(() => { + localStorage.setItem("products", JSON.stringify(products)); + }, [products]); + + return ( +
+ + + + + + + + + + + + {products.map((product) => ( + + + + + + + + ))} + +
+ 상품명 + + 가격 + + 재고 + + 설명 + + 작업 +
+ {product.name} + + {formatPriceWon(product.price)} + + 10 + ? "bg-green-100 text-green-800" + : product.stock > 0 + ? "bg-yellow-100 text-yellow-800" + : "bg-red-100 text-red-800" + }`} + > + {product.stock}개 + + + {product.description || "-"} + + + +
+
+ ); +}; diff --git a/src/advanced/components/cart/PaymentInfo.tsx b/src/advanced/components/cart/PaymentInfo.tsx new file mode 100644 index 000000000..6436a74e6 --- /dev/null +++ b/src/advanced/components/cart/PaymentInfo.tsx @@ -0,0 +1,53 @@ +import { useCart } from "../../hooks/useCart"; +import { useCoupons } from "../../hooks/useCoupons"; + +interface PaymentInfoProps { + completeOrder: () => void; +} +export const PaymentInfo = ({ completeOrder }: PaymentInfoProps) => { + const { calculateCartTotal } = useCart(); + const { selectedCoupon } = useCoupons(); + const totals = calculateCartTotal(selectedCoupon); + return ( +
+

결제 정보

+
+
+ 상품 금액 + + {totals.totalBeforeDiscount.toLocaleString()}원 + +
+ {totals.totalBeforeDiscount - totals.totalAfterDiscount > 0 && ( +
+ 할인 금액 + + - + {( + totals.totalBeforeDiscount - totals.totalAfterDiscount + ).toLocaleString()} + 원 + +
+ )} +
+ 결제 예정 금액 + + {totals.totalAfterDiscount.toLocaleString()}원 + +
+
+ + + +
+

* 실제 결제는 이루어지지 않습니다

+
+
+ ); +}; diff --git a/src/advanced/components/cart/ProductCard.tsx b/src/advanced/components/cart/ProductCard.tsx new file mode 100644 index 000000000..7b9738aca --- /dev/null +++ b/src/advanced/components/cart/ProductCard.tsx @@ -0,0 +1,92 @@ +import { useCart } from "../../hooks/useCart"; +import { ProductWithUI } from "../../hooks/useProducts"; +import { formatProductPrice } from "../../utils/formatters"; + +interface ProductCardProps { + product: ProductWithUI; +} +export const ProductCard = ({ product }: ProductCardProps) => { + const { addToCart, getRemainingStock } = useCart(); + const remainingStock = getRemainingStock(product); + + const price = + remainingStock <= 0 ? "SOLD OUT" : formatProductPrice(product.price); + return ( +
+ {/* 상품 이미지 영역 (placeholder) */} +
+
+ + + +
+ {product.isRecommended && ( + + BEST + + )} + {product.discounts.length > 0 && ( + + ~{Math.max(...product.discounts.map((d) => d.rate)) * 100}% + + )} +
+ + {/* 상품 정보 */} +
+

{product.name}

+ {product.description && ( +

+ {product.description} +

+ )} + + {/* 가격 정보 */} +
+

{price}

+ {product.discounts.length > 0 && ( +

+ {product.discounts[0].quantity}개 이상 구매시 할인{" "} + {product.discounts[0].rate * 100}% +

+ )} +
+ + {/* 재고 상태 */} +
+ {remainingStock <= 5 && remainingStock > 0 && ( +

+ 품절임박! {remainingStock}개 남음 +

+ )} + {remainingStock > 5 && ( +

재고 {remainingStock}개

+ )} +
+ + {/* 장바구니 버튼 */} + +
+
+ ); +}; diff --git a/src/advanced/components/cart/SelectCoupon.tsx b/src/advanced/components/cart/SelectCoupon.tsx new file mode 100644 index 000000000..699511be1 --- /dev/null +++ b/src/advanced/components/cart/SelectCoupon.tsx @@ -0,0 +1,39 @@ +import { useCart } from "../../hooks/useCart"; +import { useCoupons } from "../../hooks/useCoupons"; + +export const SelectCoupon = () => { + const { calculateCartTotal } = useCart(); + const { selectedCoupon, applyCoupon, setSelectedCoupon, coupons } = + useCoupons(); + const totals = calculateCartTotal(selectedCoupon); + return ( +
+
+

쿠폰 할인

+ +
+ +
+ ); +}; diff --git a/src/advanced/components/cart/ShoppingCart.tsx b/src/advanced/components/cart/ShoppingCart.tsx new file mode 100644 index 000000000..99a74a2e2 --- /dev/null +++ b/src/advanced/components/cart/ShoppingCart.tsx @@ -0,0 +1,127 @@ +import { useCart } from "../../hooks/useCart"; + +export const ShoppingCart = () => { + const { cart, calculateItemTotal, removeFromCart, updateQuantity } = + useCart(); + return ( +
+

+ + + + 장바구니 +

+ {cart.length === 0 ? ( +
+ + + +

장바구니가 비어있습니다

+
+ ) : ( +
+ {cart.map((item) => { + const itemTotal = calculateItemTotal(item); + const originalPrice = item.product.price * item.quantity; + const hasDiscount = itemTotal < originalPrice; + const discountRate = hasDiscount + ? Math.round((1 - itemTotal / originalPrice) * 100) + : 0; + + return ( +
+
+

+ {item.product.name} +

+ +
+
+
+ + + {item.quantity} + + +
+
+ {hasDiscount && ( + + -{discountRate}% + + )} +

+ {Math.round(itemTotal).toLocaleString()}원 +

+
+
+
+ ); + })} +
+ )} +
+ ); +}; diff --git a/src/advanced/components/header/CartIcon.tsx b/src/advanced/components/header/CartIcon.tsx new file mode 100644 index 000000000..9d371a431 --- /dev/null +++ b/src/advanced/components/header/CartIcon.tsx @@ -0,0 +1,27 @@ +import { useCart } from "../../hooks/useCart"; + +export const CartIcon = () => { + const { cart, totalItemCount } = useCart(); + return ( +
+ + + + {cart.length > 0 && ( + + {totalItemCount} + + )} +
+ ); +}; diff --git a/src/advanced/components/header/SearchBar.tsx b/src/advanced/components/header/SearchBar.tsx new file mode 100644 index 000000000..09ffaa133 --- /dev/null +++ b/src/advanced/components/header/SearchBar.tsx @@ -0,0 +1,21 @@ +interface SearchBarProps { + value: string; + onChange: (value: string) => void; + placeholder?: string; +} + +export const SearchBar = ({ + value, + onChange, + placeholder = "상품 검색...", +}: SearchBarProps) => { + return ( + onChange(e.target.value)} + placeholder={placeholder} + className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" + /> + ); +}; diff --git a/src/advanced/components/header/ToggleButton.tsx b/src/advanced/components/header/ToggleButton.tsx new file mode 100644 index 000000000..52b80ccac --- /dev/null +++ b/src/advanced/components/header/ToggleButton.tsx @@ -0,0 +1,17 @@ +interface ToggleButtonProps { + isAdmin: boolean; + setIsAdmin: (isAdmin: boolean) => void; +} + +export const ToggleButton = ({ isAdmin, setIsAdmin }: ToggleButtonProps) => { + return ( + + ); +}; diff --git a/src/advanced/components/header/index.tsx b/src/advanced/components/header/index.tsx new file mode 100644 index 000000000..7adbf228e --- /dev/null +++ b/src/advanced/components/header/index.tsx @@ -0,0 +1,20 @@ +interface HeaderProps { + leftSide: React.ReactNode; + rightSide: React.ReactNode; +} + +export const Header = ({ leftSide, rightSide }: HeaderProps) => { + return ( +
+
+
+
+

SHOP

+ {leftSide} +
+ +
+
+
+ ); +}; diff --git a/src/advanced/constants/index.ts b/src/advanced/constants/index.ts new file mode 100644 index 000000000..2a5f2432d --- /dev/null +++ b/src/advanced/constants/index.ts @@ -0,0 +1,56 @@ +import { Coupon, Product } from "../../types"; + +interface ProductWithUI extends Product { + description?: string; + isRecommended?: boolean; +} + +// 초기 데이터 +export const initialProducts: ProductWithUI[] = [ + { + id: "p1", + name: "상품1", + price: 10000, + stock: 20, + discounts: [ + { quantity: 10, rate: 0.1 }, + { quantity: 20, rate: 0.2 }, + ], + description: "최고급 품질의 프리미엄 상품입니다.", + }, + { + id: "p2", + name: "상품2", + price: 20000, + stock: 20, + discounts: [{ quantity: 10, rate: 0.15 }], + description: "다양한 기능을 갖춘 실용적인 상품입니다.", + isRecommended: true, + }, + { + id: "p3", + name: "상품3", + price: 30000, + stock: 20, + discounts: [ + { quantity: 10, rate: 0.2 }, + { quantity: 30, rate: 0.25 }, + ], + description: "대용량과 고성능을 자랑하는 상품입니다.", + }, +]; + +export const initialCoupons: Coupon[] = [ + { + name: "5000원 할인", + code: "AMOUNT5000", + discountType: "amount", + discountValue: 5000, + }, + { + name: "10% 할인", + code: "PERCENT10", + discountType: "percentage", + discountValue: 10, + }, +]; diff --git a/src/advanced/hooks/useCart.ts b/src/advanced/hooks/useCart.ts new file mode 100644 index 000000000..4ba855d8d --- /dev/null +++ b/src/advanced/hooks/useCart.ts @@ -0,0 +1,94 @@ +import { CartItem, Coupon } from "../../types"; +import { ProductWithUI } from "./useProducts"; +import { cartModel } from "../models/cart"; +import { couponModel } from "../models/coupon"; +import { useNotification } from "./useNotification"; +import { useAtom, useAtomValue } from "jotai"; +import { cartAtom, totalItemCountAtom } from "../atoms/cart"; + +export const useCart = () => { + const { addNotification } = useNotification(); + const [cart, setCart] = useAtom(cartAtom); + const totalItemCount = useAtomValue(totalItemCountAtom); + + const addToCart = (product: ProductWithUI) => { + const remainingStock = cartModel.getRemainingStock(cart, product); + const isStockExceeded = cartModel.wouldExceedStock(cart, product); + + if (remainingStock <= 0) { + addNotification("재고가 부족합니다!", "error"); + return; + } + + if (isStockExceeded) { + addNotification(`재고는 ${product.stock}개까지만 있습니다.`, "error"); + return; + } + + const newCart = cartModel.addItemToCart(cart, product); + setCart(newCart); + addNotification("장바구니에 담았습니다", "success"); + }; + + const updateQuantity = ( + productId: string, + newQuantity: number, + product: ProductWithUI + ) => { + if (newQuantity > product.stock) { + addNotification(`재고는 ${product.stock}개까지만 있습니다.`, "error"); + return; + } + + const newCart = cartModel.updateCartItemQuantity( + cart, + productId, + newQuantity + ); + setCart(newCart); + }; + + const removeFromCart = (productId: string) => { + const newCart = cartModel.removeItemFromCart(cart, productId); + setCart(newCart); + }; + + const calculateCartTotal = (selectedCoupon?: Coupon | null) => { + // 1. 장바구니 총액 계산 (쿠폰 없이) + const cartTotal = cartModel.calculateCartTotal(cart); + + // 2. 쿠폰이 있으면 적용 + let finalTotal = cartTotal.totalAfterDiscount; + if (selectedCoupon) { + finalTotal = couponModel.applyCoupon( + cartTotal.totalAfterDiscount, + selectedCoupon + ); + } + + return { + totalBeforeDiscount: cartTotal.totalBeforeDiscount, + totalAfterDiscount: finalTotal, + }; + }; + + const calculateItemTotal = (item: CartItem) => { + return cartModel.calculateItemTotal(item, cart); + }; + + const getRemainingStock = (product: ProductWithUI) => { + return cartModel.getRemainingStock(cart, product); + }; + + return { + cart, + setCart, + totalItemCount, + addToCart, + updateQuantity, + removeFromCart, + calculateCartTotal, + calculateItemTotal, + getRemainingStock, + }; +}; diff --git a/src/advanced/hooks/useCouponForm.ts b/src/advanced/hooks/useCouponForm.ts new file mode 100644 index 000000000..0253e4e3d --- /dev/null +++ b/src/advanced/hooks/useCouponForm.ts @@ -0,0 +1,45 @@ +import { useState } from "react"; + +export interface CouponFormType { + name: string; + code: string; + discountType: "amount" | "percentage"; + discountValue: number; +} + +export const useCouponForm = () => { + const [couponForm, setCouponForm] = useState({ + name: "", + code: "", + discountType: "amount" as "amount" | "percentage", + discountValue: 0, + }); + + const [showCouponForm, setShowCouponForm] = useState(false); + + const toggleCouponForm = () => { + setShowCouponForm(!showCouponForm); + }; + + const updateCouponForm = (updates: Partial) => { + setCouponForm({ ...couponForm, ...updates }); + }; + + const resetCouponForm = () => { + setCouponForm({ + name: "", + code: "", + discountType: "amount", + discountValue: 0, + }); + }; + + return { + couponForm, + updateCouponForm, + resetCouponForm, + showCouponForm, + setShowCouponForm, + toggleCouponForm, + }; +}; diff --git a/src/advanced/hooks/useCoupons.ts b/src/advanced/hooks/useCoupons.ts new file mode 100644 index 000000000..16794bcc0 --- /dev/null +++ b/src/advanced/hooks/useCoupons.ts @@ -0,0 +1,51 @@ +import { useAtom } from "jotai"; +import { couponsAtom, selectedCouponAtom } from "../atoms/coupons"; +import { useNotification } from "./useNotification"; +import { Coupon } from "../../types"; +import { couponModel } from "../models/coupon"; + +export const useCoupons = () => { + const { addNotification } = useNotification(); + const [coupons, setCoupons] = useAtom(couponsAtom); + const [selectedCoupon, setSelectedCoupon] = useAtom(selectedCouponAtom); + + const isDuplicateCoupon = (newCoupon: Coupon) => { + return coupons.find((c) => c.code === newCoupon.code) !== undefined; + }; + + const addCoupon = (newCoupon: Coupon) => { + setCoupons((prev) => [...prev, newCoupon]); + }; + + const deleteCoupon = (couponCode: string) => { + setCoupons((prev) => prev.filter((c) => c.code !== couponCode)); + // selectedCoupon도 atom이므로 직접 업데이트 + if (selectedCoupon?.code === couponCode) { + setSelectedCoupon(null); + } + }; + + const applyCoupon = (coupon: Coupon, currentTotal: number) => { + const isApplicable = couponModel.isApplicable(currentTotal, coupon); + + if (!isApplicable) { + addNotification( + "percentage 쿠폰은 10,000원 이상 구매 시 사용 가능합니다.", + "error" + ); + return; + } + setSelectedCoupon(coupon); + addNotification("쿠폰이 적용되었습니다.", "success"); + }; + + return { + coupons, + selectedCoupon, + setSelectedCoupon, + addCoupon, + deleteCoupon, + isDuplicateCoupon, + applyCoupon, + }; +}; diff --git a/src/advanced/hooks/useNotification.ts b/src/advanced/hooks/useNotification.ts new file mode 100644 index 000000000..9aabda610 --- /dev/null +++ b/src/advanced/hooks/useNotification.ts @@ -0,0 +1,30 @@ +import { useSetAtom } from "jotai"; +import { notificationsAtom } from "../atoms/notifications"; +import { NotificationType } from "../atoms/notifications"; + +export function useNotification() { + const setNotifications = useSetAtom(notificationsAtom); + + const addNotification = ( + msg: string, + type: "error" | "success" | "warning" = "success" + ) => { + const id = String(Date.now()); + const newNotification: NotificationType = { id, message: msg, type }; + + setNotifications((prev) => { + const updated = [...prev, newNotification]; + return updated; + }); + + setTimeout(() => { + setNotifications((prev) => prev.filter((n) => n.id !== id)); + }, 3000); + }; + + const clearNotification = (id: string) => { + setNotifications((prev) => prev.filter((n) => n.id !== id)); + }; + + return { addNotification, clearNotification }; +} diff --git a/src/advanced/hooks/useProductForm.ts b/src/advanced/hooks/useProductForm.ts new file mode 100644 index 000000000..72c555e7a --- /dev/null +++ b/src/advanced/hooks/useProductForm.ts @@ -0,0 +1,50 @@ +import { useState } from "react"; + +export interface ProductFormType { + name: string; + price: number; + stock: number; + description: string; + discounts: Array<{ quantity: number; rate: number }>; +} + +export const useProductForm = () => { + const [productForm, setProductForm] = useState({ + name: "", + price: 0, + stock: 0, + description: "", + discounts: [] as Array<{ quantity: number; rate: number }>, + }); + + const [editingProduct, setEditingProduct] = useState(null); + const [showProductForm, setShowProductForm] = useState(false); + + const updateProductForm = (updates: Partial) => { + setProductForm({ ...productForm, ...updates }); + }; + + const resetProductForm = () => { + setProductForm({ + name: "", + price: 0, + stock: 0, + description: "", + discounts: [], + }); + + setEditingProduct(null); + setShowProductForm(false); + }; + + return { + productForm, + setProductForm, + editingProduct, + setEditingProduct, + showProductForm, + setShowProductForm, + updateProductForm, + resetProductForm, + }; +}; diff --git a/src/advanced/hooks/useProducts.ts b/src/advanced/hooks/useProducts.ts new file mode 100644 index 000000000..30f7c7d66 --- /dev/null +++ b/src/advanced/hooks/useProducts.ts @@ -0,0 +1,59 @@ +export interface ProductWithUI extends Product { + description?: string; + isRecommended?: boolean; +} + +import { Product } from "../../types"; +import { useAtom, useAtomValue } from "jotai"; +import { productsAtom } from "../atoms/products"; + +export function useProducts() { + const [products, setProducts] = useAtom(productsAtom); + + const addProduct = (newProduct: Omit) => { + const product: ProductWithUI = { + ...newProduct, + id: `p${Date.now()}`, + }; + setProducts((prev) => [...prev, product]); + }; + + const updateProduct = ( + productId: string, + updates: Partial + ) => { + setProducts((prev) => + prev.map((product) => + product.id === productId ? { ...product, ...updates } : product + ) + ); + }; + + const deleteProduct = (productId: string) => { + setProducts((prev) => prev.filter((p) => p.id !== productId)); + }; + + const filterProductsBySearchTerm = (searchTerm: string) => { + const products = useAtomValue(productsAtom); + + if (!searchTerm.trim()) { + return products; + } + + const lowerSearchTerm = searchTerm.toLowerCase(); + return products.filter( + (product) => + product.name.toLowerCase().includes(lowerSearchTerm) || + (product.description && + product.description.toLowerCase().includes(lowerSearchTerm)) + ); + }; + + return { + products, + addProduct, + updateProduct, + deleteProduct, + filterProductsBySearchTerm, + }; +} diff --git a/src/advanced/hooks/useSearch.ts b/src/advanced/hooks/useSearch.ts new file mode 100644 index 000000000..189a18672 --- /dev/null +++ b/src/advanced/hooks/useSearch.ts @@ -0,0 +1,13 @@ +import { useState } from "react"; +import { useDebounce } from "../utils/hooks/useDebounce"; + +export const useSearch = (delay: number = 500) => { + const [searchTerm, setSearchTerm] = useState(""); + const debouncedSearchTerm = useDebounce(searchTerm, delay); + + return { + searchTerm, + debouncedSearchTerm, + setSearchTerm, + }; +}; diff --git a/src/advanced/models/cart.ts b/src/advanced/models/cart.ts new file mode 100644 index 000000000..a49ec4b62 --- /dev/null +++ b/src/advanced/models/cart.ts @@ -0,0 +1,174 @@ +// TODO: 장바구니 비즈니스 로직 (순수 함수) +// 힌트: 모든 함수는 순수 함수로 구현 (부작용 없음, 같은 입력에 항상 같은 출력) +// +// 구현할 함수들: +// 1. calculateItemTotal(item): 개별 아이템의 할인 적용 후 총액 계산 +// 2. getMaxApplicableDiscount(item): 적용 가능한 최대 할인율 계산 +// 3. calculateCartTotal(cart, coupon): 장바구니 총액 계산 (할인 전/후, 할인액) +// 4. updateCartItemQuantity(cart, productId, quantity): 수량 변경 +// 5. addItemToCart(cart, product): 상품 추가 +// 6. removeItemFromCart(cart, productId): 상품 제거 +// 7. getRemainingStock(product, cart): 남은 재고 계산 +// +// 원칙: +// - UI와 관련된 로직 없음 +// - 외부 상태에 의존하지 않음 +// - 모든 필요한 데이터는 파라미터로 전달받음 + +import { CartItem } from "../../types"; +import { ProductWithUI } from "../hooks/useProducts"; + +export const cartModel = { + /** + * 상품의 기본 할인율 계산 (수량 기반) + * @param item - 장바구니 아이템 + * @returns 기본 할인율 (0 ~ 1) + */ + getBaseDiscount: (item: CartItem): number => { + const { discounts } = item.product; + const { quantity } = item; + + return discounts.reduce((maxDiscount, discount) => { + return quantity >= discount.quantity && discount.rate > maxDiscount + ? discount.rate + : maxDiscount; + }, 0); + }, + + /** + * 대량 구매 보너스 할인율 계산 + * @param cart - 전체 장바구니 + * @returns 대량 구매 보너스 할인율 (0 또는 0.05) + */ + getBulkPurchaseBonus: (cart: CartItem[]): number => { + const hasBulkPurchase = cart.some((cartItem) => cartItem.quantity >= 10); + return hasBulkPurchase ? 0.05 : 0; + }, + + /** + * 적용 가능한 최대 할인율 계산 + * @param item - 장바구니 아이템 + * @param cart - 전체 장바구니 (대량 구매 체크용) + * @returns 최대 할인율 (0 ~ 0.5, 최대 50%) + */ + getMaxApplicableDiscount: (item: CartItem, cart: CartItem[]): number => { + const baseDiscount = cartModel.getBaseDiscount(item); + const bulkBonus = cartModel.getBulkPurchaseBonus(cart); + + // 기본 할인 + 대량 구매 보너스, 최대 50% 제한 + return Math.min(baseDiscount + bulkBonus, 0.5); + }, + + /** + * 개별 아이템의 할인 적용 후 총액 계산 + * @param item - 장바구니 아이템 + * @param cart - 전체 장바구니 (대량 구매 체크용) + * @returns 할인 적용 후 총액 + */ + calculateItemTotal: (item: CartItem, cart: CartItem[]): number => { + const { price } = item.product; + const { quantity } = item; + const discount = cartModel.getMaxApplicableDiscount(item, cart); + + return Math.round(price * quantity * (1 - discount)); + }, + + /** + * 장바구니 총액 계산 (쿠폰 적용 전) + * @param cart - 장바구니 아이템 배열 + * @returns 할인 전/후 총액 (쿠폰 미적용) + */ + calculateCartTotal: (cart: CartItem[]) => { + let totalBeforeDiscount = 0; + let totalAfterDiscount = 0; + + cart.forEach((item) => { + const itemPrice = item.product.price * item.quantity; + totalBeforeDiscount += itemPrice; + totalAfterDiscount += cartModel.calculateItemTotal(item, cart); + }); + + return { + totalBeforeDiscount: Math.round(totalBeforeDiscount), + totalAfterDiscount: Math.round(totalAfterDiscount), + }; + }, + + /** + * 남은 재고 계산 + * @param cart - 장바구니 + * @param product - 상품 + * @returns 남은 재고 수량 + */ + getRemainingStock: (cart: CartItem[], product: ProductWithUI): number => { + const cartItem = cart.find((item) => item.product.id === product.id); + const remaining = product.stock - (cartItem?.quantity || 0); + + return remaining; + }, + + /** + * 재고 초과 여부 확인 + * @param cart - 장바구니 + * @param product - 상품 + * @returns 재고 초과 여부 + */ + wouldExceedStock: (cart: CartItem[], product: ProductWithUI): boolean => { + const existingItem = cart.find((item) => item.product.id === product.id); + if (existingItem) { + return existingItem.quantity + 1 > product.stock; + } + return false; + }, + + /** + * 장바구니에 상품 추가 + * @param cart - 현재 장바구니 + * @param product - 추가할 상품 + * @returns 새로운 장바구니 + */ + addItemToCart: (cart: CartItem[], product: ProductWithUI): CartItem[] => { + const existingItem = cart.find((item) => item.product.id === product.id); + + if (existingItem) { + return cart.map((item) => + item.product.id === product.id + ? { ...item, quantity: item.quantity + 1 } + : item + ); + } + + return [...cart, { product, quantity: 1 }]; + }, + + /** + * 장바구니에서 상품 제거 + * @param cart - 현재 장바구니 + * @param productId - 제거할 상품 ID + * @returns 새로운 장바구니 + */ + removeItemFromCart: (cart: CartItem[], productId: string): CartItem[] => { + return cart.filter((item) => item.product.id !== productId); + }, + + /** + * 장바구니 아이템 수량 변경 + * @param cart - 현재 장바구니 + * @param productId - 변경할 상품 ID + * @param quantity - 새로운 수량 + * @returns 새로운 장바구니 + */ + updateCartItemQuantity: ( + cart: CartItem[], + productId: string, + quantity: number + ): CartItem[] => { + if (quantity <= 0) { + return cartModel.removeItemFromCart(cart, productId); + } + + return cart.map((item) => + item.product.id === productId ? { ...item, quantity } : item + ); + }, +}; diff --git a/src/advanced/models/coupon.ts b/src/advanced/models/coupon.ts new file mode 100644 index 000000000..61de9ea22 --- /dev/null +++ b/src/advanced/models/coupon.ts @@ -0,0 +1,37 @@ +// 쿠폰 관련 비즈니스 로직 (순수 함수) +// 원칙: +// - UI와 관련된 로직 없음 +// - 외부 상태에 의존하지 않음 +// - 모든 필요한 데이터는 파라미터로 전달받음 + +import { Coupon } from "../../types"; + +export const couponModel = { + /** + * 쿠폰을 총액에 적용 + * @param total - 쿠폰 적용 전 총액 + * @param coupon - 적용할 쿠폰 + * @returns 쿠폰 적용 후 총액 + */ + applyCoupon: (total: number, coupon: Coupon): number => { + if (coupon.discountType === "amount") { + return Math.max(0, total - coupon.discountValue); + } else { + return Math.round(total * (1 - coupon.discountValue / 100)); + } + }, + + /** + * 쿠폰 적용 가능 여부 확인 + * @param total - 현재 총액 + * @param coupon - 확인할 쿠폰 + * @returns 적용 가능 여부 + */ + isApplicable: (total: number, coupon: Coupon): boolean => { + // percentage 쿠폰은 10,000원 이상 구매 시 사용 가능 + if (coupon.discountType === "percentage" && total < 10000) { + return false; + } + return true; + }, +}; diff --git a/src/advanced/models/product.ts b/src/advanced/models/product.ts new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/src/advanced/models/product.ts @@ -0,0 +1 @@ + diff --git a/src/advanced/utils/formatters.ts b/src/advanced/utils/formatters.ts new file mode 100644 index 000000000..68c1ea5b3 --- /dev/null +++ b/src/advanced/utils/formatters.ts @@ -0,0 +1,7 @@ +export const formatPriceWon = (price: number): string => { + return `${price.toLocaleString()}원`; +}; + +export const formatProductPrice = (price: number): string => { + return `₩${price.toLocaleString()}`; +}; diff --git a/src/advanced/utils/hooks/useDebounce.ts b/src/advanced/utils/hooks/useDebounce.ts new file mode 100644 index 000000000..4e83dbddb --- /dev/null +++ b/src/advanced/utils/hooks/useDebounce.ts @@ -0,0 +1,14 @@ +import { useEffect, useState } from "react"; + +export function useDebounce(value: T, delay: number): T { + const [debouncedValue, setDebouncedValue] = useState(value); + + useEffect(() => { + const timer = setTimeout(() => { + setDebouncedValue(value); + }, delay); + return () => clearTimeout(timer); + }, [value, delay]); + + return debouncedValue; +} diff --git a/src/advanced/utils/hooks/useLocalStorage.ts b/src/advanced/utils/hooks/useLocalStorage.ts new file mode 100644 index 000000000..522421bc7 --- /dev/null +++ b/src/advanced/utils/hooks/useLocalStorage.ts @@ -0,0 +1,46 @@ +// TODO: LocalStorage Hook +// 힌트: +// 1. localStorage와 React state 동기화 +// 2. 초기값 로드 시 에러 처리 +// 3. 저장 시 JSON 직렬화/역직렬화 +// 4. 빈 배열이나 undefined는 삭제 +// +// 반환값: [저장된 값, 값 설정 함수] + +import { useEffect, useState } from "react"; + +export function useLocalStorage( + key: string, + initialValue: T +): [T, (value: T | ((val: T) => T)) => void] { + const [value, setValue] = useState(() => { + try { + const saved = localStorage.getItem(key); + if (!saved) return initialValue; + + return JSON.parse(saved); + } catch (error) { + console.error(`Error "${key}":`, error); + return initialValue; + } + }); + + useEffect(() => { + try { + const shouldRemove = + value === undefined || + value === null || + (Array.isArray(value) && value.length === 0); + + if (shouldRemove) { + localStorage.removeItem(key); + } else { + localStorage.setItem(key, JSON.stringify(value)); + } + } catch (error) { + console.error(`Error "${key}":`, error); + } + }, [key, value]); + + return [value, setValue]; +} diff --git a/src/basic/App.tsx b/src/basic/App.tsx index a4369fe1d..9661f87e9 100644 --- a/src/basic/App.tsx +++ b/src/basic/App.tsx @@ -1,1124 +1,130 @@ -import { useState, useCallback, useEffect } from 'react'; -import { CartItem, Coupon, Product } from '../types'; - -interface ProductWithUI extends Product { - description?: string; - isRecommended?: boolean; -} - -interface Notification { - id: string; - message: string; - type: 'error' | 'success' | 'warning'; -} - -// 초기 데이터 -const initialProducts: ProductWithUI[] = [ - { - id: 'p1', - name: '상품1', - price: 10000, - stock: 20, - discounts: [ - { quantity: 10, rate: 0.1 }, - { quantity: 20, rate: 0.2 } - ], - description: '최고급 품질의 프리미엄 상품입니다.' - }, - { - id: 'p2', - name: '상품2', - price: 20000, - stock: 20, - discounts: [ - { quantity: 10, rate: 0.15 } - ], - description: '다양한 기능을 갖춘 실용적인 상품입니다.', - isRecommended: true - }, - { - id: 'p3', - name: '상품3', - price: 30000, - stock: 20, - discounts: [ - { quantity: 10, rate: 0.2 }, - { quantity: 30, rate: 0.25 } - ], - description: '대용량과 고성능을 자랑하는 상품입니다.' - } -]; - -const initialCoupons: Coupon[] = [ - { - name: '5000원 할인', - code: 'AMOUNT5000', - discountType: 'amount', - discountValue: 5000 - }, - { - name: '10% 할인', - code: 'PERCENT10', - discountType: 'percentage', - discountValue: 10 - } -]; +import { useState, useEffect } from "react"; +import AdminPage from "./components/AdminPage"; +import { useNotification } from "./hooks/useNotification"; +import { useProducts } from "./hooks/useProducts"; +import { useCoupons } from "./hooks/useCoupons"; +import { useSearch } from "./hooks/useSearch"; +import { Notifications } from "./components/Notifications"; +import { Header } from "./components/header"; +import { SearchBar } from "./components/header/SearchBar"; +import { ToggleButton } from "./components/header/ToggleButton"; +import { CartIcon } from "./components/header/CartIcon"; +import { useCart } from "./hooks/useCart"; +import CartPage from "./components/CartPage"; const App = () => { + // 검색 기능 + const { searchTerm, debouncedSearchTerm, setSearchTerm } = useSearch(500); + + // 알림 기능 + const { notifications, addNotification, clearNotification } = + useNotification(); + + const { + products, + addProduct, + updateProduct, + deleteProduct, + filterProductsBySearchTerm, + } = useProducts(); + + const { + coupons, + selectedCoupon, + setSelectedCoupon, + showCouponForm, + setShowCouponForm, + addCoupon, + deleteCoupon, + isDuplicateCoupon, + toggleCouponForm, + applyCoupon, + } = useCoupons({ addNotification }); + + const { + cart, + setCart, + totalItemCount, + addToCart, + updateQuantity, + calculateCartTotal, + calculateItemTotal, + removeFromCart, + getRemainingStock, + } = useCart({ addNotification }); - const [products, setProducts] = useState(() => { - const saved = localStorage.getItem('products'); - if (saved) { - try { - return JSON.parse(saved); - } catch { - return initialProducts; - } - } - return initialProducts; - }); - - const [cart, setCart] = useState(() => { - const saved = localStorage.getItem('cart'); - if (saved) { - try { - return JSON.parse(saved); - } catch { - return []; - } - } - return []; - }); - - const [coupons, setCoupons] = useState(() => { - const saved = localStorage.getItem('coupons'); - if (saved) { - try { - return JSON.parse(saved); - } catch { - return initialCoupons; - } - } - return initialCoupons; - }); - - const [selectedCoupon, setSelectedCoupon] = useState(null); const [isAdmin, setIsAdmin] = useState(false); - const [notifications, setNotifications] = useState([]); - const [showCouponForm, setShowCouponForm] = useState(false); - const [activeTab, setActiveTab] = useState<'products' | 'coupons'>('products'); - const [showProductForm, setShowProductForm] = useState(false); - const [searchTerm, setSearchTerm] = useState(''); - const [debouncedSearchTerm, setDebouncedSearchTerm] = useState(''); - - // Admin - const [editingProduct, setEditingProduct] = useState(null); - const [productForm, setProductForm] = useState({ - name: '', - price: 0, - stock: 0, - description: '', - discounts: [] as Array<{ quantity: number; rate: number }> - }); - - const [couponForm, setCouponForm] = useState({ - name: '', - code: '', - discountType: 'amount' as 'amount' | 'percentage', - discountValue: 0 - }); - - - const formatPrice = (price: number, productId?: string): string => { - if (productId) { - const product = products.find(p => p.id === productId); - if (product && getRemainingStock(product) <= 0) { - return 'SOLD OUT'; - } - } - - if (isAdmin) { - return `${price.toLocaleString()}원`; - } - - return `₩${price.toLocaleString()}`; - }; - - const getMaxApplicableDiscount = (item: CartItem): number => { - const { discounts } = item.product; - const { quantity } = item; - - const baseDiscount = discounts.reduce((maxDiscount, discount) => { - return quantity >= discount.quantity && discount.rate > maxDiscount - ? discount.rate - : maxDiscount; - }, 0); - - const hasBulkPurchase = cart.some(cartItem => cartItem.quantity >= 10); - if (hasBulkPurchase) { - return Math.min(baseDiscount + 0.05, 0.5); // 대량 구매 시 추가 5% 할인 - } - - return baseDiscount; - }; - - const calculateItemTotal = (item: CartItem): number => { - const { price } = item.product; - const { quantity } = item; - const discount = getMaxApplicableDiscount(item); - - return Math.round(price * quantity * (1 - discount)); - }; - - const calculateCartTotal = (): { - totalBeforeDiscount: number; - totalAfterDiscount: number; - } => { - let totalBeforeDiscount = 0; - let totalAfterDiscount = 0; - - cart.forEach(item => { - const itemPrice = item.product.price * item.quantity; - totalBeforeDiscount += itemPrice; - totalAfterDiscount += calculateItemTotal(item); - }); - - if (selectedCoupon) { - if (selectedCoupon.discountType === 'amount') { - totalAfterDiscount = Math.max(0, totalAfterDiscount - selectedCoupon.discountValue); - } else { - totalAfterDiscount = Math.round(totalAfterDiscount * (1 - selectedCoupon.discountValue / 100)); - } - } - - return { - totalBeforeDiscount: Math.round(totalBeforeDiscount), - totalAfterDiscount: Math.round(totalAfterDiscount) - }; - }; - - const getRemainingStock = (product: Product): number => { - const cartItem = cart.find(item => item.product.id === product.id); - const remaining = product.stock - (cartItem?.quantity || 0); - - return remaining; - }; - - const addNotification = useCallback((message: string, type: 'error' | 'success' | 'warning' = 'success') => { - const id = Date.now().toString(); - setNotifications(prev => [...prev, { id, message, type }]); - - setTimeout(() => { - setNotifications(prev => prev.filter(n => n.id !== id)); - }, 3000); - }, []); - - const [totalItemCount, setTotalItemCount] = useState(0); - - - useEffect(() => { - const count = cart.reduce((sum, item) => sum + item.quantity, 0); - setTotalItemCount(count); - }, [cart]); - - useEffect(() => { - localStorage.setItem('products', JSON.stringify(products)); - }, [products]); - - useEffect(() => { - localStorage.setItem('coupons', JSON.stringify(coupons)); - }, [coupons]); - - useEffect(() => { - if (cart.length > 0) { - localStorage.setItem('cart', JSON.stringify(cart)); - } else { - localStorage.removeItem('cart'); - } - }, [cart]); - - useEffect(() => { - const timer = setTimeout(() => { - setDebouncedSearchTerm(searchTerm); - }, 500); - return () => clearTimeout(timer); - }, [searchTerm]); - - const addToCart = useCallback((product: ProductWithUI) => { - const remainingStock = getRemainingStock(product); - if (remainingStock <= 0) { - addNotification('재고가 부족합니다!', 'error'); - return; - } - - setCart(prevCart => { - const existingItem = prevCart.find(item => item.product.id === product.id); - - if (existingItem) { - const newQuantity = existingItem.quantity + 1; - - if (newQuantity > product.stock) { - addNotification(`재고는 ${product.stock}개까지만 있습니다.`, 'error'); - return prevCart; - } - - return prevCart.map(item => - item.product.id === product.id - ? { ...item, quantity: newQuantity } - : item - ); - } - - return [...prevCart, { product, quantity: 1 }]; - }); - - addNotification('장바구니에 담았습니다', 'success'); - }, [cart, addNotification, getRemainingStock]); - - const removeFromCart = useCallback((productId: string) => { - setCart(prevCart => prevCart.filter(item => item.product.id !== productId)); - }, []); - - const updateQuantity = useCallback((productId: string, newQuantity: number) => { - if (newQuantity <= 0) { - removeFromCart(productId); - return; - } - const product = products.find(p => p.id === productId); - if (!product) return; - - const maxStock = product.stock; - if (newQuantity > maxStock) { - addNotification(`재고는 ${maxStock}개까지만 있습니다.`, 'error'); - return; - } - - setCart(prevCart => - prevCart.map(item => - item.product.id === productId - ? { ...item, quantity: newQuantity } - : item - ) - ); - }, [products, removeFromCart, addNotification, getRemainingStock]); - - const applyCoupon = useCallback((coupon: Coupon) => { - const currentTotal = calculateCartTotal().totalAfterDiscount; - - if (currentTotal < 10000 && coupon.discountType === 'percentage') { - addNotification('percentage 쿠폰은 10,000원 이상 구매 시 사용 가능합니다.', 'error'); - return; - } - - setSelectedCoupon(coupon); - addNotification('쿠폰이 적용되었습니다.', 'success'); - }, [addNotification, calculateCartTotal]); - - const completeOrder = useCallback(() => { - const orderNumber = `ORD-${Date.now()}`; - addNotification(`주문이 완료되었습니다. 주문번호: ${orderNumber}`, 'success'); - setCart([]); - setSelectedCoupon(null); - }, [addNotification]); - - const addProduct = useCallback((newProduct: Omit) => { - const product: ProductWithUI = { - ...newProduct, - id: `p${Date.now()}` - }; - setProducts(prev => [...prev, product]); - addNotification('상품이 추가되었습니다.', 'success'); - }, [addNotification]); - - const updateProduct = useCallback((productId: string, updates: Partial) => { - setProducts(prev => - prev.map(product => - product.id === productId - ? { ...product, ...updates } - : product - ) - ); - addNotification('상품이 수정되었습니다.', 'success'); - }, [addNotification]); - - const deleteProduct = useCallback((productId: string) => { - setProducts(prev => prev.filter(p => p.id !== productId)); - addNotification('상품이 삭제되었습니다.', 'success'); - }, [addNotification]); - - const addCoupon = useCallback((newCoupon: Coupon) => { - const existingCoupon = coupons.find(c => c.code === newCoupon.code); - if (existingCoupon) { - addNotification('이미 존재하는 쿠폰 코드입니다.', 'error'); - return; - } - setCoupons(prev => [...prev, newCoupon]); - addNotification('쿠폰이 추가되었습니다.', 'success'); - }, [coupons, addNotification]); - - const deleteCoupon = useCallback((couponCode: string) => { - setCoupons(prev => prev.filter(c => c.code !== couponCode)); - if (selectedCoupon?.code === couponCode) { - setSelectedCoupon(null); - } - addNotification('쿠폰이 삭제되었습니다.', 'success'); - }, [selectedCoupon, addNotification]); - - const handleProductSubmit = (e: React.FormEvent) => { - e.preventDefault(); - if (editingProduct && editingProduct !== 'new') { - updateProduct(editingProduct, productForm); - setEditingProduct(null); - } else { - addProduct({ - ...productForm, - discounts: productForm.discounts - }); - } - setProductForm({ name: '', price: 0, stock: 0, description: '', discounts: [] }); - setEditingProduct(null); - setShowProductForm(false); - }; - - const handleCouponSubmit = (e: React.FormEvent) => { - e.preventDefault(); - addCoupon(couponForm); - setCouponForm({ - name: '', - code: '', - discountType: 'amount', - discountValue: 0 - }); - setShowCouponForm(false); - }; - - const startEditProduct = (product: ProductWithUI) => { - setEditingProduct(product.id); - setProductForm({ - name: product.name, - price: product.price, - stock: product.stock, - description: product.description || '', - discounts: product.discounts || [] - }); - setShowProductForm(true); - }; - - const totals = calculateCartTotal(); - - const filteredProducts = debouncedSearchTerm - ? products.filter(product => - product.name.toLowerCase().includes(debouncedSearchTerm.toLowerCase()) || - (product.description && product.description.toLowerCase().includes(debouncedSearchTerm.toLowerCase())) - ) - : products; + const totals = calculateCartTotal(selectedCoupon); + // 검색어로 상품 필터링 + const filteredProducts = filterProductsBySearchTerm(debouncedSearchTerm); return (
{notifications.length > 0 && ( -
- {notifications.map(notif => ( -
- {notif.message} - -
- ))} -
+ )} -
-
-
-
-

SHOP

- {/* 검색창 - 안티패턴: 검색 로직이 컴포넌트에 직접 포함 */} - {!isAdmin && ( -
- setSearchTerm(e.target.value)} - placeholder="상품 검색..." - className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" - /> -
- )} +
+
- -
-
-
- + ) + } + rightSide={ + + } + />
{isAdmin ? ( -
-
-

관리자 대시보드

-

상품과 쿠폰을 관리할 수 있습니다

-
-
- -
- - {activeTab === 'products' ? ( -
-
-
-

상품 목록

- -
-
- -
- - - - - - - - - - - - {(activeTab === 'products' ? products : products).map(product => ( - - - - - - - - ))} - -
상품명가격재고설명작업
{product.name}{formatPrice(product.price, product.id)} - 10 ? 'bg-green-100 text-green-800' : - product.stock > 0 ? 'bg-yellow-100 text-yellow-800' : - 'bg-red-100 text-red-800' - }`}> - {product.stock}개 - - {product.description || '-'} - - -
-
- {showProductForm && ( -
-
-

- {editingProduct === 'new' ? '새 상품 추가' : '상품 수정'} -

-
-
- - setProductForm({ ...productForm, name: e.target.value })} - className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border" - required - /> -
-
- - setProductForm({ ...productForm, description: e.target.value })} - className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border" - /> -
-
- - { - const value = e.target.value; - if (value === '' || /^\d+$/.test(value)) { - setProductForm({ ...productForm, price: value === '' ? 0 : parseInt(value) }); - } - }} - onBlur={(e) => { - const value = e.target.value; - if (value === '') { - setProductForm({ ...productForm, price: 0 }); - } else if (parseInt(value) < 0) { - addNotification('가격은 0보다 커야 합니다', 'error'); - setProductForm({ ...productForm, price: 0 }); - } - }} - className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border" - placeholder="숫자만 입력" - required - /> -
-
- - { - const value = e.target.value; - if (value === '' || /^\d+$/.test(value)) { - setProductForm({ ...productForm, stock: value === '' ? 0 : parseInt(value) }); - } - }} - onBlur={(e) => { - const value = e.target.value; - if (value === '') { - setProductForm({ ...productForm, stock: 0 }); - } else if (parseInt(value) < 0) { - addNotification('재고는 0보다 커야 합니다', 'error'); - setProductForm({ ...productForm, stock: 0 }); - } else if (parseInt(value) > 9999) { - addNotification('재고는 9999개를 초과할 수 없습니다', 'error'); - setProductForm({ ...productForm, stock: 9999 }); - } - }} - className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border" - placeholder="숫자만 입력" - required - /> -
-
-
- -
- {productForm.discounts.map((discount, index) => ( -
- { - const newDiscounts = [...productForm.discounts]; - newDiscounts[index].quantity = parseInt(e.target.value) || 0; - setProductForm({ ...productForm, discounts: newDiscounts }); - }} - className="w-20 px-2 py-1 border rounded" - min="1" - placeholder="수량" - /> - 개 이상 구매 시 - { - const newDiscounts = [...productForm.discounts]; - newDiscounts[index].rate = (parseInt(e.target.value) || 0) / 100; - setProductForm({ ...productForm, discounts: newDiscounts }); - }} - className="w-16 px-2 py-1 border rounded" - min="0" - max="100" - placeholder="%" - /> - % 할인 - -
- ))} - -
-
- -
- - -
-
-
- )} -
- ) : ( -
-
-

쿠폰 관리

-
-
-
- {coupons.map(coupon => ( -
-
-
-

{coupon.name}

-

{coupon.code}

-
- - {coupon.discountType === 'amount' - ? `${coupon.discountValue.toLocaleString()}원 할인` - : `${coupon.discountValue}% 할인`} - -
-
- -
-
- ))} - -
- -
-
- - {showCouponForm && ( -
-
-

새 쿠폰 생성

-
-
- - setCouponForm({ ...couponForm, name: e.target.value })} - className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border text-sm" - placeholder="신규 가입 쿠폰" - required - /> -
-
- - setCouponForm({ ...couponForm, code: e.target.value.toUpperCase() })} - className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border text-sm font-mono" - placeholder="WELCOME2024" - required - /> -
-
- - -
-
- - { - const value = e.target.value; - if (value === '' || /^\d+$/.test(value)) { - setCouponForm({ ...couponForm, discountValue: value === '' ? 0 : parseInt(value) }); - } - }} - onBlur={(e) => { - const value = parseInt(e.target.value) || 0; - if (couponForm.discountType === 'percentage') { - if (value > 100) { - addNotification('할인율은 100%를 초과할 수 없습니다', 'error'); - setCouponForm({ ...couponForm, discountValue: 100 }); - } else if (value < 0) { - setCouponForm({ ...couponForm, discountValue: 0 }); - } - } else { - if (value > 100000) { - addNotification('할인 금액은 100,000원을 초과할 수 없습니다', 'error'); - setCouponForm({ ...couponForm, discountValue: 100000 }); - } else if (value < 0) { - setCouponForm({ ...couponForm, discountValue: 0 }); - } - } - }} - className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border text-sm" - placeholder={couponForm.discountType === 'amount' ? '5000' : '10'} - required - /> -
-
-
- - -
-
-
- )} -
-
- )} -
+ ) : ( -
-
- {/* 상품 목록 */} -
-
-

전체 상품

-
- 총 {products.length}개 상품 -
-
- {filteredProducts.length === 0 ? ( -
-

"{debouncedSearchTerm}"에 대한 검색 결과가 없습니다.

-
- ) : ( -
- {filteredProducts.map(product => { - const remainingStock = getRemainingStock(product); - - return ( -
- {/* 상품 이미지 영역 (placeholder) */} -
-
- - - -
- {product.isRecommended && ( - - BEST - - )} - {product.discounts.length > 0 && ( - - ~{Math.max(...product.discounts.map(d => d.rate)) * 100}% - - )} -
- - {/* 상품 정보 */} -
-

{product.name}

- {product.description && ( -

{product.description}

- )} - - {/* 가격 정보 */} -
-

{formatPrice(product.price, product.id)}

- {product.discounts.length > 0 && ( -

- {product.discounts[0].quantity}개 이상 구매시 할인 {product.discounts[0].rate * 100}% -

- )} -
- - {/* 재고 상태 */} -
- {remainingStock <= 5 && remainingStock > 0 && ( -

품절임박! {remainingStock}개 남음

- )} - {remainingStock > 5 && ( -

재고 {remainingStock}개

- )} -
- - {/* 장바구니 버튼 */} - -
-
- ); - })} -
- )} -
-
- -
-
-
-

- - - - 장바구니 -

- {cart.length === 0 ? ( -
- - - -

장바구니가 비어있습니다

-
- ) : ( -
- {cart.map(item => { - const itemTotal = calculateItemTotal(item); - const originalPrice = item.product.price * item.quantity; - const hasDiscount = itemTotal < originalPrice; - const discountRate = hasDiscount ? Math.round((1 - itemTotal / originalPrice) * 100) : 0; - - return ( -
-
-

{item.product.name}

- -
-
-
- - {item.quantity} - -
-
- {hasDiscount && ( - -{discountRate}% - )} -

- {Math.round(itemTotal).toLocaleString()}원 -

-
-
-
- ); - })} -
- )} -
- - {cart.length > 0 && ( - <> -
-
-

쿠폰 할인

- -
- {coupons.length > 0 && ( - - )} -
- -
-

결제 정보

-
-
- 상품 금액 - {totals.totalBeforeDiscount.toLocaleString()}원 -
- {totals.totalBeforeDiscount - totals.totalAfterDiscount > 0 && ( -
- 할인 금액 - -{(totals.totalBeforeDiscount - totals.totalAfterDiscount).toLocaleString()}원 -
- )} -
- 결제 예정 금액 - {totals.totalAfterDiscount.toLocaleString()}원 -
-
- - - -
-

* 실제 결제는 이루어지지 않습니다

-
-
- - )} -
-
-
+ )}
); }; -export default App; \ No newline at end of file +export default App; diff --git a/src/basic/components/AdminPage.tsx b/src/basic/components/AdminPage.tsx new file mode 100644 index 000000000..63b506995 --- /dev/null +++ b/src/basic/components/AdminPage.tsx @@ -0,0 +1,213 @@ +// 1. 탭 UI로 상품 관리와 쿠폰 관리 분리 +// 2. 상품 추가/수정/삭제 기능 +// 3. 쿠폰 생성 기능 +// 4. 할인 규칙 설정 +// +// 필요한 hooks: +// - useProducts: 상품 CRUD +// - useCoupons: 쿠폰 CRUD +// +// 하위 컴포넌트: +// - ProductForm: 새 상품 추가 폼 +// - ProductAccordion: 상품 정보 표시 및 수정 +// - CouponForm: 새 쿠폰 추가 폼 +// - CouponList: 쿠폰 목록 표시 + +import { useState } from "react"; +import { type ProductWithUI } from "../hooks/useProducts"; +import { ProductList } from "./admin/ProductList"; +import { useProductForm } from "../hooks/useProductForm"; +import { ProductForm } from "./admin/ProductForm"; +import { CouponList } from "./admin/CouponList"; +import { useCouponForm } from "../hooks/useCouponForm"; +import { CouponForm } from "./admin/CouponForm"; +import { Coupon } from "../../types"; + +interface AdminPageProps { + products: ProductWithUI[]; + addProduct: (product: Omit) => void; + updateProduct: (productId: string, updates: Partial) => void; + deleteProduct: (product: string) => void; + addNotification: ( + message: string, + type: "error" | "success" | "warning" + ) => void; + coupons: Coupon[]; + addCoupon: (coupon: Coupon) => void; + deleteCoupon: (couponCode: string) => void; + isDuplicateCoupon: (coupon: Coupon) => boolean; + toggleCouponForm: () => void; + showCouponForm: boolean; + setShowCouponForm: (show: boolean) => void; +} + +const AdminPage = ({ + products, + addProduct, + updateProduct, + deleteProduct, + addNotification, + coupons, + addCoupon, + deleteCoupon, + isDuplicateCoupon, + toggleCouponForm, + showCouponForm, + setShowCouponForm, +}: AdminPageProps) => { + const { + productForm, + setProductForm, + editingProduct, + setEditingProduct, + showProductForm, + setShowProductForm, + updateProductForm, + resetProductForm, + } = useProductForm(); + + const { couponForm, updateCouponForm, resetCouponForm } = useCouponForm(); + + const [activeTab, setActiveTab] = useState<"products" | "coupons">( + "products" + ); + + const startEditProduct = (product: ProductWithUI) => { + setEditingProduct(product.id); + setProductForm({ + name: product.name, + price: product.price, + stock: product.stock, + description: product.description || "", + discounts: product.discounts || [], + }); + setShowProductForm(true); + }; + + const handleNewProduct = () => { + resetProductForm(); + setEditingProduct("new"); + setShowProductForm(true); + }; + + const handleProductSubmit = (e: React.FormEvent) => { + e.preventDefault(); + if (editingProduct && editingProduct !== "new") { + updateProduct(editingProduct, productForm); + addNotification("상품이 수정되었습니다.", "success"); + } else { + addProduct({ + ...productForm, + discounts: productForm.discounts, + }); + addNotification("상품이 추가되었습니다.", "success"); + } + resetProductForm(); + }; + + const handleCouponSubmit = (e: React.FormEvent) => { + e.preventDefault(); + if (isDuplicateCoupon(couponForm)) { + addNotification("이미 존재하는 쿠폰 코드입니다.", "error"); + return; + } + addCoupon(couponForm); + addNotification("쿠폰이 추가되었습니다.", "success"); + resetCouponForm(); + setShowCouponForm(false); + }; + + return ( +
+
+

관리자 대시보드

+

상품과 쿠폰을 관리할 수 있습니다

+
+
+ +
+ + {activeTab === "products" ? ( +
+
+
+

상품 목록

+ +
+
+ + + {showProductForm && ( + + )} +
+ ) : ( +
+
+

쿠폰 관리

+
+
+ + + {showCouponForm && ( +
+ +
+ )} +
+
+ )} +
+ ); +}; + +export default AdminPage; diff --git a/src/basic/components/CartPage.tsx b/src/basic/components/CartPage.tsx new file mode 100644 index 000000000..0c95b1275 --- /dev/null +++ b/src/basic/components/CartPage.tsx @@ -0,0 +1,131 @@ +import { useCallback } from "react"; +import { CartItem, Coupon } from "../../types"; +import { ProductWithUI } from "../hooks/useProducts"; +import { ProductCard } from "./cart/ProductCard"; +import { ShoppingCart } from "./cart/ShoppingCart"; +import { SelectCoupon } from "./cart/SelectCoupon"; +import { PaymentInfo } from "./cart/PaymentInfo"; + +interface CartPageProps { + products: ProductWithUI[]; + filteredProducts: ProductWithUI[]; + debouncedSearchTerm: string; + getRemainingStock: (product: ProductWithUI) => number; + addToCart: (product: ProductWithUI) => void; + cart: CartItem[]; + removeFromCart: (productId: string) => void; + updateQuantity: ( + productId: string, + quantity: number, + product: ProductWithUI + ) => void; + coupons: Coupon[]; + selectedCoupon: Coupon | null; + applyCoupon: (coupon: Coupon, currentTotal: number) => void; + totals: { + totalBeforeDiscount: number; + totalAfterDiscount: number; + }; + calculateItemTotal: (item: CartItem) => number; + setSelectedCoupon: (coupon: Coupon | null) => void; + addNotification: ( + message: string, + type: "error" | "success" | "warning" + ) => void; + setCart: (cart: CartItem[]) => void; +} + +const CartPage = ({ + products, + filteredProducts, + debouncedSearchTerm, + getRemainingStock, + cart, + setCart, + addToCart, + removeFromCart, + updateQuantity, + coupons, + selectedCoupon, + setSelectedCoupon, + applyCoupon, + totals, + calculateItemTotal, + addNotification, +}: CartPageProps) => { + const completeOrder = useCallback(() => { + const orderNumber = `ORD-${Date.now()}`; + addNotification( + `주문이 완료되었습니다. 주문번호: ${orderNumber}`, + "success" + ); + setCart([]); + setSelectedCoupon(null); + }, [addNotification]); + + return ( +
+
+ {/* 상품 목록 */} +
+
+

전체 상품

+
+ 총 {products.length}개 상품 +
+
+ {filteredProducts.length === 0 ? ( +
+

+ "{debouncedSearchTerm}"에 대한 검색 결과가 없습니다. +

+
+ ) : ( +
+ {filteredProducts.map((product) => { + const remainingStock = getRemainingStock(product); + return ( + + ); + })} +
+ )} +
+
+ +
+
+ + + {cart.length > 0 && ( + <> + {coupons.length > 0 && ( + + )} + + + + )} +
+
+
+ ); +}; + +export default CartPage; diff --git a/src/basic/components/Notifications.tsx b/src/basic/components/Notifications.tsx new file mode 100644 index 000000000..968ef11ed --- /dev/null +++ b/src/basic/components/Notifications.tsx @@ -0,0 +1,48 @@ +import { NotificationType } from "../hooks/useNotification"; + +interface NotificationsProps { + notifications: NotificationType[]; + clearNotification: (id: string) => void; +} + +export const Notifications = ({ + notifications, + clearNotification, +}: NotificationsProps) => { + return ( +
+ {notifications.map((notif) => ( +
+ {notif.message} + +
+ ))} +
+ ); +}; diff --git a/src/basic/components/admin/CouponForm.tsx b/src/basic/components/admin/CouponForm.tsx new file mode 100644 index 000000000..5d0a9864d --- /dev/null +++ b/src/basic/components/admin/CouponForm.tsx @@ -0,0 +1,163 @@ +import { CouponFormType } from "../../hooks/useCouponForm"; + +interface CouponFormProps { + couponForm: { + name: string; + code: string; + discountType: "amount" | "percentage"; + discountValue: number; + }; + updateCouponForm: (updates: Partial) => void; + handleCouponSubmit: (e: React.FormEvent) => void; + addNotification: ( + message: string, + type: "error" | "success" | "warning" + ) => void; + setShowCouponForm: (show: boolean) => void; +} + +export const CouponForm = ({ + couponForm, + updateCouponForm, + handleCouponSubmit, + addNotification, + setShowCouponForm, +}: CouponFormProps) => { + return ( +
+
+

새 쿠폰 생성

+
+
+ + + updateCouponForm({ + ...couponForm, + name: e.target.value, + }) + } + className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border text-sm" + placeholder="신규 가입 쿠폰" + required + /> +
+
+ + + updateCouponForm({ + ...couponForm, + code: e.target.value.toUpperCase(), + }) + } + className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border text-sm font-mono" + placeholder="WELCOME2024" + required + /> +
+
+ + +
+
+ + { + const value = e.target.value; + if (value === "" || /^\d+$/.test(value)) { + updateCouponForm({ + ...couponForm, + discountValue: value === "" ? 0 : parseInt(value), + }); + } + }} + onBlur={(e) => { + const value = parseInt(e.target.value) || 0; + if (couponForm.discountType === "percentage") { + if (value > 100) { + addNotification( + "할인율은 100%를 초과할 수 없습니다", + "error" + ); + updateCouponForm({ + ...couponForm, + discountValue: 100, + }); + } else if (value < 0) { + updateCouponForm({ + ...couponForm, + discountValue: 0, + }); + } + } else { + if (value > 100000) { + addNotification( + "할인 금액은 100,000원을 초과할 수 없습니다", + "error" + ); + updateCouponForm({ + ...couponForm, + discountValue: 100000, + }); + } else if (value < 0) { + updateCouponForm({ + ...couponForm, + discountValue: 0, + }); + } + } + }} + className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border text-sm" + placeholder={couponForm.discountType === "amount" ? "5000" : "10"} + required + /> +
+
+
+ + +
+
+
+ ); +}; diff --git a/src/basic/components/admin/CouponList.tsx b/src/basic/components/admin/CouponList.tsx new file mode 100644 index 000000000..c8a8bf526 --- /dev/null +++ b/src/basic/components/admin/CouponList.tsx @@ -0,0 +1,95 @@ +import { useEffect } from "react"; +import { Coupon } from "../../../types"; + +interface CouponListProps { + coupons: Coupon[]; + deleteCoupon: (couponCode: string) => void; + toggleCouponForm: () => void; + addNotification: ( + message: string, + type: "error" | "success" | "warning" + ) => void; +} + +export const CouponList = ({ + coupons, + deleteCoupon, + toggleCouponForm, + addNotification, +}: CouponListProps) => { + const handleDeleteCoupon = (couponCode: string) => { + deleteCoupon(couponCode); + addNotification("쿠폰이 삭제되었습니다.", "success"); + }; + + useEffect(() => { + localStorage.setItem("coupons", JSON.stringify(coupons)); + }, [coupons]); + + return ( +
+ {coupons.map((coupon) => ( +
+
+
+

{coupon.name}

+

+ {coupon.code} +

+
+ + {coupon.discountType === "amount" + ? `${coupon.discountValue.toLocaleString()}원 할인` + : `${coupon.discountValue}% 할인`} + +
+
+ +
+
+ ))} + +
+ +
+
+ ); +}; diff --git a/src/basic/components/admin/ProductForm.tsx b/src/basic/components/admin/ProductForm.tsx new file mode 100644 index 000000000..8ce44281b --- /dev/null +++ b/src/basic/components/admin/ProductForm.tsx @@ -0,0 +1,236 @@ +import { type ProductFormType } from "../../hooks/useProductForm"; + +interface ProductFormProps { + productForm: ProductFormType; + editingProduct: string | null; + updateProductForm: (updates: Partial) => void; + resetProductForm: () => void; + handleProductSubmit: (e: React.FormEvent) => void; + addNotification: ( + message: string, + type: "error" | "success" | "warning" + ) => void; +} +export const ProductForm = ({ + productForm, + editingProduct, + updateProductForm, + resetProductForm, + handleProductSubmit, + addNotification, +}: ProductFormProps) => { + return ( +
+
+

+ {editingProduct === "new" ? "새 상품 추가" : "상품 수정"} +

+
+
+ + + updateProductForm({ + name: e.target.value, + }) + } + className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border" + required + /> +
+
+ + + updateProductForm({ + description: e.target.value, + }) + } + className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border" + /> +
+
+ + { + const value = e.target.value; + if (value === "" || /^\d+$/.test(value)) { + updateProductForm({ + price: value === "" ? 0 : parseInt(value), + }); + } + }} + onBlur={(e) => { + const value = e.target.value; + if (value === "") { + updateProductForm({ price: 0 }); + } else if (parseInt(value) < 0) { + updateProductForm({ price: 0 }); + addNotification("가격은 0보다 커야 합니다", "error"); + } + }} + className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border" + placeholder="숫자만 입력" + required + /> +
+
+ + { + const value = e.target.value; + if (value === "" || /^\d+$/.test(value)) { + updateProductForm({ + stock: value === "" ? 0 : parseInt(value), + }); + } + }} + onBlur={(e) => { + const value = e.target.value; + if (value === "") { + updateProductForm({ stock: 0 }); + } else if (parseInt(value) < 0) { + addNotification("재고는 0보다 커야 합니다", "error"); + updateProductForm({ stock: 0 }); + } else if (parseInt(value) > 9999) { + addNotification( + "재고는 9999개를 초과할 수 없습니다", + "error" + ); + updateProductForm({ stock: 9999 }); + } + }} + className="w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 px-3 py-2 border" + placeholder="숫자만 입력" + required + /> +
+
+
+ +
+ {productForm.discounts.map((discount, index) => ( +
+ { + const newDiscounts = [...productForm.discounts]; + newDiscounts[index].quantity = + parseInt(e.target.value) || 0; + updateProductForm({ + discounts: newDiscounts, + }); + }} + className="w-20 px-2 py-1 border rounded" + min="1" + placeholder="수량" + /> + 개 이상 구매 시 + { + const newDiscounts = [...productForm.discounts]; + newDiscounts[index].rate = + (parseInt(e.target.value) || 0) / 100; + updateProductForm({ + discounts: newDiscounts, + }); + }} + className="w-16 px-2 py-1 border rounded" + min="0" + max="100" + placeholder="%" + /> + % 할인 + +
+ ))} + +
+
+ +
+ + +
+
+
+ ); +}; diff --git a/src/basic/components/admin/ProductList.tsx b/src/basic/components/admin/ProductList.tsx new file mode 100644 index 000000000..4dec20e4e --- /dev/null +++ b/src/basic/components/admin/ProductList.tsx @@ -0,0 +1,97 @@ +import { useEffect } from "react"; +import { ProductWithUI } from "../../hooks/useProducts"; +import { formatPriceWon } from "../../utils/formatters"; + +interface ProductListProps { + products: ProductWithUI[]; + deleteProduct: (productId: string) => void; + startEditProduct: (product: ProductWithUI) => void; + addNotification: ( + message: string, + type: "error" | "success" | "warning" + ) => void; +} + +export const ProductList = ({ + products, + deleteProduct, + startEditProduct, + addNotification, +}: ProductListProps) => { + const handleDelete = (productId: string) => { + deleteProduct(productId); + addNotification("상품이 삭제되었습니다.", "success"); + }; + + useEffect(() => { + localStorage.setItem("products", JSON.stringify(products)); + }, [products]); + + return ( +
+ + + + + + + + + + + + {products.map((product) => ( + + + + + + + + ))} + +
+ 상품명 + + 가격 + + 재고 + + 설명 + + 작업 +
+ {product.name} + + {formatPriceWon(product.price)} + + 10 + ? "bg-green-100 text-green-800" + : product.stock > 0 + ? "bg-yellow-100 text-yellow-800" + : "bg-red-100 text-red-800" + }`} + > + {product.stock}개 + + + {product.description || "-"} + + + +
+
+ ); +}; diff --git a/src/basic/components/cart/PaymentInfo.tsx b/src/basic/components/cart/PaymentInfo.tsx new file mode 100644 index 000000000..1841d09e5 --- /dev/null +++ b/src/basic/components/cart/PaymentInfo.tsx @@ -0,0 +1,51 @@ +interface PaymentInfoProps { + totals: { + totalBeforeDiscount: number; + totalAfterDiscount: number; + }; + completeOrder: () => void; +} +export const PaymentInfo = ({ totals, completeOrder }: PaymentInfoProps) => { + return ( +
+

결제 정보

+
+
+ 상품 금액 + + {totals.totalBeforeDiscount.toLocaleString()}원 + +
+ {totals.totalBeforeDiscount - totals.totalAfterDiscount > 0 && ( +
+ 할인 금액 + + - + {( + totals.totalBeforeDiscount - totals.totalAfterDiscount + ).toLocaleString()} + 원 + +
+ )} +
+ 결제 예정 금액 + + {totals.totalAfterDiscount.toLocaleString()}원 + +
+
+ + + +
+

* 실제 결제는 이루어지지 않습니다

+
+
+ ); +}; diff --git a/src/basic/components/cart/ProductCard.tsx b/src/basic/components/cart/ProductCard.tsx new file mode 100644 index 000000000..46f26a1f7 --- /dev/null +++ b/src/basic/components/cart/ProductCard.tsx @@ -0,0 +1,94 @@ +import { ProductWithUI } from "../../hooks/useProducts"; +import { formatProductPrice } from "../../utils/formatters"; + +interface ProductCardProps { + product: ProductWithUI; + remainingStock: number; + addToCart: (product: ProductWithUI) => void; +} +export const ProductCard = ({ + product, + remainingStock, + addToCart, +}: ProductCardProps) => { + const price = + remainingStock <= 0 ? "SOLD OUT" : formatProductPrice(product.price); + return ( +
+ {/* 상품 이미지 영역 (placeholder) */} +
+
+ + + +
+ {product.isRecommended && ( + + BEST + + )} + {product.discounts.length > 0 && ( + + ~{Math.max(...product.discounts.map((d) => d.rate)) * 100}% + + )} +
+ + {/* 상품 정보 */} +
+

{product.name}

+ {product.description && ( +

+ {product.description} +

+ )} + + {/* 가격 정보 */} +
+

{price}

+ {product.discounts.length > 0 && ( +

+ {product.discounts[0].quantity}개 이상 구매시 할인{" "} + {product.discounts[0].rate * 100}% +

+ )} +
+ + {/* 재고 상태 */} +
+ {remainingStock <= 5 && remainingStock > 0 && ( +

+ 품절임박! {remainingStock}개 남음 +

+ )} + {remainingStock > 5 && ( +

재고 {remainingStock}개

+ )} +
+ + {/* 장바구니 버튼 */} + +
+
+ ); +}; diff --git a/src/basic/components/cart/SelectCoupon.tsx b/src/basic/components/cart/SelectCoupon.tsx new file mode 100644 index 000000000..ccc37c4ef --- /dev/null +++ b/src/basic/components/cart/SelectCoupon.tsx @@ -0,0 +1,51 @@ +import { Coupon } from "../../../types"; + +interface SelectCouponProps { + selectedCoupon: Coupon | null; + coupons: Coupon[]; + applyCoupon: (coupon: Coupon, currentTotal: number) => void; + setSelectedCoupon: (coupon: Coupon | null) => void; + totals: { + totalBeforeDiscount: number; + totalAfterDiscount: number; + }; +} + +export const SelectCoupon = ({ + selectedCoupon, + coupons, + applyCoupon, + setSelectedCoupon, + totals, +}: SelectCouponProps) => { + return ( +
+
+

쿠폰 할인

+ +
+ +
+ ); +}; diff --git a/src/basic/components/cart/ShoppingCart.tsx b/src/basic/components/cart/ShoppingCart.tsx new file mode 100644 index 000000000..d5c5327b0 --- /dev/null +++ b/src/basic/components/cart/ShoppingCart.tsx @@ -0,0 +1,142 @@ +import { CartItem } from "../../../types"; +import { ProductWithUI } from "../../hooks/useProducts"; + +interface ShoppingCartProps { + cart: CartItem[]; + calculateItemTotal: (item: CartItem) => number; + removeFromCart: (productId: string) => void; + updateQuantity: ( + productId: string, + quantity: number, + product: ProductWithUI + ) => void; +} + +export const ShoppingCart = ({ + cart, + calculateItemTotal, + removeFromCart, + updateQuantity, +}: ShoppingCartProps) => { + return ( +
+

+ + + + 장바구니 +

+ {cart.length === 0 ? ( +
+ + + +

장바구니가 비어있습니다

+
+ ) : ( +
+ {cart.map((item) => { + const itemTotal = calculateItemTotal(item); + const originalPrice = item.product.price * item.quantity; + const hasDiscount = itemTotal < originalPrice; + const discountRate = hasDiscount + ? Math.round((1 - itemTotal / originalPrice) * 100) + : 0; + + return ( +
+
+

+ {item.product.name} +

+ +
+
+
+ + + {item.quantity} + + +
+
+ {hasDiscount && ( + + -{discountRate}% + + )} +

+ {Math.round(itemTotal).toLocaleString()}원 +

+
+
+
+ ); + })} +
+ )} +
+ ); +}; diff --git a/src/basic/components/header/CartIcon.tsx b/src/basic/components/header/CartIcon.tsx new file mode 100644 index 000000000..ba5f1a1ea --- /dev/null +++ b/src/basic/components/header/CartIcon.tsx @@ -0,0 +1,31 @@ +import { CartItem } from "../../../types"; + +interface CartIconProps { + cart: CartItem[]; + totalItemCount: number; +} + +export const CartIcon = ({ cart, totalItemCount }: CartIconProps) => { + return ( +
+ + + + {cart.length > 0 && ( + + {totalItemCount} + + )} +
+ ); +}; diff --git a/src/basic/components/header/SearchBar.tsx b/src/basic/components/header/SearchBar.tsx new file mode 100644 index 000000000..09ffaa133 --- /dev/null +++ b/src/basic/components/header/SearchBar.tsx @@ -0,0 +1,21 @@ +interface SearchBarProps { + value: string; + onChange: (value: string) => void; + placeholder?: string; +} + +export const SearchBar = ({ + value, + onChange, + placeholder = "상품 검색...", +}: SearchBarProps) => { + return ( + onChange(e.target.value)} + placeholder={placeholder} + className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" + /> + ); +}; diff --git a/src/basic/components/header/ToggleButton.tsx b/src/basic/components/header/ToggleButton.tsx new file mode 100644 index 000000000..52b80ccac --- /dev/null +++ b/src/basic/components/header/ToggleButton.tsx @@ -0,0 +1,17 @@ +interface ToggleButtonProps { + isAdmin: boolean; + setIsAdmin: (isAdmin: boolean) => void; +} + +export const ToggleButton = ({ isAdmin, setIsAdmin }: ToggleButtonProps) => { + return ( + + ); +}; diff --git a/src/basic/components/header/index.tsx b/src/basic/components/header/index.tsx new file mode 100644 index 000000000..7adbf228e --- /dev/null +++ b/src/basic/components/header/index.tsx @@ -0,0 +1,20 @@ +interface HeaderProps { + leftSide: React.ReactNode; + rightSide: React.ReactNode; +} + +export const Header = ({ leftSide, rightSide }: HeaderProps) => { + return ( +
+
+
+
+

SHOP

+ {leftSide} +
+ +
+
+
+ ); +}; diff --git a/src/basic/constants/index.ts b/src/basic/constants/index.ts new file mode 100644 index 000000000..2a5f2432d --- /dev/null +++ b/src/basic/constants/index.ts @@ -0,0 +1,56 @@ +import { Coupon, Product } from "../../types"; + +interface ProductWithUI extends Product { + description?: string; + isRecommended?: boolean; +} + +// 초기 데이터 +export const initialProducts: ProductWithUI[] = [ + { + id: "p1", + name: "상품1", + price: 10000, + stock: 20, + discounts: [ + { quantity: 10, rate: 0.1 }, + { quantity: 20, rate: 0.2 }, + ], + description: "최고급 품질의 프리미엄 상품입니다.", + }, + { + id: "p2", + name: "상품2", + price: 20000, + stock: 20, + discounts: [{ quantity: 10, rate: 0.15 }], + description: "다양한 기능을 갖춘 실용적인 상품입니다.", + isRecommended: true, + }, + { + id: "p3", + name: "상품3", + price: 30000, + stock: 20, + discounts: [ + { quantity: 10, rate: 0.2 }, + { quantity: 30, rate: 0.25 }, + ], + description: "대용량과 고성능을 자랑하는 상품입니다.", + }, +]; + +export const initialCoupons: Coupon[] = [ + { + name: "5000원 할인", + code: "AMOUNT5000", + discountType: "amount", + discountValue: 5000, + }, + { + name: "10% 할인", + code: "PERCENT10", + discountType: "percentage", + discountValue: 10, + }, +]; diff --git a/src/basic/hooks/useCart.ts b/src/basic/hooks/useCart.ts new file mode 100644 index 000000000..2997e9837 --- /dev/null +++ b/src/basic/hooks/useCart.ts @@ -0,0 +1,128 @@ +import { useEffect, useState } from "react"; +import { CartItem, Coupon } from "../../types"; +import { ProductWithUI } from "./useProducts"; +import { cartModel } from "../models/cart"; +import { couponModel } from "../models/coupon"; +import { useLocalStorage } from "../utils/hooks/useLocalStorage"; + +// 1. 장바구니 상태 관리 (localStorage 연동) +// 2. 상품 추가/삭제/수량 변경 +// 3. 쿠폰 적용 +// 4. 총액 계산 +// 5. 재고 확인 +// +// 사용할 모델 함수: +// - cartModel.addItemToCart +// - cartModel.removeItemFromCart +// - cartModel.updateCartItemQuantity +// - cartModel.calculateCartTotal +// - cartModel.getRemainingStock +// +// 반환할 값: +// - cart: 장바구니 아이템 배열 +// - selectedCoupon: 선택된 쿠폰 +// - addToCart: 상품 추가 함수 +// - removeFromCart: 상품 제거 함수 +// - updateQuantity: 수량 변경 함수 +// - applyCoupon: 쿠폰 적용 함수 +// - calculateTotal: 총액 계산 함수 +// - getRemainingStock: 재고 확인 함수 +// - clearCart: 장바구니 비우기 함수 + +interface UseCartProps { + addNotification: ( + message: string, + type: "error" | "success" | "warning" + ) => void; +} +export const useCart = ({ addNotification }: UseCartProps) => { + const [cart, setCart] = useLocalStorage("cart", []); + const [totalItemCount, setTotalItemCount] = useState(0); + + const addToCart = (product: ProductWithUI) => { + const remainingStock = cartModel.getRemainingStock(cart, product); + const isStockExceeded = cartModel.wouldExceedStock(cart, product); + + if (remainingStock <= 0) { + addNotification("재고가 부족합니다!", "error"); + return; + } + + if (isStockExceeded) { + addNotification(`재고는 ${product.stock}개까지만 있습니다.`, "error"); + return; + } + + const newCart = cartModel.addItemToCart(cart, product); + setCart(newCart); + addNotification("장바구니에 담았습니다", "success"); + }; + + const updateQuantity = ( + productId: string, + newQuantity: number, + product: ProductWithUI + ) => { + if (newQuantity > product.stock) { + addNotification(`재고는 ${product.stock}개까지만 있습니다.`, "error"); + return; + } + + const newCart = cartModel.updateCartItemQuantity( + cart, + productId, + newQuantity + ); + setCart(newCart); + }; + + const removeFromCart = (productId: string) => { + const newCart = cartModel.removeItemFromCart(cart, productId); + setCart(newCart); + }; + + const calculateCartTotal = (selectedCoupon?: Coupon | null) => { + // 1. 장바구니 총액 계산 (쿠폰 없이) + const cartTotal = cartModel.calculateCartTotal(cart); + + // 2. 쿠폰이 있으면 적용 + let finalTotal = cartTotal.totalAfterDiscount; + if (selectedCoupon) { + finalTotal = couponModel.applyCoupon( + cartTotal.totalAfterDiscount, + selectedCoupon + ); + } + + return { + totalBeforeDiscount: cartTotal.totalBeforeDiscount, + totalAfterDiscount: finalTotal, + }; + }; + + const calculateItemTotal = (item: CartItem) => { + return cartModel.calculateItemTotal(item, cart); + }; + + const getRemainingStock = (product: ProductWithUI) => { + return cartModel.getRemainingStock(cart, product); + }; + + useEffect(() => { + const count = cart.reduce((sum, item) => sum + item.quantity, 0); + setTotalItemCount(count); + }, [cart]); + + return { + cart, + setCart, + totalItemCount, + setTotalItemCount, + addToCart, + updateQuantity, + removeFromCart, + calculateCartTotal, + calculateItemTotal, + getRemainingStock, + }; +}; diff --git a/src/basic/hooks/useCouponForm.ts b/src/basic/hooks/useCouponForm.ts new file mode 100644 index 000000000..72c164e33 --- /dev/null +++ b/src/basic/hooks/useCouponForm.ts @@ -0,0 +1,40 @@ +import { useState } from "react"; + +export interface CouponFormType { + name: string; + code: string; + discountType: "amount" | "percentage"; + discountValue: number; +} + +export const useCouponForm = () => { + const [couponForm, setCouponForm] = useState({ + name: "", + code: "", + discountType: "amount" as "amount" | "percentage", + discountValue: 0, + }); + + const [showCouponForm, setShowCouponForm] = useState(false); + + const updateCouponForm = (updates: Partial) => { + setCouponForm({ ...couponForm, ...updates }); + }; + + const resetCouponForm = () => { + setCouponForm({ + name: "", + code: "", + discountType: "amount", + discountValue: 0, + }); + }; + + return { + couponForm, + updateCouponForm, + resetCouponForm, + showCouponForm, + setShowCouponForm, + }; +}; diff --git a/src/basic/hooks/useCoupons.ts b/src/basic/hooks/useCoupons.ts new file mode 100644 index 000000000..be2c32c42 --- /dev/null +++ b/src/basic/hooks/useCoupons.ts @@ -0,0 +1,78 @@ +import { useCallback, useState } from "react"; +import { Coupon } from "../../types"; +import { initialCoupons } from "../constants"; +import { couponModel } from "../models/coupon"; +import { useLocalStorage } from "../utils/hooks/useLocalStorage"; + +interface UseCouponsProps { + addNotification: ( + message: string, + type: "error" | "success" | "warning" + ) => void; +} +export const useCoupons = ({ addNotification }: UseCouponsProps) => { + const [coupons, setCoupons] = useLocalStorage( + "coupons", + initialCoupons + ); + + const [selectedCoupon, setSelectedCoupon] = useState(null); + const [showCouponForm, setShowCouponForm] = useState(false); + + const isDuplicateCoupon = useCallback( + (newCoupon: Coupon) => { + return coupons.find((c) => c.code === newCoupon.code) !== undefined; + }, + [coupons] + ); + + const addCoupon = useCallback( + (newCoupon: Coupon) => { + setCoupons((prev) => [...prev, newCoupon]); + }, + [coupons] + ); + + const deleteCoupon = useCallback( + (couponCode: string) => { + setCoupons((prev) => prev.filter((c) => c.code !== couponCode)); + if (selectedCoupon?.code === couponCode) { + setSelectedCoupon(null); + } + }, + [selectedCoupon] + ); + const toggleCouponForm = () => { + setShowCouponForm(!showCouponForm); + }; + + const applyCoupon = useCallback( + (coupon: Coupon, currentTotal: number) => { + const isApplicable = couponModel.isApplicable(currentTotal, coupon); + + if (!isApplicable) { + addNotification( + "percentage 쿠폰은 10,000원 이상 구매 시 사용 가능합니다.", + "error" + ); + return; + } + setSelectedCoupon(coupon); + addNotification("쿠폰이 적용되었습니다.", "success"); + }, + [addNotification] + ); + + return { + coupons, + selectedCoupon, + setSelectedCoupon, + showCouponForm, + setShowCouponForm, + addCoupon, + deleteCoupon, + isDuplicateCoupon, + toggleCouponForm, + applyCoupon, + }; +}; diff --git a/src/basic/hooks/useNotification.ts b/src/basic/hooks/useNotification.ts new file mode 100644 index 000000000..451d0ad1a --- /dev/null +++ b/src/basic/hooks/useNotification.ts @@ -0,0 +1,28 @@ +import { useCallback, useState } from "react"; + +export interface NotificationType { + id: string; + message: string; + type: "error" | "success" | "warning"; +} + +export function useNotification() { + const [notifications, setNotifications] = useState([]); + + const addNotification = useCallback( + (msg: string, type: "error" | "success" | "warning" = "success") => { + const id = String(Date.now()); + setNotifications((prev) => [...prev, { id, message: msg, type }]); + setTimeout(() => { + setNotifications((prev) => prev.filter((n) => n.id !== id)); + }, 3000); + }, + [] + ); + + const clearNotification = useCallback((id: string) => { + setNotifications((prev) => prev.filter((n) => n.id !== id)); + }, []); + + return { notifications, addNotification, clearNotification }; +} diff --git a/src/basic/hooks/useProductForm.ts b/src/basic/hooks/useProductForm.ts new file mode 100644 index 000000000..72c555e7a --- /dev/null +++ b/src/basic/hooks/useProductForm.ts @@ -0,0 +1,50 @@ +import { useState } from "react"; + +export interface ProductFormType { + name: string; + price: number; + stock: number; + description: string; + discounts: Array<{ quantity: number; rate: number }>; +} + +export const useProductForm = () => { + const [productForm, setProductForm] = useState({ + name: "", + price: 0, + stock: 0, + description: "", + discounts: [] as Array<{ quantity: number; rate: number }>, + }); + + const [editingProduct, setEditingProduct] = useState(null); + const [showProductForm, setShowProductForm] = useState(false); + + const updateProductForm = (updates: Partial) => { + setProductForm({ ...productForm, ...updates }); + }; + + const resetProductForm = () => { + setProductForm({ + name: "", + price: 0, + stock: 0, + description: "", + discounts: [], + }); + + setEditingProduct(null); + setShowProductForm(false); + }; + + return { + productForm, + setProductForm, + editingProduct, + setEditingProduct, + showProductForm, + setShowProductForm, + updateProductForm, + resetProductForm, + }; +}; diff --git a/src/basic/hooks/useProducts.ts b/src/basic/hooks/useProducts.ts new file mode 100644 index 000000000..7c3c2fea9 --- /dev/null +++ b/src/basic/hooks/useProducts.ts @@ -0,0 +1,80 @@ +// TODO: 상품 관리 Hook +// 힌트: +// 1. 상품 목록 상태 관리 (localStorage 연동 고려) +// 2. 상품 CRUD 작업 +// 3. 재고 업데이트 +// 4. 할인 규칙 추가/삭제 +// +// 반환할 값: +// - products: 상품 배열 +// - updateProduct: 상품 정보 수정 +// - addProduct: 새 상품 추가 +// - updateProductStock: 재고 수정 +// - addProductDiscount: 할인 규칙 추가 +// - removeProductDiscount: 할인 규칙 삭제 + +export interface ProductWithUI extends Product { + description?: string; + isRecommended?: boolean; +} + +import { useCallback } from "react"; +import { Product } from "../../types"; +import { initialProducts } from "../constants"; +import { useLocalStorage } from "../utils/hooks/useLocalStorage"; + +export function useProducts() { + const [products, setProducts] = useLocalStorage( + "products", + initialProducts + ); + + const addProduct = useCallback((newProduct: Omit) => { + const product: ProductWithUI = { + ...newProduct, + id: `p${Date.now()}`, + }; + setProducts((prev) => [...prev, product]); + }, []); + + const updateProduct = useCallback( + (productId: string, updates: Partial) => { + setProducts((prev) => + prev.map((product) => + product.id === productId ? { ...product, ...updates } : product + ) + ); + }, + [] + ); + + const deleteProduct = useCallback((productId: string) => { + setProducts((prev) => prev.filter((p) => p.id !== productId)); + }, []); + + const filterProductsBySearchTerm = useCallback( + (searchTerm: string): ProductWithUI[] => { + if (!searchTerm.trim()) { + return products; + } + + const lowerSearchTerm = searchTerm.toLowerCase(); + + return products.filter( + (product) => + product.name.toLowerCase().includes(lowerSearchTerm) || + (product.description && + product.description.toLowerCase().includes(lowerSearchTerm)) + ); + }, + [products] + ); + + return { + products, + addProduct, + updateProduct, + deleteProduct, + filterProductsBySearchTerm, + }; +} diff --git a/src/basic/hooks/useSearch.ts b/src/basic/hooks/useSearch.ts new file mode 100644 index 000000000..189a18672 --- /dev/null +++ b/src/basic/hooks/useSearch.ts @@ -0,0 +1,13 @@ +import { useState } from "react"; +import { useDebounce } from "../utils/hooks/useDebounce"; + +export const useSearch = (delay: number = 500) => { + const [searchTerm, setSearchTerm] = useState(""); + const debouncedSearchTerm = useDebounce(searchTerm, delay); + + return { + searchTerm, + debouncedSearchTerm, + setSearchTerm, + }; +}; diff --git a/src/basic/models/cart.ts b/src/basic/models/cart.ts new file mode 100644 index 000000000..a49ec4b62 --- /dev/null +++ b/src/basic/models/cart.ts @@ -0,0 +1,174 @@ +// TODO: 장바구니 비즈니스 로직 (순수 함수) +// 힌트: 모든 함수는 순수 함수로 구현 (부작용 없음, 같은 입력에 항상 같은 출력) +// +// 구현할 함수들: +// 1. calculateItemTotal(item): 개별 아이템의 할인 적용 후 총액 계산 +// 2. getMaxApplicableDiscount(item): 적용 가능한 최대 할인율 계산 +// 3. calculateCartTotal(cart, coupon): 장바구니 총액 계산 (할인 전/후, 할인액) +// 4. updateCartItemQuantity(cart, productId, quantity): 수량 변경 +// 5. addItemToCart(cart, product): 상품 추가 +// 6. removeItemFromCart(cart, productId): 상품 제거 +// 7. getRemainingStock(product, cart): 남은 재고 계산 +// +// 원칙: +// - UI와 관련된 로직 없음 +// - 외부 상태에 의존하지 않음 +// - 모든 필요한 데이터는 파라미터로 전달받음 + +import { CartItem } from "../../types"; +import { ProductWithUI } from "../hooks/useProducts"; + +export const cartModel = { + /** + * 상품의 기본 할인율 계산 (수량 기반) + * @param item - 장바구니 아이템 + * @returns 기본 할인율 (0 ~ 1) + */ + getBaseDiscount: (item: CartItem): number => { + const { discounts } = item.product; + const { quantity } = item; + + return discounts.reduce((maxDiscount, discount) => { + return quantity >= discount.quantity && discount.rate > maxDiscount + ? discount.rate + : maxDiscount; + }, 0); + }, + + /** + * 대량 구매 보너스 할인율 계산 + * @param cart - 전체 장바구니 + * @returns 대량 구매 보너스 할인율 (0 또는 0.05) + */ + getBulkPurchaseBonus: (cart: CartItem[]): number => { + const hasBulkPurchase = cart.some((cartItem) => cartItem.quantity >= 10); + return hasBulkPurchase ? 0.05 : 0; + }, + + /** + * 적용 가능한 최대 할인율 계산 + * @param item - 장바구니 아이템 + * @param cart - 전체 장바구니 (대량 구매 체크용) + * @returns 최대 할인율 (0 ~ 0.5, 최대 50%) + */ + getMaxApplicableDiscount: (item: CartItem, cart: CartItem[]): number => { + const baseDiscount = cartModel.getBaseDiscount(item); + const bulkBonus = cartModel.getBulkPurchaseBonus(cart); + + // 기본 할인 + 대량 구매 보너스, 최대 50% 제한 + return Math.min(baseDiscount + bulkBonus, 0.5); + }, + + /** + * 개별 아이템의 할인 적용 후 총액 계산 + * @param item - 장바구니 아이템 + * @param cart - 전체 장바구니 (대량 구매 체크용) + * @returns 할인 적용 후 총액 + */ + calculateItemTotal: (item: CartItem, cart: CartItem[]): number => { + const { price } = item.product; + const { quantity } = item; + const discount = cartModel.getMaxApplicableDiscount(item, cart); + + return Math.round(price * quantity * (1 - discount)); + }, + + /** + * 장바구니 총액 계산 (쿠폰 적용 전) + * @param cart - 장바구니 아이템 배열 + * @returns 할인 전/후 총액 (쿠폰 미적용) + */ + calculateCartTotal: (cart: CartItem[]) => { + let totalBeforeDiscount = 0; + let totalAfterDiscount = 0; + + cart.forEach((item) => { + const itemPrice = item.product.price * item.quantity; + totalBeforeDiscount += itemPrice; + totalAfterDiscount += cartModel.calculateItemTotal(item, cart); + }); + + return { + totalBeforeDiscount: Math.round(totalBeforeDiscount), + totalAfterDiscount: Math.round(totalAfterDiscount), + }; + }, + + /** + * 남은 재고 계산 + * @param cart - 장바구니 + * @param product - 상품 + * @returns 남은 재고 수량 + */ + getRemainingStock: (cart: CartItem[], product: ProductWithUI): number => { + const cartItem = cart.find((item) => item.product.id === product.id); + const remaining = product.stock - (cartItem?.quantity || 0); + + return remaining; + }, + + /** + * 재고 초과 여부 확인 + * @param cart - 장바구니 + * @param product - 상품 + * @returns 재고 초과 여부 + */ + wouldExceedStock: (cart: CartItem[], product: ProductWithUI): boolean => { + const existingItem = cart.find((item) => item.product.id === product.id); + if (existingItem) { + return existingItem.quantity + 1 > product.stock; + } + return false; + }, + + /** + * 장바구니에 상품 추가 + * @param cart - 현재 장바구니 + * @param product - 추가할 상품 + * @returns 새로운 장바구니 + */ + addItemToCart: (cart: CartItem[], product: ProductWithUI): CartItem[] => { + const existingItem = cart.find((item) => item.product.id === product.id); + + if (existingItem) { + return cart.map((item) => + item.product.id === product.id + ? { ...item, quantity: item.quantity + 1 } + : item + ); + } + + return [...cart, { product, quantity: 1 }]; + }, + + /** + * 장바구니에서 상품 제거 + * @param cart - 현재 장바구니 + * @param productId - 제거할 상품 ID + * @returns 새로운 장바구니 + */ + removeItemFromCart: (cart: CartItem[], productId: string): CartItem[] => { + return cart.filter((item) => item.product.id !== productId); + }, + + /** + * 장바구니 아이템 수량 변경 + * @param cart - 현재 장바구니 + * @param productId - 변경할 상품 ID + * @param quantity - 새로운 수량 + * @returns 새로운 장바구니 + */ + updateCartItemQuantity: ( + cart: CartItem[], + productId: string, + quantity: number + ): CartItem[] => { + if (quantity <= 0) { + return cartModel.removeItemFromCart(cart, productId); + } + + return cart.map((item) => + item.product.id === productId ? { ...item, quantity } : item + ); + }, +}; diff --git a/src/basic/models/coupon.ts b/src/basic/models/coupon.ts new file mode 100644 index 000000000..61de9ea22 --- /dev/null +++ b/src/basic/models/coupon.ts @@ -0,0 +1,37 @@ +// 쿠폰 관련 비즈니스 로직 (순수 함수) +// 원칙: +// - UI와 관련된 로직 없음 +// - 외부 상태에 의존하지 않음 +// - 모든 필요한 데이터는 파라미터로 전달받음 + +import { Coupon } from "../../types"; + +export const couponModel = { + /** + * 쿠폰을 총액에 적용 + * @param total - 쿠폰 적용 전 총액 + * @param coupon - 적용할 쿠폰 + * @returns 쿠폰 적용 후 총액 + */ + applyCoupon: (total: number, coupon: Coupon): number => { + if (coupon.discountType === "amount") { + return Math.max(0, total - coupon.discountValue); + } else { + return Math.round(total * (1 - coupon.discountValue / 100)); + } + }, + + /** + * 쿠폰 적용 가능 여부 확인 + * @param total - 현재 총액 + * @param coupon - 확인할 쿠폰 + * @returns 적용 가능 여부 + */ + isApplicable: (total: number, coupon: Coupon): boolean => { + // percentage 쿠폰은 10,000원 이상 구매 시 사용 가능 + if (coupon.discountType === "percentage" && total < 10000) { + return false; + } + return true; + }, +}; diff --git a/src/basic/models/product.ts b/src/basic/models/product.ts new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/src/basic/models/product.ts @@ -0,0 +1 @@ + diff --git a/src/basic/utils/formatters.ts b/src/basic/utils/formatters.ts new file mode 100644 index 000000000..68c1ea5b3 --- /dev/null +++ b/src/basic/utils/formatters.ts @@ -0,0 +1,7 @@ +export const formatPriceWon = (price: number): string => { + return `${price.toLocaleString()}원`; +}; + +export const formatProductPrice = (price: number): string => { + return `₩${price.toLocaleString()}`; +}; diff --git a/src/basic/utils/hooks/useDebounce.ts b/src/basic/utils/hooks/useDebounce.ts new file mode 100644 index 000000000..4e83dbddb --- /dev/null +++ b/src/basic/utils/hooks/useDebounce.ts @@ -0,0 +1,14 @@ +import { useEffect, useState } from "react"; + +export function useDebounce(value: T, delay: number): T { + const [debouncedValue, setDebouncedValue] = useState(value); + + useEffect(() => { + const timer = setTimeout(() => { + setDebouncedValue(value); + }, delay); + return () => clearTimeout(timer); + }, [value, delay]); + + return debouncedValue; +} diff --git a/src/basic/utils/hooks/useLocalStorage.ts b/src/basic/utils/hooks/useLocalStorage.ts new file mode 100644 index 000000000..522421bc7 --- /dev/null +++ b/src/basic/utils/hooks/useLocalStorage.ts @@ -0,0 +1,46 @@ +// TODO: LocalStorage Hook +// 힌트: +// 1. localStorage와 React state 동기화 +// 2. 초기값 로드 시 에러 처리 +// 3. 저장 시 JSON 직렬화/역직렬화 +// 4. 빈 배열이나 undefined는 삭제 +// +// 반환값: [저장된 값, 값 설정 함수] + +import { useEffect, useState } from "react"; + +export function useLocalStorage( + key: string, + initialValue: T +): [T, (value: T | ((val: T) => T)) => void] { + const [value, setValue] = useState(() => { + try { + const saved = localStorage.getItem(key); + if (!saved) return initialValue; + + return JSON.parse(saved); + } catch (error) { + console.error(`Error "${key}":`, error); + return initialValue; + } + }); + + useEffect(() => { + try { + const shouldRemove = + value === undefined || + value === null || + (Array.isArray(value) && value.length === 0); + + if (shouldRemove) { + localStorage.removeItem(key); + } else { + localStorage.setItem(key, JSON.stringify(value)); + } + } catch (error) { + console.error(`Error "${key}":`, error); + } + }, [key, value]); + + return [value, setValue]; +} diff --git a/tsconfig.node.json b/tsconfig.node.json index 3afdd6e38..bccc62268 100644 --- a/tsconfig.node.json +++ b/tsconfig.node.json @@ -7,7 +7,8 @@ "moduleResolution": "bundler", "allowSyntheticDefaultImports": true, "strict": true, - "noEmit": true + "noEmit": true, + "types": ["node"] }, "include": ["vite.config.ts"] } diff --git a/vite.config.ts b/vite.config.ts index e6c4016bc..233db0956 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -5,6 +5,20 @@ import react from '@vitejs/plugin-react-swc'; export default mergeConfig( defineConfig({ plugins: [react()], + build: { + outDir: 'dist', + rollupOptions: { + input: { + main: './index.advanced.html', + }, + output: { + entryFileNames: 'assets/[name]-[hash].js', + chunkFileNames: 'assets/[name]-[hash].js', + assetFileNames: 'assets/[name]-[hash].[ext]', + }, + }, + }, + base: process.env.GITHUB_PAGES === 'true' ? '/front_7th_chapter3-2/' : '/', }), defineTestConfig({ test: {