Compare commits
51 Commits
72c46a296c
...
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 |
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 { AboutContent } from '@/features/about/ui/AboutContent';
|
||||||
import { AboutHero } from '@/features/about/ui/AboutHero';
|
import { AboutHero } from '@/features/about/ui/AboutHero';
|
||||||
import { PartnershipForm } from '@/features/about/ui/AboutPage';
|
import { PartnershipForm } from '@/features/about/ui/AboutPage';
|
||||||
|
import { BASE_URL } from '@/shared/config/api/URLs';
|
||||||
import { Metadata } from 'next';
|
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 {
|
interface Props {
|
||||||
params: { locale: 'uz' | 'ru' };
|
params: Promise<{ locale: 'uz' | 'ru' | 'en' }>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||||
const { locale } = await params;
|
const { locale } = await params;
|
||||||
|
|
||||||
const titles = {
|
try {
|
||||||
uz: 'Biz haqimizda | GASTRO',
|
const banner = await fetchAboutData();
|
||||||
ru: 'О нас | Магазин товаров',
|
|
||||||
};
|
|
||||||
|
|
||||||
const descriptions = {
|
const title =
|
||||||
uz: 'Bizning onlayn do‘konimizda sifatli mahsulotlarni toping. Tez yetkazib berish va qulay to‘lov imkoniyatlari mavjud.',
|
locale === 'uz'
|
||||||
ru: 'В нашем онлайн-магазине вы найдете качественные товары. Быстрая доставка и удобная оплата.',
|
? banner.title_uz
|
||||||
};
|
: locale === 'ru'
|
||||||
|
? banner.title_ru
|
||||||
|
: banner.title_en;
|
||||||
|
|
||||||
const keywords = {
|
const description =
|
||||||
uz: 'mahsulot, onlayn do‘kon, xarid, yetkazib berish',
|
locale === 'uz'
|
||||||
ru: 'товары, онлайн-магазин, покупка, доставка',
|
? banner.description_uz
|
||||||
};
|
: locale === 'ru'
|
||||||
|
? banner.description_ru
|
||||||
|
: banner.description_en;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
title: titles[locale],
|
title: title || 'Gastro Market',
|
||||||
description: descriptions[locale],
|
description: description || 'Gastro Market mahsulotlarini kashf eting',
|
||||||
keywords: keywords[locale],
|
|
||||||
openGraph: {
|
openGraph: {
|
||||||
title: titles[locale],
|
title: title || 'Gastro Market',
|
||||||
description: descriptions[locale],
|
description: description || 'Gastro Market mahsulotlarini kashf eting',
|
||||||
siteName: 'GASTRO',
|
type: 'website',
|
||||||
images: [
|
images: [
|
||||||
{
|
{
|
||||||
url: '/logos/logo.png',
|
url: getImageUrl(banner.image),
|
||||||
width: 1200,
|
width: 1200,
|
||||||
height: 1200,
|
height: 630,
|
||||||
alt: titles[locale],
|
alt: title,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
locale: locale === 'uz' ? 'uz_UZ' : 'ru_RU',
|
|
||||||
type: 'website',
|
|
||||||
},
|
},
|
||||||
twitter: {
|
twitter: {
|
||||||
card: 'summary_large_image',
|
card: 'summary_large_image',
|
||||||
title: titles[locale],
|
title: title || 'Gastro Market',
|
||||||
description: descriptions[locale],
|
description: description || 'Gastro Market mahsulotlarini kashf eting',
|
||||||
images: ['/logos/logo.png'],
|
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 (
|
return (
|
||||||
<div className="custom-container">
|
<div className="custom-container">
|
||||||
<AboutHero />
|
<AboutHero />
|
||||||
@@ -63,4 +87,4 @@ const page = () => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default page;
|
export default AboutPage;
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ export async function generateMetadata({
|
|||||||
openGraph: {
|
openGraph: {
|
||||||
title,
|
title,
|
||||||
description,
|
description,
|
||||||
url: `/search${query ? `?q=${encodeURIComponent(query)}` : ''}`,
|
url: `/search${query ? `?search=${encodeURIComponent(query)}` : ''}`,
|
||||||
type: 'website',
|
type: 'website',
|
||||||
},
|
},
|
||||||
twitter: {
|
twitter: {
|
||||||
@@ -64,7 +64,7 @@ export async function generateMetadata({
|
|||||||
openGraph: {
|
openGraph: {
|
||||||
title,
|
title,
|
||||||
description,
|
description,
|
||||||
url: `/search${query ? `?q=${encodeURIComponent(query)}` : ''}`,
|
url: `/search${query ? `?search=${encodeURIComponent(query)}` : ''}`,
|
||||||
type: 'website',
|
type: 'website',
|
||||||
},
|
},
|
||||||
twitter: {
|
twitter: {
|
||||||
|
|||||||
@@ -1,9 +1,16 @@
|
|||||||
import httpClient from '@/shared/config/api/httpClient';
|
import httpClient from '@/shared/config/api/httpClient';
|
||||||
import { API_URLS } from '@/shared/config/api/URLs';
|
import { API_URLS } from '@/shared/config/api/URLs';
|
||||||
|
import { AxiosResponse } from 'axios';
|
||||||
|
import { AboutData } from './type';
|
||||||
|
|
||||||
export const partner_api = {
|
export const partner_api = {
|
||||||
async send(body: FormData) {
|
async send(body: FormData) {
|
||||||
const res = httpClient.post(API_URLS.Partners, body);
|
const res = httpClient.post(API_URLS.Partners, body);
|
||||||
return res;
|
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;
|
phone_number: string;
|
||||||
file: File;
|
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 { useTranslations } from 'next-intl';
|
||||||
import Image from 'next/image';
|
import Image from 'next/image';
|
||||||
|
import { useParams } from 'next/navigation';
|
||||||
|
import { partner_api } from '../lib/api';
|
||||||
|
|
||||||
export function AboutContent() {
|
export function AboutContent() {
|
||||||
const t = useTranslations();
|
const t = useTranslations();
|
||||||
const features = [
|
const { locale } = useParams();
|
||||||
{
|
|
||||||
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 images = [
|
const { data: about, isLoading: loadingText } = useQuery({
|
||||||
{
|
queryKey: ['aboutText'],
|
||||||
url: '/professional-chef-cooking-gourmet-food.jpg',
|
queryFn: async () => {
|
||||||
alt: 'Professional Oshpaz',
|
return partner_api.getAbout();
|
||||||
},
|
},
|
||||||
{
|
select(data) {
|
||||||
url: '/fine-dining-restaurant-plating.jpg',
|
return data.data;
|
||||||
alt: 'Fine Dining',
|
|
||||||
},
|
},
|
||||||
{
|
});
|
||||||
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 (
|
return (
|
||||||
<section className="py-20 px-4">
|
<section className="py-20 px-4">
|
||||||
<div className="max-w-7xl mx-auto">
|
<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 */}
|
{/* 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">
|
<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>
|
</h2>
|
||||||
<p className="text-lg text-muted-foreground leading-relaxed mb-6">
|
<p className="text-lg text-muted-foreground leading-relaxed mb-6">
|
||||||
{t(
|
{locale === 'uz'
|
||||||
`Gastro Market – bu gastronomiya dunyosidagi eng so'nggi yangiliklarni`,
|
? aboutText?.[0]?.description_uz ||
|
||||||
)}
|
"Gastronomiya va kulinariya san'ati haqidagi yetakchi onlayn magazin"
|
||||||
</p>
|
: locale === 'ru'
|
||||||
<p className="text-lg text-muted-foreground leading-relaxed">
|
? aboutText?.[0]?.description_ru ||
|
||||||
{t(`Bizning jamoamiz tajribali kulinariya mutaxassislari`)}
|
'Ведущий интернет-магазин по гастрономии и кулинарному искусству'
|
||||||
|
: aboutText?.[0]?.description_en ||
|
||||||
|
"Gastronomiya va kulinariya san'ati haqidagi yetakchi onlayn magazin"}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -89,7 +84,7 @@ export function AboutContent() {
|
|||||||
{t('Bizning dunyo')}
|
{t('Bizning dunyo')}
|
||||||
</h3>
|
</h3>
|
||||||
<div className="grid md:grid-cols-3 gap-6">
|
<div className="grid md:grid-cols-3 gap-6">
|
||||||
{images.map((image, idx) => (
|
{images?.map((image, idx) => (
|
||||||
<div
|
<div
|
||||||
key={idx}
|
key={idx}
|
||||||
className="relative aspect-[4/3] overflow-hidden rounded-lg group"
|
className="relative aspect-[4/3] overflow-hidden rounded-lg group"
|
||||||
@@ -97,8 +92,8 @@ export function AboutContent() {
|
|||||||
<Image
|
<Image
|
||||||
width={500}
|
width={500}
|
||||||
height={500}
|
height={500}
|
||||||
src={image.url || '/placeholder.svg'}
|
src={BASE_URL + image.image || '/placeholder.svg'}
|
||||||
alt={image.alt}
|
alt={image.id.toString()}
|
||||||
unoptimized
|
unoptimized
|
||||||
className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
|
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 Image from 'next/image';
|
||||||
|
import { useParams } from 'next/navigation';
|
||||||
|
import { partner_api } from '../lib/api';
|
||||||
|
|
||||||
export function AboutHero() {
|
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 (
|
return (
|
||||||
<section className="relative h-[60vh] min-h-[500px] flex items-center justify-center overflow-hidden">
|
<section className="relative h-[60vh] min-h-[500px] flex items-center justify-center overflow-hidden">
|
||||||
<div className="absolute inset-0 z-0">
|
<div className="absolute inset-0 z-0">
|
||||||
@@ -10,19 +42,31 @@ export function AboutHero() {
|
|||||||
width={500}
|
width={500}
|
||||||
height={500}
|
height={500}
|
||||||
unoptimized
|
unoptimized
|
||||||
src="/gourmet-food-culinary-magazine-hero-image.jpg"
|
src={
|
||||||
|
BASE_URL + banner?.image ||
|
||||||
|
'/gourmet-food-culinary-magazine-hero-image.jpg'
|
||||||
|
}
|
||||||
alt="Gastro Market"
|
alt="Gastro Market"
|
||||||
className="w-full h-full object-cover brightness-50"
|
className="w-full h-full object-cover brightness-50"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="relative z-10 text-center px-4 max-w-4xl mx-auto">
|
<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">
|
<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>
|
</h1>
|
||||||
<p className="text-xl md:text-2xl text-white/90 font-light leading-relaxed text-balance">
|
<p className="text-xl md:text-2xl text-white/90 font-light leading-relaxed text-balance">
|
||||||
{t(
|
{locale === 'uz'
|
||||||
"Gastronomiya va kulinariya san'ati haqidagi yetakchi onlayn magazin",
|
? 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>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { Link, useRouter } from '@/shared/config/i18n/navigation';
|
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 { Button } from '@/shared/ui/button';
|
||||||
import {
|
import {
|
||||||
Form,
|
Form,
|
||||||
@@ -25,6 +25,7 @@ import { authForm } from '../lib/form';
|
|||||||
const Login = () => {
|
const Login = () => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const t = useTranslations();
|
const t = useTranslations();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
const form = useForm<z.infer<typeof authForm>>({
|
const form = useForm<z.infer<typeof authForm>>({
|
||||||
resolver: zodResolver(authForm),
|
resolver: zodResolver(authForm),
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
@@ -32,7 +33,6 @@ const Login = () => {
|
|||||||
username: '',
|
username: '',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const queryClient = useQueryClient();
|
|
||||||
|
|
||||||
const { mutate, isPending } = useMutation({
|
const { mutate, isPending } = useMutation({
|
||||||
mutationFn: (body: {
|
mutationFn: (body: {
|
||||||
@@ -41,12 +41,10 @@ const Login = () => {
|
|||||||
tg_id?: string;
|
tg_id?: string;
|
||||||
}) => auth_api.login(body),
|
}) => auth_api.login(body),
|
||||||
onSuccess: (res) => {
|
onSuccess: (res) => {
|
||||||
|
router.push('/');
|
||||||
|
queryClient.refetchQueries();
|
||||||
setToken(res.data.access);
|
setToken(res.data.access);
|
||||||
setRefToken(res.data.refresh);
|
setRefToken(res.data.refresh);
|
||||||
setUser(form.getValues('username'));
|
|
||||||
router.push('/');
|
|
||||||
queryClient.refetchQueries({ queryKey: ['product_list'] });
|
|
||||||
queryClient.refetchQueries({ queryKey: ['get_me'] });
|
|
||||||
},
|
},
|
||||||
onError: () => {
|
onError: () => {
|
||||||
toast.error(t('Username yoki parol xato kiritildi'), {
|
toast.error(t('Username yoki parol xato kiritildi'), {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ export interface CartItem {
|
|||||||
image: string;
|
image: string;
|
||||||
}[];
|
}[];
|
||||||
liked: boolean;
|
liked: boolean;
|
||||||
meansurement: null | string;
|
meansurement: null | { id: number; name: string };
|
||||||
inventory_id: null | string;
|
inventory_id: null | string;
|
||||||
product_id: string;
|
product_id: string;
|
||||||
code: string;
|
code: string;
|
||||||
@@ -31,6 +31,7 @@ export interface CartItem {
|
|||||||
marketing_group_code: null | string;
|
marketing_group_code: null | string;
|
||||||
inventory_kinds: { id: number; name: string }[];
|
inventory_kinds: { id: number; name: string }[];
|
||||||
sector_codes: { id: number; code: string }[];
|
sector_codes: { id: number; code: string }[];
|
||||||
|
balance: number;
|
||||||
prices: {
|
prices: {
|
||||||
id: number;
|
id: number;
|
||||||
price: string;
|
price: string;
|
||||||
|
|||||||
@@ -3,6 +3,6 @@ import { z } from 'zod';
|
|||||||
export const orderForm = z.object({
|
export const orderForm = z.object({
|
||||||
long: z.string().min(1, { message: 'Majburiy maydon' }),
|
long: z.string().min(1, { message: 'Majburiy maydon' }),
|
||||||
lat: 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(),
|
city: z.string().optional(),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import ProductBanner from '@/assets/product.png';
|
import ProductBanner from '@/assets/product.png';
|
||||||
import { cart_api } from '@/features/cart/lib/api';
|
import { cart_api } from '@/features/cart/lib/api';
|
||||||
import { BASE_URL } from '@/shared/config/api/URLs';
|
import { BASE_URL } from '@/shared/config/api/URLs';
|
||||||
@@ -36,19 +37,28 @@ const CartPage = () => {
|
|||||||
select: (data) => data.data.cart_item,
|
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>>({});
|
const debounceRef = useRef<Record<string, NodeJS.Timeout | null>>({});
|
||||||
|
|
||||||
|
// Initial quantities
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!cartItems) return;
|
if (!cartItems) return;
|
||||||
const initialQuantities: Record<string, string> = {};
|
const initialQuantities: Record<string, number> = {};
|
||||||
|
const initialInputValues: Record<string, string> = {};
|
||||||
cartItems.forEach((item) => {
|
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;
|
debounceRef.current[item.id] = null;
|
||||||
});
|
});
|
||||||
setQuantities(initialQuantities);
|
setQuantities(initialQuantities);
|
||||||
|
setInputValues(initialInputValues);
|
||||||
}, [cartItems]);
|
}, [cartItems]);
|
||||||
|
|
||||||
|
// Update mutation
|
||||||
const { mutate: updateCartItem } = useMutation({
|
const { mutate: updateCartItem } = useMutation({
|
||||||
mutationFn: ({
|
mutationFn: ({
|
||||||
body,
|
body,
|
||||||
@@ -57,23 +67,85 @@ const CartPage = () => {
|
|||||||
body: { quantity: number };
|
body: { quantity: number };
|
||||||
cart_item_id: string;
|
cart_item_id: string;
|
||||||
}) => cart_api.update_cart_item({ body, cart_item_id }),
|
}) => cart_api.update_cart_item({ body, cart_item_id }),
|
||||||
onSuccess: () =>
|
onSuccess: (_, variables) => {
|
||||||
queryClient.invalidateQueries({ queryKey: ['cart_items', cart_id] }),
|
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) =>
|
onError: (err: AxiosError) =>
|
||||||
toast.error(err.message, { richColors: true, position: 'top-center' }),
|
toast.error(err.message, { richColors: true, position: 'top-center' }),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Delete mutation
|
||||||
const { mutate: deleteCartItem } = useMutation({
|
const { mutate: deleteCartItem } = useMutation({
|
||||||
mutationFn: ({ cart_item_id }: { cart_item_id: string }) =>
|
mutationFn: ({ cart_item_id }: { cart_item_id: string }) =>
|
||||||
cart_api.delete_cart_item(cart_item_id),
|
cart_api.delete_cart_item(cart_item_id),
|
||||||
onSuccess: () =>
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: ['cart_items', cart_id] }),
|
queryClient.invalidateQueries({ queryKey: ['cart_items', cart_id] });
|
||||||
|
toast.success(t("Savatdan o'chirildi"), {
|
||||||
|
richColors: true,
|
||||||
|
position: 'top-center',
|
||||||
|
});
|
||||||
|
},
|
||||||
onError: (err: AxiosError) =>
|
onError: (err: AxiosError) =>
|
||||||
toast.error(err.message, { richColors: true, position: 'top-center' }),
|
toast.error(err.message, { richColors: true, position: 'top-center' }),
|
||||||
});
|
});
|
||||||
|
|
||||||
const handleCheckout = () => router.push('/cart/order');
|
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)
|
if (isLoading)
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex items-center justify-center">
|
<div className="min-h-screen flex items-center justify-center">
|
||||||
@@ -103,33 +175,19 @@ const CartPage = () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const subtotal =
|
const subtotal =
|
||||||
cartItems?.reduce((sum, item) => {
|
cartItems.reduce((sum, item) => {
|
||||||
if (item.product.prices.length === 0) return sum; // narx yo'q bo'lsa qo'shmaymiz
|
if (!item.product.prices.length) return sum;
|
||||||
|
|
||||||
// Eng yuqori narxni olish
|
const price = item.product.prices.find((p) => p.price_type.code === '1')
|
||||||
const maxPrice = Math.max(
|
? Number(
|
||||||
...item.product.prices.map((p) => Number(p.price)),
|
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;
|
const qty = quantities[item.id] ?? item.quantity;
|
||||||
}, 0) || 0; // cartItems bo'sh bo'lsa 0 qaytaradi
|
|
||||||
|
|
||||||
const handleQuantityChange = (itemId: string, value: number) => {
|
return sum + price * qty;
|
||||||
setQuantities((prev) => ({
|
}, 0) || 0;
|
||||||
...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 (
|
return (
|
||||||
<div className="custom-container mb-6">
|
<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="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||||
<div className="lg:col-span-2">
|
<div className="lg:col-span-2">
|
||||||
<div className="bg-white rounded-lg shadow-md overflow-hidden">
|
<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
|
<div
|
||||||
key={item.id}
|
key={item.id}
|
||||||
className={`p-6 flex relative gap-4 ${
|
className={`p-6 flex relative gap-4 ${index !== cartItems.length - 1 ? 'border-b' : ''}`}
|
||||||
index !== cartItems.length - 1 ? 'border-b' : ''
|
|
||||||
}`}
|
|
||||||
>
|
>
|
||||||
<Button
|
<Button
|
||||||
variant="destructive"
|
variant="destructive"
|
||||||
@@ -156,12 +219,12 @@ const CartPage = () => {
|
|||||||
onClick={() =>
|
onClick={() =>
|
||||||
deleteCartItem({ cart_item_id: String(item.id) })
|
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" />
|
<Trash className="size-4" />
|
||||||
</Button>
|
</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
|
<Image
|
||||||
src={
|
src={
|
||||||
item.product.images.length > 0
|
item.product.images.length > 0
|
||||||
@@ -171,11 +234,10 @@ const CartPage = () => {
|
|||||||
: ProductBanner
|
: ProductBanner
|
||||||
}
|
}
|
||||||
alt={item.product.name}
|
alt={item.product.name}
|
||||||
width={500}
|
width={300}
|
||||||
height={500}
|
height={300}
|
||||||
unoptimized
|
unoptimized
|
||||||
className="object-cover"
|
className="object-cover w-full h-full"
|
||||||
style={{ width: '100%', height: '100%' }}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -183,67 +245,127 @@ const CartPage = () => {
|
|||||||
<h3 className="font-semibold text-lg mb-1">
|
<h3 className="font-semibold text-lg mb-1">
|
||||||
{item.product.name}
|
{item.product.name}
|
||||||
</h3>
|
</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">
|
<span className="text-blue-600 font-bold text-xl">
|
||||||
{formatPrice(
|
{item.product.prices.find(
|
||||||
item.product.prices.length !== 0
|
(p) => p.price_type.code === '1',
|
||||||
? Math.max(
|
|
||||||
...item.product.prices.map((e) =>
|
|
||||||
Number(e.price),
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
: 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,
|
true,
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
|
<span className="text-sm text-gray-500">
|
||||||
|
/{measurementDisplay}
|
||||||
|
</span>
|
||||||
</div>
|
</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
|
<button
|
||||||
onClick={() =>
|
onClick={() => handleQuantityChange(item.id, -1)}
|
||||||
handleQuantityChange(
|
className="p-2 hover:bg-gray-50"
|
||||||
String(item.id),
|
|
||||||
Number(quantities[item.id]) - 1,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
className="p-2 cursor-pointer transition rounded-lg"
|
|
||||||
>
|
>
|
||||||
<Minus className="w-4 h-4" />
|
<Minus className="w-4 h-4" />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1 px-2">
|
||||||
<Input
|
<Input
|
||||||
value={quantities[item.id]}
|
value={inputValue}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const val = e.target.value.replace(/\D/g, ''); // faqat raqam
|
const v = e.target.value;
|
||||||
setQuantities((prev) => ({
|
|
||||||
|
// Faqat raqamlar va bitta nuqtaga ruxsat (vergul ham)
|
||||||
|
if (!/^\d*[.,]?\d*$/.test(v)) return;
|
||||||
|
|
||||||
|
// String sifatida saqlash (nuqta yo'qolmasin)
|
||||||
|
setInputValues((prev) => ({
|
||||||
...prev,
|
...prev,
|
||||||
[item.id]: val,
|
[item.id]: v,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// Debounce bilan update
|
// Bo'sh yoki faqat nuqta bo'lsa raqamga o'tkazmaymiz
|
||||||
const valNum = Number(val);
|
if (v === '' || v === '.' || v === ',') return;
|
||||||
if (!isNaN(valNum))
|
|
||||||
handleQuantityChange(String(item.id), valNum);
|
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"
|
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
|
<button
|
||||||
onClick={() =>
|
onClick={() => handleQuantityChange(item.id, 1)}
|
||||||
handleQuantityChange(
|
className="p-2 hover:bg-gray-50"
|
||||||
String(item.id),
|
|
||||||
Number(quantities[item.id]) + 1,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
className="p-2 cursor-pointer transition rounded-lg"
|
|
||||||
>
|
>
|
||||||
<Plus className="w-4 h-4" />
|
<Plus className="w-4 h-4" />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
);
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -261,11 +383,9 @@ const CartPage = () => {
|
|||||||
<span className="flex items-center gap-1">
|
<span className="flex items-center gap-1">
|
||||||
<Truck className="w-4 h-4" /> {t('Yetkazib berish')}:
|
<Truck className="w-4 h-4" /> {t('Yetkazib berish')}:
|
||||||
</span>
|
</span>
|
||||||
<span>
|
|
||||||
<span className="text-green-600 font-semibold">
|
<span className="text-green-600 font-semibold">
|
||||||
{t('Bepul')}
|
{t('Bepul')}
|
||||||
</span>
|
</span>
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -288,7 +408,7 @@ const CartPage = () => {
|
|||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={() => router.push('/')}
|
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')}
|
<ArrowLeft className="w-5 h-5" /> {t('Xaridni davom ettirish')}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
/* eslint-disable */
|
/* eslint-disable */
|
||||||
import LogosProduct from '@/assets/product.png';
|
import LogosProduct from '@/assets/product.png';
|
||||||
import { BASE_URL } from '@/shared/config/api/URLs';
|
import { BASE_URL } from '@/shared/config/api/URLs';
|
||||||
|
import { useRouter } from '@/shared/config/i18n/navigation';
|
||||||
import { useCartId } from '@/shared/hooks/cartId';
|
import { useCartId } from '@/shared/hooks/cartId';
|
||||||
import formatDate from '@/shared/lib/formatDate';
|
import formatDate from '@/shared/lib/formatDate';
|
||||||
import formatPrice from '@/shared/lib/formatPrice';
|
import formatPrice from '@/shared/lib/formatPrice';
|
||||||
@@ -41,6 +42,7 @@ import { uz } from 'date-fns/locale';
|
|||||||
import {
|
import {
|
||||||
Calendar as CalIcon,
|
Calendar as CalIcon,
|
||||||
CheckCircle2,
|
CheckCircle2,
|
||||||
|
ChevronLeft,
|
||||||
Clock,
|
Clock,
|
||||||
Loader2,
|
Loader2,
|
||||||
LocateFixed,
|
LocateFixed,
|
||||||
@@ -63,12 +65,10 @@ interface CoordsData {
|
|||||||
|
|
||||||
// Yetkazib berish vaqt oraliqlar
|
// Yetkazib berish vaqt oraliqlar
|
||||||
const deliveryTimeSlots = [
|
const deliveryTimeSlots = [
|
||||||
{ id: 1, label: '09:00 - 11:00', start: '09:00', end: '11:00' },
|
{ id: 1, label: '10:00 - 12:00', start: '10:00', end: '12:00' },
|
||||||
{ id: 2, label: '11:00 - 13:00', start: '11:00', end: '13:00' },
|
{ id: 2, label: '12:00 - 14:00', start: '12:00', end: '14:00' },
|
||||||
{ id: 3, label: '13:00 - 15:00', start: '13:00', end: '15:00' },
|
{ id: 3, label: '14:00 - 16:00', start: '14:00', end: '16:00' },
|
||||||
{ id: 4, label: '15:00 - 17:00', start: '15:00', end: '17:00' },
|
{ id: 4, label: '16:00 - 18:00', start: '16:00', end: '18: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' },
|
|
||||||
];
|
];
|
||||||
|
|
||||||
const OrderPage = () => {
|
const OrderPage = () => {
|
||||||
@@ -82,6 +82,7 @@ const OrderPage = () => {
|
|||||||
long: '69.240562',
|
long: '69.240562',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
const router = useRouter();
|
||||||
const [cart, setCart] = useState<number | string | null>(null);
|
const [cart, setCart] = useState<number | string | null>(null);
|
||||||
const { cart_id } = useCartId();
|
const { cart_id } = useCartId();
|
||||||
const [orderSuccess, setOrderSuccess] = useState(false);
|
const [orderSuccess, setOrderSuccess] = useState(false);
|
||||||
@@ -93,19 +94,25 @@ const OrderPage = () => {
|
|||||||
enabled: !!cart,
|
enabled: !!cart,
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log(data);
|
|
||||||
|
|
||||||
const { mutate, isPending } = useMutation({
|
const { mutate, isPending } = useMutation({
|
||||||
mutationFn: (body: OrderCreateBody) => cart_api.createOrder(body),
|
mutationFn: (body: OrderCreateBody) => cart_api.createOrder(body),
|
||||||
onSuccess: (res) => {
|
onSuccess: (res) => {
|
||||||
const message = JSON.parse(res.data.response);
|
const message = JSON.parse(res.data.response);
|
||||||
if (message.successes.length > 0) {
|
|
||||||
|
if (message.successes && message.successes.length > 0) {
|
||||||
|
// Buyurtma muvaffaqiyatli
|
||||||
setOrderSuccess(true);
|
setOrderSuccess(true);
|
||||||
setCart(cart_id);
|
setCart(cart_id);
|
||||||
|
|
||||||
queryClinet.refetchQueries({ queryKey: ['cart_items'] });
|
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 {
|
} else {
|
||||||
toast.error(t('Xatolik yuz berdi: Mahsulot omborxonada yetarli emas'), {
|
// Boshqa noaniq holat
|
||||||
|
toast.error(t('Xatolik yuz berdi'), {
|
||||||
richColors: true,
|
richColors: true,
|
||||||
position: 'top-center',
|
position: 'top-center',
|
||||||
});
|
});
|
||||||
@@ -135,11 +142,13 @@ const OrderPage = () => {
|
|||||||
if (item.product.prices.length === 0) return sum; // narx yo'q bo'lsa qo'shmaymiz
|
if (item.product.prices.length === 0) return sum; // narx yo'q bo'lsa qo'shmaymiz
|
||||||
|
|
||||||
// Eng yuqori narxni olish
|
// Eng yuqori narxni olish
|
||||||
const maxPrice = Math.max(
|
const maxPrice = item.product.prices.find(
|
||||||
...item.product.prices.map((p) => Number(p.price)),
|
(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
|
}, 0) || 0; // cartItems bo'sh bo'lsa 0 qaytaradi
|
||||||
|
|
||||||
const [coords, setCoords] = useState({
|
const [coords, setCoords] = useState({
|
||||||
@@ -280,15 +289,17 @@ const OrderPage = () => {
|
|||||||
warehouse_code: process.env.NEXT_PUBLIC_WARHOUSES_CODE!,
|
warehouse_code: process.env.NEXT_PUBLIC_WARHOUSES_CODE!,
|
||||||
}));
|
}));
|
||||||
if (user) {
|
if (user) {
|
||||||
|
const dealTime = formatDate.format(deliveryDate, 'DD.MM.YYYY');
|
||||||
|
|
||||||
mutate({
|
mutate({
|
||||||
order: [
|
order: [
|
||||||
{
|
{
|
||||||
filial_code: process.env.NEXT_PUBLIC_FILIAL_CODE!,
|
filial_code: process.env.NEXT_PUBLIC_FILIAL_CODE!,
|
||||||
delivery_date: formatDate.format(deliveryDate, 'DD.MM.YYYY'),
|
delivery_date: `${dealTime}`,
|
||||||
room_code: process.env.NEXT_PUBLIC_ROOM_CODE!,
|
room_code: process.env.NEXT_PUBLIC_ROOM_CODE!,
|
||||||
deal_time: formatDate.format(deliveryDate, 'DD.MM.YYYY'),
|
deal_time: formatDate.format(new Date(), 'DD.MM.YYYY'),
|
||||||
robot_code: process.env.NEXT_PUBLIC_ROBOT_CODE!,
|
robot_code: process.env.NEXT_PUBLIC_ROBOT_CODE!,
|
||||||
status: 'B#N',
|
status: 'D',
|
||||||
sales_manager_code: process.env.NEXT_PUBLIC_SALES_MANAGER_CODE!,
|
sales_manager_code: process.env.NEXT_PUBLIC_SALES_MANAGER_CODE!,
|
||||||
person_code: user?.username,
|
person_code: user?.username,
|
||||||
currency_code: '860',
|
currency_code: '860',
|
||||||
@@ -334,6 +345,15 @@ const OrderPage = () => {
|
|||||||
<div className="custom-container mb-5">
|
<div className="custom-container mb-5">
|
||||||
<div>
|
<div>
|
||||||
<div className="mb-6">
|
<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">
|
<h1 className="text-3xl font-bold text-gray-800 mb-2">
|
||||||
{t('Buyurtmani rasmiylashtirish')}
|
{t('Buyurtmani rasmiylashtirish')}
|
||||||
</h1>
|
</h1>
|
||||||
@@ -356,10 +376,14 @@ const OrderPage = () => {
|
|||||||
<FormControl>
|
<FormControl>
|
||||||
<Textarea
|
<Textarea
|
||||||
{...field}
|
{...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"
|
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')}
|
placeholder={t('Izoh')}
|
||||||
/>
|
/>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
|
<div className="text-right text-xs text-gray-500">
|
||||||
|
{field.value?.length || 0}/300
|
||||||
|
</div>
|
||||||
<FormMessage />
|
<FormMessage />
|
||||||
</FormItem>
|
</FormItem>
|
||||||
)}
|
)}
|
||||||
@@ -577,7 +601,7 @@ const OrderPage = () => {
|
|||||||
{item.quantity} x{' '}
|
{item.quantity} x{' '}
|
||||||
{formatPrice(
|
{formatPrice(
|
||||||
item.product.prices.length !== 0
|
item.product.prices.length !== 0
|
||||||
? Math.max(
|
? Math.min(
|
||||||
...item.product.prices.map((p) =>
|
...item.product.prices.map((p) =>
|
||||||
Number(p.price),
|
Number(p.price),
|
||||||
),
|
),
|
||||||
@@ -589,7 +613,7 @@ const OrderPage = () => {
|
|||||||
<p className="font-semibold text-sm">
|
<p className="font-semibold text-sm">
|
||||||
{formatPrice(
|
{formatPrice(
|
||||||
item.product.prices.length !== 0
|
item.product.prices.length !== 0
|
||||||
? Math.max(
|
? Math.min(
|
||||||
...item.product.prices.map((p) =>
|
...item.product.prices.map((p) =>
|
||||||
Number(p.price),
|
Number(p.price),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -51,11 +51,13 @@ const AllProducts = () => {
|
|||||||
const params = new URLSearchParams(searchParams.toString());
|
const params = new URLSearchParams(searchParams.toString());
|
||||||
params.set('page', newPage.toString());
|
params.set('page', newPage.toString());
|
||||||
|
|
||||||
router.push(`${pathname}?${params.toString()}`, {
|
router.push(`${pathname}?${params.toString()}`);
|
||||||
scroll: true,
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||||
|
}, [page]);
|
||||||
|
|
||||||
return (
|
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-[calc(85vh)]">
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
@@ -100,7 +102,7 @@ const AllProducts = () => {
|
|||||||
<div className="w-full mt-5 flex justify-end">
|
<div className="w-full mt-5 flex justify-end">
|
||||||
<GlobalPagination
|
<GlobalPagination
|
||||||
page={page}
|
page={page}
|
||||||
total={product.total ?? 0}
|
total={product.total}
|
||||||
pageSize={PAGE_SIZE}
|
pageSize={PAGE_SIZE}
|
||||||
onChange={handlePageChange}
|
onChange={handlePageChange}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -60,11 +60,13 @@ const Product = () => {
|
|||||||
const params = new URLSearchParams(searchParams.toString());
|
const params = new URLSearchParams(searchParams.toString());
|
||||||
params.set('page', newPage.toString());
|
params.set('page', newPage.toString());
|
||||||
|
|
||||||
router.push(`${pathname}?${params.toString()}`, {
|
router.push(`${pathname}?${params.toString()}`);
|
||||||
scroll: true,
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||||
|
}, [page]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="custom-container p-4 mb-5 flex flex-col min-h-[85vh]">
|
<div className="custom-container p-4 mb-5 flex flex-col min-h-[85vh]">
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
|
|||||||
@@ -27,8 +27,6 @@ const SubCategory = () => {
|
|||||||
router.push(`/category/${categoryId}/${subCategory.id}`);
|
router.push(`/category/${categoryId}/${subCategory.id}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log(categorys);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="custom-container">
|
<div className="custom-container">
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -7,19 +7,13 @@ import { Card } from '@/shared/ui/card';
|
|||||||
import { Skeleton } from '@/shared/ui/skeleton';
|
import { Skeleton } from '@/shared/ui/skeleton';
|
||||||
import { ProductCard } from '@/widgets/categories/ui/product-card';
|
import { ProductCard } from '@/widgets/categories/ui/product-card';
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import { AxiosError } from 'axios';
|
|
||||||
import { Heart } from 'lucide-react';
|
import { Heart } from 'lucide-react';
|
||||||
import { useTranslations } from 'next-intl';
|
import { useTranslations } from 'next-intl';
|
||||||
import { useEffect } from 'react';
|
|
||||||
|
|
||||||
export default function Favourite() {
|
export default function Favourite() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const t = useTranslations();
|
const t = useTranslations();
|
||||||
const {
|
const { data: favourite, isLoading } = useQuery({
|
||||||
data: favourite,
|
|
||||||
isLoading,
|
|
||||||
error,
|
|
||||||
} = useQuery({
|
|
||||||
queryKey: ['favourite_product'],
|
queryKey: ['favourite_product'],
|
||||||
queryFn: () => product_api.favouuriteProduct(),
|
queryFn: () => product_api.favouuriteProduct(),
|
||||||
select(data) {
|
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) {
|
if (favourite && favourite.results.length === 0) {
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen py-12">
|
<div className="min-h-screen py-12">
|
||||||
|
|||||||
@@ -3,32 +3,16 @@
|
|||||||
import { cart_api } from '@/features/cart/lib/api';
|
import { cart_api } from '@/features/cart/lib/api';
|
||||||
import { product_api } from '@/shared/config/api/product/api';
|
import { product_api } from '@/shared/config/api/product/api';
|
||||||
import { BASE_URL } from '@/shared/config/api/URLs';
|
import { BASE_URL } from '@/shared/config/api/URLs';
|
||||||
|
import { useRouter } from '@/shared/config/i18n/navigation';
|
||||||
import { useCartId } from '@/shared/hooks/cartId';
|
import { useCartId } from '@/shared/hooks/cartId';
|
||||||
import formatDate from '@/shared/lib/formatDate';
|
|
||||||
import formatPrice from '@/shared/lib/formatPrice';
|
import formatPrice from '@/shared/lib/formatPrice';
|
||||||
import { cn } from '@/shared/lib/utils';
|
import { cn } from '@/shared/lib/utils';
|
||||||
import { Button } from '@/shared/ui/button';
|
|
||||||
import {
|
|
||||||
Carousel,
|
|
||||||
CarouselApi,
|
|
||||||
CarouselContent,
|
|
||||||
CarouselItem,
|
|
||||||
} from '@/shared/ui/carousel';
|
|
||||||
import { Input } from '@/shared/ui/input';
|
import { Input } from '@/shared/ui/input';
|
||||||
import { Skeleton } from '@/shared/ui/skeleton';
|
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 { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
import { AxiosError } from 'axios';
|
import { AxiosError } from 'axios';
|
||||||
import {
|
import { Heart, Minus, Plus, Shield, ShoppingCart, Truck } from 'lucide-react';
|
||||||
ChevronLeft,
|
|
||||||
ChevronRight,
|
|
||||||
Heart,
|
|
||||||
Minus,
|
|
||||||
Plus,
|
|
||||||
Shield,
|
|
||||||
ShoppingCart,
|
|
||||||
Truck,
|
|
||||||
} from 'lucide-react';
|
|
||||||
import { useTranslations } from 'next-intl';
|
import { useTranslations } from 'next-intl';
|
||||||
import Image from 'next/image';
|
import Image from 'next/image';
|
||||||
import { useParams } from 'next/navigation';
|
import { useParams } from 'next/navigation';
|
||||||
@@ -40,20 +24,16 @@ const ProductDetail = () => {
|
|||||||
const { product } = useParams<{ product: string }>();
|
const { product } = useParams<{ product: string }>();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const { cart_id } = useCartId();
|
const { cart_id } = useCartId();
|
||||||
const [api, setApi] = useState<CarouselApi>();
|
const { user } = userStore();
|
||||||
const [canScrollPrev, setCanScrollPrev] = useState(false);
|
const router = useRouter();
|
||||||
const [canScrollNext, setCanScrollNext] = useState(false);
|
|
||||||
|
|
||||||
const [quantity, setQuantity] = useState(1);
|
const [quantity, setQuantity] = useState<number | string>(1);
|
||||||
const [selectedImage, setSelectedImage] = useState(0);
|
|
||||||
|
// ✅ debounce ref
|
||||||
const debounceRef = useRef<NodeJS.Timeout | null>(null);
|
const debounceRef = useRef<NodeJS.Timeout | null>(null);
|
||||||
|
|
||||||
/* ---------------- CART ITEMS ---------------- */
|
// ✅ Flag: faqat manual input (klaviatura) da debounce ishlaydi
|
||||||
const { data: cartItems } = useQuery({
|
const isManualInputRef = useRef(false);
|
||||||
queryKey: ['cart_items', cart_id],
|
|
||||||
queryFn: () => cart_api.get_cart_items(cart_id!),
|
|
||||||
enabled: !!cart_id,
|
|
||||||
});
|
|
||||||
|
|
||||||
/* ---------------- PRODUCT DETAIL ---------------- */
|
/* ---------------- PRODUCT DETAIL ---------------- */
|
||||||
const { data, isLoading } = useQuery({
|
const { data, isLoading } = useQuery({
|
||||||
@@ -63,18 +43,62 @@ const ProductDetail = () => {
|
|||||||
enabled: !!product,
|
enabled: !!product,
|
||||||
});
|
});
|
||||||
|
|
||||||
/* ---------------- RECOMMENDATION ---------------- */
|
/* ---------------- CART ITEMS ---------------- */
|
||||||
const { data: recomendation, isLoading: recLoad } = useQuery({
|
const { data: cartItems } = useQuery({
|
||||||
queryKey: ['product_list'],
|
queryKey: ['cart_items', cart_id],
|
||||||
queryFn: () => product_api.list({ page: 1, page_size: 12 }),
|
queryFn: () => cart_api.get_cart_items(cart_id!),
|
||||||
select: (res) => res.data.results,
|
enabled: !!cart_id,
|
||||||
});
|
});
|
||||||
|
|
||||||
/* ---------------- DERIVED DATA ---------------- */
|
const favouriteMutation = useMutation({
|
||||||
const price = Number(data?.prices?.[0]?.price || 0);
|
mutationFn: (productId: string) => product_api.favourite(productId),
|
||||||
const maxBalance = data?.balance ?? 0; // <-- balance limit
|
|
||||||
|
|
||||||
/* ---------------- SYNC CART QUANTITY ---------------- */
|
onSuccess: () => {
|
||||||
|
queryClient.refetchQueries({ queryKey: ['product_detail'] });
|
||||||
|
queryClient.refetchQueries({ queryKey: ['favourite_product'] });
|
||||||
|
},
|
||||||
|
|
||||||
|
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(() => {
|
useEffect(() => {
|
||||||
if (!data || !cartItems) return;
|
if (!data || !cartItems) return;
|
||||||
|
|
||||||
@@ -82,41 +106,31 @@ const ProductDetail = () => {
|
|||||||
(i) => Number(i.product.id) === data.id,
|
(i) => Number(i.product.id) === data.id,
|
||||||
);
|
);
|
||||||
|
|
||||||
setQuantity(item ? item.quantity : 1);
|
if (item) {
|
||||||
}, [data, cartItems]);
|
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 ---------------- */
|
/* ---------------- MUTATIONS ---------------- */
|
||||||
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 ---------------- */
|
|
||||||
const { mutate: addToCart } = useMutation({
|
const { mutate: addToCart } = useMutation({
|
||||||
mutationFn: (body: { product: string; quantity: number; cart: string }) =>
|
mutationFn: (body: { product: string; quantity: number; cart: string }) =>
|
||||||
cart_api.cart_item(body),
|
cart_api.cart_item(body),
|
||||||
onSuccess: () => {
|
|
||||||
|
onSuccess: (_, variables) => {
|
||||||
queryClient.refetchQueries({ queryKey: ['cart_items'] });
|
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) => {
|
onError: (err: AxiosError) => {
|
||||||
const msg =
|
const msg =
|
||||||
(err.response?.data as { detail: string })?.detail || err.message;
|
(err.response?.data as { detail: string })?.detail || err.message;
|
||||||
@@ -129,95 +143,115 @@ const ProductDetail = () => {
|
|||||||
cart_item_id: string;
|
cart_item_id: string;
|
||||||
body: { quantity: number };
|
body: { quantity: number };
|
||||||
}) => cart_api.update_cart_item(payload),
|
}) => 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 ---------------- */
|
/* ---------------- DEBOUNCE UPDATE (faqat manual input uchun) ---------------- */
|
||||||
const favouriteMutation = useMutation({
|
useEffect(() => {
|
||||||
mutationFn: (id: string) => product_api.favourite(id),
|
// ✅ Faqat klaviatura orqali yozilganda ishlaydi
|
||||||
onSuccess: () => {
|
if (!isManualInputRef.current) return;
|
||||||
queryClient.invalidateQueries({ queryKey: ['product_detail'] });
|
if (!cart_id || !data || !cartItems) return;
|
||||||
queryClient.invalidateQueries({ queryKey: ['product_list'] });
|
|
||||||
},
|
const cartItem = cartItems.data.cart_item.find(
|
||||||
onError: () => {
|
(i) => Number(i.product.id) === data.id,
|
||||||
toast.error(t('Tizimga kirilmagan'), {
|
);
|
||||||
richColors: true,
|
|
||||||
position: 'top-center',
|
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 ---------------- */
|
/* ---------------- HANDLERS ---------------- */
|
||||||
const handleAddToCart = () => {
|
const handleAddToCart = () => {
|
||||||
if (quantity >= maxBalance) {
|
if (user === null) {
|
||||||
toast.warning(t(`only_available`, { maxBalance }), {
|
router.push('/auth');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||||
|
isManualInputRef.current = false;
|
||||||
|
|
||||||
|
if (!data || !cart_id) {
|
||||||
|
toast.error(t('Tizimga kirilmagan'), {
|
||||||
richColors: true,
|
richColors: true,
|
||||||
position: 'top-center',
|
position: 'top-center',
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!data || !cart_id) return;
|
|
||||||
|
const normalizedQty = clampQuantity(numericQty);
|
||||||
|
|
||||||
const cartItem = cartItems?.data.cart_item.find(
|
const cartItem = cartItems?.data.cart_item.find(
|
||||||
(i) => Number(i.product.id) === data.id,
|
(i) => Number(i.product.id) === data.id,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (quantity > maxBalance) {
|
|
||||||
toast.error(t(`Faqat ${maxBalance} dona mavjud`), { richColors: true });
|
|
||||||
setQuantity(maxBalance);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cartItem) {
|
if (cartItem) {
|
||||||
updateCartItem({
|
updateCartItem({
|
||||||
cart_item_id: cartItem.id.toString(),
|
cart_item_id: cartItem.id.toString(),
|
||||||
body: { quantity },
|
body: { quantity: normalizedQty },
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
addToCart({
|
addToCart({
|
||||||
product: String(data.id),
|
product: String(data.id),
|
||||||
cart: cart_id,
|
cart: cart_id,
|
||||||
quantity,
|
quantity: normalizedQty,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
setQuantity(normalizedQty);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleIncrease = () => {
|
const handleIncrease = () => {
|
||||||
if (quantity >= maxBalance) {
|
// ✅ Bu manual input emas - flag ni false qoldirish
|
||||||
toast.warning(t(`Faqat ${maxBalance} dona mavjud`), {
|
isManualInputRef.current = false;
|
||||||
richColors: true,
|
|
||||||
position: 'top-center',
|
setQuantity((q) => {
|
||||||
|
const base = q === '' || q === '.' || q === ',' ? 0 : Number(q);
|
||||||
|
let next = base + STEP;
|
||||||
|
if (isGram) next = Math.ceil(next / STEP) * STEP;
|
||||||
|
return next;
|
||||||
});
|
});
|
||||||
return;
|
|
||||||
}
|
|
||||||
setQuantity((q) => q + 1);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDecrease = () => {
|
const handleDecrease = () => {
|
||||||
setQuantity((q) => Math.max(1, q - 1));
|
// ✅ 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);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
/* ---------------- CAROUSEL ---------------- */
|
const subtotal = data?.prices?.length
|
||||||
useEffect(() => {
|
? data.prices.find((p) => p.price_type.code === '1')
|
||||||
if (!api) return;
|
? data.prices.find((p) => p.price_type.code === '1')?.price
|
||||||
|
: Math.min(...data.prices.map((p) => Number(p.price)))
|
||||||
const updateButtons = () => {
|
: 0;
|
||||||
setCanScrollPrev(api.canScrollPrev());
|
|
||||||
setCanScrollNext(api.canScrollNext());
|
|
||||||
};
|
|
||||||
|
|
||||||
updateButtons();
|
|
||||||
api.on('select', updateButtons);
|
|
||||||
api.on('reInit', updateButtons);
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
api.off('select', updateButtons);
|
|
||||||
api.off('reInit', updateButtons);
|
|
||||||
};
|
|
||||||
}, [api]);
|
|
||||||
|
|
||||||
const scrollPrev = () => api?.scrollPrev();
|
|
||||||
const scrollNext = () => api?.scrollNext();
|
|
||||||
|
|
||||||
/* ---------------- LOADING ---------------- */
|
/* ---------------- LOADING ---------------- */
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
@@ -228,98 +262,83 @@ const ProductDetail = () => {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ===================== RENDER ===================== */
|
|
||||||
return (
|
return (
|
||||||
<div className="custom-container pb-8">
|
<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">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-8 bg-white p-6 rounded-lg shadow">
|
||||||
{/* IMAGES */}
|
|
||||||
<div>
|
<div>
|
||||||
<Image
|
<Image
|
||||||
width={500}
|
width={500}
|
||||||
unoptimized
|
|
||||||
height={500}
|
height={500}
|
||||||
|
unoptimized
|
||||||
src={
|
src={
|
||||||
data?.images?.length
|
data?.images?.length
|
||||||
? data.images[selectedImage]?.image?.includes(BASE_URL)
|
? data.images[0]?.image?.includes(BASE_URL)
|
||||||
? data.images[selectedImage]?.image
|
? data.images[0]?.image
|
||||||
: BASE_URL + data.images[selectedImage]?.image
|
: BASE_URL + data.images[0]?.image
|
||||||
: '/placeholder.svg'
|
: '/placeholder.svg'
|
||||||
}
|
}
|
||||||
alt={data?.name || 'logo'}
|
alt={data?.name || 'logo'}
|
||||||
className="w-full h-[400px] object-contain"
|
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>
|
</div>
|
||||||
|
|
||||||
{/* INFO */}
|
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold mb-2">{data?.name}</h1>
|
<h1 className="text-3xl font-bold mb-2">{data?.name}</h1>
|
||||||
<div className="text-4xl font-bold text-blue-600 mb-4">
|
|
||||||
{formatPrice(price, true)}
|
|
||||||
</div>
|
|
||||||
<p className="text-gray-600 mb-6">{data?.short_name}</p>
|
|
||||||
|
|
||||||
{/* QUANTITY */}
|
<div className="flex items-baseline gap-2 mb-4">
|
||||||
<div className="flex items-center gap-4 mb-6">
|
<span className="text-4xl font-bold text-blue-600">
|
||||||
<button onClick={handleDecrease} className="p-2 border rounded">
|
{formatPrice(Number(subtotal), true)}
|
||||||
|
</span>
|
||||||
|
<span className="text-xl text-gray-500">/{measurementDisplay}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-6">
|
||||||
|
<label className="block text-sm font-medium mb-2">
|
||||||
|
{t('Miqdor')}
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<button
|
||||||
|
onClick={handleDecrease}
|
||||||
|
disabled={numericQty <= MIN_QTY}
|
||||||
|
className="p-2 border rounded hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
<Minus />
|
<Minus />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
<Input
|
<Input
|
||||||
value={quantity}
|
value={quantity}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
let v = Number(e.target.value);
|
const v = e.target.value;
|
||||||
if (v < 1) v = 1;
|
|
||||||
if (v > maxBalance) {
|
if (!/^\d*([.,]\d*)?$/.test(v)) return;
|
||||||
toast.warning(t(`Faqat ${maxBalance} dona mavjud`), {
|
|
||||||
richColors: true,
|
// ✅ Faqat shu yerda manual input flag yoqiladi
|
||||||
position: 'top-center',
|
isManualInputRef.current = true;
|
||||||
});
|
|
||||||
v = maxBalance;
|
|
||||||
}
|
|
||||||
setQuantity(v);
|
setQuantity(v);
|
||||||
}}
|
}}
|
||||||
className="w-16 text-center"
|
className="w-24 text-center"
|
||||||
/>
|
/>
|
||||||
|
<span className="text-sm text-gray-500">
|
||||||
|
{measurementDisplay}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
<button onClick={handleIncrease} className="p-2 border rounded">
|
<button
|
||||||
|
onClick={handleIncrease}
|
||||||
|
className="p-2 border rounded hover:bg-gray-50"
|
||||||
|
>
|
||||||
<Plus />
|
<Plus />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mb-6 font-semibold">
|
|
||||||
{t('Jami')}: {formatPrice(price * quantity, true)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* ACTIONS */}
|
<div className="mb-6 text-xl font-semibold">
|
||||||
<div className="flex gap-3 mb-6">
|
{t('Jami')}: {formatPrice(Number(subtotal) * numericQty, true)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex gap-3">
|
||||||
<button
|
<button
|
||||||
onClick={handleAddToCart}
|
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"
|
className="flex-1 bg-green-600 hover:bg-green-700 text-white py-3 rounded-lg flex justify-center items-center gap-2"
|
||||||
@@ -329,96 +348,37 @@ const ProductDetail = () => {
|
|||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={() => favouriteMutation.mutate(String(data?.id))}
|
className={cn(
|
||||||
className={`p-3 rounded-lg border ${
|
'p-3 rounded-lg border cursor-pointer',
|
||||||
data?.liked ? 'border-red-500 bg-red-50' : 'border-gray-300'
|
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
|
<Heart
|
||||||
className={data?.liked ? 'fill-red-500 text-red-500' : ''}
|
className={data?.liked ? 'fill-red-500 text-red-500' : ''}
|
||||||
/>
|
/>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{/* IMPROVED UPDATED_AT WARNING */}
|
|
||||||
{data?.updated_at && data.payment_type === 'cash' && (
|
|
||||||
<div className="bg-yellow-50 border border-yellow-400 text-yellow-800 p-3 mb-4 rounded-md">
|
|
||||||
<p className="text-xs font-medium">
|
|
||||||
{t("Narxi o'zgargan bo'lishi mumkin")} • {t('Yangilangan')}:{' '}
|
|
||||||
{formatDate.format(data.updated_at, 'DD-MM-YYYY')}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className={cn('grid gap-4 mt-6 border-t pt-4', 'grid-cols-2')}>
|
<div className="grid grid-cols-2 gap-4 mt-6 border-t pt-4">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<Truck className="mx-auto mb-1" />
|
<Truck className="mx-auto mb-1" />
|
||||||
{t('Bepul yetkazib berish')}
|
<p className="text-sm">{t('Bepul yetkazib berish')}</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<Shield className="mx-auto mb-1" />
|
<Shield className="mx-auto mb-1" />
|
||||||
{t('Kafolat')}
|
<p className="text-sm">{t('Kafolat')}</p>
|
||||||
</div>
|
|
||||||
{/* {data?.payment_type && (
|
|
||||||
<div className="text-center">
|
|
||||||
<Banknote className="mx-auto mb-1" size={28} />
|
|
||||||
|
|
||||||
{data.payment_type === 'cash'
|
|
||||||
? t('Naqd bilan olinadi')
|
|
||||||
: t("Pul o'tkazish yo'li bilan olinadi")}
|
|
||||||
</div>
|
|
||||||
)} */}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* RELATED PRODUCTS */}
|
|
||||||
<div className="mt-10 bg-white p-6 rounded-lg shadow relative">
|
|
||||||
<Button
|
|
||||||
onClick={scrollPrev}
|
|
||||||
disabled={!canScrollPrev}
|
|
||||||
className="absolute top-1/2 left-0 -translate-x-1/2 z-20 rounded-full"
|
|
||||||
size={'icon'}
|
|
||||||
variant={'outline'}
|
|
||||||
>
|
|
||||||
<ChevronLeft size={32} />
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<h2 className="text-2xl font-bold mb-4">{t("O'xshash mahsulotlar")}</h2>
|
|
||||||
|
|
||||||
<Carousel setApi={setApi}>
|
|
||||||
<CarouselContent>
|
|
||||||
{recLoad &&
|
|
||||||
Array.from({ length: 6 }).map((_, i) => (
|
|
||||||
<CarouselItem
|
|
||||||
key={i}
|
|
||||||
className="basis-1/1 sm:basis-1/3 md:basis-1/4 lg:basis-1/5 xl:basis-1/6 pb-2"
|
|
||||||
>
|
|
||||||
<Skeleton className="h-60 w-full" />
|
|
||||||
</CarouselItem>
|
|
||||||
))}
|
|
||||||
|
|
||||||
{recomendation
|
|
||||||
?.filter((p) => p.state === 'A')
|
|
||||||
.map((p) => (
|
|
||||||
<CarouselItem
|
|
||||||
key={p.id}
|
|
||||||
className="basis-1/2 sm:basis-1/3 md:basis-1/4 lg:basis-1/5 xl:basis-1/6 pb-2"
|
|
||||||
>
|
|
||||||
<ProductCard product={p} />
|
|
||||||
</CarouselItem>
|
|
||||||
))}
|
|
||||||
</CarouselContent>
|
|
||||||
</Carousel>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
onClick={scrollNext}
|
|
||||||
disabled={!canScrollNext}
|
|
||||||
className="absolute top-1/2 -translate-x-1/2 z-20 -right-10 rounded-full"
|
|
||||||
size={'icon'}
|
|
||||||
variant={'outline'}
|
|
||||||
>
|
|
||||||
<ChevronRight size={32} />
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -7,7 +7,10 @@ export interface OrderList {
|
|||||||
user: number;
|
user: number;
|
||||||
comment: string;
|
comment: string;
|
||||||
delivery_date: string;
|
delivery_date: string;
|
||||||
items: {
|
items: OrderItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export default interface OrderItem {
|
||||||
id: number;
|
id: number;
|
||||||
quantity: number;
|
quantity: number;
|
||||||
price: string;
|
price: string;
|
||||||
@@ -54,7 +57,6 @@ export interface OrderList {
|
|||||||
balance: number;
|
balance: number;
|
||||||
updated_at: string;
|
updated_at: string;
|
||||||
};
|
};
|
||||||
}[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface OrderListRes {
|
export interface OrderListRes {
|
||||||
|
|||||||
@@ -16,27 +16,18 @@ import {
|
|||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { useTranslations } from 'next-intl';
|
import { useTranslations } from 'next-intl';
|
||||||
import Image from 'next/image';
|
import Image from 'next/image';
|
||||||
import { useSearchParams } from 'next/navigation';
|
|
||||||
import { useEffect, useState } from 'react';
|
|
||||||
import { order_api, OrderList } from '../lib/api';
|
import { order_api, OrderList } from '../lib/api';
|
||||||
|
|
||||||
const HistoryTabs = () => {
|
const HistoryTabs = () => {
|
||||||
const t = useTranslations();
|
const t = useTranslations();
|
||||||
const searchParams = useSearchParams();
|
|
||||||
const [page, setPage] = useState(1);
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
const { data, isLoading } = useQuery({
|
const { data, isLoading } = useQuery({
|
||||||
queryKey: ['order_list', page],
|
queryKey: ['order_list'],
|
||||||
queryFn: () => order_api.list(),
|
queryFn: () => order_api.list(),
|
||||||
select: (res) => res.data,
|
select: (res) => res.data,
|
||||||
});
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const urlPage = Number(searchParams.get('page')) || 1;
|
|
||||||
setPage(urlPage);
|
|
||||||
}, [searchParams]);
|
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center justify-center py-12">
|
<div className="flex items-center justify-center py-12">
|
||||||
@@ -47,19 +38,22 @@ const HistoryTabs = () => {
|
|||||||
|
|
||||||
if (!data || data.length === 0) {
|
if (!data || data.length === 0) {
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col items-center justify-center py-16 text-center">
|
<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">
|
<div className="bg-gray-100 p-6 rounded-full mb-4">
|
||||||
<Package className="w-16 h-16 text-gray-400" />
|
<Package className="w-12 h-12 text-gray-400" />
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xl font-bold text-gray-800 mb-2">
|
<p className="text-lg font-bold text-gray-800 mb-2">
|
||||||
{t('Buyurtmalar topilmadi')}
|
{t('Buyurtmalar topilmadi')}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-sm text-gray-500 max-w-md">
|
<p className="text-sm text-gray-500 max-w-xs">
|
||||||
{t(
|
{t(
|
||||||
"Hali buyurtma qilmagansiz. Mahsulotlarni ko'rib chiqing va birinchi buyurtmangizni bering!",
|
"Hali buyurtma qilmagansiz. Mahsulotlarni ko'rib chiqing va birinchi buyurtmangizni bering!",
|
||||||
)}
|
)}
|
||||||
</p>
|
</p>
|
||||||
<Button onClick={() => router.push('/')} className="mt-6">
|
<Button
|
||||||
|
onClick={() => router.push('/')}
|
||||||
|
className="mt-6 w-full max-w-xs"
|
||||||
|
>
|
||||||
<ShoppingBag className="w-4 h-4 mr-2" />
|
<ShoppingBag className="w-4 h-4 mr-2" />
|
||||||
{t('Xarid qilish')}
|
{t('Xarid qilish')}
|
||||||
</Button>
|
</Button>
|
||||||
@@ -68,21 +62,21 @@ const HistoryTabs = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="max-w-5xl mx-auto">
|
<div className="w-full px-3 md:px-0">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className="flex items-center justify-between mb-6 pb-4 border-b">
|
<div className="flex items-center justify-between mb-4 pb-3 border-b">
|
||||||
<div>
|
<div>
|
||||||
<h2 className="text-2xl md:text-3xl font-bold text-gray-900">
|
<h2 className="text-xl md:text-3xl font-bold text-gray-900">
|
||||||
{t('Buyurtmalar tarixi')}
|
{t('Buyurtmalar tarixi')}
|
||||||
</h2>
|
</h2>
|
||||||
<p className="text-sm text-gray-500 mt-1">
|
<p className="text-xs md:text-sm text-gray-500 mt-0.5">
|
||||||
{data.length} {t('ta buyurtma')}
|
{data.length} {t('ta buyurtma')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Orders List */}
|
{/* Orders List */}
|
||||||
<div className="space-y-6">
|
<div className="space-y-3 md:space-y-6">
|
||||||
{data.map((order: OrderList) => {
|
{data.map((order: OrderList) => {
|
||||||
const totalPrice = order.items.reduce(
|
const totalPrice = order.items.reduce(
|
||||||
(sum, item) => sum + Number(item.price) * item.quantity,
|
(sum, item) => sum + Number(item.price) * item.quantity,
|
||||||
@@ -92,31 +86,31 @@ const HistoryTabs = () => {
|
|||||||
return (
|
return (
|
||||||
<Card
|
<Card
|
||||||
key={order.id}
|
key={order.id}
|
||||||
className="border-2 border-gray-200 hover:border-blue-400 transition-all duration-200 shadow-sm hover:shadow-lg"
|
className="border border-gray-200 hover:border-blue-400 transition-all duration-200 shadow-sm hover:shadow-md rounded-xl overflow-hidden"
|
||||||
>
|
>
|
||||||
<CardContent className="p-0">
|
<CardContent className="p-0">
|
||||||
{/* Order Header */}
|
{/* Order Header */}
|
||||||
<div className="bg-gradient-to-r from-blue-50 to-indigo-50 p-4 border-b-2 border-gray-200">
|
<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 flex-col md:flex-row md:items-center justify-between gap-3">
|
<div className="flex items-center justify-between gap-2">
|
||||||
<div className="flex items-center gap-3">
|
{/* Order ID */}
|
||||||
<div className="bg-blue-600 text-white px-3 py-1 rounded-full text-sm font-bold">
|
<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}
|
#{order.id}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
|
||||||
<p className="text-xs text-gray-500">
|
<p className="text-xs text-gray-500">
|
||||||
{t('Buyurtma raqami')}
|
{t('Buyurtma raqami')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
|
{/* Delivery date - compact on mobile */}
|
||||||
{order.delivery_date && (
|
{order.delivery_date && (
|
||||||
<div className="flex items-center gap-2 bg-white px-3 py-2 rounded-lg shadow-sm">
|
<div className="flex items-center gap-1.5 bg-white px-2 py-1 rounded-lg shadow-sm">
|
||||||
<Calendar className="w-4 h-4 text-blue-600" />
|
<Calendar className="w-3.5 h-3.5 text-blue-600 flex-shrink-0" />
|
||||||
<div>
|
<div>
|
||||||
<p className="text-xs text-gray-500">
|
<p className="text-[10px] text-gray-500 leading-none">
|
||||||
{t('Yetkazib berish')}
|
{t('Yetkazib berish')}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-sm font-semibold text-gray-800">
|
<p className="text-xs font-semibold text-gray-800 mt-0.5">
|
||||||
{order.delivery_date}
|
{order.delivery_date}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -126,14 +120,14 @@ const HistoryTabs = () => {
|
|||||||
|
|
||||||
{/* Comment */}
|
{/* Comment */}
|
||||||
{order.comment && (
|
{order.comment && (
|
||||||
<div className="mt-3 bg-white p-3 rounded-lg shadow-sm border border-gray-200">
|
<div className="mt-2 bg-white p-2.5 rounded-lg shadow-sm border border-gray-100">
|
||||||
<div className="flex items-start gap-2">
|
<div className="flex items-start gap-2">
|
||||||
<MessageSquare className="w-4 h-4 text-blue-600 mt-0.5 flex-shrink-0" />
|
<MessageSquare className="w-3.5 h-3.5 text-blue-600 mt-0.5 flex-shrink-0" />
|
||||||
<div className="flex-1">
|
<div className="flex-1 min-w-0">
|
||||||
<p className="text-xs font-medium text-gray-500 mb-1">
|
<p className="text-[10px] font-medium text-gray-500 mb-0.5">
|
||||||
{t('Izoh')}:
|
{t('Izoh')}:
|
||||||
</p>
|
</p>
|
||||||
<p className="text-sm text-gray-700 leading-relaxed">
|
<p className="text-xs text-gray-700 leading-relaxed line-clamp-3">
|
||||||
{order.comment}
|
{order.comment}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -143,11 +137,10 @@ const HistoryTabs = () => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Products */}
|
{/* Products */}
|
||||||
<div className="p-4 space-y-3">
|
<div className="p-2.5 md:p-4 space-y-2 md:space-y-3">
|
||||||
{order.items.map((item, index) => {
|
{order.items.map((item, index) => {
|
||||||
const product = item.product;
|
const product = item.product;
|
||||||
|
|
||||||
// Get product image
|
|
||||||
const productImage = product.images?.[0]?.images
|
const productImage = product.images?.[0]?.images
|
||||||
? product.images[0].images.includes(BASE_URL)
|
? product.images[0].images.includes(BASE_URL)
|
||||||
? product.images[0].images
|
? product.images[0].images
|
||||||
@@ -157,13 +150,12 @@ const HistoryTabs = () => {
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={item.id}
|
key={item.id}
|
||||||
className="border-2 border-gray-100 rounded-xl p-4 bg-gradient-to-br from-white to-gray-50 hover:shadow-md transition-shadow"
|
className="border border-gray-100 rounded-lg p-2.5 md:p-4 bg-white hover:shadow-sm transition-shadow"
|
||||||
>
|
>
|
||||||
{/* Product Header with Image */}
|
<div className="flex gap-2.5 md:gap-4">
|
||||||
<div className="flex gap-4 mb-3">
|
{/* Image — smaller on mobile */}
|
||||||
{/* Product Image */}
|
|
||||||
<div className="flex-shrink-0">
|
<div className="flex-shrink-0">
|
||||||
<div className="w-20 h-20 md:w-24 md:h-24 bg-gray-100 rounded-lg overflow-hidden border-2 border-gray-200">
|
<div className="w-14 h-14 md:w-24 md:h-24 bg-gray-50 rounded-lg overflow-hidden border border-gray-200">
|
||||||
<Image
|
<Image
|
||||||
src={productImage}
|
src={productImage}
|
||||||
alt={product.name}
|
alt={product.name}
|
||||||
@@ -175,52 +167,44 @@ const HistoryTabs = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Product Info */}
|
{/* Info */}
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<div className="flex items-start justify-between gap-3 mb-2">
|
{/* Name row */}
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex items-start justify-between gap-1 mb-1.5">
|
||||||
<div className="flex items-center gap-2 mb-2">
|
<div className="flex items-center gap-1.5 min-w-0">
|
||||||
<span className="bg-blue-100 text-blue-800 text-xs font-semibold px-2 py-1 rounded">
|
<span className="bg-blue-100 text-blue-800 text-[10px] font-semibold px-1.5 py-0.5 rounded flex-shrink-0">
|
||||||
{index + 1}
|
{index + 1}
|
||||||
</span>
|
</span>
|
||||||
<h3 className="font-bold text-base md:text-lg text-gray-900 truncate">
|
<h3 className="font-bold text-sm text-gray-900 truncate">
|
||||||
{product.name}
|
{product.name}
|
||||||
</h3>
|
</h3>
|
||||||
</div>
|
</div>
|
||||||
{product.short_name && (
|
<p className="text-sm font-bold text-blue-600 flex-shrink-0">
|
||||||
<p className="text-sm text-gray-600 line-clamp-2">
|
|
||||||
{product.short_name}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="text-right flex-shrink-0">
|
|
||||||
<p className="text-xs text-gray-500 mb-1">
|
|
||||||
{t('Mahsulotlar narxi')}
|
|
||||||
</p>
|
|
||||||
<p className="text-lg font-bold text-blue-600">
|
|
||||||
{formatPrice(Number(item.price), true)}
|
{formatPrice(Number(item.price), true)}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Product Details Grid */}
|
{product.short_name && (
|
||||||
<div className="grid grid-cols-2 gap-3 p-3 bg-white rounded-lg border border-gray-200">
|
<p className="text-xs text-gray-500 line-clamp-1 mb-1.5">
|
||||||
<div className="flex flex-col">
|
{product.short_name}
|
||||||
<span className="text-xs text-gray-500 mb-1">
|
</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')}
|
{t('Miqdor')}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-base font-bold text-gray-900">
|
<span className="text-xs font-bold">
|
||||||
{item.quantity}{' '}
|
{item.quantity}
|
||||||
{product.meansurement || t('dona')}
|
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col items-end">
|
<div className="text-right">
|
||||||
<span className="text-xs text-gray-500 mb-1">
|
<span className="text-[10px] text-gray-400 block">
|
||||||
{t('Jami')}
|
{t('Jami')}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-base font-bold text-green-600">
|
<span className="text-xs font-bold text-green-600">
|
||||||
{formatPrice(
|
{formatPrice(
|
||||||
Number(item.price) * item.quantity,
|
Number(item.price) * item.quantity,
|
||||||
true,
|
true,
|
||||||
@@ -229,59 +213,54 @@ const HistoryTabs = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Order Footer */}
|
{/* Footer */}
|
||||||
<div className="bg-gradient-to-r from-gray-50 to-blue-50 p-4 border-t-2 border-gray-200">
|
<div className="bg-gradient-to-r from-gray-50 to-blue-50 px-3 py-3 md:p-4 border-t border-gray-200">
|
||||||
{/* Price Breakdown */}
|
<div className="space-y-1 text-xs md:text-sm">
|
||||||
<div className="mb-4 space-y-2">
|
<div className="flex justify-between text-gray-500">
|
||||||
<div className="flex justify-between text-sm text-gray-600">
|
|
||||||
<span>{t('Mahsulotlar narxi')}:</span>
|
<span>{t('Mahsulotlar narxi')}:</span>
|
||||||
<span className="font-semibold">
|
<span className="font-semibold text-gray-700">
|
||||||
{formatPrice(totalPrice, true)}
|
{formatPrice(totalPrice, true)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-between text-sm text-gray-600">
|
|
||||||
|
<div className="flex justify-between text-gray-500">
|
||||||
<span>{t('Mahsulotlar soni')}:</span>
|
<span>{t('Mahsulotlar soni')}:</span>
|
||||||
<span className="font-semibold">
|
<span className="font-semibold text-gray-700">
|
||||||
{order.items.reduce(
|
{order.items.reduce(
|
||||||
(sum, item) => sum + item.quantity,
|
(sum, item) => sum + item.quantity,
|
||||||
0,
|
0,
|
||||||
)}
|
)}{' '}
|
||||||
{t('dona')}
|
{t('dona')}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="border-t-2 border-dashed border-gray-300 pt-2 mt-2">
|
|
||||||
<div className="flex justify-between items-center">
|
<div className="border-t border-dashed pt-2 flex justify-between items-center">
|
||||||
<span className="text-base font-bold text-gray-800">
|
<span className="font-bold text-sm md:text-base">
|
||||||
{t('Umumiy summa')}:
|
{t('Umumiy summa')}:
|
||||||
</span>
|
</span>
|
||||||
<span className="text-2xl font-bold text-green-600">
|
<span className="text-base md:text-2xl font-bold text-green-600">
|
||||||
{formatPrice(totalPrice, true)}
|
{formatPrice(totalPrice, true)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-col md:flex-row items-center justify-between gap-4">
|
|
||||||
{/* Actions */}
|
|
||||||
<div className="flex gap-2 w-full md:w-auto">
|
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="default"
|
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
router.push(`/profile/refresh-order?id=${order.id}`)
|
router.push(`/profile/refresh-order?id=${order.id}`)
|
||||||
}
|
}
|
||||||
className="flex-1 md:flex-none gap-2 font-semibold hover:bg-blue-50 hover:text-blue-600 hover:border-blue-600 transition-colors"
|
className="w-full mt-3 gap-2 text-sm h-9"
|
||||||
>
|
>
|
||||||
<RefreshCw className="w-4 h-4" />
|
<RefreshCw className="w-4 h-4" />
|
||||||
{t('Qayta buyurtma')}
|
{t('Qayta buyurtma')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,10 +2,11 @@
|
|||||||
|
|
||||||
import { useRouter } from '@/shared/config/i18n/navigation';
|
import { useRouter } from '@/shared/config/i18n/navigation';
|
||||||
import { useCartId } from '@/shared/hooks/cartId';
|
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 { Avatar, AvatarFallback, AvatarImage } from '@/shared/ui/avatar';
|
||||||
import { Button } from '@/shared/ui/button';
|
import { Button } from '@/shared/ui/button';
|
||||||
import { banner_api } from '@/widgets/welcome/lib/api';
|
import { banner_api } from '@/widgets/welcome/lib/api';
|
||||||
|
import { userStore } from '@/widgets/welcome/lib/hook';
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
import { Headset, Home, LogOut } from 'lucide-react';
|
import { Headset, Home, LogOut } from 'lucide-react';
|
||||||
import { useTranslations } from 'next-intl';
|
import { useTranslations } from 'next-intl';
|
||||||
@@ -17,6 +18,7 @@ const Profile = () => {
|
|||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const t = useTranslations();
|
const t = useTranslations();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
const { setUser } = userStore();
|
||||||
|
|
||||||
const { data: me, isError } = useQuery({
|
const { data: me, isError } = useQuery({
|
||||||
queryKey: ['get_me'],
|
queryKey: ['get_me'],
|
||||||
@@ -42,7 +44,7 @@ const Profile = () => {
|
|||||||
const renderContent = () => {
|
const renderContent = () => {
|
||||||
switch (activeSection) {
|
switch (activeSection) {
|
||||||
case 'support':
|
case 'support':
|
||||||
router.push('https://t.me/web_app_0515_bot');
|
router.push('https://t.me/gastrohubbot');
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return <HistoryTabs />;
|
return <HistoryTabs />;
|
||||||
@@ -115,13 +117,12 @@ const Profile = () => {
|
|||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
onClick={() => {
|
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('/');
|
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"
|
className="w-full justify-start gap-3 text-red-500 hover:text-red-600 hover:bg-red-50 mt-4"
|
||||||
>
|
>
|
||||||
@@ -131,7 +132,7 @@ const Profile = () => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Main Content */}
|
{/* 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="lg:hidden flex items-center justify-between mb-4 md:mb-6">
|
||||||
<div className="flex items-center gap-2 md:gap-3">
|
<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">
|
<Avatar className="w-10 h-10 md:w-12 md:h-12 ring-2 ring-emerald-500 ring-offset-2">
|
||||||
@@ -152,14 +153,9 @@ const Profile = () => {
|
|||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
queryClient.refetchQueries({ queryKey: ['product_list'] });
|
queryClient.refetchQueries();
|
||||||
queryClient.refetchQueries({ queryKey: ['cart_items'] });
|
|
||||||
queryClient.refetchQueries({
|
|
||||||
queryKey: ['favourite_product'],
|
|
||||||
});
|
|
||||||
queryClient.refetchQueries({ queryKey: ['search'] });
|
|
||||||
removeToken();
|
removeToken();
|
||||||
setCartId(null);
|
removeRefToken();
|
||||||
router.push('/');
|
router.push('/');
|
||||||
}}
|
}}
|
||||||
className="w-9 h-9 md:w-10 md:h-10"
|
className="w-9 h-9 md:w-10 md:h-10"
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ import {
|
|||||||
SelectValue,
|
SelectValue,
|
||||||
} from '@/shared/ui/select';
|
} from '@/shared/ui/select';
|
||||||
import { Textarea } from '@/shared/ui/textarea';
|
import { Textarea } from '@/shared/ui/textarea';
|
||||||
|
import { userStore } from '@/widgets/welcome/lib/hook';
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import {
|
import {
|
||||||
Map,
|
Map,
|
||||||
@@ -42,26 +43,27 @@ import {
|
|||||||
Loader2,
|
Loader2,
|
||||||
LocateFixed,
|
LocateFixed,
|
||||||
MapPin,
|
MapPin,
|
||||||
|
Minus,
|
||||||
Package,
|
Package,
|
||||||
|
Plus,
|
||||||
ShoppingBag,
|
ShoppingBag,
|
||||||
|
Trash2,
|
||||||
User,
|
User,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { useTranslations } from 'next-intl';
|
import { useTranslations } from 'next-intl';
|
||||||
import Image from 'next/image';
|
import Image from 'next/image';
|
||||||
import { useSearchParams } from 'next/navigation';
|
import { useRouter, useSearchParams } from 'next/navigation';
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import z from 'zod';
|
import z from 'zod';
|
||||||
import { order_api } from '../lib/api';
|
import OrderItem, { order_api } from '../lib/api';
|
||||||
|
|
||||||
const deliveryTimeSlots = [
|
const deliveryTimeSlots = [
|
||||||
{ id: 1, label: '09:00 - 11:00', start: '09:00', end: '11:00' },
|
{ id: 1, label: '10:00 - 12:00', start: '10:00', end: '12:00' },
|
||||||
{ id: 2, label: '11:00 - 13:00', start: '11:00', end: '13:00' },
|
{ id: 2, label: '12:00 - 14:00', start: '12:00', end: '14:00' },
|
||||||
{ id: 3, label: '13:00 - 15:00', start: '13:00', end: '15:00' },
|
{ id: 3, label: '14:00 - 16:00', start: '14:00', end: '16:00' },
|
||||||
{ id: 4, label: '15:00 - 17:00', start: '15:00', end: '17:00' },
|
{ id: 4, label: '16:00 - 18:00', start: '16:00', end: '18: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' },
|
|
||||||
];
|
];
|
||||||
|
|
||||||
interface CoordsData {
|
interface CoordsData {
|
||||||
@@ -73,9 +75,16 @@ interface CoordsData {
|
|||||||
const RefreshOrder = () => {
|
const RefreshOrder = () => {
|
||||||
const [deliveryDate, setDeliveryDate] = useState<Date>();
|
const [deliveryDate, setDeliveryDate] = useState<Date>();
|
||||||
const [selectedTimeSlot, setSelectedTimeSlot] = useState<string>('');
|
const [selectedTimeSlot, setSelectedTimeSlot] = useState<string>('');
|
||||||
|
const [orderItems, setOrderItems] = useState<OrderItem[]>([]);
|
||||||
|
const { user } = userStore();
|
||||||
|
const [quantityInputs, setQuantityInputs] = useState<Record<number, string>>(
|
||||||
|
{},
|
||||||
|
);
|
||||||
|
|
||||||
const t = useTranslations();
|
const t = useTranslations();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
|
const router = useRouter();
|
||||||
const id = searchParams.get('id');
|
const id = searchParams.get('id');
|
||||||
|
|
||||||
const { data, isLoading } = useQuery({
|
const { data, isLoading } = useQuery({
|
||||||
@@ -86,6 +95,18 @@ const RefreshOrder = () => {
|
|||||||
|
|
||||||
const initialValues = data?.find((e) => e.id === Number(id));
|
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>>({
|
const form = useForm<z.infer<typeof orderForm>>({
|
||||||
resolver: zodResolver(orderForm),
|
resolver: zodResolver(orderForm),
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
@@ -95,7 +116,6 @@ const RefreshOrder = () => {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Update form when initialValues loads
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (initialValues?.comment) {
|
if (initialValues?.comment) {
|
||||||
form.setValue('comment', initialValues.comment);
|
form.setValue('comment', initialValues.comment);
|
||||||
@@ -128,6 +148,66 @@ const RefreshOrder = () => {
|
|||||||
[number, number][][] | null
|
[number, number][][] | null
|
||||||
>(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 getCoords = async (name: string): Promise<CoordsData | null> => {
|
||||||
const res = await fetch(
|
const res = await fetch(
|
||||||
`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(
|
`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(
|
||||||
@@ -189,11 +269,7 @@ const RefreshOrder = () => {
|
|||||||
const timeout = setTimeout(async () => {
|
const timeout = setTimeout(async () => {
|
||||||
const result = await getCoords(cityValue);
|
const result = await getCoords(cityValue);
|
||||||
if (!result) return;
|
if (!result) return;
|
||||||
setCoords({
|
setCoords({ latitude: result.lat, longitude: result.lon, zoom: 12 });
|
||||||
latitude: result.lat,
|
|
||||||
longitude: result.lon,
|
|
||||||
zoom: 12,
|
|
||||||
});
|
|
||||||
setPolygonCoords(result.polygon);
|
setPolygonCoords(result.polygon);
|
||||||
form.setValue('lat', result.lat.toString(), { shouldDirty: true });
|
form.setValue('lat', result.lat.toString(), { shouldDirty: true });
|
||||||
form.setValue('long', result.lon.toString(), { shouldDirty: true });
|
form.setValue('long', result.lon.toString(), { shouldDirty: true });
|
||||||
@@ -226,7 +302,7 @@ const RefreshOrder = () => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const order_products = initialValues.items
|
const order_products = orderItems
|
||||||
.filter(
|
.filter(
|
||||||
(item) =>
|
(item) =>
|
||||||
item.product.prices &&
|
item.product.prices &&
|
||||||
@@ -240,39 +316,44 @@ const RefreshOrder = () => {
|
|||||||
on_balance: 'Y',
|
on_balance: 'Y',
|
||||||
order_quant: item.quantity,
|
order_quant: item.quantity,
|
||||||
price_type_code: item.product.prices![0].price_type.code,
|
price_type_code: item.product.prices![0].price_type.code,
|
||||||
product_price: item.product.prices![0].price,
|
product_price: item.price,
|
||||||
warehouse_code: 'wh1',
|
warehouse_code: process.env.NEXT_PUBLIC_WARHOUSES_CODE!,
|
||||||
}));
|
}));
|
||||||
|
if (user) {
|
||||||
|
const dealTime = formatDate.format(deliveryDate, 'DD.MM.YYYY');
|
||||||
|
|
||||||
mutate({
|
mutate({
|
||||||
order: [
|
order: [
|
||||||
{
|
{
|
||||||
filial_code: 'dodge',
|
filial_code: process.env.NEXT_PUBLIC_FILIAL_CODE!,
|
||||||
delivery_date: formatDate.format(deliveryDate, 'DD.MM.YYYY'),
|
delivery_date: `${dealTime}`,
|
||||||
room_code: '100',
|
room_code: process.env.NEXT_PUBLIC_ROOM_CODE!,
|
||||||
deal_time: formatDate.format(deliveryDate, 'DD.MM.YYYY'),
|
deal_time: formatDate.format(new Date(), 'DD.MM.YYYY'),
|
||||||
robot_code: 'r2',
|
robot_code: process.env.NEXT_PUBLIC_ROBOT_CODE!,
|
||||||
status: 'B#N',
|
status: 'D',
|
||||||
sales_manager_code: '1',
|
sales_manager_code: process.env.NEXT_PUBLIC_SALES_MANAGER_CODE!,
|
||||||
person_code: '12345678',
|
person_code: user?.username,
|
||||||
currency_code: '860',
|
currency_code: '860',
|
||||||
owner_person_code: '1234567',
|
owner_person_code: user?.username,
|
||||||
note: value.comment,
|
note: value.comment,
|
||||||
order_products: order_products,
|
order_products: order_products,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
} else {
|
||||||
|
toast.error(t('Xatolik yuz berdi'), {
|
||||||
|
richColors: true,
|
||||||
|
position: 'top-center',
|
||||||
|
});
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Calculate total price
|
const totalPrice = orderItems.reduce(
|
||||||
const totalPrice =
|
|
||||||
initialValues?.items.reduce(
|
|
||||||
(sum, item) => sum + Number(item.price) * item.quantity,
|
(sum, item) => sum + Number(item.price) * item.quantity,
|
||||||
0,
|
0,
|
||||||
) || 0;
|
);
|
||||||
|
|
||||||
const totalItems =
|
const totalItems = orderItems.reduce((sum, item) => sum + item.quantity, 0);
|
||||||
initialValues?.items.reduce((sum, item) => sum + item.quantity, 0) || 0;
|
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return (
|
return (
|
||||||
@@ -361,10 +442,14 @@ const RefreshOrder = () => {
|
|||||||
<FormControl>
|
<FormControl>
|
||||||
<Textarea
|
<Textarea
|
||||||
{...field}
|
{...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"
|
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')}
|
placeholder={t('Izoh')}
|
||||||
/>
|
/>
|
||||||
</FormControl>
|
</FormControl>
|
||||||
|
<div className="text-right text-xs text-gray-500">
|
||||||
|
{field.value?.length || 0}/300
|
||||||
|
</div>
|
||||||
<FormMessage />
|
<FormMessage />
|
||||||
</FormItem>
|
</FormItem>
|
||||||
)}
|
)}
|
||||||
@@ -558,7 +643,7 @@ const RefreshOrder = () => {
|
|||||||
|
|
||||||
{/* Cart Items */}
|
{/* Cart Items */}
|
||||||
<div className="space-y-3 mb-4 max-h-96 overflow-y-auto">
|
<div className="space-y-3 mb-4 max-h-96 overflow-y-auto">
|
||||||
{initialValues.items.map((item) => {
|
{orderItems.map((item) => {
|
||||||
const productImage = item.product.images?.[0]?.images
|
const productImage = item.product.images?.[0]?.images
|
||||||
? item.product.images[0].images.includes(BASE_URL)
|
? item.product.images[0].images.includes(BASE_URL)
|
||||||
? item.product.images[0].images
|
? item.product.images[0].images
|
||||||
@@ -581,19 +666,54 @@ const RefreshOrder = () => {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex-1 min-w-0">
|
<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">
|
<h4 className="font-semibold text-sm text-gray-900 truncate">
|
||||||
{item.product.name}
|
{item.product.name}
|
||||||
</h4>
|
</h4>
|
||||||
<p className="text-xs text-gray-500 mt-1">
|
{/* O'chirish tugmasi */}
|
||||||
{item.quantity} ×{' '}
|
<button
|
||||||
{formatPrice(Number(item.price), true)}
|
type="button"
|
||||||
</p>
|
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">
|
<p className="text-sm font-bold text-blue-600 mt-1">
|
||||||
{formatPrice(
|
{formatPrice(
|
||||||
Number(item.price) * item.quantity,
|
Number(item.price) * item.quantity,
|
||||||
true,
|
true,
|
||||||
)}
|
)}
|
||||||
</p>
|
</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>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -3,36 +3,31 @@
|
|||||||
import { product_api } from '@/shared/config/api/product/api';
|
import { product_api } from '@/shared/config/api/product/api';
|
||||||
import { ProductListResult } from '@/shared/config/api/product/type';
|
import { ProductListResult } from '@/shared/config/api/product/type';
|
||||||
import { useRouter } from '@/shared/config/i18n/navigation';
|
import { useRouter } from '@/shared/config/i18n/navigation';
|
||||||
|
import { Button } from '@/shared/ui/button';
|
||||||
import { Input } from '@/shared/ui/input';
|
import { Input } from '@/shared/ui/input';
|
||||||
import { ProductCard } from '@/widgets/categories/ui/product-card';
|
import { ProductCard } from '@/widgets/categories/ui/product-card';
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import { Search, X } from 'lucide-react';
|
import { Search } from 'lucide-react';
|
||||||
import { useTranslations } from 'next-intl';
|
import { useTranslations } from 'next-intl';
|
||||||
import { useSearchParams } from 'next/navigation';
|
import { useSearchParams } from 'next/navigation';
|
||||||
import { useEffect, useState } from 'react';
|
import { useState } from 'react';
|
||||||
|
|
||||||
const SearchResult = () => {
|
const SearchResult = () => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const t = useTranslations();
|
const t = useTranslations();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
|
|
||||||
const query = searchParams.get('q') || '';
|
const query = searchParams.get('search') || '';
|
||||||
const [inputValue, setInputValue] = useState(query);
|
const [inputValue, setInputValue] = useState(query);
|
||||||
|
|
||||||
/* 🔹 Input va URL sync */
|
|
||||||
useEffect(() => {
|
|
||||||
setInputValue(query);
|
|
||||||
}, [query]);
|
|
||||||
|
|
||||||
/* 🔹 Default product list */
|
|
||||||
const { data: productList, isLoading: listLoading } = useQuery({
|
const { data: productList, isLoading: listLoading } = useQuery({
|
||||||
queryKey: ['product_list'],
|
queryKey: ['product_list'],
|
||||||
queryFn: () => product_api.list({ page: 1, page_size: 12 }),
|
queryFn: () => product_api.list({ page: 1, page_size: 12 }),
|
||||||
select: (res) => res.data.results,
|
select: (res) => res.data.results,
|
||||||
enabled: !query,
|
enabled: !query,
|
||||||
|
staleTime: 0,
|
||||||
});
|
});
|
||||||
|
|
||||||
/* 🔹 Search query */
|
|
||||||
const { data: searchList, isLoading: searchLoading } = useQuery({
|
const { data: searchList, isLoading: searchLoading } = useQuery({
|
||||||
queryKey: ['search', query],
|
queryKey: ['search', query],
|
||||||
queryFn: () =>
|
queryFn: () =>
|
||||||
@@ -41,32 +36,14 @@ const SearchResult = () => {
|
|||||||
page: 1,
|
page: 1,
|
||||||
page_size: 12,
|
page_size: 12,
|
||||||
}),
|
}),
|
||||||
select: (res) => {
|
select: (res) => res.data.products,
|
||||||
return res.data.products;
|
|
||||||
},
|
|
||||||
enabled: !!query,
|
enabled: !!query,
|
||||||
|
staleTime: 0,
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = query ? (searchList ?? []) : (productList ?? []);
|
const data = query ? (searchList ?? []) : (productList ?? []);
|
||||||
const isLoading = query ? searchLoading : listLoading;
|
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 (
|
return (
|
||||||
<div className="custom-container min-h-screen">
|
<div className="custom-container min-h-screen">
|
||||||
{/* 🔍 Search input */}
|
{/* 🔍 Search input */}
|
||||||
@@ -77,18 +54,27 @@ const SearchResult = () => {
|
|||||||
<Input
|
<Input
|
||||||
value={inputValue}
|
value={inputValue}
|
||||||
placeholder={t('Mahsulot nomi')}
|
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"
|
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
|
<button
|
||||||
onClick={clearSearch}
|
onClick={clearSearch}
|
||||||
className="absolute right-3 top-1/2 -translate-y-1/2"
|
className="absolute right-3 top-1/2 -translate-y-1/2"
|
||||||
>
|
>
|
||||||
<X />
|
<X className="w-5 h-5" />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)} */}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -97,10 +83,10 @@ const SearchResult = () => {
|
|||||||
<div className="text-center py-20">{t('Yuklanmoqda')}...</div>
|
<div className="text-center py-20">{t('Yuklanmoqda')}...</div>
|
||||||
) : data.length > 0 ? (
|
) : data.length > 0 ? (
|
||||||
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
|
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
|
||||||
{data.map((products) => (
|
{data.map((product) => (
|
||||||
<ProductCard
|
<ProductCard
|
||||||
product={products as ProductListResult}
|
key={(product as ProductListResult).id}
|
||||||
key={(products as ProductListResult).id}
|
product={product as ProductListResult}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ export const API_URLS = {
|
|||||||
Banner: `${API_V}shared/banner/list/`,
|
Banner: `${API_V}shared/banner/list/`,
|
||||||
Category: `${API_V}products/category/list/`,
|
Category: `${API_V}products/category/list/`,
|
||||||
Product: `${API_V}products/product/`,
|
Product: `${API_V}products/product/`,
|
||||||
|
ProductList: `${API_V}products/all/`,
|
||||||
Login: `${API_V}accounts/login/`,
|
Login: `${API_V}accounts/login/`,
|
||||||
Search_Product: `${API_V}products/search/`,
|
Search_Product: `${API_V}products/search/`,
|
||||||
Favourite: (product_id: string) => `${API_V}accounts/${product_id}/like/`,
|
Favourite: (product_id: string) => `${API_V}accounts/${product_id}/like/`,
|
||||||
@@ -23,4 +24,5 @@ export const API_URLS = {
|
|||||||
OrderList: `${API_V}orders/order/list/`,
|
OrderList: `${API_V}orders/order/list/`,
|
||||||
Refresh_Token: `${API_V}accounts/refresh/token/`,
|
Refresh_Token: `${API_V}accounts/refresh/token/`,
|
||||||
Get_Me: `${API_V}accounts/me/`,
|
Get_Me: `${API_V}accounts/me/`,
|
||||||
|
About: `${API_V}shared/aboutus/`,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -12,7 +12,10 @@ export interface ProductListResult {
|
|||||||
id: number;
|
id: number;
|
||||||
images: { id: number; image: string }[];
|
images: { id: number; image: string }[];
|
||||||
liked: boolean;
|
liked: boolean;
|
||||||
meansurement: null | string;
|
meansurement: {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
} | null;
|
||||||
inventory_id: null | string;
|
inventory_id: null | string;
|
||||||
product_id: string;
|
product_id: string;
|
||||||
code: string;
|
code: string;
|
||||||
@@ -23,7 +26,7 @@ export interface ProductListResult {
|
|||||||
litr: null | string;
|
litr: null | string;
|
||||||
box_type_code: null | string;
|
box_type_code: null | string;
|
||||||
box_quant: null | string;
|
box_quant: null | string;
|
||||||
groups: number[];
|
groups: { id: number; name: string };
|
||||||
state: 'A' | 'P';
|
state: 'A' | 'P';
|
||||||
payment_type: 'cash' | 'card' | null;
|
payment_type: 'cash' | 'card' | null;
|
||||||
barcodes: string;
|
barcodes: string;
|
||||||
@@ -37,6 +40,7 @@ export interface ProductListResult {
|
|||||||
price_type: {
|
price_type: {
|
||||||
id: number;
|
id: number;
|
||||||
name: string;
|
name: string;
|
||||||
|
code: string;
|
||||||
};
|
};
|
||||||
}[];
|
}[];
|
||||||
balance: number;
|
balance: number;
|
||||||
@@ -73,6 +77,7 @@ export interface ProductDetail {
|
|||||||
price_type: {
|
price_type: {
|
||||||
id: number;
|
id: number;
|
||||||
name: string;
|
name: string;
|
||||||
|
code: string;
|
||||||
};
|
};
|
||||||
}[];
|
}[];
|
||||||
}
|
}
|
||||||
@@ -99,7 +104,10 @@ export interface FavouriteProductRes {
|
|||||||
id: number;
|
id: number;
|
||||||
images: { id: number; image: string }[];
|
images: { id: number; image: string }[];
|
||||||
liked: boolean;
|
liked: boolean;
|
||||||
meansurement: null | string;
|
meansurement: {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
} | null;
|
||||||
inventory_id: null | string;
|
inventory_id: null | string;
|
||||||
product_id: string;
|
product_id: string;
|
||||||
code: string;
|
code: string;
|
||||||
@@ -110,7 +118,7 @@ export interface FavouriteProductRes {
|
|||||||
litr: null | string;
|
litr: null | string;
|
||||||
box_type_code: null | string;
|
box_type_code: null | string;
|
||||||
box_quant: null | string;
|
box_quant: null | string;
|
||||||
groups: number[];
|
groups: { id: number; name: string };
|
||||||
payment_type: 'cash' | 'card' | null;
|
payment_type: 'cash' | 'card' | null;
|
||||||
state: 'A' | 'P';
|
state: 'A' | 'P';
|
||||||
barcodes: string;
|
barcodes: string;
|
||||||
@@ -125,6 +133,7 @@ export interface FavouriteProductRes {
|
|||||||
price_type: {
|
price_type: {
|
||||||
id: number;
|
id: number;
|
||||||
name: string;
|
name: string;
|
||||||
|
code: string;
|
||||||
};
|
};
|
||||||
}[];
|
}[];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -224,5 +224,6 @@
|
|||||||
"Umumiy summa": "Общая сумма",
|
"Umumiy summa": "Общая сумма",
|
||||||
"Qayta buyurtma": "Заказать заново",
|
"Qayta buyurtma": "Заказать заново",
|
||||||
"Yangilangan": "Обновлено",
|
"Yangilangan": "Обновлено",
|
||||||
"Narxi o'zgargan bo'lishi mumkin": "Цена может быть изменена"
|
"Narxi o'zgargan bo'lishi mumkin": "Цена может быть изменена",
|
||||||
|
"ga yangilandi": "обновлено"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -224,5 +224,6 @@ declare const messages: {
|
|||||||
'Qayta buyurtma': 'Qayta buyurtma';
|
'Qayta buyurtma': 'Qayta buyurtma';
|
||||||
Yangilangan: 'Yangilangan';
|
Yangilangan: 'Yangilangan';
|
||||||
"Narxi o'zgargan bo'lishi mumkin": "Narxi o'zgargan bo'lishi mumkin";
|
"Narxi o'zgargan bo'lishi mumkin": "Narxi o'zgargan bo'lishi mumkin";
|
||||||
|
'ga yangilandi': 'ga yangilandi';
|
||||||
};
|
};
|
||||||
export default messages;
|
export default messages;
|
||||||
|
|||||||
@@ -220,5 +220,6 @@
|
|||||||
"Umumiy summa": "Umumiy summa",
|
"Umumiy summa": "Umumiy summa",
|
||||||
"Qayta buyurtma": "Qayta buyurtma",
|
"Qayta buyurtma": "Qayta buyurtma",
|
||||||
"Yangilangan": "Yangilangan",
|
"Yangilangan": "Yangilangan",
|
||||||
"Narxi o'zgargan bo'lishi mumkin": "Narxi o'zgargan bo'lishi mumkin"
|
"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 = {
|
type GlobalPaginationProps = {
|
||||||
page: number;
|
page: number;
|
||||||
total: number;
|
total: number;
|
||||||
pageSize?: number;
|
pageSize: number;
|
||||||
onChange: (page: number) => void;
|
onChange: (page: number) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -42,7 +42,7 @@ const getPages = (current: number, total: number) => {
|
|||||||
export const GlobalPagination = ({
|
export const GlobalPagination = ({
|
||||||
page,
|
page,
|
||||||
total,
|
total,
|
||||||
pageSize = 36,
|
pageSize,
|
||||||
onChange,
|
onChange,
|
||||||
}: GlobalPaginationProps) => {
|
}: GlobalPaginationProps) => {
|
||||||
const totalPages = Math.ceil(total / pageSize);
|
const totalPages = Math.ceil(total / pageSize);
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { ProductTypes } from '@/shared/config/api/category/type';
|
|
||||||
import { product_api } from '@/shared/config/api/product/api';
|
|
||||||
import { useRouter } from '@/shared/config/i18n/navigation';
|
import { useRouter } from '@/shared/config/i18n/navigation';
|
||||||
import { cn } from '@/shared/lib/utils';
|
import { cn } from '@/shared/lib/utils';
|
||||||
import { Button } from '@/shared/ui/button';
|
import { Button } from '@/shared/ui/button';
|
||||||
|
import { Card } from '@/shared/ui/card';
|
||||||
import {
|
import {
|
||||||
Carousel,
|
Carousel,
|
||||||
CarouselContent,
|
CarouselContent,
|
||||||
CarouselItem,
|
CarouselItem,
|
||||||
type CarouselApi,
|
type CarouselApi,
|
||||||
} from '@/shared/ui/carousel';
|
} from '@/shared/ui/carousel';
|
||||||
|
import { Skeleton } from '@/shared/ui/skeleton';
|
||||||
import { ProductCard } from '@/widgets/categories/ui/product-card';
|
import { ProductCard } from '@/widgets/categories/ui/product-card';
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { ProductRes } from '@/widgets/welcome/lib/api';
|
||||||
import { ChevronLeft, ChevronRight } from 'lucide-react';
|
import { ChevronLeft, ChevronRight } from 'lucide-react';
|
||||||
import { memo, useEffect, useRef, useState } from 'react';
|
import { memo, useEffect, useRef, useState } from 'react';
|
||||||
|
|
||||||
@@ -20,11 +20,15 @@ import { memo, useEffect, useRef, useState } from 'react';
|
|||||||
/// CategoryCarousel optimized
|
/// CategoryCarousel optimized
|
||||||
//////////////////////////
|
//////////////////////////
|
||||||
interface CategoryCarouselProps {
|
interface CategoryCarouselProps {
|
||||||
category: ProductTypes;
|
category: ProductRes;
|
||||||
|
isLoading: boolean;
|
||||||
|
isError: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const CategoryCarousel = memo(function CategoryCarousel({
|
const CategoryCarousel = memo(function CategoryCarousel({
|
||||||
category,
|
category,
|
||||||
|
isLoading,
|
||||||
|
isError,
|
||||||
}: CategoryCarouselProps) {
|
}: CategoryCarouselProps) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [api, setApi] = useState<CarouselApi>();
|
const [api, setApi] = useState<CarouselApi>();
|
||||||
@@ -36,7 +40,6 @@ const CategoryCarousel = memo(function CategoryCarousel({
|
|||||||
// Intersection Observer
|
// Intersection Observer
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!sectionRef.current) return;
|
if (!sectionRef.current) return;
|
||||||
|
|
||||||
const observer = new IntersectionObserver(
|
const observer = new IntersectionObserver(
|
||||||
(entries) => {
|
(entries) => {
|
||||||
entries.forEach((entry) => {
|
entries.forEach((entry) => {
|
||||||
@@ -48,7 +51,6 @@ const CategoryCarousel = memo(function CategoryCarousel({
|
|||||||
},
|
},
|
||||||
{ rootMargin: '100px', threshold: 0.1 },
|
{ rootMargin: '100px', threshold: 0.1 },
|
||||||
);
|
);
|
||||||
|
|
||||||
observer.observe(sectionRef.current);
|
observer.observe(sectionRef.current);
|
||||||
return () => observer.disconnect();
|
return () => observer.disconnect();
|
||||||
}, []);
|
}, []);
|
||||||
@@ -72,20 +74,6 @@ const CategoryCarousel = memo(function CategoryCarousel({
|
|||||||
const scrollPrev = () => api?.scrollPrev();
|
const scrollPrev = () => api?.scrollPrev();
|
||||||
const scrollNext = () => api?.scrollNext();
|
const scrollNext = () => api?.scrollNext();
|
||||||
|
|
||||||
// React Query
|
|
||||||
const { data: product, isLoading } = useQuery({
|
|
||||||
queryKey: ['product_list', category.id],
|
|
||||||
queryFn: () =>
|
|
||||||
product_api.list({
|
|
||||||
page: 1,
|
|
||||||
page_size: 16,
|
|
||||||
category_id: category.id,
|
|
||||||
}),
|
|
||||||
select: (data) => data.data,
|
|
||||||
enabled: isVisible,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Shartli renderlar
|
|
||||||
if (!isVisible) {
|
if (!isVisible) {
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
@@ -95,12 +83,8 @@ const CategoryCarousel = memo(function CategoryCarousel({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!isLoading && (!product || product.results.length === 0)) return null;
|
const activeProducts =
|
||||||
|
category?.products?.filter((p) => p.state === 'A') ?? [];
|
||||||
const activeProducts = product?.results.filter((p) => p.state === 'A') ?? [];
|
|
||||||
if (!isLoading && activeProducts.length === 0) return null;
|
|
||||||
|
|
||||||
if (isLoading) return null;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
@@ -113,7 +97,7 @@ const CategoryCarousel = memo(function CategoryCarousel({
|
|||||||
onClick={() => router.push(`/category/${category.id}/`)}
|
onClick={() => router.push(`/category/${category.id}/`)}
|
||||||
>
|
>
|
||||||
<h2 className="text-2xl font-bold text-slate-800 group-hover:text-blue-600 transition-colors">
|
<h2 className="text-2xl font-bold text-slate-800 group-hover:text-blue-600 transition-colors">
|
||||||
{category.name}
|
{category.name || '---'}
|
||||||
</h2>
|
</h2>
|
||||||
<div className="p-1.5 bg-slate-100 rounded-full group-hover:bg-blue-100 transition-all">
|
<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" />
|
<ChevronRight className="text-slate-600 group-hover:text-blue-600 group-hover:translate-x-0.5 transition-all" />
|
||||||
@@ -121,9 +105,27 @@ const CategoryCarousel = memo(function CategoryCarousel({
|
|||||||
</div>
|
</div>
|
||||||
</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">
|
<CarouselContent className="pr-[12%] sm:pr-0">
|
||||||
{activeProducts.map((product) => (
|
{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"
|
||||||
|
>
|
||||||
|
<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>
|
||||||
|
))
|
||||||
|
: activeProducts.map((product) => (
|
||||||
<CarouselItem
|
<CarouselItem
|
||||||
key={product.id}
|
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"
|
className="basis-1/2 sm:basis-1/3 md:basis-1/4 lg:basis-1/5 xl:basis-1/6 pb-2"
|
||||||
|
|||||||
@@ -16,9 +16,10 @@ import { Button } from '@/shared/ui/button';
|
|||||||
import { Card, CardContent } from '@/shared/ui/card';
|
import { Card, CardContent } from '@/shared/ui/card';
|
||||||
import { Input } from '@/shared/ui/input';
|
import { Input } from '@/shared/ui/input';
|
||||||
import { FlyingAnimationPortal } from '@/widgets/animation/FlyingAnimationPortal';
|
import { FlyingAnimationPortal } from '@/widgets/animation/FlyingAnimationPortal';
|
||||||
|
import { userStore } from '@/widgets/welcome/lib/hook';
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
import { AxiosError } from 'axios';
|
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 { useTranslations } from 'next-intl';
|
||||||
import Image from 'next/image';
|
import Image from 'next/image';
|
||||||
import { MouseEvent, useEffect, useRef, useState } from 'react';
|
import { MouseEvent, useEffect, useRef, useState } from 'react';
|
||||||
@@ -33,32 +34,49 @@ export function ProductCard({
|
|||||||
error?: boolean;
|
error?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const { setProduct } = useProductStore();
|
const { setProduct } = useProductStore();
|
||||||
const [quantity, setQuantity] = useState<number | ''>(0);
|
const [quantity, setQuantity] = useState<number | string>(0);
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const t = useTranslations();
|
const t = useTranslations();
|
||||||
const { cart_id } = useCartId();
|
const { cart_id } = useCartId();
|
||||||
const [animated, setAnimated] = useState<boolean>(false);
|
const [animated, setAnimated] = useState(false);
|
||||||
const debounceRef = useRef<NodeJS.Timeout | null>(null);
|
const debounceRef = useRef<NodeJS.Timeout | null>(null);
|
||||||
const imageRef = useRef<HTMLDivElement>(null);
|
const imageRef = useRef<HTMLDivElement>(null);
|
||||||
|
const { user } = userStore();
|
||||||
|
|
||||||
|
/** ✅ 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({
|
const { mutate: addToCart } = useMutation({
|
||||||
mutationFn: (body: { product: string; quantity: number; cart: string }) =>
|
mutationFn: (body: { product: string; quantity: number; cart: string }) =>
|
||||||
cart_api.cart_item(body),
|
cart_api.cart_item(body),
|
||||||
onSuccess: () => {
|
|
||||||
|
onSuccess: (_, variables) => {
|
||||||
queryClient.refetchQueries({ queryKey: ['cart_items'] });
|
queryClient.refetchQueries({ queryKey: ['cart_items'] });
|
||||||
setAnimated(true);
|
setAnimated(true);
|
||||||
|
|
||||||
|
toast.success(
|
||||||
|
`${variables.quantity} ${measurementDisplay} ${t("savatga qo'shildi")}`,
|
||||||
|
{ richColors: true, position: 'top-center' },
|
||||||
|
);
|
||||||
},
|
},
|
||||||
|
|
||||||
onError: (err: AxiosError) => {
|
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, {
|
toast.error(detail || err.message, {
|
||||||
richColors: true,
|
richColors: true,
|
||||||
position: 'top-center',
|
position: 'top-center',
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const maxBalance = product.balance ?? 0;
|
|
||||||
|
|
||||||
|
/** 🔄 Update */
|
||||||
const { mutate: updateCartItem } = useMutation({
|
const { mutate: updateCartItem } = useMutation({
|
||||||
mutationFn: ({
|
mutationFn: ({
|
||||||
body,
|
body,
|
||||||
@@ -67,33 +85,32 @@ export function ProductCard({
|
|||||||
body: { quantity: number };
|
body: { quantity: number };
|
||||||
cart_item_id: string;
|
cart_item_id: string;
|
||||||
}) => cart_api.update_cart_item({ body, cart_item_id }),
|
}) => cart_api.update_cart_item({ body, cart_item_id }),
|
||||||
|
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.refetchQueries({ queryKey: ['cart_items'] });
|
queryClient.refetchQueries({ queryKey: ['cart_items'] });
|
||||||
setAnimated(true);
|
setAnimated(true);
|
||||||
},
|
},
|
||||||
onError: (err: AxiosError) => {
|
|
||||||
toast.error(err.message, { richColors: true, position: 'top-center' });
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** ❌ Delete */
|
||||||
const { mutate: deleteCartItem } = useMutation({
|
const { mutate: deleteCartItem } = useMutation({
|
||||||
mutationFn: ({ cart_item_id }: { cart_item_id: string }) =>
|
mutationFn: ({ cart_item_id }: { cart_item_id: string }) =>
|
||||||
cart_api.delete_cart_item(cart_item_id),
|
cart_api.delete_cart_item(cart_item_id),
|
||||||
|
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.refetchQueries({ queryKey: ['cart_items'] });
|
queryClient.refetchQueries({ queryKey: ['cart_items'] });
|
||||||
setAnimated(true);
|
setAnimated(true);
|
||||||
},
|
},
|
||||||
onError: (err: AxiosError) => {
|
|
||||||
toast.error(err.message, { richColors: true, position: 'top-center' });
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** 📦 Cart */
|
||||||
const { data: cartItems } = useQuery({
|
const { data: cartItems } = useQuery({
|
||||||
queryKey: ['cart_items', cart_id],
|
queryKey: ['cart_items', cart_id],
|
||||||
queryFn: () => cart_api.get_cart_items(cart_id!),
|
queryFn: () => cart_api.get_cart_items(cart_id!),
|
||||||
enabled: !!cart_id,
|
enabled: !!cart_id,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** 🔁 Sync */
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const item = cartItems?.data?.cart_item?.find(
|
const item = cartItems?.data?.cart_item?.find(
|
||||||
(item) => Number(item.product.id) === product.id,
|
(item) => Number(item.product.id) === product.id,
|
||||||
@@ -102,87 +119,84 @@ export function ProductCard({
|
|||||||
setQuantity(item ? item.quantity : 0);
|
setQuantity(item ? item.quantity : 0);
|
||||||
}, [cartItems, product.id]);
|
}, [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({
|
const favouriteMutation = useMutation({
|
||||||
mutationFn: (productId: string) => product_api.favourite(productId),
|
mutationFn: (productId: string) => product_api.favourite(productId),
|
||||||
|
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.refetchQueries({ queryKey: ['product_list'] });
|
queryClient.refetchQueries({ queryKey: ['product_list'] });
|
||||||
queryClient.refetchQueries({ queryKey: ['list'] });
|
|
||||||
queryClient.refetchQueries({ queryKey: ['favourite_product'] });
|
queryClient.refetchQueries({ queryKey: ['favourite_product'] });
|
||||||
queryClient.refetchQueries({ queryKey: ['search'] });
|
|
||||||
queryClient.refetchQueries({ queryKey: ['product_detail', product] });
|
|
||||||
},
|
},
|
||||||
|
|
||||||
onError: () => {
|
onError: (err: AxiosError) => {
|
||||||
toast.error(t('Tizimga kirilmagan'), {
|
const detail = (err.response?.data as { detail?: string })?.detail;
|
||||||
|
toast.error(detail || err.message, {
|
||||||
richColors: true,
|
richColors: true,
|
||||||
position: 'top-center',
|
position: 'top-center',
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const decrease = (e: MouseEvent<HTMLButtonElement>) => {
|
const price = product.prices.find((p) => p.price_type.code === '1')
|
||||||
e.stopPropagation();
|
? product.prices.find((p) => p.price_type.code === '1')?.price
|
||||||
|
: Math.min(...product.prices.map((p) => Number(p.price)));
|
||||||
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 getCartItemId = () =>
|
|
||||||
cartItems?.data.cart_item.find(
|
|
||||||
(item) => Number(item.product.id) === product.id,
|
|
||||||
)?.id;
|
|
||||||
|
|
||||||
const increase = (e: MouseEvent<HTMLButtonElement>) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
|
|
||||||
const current = quantity === '' ? 0 : quantity;
|
|
||||||
|
|
||||||
if (current >= maxBalance) {
|
|
||||||
toast.warning(t(`Faqat ${maxBalance} dona mavjud`), {
|
|
||||||
richColors: true,
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const newQty = current + 1;
|
|
||||||
setQuantity(newQty);
|
|
||||||
|
|
||||||
const id = getCartItemId();
|
|
||||||
if (id) {
|
|
||||||
updateCartItem({
|
|
||||||
cart_item_id: id.toString(),
|
|
||||||
body: { quantity: newQty },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
/** ❌ Error */
|
||||||
if (error) {
|
if (error) {
|
||||||
return (
|
return (
|
||||||
<Card className="p-4 rounded-xl">
|
<Card className="p-4 rounded-xl">
|
||||||
<Alert variant="destructive">
|
<Alert variant="destructive">
|
||||||
<AlertTitle>Xatolik</AlertTitle>
|
<AlertTitle>{t('Xatolik')}</AlertTitle>
|
||||||
<AlertDescription>{t('Mahsulotni yuklab bo‘lmadi')}</AlertDescription>
|
<AlertDescription>{t("Mahsulotni yuklab bo'lmadi")}</AlertDescription>
|
||||||
</Alert>
|
</Alert>
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
@@ -200,25 +214,21 @@ export function ProductCard({
|
|||||||
>
|
>
|
||||||
<CardContent className="p-0 flex flex-col h-full">
|
<CardContent className="p-0 flex flex-col h-full">
|
||||||
<div className="relative overflow-hidden">
|
<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
|
<Button
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
|
if (user === null) {
|
||||||
|
router.push('/auth');
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
favouriteMutation.mutate(String(product.id));
|
favouriteMutation.mutate(String(product.id));
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
aria-label="liked"
|
className="absolute top-2 right-2 z-10 bg-white hover:bg-gray-200 rounded-full p-2 shadow"
|
||||||
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"
|
|
||||||
>
|
>
|
||||||
<Heart
|
<Heart
|
||||||
className={`w-4 h-4 sm:w-5 sm:h-5 ${
|
className={`w-4 h-4 ${
|
||||||
product.liked
|
product.liked ? 'fill-red-500 text-red-500' : 'text-slate-400'
|
||||||
? 'fill-red-500 text-red-500'
|
|
||||||
: 'text-slate-400 hover:text-red-400'
|
|
||||||
}`}
|
}`}
|
||||||
/>
|
/>
|
||||||
</Button>
|
</Button>
|
||||||
@@ -228,7 +238,7 @@ export function ProductCard({
|
|||||||
fill
|
fill
|
||||||
src={
|
src={
|
||||||
product.images.length > 0
|
product.images.length > 0
|
||||||
? product?.images[0].image?.includes(BASE_URL)
|
? product.images[0].image?.includes(BASE_URL)
|
||||||
? product.images[0].image
|
? product.images[0].image
|
||||||
: BASE_URL + product.images[0].image
|
: BASE_URL + product.images[0].image
|
||||||
: LogosProduct
|
: LogosProduct
|
||||||
@@ -240,123 +250,93 @@ export function ProductCard({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="p-3 sm:p-4 space-y-1 flex-1">
|
<div className="p-3 sm:p-4 space-y-2 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>
|
|
||||||
{product.prices.length > 0 && (
|
{product.prices.length > 0 && (
|
||||||
<span className="text-lg sm:text-xl font-bold text-green-600">
|
<p className="text-lg font-bold">
|
||||||
{formatPrice(
|
{formatPrice(Number(price), true)}
|
||||||
Math.max(...product.prices.map((p) => Number(p.price))),
|
<span className="text-sm text-slate-500 ml-1">
|
||||||
true,
|
/{measurementDisplay}
|
||||||
)}
|
|
||||||
</span>
|
</span>
|
||||||
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* {product. && (
|
<h3 className="text-sm font-medium line-clamp-2">{product.name}</h3>
|
||||||
<div className="text-xs sm:text-sm text-slate-400 line-through">
|
|
||||||
{formatPrice(product.oldPrice, true)}
|
|
||||||
</div>
|
</div>
|
||||||
)} */}
|
|
||||||
</div>
|
<div className="p-3 sm:p-4 pt-0">
|
||||||
</div>
|
{typeof quantity === 'number' && quantity === 0 ? (
|
||||||
<div className="p-4 pt-0">
|
|
||||||
{quantity === 0 ? (
|
|
||||||
<Button
|
<Button
|
||||||
disabled={maxBalance <= 0}
|
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
|
|
||||||
if (maxBalance <= 0) {
|
if (user) {
|
||||||
toast.error(t('Mahsulot mavjud emas'));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
addToCart({
|
addToCart({
|
||||||
product: String(product.id),
|
product: String(product.id),
|
||||||
quantity: 1,
|
quantity: defaultQty,
|
||||||
cart: cart_id!,
|
cart: cart_id!,
|
||||||
});
|
});
|
||||||
|
} else {
|
||||||
|
router.push('/auth');
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
className="w-full bg-green-600"
|
className="w-full bg-white border border-slate-300 text-slate-700"
|
||||||
>
|
>
|
||||||
<ShoppingCart className="w-4 h-4 mr-1" />
|
|
||||||
{t('Savatga')}
|
{t('Savatga')}
|
||||||
</Button>
|
</Button>
|
||||||
) : (
|
) : (
|
||||||
<div
|
<div
|
||||||
onClick={(e) => e.stopPropagation()}
|
onClick={(e) => e.stopPropagation()}
|
||||||
className="flex items-center justify-between border border-green-500 rounded-lg h-10"
|
className="flex items-center justify-between border border-slate-300 rounded-lg h-10"
|
||||||
>
|
>
|
||||||
<Button size="icon" variant="ghost" onClick={decrease}>
|
<Button size="icon" variant="ghost" onClick={decrease}>
|
||||||
<Minus />
|
<Minus className="w-4 h-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
<Input
|
<Input
|
||||||
value={quantity}
|
value={quantity}
|
||||||
className="border-none text-center"
|
className="border-none text-center w-16"
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const v = e.target.value;
|
const v = e.target.value;
|
||||||
if (!/^\d*$/.test(v)) return;
|
|
||||||
|
|
||||||
if (debounceRef.current) {
|
/** ✅ Decimal + comma */
|
||||||
|
if (!/^\d*([.,]\d*)?$/.test(v)) return;
|
||||||
|
|
||||||
|
if (debounceRef.current)
|
||||||
clearTimeout(debounceRef.current);
|
clearTimeout(debounceRef.current);
|
||||||
}
|
|
||||||
|
|
||||||
if (v === '') {
|
setQuantity(v);
|
||||||
setQuantity('');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let num = Number(v);
|
|
||||||
if (num > maxBalance) {
|
|
||||||
num = maxBalance;
|
|
||||||
toast.warning(t(`Maksimal ${maxBalance} dona`), {
|
|
||||||
richColors: true,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
setQuantity(num);
|
|
||||||
|
|
||||||
const id = getCartItemId();
|
const id = getCartItemId();
|
||||||
if (!id) return;
|
if (!id) return;
|
||||||
|
|
||||||
if (num === 0) {
|
const num = Number(v.replace(',', '.'));
|
||||||
deleteCartItem({ cart_item_id: id.toString() });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
debounceRef.current = setTimeout(() => {
|
debounceRef.current = setTimeout(() => {
|
||||||
|
if (num === 0) {
|
||||||
|
deleteCartItem({
|
||||||
|
cart_item_id: id.toString(),
|
||||||
|
});
|
||||||
|
} else if (!isNaN(num)) {
|
||||||
updateCartItem({
|
updateCartItem({
|
||||||
cart_item_id: id.toString(),
|
cart_item_id: id.toString(),
|
||||||
body: { quantity: num },
|
body: { quantity: num },
|
||||||
});
|
});
|
||||||
|
}
|
||||||
}, 500);
|
}, 500);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
<Button
|
<Button size="icon" variant="ghost" onClick={increase}>
|
||||||
size="icon"
|
<Plus className="w-4 h-4" />
|
||||||
variant="ghost"
|
|
||||||
onClick={increase}
|
|
||||||
disabled={Number(quantity) >= maxBalance}
|
|
||||||
>
|
|
||||||
<Plus />
|
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<FlyingAnimationPortal
|
<FlyingAnimationPortal
|
||||||
product={product}
|
product={product}
|
||||||
animated={animated}
|
animated={animated}
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ const NavbarMobile = () => {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (cartItems) {
|
if (cartItems) {
|
||||||
const total = cartItems.reduce((sum, item) => sum + item.quantity, 0);
|
const total = cartItems.length;
|
||||||
setCartQuenty(total > 9 ? 9 : total);
|
setCartQuenty(total > 9 ? 9 : total);
|
||||||
}
|
}
|
||||||
}, [cartItems]);
|
}, [cartItems]);
|
||||||
|
|||||||
@@ -99,7 +99,6 @@ export const SearchResult = ({ query }: SearchResultProps) => {
|
|||||||
|
|
||||||
{list
|
{list
|
||||||
.filter((item) => item.state === 'A')
|
.filter((item) => item.state === 'A')
|
||||||
.slice(0, 5)
|
|
||||||
.map((product) => {
|
.map((product) => {
|
||||||
const image =
|
const image =
|
||||||
product.images.length > 0
|
product.images.length > 0
|
||||||
@@ -107,7 +106,9 @@ export const SearchResult = ({ query }: SearchResultProps) => {
|
|||||||
? product.images[0].image
|
? product.images[0].image
|
||||||
: BASE_URL + product.images[0].image
|
: BASE_URL + product.images[0].image
|
||||||
: LogosProduct;
|
: 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 (
|
return (
|
||||||
<div
|
<div
|
||||||
@@ -128,11 +129,9 @@ export const SearchResult = ({ query }: SearchResultProps) => {
|
|||||||
<p className="text-sm font-medium text-slate-900 line-clamp-2">
|
<p className="text-sm font-medium text-slate-900 line-clamp-2">
|
||||||
{product.name}
|
{product.name}
|
||||||
</p>
|
</p>
|
||||||
{price && (
|
|
||||||
<p className="text-sm font-semibold text-[#57A595] mt-1">
|
<p className="text-sm font-semibold text-[#57A595] mt-1">
|
||||||
{formatPrice(price)}
|
{formatPrice(Number(price), true)}
|
||||||
</p>
|
</p>
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -104,7 +104,7 @@ const Navbar = () => {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (cartItems) {
|
if (cartItems) {
|
||||||
const total = cartItems.reduce((sum, item) => sum + item.quantity, 0);
|
const total = cartItems.length;
|
||||||
setCartQuenty(total > 9 ? 9 : total);
|
setCartQuenty(total > 9 ? 9 : total);
|
||||||
} else if (cart_id === null) {
|
} else if (cart_id === null) {
|
||||||
setCartQuenty(0);
|
setCartQuenty(0);
|
||||||
@@ -429,7 +429,7 @@ const Navbar = () => {
|
|||||||
onBlur={() => setTimeout(() => setSearchOpen(false), 200)}
|
onBlur={() => setTimeout(() => setSearchOpen(false), 200)}
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
if (e.key === 'Enter' && query.trim()) {
|
if (e.key === 'Enter' && query.trim()) {
|
||||||
router.push(`/search?q=${encodeURIComponent(query)}`);
|
router.push(`/search?search=${encodeURIComponent(query)}`);
|
||||||
setSearchOpen(false);
|
setSearchOpen(false);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
@@ -453,7 +453,14 @@ const Navbar = () => {
|
|||||||
<Button
|
<Button
|
||||||
variant={'ghost'}
|
variant={'ghost'}
|
||||||
className="h-10 max-lg:hidden cursor-pointer border border-slate-200"
|
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"
|
aria-label="my favouurite product"
|
||||||
>
|
>
|
||||||
<Heart className="size-4 text-foreground" />
|
<Heart className="size-4 text-foreground" />
|
||||||
@@ -461,7 +468,14 @@ const Navbar = () => {
|
|||||||
<Button
|
<Button
|
||||||
variant={'ghost'}
|
variant={'ghost'}
|
||||||
id="cart-icon"
|
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"
|
className="h-10 relative max-lg:hidden cursor-pointer border border-slate-200"
|
||||||
>
|
>
|
||||||
<ShoppingCart className="size-4 text-foreground" />
|
<ShoppingCart className="size-4 text-foreground" />
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import httpClient from '@/shared/config/api/httpClient';
|
import httpClient from '@/shared/config/api/httpClient';
|
||||||
|
import { ProductListResult } from '@/shared/config/api/product/type';
|
||||||
import { API_URLS } from '@/shared/config/api/URLs';
|
import { API_URLS } from '@/shared/config/api/URLs';
|
||||||
import { AxiosResponse } from 'axios';
|
import { AxiosResponse } from 'axios';
|
||||||
import { BannerRes } from './type';
|
import { BannerRes } from './type';
|
||||||
@@ -26,6 +27,12 @@ export interface UserRes {
|
|||||||
username: string;
|
username: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ProductRes {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
products: ProductListResult[];
|
||||||
|
}
|
||||||
|
|
||||||
export const banner_api = {
|
export const banner_api = {
|
||||||
async getBanner(): Promise<AxiosResponse<BannerRes[]>> {
|
async getBanner(): Promise<AxiosResponse<BannerRes[]>> {
|
||||||
const res = await httpClient.get(API_URLS.Banner);
|
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);
|
const res = await httpClient.get(API_URLS.Get_Me);
|
||||||
return res;
|
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 = {
|
type Actions = {
|
||||||
setUser: (qty: UserRes) => void;
|
setUser: (qty: UserRes | null) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const userStore = create<State & Actions>((set) => ({
|
export const userStore = create<State & Actions>((set) => ({
|
||||||
user: null,
|
user: null,
|
||||||
setUser: (user: UserRes) => set(() => ({ user })),
|
setUser: (user: UserRes | null) => set(() => ({ user })),
|
||||||
}));
|
}));
|
||||||
|
|||||||
@@ -80,6 +80,18 @@ const Welcome = () => {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: allProducts,
|
||||||
|
isLoading: allProductsLoading,
|
||||||
|
isError: allProductsError,
|
||||||
|
} = useQuery({
|
||||||
|
queryKey: ['all_products'],
|
||||||
|
queryFn: () => banner_api.getAllProducts(),
|
||||||
|
select(data) {
|
||||||
|
return data.data;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const scrollPrev = () => {
|
const scrollPrev = () => {
|
||||||
if (api?.canScrollPrev()) {
|
if (api?.canScrollPrev()) {
|
||||||
api?.scrollPrev();
|
api?.scrollPrev();
|
||||||
@@ -111,7 +123,14 @@ const Welcome = () => {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="custom-container">
|
<div className="custom-container">
|
||||||
<Carousel className="w-full" setApi={setApi}>
|
<Carousel
|
||||||
|
className="w-full"
|
||||||
|
setApi={setApi}
|
||||||
|
opts={{
|
||||||
|
align: 'start',
|
||||||
|
dragFree: true, // 🔥 free scroll
|
||||||
|
}}
|
||||||
|
>
|
||||||
<CarouselContent>
|
<CarouselContent>
|
||||||
{isLoading && (
|
{isLoading && (
|
||||||
<CarouselItem className="relative">
|
<CarouselItem className="relative">
|
||||||
@@ -163,7 +182,13 @@ const Welcome = () => {
|
|||||||
</CarouselContent>
|
</CarouselContent>
|
||||||
</Carousel>
|
</Carousel>
|
||||||
|
|
||||||
<Carousel className="w-full mt-5">
|
<Carousel
|
||||||
|
opts={{
|
||||||
|
align: 'start',
|
||||||
|
dragFree: true,
|
||||||
|
}}
|
||||||
|
className="w-full mt-5"
|
||||||
|
>
|
||||||
<CarouselContent className="py-2 px-1 pr-[12%]">
|
<CarouselContent className="py-2 px-1 pr-[12%]">
|
||||||
{category &&
|
{category &&
|
||||||
category.map((banner, index) => (
|
category.map((banner, index) => (
|
||||||
@@ -212,7 +237,14 @@ const Welcome = () => {
|
|||||||
<div className="p-1.5 bg-slate-100 rounded-full group-hover:bg-blue-100 transition-all"></div>
|
<div className="p-1.5 bg-slate-100 rounded-full group-hover:bg-blue-100 transition-all"></div>
|
||||||
</div>
|
</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">
|
<CarouselContent className="pr-[12%] sm:pr-0">
|
||||||
{productLoading &&
|
{productLoading &&
|
||||||
Array.from({ length: 6 }).map((__, index) => (
|
Array.from({ length: 6 }).map((__, index) => (
|
||||||
@@ -272,8 +304,43 @@ const Welcome = () => {
|
|||||||
</Button>
|
</Button>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
{category &&
|
{productLoading || allProductsLoading ? (
|
||||||
category.map((e) => <CategoryCarousel category={e} key={e.id} />)}
|
<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