order status update
This commit is contained in:
@@ -36,25 +36,21 @@ const CartPage = () => {
|
||||
select: (data) => data.data.cart_item,
|
||||
});
|
||||
|
||||
const [quantities, setQuantities] = useState<Record<string, string>>({});
|
||||
const [quantities, setQuantities] = useState<Record<string, number>>({});
|
||||
const debounceRef = useRef<Record<string, NodeJS.Timeout | null>>({});
|
||||
|
||||
// O'lchov birligini formatlash uchun yordamchi funksiya
|
||||
const getQuantityMessage = (qty: number, measurement: string | null) => {
|
||||
if (!measurement) return `${qty} dona`;
|
||||
return `${qty} ${measurement}`;
|
||||
};
|
||||
|
||||
// Initial state
|
||||
useEffect(() => {
|
||||
if (!cartItems) return;
|
||||
const initialQuantities: Record<string, string> = {};
|
||||
const initialQuantities: Record<string, number> = {};
|
||||
cartItems.forEach((item) => {
|
||||
initialQuantities[item.id] = String(item.quantity);
|
||||
initialQuantities[item.id] = item.quantity;
|
||||
debounceRef.current[item.id] = null;
|
||||
});
|
||||
setQuantities(initialQuantities);
|
||||
}, [cartItems]);
|
||||
|
||||
// Update cart item mutation
|
||||
const { mutate: updateCartItem } = useMutation({
|
||||
mutationFn: ({
|
||||
body,
|
||||
@@ -66,18 +62,14 @@ const CartPage = () => {
|
||||
onSuccess: (_, variables) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['cart_items', cart_id] });
|
||||
|
||||
// Qaysi mahsulot yangilanganini topish
|
||||
const item = cartItems?.find(
|
||||
(i) => String(i.id) === variables.cart_item_id,
|
||||
);
|
||||
if (item) {
|
||||
const measurementName = item.product.meansurement?.name || null;
|
||||
toast.success(
|
||||
`${t('Miqdor')} ${getQuantityMessage(variables.body.quantity, measurementName)} ${t('ga yangilandi')}`,
|
||||
{
|
||||
richColors: true,
|
||||
position: 'top-center',
|
||||
},
|
||||
`${t('Miqdor')} ${variables.body.quantity} ${measurementName || 'шт.'} ${t('ga yangilandi')}`,
|
||||
{ richColors: true, position: 'top-center' },
|
||||
);
|
||||
}
|
||||
},
|
||||
@@ -85,6 +77,7 @@ const CartPage = () => {
|
||||
toast.error(err.message, { richColors: true, position: 'top-center' }),
|
||||
});
|
||||
|
||||
// Delete cart item mutation
|
||||
const { mutate: deleteCartItem } = useMutation({
|
||||
mutationFn: ({ cart_item_id }: { cart_item_id: string }) =>
|
||||
cart_api.delete_cart_item(cart_item_id),
|
||||
@@ -130,31 +123,53 @@ const CartPage = () => {
|
||||
);
|
||||
|
||||
const subtotal =
|
||||
cartItems?.reduce((sum, item) => {
|
||||
if (item.product.prices.length === 0) return sum;
|
||||
|
||||
cartItems.reduce((sum, item) => {
|
||||
if (!item.product.prices.length) return sum;
|
||||
const maxPrice = Math.max(
|
||||
...item.product.prices.map((p) => Number(p.price)),
|
||||
);
|
||||
|
||||
return sum + maxPrice * item.quantity;
|
||||
return sum + maxPrice * (quantities[item.id] || item.quantity);
|
||||
}, 0) || 0;
|
||||
|
||||
const handleQuantityChange = (itemId: string, value: number) => {
|
||||
setQuantities((prev) => ({
|
||||
...prev,
|
||||
[itemId]: String(value),
|
||||
}));
|
||||
const handleQuantityChange = (
|
||||
itemId: number,
|
||||
delta: number = 0,
|
||||
newValue?: number,
|
||||
) => {
|
||||
setQuantities((prev) => {
|
||||
const item = cartItems?.find((i) => i.id === Number(itemId));
|
||||
if (!item) return prev;
|
||||
|
||||
if (debounceRef.current[itemId]) clearTimeout(debounceRef.current[itemId]!);
|
||||
const isGram = item.product.meansurement?.name?.toLowerCase() === 'gr';
|
||||
const STEP = isGram ? 100 : 1;
|
||||
const MIN_QTY = isGram ? 100 : 1;
|
||||
|
||||
debounceRef.current[itemId] = setTimeout(() => {
|
||||
if (value <= 0) {
|
||||
deleteCartItem({ cart_item_id: itemId });
|
||||
let updatedQty;
|
||||
|
||||
if (newValue !== undefined) {
|
||||
// Input'dan kiritilgan qiymat - minimal limitni qo'llash shart emas
|
||||
updatedQty = newValue;
|
||||
} else {
|
||||
updateCartItem({ body: { quantity: value }, cart_item_id: itemId });
|
||||
// +/- tugmalar bosilganda - STEP qo'llash va minimal limit
|
||||
updatedQty = (prev[itemId] ?? MIN_QTY) + delta * STEP;
|
||||
if (updatedQty < MIN_QTY) updatedQty = MIN_QTY;
|
||||
}
|
||||
}, 500);
|
||||
|
||||
// Debounce server update
|
||||
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 };
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -172,13 +187,10 @@ const CartPage = () => {
|
||||
{cartItems.map((item, index) => {
|
||||
const measurementDisplay =
|
||||
item.product.meansurement?.name || 'шт.';
|
||||
|
||||
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"
|
||||
@@ -216,13 +228,9 @@ const CartPage = () => {
|
||||
<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,
|
||||
Math.max(
|
||||
...item.product.prices.map((p) => Number(p.price)),
|
||||
),
|
||||
true,
|
||||
)}
|
||||
</span>
|
||||
@@ -231,19 +239,13 @@ const CartPage = () => {
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* O'lchov ko'rsatkichi */}
|
||||
<p className="text-sm text-gray-500 mb-2">
|
||||
{t('Miqdor')}: {quantities[item.id]} {measurementDisplay}
|
||||
</p>
|
||||
|
||||
<div className="flex items-center border border-gray-300 rounded-lg w-max">
|
||||
<button
|
||||
onClick={() =>
|
||||
handleQuantityChange(
|
||||
String(item.id),
|
||||
Number(quantities[item.id]) - 1,
|
||||
)
|
||||
}
|
||||
onClick={() => handleQuantityChange(item.id, -1)}
|
||||
className="p-2 cursor-pointer transition rounded-lg hover:bg-gray-50"
|
||||
>
|
||||
<Minus className="w-4 h-4" />
|
||||
@@ -251,18 +253,11 @@ const CartPage = () => {
|
||||
|
||||
<div className="flex items-center gap-1 px-2">
|
||||
<Input
|
||||
value={quantities[item.id]}
|
||||
value={quantities[item.id] || ''}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value.replace(/\D/g, '');
|
||||
const valNum = Number(val);
|
||||
|
||||
setQuantities((prev) => ({
|
||||
...prev,
|
||||
[item.id]: val,
|
||||
}));
|
||||
|
||||
if (!isNaN(valNum))
|
||||
handleQuantityChange(String(item.id), valNum);
|
||||
const cleaned = e.target.value.replace(/\D/g, '');
|
||||
const val = cleaned === '' ? 0 : Number(cleaned);
|
||||
handleQuantityChange(item.id, 0, val);
|
||||
}}
|
||||
type="text"
|
||||
className="w-14 text-center border-none p-0"
|
||||
@@ -273,13 +268,8 @@ const CartPage = () => {
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() =>
|
||||
handleQuantityChange(
|
||||
String(item.id),
|
||||
Number(quantities[item.id]) + 1,
|
||||
)
|
||||
}
|
||||
className="p-2 cursor-pointer transition rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
onClick={() => handleQuantityChange(item.id, 1)}
|
||||
className="p-2 cursor-pointer transition rounded-lg hover:bg-gray-50"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
Reference in New Issue
Block a user