Обновлена логика добавления товаров в корзину во всех компонентах. Теперь добавление происходит асинхронно с обработкой успешных и ошибочных результатов. Добавлена информация о наличии товара при добавлении в корзину. Улучшены уведомления о добавлении товара с учетом статуса операции.
This commit is contained in:
@ -73,7 +73,7 @@ const BestPriceCard: React.FC<BestPriceCardProps> = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Обработчик добавления в корзину
|
// Обработчик добавления в корзину
|
||||||
const handleAddToCart = (e: React.MouseEvent) => {
|
const handleAddToCart = async (e: React.MouseEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
|
|
||||||
@ -88,14 +88,8 @@ const BestPriceCard: React.FC<BestPriceCardProps> = ({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Проверяем наличие
|
|
||||||
if (maxCount !== undefined && count > maxCount) {
|
|
||||||
toast.error(`Недостаточно товара в наличии. Доступно: ${maxCount} шт.`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
addItem({
|
const result = await addItem({
|
||||||
productId: offer.productId,
|
productId: offer.productId,
|
||||||
offerKey: offer.offerKey,
|
offerKey: offer.offerKey,
|
||||||
name: description,
|
name: description,
|
||||||
@ -105,6 +99,7 @@ const BestPriceCard: React.FC<BestPriceCardProps> = ({
|
|||||||
price: numericPrice,
|
price: numericPrice,
|
||||||
currency: offer.currency || 'RUB',
|
currency: offer.currency || 'RUB',
|
||||||
quantity: count,
|
quantity: count,
|
||||||
|
stock: maxCount, // передаем информацию о наличии
|
||||||
deliveryTime: delivery,
|
deliveryTime: delivery,
|
||||||
warehouse: offer.warehouse || 'Склад',
|
warehouse: offer.warehouse || 'Склад',
|
||||||
supplier: offer.supplier || (offer.isExternal ? 'AutoEuro' : 'Protek'),
|
supplier: offer.supplier || (offer.isExternal ? 'AutoEuro' : 'Protek'),
|
||||||
@ -112,17 +107,22 @@ const BestPriceCard: React.FC<BestPriceCardProps> = ({
|
|||||||
image: offer.image,
|
image: offer.image,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Показываем тоастер об успешном добавлении
|
if (result.success) {
|
||||||
toast.success(
|
// Показываем тоастер об успешном добавлении
|
||||||
<div>
|
toast.success(
|
||||||
<div className="font-semibold" style={{ color: '#fff' }}>Товар добавлен в корзину!</div>
|
<div>
|
||||||
<div className="text-sm" style={{ color: '#fff', opacity: 0.9 }}>{`${offer.brand} ${offer.articleNumber} (${count} шт.)`}</div>
|
<div className="font-semibold" style={{ color: '#fff' }}>Товар добавлен в корзину!</div>
|
||||||
</div>,
|
<div className="text-sm" style={{ color: '#fff', opacity: 0.9 }}>{`${offer.brand} ${offer.articleNumber} (${count} шт.)`}</div>
|
||||||
{
|
</div>,
|
||||||
duration: 3000,
|
{
|
||||||
icon: <CartIcon size={20} color="#fff" />,
|
duration: 3000,
|
||||||
}
|
icon: <CartIcon size={20} color="#fff" />,
|
||||||
);
|
}
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Показываем ошибку
|
||||||
|
toast.error(result.error || 'Ошибка при добавлении товара в корзину');
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Ошибка добавления в корзину:', error);
|
console.error('Ошибка добавления в корзину:', error);
|
||||||
toast.error('Ошибка добавления товара в корзину');
|
toast.error('Ошибка добавления товара в корзину');
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import React from "react";
|
import React, { useEffect } from "react";
|
||||||
import CartItem from "./CartItem";
|
import CartItem from "./CartItem";
|
||||||
import { useCart } from "@/contexts/CartContext";
|
import { useCart } from "@/contexts/CartContext";
|
||||||
import { useFavorites } from "@/contexts/FavoritesContext";
|
import { useFavorites } from "@/contexts/FavoritesContext";
|
||||||
@ -8,7 +8,7 @@ interface CartListProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const CartList: React.FC<CartListProps> = ({ isSummaryStep = false }) => {
|
const CartList: React.FC<CartListProps> = ({ isSummaryStep = false }) => {
|
||||||
const { state, toggleSelect, updateComment, removeItem, selectAll, removeSelected, updateQuantity } = useCart();
|
const { state, toggleSelect, updateComment, removeItem, selectAll, removeSelected, updateQuantity, clearError } = useCart();
|
||||||
const { addToFavorites, removeFromFavorites, isFavorite, favorites } = useFavorites();
|
const { addToFavorites, removeFromFavorites, isFavorite, favorites } = useFavorites();
|
||||||
const { items } = state;
|
const { items } = state;
|
||||||
|
|
||||||
@ -73,8 +73,40 @@ const CartList: React.FC<CartListProps> = ({ isSummaryStep = false }) => {
|
|||||||
// На втором шаге показываем только выбранные товары
|
// На втором шаге показываем только выбранные товары
|
||||||
const displayItems = isSummaryStep ? items.filter(item => item.selected) : items;
|
const displayItems = isSummaryStep ? items.filter(item => item.selected) : items;
|
||||||
|
|
||||||
|
// Автоматически очищаем ошибки через 5 секунд
|
||||||
|
useEffect(() => {
|
||||||
|
if (state.error) {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
clearError();
|
||||||
|
}, 5000);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}
|
||||||
|
}, [state.error, clearError]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-layout-vflex flex-block-48">
|
<div className="w-layout-vflex flex-block-48">
|
||||||
|
{/* Отображение ошибок корзины */}
|
||||||
|
{state.error && (
|
||||||
|
<div className="alert alert-error mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center">
|
||||||
|
<svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
|
||||||
|
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
|
||||||
|
</svg>
|
||||||
|
<span>{state.error}</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={clearError}
|
||||||
|
className="ml-2 text-red-500 hover:text-red-700"
|
||||||
|
aria-label="Закрыть уведомление"
|
||||||
|
>
|
||||||
|
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<div className="w-layout-vflex product-list-cart">
|
<div className="w-layout-vflex product-list-cart">
|
||||||
{!isSummaryStep && (
|
{!isSummaryStep && (
|
||||||
<div className="w-layout-hflex multi-control">
|
<div className="w-layout-hflex multi-control">
|
||||||
|
@ -37,13 +37,14 @@ const RecommendedProductCard: React.FC<{
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Добавляем товар в корзину
|
// Добавляем товар в корзину
|
||||||
addItem({
|
const result = await addItem({
|
||||||
productId: String(item.artId) || undefined,
|
productId: String(item.artId) || undefined,
|
||||||
name: item.name || `${item.brand} ${item.articleNumber}`,
|
name: item.name || `${item.brand} ${item.articleNumber}`,
|
||||||
description: item.name || `${item.brand} ${item.articleNumber}`,
|
description: item.name || `${item.brand} ${item.articleNumber}`,
|
||||||
price: numericPrice,
|
price: numericPrice,
|
||||||
currency: 'RUB',
|
currency: 'RUB',
|
||||||
quantity: 1,
|
quantity: 1,
|
||||||
|
stock: undefined, // информация о наличии не доступна для рекомендуемых товаров
|
||||||
image: displayImage,
|
image: displayImage,
|
||||||
brand: item.brand,
|
brand: item.brand,
|
||||||
article: item.articleNumber,
|
article: item.articleNumber,
|
||||||
@ -52,17 +53,22 @@ const RecommendedProductCard: React.FC<{
|
|||||||
isExternal: true
|
isExternal: true
|
||||||
});
|
});
|
||||||
|
|
||||||
// Показываем успешный тоастер
|
if (result.success) {
|
||||||
toast.success(
|
// Показываем успешный тоастер
|
||||||
<div>
|
toast.success(
|
||||||
<div className="font-semibold" style={{ color: '#fff' }}>Товар добавлен в корзину!</div>
|
<div>
|
||||||
<div className="text-sm" style={{ color: '#fff', opacity: 0.9 }}>{item.name || `${item.brand} ${item.articleNumber}`}</div>
|
<div className="font-semibold" style={{ color: '#fff' }}>Товар добавлен в корзину!</div>
|
||||||
</div>,
|
<div className="text-sm" style={{ color: '#fff', opacity: 0.9 }}>{item.name || `${item.brand} ${item.articleNumber}`}</div>
|
||||||
{
|
</div>,
|
||||||
duration: 3000,
|
{
|
||||||
icon: <CartIcon size={20} color="#fff" />,
|
duration: 3000,
|
||||||
}
|
icon: <CartIcon size={20} color="#fff" />,
|
||||||
);
|
}
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Показываем ошибку
|
||||||
|
toast.error(result.error || 'Ошибка при добавлении товара в корзину');
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Ошибка добавления в корзину:', error);
|
console.error('Ошибка добавления в корзину:', error);
|
||||||
toast.error('Ошибка при добавлении товара в корзину');
|
toast.error('Ошибка при добавлении товара в корзину');
|
||||||
|
@ -123,19 +123,13 @@ const CoreProductCard: React.FC<CoreProductCardProps> = ({
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleAddToCart = (offer: CoreProductCardOffer, index: number) => {
|
const handleAddToCart = async (offer: CoreProductCardOffer, index: number) => {
|
||||||
const quantity = quantities[index] || 1;
|
const quantity = quantities[index] || 1;
|
||||||
const availableStock = parseStock(offer.pcs);
|
const availableStock = parseStock(offer.pcs);
|
||||||
|
|
||||||
// Проверяем наличие
|
|
||||||
if (quantity > availableStock) {
|
|
||||||
toast.error(`Недостаточно товара в наличии. Доступно: ${availableStock} шт.`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const numericPrice = parsePrice(offer.price);
|
const numericPrice = parsePrice(offer.price);
|
||||||
|
|
||||||
addItem({
|
const result = await addItem({
|
||||||
productId: offer.productId,
|
productId: offer.productId,
|
||||||
offerKey: offer.offerKey,
|
offerKey: offer.offerKey,
|
||||||
name: name,
|
name: name,
|
||||||
@ -145,6 +139,7 @@ const CoreProductCard: React.FC<CoreProductCardProps> = ({
|
|||||||
price: numericPrice,
|
price: numericPrice,
|
||||||
currency: offer.currency || 'RUB',
|
currency: offer.currency || 'RUB',
|
||||||
quantity: quantity,
|
quantity: quantity,
|
||||||
|
stock: availableStock, // передаем информацию о наличии
|
||||||
deliveryTime: parseDeliveryTime(offer.days),
|
deliveryTime: parseDeliveryTime(offer.days),
|
||||||
warehouse: offer.warehouse || 'Склад',
|
warehouse: offer.warehouse || 'Склад',
|
||||||
supplier: offer.supplier || (offer.isExternal ? 'AutoEuro' : 'Protek'),
|
supplier: offer.supplier || (offer.isExternal ? 'AutoEuro' : 'Protek'),
|
||||||
@ -152,17 +147,22 @@ const CoreProductCard: React.FC<CoreProductCardProps> = ({
|
|||||||
image: image,
|
image: image,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Показываем тоастер вместо alert
|
if (result.success) {
|
||||||
toast.success(
|
// Показываем тоастер вместо alert
|
||||||
<div>
|
toast.success(
|
||||||
<div className="font-semibold" style={{ color: '#fff' }}>Товар добавлен в корзину!</div>
|
<div>
|
||||||
<div className="text-sm" style={{ color: '#fff', opacity: 0.9 }}>{`${brand} ${article} (${quantity} шт.)`}</div>
|
<div className="font-semibold" style={{ color: '#fff' }}>Товар добавлен в корзину!</div>
|
||||||
</div>,
|
<div className="text-sm" style={{ color: '#fff', opacity: 0.9 }}>{`${brand} ${article} (${quantity} шт.)`}</div>
|
||||||
{
|
</div>,
|
||||||
duration: 3000,
|
{
|
||||||
icon: <CartIcon size={20} color="#fff" />,
|
duration: 3000,
|
||||||
}
|
icon: <CartIcon size={20} color="#fff" />,
|
||||||
);
|
}
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Показываем ошибку
|
||||||
|
toast.error(result.error || 'Ошибка при добавлении товара в корзину');
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Обработчик клика по сердечку
|
// Обработчик клика по сердечку
|
||||||
|
@ -59,19 +59,13 @@ const ProductListCard: React.FC<ProductListCardProps> = ({
|
|||||||
return match ? parseInt(match[0]) : 0;
|
return match ? parseInt(match[0]) : 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleAddToCart = () => {
|
const handleAddToCart = async () => {
|
||||||
const availableStock = parseStock(stock);
|
const availableStock = parseStock(stock);
|
||||||
|
|
||||||
// Проверяем наличие
|
|
||||||
if (count > availableStock) {
|
|
||||||
alert(`Недостаточно товара в наличии. Доступно: ${availableStock} шт.`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const numericPrice = parsePrice(price);
|
const numericPrice = parsePrice(price);
|
||||||
const numericOldPrice = oldPrice ? parsePrice(oldPrice) : undefined;
|
const numericOldPrice = oldPrice ? parsePrice(oldPrice) : undefined;
|
||||||
|
|
||||||
addItem({
|
const result = await addItem({
|
||||||
productId: productId,
|
productId: productId,
|
||||||
offerKey: offerKey,
|
offerKey: offerKey,
|
||||||
name: title,
|
name: title,
|
||||||
@ -81,6 +75,7 @@ const ProductListCard: React.FC<ProductListCardProps> = ({
|
|||||||
originalPrice: numericOldPrice,
|
originalPrice: numericOldPrice,
|
||||||
currency: currency,
|
currency: currency,
|
||||||
quantity: count,
|
quantity: count,
|
||||||
|
stock: availableStock, // передаем информацию о наличии
|
||||||
deliveryTime: deliveryTime || delivery,
|
deliveryTime: deliveryTime || delivery,
|
||||||
warehouse: warehouse || address,
|
warehouse: warehouse || address,
|
||||||
supplier: supplier,
|
supplier: supplier,
|
||||||
@ -88,8 +83,13 @@ const ProductListCard: React.FC<ProductListCardProps> = ({
|
|||||||
image: image,
|
image: image,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Показываем уведомление о добавлении
|
if (result.success) {
|
||||||
alert(`Товар "${title}" добавлен в корзину (${count} шт.)`);
|
// Показываем уведомление о добавлении
|
||||||
|
alert(`Товар "${title}" добавлен в корзину (${count} шт.)`);
|
||||||
|
} else {
|
||||||
|
// Показываем ошибку
|
||||||
|
alert(result.error || 'Ошибка при добавлении товара в корзину');
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
@ -38,7 +38,7 @@ const ProductBuyBlock = ({ offer }: ProductBuyBlockProps) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Добавляем товар в корзину
|
// Добавляем товар в корзину
|
||||||
addItem({
|
const result = await addItem({
|
||||||
productId: offer.id ? String(offer.id) : undefined,
|
productId: offer.id ? String(offer.id) : undefined,
|
||||||
offerKey: offer.offerKey || undefined,
|
offerKey: offer.offerKey || undefined,
|
||||||
name: offer.name || `${offer.brand} ${offer.articleNumber}`,
|
name: offer.name || `${offer.brand} ${offer.articleNumber}`,
|
||||||
@ -46,6 +46,7 @@ const ProductBuyBlock = ({ offer }: ProductBuyBlockProps) => {
|
|||||||
price: offer.price,
|
price: offer.price,
|
||||||
currency: 'RUB',
|
currency: 'RUB',
|
||||||
quantity: quantity,
|
quantity: quantity,
|
||||||
|
stock: offer.quantity, // передаем информацию о наличии
|
||||||
image: offer.image || undefined,
|
image: offer.image || undefined,
|
||||||
brand: offer.brand,
|
brand: offer.brand,
|
||||||
article: offer.articleNumber,
|
article: offer.articleNumber,
|
||||||
@ -54,17 +55,22 @@ const ProductBuyBlock = ({ offer }: ProductBuyBlockProps) => {
|
|||||||
isExternal: offer.type === 'external'
|
isExternal: offer.type === 'external'
|
||||||
});
|
});
|
||||||
|
|
||||||
// Показываем успешный тоастер
|
if (result.success) {
|
||||||
toast.success(
|
// Показываем успешный тоастер
|
||||||
<div>
|
toast.success(
|
||||||
<div className="font-semibold" style={{ color: '#fff' }}>Товар добавлен в корзину!</div>
|
<div>
|
||||||
<div className="text-sm" style={{ color: '#fff', opacity: 0.9 }}>{offer.name || `${offer.brand} ${offer.articleNumber}`}</div>
|
<div className="font-semibold" style={{ color: '#fff' }}>Товар добавлен в корзину!</div>
|
||||||
</div>,
|
<div className="text-sm" style={{ color: '#fff', opacity: 0.9 }}>{offer.name || `${offer.brand} ${offer.articleNumber}`}</div>
|
||||||
{
|
</div>,
|
||||||
duration: 3000,
|
{
|
||||||
icon: <CartIcon size={20} color="#fff" />,
|
duration: 3000,
|
||||||
}
|
icon: <CartIcon size={20} color="#fff" />,
|
||||||
);
|
}
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Показываем ошибку
|
||||||
|
toast.error(result.error || 'Ошибка при добавлении товара в корзину');
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Ошибка добавления в корзину:', error);
|
console.error('Ошибка добавления в корзину:', error);
|
||||||
toast.error('Ошибка при добавлении товара в корзину');
|
toast.error('Ошибка при добавлении товара в корзину');
|
||||||
|
@ -25,6 +25,8 @@ const initialState: CartState = {
|
|||||||
// Типы действий
|
// Типы действий
|
||||||
type CartAction =
|
type CartAction =
|
||||||
| { type: 'ADD_ITEM'; payload: Omit<CartItem, 'id' | 'selected' | 'favorite'> }
|
| { type: 'ADD_ITEM'; payload: Omit<CartItem, 'id' | 'selected' | 'favorite'> }
|
||||||
|
| { type: 'ADD_ITEM_SUCCESS'; payload: { items: CartItem[]; summary: any } }
|
||||||
|
| { type: 'ADD_ITEM_ERROR'; payload: string }
|
||||||
| { type: 'REMOVE_ITEM'; payload: string }
|
| { type: 'REMOVE_ITEM'; payload: string }
|
||||||
| { type: 'UPDATE_QUANTITY'; payload: { id: string; quantity: number } }
|
| { type: 'UPDATE_QUANTITY'; payload: { id: string; quantity: number } }
|
||||||
| { type: 'TOGGLE_SELECT'; payload: string }
|
| { type: 'TOGGLE_SELECT'; payload: string }
|
||||||
@ -44,6 +46,16 @@ type CartAction =
|
|||||||
// Функция для генерации ID
|
// Функция для генерации ID
|
||||||
const generateId = () => Math.random().toString(36).substr(2, 9)
|
const generateId = () => Math.random().toString(36).substr(2, 9)
|
||||||
|
|
||||||
|
// Утилитарная функция для парсинга количества в наличии
|
||||||
|
const parseStock = (stockStr: string | number | undefined): number => {
|
||||||
|
if (typeof stockStr === 'number') return stockStr;
|
||||||
|
if (typeof stockStr === 'string') {
|
||||||
|
const match = stockStr.match(/\d+/);
|
||||||
|
return match ? parseInt(match[0]) : 0;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
};
|
||||||
|
|
||||||
// Функция для расчета итогов
|
// Функция для расчета итогов
|
||||||
const calculateSummary = (items: CartItem[], deliveryPrice: number) => {
|
const calculateSummary = (items: CartItem[], deliveryPrice: number) => {
|
||||||
const selectedItems = items.filter(item => item.selected)
|
const selectedItems = items.filter(item => item.selected)
|
||||||
@ -78,9 +90,12 @@ const cartReducer = (state: CartState, action: CartAction): CartState => {
|
|||||||
|
|
||||||
if (existingItemIndex >= 0) {
|
if (existingItemIndex >= 0) {
|
||||||
// Увеличиваем количество существующего товара
|
// Увеличиваем количество существующего товара
|
||||||
|
const existingItem = state.items[existingItemIndex];
|
||||||
|
const totalQuantity = existingItem.quantity + action.payload.quantity;
|
||||||
|
|
||||||
newItems = state.items.map((item, index) =>
|
newItems = state.items.map((item, index) =>
|
||||||
index === existingItemIndex
|
index === existingItemIndex
|
||||||
? { ...item, quantity: item.quantity + action.payload.quantity }
|
? { ...item, quantity: totalQuantity }
|
||||||
: item
|
: item
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
@ -335,8 +350,31 @@ export const CartProvider: React.FC<{ children: React.ReactNode }> = ({ children
|
|||||||
}, [state.items, state.delivery, state.orderComment, isInitialized])
|
}, [state.items, state.delivery, state.orderComment, isInitialized])
|
||||||
|
|
||||||
// Функции для работы с корзиной
|
// Функции для работы с корзиной
|
||||||
const addItem = (item: Omit<CartItem, 'id' | 'selected' | 'favorite'>) => {
|
const addItem = async (item: Omit<CartItem, 'id' | 'selected' | 'favorite'>) => {
|
||||||
|
// Проверяем наличие товара на складе перед добавлением
|
||||||
|
const existingItemIndex = state.items.findIndex(
|
||||||
|
existingItem =>
|
||||||
|
(existingItem.productId && existingItem.productId === item.productId) ||
|
||||||
|
(existingItem.offerKey && existingItem.offerKey === item.offerKey)
|
||||||
|
)
|
||||||
|
|
||||||
|
let totalQuantity = item.quantity;
|
||||||
|
if (existingItemIndex >= 0) {
|
||||||
|
const existingItem = state.items[existingItemIndex];
|
||||||
|
totalQuantity = existingItem.quantity + item.quantity;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Проверяем наличие товара на складе
|
||||||
|
const availableStock = parseStock(item.stock);
|
||||||
|
if (availableStock > 0 && totalQuantity > availableStock) {
|
||||||
|
const errorMessage = `Недостаточно товара в наличии. Доступно: ${availableStock} шт., запрошено: ${totalQuantity} шт.`;
|
||||||
|
dispatch({ type: 'SET_ERROR', payload: errorMessage });
|
||||||
|
return { success: false, error: errorMessage };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Если проверка прошла успешно, добавляем товар
|
||||||
dispatch({ type: 'ADD_ITEM', payload: item })
|
dispatch({ type: 'ADD_ITEM', payload: item })
|
||||||
|
return { success: true }
|
||||||
}
|
}
|
||||||
|
|
||||||
const removeItem = (id: string) => {
|
const removeItem = (id: string) => {
|
||||||
@ -344,6 +382,17 @@ export const CartProvider: React.FC<{ children: React.ReactNode }> = ({ children
|
|||||||
}
|
}
|
||||||
|
|
||||||
const updateQuantity = (id: string, quantity: number) => {
|
const updateQuantity = (id: string, quantity: number) => {
|
||||||
|
// Найдем товар для проверки наличия
|
||||||
|
const item = state.items.find(item => item.id === id);
|
||||||
|
if (item) {
|
||||||
|
const availableStock = parseStock(item.stock);
|
||||||
|
if (availableStock > 0 && quantity > availableStock) {
|
||||||
|
// Показываем ошибку, но не изменяем количество
|
||||||
|
dispatch({ type: 'SET_ERROR', payload: `Недостаточно товара в наличии. Доступно: ${availableStock} шт.` });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
dispatch({ type: 'UPDATE_QUANTITY', payload: { id, quantity } })
|
dispatch({ type: 'UPDATE_QUANTITY', payload: { id, quantity } })
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -388,6 +437,10 @@ export const CartProvider: React.FC<{ children: React.ReactNode }> = ({ children
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const clearError = () => {
|
||||||
|
dispatch({ type: 'SET_ERROR', payload: '' })
|
||||||
|
}
|
||||||
|
|
||||||
const contextValue: CartContextType = {
|
const contextValue: CartContextType = {
|
||||||
state,
|
state,
|
||||||
addItem,
|
addItem,
|
||||||
@ -401,7 +454,8 @@ export const CartProvider: React.FC<{ children: React.ReactNode }> = ({ children
|
|||||||
removeAll,
|
removeAll,
|
||||||
removeSelected,
|
removeSelected,
|
||||||
updateDelivery,
|
updateDelivery,
|
||||||
clearCart
|
clearCart,
|
||||||
|
clearError
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
@ -231,6 +231,7 @@ export const useCatalogPrices = (): UseCatalogPricesReturn => {
|
|||||||
price: cheapestOffer.price,
|
price: cheapestOffer.price,
|
||||||
currency: cheapestOffer.currency || 'RUB',
|
currency: cheapestOffer.currency || 'RUB',
|
||||||
quantity: 1,
|
quantity: 1,
|
||||||
|
stock: cheapestOffer.quantity, // передаем информацию о наличии
|
||||||
deliveryTime: cheapestOffer.deliveryDays?.toString() || '0',
|
deliveryTime: cheapestOffer.deliveryDays?.toString() || '0',
|
||||||
warehouse: cheapestOffer.warehouse || 'Склад',
|
warehouse: cheapestOffer.warehouse || 'Склад',
|
||||||
supplier: cheapestOffer.supplierName || 'Неизвестный поставщик',
|
supplier: cheapestOffer.supplierName || 'Неизвестный поставщик',
|
||||||
@ -238,10 +239,14 @@ export const useCatalogPrices = (): UseCatalogPricesReturn => {
|
|||||||
image: '', // Убираем мокап-фотку, изображения будут загружаться отдельно
|
image: '', // Убираем мокап-фотку, изображения будут загружаться отдельно
|
||||||
};
|
};
|
||||||
|
|
||||||
addItem(itemToAdd);
|
const result = await addItem(itemToAdd);
|
||||||
|
|
||||||
// Показываем уведомление
|
if (result.success) {
|
||||||
toast.success(`Товар "${brand} ${articleNumber}" добавлен в корзину за ${cheapestOffer.price} ₽`);
|
// Показываем уведомление
|
||||||
|
toast.success(`Товар "${brand} ${articleNumber}" добавлен в корзину за ${cheapestOffer.price} ₽`);
|
||||||
|
} else {
|
||||||
|
toast.error(result.error || 'Ошибка добавления товара в корзину');
|
||||||
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Ошибка добавления в корзину:', error);
|
console.error('Ошибка добавления в корзину:', error);
|
||||||
|
@ -721,7 +721,7 @@ export default function Catalog() {
|
|||||||
productId={entity.id}
|
productId={entity.id}
|
||||||
artId={entity.id}
|
artId={entity.id}
|
||||||
offerKey={priceData?.offerKey}
|
offerKey={priceData?.offerKey}
|
||||||
onAddToCart={() => {
|
onAddToCart={async () => {
|
||||||
// Если цена не загружена, загружаем её и добавляем в корзину
|
// Если цена не загружена, загружаем её и добавляем в корзину
|
||||||
if (!priceData && !isLoadingPriceData) {
|
if (!priceData && !isLoadingPriceData) {
|
||||||
loadPriceOnDemand(productForPrice);
|
loadPriceOnDemand(productForPrice);
|
||||||
@ -741,6 +741,7 @@ export default function Catalog() {
|
|||||||
price: priceData.price,
|
price: priceData.price,
|
||||||
currency: priceData.currency || 'RUB',
|
currency: priceData.currency || 'RUB',
|
||||||
quantity: 1,
|
quantity: 1,
|
||||||
|
stock: undefined, // информация о наличии не доступна для PartsIndex
|
||||||
deliveryTime: '1-3 дня',
|
deliveryTime: '1-3 дня',
|
||||||
warehouse: 'Parts Index',
|
warehouse: 'Parts Index',
|
||||||
supplier: 'Parts Index',
|
supplier: 'Parts Index',
|
||||||
@ -748,19 +749,23 @@ export default function Catalog() {
|
|||||||
image: entity.images?.[0] || '',
|
image: entity.images?.[0] || '',
|
||||||
};
|
};
|
||||||
|
|
||||||
addItem(itemToAdd);
|
const result = await addItem(itemToAdd);
|
||||||
|
|
||||||
// Показываем уведомление
|
if (result.success) {
|
||||||
toast.success(
|
// Показываем уведомление
|
||||||
<div>
|
toast.success(
|
||||||
<div className="font-semibold" style={{ color: '#fff' }}>Товар добавлен в корзину!</div>
|
<div>
|
||||||
<div className="text-sm" style={{ color: '#fff', opacity: 0.9 }}>{`${entity.brand.name} ${entity.code} за ${priceData.price.toLocaleString('ru-RU')} ₽`}</div>
|
<div className="font-semibold" style={{ color: '#fff' }}>Товар добавлен в корзину!</div>
|
||||||
</div>,
|
<div className="text-sm" style={{ color: '#fff', opacity: 0.9 }}>{`${entity.brand.name} ${entity.code} за ${priceData.price.toLocaleString('ru-RU')} ₽`}</div>
|
||||||
{
|
</div>,
|
||||||
duration: 3000,
|
{
|
||||||
icon: <CartIcon size={20} color="#fff" />,
|
duration: 3000,
|
||||||
}
|
icon: <CartIcon size={20} color="#fff" />,
|
||||||
);
|
}
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
toast.error(result.error || 'Ошибка при добавлении товара в корзину');
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
toast.error('Цена товара еще загружается. Попробуйте снова через несколько секунд.');
|
toast.error('Цена товара еще загружается. Попробуйте снова через несколько секунд.');
|
||||||
}
|
}
|
||||||
|
@ -10,6 +10,7 @@ export interface CartItem {
|
|||||||
originalPrice?: number
|
originalPrice?: number
|
||||||
currency: string
|
currency: string
|
||||||
quantity: number
|
quantity: number
|
||||||
|
stock?: string | number // количество товара в наличии на складе
|
||||||
deliveryTime?: string
|
deliveryTime?: string
|
||||||
deliveryDate?: string
|
deliveryDate?: string
|
||||||
warehouse?: string
|
warehouse?: string
|
||||||
@ -52,7 +53,7 @@ export interface CartState {
|
|||||||
|
|
||||||
export interface CartContextType {
|
export interface CartContextType {
|
||||||
state: CartState
|
state: CartState
|
||||||
addItem: (item: Omit<CartItem, 'id' | 'selected' | 'favorite'>) => void
|
addItem: (item: Omit<CartItem, 'id' | 'selected' | 'favorite'>) => Promise<{ success: boolean; error?: string }>
|
||||||
removeItem: (id: string) => void
|
removeItem: (id: string) => void
|
||||||
updateQuantity: (id: string, quantity: number) => void
|
updateQuantity: (id: string, quantity: number) => void
|
||||||
toggleSelect: (id: string) => void
|
toggleSelect: (id: string) => void
|
||||||
@ -64,4 +65,5 @@ export interface CartContextType {
|
|||||||
removeSelected: () => void
|
removeSelected: () => void
|
||||||
updateDelivery: (delivery: Partial<DeliveryInfo>) => void
|
updateDelivery: (delivery: Partial<DeliveryInfo>) => void
|
||||||
clearCart: () => void
|
clearCart: () => void
|
||||||
|
clearError: () => void
|
||||||
}
|
}
|
Reference in New Issue
Block a user