Compare commits
61 Commits
8a4682212f
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9ec9ea586f | ||
|
|
1a2d3eef6c | ||
|
|
86ceda48f7 | ||
|
|
68dad90900 | ||
|
|
855600cfe2 | ||
|
|
35374094eb | ||
|
|
95d17b274f | ||
|
|
f04ae13c39 | ||
|
|
3fcbf22b70 | ||
|
|
a0994df9bd | ||
|
|
fc1bc9c0a9 | ||
|
|
729544cb7e | ||
|
|
86f49f6d82 | ||
|
|
58ff67ce81 | ||
|
|
8248e5aa2a | ||
|
|
4f47455233 | ||
|
|
ec6e508b1e | ||
|
|
705ef2e7bc | ||
|
|
f68bdcd89e | ||
|
|
e2aa75031e | ||
|
|
db58ae240f | ||
|
|
5077c0d950 | ||
|
|
f3a1b9efef | ||
|
|
7b00b67746 | ||
|
|
edcaaaf961 | ||
|
|
e7f0731353 | ||
|
|
5e60ac8dd4 | ||
|
|
6642f5cfe1 | ||
|
|
75b3674e20 | ||
|
|
7fdf219d7f | ||
|
|
8aef5f8b18 | ||
|
|
18cfa5cdf9 | ||
|
|
a2be8ef125 | ||
|
|
9f8a41ea7b | ||
|
|
4d35b8f6d1 | ||
|
|
ed5ee752c9 | ||
|
|
4fd458075c | ||
|
|
c7ac5ad861 | ||
|
|
09290cc352 | ||
|
|
ef55c1ecd8 | ||
|
|
bb84da82a8 | ||
|
|
734087aac5 | ||
|
|
f3e0c3e2be | ||
|
|
ea097d3953 | ||
|
|
78e79d295e | ||
|
|
fa1110ea20 | ||
|
|
a3f01e0ee7 | ||
|
|
d5148aaf06 | ||
|
|
f6231229da | ||
|
|
b1fb8fb0c4 | ||
|
|
ed4601b8e8 | ||
|
|
72c46a296c | ||
|
|
e270495a17 | ||
|
|
8abd0e448b | ||
|
|
5e1430adf6 | ||
|
|
2bdd6f17a2 | ||
|
|
bb782d96da | ||
|
|
08a96d2821 | ||
|
|
512701140d | ||
|
|
2535913eb2 | ||
|
|
4d22e3441c |
38
src/app/[locale]/about/AboutSEO.tsx
Normal file
38
src/app/[locale]/about/AboutSEO.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
'use client';
|
||||
|
||||
import { partner_api } from '@/features/about/lib/api';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useParams } from 'next/navigation';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export default function AboutSEO() {
|
||||
const { locale } = useParams();
|
||||
|
||||
const { data } = useQuery({
|
||||
queryKey: ['aboutData'],
|
||||
queryFn: async () => (await partner_api.getAbout()).data,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!data) return;
|
||||
const banner = data.banner;
|
||||
const title =
|
||||
locale === 'uz'
|
||||
? banner.title_uz
|
||||
: locale === 'ru'
|
||||
? banner.title_ru
|
||||
: banner.title_en;
|
||||
const description =
|
||||
locale === 'uz'
|
||||
? banner.description_uz
|
||||
: locale === 'ru'
|
||||
? banner.description_ru
|
||||
: banner.description_en;
|
||||
|
||||
document.title = title || 'Gastro Market';
|
||||
const descMeta = document.querySelector('meta[name="description"]');
|
||||
if (descMeta) descMeta.setAttribute('content', description || '');
|
||||
}, [data, locale]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,59 +1,83 @@
|
||||
// app/[locale]/about/page.tsx
|
||||
export const dynamic = 'force-dynamic';
|
||||
import { AboutContent } from '@/features/about/ui/AboutContent';
|
||||
import { AboutHero } from '@/features/about/ui/AboutHero';
|
||||
import { PartnershipForm } from '@/features/about/ui/AboutPage';
|
||||
import { BASE_URL } from '@/shared/config/api/URLs';
|
||||
import { Metadata } from 'next';
|
||||
|
||||
function getImageUrl(image?: string | null): string {
|
||||
if (!image) return '/placeholder.svg';
|
||||
return image.includes(BASE_URL) ? image : BASE_URL + image;
|
||||
}
|
||||
|
||||
const fetchAboutData = async () => {
|
||||
const res = await fetch(
|
||||
'https://api.gastro.felixits.uz/api/v1/shared/aboutus/',
|
||||
{ cache: 'no-store' },
|
||||
);
|
||||
if (!res.ok) throw new Error(`Failed to fetch about data: ${res.status}`);
|
||||
const data = await res.json();
|
||||
return data.banner;
|
||||
};
|
||||
|
||||
interface Props {
|
||||
params: { locale: 'uz' | 'ru' };
|
||||
params: Promise<{ locale: 'uz' | 'ru' | 'en' }>;
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
const { locale } = await params;
|
||||
|
||||
const titles = {
|
||||
uz: 'Biz haqimizda | GASTRO',
|
||||
ru: 'О нас | Магазин товаров',
|
||||
};
|
||||
try {
|
||||
const banner = await fetchAboutData();
|
||||
|
||||
const descriptions = {
|
||||
uz: 'Bizning onlayn do‘konimizda sifatli mahsulotlarni toping. Tez yetkazib berish va qulay to‘lov imkoniyatlari mavjud.',
|
||||
ru: 'В нашем онлайн-магазине вы найдете качественные товары. Быстрая доставка и удобная оплата.',
|
||||
};
|
||||
const title =
|
||||
locale === 'uz'
|
||||
? banner.title_uz
|
||||
: locale === 'ru'
|
||||
? banner.title_ru
|
||||
: banner.title_en;
|
||||
|
||||
const keywords = {
|
||||
uz: 'mahsulot, onlayn do‘kon, xarid, yetkazib berish',
|
||||
ru: 'товары, онлайн-магазин, покупка, доставка',
|
||||
};
|
||||
const description =
|
||||
locale === 'uz'
|
||||
? banner.description_uz
|
||||
: locale === 'ru'
|
||||
? banner.description_ru
|
||||
: banner.description_en;
|
||||
|
||||
return {
|
||||
title: titles[locale],
|
||||
description: descriptions[locale],
|
||||
keywords: keywords[locale],
|
||||
title: title || 'Gastro Market',
|
||||
description: description || 'Gastro Market mahsulotlarini kashf eting',
|
||||
openGraph: {
|
||||
title: titles[locale],
|
||||
description: descriptions[locale],
|
||||
siteName: 'GASTRO',
|
||||
title: title || 'Gastro Market',
|
||||
description: description || 'Gastro Market mahsulotlarini kashf eting',
|
||||
type: 'website',
|
||||
images: [
|
||||
{
|
||||
url: '/logos/logo.png',
|
||||
url: getImageUrl(banner.image),
|
||||
width: 1200,
|
||||
height: 1200,
|
||||
alt: titles[locale],
|
||||
height: 630,
|
||||
alt: title,
|
||||
},
|
||||
],
|
||||
locale: locale === 'uz' ? 'uz_UZ' : 'ru_RU',
|
||||
type: 'website',
|
||||
},
|
||||
twitter: {
|
||||
card: 'summary_large_image',
|
||||
title: titles[locale],
|
||||
description: descriptions[locale],
|
||||
images: ['/logos/logo.png'],
|
||||
title: title || 'Gastro Market',
|
||||
description: description || 'Gastro Market mahsulotlarini kashf eting',
|
||||
images: [getImageUrl(banner.image)],
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.error('About metadata error:', err);
|
||||
return {
|
||||
title: 'Gastro Market',
|
||||
description: 'Gastro Market mahsulotlarini kashf eting',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const page = () => {
|
||||
const AboutPage = async () => {
|
||||
return (
|
||||
<div className="custom-container">
|
||||
<AboutHero />
|
||||
@@ -63,4 +87,4 @@ const page = () => {
|
||||
);
|
||||
};
|
||||
|
||||
export default page;
|
||||
export default AboutPage;
|
||||
|
||||
@@ -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 [];
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ export async function generateMetadata({
|
||||
openGraph: {
|
||||
title,
|
||||
description,
|
||||
url: `/search${query ? `?q=${encodeURIComponent(query)}` : ''}`,
|
||||
url: `/search${query ? `?search=${encodeURIComponent(query)}` : ''}`,
|
||||
type: 'website',
|
||||
},
|
||||
twitter: {
|
||||
@@ -64,7 +64,7 @@ export async function generateMetadata({
|
||||
openGraph: {
|
||||
title,
|
||||
description,
|
||||
url: `/search${query ? `?q=${encodeURIComponent(query)}` : ''}`,
|
||||
url: `/search${query ? `?search=${encodeURIComponent(query)}` : ''}`,
|
||||
type: 'website',
|
||||
},
|
||||
twitter: {
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import httpClient from '@/shared/config/api/httpClient';
|
||||
import { API_URLS } from '@/shared/config/api/URLs';
|
||||
import { AxiosResponse } from 'axios';
|
||||
import { AboutData } from './type';
|
||||
|
||||
export const partner_api = {
|
||||
async send(body: FormData) {
|
||||
const res = httpClient.post(API_URLS.Partners, body);
|
||||
return res;
|
||||
},
|
||||
|
||||
async getAbout(): Promise<AxiosResponse<AboutData>> {
|
||||
const res = httpClient.get(API_URLS.About);
|
||||
return res;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -4,3 +4,35 @@ export interface PartnerSendBody {
|
||||
phone_number: string;
|
||||
file: File;
|
||||
}
|
||||
|
||||
export interface AboutData {
|
||||
banner: {
|
||||
id: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
title_uz: string;
|
||||
title_ru: string;
|
||||
title_en: string;
|
||||
description_uz: string;
|
||||
description_ru: string;
|
||||
description_en: string;
|
||||
image: string;
|
||||
};
|
||||
images: {
|
||||
id: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
image: string;
|
||||
}[];
|
||||
text: {
|
||||
id: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
title_uz: string;
|
||||
title_ru: string;
|
||||
title_en: string;
|
||||
description_uz: string;
|
||||
description_ru: string;
|
||||
description_en: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
@@ -1,85 +1,80 @@
|
||||
import { Card } from '@/shared/ui/card';
|
||||
'use client';
|
||||
|
||||
import { BASE_URL } from '@/shared/config/api/URLs';
|
||||
import { Skeleton } from '@/shared/ui/skeleton';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import Image from 'next/image';
|
||||
import { useParams } from 'next/navigation';
|
||||
import { partner_api } from '../lib/api';
|
||||
|
||||
export function AboutContent() {
|
||||
const t = useTranslations();
|
||||
const features = [
|
||||
{
|
||||
number: '1',
|
||||
title: 'Sifatli Kontent',
|
||||
description:
|
||||
"Jahon oshpazlik san'ati va zamonaviy gastronomiya tendentsiyalari haqida chuqur maqolalar va tahlillar",
|
||||
},
|
||||
{
|
||||
number: '2',
|
||||
title: 'Professional Jamoa',
|
||||
description:
|
||||
'Tajribali kulinariya mutaxassislari va oshpazlar tomonidan tayyorlangan kontent',
|
||||
},
|
||||
{
|
||||
number: '3',
|
||||
title: 'Yangiliklar',
|
||||
description:
|
||||
"Gastronomiya sohasidagi so'nggi yangiliklar va eng yangi trendlar haqida xabarlar",
|
||||
},
|
||||
];
|
||||
const { locale } = useParams();
|
||||
|
||||
const images = [
|
||||
{
|
||||
url: '/professional-chef-cooking-gourmet-food.jpg',
|
||||
alt: 'Professional Oshpaz',
|
||||
const { data: about, isLoading: loadingText } = useQuery({
|
||||
queryKey: ['aboutText'],
|
||||
queryFn: async () => {
|
||||
return partner_api.getAbout();
|
||||
},
|
||||
{
|
||||
url: '/fine-dining-restaurant-plating.jpg',
|
||||
alt: 'Fine Dining',
|
||||
select(data) {
|
||||
return data.data;
|
||||
},
|
||||
{
|
||||
url: '/fresh-ingredients-culinary-market.jpg',
|
||||
alt: 'Fresh Ingredients',
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
const aboutText = about?.text;
|
||||
const images = about?.images;
|
||||
|
||||
// Loading holati
|
||||
if (loadingText) {
|
||||
return (
|
||||
<section className="py-20 px-4">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
{/* Text Skeleton */}
|
||||
<div className="mb-20 text-center space-y-6">
|
||||
<Skeleton className="h-12 md:h-16 w-3/4 mx-auto rounded-lg" />
|
||||
<Skeleton className="h-6 md:h-8 w-5/6 mx-auto rounded-lg" />
|
||||
<Skeleton className="h-6 md:h-8 w-5/6 mx-auto rounded-lg" />
|
||||
</div>
|
||||
|
||||
{/* Image Gallery Skeleton */}
|
||||
<div className="mb-20">
|
||||
<Skeleton className="h-8 w-1/3 mx-auto rounded-lg mb-12" />
|
||||
<div className="grid md:grid-cols-3 gap-6">
|
||||
{[...Array(3)].map((_, idx) => (
|
||||
<Skeleton
|
||||
key={idx}
|
||||
className="aspect-[4/3] w-full rounded-lg"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="py-20 px-4">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
{/* Mission Section */}
|
||||
<div className="mb-20">
|
||||
<h2 className="text-4xl md:text-5xl font-bold text-center mb-16 text-balance">
|
||||
{t('Bizning maqsadimiz')}
|
||||
</h2>
|
||||
<div className="grid md:grid-cols-3 gap-8">
|
||||
{features.map((feature) => (
|
||||
<Card
|
||||
key={feature.number}
|
||||
className="p-8 hover:shadow-lg transition-shadow"
|
||||
>
|
||||
<div className="text-6xl font-bold text-primary mb-4">
|
||||
{feature.number}
|
||||
</div>
|
||||
<h3 className="text-2xl font-semibold mb-4">
|
||||
{t(feature.title)}
|
||||
</h3>
|
||||
<p className="text-muted-foreground leading-relaxed">
|
||||
{t(feature.description)}
|
||||
</p>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* About Text */}
|
||||
<div className="mb-20 max-w-4xl mx-auto text-center">
|
||||
<div className="mb-20 text-center">
|
||||
<h2 className="text-3xl md:text-4xl font-bold mb-8 text-balance">
|
||||
{t('Innovatsiya, sifat va professionallik')}
|
||||
{locale === 'uz'
|
||||
? aboutText?.[0]?.title_uz || 'Gastro Market'
|
||||
: locale === 'ru'
|
||||
? aboutText?.[0]?.title_ru || 'Gastro Market'
|
||||
: aboutText?.[0]?.title_en || 'Gastro Market'}
|
||||
</h2>
|
||||
<p className="text-lg text-muted-foreground leading-relaxed mb-6">
|
||||
{t(
|
||||
`Gastro Market – bu gastronomiya dunyosidagi eng so'nggi yangiliklarni`,
|
||||
)}
|
||||
</p>
|
||||
<p className="text-lg text-muted-foreground leading-relaxed">
|
||||
{t(`Bizning jamoamiz tajribali kulinariya mutaxassislari`)}
|
||||
{locale === 'uz'
|
||||
? aboutText?.[0]?.description_uz ||
|
||||
"Gastronomiya va kulinariya san'ati haqidagi yetakchi onlayn magazin"
|
||||
: locale === 'ru'
|
||||
? aboutText?.[0]?.description_ru ||
|
||||
'Ведущий интернет-магазин по гастрономии и кулинарному искусству'
|
||||
: aboutText?.[0]?.description_en ||
|
||||
"Gastronomiya va kulinariya san'ati haqidagi yetakchi onlayn magazin"}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -89,7 +84,7 @@ export function AboutContent() {
|
||||
{t('Bizning dunyo')}
|
||||
</h3>
|
||||
<div className="grid md:grid-cols-3 gap-6">
|
||||
{images.map((image, idx) => (
|
||||
{images?.map((image, idx) => (
|
||||
<div
|
||||
key={idx}
|
||||
className="relative aspect-[4/3] overflow-hidden rounded-lg group"
|
||||
@@ -97,8 +92,8 @@ export function AboutContent() {
|
||||
<Image
|
||||
width={500}
|
||||
height={500}
|
||||
src={image.url || '/placeholder.svg'}
|
||||
alt={image.alt}
|
||||
src={BASE_URL + image.image || '/placeholder.svg'}
|
||||
alt={image.id.toString()}
|
||||
unoptimized
|
||||
className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
|
||||
/>
|
||||
|
||||
@@ -1,8 +1,40 @@
|
||||
import { useTranslations } from 'next-intl';
|
||||
'use client';
|
||||
|
||||
import { BASE_URL } from '@/shared/config/api/URLs';
|
||||
import { Skeleton } from '@/shared/ui/skeleton';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import Image from 'next/image';
|
||||
import { useParams } from 'next/navigation';
|
||||
import { partner_api } from '../lib/api';
|
||||
|
||||
export function AboutHero() {
|
||||
const t = useTranslations();
|
||||
const { locale } = useParams();
|
||||
|
||||
const { data: banner, isLoading } = useQuery({
|
||||
queryKey: ['about'],
|
||||
queryFn: async () => {
|
||||
return partner_api.getAbout();
|
||||
},
|
||||
select(data) {
|
||||
return data.data.banner;
|
||||
},
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<section className="relative h-[60vh] min-h-[500px] flex items-center rounded-lg justify-center overflow-hidden bg-gray-200">
|
||||
{/* Background skeleton */}
|
||||
<Skeleton className="absolute inset-0 w-full h-full" />
|
||||
{/* Content skeleton */}
|
||||
<div className="relative z-10 text-center px-4 max-w-4xl mx-auto space-y-6">
|
||||
<Skeleton className="h-16 md:h-24 w-3/4 mx-auto rounded-lg" />
|
||||
<Skeleton className="h-6 md:h-10 w-5/6 mx-auto rounded-lg" />
|
||||
<Skeleton className="h-6 md:h-10 w-4/6 mx-auto rounded-lg" />
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="relative h-[60vh] min-h-[500px] flex items-center justify-center overflow-hidden">
|
||||
<div className="absolute inset-0 z-0">
|
||||
@@ -10,19 +42,31 @@ export function AboutHero() {
|
||||
width={500}
|
||||
height={500}
|
||||
unoptimized
|
||||
src="/gourmet-food-culinary-magazine-hero-image.jpg"
|
||||
src={
|
||||
BASE_URL + banner?.image ||
|
||||
'/gourmet-food-culinary-magazine-hero-image.jpg'
|
||||
}
|
||||
alt="Gastro Market"
|
||||
className="w-full h-full object-cover brightness-50"
|
||||
/>
|
||||
</div>
|
||||
<div className="relative z-10 text-center px-4 max-w-4xl mx-auto">
|
||||
<h1 className="text-5xl md:text-7xl font-bold text-white mb-6 text-balance">
|
||||
Gastro Market
|
||||
{locale === 'uz'
|
||||
? banner?.title_uz || 'Gastro Market'
|
||||
: locale === 'ru'
|
||||
? banner?.title_ru || 'Gastro Market'
|
||||
: banner?.title_en || 'Gastro Market'}
|
||||
</h1>
|
||||
<p className="text-xl md:text-2xl text-white/90 font-light leading-relaxed text-balance">
|
||||
{t(
|
||||
"Gastronomiya va kulinariya san'ati haqidagi yetakchi onlayn magazin",
|
||||
)}
|
||||
{locale === 'uz'
|
||||
? banner?.description_uz ||
|
||||
"Gastronomiya va kulinariya san'ati haqidagi yetakchi onlayn magazin"
|
||||
: locale === 'ru'
|
||||
? banner?.description_ru ||
|
||||
'Ведущий интернет-магазин по гастрономии и кулинарному искусству'
|
||||
: banner?.description_en ||
|
||||
"Gastronomiya va kulinariya san'ati haqidagi yetakchi onlayn magazin"}
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { Link, useRouter } from '@/shared/config/i18n/navigation';
|
||||
import { setRefToken, setToken, setUser } from '@/shared/lib/token';
|
||||
import { setRefToken, setToken } from '@/shared/lib/token';
|
||||
import { Button } from '@/shared/ui/button';
|
||||
import {
|
||||
Form,
|
||||
@@ -25,6 +25,7 @@ import { authForm } from '../lib/form';
|
||||
const Login = () => {
|
||||
const router = useRouter();
|
||||
const t = useTranslations();
|
||||
const queryClient = useQueryClient();
|
||||
const form = useForm<z.infer<typeof authForm>>({
|
||||
resolver: zodResolver(authForm),
|
||||
defaultValues: {
|
||||
@@ -32,7 +33,6 @@ const Login = () => {
|
||||
username: '',
|
||||
},
|
||||
});
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { mutate, isPending } = useMutation({
|
||||
mutationFn: (body: {
|
||||
@@ -41,12 +41,10 @@ const Login = () => {
|
||||
tg_id?: string;
|
||||
}) => auth_api.login(body),
|
||||
onSuccess: (res) => {
|
||||
router.push('/');
|
||||
queryClient.refetchQueries();
|
||||
setToken(res.data.access);
|
||||
setRefToken(res.data.refresh);
|
||||
setUser(form.getValues('username'));
|
||||
router.push('/');
|
||||
queryClient.refetchQueries({ queryKey: ['product_list'] });
|
||||
queryClient.refetchQueries({ queryKey: ['get_me'] });
|
||||
},
|
||||
onError: () => {
|
||||
toast.error(t('Username yoki parol xato kiritildi'), {
|
||||
|
||||
@@ -13,7 +13,7 @@ export interface CartItem {
|
||||
image: string;
|
||||
}[];
|
||||
liked: boolean;
|
||||
meansurement: null | string;
|
||||
meansurement: null | { id: number; name: string };
|
||||
inventory_id: null | string;
|
||||
product_id: string;
|
||||
code: string;
|
||||
@@ -31,6 +31,7 @@ export interface CartItem {
|
||||
marketing_group_code: null | string;
|
||||
inventory_kinds: { id: number; name: string }[];
|
||||
sector_codes: { id: number; code: string }[];
|
||||
balance: number;
|
||||
prices: {
|
||||
id: number;
|
||||
price: string;
|
||||
|
||||
@@ -3,6 +3,6 @@ import { z } from 'zod';
|
||||
export const orderForm = z.object({
|
||||
long: z.string().min(1, { message: 'Majburiy maydon' }),
|
||||
lat: z.string().min(1, { message: 'Majburiy maydon' }),
|
||||
comment: z.string().min(1, { message: 'Majburiy maydon' }),
|
||||
comment: z.string().max(300, 'Izoh 300 ta belgidan oshmasligi kerak'),
|
||||
city: z.string().optional(),
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
'use client';
|
||||
|
||||
import ProductBanner from '@/assets/product.png';
|
||||
import { cart_api } from '@/features/cart/lib/api';
|
||||
import { BASE_URL } from '@/shared/config/api/URLs';
|
||||
@@ -36,19 +37,28 @@ const CartPage = () => {
|
||||
select: (data) => data.data.cart_item,
|
||||
});
|
||||
|
||||
const [quantities, setQuantities] = useState<Record<string, string>>({});
|
||||
// Haqiqiy raqamlar (hisob-kitob uchun)
|
||||
const [quantities, setQuantities] = useState<Record<string, number>>({});
|
||||
// Input ko'rinishi uchun string (nuqta bilan yozish imkonini beradi)
|
||||
const [inputValues, setInputValues] = useState<Record<string, string>>({});
|
||||
|
||||
const debounceRef = useRef<Record<string, NodeJS.Timeout | null>>({});
|
||||
|
||||
// Initial quantities
|
||||
useEffect(() => {
|
||||
if (!cartItems) return;
|
||||
const initialQuantities: Record<string, string> = {};
|
||||
const initialQuantities: Record<string, number> = {};
|
||||
const initialInputValues: Record<string, string> = {};
|
||||
cartItems.forEach((item) => {
|
||||
initialQuantities[item.id] = String(item.quantity);
|
||||
initialQuantities[item.id] = item.quantity;
|
||||
initialInputValues[item.id] = String(item.quantity);
|
||||
debounceRef.current[item.id] = null;
|
||||
});
|
||||
setQuantities(initialQuantities);
|
||||
setInputValues(initialInputValues);
|
||||
}, [cartItems]);
|
||||
|
||||
// Update mutation
|
||||
const { mutate: updateCartItem } = useMutation({
|
||||
mutationFn: ({
|
||||
body,
|
||||
@@ -57,23 +67,85 @@ const CartPage = () => {
|
||||
body: { quantity: number };
|
||||
cart_item_id: string;
|
||||
}) => cart_api.update_cart_item({ body, cart_item_id }),
|
||||
onSuccess: () =>
|
||||
queryClient.invalidateQueries({ queryKey: ['cart_items', cart_id] }),
|
||||
onSuccess: (_, variables) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['cart_items', cart_id] });
|
||||
const item = cartItems?.find(
|
||||
(i) => String(i.id) === variables.cart_item_id,
|
||||
);
|
||||
if (item) {
|
||||
const measurementName = item.product.meansurement?.name || 'шт.';
|
||||
toast.success(
|
||||
`${t('Miqdor')} ${variables.body.quantity} ${measurementName} ${t('ga yangilandi')}`,
|
||||
{ richColors: true, position: 'top-center' },
|
||||
);
|
||||
}
|
||||
},
|
||||
onError: (err: AxiosError) =>
|
||||
toast.error(err.message, { richColors: true, position: 'top-center' }),
|
||||
});
|
||||
|
||||
// Delete mutation
|
||||
const { mutate: deleteCartItem } = useMutation({
|
||||
mutationFn: ({ cart_item_id }: { cart_item_id: string }) =>
|
||||
cart_api.delete_cart_item(cart_item_id),
|
||||
onSuccess: () =>
|
||||
queryClient.invalidateQueries({ queryKey: ['cart_items', cart_id] }),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['cart_items', cart_id] });
|
||||
toast.success(t("Savatdan o'chirildi"), {
|
||||
richColors: true,
|
||||
position: 'top-center',
|
||||
});
|
||||
},
|
||||
onError: (err: AxiosError) =>
|
||||
toast.error(err.message, { richColors: true, position: 'top-center' }),
|
||||
});
|
||||
|
||||
const handleCheckout = () => router.push('/cart/order');
|
||||
|
||||
const handleQuantityChange = (
|
||||
itemId: number,
|
||||
delta: number = 0,
|
||||
newValue?: number,
|
||||
) => {
|
||||
setQuantities((prev) => {
|
||||
const item = cartItems?.find((i) => i.id === itemId);
|
||||
if (!item) return prev;
|
||||
|
||||
const isGram = item.product.meansurement?.name?.toLowerCase() === 'gr';
|
||||
const STEP = isGram ? 100 : 1;
|
||||
const MIN_QTY = isGram ? 100 : 0.5;
|
||||
|
||||
let updatedQty: number;
|
||||
if (newValue !== undefined) {
|
||||
updatedQty = newValue;
|
||||
} else {
|
||||
updatedQty = (prev[itemId] ?? MIN_QTY) + delta * STEP;
|
||||
if (updatedQty < MIN_QTY) updatedQty = MIN_QTY;
|
||||
}
|
||||
|
||||
// inputValues ni ham yangilash
|
||||
setInputValues((prevInput) => ({
|
||||
...prevInput,
|
||||
[itemId]: String(updatedQty),
|
||||
}));
|
||||
|
||||
if (debounceRef.current[itemId])
|
||||
clearTimeout(debounceRef.current[itemId]!);
|
||||
|
||||
debounceRef.current[itemId] = setTimeout(() => {
|
||||
if (updatedQty <= 0) {
|
||||
deleteCartItem({ cart_item_id: itemId.toString() });
|
||||
} else {
|
||||
updateCartItem({
|
||||
body: { quantity: updatedQty },
|
||||
cart_item_id: itemId.toString(),
|
||||
});
|
||||
}
|
||||
}, 500);
|
||||
|
||||
return { ...prev, [itemId]: updatedQty };
|
||||
});
|
||||
};
|
||||
|
||||
if (isLoading)
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
@@ -103,33 +175,19 @@ const CartPage = () => {
|
||||
);
|
||||
|
||||
const subtotal =
|
||||
cartItems?.reduce((sum, item) => {
|
||||
if (item.product.prices.length === 0) return sum; // narx yo'q bo'lsa qo'shmaymiz
|
||||
cartItems.reduce((sum, item) => {
|
||||
if (!item.product.prices.length) return sum;
|
||||
|
||||
// Eng yuqori narxni olish
|
||||
const maxPrice = Math.max(
|
||||
...item.product.prices.map((p) => Number(p.price)),
|
||||
);
|
||||
const price = item.product.prices.find((p) => p.price_type.code === '1')
|
||||
? Number(
|
||||
item.product.prices.find((p) => p.price_type.code === '1')?.price,
|
||||
)
|
||||
: Math.min(...item.product.prices.map((p) => Number(p.price)));
|
||||
|
||||
return sum + maxPrice * item.quantity;
|
||||
}, 0) || 0; // cartItems bo'sh bo'lsa 0 qaytaradi
|
||||
const qty = quantities[item.id] ?? item.quantity;
|
||||
|
||||
const handleQuantityChange = (itemId: string, value: number) => {
|
||||
setQuantities((prev) => ({
|
||||
...prev,
|
||||
[itemId]: String(value),
|
||||
}));
|
||||
|
||||
if (debounceRef.current[itemId]) clearTimeout(debounceRef.current[itemId]!);
|
||||
|
||||
debounceRef.current[itemId] = setTimeout(() => {
|
||||
if (value <= 0) {
|
||||
deleteCartItem({ cart_item_id: itemId });
|
||||
} else {
|
||||
updateCartItem({ body: { quantity: value }, cart_item_id: itemId });
|
||||
}
|
||||
}, 500);
|
||||
};
|
||||
return sum + price * qty;
|
||||
}, 0) || 0;
|
||||
|
||||
return (
|
||||
<div className="custom-container mb-6">
|
||||
@@ -143,12 +201,17 @@ const CartPage = () => {
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
<div className="lg:col-span-2">
|
||||
<div className="bg-white rounded-lg shadow-md overflow-hidden">
|
||||
{cartItems.map((item, index) => (
|
||||
{cartItems.map((item, index) => {
|
||||
const measurementDisplay =
|
||||
item.product.meansurement?.name || 'шт.';
|
||||
const quantity = quantities[item.id] ?? item.quantity;
|
||||
// Input uchun string qiymat (nuqta bilan yozish imkonini beradi)
|
||||
const inputValue = inputValues[item.id] ?? String(item.quantity);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
className={`p-6 flex relative gap-4 ${
|
||||
index !== cartItems.length - 1 ? 'border-b' : ''
|
||||
}`}
|
||||
className={`p-6 flex relative gap-4 ${index !== cartItems.length - 1 ? 'border-b' : ''}`}
|
||||
>
|
||||
<Button
|
||||
variant="destructive"
|
||||
@@ -156,24 +219,25 @@ const CartPage = () => {
|
||||
onClick={() =>
|
||||
deleteCartItem({ cart_item_id: String(item.id) })
|
||||
}
|
||||
className="absolute right-2 w-7 h-7 top-2 cursor-pointer"
|
||||
className="absolute right-2 w-7 h-7 top-2"
|
||||
>
|
||||
<Trash className="size-4" />
|
||||
</Button>
|
||||
|
||||
<div className="w-24 h-40 bg-gray-100 rounded-lg flex-shrink-0 overflow-hidden">
|
||||
<div className="w-24 h-40 bg-gray-100 rounded-lg overflow-hidden">
|
||||
<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}
|
||||
width={500}
|
||||
height={500}
|
||||
width={300}
|
||||
height={300}
|
||||
unoptimized
|
||||
className="object-cover"
|
||||
style={{ width: '100%', height: '100%' }}
|
||||
className="object-cover w-full h-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -181,67 +245,127 @@ const CartPage = () => {
|
||||
<h3 className="font-semibold text-lg mb-1">
|
||||
{item.product.name}
|
||||
</h3>
|
||||
<div className="flex items-center gap-2 mb-3 max-lg:flex-col max-lg:items-start max-lg:gap-1">
|
||||
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<span className="text-blue-600 font-bold text-xl">
|
||||
{formatPrice(
|
||||
item.product.prices.length !== 0
|
||||
? Math.max(
|
||||
...item.product.prices.map((e) =>
|
||||
Number(e.price),
|
||||
),
|
||||
{item.product.prices.find(
|
||||
(p) => p.price_type.code === '1',
|
||||
)
|
||||
: 0,
|
||||
? formatPrice(
|
||||
Number(
|
||||
item.product.prices.find(
|
||||
(p) => p.price_type.code === '1',
|
||||
)?.price,
|
||||
),
|
||||
true,
|
||||
)
|
||||
: formatPrice(
|
||||
Math.min(
|
||||
...item.product.prices.map((p) =>
|
||||
Number(p.price),
|
||||
),
|
||||
),
|
||||
true,
|
||||
)}
|
||||
</span>
|
||||
<span className="text-sm text-gray-500">
|
||||
/{measurementDisplay}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center border border-gray-300 rounded-lg w-max">
|
||||
<p className="text-sm text-gray-500 mb-2">
|
||||
{t('Miqdor')}: {quantity} {measurementDisplay}
|
||||
</p>
|
||||
|
||||
<div className="flex items-center border rounded-lg w-max">
|
||||
<button
|
||||
onClick={() =>
|
||||
handleQuantityChange(
|
||||
String(item.id),
|
||||
Number(quantities[item.id]) - 1,
|
||||
)
|
||||
}
|
||||
className="p-2 cursor-pointer transition rounded-lg"
|
||||
onClick={() => handleQuantityChange(item.id, -1)}
|
||||
className="p-2 hover:bg-gray-50"
|
||||
>
|
||||
<Minus className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-1 px-2">
|
||||
<Input
|
||||
value={quantities[item.id]}
|
||||
value={inputValue}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value.replace(/\D/g, ''); // faqat raqam
|
||||
setQuantities((prev) => ({
|
||||
const v = e.target.value;
|
||||
|
||||
// Faqat raqamlar va bitta nuqtaga ruxsat (vergul ham)
|
||||
if (!/^\d*[.,]?\d*$/.test(v)) return;
|
||||
|
||||
// String sifatida saqlash (nuqta yo'qolmasin)
|
||||
setInputValues((prev) => ({
|
||||
...prev,
|
||||
[item.id]: val,
|
||||
[item.id]: v,
|
||||
}));
|
||||
|
||||
// Debounce bilan update
|
||||
const valNum = Number(val);
|
||||
if (!isNaN(valNum))
|
||||
handleQuantityChange(String(item.id), valNum);
|
||||
// Bo'sh yoki faqat nuqta bo'lsa raqamga o'tkazmaymiz
|
||||
if (v === '' || v === '.' || v === ',') return;
|
||||
|
||||
const parsed = parseFloat(v.replace(',', '.'));
|
||||
if (isNaN(parsed)) return;
|
||||
|
||||
// quantities ni yangilash
|
||||
setQuantities((prev) => ({
|
||||
...prev,
|
||||
[item.id]: parsed,
|
||||
}));
|
||||
|
||||
// Debounce bilan API ga yuborish
|
||||
if (debounceRef.current[item.id])
|
||||
clearTimeout(debounceRef.current[item.id]!);
|
||||
|
||||
debounceRef.current[item.id] = setTimeout(() => {
|
||||
if (parsed <= 0) {
|
||||
deleteCartItem({
|
||||
cart_item_id: String(item.id),
|
||||
});
|
||||
} else {
|
||||
updateCartItem({
|
||||
body: { quantity: parsed },
|
||||
cart_item_id: String(item.id),
|
||||
});
|
||||
}
|
||||
}, 500);
|
||||
}}
|
||||
onBlur={() => {
|
||||
// Blur bo'lganda noto'g'ri qiymatlarni tuzatish
|
||||
const isGram =
|
||||
item.product.meansurement?.name?.toLowerCase() ===
|
||||
'gr';
|
||||
const MIN_QTY = isGram ? 100 : 0.5;
|
||||
let value = quantities[item.id] ?? item.quantity;
|
||||
|
||||
if (!value || isNaN(value) || value < MIN_QTY)
|
||||
value = MIN_QTY;
|
||||
|
||||
setInputValues((prev) => ({
|
||||
...prev,
|
||||
[item.id]: String(value),
|
||||
}));
|
||||
handleQuantityChange(item.id, 0, value);
|
||||
}}
|
||||
type="text"
|
||||
className="w-16 text-center"
|
||||
inputMode="decimal"
|
||||
className="w-16 text-center border-none p-0"
|
||||
/>
|
||||
<span className="text-xs text-gray-500">
|
||||
{measurementDisplay}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() =>
|
||||
handleQuantityChange(
|
||||
String(item.id),
|
||||
Number(quantities[item.id]) + 1,
|
||||
)
|
||||
}
|
||||
className="p-2 cursor-pointer transition rounded-lg"
|
||||
onClick={() => handleQuantityChange(item.id, 1)}
|
||||
className="p-2 hover:bg-gray-50"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -259,11 +383,9 @@ const CartPage = () => {
|
||||
<span className="flex items-center gap-1">
|
||||
<Truck className="w-4 h-4" /> {t('Yetkazib berish')}:
|
||||
</span>
|
||||
<span>
|
||||
<span className="text-green-600 font-semibold">
|
||||
{t('Bepul')}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -286,7 +408,7 @@ const CartPage = () => {
|
||||
|
||||
<button
|
||||
onClick={() => router.push('/')}
|
||||
className="w-full border-2 border-gray-300 cursor-pointer text-gray-700 py-3 rounded-lg font-semibold hover:bg-gray-50 transition flex items-center justify-center gap-2"
|
||||
className="w-full border-2 border-gray-300 text-gray-700 py-3 rounded-lg font-semibold hover:bg-gray-50 transition flex items-center justify-center gap-2"
|
||||
>
|
||||
<ArrowLeft className="w-5 h-5" /> {t('Xaridni davom ettirish')}
|
||||
</button>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
/* eslint-disable */
|
||||
import LogosProduct from '@/assets/product.png';
|
||||
import { BASE_URL } from '@/shared/config/api/URLs';
|
||||
import { useRouter } from '@/shared/config/i18n/navigation';
|
||||
import { useCartId } from '@/shared/hooks/cartId';
|
||||
import formatDate from '@/shared/lib/formatDate';
|
||||
import formatPrice from '@/shared/lib/formatPrice';
|
||||
@@ -36,12 +37,12 @@ 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 {
|
||||
Calendar as CalIcon,
|
||||
CheckCircle2,
|
||||
ChevronLeft,
|
||||
Clock,
|
||||
Loader2,
|
||||
LocateFixed,
|
||||
@@ -64,12 +65,10 @@ interface CoordsData {
|
||||
|
||||
// Yetkazib berish vaqt oraliqlar
|
||||
const deliveryTimeSlots = [
|
||||
{ id: 1, label: '09:00 - 11:00', start: '09:00', end: '11:00' },
|
||||
{ id: 2, label: '11:00 - 13:00', start: '11:00', end: '13:00' },
|
||||
{ id: 3, label: '13:00 - 15:00', start: '13:00', end: '15:00' },
|
||||
{ id: 4, label: '15:00 - 17:00', start: '15:00', end: '17:00' },
|
||||
{ id: 5, label: '17:00 - 19:00', start: '17:00', end: '19:00' },
|
||||
{ id: 6, label: '19:00 - 21:00', start: '19:00', end: '21:00' },
|
||||
{ id: 1, label: '10:00 - 12:00', start: '10:00', end: '12:00' },
|
||||
{ id: 2, label: '12:00 - 14:00', start: '12:00', end: '14:00' },
|
||||
{ id: 3, label: '14:00 - 16:00', start: '14:00', end: '16:00' },
|
||||
{ id: 4, label: '16:00 - 18:00', start: '16:00', end: '18:00' },
|
||||
];
|
||||
|
||||
const OrderPage = () => {
|
||||
@@ -83,6 +82,7 @@ const OrderPage = () => {
|
||||
long: '69.240562',
|
||||
},
|
||||
});
|
||||
const router = useRouter();
|
||||
const [cart, setCart] = useState<number | string | null>(null);
|
||||
const { cart_id } = useCartId();
|
||||
const [orderSuccess, setOrderSuccess] = useState(false);
|
||||
@@ -94,32 +94,35 @@ const OrderPage = () => {
|
||||
enabled: !!cart,
|
||||
});
|
||||
|
||||
console.log(data);
|
||||
|
||||
const { mutate, isPending } = useMutation({
|
||||
mutationFn: (body: OrderCreateBody) => cart_api.createOrder(body),
|
||||
onSuccess: (res) => {
|
||||
const message = JSON.parse(res.data.response);
|
||||
if (message.successes.length > 0) {
|
||||
|
||||
if (message.successes && message.successes.length > 0) {
|
||||
// Buyurtma muvaffaqiyatli
|
||||
setOrderSuccess(true);
|
||||
setCart(cart_id);
|
||||
|
||||
queryClinet.refetchQueries({ queryKey: ['cart_items'] });
|
||||
} else if (message.errors && message.errors.length > 0) {
|
||||
// Xatolik bo'lsa chiqarish
|
||||
toast.error(t('Xatolik yuz berdi: ') + message.errors[0].message, {
|
||||
richColors: true,
|
||||
position: 'top-center',
|
||||
});
|
||||
} else {
|
||||
// Boshqa noaniq holat
|
||||
toast.error(t('Xatolik yuz berdi'), {
|
||||
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',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
@@ -139,11 +142,13 @@ const OrderPage = () => {
|
||||
if (item.product.prices.length === 0) return sum; // narx yo'q bo'lsa qo'shmaymiz
|
||||
|
||||
// Eng yuqori narxni olish
|
||||
const maxPrice = Math.max(
|
||||
...item.product.prices.map((p) => Number(p.price)),
|
||||
);
|
||||
const maxPrice = item.product.prices.find(
|
||||
(p) => p.price_type.code === '1',
|
||||
)
|
||||
? item.product.prices.find((p) => p.price_type.code === '1')?.price
|
||||
: Math.min(...item.product.prices.map((p) => Number(p.price)));
|
||||
|
||||
return sum + maxPrice * item.quantity;
|
||||
return sum + Number(maxPrice) * item.quantity;
|
||||
}, 0) || 0; // cartItems bo'sh bo'lsa 0 qaytaradi
|
||||
|
||||
const [coords, setCoords] = useState({
|
||||
@@ -281,19 +286,21 @@ 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) {
|
||||
const dealTime = formatDate.format(deliveryDate, 'DD.MM.YYYY');
|
||||
|
||||
mutate({
|
||||
order: [
|
||||
{
|
||||
filial_code: 'dodge',
|
||||
delivery_date: formatDate.format(deliveryDate, 'DD.MM.YYYY'),
|
||||
room_code: process.env.NEXT_ROOM_CODE!,
|
||||
deal_time: formatDate.format(deliveryDate, 'DD.MM.YYYY'),
|
||||
robot_code: process.env.NEXT_ROBOT_CODE!,
|
||||
status: 'B#N',
|
||||
sales_manager_code: process.env.NEXT_SALES_MANAGER_CODE!,
|
||||
filial_code: process.env.NEXT_PUBLIC_FILIAL_CODE!,
|
||||
delivery_date: `${dealTime}`,
|
||||
room_code: process.env.NEXT_PUBLIC_ROOM_CODE!,
|
||||
deal_time: formatDate.format(new Date(), 'DD.MM.YYYY'),
|
||||
robot_code: process.env.NEXT_PUBLIC_ROBOT_CODE!,
|
||||
status: 'D',
|
||||
sales_manager_code: process.env.NEXT_PUBLIC_SALES_MANAGER_CODE!,
|
||||
person_code: user?.username,
|
||||
currency_code: '860',
|
||||
owner_person_code: user?.username,
|
||||
@@ -338,6 +345,15 @@ const OrderPage = () => {
|
||||
<div className="custom-container mb-5">
|
||||
<div>
|
||||
<div className="mb-6">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => router.back()}
|
||||
className="mb-4 w-fit px-2"
|
||||
size={'icon'}
|
||||
>
|
||||
<ChevronLeft size={32} />
|
||||
<p>{t('Orqaga')}</p>
|
||||
</Button>
|
||||
<h1 className="text-3xl font-bold text-gray-800 mb-2">
|
||||
{t('Buyurtmani rasmiylashtirish')}
|
||||
</h1>
|
||||
@@ -360,10 +376,14 @@ const OrderPage = () => {
|
||||
<FormControl>
|
||||
<Textarea
|
||||
{...field}
|
||||
maxLength={300}
|
||||
className="w-full min-h-42 max-h-64 border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:border-blue-500"
|
||||
placeholder={t('Izoh')}
|
||||
/>
|
||||
</FormControl>
|
||||
<div className="text-right text-xs text-gray-500">
|
||||
{field.value?.length || 0}/300
|
||||
</div>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
@@ -565,7 +585,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}
|
||||
@@ -579,7 +601,7 @@ const OrderPage = () => {
|
||||
{item.quantity} x{' '}
|
||||
{formatPrice(
|
||||
item.product.prices.length !== 0
|
||||
? Math.max(
|
||||
? Math.min(
|
||||
...item.product.prices.map((p) =>
|
||||
Number(p.price),
|
||||
),
|
||||
@@ -591,7 +613,7 @@ const OrderPage = () => {
|
||||
<p className="font-semibold text-sm">
|
||||
{formatPrice(
|
||||
item.product.prices.length !== 0
|
||||
? Math.max(
|
||||
? Math.min(
|
||||
...item.product.prices.map((p) =>
|
||||
Number(p.price),
|
||||
),
|
||||
|
||||
@@ -51,11 +51,13 @@ const AllProducts = () => {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
params.set('page', newPage.toString());
|
||||
|
||||
router.push(`${pathname}?${params.toString()}`, {
|
||||
scroll: true,
|
||||
});
|
||||
router.push(`${pathname}?${params.toString()}`);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
}, [page]);
|
||||
|
||||
return (
|
||||
<div className="custom-container p-4 mb-5 flex flex-col min-h-[calc(85vh)]">
|
||||
<div className="flex-1">
|
||||
@@ -100,7 +102,7 @@ const AllProducts = () => {
|
||||
<div className="w-full mt-5 flex justify-end">
|
||||
<GlobalPagination
|
||||
page={page}
|
||||
total={product.total ?? 0}
|
||||
total={product.total}
|
||||
pageSize={PAGE_SIZE}
|
||||
onChange={handlePageChange}
|
||||
/>
|
||||
|
||||
@@ -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();
|
||||
};
|
||||
@@ -54,13 +60,15 @@ const Product = () => {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
params.set('page', newPage.toString());
|
||||
|
||||
router.push(`${pathname}?${params.toString()}`, {
|
||||
scroll: true,
|
||||
});
|
||||
router.push(`${pathname}?${params.toString()}`);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
}, [page]);
|
||||
|
||||
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 +80,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) => (
|
||||
|
||||
{/* 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,41 @@
|
||||
'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}`);
|
||||
};
|
||||
|
||||
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)}
|
||||
|
||||
@@ -7,19 +7,13 @@ import { Card } from '@/shared/ui/card';
|
||||
import { Skeleton } from '@/shared/ui/skeleton';
|
||||
import { ProductCard } from '@/widgets/categories/ui/product-card';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { AxiosError } from 'axios';
|
||||
import { Heart } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export default function Favourite() {
|
||||
const router = useRouter();
|
||||
const t = useTranslations();
|
||||
const {
|
||||
data: favourite,
|
||||
isLoading,
|
||||
error,
|
||||
} = useQuery({
|
||||
const { data: favourite, isLoading } = useQuery({
|
||||
queryKey: ['favourite_product'],
|
||||
queryFn: () => product_api.favouuriteProduct(),
|
||||
select(data) {
|
||||
@@ -27,14 +21,6 @@ export default function Favourite() {
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if ((error as AxiosError)?.status === 403) {
|
||||
router.replace('/auth');
|
||||
} else if ((error as AxiosError)?.status === 401) {
|
||||
router.replace('/auth');
|
||||
}
|
||||
}, [error]);
|
||||
|
||||
if (favourite && favourite.results.length === 0) {
|
||||
return (
|
||||
<div className="min-h-screen py-12">
|
||||
|
||||
@@ -3,18 +3,13 @@
|
||||
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 { useRouter } from '@/shared/config/i18n/navigation';
|
||||
import { useCartId } from '@/shared/hooks/cartId';
|
||||
import formatPrice from '@/shared/lib/formatPrice';
|
||||
import {
|
||||
Carousel,
|
||||
CarouselContent,
|
||||
CarouselItem,
|
||||
CarouselNext,
|
||||
CarouselPrevious,
|
||||
} from '@/shared/ui/carousel';
|
||||
import { cn } from '@/shared/lib/utils';
|
||||
import { Input } from '@/shared/ui/input';
|
||||
import { Skeleton } from '@/shared/ui/skeleton';
|
||||
import { ProductCard } from '@/widgets/categories/ui/product-card';
|
||||
import { userStore } from '@/widgets/welcome/lib/hook';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { AxiosError } from 'axios';
|
||||
import { Heart, Minus, Plus, Shield, ShoppingCart, Truck } from 'lucide-react';
|
||||
@@ -29,17 +24,16 @@ const ProductDetail = () => {
|
||||
const { product } = useParams<{ product: string }>();
|
||||
const queryClient = useQueryClient();
|
||||
const { cart_id } = useCartId();
|
||||
const { user } = userStore();
|
||||
const router = useRouter();
|
||||
|
||||
const [quantity, setQuantity] = useState(1);
|
||||
const [selectedImage, setSelectedImage] = useState(0);
|
||||
const [quantity, setQuantity] = useState<number | string>(1);
|
||||
|
||||
// ✅ debounce ref
|
||||
const debounceRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
/* ---------------- CART ITEMS ---------------- */
|
||||
const { data: cartItems } = useQuery({
|
||||
queryKey: ['cart_items', cart_id],
|
||||
queryFn: () => cart_api.get_cart_items(cart_id!),
|
||||
enabled: !!cart_id,
|
||||
});
|
||||
// ✅ Flag: faqat manual input (klaviatura) da debounce ishlaydi
|
||||
const isManualInputRef = useRef(false);
|
||||
|
||||
/* ---------------- PRODUCT DETAIL ---------------- */
|
||||
const { data, isLoading } = useQuery({
|
||||
@@ -49,19 +43,62 @@ const ProductDetail = () => {
|
||||
enabled: !!product,
|
||||
});
|
||||
|
||||
/* ---------------- RECOMMENDATION ---------------- */
|
||||
const { data: recomendation, isLoading: recLoad } = useQuery({
|
||||
queryKey: ['product_list'],
|
||||
queryFn: () => product_api.list({ page: 1, page_size: 12 }),
|
||||
select: (res) => res.data.results,
|
||||
/* ---------------- CART ITEMS ---------------- */
|
||||
const { data: cartItems } = useQuery({
|
||||
queryKey: ['cart_items', cart_id],
|
||||
queryFn: () => cart_api.get_cart_items(cart_id!),
|
||||
enabled: !!cart_id,
|
||||
});
|
||||
|
||||
/* ---------------- DERIVED DATA ---------------- */
|
||||
const price = Number(data?.prices?.[0]?.price || 0);
|
||||
const favouriteMutation = useMutation({
|
||||
mutationFn: (productId: string) => product_api.favourite(productId),
|
||||
|
||||
const category = 'Ichimliklar'; // default category
|
||||
onSuccess: () => {
|
||||
queryClient.refetchQueries({ queryKey: ['product_detail'] });
|
||||
queryClient.refetchQueries({ queryKey: ['favourite_product'] });
|
||||
},
|
||||
|
||||
/* ---------------- SYNC CART QUANTITY ---------------- */
|
||||
onError: (err: AxiosError) => {
|
||||
const detail = (err.response?.data as { detail?: string })?.detail;
|
||||
toast.error(detail || err.message, {
|
||||
richColors: true,
|
||||
position: 'top-center',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const measurement = data?.meansurement?.name?.toLowerCase() || '';
|
||||
const isGram = measurement === 'gr';
|
||||
|
||||
const STEP = isGram ? 100 : 1;
|
||||
const MIN_QTY = isGram ? 100 : 1;
|
||||
|
||||
const measurementDisplay = data?.meansurement?.name || 'шт.';
|
||||
|
||||
/** Safe numeric value */
|
||||
const numericQty =
|
||||
quantity === '' || quantity === '.' || quantity === ','
|
||||
? 0
|
||||
: Number(String(quantity).replace(',', '.'));
|
||||
|
||||
const clampQuantity = (value: number) => {
|
||||
if (isNaN(value)) return MIN_QTY;
|
||||
|
||||
let safe = value;
|
||||
|
||||
if (isGram) {
|
||||
safe = Math.max(value, MIN_QTY);
|
||||
safe = Math.ceil(safe / STEP) * STEP;
|
||||
}
|
||||
|
||||
return safe;
|
||||
};
|
||||
const getQuantityMessage = (qty: number, measurement: string | null) => {
|
||||
if (!measurement) return `${qty} dona`;
|
||||
return `${qty} ${measurement}`;
|
||||
};
|
||||
|
||||
/* ---------------- SYNC CART (boshlang'ich holat) ---------------- */
|
||||
useEffect(() => {
|
||||
if (!data || !cartItems) return;
|
||||
|
||||
@@ -69,41 +106,31 @@ const ProductDetail = () => {
|
||||
(i) => Number(i.product.id) === data.id,
|
||||
);
|
||||
|
||||
setQuantity(item ? item.quantity : 1);
|
||||
}, [data, cartItems]);
|
||||
if (item) {
|
||||
setQuantity(item.quantity);
|
||||
} else {
|
||||
setQuantity(MIN_QTY);
|
||||
}
|
||||
// isManualInputRef ni reset qilish shart - bu sync, manual input emas
|
||||
isManualInputRef.current = false;
|
||||
}, [data, cartItems, MIN_QTY]);
|
||||
|
||||
/* ---------------- DEBOUNCE UPDATE ---------------- */
|
||||
useEffect(() => {
|
||||
if (!cart_id || !data || !cartItems || quantity <= 0) return;
|
||||
|
||||
const cartItem = cartItems.data.cart_item.find(
|
||||
(i) => Number(i.product.id) === data.id,
|
||||
);
|
||||
|
||||
if (!cartItem || cartItem.quantity === quantity) return;
|
||||
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
|
||||
debounceRef.current = setTimeout(() => {
|
||||
updateCartItem({
|
||||
cart_item_id: cartItem.id.toString(),
|
||||
body: { quantity },
|
||||
});
|
||||
}, 500);
|
||||
|
||||
return () => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
};
|
||||
}, [quantity]);
|
||||
|
||||
/* ---------------- ADD TO CART ---------------- */
|
||||
/* ---------------- MUTATIONS ---------------- */
|
||||
const { mutate: addToCart } = useMutation({
|
||||
mutationFn: (body: { product: string; quantity: number; cart: string }) =>
|
||||
cart_api.cart_item(body),
|
||||
onSuccess: () => {
|
||||
|
||||
onSuccess: (_, variables) => {
|
||||
queryClient.refetchQueries({ queryKey: ['cart_items'] });
|
||||
toast.success(t("Mahsulot savatga qo'shildi"), { richColors: true });
|
||||
|
||||
const measurementName = data?.meansurement?.name || null;
|
||||
|
||||
toast.success(
|
||||
`${getQuantityMessage(variables.quantity, measurementName)} ${t("savatga qo'shildi")}`,
|
||||
{ richColors: true, position: 'top-center' },
|
||||
);
|
||||
},
|
||||
|
||||
onError: (err: AxiosError) => {
|
||||
const msg =
|
||||
(err.response?.data as { detail: string })?.detail || err.message;
|
||||
@@ -116,27 +143,66 @@ const ProductDetail = () => {
|
||||
cart_item_id: string;
|
||||
body: { quantity: number };
|
||||
}) => cart_api.update_cart_item(payload),
|
||||
onSuccess: () => queryClient.refetchQueries({ queryKey: ['cart_items'] }),
|
||||
|
||||
onSuccess: (_, variables) => {
|
||||
queryClient.refetchQueries({ queryKey: ['cart_items'] });
|
||||
|
||||
const measurementName = data?.meansurement?.name || null;
|
||||
|
||||
toast.success(
|
||||
`${t('Miqdor')} ${getQuantityMessage(variables.body.quantity, measurementName)} ${t('ga yangilandi')}`,
|
||||
{ richColors: true, position: 'top-center' },
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
/* ---------------- FAVOURITE ---------------- */
|
||||
const favouriteMutation = useMutation({
|
||||
mutationFn: (id: string) => product_api.favourite(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['product_detail'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['product_list'] });
|
||||
},
|
||||
onError: () => {
|
||||
/* ---------------- DEBOUNCE UPDATE (faqat manual input uchun) ---------------- */
|
||||
useEffect(() => {
|
||||
// ✅ Faqat klaviatura orqali yozilganda ishlaydi
|
||||
if (!isManualInputRef.current) return;
|
||||
if (!cart_id || !data || !cartItems) return;
|
||||
|
||||
const cartItem = cartItems.data.cart_item.find(
|
||||
(i) => Number(i.product.id) === data.id,
|
||||
);
|
||||
|
||||
if (!cartItem || cartItem.quantity === numericQty) return;
|
||||
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
|
||||
debounceRef.current = setTimeout(() => {
|
||||
if (numericQty >= MIN_QTY) {
|
||||
updateCartItem({
|
||||
cart_item_id: cartItem.id.toString(),
|
||||
body: { quantity: numericQty },
|
||||
});
|
||||
}
|
||||
isManualInputRef.current = false;
|
||||
}, 500);
|
||||
|
||||
return () => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
};
|
||||
}, [numericQty]);
|
||||
|
||||
/* ---------------- HANDLERS ---------------- */
|
||||
const handleAddToCart = () => {
|
||||
if (user === null) {
|
||||
router.push('/auth');
|
||||
return;
|
||||
}
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
isManualInputRef.current = false;
|
||||
|
||||
if (!data || !cart_id) {
|
||||
toast.error(t('Tizimga kirilmagan'), {
|
||||
richColors: true,
|
||||
position: 'top-center',
|
||||
});
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
/* ---------------- HANDLERS ---------------- */
|
||||
const handleAddToCart = () => {
|
||||
if (!data || !cart_id) return;
|
||||
const normalizedQty = clampQuantity(numericQty);
|
||||
|
||||
const cartItem = cartItems?.data.cart_item.find(
|
||||
(i) => Number(i.product.id) === data.id,
|
||||
@@ -145,17 +211,48 @@ const ProductDetail = () => {
|
||||
if (cartItem) {
|
||||
updateCartItem({
|
||||
cart_item_id: cartItem.id.toString(),
|
||||
body: { quantity },
|
||||
body: { quantity: normalizedQty },
|
||||
});
|
||||
} else {
|
||||
addToCart({
|
||||
product: String(data.id),
|
||||
cart: cart_id,
|
||||
quantity,
|
||||
quantity: normalizedQty,
|
||||
});
|
||||
}
|
||||
setQuantity(normalizedQty);
|
||||
};
|
||||
|
||||
const handleIncrease = () => {
|
||||
// ✅ Bu manual input emas - flag ni false qoldirish
|
||||
isManualInputRef.current = false;
|
||||
|
||||
setQuantity((q) => {
|
||||
const base = q === '' || q === '.' || q === ',' ? 0 : Number(q);
|
||||
let next = base + STEP;
|
||||
if (isGram) next = Math.ceil(next / STEP) * STEP;
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handleDecrease = () => {
|
||||
// ✅ Bu manual input emas - flag ni false qoldirish
|
||||
isManualInputRef.current = false;
|
||||
|
||||
setQuantity((q) => {
|
||||
const base = q === '' || q === '.' || q === ',' ? MIN_QTY : Number(q);
|
||||
let next = base - STEP;
|
||||
if (isGram) next = Math.floor(next / STEP) * STEP;
|
||||
return Math.max(next, MIN_QTY);
|
||||
});
|
||||
};
|
||||
|
||||
const subtotal = data?.prices?.length
|
||||
? data.prices.find((p) => p.price_type.code === '1')
|
||||
? data.prices.find((p) => p.price_type.code === '1')?.price
|
||||
: Math.min(...data.prices.map((p) => Number(p.price)))
|
||||
: 0;
|
||||
|
||||
/* ---------------- LOADING ---------------- */
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -165,102 +262,83 @@ const ProductDetail = () => {
|
||||
);
|
||||
}
|
||||
|
||||
/* ===================== RENDER ===================== */
|
||||
return (
|
||||
<div className="custom-container pb-8">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8 bg-white p-6 rounded-lg shadow">
|
||||
{/* IMAGES */}
|
||||
<div>
|
||||
<Image
|
||||
width={500}
|
||||
unoptimized
|
||||
height={500}
|
||||
unoptimized
|
||||
src={
|
||||
data?.images?.length
|
||||
? BASE_URL + data.images[selectedImage]?.image
|
||||
? data.images[0]?.image?.includes(BASE_URL)
|
||||
? data.images[0]?.image
|
||||
: BASE_URL + data.images[0]?.image
|
||||
: '/placeholder.svg'
|
||||
}
|
||||
alt={data?.name || 'logo'}
|
||||
className="w-full h-[400px] object-contain"
|
||||
/>
|
||||
<Carousel className="mt-4">
|
||||
<CarouselContent>
|
||||
{(data?.images?.length
|
||||
? data.images
|
||||
: [{ id: 0, image: '/placeholder.svg' }]
|
||||
).map((img, i) => (
|
||||
<CarouselItem key={i} className="basis-1/4">
|
||||
<button
|
||||
onClick={() => setSelectedImage(i)}
|
||||
className={`border rounded-lg p-1 ${
|
||||
i === selectedImage
|
||||
? 'border-blue-500'
|
||||
: 'border-gray-200'
|
||||
}`}
|
||||
>
|
||||
<Image
|
||||
src={img.image!}
|
||||
alt={data?.name || 'Mahsulot rasmi'}
|
||||
width={120}
|
||||
height={120}
|
||||
className="object-contain"
|
||||
unoptimized
|
||||
/>
|
||||
</button>
|
||||
</CarouselItem>
|
||||
))}
|
||||
</CarouselContent>
|
||||
</Carousel>
|
||||
</div>
|
||||
|
||||
{/* 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 className="flex items-baseline gap-2 mb-4">
|
||||
<span className="text-4xl font-bold text-blue-600">
|
||||
{formatPrice(Number(subtotal), true)}
|
||||
</span>
|
||||
<span className="text-xl text-gray-500">/{measurementDisplay}</span>
|
||||
</div>
|
||||
|
||||
<p className="text-gray-600 mb-6">{data?.short_name}</p>
|
||||
<div className="mb-6">
|
||||
<label className="block text-sm font-medium mb-2">
|
||||
{t('Miqdor')}
|
||||
</label>
|
||||
|
||||
<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>
|
||||
|
||||
<div className="flex items-center gap-4 mb-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
onClick={() => setQuantity((q) => Math.max(1, q - 1))}
|
||||
className="p-2 border rounded"
|
||||
onClick={handleDecrease}
|
||||
disabled={numericQty <= MIN_QTY}
|
||||
className="p-2 border rounded hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Minus />
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
value={quantity}
|
||||
onChange={(e) => {
|
||||
const v = Number(e.target.value);
|
||||
if (v > 0) setQuantity(v);
|
||||
const v = e.target.value;
|
||||
|
||||
if (!/^\d*([.,]\d*)?$/.test(v)) return;
|
||||
|
||||
// ✅ Faqat shu yerda manual input flag yoqiladi
|
||||
isManualInputRef.current = true;
|
||||
setQuantity(v);
|
||||
}}
|
||||
className="w-16 text-center"
|
||||
className="w-24 text-center"
|
||||
/>
|
||||
<span className="text-sm text-gray-500">
|
||||
{measurementDisplay}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => setQuantity((q) => q + 1)}
|
||||
className="p-2 border rounded"
|
||||
onClick={handleIncrease}
|
||||
className="p-2 border rounded hover:bg-gray-50"
|
||||
>
|
||||
<Plus />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mb-6 font-semibold">
|
||||
{t('Jami')}: {formatPrice(price * quantity, true)}
|
||||
</div>
|
||||
|
||||
{/* ACTIONS */}
|
||||
<div className="flex gap-3 mb-6">
|
||||
<div className="mb-6 text-xl font-semibold">
|
||||
{t('Jami')}: {formatPrice(Number(subtotal) * numericQty, true)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
onClick={handleAddToCart}
|
||||
className="flex-1 bg-green-600 hover:bg-green-700 text-white py-3 rounded-lg flex justify-center items-center gap-2"
|
||||
@@ -270,10 +348,19 @@ const ProductDetail = () => {
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => favouriteMutation.mutate(String(data?.id))}
|
||||
className={`p-3 rounded-lg border ${
|
||||
data?.liked ? 'border-red-500 bg-red-50' : 'border-gray-300'
|
||||
}`}
|
||||
className={cn(
|
||||
'p-3 rounded-lg border cursor-pointer',
|
||||
data?.liked ? 'border-red-500 bg-red-50' : 'border-gray-300',
|
||||
)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (user === null) {
|
||||
router.push('/auth');
|
||||
return;
|
||||
} else {
|
||||
favouriteMutation.mutate(String(data?.id));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Heart
|
||||
className={data?.liked ? 'fill-red-500 text-red-500' : ''}
|
||||
@@ -281,46 +368,18 @@ const ProductDetail = () => {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* FEATURES */}
|
||||
<div className="grid grid-cols-2 gap-4 mt-6 border-t pt-4">
|
||||
<div className="text-center">
|
||||
<Truck className="mx-auto mb-1" />
|
||||
{t('Bepul yetkazib berish')}
|
||||
<p className="text-sm">{t('Bepul yetkazib berish')}</p>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<Shield className="mx-auto mb-1" />
|
||||
{t('Kafolat')}
|
||||
<p className="text-sm">{t('Kafolat')}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* RELATED */}
|
||||
<div className="mt-10 bg-white p-6 rounded-lg shadow">
|
||||
<h2 className="text-2xl font-bold mb-4">{t("O'xshash mahsulotlar")}</h2>
|
||||
|
||||
<Carousel>
|
||||
<CarouselContent>
|
||||
{recLoad &&
|
||||
Array.from({ length: 6 }).map((_, i) => (
|
||||
<CarouselItem key={i} className="basis-1/5">
|
||||
<Skeleton className="h-60 w-full" />
|
||||
</CarouselItem>
|
||||
))}
|
||||
|
||||
{recomendation
|
||||
?.filter((p) => p.state === 'A')
|
||||
.map((p) => (
|
||||
<CarouselItem key={p.id} className="basis-1/5">
|
||||
<ProductCard product={p} />
|
||||
</CarouselItem>
|
||||
))}
|
||||
</CarouselContent>
|
||||
|
||||
<CarouselPrevious />
|
||||
<CarouselNext />
|
||||
</Carousel>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -3,13 +3,60 @@ 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: OrderItem[];
|
||||
}
|
||||
|
||||
export default interface OrderItem {
|
||||
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 +88,10 @@ export interface OrderListRes {
|
||||
expires_date: string;
|
||||
manufacturer: string;
|
||||
volume: string;
|
||||
images: [
|
||||
{
|
||||
images: {
|
||||
id: string;
|
||||
image: string;
|
||||
},
|
||||
];
|
||||
}[];
|
||||
};
|
||||
price: number;
|
||||
quantity: number;
|
||||
@@ -57,11 +102,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,245 +1,272 @@
|
||||
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 { useSearchParams } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { order_api, OrderListRes } from '../lib/api';
|
||||
import Image from 'next/image';
|
||||
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;
|
||||
},
|
||||
queryKey: ['order_list'],
|
||||
queryFn: () => order_api.list(),
|
||||
select: (res) => res.data,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const urlPage = Number(searchParams.get('page')) || 1;
|
||||
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 px-4">
|
||||
<div className="bg-gray-100 p-6 rounded-full mb-4">
|
||||
<Package className="w-12 h-12 text-gray-400" />
|
||||
</div>
|
||||
<p className="text-lg 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-xs">
|
||||
{t(
|
||||
"Hali buyurtma qilmagansiz. Mahsulotlarni ko'rib chiqing va birinchi buyurtmangizni bering!",
|
||||
)}
|
||||
</p>
|
||||
<Button
|
||||
onClick={() => router.push('/')}
|
||||
className="mt-6 w-full max-w-xs"
|
||||
>
|
||||
<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">
|
||||
<div className="w-full px-3 md:px-0">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-4 pb-3 border-b">
|
||||
<div>
|
||||
<h2 className="text-xl md:text-3xl font-bold text-gray-900">
|
||||
{t('Buyurtmalar tarixi')}
|
||||
</h2>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{data.results.length} ta buyurtma
|
||||
<p className="text-xs md:text-sm text-gray-500 mt-0.5">
|
||||
{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-3 md: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,
|
||||
)}
|
||||
<Card
|
||||
key={order.id}
|
||||
className="border border-gray-200 hover:border-blue-400 transition-all duration-200 shadow-sm hover:shadow-md rounded-xl overflow-hidden"
|
||||
>
|
||||
<StatusIcon
|
||||
className={cn(
|
||||
'w-4 h-4 md:w-5 md:h-5',
|
||||
statusConfig.textColor,
|
||||
<CardContent className="p-0">
|
||||
{/* Order Header */}
|
||||
<div className="bg-gradient-to-r from-blue-50 to-indigo-50 px-3 py-2.5 md:p-4 border-b border-gray-200">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
{/* Order ID */}
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="bg-blue-600 text-white px-2.5 py-1 rounded-full text-xs font-bold">
|
||||
#{order.id}
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">
|
||||
{t('Buyurtma raqami')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Delivery date - compact on mobile */}
|
||||
{order.delivery_date && (
|
||||
<div className="flex items-center gap-1.5 bg-white px-2 py-1 rounded-lg shadow-sm">
|
||||
<Calendar className="w-3.5 h-3.5 text-blue-600 flex-shrink-0" />
|
||||
<div>
|
||||
<p className="text-[10px] text-gray-500 leading-none">
|
||||
{t('Yetkazib berish')}
|
||||
</p>
|
||||
<p className="text-xs font-semibold text-gray-800 mt-0.5">
|
||||
{order.delivery_date}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Comment */}
|
||||
{order.comment && (
|
||||
<div className="mt-2 bg-white p-2.5 rounded-lg shadow-sm border border-gray-100">
|
||||
<div className="flex items-start gap-2">
|
||||
<MessageSquare className="w-3.5 h-3.5 text-blue-600 mt-0.5 flex-shrink-0" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-[10px] font-medium text-gray-500 mb-0.5">
|
||||
{t('Izoh')}:
|
||||
</p>
|
||||
<p className="text-xs text-gray-700 leading-relaxed line-clamp-3">
|
||||
{order.comment}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Products */}
|
||||
<div className="p-2.5 md:p-4 space-y-2 md:space-y-3">
|
||||
{order.items.map((item, index) => {
|
||||
const product = item.product;
|
||||
|
||||
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 border-gray-100 rounded-lg p-2.5 md:p-4 bg-white hover:shadow-sm transition-shadow"
|
||||
>
|
||||
<div className="flex gap-2.5 md:gap-4">
|
||||
{/* Image — smaller on mobile */}
|
||||
<div className="flex-shrink-0">
|
||||
<div className="w-14 h-14 md:w-24 md:h-24 bg-gray-50 rounded-lg overflow-hidden border border-gray-200">
|
||||
<Image
|
||||
src={productImage}
|
||||
alt={product.name}
|
||||
width={96}
|
||||
height={96}
|
||||
className="w-full h-full object-contain"
|
||||
unoptimized
|
||||
/>
|
||||
</div>
|
||||
|
||||
{idx < data.results.length - 1 && (
|
||||
<div className="w-0.5 flex-1 bg-slate-200 my-2" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 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}
|
||||
{/* Info */}
|
||||
<div className="flex-1 min-w-0">
|
||||
{/* Name row */}
|
||||
<div className="flex items-start justify-between gap-1 mb-1.5">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
<span className="bg-blue-100 text-blue-800 text-[10px] font-semibold px-1.5 py-0.5 rounded flex-shrink-0">
|
||||
{index + 1}
|
||||
</span>
|
||||
<h3 className="font-bold text-sm text-gray-900 truncate">
|
||||
{product.name}
|
||||
</h3>
|
||||
</div>
|
||||
<p className="text-sm font-bold text-blue-600 flex-shrink-0">
|
||||
{formatPrice(Number(item.price), true)}
|
||||
</p>
|
||||
<span
|
||||
className={cn(
|
||||
'text-xs px-2 py-0.5 rounded-full',
|
||||
statusConfig.bgColor,
|
||||
statusConfig.textColor,
|
||||
)}
|
||||
>
|
||||
{statusConfig.text}
|
||||
</span>
|
||||
</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',
|
||||
|
||||
{product.short_name && (
|
||||
<p className="text-xs text-gray-500 line-clamp-1 mb-1.5">
|
||||
{product.short_name}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Qty + Total — single row on mobile */}
|
||||
<div className="flex items-center justify-between bg-gray-50 rounded-lg px-2.5 py-1.5 border border-gray-100">
|
||||
<div>
|
||||
<span className="text-[10px] text-gray-400 block">
|
||||
{t('Miqdor')}
|
||||
</span>
|
||||
<span className="text-xs font-bold">
|
||||
{item.quantity}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="font-bold text-base md:text-lg text-foreground">
|
||||
<span className="text-[10px] text-gray-400 block">
|
||||
{t('Jami')}
|
||||
</span>
|
||||
<span className="text-xs font-bold text-green-600">
|
||||
{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,
|
||||
Number(item.price) * item.quantity,
|
||||
true,
|
||||
)}
|
||||
</span>
|
||||
</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>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="w-full flex justify-end mt-5">
|
||||
<GlobalPagination
|
||||
onChange={handlePageChange}
|
||||
page={page}
|
||||
total={data.total_pages}
|
||||
pageSize={PAGE_SIZE}
|
||||
/>
|
||||
{/* Footer */}
|
||||
<div className="bg-gradient-to-r from-gray-50 to-blue-50 px-3 py-3 md:p-4 border-t border-gray-200">
|
||||
<div className="space-y-1 text-xs md:text-sm">
|
||||
<div className="flex justify-between text-gray-500">
|
||||
<span>{t('Mahsulotlar narxi')}:</span>
|
||||
<span className="font-semibold text-gray-700">
|
||||
{formatPrice(totalPrice, true)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between text-gray-500">
|
||||
<span>{t('Mahsulotlar soni')}:</span>
|
||||
<span className="font-semibold text-gray-700">
|
||||
{order.items.reduce(
|
||||
(sum, item) => sum + item.quantity,
|
||||
0,
|
||||
)}{' '}
|
||||
{t('dona')}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-dashed pt-2 flex justify-between items-center">
|
||||
<span className="font-bold text-sm md:text-base">
|
||||
{t('Umumiy summa')}:
|
||||
</span>
|
||||
<span className="text-base md:text-2xl font-bold text-green-600">
|
||||
{formatPrice(totalPrice, true)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
router.push(`/profile/refresh-order?id=${order.id}`)
|
||||
}
|
||||
className="w-full mt-3 gap-2 text-sm h-9"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
{t('Qayta buyurtma')}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
import { useRouter } from '@/shared/config/i18n/navigation';
|
||||
import { useCartId } from '@/shared/hooks/cartId';
|
||||
import { removeToken } from '@/shared/lib/token';
|
||||
import { removeRefToken, removeToken } from '@/shared/lib/token';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/shared/ui/avatar';
|
||||
import { Button } from '@/shared/ui/button';
|
||||
import { banner_api } from '@/widgets/welcome/lib/api';
|
||||
import { userStore } from '@/widgets/welcome/lib/hook';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
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 +18,23 @@ const Profile = () => {
|
||||
const router = useRouter();
|
||||
const t = useTranslations();
|
||||
const queryClient = useQueryClient();
|
||||
const { user } = userStore();
|
||||
const { setCartId } = useCartId();
|
||||
const { setUser } = userStore();
|
||||
|
||||
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 },
|
||||
@@ -34,7 +44,7 @@ const Profile = () => {
|
||||
const renderContent = () => {
|
||||
switch (activeSection) {
|
||||
case 'support':
|
||||
router.push('https://t.me/web_app_0515_bot');
|
||||
router.push('https://t.me/gastrohubbot');
|
||||
|
||||
default:
|
||||
return <HistoryTabs />;
|
||||
@@ -73,14 +83,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>
|
||||
@@ -107,13 +117,12 @@ const Profile = () => {
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
queryClient.refetchQueries({ queryKey: ['product_list'] });
|
||||
queryClient.refetchQueries({ queryKey: ['favourite_product'] });
|
||||
queryClient.refetchQueries({ queryKey: ['cart_items'] });
|
||||
queryClient.refetchQueries({ queryKey: ['search'] });
|
||||
setCartId(null);
|
||||
removeToken();
|
||||
router.push('/');
|
||||
removeToken();
|
||||
removeRefToken();
|
||||
setCartId(null);
|
||||
setUser(null);
|
||||
queryClient.refetchQueries();
|
||||
}}
|
||||
className="w-full justify-start gap-3 text-red-500 hover:text-red-600 hover:bg-red-50 mt-4"
|
||||
>
|
||||
@@ -123,20 +132,20 @@ const Profile = () => {
|
||||
</div>
|
||||
|
||||
{/* Main Content */}
|
||||
<main className="flex-1 md:p-4 lg:p-8 lg:pb-8">
|
||||
<main className="flex-1 p-2 overflow-hidden">
|
||||
<div className="lg:hidden flex items-center justify-between mb-4 md:mb-6">
|
||||
<div className="flex items-center gap-2 md:gap-3">
|
||||
<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>
|
||||
@@ -144,14 +153,9 @@ const Profile = () => {
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => {
|
||||
queryClient.refetchQueries({ queryKey: ['product_list'] });
|
||||
queryClient.refetchQueries({ queryKey: ['cart_items'] });
|
||||
queryClient.refetchQueries({
|
||||
queryKey: ['favourite_product'],
|
||||
});
|
||||
queryClient.refetchQueries({ queryKey: ['search'] });
|
||||
queryClient.refetchQueries();
|
||||
removeToken();
|
||||
setCartId(null);
|
||||
removeRefToken();
|
||||
router.push('/');
|
||||
}}
|
||||
className="w-9 h-9 md:w-10 md:h-10"
|
||||
|
||||
@@ -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';
|
||||
@@ -25,6 +26,7 @@ import {
|
||||
SelectValue,
|
||||
} from '@/shared/ui/select';
|
||||
import { Textarea } from '@/shared/ui/textarea';
|
||||
import { userStore } from '@/widgets/welcome/lib/hook';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import {
|
||||
Map,
|
||||
@@ -33,7 +35,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,23 +43,27 @@ import {
|
||||
Loader2,
|
||||
LocateFixed,
|
||||
MapPin,
|
||||
Minus,
|
||||
Package,
|
||||
Plus,
|
||||
ShoppingBag,
|
||||
Trash2,
|
||||
User,
|
||||
} from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import Image from 'next/image';
|
||||
import { useRouter, 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 OrderItem, { order_api } from '../lib/api';
|
||||
|
||||
const deliveryTimeSlots = [
|
||||
{ id: 1, label: '09:00 - 11:00', start: '09:00', end: '11:00' },
|
||||
{ id: 2, label: '11:00 - 13:00', start: '11:00', end: '13:00' },
|
||||
{ id: 3, label: '13:00 - 15:00', start: '13:00', end: '15:00' },
|
||||
{ id: 4, label: '15:00 - 17:00', start: '15:00', end: '17:00' },
|
||||
{ id: 5, label: '17:00 - 19:00', start: '17:00', end: '19:00' },
|
||||
{ id: 6, label: '19:00 - 21:00', start: '19:00', end: '21:00' },
|
||||
{ id: 1, label: '10:00 - 12:00', start: '10:00', end: '12:00' },
|
||||
{ id: 2, label: '12:00 - 14:00', start: '12:00', end: '14:00' },
|
||||
{ id: 3, label: '14:00 - 16:00', start: '14:00', end: '16:00' },
|
||||
{ id: 4, label: '16:00 - 18:00', start: '16:00', end: '18:00' },
|
||||
];
|
||||
|
||||
interface CoordsData {
|
||||
@@ -69,46 +75,61 @@ interface CoordsData {
|
||||
const RefreshOrder = () => {
|
||||
const [deliveryDate, setDeliveryDate] = useState<Date>();
|
||||
const [selectedTimeSlot, setSelectedTimeSlot] = useState<string>('');
|
||||
const { order: initialValues } = useOrderStore();
|
||||
const [orderItems, setOrderItems] = useState<OrderItem[]>([]);
|
||||
const { user } = userStore();
|
||||
const [quantityInputs, setQuantityInputs] = useState<Record<number, string>>(
|
||||
{},
|
||||
);
|
||||
|
||||
const t = useTranslations();
|
||||
const queryClient = useQueryClient();
|
||||
const searchParams = useSearchParams();
|
||||
const router = useRouter();
|
||||
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));
|
||||
|
||||
useEffect(() => {
|
||||
if (initialValues?.items) {
|
||||
const items = initialValues.items.map((item: OrderItem) => ({ ...item }));
|
||||
setOrderItems(items);
|
||||
const inputs: Record<number, string> = {};
|
||||
items.forEach((item: OrderItem) => {
|
||||
inputs[item.id] = String(item.quantity);
|
||||
});
|
||||
setQuantityInputs(inputs);
|
||||
}
|
||||
}, [initialValues]);
|
||||
|
||||
const form = useForm<z.infer<typeof orderForm>>({
|
||||
resolver: zodResolver(orderForm),
|
||||
defaultValues: {
|
||||
comment: '',
|
||||
comment: initialValues?.comment || '',
|
||||
lat: '41.311081',
|
||||
long: '69.240562',
|
||||
},
|
||||
});
|
||||
|
||||
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'), {
|
||||
@@ -127,6 +148,66 @@ const RefreshOrder = () => {
|
||||
[number, number][][] | null
|
||||
>(null);
|
||||
|
||||
// Input o'zgarishi — foydalanuvchi "0.5", "1.75" yoza oladi
|
||||
const handleQuantityInput = (itemId: number, value: string) => {
|
||||
// Faqat raqam va nuqtaga ruxsat
|
||||
if (!/^(\d+\.?\d*)?$/.test(value)) return;
|
||||
setQuantityInputs((prev) => ({ ...prev, [itemId]: value }));
|
||||
|
||||
const parsed = parseFloat(value);
|
||||
if (!isNaN(parsed) && parsed > 0) {
|
||||
setOrderItems((prev) =>
|
||||
prev.map((item) =>
|
||||
item.id === itemId ? { ...item, quantity: parsed } : item,
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Blur — bo'sh yoki 0 qiymatni 1 ga qaytarish
|
||||
const handleQuantityBlur = (itemId: number) => {
|
||||
const val = parseFloat(quantityInputs[itemId]);
|
||||
if (!val || val <= 0) {
|
||||
setQuantityInputs((prev) => ({ ...prev, [itemId]: '1' }));
|
||||
setOrderItems((prev) =>
|
||||
prev.map((item) =>
|
||||
item.id === itemId ? { ...item, quantity: 1 } : item,
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// ± tugmalar — 0.5 qadamda o'zgartirish
|
||||
const updateQuantity = (itemId: number, delta: number) => {
|
||||
setOrderItems((prev) =>
|
||||
prev.map((item) => {
|
||||
if (item.id !== itemId) return item;
|
||||
const newQty = Math.max(
|
||||
0.5,
|
||||
Math.round((item.quantity + delta) * 100) / 100,
|
||||
);
|
||||
setQuantityInputs((inputs) => ({
|
||||
...inputs,
|
||||
[itemId]: String(newQty),
|
||||
}));
|
||||
return { ...item, quantity: newQty };
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
// Item o'chirish — agar 0 ta qolsa profile sahifaga yo'naltiradi
|
||||
const deleteItem = (itemId: number) => {
|
||||
const updated = orderItems.filter((item) => item.id !== itemId);
|
||||
setOrderItems(updated);
|
||||
if (updated.length === 0) {
|
||||
toast.info(t('Buyurtmada mahsulot qolmadi'), {
|
||||
richColors: true,
|
||||
position: 'top-center',
|
||||
});
|
||||
router.push('/profile');
|
||||
}
|
||||
};
|
||||
|
||||
const getCoords = async (name: string): Promise<CoordsData | null> => {
|
||||
const res = await fetch(
|
||||
`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(
|
||||
@@ -164,7 +245,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(
|
||||
@@ -188,11 +269,7 @@ const RefreshOrder = () => {
|
||||
const timeout = setTimeout(async () => {
|
||||
const result = await getCoords(cityValue);
|
||||
if (!result) return;
|
||||
setCoords({
|
||||
latitude: result.lat,
|
||||
longitude: result.lon,
|
||||
zoom: 12,
|
||||
});
|
||||
setCoords({ latitude: result.lat, longitude: result.lon, zoom: 12 });
|
||||
setPolygonCoords(result.polygon);
|
||||
form.setValue('lat', result.lat.toString(), { shouldDirty: true });
|
||||
form.setValue('long', result.lon.toString(), { shouldDirty: true });
|
||||
@@ -217,15 +294,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 = orderItems
|
||||
.filter(
|
||||
(item) =>
|
||||
item.product.prices &&
|
||||
@@ -239,30 +316,70 @@ const RefreshOrder = () => {
|
||||
on_balance: 'Y',
|
||||
order_quant: item.quantity,
|
||||
price_type_code: item.product.prices![0].price_type.code,
|
||||
product_price: item.product.prices![0].price,
|
||||
warehouse_code: 'wh1',
|
||||
product_price: item.price,
|
||||
warehouse_code: process.env.NEXT_PUBLIC_WARHOUSES_CODE!,
|
||||
}));
|
||||
if (user) {
|
||||
const dealTime = formatDate.format(deliveryDate, 'DD.MM.YYYY');
|
||||
|
||||
mutate({
|
||||
order: [
|
||||
{
|
||||
filial_code: 'dodge',
|
||||
delivery_date: formatDate.format(deliveryDate, 'DD.MM.YYYY'),
|
||||
room_code: '100',
|
||||
deal_time: formatDate.format(deliveryDate, 'DD.MM.YYYY'),
|
||||
robot_code: 'r2',
|
||||
status: 'B#N',
|
||||
sales_manager_code: '1',
|
||||
person_code: '12345678',
|
||||
filial_code: process.env.NEXT_PUBLIC_FILIAL_CODE!,
|
||||
delivery_date: `${dealTime}`,
|
||||
room_code: process.env.NEXT_PUBLIC_ROOM_CODE!,
|
||||
deal_time: formatDate.format(new Date(), 'DD.MM.YYYY'),
|
||||
robot_code: process.env.NEXT_PUBLIC_ROBOT_CODE!,
|
||||
status: 'D',
|
||||
sales_manager_code: process.env.NEXT_PUBLIC_SALES_MANAGER_CODE!,
|
||||
person_code: user?.username,
|
||||
currency_code: '860',
|
||||
owner_person_code: '1234567',
|
||||
owner_person_code: user?.username,
|
||||
note: value.comment,
|
||||
order_products: order_products,
|
||||
},
|
||||
],
|
||||
});
|
||||
} else {
|
||||
toast.error(t('Xatolik yuz berdi'), {
|
||||
richColors: true,
|
||||
position: 'top-center',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const totalPrice = orderItems.reduce(
|
||||
(sum, item) => sum + Number(item.price) * item.quantity,
|
||||
0,
|
||||
);
|
||||
|
||||
const totalItems = orderItems.reduce((sum, item) => sum + item.quantity, 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 +391,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 +410,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)}>
|
||||
@@ -322,10 +442,14 @@ const RefreshOrder = () => {
|
||||
<FormControl>
|
||||
<Textarea
|
||||
{...field}
|
||||
maxLength={300}
|
||||
className="w-full min-h-42 max-h-64 border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:border-blue-500"
|
||||
placeholder={t('Izoh')}
|
||||
/>
|
||||
</FormControl>
|
||||
<div className="text-right text-xs text-gray-500">
|
||||
{field.value?.length || 0}/300
|
||||
</div>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
@@ -409,7 +533,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 +634,105 @@ 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">
|
||||
<div className="space-y-3 mb-4 max-h-96 overflow-y-auto">
|
||||
{orderItems.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
|
||||
width={500}
|
||||
height={500}
|
||||
src={item.product_image}
|
||||
alt={item.product_name}
|
||||
src={productImage}
|
||||
alt={item.product.name}
|
||||
width={64}
|
||||
height={64}
|
||||
className="w-full h-full object-contain"
|
||||
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}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-start justify-between gap-1">
|
||||
<h4 className="font-semibold text-sm text-gray-900 truncate">
|
||||
{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">
|
||||
{/* O'chirish tugmasi */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => deleteItem(item.id)}
|
||||
className="flex-shrink-0 w-6 h-6 flex items-center justify-center rounded-full text-red-400 hover:text-red-600 hover:bg-red-50 transition"
|
||||
title={t("O'chirish")}
|
||||
>
|
||||
<Trash2 className="w-8 h-8" />
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-sm font-bold text-blue-600 mt-1">
|
||||
{formatPrice(
|
||||
Number(item.product_price) * item.quantity,
|
||||
Number(item.price) * item.quantity,
|
||||
true,
|
||||
)}
|
||||
</p>
|
||||
|
||||
{/* Quantity — input + ± tugmalar */}
|
||||
<div className="flex items-center gap-1 mt-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => updateQuantity(item.id, -1)}
|
||||
className="w-7 h-7 max-lg:w-10 max-lg:h-10 flex items-center justify-center rounded-full border border-gray-300 bg-white hover:bg-gray-100 transition"
|
||||
>
|
||||
<Minus className="w-3 h-3 max-lg:w-4 max-lg:h-4" />
|
||||
</button>
|
||||
<input
|
||||
type="text"
|
||||
inputMode="decimal"
|
||||
value={quantityInputs[item.id] ?? item.quantity}
|
||||
onChange={(e) =>
|
||||
handleQuantityInput(item.id, e.target.value)
|
||||
}
|
||||
onBlur={() => handleQuantityBlur(item.id)}
|
||||
className="w-14 h-7 max-lg:w-24 max-lg:h-10 text-center text-sm font-semibold border border-gray-300 rounded-md focus:outline-none focus:border-blue-500"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => updateQuantity(item.id, 1)}
|
||||
className="w-7 h-7 max-lg:w-10 max-lg:h-10 flex items-center justify-center rounded-full border border-gray-300 bg-white hover:bg-gray-100 transition"
|
||||
>
|
||||
<Plus className="w-3 h-3 max-lg:w-4 max-lg:h-4" />
|
||||
</button>
|
||||
</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 +741,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 +755,7 @@ const RefreshOrder = () => {
|
||||
{isPending ? (
|
||||
<span className="flex items-center justify-center gap-2">
|
||||
<Loader2 className="animate-spin" />
|
||||
{t('Yuklanmoqda...')}
|
||||
</span>
|
||||
) : (
|
||||
t('Buyurtmani tasdiqlash')
|
||||
|
||||
@@ -3,36 +3,31 @@
|
||||
import { product_api } from '@/shared/config/api/product/api';
|
||||
import { ProductListResult } from '@/shared/config/api/product/type';
|
||||
import { useRouter } from '@/shared/config/i18n/navigation';
|
||||
import { Button } from '@/shared/ui/button';
|
||||
import { Input } from '@/shared/ui/input';
|
||||
import { ProductCard } from '@/widgets/categories/ui/product-card';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Search, X } from 'lucide-react';
|
||||
import { Search } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
|
||||
const SearchResult = () => {
|
||||
const router = useRouter();
|
||||
const t = useTranslations();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const query = searchParams.get('q') || '';
|
||||
const query = searchParams.get('search') || '';
|
||||
const [inputValue, setInputValue] = useState(query);
|
||||
|
||||
/* 🔹 Input va URL sync */
|
||||
useEffect(() => {
|
||||
setInputValue(query);
|
||||
}, [query]);
|
||||
|
||||
/* 🔹 Default product list */
|
||||
const { data: productList, isLoading: listLoading } = useQuery({
|
||||
queryKey: ['product_list'],
|
||||
queryFn: () => product_api.list({ page: 1, page_size: 12 }),
|
||||
select: (res) => res.data.results,
|
||||
enabled: !query,
|
||||
staleTime: 0,
|
||||
});
|
||||
|
||||
/* 🔹 Search query */
|
||||
const { data: searchList, isLoading: searchLoading } = useQuery({
|
||||
queryKey: ['search', query],
|
||||
queryFn: () =>
|
||||
@@ -41,32 +36,14 @@ const SearchResult = () => {
|
||||
page: 1,
|
||||
page_size: 12,
|
||||
}),
|
||||
select: (res) => {
|
||||
return res.data.products;
|
||||
},
|
||||
select: (res) => res.data.products,
|
||||
enabled: !!query,
|
||||
staleTime: 0,
|
||||
});
|
||||
|
||||
const data = query ? (searchList ?? []) : (productList ?? []);
|
||||
const isLoading = query ? searchLoading : listLoading;
|
||||
|
||||
/* 🔹 Handlers */
|
||||
const handleSearch = (value: string) => {
|
||||
setInputValue(value);
|
||||
|
||||
if (!value.trim()) {
|
||||
router.push('/search');
|
||||
return;
|
||||
}
|
||||
|
||||
router.push(`/search?q=${encodeURIComponent(value)}`);
|
||||
};
|
||||
|
||||
const clearSearch = () => {
|
||||
setInputValue('');
|
||||
router.push('/search');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="custom-container min-h-screen">
|
||||
{/* 🔍 Search input */}
|
||||
@@ -77,18 +54,27 @@ const SearchResult = () => {
|
||||
<Input
|
||||
value={inputValue}
|
||||
placeholder={t('Mahsulot nomi')}
|
||||
onChange={(e) => handleSearch(e.target.value)}
|
||||
onChange={(e) => setInputValue(e.target.value)}
|
||||
className="w-full pl-10 pr-10 h-12"
|
||||
/>
|
||||
|
||||
{inputValue && (
|
||||
<Button
|
||||
className="absolute top-0 right-0 h-12 cursor-pointer"
|
||||
onClick={() =>
|
||||
router.replace(`/search?search=${encodeURIComponent(inputValue)}`)
|
||||
}
|
||||
>
|
||||
{t('Qidirish')}
|
||||
</Button>
|
||||
|
||||
{/* {inputValue && (
|
||||
<button
|
||||
onClick={clearSearch}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2"
|
||||
>
|
||||
<X />
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
)}
|
||||
)} */}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -97,10 +83,10 @@ const SearchResult = () => {
|
||||
<div className="text-center py-20">{t('Yuklanmoqda')}...</div>
|
||||
) : data.length > 0 ? (
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
|
||||
{data.map((products) => (
|
||||
{data.map((product) => (
|
||||
<ProductCard
|
||||
product={products as ProductListResult}
|
||||
key={(products as ProductListResult).id}
|
||||
key={(product as ProductListResult).id}
|
||||
product={product as ProductListResult}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -7,6 +7,7 @@ export const API_URLS = {
|
||||
Banner: `${API_V}shared/banner/list/`,
|
||||
Category: `${API_V}products/category/list/`,
|
||||
Product: `${API_V}products/product/`,
|
||||
ProductList: `${API_V}products/all/`,
|
||||
Login: `${API_V}accounts/login/`,
|
||||
Search_Product: `${API_V}products/search/`,
|
||||
Favourite: (product_id: string) => `${API_V}accounts/${product_id}/like/`,
|
||||
@@ -23,4 +24,5 @@ export const API_URLS = {
|
||||
OrderList: `${API_V}orders/order/list/`,
|
||||
Refresh_Token: `${API_V}accounts/refresh/token/`,
|
||||
Get_Me: `${API_V}accounts/me/`,
|
||||
About: `${API_V}shared/aboutus/`,
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -12,7 +12,10 @@ export interface ProductListResult {
|
||||
id: number;
|
||||
images: { id: number; image: string }[];
|
||||
liked: boolean;
|
||||
meansurement: null | string;
|
||||
meansurement: {
|
||||
id: number;
|
||||
name: string;
|
||||
} | null;
|
||||
inventory_id: null | string;
|
||||
product_id: string;
|
||||
code: string;
|
||||
@@ -23,8 +26,9 @@ export interface ProductListResult {
|
||||
litr: null | string;
|
||||
box_type_code: null | string;
|
||||
box_quant: null | string;
|
||||
groups: number[];
|
||||
groups: { id: number; name: string };
|
||||
state: 'A' | 'P';
|
||||
payment_type: 'cash' | 'card' | null;
|
||||
barcodes: string;
|
||||
article_code: null | string;
|
||||
marketing_group_code: null | string;
|
||||
@@ -36,8 +40,10 @@ export interface ProductListResult {
|
||||
price_type: {
|
||||
id: number;
|
||||
name: string;
|
||||
code: string;
|
||||
};
|
||||
}[];
|
||||
balance: number;
|
||||
}
|
||||
|
||||
export interface ProductDetail {
|
||||
@@ -55,19 +61,23 @@ 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;
|
||||
price_type: {
|
||||
id: number;
|
||||
name: string;
|
||||
code: string;
|
||||
};
|
||||
}[];
|
||||
}
|
||||
@@ -94,7 +104,10 @@ export interface FavouriteProductRes {
|
||||
id: number;
|
||||
images: { id: number; image: string }[];
|
||||
liked: boolean;
|
||||
meansurement: null | string;
|
||||
meansurement: {
|
||||
id: number;
|
||||
name: string;
|
||||
} | null;
|
||||
inventory_id: null | string;
|
||||
product_id: string;
|
||||
code: string;
|
||||
@@ -105,19 +118,22 @@ export interface FavouriteProductRes {
|
||||
litr: null | string;
|
||||
box_type_code: null | string;
|
||||
box_quant: null | string;
|
||||
groups: number[];
|
||||
groups: { id: number; name: string };
|
||||
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;
|
||||
price_type: {
|
||||
id: number;
|
||||
name: string;
|
||||
code: string;
|
||||
};
|
||||
}[];
|
||||
}
|
||||
|
||||
@@ -204,5 +204,26 @@
|
||||
"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": "Цена может быть изменена",
|
||||
"ga yangilandi": "обновлено"
|
||||
}
|
||||
|
||||
@@ -204,5 +204,26 @@ 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";
|
||||
'ga yangilandi': 'ga yangilandi';
|
||||
};
|
||||
export default messages;
|
||||
|
||||
@@ -200,5 +200,26 @@
|
||||
"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",
|
||||
"ga yangilandi": "ga yangilandi"
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import { Button } from './button';
|
||||
type GlobalPaginationProps = {
|
||||
page: number;
|
||||
total: number;
|
||||
pageSize?: number;
|
||||
pageSize: number;
|
||||
onChange: (page: number) => void;
|
||||
};
|
||||
|
||||
@@ -42,7 +42,7 @@ const getPages = (current: number, total: number) => {
|
||||
export const GlobalPagination = ({
|
||||
page,
|
||||
total,
|
||||
pageSize = 36,
|
||||
pageSize,
|
||||
onChange,
|
||||
}: GlobalPaginationProps) => {
|
||||
const totalPages = Math.ceil(total / pageSize);
|
||||
|
||||
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,84 +1,103 @@
|
||||
'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 { Card } from '@/shared/ui/card';
|
||||
import {
|
||||
Carousel,
|
||||
CarouselApi,
|
||||
CarouselContent,
|
||||
CarouselItem,
|
||||
type CarouselApi,
|
||||
} from '@/shared/ui/carousel';
|
||||
import { Skeleton } from '@/shared/ui/skeleton';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { ProductCard } from '@/widgets/categories/ui/product-card';
|
||||
import { ProductRes } from '@/widgets/welcome/lib/api';
|
||||
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: ProductRes;
|
||||
isLoading: boolean;
|
||||
isError: boolean;
|
||||
}
|
||||
|
||||
const CategoryCarousel = memo(function CategoryCarousel({
|
||||
category,
|
||||
isLoading,
|
||||
isError,
|
||||
}: 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 scrollPrev = () => api?.scrollPrev();
|
||||
const scrollNext = () => api?.scrollNext();
|
||||
|
||||
const scrollNext = () => {
|
||||
if (api) {
|
||||
api?.scrollNext();
|
||||
if (!isVisible) {
|
||||
return (
|
||||
<section
|
||||
ref={sectionRef}
|
||||
className="relative custom-container mt-5 min-h-[300px]"
|
||||
/>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const { data: product, isLoading } = useQuery({
|
||||
queryKey: ['product_list', category],
|
||||
queryFn: () =>
|
||||
product_api.listGetCategoryId({
|
||||
category_id: category.id,
|
||||
params: { page: 1, page_size: 16 },
|
||||
}),
|
||||
select(data) {
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
if (product?.results.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const activeProducts =
|
||||
category?.products?.filter((p) => p.state === 'A') ?? [];
|
||||
|
||||
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"
|
||||
onClick={() => router.push(`/category/${category.id}/`)}
|
||||
>
|
||||
<h2 className="text-2xl font-bold text-slate-800 group-hover:text-blue-600 transition-colors">
|
||||
{category.name}
|
||||
{category.name || '---'}
|
||||
</h2>
|
||||
<div className="p-1.5 bg-slate-100 rounded-full group-hover:bg-blue-100 transition-all">
|
||||
<ChevronRight className="text-slate-600 group-hover:text-blue-600 group-hover:translate-x-0.5 transition-all" />
|
||||
@@ -86,10 +105,14 @@ export function CategoryCarousel({ category }: { category: CategoryResult }) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Carousel className="w-full mt-2" setApi={setApi}>
|
||||
<Carousel
|
||||
opts={{ align: 'start', dragFree: true }}
|
||||
className="w-full mt-2"
|
||||
setApi={setApi}
|
||||
>
|
||||
<CarouselContent className="pr-[12%] sm:pr-0">
|
||||
{isLoading &&
|
||||
Array.from({ length: 6 }).map((__, index) => (
|
||||
{isLoading || isError || activeProducts.length === 0
|
||||
? 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"
|
||||
@@ -101,12 +124,8 @@ export function CategoryCarousel({ category }: { category: CategoryResult }) {
|
||||
<Skeleton className="h-10 w-full rounded-lg" />
|
||||
</Card>
|
||||
</CarouselItem>
|
||||
))}
|
||||
{product &&
|
||||
!isLoading &&
|
||||
product.results
|
||||
.filter((product) => product.state === 'A')
|
||||
.map((product) => (
|
||||
))
|
||||
: 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"
|
||||
@@ -116,6 +135,7 @@ export function CategoryCarousel({ category }: { category: CategoryResult }) {
|
||||
))}
|
||||
</CarouselContent>
|
||||
</Carousel>
|
||||
|
||||
<Button
|
||||
onClick={scrollNext}
|
||||
className={cn(
|
||||
@@ -138,7 +158,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 +165,6 @@ export function CategoryCarousel({ category }: { category: CategoryResult }) {
|
||||
</Button>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
export default CategoryCarousel;
|
||||
|
||||
@@ -16,9 +16,10 @@ import { Button } from '@/shared/ui/button';
|
||||
import { Card, CardContent } from '@/shared/ui/card';
|
||||
import { Input } from '@/shared/ui/input';
|
||||
import { FlyingAnimationPortal } from '@/widgets/animation/FlyingAnimationPortal';
|
||||
import { userStore } from '@/widgets/welcome/lib/hook';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { AxiosError } from 'axios';
|
||||
import { Heart, Minus, Plus, ShoppingCart } from 'lucide-react';
|
||||
import { Heart, Minus, Plus } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import Image from 'next/image';
|
||||
import { MouseEvent, useEffect, useRef, useState } from 'react';
|
||||
@@ -33,24 +34,41 @@ export function ProductCard({
|
||||
error?: boolean;
|
||||
}) {
|
||||
const { setProduct } = useProductStore();
|
||||
const [quantity, setQuantity] = useState<number | ''>(0);
|
||||
const [quantity, setQuantity] = useState<number | string>(0);
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const t = useTranslations();
|
||||
const { cart_id } = useCartId();
|
||||
const [animated, setAnimated] = useState<boolean>(false);
|
||||
const [animated, setAnimated] = useState(false);
|
||||
const debounceRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const imageRef = useRef<HTMLDivElement>(null);
|
||||
const { user } = userStore();
|
||||
|
||||
const { mutate } = useMutation({
|
||||
/** ✅ Measurement */
|
||||
const measurementName = product.meansurement?.name ?? null;
|
||||
const isGram = measurementName === 'gr';
|
||||
|
||||
const defaultQty = isGram ? 100 : 1;
|
||||
const step = isGram ? 100 : 1;
|
||||
const measurementDisplay = measurementName || 'шт.';
|
||||
|
||||
/** 🛒 Add */
|
||||
const { mutate: addToCart } = useMutation({
|
||||
mutationFn: (body: { product: string; quantity: number; cart: string }) =>
|
||||
cart_api.cart_item(body),
|
||||
onSuccess: () => {
|
||||
|
||||
onSuccess: (_, variables) => {
|
||||
queryClient.refetchQueries({ queryKey: ['cart_items'] });
|
||||
setAnimated(true);
|
||||
|
||||
toast.success(
|
||||
`${variables.quantity} ${measurementDisplay} ${t("savatga qo'shildi")}`,
|
||||
{ richColors: true, position: 'top-center' },
|
||||
);
|
||||
},
|
||||
|
||||
onError: (err: AxiosError) => {
|
||||
const detail = (err.response?.data as { detail: string }).detail;
|
||||
const detail = (err.response?.data as { detail?: string })?.detail;
|
||||
toast.error(detail || err.message, {
|
||||
richColors: true,
|
||||
position: 'top-center',
|
||||
@@ -58,6 +76,7 @@ export function ProductCard({
|
||||
},
|
||||
});
|
||||
|
||||
/** 🔄 Update */
|
||||
const { mutate: updateCartItem } = useMutation({
|
||||
mutationFn: ({
|
||||
body,
|
||||
@@ -66,33 +85,32 @@ export function ProductCard({
|
||||
body: { quantity: number };
|
||||
cart_item_id: string;
|
||||
}) => cart_api.update_cart_item({ body, cart_item_id }),
|
||||
|
||||
onSuccess: () => {
|
||||
queryClient.refetchQueries({ queryKey: ['cart_items'] });
|
||||
setAnimated(true);
|
||||
},
|
||||
onError: (err: AxiosError) => {
|
||||
toast.error(err.message, { richColors: true, position: 'top-center' });
|
||||
},
|
||||
});
|
||||
|
||||
/** ❌ Delete */
|
||||
const { mutate: deleteCartItem } = useMutation({
|
||||
mutationFn: ({ cart_item_id }: { cart_item_id: string }) =>
|
||||
cart_api.delete_cart_item(cart_item_id),
|
||||
|
||||
onSuccess: () => {
|
||||
queryClient.refetchQueries({ queryKey: ['cart_items'] });
|
||||
setAnimated(true);
|
||||
},
|
||||
onError: (err: AxiosError) => {
|
||||
toast.error(err.message, { richColors: true, position: 'top-center' });
|
||||
},
|
||||
});
|
||||
|
||||
/** 📦 Cart */
|
||||
const { data: cartItems } = useQuery({
|
||||
queryKey: ['cart_items', cart_id],
|
||||
queryFn: () => cart_api.get_cart_items(cart_id!),
|
||||
enabled: !!cart_id,
|
||||
});
|
||||
|
||||
/** 🔁 Sync */
|
||||
useEffect(() => {
|
||||
const item = cartItems?.data?.cart_item?.find(
|
||||
(item) => Number(item.product.id) === product.id,
|
||||
@@ -101,76 +119,84 @@ export function ProductCard({
|
||||
setQuantity(item ? item.quantity : 0);
|
||||
}, [cartItems, product.id]);
|
||||
|
||||
const getCartItemId = () =>
|
||||
cartItems?.data.cart_item.find(
|
||||
(item) => Number(item.product.id) === product.id,
|
||||
)?.id;
|
||||
|
||||
const numericQty =
|
||||
quantity === '' || quantity === '.' || quantity === ','
|
||||
? 0
|
||||
: Number(String(quantity).replace(',', '.'));
|
||||
|
||||
/** ➖ Decrease */
|
||||
const decrease = (e: MouseEvent<HTMLButtonElement>) => {
|
||||
e.stopPropagation();
|
||||
if (!cartItems) return;
|
||||
|
||||
const newQty = numericQty - step;
|
||||
const id = getCartItemId();
|
||||
if (!id) return;
|
||||
|
||||
if (newQty <= 0) {
|
||||
setQuantity(0);
|
||||
deleteCartItem({ cart_item_id: id.toString() });
|
||||
return;
|
||||
}
|
||||
|
||||
setQuantity(newQty);
|
||||
|
||||
updateCartItem({
|
||||
cart_item_id: id.toString(),
|
||||
body: { quantity: newQty },
|
||||
});
|
||||
};
|
||||
|
||||
/** ➕ Increase */
|
||||
const increase = (e: MouseEvent<HTMLButtonElement>) => {
|
||||
e.stopPropagation();
|
||||
|
||||
const newQty = numericQty + step;
|
||||
const id = getCartItemId();
|
||||
if (!id) return;
|
||||
|
||||
setQuantity(newQty);
|
||||
|
||||
updateCartItem({
|
||||
cart_item_id: id.toString(),
|
||||
body: { quantity: newQty },
|
||||
});
|
||||
};
|
||||
|
||||
/** ❤️ Favourite */
|
||||
const favouriteMutation = useMutation({
|
||||
mutationFn: (productId: string) => product_api.favourite(productId),
|
||||
|
||||
onSuccess: () => {
|
||||
queryClient.refetchQueries({ queryKey: ['product_list'] });
|
||||
queryClient.refetchQueries({ queryKey: ['list'] });
|
||||
queryClient.refetchQueries({ queryKey: ['favourite_product'] });
|
||||
queryClient.refetchQueries({ queryKey: ['search'] });
|
||||
queryClient.refetchQueries({ queryKey: ['product_detail', product] });
|
||||
},
|
||||
|
||||
onError: () => {
|
||||
toast.error(t('Tizimga kirilmagan'), {
|
||||
onError: (err: AxiosError) => {
|
||||
const detail = (err.response?.data as { detail?: string })?.detail;
|
||||
toast.error(detail || err.message, {
|
||||
richColors: true,
|
||||
position: 'top-center',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
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();
|
||||
|
||||
if (!cartItems) return;
|
||||
|
||||
const currentQty = quantity === '' ? 0 : quantity;
|
||||
const newQty = currentQty - 1;
|
||||
|
||||
const cartItemId = cartItems.data.cart_item.find(
|
||||
(item) => Number(item.product.id) === product.id,
|
||||
)?.id;
|
||||
|
||||
if (!cartItemId) return;
|
||||
|
||||
if (newQty <= 0) {
|
||||
setQuantity(0);
|
||||
deleteCartItem({ cart_item_id: cartItemId.toString() });
|
||||
return;
|
||||
}
|
||||
|
||||
setQuantity(newQty);
|
||||
updateCartItem({
|
||||
body: { quantity: newQty },
|
||||
cart_item_id: cartItemId.toString(),
|
||||
});
|
||||
};
|
||||
const price = product.prices.find((p) => p.price_type.code === '1')
|
||||
? product.prices.find((p) => p.price_type.code === '1')?.price
|
||||
: Math.min(...product.prices.map((p) => Number(p.price)));
|
||||
|
||||
/** ❌ Error */
|
||||
if (error) {
|
||||
return (
|
||||
<Card className="p-4 rounded-xl">
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>Xatolik</AlertTitle>
|
||||
<AlertDescription>{t('Mahsulotni yuklab bo‘lmadi')}</AlertDescription>
|
||||
<AlertTitle>{t('Xatolik')}</AlertTitle>
|
||||
<AlertDescription>{t("Mahsulotni yuklab bo'lmadi")}</AlertDescription>
|
||||
</Alert>
|
||||
</Card>
|
||||
);
|
||||
@@ -188,25 +214,21 @@ export function ProductCard({
|
||||
>
|
||||
<CardContent className="p-0 flex flex-col h-full">
|
||||
<div className="relative overflow-hidden">
|
||||
{/* {product. > 0 && (
|
||||
<div className="absolute top-2 left-2 z-10 bg-orange-500 text-white px-2 py-0.5 rounded-full text-xs sm:text-sm font-bold">
|
||||
-{product.discount}%
|
||||
</div>
|
||||
)} */}
|
||||
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (user === null) {
|
||||
router.push('/auth');
|
||||
return;
|
||||
} else {
|
||||
favouriteMutation.mutate(String(product.id));
|
||||
}
|
||||
}}
|
||||
aria-label="liked"
|
||||
className="absolute top-2 right-2 z-10 bg-white hover:bg-gray-200 cursor-pointer rounded-full p-1.5 sm:p-2 shadow hover:scale-110"
|
||||
className="absolute top-2 right-2 z-10 bg-white hover:bg-gray-200 rounded-full p-2 shadow"
|
||||
>
|
||||
<Heart
|
||||
className={`w-4 h-4 sm:w-5 sm:h-5 ${
|
||||
product.liked
|
||||
? 'fill-red-500 text-red-500'
|
||||
: 'text-slate-400 hover:text-red-400'
|
||||
className={`w-4 h-4 ${
|
||||
product.liked ? 'fill-red-500 text-red-500' : 'text-slate-400'
|
||||
}`}
|
||||
/>
|
||||
</Button>
|
||||
@@ -216,7 +238,7 @@ export function ProductCard({
|
||||
fill
|
||||
src={
|
||||
product.images.length > 0
|
||||
? product?.images[0].image?.includes(BASE_URL)
|
||||
? product.images[0].image?.includes(BASE_URL)
|
||||
? product.images[0].image
|
||||
: BASE_URL + product.images[0].image
|
||||
: LogosProduct
|
||||
@@ -228,106 +250,83 @@ export function ProductCard({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-3 sm:p-4 space-y-1 flex-1">
|
||||
{/* <div className="flex items-center gap-2">
|
||||
<Star className="w-3.5 h-3.5 sm:w-4 sm:h-4 fill-orange-400 text-orange-400" />
|
||||
<span className="text-xs sm:text-sm font-semibold text-orange-600">
|
||||
{product.rating}
|
||||
</span>
|
||||
</div> */}
|
||||
|
||||
<h3 className="text-sm sm:text-base font-semibold text-slate-800 line-clamp-1">
|
||||
{product.name}
|
||||
</h3>
|
||||
|
||||
<div>
|
||||
<div className="p-3 sm:p-4 space-y-2 flex-1">
|
||||
{product.prices.length > 0 && (
|
||||
<span className="text-lg sm:text-xl font-bold text-green-600">
|
||||
{formatPrice(
|
||||
Math.max(...product.prices.map((p) => Number(p.price))),
|
||||
true,
|
||||
)}
|
||||
<p className="text-lg font-bold">
|
||||
{formatPrice(Number(price), true)}
|
||||
<span className="text-sm text-slate-500 ml-1">
|
||||
/{measurementDisplay}
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* {product. && (
|
||||
<div className="text-xs sm:text-sm text-slate-400 line-through">
|
||||
{formatPrice(product.oldPrice, true)}
|
||||
</div>
|
||||
)} */}
|
||||
</div>
|
||||
<h3 className="text-sm font-medium line-clamp-2">{product.name}</h3>
|
||||
</div>
|
||||
|
||||
<div className="p-3 sm:p-4 pt-0">
|
||||
{quantity === 0 ? (
|
||||
{typeof quantity === 'number' && quantity === 0 ? (
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
mutate({
|
||||
|
||||
if (user) {
|
||||
addToCart({
|
||||
product: String(product.id),
|
||||
quantity: 1,
|
||||
quantity: defaultQty,
|
||||
cart: cart_id!,
|
||||
});
|
||||
} else {
|
||||
router.push('/auth');
|
||||
}
|
||||
}}
|
||||
className="w-full h-9 sm:h-11 text-sm bg-green-600 hover:bg-green-600/80"
|
||||
className="w-full bg-white border border-slate-300 text-slate-700"
|
||||
>
|
||||
<ShoppingCart className="w-4 h-4 mr-1" />
|
||||
{t('Savatga')}
|
||||
</Button>
|
||||
) : (
|
||||
<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-slate-300 rounded-lg h-10"
|
||||
>
|
||||
<Button size="icon" variant="ghost" onClick={decrease}>
|
||||
<Minus className="w-4 h-4" />
|
||||
</Button>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
value={quantity}
|
||||
className="border-none text-center focus-visible:border-none focus-visible:ring-0"
|
||||
className="border-none text-center w-16"
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
|
||||
// ❌ faqat raqam
|
||||
if (!/^\d*$/.test(v)) return;
|
||||
/** ✅ Decimal + comma */
|
||||
if (!/^\d*([.,]\d*)?$/.test(v)) return;
|
||||
|
||||
// ⛔ oldingi debounce'ni tozalaymiz
|
||||
if (debounceRef.current) {
|
||||
if (debounceRef.current)
|
||||
clearTimeout(debounceRef.current);
|
||||
}
|
||||
|
||||
// bo‘sh input — faqat UI
|
||||
if (v === '') {
|
||||
setQuantity('');
|
||||
return;
|
||||
}
|
||||
setQuantity(v);
|
||||
|
||||
const num = Number(v);
|
||||
setQuantity(num);
|
||||
const id = getCartItemId();
|
||||
if (!id) return;
|
||||
|
||||
if (!cartItems) return;
|
||||
const num = Number(v.replace(',', '.'));
|
||||
|
||||
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() });
|
||||
return;
|
||||
}
|
||||
|
||||
// 🕒 debounce bilan UPDATE
|
||||
debounceRef.current = setTimeout(() => {
|
||||
updateCartItem({
|
||||
body: { quantity: num },
|
||||
cart_item_id: cartItemId.toString(),
|
||||
if (num === 0) {
|
||||
deleteCartItem({
|
||||
cart_item_id: id.toString(),
|
||||
});
|
||||
} else if (!isNaN(num)) {
|
||||
updateCartItem({
|
||||
cart_item_id: id.toString(),
|
||||
body: { quantity: num },
|
||||
});
|
||||
}
|
||||
}, 500);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button size="icon" variant="ghost" onClick={increase}>
|
||||
<Plus className="w-4 h-4" />
|
||||
@@ -337,6 +336,7 @@ export function ProductCard({
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<FlyingAnimationPortal
|
||||
product={product}
|
||||
animated={animated}
|
||||
|
||||
@@ -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 })),
|
||||
}));
|
||||
|
||||
@@ -48,7 +48,7 @@ const NavbarMobile = () => {
|
||||
|
||||
useEffect(() => {
|
||||
if (cartItems) {
|
||||
const total = cartItems.reduce((sum, item) => sum + item.quantity, 0);
|
||||
const total = cartItems.length;
|
||||
setCartQuenty(total > 9 ? 9 : total);
|
||||
}
|
||||
}, [cartItems]);
|
||||
|
||||
@@ -99,7 +99,6 @@ export const SearchResult = ({ query }: SearchResultProps) => {
|
||||
|
||||
{list
|
||||
.filter((item) => item.state === 'A')
|
||||
.slice(0, 5)
|
||||
.map((product) => {
|
||||
const image =
|
||||
product.images.length > 0
|
||||
@@ -107,7 +106,9 @@ export const SearchResult = ({ query }: SearchResultProps) => {
|
||||
? product.images[0].image
|
||||
: BASE_URL + product.images[0].image
|
||||
: LogosProduct;
|
||||
const price = product.prices?.[0]?.price;
|
||||
const price = product.prices.find((p) => p.price_type.code === '1')
|
||||
? product.prices.find((p) => p.price_type.code === '1')?.price
|
||||
: Math.min(...product.prices.map((p) => Number(p.price)));
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -128,11 +129,9 @@ export const SearchResult = ({ query }: SearchResultProps) => {
|
||||
<p className="text-sm font-medium text-slate-900 line-clamp-2">
|
||||
{product.name}
|
||||
</p>
|
||||
{price && (
|
||||
<p className="text-sm font-semibold text-[#57A595] mt-1">
|
||||
{formatPrice(price)}
|
||||
{formatPrice(Number(price), true)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -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);
|
||||
@@ -94,7 +104,7 @@ const Navbar = () => {
|
||||
|
||||
useEffect(() => {
|
||||
if (cartItems) {
|
||||
const total = cartItems.reduce((sum, item) => sum + item.quantity, 0);
|
||||
const total = cartItems.length;
|
||||
setCartQuenty(total > 9 ? 9 : total);
|
||||
} else if (cart_id === null) {
|
||||
setCartQuenty(0);
|
||||
@@ -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
|
||||
@@ -419,7 +429,7 @@ const Navbar = () => {
|
||||
onBlur={() => setTimeout(() => setSearchOpen(false), 200)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && query.trim()) {
|
||||
router.push(`/search?q=${encodeURIComponent(query)}`);
|
||||
router.push(`/search?search=${encodeURIComponent(query)}`);
|
||||
setSearchOpen(false);
|
||||
}
|
||||
}}
|
||||
@@ -443,7 +453,14 @@ const Navbar = () => {
|
||||
<Button
|
||||
variant={'ghost'}
|
||||
className="h-10 max-lg:hidden cursor-pointer border border-slate-200"
|
||||
onClick={() => router.push('/favourite')}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (token) {
|
||||
router.push('/favourite');
|
||||
return;
|
||||
}
|
||||
router.push('/auth');
|
||||
}}
|
||||
aria-label="my favouurite product"
|
||||
>
|
||||
<Heart className="size-4 text-foreground" />
|
||||
@@ -451,7 +468,14 @@ const Navbar = () => {
|
||||
<Button
|
||||
variant={'ghost'}
|
||||
id="cart-icon"
|
||||
onClick={() => router.push('/cart')}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (token) {
|
||||
router.push('/cart');
|
||||
return;
|
||||
}
|
||||
router.push('/auth');
|
||||
}}
|
||||
className="h-10 relative max-lg:hidden cursor-pointer border border-slate-200"
|
||||
>
|
||||
<ShoppingCart className="size-4 text-foreground" />
|
||||
@@ -483,12 +507,13 @@ 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) => {
|
||||
{category &&
|
||||
category.map((e, index) => {
|
||||
const isActive = active?.name === e.name;
|
||||
|
||||
return (
|
||||
@@ -503,19 +528,22 @@ const Navbar = () => {
|
||||
: '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'}`}
|
||||
>
|
||||
<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 ${isActive ? 'text-blue-700' : 'text-slate-700'}`}
|
||||
className={`text-sm font-medium truncate ${
|
||||
isActive ? 'text-blue-700' : 'text-slate-700'
|
||||
}`}
|
||||
>
|
||||
{e.name}
|
||||
</p>
|
||||
@@ -538,21 +566,30 @@ const Navbar = () => {
|
||||
{active?.name}
|
||||
</h3>
|
||||
|
||||
{active && active?.product_types?.length > 0 ? (
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{active?.subCategories.map((sub, index) => (
|
||||
{active.product_types.map((sub, index) => (
|
||||
<Button
|
||||
key={index}
|
||||
onClick={() => {
|
||||
setCloseToolbar(false);
|
||||
router.push(`/category/${active.name}/${sub.name}`);
|
||||
router.push(`/category/${active.id}/${sub.id}`);
|
||||
}}
|
||||
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"
|
||||
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>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import httpClient from '@/shared/config/api/httpClient';
|
||||
import { ProductListResult } from '@/shared/config/api/product/type';
|
||||
import { API_URLS } from '@/shared/config/api/URLs';
|
||||
import { AxiosResponse } from 'axios';
|
||||
import { BannerRes } from './type';
|
||||
@@ -26,6 +27,12 @@ export interface UserRes {
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface ProductRes {
|
||||
id: number;
|
||||
name: string;
|
||||
products: ProductListResult[];
|
||||
}
|
||||
|
||||
export const banner_api = {
|
||||
async getBanner(): Promise<AxiosResponse<BannerRes[]>> {
|
||||
const res = await httpClient.get(API_URLS.Banner);
|
||||
@@ -35,4 +42,9 @@ export const banner_api = {
|
||||
const res = await httpClient.get(API_URLS.Get_Me);
|
||||
return res;
|
||||
},
|
||||
|
||||
async getAllProducts(): Promise<AxiosResponse<ProductRes[]>> {
|
||||
const res = await httpClient.get(API_URLS.ProductList);
|
||||
return res;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -6,10 +6,10 @@ type State = {
|
||||
};
|
||||
|
||||
type Actions = {
|
||||
setUser: (qty: UserRes) => void;
|
||||
setUser: (qty: UserRes | null) => void;
|
||||
};
|
||||
|
||||
export const userStore = create<State & Actions>((set) => ({
|
||||
user: null,
|
||||
setUser: (user: UserRes) => set(() => ({ user })),
|
||||
setUser: (user: UserRes | null) => set(() => ({ user })),
|
||||
}));
|
||||
|
||||
@@ -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,19 @@ const Welcome = () => {
|
||||
queryKey: ['category_list'],
|
||||
queryFn: () => category_api.getCategory({ page: 1, page_size: 99 }),
|
||||
select(data) {
|
||||
return data.data.results;
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
data: allProducts,
|
||||
isLoading: allProductsLoading,
|
||||
isError: allProductsError,
|
||||
} = useQuery({
|
||||
queryKey: ['all_products'],
|
||||
queryFn: () => banner_api.getAllProducts(),
|
||||
select(data) {
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -89,10 +100,6 @@ const Welcome = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const scrollPrevCar = () => {
|
||||
apiCat?.scrollPrev();
|
||||
};
|
||||
|
||||
const scrollNext = () => {
|
||||
if (api?.canScrollNext()) {
|
||||
api?.scrollNext();
|
||||
@@ -101,10 +108,6 @@ const Welcome = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const scrollNextCat = () => {
|
||||
apiCat?.scrollNext();
|
||||
};
|
||||
|
||||
const { data: product, isLoading: productLoading } = useQuery({
|
||||
queryKey: ['list'],
|
||||
queryFn: () =>
|
||||
@@ -120,7 +123,14 @@ const Welcome = () => {
|
||||
return (
|
||||
<>
|
||||
<div className="custom-container">
|
||||
<Carousel className="w-full" setApi={setApi}>
|
||||
<Carousel
|
||||
className="w-full"
|
||||
setApi={setApi}
|
||||
opts={{
|
||||
align: 'start',
|
||||
dragFree: true, // 🔥 free scroll
|
||||
}}
|
||||
>
|
||||
<CarouselContent>
|
||||
{isLoading && (
|
||||
<CarouselItem className="relative">
|
||||
@@ -172,7 +182,13 @@ const Welcome = () => {
|
||||
</CarouselContent>
|
||||
</Carousel>
|
||||
|
||||
<Carousel className="w-full mt-5" setApi={setApiCat}>
|
||||
<Carousel
|
||||
opts={{
|
||||
align: 'start',
|
||||
dragFree: true,
|
||||
}}
|
||||
className="w-full mt-5"
|
||||
>
|
||||
<CarouselContent className="py-2 px-1 pr-[12%]">
|
||||
{category &&
|
||||
category.map((banner, index) => (
|
||||
@@ -200,24 +216,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">
|
||||
@@ -239,7 +237,14 @@ const Welcome = () => {
|
||||
<div className="p-1.5 bg-slate-100 rounded-full group-hover:bg-blue-100 transition-all"></div>
|
||||
</div>
|
||||
</div>
|
||||
<Carousel className="w-full" setApi={setApiPro}>
|
||||
<Carousel
|
||||
opts={{
|
||||
align: 'start',
|
||||
dragFree: true,
|
||||
}}
|
||||
className="w-full"
|
||||
setApi={setApiPro}
|
||||
>
|
||||
<CarouselContent className="pr-[12%] sm:pr-0">
|
||||
{productLoading &&
|
||||
Array.from({ length: 6 }).map((__, index) => (
|
||||
@@ -268,7 +273,7 @@ const Welcome = () => {
|
||||
</CarouselItem>
|
||||
))}
|
||||
</CarouselContent>
|
||||
</Carousel>{' '}
|
||||
</Carousel>
|
||||
<Button
|
||||
onClick={scrollNextPro}
|
||||
className={cn(
|
||||
@@ -299,10 +304,43 @@ const Welcome = () => {
|
||||
</Button>
|
||||
</section>
|
||||
|
||||
{category &&
|
||||
category
|
||||
.slice(0, 6)
|
||||
.map((e) => <CategoryCarousel category={e} key={e.id} />)}
|
||||
{productLoading || allProductsLoading ? (
|
||||
<section className="relative custom-container mt-5 justify-center items-center border-b border-slate-200">
|
||||
<Carousel
|
||||
opts={{
|
||||
align: 'start',
|
||||
dragFree: true,
|
||||
}}
|
||||
className="w-full"
|
||||
setApi={setApiPro}
|
||||
>
|
||||
<CarouselContent className="pr-[12%] sm:pr-0">
|
||||
{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>
|
||||
))}
|
||||
</CarouselContent>
|
||||
</Carousel>
|
||||
</section>
|
||||
) : (
|
||||
allProducts?.map((e) => (
|
||||
<CategoryCarousel
|
||||
category={e}
|
||||
key={e.id}
|
||||
isLoading={allProductsLoading}
|
||||
isError={allProductsError}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user