added baha tassyklamak

This commit is contained in:
Jelaletdin12
2026-04-26 22:07:09 +05:00
parent 7060d05ae9
commit cc89455967
8 changed files with 792 additions and 547 deletions

View File

@@ -3,36 +3,32 @@ import styles from "./ProductCard.module.scss";
import { IoMdHeartEmpty, IoMdHeart } from "react-icons/io";
import { FaShoppingCart } from "react-icons/fa";
import { useNavigate } from "react-router-dom";
import { debounce } from "lodash";
import {
useAddFavoriteMutation,
useRemoveFavoriteMutation,
useGetFavoritesQuery,
} from "../../app/api/favoritesApi";
import { useGetFavoritesQuery } from "../../app/api/favoritesApi";
import {
useAddToCartMutation,
useUpdateCartItemMutation,
useRemoveFromCartMutation,
useGetCartQuery,
} from "../../app/api/cartApi";
import { Modal } from "antd";
import { useTranslation } from "react-i18next";
import { DecreaseIcon, IncreaseIcon } from "../Icons";
import ImageCarousel from "./imageCarousel/index";
import { useCart } from "../../app/api/useCart";
// Helper function to strip HTML tags and truncate text
const truncateDescription = (htmlString, maxLength = 80) => {
const tempDiv = document.createElement("div");
tempDiv.innerHTML = htmlString;
const textContent = tempDiv.textContent || tempDiv.innerText || "";
const truncatedText =
textContent.length > maxLength
? textContent.substring(0, maxLength).trim() + "..."
: textContent;
return truncatedText;
return textContent.length > maxLength
? textContent.substring(0, maxLength).trim() + "..."
: textContent;
};
import { useCart } from "../../app/api/useCart";
const isPriceZero = (price) => !price || parseFloat(price) === 0;
const ProductCard = ({
product,
@@ -45,22 +41,20 @@ const ProductCard = ({
}) => {
const { t } = useTranslation();
const navigate = useNavigate();
const [stockErrorModalVisible, setStockErrorModalVisible] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [isHovered, setIsHovered] = useState(false);
const [addFavorite] = useAddFavoriteMutation();
const [removeFavorite] = useRemoveFavoriteMutation();
const { data: favoriteProducts = [] } = useGetFavoritesQuery();
const [isLoading, setIsLoading] = useState(false);
const [localIsFavorite, setLocalIsFavorite] = useState(
favoriteProducts.some((fav) => fav.product?.id === product.id),
);
// const [isHovered, setIsHovered] = useState(false);
const truncatedDesc = truncateDescription(
product.description,
descriptionMaxLength,
favoriteProducts.some((fav) => fav.product?.id === product.id)
);
const { getCartItem } = useCart();
const [addToCart] = useAddToCartMutation();
const [updateCartItem] = useUpdateCartItemMutation();
const [removeFromCart] = useRemoveFromCartMutation();
@@ -69,26 +63,54 @@ const ProductCard = ({
const [localQuantity, setLocalQuantity] = useState(0);
const [pendingQuantity, setPendingQuantity] = useState(0);
// ✅ Cart item değiştiğinde local state'i güncelle
const { name, price_amount, old_price_amount, media = [], reviews } = product;
const truncatedDesc = truncateDescription(product.description, descriptionMaxLength);
const calculatedDiscount =
!product.discount &&
old_price_amount &&
price_amount &&
old_price_amount > price_amount
? Math.round(((old_price_amount - price_amount) / old_price_amount) * 100)
: null;
useEffect(() => {
const qty = parseInt(
cartItem?.quantity || cartItem?.product_quantity || 0,
10,
);
const qty = parseInt(cartItem?.quantity || cartItem?.product_quantity || 0, 10);
setLocalQuantity(qty);
setPendingQuantity(qty);
}, [cartItem]);
// ✅ Favorite state'i güncelle
useEffect(() => {
if (Array.isArray(favoriteProducts)) {
const isFav = favoriteProducts.some(
(fav) => fav.product?.id === product.id,
setLocalIsFavorite(
favoriteProducts.some((fav) => fav.product?.id === product.id)
);
setLocalIsFavorite(isFav);
}
}, [favoriteProducts, product.id]);
useEffect(() => {
const serverQty = parseInt(cartItem?.quantity || cartItem?.product_quantity || 0, 10);
if (pendingQuantity === serverQty || pendingQuantity <= 0) return;
const handler = setTimeout(async () => {
try {
setIsLoading(true);
await updateCartItem({ productId: product.id, quantity: pendingQuantity }).unwrap();
} catch {
setLocalQuantity(serverQty);
setPendingQuantity(serverQty);
} finally {
setIsLoading(false);
}
}, 500);
return () => clearTimeout(handler);
}, [pendingQuantity, cartItem, product.id, updateCartItem]);
const handleCardClick = () => navigate(`/product/${product.id}`);
const handleAddToCart = async (event) => {
event.preventDefault();
event.stopPropagation();
@@ -98,51 +120,17 @@ const ProductCard = ({
return;
}
// ✅ Optimistic update
setLocalQuantity((prev) => prev + 1);
setPendingQuantity((prev) => prev + 1);
try {
await addToCart({ productId: product.id, quantity: 1 }).unwrap();
// ✅ Başarılı - RTK Query otomatik cache'i güncelleyecek
} catch (error) {
console.error("Failed to add to cart:", error);
// ✅ Hata varsa geri al
} catch {
setLocalQuantity((prev) => prev - 1);
setPendingQuantity((prev) => prev - 1);
}
};
// ✅ Debounced update - sadece mutation, refetch yok
useEffect(() => {
const serverQty = parseInt(
cartItem?.quantity || cartItem?.product_quantity || 0,
10,
);
if (pendingQuantity === serverQty || pendingQuantity <= 0) {
return;
}
const handler = setTimeout(async () => {
try {
setIsLoading(true);
await updateCartItem({
productId: product.id,
quantity: pendingQuantity,
}).unwrap();
} catch (error) {
console.error("Failed to update cart item:", error);
setLocalQuantity(serverQty);
setPendingQuantity(serverQty);
} finally {
setIsLoading(false);
}
}, 500);
return () => clearTimeout(handler);
}, [pendingQuantity, cartItem, product.id, updateCartItem]);
const handleQuantityIncrease = (event) => {
event.preventDefault();
event.stopPropagation();
@@ -165,24 +153,17 @@ const ProductCard = ({
if (isLoading) return;
if (pendingQuantity <= 1) {
// ✅ Sıfıra düşünce direkt sil
setPendingQuantity(0);
setLocalQuantity(0);
setIsLoading(true);
removeFromCart({ productId: product.id })
.unwrap()
.then(() => {
// ✅ Başarılı - RTK Query cache'i güncelleyecek
})
.catch(() => {
// ✅ Hata varsa geri al
setLocalQuantity(1);
setPendingQuantity(1);
})
.finally(() => {
setIsLoading(false);
});
.finally(() => setIsLoading(false));
} else {
setLocalQuantity((prev) => prev - 1);
setPendingQuantity((prev) => prev - 1);
@@ -196,45 +177,25 @@ const ProductCard = ({
if (isLoading) return;
setIsLoading(true);
// ✅ Optimistic update
setLocalIsFavorite(!localIsFavorite);
setLocalIsFavorite((prev) => !prev);
try {
if (localIsFavorite) {
const result = await removeFavorite(product.id).unwrap();
// ✅ Başarılı - RTK Query otomatik güncelleyecek
await removeFavorite(product.id).unwrap();
} else {
const result = await addFavorite(product.id).unwrap();
// ✅ Başarılı - RTK Query otomatik güncelleyecek
await addFavorite(product.id).unwrap();
}
} catch (error) {
console.error("Failed to toggle favorite:", error);
// ✅ Hata varsa geri al
setLocalIsFavorite(localIsFavorite);
} catch {
setLocalIsFavorite((prev) => !prev); // revert
} finally {
setIsLoading(false);
}
};
const handleCardClick = () => {
navigate(`/product/${product.id}`);
};
const [isHovered, setIsHovered] = useState(false);
const { name, price_amount, old_price_amount, media = [], reviews } = product;
// Hesaplanmış indirim oranı
let calculatedDiscount = null;
if (!product.discount && old_price_amount && price_amount && old_price_amount > price_amount) {
calculatedDiscount = Math.round(((old_price_amount - price_amount) / old_price_amount) * 100);
}
return (
<>
<div
className={styles.productCard}
<div
className={styles.productCard}
onClick={handleCardClick}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
@@ -242,7 +203,7 @@ const ProductCard = ({
<div className={styles.imageContainer}>
{(product.discount || calculatedDiscount) && (
<span className={styles.discountBadge}>
-{product.discount ? product.discount : calculatedDiscount}%
-{product.discount ?? calculatedDiscount}%
</span>
)}
{product.stock === 0 && (
@@ -250,22 +211,29 @@ const ProductCard = ({
{t("common.out_of_stock")}
</span>
)}
<ImageCarousel images={media} altText={name} isHovered={isHovered}/>
<ImageCarousel images={media} altText={name} isHovered={isHovered} />
</div>
<div className={styles.productInfo}>
<h3 className={styles.productName}>{name}</h3>
<p className={styles.productDescription}>{truncatedDesc}</p>
<div className={styles.priceContainer}>
<div>
<span className={styles.currentPrice}>{price_amount} m.</span>
{old_price_amount && (
<span className={styles.oldPrice}>{old_price_amount} m.</span>
{isPriceZero(price_amount) ? (
<span className={styles.currentPrice}>Bahasyny anyklamaly</span>
) : (
<>
<span className={styles.currentPrice}>{price_amount} m.</span>
{old_price_amount && (
<span className={styles.oldPrice}>{old_price_amount} m.</span>
)}
</>
)}
</div>
</div>
</div>
<div className={styles.actions}>
{showFavoriteButton && (
<button
@@ -276,6 +244,7 @@ const ProductCard = ({
{localIsFavorite ? <IoMdHeart /> : <IoMdHeartEmpty />}
</button>
)}
{showAddToCart && (
<>
{localQuantity > 0 ? (
@@ -337,4 +306,4 @@ const ProductCard = ({
);
};
export default ProductCard;
export default ProductCard;