diff --git a/app/[locale]/cart/page.tsx b/app/[locale]/cart/page.tsx index 009dfe3..3b9ae8d 100644 --- a/app/[locale]/cart/page.tsx +++ b/app/[locale]/cart/page.tsx @@ -1,53 +1,79 @@ -"use client" -import { useState, useEffect } from "react" -import { Card } from "@/components/ui/card" -import { Separator } from "@/components/ui/separator" -import CartItemCard from "./ui/CartItemCard" -import OrderSummary from "./ui/OrderSummary" -import { useCart, useCreateOrder, useRegions, useAddresses, usePaymentTypes } from "@/lib/hooks" -import { useTranslations } from "next-intl" -import { useRouter } from "next/navigation" -import type { DeliveryType, PaymentTypeOption } from "./ui/types" +"use client"; +import { useState, useEffect } from "react"; +import { Card } from "@/components/ui/card"; +import { Separator } from "@/components/ui/separator"; +import CartItemCard from "../../../features/cart/components/CartItemCard"; +import OrderSummary from "../../../features/cart/components/OrderSummary"; +import { + useCart, + useCreateOrder, + useRegions, + usePaymentTypes, +} from "@/lib/hooks"; +import { userStore } from "@/features/profile/userStore"; +import { useTranslations } from "next-intl"; +import { useRouter } from "next/navigation"; +import type { DeliveryType, PaymentType } from "../../../features/cart/types"; export default function CartPage() { - const [isClient, setIsClient] = useState(false) - const [paymentType, setPaymentType] = useState(null) - const [deliveryType, setDeliveryType] = useState("SELECTED_DELIVERY") - const [selectedRegion, setSelectedRegion] = useState(null) - const [selectedAddress, setSelectedAddress] = useState("") - const [note, setNote] = useState("") - const router = useRouter() + const [isClient, setIsClient] = useState(false); + const [paymentType, setPaymentType] = useState(null); + const [deliveryType, setDeliveryType] = useState("SELECTED_DELIVERY"); + const [selectedRegion, setSelectedRegion] = useState(""); + const [selectedProvince, setSelectedProvince] = useState(null); + const [note, setNote] = useState(""); + const router = useRouter(); - const t = useTranslations() + const t = useTranslations(); - // useCart dönen data yapısı: { message: "success", data: [...] } - const { data: cartResponse, isLoading, isError } = useCart() - const { data: regions = [] } = useRegions() - const { data: addresses = [] } = useAddresses() - const { data: paymentTypes = [] } = usePaymentTypes() - const { mutate: createOrder, isPending: isCreatingOrder } = useCreateOrder() + const { data: cartResponse, isLoading, isError } = useCart(); + const { data: provinces = [] } = useRegions(); + const { data: paymentTypes = [] } = usePaymentTypes(); + const { mutate: createOrder, isPending: isCreatingOrder } = useCreateOrder(); - // Cart items'ı doğru şekilde al - const cartItems = cartResponse?.data || [] + const cartItems = cartResponse?.data || []; useEffect(() => { - setIsClient(true) - }, []) + setIsClient(true); + }, []); + + const regionGroups = provinces.reduce((acc, province) => { + if (!acc[province.region]) { + acc[province.region] = []; + } + acc[province.region].push(province); + return acc; + }, {} as Record); + + const availableRegions = Object.keys(regionGroups); const handleDeliveryTypeChange = (type: DeliveryType) => { - setDeliveryType(type) - setSelectedAddress("") - } + setDeliveryType(type); + setSelectedProvince(null); + }; const handleCompleteOrder = () => { - if (!selectedRegion || !selectedAddress || !paymentType) { - console.warn("Missing required fields for order") - return + if (!selectedRegion || !selectedProvince || !paymentType) { + console.warn("Missing required fields for order"); + return; + } + + const selectedProvinceData = provinces.find((p) => p.id === selectedProvince); + if (!selectedProvinceData) return; + + // Kullanıcı bilgilerini store'dan al + const orderData = userStore.getOrderData(); + if (!orderData) { + console.error("User data not found"); + router.push("/login"); + return; } createOrder( { - customer_address: selectedAddress, + customer_name: orderData.customer_name, + customer_phone: orderData.customer_phone, + customer_address: selectedProvinceData.name, shipping_method: deliveryType === "PICK_UP" ? "pickup" : "standart", payment_type_id: paymentType.id, region: selectedRegion, @@ -55,30 +81,30 @@ export default function CartPage() { }, { onSuccess: () => { - router.push(`/orders`) + router.push(`/orders`); }, - }, - ) - } + } + ); + }; - if (!isClient) return null + if (!isClient) return null; if (isLoading) { return (

{t("loading")}

- ) + ); } if (isError || cartItems.length === 0) { return (

- {t("emptyCart") || "Your cart is empty"} + {t("emptyCart")}

- ) + ); } const translations = { @@ -100,105 +126,108 @@ export default function CartPage() { placeOrder: t("order"), emptyCart: t("cart_empty"), map: t("address"), - } + }; - // Group items by seller (from channel) - const itemsBySeller = cartItems.reduce( - (acc, item) => { - const sellerId = item.product.channel?.[0]?.id || 0 - const sellerName = item.product.channel?.[0]?.name || "Unknown Seller" - - if (!acc[sellerId]) { - acc[sellerId] = { - seller: { id: sellerId, name: sellerName }, - items: [] - } - } - acc[sellerId].items.push(item) - return acc - }, - {} as Record - ) + const itemsBySeller = cartItems.reduce((acc, item) => { + const sellerId = item.product.channel?.[0]?.id || 0; + const sellerName = item.product.channel?.[0]?.name || "Unknown Seller"; + + if (!acc[sellerId]) { + acc[sellerId] = { + seller: { id: sellerId, name: sellerName }, + items: [], + }; + } + acc[sellerId].items.push(item); + return acc; + }, {} as Record); - // Calculate total const totalAmount = cartItems.reduce((sum, item) => { - const price = parseFloat(item.product.price_amount || "0") - return sum + (price * item.product_quantity) - }, 0) + const price = parseFloat(item.product.price_amount || "0"); + return sum + price * item.product_quantity; + }, 0); return (

{translations.cart}

- {/* Cart Items Section */}
- {/* Sellers */} - {Object.entries(itemsBySeller).map(([sellerId, { seller, items }]) => ( -
-

{seller.name}

-
- {items.map((item) => { - const price = parseFloat(item.product.price_amount || "0") - const quantity = item.product_quantity - const total = price * quantity - - return ( - m.images_800x800 || m.thumbnail) || [] - } - }} - translations={translations} - /> - ) - })} + {Object.entries(itemsBySeller).map( + ([sellerId, { seller, items }]) => ( +
+

{seller.name}

+
+ {items.map((item) => { + const price = parseFloat(item.product.price_amount || "0"); + const quantity = item.product_quantity; + const total = price * quantity; + + return ( + m.images_800x800 || m.thumbnail + ) || [], + }, + }} + translations={translations} + /> + ); + })} +
+ {Object.entries(itemsBySeller).length > 1 && ( + + )}
- {Object.entries(itemsBySeller).length > 1 && } -
- ))} + ) + )}
- {/* Order Summary Sidebar */} ({ + items: cartItems.map((item) => ({ ...item, quantity: item.product_quantity, price: parseFloat(item.product.price_amount || "0"), - total: parseFloat(item.product.price_amount || "0") * item.product_quantity, - seller: { - id: item.product.channel?.[0]?.id || 0, - name: item.product.channel?.[0]?.name || "Unknown" - } + total: + parseFloat(item.product.price_amount || "0") * + item.product_quantity, + seller: { + id: item.product.channel?.[0]?.id || 0, + name: item.product.channel?.[0]?.name || "Unknown", + }, })), billing: { body: [ - { - title: t("goods"), - value: `${totalAmount.toFixed(2)} TMT` - } + { + title: t("goods"), + value: `${totalAmount.toFixed(2)} TMT`, + }, ], - footer: { - title: t("total"), - value: `${totalAmount.toFixed(2)} TMT` + footer: { + title: t("total"), + value: `${totalAmount.toFixed(2)} TMT`, }, }, }} @@ -206,21 +235,20 @@ export default function CartPage() { paymentType={paymentType} deliveryType={deliveryType} selectedRegion={selectedRegion} - selectedAddress={selectedAddress} + selectedProvince={selectedProvince} note={note} - regions={regions} - addresses={addresses} + regionGroups={regionGroups} + availableRegions={availableRegions} paymentTypes={paymentTypes} onPaymentTypeChange={setPaymentType} onDeliveryTypeChange={handleDeliveryTypeChange} onRegionChange={setSelectedRegion} - onAddressChange={setSelectedAddress} + onProvinceChange={setSelectedProvince} onNoteChange={setNote} - onMapOpen={() => {}} onCompleteOrder={handleCompleteOrder} isLoading={isCreatingOrder} />
- ) + ); } \ No newline at end of file diff --git a/app/[locale]/cart/ui/OrderSummary.tsx b/app/[locale]/cart/ui/OrderSummary.tsx deleted file mode 100644 index cb083d7..0000000 --- a/app/[locale]/cart/ui/OrderSummary.tsx +++ /dev/null @@ -1,216 +0,0 @@ -"use client" -import { MapPin } from "lucide-react" -import { Button } from "@/components/ui/button" -import { Card } from "@/components/ui/card" -import { Label } from "@/components/ui/label" -import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group" -import { Textarea } from "@/components/ui/textarea" -import { Separator } from "@/components/ui/separator" -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue -} from "@/components/ui/select" -import DeliveryTypeSelector from "./DeliveryTypeSelector" -import type { - Order, - Region, - Address, - DeliveryType, - CartTranslations, - PaymentTypeOption -} from "./types" - -interface OrderSummaryProps { - order: Order - translations: CartTranslations - paymentType: PaymentTypeOption | null - deliveryType: DeliveryType - selectedRegion: string | null - selectedAddress: string - note: string - regions: Region[] - addresses: Address[] - paymentTypes: PaymentTypeOption[] - onPaymentTypeChange: (type: PaymentTypeOption) => void - onDeliveryTypeChange: (type: DeliveryType) => void - onRegionChange: (regionCode: string) => void - onAddressChange: (address: string) => void - onNoteChange: (note: string) => void - onMapOpen: () => void - onCompleteOrder: () => void - isLoading: boolean -} - -export default function OrderSummary({ - order, - translations: t, - paymentType, - deliveryType, - selectedRegion, - selectedAddress, - note, - regions, - addresses, - paymentTypes, - onPaymentTypeChange, - onDeliveryTypeChange, - onRegionChange, - onAddressChange, - onNoteChange, - onMapOpen, - onCompleteOrder, - isLoading, -}: OrderSummaryProps) { - // Filter addresses based on selected region - const filteredAddresses = selectedRegion - ? addresses.filter((addr) => { - const region = regions.find((r) => r.code === selectedRegion) - return region && addr.region_id === region.id - }) - : [] - - // Validate form completion - const isFormValid = selectedRegion && selectedAddress && paymentType - - return ( - - {/* Payment Type Selection */} -
-

{t.paymentType}

-
- {paymentTypes.map((type) => ( - onPaymentTypeChange(type)} - > -
- {type.name} -
-
- ))} -
-
- - {/* Delivery Type Selection */} - - - {/* Region Selection */} -
- - - {regions.map((region) => ( -
- - -
- ))} -
-
- - {/* Address Selection (only show when region is selected) */} - {selectedRegion && filteredAddresses.length > 0 && ( -
- -
- - -
-
- )} - - {/* Note Input */} -
- -