Compare commits
13 Commits
72c46a296c
...
09290cc352
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
09290cc352 | ||
|
|
ef55c1ecd8 | ||
|
|
bb84da82a8 | ||
|
|
734087aac5 | ||
|
|
f3e0c3e2be | ||
|
|
ea097d3953 | ||
|
|
78e79d295e | ||
|
|
fa1110ea20 | ||
|
|
a3f01e0ee7 | ||
|
|
d5148aaf06 | ||
|
|
f6231229da | ||
|
|
b1fb8fb0c4 | ||
|
|
ed4601b8e8 |
@@ -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,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,
|
||||
@@ -41,12 +41,11 @@ const Login = () => {
|
||||
tg_id?: string;
|
||||
}) => auth_api.login(body),
|
||||
onSuccess: (res) => {
|
||||
router.push('/');
|
||||
queryClient.refetchQueries({ queryKey: ['all_products'] });
|
||||
queryClient.refetchQueries({ queryKey: ['list'] });
|
||||
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;
|
||||
|
||||
@@ -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,14 @@ const CartPage = () => {
|
||||
);
|
||||
|
||||
const subtotal =
|
||||
cartItems?.reduce((sum, item) => {
|
||||
if (item.product.prices.length === 0) return sum; // narx yo'q bo'lsa qo'shmaymiz
|
||||
|
||||
// Eng yuqori narxni olish
|
||||
const maxPrice = Math.max(
|
||||
cartItems.reduce((sum, item) => {
|
||||
if (!item.product.prices.length) return sum;
|
||||
const 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 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);
|
||||
};
|
||||
const qty = quantities[item.id] ?? item.quantity;
|
||||
return sum + price * qty;
|
||||
}, 0) || 0;
|
||||
|
||||
return (
|
||||
<div className="custom-container mb-6">
|
||||
@@ -143,107 +196,158 @@ 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) => (
|
||||
<div
|
||||
key={item.id}
|
||||
className={`p-6 flex relative gap-4 ${
|
||||
index !== cartItems.length - 1 ? 'border-b' : ''
|
||||
}`}
|
||||
>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="icon"
|
||||
onClick={() =>
|
||||
deleteCartItem({ cart_item_id: String(item.id) })
|
||||
}
|
||||
className="absolute right-2 w-7 h-7 top-2 cursor-pointer"
|
||||
{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' : ''}`}
|
||||
>
|
||||
<Trash className="size-4" />
|
||||
</Button>
|
||||
|
||||
<div className="w-24 h-40 bg-gray-100 rounded-lg flex-shrink-0 overflow-hidden">
|
||||
<Image
|
||||
src={
|
||||
item.product.images.length > 0
|
||||
? item.product.images[0].image.includes(BASE_URL)
|
||||
? item.product.images[0].image
|
||||
: BASE_URL + item.product.images[0].image
|
||||
: ProductBanner
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="icon"
|
||||
onClick={() =>
|
||||
deleteCartItem({ cart_item_id: String(item.id) })
|
||||
}
|
||||
alt={item.product.name}
|
||||
width={500}
|
||||
height={500}
|
||||
unoptimized
|
||||
className="object-cover"
|
||||
style={{ width: '100%', height: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
className="absolute right-2 w-7 h-7 top-2"
|
||||
>
|
||||
<Trash className="size-4" />
|
||||
</Button>
|
||||
|
||||
<div className="flex-1">
|
||||
<h3 className="font-semibold text-lg mb-1">
|
||||
{item.product.name}
|
||||
</h3>
|
||||
<div className="flex items-center gap-2 mb-3 max-lg:flex-col max-lg:items-start max-lg:gap-1">
|
||||
<span className="text-blue-600 font-bold text-xl">
|
||||
{formatPrice(
|
||||
item.product.prices.length !== 0
|
||||
? Math.max(
|
||||
...item.product.prices.map((e) =>
|
||||
Number(e.price),
|
||||
),
|
||||
)
|
||||
: 0,
|
||||
true,
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center border border-gray-300 rounded-lg w-max">
|
||||
<button
|
||||
onClick={() =>
|
||||
handleQuantityChange(
|
||||
String(item.id),
|
||||
Number(quantities[item.id]) - 1,
|
||||
)
|
||||
<div className="w-24 h-40 bg-gray-100 rounded-lg overflow-hidden">
|
||||
<Image
|
||||
src={
|
||||
item.product.images.length > 0
|
||||
? item.product.images[0].image.includes(BASE_URL)
|
||||
? item.product.images[0].image
|
||||
: BASE_URL + item.product.images[0].image
|
||||
: ProductBanner
|
||||
}
|
||||
className="p-2 cursor-pointer transition rounded-lg"
|
||||
>
|
||||
<Minus className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
<Input
|
||||
value={quantities[item.id]}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value.replace(/\D/g, ''); // faqat raqam
|
||||
setQuantities((prev) => ({
|
||||
...prev,
|
||||
[item.id]: val,
|
||||
}));
|
||||
|
||||
// Debounce bilan update
|
||||
const valNum = Number(val);
|
||||
if (!isNaN(valNum))
|
||||
handleQuantityChange(String(item.id), valNum);
|
||||
}}
|
||||
type="text"
|
||||
className="w-16 text-center"
|
||||
alt={item.product.name}
|
||||
width={300}
|
||||
height={300}
|
||||
unoptimized
|
||||
className="object-cover w-full h-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() =>
|
||||
handleQuantityChange(
|
||||
String(item.id),
|
||||
Number(quantities[item.id]) + 1,
|
||||
)
|
||||
}
|
||||
className="p-2 cursor-pointer transition rounded-lg"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</button>
|
||||
<div className="flex-1">
|
||||
<h3 className="font-semibold text-lg mb-1">
|
||||
{item.product.name}
|
||||
</h3>
|
||||
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<span className="text-blue-600 font-bold text-xl">
|
||||
{formatPrice(
|
||||
Math.min(
|
||||
...item.product.prices.map((p) => Number(p.price)),
|
||||
),
|
||||
true,
|
||||
)}
|
||||
</span>
|
||||
<span className="text-sm text-gray-500">
|
||||
/{measurementDisplay}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<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(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={inputValue}
|
||||
onChange={(e) => {
|
||||
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]: v,
|
||||
}));
|
||||
|
||||
// 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"
|
||||
inputMode="decimal"
|
||||
className="w-16 text-center border-none p-0"
|
||||
/>
|
||||
<span className="text-xs text-gray-500">
|
||||
{measurementDisplay}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => handleQuantityChange(item.id, 1)}
|
||||
className="p-2 hover:bg-gray-50"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -261,10 +365,8 @@ 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 className="text-green-600 font-semibold">
|
||||
{t('Bepul')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -288,7 +390,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>
|
||||
|
||||
@@ -63,12 +63,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 = () => {
|
||||
@@ -99,13 +97,21 @@ const OrderPage = () => {
|
||||
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,7 +141,7 @@ 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(
|
||||
const maxPrice = Math.min(
|
||||
...item.product.prices.map((p) => Number(p.price)),
|
||||
);
|
||||
|
||||
@@ -280,15 +286,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',
|
||||
@@ -577,7 +585,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 +597,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),
|
||||
),
|
||||
|
||||
@@ -4,31 +4,13 @@ import { cart_api } from '@/features/cart/lib/api';
|
||||
import { product_api } from '@/shared/config/api/product/api';
|
||||
import { BASE_URL } from '@/shared/config/api/URLs';
|
||||
import { 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 { 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,21 +22,11 @@ const ProductDetail = () => {
|
||||
const { product } = useParams<{ product: string }>();
|
||||
const queryClient = useQueryClient();
|
||||
const { cart_id } = useCartId();
|
||||
const [api, setApi] = useState<CarouselApi>();
|
||||
const [canScrollPrev, setCanScrollPrev] = useState(false);
|
||||
const [canScrollNext, setCanScrollNext] = useState(false);
|
||||
|
||||
const [quantity, setQuantity] = useState(1);
|
||||
const [selectedImage, setSelectedImage] = useState(0);
|
||||
/** ✅ number | string */
|
||||
const [quantity, setQuantity] = useState<number | string>(1);
|
||||
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,
|
||||
});
|
||||
|
||||
/* ---------------- PRODUCT DETAIL ---------------- */
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['product_detail', product],
|
||||
@@ -63,18 +35,43 @@ 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 maxBalance = data?.balance ?? 0;
|
||||
|
||||
/* ---------------- SYNC CART QUANTITY ---------------- */
|
||||
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 */
|
||||
const numericQty =
|
||||
quantity === '' || quantity === '.' || quantity === ','
|
||||
? 0
|
||||
: Number(String(quantity).replace(',', '.'));
|
||||
|
||||
/* ---------------- HELPERS ---------------- */
|
||||
const clampQuantity = (value: number) => {
|
||||
if (!maxBalance) return value;
|
||||
return Math.min(value, maxBalance);
|
||||
};
|
||||
|
||||
const getQuantityMessage = (qty: number, measurement: string | null) => {
|
||||
if (!measurement) return `${qty} dona`;
|
||||
return `${qty} ${measurement}`;
|
||||
};
|
||||
|
||||
/* ---------------- SYNC CART ---------------- */
|
||||
useEffect(() => {
|
||||
if (!data || !cartItems) return;
|
||||
|
||||
@@ -82,44 +79,62 @@ 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);
|
||||
}
|
||||
}, [data, cartItems, MIN_QTY]);
|
||||
|
||||
/* ---------------- DEBOUNCE UPDATE ---------------- */
|
||||
useEffect(() => {
|
||||
if (!cart_id || !data || !cartItems || quantity <= 0) 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 === quantity) return;
|
||||
if (!cartItem || cartItem.quantity === numericQty) return;
|
||||
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
|
||||
debounceRef.current = setTimeout(() => {
|
||||
updateCartItem({
|
||||
cart_item_id: cartItem.id.toString(),
|
||||
body: { quantity },
|
||||
});
|
||||
if (numericQty > 0) {
|
||||
updateCartItem({
|
||||
cart_item_id: cartItem.id.toString(),
|
||||
body: { quantity: numericQty },
|
||||
});
|
||||
}
|
||||
}, 500);
|
||||
|
||||
return () => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
};
|
||||
}, [quantity]);
|
||||
}, [numericQty]);
|
||||
|
||||
/* ---------------- ADD TO CART ---------------- */
|
||||
/* ---------------- 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'] });
|
||||
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;
|
||||
|
||||
toast.error(msg, { richColors: true });
|
||||
},
|
||||
});
|
||||
@@ -129,96 +144,70 @@ const ProductDetail = () => {
|
||||
cart_item_id: string;
|
||||
body: { quantity: number };
|
||||
}) => cart_api.update_cart_item(payload),
|
||||
onSuccess: () => queryClient.refetchQueries({ queryKey: ['cart_items'] }),
|
||||
});
|
||||
|
||||
/* ---------------- 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',
|
||||
});
|
||||
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' },
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
/* ---------------- HANDLERS ---------------- */
|
||||
const handleAddToCart = () => {
|
||||
if (quantity >= maxBalance) {
|
||||
toast.warning(t(`only_available`, { maxBalance }), {
|
||||
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',
|
||||
});
|
||||
return;
|
||||
}
|
||||
setQuantity((q) => q + 1);
|
||||
setQuantity((q) => {
|
||||
const base = q === '' || q === '.' || q === ',' ? 0 : Number(q);
|
||||
let next = base + STEP;
|
||||
|
||||
if (isGram) next = Math.ceil(next / STEP) * STEP;
|
||||
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handleDecrease = () => {
|
||||
setQuantity((q) => Math.max(1, q - 1));
|
||||
setQuantity((q) => {
|
||||
const base = q === '' || q === '.' || q === ',' ? 0 : Number(q);
|
||||
let next = base - STEP;
|
||||
|
||||
if (isGram) next = Math.floor(next / STEP) * STEP;
|
||||
|
||||
return next <= MIN_QTY ? MIN_QTY : next;
|
||||
});
|
||||
};
|
||||
|
||||
/* ---------------- CAROUSEL ---------------- */
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
|
||||
const updateButtons = () => {
|
||||
setCanScrollPrev(api.canScrollPrev());
|
||||
setCanScrollNext(api.canScrollNext());
|
||||
};
|
||||
|
||||
updateButtons();
|
||||
api.on('select', updateButtons);
|
||||
api.on('reInit', updateButtons);
|
||||
|
||||
return () => {
|
||||
api.off('select', updateButtons);
|
||||
api.off('reInit', updateButtons);
|
||||
};
|
||||
}, [api]);
|
||||
|
||||
const scrollPrev = () => api?.scrollPrev();
|
||||
const scrollNext = () => api?.scrollNext();
|
||||
|
||||
/* ---------------- LOADING ---------------- */
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -228,98 +217,82 @@ 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">
|
||||
<Minus />
|
||||
</button>
|
||||
|
||||
<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;
|
||||
}
|
||||
setQuantity(v);
|
||||
}}
|
||||
className="w-16 text-center"
|
||||
/>
|
||||
|
||||
<button onClick={handleIncrease} className="p-2 border rounded">
|
||||
<Plus />
|
||||
</button>
|
||||
<div className="flex items-baseline gap-2 mb-4">
|
||||
<span className="text-4xl font-bold text-blue-600">
|
||||
{formatPrice(price, true)}
|
||||
</span>
|
||||
<span className="text-xl text-gray-500">/{measurementDisplay}</span>
|
||||
</div>
|
||||
|
||||
<div className="mb-6 font-semibold">
|
||||
{t('Jami')}: {formatPrice(price * quantity, true)}
|
||||
{/* ✅ INPUT FIXED */}
|
||||
<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}
|
||||
className="p-2 border rounded hover:bg-gray-50"
|
||||
>
|
||||
<Minus />
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
value={quantity}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
|
||||
/** ✅ allow 0 + decimal + comma */
|
||||
if (!/^\d*([.,]\d*)?$/.test(v)) return;
|
||||
|
||||
setQuantity(v);
|
||||
}}
|
||||
className="w-24 text-center"
|
||||
/>
|
||||
<span className="text-sm text-gray-500">
|
||||
{measurementDisplay}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleIncrease}
|
||||
className="p-2 border rounded hover:bg-gray-50"
|
||||
>
|
||||
<Plus />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ACTIONS */}
|
||||
<div className="flex gap-3 mb-6">
|
||||
<div className="mb-6 text-xl font-semibold">
|
||||
{t('Jami')}: {formatPrice(price * 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,97 +302,29 @@ 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',
|
||||
data?.liked ? 'border-red-500 bg-red-50' : 'border-gray-300',
|
||||
)}
|
||||
>
|
||||
<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')}
|
||||
<p className="text-sm">{t('Kafolat')}</p>
|
||||
</div>
|
||||
{/* {data?.payment_type && (
|
||||
<div className="text-center">
|
||||
<Banknote className="mx-auto mb-1" size={28} />
|
||||
|
||||
{data.payment_type === 'cash'
|
||||
? t('Naqd bilan olinadi')
|
||||
: t("Pul o'tkazish yo'li bilan olinadi")}
|
||||
</div>
|
||||
)} */}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 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>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -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>
|
||||
<p className="text-xs text-gray-500">
|
||||
{t('Buyurtma raqami')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Delivery date - compact on mobile */}
|
||||
{order.delivery_date && (
|
||||
<div className="flex items-center gap-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,112 +167,99 @@ 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">
|
||||
{index + 1}
|
||||
</span>
|
||||
<h3 className="font-bold text-base md:text-lg text-gray-900 truncate">
|
||||
{product.name}
|
||||
</h3>
|
||||
</div>
|
||||
{product.short_name && (
|
||||
<p className="text-sm text-gray-600 line-clamp-2">
|
||||
{product.short_name}
|
||||
</p>
|
||||
)}
|
||||
{/* Name row */}
|
||||
<div className="flex items-start justify-between gap-1 mb-1.5">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
<span className="bg-blue-100 text-blue-800 text-[10px] font-semibold px-1.5 py-0.5 rounded flex-shrink-0">
|
||||
{index + 1}
|
||||
</span>
|
||||
<h3 className="font-bold text-sm text-gray-900 truncate">
|
||||
{product.name}
|
||||
</h3>
|
||||
</div>
|
||||
<div className="text-right flex-shrink-0">
|
||||
<p className="text-xs text-gray-500 mb-1">
|
||||
{t('Mahsulotlar narxi')}
|
||||
</p>
|
||||
<p className="text-lg font-bold text-blue-600">
|
||||
{formatPrice(Number(item.price), true)}
|
||||
</p>
|
||||
<p className="text-sm font-bold text-blue-600 flex-shrink-0">
|
||||
{formatPrice(Number(item.price), true)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{product.short_name && (
|
||||
<p className="text-xs text-gray-500 line-clamp-1 mb-1.5">
|
||||
{product.short_name}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Qty + Total — single row on mobile */}
|
||||
<div className="flex items-center justify-between bg-gray-50 rounded-lg px-2.5 py-1.5 border border-gray-100">
|
||||
<div>
|
||||
<span className="text-[10px] text-gray-400 block">
|
||||
{t('Miqdor')}
|
||||
</span>
|
||||
<span className="text-xs font-bold">
|
||||
{item.quantity}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<span className="text-[10px] text-gray-400 block">
|
||||
{t('Jami')}
|
||||
</span>
|
||||
<span className="text-xs font-bold text-green-600">
|
||||
{formatPrice(
|
||||
Number(item.price) * item.quantity,
|
||||
true,
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Product Details Grid */}
|
||||
<div className="grid grid-cols-2 gap-3 p-3 bg-white rounded-lg border border-gray-200">
|
||||
<div className="flex flex-col">
|
||||
<span className="text-xs text-gray-500 mb-1">
|
||||
{t('Miqdor')}
|
||||
</span>
|
||||
<span className="text-base font-bold text-gray-900">
|
||||
{item.quantity}{' '}
|
||||
{product.meansurement || t('dona')}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-col items-end">
|
||||
<span className="text-xs text-gray-500 mb-1">
|
||||
{t('Jami')}
|
||||
</span>
|
||||
<span className="text-base font-bold text-green-600">
|
||||
{formatPrice(
|
||||
Number(item.price) * item.quantity,
|
||||
true,
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* 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">
|
||||
{t('Umumiy summa')}:
|
||||
</span>
|
||||
<span className="text-2xl font-bold text-green-600">
|
||||
{formatPrice(totalPrice, true)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-dashed pt-2 flex justify-between items-center">
|
||||
<span className="font-bold text-sm md:text-base">
|
||||
{t('Umumiy summa')}:
|
||||
</span>
|
||||
<span className="text-base md:text-2xl font-bold text-green-600">
|
||||
{formatPrice(totalPrice, true)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col md:flex-row items-center justify-between gap-4">
|
||||
{/* Actions */}
|
||||
<div className="flex gap-2 w-full md:w-auto">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="default"
|
||||
onClick={() =>
|
||||
router.push(`/profile/refresh-order?id=${order.id}`)
|
||||
}
|
||||
className="flex-1 md:flex-none gap-2 font-semibold hover:bg-blue-50 hover:text-blue-600 hover:border-blue-600 transition-colors"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
{t('Qayta buyurtma')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
router.push(`/profile/refresh-order?id=${order.id}`)
|
||||
}
|
||||
className="w-full mt-3 gap-2 text-sm h-9"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
{t('Qayta buyurtma')}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
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';
|
||||
@@ -115,13 +115,11 @@ 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);
|
||||
queryClient.refetchQueries();
|
||||
}}
|
||||
className="w-full justify-start gap-3 text-red-500 hover:text-red-600 hover:bg-red-50 mt-4"
|
||||
>
|
||||
@@ -131,7 +129,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 +150,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"
|
||||
|
||||
@@ -56,14 +56,11 @@ import z from 'zod';
|
||||
import { 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 {
|
||||
lat: number;
|
||||
lon: number;
|
||||
@@ -250,7 +247,10 @@ const RefreshOrder = () => {
|
||||
filial_code: 'dodge',
|
||||
delivery_date: formatDate.format(deliveryDate, 'DD.MM.YYYY'),
|
||||
room_code: '100',
|
||||
deal_time: formatDate.format(deliveryDate, 'DD.MM.YYYY'),
|
||||
deal_time:
|
||||
formatDate.format(deliveryDate, 'DD.MM.YYYY') +
|
||||
' ' +
|
||||
selectedTimeSlot,
|
||||
robot_code: 'r2',
|
||||
status: 'B#N',
|
||||
sales_manager_code: '1',
|
||||
|
||||
@@ -16,55 +16,57 @@ const SearchResult = () => {
|
||||
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 */
|
||||
/* 🔹 URL → Input sync */
|
||||
useEffect(() => {
|
||||
setInputValue(query);
|
||||
}, [query]);
|
||||
|
||||
/* 🔹 Debounce → Input → URL sync */
|
||||
useEffect(() => {
|
||||
const delay = setTimeout(() => {
|
||||
if (!inputValue.trim()) {
|
||||
router.replace('/search');
|
||||
} else {
|
||||
router.replace(`/search?search=${encodeURIComponent(inputValue)}`);
|
||||
}
|
||||
}, 400);
|
||||
|
||||
return () => clearTimeout(delay);
|
||||
}, [inputValue, router]);
|
||||
|
||||
/* 🔹 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],
|
||||
queryKey: ['search', query, inputValue],
|
||||
queryFn: () =>
|
||||
product_api.search({
|
||||
search: query,
|
||||
search: inputValue, // agar backend `q` kutsa → q: query
|
||||
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');
|
||||
router.replace('/search');
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -77,7 +79,7 @@ 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"
|
||||
/>
|
||||
|
||||
@@ -86,7 +88,7 @@ const SearchResult = () => {
|
||||
onClick={clearSearch}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2"
|
||||
>
|
||||
<X />
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
@@ -97,10 +99,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/`,
|
||||
|
||||
@@ -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;
|
||||
@@ -99,7 +102,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 +116,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;
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ const getPages = (current: number, total: number) => {
|
||||
pages.push('dots');
|
||||
}
|
||||
|
||||
const start = Math.max(2, current - 1);
|
||||
const start = Math.min(2, current - 1);
|
||||
const end = Math.min(total - 1, current + 1);
|
||||
|
||||
for (let i = start; i <= end; i++) {
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
'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';
|
||||
@@ -12,7 +10,7 @@ import {
|
||||
type CarouselApi,
|
||||
} from '@/shared/ui/carousel';
|
||||
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 +18,13 @@ import { memo, useEffect, useRef, useState } from 'react';
|
||||
/// CategoryCarousel optimized
|
||||
//////////////////////////
|
||||
interface CategoryCarouselProps {
|
||||
category: ProductTypes;
|
||||
category: ProductRes;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
const CategoryCarousel = memo(function CategoryCarousel({
|
||||
category,
|
||||
isLoading,
|
||||
}: CategoryCarouselProps) {
|
||||
const router = useRouter();
|
||||
const [api, setApi] = useState<CarouselApi>();
|
||||
@@ -72,19 +72,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 (
|
||||
@@ -95,13 +82,12 @@ const CategoryCarousel = memo(function CategoryCarousel({
|
||||
);
|
||||
}
|
||||
|
||||
if (!isLoading && (!product || product.results.length === 0)) return null;
|
||||
if (!isLoading && !category) return null;
|
||||
|
||||
const activeProducts = product?.results.filter((p) => p.state === 'A') ?? [];
|
||||
const activeProducts =
|
||||
category?.products.filter((p) => p.state === 'A') ?? [];
|
||||
if (!isLoading && activeProducts.length === 0) return null;
|
||||
|
||||
if (isLoading) return null;
|
||||
|
||||
return (
|
||||
<section
|
||||
ref={sectionRef}
|
||||
|
||||
@@ -18,7 +18,7 @@ import { Input } from '@/shared/ui/input';
|
||||
import { FlyingAnimationPortal } from '@/widgets/animation/FlyingAnimationPortal';
|
||||
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 +33,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);
|
||||
|
||||
/** ✅ 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 +84,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,15 +118,62 @@ 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: () => {
|
||||
@@ -121,68 +184,13 @@ export function ProductCard({
|
||||
},
|
||||
});
|
||||
|
||||
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 },
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/** ❌ 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 +208,16 @@ 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();
|
||||
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 +227,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 +239,94 @@ 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>
|
||||
{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,
|
||||
)}
|
||||
<div className="p-3 sm:p-4 space-y-2 flex-1">
|
||||
{product.prices.length > 0 && (
|
||||
<p className="text-lg font-bold">
|
||||
{formatPrice(
|
||||
Math.max(...product.prices.map((p) => Number(p.price))),
|
||||
true,
|
||||
)}
|
||||
<span className="text-sm text-slate-500 ml-1">
|
||||
/{measurementDisplay}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* {product. && (
|
||||
<div className="text-xs sm:text-sm text-slate-400 line-through">
|
||||
{formatPrice(product.oldPrice, true)}
|
||||
</div>
|
||||
)} */}
|
||||
</div>
|
||||
<h3 className="text-sm font-medium line-clamp-2">{product.name}</h3>
|
||||
</div>
|
||||
<div className="p-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;
|
||||
}
|
||||
|
||||
addToCart({
|
||||
product: String(product.id),
|
||||
quantity: 1,
|
||||
quantity: defaultQty,
|
||||
cart: cart_id!,
|
||||
});
|
||||
}}
|
||||
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>
|
||||
|
||||
<Input
|
||||
value={quantity}
|
||||
className="border-none text-center"
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
if (!/^\d*$/.test(v)) return;
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
value={quantity}
|
||||
className="border-none text-center w-16"
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
|
||||
if (debounceRef.current) {
|
||||
clearTimeout(debounceRef.current);
|
||||
}
|
||||
/** ✅ Decimal + comma */
|
||||
if (!/^\d*([.,]\d*)?$/.test(v)) return;
|
||||
|
||||
if (v === '') {
|
||||
setQuantity('');
|
||||
return;
|
||||
}
|
||||
if (debounceRef.current)
|
||||
clearTimeout(debounceRef.current);
|
||||
|
||||
let num = Number(v);
|
||||
if (num > maxBalance) {
|
||||
num = maxBalance;
|
||||
toast.warning(t(`Maksimal ${maxBalance} dona`), {
|
||||
richColors: true,
|
||||
});
|
||||
}
|
||||
setQuantity(v);
|
||||
|
||||
setQuantity(num);
|
||||
const id = getCartItemId();
|
||||
if (!id) return;
|
||||
|
||||
const id = getCartItemId();
|
||||
if (!id) return;
|
||||
const num = Number(v.replace(',', '.'));
|
||||
|
||||
if (num === 0) {
|
||||
deleteCartItem({ cart_item_id: id.toString() });
|
||||
return;
|
||||
}
|
||||
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);
|
||||
}}
|
||||
/>
|
||||
<span className="text-xs text-slate-500">
|
||||
{measurementDisplay}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
debounceRef.current = setTimeout(() => {
|
||||
updateCartItem({
|
||||
cart_item_id: id.toString(),
|
||||
body: { quantity: num },
|
||||
});
|
||||
}, 500);
|
||||
}}
|
||||
/>
|
||||
|
||||
<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}
|
||||
|
||||
@@ -130,7 +130,9 @@ export const SearchResult = ({ query }: SearchResultProps) => {
|
||||
</p>
|
||||
{price && (
|
||||
<p className="text-sm font-semibold text-[#57A595] mt-1">
|
||||
{formatPrice(price)}
|
||||
{formatPrice(
|
||||
Math.min(...product.prices.map((p) => Number(p.price))),
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}}
|
||||
|
||||
@@ -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;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -80,6 +80,14 @@ const Welcome = () => {
|
||||
},
|
||||
});
|
||||
|
||||
const { data: allProducts, isLoading: allProductsLoading } = useQuery({
|
||||
queryKey: ['all_products'],
|
||||
queryFn: () => banner_api.getAllProducts(),
|
||||
select(data) {
|
||||
return data.data;
|
||||
},
|
||||
});
|
||||
|
||||
const scrollPrev = () => {
|
||||
if (api?.canScrollPrev()) {
|
||||
api?.scrollPrev();
|
||||
@@ -272,8 +280,14 @@ const Welcome = () => {
|
||||
</Button>
|
||||
</section>
|
||||
|
||||
{category &&
|
||||
category.map((e) => <CategoryCarousel category={e} key={e.id} />)}
|
||||
{allProducts &&
|
||||
allProducts.map((e) => (
|
||||
<CategoryCarousel
|
||||
category={e}
|
||||
key={e.id}
|
||||
isLoading={allProductsLoading}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user