connected api with profile, order

This commit is contained in:
Jelaletdin12
2025-11-15 16:14:01 +05:00
parent 21b9e88c5c
commit f867896817
70 changed files with 2370 additions and 2317 deletions

View File

@@ -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<PaymentTypeOption | null>(null)
const [deliveryType, setDeliveryType] = useState<DeliveryType>("SELECTED_DELIVERY")
const [selectedRegion, setSelectedRegion] = useState<string | null>(null)
const [selectedAddress, setSelectedAddress] = useState<string>("")
const [note, setNote] = useState<string>("")
const router = useRouter()
const [isClient, setIsClient] = useState(false);
const [paymentType, setPaymentType] = useState<PaymentType | null>(null);
const [deliveryType, setDeliveryType] = useState<DeliveryType>("SELECTED_DELIVERY");
const [selectedRegion, setSelectedRegion] = useState<string>("");
const [selectedProvince, setSelectedProvince] = useState<number | null>(null);
const [note, setNote] = useState<string>("");
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<string, typeof provinces>);
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 (
<div className="container mx-auto px-4 min-h-[90vh] flex items-center justify-center">
<p>{t("loading")}</p>
</div>
)
);
}
if (isError || cartItems.length === 0) {
return (
<div className="container mx-auto px-4 min-h-[90vh] flex items-center justify-center">
<h2 className="text-3xl md:text-4xl lg:text-5xl text-gray-400 font-semibold">
{t("emptyCart") || "Your cart is empty"}
{t("emptyCart")}
</h2>
</div>
)
);
}
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<number, { seller: any; items: typeof cartItems }>
)
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<number, { seller: any; items: typeof cartItems }>);
// 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 (
<div className="container mx-auto px-4 py-8 min-h-screen">
<h1 className="text-3xl font-bold mb-6">{translations.cart}</h1>
<div className="flex flex-col md:flex-row gap-6">
{/* Cart Items Section */}
<div className="flex-1">
<Card className="p-6 rounded-xl">
{/* Sellers */}
{Object.entries(itemsBySeller).map(([sellerId, { seller, items }]) => (
<div key={sellerId} className="mb-6">
<p className="text-base font-semibold mb-3">{seller.name}</p>
<div className="space-y-4">
{items.map((item) => {
const price = parseFloat(item.product.price_amount || "0")
const quantity = item.product_quantity
const total = price * quantity
return (
<CartItemCard
key={item.id}
item={{
...item,
quantity: quantity,
price: price,
total: total,
seller: seller,
price_formatted: `${item.product.price_amount} TMT`,
sub_total_formatted: `${item.product.price_amount} TMT`,
total_formatted: `${total.toFixed(2)} TMT`,
discount_formatted: "0 TMT",
product: {
...item.product,
image: item.product.media?.[0]?.images_800x800 || item.product.media?.[0]?.thumbnail,
images: item.product.media?.map(m => m.images_800x800 || m.thumbnail) || []
}
}}
translations={translations}
/>
)
})}
{Object.entries(itemsBySeller).map(
([sellerId, { seller, items }]) => (
<div key={sellerId} className="mb-6">
<p className="text-base font-semibold mb-3">{seller.name}</p>
<div className="space-y-4">
{items.map((item) => {
const price = parseFloat(item.product.price_amount || "0");
const quantity = item.product_quantity;
const total = price * quantity;
return (
<CartItemCard
key={item.id}
item={{
...item,
quantity: quantity,
price: price,
total: total,
seller: seller,
price_formatted: `${item.product.price_amount} TMT`,
sub_total_formatted: `${item.product.price_amount} TMT`,
total_formatted: `${total.toFixed(2)} TMT`,
discount_formatted: "0 TMT",
product: {
...item.product,
image:
item.product.media?.[0]?.images_800x800 ||
item.product.media?.[0]?.thumbnail,
images:
item.product.media?.map(
(m) => m.images_800x800 || m.thumbnail
) || [],
},
}}
translations={translations}
/>
);
})}
</div>
{Object.entries(itemsBySeller).length > 1 && (
<Separator className="mt-4" />
)}
</div>
{Object.entries(itemsBySeller).length > 1 && <Separator className="mt-4" />}
</div>
))}
)
)}
</Card>
</div>
{/* Order Summary Sidebar */}
<OrderSummary
order={{
id: 1,
seller: { id: 1, name: "Store" },
items: cartItems.map(item => ({
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}
/>
</div>
</div>
)
);
}

View File

@@ -1,229 +0,0 @@
"use client"
import { useState, useEffect, useRef } from "react"
import Image from "next/image"
import { Minus, Plus, Trash2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import {
useUpdateCartItemQuantity,
useRemoveFromCart
} from "@/lib/hooks"
import type { CartItem, CartTranslations } from "./types"
interface CartItemCardProps {
item: CartItem
translations: CartTranslations
onUpdate?: () => void
}
export default function CartItemCard({
item,
translations: t,
onUpdate
}: CartItemCardProps) {
const [localQuantity, setLocalQuantity] = useState(item.quantity)
const [pendingQuantity, setPendingQuantity] = useState(item.quantity)
const [isLoading, setIsLoading] = useState(false)
const updateTimeoutRef = useRef<NodeJS.Timeout>()
const { mutate: updateQuantity } = useUpdateCartItemQuantity()
const { mutate: removeItem, isPending: isRemoving } = useRemoveFromCart()
// Sync local quantity with server quantity
useEffect(() => {
setLocalQuantity(item.quantity)
setPendingQuantity(item.quantity)
}, [item.quantity])
// Debounced update effect
useEffect(() => {
if (pendingQuantity === item.quantity) {
return
}
// Clear previous timeout
if (updateTimeoutRef.current) {
clearTimeout(updateTimeoutRef.current)
}
// Set new timeout for update
updateTimeoutRef.current = setTimeout(() => {
setIsLoading(true)
if (pendingQuantity <= 0) {
removeItem(item.id, {
onSuccess: () => {
onUpdate?.()
},
onError: (error) => {
console.error("Failed to remove item:", error)
// Revert on error
setLocalQuantity(item.quantity)
setPendingQuantity(item.quantity)
},
onSettled: () => {
setIsLoading(false)
},
})
} else {
updateQuantity(
{ itemId: item.id, quantity: pendingQuantity },
{
onSuccess: () => {
onUpdate?.()
},
onError: (error) => {
console.error("Failed to update quantity:", error)
// Revert on error
setLocalQuantity(item.quantity)
setPendingQuantity(item.quantity)
},
onSettled: () => {
setIsLoading(false)
},
}
)
}
}, 300)
return () => {
if (updateTimeoutRef.current) {
clearTimeout(updateTimeoutRef.current)
}
}
}, [pendingQuantity, item.quantity, item.id, updateQuantity, removeItem, onUpdate])
const handleQuantityIncrease = (e: React.MouseEvent) => {
e.preventDefault()
e.stopPropagation()
if (isLoading) return
const newQuantity = localQuantity + 1
setLocalQuantity(newQuantity)
setPendingQuantity(newQuantity)
}
const handleQuantityDecrease = (e: React.MouseEvent) => {
e.preventDefault()
e.stopPropagation()
if (isLoading) return
const newQuantity = localQuantity - 1
if (newQuantity < 1) {
handleDelete()
return
}
setLocalQuantity(newQuantity)
setPendingQuantity(newQuantity)
}
const handleDelete = () => {
setIsLoading(true)
removeItem(item.id, {
onSuccess: () => {
onUpdate?.()
},
onError: (error) => {
console.error("Failed to remove item:", error)
},
onSettled: () => {
setIsLoading(false)
},
})
}
const getImageSrc = () => {
if (item.product.image) return item.product.image
if (item.product.images && item.product.images.length > 0) {
return item.product.images[0]
}
return "/placeholder.svg"
}
return (
<Card className="p-4 shadow-none border">
<div className="flex flex-col sm:flex-row gap-4">
{/* Product Image & Info */}
<div className="flex gap-4 flex-1">
<div className="relative w-[88px] h-[117px] rounded-xl border overflow-hidden flex-shrink-0">
<Image
src={getImageSrc()}
alt={item.product.name}
fill
className="object-contain"
/>
</div>
<div className="flex flex-col gap-2">
<h3 className="font-semibold text-base">{item.product.name}</h3>
<p className="text-sm text-gray-600">{item.seller.name}</p>
<Button
variant="ghost"
size="sm"
onClick={handleDelete}
disabled={isRemoving || isLoading}
className="w-fit p-0 h-auto hover:bg-transparent hover:text-red-500"
>
<Trash2 className="h-5 w-5" />
</Button>
</div>
</div>
{/* Price & Quantity */}
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4 justify-between">
<div className="space-y-1">
<p className="text-sm font-semibold">
{t.pricePerUnit}{" "}
<span className="text-primary">
{item.price_formatted || `${item.price} TMT`}
</span>
</p>
<p className="text-sm font-semibold">
{t.additionalPrice}{" "}
{item.sub_total_formatted || `${item.total} TMT`}
</p>
{item.discount_formatted && item.discount_formatted !== "0 TMT" && (
<p className="text-sm font-semibold">
{t.discount} {item.discount_formatted}
</p>
)}
<div className="flex items-center gap-2">
<span className="text-sm font-semibold">{t.totalPrice}</span>
<span className="bg-green-500 text-white px-3 py-1 rounded-xl font-semibold text-base">
{item.total_formatted || `${item.total} TMT`}
</span>
</div>
</div>
{/* Quantity Controls */}
<div className="flex items-center gap-2">
<Button
variant="outline"
size="icon"
onClick={handleQuantityDecrease}
disabled={isLoading || isRemoving}
className="rounded-xl bg-blue-50"
>
<Minus className="h-4 w-4" />
</Button>
<div className="w-12 text-center font-semibold">
{localQuantity}
</div>
<Button
variant="outline"
size="icon"
onClick={handleQuantityIncrease}
disabled={isLoading || isRemoving}
className="rounded-xl bg-blue-50"
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
</div>
</Card>
)
}

View File

@@ -1,57 +0,0 @@
"use client"
import { Truck, Warehouse } from "lucide-react"
import { Card } from "@/components/ui/card"
import { DeliveryType, CartTranslations } from "./types"
interface DeliveryTypeSelectorProps {
selectedType: DeliveryType
onSelect: (type: DeliveryType) => void
translations: CartTranslations
}
export default function DeliveryTypeSelector({
selectedType,
onSelect,
translations: t,
}: DeliveryTypeSelectorProps) {
const deliveryOptions: {
type: DeliveryType
label: string
icon: typeof Truck
}[] = [
{ type: "SELECTED_DELIVERY", label: t.delivery, icon: Truck },
{ type: "PICK_UP", label: t.pickup, icon: Warehouse },
]
return (
<div className="mb-6">
<h3 className="text-lg font-semibold mb-3">{t.deliveryType}</h3>
<div className="flex gap-2">
{deliveryOptions.map(({ type, label, icon: Icon }) => (
<Card
key={type}
className={`flex-1 cursor-pointer transition-all hover:shadow-md ${
selectedType === type
? "border-2 border-[#005bff] bg-blue-50"
: "border-2 border-gray-200"
}`}
onClick={() => onSelect(type)}
>
<div className="flex flex-col items-center justify-center p-4 gap-2">
<Icon
className={`h-8 w-8 ${
selectedType === type ? "text-[#005bff]" : "text-gray-600"
}`}
/>
<span className={`text-xs font-medium ${
selectedType === type ? "text-[#005bff]" : "text-gray-700"
}`}>
{label}
</span>
</div>
</Card>
))}
</div>
</div>
)
}

View File

@@ -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 (
<Card className="w-full md:w-[380px] p-6 rounded-xl h-fit sticky top-20">
{/* Payment Type Selection */}
<div className="mb-6">
<h3 className="text-lg font-semibold mb-3">{t.paymentType}</h3>
<div className="flex gap-2">
{paymentTypes.map((type) => (
<Card
key={type.id}
className={`flex-1 cursor-pointer transition-all ${
paymentType?.id === type.id
? "border-2 border-[#005bff]"
: "border-2 border-gray-200"
}`}
onClick={() => onPaymentTypeChange(type)}
>
<div className="flex flex-col items-center justify-center p-4 gap-2">
<span className="text-xs font-medium">{type.name}</span>
</div>
</Card>
))}
</div>
</div>
{/* Delivery Type Selection */}
<DeliveryTypeSelector
selectedType={deliveryType}
onSelect={onDeliveryTypeChange}
translations={t}
/>
{/* Region Selection */}
<div className="mb-6">
<Label className="text-lg font-semibold mb-3 block">
{t.selectRegion}
</Label>
<RadioGroup
value={selectedRegion || ""}
onValueChange={onRegionChange}
className="flex flex-wrap gap-4"
>
{regions.map((region) => (
<div key={region.id} className="flex items-center space-x-2">
<RadioGroupItem
value={region.code}
id={`region-${region.id}`}
className="border-2 border-gray-400 data-[state=checked]:border-[#005bff] data-[state=checked]:bg-white data-[state=checked]:[&_svg]:fill-[#005bff] data-[state=checked]:[&_svg]:stroke-[#005bff]"
/>
<Label
htmlFor={`region-${region.id}`}
className="cursor-pointer"
>
{region.name}
</Label>
</div>
))}
</RadioGroup>
</div>
{/* Address Selection (only show when region is selected) */}
{selectedRegion && filteredAddresses.length > 0 && (
<div className="mb-6">
<Label className="text-lg font-semibold mb-3 block">
{t.selectAddress}
</Label>
<div className="flex gap-2">
<Select value={selectedAddress} onValueChange={onAddressChange}>
<SelectTrigger className="rounded-xl">
<SelectValue placeholder={t.selectAddress} />
</SelectTrigger>
<SelectContent>
{filteredAddresses.map((addr) => (
<SelectItem key={addr.id} value={addr.address}>
{addr.title} - {addr.address}
</SelectItem>
))}
</SelectContent>
</Select>
<Button
variant="outline"
size="icon"
onClick={onMapOpen}
className="rounded-xl flex-shrink-0 bg-transparent"
>
<MapPin className="h-5 w-5" />
</Button>
</div>
</div>
)}
{/* Note Input */}
<div className="mb-6">
<Label className="text-lg font-semibold mb-3 block">{t.note}</Label>
<Textarea
value={note}
onChange={(e) => onNoteChange(e.target.value)}
className="rounded-xl resize-none"
rows={3}
placeholder={t.note}
/>
</div>
{/* Billing Summary */}
<div className="space-y-2 mb-4">
{order.billing.body.map((item, index) => (
<div
key={index}
className="flex justify-between text-base font-medium"
>
<span>{item.title}:</span>
<span>{item.value}</span>
</div>
))}
</div>
<Separator className="my-4" />
{/* Total Amount */}
<div className="flex justify-between items-center mb-6">
<span className="text-lg font-semibold">
{order.billing.footer.title}:
</span>
<span className="text-lg font-bold text-green-600">
{order.billing.footer.value}
</span>
</div>
{/* Complete Order Button */}
<Button
onClick={onCompleteOrder}
disabled={!isFormValid || isLoading}
className="w-full rounded-xl bg-[#005bff] hover:bg-[#004dcc] cursor-pointer h-12 text-lg font-bold disabled:opacity-50 disabled:cursor-not-allowed"
size="lg"
>
{isLoading ? `${t.placeOrder}...` : t.placeOrder}
</Button>
</Card>
)
}

View File

@@ -1,49 +0,0 @@
import React from "react";
import { CreditCard } from "lucide-react";
import { Card } from "@/components/ui/card";
import { PaymentType, CartTranslations } from "./types";
interface PaymentTypeSelectorProps {
selectedType: PaymentType;
onSelect: (type: PaymentType) => void;
translations: CartTranslations;
}
export default function PaymentTypeSelector({
selectedType,
onSelect,
translations: t,
}: PaymentTypeSelectorProps) {
const paymentOptions: { type: PaymentType; label: string }[] = [
{ type: "CASH", label: t.cash },
{ type: "CARD", label: t.card },
];
return (
<div className="mb-6">
<h3 className="text-lg font-semibold mb-3">{t.paymentType}</h3>
<div className="flex gap-2">
{paymentOptions.map(({ type, label }) => (
<Card
key={type}
className={`flex-1 cursor-pointer transition-all ${
selectedType === type
? "border-2 border-[#005bff]"
: "border-2 border-gray-200"
}`}
onClick={() => onSelect(type)}
>
<div className="flex flex-col items-center justify-center p-4 gap-2">
<CreditCard
className={`h-8 w-8 ${
selectedType === type ? "text-[#005bff]" : ""
}`}
/>
<span className="text-xs">{label}</span>
</div>
</Card>
))}
</div>
</div>
);
}

View File

@@ -1,119 +0,0 @@
import type { StaticImageData } from "next/image"
export interface CartItem {
id: number
product_id: number
product: {
id: number
name: string
description?: string
images: (StaticImageData | string)[]
image?: StaticImageData | string
stock?: number
price_amount?: string
}
seller: {
id: number
name: string
}
quantity: number
product_quantity?: number // For compatibility with old API
price: number
total: number
price_formatted?: string
sub_total_formatted?: string
discount_formatted?: string
total_formatted?: string
}
export interface Cart {
message: string
data: CartItem[]
errorDetails?: string
total?: number
total_formatted?: string
items?: CartItem[] // Alternative structure
}
export interface Order {
id: number
seller: {
id: number
name: string
}
items: CartItem[]
billing: {
body: Array<{ title: string; value: string }>
footer: { title: string; value: string }
}
}
export interface Region {
id: number
code: string
name: string
}
export interface Address {
id: number
title: string
region_id: number
address: string
phone?: string
is_default?: boolean
}
export interface PickUpPoint {
id: number
name: string
address: string
}
export interface PaymentTypeOption {
id: number
name: string
code: string
}
export interface CartTranslations {
cart: string
ordersIn: string
pricePerUnit: string
additionalPrice: string
discount: string
totalPrice: string
paymentType: string
cash: string
card: string
deliveryType: string
delivery: string
pickup: string
selectRegion: string
selectAddress: string
note: string
placeOrder: string
emptyCart: string
map: string
}
export type PaymentType = "CASH" | "CARD"
export type DeliveryType = "SELECTED_DELIVERY" | "PICK_UP"
// API Response types
export interface ApiResponse<T> {
message: string
data: T
errorDetails?: string
}
export interface CreateOrderPayload {
customer_name?: string
customer_phone?: string
customer_address: string
shipping_method: string
payment_type_id: number
delivery_time?: string
delivery_at?: string
region: string
note?: string
}

View File

@@ -31,6 +31,6 @@ export default async function CategoryPage(props: Props) {
const params = await props.params
const { slug } = params
const CategoryPageClient = (await import("./ui/CategoryClient")).default
const CategoryPageClient = (await import("../../../../features/category/components/CategoryClient")).default
return <CategoryPageClient params={params} />
}

View File

@@ -1,653 +0,0 @@
"use client";
import { useEffect, useState, useMemo, useCallback } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { ChevronLeft, SlidersHorizontal, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Slider } from "@/components/ui/slider";
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetTrigger,
} from "@/components/ui/sheet";
import { ScrollArea } from "@/components/ui/scroll-area";
import InfiniteScroll from "react-infinite-scroll-component";
import ProductCard from "@/components/ProductCard";
import Loader from "@/components/Loader";
import {
useCategories,
useAllCategoryProducts,
useAllCategoryProductsPaginated,
useCategoryProducts,
} from "@/lib/hooks/useCategories";
import { notFound } from "next/navigation";
import type { Category, Product } from "@/lib/types/api";
interface CategoryPageClientProps {
params: { locale: string; slug: string };
}
export default function CategoryPageClient({
params,
}: CategoryPageClientProps) {
const { slug, locale } = params;
const router = useRouter();
const searchParams = useSearchParams();
const [isOpen, setIsOpen] = useState(false);
// Fetch all categories first
const { data: categoriesData, isLoading: categoriesLoading } =
useCategories();
// Find category from slug
const selectedCategory = useMemo(() => {
if (!categoriesData || !slug) return null;
const findBySlug = (categories: Category[]): Category | null => {
for (const category of categories) {
if (category.slug === slug) return category;
if (category.children) {
const found = findBySlug(category.children);
if (found) return found;
}
}
return null;
};
return findBySlug(categoriesData);
}, [categoriesData, slug]);
// Track subcategories
const [hasSubcategories, setHasSubcategories] = useState(false);
const [subcategoriesToShow, setSubcategoriesToShow] = useState<Category[]>(
[]
);
// Pagination state
const [currentPage, setCurrentPage] = useState(1);
const [hasMore, setHasMore] = useState(true);
const [allProducts, setAllProducts] = useState<Product[]>([]);
// Price sorting state
const [priceSort, setPriceSort] = useState<
"none" | "lowToHigh" | "highToLow"
>("none");
// Price filter state
const [priceRange, setPriceRange] = useState<[number, number]>([0, 10000]);
// Selected filters state
const [selectedFilters, setSelectedFilters] = useState<
Record<string, Set<number>>
>({
brand: new Set(),
color: new Set(),
tag: new Set(),
});
// Determine if category is a subcategory
const isSubCategory = useMemo(() => {
if (!categoriesData || !selectedCategory) return false;
const checkIsSubCategory = (
categories: Category[],
targetId: number
): boolean => {
for (const category of categories) {
if (category.children) {
for (const subCategory of category.children) {
if (subCategory.id === targetId) return true;
if (subCategory.children) {
const foundInNested = checkIsSubCategory([subCategory], targetId);
if (foundInNested) return true;
}
}
}
}
return false;
};
return checkIsSubCategory(categoriesData, selectedCategory.id);
}, [categoriesData, selectedCategory]);
// Fetch initial products for subcategories (first page only)
const { data: subcategoryProducts = [], isLoading: subcategoryLoading } =
useAllCategoryProducts(selectedCategory || undefined, {
enabled: !!selectedCategory && isSubCategory && currentPage === 1,
});
// Fetch paginated subcategory products (page 2+)
const {
data: paginatedSubcategoryData,
isLoading: subcategoryPaginatedLoading,
} = useAllCategoryProductsPaginated(selectedCategory || undefined, {
enabled: !!selectedCategory && isSubCategory && currentPage > 1,
page: currentPage,
limit: 6,
});
// Fetch paginated category products (for non-subcategories)
const {
data: paginatedCategoryData,
isLoading: categoryPaginatedLoading,
isFetching: categoryPaginatedFetching,
} = useCategoryProducts(selectedCategory?.id?.toString() || "", {
enabled: !!selectedCategory && !isSubCategory,
page: currentPage,
limit: 6,
});
const t = {
filter: "Filtreler",
from: "Min",
to: "Max",
reset: "Sıfırla",
total: "Toplam",
items: "ürün",
subCategories: "Alt Kategoriler",
composition: "Sıralama",
neverMind: "Varsayılan",
From_cheap_to_expensive: "Ucuzdan Pahalıya",
From_expensive_to_cheap: "Pahalıdan Ucuza",
brands: "Markalar",
noResults: "Ürün bulunamadı",
};
if (!slug) {
notFound();
}
// Helper function to find category by ID
const findCategoryById = (
categories: Category[] | undefined,
id: number
): Category | null => {
if (!categories) return null;
for (const category of categories) {
if (category.id === id) return category;
if (category.children) {
const found = findCategoryById(category.children, id);
if (found) return found;
}
}
return null;
};
// Helper to check if product already exists in list
const isProductInList = (list: Product[], newProduct: Product) => {
return list.some((product) => product.id === newProduct.id);
};
// Setup subcategories when category changes
useEffect(() => {
if (selectedCategory) {
// Reset states
setAllProducts([]);
setHasMore(true);
setCurrentPage(1);
// Set subcategories
if (selectedCategory.children && selectedCategory.children.length > 0) {
setHasSubcategories(true);
setSubcategoriesToShow(selectedCategory.children);
} else {
setHasSubcategories(false);
setSubcategoriesToShow([]);
}
}
}, [selectedCategory?.id]);
// Handle first page products for subcategories
useEffect(() => {
if (
selectedCategory &&
isSubCategory &&
subcategoryProducts.length > 0 &&
currentPage === 1
) {
console.log("Setting subcategory products:", subcategoryProducts.length);
setAllProducts(subcategoryProducts);
setHasMore(true);
}
}, [selectedCategory, subcategoryProducts, currentPage, isSubCategory]);
// Handle paginated category products (non-subcategories)
useEffect(() => {
if (paginatedCategoryData && selectedCategory && !isSubCategory) {
console.log("Paginated category data:", paginatedCategoryData);
if (paginatedCategoryData.data && paginatedCategoryData.data.length > 0) {
setAllProducts((prevProducts) => {
if (currentPage === 1) {
return [...paginatedCategoryData.data];
}
const newProducts = paginatedCategoryData.data.filter(
(newProduct: Product) => !isProductInList(prevProducts, newProduct)
);
return [...prevProducts, ...newProducts];
});
setHasMore(!!paginatedCategoryData.pagination?.next_page_url);
} else if (currentPage === 1) {
setAllProducts([]);
setHasMore(false);
}
}
}, [paginatedCategoryData, currentPage, selectedCategory, isSubCategory]);
// Handle paginated subcategory products
useEffect(() => {
if (
paginatedSubcategoryData &&
selectedCategory &&
isSubCategory &&
currentPage > 1
) {
console.log("Paginated subcategory data:", paginatedSubcategoryData);
if (
paginatedSubcategoryData.data &&
paginatedSubcategoryData.data.length > 0
) {
setAllProducts((prevProducts) => {
const newProducts = paginatedSubcategoryData.data.filter(
(newProduct: Product) => !isProductInList(prevProducts, newProduct)
);
return [...prevProducts, ...newProducts];
});
setHasMore(paginatedSubcategoryData.pagination?.hasMorePages || false);
} else {
setHasMore(false);
}
}
}, [paginatedSubcategoryData, currentPage, selectedCategory, isSubCategory]);
const loadMoreData = useCallback(() => {
if (!hasMore || categoryPaginatedFetching || subcategoryPaginatedLoading)
return;
console.log("Loading more, page:", currentPage + 1);
setCurrentPage((prevPage) => prevPage + 1);
}, [
hasMore,
categoryPaginatedFetching,
subcategoryPaginatedLoading,
currentPage,
]);
const isLoading =
categoriesLoading ||
(subcategoryLoading && currentPage === 1) ||
(categoryPaginatedLoading && currentPage === 1);
const products = useMemo(() => {
let productsList = [...allProducts];
if (priceSort === "lowToHigh") {
return [...productsList].sort(
(a, b) =>
parseFloat(a.price_amount || "0") - parseFloat(b.price_amount || "0")
);
} else if (priceSort === "highToLow") {
return [...productsList].sort(
(a, b) =>
parseFloat(b.price_amount || "0") - parseFloat(a.price_amount || "0")
);
}
return productsList;
}, [priceSort, allProducts]);
const totalItems = useMemo(() => {
if (
paginatedCategoryData?.pagination &&
!isSubCategory &&
selectedCategory
) {
return paginatedCategoryData.pagination.total || products.length || 0;
}
return products.length || 0;
}, [paginatedCategoryData, products, isSubCategory, selectedCategory]);
const handlePriceSortChange = (
sortType: "none" | "lowToHigh" | "highToLow"
) => {
setPriceSort(sortType);
};
const handleSubCategorySelect = (subCategory: Category) => {
setAllProducts([]);
setCurrentPage(1);
setHasMore(true);
setPriceSort("none");
router.push(`/${locale}/category/${subCategory.slug}`, { scroll: false });
};
const handleCategoryClick = (category: Category) => {
setAllProducts([]);
setCurrentPage(1);
setHasMore(true);
router.push(`/${locale}/category/${category.slug}`);
};
const renderBreadcrumbs = () => {
if (!categoriesData || !selectedCategory) return null;
const breadcrumbs: Category[] = [];
let currentCategory = selectedCategory;
let parentId = currentCategory.parent_id;
breadcrumbs.unshift(currentCategory);
while (parentId) {
const parentCategory = findCategoryById(categoriesData, parentId);
if (parentCategory) {
breadcrumbs.unshift(parentCategory);
parentId = parentCategory.parent_id;
} else {
break;
}
}
return (
<div className="flex items-center gap-2 mb-4 text-sm">
{breadcrumbs.map((category, index) => (
<div key={category.id} className="flex items-center gap-2">
<button
onClick={() => handleCategoryClick(category)}
className="hover:text-primary transition-colors"
>
{category.name}
</button>
{index < breadcrumbs.length - 1 && <span>/</span>}
</div>
))}
</div>
);
};
const pageTitle = selectedCategory?.name || "Kategori";
const handleFilterChange = (key: string, value: number) => {
setSelectedFilters((prev) => {
const newFilters = { ...prev };
if (!newFilters[key]) {
newFilters[key] = new Set();
}
if (newFilters[key].has(value)) {
newFilters[key].delete(value);
} else {
newFilters[key].add(value);
}
return newFilters;
});
};
const handlePriceChange = (values: number[]) => {
setPriceRange([values[0], values[1]]);
};
const handlePriceInputChange = (type: "from" | "to", value: string) => {
const numValue = parseInt(value) || 0;
if (type === "from") {
setPriceRange([numValue, priceRange[1]]);
} else {
setPriceRange([priceRange[0], numValue]);
}
};
const resetFilters = () => {
setSelectedFilters({
brand: new Set(),
color: new Set(),
tag: new Set(),
});
setPriceRange([0, 10000]);
setPriceSort("none");
};
const FiltersContent = () => (
<div className="space-y-6">
{hasSubcategories && subcategoriesToShow.length > 0 && (
<div>
<h3 className="text-lg font-semibold mb-3">{t.subCategories}</h3>
<div className="space-y-1">
{subcategoriesToShow.map((subCategory) => (
<button
key={subCategory.id}
onClick={() => handleSubCategorySelect(subCategory)}
className={`w-full text-left py-2 px-2 rounded-lg hover:bg-gray-100 transition-colors ${
slug === subCategory.slug
? "text-primary font-medium bg-gray-50"
: ""
}`}
>
{subCategory.name}
</button>
))}
</div>
</div>
)}
<div>
<h3 className="text-lg font-semibold mb-3">{t.composition}</h3>
<div className="space-y-2">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="radio"
name="sort"
checked={priceSort === "none"}
onChange={() => handlePriceSortChange("none")}
className="w-4 h-4"
/>
<span>{t.neverMind}</span>
</label>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="radio"
name="sort"
checked={priceSort === "lowToHigh"}
onChange={() => handlePriceSortChange("lowToHigh")}
className="w-4 h-4"
/>
<span>{t.From_cheap_to_expensive}</span>
</label>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="radio"
name="sort"
checked={priceSort === "highToLow"}
onChange={() => handlePriceSortChange("highToLow")}
className="w-4 h-4"
/>
<span>{t.From_expensive_to_cheap}</span>
</label>
</div>
</div>
<PriceFilter
title="Fiyat"
priceRange={priceRange}
onPriceChange={handlePriceChange}
onInputChange={handlePriceInputChange}
translations={{ from: t.from, to: t.to }}
/>
<Button
variant="outline"
className="w-full rounded-xl bg-transparent"
onClick={resetFilters}
>
{t.reset}
</Button>
</div>
);
if (isLoading) return <div>Loading...</div>;
if (!selectedCategory && !categoriesLoading) {
return <div className="text-center py-8">Kategori bulunamadı</div>;
}
console.log(
"Current products:",
products.length,
"Has more:",
hasMore,
"Page:",
currentPage
);
return (
<div className="flex flex-col gap-4">
{selectedCategory && renderBreadcrumbs()}
<h2 className="text-3xl font-bold">{pageTitle}</h2>
<p className="text-gray-600">
{t.total}: {totalItems} {t.items}
</p>
<div className="flex gap-4">
{/* Desktop Filters - LEFT SIDE */}
<div className="hidden sm:block w-[280px] flex-shrink-0 border-r pr-4">
<ScrollArea className="h-[calc(100vh-200px)]">
<FiltersContent />
</ScrollArea>
</div>
{/* Content - RIGHT SIDE */}
<div className="flex-1">
{products.length > 0 ? (
<InfiniteScroll
dataLength={products.length}
next={loadMoreData}
hasMore={hasMore}
scrollThreshold={0.8}
style={{ overflow: "visible" }}
loader={
<div className="flex justify-center py-4">
<div>Loading...</div>
</div>
}
>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{products.map((product) => (
<ProductCard
key={product.id}
id={product.id}
name={product.name}
price={
product.price_amount
? parseFloat(product.price_amount)
: null
}
struct_price_text={`${product.price_amount} TMT`}
images={[product.media?.[0]?.images_400x400]}
is_favorite={false}
/>
))}
</div>
</InfiniteScroll>
) : (
<div className="text-center py-8 text-gray-500">{t.noResults}</div>
)}
</div>
</div>
{/* Mobile Filter Sheet */}
<Sheet open={isOpen} onOpenChange={setIsOpen}>
<SheetTrigger asChild>
<Button
className="sm:hidden fixed bottom-20 right-4 rounded-xl font-bold gap-2 z-10 shadow-lg"
size="lg"
>
{t.filter}
<SlidersHorizontal className="h-5 w-5" />
</Button>
</SheetTrigger>
<SheetContent side="left" className="w-[290px] p-0">
<SheetHeader className="p-4 border-b">
<SheetTitle>{t.filter}</SheetTitle>
<button
onClick={() => setIsOpen(false)}
className="absolute top-4 right-4 rounded-md ring-offset-background transition-opacity hover:opacity-100"
>
<X className="h-4 w-4" />
<span className="sr-only">Kapat</span>
</button>
</SheetHeader>
<ScrollArea className="h-[calc(100vh-80px)] p-4">
<FiltersContent />
</ScrollArea>
</SheetContent>
</Sheet>
</div>
);
}
function PriceFilter({
title,
priceRange,
onPriceChange,
onInputChange,
translations,
}: {
title: string;
priceRange: [number, number];
onPriceChange: (values: number[]) => void;
onInputChange: (type: "from" | "to", value: string) => void;
translations: { from: string; to: string };
}) {
return (
<div>
<h3 className="text-lg font-semibold mb-3">{title}</h3>
<div className="space-y-4">
<div className="flex gap-2">
<div className="flex-1">
<Label htmlFor="price-from" className="text-xs mb-1">
{translations.from}
</Label>
<Input
id="price-from"
type="number"
value={priceRange[0]}
onChange={(e) => onInputChange("from", e.target.value)}
className="rounded-lg"
/>
</div>
<div className="flex-1">
<Label htmlFor="price-to" className="text-xs mb-1">
{translations.to}
</Label>
<Input
id="price-to"
type="number"
value={priceRange[1]}
onChange={(e) => onInputChange("to", e.target.value)}
className="rounded-lg"
/>
</div>
</div>
<Slider
min={0}
max={99999}
step={100}
value={priceRange}
onValueChange={onPriceChange}
className="mt-2"
/>
</div>
</div>
);
}

View File

@@ -1,9 +0,0 @@
"use client"
export default function CategoryPageContent({ slug }: { slug: string }) {
return (
<div className="container mx-auto px-4 py-8">
<h1 className="text-3xl font-bold mb-6">Category: {slug}</h1>
{/* Category content will go here */}
</div>
)
}

View File

@@ -179,7 +179,7 @@ function ProductCard({
onMouseEnter={() => onHover(productId)}
onMouseLeave={() => onHover(null)}
>
<Link href={`/product/${product.slug || productId}`} className="block">
<Link href={`/product/${productId|| product.slug}`} className="block">
<div className="relative aspect-square bg-gray-50">
{/* Favorite Button */}
<button

View File

@@ -43,7 +43,7 @@ export default async function RootLayout({ children, params }: Props) {
let messages
try {
messages = (await import(`../../messages/${locale}.json`)).default
messages = (await import(`../../i18n/messages/${locale}.json`)).default
} catch {
messages = {}
}

View File

@@ -1,123 +0,0 @@
"use client"
import { LogOut } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { useUserProfile } from "@/lib/hooks"
import { Skeleton } from "@/components/ui/skeleton"
interface ProfilePageProps {
params: Promise<{ locale: string }>
}
export default function ClientProfilePage(props: ProfilePageProps) {
const { data: user, isLoading, error } = useUserProfile()
const translations = {
profile: "Профиль",
firstName: "Имя",
lastName: "Фамилия",
phone: "Номер телефона",
email: "Email",
logout: "Выйти",
loading: "Загрузка...",
}
const handleLogout = () => {
// Clear auth token
window.location.href = "/"
}
if (isLoading) {
return (
<div className="min-h-screen bg-gray-50 p-4 pt-20">
<div className="container mx-auto max-w-2xl">
<Skeleton className="h-10 w-48 mb-6" />
<Card className="shadow-lg mb-4">
<CardHeader>
<Skeleton className="h-6 w-32 mb-2" />
<Skeleton className="h-4 w-48" />
</CardHeader>
<CardContent className="space-y-4">
{[1, 2, 3, 4].map((i) => (
<div key={i} className="space-y-2">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-10 w-full" />
</div>
))}
</CardContent>
</Card>
</div>
</div>
)
}
if (error) {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
<Card className="w-full max-w-md">
<CardContent className="pt-6 text-center">
<p className="text-red-600 mb-4">Failed to load profile</p>
<Button onClick={() => window.location.reload()}>Try Again</Button>
</CardContent>
</Card>
</div>
)
}
return (
<div className="min-h-screen bg-gray-50 p-4 pt-20">
<div className="container mx-auto max-w-2xl">
<h1 className="text-3xl font-bold mb-6">{translations.profile}</h1>
<Card className="shadow-lg mb-4">
<CardHeader>
<CardTitle>Личная информация</CardTitle>
<CardDescription>Ваши данные профиля</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{user && (
<>
{/* First Name */}
<div className="space-y-2">
<Label htmlFor="firstName">{translations.firstName}</Label>
<Input id="firstName" value={user.first_name || ""} disabled className="bg-gray-50" />
</div>
{/* Last Name */}
<div className="space-y-2">
<Label htmlFor="lastName">{translations.lastName}</Label>
<Input id="lastName" value={user.last_name || ""} disabled className="bg-gray-50" />
</div>
{/* Phone */}
<div className="space-y-2">
<Label htmlFor="phone">{translations.phone}</Label>
<Input id="phone" value={user.phone || ""} disabled className="bg-gray-50" />
</div>
{/* Email */}
<div className="space-y-2">
<Label htmlFor="email">{translations.email}</Label>
<Input id="email" value={user.email || ""} disabled className="bg-gray-50" />
</div>
</>
)}
</CardContent>
</Card>
{/* Logout Button */}
<Button
onClick={handleLogout}
variant="destructive"
size="lg"
className="w-full max-w-md flex items-center justify-center gap-2"
>
<LogOut className="h-5 w-5" />
{translations.logout}
</Button>
</div>
</div>
)
}

View File

@@ -1,5 +1,5 @@
import type { Metadata } from "next"
import ClientProfilePage from "./client-page"
import ClientProfilePage from "../../../features/profile/components/client-page"
export const metadata: Metadata = {
title: "My Profile | E-Commerce",

View File

@@ -1,66 +0,0 @@
"use client"
import { useState, useEffect } from "react"
interface User {
first_name: string
last_name: string
phone: string
email?: string
}
interface ProfileContentProps {
locale: string
}
export default function ProfilePageContent({ locale }: ProfileContentProps) {
const [user, setUser] = useState<User | null>(null)
const [loading, setLoading] = useState(true)
const t = {
profile: "Профиль",
firstName: "Имя",
lastName: "Фамилия",
phone: "Номер телефона",
email: "Email",
logout: "Выйти",
loading: "Загрузка...",
}
useEffect(() => {
const fetchUserData = () => {
setTimeout(() => {
setUser({
first_name: "Иван",
last_name: "Иванов",
phone: "+99361234567",
email: "ivan@example.com",
})
setLoading(false)
}, 500)
}
fetchUserData()
}, [])
const handleLogout = () => {
window.location.href = "/"
}
if (loading) {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
<p className="text-lg text-gray-600">{t.loading}</p>
</div>
)
}
return (
<div className="min-h-screen bg-gray-50 p-4 pt-20">
<div className="container mx-auto max-w-2xl">
<h1 className="text-3xl font-bold mb-6">{t.profile}</h1>
{/* Profile content */}
</div>
</div>
)
}

View File

@@ -1,46 +0,0 @@
"use client"
import { useState } from "react"
// ... existing types and code ...
interface OrdersContentProps {
locale: string
}
export default function OrdersPageContent({ locale }: OrdersContentProps) {
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
const [selectedOrderId, setSelectedOrderId] = useState<number | null>(null)
const [activeTab, setActiveTab] = useState<"active" | "completed">("active")
const t = {
orders: "Заказы",
active: "Активные",
completed: "Завершенные",
cancelOrder: "Отменить заказ",
areYouSure: "Вы уверены?",
yes: "Да",
no: "Нет",
orderNumber: "№",
}
const handleCancelOrder = (orderId: number) => {
setSelectedOrderId(orderId)
setIsDeleteModalOpen(true)
}
const confirmCancelOrder = async () => {
if (selectedOrderId) {
console.log("Canceling order:", selectedOrderId)
setIsDeleteModalOpen(false)
setSelectedOrderId(null)
}
}
return (
<div className="container mx-auto px-4 py-8 min-h-screen">
<h1 className="text-3xl font-bold mb-6">{t.orders}</h1>
{/* Orders content */}
</div>
)
}

View File

@@ -1,334 +0,0 @@
"use client"
import { useState } from "react"
import Image from "next/image"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Skeleton } from "@/components/ui/skeleton"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { useToast } from "@/hooks/use-toast"
import { useOrders, useCancelOrder } from "@/lib/hooks"
import type { Order } from "@/lib/types/api"
interface OrdersPageProps {
locale?: string
}
export default function OrdersPageClient({ locale }: OrdersPageProps) {
const [isCancelDialogOpen, setIsCancelDialogOpen] = useState(false)
const [orderToCancel, setOrderToCancel] = useState<Order | null>(null)
const { toast } = useToast()
const { data: orders, isLoading, isError, error } = useOrders()
const { mutate: cancelOrder, isPending: isCancellingOrder } = useCancelOrder()
const t = {
orders: "Заказы",
myOrders: "Мои заказы",
active: "Активные",
completed: "Завершенные",
activeOrders: "Активные заказы",
completedOrders: "Завершенные заказы",
cancelOrder: "Отменить заказ",
keepOrder: "Оставить заказ",
areYouSure: "Вы уверены?",
cancelConfirmation: "Вы уверены, что хотите отменить этот заказ? Это действие нельзя отменить.",
cancelling: "Отмена...",
orderNumber: "Заказ №",
ordered: "Заказано",
completed: "Завершено",
estimatedDelivery: "Ожид. доставка",
quantity: "Кол-во",
total: "Итого",
noOrders: "У вас пока нет заказов",
noActiveOrders: "У вас нет активных заказов",
noCompletedOrders: "У вас нет завершенных заказов",
loadError: "Не удалось загрузить заказы. Пожалуйста, попробуйте позже.",
orderCancelled: "Заказ отменен",
orderCancelledDescription: "Ваш заказ был успешно отменен",
error: "Ошибка",
cannotCancelShipped: "Нельзя отменить заказ, который уже отправлен или доставлен",
}
const handleCancelOrder = (order: Order) => {
// Check if order can be cancelled
if (order.status === "shipped" || order.status === "delivered") {
toast({
title: t.error,
description: t.cannotCancelShipped,
variant: "destructive",
})
return
}
setOrderToCancel(order)
setIsCancelDialogOpen(true)
}
const confirmCancelOrder = () => {
if (!orderToCancel) return
cancelOrder(orderToCancel.id, {
onSuccess: () => {
toast({
title: t.orderCancelled,
description: t.orderCancelledDescription,
})
setIsCancelDialogOpen(false)
setOrderToCancel(null)
},
onError: (error: any) => {
toast({
title: t.error,
description: error.message || "Не удалось отменить заказ",
variant: "destructive",
})
},
})
}
const getStatusBadge = (status: Order["status"]) => {
const statusMap: Record<string, { label: string; variant: string; className?: string }> = {
pending: { label: "Ожидание", variant: "outline" },
processing: { label: "Обработка", variant: "secondary" },
shipped: { label: "Отправлен", variant: "default" },
delivered: { label: "Доставлен", variant: "default", className: "bg-green-600" },
cancelled: { label: "Отменен", variant: "destructive" },
}
const statusInfo = statusMap[status] || { label: status, variant: "default" }
return (
<Badge variant={statusInfo.variant as any} className={statusInfo.className}>
{statusInfo.label}
</Badge>
)
}
const activeOrders = orders?.filter((o) => ["pending", "processing", "shipped"].includes(o.status)) || []
const completedOrders = orders?.filter((o) => ["delivered", "cancelled"].includes(o.status)) || []
if (isLoading) {
return (
<div className="container mx-auto p-4 min-h-screen">
<h1 className="text-3xl font-bold mb-6">{t.myOrders}</h1>
<div className="space-y-4">
<Skeleton className="h-10 w-40" />
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{Array.from({ length: 6 }).map((_, i) => (
<Skeleton key={i} className="h-64 rounded-lg" />
))}
</div>
</div>
</div>
)
}
if (isError) {
return (
<div className="container mx-auto p-4 min-h-screen">
<h1 className="text-3xl font-bold mb-6">{t.myOrders}</h1>
<div className="bg-red-50 p-4 rounded-lg border border-red-200">
<p className="text-red-600">{t.loadError}</p>
{error && <p className="text-sm text-red-500 mt-2">{error.message}</p>}
</div>
</div>
)
}
if (!orders || orders.length === 0) {
return (
<div className="container mx-auto p-4 min-h-screen">
<h1 className="text-3xl font-bold mb-6">{t.myOrders}</h1>
<div className="flex items-center justify-center min-h-[60vh]">
<p className="text-2xl text-gray-400">{t.noOrders}</p>
</div>
</div>
)
}
return (
<div className="container mx-auto p-4 min-h-screen">
<h1 className="text-3xl font-bold mb-6">{t.myOrders}</h1>
<Tabs defaultValue="active" className="w-full">
<TabsList className="mb-6">
<TabsTrigger value="active">
{t.activeOrders} ({activeOrders.length})
</TabsTrigger>
<TabsTrigger value="completed">
{t.completedOrders} ({completedOrders.length})
</TabsTrigger>
</TabsList>
<TabsContent value="active">
{activeOrders.length === 0 ? (
<div className="flex items-center justify-center min-h-[40vh]">
<p className="text-xl text-gray-400">{t.noActiveOrders}</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{activeOrders.map((order) => (
<OrderCard
key={order.id}
order={order}
onCancel={handleCancelOrder}
isCancelling={isCancellingOrder}
getStatusBadge={getStatusBadge}
translations={t}
showCancelButton
/>
))}
</div>
)}
</TabsContent>
<TabsContent value="completed">
{completedOrders.length === 0 ? (
<div className="flex items-center justify-center min-h-[40vh]">
<p className="text-xl text-gray-400">{t.noCompletedOrders}</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{completedOrders.map((order) => (
<OrderCard
key={order.id}
order={order}
onCancel={handleCancelOrder}
isCancelling={isCancellingOrder}
getStatusBadge={getStatusBadge}
translations={t}
showCancelButton={false}
/>
))}
</div>
)}
</TabsContent>
</Tabs>
<Dialog open={isCancelDialogOpen} onOpenChange={setIsCancelDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>
{t.cancelOrder} #{orderToCancel?.id}
</DialogTitle>
<DialogDescription>{t.cancelConfirmation}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
variant="outline"
onClick={() => setIsCancelDialogOpen(false)}
disabled={isCancellingOrder}
>
{t.keepOrder}
</Button>
<Button variant="destructive" onClick={confirmCancelOrder} disabled={isCancellingOrder}>
{isCancellingOrder ? t.cancelling : t.cancelOrder}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}
interface OrderCardProps {
order: Order
onCancel: (order: Order) => void
isCancelling: boolean
getStatusBadge: (status: Order["status"]) => React.ReactNode
translations: any
showCancelButton: boolean
}
function OrderCard({
order,
onCancel,
isCancelling,
getStatusBadge,
translations: t,
showCancelButton,
}: OrderCardProps) {
const canCancel =
showCancelButton && order.status !== "shipped" && order.status !== "delivered" && order.status !== "cancelled"
return (
<Card className="p-4 flex flex-col justify-between">
<div>
<div className="flex justify-between items-center mb-3">
<h3 className="text-lg font-semibold">
{t.orderNumber}{order.id}
</h3>
{getStatusBadge(order.status)}
</div>
<div className="mb-3 space-y-1">
<p className="text-sm text-gray-600">
{t.ordered}: {new Date(order.created_at).toLocaleDateString()}
</p>
{order.estimated_delivery && (
<p className="text-sm text-gray-600">
{t.estimatedDelivery}: {order.estimated_delivery}
</p>
)}
{!showCancelButton && order.updated_at && (
<p className="text-sm text-gray-600">
{t.completed}: {new Date(order.updated_at).toLocaleDateString()}
</p>
)}
</div>
<div className="space-y-2 mb-3 max-h-48 overflow-y-auto">
{order.items?.map((item) => (
<div key={item.id} className="flex items-start gap-3">
{item.product?.image && (
<Image
src={item.product.image || "/placeholder.svg"}
alt={item.product.name}
width={50}
height={50}
className="rounded object-cover"
/>
)}
<div className="flex-1 min-w-0">
<p className="text-sm font-medium line-clamp-2">{item.product?.name}</p>
<p className="text-xs text-gray-500">
{t.quantity}: {item.quantity}
</p>
</div>
</div>
))}
</div>
<div className="border-t pt-3">
<div className="flex justify-between font-semibold">
<span>{t.total}</span>
<span>{order.total_formatted || `$${order.total}`}</span>
</div>
</div>
</div>
{canCancel && (
<div className="mt-4">
<Button
variant="destructive"
onClick={() => onCancel(order)}
disabled={isCancelling}
className="w-full"
>
{t.cancelOrder}
</Button>
</div>
)}
</Card>
)
}

View File

@@ -1,5 +1,5 @@
import type { Metadata } from "next"
import OrdersPageClient from "./orders-page-client"
import OrdersPageClient from "../../../features/orders/components/orders-page-client"
export const metadata: Metadata = {
title: "My Orders | E-Commerce",

View File

@@ -1,35 +1,35 @@
import type { Metadata } from "next"
import HomePage from "@/components/home/HomePage"
import type { Metadata } from "next";
import HomePage from "@/features/home/components/HomePage";
export const revalidate = 300
export const revalidate = 300;
export async function generateMetadata({
params
}: {
params: Promise<{ locale: string }>
export async function generateMetadata({
params,
}: {
params: Promise<{ locale: string }>;
}): Promise<Metadata> {
const { locale } = await params
const { locale } = await params;
const meta = {
ru: {
title: "Интернет магазин - Лучшие товары по низким ценам",
description: "Качественные товары с быстрой доставкой по всей стране"
description: "Качественные товары с быстрой доставкой по всей стране",
},
tm: {
title: "Satym dükanı - Iň gowy harytlar aşak bahada",
description: "Suw harytly towarnama. Elektrika, eşik, ev we bag"
}
}
description: "Suw harytly towarnama. Elektrika, eşik, ev we bag",
},
};
const { title, description } = meta[locale as keyof typeof meta] || meta.ru
const { title, description } = meta[locale as keyof typeof meta] || meta.ru;
return {
title,
description,
openGraph: { type: "website", locale, title, description }
}
openGraph: { type: "website", locale, title, description },
};
}
export default function Page() {
return <HomePage />
}
return <HomePage />;
}

View File

@@ -1,401 +0,0 @@
"use client"
import { useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { Minus, Plus, Heart, ShoppingCart, Store } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Separator } from "@/components/ui/separator"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { Skeleton } from "@/components/ui/skeleton"
import { useProductsBySlug } from "@/lib/hooks/useProducts"
import { useAddToCart, useUpdateCartItemQuantity, useCart } from "@/lib/hooks/useCart"
import { toast } from "sonner"
interface ProductDetailProps {
slug: string
}
const ProductPageContent = ({ slug }: ProductDetailProps) => {
const [selectedImage, setSelectedImage] = useState(0)
const [quantity, setQuantity] = useState(1)
const [isFavorite, setIsFavorite] = useState(false)
// Get product data
const { data: product, isLoading: productLoading, error } = useProductsBySlug(slug)
// Get cart data to check if product is already in cart
const { data: cartData } = useCart()
// Cart mutations
const addToCartMutation = useAddToCart()
const updateCartMutation = useUpdateCartItemQuantity()
const t = {
addToCart: "Sebede goş",
goToCart: "Sebede git",
price: "Bahasy:",
aboutProduct: "Haryt barada",
brand: "Marka",
stock: "Mukdary",
description: "Düşündiriş",
store: "Dükan",
writeToStore: "Dükana ýaz",
color: "Reňk:",
category: "Kategoriýa:",
barcode: "Barkod:",
addedToCart: "Sebede goşuldy",
updatedCart: "Sebe täzelendi",
error: "Ýalňyşlyk ýüze çykdy",
}
// Check if product is in cart
const cartItem = cartData?.data?.find((item: any) => item.product?.id === product?.id)
const isInCart = !!cartItem
const handleAddToCart = async () => {
if (!product?.id) return
try {
await addToCartMutation.mutateAsync({
productId: product.id,
quantity: quantity,
})
toast.success(t.addedToCart, {
description: `${product.name} sebede goşuldy`,
})
} catch (error) {
console.error("Add to cart error:", error)
toast.error(t.error, {
description: "Haryt sebede goşup bolmady",
})
}
}
const handleQuantityChange = async (newQuantity: number) => {
if (newQuantity < 1 || !product?.id) return
if (newQuantity > product.stock) return
setQuantity(newQuantity)
// If product is already in cart, update it
if (isInCart) {
try {
await updateCartMutation.mutateAsync({
productId: product.id,
quantity: newQuantity,
})
toast.success(t.updatedCart, {
description: `Mukdar: ${newQuantity}`,
})
} catch (error) {
console.error("Update cart error:", error)
toast.error(t.error, {
description: "Mukdar täzelenip bolmady",
})
}
}
}
const handleToggleFavorite = () => {
setIsFavorite(!isFavorite)
// TODO: Implement favorites API
}
// Loading state
if (productLoading) {
return (
<div className="container mx-auto px-4 py-8">
<div className="flex flex-col lg:flex-row gap-8">
<div className="flex-1 max-w-2xl">
<Skeleton className="aspect-square w-full rounded-2xl" />
<div className="mt-4 flex gap-2">
{[1, 2, 3].map((i) => (
<Skeleton key={i} className="w-16 h-16 rounded" />
))}
</div>
</div>
<div className="flex-1 space-y-6">
<Skeleton className="h-10 w-64" />
<Skeleton className="h-20 w-full" />
</div>
</div>
</div>
)
}
// Error state
if (error || !product) {
return (
<div className="container mx-auto px-4 py-8 text-center">
<h2 className="text-2xl font-bold text-red-600">Haryt tapylmady</h2>
<p className="text-gray-500 mt-2">Bu haryt ýok ýa-da aýryldy</p>
</div>
)
}
// Extract image URLs from media array
const imageUrls = product.media?.map(m => m.images_800x800 || m.images_720x720 || m.thumbnail) || []
const isLoading = addToCartMutation.isPending || updateCartMutation.isPending
return (
<div className="container mx-auto px-4 py-8">
<div className="flex flex-col lg:flex-row gap-8">
{/* Product Images */}
<div className="flex-1 max-w-2xl">
<div className="relative">
<div className="relative aspect-square w-full rounded-2xl overflow-hidden bg-gray-50">
{imageUrls.length > 0 ? (
<Image
src={imageUrls[selectedImage]}
alt={product.name}
fill
className="object-contain"
priority
/>
) : (
<div className="flex items-center justify-center h-full text-gray-400">
Surat ýok
</div>
)}
</div>
{/* Thumbnail Images */}
{imageUrls.length > 1 && (
<div className="mt-4 flex gap-2 overflow-x-auto pb-2">
{imageUrls.map((image, index) => (
<button
key={index}
onClick={() => setSelectedImage(index)}
className={`relative w-16 h-16 flex-shrink-0 rounded overflow-hidden border-2 transition-all ${
selectedImage === index
? "border-primary ring-2 ring-primary/20"
: "border-gray-200 hover:border-gray-300"
}`}
>
<Image
src={image}
alt={`${product.name} ${index + 1}`}
fill
className="object-cover"
/>
</button>
))}
</div>
)}
</div>
</div>
{/* Product Info */}
<div className="flex-1 space-y-6">
<div>
<h1 className="text-3xl font-bold mb-2">{product.name}</h1>
{product.categories && product.categories.length > 0 && (
<div className="flex gap-2 flex-wrap mt-2">
{product.categories.map((cat, idx) => (
<span
key={idx}
className="text-sm px-3 py-1 bg-gray-100 rounded-full text-gray-600"
>
{cat.name}
</span>
))}
</div>
)}
</div>
{/* Product Info Table */}
<Card className="p-4 rounded-xl border-gray-200">
<h3 className="text-xl font-semibold mb-4">{t.aboutProduct}</h3>
<div className="space-y-3">
{product.brand?.name && (
<>
<div className="flex justify-between items-center py-2">
<span className="text-gray-500">{t.brand}</span>
<span className="font-medium">{product.brand.name}</span>
</div>
<Separator />
</>
)}
{product.stock !== undefined && (
<>
<div className="flex justify-between items-center py-2">
<span className="text-gray-500">{t.stock}</span>
<span className={`font-medium ${product.stock === 0 ? 'text-red-500' : 'text-green-600'}`}>
{product.stock === 0 ? 'Ýok' : product.stock}
</span>
</div>
<Separator />
</>
)}
{product.barcode && (
<>
<div className="flex justify-between items-center py-2">
<span className="text-gray-500">{t.barcode}</span>
<span className="font-mono text-sm">{product.barcode}</span>
</div>
<Separator />
</>
)}
{product.colour && (
<>
<div className="flex justify-between items-center py-2">
<span className="text-gray-500">{t.color}</span>
<span className="font-medium">{product.colour}</span>
</div>
<Separator />
</>
)}
{product.properties && product.properties.length > 0 && (
<>
{product.properties.map((prop, idx) => (
prop.value && (
<div key={idx}>
<div className="flex justify-between items-center py-2">
<span className="text-gray-500">{prop.name}</span>
<span className="font-medium">{prop.value}</span>
</div>
{idx < product.properties.length - 1 && <Separator />}
</div>
)
))}
</>
)}
</div>
</Card>
{/* Description */}
{product.description && (
<Card className="p-4 rounded-xl border-gray-200">
<h3 className="text-xl font-semibold mb-3">{t.description}</h3>
<div
className="text-gray-700 leading-relaxed prose prose-sm max-w-none"
dangerouslySetInnerHTML={{ __html: product.description }}
/>
</Card>
)}
</div>
{/* Price & Actions Sidebar */}
<div className="lg:w-[380px] space-y-4">
<Card className="p-6 rounded-xl shadow-lg sticky top-4">
<div className="flex justify-between items-start mb-6">
<span className="text-lg text-gray-500">{t.price}</span>
<div className="flex flex-col items-end">
<span className="text-3xl font-bold text-primary">
{product.price_amount} TMT
</span>
{product.old_price_amount && parseFloat(product.old_price_amount) > 0 && (
<span className="text-lg text-gray-400 line-through">
{product.old_price_amount} TMT
</span>
)}
</div>
</div>
<div className="space-y-3">
{isInCart ? (
<>
<Link href="/cart">
<Button
size="lg"
className="w-full rounded-xl text-lg font-bold bg-green-600 hover:bg-green-700"
>
<ShoppingCart className="mr-2 h-5 w-5" />
{t.goToCart}
</Button>
</Link>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="icon"
onClick={() => handleQuantityChange(quantity - 1)}
disabled={quantity === 1 || isLoading}
className="rounded-xl h-12 w-12"
>
<Minus className="h-5 w-5" />
</Button>
<div className="flex-1 text-center font-semibold text-xl border rounded-xl h-12 flex items-center justify-center">
{quantity}
</div>
<Button
variant="outline"
size="icon"
onClick={() => handleQuantityChange(quantity + 1)}
disabled={isLoading || quantity >= product.stock}
className="rounded-xl h-12 w-12"
>
<Plus className="h-5 w-5" />
</Button>
</div>
</>
) : (
<Button
size="lg"
onClick={handleAddToCart}
disabled={isLoading || product.stock === 0}
className="w-full rounded-xl text-lg font-bold"
>
<ShoppingCart className="mr-2 h-5 w-5" />
{isLoading ? "Goşulýar..." : product.stock === 0 ? "Haryt ýok" : t.addToCart}
</Button>
)}
<Button
variant="outline"
size="lg"
onClick={handleToggleFavorite}
className={`w-full rounded-xl transition-all ${
isFavorite
? "bg-red-50 border-red-300 hover:bg-red-100"
: "hover:bg-gray-50"
}`}
>
<Heart
className={`h-6 w-6 transition-all ${
isFavorite ? "fill-red-500 text-red-500" : "text-gray-600"
}`}
/>
</Button>
</div>
</Card>
{/* Store/Channel Card */}
{product.channel && product.channel.length > 0 && (
<Card className="p-6 rounded-xl">
<div className="flex items-center gap-4 mb-4">
<Avatar className="w-14 h-14 bg-primary/10">
<AvatarFallback className="bg-transparent">
<Store className="h-6 w-6 text-primary" />
</AvatarFallback>
</Avatar>
<div>
<p className="text-sm text-gray-500">{t.store}</p>
<h4 className="text-lg font-bold">{product.channel[0].name}</h4>
</div>
</div>
<Button
variant="outline"
size="lg"
className="w-full rounded-xl"
>
{t.writeToStore}
</Button>
</Card>
)}
</div>
</div>
</div>
)
}
export default ProductPageContent

View File

@@ -1,6 +1,6 @@
import type { Metadata } from "next"
import { notFound } from "next/navigation"
import ProductPageContent from "./ProductPageContent"
import ProductPageContent from "../../../../features/products/components/ProductPageContent"
type Props = {
params: Promise<{ locale: string; slug: string }>

View File

@@ -1,9 +0,0 @@
"use client"
export default function ProductPageContent({ slug }: { slug: string }) {
return (
<div className="container mx-auto px-4 py-8">
<h1 className="text-3xl font-bold">Product: {slug}</h1>
{/* Product content will go here */}
</div>
)
}