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