Compare commits
10 Commits
8a4682212f
...
72c46a296c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
72c46a296c | ||
|
|
e270495a17 | ||
|
|
8abd0e448b | ||
|
|
5e1430adf6 | ||
|
|
2bdd6f17a2 | ||
|
|
bb782d96da | ||
|
|
08a96d2821 | ||
|
|
512701140d | ||
|
|
2535913eb2 | ||
|
|
4d22e3441c |
@@ -1,4 +1,4 @@
|
||||
import Product from '@/features/category/ui/Product';
|
||||
import SubCategory from '@/features/category/ui/SubCategory';
|
||||
import { category_api } from '@/shared/config/api/category/api';
|
||||
import { BASE_URL } from '@/shared/config/api/URLs';
|
||||
import { Metadata } from 'next';
|
||||
@@ -13,7 +13,7 @@ interface Params {
|
||||
const fetchCategory = async (categoryId: string) => {
|
||||
try {
|
||||
const res = await category_api.getCategory({ page: 1, page_size: 99 });
|
||||
return res.data.results.find((c) => c.id.toString() === categoryId);
|
||||
return res.data.find((c) => c.id.toString() === categoryId);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -60,7 +60,7 @@ export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||
const Page = () => {
|
||||
return (
|
||||
<Suspense>
|
||||
<Product />
|
||||
<SubCategory />
|
||||
</Suspense>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Suspense } from 'react';
|
||||
const fetchCategoryData = async () => {
|
||||
try {
|
||||
const res = await category_api.getCategory({ page: 1, page_size: 99 });
|
||||
return res.data.results;
|
||||
return res.data;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -165,7 +165,9 @@ const CartPage = () => {
|
||||
<Image
|
||||
src={
|
||||
item.product.images.length > 0
|
||||
? BASE_URL + item.product.images[0].image
|
||||
? item.product.images[0].image.includes(BASE_URL)
|
||||
? item.product.images[0].image
|
||||
: BASE_URL + item.product.images[0].image
|
||||
: ProductBanner
|
||||
}
|
||||
alt={item.product.name}
|
||||
|
||||
@@ -36,7 +36,6 @@ import {
|
||||
ZoomControl,
|
||||
} from '@pbe/react-yandex-maps';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { AxiosError } from 'axios';
|
||||
import { format } from 'date-fns';
|
||||
import { uz } from 'date-fns/locale';
|
||||
import {
|
||||
@@ -106,20 +105,17 @@ const OrderPage = () => {
|
||||
|
||||
queryClinet.refetchQueries({ queryKey: ['cart_items'] });
|
||||
} else {
|
||||
toast.error(t('Xatolik yuz berdi'), {
|
||||
toast.error(t('Xatolik yuz berdi: Mahsulot omborxonada yetarli emas'), {
|
||||
richColors: true,
|
||||
position: 'top-center',
|
||||
});
|
||||
}
|
||||
},
|
||||
onError: (error: AxiosError) => {
|
||||
(
|
||||
error.response?.data as { items: { non_field_errors: string[] }[] }
|
||||
).items
|
||||
?.flatMap((i) => i.non_field_errors || [])
|
||||
.forEach((msg: string) =>
|
||||
toast.error(msg, { richColors: true, position: 'top-center' }),
|
||||
);
|
||||
onError: () => {
|
||||
toast.error(t('Xatolik yuz berdi: Mahsulot omborxoda yetarli emas'), {
|
||||
richColors: true,
|
||||
position: 'top-center',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
@@ -281,19 +277,19 @@ const OrderPage = () => {
|
||||
order_quant: item.quantity,
|
||||
price_type_code: item.product.prices![0].price_type.code,
|
||||
product_price: item.product.prices![0].price,
|
||||
warehouse_code: 'wh1',
|
||||
warehouse_code: process.env.NEXT_PUBLIC_WARHOUSES_CODE!,
|
||||
}));
|
||||
if (user) {
|
||||
mutate({
|
||||
order: [
|
||||
{
|
||||
filial_code: 'dodge',
|
||||
filial_code: process.env.NEXT_PUBLIC_FILIAL_CODE!,
|
||||
delivery_date: formatDate.format(deliveryDate, 'DD.MM.YYYY'),
|
||||
room_code: process.env.NEXT_ROOM_CODE!,
|
||||
room_code: process.env.NEXT_PUBLIC_ROOM_CODE!,
|
||||
deal_time: formatDate.format(deliveryDate, 'DD.MM.YYYY'),
|
||||
robot_code: process.env.NEXT_ROBOT_CODE!,
|
||||
robot_code: process.env.NEXT_PUBLIC_ROBOT_CODE!,
|
||||
status: 'B#N',
|
||||
sales_manager_code: process.env.NEXT_SALES_MANAGER_CODE!,
|
||||
sales_manager_code: process.env.NEXT_PUBLIC_SALES_MANAGER_CODE!,
|
||||
person_code: user?.username,
|
||||
currency_code: '860',
|
||||
owner_person_code: user?.username,
|
||||
@@ -565,7 +561,9 @@ const OrderPage = () => {
|
||||
unoptimized
|
||||
src={
|
||||
item.product.images.length !== 0
|
||||
? BASE_URL + item.product.images[0].image
|
||||
? item.product.images[0].image.includes(BASE_URL)
|
||||
? item.product.images[0].image
|
||||
: BASE_URL + item.product.images[0].image
|
||||
: LogosProduct
|
||||
}
|
||||
alt={item.product.name}
|
||||
|
||||
@@ -14,7 +14,7 @@ const Category = () => {
|
||||
queryKey: ['category_list'],
|
||||
queryFn: () => category_api.getCategory({ page: 1, page_size: 99 }),
|
||||
select(data) {
|
||||
return data.data.results;
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -7,21 +7,22 @@ import { GlobalPagination } from '@/shared/ui/global-pagination';
|
||||
import { Skeleton } from '@/shared/ui/skeleton';
|
||||
import { ProductCard } from '@/widgets/categories/ui/product-card';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { ArrowLeft } from 'lucide-react';
|
||||
import { ArrowLeft, ShoppingBag } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useParams, useSearchParams } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
const PAGE_SIZE = 36;
|
||||
|
||||
const Product = () => {
|
||||
const { categoryId } = useParams();
|
||||
const { subId } = useParams();
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const [page, setPage] = useState(1);
|
||||
const t = useTranslations();
|
||||
|
||||
const [page, setPage] = useState(1);
|
||||
|
||||
useEffect(() => {
|
||||
const urlPage = Number(searchParams.get('page')) || 1;
|
||||
setPage(urlPage);
|
||||
@@ -32,20 +33,25 @@ const Product = () => {
|
||||
isLoading,
|
||||
isError,
|
||||
} = useQuery({
|
||||
queryKey: ['product_list', categoryId, page],
|
||||
queryKey: ['product_list', subId, page],
|
||||
queryFn: () => {
|
||||
if (!categoryId) throw new Error('Category ID is required');
|
||||
return product_api.listGetCategoryId({
|
||||
category_id: categoryId.toString(),
|
||||
params: { page, page_size: PAGE_SIZE },
|
||||
if (!subId) throw new Error('Category ID is required');
|
||||
return product_api.list({
|
||||
page,
|
||||
page_size: PAGE_SIZE,
|
||||
product_type_id: Number(subId),
|
||||
});
|
||||
},
|
||||
select(data) {
|
||||
return data.data;
|
||||
},
|
||||
enabled: !!categoryId,
|
||||
enabled: !!subId,
|
||||
});
|
||||
|
||||
const activeProducts = useMemo(() => {
|
||||
return product?.results?.filter((item) => item.state === 'A') ?? [];
|
||||
}, [product]);
|
||||
|
||||
const handleBack = () => {
|
||||
router.back();
|
||||
};
|
||||
@@ -60,7 +66,7 @@ const Product = () => {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="custom-container p-4 mb-5 flex flex-col min-h-[calc(85vh)]">
|
||||
<div className="custom-container p-4 mb-5 flex flex-col min-h-[85vh]">
|
||||
<div className="flex-1">
|
||||
{/* Header */}
|
||||
<div className="mb-6">
|
||||
@@ -72,38 +78,50 @@ const Product = () => {
|
||||
<span>{t('Orqaga')}</span>
|
||||
</button>
|
||||
|
||||
<p className="text-gray-600 text-sm mt-1">
|
||||
{product?.total} {t('ta mahsulot')}
|
||||
<p className="text-gray-600 text-sm">
|
||||
{product?.total ?? 0} {t('ta mahsulot')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Products grid */}
|
||||
{/* Products */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 gap-3">
|
||||
{/* Loading */}
|
||||
{isLoading &&
|
||||
Array.from({ length: 6 }).map((_, index) => (
|
||||
<Card className="p-3 space-y-3 rounded-xl" key={index}>
|
||||
<Card key={index} className="p-3 space-y-3 rounded-xl">
|
||||
<Skeleton className="h-40 sm:h-48 md:h-56 w-full rounded-lg" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-4 w-1/2" />
|
||||
<Skeleton className="h-10 w-full rounded-lg" />
|
||||
</Card>
|
||||
))}
|
||||
{product &&
|
||||
!isLoading &&
|
||||
product.results
|
||||
.filter((product) => product.state === 'A')
|
||||
.map((item) => (
|
||||
<ProductCard key={item.id} product={item} error={isError} />
|
||||
))}
|
||||
|
||||
{/* Empty state */}
|
||||
{!isLoading && activeProducts.length === 0 && (
|
||||
<div className="col-span-full flex flex-col items-center justify-center py-24 text-gray-500">
|
||||
<div className="text-5xl mb-4">
|
||||
<ShoppingBag size={70} />
|
||||
</div>
|
||||
<p className="text-lg font-medium text-center">
|
||||
{t("Hozirchali bu kategoriyada mahsulot yo'q")}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Products list */}
|
||||
{!isLoading &&
|
||||
activeProducts.map((item) => (
|
||||
<ProductCard key={item.id} product={item} error={isError} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Pagination at the bottom */}
|
||||
{product && (
|
||||
<div className="w-full mt-5 flex justify-end">
|
||||
{/* Pagination */}
|
||||
{product && product.total > PAGE_SIZE && (
|
||||
<div className="w-full mt-6 flex justify-end">
|
||||
<GlobalPagination
|
||||
page={page}
|
||||
total={product.total ?? 0}
|
||||
total={product.total}
|
||||
pageSize={PAGE_SIZE}
|
||||
onChange={handlePageChange}
|
||||
/>
|
||||
|
||||
@@ -1,30 +1,43 @@
|
||||
'use client';
|
||||
|
||||
import { category_api } from '@/shared/config/api/category/api';
|
||||
import { useRouter } from '@/shared/config/i18n/navigation';
|
||||
import { categoryList } from '@/widgets/welcome/lib/data';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { ChevronRight } from 'lucide-react';
|
||||
import { useParams } from 'next/navigation';
|
||||
|
||||
const SubCategory = () => {
|
||||
const { categoryId } = useParams();
|
||||
|
||||
const router = useRouter();
|
||||
const category =
|
||||
categoryList.find((cat) => cat.name === categoryId) || categoryList[0];
|
||||
const { data: category } = useQuery({
|
||||
queryKey: ['category_list'],
|
||||
queryFn: () => category_api.getCategory({ page: 1, page_size: 99 }),
|
||||
select(data) {
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubCategoryClick = (subCategory: { name: string }) => {
|
||||
router.push(`/category/${categoryId}/${subCategory.name}`);
|
||||
const router = useRouter();
|
||||
const categorys = category?.find((cat) => cat.id === Number(categoryId));
|
||||
|
||||
const handleSubCategoryClick = (subCategory: {
|
||||
name: string;
|
||||
id: number;
|
||||
}) => {
|
||||
router.push(`/category/${categoryId}/${subCategory.id}`);
|
||||
};
|
||||
|
||||
console.log(categorys);
|
||||
|
||||
return (
|
||||
<div className="custom-container">
|
||||
<>
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mb-6">
|
||||
{category.name}
|
||||
{categorys?.name}
|
||||
</h1>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
|
||||
{category.subCategories.map((subCategory, index) => (
|
||||
{categorys?.product_types.map((subCategory, index) => (
|
||||
<button
|
||||
key={index}
|
||||
onClick={() => handleSubCategoryClick(subCategory)}
|
||||
|
||||
@@ -4,20 +4,31 @@ import { cart_api } from '@/features/cart/lib/api';
|
||||
import { product_api } from '@/shared/config/api/product/api';
|
||||
import { BASE_URL } from '@/shared/config/api/URLs';
|
||||
import { useCartId } from '@/shared/hooks/cartId';
|
||||
import formatDate from '@/shared/lib/formatDate';
|
||||
import formatPrice from '@/shared/lib/formatPrice';
|
||||
import { cn } from '@/shared/lib/utils';
|
||||
import { Button } from '@/shared/ui/button';
|
||||
import {
|
||||
Carousel,
|
||||
CarouselApi,
|
||||
CarouselContent,
|
||||
CarouselItem,
|
||||
CarouselNext,
|
||||
CarouselPrevious,
|
||||
} from '@/shared/ui/carousel';
|
||||
import { Input } from '@/shared/ui/input';
|
||||
import { Skeleton } from '@/shared/ui/skeleton';
|
||||
import { ProductCard } from '@/widgets/categories/ui/product-card';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { AxiosError } from 'axios';
|
||||
import { Heart, Minus, Plus, Shield, ShoppingCart, Truck } from 'lucide-react';
|
||||
import {
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Heart,
|
||||
Minus,
|
||||
Plus,
|
||||
Shield,
|
||||
ShoppingCart,
|
||||
Truck,
|
||||
} from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import Image from 'next/image';
|
||||
import { useParams } from 'next/navigation';
|
||||
@@ -29,6 +40,9 @@ const ProductDetail = () => {
|
||||
const { product } = useParams<{ product: string }>();
|
||||
const queryClient = useQueryClient();
|
||||
const { cart_id } = useCartId();
|
||||
const [api, setApi] = useState<CarouselApi>();
|
||||
const [canScrollPrev, setCanScrollPrev] = useState(false);
|
||||
const [canScrollNext, setCanScrollNext] = useState(false);
|
||||
|
||||
const [quantity, setQuantity] = useState(1);
|
||||
const [selectedImage, setSelectedImage] = useState(0);
|
||||
@@ -58,8 +72,7 @@ const ProductDetail = () => {
|
||||
|
||||
/* ---------------- DERIVED DATA ---------------- */
|
||||
const price = Number(data?.prices?.[0]?.price || 0);
|
||||
|
||||
const category = 'Ichimliklar'; // default category
|
||||
const maxBalance = data?.balance ?? 0; // <-- balance limit
|
||||
|
||||
/* ---------------- SYNC CART QUANTITY ---------------- */
|
||||
useEffect(() => {
|
||||
@@ -136,12 +149,25 @@ const ProductDetail = () => {
|
||||
|
||||
/* ---------------- HANDLERS ---------------- */
|
||||
const handleAddToCart = () => {
|
||||
if (quantity >= maxBalance) {
|
||||
toast.warning(t(`only_available`, { maxBalance }), {
|
||||
richColors: true,
|
||||
position: 'top-center',
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!data || !cart_id) return;
|
||||
|
||||
const cartItem = cartItems?.data.cart_item.find(
|
||||
(i) => Number(i.product.id) === data.id,
|
||||
);
|
||||
|
||||
if (quantity > maxBalance) {
|
||||
toast.error(t(`Faqat ${maxBalance} dona mavjud`), { richColors: true });
|
||||
setQuantity(maxBalance);
|
||||
return;
|
||||
}
|
||||
|
||||
if (cartItem) {
|
||||
updateCartItem({
|
||||
cart_item_id: cartItem.id.toString(),
|
||||
@@ -156,6 +182,43 @@ const ProductDetail = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleIncrease = () => {
|
||||
if (quantity >= maxBalance) {
|
||||
toast.warning(t(`Faqat ${maxBalance} dona mavjud`), {
|
||||
richColors: true,
|
||||
position: 'top-center',
|
||||
});
|
||||
return;
|
||||
}
|
||||
setQuantity((q) => q + 1);
|
||||
};
|
||||
|
||||
const handleDecrease = () => {
|
||||
setQuantity((q) => Math.max(1, q - 1));
|
||||
};
|
||||
|
||||
/* ---------------- CAROUSEL ---------------- */
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
|
||||
const updateButtons = () => {
|
||||
setCanScrollPrev(api.canScrollPrev());
|
||||
setCanScrollNext(api.canScrollNext());
|
||||
};
|
||||
|
||||
updateButtons();
|
||||
api.on('select', updateButtons);
|
||||
api.on('reInit', updateButtons);
|
||||
|
||||
return () => {
|
||||
api.off('select', updateButtons);
|
||||
api.off('reInit', updateButtons);
|
||||
};
|
||||
}, [api]);
|
||||
|
||||
const scrollPrev = () => api?.scrollPrev();
|
||||
const scrollNext = () => api?.scrollNext();
|
||||
|
||||
/* ---------------- LOADING ---------------- */
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -177,7 +240,9 @@ const ProductDetail = () => {
|
||||
height={500}
|
||||
src={
|
||||
data?.images?.length
|
||||
? BASE_URL + data.images[selectedImage]?.image
|
||||
? data.images[selectedImage]?.image?.includes(BASE_URL)
|
||||
? data.images[selectedImage]?.image
|
||||
: BASE_URL + data.images[selectedImage]?.image
|
||||
: '/placeholder.svg'
|
||||
}
|
||||
alt={data?.name || 'logo'}
|
||||
@@ -216,41 +281,35 @@ const ProductDetail = () => {
|
||||
{/* INFO */}
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold mb-2">{data?.name}</h1>
|
||||
|
||||
<div className="text-4xl font-bold text-blue-600 mb-4">
|
||||
{formatPrice(price, true)}
|
||||
</div>
|
||||
|
||||
<p className="text-gray-600 mb-6">{data?.short_name}</p>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4 mb-6">
|
||||
<div>
|
||||
<span className="text-gray-500">Kategoriya:</span>
|
||||
<p className="font-semibold">{category}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* QUANTITY */}
|
||||
<div className="flex items-center gap-4 mb-6">
|
||||
<button
|
||||
onClick={() => setQuantity((q) => Math.max(1, q - 1))}
|
||||
className="p-2 border rounded"
|
||||
>
|
||||
<button onClick={handleDecrease} className="p-2 border rounded">
|
||||
<Minus />
|
||||
</button>
|
||||
|
||||
<Input
|
||||
value={quantity}
|
||||
onChange={(e) => {
|
||||
const v = Number(e.target.value);
|
||||
if (v > 0) setQuantity(v);
|
||||
let v = Number(e.target.value);
|
||||
if (v < 1) v = 1;
|
||||
if (v > maxBalance) {
|
||||
toast.warning(t(`Faqat ${maxBalance} dona mavjud`), {
|
||||
richColors: true,
|
||||
position: 'top-center',
|
||||
});
|
||||
v = maxBalance;
|
||||
}
|
||||
setQuantity(v);
|
||||
}}
|
||||
className="w-16 text-center"
|
||||
/>
|
||||
|
||||
<button
|
||||
onClick={() => setQuantity((q) => q + 1)}
|
||||
className="p-2 border rounded"
|
||||
>
|
||||
<button onClick={handleIncrease} className="p-2 border rounded">
|
||||
<Plus />
|
||||
</button>
|
||||
</div>
|
||||
@@ -280,9 +339,17 @@ const ProductDetail = () => {
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
{/* IMPROVED UPDATED_AT WARNING */}
|
||||
{data?.updated_at && data.payment_type === 'cash' && (
|
||||
<div className="bg-yellow-50 border border-yellow-400 text-yellow-800 p-3 mb-4 rounded-md">
|
||||
<p className="text-xs font-medium">
|
||||
{t("Narxi o'zgargan bo'lishi mumkin")} • {t('Yangilangan')}:{' '}
|
||||
{formatDate.format(data.updated_at, 'DD-MM-YYYY')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* FEATURES */}
|
||||
<div className="grid grid-cols-2 gap-4 mt-6 border-t pt-4">
|
||||
<div className={cn('grid gap-4 mt-6 border-t pt-4', 'grid-cols-2')}>
|
||||
<div className="text-center">
|
||||
<Truck className="mx-auto mb-1" />
|
||||
{t('Bepul yetkazib berish')}
|
||||
@@ -291,19 +358,41 @@ const ProductDetail = () => {
|
||||
<Shield className="mx-auto mb-1" />
|
||||
{t('Kafolat')}
|
||||
</div>
|
||||
{/* {data?.payment_type && (
|
||||
<div className="text-center">
|
||||
<Banknote className="mx-auto mb-1" size={28} />
|
||||
|
||||
{data.payment_type === 'cash'
|
||||
? t('Naqd bilan olinadi')
|
||||
: t("Pul o'tkazish yo'li bilan olinadi")}
|
||||
</div>
|
||||
)} */}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* RELATED */}
|
||||
<div className="mt-10 bg-white p-6 rounded-lg shadow">
|
||||
{/* RELATED PRODUCTS */}
|
||||
<div className="mt-10 bg-white p-6 rounded-lg shadow relative">
|
||||
<Button
|
||||
onClick={scrollPrev}
|
||||
disabled={!canScrollPrev}
|
||||
className="absolute top-1/2 left-0 -translate-x-1/2 z-20 rounded-full"
|
||||
size={'icon'}
|
||||
variant={'outline'}
|
||||
>
|
||||
<ChevronLeft size={32} />
|
||||
</Button>
|
||||
|
||||
<h2 className="text-2xl font-bold mb-4">{t("O'xshash mahsulotlar")}</h2>
|
||||
|
||||
<Carousel>
|
||||
<Carousel setApi={setApi}>
|
||||
<CarouselContent>
|
||||
{recLoad &&
|
||||
Array.from({ length: 6 }).map((_, i) => (
|
||||
<CarouselItem key={i} className="basis-1/5">
|
||||
<CarouselItem
|
||||
key={i}
|
||||
className="basis-1/1 sm:basis-1/3 md:basis-1/4 lg:basis-1/5 xl:basis-1/6 pb-2"
|
||||
>
|
||||
<Skeleton className="h-60 w-full" />
|
||||
</CarouselItem>
|
||||
))}
|
||||
@@ -311,15 +400,25 @@ const ProductDetail = () => {
|
||||
{recomendation
|
||||
?.filter((p) => p.state === 'A')
|
||||
.map((p) => (
|
||||
<CarouselItem key={p.id} className="basis-1/5">
|
||||
<CarouselItem
|
||||
key={p.id}
|
||||
className="basis-1/2 sm:basis-1/3 md:basis-1/4 lg:basis-1/5 xl:basis-1/6 pb-2"
|
||||
>
|
||||
<ProductCard product={p} />
|
||||
</CarouselItem>
|
||||
))}
|
||||
</CarouselContent>
|
||||
|
||||
<CarouselPrevious />
|
||||
<CarouselNext />
|
||||
</Carousel>
|
||||
|
||||
<Button
|
||||
onClick={scrollNext}
|
||||
disabled={!canScrollNext}
|
||||
className="absolute top-1/2 -translate-x-1/2 z-20 -right-10 rounded-full"
|
||||
size={'icon'}
|
||||
variant={'outline'}
|
||||
>
|
||||
<ChevronRight size={32} />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -3,13 +3,58 @@ import { API_URLS } from '@/shared/config/api/URLs';
|
||||
import { AxiosResponse } from 'axios';
|
||||
|
||||
export interface OrderList {
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
total_pages: number;
|
||||
has_next: boolean;
|
||||
has_previous: boolean;
|
||||
results: OrderListRes[];
|
||||
id: number;
|
||||
user: number;
|
||||
comment: string;
|
||||
delivery_date: string;
|
||||
items: {
|
||||
id: number;
|
||||
quantity: number;
|
||||
price: string;
|
||||
product: {
|
||||
id: number;
|
||||
images: { id: number; images: string | null }[];
|
||||
liked: false;
|
||||
meansurement: null | string;
|
||||
inventory_id: null | string;
|
||||
product_id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
short_name: string;
|
||||
weight_netto: null | number;
|
||||
weight_brutto: null | number;
|
||||
litr: null | number;
|
||||
box_type_code: null | number;
|
||||
box_quant: null | number;
|
||||
groups: {
|
||||
id: number;
|
||||
name: string;
|
||||
}[];
|
||||
state: 'A' | 'P';
|
||||
barcodes: string;
|
||||
article_code: null | string;
|
||||
marketing_group_code: null | string;
|
||||
inventory_kinds: {
|
||||
id: number;
|
||||
name: string;
|
||||
}[];
|
||||
|
||||
sector_codes: [];
|
||||
prices: {
|
||||
id: number;
|
||||
price: string;
|
||||
price_type: {
|
||||
id: number;
|
||||
name: string;
|
||||
code: string;
|
||||
};
|
||||
}[];
|
||||
|
||||
payment_type: null | string;
|
||||
balance: number;
|
||||
updated_at: string;
|
||||
};
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface OrderListRes {
|
||||
@@ -41,12 +86,10 @@ export interface OrderListRes {
|
||||
expires_date: string;
|
||||
manufacturer: string;
|
||||
volume: string;
|
||||
images: [
|
||||
{
|
||||
id: string;
|
||||
image: string;
|
||||
},
|
||||
];
|
||||
images: {
|
||||
id: string;
|
||||
image: string;
|
||||
}[];
|
||||
};
|
||||
price: number;
|
||||
quantity: number;
|
||||
@@ -57,11 +100,8 @@ export interface OrderListRes {
|
||||
}
|
||||
|
||||
export const order_api = {
|
||||
async list(params: {
|
||||
page: number;
|
||||
page_size: number;
|
||||
}): Promise<AxiosResponse<OrderList>> {
|
||||
const res = await httpClient.get(API_URLS.OrderList, { params });
|
||||
async list(): Promise<AxiosResponse<OrderList[]>> {
|
||||
const res = await httpClient.get(API_URLS.OrderList);
|
||||
return res;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,38 +1,35 @@
|
||||
import { usePathname, useRouter } from '@/shared/config/i18n/navigation';
|
||||
import formatDate from '@/shared/lib/formatDate';
|
||||
'use client';
|
||||
|
||||
import { BASE_URL } from '@/shared/config/api/URLs';
|
||||
import { useRouter } from '@/shared/config/i18n/navigation';
|
||||
import formatPrice from '@/shared/lib/formatPrice';
|
||||
import { cn } from '@/shared/lib/utils';
|
||||
import { Button } from '@/shared/ui/button';
|
||||
import { Card, CardContent } from '@/shared/ui/card';
|
||||
import { GlobalPagination } from '@/shared/ui/global-pagination';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import {
|
||||
Calendar,
|
||||
CheckCircle,
|
||||
Clock,
|
||||
Loader2,
|
||||
MessageSquare,
|
||||
Package,
|
||||
RefreshCw,
|
||||
ShoppingBag,
|
||||
} from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import Image from 'next/image';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { order_api, OrderListRes } from '../lib/api';
|
||||
import { order_api, OrderList } from '../lib/api';
|
||||
|
||||
const HistoryTabs = () => {
|
||||
const t = useTranslations();
|
||||
const searchParams = useSearchParams();
|
||||
const [page, setPage] = useState(1);
|
||||
const PAGE_SIZE = 36;
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['order_list', page],
|
||||
queryFn: () => order_api.list({ page, page_size: PAGE_SIZE }),
|
||||
select(data) {
|
||||
return data.data;
|
||||
},
|
||||
queryFn: () => order_api.list(),
|
||||
select: (res) => res.data,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -40,206 +37,257 @@ const HistoryTabs = () => {
|
||||
setPage(urlPage);
|
||||
}, [searchParams]);
|
||||
|
||||
const handlePageChange = (newPage: number) => {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
params.set('page', newPage.toString());
|
||||
|
||||
router.push(`${pathname}?${params.toString()}`, {
|
||||
scroll: true,
|
||||
});
|
||||
};
|
||||
|
||||
const getStatusConfig = (status: 'NEW' | 'DONE') => {
|
||||
return status === 'DONE'
|
||||
? {
|
||||
bgColor: 'bg-emerald-100',
|
||||
textColor: 'text-emerald-600',
|
||||
icon: CheckCircle,
|
||||
text: 'Yetkazildi',
|
||||
}
|
||||
: {
|
||||
bgColor: 'bg-yellow-100',
|
||||
textColor: 'text-yellow-600',
|
||||
icon: Clock,
|
||||
text: 'Kutilmoqda',
|
||||
};
|
||||
};
|
||||
|
||||
const getPaymentTypeText = (type: 'CASH' | 'ACCOUNT_NUMBER') => {
|
||||
return type === 'CASH' ? 'Naqd pul' : 'Hisob raqami';
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-primary" />
|
||||
<Loader2 className="w-8 h-8 animate-spin text-blue-600" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!data?.results || data.results.length === 0) {
|
||||
if (!data || data.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<Package className="w-16 h-16 text-muted-foreground mb-4" />
|
||||
<p className="text-lg font-semibold text-foreground mb-2">
|
||||
<div className="flex flex-col items-center justify-center py-16 text-center">
|
||||
<div className="bg-gray-100 p-6 rounded-full mb-4">
|
||||
<Package className="w-16 h-16 text-gray-400" />
|
||||
</div>
|
||||
<p className="text-xl font-bold text-gray-800 mb-2">
|
||||
{t('Buyurtmalar topilmadi')}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('Hali buyurtma qilmagansiz')}
|
||||
<p className="text-sm text-gray-500 max-w-md">
|
||||
{t(
|
||||
"Hali buyurtma qilmagansiz. Mahsulotlarni ko'rib chiqing va birinchi buyurtmangizni bering!",
|
||||
)}
|
||||
</p>
|
||||
<Button onClick={() => router.push('/')} className="mt-6">
|
||||
<ShoppingBag className="w-4 h-4 mr-2" />
|
||||
{t('Xarid qilish')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between mb-4 md:mb-6">
|
||||
<h2 className="text-xl md:text-2xl font-bold text-foreground">
|
||||
{t('Buyurtmalar tarixi')}
|
||||
</h2>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{data.results.length} ta buyurtma
|
||||
<div className="max-w-5xl mx-auto">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-6 pb-4 border-b">
|
||||
<div>
|
||||
<h2 className="text-2xl md:text-3xl font-bold text-gray-900">
|
||||
{t('Buyurtmalar tarixi')}
|
||||
</h2>
|
||||
<p className="text-sm text-gray-500 mt-1">
|
||||
{data.length} {t('ta buyurtma')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 md:space-y-4">
|
||||
{data.results.map((order: OrderListRes, idx: number) => {
|
||||
const statusConfig = getStatusConfig(order.status);
|
||||
const StatusIcon = statusConfig.icon;
|
||||
{/* Orders List */}
|
||||
<div className="space-y-6">
|
||||
{data.map((order: OrderList) => {
|
||||
const totalPrice = order.items.reduce(
|
||||
(sum, item) => sum + Number(item.price) * item.quantity,
|
||||
0,
|
||||
);
|
||||
|
||||
return (
|
||||
<div key={order.id} className="flex gap-3 md:gap-4">
|
||||
{/* Status Timeline */}
|
||||
<div className="flex flex-col items-center">
|
||||
<div
|
||||
className={cn(
|
||||
'w-8 h-8 md:w-10 md:h-10 rounded-full flex items-center justify-center shrink-0',
|
||||
statusConfig.bgColor,
|
||||
)}
|
||||
>
|
||||
<StatusIcon
|
||||
className={cn(
|
||||
'w-4 h-4 md:w-5 md:h-5',
|
||||
statusConfig.textColor,
|
||||
<Card
|
||||
key={order.id}
|
||||
className="border-2 border-gray-200 hover:border-blue-400 transition-all duration-200 shadow-sm hover:shadow-lg"
|
||||
>
|
||||
<CardContent className="p-0">
|
||||
{/* Order Header */}
|
||||
<div className="bg-gradient-to-r from-blue-50 to-indigo-50 p-4 border-b-2 border-gray-200">
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="bg-blue-600 text-white px-3 py-1 rounded-full text-sm font-bold">
|
||||
#{order.id}
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs text-gray-500">
|
||||
{t('Buyurtma raqami')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{order.delivery_date && (
|
||||
<div className="flex items-center gap-2 bg-white px-3 py-2 rounded-lg shadow-sm">
|
||||
<Calendar className="w-4 h-4 text-blue-600" />
|
||||
<div>
|
||||
<p className="text-xs text-gray-500">
|
||||
{t('Yetkazib berish')}
|
||||
</p>
|
||||
<p className="text-sm font-semibold text-gray-800">
|
||||
{order.delivery_date}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Comment */}
|
||||
{order.comment && (
|
||||
<div className="mt-3 bg-white p-3 rounded-lg shadow-sm border border-gray-200">
|
||||
<div className="flex items-start gap-2">
|
||||
<MessageSquare className="w-4 h-4 text-blue-600 mt-0.5 flex-shrink-0" />
|
||||
<div className="flex-1">
|
||||
<p className="text-xs font-medium text-gray-500 mb-1">
|
||||
{t('Izoh')}:
|
||||
</p>
|
||||
<p className="text-sm text-gray-700 leading-relaxed">
|
||||
{order.comment}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{idx < data.results.length - 1 && (
|
||||
<div className="w-0.5 flex-1 bg-slate-200 my-2" />
|
||||
)}
|
||||
</div>
|
||||
{/* Products */}
|
||||
<div className="p-4 space-y-3">
|
||||
{order.items.map((item, index) => {
|
||||
const product = item.product;
|
||||
|
||||
{/* Order Card */}
|
||||
<Card className="flex-1 border-0 shadow-sm hover:shadow-md transition-shadow">
|
||||
<CardContent className="p-3 md:p-4">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col md:flex-row md:items-start justify-between mb-3 gap-2">
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<p className="font-semibold text-sm md:text-base text-foreground">
|
||||
#{order.order_number}
|
||||
</p>
|
||||
<span
|
||||
className={cn(
|
||||
'text-xs px-2 py-0.5 rounded-full',
|
||||
statusConfig.bgColor,
|
||||
statusConfig.textColor,
|
||||
)}
|
||||
>
|
||||
{statusConfig.text}
|
||||
</span>
|
||||
// Get product image
|
||||
const productImage = product.images?.[0]?.images
|
||||
? product.images[0].images.includes(BASE_URL)
|
||||
? product.images[0].images
|
||||
: BASE_URL + product.images[0].images
|
||||
: '/placeholder.svg';
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
className="border-2 border-gray-100 rounded-xl p-4 bg-gradient-to-br from-white to-gray-50 hover:shadow-md transition-shadow"
|
||||
>
|
||||
{/* Product Header with Image */}
|
||||
<div className="flex gap-4 mb-3">
|
||||
{/* Product Image */}
|
||||
<div className="flex-shrink-0">
|
||||
<div className="w-20 h-20 md:w-24 md:h-24 bg-gray-100 rounded-lg overflow-hidden border-2 border-gray-200">
|
||||
<Image
|
||||
src={productImage}
|
||||
alt={product.name}
|
||||
width={96}
|
||||
height={96}
|
||||
className="w-full h-full object-contain"
|
||||
unoptimized
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Product Info */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-start justify-between gap-3 mb-2">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<span className="bg-blue-100 text-blue-800 text-xs font-semibold px-2 py-1 rounded">
|
||||
{index + 1}
|
||||
</span>
|
||||
<h3 className="font-bold text-base md:text-lg text-gray-900 truncate">
|
||||
{product.name}
|
||||
</h3>
|
||||
</div>
|
||||
{product.short_name && (
|
||||
<p className="text-sm text-gray-600 line-clamp-2">
|
||||
{product.short_name}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-right flex-shrink-0">
|
||||
<p className="text-xs text-gray-500 mb-1">
|
||||
{t('Mahsulotlar narxi')}
|
||||
</p>
|
||||
<p className="text-lg font-bold text-blue-600">
|
||||
{formatPrice(Number(item.price), true)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Product Details Grid */}
|
||||
<div className="grid grid-cols-2 gap-3 p-3 bg-white rounded-lg border border-gray-200">
|
||||
<div className="flex flex-col">
|
||||
<span className="text-xs text-gray-500 mb-1">
|
||||
{t('Miqdor')}
|
||||
</span>
|
||||
<span className="text-base font-bold text-gray-900">
|
||||
{item.quantity}{' '}
|
||||
{product.meansurement || t('dona')}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-col items-end">
|
||||
<span className="text-xs text-gray-500 mb-1">
|
||||
{t('Jami')}
|
||||
</span>
|
||||
<span className="text-base font-bold text-green-600">
|
||||
{formatPrice(
|
||||
Number(item.price) * item.quantity,
|
||||
true,
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-xs md:text-sm text-muted-foreground flex-wrap">
|
||||
<span className="flex items-center gap-1">
|
||||
<Calendar className="w-3 h-3 md:w-4 md:h-4" />
|
||||
{formatDate.format(
|
||||
order.created_at,
|
||||
'DD.MM.YYYY HH:mm',
|
||||
)}
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Order Footer */}
|
||||
<div className="bg-gradient-to-r from-gray-50 to-blue-50 p-4 border-t-2 border-gray-200">
|
||||
{/* Price Breakdown */}
|
||||
<div className="mb-4 space-y-2">
|
||||
<div className="flex justify-between text-sm text-gray-600">
|
||||
<span>{t('Mahsulotlar narxi')}:</span>
|
||||
<span className="font-semibold">
|
||||
{formatPrice(totalPrice, true)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm text-gray-600">
|
||||
<span>{t('Mahsulotlar soni')}:</span>
|
||||
<span className="font-semibold">
|
||||
{order.items.reduce(
|
||||
(sum, item) => sum + item.quantity,
|
||||
0,
|
||||
)}
|
||||
{t('dona')}
|
||||
</span>
|
||||
</div>
|
||||
<div className="border-t-2 border-dashed border-gray-300 pt-2 mt-2">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-base font-bold text-gray-800">
|
||||
{t('Umumiy summa')}:
|
||||
</span>
|
||||
<span className="text-2xl font-bold text-green-600">
|
||||
{formatPrice(totalPrice, true)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="font-bold text-base md:text-lg text-foreground">
|
||||
{formatPrice(
|
||||
order.total_price + order.delivery_price,
|
||||
true,
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{getPaymentTypeText(order.payment_type)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{order.comment && (
|
||||
<div className="mb-3 p-2 bg-slate-50 rounded-lg">
|
||||
<p className="text-xs text-muted-foreground mb-1">
|
||||
Izoh:
|
||||
</p>
|
||||
<p className="text-sm text-foreground">{order.comment}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Total Price Breakdown */}
|
||||
<div className="border-t pt-3 mb-3 space-y-1 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">
|
||||
Mahsulotlar narxi:
|
||||
</span>
|
||||
<span className="font-medium">
|
||||
{formatPrice(order.total_price, true)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Yetkazish:</span>
|
||||
<span className="font-medium">
|
||||
{formatPrice(order.delivery_price, true)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between font-bold text-base pt-1 border-t">
|
||||
<span>Jami:</span>
|
||||
<span>
|
||||
{formatPrice(
|
||||
order.total_price + order.delivery_price,
|
||||
true,
|
||||
)}
|
||||
</span>
|
||||
<div className="flex flex-col md:flex-row items-center justify-between gap-4">
|
||||
{/* Actions */}
|
||||
<div className="flex gap-2 w-full md:w-auto">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="default"
|
||||
onClick={() =>
|
||||
router.push(`/profile/refresh-order?id=${order.id}`)
|
||||
}
|
||||
className="flex-1 md:flex-none gap-2 font-semibold hover:bg-blue-50 hover:text-blue-600 hover:border-blue-600 transition-colors"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
{t('Qayta buyurtma')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
router.push('/profile/refresh-order');
|
||||
// setOrder(order);
|
||||
}}
|
||||
className="bg-transparent gap-1 md:gap-2 text-xs md:text-sm h-8 md:h-9 px-2 md:px-3"
|
||||
>
|
||||
<RefreshCw className="w-3 h-3 md:w-4 md:h-4" />
|
||||
{t('Qayta buyurtma')}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="w-full flex justify-end mt-5">
|
||||
<GlobalPagination
|
||||
onChange={handlePageChange}
|
||||
page={page}
|
||||
total={data.total_pages}
|
||||
pageSize={PAGE_SIZE}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@ import { useCartId } from '@/shared/hooks/cartId';
|
||||
import { removeToken } from '@/shared/lib/token';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/shared/ui/avatar';
|
||||
import { Button } from '@/shared/ui/button';
|
||||
import { userStore } from '@/widgets/welcome/lib/hook';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { banner_api } from '@/widgets/welcome/lib/api';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Headset, Home, LogOut } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useState } from 'react';
|
||||
@@ -17,14 +17,22 @@ const Profile = () => {
|
||||
const router = useRouter();
|
||||
const t = useTranslations();
|
||||
const queryClient = useQueryClient();
|
||||
const { user } = userStore();
|
||||
const { setCartId } = useCartId();
|
||||
|
||||
const { data: me, isError } = useQuery({
|
||||
queryKey: ['get_me'],
|
||||
queryFn: () => banner_api.getMe(),
|
||||
select(data) {
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (user === null) {
|
||||
router.replace('/auth');
|
||||
if (isError) {
|
||||
router.replace('/');
|
||||
}
|
||||
}, [user]);
|
||||
}, [isError]);
|
||||
|
||||
const { setCartId } = useCartId();
|
||||
|
||||
const menuItems = [
|
||||
{ id: 'overview', label: 'Umumiy', icon: Home },
|
||||
@@ -73,14 +81,14 @@ const Profile = () => {
|
||||
<Avatar className="w-14 h-14 ring-2 ring-emerald-500 ring-offset-2 flex items-center justify-center">
|
||||
<AvatarImage />
|
||||
<AvatarFallback className="text-muted-foreground font-semibold">
|
||||
{user?.first_name.slice(0, 1).toUpperCase()}
|
||||
{me?.first_name.slice(0, 1).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<p className="text-lg text-muted-foreground font-medium">
|
||||
{user &&
|
||||
user.first_name.charAt(0).toUpperCase() +
|
||||
user.first_name.slice(1)}
|
||||
{me &&
|
||||
me.first_name.charAt(0).toUpperCase() +
|
||||
me.first_name.slice(1)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -129,14 +137,14 @@ const Profile = () => {
|
||||
<Avatar className="w-10 h-10 md:w-12 md:h-12 ring-2 ring-emerald-500 ring-offset-2">
|
||||
<AvatarImage />
|
||||
<AvatarFallback className="text-muted-foreground font-semibold">
|
||||
{user?.first_name?.slice(0, 1).toUpperCase()}
|
||||
{me?.first_name?.slice(0, 1).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<p className="text-md md:text-xl text-muted-foreground">
|
||||
{user &&
|
||||
user.first_name.charAt(0).toUpperCase() +
|
||||
user.first_name.slice(1)}
|
||||
{me &&
|
||||
me.first_name.charAt(0).toUpperCase() +
|
||||
me.first_name.slice(1)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { cart_api, OrderCreateBody } from '@/features/cart/lib/api';
|
||||
import { orderForm } from '@/features/cart/lib/form';
|
||||
import { BASE_URL } from '@/shared/config/api/URLs';
|
||||
import formatDate from '@/shared/lib/formatDate';
|
||||
import formatPrice from '@/shared/lib/formatPrice';
|
||||
import { cn } from '@/shared/lib/utils';
|
||||
@@ -33,7 +34,7 @@ import {
|
||||
YMaps,
|
||||
ZoomControl,
|
||||
} from '@pbe/react-yandex-maps';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
Calendar as CalIcon,
|
||||
CheckCircle2,
|
||||
@@ -41,15 +42,18 @@ import {
|
||||
Loader2,
|
||||
LocateFixed,
|
||||
MapPin,
|
||||
Package,
|
||||
ShoppingBag,
|
||||
User,
|
||||
} from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import Image from 'next/image';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import z from 'zod';
|
||||
import useOrderStore from '../lib/order';
|
||||
import { order_api } from '../lib/api';
|
||||
|
||||
const deliveryTimeSlots = [
|
||||
{ id: 1, label: '09:00 - 11:00', start: '09:00', end: '11:00' },
|
||||
@@ -69,46 +73,43 @@ interface CoordsData {
|
||||
const RefreshOrder = () => {
|
||||
const [deliveryDate, setDeliveryDate] = useState<Date>();
|
||||
const [selectedTimeSlot, setSelectedTimeSlot] = useState<string>('');
|
||||
const { order: initialValues } = useOrderStore();
|
||||
const t = useTranslations();
|
||||
const queryClient = useQueryClient();
|
||||
const searchParams = useSearchParams();
|
||||
const id = searchParams.get('id');
|
||||
|
||||
const initialCartItems = initialValues?.cart_item.map((item) => ({
|
||||
id: item.id,
|
||||
product_id: item.product.id,
|
||||
product_name: item.product.name,
|
||||
product_price: item.product.prices[0].price,
|
||||
product_image: item.product.images[0].image || '/placeholder.svg',
|
||||
quantity: item.quantity,
|
||||
}));
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['order_list'],
|
||||
queryFn: () => order_api.list(),
|
||||
select: (res) => res.data,
|
||||
});
|
||||
|
||||
const cartItems = initialCartItems;
|
||||
const initialValues = data?.find((e) => e.id === Number(id));
|
||||
|
||||
const form = useForm<z.infer<typeof orderForm>>({
|
||||
resolver: zodResolver(orderForm),
|
||||
defaultValues: {
|
||||
comment: '',
|
||||
comment: initialValues?.comment || '',
|
||||
lat: '41.311081',
|
||||
long: '69.240562',
|
||||
},
|
||||
});
|
||||
|
||||
// Update form when initialValues loads
|
||||
useEffect(() => {
|
||||
if (initialValues?.comment) {
|
||||
form.setValue('comment', initialValues.comment);
|
||||
}
|
||||
}, [initialValues, form]);
|
||||
|
||||
const [orderSuccess, setOrderSuccess] = useState(false);
|
||||
|
||||
const subtotal = cartItems
|
||||
? cartItems.reduce(
|
||||
(sum, item) => sum + Number(item.product_price) * item.quantity,
|
||||
0,
|
||||
)
|
||||
: 0;
|
||||
|
||||
const total = subtotal;
|
||||
|
||||
const { mutate, isPending } = useMutation({
|
||||
mutationFn: (body: OrderCreateBody) => cart_api.createOrder(body),
|
||||
onSuccess: () => {
|
||||
setOrderSuccess(true);
|
||||
queryClient.refetchQueries({ queryKey: ['cart_items'] });
|
||||
queryClient.refetchQueries({ queryKey: ['order_list'] });
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('Xatolik yuz berdi'), {
|
||||
@@ -164,7 +165,7 @@ const RefreshOrder = () => {
|
||||
|
||||
const handleShowMyLocation = () => {
|
||||
if (!navigator.geolocation) {
|
||||
alert('Sizning brauzeringiz geolokatsiyani qo‘llab-quvvatlamaydi');
|
||||
alert("Sizning brauzeringiz geolokatsiyani qo'llab-quvvatlamaydi");
|
||||
return;
|
||||
}
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
@@ -217,15 +218,15 @@ const RefreshOrder = () => {
|
||||
return;
|
||||
}
|
||||
|
||||
if (initialValues === null) {
|
||||
toast.error(t('Savatcha bo‘sh'), {
|
||||
if (!initialValues) {
|
||||
toast.error(t('Buyurtma topilmadi'), {
|
||||
richColors: true,
|
||||
position: 'top-center',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const order_products = initialValues.cart_item
|
||||
const order_products = initialValues.items
|
||||
.filter(
|
||||
(item) =>
|
||||
item.product.prices &&
|
||||
@@ -263,6 +264,41 @@ const RefreshOrder = () => {
|
||||
});
|
||||
};
|
||||
|
||||
// Calculate total price
|
||||
const totalPrice =
|
||||
initialValues?.items.reduce(
|
||||
(sum, item) => sum + Number(item.price) * item.quantity,
|
||||
0,
|
||||
) || 0;
|
||||
|
||||
const totalItems =
|
||||
initialValues?.items.reduce((sum, item) => sum + item.quantity, 0) || 0;
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-screen">
|
||||
<Loader2 className="w-12 h-12 animate-spin text-blue-600" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!initialValues) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-screen">
|
||||
<Package className="w-20 h-20 text-gray-400 mb-4" />
|
||||
<h2 className="text-2xl font-bold text-gray-800 mb-2">
|
||||
{t('Buyurtma topilmadi')}
|
||||
</h2>
|
||||
<p className="text-gray-500 mb-6">
|
||||
{t("Ushbu buyurtma mavjud emas yoki o'chirilgan")}
|
||||
</p>
|
||||
<Button onClick={() => (window.location.href = '/profile/history')}>
|
||||
{t('Buyurtmalar tarixiga qaytish')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (orderSuccess) {
|
||||
return (
|
||||
<div className="flex justify-center items-center h-screen">
|
||||
@@ -274,7 +310,7 @@ const RefreshOrder = () => {
|
||||
{t('Buyurtma qabul qilindi!')}
|
||||
</h2>
|
||||
<p className="text-gray-500 mb-6">
|
||||
{t('Buyurtmangiz muvaffaqiyatli qabul qilindi')}
|
||||
{t('Buyurtmangiz muvaffaqiyatli qayta qabul qilindi')}
|
||||
</p>
|
||||
<button
|
||||
onClick={() => (window.location.href = '/')}
|
||||
@@ -293,9 +329,12 @@ const RefreshOrder = () => {
|
||||
{/* Header */}
|
||||
<div className="mb-6">
|
||||
<h1 className="text-3xl font-bold text-gray-800 mb-2">
|
||||
{t('Buyurtmani rasmiylashtirish')}
|
||||
{t('Buyurtmani qayta rasmiylashtirish')}
|
||||
</h1>
|
||||
<p className="text-gray-600">{t("Ma'lumotlaringizni to'ldiring")}</p>
|
||||
<p className="text-gray-600">
|
||||
{t('Buyurtma')} #{initialValues.id}{' '}
|
||||
{t("uchun ma'lumotlarni yangilang")}
|
||||
</p>
|
||||
</div>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
@@ -409,7 +448,7 @@ const RefreshOrder = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Yetkazib berish vaqti - Yangilangan versiya */}
|
||||
{/* Yetkazib berish vaqti */}
|
||||
<div className="bg-white rounded-lg shadow-md p-6">
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<Clock className="w-5 h-5 text-blue-600" />
|
||||
@@ -510,44 +549,70 @@ const RefreshOrder = () => {
|
||||
{/* Right Column - 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">{t('Mahsulotlar')}</h3>
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<ShoppingBag className="w-5 h-5 text-blue-600" />
|
||||
<h3 className="text-xl font-bold">
|
||||
{t('Buyurtma tafsilotlari')}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
{/* Cart Items */}
|
||||
<div className="space-y-3 mb-4 max-h-60 overflow-y-auto">
|
||||
{cartItems?.map((item) => (
|
||||
<div key={item.id} className="flex gap-3 pb-3 border-b">
|
||||
<Image
|
||||
width={500}
|
||||
height={500}
|
||||
src={item.product_image}
|
||||
alt={item.product_name}
|
||||
unoptimized
|
||||
className="w-16 h-16 object-contain bg-gray-100 rounded"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<h4 className="font-medium text-sm">
|
||||
{item.product_name}
|
||||
</h4>
|
||||
<p className="text-sm text-gray-500">
|
||||
{item.quantity} x{' '}
|
||||
{formatPrice(item.product_price, true)}
|
||||
</p>
|
||||
<p className="font-semibold text-sm">
|
||||
{formatPrice(
|
||||
Number(item.product_price) * item.quantity,
|
||||
true,
|
||||
)}
|
||||
</p>
|
||||
<div className="space-y-3 mb-4 max-h-96 overflow-y-auto">
|
||||
{initialValues.items.map((item) => {
|
||||
const productImage = item.product.images?.[0]?.images
|
||||
? item.product.images[0].images.includes(BASE_URL)
|
||||
? item.product.images[0].images
|
||||
: BASE_URL + item.product.images[0].images
|
||||
: '/placeholder.svg';
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
className="flex gap-3 p-3 bg-gray-50 rounded-lg border border-gray-200"
|
||||
>
|
||||
<div className="w-16 h-16 flex-shrink-0 bg-white rounded-lg overflow-hidden border">
|
||||
<Image
|
||||
src={productImage}
|
||||
alt={item.product.name}
|
||||
width={64}
|
||||
height={64}
|
||||
className="w-full h-full object-contain"
|
||||
unoptimized
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h4 className="font-semibold text-sm text-gray-900 truncate">
|
||||
{item.product.name}
|
||||
</h4>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
{item.quantity} ×{' '}
|
||||
{formatPrice(Number(item.price), true)}
|
||||
</p>
|
||||
<p className="text-sm font-bold text-blue-600 mt-1">
|
||||
{formatPrice(
|
||||
Number(item.price) * item.quantity,
|
||||
true,
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Pricing */}
|
||||
<div className="space-y-2 mb-4 pt-4 border-t">
|
||||
<div className="flex justify-between text-gray-600">
|
||||
<span>{t('Mahsulotlar')}:</span>
|
||||
<span>{subtotal && formatPrice(subtotal, true)}</span>
|
||||
<span>{t('Mahsulotlar soni')}:</span>
|
||||
<span className="font-semibold">
|
||||
{totalItems} {t('dona')}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-gray-600">
|
||||
<span>{t('Mahsulotlar narxi')}:</span>
|
||||
<span className="font-semibold">
|
||||
{formatPrice(totalPrice, true)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -556,8 +621,8 @@ const RefreshOrder = () => {
|
||||
<span className="text-lg font-semibold">
|
||||
{t('Jami')}:
|
||||
</span>
|
||||
<span className="text-2xl font-bold text-blue-600">
|
||||
{total && formatPrice(total, true)}
|
||||
<span className="text-2xl font-bold text-green-600">
|
||||
{formatPrice(totalPrice, true)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -570,6 +635,7 @@ const RefreshOrder = () => {
|
||||
{isPending ? (
|
||||
<span className="flex items-center justify-center gap-2">
|
||||
<Loader2 className="animate-spin" />
|
||||
{t('Yuklanmoqda...')}
|
||||
</span>
|
||||
) : (
|
||||
t('Buyurtmani tasdiqlash')
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { AxiosResponse } from 'axios';
|
||||
import httpClient from '../httpClient';
|
||||
import { API_URLS } from '../URLs';
|
||||
import { Category } from './type';
|
||||
import { CategoryResult } from './type';
|
||||
|
||||
export const category_api = {
|
||||
async getCategory(params: {
|
||||
page: number;
|
||||
page_size: number;
|
||||
}): Promise<AxiosResponse<Category>> {
|
||||
}): Promise<AxiosResponse<CategoryResult[]>> {
|
||||
const res = await httpClient.get(API_URLS.Category, { params });
|
||||
return res;
|
||||
},
|
||||
|
||||
@@ -9,7 +9,12 @@ export interface Category {
|
||||
}
|
||||
|
||||
export interface CategoryResult {
|
||||
id: string;
|
||||
id: number;
|
||||
name: string;
|
||||
image: string | null;
|
||||
product_types: ProductTypes[];
|
||||
}
|
||||
export interface ProductTypes {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
@@ -75,6 +75,7 @@ httpClient.interceptors.response.use(
|
||||
} catch {
|
||||
removeToken();
|
||||
removeRefToken();
|
||||
window.location.href = '/';
|
||||
}
|
||||
}
|
||||
return Promise.reject(error);
|
||||
|
||||
@@ -12,6 +12,8 @@ export const product_api = {
|
||||
async list(params: {
|
||||
page: number;
|
||||
page_size: number;
|
||||
product_type_id?: number;
|
||||
category_id?: number;
|
||||
}): Promise<AxiosResponse<ProductList>> {
|
||||
const res = await httpClient.get(`${API_URLS.Product}list/`, { params });
|
||||
return res;
|
||||
|
||||
@@ -25,6 +25,7 @@ export interface ProductListResult {
|
||||
box_quant: null | string;
|
||||
groups: number[];
|
||||
state: 'A' | 'P';
|
||||
payment_type: 'cash' | 'card' | null;
|
||||
barcodes: string;
|
||||
article_code: null | string;
|
||||
marketing_group_code: null | string;
|
||||
@@ -38,6 +39,7 @@ export interface ProductListResult {
|
||||
name: string;
|
||||
};
|
||||
}[];
|
||||
balance: number;
|
||||
}
|
||||
|
||||
export interface ProductDetail {
|
||||
@@ -55,13 +57,16 @@ export interface ProductDetail {
|
||||
litr: null | string;
|
||||
box_type_code: null | string;
|
||||
box_quant: null | string;
|
||||
groups: number[];
|
||||
groups: { id: number; name: string }[];
|
||||
state: 'A' | 'P';
|
||||
barcodes: string;
|
||||
article_code: null | string;
|
||||
marketing_group_code: null | string;
|
||||
inventory_kinds: { id: number; name: string }[];
|
||||
sector_codes: { id: number; code: string }[];
|
||||
payment_type: null | 'cash' | 'card';
|
||||
balance: number;
|
||||
updated_at: string;
|
||||
prices: {
|
||||
id: number;
|
||||
price: string;
|
||||
@@ -106,12 +111,14 @@ export interface FavouriteProductRes {
|
||||
box_type_code: null | string;
|
||||
box_quant: null | string;
|
||||
groups: number[];
|
||||
payment_type: 'cash' | 'card' | null;
|
||||
state: 'A' | 'P';
|
||||
barcodes: string;
|
||||
article_code: null | string;
|
||||
marketing_group_code: null | string;
|
||||
inventory_kinds: { id: number; name: string }[];
|
||||
sector_codes: { id: number; code: string }[];
|
||||
balance: number;
|
||||
prices: {
|
||||
id: number;
|
||||
price: string;
|
||||
|
||||
@@ -204,5 +204,25 @@
|
||||
"Tez-tez So'raladigan Savollar": "Часто задаваемые вопросы",
|
||||
"Gastro Market haqida eng ko'p so'raladigan savollarga javoblar": "Ответы на самые часто задаваемые вопросы о Gastro Market",
|
||||
|
||||
"Barcha mahsulotlar": "Все товары"
|
||||
"Barcha mahsulotlar": "Все товары",
|
||||
"Xatolik yuz berdi: Mahsulot omborxonada yetarli emas": "Произошла ошибка: недостаточно товаров на складе",
|
||||
"Bu kategoriyada hozircha mahsulot yo‘q": "В этой категории пока нет товаров",
|
||||
"Tez orada qo‘shiladi": "Скоро будет добавлено",
|
||||
"Hozirchali bu kategoriyada mahsulot yo'q": "Пока нет товаров в этой категории",
|
||||
"Kataloglar": "Каталог",
|
||||
|
||||
"Naqd bilan olinadi": "Получено наличными",
|
||||
"Pul o'tkazish yo'li bilan olinadi": "Получено путём перевода денег",
|
||||
"Diqqat! Mahsulot narxi o'zgargan bo'lishi mumkin": "Внимание! Цена продукта может измениться",
|
||||
"So'nggi yangilanish:": "Последнее обновление",
|
||||
"only_available": "Доступно только {maxBalance} штук",
|
||||
"Buyurtmalar topilmadi": "Заказов не найдено",
|
||||
"Hali buyurtma qilmagansiz": "Вы ещё не сделали заказ",
|
||||
"ta buyurtma": "Заказы",
|
||||
"Mahsulotlar soni": "Количество товаров",
|
||||
"dona": "шт",
|
||||
"Umumiy summa": "Общая сумма",
|
||||
"Qayta buyurtma": "Заказать заново",
|
||||
"Yangilangan": "Обновлено",
|
||||
"Narxi o'zgargan bo'lishi mumkin": "Цена может быть изменена"
|
||||
}
|
||||
|
||||
@@ -204,5 +204,25 @@ declare const messages: {
|
||||
"Gastro Market haqida eng ko'p so'raladigan savollarga javoblar": "Gastro Market haqida eng ko'p so'raladigan savollarga javoblar";
|
||||
|
||||
'Barcha mahsulotlar': 'Barcha mahsulotlar';
|
||||
'Xatolik yuz berdi: Mahsulot omborxonada yetarli emas': 'Xatolik yuz berdi: Mahsulot omborxonada yetarli emas';
|
||||
'Bu kategoriyada hozircha mahsulot yo‘q': 'Bu kategoriyada hozircha mahsulot yo‘q';
|
||||
'Tez orada qo‘shiladi': 'Tez orada qo‘shiladi';
|
||||
"Hozirchali bu kategoriyada mahsulot yo'q": "Hozirchali bu kategoriyada mahsulot yo'q";
|
||||
Kataloglar: 'Kataloglar';
|
||||
'Naqd bilan olinadi': 'Naqd bilan olinadi';
|
||||
"Pul o'tkazish yo'li bilan olinadi": "Pul o'tkazish yo'li bilan olinadi";
|
||||
|
||||
"Diqqat! Mahsulot narxi o'zgargan bo'lishi mumkin": "Diqqat! Mahsulot narxi o'zgargan bo'lishi mumkin";
|
||||
"So'nggi yangilanish:": "So'nggi yangilanish";
|
||||
only_available: 'Faqat {maxBalance} dona mavjud';
|
||||
'Buyurtmalar topilmadi': 'Buyurtmalar topilmadi';
|
||||
'Hali buyurtma qilmagansiz': 'Hali buyurtma qilmagansiz';
|
||||
'ta buyurtma': 'ta buyurtma';
|
||||
'Mahsulotlar soni': 'Mahsulotlar soni';
|
||||
dona: 'dona';
|
||||
'Umumiy summa': 'Umumiy summa';
|
||||
'Qayta buyurtma': 'Qayta buyurtma';
|
||||
Yangilangan: 'Yangilangan';
|
||||
"Narxi o'zgargan bo'lishi mumkin": "Narxi o'zgargan bo'lishi mumkin";
|
||||
};
|
||||
export default messages;
|
||||
|
||||
@@ -200,5 +200,25 @@
|
||||
"Tez-tez So'raladigan Savollar": "Tez-tez So'raladigan Savollar",
|
||||
"Gastro Market haqida eng ko'p so'raladigan savollarga javoblar": "Gastro Market haqida eng ko'p so'raladigan savollarga javoblar",
|
||||
|
||||
"Barcha mahsulotlar": "Barcha mahsulotlar"
|
||||
"Barcha mahsulotlar": "Barcha mahsulotlar",
|
||||
"Xatolik yuz berdi: Mahsulot omborxonada yetarli emas": "Xatolik yuz berdi: Mahsulot omborxonada yetarli emas",
|
||||
"Bu kategoriyada hozircha mahsulot yo‘q": "Bu kategoriyada hozircha mahsulot yo‘q",
|
||||
"Tez orada qo‘shiladi": "Tez orada qo‘shiladi",
|
||||
"Hozirchali bu kategoriyada mahsulot yo'q": "Hozirchali bu kategoriyada mahsulot yo'q",
|
||||
"Kataloglar": "Kataloglar",
|
||||
"Naqd bilan olinadi": "Naqd bilan olinadi",
|
||||
"Pul o'tkazish yo'li bilan olinadi": "Pul o'tkazish yo'li bilan olinadi",
|
||||
|
||||
"Diqqat! Mahsulot narxi o'zgargan bo'lishi mumkin": "Diqqat! Mahsulot narxi o'zgargan bo'lishi mumkin",
|
||||
"So'nggi yangilanish:": "So'nggi yangilanish",
|
||||
"only_available": "Faqat {maxBalance} dona mavjud",
|
||||
"Buyurtmalar topilmadi": "Buyurtmalar topilmadi",
|
||||
"Hali buyurtma qilmagansiz": "Hali buyurtma qilmagansiz",
|
||||
"ta buyurtma": "ta buyurtma",
|
||||
"Mahsulotlar soni": "Mahsulotlar soni",
|
||||
"dona": "dona",
|
||||
"Umumiy summa": "Umumiy summa",
|
||||
"Qayta buyurtma": "Qayta buyurtma",
|
||||
"Yangilangan": "Yangilangan",
|
||||
"Narxi o'zgargan bo'lishi mumkin": "Narxi o'zgargan bo'lishi mumkin"
|
||||
}
|
||||
|
||||
358
src/widgets/categories/ui/CategoryAccordion.tsx
Normal file
358
src/widgets/categories/ui/CategoryAccordion.tsx
Normal file
@@ -0,0 +1,358 @@
|
||||
'use client';
|
||||
|
||||
import { CategoryResult } from '@/shared/config/api/category/type';
|
||||
import { product_api } from '@/shared/config/api/product/api';
|
||||
import { useRouter } from '@/shared/config/i18n/navigation';
|
||||
import { cn } from '@/shared/lib/utils';
|
||||
import { Button } from '@/shared/ui/button';
|
||||
import {
|
||||
Carousel,
|
||||
CarouselContent,
|
||||
CarouselItem,
|
||||
type CarouselApi,
|
||||
} from '@/shared/ui/carousel';
|
||||
import { ProductCard } from '@/widgets/categories/ui/product-card';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { ChevronDown, ChevronLeft, ChevronRight, Package } from 'lucide-react';
|
||||
import { memo, useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
interface CategoryAccordionProps {
|
||||
category: CategoryResult;
|
||||
}
|
||||
|
||||
const CategoryAccordion = memo(function CategoryAccordion({
|
||||
category,
|
||||
}: CategoryAccordionProps) {
|
||||
const router = useRouter();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [carousels, setCarousels] = useState<Map<string, CarouselApi>>(
|
||||
new Map(),
|
||||
);
|
||||
const [scrollStates, setScrollStates] = useState<
|
||||
Map<string, { prev: boolean; next: boolean }>
|
||||
>(new Map());
|
||||
|
||||
// Ref to track if event listeners are already attached
|
||||
const listenersAttached = useRef<Set<string>>(new Set());
|
||||
|
||||
const toggle = useCallback(() => setIsOpen((prev) => !prev), []);
|
||||
|
||||
// Separate effect to handle carousel listeners
|
||||
useEffect(() => {
|
||||
if (carousels.size === 0) return;
|
||||
|
||||
const updateScrollState = (subId: string, api: CarouselApi) => {
|
||||
if (!api) return; // Guard clause
|
||||
|
||||
setScrollStates((prev) => {
|
||||
const newMap = new Map(prev);
|
||||
newMap.set(subId, {
|
||||
prev: api.canScrollPrev(),
|
||||
next: api.canScrollNext(),
|
||||
});
|
||||
return newMap;
|
||||
});
|
||||
};
|
||||
|
||||
const cleanupFunctions: (() => void)[] = [];
|
||||
|
||||
carousels.forEach((api, subId) => {
|
||||
// Skip if api is undefined or listeners already attached
|
||||
if (!api || listenersAttached.current.has(subId)) return;
|
||||
|
||||
const handleUpdate = () => updateScrollState(subId, api);
|
||||
|
||||
// Initial update
|
||||
handleUpdate();
|
||||
|
||||
// Attach listeners
|
||||
api.on('select', handleUpdate);
|
||||
api.on('reInit', handleUpdate);
|
||||
|
||||
// Mark as attached
|
||||
listenersAttached.current.add(subId);
|
||||
|
||||
// Cleanup function
|
||||
cleanupFunctions.push(() => {
|
||||
api.off('select', handleUpdate);
|
||||
api.off('reInit', handleUpdate);
|
||||
listenersAttached.current.delete(subId);
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
cleanupFunctions.forEach((cleanup) => cleanup());
|
||||
};
|
||||
}, [carousels]);
|
||||
|
||||
const handleSetApi = useCallback(
|
||||
(subId: string, api: CarouselApi | undefined) => {
|
||||
if (!api) return;
|
||||
|
||||
setCarousels((prev) => {
|
||||
// Only update if this is a new or different API
|
||||
const existing = prev.get(subId);
|
||||
if (existing === api) return prev;
|
||||
|
||||
const newMap = new Map(prev);
|
||||
newMap.set(subId, api);
|
||||
return newMap;
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const scrollPrev = useCallback(
|
||||
(subId: string) => {
|
||||
const api = carousels.get(subId);
|
||||
if (api) {
|
||||
api.scrollPrev();
|
||||
}
|
||||
},
|
||||
[carousels],
|
||||
);
|
||||
|
||||
const scrollNext = useCallback(
|
||||
(subId: string) => {
|
||||
const api = carousels.get(subId);
|
||||
if (api) {
|
||||
api.scrollNext();
|
||||
}
|
||||
},
|
||||
[carousels],
|
||||
);
|
||||
|
||||
const { data: productsData, isLoading } = useQuery({
|
||||
queryKey: ['category_products', category.id],
|
||||
queryFn: async () => {
|
||||
const results = await Promise.all(
|
||||
category.product_types.map((sub) =>
|
||||
product_api.list({ page: 1, page_size: 16, product_type_id: sub.id }),
|
||||
),
|
||||
);
|
||||
return results.map((r, i) => ({
|
||||
subCategory: category.product_types[i],
|
||||
products: r.data.results.filter((p) => p.state === 'A'),
|
||||
}));
|
||||
},
|
||||
enabled: isOpen,
|
||||
staleTime: 5 * 60 * 1000,
|
||||
});
|
||||
|
||||
return (
|
||||
<section className="custom-container mt-8 mb-6">
|
||||
{/* Header */}
|
||||
<div
|
||||
className={cn(
|
||||
'group relative overflow-hidden cursor-pointer',
|
||||
'bg-gradient-to-br from-white via-blue-50 to-indigo-50',
|
||||
'hover:from-blue-50 hover:via-blue-100 hover:to-indigo-100',
|
||||
'border border-slate-200 rounded-2xl transition-all duration-500 ease-in-out',
|
||||
'shadow-sm hover:shadow-lg',
|
||||
isOpen &&
|
||||
'border-blue-400 shadow-xl bg-gradient-to-br from-blue-50 to-indigo-50',
|
||||
)}
|
||||
onClick={toggle}
|
||||
>
|
||||
<div className="flex justify-between items-center p-6 sm:p-8">
|
||||
<div className="flex items-center gap-4">
|
||||
<div
|
||||
className={cn(
|
||||
'p-3.5 rounded-xl transition-all duration-500 transform',
|
||||
'bg-white shadow-md',
|
||||
'group-hover:bg-gradient-to-br group-hover:from-blue-100 group-hover:to-indigo-100 group-hover:shadow-lg group-hover:scale-110',
|
||||
isOpen &&
|
||||
'bg-gradient-to-br from-blue-200 to-indigo-200 shadow-lg scale-110',
|
||||
)}
|
||||
>
|
||||
<Package
|
||||
className={cn(
|
||||
'size-6 transition-all duration-500',
|
||||
'text-slate-700',
|
||||
'group-hover:text-blue-700',
|
||||
isOpen && 'text-blue-700',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h2
|
||||
className={cn(
|
||||
'text-xl sm:text-3xl font-bold transition-all duration-300',
|
||||
'text-slate-900',
|
||||
'group-hover:text-blue-800',
|
||||
isOpen && 'text-blue-800',
|
||||
)}
|
||||
>
|
||||
{category.name}
|
||||
</h2>
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<span className="inline-flex items-center gap-1 px-3 py-1 rounded-full bg-slate-100 group-hover:bg-blue-100 transition-colors">
|
||||
<span className="text-xs sm:text-sm font-semibold text-slate-700 group-hover:text-blue-700">
|
||||
{category.product_types.length}
|
||||
</span>
|
||||
<span className="text-xs sm:text-sm text-slate-600 group-hover:text-blue-600">
|
||||
kategoriya
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'p-3 rounded-full transition-all duration-500 transform',
|
||||
'bg-white shadow-md',
|
||||
'group-hover:bg-blue-100 group-hover:shadow-lg group-hover:scale-125',
|
||||
isOpen && 'bg-blue-200 shadow-lg scale-125',
|
||||
)}
|
||||
>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
'size-6 transition-all duration-500',
|
||||
'text-slate-700',
|
||||
'group-hover:text-blue-700',
|
||||
isOpen ? 'rotate-180 text-blue-700' : 'rotate-0',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'h-1.5 bg-gradient-to-r from-blue-600 via-indigo-600 to-purple-600 transition-all duration-500',
|
||||
'scale-x-0 group-hover:scale-x-100',
|
||||
isOpen && 'scale-x-100',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div
|
||||
className={cn(
|
||||
'overflow-hidden transition-all duration-700 ease-in-out',
|
||||
isOpen ? 'max-h-[10000px] opacity-100 mt-6' : 'max-h-0 opacity-0',
|
||||
)}
|
||||
>
|
||||
{isLoading ? (
|
||||
<div className="space-y-8">
|
||||
{Array.from({ length: 2 }).map((_, idx) => (
|
||||
<div key={idx} className="space-y-4">
|
||||
<div className="h-7 w-56 bg-gradient-to-r from-slate-200 to-slate-100 rounded-lg animate-pulse" />
|
||||
<div className="flex gap-4 overflow-hidden">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="flex-shrink-0 w-44 h-72 bg-gradient-to-br from-slate-100 to-slate-50 rounded-2xl animate-pulse"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-10 pb-8">
|
||||
{productsData?.map((sub) => {
|
||||
if (!sub.products.length) return null;
|
||||
|
||||
const subId = sub.subCategory.id.toString();
|
||||
const scrollState = scrollStates.get(subId) || {
|
||||
prev: false,
|
||||
next: false,
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
key={sub.subCategory.id}
|
||||
className="bg-gradient-to-br from-white to-slate-50 rounded-2xl border border-slate-200 p-6 sm:p-8 shadow-md hover:shadow-xl transition-all duration-300"
|
||||
>
|
||||
{/* Subcategory Header */}
|
||||
<div className="flex items-center justify-between mb-6 pb-4 border-b border-slate-200">
|
||||
<div
|
||||
className="flex items-center gap-3 group/title cursor-pointer flex-1"
|
||||
onClick={() =>
|
||||
router.push(
|
||||
`/category/${category.id}/${sub.subCategory.id}/`,
|
||||
)
|
||||
}
|
||||
>
|
||||
<div className="w-1.5 h-8 bg-gradient-to-b from-blue-600 to-indigo-600 rounded-full"></div>
|
||||
<h3 className="text-xl sm:text-2xl font-bold text-slate-900 group-hover/title:text-blue-700 transition-all duration-300">
|
||||
{sub.subCategory.name}
|
||||
</h3>
|
||||
<div className="p-2 bg-slate-100 rounded-lg group-hover/title:bg-blue-100 transition-all duration-300 ml-auto sm:ml-0">
|
||||
<ChevronRight className="size-5 text-slate-600 group-hover/title:text-blue-600 group-hover/title:translate-x-1 transition-all duration-300" />
|
||||
</div>
|
||||
</div>
|
||||
<span className="inline-flex items-center gap-2 px-4 py-2 bg-blue-50 rounded-full border border-blue-200 ml-4">
|
||||
<span className="text-sm font-bold text-blue-700">
|
||||
{sub.products.length}
|
||||
</span>
|
||||
<span className="text-sm text-blue-600">mahsulot</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Carousel */}
|
||||
<div className="relative">
|
||||
<Carousel
|
||||
className="w-full"
|
||||
setApi={(api) => handleSetApi(subId, api)}
|
||||
>
|
||||
<CarouselContent className="pr-[12%] sm:pr-0 -ml-3">
|
||||
{sub.products.map((product) => (
|
||||
<CarouselItem
|
||||
key={product.id}
|
||||
className="pl-3 basis-1/2 sm:basis-1/3 md:basis-1/4 lg:basis-1/5 xl:basis-1/6"
|
||||
>
|
||||
<ProductCard product={product} />
|
||||
</CarouselItem>
|
||||
))}
|
||||
</CarouselContent>
|
||||
</Carousel>
|
||||
|
||||
{/* Navigation Buttons */}
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
scrollNext(subId);
|
||||
}}
|
||||
className={cn(
|
||||
'absolute -top-16 right-4 max-lg:hidden text-white shadow-xl transition-all duration-300 transform hover:scale-110 active:scale-95',
|
||||
scrollState.next
|
||||
? 'bg-gradient-to-br from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700'
|
||||
: 'bg-slate-300 cursor-not-allowed opacity-40',
|
||||
)}
|
||||
disabled={!scrollState.next}
|
||||
size="icon"
|
||||
aria-label="next products"
|
||||
>
|
||||
<ChevronRight className="size-6" />
|
||||
</Button>
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
scrollPrev(subId);
|
||||
}}
|
||||
className={cn(
|
||||
'absolute -top-16 right-16 max-lg:hidden text-white shadow-xl transition-all duration-300 transform hover:scale-110 active:scale-95',
|
||||
scrollState.prev
|
||||
? 'bg-gradient-to-br from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700'
|
||||
: 'bg-slate-300 cursor-not-allowed opacity-40',
|
||||
)}
|
||||
disabled={!scrollState.prev}
|
||||
size="icon"
|
||||
aria-label="previous products"
|
||||
>
|
||||
<ChevronLeft className="size-6" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
});
|
||||
|
||||
export default CategoryAccordion;
|
||||
@@ -1,77 +1,112 @@
|
||||
'use client';
|
||||
|
||||
import { CategoryResult } from '@/shared/config/api/category/type';
|
||||
import { ProductTypes } from '@/shared/config/api/category/type';
|
||||
import { product_api } from '@/shared/config/api/product/api';
|
||||
import { useRouter } from '@/shared/config/i18n/navigation';
|
||||
import { cn } from '@/shared/lib/utils';
|
||||
import { Button } from '@/shared/ui/button';
|
||||
import { Card } from '@/shared/ui/card';
|
||||
import {
|
||||
Carousel,
|
||||
CarouselApi,
|
||||
CarouselContent,
|
||||
CarouselItem,
|
||||
type CarouselApi,
|
||||
} from '@/shared/ui/carousel';
|
||||
import { Skeleton } from '@/shared/ui/skeleton';
|
||||
import { ProductCard } from '@/widgets/categories/ui/product-card';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { ProductCard } from './product-card';
|
||||
import { memo, useEffect, useRef, useState } from 'react';
|
||||
|
||||
export function CategoryCarousel({ category }: { category: CategoryResult }) {
|
||||
//////////////////////////
|
||||
/// CategoryCarousel optimized
|
||||
//////////////////////////
|
||||
interface CategoryCarouselProps {
|
||||
category: ProductTypes;
|
||||
}
|
||||
|
||||
const CategoryCarousel = memo(function CategoryCarousel({
|
||||
category,
|
||||
}: CategoryCarouselProps) {
|
||||
const router = useRouter();
|
||||
const [api, setApi] = useState<CarouselApi>();
|
||||
const [canScrollPrev, setCanScrollPrev] = useState(false);
|
||||
const [canScrollNext, setCanScrollNext] = useState(false);
|
||||
const [isVisible, setIsVisible] = useState(false);
|
||||
const sectionRef = useRef<HTMLElement>(null);
|
||||
|
||||
// Intersection Observer
|
||||
useEffect(() => {
|
||||
if (!sectionRef.current) return;
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
entries.forEach((entry) => {
|
||||
if (entry.isIntersecting) {
|
||||
setIsVisible(true);
|
||||
observer.disconnect();
|
||||
}
|
||||
});
|
||||
},
|
||||
{ rootMargin: '100px', threshold: 0.1 },
|
||||
);
|
||||
|
||||
observer.observe(sectionRef.current);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
// Carousel buttons
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
|
||||
const updateButtons = () => {
|
||||
setCanScrollPrev(api.canScrollPrev());
|
||||
setCanScrollNext(api.canScrollNext());
|
||||
};
|
||||
|
||||
updateButtons();
|
||||
api.on('select', updateButtons);
|
||||
api.on('reInit', updateButtons);
|
||||
|
||||
return () => {
|
||||
api.off('select', updateButtons);
|
||||
api.off('reInit', updateButtons);
|
||||
};
|
||||
}, [api]);
|
||||
|
||||
const scrollPrev = () => {
|
||||
if (api) {
|
||||
api?.scrollPrev();
|
||||
}
|
||||
};
|
||||
|
||||
const scrollNext = () => {
|
||||
if (api) {
|
||||
api?.scrollNext();
|
||||
}
|
||||
};
|
||||
const scrollPrev = () => api?.scrollPrev();
|
||||
const scrollNext = () => api?.scrollNext();
|
||||
|
||||
// React Query
|
||||
const { data: product, isLoading } = useQuery({
|
||||
queryKey: ['product_list', category],
|
||||
queryKey: ['product_list', category.id],
|
||||
queryFn: () =>
|
||||
product_api.listGetCategoryId({
|
||||
product_api.list({
|
||||
page: 1,
|
||||
page_size: 16,
|
||||
category_id: category.id,
|
||||
params: { page: 1, page_size: 16 },
|
||||
}),
|
||||
select(data) {
|
||||
return data.data;
|
||||
},
|
||||
select: (data) => data.data,
|
||||
enabled: isVisible,
|
||||
});
|
||||
|
||||
if (product?.results.length === 0) {
|
||||
return null;
|
||||
// Shartli renderlar
|
||||
if (!isVisible) {
|
||||
return (
|
||||
<section
|
||||
ref={sectionRef}
|
||||
className="relative custom-container mt-5 min-h-[300px]"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isLoading && (!product || product.results.length === 0)) return null;
|
||||
|
||||
const activeProducts = product?.results.filter((p) => p.state === 'A') ?? [];
|
||||
if (!isLoading && activeProducts.length === 0) return null;
|
||||
|
||||
if (isLoading) return null;
|
||||
|
||||
return (
|
||||
<section className="relative custom-container mt-5 justify-center items-center border-b border-slate-200">
|
||||
<section
|
||||
ref={sectionRef}
|
||||
className="relative custom-container mt-5 justify-center items-center border-b border-slate-200"
|
||||
>
|
||||
<div className="flex items-center justify-between pb-3">
|
||||
<div
|
||||
className="flex items-center gap-2 group cursor-pointer"
|
||||
@@ -88,34 +123,17 @@ export function CategoryCarousel({ category }: { category: CategoryResult }) {
|
||||
|
||||
<Carousel className="w-full mt-2" setApi={setApi}>
|
||||
<CarouselContent className="pr-[12%] sm:pr-0">
|
||||
{isLoading &&
|
||||
Array.from({ length: 6 }).map((__, index) => (
|
||||
<CarouselItem
|
||||
key={index}
|
||||
className="basis-1/2 sm:basis-1/3 md:basis-1/4 lg:basis-1/5 xl:basis-1/6 pb-2"
|
||||
>
|
||||
<Card className="p-3 space-y-3 rounded-xl">
|
||||
<Skeleton className="h-40 sm:h-48 md:h-56 w-full rounded-lg" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-4 w-1/2" />
|
||||
<Skeleton className="h-10 w-full rounded-lg" />
|
||||
</Card>
|
||||
</CarouselItem>
|
||||
))}
|
||||
{product &&
|
||||
!isLoading &&
|
||||
product.results
|
||||
.filter((product) => product.state === 'A')
|
||||
.map((product) => (
|
||||
<CarouselItem
|
||||
key={product.id}
|
||||
className="basis-1/2 sm:basis-1/3 md:basis-1/4 lg:basis-1/5 xl:basis-1/6 pb-2"
|
||||
>
|
||||
<ProductCard product={product} />
|
||||
</CarouselItem>
|
||||
))}
|
||||
{activeProducts.map((product) => (
|
||||
<CarouselItem
|
||||
key={product.id}
|
||||
className="basis-1/2 sm:basis-1/3 md:basis-1/4 lg:basis-1/5 xl:basis-1/6 pb-2"
|
||||
>
|
||||
<ProductCard product={product} />
|
||||
</CarouselItem>
|
||||
))}
|
||||
</CarouselContent>
|
||||
</Carousel>
|
||||
|
||||
<Button
|
||||
onClick={scrollNext}
|
||||
className={cn(
|
||||
@@ -138,7 +156,6 @@ export function CategoryCarousel({ category }: { category: CategoryResult }) {
|
||||
? 'bg-green-600 hover:bg-green-600/70'
|
||||
: 'bg-green-600/50 cursor-not-allowed',
|
||||
)}
|
||||
aria-label="prev images"
|
||||
disabled={!canScrollPrev}
|
||||
size="icon"
|
||||
>
|
||||
@@ -146,4 +163,6 @@ export function CategoryCarousel({ category }: { category: CategoryResult }) {
|
||||
</Button>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
export default CategoryCarousel;
|
||||
|
||||
@@ -42,7 +42,7 @@ export function ProductCard({
|
||||
const debounceRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const imageRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { mutate } = useMutation({
|
||||
const { mutate: addToCart } = useMutation({
|
||||
mutationFn: (body: { product: string; quantity: number; cart: string }) =>
|
||||
cart_api.cart_item(body),
|
||||
onSuccess: () => {
|
||||
@@ -57,6 +57,7 @@ export function ProductCard({
|
||||
});
|
||||
},
|
||||
});
|
||||
const maxBalance = product.balance ?? 0;
|
||||
|
||||
const { mutate: updateCartItem } = useMutation({
|
||||
mutationFn: ({
|
||||
@@ -120,24 +121,6 @@ export function ProductCard({
|
||||
},
|
||||
});
|
||||
|
||||
const increase = (e: MouseEvent<HTMLButtonElement>) => {
|
||||
e.stopPropagation();
|
||||
const newQty = (quantity === '' ? 0 : quantity) + 1;
|
||||
setQuantity(newQty);
|
||||
|
||||
if (newQty > 1) {
|
||||
const cartItemId = cartItems?.data?.cart_item.find(
|
||||
(item) => Number(item.product.id) === product.id,
|
||||
)?.id;
|
||||
if (cartItemId) {
|
||||
updateCartItem({
|
||||
body: { quantity: newQty },
|
||||
cart_item_id: cartItemId.toString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const decrease = (e: MouseEvent<HTMLButtonElement>) => {
|
||||
e.stopPropagation();
|
||||
|
||||
@@ -165,6 +148,35 @@ export function ProductCard({
|
||||
});
|
||||
};
|
||||
|
||||
const getCartItemId = () =>
|
||||
cartItems?.data.cart_item.find(
|
||||
(item) => Number(item.product.id) === product.id,
|
||||
)?.id;
|
||||
|
||||
const increase = (e: MouseEvent<HTMLButtonElement>) => {
|
||||
e.stopPropagation();
|
||||
|
||||
const current = quantity === '' ? 0 : quantity;
|
||||
|
||||
if (current >= maxBalance) {
|
||||
toast.warning(t(`Faqat ${maxBalance} dona mavjud`), {
|
||||
richColors: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const newQty = current + 1;
|
||||
setQuantity(newQty);
|
||||
|
||||
const id = getCartItemId();
|
||||
if (id) {
|
||||
updateCartItem({
|
||||
cart_item_id: id.toString(),
|
||||
body: { quantity: newQty },
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Card className="p-4 rounded-xl">
|
||||
@@ -257,18 +269,25 @@ export function ProductCard({
|
||||
)} */}
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-3 sm:p-4 pt-0">
|
||||
<div className="p-4 pt-0">
|
||||
{quantity === 0 ? (
|
||||
<Button
|
||||
disabled={maxBalance <= 0}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
mutate({
|
||||
|
||||
if (maxBalance <= 0) {
|
||||
toast.error(t('Mahsulot mavjud emas'));
|
||||
return;
|
||||
}
|
||||
|
||||
addToCart({
|
||||
product: String(product.id),
|
||||
quantity: 1,
|
||||
cart: cart_id!,
|
||||
});
|
||||
}}
|
||||
className="w-full h-9 sm:h-11 text-sm bg-green-600 hover:bg-green-600/80"
|
||||
className="w-full bg-green-600"
|
||||
>
|
||||
<ShoppingCart className="w-4 h-4 mr-1" />
|
||||
{t('Savatga')}
|
||||
@@ -276,61 +295,62 @@ export function ProductCard({
|
||||
) : (
|
||||
<div
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="flex items-center justify-between border border-green-500 rounded-lg h-9 sm:h-11"
|
||||
className="flex items-center justify-between border border-green-500 rounded-lg h-10"
|
||||
>
|
||||
<Button size="icon" variant="ghost" onClick={decrease}>
|
||||
<Minus className="w-4 h-4" />
|
||||
<Minus />
|
||||
</Button>
|
||||
|
||||
<Input
|
||||
value={quantity}
|
||||
className="border-none text-center focus-visible:border-none focus-visible:ring-0"
|
||||
className="border-none text-center"
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
|
||||
// ❌ faqat raqam
|
||||
if (!/^\d*$/.test(v)) return;
|
||||
|
||||
// ⛔ oldingi debounce'ni tozalaymiz
|
||||
if (debounceRef.current) {
|
||||
clearTimeout(debounceRef.current);
|
||||
}
|
||||
|
||||
// bo‘sh input — faqat UI
|
||||
if (v === '') {
|
||||
setQuantity('');
|
||||
return;
|
||||
}
|
||||
|
||||
const num = Number(v);
|
||||
let num = Number(v);
|
||||
if (num > maxBalance) {
|
||||
num = maxBalance;
|
||||
toast.warning(t(`Maksimal ${maxBalance} dona`), {
|
||||
richColors: true,
|
||||
});
|
||||
}
|
||||
|
||||
setQuantity(num);
|
||||
|
||||
if (!cartItems) return;
|
||||
const id = getCartItemId();
|
||||
if (!id) return;
|
||||
|
||||
const cartItemId = cartItems.data.cart_item.find(
|
||||
(item) => Number(item.product.id) === product.id,
|
||||
)?.id;
|
||||
|
||||
if (!cartItemId) return;
|
||||
|
||||
// ❗ 0 bo‘lsa — DELETE (darhol)
|
||||
if (num === 0) {
|
||||
deleteCartItem({ cart_item_id: cartItemId.toString() });
|
||||
deleteCartItem({ cart_item_id: id.toString() });
|
||||
return;
|
||||
}
|
||||
|
||||
// 🕒 debounce bilan UPDATE
|
||||
debounceRef.current = setTimeout(() => {
|
||||
updateCartItem({
|
||||
cart_item_id: id.toString(),
|
||||
body: { quantity: num },
|
||||
cart_item_id: cartItemId.toString(),
|
||||
});
|
||||
}, 500);
|
||||
}}
|
||||
/>
|
||||
|
||||
<Button size="icon" variant="ghost" onClick={increase}>
|
||||
<Plus className="w-4 h-4" />
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
onClick={increase}
|
||||
disabled={Number(quantity) >= maxBalance}
|
||||
>
|
||||
<Plus />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -14,7 +14,7 @@ const Footer = () => {
|
||||
queryKey: ['category_list'],
|
||||
queryFn: () => category_api.getCategory({ page: 1, page_size: 12 }),
|
||||
select(data) {
|
||||
return data.data.results;
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { CategoryType } from '@/widgets/welcome/lib/data';
|
||||
import { CategoryResult } from '@/shared/config/api/category/type';
|
||||
import { create } from 'zustand';
|
||||
|
||||
type Category = {
|
||||
active: CategoryType | null;
|
||||
active: CategoryResult | null;
|
||||
openToolbar: boolean;
|
||||
};
|
||||
|
||||
type Actions = {
|
||||
setActive: (active: CategoryType | null) => void;
|
||||
setActive: (active: CategoryResult | null) => void;
|
||||
setOpenToolbar: (openToolbar: boolean) => void;
|
||||
setCloseToolbar: (openToolbar: boolean) => void;
|
||||
};
|
||||
@@ -15,7 +15,7 @@ type Actions = {
|
||||
const useCategoryActive = create<Category & Actions>((set) => ({
|
||||
active: null,
|
||||
openToolbar: false,
|
||||
setActive: (active: CategoryType | null) => set(() => ({ active })),
|
||||
setActive: (active: CategoryResult | null) => set(() => ({ active })),
|
||||
setOpenToolbar: () => set(() => ({ openToolbar: true })),
|
||||
setCloseToolbar: () => set(() => ({ openToolbar: false })),
|
||||
}));
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { cart_api } from '@/features/cart/lib/api';
|
||||
import { category_api } from '@/shared/config/api/category/api';
|
||||
import { Link, useRouter } from '@/shared/config/i18n/navigation';
|
||||
import { useCartId } from '@/shared/hooks/cartId';
|
||||
import formatPhone from '@/shared/lib/formatPhone';
|
||||
@@ -18,7 +19,6 @@ import {
|
||||
SheetTrigger,
|
||||
} from '@/shared/ui/sheet';
|
||||
import { banner_api } from '@/widgets/welcome/lib/api';
|
||||
import { categoryList } from '@/widgets/welcome/lib/data';
|
||||
import { userStore } from '@/widgets/welcome/lib/hook';
|
||||
import { PopoverTrigger } from '@radix-ui/react-popover';
|
||||
import { useMutation, useQuery } from '@tanstack/react-query';
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
Facebook,
|
||||
Heart,
|
||||
Instagram,
|
||||
LayoutGrid,
|
||||
Mail,
|
||||
MenuIcon,
|
||||
Phone,
|
||||
@@ -35,6 +36,7 @@ import {
|
||||
ShoppingCart,
|
||||
Twitter,
|
||||
User,
|
||||
XIcon,
|
||||
} from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import Image from 'next/image';
|
||||
@@ -69,6 +71,14 @@ const Navbar = () => {
|
||||
queryFn: () => banner_api.getMe(),
|
||||
});
|
||||
|
||||
const { data: category } = useQuery({
|
||||
queryKey: ['category_list'],
|
||||
queryFn: () => category_api.getCategory({ page: 1, page_size: 99 }),
|
||||
select(data) {
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (me) {
|
||||
setUser(me.data);
|
||||
@@ -392,7 +402,7 @@ const Navbar = () => {
|
||||
</Sheet>
|
||||
</div>
|
||||
<div className="flex-1 flex gap-3">
|
||||
{/* <Button
|
||||
<Button
|
||||
variant={'outline'}
|
||||
className="h-10 max-lg:hidden cursor-pointer"
|
||||
onClick={() => {
|
||||
@@ -408,8 +418,8 @@ const Navbar = () => {
|
||||
) : (
|
||||
<LayoutGrid className="size-4 text-foreground" />
|
||||
)}
|
||||
<p className="text-foreground">Kataloglar</p>
|
||||
</Button> */}
|
||||
<p className="text-foreground">{t('Kataloglar')}</p>
|
||||
</Button>
|
||||
|
||||
<div className="relative w-full max-lg:hidden">
|
||||
<Input
|
||||
@@ -483,54 +493,58 @@ const Navbar = () => {
|
||||
<div />
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
className="w-[100vw] !p-0 h-[100vh] rounded-b-xl border-t-2 border-blue-500"
|
||||
className="w-[100vw] !p-0 h-[100vh] rounded-b-xl"
|
||||
onInteractOutside={() => setOpenToolbar(false)}
|
||||
>
|
||||
<div className="flex h-[90vh]">
|
||||
<div className="border-r border-slate-200 w-[20%] py-3 flex flex-col gap-2 px-3 overflow-y-auto scrollbar-thin bg-slate-50">
|
||||
{categoryList.map((e, index) => {
|
||||
const isActive = active?.name === e.name;
|
||||
{category &&
|
||||
category.map((e, index) => {
|
||||
const isActive = active?.name === e.name;
|
||||
|
||||
return (
|
||||
<Button
|
||||
key={index}
|
||||
variant="secondary"
|
||||
onMouseEnter={() => setActive(e)}
|
||||
onClick={() => setActive(e)}
|
||||
className={`flex justify-between items-center cursor-pointer px-4 h-14 rounded-xl transition-all duration-300 ${
|
||||
isActive
|
||||
? 'bg-blue-100 border border-blue-400'
|
||||
: 'hover:bg-slate-100 border border-transparent'
|
||||
}`}
|
||||
>
|
||||
<div className="flex gap-3 items-center">
|
||||
<div
|
||||
className={`p-1.5 rounded-lg ${isActive ? 'bg-white' : 'bg-white'}`}
|
||||
>
|
||||
<Image
|
||||
src={e.image || '/placeholder.svg'}
|
||||
alt={e.name}
|
||||
unoptimized
|
||||
className="w-5 h-5 object-contain"
|
||||
/>
|
||||
</div>
|
||||
<p
|
||||
className={`text-sm font-medium ${isActive ? 'text-blue-700' : 'text-slate-700'}`}
|
||||
>
|
||||
{e.name}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ChevronRight
|
||||
className={`size-5 transition-transform duration-300 ${
|
||||
return (
|
||||
<Button
|
||||
key={index}
|
||||
variant="secondary"
|
||||
onMouseEnter={() => setActive(e)}
|
||||
onClick={() => setActive(e)}
|
||||
className={`flex justify-between items-center cursor-pointer px-4 h-14 rounded-xl transition-all duration-300 ${
|
||||
isActive
|
||||
? 'rotate-90 text-blue-600'
|
||||
: 'text-slate-400'
|
||||
? 'bg-blue-100 border border-blue-400'
|
||||
: 'hover:bg-slate-100 border border-transparent'
|
||||
}`}
|
||||
/>
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
>
|
||||
<div className="flex gap-3 items-center min-w-0">
|
||||
<div className={`p-1.5 rounded-lg bg-white shrink-0`}>
|
||||
<Image
|
||||
src={e.image || '/placeholder.svg'}
|
||||
alt={e.name}
|
||||
width={500}
|
||||
height={500}
|
||||
unoptimized
|
||||
className="w-5 h-5 object-contain"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p
|
||||
className={`text-sm font-medium truncate ${
|
||||
isActive ? 'text-blue-700' : 'text-slate-700'
|
||||
}`}
|
||||
>
|
||||
{e.name}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ChevronRight
|
||||
className={`size-5 transition-transform duration-300 ${
|
||||
isActive
|
||||
? 'rotate-90 text-blue-600'
|
||||
: 'text-slate-400'
|
||||
}`}
|
||||
/>
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="w-[80%] overflow-y-auto p-8 scrollbar-thin bg-white">
|
||||
@@ -538,21 +552,30 @@ const Navbar = () => {
|
||||
{active?.name}
|
||||
</h3>
|
||||
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{active?.subCategories.map((sub, index) => (
|
||||
<Button
|
||||
key={index}
|
||||
onClick={() => {
|
||||
setCloseToolbar(false);
|
||||
router.push(`/category/${active.name}/${sub.name}`);
|
||||
}}
|
||||
variant="outline"
|
||||
className="justify-start h-12 cursor-pointer border border-slate-200 hover:border-blue-400 hover:bg-blue-50 transition-all text-slate-700 hover:text-blue-700 font-medium rounded-xl bg-transparent"
|
||||
>
|
||||
{sub.name}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
{active && active?.product_types?.length > 0 ? (
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{active.product_types.map((sub, index) => (
|
||||
<Button
|
||||
key={index}
|
||||
onClick={() => {
|
||||
setCloseToolbar(false);
|
||||
router.push(`/category/${active.id}/${sub.id}`);
|
||||
}}
|
||||
variant="outline"
|
||||
className="justify-start h-12 border border-slate-200 hover:border-blue-400 hover:bg-blue-50 transition-all rounded-xl"
|
||||
>
|
||||
{sub.name}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center justify-center h-[50vh] text-slate-400">
|
||||
<p className="text-lg font-medium">
|
||||
{t('Bu kategoriyada hozircha mahsulot yo‘q')}
|
||||
</p>
|
||||
<p className="text-sm mt-1">{t('Tez orada qo‘shiladi')}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
type CarouselApi,
|
||||
} from '@/shared/ui/carousel';
|
||||
import { Skeleton } from '@/shared/ui/skeleton';
|
||||
import { CategoryCarousel } from '@/widgets/categories/ui/category-carousel';
|
||||
import CategoryCarousel from '@/widgets/categories/ui/category-carousel';
|
||||
import { ProductCard } from '@/widgets/categories/ui/product-card';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { AlertCircle, ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
@@ -31,7 +31,6 @@ const Welcome = () => {
|
||||
const [apiPro, setApiPro] = useState<CarouselApi>();
|
||||
const [canScrollPrev, setCanScrollPrev] = useState(false);
|
||||
const [canScrollNext, setCanScrollNext] = useState(false);
|
||||
const [apiCat, setApiCat] = useState<CarouselApi>();
|
||||
const router = useRouter();
|
||||
const t = useTranslations();
|
||||
|
||||
@@ -77,7 +76,7 @@ const Welcome = () => {
|
||||
queryKey: ['category_list'],
|
||||
queryFn: () => category_api.getCategory({ page: 1, page_size: 99 }),
|
||||
select(data) {
|
||||
return data.data.results;
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -89,10 +88,6 @@ const Welcome = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const scrollPrevCar = () => {
|
||||
apiCat?.scrollPrev();
|
||||
};
|
||||
|
||||
const scrollNext = () => {
|
||||
if (api?.canScrollNext()) {
|
||||
api?.scrollNext();
|
||||
@@ -101,10 +96,6 @@ const Welcome = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const scrollNextCat = () => {
|
||||
apiCat?.scrollNext();
|
||||
};
|
||||
|
||||
const { data: product, isLoading: productLoading } = useQuery({
|
||||
queryKey: ['list'],
|
||||
queryFn: () =>
|
||||
@@ -172,7 +163,7 @@ const Welcome = () => {
|
||||
</CarouselContent>
|
||||
</Carousel>
|
||||
|
||||
<Carousel className="w-full mt-5" setApi={setApiCat}>
|
||||
<Carousel className="w-full mt-5">
|
||||
<CarouselContent className="py-2 px-1 pr-[12%]">
|
||||
{category &&
|
||||
category.map((banner, index) => (
|
||||
@@ -200,24 +191,6 @@ const Welcome = () => {
|
||||
</CarouselItem>
|
||||
))}
|
||||
</CarouselContent>
|
||||
<Button
|
||||
onClick={scrollNextCat}
|
||||
className="absolute max-lg:w-8 max-lg:h-8 top-1/2 -translate-y-1/2 -right-2 cursor-pointer"
|
||||
variant={'secondary'}
|
||||
size={'icon'}
|
||||
aria-label="next images"
|
||||
>
|
||||
<ChevronRight className="size-6 max-lg:size-6" />
|
||||
</Button>
|
||||
<Button
|
||||
onClick={scrollPrevCar}
|
||||
className="absolute max-lg:w-8 max-lg:h-8 top-1/2 -translate-y-1/2 -left-2 cursor-pointer"
|
||||
variant={'secondary'}
|
||||
size={'icon'}
|
||||
aria-label="prev images"
|
||||
>
|
||||
<ChevronLeft className="size-6 max-lg:size-6" />
|
||||
</Button>
|
||||
</Carousel>
|
||||
</div>
|
||||
<section className="relative custom-container mt-5 justify-center items-center border-b border-slate-200">
|
||||
@@ -268,7 +241,7 @@ const Welcome = () => {
|
||||
</CarouselItem>
|
||||
))}
|
||||
</CarouselContent>
|
||||
</Carousel>{' '}
|
||||
</Carousel>
|
||||
<Button
|
||||
onClick={scrollNextPro}
|
||||
className={cn(
|
||||
@@ -300,9 +273,7 @@ const Welcome = () => {
|
||||
</section>
|
||||
|
||||
{category &&
|
||||
category
|
||||
.slice(0, 6)
|
||||
.map((e) => <CategoryCarousel category={e} key={e.id} />)}
|
||||
category.map((e) => <CategoryCarousel category={e} key={e.id} />)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user