api ulandi
This commit is contained in:
@@ -1,8 +1,13 @@
|
||||
'use client';
|
||||
|
||||
import { cart_api } from '@/features/cart/lib/api';
|
||||
import { BASE_URL } from '@/shared/config/api/URLs';
|
||||
import { useRouter } from '@/shared/config/i18n/navigation';
|
||||
import { useCartId } from '@/shared/hooks/cartId';
|
||||
import formatPrice from '@/shared/lib/formatPrice';
|
||||
import { Button } from '@/shared/ui/button';
|
||||
import { Input } from '@/shared/ui/input';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { AxiosError } from 'axios';
|
||||
import {
|
||||
ArrowLeft,
|
||||
CreditCard,
|
||||
@@ -12,305 +17,258 @@ import {
|
||||
Trash,
|
||||
Truck,
|
||||
} from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import Image from 'next/image';
|
||||
import { useState } from 'react';
|
||||
|
||||
interface CartItem {
|
||||
id: number;
|
||||
name: string;
|
||||
price: number;
|
||||
oldPrice: number;
|
||||
image: string;
|
||||
quantity: number | string;
|
||||
inStock: boolean;
|
||||
}
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
const CartPage = () => {
|
||||
const { cart_id } = useCartId();
|
||||
const queryClient = useQueryClient();
|
||||
const router = useRouter();
|
||||
const [cartItems, setCartItems] = useState<CartItem[]>([
|
||||
{
|
||||
id: 5,
|
||||
name: 'Coca-Cola 1.5L',
|
||||
price: 12000,
|
||||
oldPrice: 14000,
|
||||
image: '/classic-coca-cola.png',
|
||||
quantity: 2,
|
||||
inStock: true,
|
||||
},
|
||||
{
|
||||
id: 6,
|
||||
name: 'Pepsi 2L',
|
||||
price: 11000,
|
||||
oldPrice: 13000,
|
||||
image: '/pepsi-bottle.jpg',
|
||||
quantity: 1,
|
||||
inStock: true,
|
||||
},
|
||||
{
|
||||
id: 8,
|
||||
name: 'Sprite 1.5L',
|
||||
price: 10000,
|
||||
oldPrice: 12000,
|
||||
image: '/clear-soda-bottle.png',
|
||||
quantity: 3,
|
||||
inStock: true,
|
||||
},
|
||||
]);
|
||||
const t = useTranslations();
|
||||
|
||||
const subtotal = cartItems.reduce(
|
||||
(sum, item) => sum + item.price * Number(item.quantity),
|
||||
0,
|
||||
);
|
||||
const discount = cartItems.reduce((sum, item) => {
|
||||
if (item.oldPrice) {
|
||||
return sum + (item.oldPrice - item.price) * Number(item.quantity);
|
||||
}
|
||||
return sum;
|
||||
}, 0);
|
||||
const deliveryFee = subtotal > 50000 ? 0 : 15000;
|
||||
const total = subtotal - discount + deliveryFee;
|
||||
const { data: cartItems, isLoading } = useQuery({
|
||||
queryKey: ['cart_items', cart_id],
|
||||
queryFn: () => cart_api.get_cart_items(cart_id!),
|
||||
enabled: !!cart_id,
|
||||
select: (data) => data.data.cart_item,
|
||||
});
|
||||
|
||||
const handleQuantityChange = (id: number, type: 'increase' | 'decrease') => {
|
||||
setCartItems((prev) =>
|
||||
prev.map((item) => {
|
||||
if (item.id === id) {
|
||||
if (type === 'increase')
|
||||
return { ...item, quantity: Number(item.quantity) + 1 };
|
||||
if (type === 'decrease' && Number(item.quantity) > 1)
|
||||
return { ...item, quantity: Number(item.quantity) - 1 };
|
||||
}
|
||||
return item;
|
||||
}),
|
||||
const [quantities, setQuantities] = useState<Record<string, string>>({});
|
||||
const debounceRef = useRef<Record<string, NodeJS.Timeout | null>>({});
|
||||
|
||||
useEffect(() => {
|
||||
if (!cartItems) return;
|
||||
const initialQuantities: Record<string, string> = {};
|
||||
cartItems.forEach((item) => {
|
||||
initialQuantities[item.id] = String(item.quantity);
|
||||
debounceRef.current[item.id] = null;
|
||||
});
|
||||
setQuantities(initialQuantities);
|
||||
}, [cartItems]);
|
||||
|
||||
const { mutate: updateCartItem } = useMutation({
|
||||
mutationFn: ({
|
||||
body,
|
||||
cart_item_id,
|
||||
}: {
|
||||
body: { quantity: number };
|
||||
cart_item_id: string;
|
||||
}) => cart_api.update_cart_item({ body, cart_item_id }),
|
||||
onSuccess: () =>
|
||||
queryClient.invalidateQueries({ queryKey: ['cart_items', cart_id] }),
|
||||
onError: (err: AxiosError) =>
|
||||
toast.error(err.message, { richColors: true, position: 'top-center' }),
|
||||
});
|
||||
|
||||
const { mutate: deleteCartItem } = useMutation({
|
||||
mutationFn: ({ cart_item_id }: { cart_item_id: string }) =>
|
||||
cart_api.delete_cart_item(cart_item_id),
|
||||
onSuccess: () =>
|
||||
queryClient.invalidateQueries({ queryKey: ['cart_items', cart_id] }),
|
||||
onError: (err: AxiosError) =>
|
||||
toast.error(err.message, { richColors: true, position: 'top-center' }),
|
||||
});
|
||||
|
||||
const handleCheckout = () => router.push('/cart/order');
|
||||
|
||||
if (isLoading)
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
Loading...
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Remove item from cart
|
||||
const handleRemoveItem = (id: number) => {
|
||||
setCartItems((prev) => prev.filter((item) => item.id !== id));
|
||||
};
|
||||
|
||||
const handleCheckout = () => {
|
||||
router.push('/cart/order');
|
||||
};
|
||||
|
||||
if (cartItems.length === 0) {
|
||||
if (!cartItems || cartItems.length === 0)
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<ShoppingBag className="w-24 h-24 text-gray-300 mx-auto mb-4" />
|
||||
<h2 className="text-2xl font-bold text-gray-800 mb-2">
|
||||
{"Savatingiz bo'sh"}
|
||||
{t("Savatingiz bo'sh")}
|
||||
</h2>
|
||||
<p className="text-gray-600 mb-6">
|
||||
{"Mahsulotlar qo'shish uchun katalogga o'ting"}
|
||||
{t("Mahsulotlar qo'shish uchun katalogga o'ting")}
|
||||
</p>
|
||||
<button
|
||||
onClick={() => router.push('/')}
|
||||
className="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition flex items-center gap-2 mx-auto"
|
||||
>
|
||||
<ArrowLeft className="w-5 h-5" /> Xarid qilishni boshlash
|
||||
<ArrowLeft className="w-5 h-5" /> {t('Xarid qilishni boshlash')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const subtotal = cartItems.reduce(
|
||||
(sum, item) => sum + item.product_price * Number(item.quantity),
|
||||
0,
|
||||
);
|
||||
|
||||
const handleQuantityChange = (itemId: string, value: number) => {
|
||||
setQuantities((prev) => ({
|
||||
...prev,
|
||||
[itemId]: String(value),
|
||||
}));
|
||||
|
||||
if (debounceRef.current[itemId]) clearTimeout(debounceRef.current[itemId]!);
|
||||
|
||||
debounceRef.current[itemId] = setTimeout(() => {
|
||||
if (value <= 0) {
|
||||
deleteCartItem({ cart_item_id: itemId });
|
||||
} else {
|
||||
updateCartItem({ body: { quantity: value }, cart_item_id: itemId });
|
||||
}
|
||||
}, 500);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="custom-container mb-6">
|
||||
<>
|
||||
{/* Header */}
|
||||
<div className="mb-6">
|
||||
<h1 className="text-3xl font-bold text-gray-800 mb-2">Savat</h1>
|
||||
<p className="text-gray-600">{cartItems.length} ta mahsulot</p>
|
||||
</div>
|
||||
<div className="mb-6">
|
||||
<h1 className="text-3xl font-bold text-gray-800 mb-2">{t('Savat')}</h1>
|
||||
<p className="text-gray-600">
|
||||
{cartItems.length} {t('ta mahsulot')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* Cart Items */}
|
||||
<div className="lg:col-span-2">
|
||||
<div className="bg-white rounded-lg shadow-md overflow-hidden">
|
||||
{cartItems.map((item, index) => (
|
||||
<div
|
||||
key={item.id}
|
||||
className={`p-6 flex relative gap-4 ${index !== cartItems.length - 1 ? 'border-b' : ''}`}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
<div className="lg:col-span-2">
|
||||
<div className="bg-white rounded-lg shadow-md overflow-hidden">
|
||||
{cartItems.map((item, index) => (
|
||||
<div
|
||||
key={item.id}
|
||||
className={`p-6 flex relative gap-4 ${
|
||||
index !== cartItems.length - 1 ? 'border-b' : ''
|
||||
}`}
|
||||
>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="icon"
|
||||
onClick={() => deleteCartItem({ cart_item_id: item.id })}
|
||||
className="absolute right-2 w-7 h-7 top-2 cursor-pointer"
|
||||
>
|
||||
{/* Product Image */}
|
||||
<Button
|
||||
variant={'destructive'}
|
||||
size={'icon'}
|
||||
onClick={() => handleRemoveItem(item.id)}
|
||||
className="absolute right-2 w-7 h-7 top-2 cursor-pointer"
|
||||
>
|
||||
<Trash className="size-4" />
|
||||
</Button>
|
||||
<div className="w-24 h-40 bg-gray-100 rounded-lg flex-shrink-0 overflow-hidden">
|
||||
<Image
|
||||
width={500}
|
||||
height={500}
|
||||
src={item.image}
|
||||
alt={item.name}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
<Trash className="size-4" />
|
||||
</Button>
|
||||
|
||||
{/* Product Info */}
|
||||
<div className="flex-1">
|
||||
<h3 className="font-semibold text-lg mb-1">{item.name}</h3>
|
||||
<div className="flex items-center gap-2 mb-3 max-lg:flex-col max-lg:items-start max-lg:gap-1">
|
||||
<span className="text-blue-600 font-bold text-xl">
|
||||
{item.price.toLocaleString()} {"so'm"}
|
||||
</span>
|
||||
{item.oldPrice && (
|
||||
<span className="text-gray-400 line-through text-sm">
|
||||
{item.oldPrice.toLocaleString()} {"so'm"}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between max-lg:flex-col max-lg:items-start max-lg:gap-1">
|
||||
{/* Quantity Controls */}
|
||||
<div className="flex items-center border border-gray-300 rounded-lg">
|
||||
<button
|
||||
onClick={() =>
|
||||
handleQuantityChange(item.id, 'decrease')
|
||||
}
|
||||
className="p-2 cursor-pointer transition rounded-lg"
|
||||
disabled={Number(item.quantity) <= 1}
|
||||
>
|
||||
<Minus className="w-4 h-4" />
|
||||
</button>
|
||||
<Input
|
||||
type="text"
|
||||
min={1}
|
||||
value={item.quantity}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
// Bo'sh qiymatga ruxsat berish
|
||||
if (value === '') {
|
||||
setCartItems((prev) =>
|
||||
prev.map((cartItem) =>
|
||||
cartItem.id === item.id
|
||||
? { ...cartItem, quantity: '' }
|
||||
: cartItem,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const number = parseInt(value, 10);
|
||||
if (!isNaN(number) && number > 0) {
|
||||
setCartItems((prev) =>
|
||||
prev.map((cartItem) =>
|
||||
cartItem.id === item.id
|
||||
? { ...cartItem, quantity: number }
|
||||
: cartItem,
|
||||
),
|
||||
);
|
||||
}
|
||||
}}
|
||||
className="w-16 text-center outline-none ring-0 focus-visible:ring-0 border-none font-semibold"
|
||||
/>
|
||||
<button
|
||||
onClick={() =>
|
||||
handleQuantityChange(item.id, 'increase')
|
||||
}
|
||||
className="p-2 cursor-pointer transition rounded-lg"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Order Summary */}
|
||||
<div className="lg:col-span-1">
|
||||
<div className="bg-white rounded-lg shadow-md p-6 sticky top-4">
|
||||
<h3 className="text-xl font-bold mb-4">Buyurtma xulasasi</h3>
|
||||
|
||||
<div className="space-y-3 mb-4">
|
||||
<div className="flex justify-between text-gray-600">
|
||||
<span>Mahsulotlar narxi:</span>
|
||||
<span>
|
||||
{subtotal.toLocaleString()} {"so'm"}
|
||||
</span>
|
||||
<div className="w-24 h-40 bg-gray-100 rounded-lg flex-shrink-0 overflow-hidden">
|
||||
<Image
|
||||
src={BASE_URL + item.product_image}
|
||||
alt={item.product_name}
|
||||
width={500}
|
||||
height={500}
|
||||
className="object-cover"
|
||||
style={{ width: '100%', height: 'auto' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{discount > 0 && (
|
||||
<div className="flex justify-between text-green-600">
|
||||
<span>Chegirma:</span>
|
||||
<span>
|
||||
-{discount.toLocaleString()} {"so'm"}
|
||||
<div className="flex-1">
|
||||
<h3 className="font-semibold text-lg mb-1">
|
||||
{item.product_name}
|
||||
</h3>
|
||||
<div className="flex items-center gap-2 mb-3 max-lg:flex-col max-lg:items-start max-lg:gap-1">
|
||||
<span className="text-blue-600 font-bold text-xl">
|
||||
{formatPrice(item.product_price, true)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-between text-gray-600">
|
||||
<span className="flex items-center gap-1">
|
||||
<Truck className="w-4 h-4" />
|
||||
Yetkazib berish:
|
||||
</span>
|
||||
<span>
|
||||
{deliveryFee === 0 ? (
|
||||
<span className="text-green-600 font-semibold">
|
||||
Bepul
|
||||
</span>
|
||||
) : (
|
||||
`${deliveryFee.toLocaleString()} so'm`
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center border border-gray-300 rounded-lg w-max">
|
||||
<button
|
||||
onClick={() =>
|
||||
handleQuantityChange(
|
||||
item.id,
|
||||
Number(quantities[item.id]) - 1,
|
||||
)
|
||||
}
|
||||
className="p-2 cursor-pointer transition rounded-lg"
|
||||
>
|
||||
<Minus className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
{deliveryFee > 0 && (
|
||||
<p className="text-sm text-gray-500 bg-blue-50 p-2 rounded">
|
||||
{
|
||||
"50,000 so'mdan ortiq xarid qiling va yetkazib berishni bepul oling!"
|
||||
}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<Input
|
||||
value={quantities[item.id]}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value.replace(/\D/g, ''); // faqat raqam
|
||||
setQuantities((prev) => ({
|
||||
...prev,
|
||||
[item.id]: val,
|
||||
}));
|
||||
|
||||
<div className="border-t pt-4 mb-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-lg font-semibold">Jami:</span>
|
||||
<span className="text-2xl font-bold text-blue-600">
|
||||
{total.toLocaleString()} {"so'm"}
|
||||
</span>
|
||||
// Debounce bilan update
|
||||
const valNum = Number(val);
|
||||
if (!isNaN(valNum))
|
||||
handleQuantityChange(item.id, valNum);
|
||||
}}
|
||||
type="text"
|
||||
className="w-16 text-center"
|
||||
/>
|
||||
|
||||
<button
|
||||
onClick={() =>
|
||||
handleQuantityChange(
|
||||
item.id,
|
||||
Number(quantities[item.id]) + 1,
|
||||
)
|
||||
}
|
||||
className="p-2 cursor-pointer transition rounded-lg"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleCheckout}
|
||||
className="w-full bg-blue-600 text-white py-4 rounded-lg font-semibold hover:bg-blue-700 transition flex items-center justify-center gap-2 mb-4"
|
||||
>
|
||||
<CreditCard className="w-5 h-5" />
|
||||
Buyurtmani rasmiylashtirish
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => router.push('/')}
|
||||
className="w-full border-2 border-gray-300 cursor-pointer text-gray-700 py-3 rounded-lg font-semibold hover:bg-gray-50 transition flex items-center justify-center gap-2"
|
||||
>
|
||||
<ArrowLeft className="w-5 h-5" />
|
||||
Xaridni davom ettirish
|
||||
</button>
|
||||
|
||||
{/* Additional Info */}
|
||||
<div className="mt-6 space-y-3 text-sm text-gray-600">
|
||||
<div className="flex items-start gap-2">
|
||||
<Truck className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
|
||||
<span>Tez yetkazib berish 1-2 kun ichida</span>
|
||||
</div>
|
||||
<div className="flex items-start gap-2">
|
||||
<CreditCard className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
|
||||
<span>{"Xavfsiz to'lov usullari"}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
|
||||
<div className="lg:col-span-1">
|
||||
<div className="bg-white rounded-lg shadow-md p-6 sticky top-4">
|
||||
<h3 className="text-xl font-bold mb-4">{t('Buyurtma haqida')}</h3>
|
||||
|
||||
<div className="space-y-3 mb-4">
|
||||
<div className="flex justify-between text-gray-600">
|
||||
<span>{t('Mahsulotlar narxi')}:</span>
|
||||
<span>{formatPrice(subtotal, true)}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between text-gray-600">
|
||||
<span className="flex items-center gap-1">
|
||||
<Truck className="w-4 h-4" /> {t('Yetkazib berish')}:
|
||||
</span>
|
||||
<span>
|
||||
<span className="text-green-600 font-semibold">
|
||||
{t('Bepul')}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t pt-4 mb-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-lg font-semibold">{t('Jami')}:</span>
|
||||
<span className="text-2xl font-bold text-blue-600">
|
||||
{formatPrice(subtotal, true)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleCheckout}
|
||||
className="w-full bg-blue-600 text-white py-4 rounded-lg font-semibold hover:bg-blue-700 transition flex items-center justify-center gap-2 mb-4"
|
||||
>
|
||||
<CreditCard className="w-5 h-5" />{' '}
|
||||
{t('Buyurtmani rasmiylashtirish')}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => router.push('/')}
|
||||
className="w-full border-2 border-gray-300 cursor-pointer text-gray-700 py-3 rounded-lg font-semibold hover:bg-gray-50 transition flex items-center justify-center gap-2"
|
||||
>
|
||||
<ArrowLeft className="w-5 h-5" /> {t('Xaridni davom ettirish')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user