diff --git a/404.html b/404.html new file mode 100644 index 00000000..5e239920 --- /dev/null +++ b/404.html @@ -0,0 +1,13 @@ + + + + + + 장바구니로 학습하는 디자인패턴 + + + +
+ + + diff --git a/index.advanced.html b/index.html similarity index 100% rename from index.advanced.html rename to index.html diff --git a/package.json b/package.json index 79034acb..6eb4d6c2 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", - "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0" + "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", + "deploy": "npx gh-pages -d dist" }, "dependencies": { + "jotai": "^2.13.0", "react": "^19.1.1", "react-dom": "^19.1.1" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2dddaf85..51539e27 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,6 +8,9 @@ importers: .: dependencies: + jotai: + specifier: ^2.13.0 + version: 2.13.0(@types/react@19.1.9)(react@19.1.1) react: specifier: ^19.1.1 version: 19.1.1 @@ -1056,6 +1059,24 @@ packages: isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + jotai@2.13.0: + resolution: {integrity: sha512-H43zXdanNTdpfOEJ4NVbm4hgmrctpXLZagjJNcqAywhUv+sTE7esvFjwm5oBg/ywT9Qw63lIkM6fjrhFuW8UDg==} + 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==} @@ -2413,6 +2434,11 @@ snapshots: isexe@2.0.0: {} + jotai@2.13.0(@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: {} diff --git a/src/advanced/App.tsx b/src/advanced/App.tsx index a4369fe1..1e7e234b 100644 --- a/src/advanced/App.tsx +++ b/src/advanced/App.tsx @@ -1,1124 +1,23 @@ -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 } from 'react'; +import { NotificationToast, Header } from './shared/ui'; +import ShoppingPage from './pages/ShoppingPage'; +import AdminPage from './pages/AdminPage'; 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 [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" - /> -
- )} -
- -
-
-
- -
- {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()}원 -
-
- - - -
-

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

-
-
- - )} -
-
-
- )} +
+ {/* 알림 시스템 */} + + {/* 헤더 */} +
setIsAdmin(!isAdmin)} /> + {/* 메인 컨텐츠 */} +
+ {isAdmin ? : }
); }; -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 3f5c3d55..77f24a4e 100644 --- a/src/advanced/__tests__/origin.test.tsx +++ b/src/advanced/__tests__/origin.test.tsx @@ -1,9 +1,18 @@ // @ts-nocheck import { render, screen, fireEvent, within, waitFor } from '@testing-library/react'; import { vi } from 'vitest'; +import { Provider } from 'jotai'; import App from '../App'; import '../../setupTests'; +const renderWithProvider = () => { + return render( + + + + ); +}; + describe('쇼핑몰 앱 통합 테스트', () => { beforeEach(() => { // localStorage 초기화 @@ -19,7 +28,7 @@ describe('쇼핑몰 앱 통합 테스트', () => { describe('고객 쇼핑 플로우', () => { test('상품을 검색하고 장바구니에 추가할 수 있다', async () => { - render(); + renderWithProvider(); // 검색창에 "프리미엄" 입력 const searchInput = screen.getByPlaceholderText('상품 검색...'); @@ -45,7 +54,7 @@ describe('쇼핑몰 앱 통합 테스트', () => { }); test('장바구니에서 수량을 조절하고 할인을 확인할 수 있다', () => { - render(); + renderWithProvider(); // 상품1을 장바구니에 추가 const product1 = screen.getAllByText('장바구니 담기')[0]; @@ -64,7 +73,7 @@ describe('쇼핑몰 앱 통합 테스트', () => { }); test('쿠폰을 선택하고 적용할 수 있다', () => { - render(); + renderWithProvider(); // 상품 추가 const addButton = screen.getAllByText('장바구니 담기')[0]; @@ -81,7 +90,7 @@ describe('쇼핑몰 앱 통합 테스트', () => { }); test('품절 임박 상품에 경고가 표시된다', async () => { - render(); + renderWithProvider(); // 관리자 모드로 전환 fireEvent.click(screen.getByText('관리자 페이지로')); @@ -111,7 +120,7 @@ describe('쇼핑몰 앱 통합 테스트', () => { }); test('주문을 완료할 수 있다', () => { - render(); + renderWithProvider(); // 상품 추가 fireEvent.click(screen.getAllByText('장바구니 담기')[0]); @@ -128,7 +137,7 @@ describe('쇼핑몰 앱 통합 테스트', () => { }); test('장바구니에서 상품을 삭제할 수 있다', () => { - render(); + renderWithProvider(); // 상품 2개 추가 fireEvent.click(screen.getAllByText('장바구니 담기')[0]); @@ -151,7 +160,7 @@ describe('쇼핑몰 앱 통합 테스트', () => { }); test('재고를 초과하여 구매할 수 없다', async () => { - render(); + renderWithProvider(); // 상품1 장바구니에 추가 fireEvent.click(screen.getAllByText('장바구니 담기')[0]); @@ -178,7 +187,7 @@ describe('쇼핑몰 앱 통합 테스트', () => { }); test('장바구니에서 수량을 감소시킬 수 있다', () => { - render(); + renderWithProvider(); // 상품 추가 fireEvent.click(screen.getAllByText('장바구니 담기')[0]); @@ -213,7 +222,7 @@ describe('쇼핑몰 앱 통합 테스트', () => { }); test('20개 이상 구매 시 최대 할인이 적용된다', async () => { - render(); + renderWithProvider(); // 관리자 모드로 전환하여 상품1의 재고를 늘림 fireEvent.click(screen.getByText('관리자 페이지로')); @@ -250,7 +259,7 @@ describe('쇼핑몰 앱 통합 테스트', () => { describe('관리자 기능', () => { beforeEach(() => { - render(); + renderWithProvider(); // 관리자 모드로 전환 fireEvent.click(screen.getByText('관리자 페이지로')); }); @@ -404,7 +413,7 @@ describe('쇼핑몰 앱 통합 테스트', () => { describe('로컬스토리지 동기화', () => { test('상품, 장바구니, 쿠폰이 localStorage에 저장된다', () => { - render(); + renderWithProvider(); // 상품을 장바구니에 추가 fireEvent.click(screen.getAllByText('장바구니 담기')[0]); @@ -437,7 +446,7 @@ describe('쇼핑몰 앱 통합 테스트', () => { }); test('페이지 새로고침 후에도 데이터가 유지된다', () => { - const { unmount } = render(); + const { unmount } = renderWithProvider(); // 장바구니에 상품 추가 fireEvent.click(screen.getAllByText('장바구니 담기')[0]); @@ -447,7 +456,7 @@ describe('쇼핑몰 앱 통합 테스트', () => { unmount(); // 다시 mount - render(); + renderWithProvider(); // 장바구니 아이템이 유지되는지 확인 const cartSection = screen.getByText('장바구니').closest('section'); @@ -458,7 +467,7 @@ describe('쇼핑몰 앱 통합 테스트', () => { describe('UI 상태 관리', () => { test('할인이 있을 때 할인율이 표시된다', async () => { - render(); + renderWithProvider(); // 상품을 10개 담아서 할인 발생 const addButton = screen.getAllByText('장바구니 담기')[0]; @@ -473,7 +482,7 @@ describe('쇼핑몰 앱 통합 테스트', () => { }); test('장바구니 아이템 개수가 헤더에 표시된다', () => { - render(); + renderWithProvider(); // 상품 추가 fireEvent.click(screen.getAllByText('장바구니 담기')[0]); @@ -486,7 +495,7 @@ describe('쇼핑몰 앱 통합 테스트', () => { }); test('검색을 초기화할 수 있다', async () => { - render(); + renderWithProvider(); // 검색어 입력 const searchInput = screen.getByPlaceholderText('상품 검색...'); @@ -511,7 +520,7 @@ describe('쇼핑몰 앱 통합 테스트', () => { }); test('알림 메시지가 자동으로 사라진다', async () => { - render(); + renderWithProvider(); // 상품 추가하여 알림 발생 fireEvent.click(screen.getAllByText('장바구니 담기')[0]); diff --git a/src/advanced/entities/cart/index.ts b/src/advanced/entities/cart/index.ts new file mode 100644 index 00000000..05920651 --- /dev/null +++ b/src/advanced/entities/cart/index.ts @@ -0,0 +1,11 @@ +// 타입 관련 +export type { CartTotal, CartCalculationOptions } from './types'; + +// 유틸리티 함수 관련 +export { + getProductDiscount, + getBulkPurchaseDiscount, + getMaxApplicableDiscount, + calculateItemTotal, + calculateCartTotal, +} from './utils'; diff --git a/src/advanced/entities/cart/types.ts b/src/advanced/entities/cart/types.ts new file mode 100644 index 00000000..7b9e8f54 --- /dev/null +++ b/src/advanced/entities/cart/types.ts @@ -0,0 +1,13 @@ +import { CartItem, Coupon } from '../../../types'; + +// 장바구니 총액 계산 결과 +export interface CartTotal { + totalBeforeDiscount: number; + totalAfterDiscount: number; +} + +// 장바구니 계산에 필요한 옵션들 +export interface CartCalculationOptions { + cart: CartItem[]; + selectedCoupon?: Coupon | null; +} diff --git a/src/advanced/entities/cart/utils.ts b/src/advanced/entities/cart/utils.ts new file mode 100644 index 00000000..b0dca1a1 --- /dev/null +++ b/src/advanced/entities/cart/utils.ts @@ -0,0 +1,103 @@ +import { CartItem, Coupon } from '../../../types'; +import { CartTotal } from './types'; + +/** + * 개별 상품의 할인율 계산 + * 상품별로 설정된 수량 할인 정책에 따라 할인율을 결정 + */ +export const getProductDiscount = (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); +}; + +/** + * 대량구매 할인 체크 + * 장바구니에 10개 이상 구매한 상품이 하나라도 있으면 모든 상품에 5% 추가 할인 + */ +export const getBulkPurchaseDiscount = (cart: CartItem[]): number => { + const hasBulkPurchase = cart.some((cartItem) => cartItem.quantity >= 10); + return hasBulkPurchase ? 0.05 : 0; +}; + +/** + * 개별 아이템의 최대 적용 가능한 할인율 계산 + * @param item 계산할 장바구니 아이템 + * @param cart 전체 장바구니 + */ +export const getMaxApplicableDiscount = ( + item: CartItem, + cart: CartItem[] +): number => { + const baseDiscount = getProductDiscount(item); + const bulkDiscount = getBulkPurchaseDiscount(cart); + return Math.min(baseDiscount + bulkDiscount, 0.5); +}; + +/** + * 개별 상품의 할인 적용된 총액 계산 + * @param item 계산할 장바구니 아이템 + * @param cart 전체 장바구니 + */ +export const calculateItemTotal = ( + item: CartItem, + cart: CartItem[] +): number => { + const { price } = item.product; + const { quantity } = item; + const discount = getMaxApplicableDiscount(item, cart); + + return Math.round(price * quantity * (1 - discount)); +}; + +/** + * 장바구니 전체 금액 계산 (쿠폰 할인 포함) + * 대량구매 할인을 한 번만 계산하여 모든 아이템에 적용 + */ +export const calculateCartTotal = ( + cart: CartItem[], + selectedCoupon: Coupon | null = null +): CartTotal => { + let totalBeforeDiscount = 0; + let totalAfterDiscount = 0; + + // 대량구매 할인은 한 번만 계산 + const bulkDiscount = getBulkPurchaseDiscount(cart); + + // 각 상품별 금액 계산 + cart.forEach((item) => { + const itemPrice = item.product.price * item.quantity; + totalBeforeDiscount += itemPrice; + + // 개별 상품 할인 + 대량구매 할인 조합 + const productDiscount = getProductDiscount(item); + const totalDiscount = Math.min(productDiscount + bulkDiscount, 0.5); + const itemTotal = Math.round(itemPrice * (1 - totalDiscount)); + + totalAfterDiscount += itemTotal; + }); + + // 쿠폰 할인 적용 + 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), + }; +}; diff --git a/src/advanced/entities/coupon/data.ts b/src/advanced/entities/coupon/data.ts new file mode 100644 index 00000000..cbc4813d --- /dev/null +++ b/src/advanced/entities/coupon/data.ts @@ -0,0 +1,19 @@ +import { Coupon } from '../../../types'; + +/** + * 초기 쿠폰 데이터 + */ +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/entities/coupon/hooks/index.ts b/src/advanced/entities/coupon/hooks/index.ts new file mode 100644 index 00000000..9ef23f5e --- /dev/null +++ b/src/advanced/entities/coupon/hooks/index.ts @@ -0,0 +1 @@ +export { useCoupons } from './useCoupons'; diff --git a/src/advanced/entities/coupon/hooks/useCoupons.ts b/src/advanced/entities/coupon/hooks/useCoupons.ts new file mode 100644 index 00000000..b850554b --- /dev/null +++ b/src/advanced/entities/coupon/hooks/useCoupons.ts @@ -0,0 +1,70 @@ +import { useCallback } from 'react'; +import { useAtom, useAtomValue } from 'jotai'; +import { Coupon } from '../../../../types'; +import { + couponsAtom, + selectedCouponAtom, +} from '../../../shared/store/couponsAtom'; +import { cartTotalsAtom } from '../../../shared/store/cartTotalsAtom'; +import { useNotification } from '../../../shared/utils'; + +export function useCoupons() { + const { addNotification } = useNotification(); + const [coupons, setCoupons] = useAtom(couponsAtom); + const [selectedCoupon, setSelectedCoupon] = useAtom(selectedCouponAtom); + const cartTotals = useAtomValue(cartTotalsAtom); + + // 쿠폰 추가 + 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, setCoupons] + ); + + // 쿠폰 삭제 + const deleteCoupon = useCallback( + (couponCode: string) => { + setCoupons((prev) => prev.filter((c) => c.code !== couponCode)); + if (selectedCoupon?.code === couponCode) { + setSelectedCoupon(null); + } + addNotification('쿠폰이 삭제되었습니다.', 'success'); + }, + [selectedCoupon, addNotification, setCoupons, setSelectedCoupon] + ); + + // 쿠폰 적용 + const applyCoupon = useCallback( + (coupon: Coupon) => { + const currentTotal = cartTotals.totalAfterDiscount; + + if (currentTotal < 10000 && coupon.discountType === 'percentage') { + addNotification( + 'percentage 쿠폰은 10,000원 이상 구매 시 사용 가능합니다.', + 'error' + ); + return; + } + + setSelectedCoupon(coupon); + addNotification('쿠폰이 적용되었습니다.', 'success'); + }, + [addNotification, cartTotals.totalAfterDiscount, setSelectedCoupon] + ); + + return { + coupons, + selectedCoupon, + addCoupon, + deleteCoupon, + applyCoupon, + setSelectedCoupon, + }; +} diff --git a/src/advanced/entities/coupon/index.ts b/src/advanced/entities/coupon/index.ts new file mode 100644 index 00000000..5e90635a --- /dev/null +++ b/src/advanced/entities/coupon/index.ts @@ -0,0 +1,2 @@ +// 데이터 관련 +export { initialCoupons } from './data'; diff --git a/src/advanced/entities/product/data.ts b/src/advanced/entities/product/data.ts new file mode 100644 index 00000000..cf0bfc59 --- /dev/null +++ b/src/advanced/entities/product/data.ts @@ -0,0 +1,38 @@ +import { ProductWithUI } from './types'; + +/** + * 초기 상품 데이터 + */ +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: '대용량과 고성능을 자랑하는 상품입니다.', + }, +]; diff --git a/src/advanced/entities/product/index.ts b/src/advanced/entities/product/index.ts new file mode 100644 index 00000000..0d4ee263 --- /dev/null +++ b/src/advanced/entities/product/index.ts @@ -0,0 +1,5 @@ +// 타입 관련 +export type { ProductWithUI } from './types'; + +// 데이터 관련 +export { initialProducts } from './data'; diff --git a/src/advanced/entities/product/types.ts b/src/advanced/entities/product/types.ts new file mode 100644 index 00000000..dfa1402c --- /dev/null +++ b/src/advanced/entities/product/types.ts @@ -0,0 +1,6 @@ +import { Product } from '../../../types'; + +export interface ProductWithUI extends Product { + description?: string; + isRecommended?: boolean; +} diff --git a/src/advanced/features/cart/hooks/index.ts b/src/advanced/features/cart/hooks/index.ts new file mode 100644 index 00000000..bbe99fcd --- /dev/null +++ b/src/advanced/features/cart/hooks/index.ts @@ -0,0 +1 @@ +export { useCart } from './useCart'; \ No newline at end of file diff --git a/src/advanced/features/cart/hooks/useCart.ts b/src/advanced/features/cart/hooks/useCart.ts new file mode 100644 index 00000000..fea59154 --- /dev/null +++ b/src/advanced/features/cart/hooks/useCart.ts @@ -0,0 +1,103 @@ +import { useCallback } from 'react'; +import { useAtom, useAtomValue } from 'jotai'; +import { ProductWithUI } from '../../../entities/product'; +import { getRemainingStock, useNotification } from '../../../shared/utils'; +import { cartAtom, productsAtom } from '../../../shared/store'; + +export function useCart() { + const { addNotification } = useNotification(); + const [cart, setCart] = useAtom(cartAtom); + const products = useAtomValue(productsAtom); + + // 특정 상품의 장바구니 수량 찾기 + const getCartQuantity = useCallback( + (productId: string): number => { + const cartItem = cart.find((item) => item.product.id === productId); + return cartItem?.quantity || 0; + }, + [cart] + ); + + // 장바구니에 상품 추가 + const addToCart = useCallback( + (product: ProductWithUI) => { + const cartQuantity = getCartQuantity(product.id); + const remainingStock = getRemainingStock({ + stock: product.stock, + cartQuantity, + }); + + if (remainingStock <= 0) { + addNotification('재고가 부족합니다!', 'error'); + return; + } + + const existingItem = cart.find((item) => item.product.id === product.id); + + if (existingItem) { + const newQuantity = existingItem.quantity + 1; + + if (newQuantity > product.stock) { + addNotification(`재고는 ${product.stock}개까지만 있습니다.`, 'error'); + return; + } + + const newCart = cart.map((item) => + item.product.id === product.id + ? { ...item, quantity: newQuantity } + : item + ); + setCart(newCart); + } else { + setCart([...cart, { product, quantity: 1 }]); + } + + addNotification('장바구니에 담았습니다', 'success'); + }, + [addNotification, cart, setCart, getCartQuantity] + ); + + // 장바구니에서 상품 제거 + const removeFromCart = useCallback( + (productId: string) => { + const newCart = cart.filter((item) => item.product.id !== productId); + setCart(newCart); + }, + [cart, setCart] + ); + + // 장바구니 상품 수량 업데이트 + 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; + } + + const newCart = cart.map((item) => + item.product.id === productId + ? { ...item, quantity: newQuantity } + : item + ); + setCart(newCart); + }, + [products, cart, removeFromCart, addNotification, setCart] + ); + + return { + cart, + addToCart, + removeFromCart, + updateQuantity, + getCartQuantity, + }; +} diff --git a/src/advanced/features/cart/ui/CartItemsList.tsx b/src/advanced/features/cart/ui/CartItemsList.tsx new file mode 100644 index 00000000..db7a3b0e --- /dev/null +++ b/src/advanced/features/cart/ui/CartItemsList.tsx @@ -0,0 +1,131 @@ +import { CartItem } from '../../../../types'; +import { Button } from '../../../shared/ui'; +import { calculateItemTotal } from '../../../entities/cart'; + +interface CartItemsListProps { + cart: CartItem[]; + onRemove: (productId: string) => void; + onUpdateQuantity: (productId: string, newQuantity: number) => void; +} + +export function CartItemsList({ + cart, + onRemove, + onUpdateQuantity, +}: CartItemsListProps) { + return ( +
+

+ + + + 장바구니 +

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

장바구니가 비어있습니다

+
+ ) : ( +
+ {cart.map((item) => { + const itemTotal = calculateItemTotal(item, cart); + 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/features/cart/ui/index.ts b/src/advanced/features/cart/ui/index.ts new file mode 100644 index 00000000..7408d52f --- /dev/null +++ b/src/advanced/features/cart/ui/index.ts @@ -0,0 +1 @@ +export { CartItemsList } from './CartItemsList'; diff --git a/src/advanced/features/coupon/admin/ui/CouponForm.tsx b/src/advanced/features/coupon/admin/ui/CouponForm.tsx new file mode 100644 index 00000000..39e8a8e0 --- /dev/null +++ b/src/advanced/features/coupon/admin/ui/CouponForm.tsx @@ -0,0 +1,167 @@ +import { FormEvent } from 'react'; +import { Button } from '../../../../shared/ui'; +import { useNotification } from '../../../../shared/utils'; + +interface CouponFormData { + name: string; + code: string; + discountType: 'amount' | 'percentage'; + discountValue: number; +} + +interface CouponFormProps { + couponForm: CouponFormData; + setCouponForm: React.Dispatch>; + onSubmit: () => void; + onCancel: () => void; +} + +export default function CouponForm({ + couponForm, + setCouponForm, + onSubmit, + onCancel, +}: CouponFormProps) { + const { addNotification } = useNotification(); + + const handleSubmit = (e: FormEvent) => { + e.preventDefault(); + onSubmit(); + }; + + const handleDiscountValueChange = ( + e: React.ChangeEvent + ) => { + const value = e.target.value; + if (value === '' || /^\d+$/.test(value)) { + setCouponForm({ + ...couponForm, + discountValue: value === '' ? 0 : parseInt(value), + }); + } + }; + + const handleDiscountValueBlur = (e: React.FocusEvent) => { + 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, + }); + } + } + }; + + return ( +
+
+

새 쿠폰 생성

+ +
+
+ + + 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 + /> +
+ +
+ + +
+ +
+ + +
+
+ +
+ + +
+
+
+ ); +} diff --git a/src/advanced/features/coupon/admin/ui/CouponManagement.tsx b/src/advanced/features/coupon/admin/ui/CouponManagement.tsx new file mode 100644 index 00000000..dc8b973e --- /dev/null +++ b/src/advanced/features/coupon/admin/ui/CouponManagement.tsx @@ -0,0 +1,60 @@ +import { useState } from 'react'; +import CouponTable from './CouponTable'; +import CouponForm from './CouponForm'; +import { useCoupons } from '../../../../entities/coupon/hooks/useCoupons'; + +export default function CouponManagement() { + const { coupons, addCoupon, deleteCoupon } = useCoupons(); + + const [showCouponForm, setShowCouponForm] = useState(false); + const [couponForm, setCouponForm] = useState({ + name: '', + code: '', + discountType: 'amount' as 'amount' | 'percentage', + discountValue: 0, + }); + + const handleCouponSubmit = () => { + addCoupon(couponForm); + resetForm(); + }; + + const resetForm = () => { + setCouponForm({ + name: '', + code: '', + discountType: 'amount', + discountValue: 0, + }); + setShowCouponForm(false); + }; + + const startAddCoupon = () => { + setShowCouponForm(true); + }; + + return ( +
+
+

쿠폰 관리

+
+ +
+ + + {showCouponForm && ( + + )} +
+
+ ); +} diff --git a/src/advanced/features/coupon/admin/ui/CouponTable.tsx b/src/advanced/features/coupon/admin/ui/CouponTable.tsx new file mode 100644 index 00000000..a89f3c8e --- /dev/null +++ b/src/advanced/features/coupon/admin/ui/CouponTable.tsx @@ -0,0 +1,79 @@ +import { Coupon } from '../../../../../types'; +import { Button } from '../../../../shared/ui'; + +interface CouponTableProps { + coupons: Coupon[]; + onDelete: (couponCode: string) => void; + onAddNew: () => void; +} + +export default function CouponTable({ + coupons, + onDelete, + onAddNew, +}: CouponTableProps) { + return ( +
+ {coupons.map((coupon) => ( +
+
+
+

{coupon.name}

+

+ {coupon.code} +

+
+ + {coupon.discountType === 'amount' + ? `${coupon.discountValue.toLocaleString()}원 할인` + : `${coupon.discountValue}% 할인`} + +
+
+ +
+
+ ))} + +
+ +
+
+ ); +} diff --git a/src/advanced/features/coupon/admin/ui/index.ts b/src/advanced/features/coupon/admin/ui/index.ts new file mode 100644 index 00000000..2e9fed33 --- /dev/null +++ b/src/advanced/features/coupon/admin/ui/index.ts @@ -0,0 +1,3 @@ +export { default as CouponManagement } from './CouponManagement'; +export { default as CouponForm } from './CouponForm'; +export { default as CouponTable } from './CouponTable'; diff --git a/src/advanced/features/coupon/shop/ui/CouponSelector.tsx b/src/advanced/features/coupon/shop/ui/CouponSelector.tsx new file mode 100644 index 00000000..4e1ff8cf --- /dev/null +++ b/src/advanced/features/coupon/shop/ui/CouponSelector.tsx @@ -0,0 +1,68 @@ +import { useCallback } from 'react'; +import { useAtomValue, useAtom } from 'jotai'; +import { Coupon } from '../../../../../types'; +import { Button } from '../../../../shared/ui'; +import { useNotification } from '../../../../shared/utils'; +import { + couponsAtom, + selectedCouponAtom, + cartTotalsAtom, +} from '../../../../shared/store'; + +export function CouponSelector() { + const coupons = useAtomValue(couponsAtom); + const [selectedCoupon, setSelectedCoupon] = useAtom(selectedCouponAtom); + const cartTotals = useAtomValue(cartTotalsAtom); + const { addNotification } = useNotification(); + + const applyCoupon = useCallback( + (coupon: Coupon) => { + const currentTotal = cartTotals.totalAfterDiscount; + + if (currentTotal < 10000 && coupon.discountType === 'percentage') { + addNotification( + 'percentage 쿠폰은 10,000원 이상 구매 시 사용 가능합니다.', + 'error' + ); + return; + } + + setSelectedCoupon(coupon); + addNotification('쿠폰이 적용되었습니다.', 'success'); + }, + [addNotification, cartTotals.totalAfterDiscount, setSelectedCoupon] + ); + + return ( +
+
+

쿠폰 할인

+ +
+ {coupons.length > 0 && ( + + )} +
+ ); +} diff --git a/src/advanced/features/coupon/shop/ui/index.ts b/src/advanced/features/coupon/shop/ui/index.ts new file mode 100644 index 00000000..b4bb0ed2 --- /dev/null +++ b/src/advanced/features/coupon/shop/ui/index.ts @@ -0,0 +1 @@ +export { CouponSelector } from './CouponSelector'; diff --git a/src/advanced/features/order/hooks/index.ts b/src/advanced/features/order/hooks/index.ts new file mode 100644 index 00000000..caa7eff1 --- /dev/null +++ b/src/advanced/features/order/hooks/index.ts @@ -0,0 +1 @@ +export { useOrder } from './useOrder'; \ No newline at end of file diff --git a/src/advanced/features/order/hooks/useOrder.ts b/src/advanced/features/order/hooks/useOrder.ts new file mode 100644 index 00000000..bc6f660d --- /dev/null +++ b/src/advanced/features/order/hooks/useOrder.ts @@ -0,0 +1,25 @@ +import { useCallback } from 'react'; +import { useSetAtom } from 'jotai'; +import { useNotification } from '../../../shared/utils'; +import { cartAtom, selectedCouponAtom } from '../../../shared/store'; + +export function useOrder() { + const { addNotification } = useNotification(); + const setCart = useSetAtom(cartAtom); + const setSelectedCoupon = useSetAtom(selectedCouponAtom); + + // 주문 완료 처리 + const completeOrder = useCallback(() => { + const orderNumber = `ORD-${Date.now()}`; + addNotification( + `주문이 완료되었습니다. 주문번호: ${orderNumber}`, + 'success' + ); + setCart([]); + setSelectedCoupon(null); + }, [addNotification, setCart, setSelectedCoupon]); + + return { + completeOrder, + }; +} diff --git a/src/advanced/features/order/ui/OrderSummary.tsx b/src/advanced/features/order/ui/OrderSummary.tsx new file mode 100644 index 00000000..308f942d --- /dev/null +++ b/src/advanced/features/order/ui/OrderSummary.tsx @@ -0,0 +1,58 @@ +import { Button } from '../../../shared/ui'; +import { useOrder } from '../hooks'; + +interface OrderSummaryProps { + totals: { + totalBeforeDiscount: number; + totalAfterDiscount: number; + }; +} + +export function OrderSummary({ totals }: OrderSummaryProps) { + const { completeOrder } = useOrder(); + + return ( +
+

결제 정보

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

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

+
+
+ ); +} diff --git a/src/advanced/features/order/ui/index.ts b/src/advanced/features/order/ui/index.ts new file mode 100644 index 00000000..dd49db3a --- /dev/null +++ b/src/advanced/features/order/ui/index.ts @@ -0,0 +1 @@ +export { OrderSummary } from './OrderSummary'; diff --git a/src/advanced/features/product/admin/hooks/index.ts b/src/advanced/features/product/admin/hooks/index.ts new file mode 100644 index 00000000..5977d886 --- /dev/null +++ b/src/advanced/features/product/admin/hooks/index.ts @@ -0,0 +1 @@ +export { useProducts } from './useProducts'; diff --git a/src/advanced/features/product/admin/hooks/useProducts.ts b/src/advanced/features/product/admin/hooks/useProducts.ts new file mode 100644 index 00000000..aff752ce --- /dev/null +++ b/src/advanced/features/product/admin/hooks/useProducts.ts @@ -0,0 +1,51 @@ +import { useCallback } from 'react'; +import { useAtom } from 'jotai'; +import { useNotification } from '../../../../shared/utils'; +import { ProductWithUI } from '../../../../entities/product'; +import { productsAtom } from '../../../../shared/store'; + +export function useProducts() { + const { addNotification } = useNotification(); + const [products, setProducts] = useAtom(productsAtom); + // 상품 추가 + const addProduct = useCallback( + (newProduct: Omit) => { + const product: ProductWithUI = { + ...newProduct, + id: `p${Date.now()}`, + }; + setProducts((prev) => [...prev, product]); + addNotification('상품이 추가되었습니다.', 'success'); + }, + [setProducts, addNotification] + ); + + // 상품 업데이트 + const updateProduct = useCallback( + (productId: string, updates: Partial) => { + setProducts((prev) => + prev.map((product) => + product.id === productId ? { ...product, ...updates } : product + ) + ); + addNotification('상품이 수정되었습니다.', 'success'); + }, + [setProducts, addNotification] + ); + + // 상품 삭제 + const deleteProduct = useCallback( + (productId: string) => { + setProducts((prev) => prev.filter((p) => p.id !== productId)); + addNotification('상품이 삭제되었습니다.', 'success'); + }, + [setProducts, addNotification] + ); + + return { + products, + addProduct, + updateProduct, + deleteProduct, + }; +} diff --git a/src/advanced/features/product/admin/ui/ProductForm.tsx b/src/advanced/features/product/admin/ui/ProductForm.tsx new file mode 100644 index 00000000..85b8c5b6 --- /dev/null +++ b/src/advanced/features/product/admin/ui/ProductForm.tsx @@ -0,0 +1,261 @@ +import { FormEvent } from 'react'; +import { Button } from '../../../../shared/ui'; +import { useNotification } from '../../../../shared/utils'; + +interface ProductFormData { + name: string; + price: number; + stock: number; + description: string; + discounts: Array<{ quantity: number; rate: number }>; +} + +interface ProductFormProps { + productForm: ProductFormData; + setProductForm: React.Dispatch>; + onSubmit: () => void; + onCancel: () => void; + isEditing: boolean; +} + +export default function ProductForm({ + productForm, + setProductForm, + onSubmit, + onCancel, + isEditing, +}: ProductFormProps) { + const { addNotification } = useNotification(); + + const handleSubmit = (e: FormEvent) => { + e.preventDefault(); + onSubmit(); + }; + + const addDiscount = () => { + setProductForm({ + ...productForm, + discounts: [...productForm.discounts, { quantity: 10, rate: 0.1 }], + }); + }; + + const removeDiscount = (index: number) => { + const newDiscounts = productForm.discounts.filter((_, i) => i !== index); + setProductForm({ + ...productForm, + discounts: newDiscounts, + }); + }; + + const updateDiscount = ( + index: number, + field: 'quantity' | 'rate', + value: number + ) => { + const newDiscounts = [...productForm.discounts]; + newDiscounts[index][field] = value; + setProductForm({ + ...productForm, + discounts: newDiscounts, + }); + }; + + return ( +
+
+

+ {isEditing ? '상품 수정' : '새 상품 추가'} +

+ +
+
+ + + 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) => ( +
+ { + updateDiscount( + index, + 'quantity', + parseInt(e.target.value) || 0 + ); + }} + className='w-20 px-2 py-1 border rounded' + min='1' + placeholder='수량' + /> + 개 이상 구매 시 + { + updateDiscount( + index, + 'rate', + (parseInt(e.target.value) || 0) / 100 + ); + }} + className='w-16 px-2 py-1 border rounded' + min='0' + max='100' + placeholder='%' + /> + % 할인 + +
+ ))} + +
+
+ +
+ + +
+
+
+ ); +} diff --git a/src/advanced/features/product/admin/ui/ProductManagement.tsx b/src/advanced/features/product/admin/ui/ProductManagement.tsx new file mode 100644 index 00000000..75da2251 --- /dev/null +++ b/src/advanced/features/product/admin/ui/ProductManagement.tsx @@ -0,0 +1,95 @@ +import { useState } from 'react'; +import { ProductWithUI } from '../../../../entities/product'; +import { useProducts } from '../hooks'; +import { Button } from '../../../../shared/ui'; +import ProductTable from './ProductTable'; +import ProductForm from './ProductForm'; + +export default function ProductManagement() { + const { products, addProduct, updateProduct, deleteProduct } = useProducts(); + + const [showProductForm, setShowProductForm] = useState(false); + const [editingProduct, setEditingProduct] = useState(null); + const [productForm, setProductForm] = useState({ + name: '', + price: 0, + stock: 0, + description: '', + discounts: [] as Array<{ quantity: number; rate: number }>, + }); + + const handleProductSubmit = () => { + if (editingProduct && editingProduct !== 'new') { + updateProduct(editingProduct, productForm); + setEditingProduct(null); + } else { + addProduct(productForm); + } + resetForm(); + }; + + 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 startAddProduct = () => { + setEditingProduct('new'); + setProductForm({ + name: '', + price: 0, + stock: 0, + description: '', + discounts: [], + }); + setShowProductForm(true); + }; + + const resetForm = () => { + setProductForm({ + name: '', + price: 0, + stock: 0, + description: '', + discounts: [], + }); + setEditingProduct(null); + setShowProductForm(false); + }; + + return ( +
+
+
+

상품 목록

+ +
+
+ + + + {showProductForm && ( + + )} +
+ ); +} diff --git a/src/advanced/features/product/admin/ui/ProductTable.tsx b/src/advanced/features/product/admin/ui/ProductTable.tsx new file mode 100644 index 00000000..9783bfe9 --- /dev/null +++ b/src/advanced/features/product/admin/ui/ProductTable.tsx @@ -0,0 +1,86 @@ +import { ProductWithUI } from '../../../../entities/product'; +import { Button } from '../../../../shared/ui'; +import { formatPrice } from '../../../../shared/utils'; + +interface ProductTableProps { + products: ProductWithUI[]; + onEdit: (product: ProductWithUI) => void; + onDelete: (productId: string) => void; +} + +export default function ProductTable({ + products, + onEdit, + onDelete, +}: ProductTableProps) { + // 관리자용 가격 표시 함수 + const displayAdminPrice = (price: number) => { + const formatted = formatPrice(price); + return `${formatted}원`; + }; + return ( +
+ + + + + + + + + + + + {products.map((product) => ( + + + + + + + + ))} + +
+ 상품명 + + 가격 + + 재고 + + 설명 + + 작업 +
+ {product.name} + + {displayAdminPrice(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/features/product/admin/ui/index.ts b/src/advanced/features/product/admin/ui/index.ts new file mode 100644 index 00000000..83093283 --- /dev/null +++ b/src/advanced/features/product/admin/ui/index.ts @@ -0,0 +1,3 @@ +export { default as ProductManagement } from './ProductManagement'; +export { default as ProductTable } from './ProductTable'; +export { default as ProductForm } from './ProductForm'; diff --git a/src/advanced/features/product/shop/hooks/index.ts b/src/advanced/features/product/shop/hooks/index.ts new file mode 100644 index 00000000..57636cb8 --- /dev/null +++ b/src/advanced/features/product/shop/hooks/index.ts @@ -0,0 +1 @@ +export { useProductSearch } from './useProductSearch'; diff --git a/src/advanced/features/product/shop/hooks/useProductSearch.tsx b/src/advanced/features/product/shop/hooks/useProductSearch.tsx new file mode 100644 index 00000000..b934b635 --- /dev/null +++ b/src/advanced/features/product/shop/hooks/useProductSearch.tsx @@ -0,0 +1,32 @@ +import { useMemo } from 'react'; +import { ProductWithUI } from '../../../../entities/product'; +import { useDebounce } from '../../../../shared/hooks'; + +export function useProductSearch( + products: ProductWithUI[], + searchTerm: string +) { + const debouncedSearchTerm = useDebounce(searchTerm, 500); + + const filteredProducts = useMemo(() => { + if (!debouncedSearchTerm) { + return products; + } + + return products.filter( + (product) => + product.name + .toLowerCase() + .includes(debouncedSearchTerm.toLowerCase()) || + (product.description && + product.description + .toLowerCase() + .includes(debouncedSearchTerm.toLowerCase())) + ); + }, [products, debouncedSearchTerm]); + + return { + debouncedSearchTerm, + filteredProducts, + }; +} diff --git a/src/advanced/features/product/shop/ui/ProductCard.tsx b/src/advanced/features/product/shop/ui/ProductCard.tsx new file mode 100644 index 00000000..29b0d6f7 --- /dev/null +++ b/src/advanced/features/product/shop/ui/ProductCard.tsx @@ -0,0 +1,117 @@ +import { useAtomValue } from 'jotai'; +import { ProductWithUI } from '../../../../entities/product'; +import { Button } from '../../../../shared/ui'; +import { formatPrice, getRemainingStock, getProductStockStatus } from '../../../../shared/utils'; +import { cartAtom } from '../../../../shared/store'; + +interface ProductCardProps { + product: ProductWithUI; + onAddToCart: (product: ProductWithUI) => void; +} + +export default function ProductCard({ + product, + onAddToCart, +}: ProductCardProps) { + const cart = useAtomValue(cartAtom); + + // 장바구니에서 현재 상품 수량 찾기 + const cartQuantity = cart.find(item => item.product.id === product.id)?.quantity || 0; + + // 남은 재고 계산 + const remainingStock = getRemainingStock({ + stock: product.stock, + cartQuantity + }); + + // 품절 상태 체크 + const stockStatus = getProductStockStatus({ + stock: product.stock, + cartQuantity + }); + + // 가격 표시 함수 + const displayPrice = () => { + if (stockStatus) return stockStatus; + const formatted = formatPrice(product.price); + return `₩${formatted}`; + }; + return ( +
+ {/* 상품 이미지 영역 (placeholder) */} +
+
+ + + +
+ {product.isRecommended && ( + + BEST + + )} + {product.discounts.length > 0 && ( + + ~{Math.max(...product.discounts.map((d) => d.rate)) * 100}% + + )} +
+ + {/* 상품 정보 */} +
+

{product.name}

+ {product.description && ( +

+ {product.description} +

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

+ {displayPrice()} +

+ {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/features/product/shop/ui/ProductList.tsx b/src/advanced/features/product/shop/ui/ProductList.tsx new file mode 100644 index 00000000..49818b56 --- /dev/null +++ b/src/advanced/features/product/shop/ui/ProductList.tsx @@ -0,0 +1,38 @@ +import { ProductWithUI } from '../../../../entities/product'; +import ProductCard from './ProductCard'; + +interface ProductListProps { + products: ProductWithUI[]; + searchTerm: string; + onAddToCart: (product: ProductWithUI) => void; +} + +export default function ProductList({ + products, + searchTerm, + onAddToCart, +}: ProductListProps) { + if (products.length === 0) { + return ( +
+

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

+
+ ); + } + + return ( +
+ {products.map((product) => { + return ( + + ); + })} +
+ ); +} diff --git a/src/advanced/features/product/shop/ui/index.ts b/src/advanced/features/product/shop/ui/index.ts new file mode 100644 index 00000000..ff14cf93 --- /dev/null +++ b/src/advanced/features/product/shop/ui/index.ts @@ -0,0 +1,2 @@ +export { default as ProductList } from './ProductList'; +export { default as ProductCard } from './ProductCard'; diff --git a/src/advanced/main.tsx b/src/advanced/main.tsx index e63eef4a..f88d2765 100644 --- a/src/advanced/main.tsx +++ b/src/advanced/main.tsx @@ -1,9 +1,12 @@ -import React from 'react' -import ReactDOM from 'react-dom/client' -import App from './App.tsx' +import React from 'react'; +import ReactDOM from 'react-dom/client'; +import App from './App.tsx'; +import { Provider } from 'jotai'; ReactDOM.createRoot(document.getElementById('root')!).render( - - , -) + + + + +); diff --git a/src/advanced/pages/AdminPage.tsx b/src/advanced/pages/AdminPage.tsx new file mode 100644 index 00000000..42ded881 --- /dev/null +++ b/src/advanced/pages/AdminPage.tsx @@ -0,0 +1,52 @@ +import { useState } from 'react'; +import { ProductManagement } from '../features/product/admin/ui'; +import { CouponManagement } from '../features/coupon/admin/ui'; + +export default function AdminPage() { + const [activeTab, setActiveTab] = useState<'products' | 'coupons'>( + 'products' + ); + + return ( +
+ {/* 관리자 대시보드 헤더 */} +
+

관리자 대시보드

+

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

+
+ + {/* 탭 네비게이션 */} +
+ +
+ + {/* 탭 컨텐츠 */} + {activeTab === 'products' ? ( + + ) : ( + + )} +
+ ); +} diff --git a/src/advanced/pages/ShoppingPage.tsx b/src/advanced/pages/ShoppingPage.tsx new file mode 100644 index 00000000..b3d54860 --- /dev/null +++ b/src/advanced/pages/ShoppingPage.tsx @@ -0,0 +1,41 @@ +import { useAtomValue } from 'jotai'; +import { ProductList } from '../features/product/shop/ui'; +import { useCart } from '../features/cart/hooks'; +import { useProductSearch } from '../features/product/shop/hooks'; +import { ShoppingSidebar } from '../widgets/ShoppingSidebar/ui'; +import { productsAtom, searchTermAtom } from '../shared/store'; + +export default function ShoppingPage() { + const products = useAtomValue(productsAtom); + const searchTerm = useAtomValue(searchTermAtom); + const { filteredProducts } = useProductSearch(products, searchTerm); + + const { addToCart } = useCart(); + + return ( +
+
+ {/* 상품 목록 섹션 */} +
+
+

전체 상품

+
+ 총 {products.length}개 상품 +
+
+ + +
+
+ + {/* ShoppingSidebar (widgets) */} +
+ +
+
+ ); +} diff --git a/src/advanced/pages/index.ts b/src/advanced/pages/index.ts new file mode 100644 index 00000000..1cc41ff8 --- /dev/null +++ b/src/advanced/pages/index.ts @@ -0,0 +1,2 @@ +export { default as ShoppingPage } from './ShoppingPage'; +export { default as AdminPage } from './AdminPage'; diff --git a/src/advanced/shared/hooks/index.ts b/src/advanced/shared/hooks/index.ts new file mode 100644 index 00000000..0af9fea2 --- /dev/null +++ b/src/advanced/shared/hooks/index.ts @@ -0,0 +1,5 @@ +// localStorage 훅 +export { useLocalStorage } from './useLocalStorage'; + +// 디바운스 훅 +export { useDebounce } from './useDebounce'; diff --git a/src/advanced/shared/hooks/useDebounce.ts b/src/advanced/shared/hooks/useDebounce.ts new file mode 100644 index 00000000..cf979960 --- /dev/null +++ b/src/advanced/shared/hooks/useDebounce.ts @@ -0,0 +1,23 @@ +import { useState, useEffect } from 'react'; + +/** + * 값의 변경을 지연시키는 디바운스 훅 + * @param value 디바운스할 값 + * @param delay 지연 시간 (밀리초) + * @returns 디바운스된 값 + */ +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/shared/hooks/useLocalStorage.ts b/src/advanced/shared/hooks/useLocalStorage.ts new file mode 100644 index 00000000..5488dc7a --- /dev/null +++ b/src/advanced/shared/hooks/useLocalStorage.ts @@ -0,0 +1,41 @@ +import { useState, useEffect } from 'react'; + +/** + * localStorage와 연동된 상태를 관리하는 커스텀 훅 + * @param key localStorage 키 + * @param defaultValue 기본값 + * @returns [상태값, 상태변경함수] + */ +export function useLocalStorage( + key: string, + defaultValue: T +): [T, React.Dispatch>] { + // 초기값 설정 - localStorage에서 복원 + const [state, setState] = useState(() => { + try { + const saved = localStorage.getItem(key); + if (saved) { + return JSON.parse(saved); + } + } catch (error) { + console.warn(`localStorage에서 ${key} 읽기 실패:`, error); + } + return defaultValue; + }); + + // 상태가 변경될 때마다 localStorage에 저장 + useEffect(() => { + try { + if (key === 'cart' && Array.isArray(state) && state.length === 0) { + // 장바구니가 비어있으면 localStorage에서 제거 + localStorage.removeItem(key); + } else { + localStorage.setItem(key, JSON.stringify(state)); + } + } catch (error) { + console.warn(`localStorage에 ${key} 저장 실패:`, error); + } + }, [key, state]); + + return [state, setState]; +} diff --git a/src/advanced/shared/store/cartAtom.ts b/src/advanced/shared/store/cartAtom.ts new file mode 100644 index 00000000..9be94d97 --- /dev/null +++ b/src/advanced/shared/store/cartAtom.ts @@ -0,0 +1,5 @@ +import { atomWithStorage } from 'jotai/utils'; +import { CartItem } from '../../../types'; + +// localStorage와 자동 동기화되는 cart atom +export const cartAtom = atomWithStorage('cart', []); \ No newline at end of file diff --git a/src/advanced/shared/store/cartTotalsAtom.ts b/src/advanced/shared/store/cartTotalsAtom.ts new file mode 100644 index 00000000..572af675 --- /dev/null +++ b/src/advanced/shared/store/cartTotalsAtom.ts @@ -0,0 +1,11 @@ +import { atom } from 'jotai'; +import { calculateCartTotal } from '../../entities/cart'; +import { cartAtom } from './cartAtom'; +import { selectedCouponAtom } from './couponsAtom'; + +// 장바구니 총액 계산 derived atom +export const cartTotalsAtom = atom((get) => { + const cart = get(cartAtom); + const selectedCoupon = get(selectedCouponAtom); + return calculateCartTotal(cart, selectedCoupon); +}); \ No newline at end of file diff --git a/src/advanced/shared/store/couponsAtom.ts b/src/advanced/shared/store/couponsAtom.ts new file mode 100644 index 00000000..0fd56c69 --- /dev/null +++ b/src/advanced/shared/store/couponsAtom.ts @@ -0,0 +1,10 @@ +import { atom } from 'jotai'; +import { atomWithStorage } from 'jotai/utils'; +import { Coupon } from '../../../types'; +import { initialCoupons } from '../../entities/coupon'; + +// localStorage와 자동 동기화되는 coupons atom +export const couponsAtom = atomWithStorage('coupons', initialCoupons); + +// 선택된 쿠폰 atom +export const selectedCouponAtom = atom(null); diff --git a/src/advanced/shared/store/index.ts b/src/advanced/shared/store/index.ts new file mode 100644 index 00000000..45250057 --- /dev/null +++ b/src/advanced/shared/store/index.ts @@ -0,0 +1,6 @@ +export * from './notificationAtom'; +export * from './cartAtom'; +export * from './productsAtom'; +export * from './couponsAtom'; +export * from './searchAtom'; +export * from './cartTotalsAtom'; \ No newline at end of file diff --git a/src/advanced/shared/store/notificationAtom.ts b/src/advanced/shared/store/notificationAtom.ts new file mode 100644 index 00000000..78c1844d --- /dev/null +++ b/src/advanced/shared/store/notificationAtom.ts @@ -0,0 +1,9 @@ +import { atom } from 'jotai'; + +export interface Notification { + id: string; + message: string; + type: 'error' | 'success' | 'warning'; +} + +export const notificationsAtom = atom([]); \ No newline at end of file diff --git a/src/advanced/shared/store/productsAtom.ts b/src/advanced/shared/store/productsAtom.ts new file mode 100644 index 00000000..d1dbe518 --- /dev/null +++ b/src/advanced/shared/store/productsAtom.ts @@ -0,0 +1,6 @@ +import { atomWithStorage } from 'jotai/utils'; +import { ProductWithUI } from '../../entities/product'; +import { initialProducts } from '../../entities/product'; + +// localStorage와 자동 동기화되는 products atom +export const productsAtom = atomWithStorage('products', initialProducts); \ No newline at end of file diff --git a/src/advanced/shared/store/searchAtom.ts b/src/advanced/shared/store/searchAtom.ts new file mode 100644 index 00000000..2b44f603 --- /dev/null +++ b/src/advanced/shared/store/searchAtom.ts @@ -0,0 +1,4 @@ +import { atom } from 'jotai'; + +// 검색어 atom +export const searchTermAtom = atom(''); diff --git a/src/advanced/shared/ui/Button.tsx b/src/advanced/shared/ui/Button.tsx new file mode 100644 index 00000000..7eae07d2 --- /dev/null +++ b/src/advanced/shared/ui/Button.tsx @@ -0,0 +1,49 @@ +import React from 'react'; + +export interface ButtonProps + extends React.ButtonHTMLAttributes { + variant?: 'primary' | 'secondary' | 'danger' | 'ghost' | 'icon' | 'link'; + size?: 'sm' | 'md' | 'lg'; + children: React.ReactNode; +} + +const Button: React.FC = ({ + variant = 'primary', + size, + className = '', + children, + disabled, + ...props +}) => { + const baseClasses = 'transition-colors focus:outline-none'; + + const variantClasses = { + primary: + 'inline-flex items-center justify-center font-medium bg-gray-900 text-white hover:bg-gray-800 focus:ring-gray-500 disabled:bg-gray-100 disabled:text-gray-400 disabled:cursor-not-allowed', + secondary: + 'inline-flex items-center justify-center font-medium bg-indigo-600 text-white hover:bg-indigo-700 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed', + danger: 'font-medium text-red-600 hover:text-red-800 focus:ring-red-500', + ghost: + 'inline-flex items-center justify-center font-medium border border-gray-300 text-gray-700 bg-white hover:bg-gray-50 focus:ring-gray-500 disabled:opacity-50 disabled:cursor-not-allowed', + icon: 'inline-flex items-center justify-center text-gray-400 hover:text-gray-600', + link: 'text-indigo-600 hover:text-indigo-800', + }; + + const sizeClasses = { + sm: 'px-2 py-1 text-xs rounded', + md: 'px-4 py-2 text-sm rounded-md', + lg: 'px-6 py-3 text-base rounded-lg', + }; + + const classes = `${baseClasses} ${variantClasses[variant]} ${ + size ? sizeClasses[size] : '' + } ${className}`.trim(); + + return ( + + ); +}; + +export default Button; diff --git a/src/advanced/shared/ui/Header.tsx b/src/advanced/shared/ui/Header.tsx new file mode 100644 index 00000000..da0ad68b --- /dev/null +++ b/src/advanced/shared/ui/Header.tsx @@ -0,0 +1,70 @@ +import { useAtomValue, useAtom } from 'jotai'; +import { SearchInput, Button } from '.'; +import { cartAtom, searchTermAtom } from '../store'; + +interface HeaderProps { + isAdmin: boolean; + onToggleAdmin: () => void; +} + +export default function Header({ + isAdmin, + onToggleAdmin, +}: HeaderProps) { + const cart = useAtomValue(cartAtom); + const [searchTerm, setSearchTerm] = useAtom(searchTermAtom); + const totalItemCount = cart.reduce((sum, item) => sum + item.quantity, 0); + const cartLength = cart.length; + + return ( +
+
+
+
+

SHOP

+ {/* 검색창 */} + {!isAdmin && ( + + )} +
+ +
+
+
+ ); +} diff --git a/src/advanced/shared/ui/NotificationToast.tsx b/src/advanced/shared/ui/NotificationToast.tsx new file mode 100644 index 00000000..eb441252 --- /dev/null +++ b/src/advanced/shared/ui/NotificationToast.tsx @@ -0,0 +1,49 @@ +import { useAtom } from 'jotai'; +import { notificationsAtom } from '../store'; + +export default function NotificationToast() { + const [notifications, setNotifications] = useAtom(notificationsAtom); + + const removeNotification = (id: string) => { + setNotifications(prev => prev.filter(n => n.id !== id)); + }; + if (notifications.length === 0) return null; + + return ( +
+ {notifications.map((notif) => ( +
+ {notif.message} + +
+ ))} +
+ ); +} diff --git a/src/advanced/shared/ui/SearchInput.tsx b/src/advanced/shared/ui/SearchInput.tsx new file mode 100644 index 00000000..9e9ee832 --- /dev/null +++ b/src/advanced/shared/ui/SearchInput.tsx @@ -0,0 +1,40 @@ +interface SearchInputProps { + value: string; + onChange: (value: string) => void; + placeholder?: string; + className?: string; +} + +export default function SearchInput({ + value, + onChange, + placeholder = '상품 검색...', + className, +}: SearchInputProps) { + 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/shared/ui/index.ts b/src/advanced/shared/ui/index.ts new file mode 100644 index 00000000..20260123 --- /dev/null +++ b/src/advanced/shared/ui/index.ts @@ -0,0 +1,11 @@ +// 알림 관련 +export { default as NotificationToast } from './NotificationToast'; + +// 입력 관련 +export { default as SearchInput } from './SearchInput'; + +// 버튼 관련 +export { default as Button } from './Button'; + +// 레이아웃 관련 +export { default as Header } from './Header'; diff --git a/src/advanced/shared/utils/index.ts b/src/advanced/shared/utils/index.ts new file mode 100644 index 00000000..b25a568b --- /dev/null +++ b/src/advanced/shared/utils/index.ts @@ -0,0 +1,3 @@ +export * from './priceUtils'; +export * from './stockUtils'; +export * from './notificationUtils'; \ No newline at end of file diff --git a/src/advanced/shared/utils/notificationUtils.ts b/src/advanced/shared/utils/notificationUtils.ts new file mode 100644 index 00000000..4dd61770 --- /dev/null +++ b/src/advanced/shared/utils/notificationUtils.ts @@ -0,0 +1,24 @@ +import { useCallback } from 'react'; +import { useSetAtom } from 'jotai'; +import { notificationsAtom } from '../store'; + +let idCounter = 0; + +const generateUniqueId = () => { + return `notification-${Date.now()}-${++idCounter}`; +}; + +export const useNotification = () => { + const setNotifications = useSetAtom(notificationsAtom); + + const addNotification = useCallback((message: string, type: 'error' | 'success' | 'warning' = 'success') => { + const id = generateUniqueId(); + setNotifications(prev => [...prev, { id, message, type }]); + + setTimeout(() => { + setNotifications(prev => prev.filter(n => n.id !== id)); + }, 3000); + }, [setNotifications]); + + return { addNotification }; +}; \ No newline at end of file diff --git a/src/advanced/shared/utils/priceUtils.ts b/src/advanced/shared/utils/priceUtils.ts new file mode 100644 index 00000000..9011aea8 --- /dev/null +++ b/src/advanced/shared/utils/priceUtils.ts @@ -0,0 +1,8 @@ +/** + * 숫자를 천 단위 구분자가 있는 문자열로 포맷팅 + * @param price 포맷팅할 가격 + * @returns 천 단위 구분자가 포함된 문자열 (예: "10,000") + */ +export const formatPrice = (price: number): string => { + return price.toLocaleString(); +}; \ No newline at end of file diff --git a/src/advanced/shared/utils/stockUtils.ts b/src/advanced/shared/utils/stockUtils.ts new file mode 100644 index 00000000..b20d84f2 --- /dev/null +++ b/src/advanced/shared/utils/stockUtils.ts @@ -0,0 +1,31 @@ +/** + * 전체 재고에서 장바구니 수량을 뺀 남은 재고 계산 + * @param stock 전체 재고 수량 + * @param cartQuantity 장바구니에 담긴 수량 + * @returns 남은 재고 수량 + */ +export const getRemainingStock = ({ + stock, + cartQuantity, +}: { + stock: number; + cartQuantity: number; +}) => { + return stock - cartQuantity; +}; + +/** + * 재고 상태를 확인해서 품절 여부를 문자열로 반환 + * @param stock 전체 재고 수량 + * @param cartQuantity 장바구니에 담긴 수량 + * @returns 품절이면 "SOLD OUT", 아니면 빈 문자열 + */ +export const getProductStockStatus = ({ + stock, + cartQuantity, +}: { + stock: number; + cartQuantity: number; +}) => { + return getRemainingStock({ stock, cartQuantity }) <= 0 ? 'SOLD OUT' : ''; +}; \ No newline at end of file diff --git a/src/advanced/widgets/ShoppingSidebar/ui/ShoppingSidebar.tsx b/src/advanced/widgets/ShoppingSidebar/ui/ShoppingSidebar.tsx new file mode 100644 index 00000000..6a4692b3 --- /dev/null +++ b/src/advanced/widgets/ShoppingSidebar/ui/ShoppingSidebar.tsx @@ -0,0 +1,32 @@ +import { useAtomValue } from 'jotai'; +import { useCart } from '../../../features/cart/hooks'; +import { CartItemsList } from '../../../features/cart/ui'; +import { CouponSelector } from '../../../features/coupon/shop/ui'; +import { OrderSummary } from '../../../features/order/ui'; +import { cartAtom, cartTotalsAtom } from '../../../shared/store'; + +export function ShoppingSidebar() { + const cart = useAtomValue(cartAtom); + const totals = useAtomValue(cartTotalsAtom); + const { removeFromCart, updateQuantity } = useCart(); + + return ( +
+ {/* 장바구니 아이템 섹션 */} + + {/* 쿠폰 + 주문 섹션 */} + {cart.length > 0 && ( + <> + + + + )} +
+ ); +} diff --git a/src/advanced/widgets/ShoppingSidebar/ui/index.ts b/src/advanced/widgets/ShoppingSidebar/ui/index.ts new file mode 100644 index 00000000..4f959865 --- /dev/null +++ b/src/advanced/widgets/ShoppingSidebar/ui/index.ts @@ -0,0 +1 @@ +export { ShoppingSidebar } from './ShoppingSidebar'; diff --git a/src/basic/App.tsx b/src/basic/App.tsx index a4369fe1..849d5dbf 100644 --- a/src/basic/App.tsx +++ b/src/basic/App.tsx @@ -1,1124 +1,77 @@ -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, useCallback } from 'react'; +import { CartItem, Coupon } from '../types'; +import { initialProducts } from './entities/product'; +import { initialCoupons } from './entities/coupon'; +import { calculateCartTotal } from './entities/cart'; +import { useLocalStorage, useNotification } from './shared/hooks'; +import { NotificationToast, Header } from './shared/ui'; +import ShoppingPage from './pages/ShoppingPage'; +import AdminPage from './pages/AdminPage'; const App = () => { + // localStorage와 연동된 데이터 상태들 + const [products, setProducts] = useLocalStorage('products', initialProducts); + const [cart, setCart] = useLocalStorage('cart', []); + const [coupons, setCoupons] = useLocalStorage('coupons', initialCoupons); - 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; - }); - + // UI 상태 관리 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 { notifications, addNotification, removeNotification } = + useNotification(); - const calculateCartTotal = (): { + // 장바구니 전체 금액 계산 (쿠폰 할인 포함) - entities/cart 함수 사용 + const calculateCartTotalWithCoupon = useCallback((): { 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 calculateCartTotal(cart, selectedCoupon); + }, [cart, selectedCoupon]); 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" - /> -
- )} -
- -
-
-
- -
+
+ {/* 알림 시스템 */} + + {/* 헤더 */} +
setIsAdmin(!isAdmin)} + onSearchChange={setSearchTerm} + /> + {/* 메인 컨텐츠 */} +
{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/__tests__/origin.test.tsx b/src/basic/__tests__/origin.test.tsx index 3f5c3d55..38dfbc80 100644 --- a/src/basic/__tests__/origin.test.tsx +++ b/src/basic/__tests__/origin.test.tsx @@ -1,5 +1,11 @@ // @ts-nocheck -import { render, screen, fireEvent, within, waitFor } from '@testing-library/react'; +import { + render, + screen, + fireEvent, + within, + waitFor, +} from '@testing-library/react'; import { vi } from 'vitest'; import App from '../App'; import '../../setupTests'; @@ -20,25 +26,30 @@ describe('쇼핑몰 앱 통합 테스트', () => { describe('고객 쇼핑 플로우', () => { test('상품을 검색하고 장바구니에 추가할 수 있다', async () => { render(); - + // 검색창에 "프리미엄" 입력 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('장바구니 담기'); fireEvent.click(addButtons[0]); - + // 알림 메시지 확인 await waitFor(() => { expect(screen.getByText('장바구니에 담았습니다')).toBeInTheDocument(); }); - + // 장바구니에 추가됨 확인 (장바구니 섹션에서) const cartSection = screen.getByText('장바구니').closest('section'); expect(within(cartSection).getByText('상품1')).toBeInTheDocument(); @@ -46,64 +57,66 @@ describe('쇼핑몰 앱 통합 테스트', () => { test('장바구니에서 수량을 조절하고 할인을 확인할 수 있다', () => { render(); - + // 상품1을 장바구니에 추가 const product1 = screen.getAllByText('장바구니 담기')[0]; fireEvent.click(product1); - + // 수량을 10개로 증가 (10% 할인 적용) 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(); }); test('쿠폰을 선택하고 적용할 수 있다', () => { render(); - + // 상품 추가 const addButton = screen.getAllByText('장바구니 담기')[0]; fireEvent.click(addButton); - + // 쿠폰 선택 const couponSelect = screen.getByRole('combobox'); fireEvent.change(couponSelect, { target: { value: 'AMOUNT5000' } }); - + // 결제 정보에서 할인 금액 확인 const paymentSection = screen.getByText('결제 정보').closest('section'); - const discountRow = within(paymentSection).getByText('할인 금액').closest('div'); + const discountRow = within(paymentSection) + .getByText('할인 금액') + .closest('div'); expect(within(discountRow).getByText('-5,000원')).toBeInTheDocument(); }); test('품절 임박 상품에 경고가 표시된다', async () => { render(); - + // 관리자 모드로 전환 fireEvent.click(screen.getByText('관리자 페이지로')); - + // 상품 수정 const editButton = screen.getAllByText('수정')[0]; fireEvent.click(editButton); - + // 재고를 5개로 변경 const stockInputs = screen.getAllByPlaceholderText('숫자만 입력'); const stockInput = stockInputs[1]; // 재고 입력 필드는 두 번째 fireEvent.change(stockInput, { target: { value: '5' } }); fireEvent.blur(stockInput); - + // 수정 완료 버튼 클릭 const editButtons = screen.getAllByText('수정'); const completeEditButton = editButtons[editButtons.length - 1]; // 마지막 수정 버튼 (완료 버튼) fireEvent.click(completeEditButton); - + // 쇼핑몰로 돌아가기 fireEvent.click(screen.getByText('쇼핑몰로 돌아가기')); - + // 품절임박 메시지 확인 - 재고가 5개 이하면 품절임박 표시 await waitFor(() => { expect(screen.getByText('품절임박! 5개 남음')).toBeInTheDocument(); @@ -112,39 +125,39 @@ describe('쇼핑몰 앱 통합 테스트', () => { test('주문을 완료할 수 있다', () => { render(); - + // 상품 추가 fireEvent.click(screen.getAllByText('장바구니 담기')[0]); - + // 결제하기 버튼 클릭 const orderButton = screen.getByText(/원 결제하기/); fireEvent.click(orderButton); - + // 주문 완료 알림 확인 expect(screen.getByText(/주문이 완료되었습니다/)).toBeInTheDocument(); - + // 장바구니가 비어있는지 확인 expect(screen.getByText('장바구니가 비어있습니다')).toBeInTheDocument(); }); test('장바구니에서 상품을 삭제할 수 있다', () => { render(); - + // 상품 2개 추가 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(); - + // 첫 번째 상품 삭제 (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(); @@ -152,54 +165,56 @@ describe('쇼핑몰 앱 통합 테스트', () => { test('재고를 초과하여 구매할 수 없다', async () => { render(); - + // 상품1 장바구니에 추가 fireEvent.click(screen.getAllByText('장바구니 담기')[0]); - + // 수량을 재고(20개) 이상으로 증가 시도 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(); - + // 재고 부족 메시지 확인 await waitFor(() => { - expect(screen.getByText(/재고는.*개까지만 있습니다/)).toBeInTheDocument(); + expect( + screen.getByText(/재고는.*개까지만 있습니다/) + ).toBeInTheDocument(); }); }); 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 마이너스 기호 - + // 수량 3개로 증가 fireEvent.click(plusButton); fireEvent.click(plusButton); expect(within(cartSection).getByText('3')).toBeInTheDocument(); - + // 수량 감소 fireEvent.click(minusButton); expect(within(cartSection).getByText('2')).toBeInTheDocument(); - + // 1개로 더 감소 fireEvent.click(minusButton); expect(within(cartSection).getByText('1')).toBeInTheDocument(); - + // 1개에서 한 번 더 감소하면 장바구니에서 제거될 수도 있음 fireEvent.click(minusButton); // 장바구니가 비었는지 확인 @@ -214,31 +229,31 @@ describe('쇼핑몰 앱 통합 테스트', () => { 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(editButtons[editButtons.length - 1]); - + // 쇼핑몰로 돌아가기 fireEvent.click(screen.getByText('쇼핑몰로 돌아가기')); - + // 상품1을 장바구니에 추가 fireEvent.click(screen.getAllByText('장바구니 담기')[0]); - + // 수량을 20개로 증가 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%'); @@ -258,27 +273,27 @@ describe('쇼핑몰 앱 통합 테스트', () => { test('새 상품을 추가할 수 있다', () => { // 새 상품 추가 버튼 클릭 fireEvent.click(screen.getByText('새 상품 추가')); - + // 폼 입력 - 상품명 입력 const labels = screen.getAllByText('상품명'); - const nameLabel = labels.find(el => el.tagName === 'LABEL'); + 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 descLabel = descLabels.find((el) => el.tagName === 'LABEL'); const descInput = descLabel.closest('div').querySelector('input'); fireEvent.change(descInput, { target: { value: '테스트 설명' } }); - + // 저장 fireEvent.click(screen.getByText('추가')); - + // 추가된 상품 확인 expect(screen.getByText('테스트 상품')).toBeInTheDocument(); expect(screen.getByText('25,000원')).toBeInTheDocument(); @@ -287,21 +302,25 @@ describe('쇼핑몰 앱 통합 테스트', () => { test('쿠폰 탭으로 전환하고 새 쿠폰을 추가할 수 있다', () => { // 쿠폰 관리 탭으로 전환 fireEvent.click(screen.getByText('쿠폰 관리')); - + // 새 쿠폰 추가 버튼 클릭 const addCouponButton = screen.getByText('새 쿠폰 추가'); fireEvent.click(addCouponButton); - + // 쿠폰 정보 입력 - fireEvent.change(screen.getByPlaceholderText('신규 가입 쿠폰'), { target: { value: '테스트 쿠폰' } }); - fireEvent.change(screen.getByPlaceholderText('WELCOME2024'), { target: { value: 'TEST2024' } }); - + 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('쿠폰 생성')); - + // 생성된 쿠폰 확인 expect(screen.getByText('테스트 쿠폰')).toBeInTheDocument(); expect(screen.getByText('TEST2024')).toBeInTheDocument(); @@ -311,25 +330,25 @@ describe('쇼핑몰 앱 통합 테스트', () => { test('상품의 가격 입력 시 숫자만 허용된다', async () => { // 상품 수정 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: '123' } }); expect(priceInput.value).toBe('123'); - + // 음수 입력 시도 - regex가 매치되지 않아 값이 변경되지 않음 fireEvent.change(priceInput, { target: { value: '-100' } }); expect(priceInput.value).toBe('123'); // 이전 값 유지 - + // 유효한 음수 입력하기 위해 먼저 1 입력 후 앞에 - 추가는 불가능 // 대신 blur 이벤트를 통해 음수 검증을 테스트 // parseInt()는 실제로 음수를 파싱할 수 있으므로 다른 방법으로 테스트 - + // 공백 입력 시도 fireEvent.change(priceInput, { target: { value: ' ' } }); expect(priceInput.value).toBe('123'); // 유효하지 않은 입력은 무시됨 @@ -338,23 +357,25 @@ describe('쇼핑몰 앱 통합 테스트', () => { test('쿠폰 할인율 검증이 작동한다', async () => { // 쿠폰 관리 탭으로 전환 fireEvent.click(screen.getByText('쿠폰 관리')); - + // 새 쿠폰 추가 fireEvent.click(screen.getByText('새 쿠폰 추가')); - + // 퍼센트 타입으로 변경 - 쿠폰 폼 내의 select 찾기 const couponFormSelects = screen.getAllByRole('combobox'); const typeSelect = couponFormSelects[couponFormSelects.length - 1]; // 마지막 select가 타입 선택 fireEvent.change(typeSelect, { target: { value: 'percentage' } }); - + // 100% 초과 할인율 입력 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(); }); }); @@ -362,15 +383,15 @@ describe('쇼핑몰 앱 통합 테스트', () => { // 초기 상품명들 확인 (테이블에서) 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(); @@ -379,76 +400,79 @@ describe('쇼핑몰 앱 통합 테스트', () => { test('쿠폰을 삭제할 수 있다', () => { // 쿠폰 관리 탭으로 전환 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 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(); }); - }); describe('로컬스토리지 동기화', () => { test('상품, 장바구니, 쿠폰이 localStorage에 저장된다', () => { render(); - + // 상품을 장바구니에 추가 fireEvent.click(screen.getAllByText('장바구니 담기')[0]); - + // localStorage 확인 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 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(products.some((p) => p.name === '저장 테스트')).toBe(true); }); test('페이지 새로고침 후에도 데이터가 유지된다', () => { const { unmount } = render(); - + // 장바구니에 상품 추가 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(); @@ -459,13 +483,13 @@ describe('쇼핑몰 앱 통합 테스트', () => { describe('UI 상태 관리', () => { test('할인이 있을 때 할인율이 표시된다', async () => { render(); - + // 상품을 10개 담아서 할인 발생 const addButton = screen.getAllByText('장바구니 담기')[0]; for (let i = 0; i < 10; i++) { fireEvent.click(addButton); } - + // 할인율 표시 확인 - 대량 구매로 15% 할인 await waitFor(() => { expect(screen.getByText('-15%')).toBeInTheDocument(); @@ -474,12 +498,12 @@ describe('쇼핑몰 앱 통합 테스트', () => { test('장바구니 아이템 개수가 헤더에 표시된다', () => { render(); - + // 상품 추가 fireEvent.click(screen.getAllByText('장바구니 담기')[0]); fireEvent.click(screen.getAllByText('장바구니 담기')[0]); fireEvent.click(screen.getAllByText('장바구니 담기')[1]); - + // 헤더의 장바구니 아이콘 옆 숫자 확인 const cartCount = screen.getByText('3'); expect(cartCount).toBeInTheDocument(); @@ -487,42 +511,57 @@ describe('쇼핑몰 앱 통합 테스트', () => { test('검색을 초기화할 수 있다', async () => { render(); - + // 검색어 입력 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: '' } }); - + // 모든 상품이 다시 표시됨 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(); - + // 상품 추가하여 알림 발생 fireEvent.click(screen.getAllByText('장바구니 담기')[0]); - + // 알림 메시지 확인 expect(screen.getByText('장바구니에 담았습니다')).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/basic/entities/cart/index.ts b/src/basic/entities/cart/index.ts new file mode 100644 index 00000000..05920651 --- /dev/null +++ b/src/basic/entities/cart/index.ts @@ -0,0 +1,11 @@ +// 타입 관련 +export type { CartTotal, CartCalculationOptions } from './types'; + +// 유틸리티 함수 관련 +export { + getProductDiscount, + getBulkPurchaseDiscount, + getMaxApplicableDiscount, + calculateItemTotal, + calculateCartTotal, +} from './utils'; diff --git a/src/basic/entities/cart/types.ts b/src/basic/entities/cart/types.ts new file mode 100644 index 00000000..7b9e8f54 --- /dev/null +++ b/src/basic/entities/cart/types.ts @@ -0,0 +1,13 @@ +import { CartItem, Coupon } from '../../../types'; + +// 장바구니 총액 계산 결과 +export interface CartTotal { + totalBeforeDiscount: number; + totalAfterDiscount: number; +} + +// 장바구니 계산에 필요한 옵션들 +export interface CartCalculationOptions { + cart: CartItem[]; + selectedCoupon?: Coupon | null; +} diff --git a/src/basic/entities/cart/utils.ts b/src/basic/entities/cart/utils.ts new file mode 100644 index 00000000..b0dca1a1 --- /dev/null +++ b/src/basic/entities/cart/utils.ts @@ -0,0 +1,103 @@ +import { CartItem, Coupon } from '../../../types'; +import { CartTotal } from './types'; + +/** + * 개별 상품의 할인율 계산 + * 상품별로 설정된 수량 할인 정책에 따라 할인율을 결정 + */ +export const getProductDiscount = (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); +}; + +/** + * 대량구매 할인 체크 + * 장바구니에 10개 이상 구매한 상품이 하나라도 있으면 모든 상품에 5% 추가 할인 + */ +export const getBulkPurchaseDiscount = (cart: CartItem[]): number => { + const hasBulkPurchase = cart.some((cartItem) => cartItem.quantity >= 10); + return hasBulkPurchase ? 0.05 : 0; +}; + +/** + * 개별 아이템의 최대 적용 가능한 할인율 계산 + * @param item 계산할 장바구니 아이템 + * @param cart 전체 장바구니 + */ +export const getMaxApplicableDiscount = ( + item: CartItem, + cart: CartItem[] +): number => { + const baseDiscount = getProductDiscount(item); + const bulkDiscount = getBulkPurchaseDiscount(cart); + return Math.min(baseDiscount + bulkDiscount, 0.5); +}; + +/** + * 개별 상품의 할인 적용된 총액 계산 + * @param item 계산할 장바구니 아이템 + * @param cart 전체 장바구니 + */ +export const calculateItemTotal = ( + item: CartItem, + cart: CartItem[] +): number => { + const { price } = item.product; + const { quantity } = item; + const discount = getMaxApplicableDiscount(item, cart); + + return Math.round(price * quantity * (1 - discount)); +}; + +/** + * 장바구니 전체 금액 계산 (쿠폰 할인 포함) + * 대량구매 할인을 한 번만 계산하여 모든 아이템에 적용 + */ +export const calculateCartTotal = ( + cart: CartItem[], + selectedCoupon: Coupon | null = null +): CartTotal => { + let totalBeforeDiscount = 0; + let totalAfterDiscount = 0; + + // 대량구매 할인은 한 번만 계산 + const bulkDiscount = getBulkPurchaseDiscount(cart); + + // 각 상품별 금액 계산 + cart.forEach((item) => { + const itemPrice = item.product.price * item.quantity; + totalBeforeDiscount += itemPrice; + + // 개별 상품 할인 + 대량구매 할인 조합 + const productDiscount = getProductDiscount(item); + const totalDiscount = Math.min(productDiscount + bulkDiscount, 0.5); + const itemTotal = Math.round(itemPrice * (1 - totalDiscount)); + + totalAfterDiscount += itemTotal; + }); + + // 쿠폰 할인 적용 + 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), + }; +}; diff --git a/src/basic/entities/coupon/data.ts b/src/basic/entities/coupon/data.ts new file mode 100644 index 00000000..cbc4813d --- /dev/null +++ b/src/basic/entities/coupon/data.ts @@ -0,0 +1,19 @@ +import { Coupon } from '../../../types'; + +/** + * 초기 쿠폰 데이터 + */ +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/entities/coupon/hooks/index.ts b/src/basic/entities/coupon/hooks/index.ts new file mode 100644 index 00000000..9ef23f5e --- /dev/null +++ b/src/basic/entities/coupon/hooks/index.ts @@ -0,0 +1 @@ +export { useCoupons } from './useCoupons'; diff --git a/src/basic/entities/coupon/hooks/useCoupons.ts b/src/basic/entities/coupon/hooks/useCoupons.ts new file mode 100644 index 00000000..6e4e6fa5 --- /dev/null +++ b/src/basic/entities/coupon/hooks/useCoupons.ts @@ -0,0 +1,80 @@ +import { useCallback } from 'react'; +import { Coupon } from '../../../../types'; + +interface UseCouponsProps { + coupons: Coupon[]; + setCoupons: React.Dispatch>; + selectedCoupon: Coupon | null; + setSelectedCoupon: React.Dispatch>; + addNotification: ( + message: string, + type?: 'error' | 'success' | 'warning' + ) => void; + calculateCartTotalWithCoupon: () => { + totalBeforeDiscount: number; + totalAfterDiscount: number; + }; +} + +export function useCoupons({ + coupons, + setCoupons, + selectedCoupon, + setSelectedCoupon, + addNotification, + calculateCartTotalWithCoupon, +}: UseCouponsProps) { + // 쿠폰 추가 + 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, setCoupons] + ); + + // 쿠폰 삭제 + const deleteCoupon = useCallback( + (couponCode: string) => { + setCoupons((prev) => prev.filter((c) => c.code !== couponCode)); + if (selectedCoupon?.code === couponCode) { + setSelectedCoupon(null); + } + addNotification('쿠폰이 삭제되었습니다.', 'success'); + }, + [selectedCoupon, addNotification, setCoupons, setSelectedCoupon] + ); + + // 쿠폰 적용 + const applyCoupon = useCallback( + (coupon: Coupon) => { + const currentTotal = calculateCartTotalWithCoupon().totalAfterDiscount; + + if (currentTotal < 10000 && coupon.discountType === 'percentage') { + addNotification( + 'percentage 쿠폰은 10,000원 이상 구매 시 사용 가능합니다.', + 'error' + ); + return; + } + + setSelectedCoupon(coupon); + addNotification('쿠폰이 적용되었습니다.', 'success'); + }, + [addNotification, calculateCartTotalWithCoupon, setSelectedCoupon] + ); + + return { + coupons, + selectedCoupon, + addCoupon, + deleteCoupon, + applyCoupon, + setSelectedCoupon, + }; +} diff --git a/src/basic/entities/coupon/index.ts b/src/basic/entities/coupon/index.ts new file mode 100644 index 00000000..5e90635a --- /dev/null +++ b/src/basic/entities/coupon/index.ts @@ -0,0 +1,2 @@ +// 데이터 관련 +export { initialCoupons } from './data'; diff --git a/src/basic/entities/product/data.ts b/src/basic/entities/product/data.ts new file mode 100644 index 00000000..cf0bfc59 --- /dev/null +++ b/src/basic/entities/product/data.ts @@ -0,0 +1,38 @@ +import { ProductWithUI } from './types'; + +/** + * 초기 상품 데이터 + */ +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: '대용량과 고성능을 자랑하는 상품입니다.', + }, +]; diff --git a/src/basic/entities/product/index.ts b/src/basic/entities/product/index.ts new file mode 100644 index 00000000..0d4ee263 --- /dev/null +++ b/src/basic/entities/product/index.ts @@ -0,0 +1,5 @@ +// 타입 관련 +export type { ProductWithUI } from './types'; + +// 데이터 관련 +export { initialProducts } from './data'; diff --git a/src/basic/entities/product/types.ts b/src/basic/entities/product/types.ts new file mode 100644 index 00000000..dfa1402c --- /dev/null +++ b/src/basic/entities/product/types.ts @@ -0,0 +1,6 @@ +import { Product } from '../../../types'; + +export interface ProductWithUI extends Product { + description?: string; + isRecommended?: boolean; +} diff --git a/src/basic/features/cart/hooks/index.ts b/src/basic/features/cart/hooks/index.ts new file mode 100644 index 00000000..bbe99fcd --- /dev/null +++ b/src/basic/features/cart/hooks/index.ts @@ -0,0 +1 @@ +export { useCart } from './useCart'; \ No newline at end of file diff --git a/src/basic/features/cart/hooks/useCart.ts b/src/basic/features/cart/hooks/useCart.ts new file mode 100644 index 00000000..49bc4fb3 --- /dev/null +++ b/src/basic/features/cart/hooks/useCart.ts @@ -0,0 +1,121 @@ +import { useCallback } from 'react'; +import { CartItem } from '../../../../types'; +import { ProductWithUI } from '../../../entities/product'; +import { getRemainingStock } from '../../../shared/utils'; + +interface UseCartProps { + cart: CartItem[]; + setCart: React.Dispatch>; + products: ProductWithUI[]; + addNotification: ( + message: string, + type?: 'error' | 'success' | 'warning' + ) => void; +} + +export function useCart({ + cart, + setCart, + products, + addNotification, +}: UseCartProps) { + // 특정 상품의 장바구니 수량 찾기 + const getCartQuantity = useCallback( + (productId: string): number => { + const cartItem = cart.find((item) => item.product.id === productId); + return cartItem?.quantity || 0; + }, + [cart] + ); + + // 장바구니에 상품 추가 + const addToCart = useCallback( + (product: ProductWithUI) => { + const cartQuantity = getCartQuantity(product.id); + const remainingStock = getRemainingStock({ + stock: product.stock, + cartQuantity + }); + + 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'); + }, + [addNotification, getCartQuantity, setCart] + ); + + // 장바구니에서 상품 제거 + const removeFromCart = useCallback( + (productId: string) => { + setCart((prevCart) => + prevCart.filter((item) => item.product.id !== productId) + ); + }, + [setCart] + ); + + // 장바구니 상품 수량 업데이트 + 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, setCart] + ); + + return { + cart, + addToCart, + removeFromCart, + updateQuantity, + getCartQuantity, + }; +} \ No newline at end of file diff --git a/src/basic/features/cart/ui/CartItemsList.tsx b/src/basic/features/cart/ui/CartItemsList.tsx new file mode 100644 index 00000000..db7a3b0e --- /dev/null +++ b/src/basic/features/cart/ui/CartItemsList.tsx @@ -0,0 +1,131 @@ +import { CartItem } from '../../../../types'; +import { Button } from '../../../shared/ui'; +import { calculateItemTotal } from '../../../entities/cart'; + +interface CartItemsListProps { + cart: CartItem[]; + onRemove: (productId: string) => void; + onUpdateQuantity: (productId: string, newQuantity: number) => void; +} + +export function CartItemsList({ + cart, + onRemove, + onUpdateQuantity, +}: CartItemsListProps) { + return ( +
+

+ + + + 장바구니 +

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

장바구니가 비어있습니다

+
+ ) : ( +
+ {cart.map((item) => { + const itemTotal = calculateItemTotal(item, cart); + 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/features/cart/ui/index.ts b/src/basic/features/cart/ui/index.ts new file mode 100644 index 00000000..7408d52f --- /dev/null +++ b/src/basic/features/cart/ui/index.ts @@ -0,0 +1 @@ +export { CartItemsList } from './CartItemsList'; diff --git a/src/basic/features/coupon/admin/ui/CouponForm.tsx b/src/basic/features/coupon/admin/ui/CouponForm.tsx new file mode 100644 index 00000000..7ccdd871 --- /dev/null +++ b/src/basic/features/coupon/admin/ui/CouponForm.tsx @@ -0,0 +1,169 @@ +import { FormEvent } from 'react'; +import { Button } from '../../../../shared/ui'; + +interface CouponFormData { + name: string; + code: string; + discountType: 'amount' | 'percentage'; + discountValue: number; +} + +interface CouponFormProps { + couponForm: CouponFormData; + setCouponForm: React.Dispatch>; + onSubmit: () => void; + onCancel: () => void; + addNotification: ( + message: string, + type?: 'error' | 'success' | 'warning' + ) => void; +} + +export default function CouponForm({ + couponForm, + setCouponForm, + onSubmit, + onCancel, + addNotification, +}: CouponFormProps) { + const handleSubmit = (e: FormEvent) => { + e.preventDefault(); + onSubmit(); + }; + + const handleDiscountValueChange = ( + e: React.ChangeEvent + ) => { + const value = e.target.value; + if (value === '' || /^\d+$/.test(value)) { + setCouponForm({ + ...couponForm, + discountValue: value === '' ? 0 : parseInt(value), + }); + } + }; + + const handleDiscountValueBlur = (e: React.FocusEvent) => { + 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, + }); + } + } + }; + + return ( +
+
+

새 쿠폰 생성

+ +
+
+ + + 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 + /> +
+ +
+ + +
+ +
+ + +
+
+ +
+ + +
+
+
+ ); +} diff --git a/src/basic/features/coupon/admin/ui/CouponManagement.tsx b/src/basic/features/coupon/admin/ui/CouponManagement.tsx new file mode 100644 index 00000000..de831b52 --- /dev/null +++ b/src/basic/features/coupon/admin/ui/CouponManagement.tsx @@ -0,0 +1,85 @@ +import { useState } from 'react'; +import { Coupon } from '../../../../../types'; +import { useCoupons } from '../../../../entities/coupon/hooks'; +import CouponTable from './CouponTable'; +import CouponForm from './CouponForm'; + +interface CouponManagementProps { + coupons: Coupon[]; + setCoupons: React.Dispatch>; + addNotification: ( + message: string, + type?: 'error' | 'success' | 'warning' + ) => void; +} + +export function CouponManagement({ + coupons, + setCoupons, + addNotification, +}: CouponManagementProps) { + const { addCoupon, deleteCoupon } = useCoupons({ + coupons, + setCoupons, + selectedCoupon: null, // Admin에서는 쿠폰 선택 불필요 + setSelectedCoupon: () => {}, // Admin에서는 쿠폰 선택 불필요 + addNotification, + calculateCartTotalWithCoupon: () => ({ + totalBeforeDiscount: 0, + totalAfterDiscount: 0, + }), + }); + + const [showCouponForm, setShowCouponForm] = useState(false); + const [couponForm, setCouponForm] = useState({ + name: '', + code: '', + discountType: 'amount' as 'amount' | 'percentage', + discountValue: 0, + }); + + const handleCouponSubmit = () => { + addCoupon(couponForm); + resetForm(); + }; + + const resetForm = () => { + setCouponForm({ + name: '', + code: '', + discountType: 'amount', + discountValue: 0, + }); + setShowCouponForm(false); + }; + + const startAddCoupon = () => { + setShowCouponForm(true); + }; + + return ( +
+
+

쿠폰 관리

+
+ +
+ + + {showCouponForm && ( + + )} +
+
+ ); +} diff --git a/src/basic/features/coupon/admin/ui/CouponTable.tsx b/src/basic/features/coupon/admin/ui/CouponTable.tsx new file mode 100644 index 00000000..a89f3c8e --- /dev/null +++ b/src/basic/features/coupon/admin/ui/CouponTable.tsx @@ -0,0 +1,79 @@ +import { Coupon } from '../../../../../types'; +import { Button } from '../../../../shared/ui'; + +interface CouponTableProps { + coupons: Coupon[]; + onDelete: (couponCode: string) => void; + onAddNew: () => void; +} + +export default function CouponTable({ + coupons, + onDelete, + onAddNew, +}: CouponTableProps) { + return ( +
+ {coupons.map((coupon) => ( +
+
+
+

{coupon.name}

+

+ {coupon.code} +

+
+ + {coupon.discountType === 'amount' + ? `${coupon.discountValue.toLocaleString()}원 할인` + : `${coupon.discountValue}% 할인`} + +
+
+ +
+
+ ))} + +
+ +
+
+ ); +} diff --git a/src/basic/features/coupon/admin/ui/index.ts b/src/basic/features/coupon/admin/ui/index.ts new file mode 100644 index 00000000..d8dc0a82 --- /dev/null +++ b/src/basic/features/coupon/admin/ui/index.ts @@ -0,0 +1,3 @@ +export { CouponManagement } from './CouponManagement'; +export { default as CouponForm } from './CouponForm'; +export { default as CouponTable } from './CouponTable'; diff --git a/src/basic/features/coupon/shop/ui/CouponSelector.tsx b/src/basic/features/coupon/shop/ui/CouponSelector.tsx new file mode 100644 index 00000000..c5f8a111 --- /dev/null +++ b/src/basic/features/coupon/shop/ui/CouponSelector.tsx @@ -0,0 +1,67 @@ +import { Coupon } from '../../../../../types'; +import { Button } from '../../../../shared/ui'; +import { useCoupons } from '../../../../entities/coupon/hooks'; + +interface CouponSelectorProps { + coupons: Coupon[]; + selectedCoupon: Coupon | null; + setSelectedCoupon: React.Dispatch>; + addNotification: ( + message: string, + type?: 'error' | 'success' | 'warning' + ) => void; + calculateCartTotalWithCoupon: () => { + totalBeforeDiscount: number; + totalAfterDiscount: number; + }; +} + +export function CouponSelector({ + coupons, + selectedCoupon, + setSelectedCoupon, + addNotification, + calculateCartTotalWithCoupon, +}: CouponSelectorProps) { + const { applyCoupon } = useCoupons({ + coupons, + setCoupons: () => {}, + selectedCoupon, + setSelectedCoupon, + addNotification, + calculateCartTotalWithCoupon, + }); + + return ( +
+
+

쿠폰 할인

+ +
+ {coupons.length > 0 && ( + + )} +
+ ); +} diff --git a/src/basic/features/coupon/shop/ui/index.ts b/src/basic/features/coupon/shop/ui/index.ts new file mode 100644 index 00000000..b4bb0ed2 --- /dev/null +++ b/src/basic/features/coupon/shop/ui/index.ts @@ -0,0 +1 @@ +export { CouponSelector } from './CouponSelector'; diff --git a/src/basic/features/order/hooks/index.ts b/src/basic/features/order/hooks/index.ts new file mode 100644 index 00000000..caa7eff1 --- /dev/null +++ b/src/basic/features/order/hooks/index.ts @@ -0,0 +1 @@ +export { useOrder } from './useOrder'; \ No newline at end of file diff --git a/src/basic/features/order/hooks/useOrder.ts b/src/basic/features/order/hooks/useOrder.ts new file mode 100644 index 00000000..e1f8768d --- /dev/null +++ b/src/basic/features/order/hooks/useOrder.ts @@ -0,0 +1,32 @@ +import { useCallback } from 'react'; +import { CartItem, Coupon } from '../../../../types'; + +interface UseOrderProps { + setCart: React.Dispatch>; + setSelectedCoupon: React.Dispatch>; + addNotification: ( + message: string, + type?: 'error' | 'success' | 'warning' + ) => void; +} + +export function useOrder({ + setCart, + setSelectedCoupon, + addNotification, +}: UseOrderProps) { + // 주문 완료 처리 + const completeOrder = useCallback(() => { + const orderNumber = `ORD-${Date.now()}`; + addNotification( + `주문이 완료되었습니다. 주문번호: ${orderNumber}`, + 'success' + ); + setCart([]); + setSelectedCoupon(null); + }, [addNotification, setCart, setSelectedCoupon]); + + return { + completeOrder, + }; +} \ No newline at end of file diff --git a/src/basic/features/order/ui/OrderSummary.tsx b/src/basic/features/order/ui/OrderSummary.tsx new file mode 100644 index 00000000..da519b8b --- /dev/null +++ b/src/basic/features/order/ui/OrderSummary.tsx @@ -0,0 +1,74 @@ +import { CartItem, Coupon } from '../../../../types'; +import { Button } from '../../../shared/ui'; +import { useOrder } from '../hooks'; + +interface OrderSummaryProps { + totals: { + totalBeforeDiscount: number; + totalAfterDiscount: number; + }; + setCart: React.Dispatch>; + setSelectedCoupon: React.Dispatch>; + addNotification: ( + message: string, + type?: 'error' | 'success' | 'warning' + ) => void; +} + +export function OrderSummary({ + totals, + setCart, + setSelectedCoupon, + addNotification, +}: OrderSummaryProps) { + const { completeOrder } = useOrder({ + setCart, + setSelectedCoupon, + addNotification, + }); + + return ( +
+

결제 정보

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

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

+
+
+ ); +} diff --git a/src/basic/features/order/ui/index.ts b/src/basic/features/order/ui/index.ts new file mode 100644 index 00000000..dd49db3a --- /dev/null +++ b/src/basic/features/order/ui/index.ts @@ -0,0 +1 @@ +export { OrderSummary } from './OrderSummary'; diff --git a/src/basic/features/product/admin/hooks/index.ts b/src/basic/features/product/admin/hooks/index.ts new file mode 100644 index 00000000..5977d886 --- /dev/null +++ b/src/basic/features/product/admin/hooks/index.ts @@ -0,0 +1 @@ +export { useProducts } from './useProducts'; diff --git a/src/basic/features/product/admin/hooks/useProducts.ts b/src/basic/features/product/admin/hooks/useProducts.ts new file mode 100644 index 00000000..2ae395e3 --- /dev/null +++ b/src/basic/features/product/admin/hooks/useProducts.ts @@ -0,0 +1,59 @@ +import { useCallback } from 'react'; +import { ProductWithUI } from '../../../../entities/product'; + +interface UseProductsProps { + products: ProductWithUI[]; + setProducts: React.Dispatch>; + addNotification: ( + message: string, + type?: 'error' | 'success' | 'warning' + ) => void; +} + +export function useProducts({ + products, + setProducts, + addNotification, +}: UseProductsProps) { + // 상품 추가 + const addProduct = useCallback( + (newProduct: Omit) => { + const product: ProductWithUI = { + ...newProduct, + id: `p${Date.now()}`, + }; + setProducts((prev) => [...prev, product]); + addNotification('상품이 추가되었습니다.', 'success'); + }, + [setProducts, addNotification] + ); + + // 상품 업데이트 + const updateProduct = useCallback( + (productId: string, updates: Partial) => { + setProducts((prev) => + prev.map((product) => + product.id === productId ? { ...product, ...updates } : product + ) + ); + addNotification('상품이 수정되었습니다.', 'success'); + }, + [setProducts, addNotification] + ); + + // 상품 삭제 + const deleteProduct = useCallback( + (productId: string) => { + setProducts((prev) => prev.filter((p) => p.id !== productId)); + addNotification('상품이 삭제되었습니다.', 'success'); + }, + [setProducts, addNotification] + ); + + return { + products, + addProduct, + updateProduct, + deleteProduct, + }; +} diff --git a/src/basic/features/product/admin/ui/ProductForm.tsx b/src/basic/features/product/admin/ui/ProductForm.tsx new file mode 100644 index 00000000..9358c8e2 --- /dev/null +++ b/src/basic/features/product/admin/ui/ProductForm.tsx @@ -0,0 +1,263 @@ +import { FormEvent } from 'react'; +import { Button } from '../../../../shared/ui'; + +interface ProductFormData { + name: string; + price: number; + stock: number; + description: string; + discounts: Array<{ quantity: number; rate: number }>; +} + +interface ProductFormProps { + productForm: ProductFormData; + setProductForm: React.Dispatch>; + onSubmit: () => void; + onCancel: () => void; + isEditing: boolean; + addNotification: ( + message: string, + type?: 'error' | 'success' | 'warning' + ) => void; +} + +export default function ProductForm({ + productForm, + setProductForm, + onSubmit, + onCancel, + isEditing, + addNotification, +}: ProductFormProps) { + const handleSubmit = (e: FormEvent) => { + e.preventDefault(); + onSubmit(); + }; + + const addDiscount = () => { + setProductForm({ + ...productForm, + discounts: [...productForm.discounts, { quantity: 10, rate: 0.1 }], + }); + }; + + const removeDiscount = (index: number) => { + const newDiscounts = productForm.discounts.filter((_, i) => i !== index); + setProductForm({ + ...productForm, + discounts: newDiscounts, + }); + }; + + const updateDiscount = ( + index: number, + field: 'quantity' | 'rate', + value: number + ) => { + const newDiscounts = [...productForm.discounts]; + newDiscounts[index][field] = value; + setProductForm({ + ...productForm, + discounts: newDiscounts, + }); + }; + + return ( +
+
+

+ {isEditing ? '상품 수정' : '새 상품 추가'} +

+ +
+
+ + + 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) => ( +
+ { + updateDiscount( + index, + 'quantity', + parseInt(e.target.value) || 0 + ); + }} + className='w-20 px-2 py-1 border rounded' + min='1' + placeholder='수량' + /> + 개 이상 구매 시 + { + updateDiscount( + index, + 'rate', + (parseInt(e.target.value) || 0) / 100 + ); + }} + className='w-16 px-2 py-1 border rounded' + min='0' + max='100' + placeholder='%' + /> + % 할인 + +
+ ))} + +
+
+ +
+ + +
+
+
+ ); +} diff --git a/src/basic/features/product/admin/ui/ProductManagement.tsx b/src/basic/features/product/admin/ui/ProductManagement.tsx new file mode 100644 index 00000000..94a08563 --- /dev/null +++ b/src/basic/features/product/admin/ui/ProductManagement.tsx @@ -0,0 +1,113 @@ +import { useState } from 'react'; +import { ProductWithUI } from '../../../../entities/product'; +import { useProducts } from '../hooks'; +import { Button } from '../../../../shared/ui'; +import ProductTable from './ProductTable'; +import ProductForm from './ProductForm'; + +interface ProductManagementProps { + products: ProductWithUI[]; + setProducts: React.Dispatch>; + addNotification: ( + message: string, + type?: 'error' | 'success' | 'warning' + ) => void; +} + +export default function ProductManagement({ + products, + setProducts, + addNotification, +}: ProductManagementProps) { + const { addProduct, updateProduct, deleteProduct } = useProducts({ + products, + setProducts, + addNotification, + }); + + const [showProductForm, setShowProductForm] = useState(false); + const [editingProduct, setEditingProduct] = useState(null); + const [productForm, setProductForm] = useState({ + name: '', + price: 0, + stock: 0, + description: '', + discounts: [] as Array<{ quantity: number; rate: number }>, + }); + + const handleProductSubmit = () => { + if (editingProduct && editingProduct !== 'new') { + updateProduct(editingProduct, productForm); + setEditingProduct(null); + } else { + addProduct(productForm); + } + resetForm(); + }; + + 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 startAddProduct = () => { + setEditingProduct('new'); + setProductForm({ + name: '', + price: 0, + stock: 0, + description: '', + discounts: [], + }); + setShowProductForm(true); + }; + + const resetForm = () => { + setProductForm({ + name: '', + price: 0, + stock: 0, + description: '', + discounts: [], + }); + setEditingProduct(null); + setShowProductForm(false); + }; + + return ( +
+
+
+

상품 목록

+ +
+
+ + + + {showProductForm && ( + + )} +
+ ); +} diff --git a/src/basic/features/product/admin/ui/ProductTable.tsx b/src/basic/features/product/admin/ui/ProductTable.tsx new file mode 100644 index 00000000..9783bfe9 --- /dev/null +++ b/src/basic/features/product/admin/ui/ProductTable.tsx @@ -0,0 +1,86 @@ +import { ProductWithUI } from '../../../../entities/product'; +import { Button } from '../../../../shared/ui'; +import { formatPrice } from '../../../../shared/utils'; + +interface ProductTableProps { + products: ProductWithUI[]; + onEdit: (product: ProductWithUI) => void; + onDelete: (productId: string) => void; +} + +export default function ProductTable({ + products, + onEdit, + onDelete, +}: ProductTableProps) { + // 관리자용 가격 표시 함수 + const displayAdminPrice = (price: number) => { + const formatted = formatPrice(price); + return `${formatted}원`; + }; + return ( +
+ + + + + + + + + + + + {products.map((product) => ( + + + + + + + + ))} + +
+ 상품명 + + 가격 + + 재고 + + 설명 + + 작업 +
+ {product.name} + + {displayAdminPrice(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/features/product/admin/ui/index.ts b/src/basic/features/product/admin/ui/index.ts new file mode 100644 index 00000000..83093283 --- /dev/null +++ b/src/basic/features/product/admin/ui/index.ts @@ -0,0 +1,3 @@ +export { default as ProductManagement } from './ProductManagement'; +export { default as ProductTable } from './ProductTable'; +export { default as ProductForm } from './ProductForm'; diff --git a/src/basic/features/product/shop/hooks/index.ts b/src/basic/features/product/shop/hooks/index.ts new file mode 100644 index 00000000..57636cb8 --- /dev/null +++ b/src/basic/features/product/shop/hooks/index.ts @@ -0,0 +1 @@ +export { useProductSearch } from './useProductSearch'; diff --git a/src/basic/features/product/shop/hooks/useProductSearch.tsx b/src/basic/features/product/shop/hooks/useProductSearch.tsx new file mode 100644 index 00000000..b934b635 --- /dev/null +++ b/src/basic/features/product/shop/hooks/useProductSearch.tsx @@ -0,0 +1,32 @@ +import { useMemo } from 'react'; +import { ProductWithUI } from '../../../../entities/product'; +import { useDebounce } from '../../../../shared/hooks'; + +export function useProductSearch( + products: ProductWithUI[], + searchTerm: string +) { + const debouncedSearchTerm = useDebounce(searchTerm, 500); + + const filteredProducts = useMemo(() => { + if (!debouncedSearchTerm) { + return products; + } + + return products.filter( + (product) => + product.name + .toLowerCase() + .includes(debouncedSearchTerm.toLowerCase()) || + (product.description && + product.description + .toLowerCase() + .includes(debouncedSearchTerm.toLowerCase())) + ); + }, [products, debouncedSearchTerm]); + + return { + debouncedSearchTerm, + filteredProducts, + }; +} diff --git a/src/basic/features/product/shop/ui/ProductCard.tsx b/src/basic/features/product/shop/ui/ProductCard.tsx new file mode 100644 index 00000000..281167c8 --- /dev/null +++ b/src/basic/features/product/shop/ui/ProductCard.tsx @@ -0,0 +1,116 @@ +import { CartItem } from '../../../../../types'; +import { ProductWithUI } from '../../../../entities/product'; +import { Button } from '../../../../shared/ui'; +import { formatPrice, getRemainingStock, getProductStockStatus } from '../../../../shared/utils'; + +interface ProductCardProps { + product: ProductWithUI; + cart: CartItem[]; + onAddToCart: (product: ProductWithUI) => void; +} + +export default function ProductCard({ + product, + cart, + onAddToCart, +}: ProductCardProps) { + // 장바구니에서 현재 상품 수량 찾기 + const cartQuantity = cart.find(item => item.product.id === product.id)?.quantity || 0; + + // 남은 재고 계산 + const remainingStock = getRemainingStock({ + stock: product.stock, + cartQuantity + }); + + // 품절 상태 체크 + const stockStatus = getProductStockStatus({ + stock: product.stock, + cartQuantity + }); + + // 가격 표시 함수 + const displayPrice = () => { + if (stockStatus) return stockStatus; + const formatted = formatPrice(product.price); + return `₩${formatted}`; + }; + return ( +
+ {/* 상품 이미지 영역 (placeholder) */} +
+
+ + + +
+ {product.isRecommended && ( + + BEST + + )} + {product.discounts.length > 0 && ( + + ~{Math.max(...product.discounts.map((d) => d.rate)) * 100}% + + )} +
+ + {/* 상품 정보 */} +
+

{product.name}

+ {product.description && ( +

+ {product.description} +

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

+ {displayPrice()} +

+ {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/features/product/shop/ui/ProductList.tsx b/src/basic/features/product/shop/ui/ProductList.tsx new file mode 100644 index 00000000..0764678a --- /dev/null +++ b/src/basic/features/product/shop/ui/ProductList.tsx @@ -0,0 +1,42 @@ +import { CartItem } from '../../../../../types'; +import { ProductWithUI } from '../../../../entities/product'; +import ProductCard from './ProductCard'; + +interface ProductListProps { + products: ProductWithUI[]; + searchTerm: string; + cart: CartItem[]; + onAddToCart: (product: ProductWithUI) => void; +} + +export default function ProductList({ + products, + searchTerm, + cart, + onAddToCart, +}: ProductListProps) { + if (products.length === 0) { + return ( +
+

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

+
+ ); + } + + return ( +
+ {products.map((product) => { + return ( + + ); + })} +
+ ); +} diff --git a/src/basic/features/product/shop/ui/index.ts b/src/basic/features/product/shop/ui/index.ts new file mode 100644 index 00000000..ff14cf93 --- /dev/null +++ b/src/basic/features/product/shop/ui/index.ts @@ -0,0 +1,2 @@ +export { default as ProductList } from './ProductList'; +export { default as ProductCard } from './ProductCard'; diff --git a/src/basic/pages/AdminPage.tsx b/src/basic/pages/AdminPage.tsx new file mode 100644 index 00000000..b16a7814 --- /dev/null +++ b/src/basic/pages/AdminPage.tsx @@ -0,0 +1,79 @@ +import { useState } from 'react'; +import { Coupon } from '../../types'; +import { ProductWithUI } from '../entities/product'; +import { ProductManagement } from '../features/product/admin/ui'; +import { CouponManagement } from '../features/coupon/admin/ui'; + +interface AdminPageProps { + products: ProductWithUI[]; + setProducts: React.Dispatch>; + coupons: Coupon[]; + setCoupons: React.Dispatch>; + addNotification: ( + message: string, + type?: 'error' | 'success' | 'warning' + ) => void; +} + +export default function AdminPage({ + products, + setProducts, + coupons, + setCoupons, + addNotification, +}: AdminPageProps) { + const [activeTab, setActiveTab] = useState<'products' | 'coupons'>( + 'products' + ); + + return ( +
+ {/* 관리자 대시보드 헤더 */} +
+

관리자 대시보드

+

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

+
+ + {/* 탭 네비게이션 */} +
+ +
+ + {/* 탭 컨텐츠 */} + {activeTab === 'products' ? ( + + ) : ( + + )} +
+ ); +} diff --git a/src/basic/pages/ShoppingPage.tsx b/src/basic/pages/ShoppingPage.tsx new file mode 100644 index 00000000..c19bce6a --- /dev/null +++ b/src/basic/pages/ShoppingPage.tsx @@ -0,0 +1,82 @@ +import { CartItem, Coupon } from '../../types'; +import { ProductWithUI } from '../entities/product'; +import { ProductList } from '../features/product/shop/ui'; +import { useCart } from '../features/cart/hooks'; +import { useProductSearch } from '../features/product/shop/hooks'; +import { ShoppingSidebar } from '../widgets/ShoppingSidebar/ui'; + +interface ShoppingPageProps { + products: ProductWithUI[]; + searchTerm: string; + cart: CartItem[]; + setCart: React.Dispatch>; + coupons: Coupon[]; + selectedCoupon: Coupon | null; + setSelectedCoupon: React.Dispatch>; + addNotification: ( + message: string, + type?: 'error' | 'success' | 'warning' + ) => void; + calculateCartTotalWithCoupon: () => { + totalBeforeDiscount: number; + totalAfterDiscount: number; + }; +} + +export default function ShoppingPage({ + products, + searchTerm, + cart, + setCart, + coupons, + selectedCoupon, + setSelectedCoupon, + addNotification, + calculateCartTotalWithCoupon, +}: ShoppingPageProps) { + const { filteredProducts } = useProductSearch(products, searchTerm); + + const { addToCart } = useCart({ + cart, + setCart, + products, + addNotification, + }); + + return ( +
+
+ {/* 상품 목록 섹션 */} +
+
+

전체 상품

+
+ 총 {products.length}개 상품 +
+
+ + +
+
+ + {/* ShoppingSidebar (widgets) */} +
+ +
+
+ ); +} diff --git a/src/basic/pages/index.ts b/src/basic/pages/index.ts new file mode 100644 index 00000000..1cc41ff8 --- /dev/null +++ b/src/basic/pages/index.ts @@ -0,0 +1,2 @@ +export { default as ShoppingPage } from './ShoppingPage'; +export { default as AdminPage } from './AdminPage'; diff --git a/src/basic/shared/hooks/index.ts b/src/basic/shared/hooks/index.ts new file mode 100644 index 00000000..403a7e87 --- /dev/null +++ b/src/basic/shared/hooks/index.ts @@ -0,0 +1,9 @@ +// localStorage 훅 +export { useLocalStorage } from './useLocalStorage'; + +// 알림 시스템 훅 +export { useNotification } from './useNotification'; +export type { Notification, UseNotificationReturn } from './useNotification'; + +// 디바운스 훅 +export { useDebounce } from './useDebounce'; diff --git a/src/basic/shared/hooks/useDebounce.ts b/src/basic/shared/hooks/useDebounce.ts new file mode 100644 index 00000000..cf979960 --- /dev/null +++ b/src/basic/shared/hooks/useDebounce.ts @@ -0,0 +1,23 @@ +import { useState, useEffect } from 'react'; + +/** + * 값의 변경을 지연시키는 디바운스 훅 + * @param value 디바운스할 값 + * @param delay 지연 시간 (밀리초) + * @returns 디바운스된 값 + */ +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/shared/hooks/useLocalStorage.ts b/src/basic/shared/hooks/useLocalStorage.ts new file mode 100644 index 00000000..5488dc7a --- /dev/null +++ b/src/basic/shared/hooks/useLocalStorage.ts @@ -0,0 +1,41 @@ +import { useState, useEffect } from 'react'; + +/** + * localStorage와 연동된 상태를 관리하는 커스텀 훅 + * @param key localStorage 키 + * @param defaultValue 기본값 + * @returns [상태값, 상태변경함수] + */ +export function useLocalStorage( + key: string, + defaultValue: T +): [T, React.Dispatch>] { + // 초기값 설정 - localStorage에서 복원 + const [state, setState] = useState(() => { + try { + const saved = localStorage.getItem(key); + if (saved) { + return JSON.parse(saved); + } + } catch (error) { + console.warn(`localStorage에서 ${key} 읽기 실패:`, error); + } + return defaultValue; + }); + + // 상태가 변경될 때마다 localStorage에 저장 + useEffect(() => { + try { + if (key === 'cart' && Array.isArray(state) && state.length === 0) { + // 장바구니가 비어있으면 localStorage에서 제거 + localStorage.removeItem(key); + } else { + localStorage.setItem(key, JSON.stringify(state)); + } + } catch (error) { + console.warn(`localStorage에 ${key} 저장 실패:`, error); + } + }, [key, state]); + + return [state, setState]; +} diff --git a/src/basic/shared/hooks/useNotification.ts b/src/basic/shared/hooks/useNotification.ts new file mode 100644 index 00000000..7b9aa844 --- /dev/null +++ b/src/basic/shared/hooks/useNotification.ts @@ -0,0 +1,55 @@ +import { useState, useCallback } from 'react'; + +export interface Notification { + id: string; + message: string; + type: 'error' | 'success' | 'warning'; +} + +export interface UseNotificationReturn { + notifications: Notification[]; + addNotification: ( + message: string, + type?: 'error' | 'success' | 'warning' + ) => void; + removeNotification: (id: string) => void; +} + +/** + * 알림 시스템을 관리하는 커스텀 훅 + * 알림 추가, 자동 제거, 수동 제거 기능 제공 + */ +export function useNotification(): UseNotificationReturn { + const [notifications, setNotifications] = useState([]); + + /** + * 새 알림 추가 (3초 후 자동 제거) + */ + const addNotification = useCallback( + (message: string, type: 'error' | 'success' | 'warning' = 'success') => { + const id = Date.now().toString(); + const newNotification: Notification = { id, message, type }; + + setNotifications((prev) => [...prev, newNotification]); + + // 3초 후 자동 제거 + setTimeout(() => { + setNotifications((prev) => prev.filter((n) => n.id !== id)); + }, 3000); + }, + [] + ); + + /** + * 특정 알림 수동 제거 + */ + const removeNotification = useCallback((id: string) => { + setNotifications((prev) => prev.filter((n) => n.id !== id)); + }, []); + + return { + notifications, + addNotification, + removeNotification, + }; +} diff --git a/src/basic/shared/ui/Button.tsx b/src/basic/shared/ui/Button.tsx new file mode 100644 index 00000000..7eae07d2 --- /dev/null +++ b/src/basic/shared/ui/Button.tsx @@ -0,0 +1,49 @@ +import React from 'react'; + +export interface ButtonProps + extends React.ButtonHTMLAttributes { + variant?: 'primary' | 'secondary' | 'danger' | 'ghost' | 'icon' | 'link'; + size?: 'sm' | 'md' | 'lg'; + children: React.ReactNode; +} + +const Button: React.FC = ({ + variant = 'primary', + size, + className = '', + children, + disabled, + ...props +}) => { + const baseClasses = 'transition-colors focus:outline-none'; + + const variantClasses = { + primary: + 'inline-flex items-center justify-center font-medium bg-gray-900 text-white hover:bg-gray-800 focus:ring-gray-500 disabled:bg-gray-100 disabled:text-gray-400 disabled:cursor-not-allowed', + secondary: + 'inline-flex items-center justify-center font-medium bg-indigo-600 text-white hover:bg-indigo-700 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed', + danger: 'font-medium text-red-600 hover:text-red-800 focus:ring-red-500', + ghost: + 'inline-flex items-center justify-center font-medium border border-gray-300 text-gray-700 bg-white hover:bg-gray-50 focus:ring-gray-500 disabled:opacity-50 disabled:cursor-not-allowed', + icon: 'inline-flex items-center justify-center text-gray-400 hover:text-gray-600', + link: 'text-indigo-600 hover:text-indigo-800', + }; + + const sizeClasses = { + sm: 'px-2 py-1 text-xs rounded', + md: 'px-4 py-2 text-sm rounded-md', + lg: 'px-6 py-3 text-base rounded-lg', + }; + + const classes = `${baseClasses} ${variantClasses[variant]} ${ + size ? sizeClasses[size] : '' + } ${className}`.trim(); + + return ( + + ); +}; + +export default Button; diff --git a/src/basic/shared/ui/Header.tsx b/src/basic/shared/ui/Header.tsx new file mode 100644 index 00000000..e72b5e18 --- /dev/null +++ b/src/basic/shared/ui/Header.tsx @@ -0,0 +1,73 @@ +import { SearchInput, Button } from '.'; +import { CartItem } from '../../../types'; + +interface HeaderProps { + isAdmin: boolean; + searchTerm: string; + cart: CartItem[]; + onToggleAdmin: () => void; + onSearchChange: (value: string) => void; +} + +export default function Header({ + isAdmin, + searchTerm, + cart, + onToggleAdmin, + onSearchChange, +}: HeaderProps) { + const totalItemCount = cart.reduce((sum, item) => sum + item.quantity, 0); + const cartLength = cart.length; + + return ( +
+
+
+
+

SHOP

+ {/* 검색창 */} + {!isAdmin && ( + + )} +
+ +
+
+
+ ); +} diff --git a/src/basic/shared/ui/NotificationToast.tsx b/src/basic/shared/ui/NotificationToast.tsx new file mode 100644 index 00000000..ec858603 --- /dev/null +++ b/src/basic/shared/ui/NotificationToast.tsx @@ -0,0 +1,51 @@ +import { Notification } from '../hooks/useNotification'; + +interface NotificationToastProps { + notifications: Notification[]; + onRemove: (id: string) => void; +} + +export default function NotificationToast({ + notifications, + onRemove, +}: NotificationToastProps) { + if (notifications.length === 0) return null; + + return ( +
+ {notifications.map((notif) => ( +
+ {notif.message} + +
+ ))} +
+ ); +} diff --git a/src/basic/shared/ui/SearchInput.tsx b/src/basic/shared/ui/SearchInput.tsx new file mode 100644 index 00000000..9e9ee832 --- /dev/null +++ b/src/basic/shared/ui/SearchInput.tsx @@ -0,0 +1,40 @@ +interface SearchInputProps { + value: string; + onChange: (value: string) => void; + placeholder?: string; + className?: string; +} + +export default function SearchInput({ + value, + onChange, + placeholder = '상품 검색...', + className, +}: SearchInputProps) { + 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/shared/ui/index.ts b/src/basic/shared/ui/index.ts new file mode 100644 index 00000000..20260123 --- /dev/null +++ b/src/basic/shared/ui/index.ts @@ -0,0 +1,11 @@ +// 알림 관련 +export { default as NotificationToast } from './NotificationToast'; + +// 입력 관련 +export { default as SearchInput } from './SearchInput'; + +// 버튼 관련 +export { default as Button } from './Button'; + +// 레이아웃 관련 +export { default as Header } from './Header'; diff --git a/src/basic/shared/utils/index.ts b/src/basic/shared/utils/index.ts new file mode 100644 index 00000000..1adf3e41 --- /dev/null +++ b/src/basic/shared/utils/index.ts @@ -0,0 +1,2 @@ +export * from './priceUtils'; +export * from './stockUtils'; \ No newline at end of file diff --git a/src/basic/shared/utils/priceUtils.ts b/src/basic/shared/utils/priceUtils.ts new file mode 100644 index 00000000..9011aea8 --- /dev/null +++ b/src/basic/shared/utils/priceUtils.ts @@ -0,0 +1,8 @@ +/** + * 숫자를 천 단위 구분자가 있는 문자열로 포맷팅 + * @param price 포맷팅할 가격 + * @returns 천 단위 구분자가 포함된 문자열 (예: "10,000") + */ +export const formatPrice = (price: number): string => { + return price.toLocaleString(); +}; \ No newline at end of file diff --git a/src/basic/shared/utils/stockUtils.ts b/src/basic/shared/utils/stockUtils.ts new file mode 100644 index 00000000..b20d84f2 --- /dev/null +++ b/src/basic/shared/utils/stockUtils.ts @@ -0,0 +1,31 @@ +/** + * 전체 재고에서 장바구니 수량을 뺀 남은 재고 계산 + * @param stock 전체 재고 수량 + * @param cartQuantity 장바구니에 담긴 수량 + * @returns 남은 재고 수량 + */ +export const getRemainingStock = ({ + stock, + cartQuantity, +}: { + stock: number; + cartQuantity: number; +}) => { + return stock - cartQuantity; +}; + +/** + * 재고 상태를 확인해서 품절 여부를 문자열로 반환 + * @param stock 전체 재고 수량 + * @param cartQuantity 장바구니에 담긴 수량 + * @returns 품절이면 "SOLD OUT", 아니면 빈 문자열 + */ +export const getProductStockStatus = ({ + stock, + cartQuantity, +}: { + stock: number; + cartQuantity: number; +}) => { + return getRemainingStock({ stock, cartQuantity }) <= 0 ? 'SOLD OUT' : ''; +}; \ No newline at end of file diff --git a/src/basic/widgets/ShoppingSidebar/ui/ShoppingSidebar.tsx b/src/basic/widgets/ShoppingSidebar/ui/ShoppingSidebar.tsx new file mode 100644 index 00000000..7443861d --- /dev/null +++ b/src/basic/widgets/ShoppingSidebar/ui/ShoppingSidebar.tsx @@ -0,0 +1,76 @@ +import { useMemo } from 'react'; +import { CartItem, Coupon } from '../../../../types'; +import { ProductWithUI } from '../../../entities/product'; +import { useCart } from '../../../features/cart/hooks'; +import { calculateCartTotal } from '../../../entities/cart'; +import { CartItemsList } from '../../../features/cart/ui'; +import { CouponSelector } from '../../../features/coupon/shop/ui'; +import { OrderSummary } from '../../../features/order/ui'; + +interface ShoppingSidebarProps { + cart: CartItem[]; + setCart: React.Dispatch>; + coupons: Coupon[]; + selectedCoupon: Coupon | null; + setSelectedCoupon: React.Dispatch>; + products: ProductWithUI[]; + addNotification: ( + message: string, + type?: 'error' | 'success' | 'warning' + ) => void; + calculateCartTotalWithCoupon: () => { + totalBeforeDiscount: number; + totalAfterDiscount: number; + }; +} + +export function ShoppingSidebar({ + cart, + setCart, + coupons, + selectedCoupon, + setSelectedCoupon, + products, + addNotification, + calculateCartTotalWithCoupon, +}: ShoppingSidebarProps) { + const { removeFromCart, updateQuantity } = useCart({ + cart, + setCart, + products, + addNotification, + }); + + const totals = useMemo(() => { + return calculateCartTotal(cart, selectedCoupon); + }, [cart, selectedCoupon]); + + return ( +
+ {/* 장바구니 아이템 섹션 */} + + {/* 쿠폰 + 주문 섹션 */} + {cart.length > 0 && ( + <> + + + + )} +
+ ); +} diff --git a/src/basic/widgets/ShoppingSidebar/ui/index.ts b/src/basic/widgets/ShoppingSidebar/ui/index.ts new file mode 100644 index 00000000..4f959865 --- /dev/null +++ b/src/basic/widgets/ShoppingSidebar/ui/index.ts @@ -0,0 +1 @@ +export { ShoppingSidebar } from './ShoppingSidebar'; diff --git a/src/origin/App.tsx b/src/origin/App.tsx index a4369fe1..73760c6b 100644 --- a/src/origin/App.tsx +++ b/src/origin/App.tsx @@ -1,6 +1,9 @@ import { useState, useCallback, useEffect } from 'react'; import { CartItem, Coupon, Product } from '../types'; +// ============================================================================ +// 타입 정의 - UI 확장을 위한 Product 타입 확장 +// ============================================================================ interface ProductWithUI extends Product { description?: string; isRecommended?: boolean; @@ -12,7 +15,9 @@ interface Notification { type: 'error' | 'success' | 'warning'; } -// 초기 데이터 +// ============================================================================ +// 초기 데이터 - 하드코딩된 상품 및 쿠폰 데이터 +// ============================================================================ const initialProducts: ProductWithUI[] = [ { id: 'p1', @@ -21,20 +26,18 @@ const initialProducts: ProductWithUI[] = [ stock: 20, discounts: [ { quantity: 10, rate: 0.1 }, - { quantity: 20, rate: 0.2 } + { quantity: 20, rate: 0.2 }, ], - description: '최고급 품질의 프리미엄 상품입니다.' + description: '최고급 품질의 프리미엄 상품입니다.', }, { id: 'p2', name: '상품2', price: 20000, stock: 20, - discounts: [ - { quantity: 10, rate: 0.15 } - ], + discounts: [{ quantity: 10, rate: 0.15 }], description: '다양한 기능을 갖춘 실용적인 상품입니다.', - isRecommended: true + isRecommended: true, }, { id: 'p3', @@ -43,10 +46,10 @@ const initialProducts: ProductWithUI[] = [ stock: 20, discounts: [ { quantity: 10, rate: 0.2 }, - { quantity: 30, rate: 0.25 } + { quantity: 30, rate: 0.25 }, ], - description: '대용량과 고성능을 자랑하는 상품입니다.' - } + description: '대용량과 고성능을 자랑하는 상품입니다.', + }, ]; const initialCoupons: Coupon[] = [ @@ -54,18 +57,22 @@ const initialCoupons: Coupon[] = [ name: '5000원 할인', code: 'AMOUNT5000', discountType: 'amount', - discountValue: 5000 + discountValue: 5000, }, { name: '10% 할인', code: 'PERCENT10', discountType: 'percentage', - discountValue: 10 - } + discountValue: 10, + }, ]; const App = () => { + // ============================================================================ + // 상태 관리 - localStorage와 연동된 데이터 상태들 + // ============================================================================ + // 상품 목록 상태 (localStorage에서 복원) const [products, setProducts] = useState(() => { const saved = localStorage.getItem('products'); if (saved) { @@ -78,6 +85,7 @@ const App = () => { return initialProducts; }); + // 장바구니 상태 (localStorage에서 복원) const [cart, setCart] = useState(() => { const saved = localStorage.getItem('cart'); if (saved) { @@ -90,6 +98,7 @@ const App = () => { return []; }); + // 쿠폰 목록 상태 (localStorage에서 복원) const [coupons, setCoupons] = useState(() => { const saved = localStorage.getItem('coupons'); if (saved) { @@ -102,36 +111,52 @@ const App = () => { 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); + // ============================================================================ + // UI 상태 관리 - 화면 표시 및 사용자 인터랙션 관련 상태들 + // ============================================================================ + + 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(''); // 디바운스된 검색어 + + // ============================================================================ + // 관리자 폼 상태 - 상품/쿠폰 편집을 위한 폼 데이터 + // ============================================================================ + + const [editingProduct, setEditingProduct] = useState(null); // 편집 중인 상품 ID + + // 상품 폼 데이터 const [productForm, setProductForm] = useState({ name: '', price: 0, stock: 0, description: '', - discounts: [] as Array<{ quantity: number; rate: number }> + discounts: [] as Array<{ quantity: number; rate: number }>, }); + // 쿠폰 폼 데이터 const [couponForm, setCouponForm] = useState({ name: '', code: '', discountType: 'amount' as 'amount' | 'percentage', - discountValue: 0 + discountValue: 0, }); + // ============================================================================ + // 유틸리티 함수들 - 데이터 포맷팅 및 계산 로직 + // ============================================================================ + // 가격 포맷팅 함수 (관리자/일반 사용자 구분, 품절 처리) const formatPrice = (price: number, productId?: string): string => { if (productId) { - const product = products.find(p => p.id === productId); + const product = products.find((p) => p.id === productId); if (product && getRemainingStock(product) <= 0) { return 'SOLD OUT'; } @@ -140,36 +165,41 @@ const App = () => { 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 + return quantity >= discount.quantity && discount.rate > maxDiscount + ? discount.rate : maxDiscount; }, 0); - - const hasBulkPurchase = cart.some(cartItem => cartItem.quantity >= 10); + + // 대량구매 시 추가 할인 (10개 이상 구매 시 5% 추가) + const hasBulkPurchase = cart.some((cartItem) => cartItem.quantity >= 10); if (hasBulkPurchase) { - return Math.min(baseDiscount + 0.05, 0.5); // 대량 구매 시 추가 5% 할인 + return Math.min(baseDiscount + 0.05, 0.5); // 최대 50% 제한 } - + 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; @@ -177,50 +207,74 @@ const App = () => { let totalBeforeDiscount = 0; let totalAfterDiscount = 0; - cart.forEach(item => { + // 각 상품별 금액 계산 + 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); + totalAfterDiscount = Math.max( + 0, + totalAfterDiscount - selectedCoupon.discountValue + ); } else { - totalAfterDiscount = Math.round(totalAfterDiscount * (1 - selectedCoupon.discountValue / 100)); + totalAfterDiscount = Math.round( + totalAfterDiscount * (1 - selectedCoupon.discountValue / 100) + ); } } return { totalBeforeDiscount: Math.round(totalBeforeDiscount), - totalAfterDiscount: Math.round(totalAfterDiscount) + totalAfterDiscount: Math.round(totalAfterDiscount), }; }; + // 남은 재고 계산 (전체 재고 - 장바구니 수량) const getRemainingStock = (product: Product): number => { - const cartItem = cart.find(item => item.product.id === product.id); + 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); - }, []); + // ============================================================================ + // 알림 시스템 - 사용자에게 피드백 제공 + // ============================================================================ + + // 알림 추가 함수 (3초 후 자동 제거) + 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); - + const [totalItemCount, setTotalItemCount] = useState(0); // 장바구니 총 아이템 수 + // 장바구니 아이템 수 업데이트 useEffect(() => { const count = cart.reduce((sum, item) => sum + item.quantity, 0); setTotalItemCount(count); }, [cart]); + // ============================================================================ + // localStorage 동기화 Effects - 상태 변경 시 localStorage에 저장 + // ============================================================================ + useEffect(() => { localStorage.setItem('products', JSON.stringify(products)); }, [products]); @@ -237,6 +291,10 @@ const App = () => { } }, [cart]); + // ============================================================================ + // 검색 기능 - 디바운스를 통한 성능 최적화 + // ============================================================================ + useEffect(() => { const timer = setTimeout(() => { setDebouncedSearchTerm(searchTerm); @@ -244,127 +302,198 @@ const App = () => { 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; - } + // 장바구니에 상품 추가 + const addToCart = useCallback( + (product: ProductWithUI) => { + const remainingStock = getRemainingStock(product); + if (remainingStock <= 0) { + addNotification('재고가 부족합니다!', 'error'); + return; + } - return prevCart.map(item => - item.product.id === product.id - ? { ...item, quantity: newQuantity } - : item + setCart((prevCart) => { + const existingItem = prevCart.find( + (item) => item.product.id === product.id ); - } - - return [...prevCart, { product, quantity: 1 }]; - }); - - addNotification('장바구니에 담았습니다', 'success'); - }, [cart, addNotification, getRemainingStock]); + 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)); + setCart((prevCart) => + prevCart.filter((item) => item.product.id !== productId) + ); }, []); - const updateQuantity = useCallback((productId: string, newQuantity: number) => { - if (newQuantity <= 0) { - removeFromCart(productId); - return; - } + // 장바구니 상품 수량 업데이트 + 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 product = products.find((p) => p.id === productId); + if (!product) return; - const maxStock = product.stock; - if (newQuantity > maxStock) { - addNotification(`재고는 ${maxStock}개까지만 있습니다.`, 'error'); - 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; - } + 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; - setSelectedCoupon(coupon); - addNotification('쿠폰이 적용되었습니다.', 'success'); - }, [addNotification, calculateCartTotal]); + // 퍼센트 쿠폰 최소 주문 금액 검증 + 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'); + 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 addProduct = useCallback( + (newProduct: Omit) => { + const product: ProductWithUI = { + ...newProduct, + id: `p${Date.now()}`, + }; + setProducts((prev) => [...prev, product]); + addNotification('상품이 추가되었습니다.', 'success'); + }, + [addNotification] + ); - const deleteProduct = useCallback((productId: string) => { - setProducts(prev => prev.filter(p => p.id !== productId)); - 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 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 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') { @@ -373,14 +502,21 @@ const App = () => { } else { addProduct({ ...productForm, - discounts: productForm.discounts + discounts: productForm.discounts, }); } - setProductForm({ name: '', price: 0, stock: 0, description: '', discounts: [] }); + setProductForm({ + name: '', + price: 0, + stock: 0, + description: '', + discounts: [], + }); setEditingProduct(null); setShowProductForm(false); }; + // 쿠폰 폼 제출 const handleCouponSubmit = (e: React.FormEvent) => { e.preventDefault(); addCoupon(couponForm); @@ -388,11 +524,12 @@ const App = () => { name: '', code: '', discountType: 'amount', - discountValue: 0 + discountValue: 0, }); setShowCouponForm(false); }; + // 상품 편집 시작 const startEditProduct = (product: ProductWithUI) => { setEditingProduct(product.id); setProductForm({ @@ -400,82 +537,126 @@ const App = () => { price: product.price, stock: product.stock, description: product.description || '', - discounts: product.discounts || [] + discounts: product.discounts || [], }); setShowProductForm(true); }; - const totals = calculateCartTotal(); + // ============================================================================ + // 계산된 값들 - 렌더링에 필요한 파생 데이터 + // ============================================================================ + + const totals = calculateCartTotal(); // 장바구니 총액 계산 결과 + // 검색 필터링된 상품 목록 const filteredProducts = debouncedSearchTerm - ? products.filter(product => - product.name.toLowerCase().includes(debouncedSearchTerm.toLowerCase()) || - (product.description && product.description.toLowerCase().includes(debouncedSearchTerm.toLowerCase())) + ? products.filter( + (product) => + product.name + .toLowerCase() + .includes(debouncedSearchTerm.toLowerCase()) || + (product.description && + product.description + .toLowerCase() + .includes(debouncedSearchTerm.toLowerCase())) ) : products; + // ============================================================================ + // 거대한 JSX 렌더링 - 모든 UI 컴포넌트가 인라인으로 작성됨 + // ============================================================================ + return ( -
+
+ {/* 알림 시스템 - 우상단 고정 위치 */} {notifications.length > 0 && ( -
- {notifications.map(notif => ( +
+ {notifications.map((notif) => (
- {notif.message} -
))}
)} -
-
-
-
-

SHOP

+ + {/* 헤더 - 검색바, 관리자 모드 토글, 장바구니 아이콘 */} +
+
+
+
+

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" + placeholder='상품 검색...' + className='w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500' />
)}
-
-
+ {/* 메인 컨텐츠 - 관리자 모드와 쇼핑몰 모드 조건부 렌더링 */} +
{isAdmin ? ( -
-
-

관리자 대시보드

-

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

+ // ============================================================================ + // 관리자 페이지 전체 UI (상품 관리 + 쿠폰 관리) + // ============================================================================ +
+
+

+ 관리자 대시보드 +

+

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

-
-
{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) }); + + + {(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, + }) } - }} - 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' + 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" - placeholder="숫자만 입력" - required - /> -
-
- - { - const value = e.target.value; - if (value === '' || /^\d+$/.test(value)) { - setProductForm({ ...productForm, stock: value === '' ? 0 : parseInt(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 === '') { - 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 }); + onChange={(e) => { + 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 + /> +
+
+ + + onChange={(e) => { + 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="%" - /> - % 할인 - -
- ))} + { + 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 - /> -
-
-
- +
+
+

+ {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}"에 대한 검색 결과가 없습니다.

+
+

+ "{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)}

+
+ {filteredProducts.map((product) => { + const remainingStock = getRemainingStock(product); + + return ( + // 개별 상품 카드 +
+ {/* 상품 이미지 영역 (placeholder) */} +
+
+ + + +
+ {product.isRecommended && ( + + BEST + + )} {product.discounts.length > 0 && ( -

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

+ + ~ + {Math.max( + ...product.discounts.map((d) => d.rate) + ) * 100} + % + )}
- - {/* 재고 상태 */} -
- {remainingStock <= 5 && remainingStock > 0 && ( -

품절임박! {remainingStock}개 남음

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

재고 {remainingStock}개

+ + {/* 상품 정보 */} +
+

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

{item.product.name}

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

+

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

@@ -1049,64 +1534,85 @@ const App = () => { )}
+ {/* 쿠폰 할인 섹션 */} {cart.length > 0 && ( <> -
-
-

쿠폰 할인

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

결제 정보

-
-
- 상품 금액 - {totals.totalBeforeDiscount.toLocaleString()}원 + {/* 결제 정보 섹션 */} +
+

결제 정보

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

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

@@ -1121,4 +1627,4 @@ const App = () => { ); }; -export default App; \ No newline at end of file +export default App; diff --git a/tsconfig.app.json b/tsconfig.app.json index d739292a..2ef6aebb 100644 --- a/tsconfig.app.json +++ b/tsconfig.app.json @@ -23,5 +23,6 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true }, - "include": ["src"] + "include": ["src"], + "exclude": ["node_modules", "src/refactoring(hint)/**/*"] } diff --git a/vite.config.ts b/vite.config.ts index e6c4016b..d03b4afd 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -5,12 +5,22 @@ import react from '@vitejs/plugin-react-swc'; export default mergeConfig( defineConfig({ plugins: [react()], + base: '/front_6th_chapter2-2/', // 프로덕션용 고정값 + build: { + outDir: 'dist', + rollupOptions: { + input: { + main: 'index.html', + }, + external: [/src\/refactoring\(hint\)/], + }, + }, }), defineTestConfig({ test: { globals: true, environment: 'jsdom', - setupFiles: './src/setupTests.ts' + setupFiles: './src/setupTests.ts', }, }) -) +);