changed order

This commit is contained in:
Jelaletdin12
2025-12-23 22:55:19 +05:00
parent db68bf9c3d
commit 9d95438ab2
13 changed files with 541 additions and 339 deletions

View File

@@ -24,7 +24,7 @@ const useDeviceType = () => {
return deviceType;
};
const Checkout = ({ cartItems, onBackToCart, onPlaceOrder }) => {
const Checkout = ({ cartItems, shippingPrice, productIds, onBackToCart, onPlaceOrder }) => {
const { t } = useTranslation();
const [formData, setFormData] = useState({
customer_name: "",
@@ -154,55 +154,57 @@ const Checkout = ({ cartItems, onBackToCart, onPlaceOrder }) => {
delivery_time: defaultTimeSlot.hour,
delivery_at: defaultTimeSlot.date,
region: formData.region || "",
notes: formData.notes || ""
notes: formData.notes || "",
// Add shipping price and product IDs
shipping_price: shippingPrice,
product_ids: productIds // Array of product IDs [1, 3, 4, etc.]
};
};
// Make handlePlaceOrder available to the parent through a ref or expose it
// Create the place order function
const handlePlaceOrder = async () => {
const orderDetails = getOrderData();
if (!orderDetails) return false;
try {
const response = await placeOrder(orderDetails).unwrap();
console.log("Order placed successfully:", response);
window.location.href = "/orders";
return true;
} catch (error) {
console.error("Failed to place order:", error);
if (
error.data &&
typeof error.data === "string" &&
error.data.includes("<!doctype html>")
) {
console.error(
"Server returned HTML instead of a proper API response"
);
alert(
"There was a problem with the server. Please try again later or contact support."
);
} else {
alert(
"Failed to place order. Please check your information and try again."
);
}
return false;
}
};
// Expose the function to parent component via callback
useEffect(() => {
if (onPlaceOrder) {
onPlaceOrder.current = async () => {
const orderDetails = getOrderData();
if (!orderDetails) return false;
try {
const response = await placeOrder(orderDetails);
if (response.data && !response.error) {
console.log("Order placed successfully:", response.data);
window.location.href = "/orders";
return true;
} else {
throw new Error(response.error || "Unknown error occurred");
}
} catch (error) {
console.error("Failed to place order:", error);
if (
error.data &&
typeof error.data === "string" &&
error.data.includes("<!doctype html>")
) {
console.error(
"Server returned HTML instead of a proper API response"
);
alert(
"There was a problem with the server. Please try again later or contact support."
);
} else {
alert(
"Failed to place order. Please check your information and try again."
);
}
return false;
}
};
onPlaceOrder(handlePlaceOrder);
}
}, [formData, placeOrder, onPlaceOrder]);
}, [formData, shippingPrice, productIds]);
return (
<div className={styles.checkoutContainer}>
<h2>{t("cart.basket")} (2)</h2>
<h2>{t("cart.basket")} ({cartItems?.length || 0})</h2>
<div className={styles.formSection}>
<div className={styles.paymentOptions}>
<h3>{t("checkout.paymentMethod")}:</h3>

View File

@@ -2,31 +2,63 @@ import React from "react";
import { Home, ShoppingBag, ShoppingCart, Heart, User } from "lucide-react";
import { Link, useLocation } from "react-router-dom";
import styles from "./FooterBar.module.scss";
import { useGetCartQuery } from "../../app/api/cartApi"; // Sepet API
import { useGetFavoritesQuery } from "../../app/api/favoritesApi"; // Favori API
import { useGetCartQuery } from "../../app/api/cartApi";
import { useGetFavoritesQuery } from "../../app/api/favoritesApi";
import { useTranslation } from "react-i18next";
const FooterBar = () => {
const location = useLocation();
const { t } = useTranslation();
const { data: cartData } = useGetCartQuery();
const { data: favoriteData } = useGetFavoritesQuery();
const { data: cartData } = useGetCartQuery();
const { data: favoriteData } = useGetFavoritesQuery();
const cartCount =
cartData?.data?.reduce((total, item) => {
return total + (parseInt(item.product_quantity, 10) || 0);
}, 0) || 0;
// FIX: Object içindeki tüm channel'ların item'larını birleştir
const getCartCount = () => {
if (!cartData?.data || typeof cartData.data !== 'object') {
return 0;
}
// Object.values ile tüm channel array'lerini al
const allCartItems = Object.values(cartData.data).flat();
return allCartItems.reduce((total, item) => {
return total + (parseInt(item.product_quantity, 10) || 0);
}, 0);
};
const cartCount = getCartCount();
const favoriteCount = favoriteData?.length || 0;
const navItems = [
{ id: 1, icon: <Home />, label: t("navbar.home"), count: 0, path: "/" },
{ id: 2, icon: <ShoppingBag />, label: t("navbar.brands"), count: 0, path: "/brands" },
{ id: 3, icon: <ShoppingCart />, label: t("navbar.cart"), count: cartCount, path: "/cart" },
{ id: 4, icon: <Heart />, label: t("wishtList.likedProducts"), count: favoriteCount, path: "/wishlist" },
{ id: 5, icon: <User />, label: t("profile.profile"), count: 0, path: "/profile" },
{
id: 2,
icon: <ShoppingBag />,
label: t("navbar.brands"),
count: 0,
path: "/brands",
},
{
id: 3,
icon: <ShoppingCart />,
label: t("navbar.cart"),
count: cartCount,
path: "/cart",
},
{
id: 4,
icon: <Heart />,
label: t("wishtList.likedProducts"),
count: favoriteCount,
path: "/wishlist",
},
{
id: 5,
icon: <User />,
label: t("profile.profile"),
count: 0,
path: "/profile",
},
];
return (
@@ -37,11 +69,15 @@ const FooterBar = () => {
<Link
key={item.id}
to={item.path}
className={`${styles.navItem} ${location.pathname === item.path ? styles.active : ""}`}
className={`${styles.navItem} ${
location.pathname === item.path ? styles.active : ""
}`}
>
<div className={styles.iconWrapper}>
<div className={styles.icon}>{item.icon}</div>
{item.count > 0 && <div className={styles.badge}>{item.count}</div>}
{item.count > 0 && (
<div className={styles.badge}>{item.count}</div>
)}
</div>
<span className={styles.label}>{item.label}</span>
</Link>
@@ -52,4 +88,4 @@ const FooterBar = () => {
);
};
export default FooterBar;
export default FooterBar;

View File

@@ -22,6 +22,7 @@ import { useGetOrdersQuery } from "../../app/api/orderApi";
import { useGetFavoritesQuery } from "../../app/api/favoritesApi";
import { useAuth } from "../../context/authContext";
import ProfileModal from "../../components/MyProfileModal/index";
const NavbarDown = () => {
const [isSearchVisible, setSearchVisible] = useState(false);
const { t, i18n } = useTranslation();
@@ -34,10 +35,22 @@ const NavbarDown = () => {
refetchOnMountOrArgChange: false,
});
const { isAuthenticated, logout } = useAuth();
const cartItemCount =
cartData?.data?.reduce((total, item) => {
// FIX: Object içindeki tüm channel'ların item'larını birleştir
const getCartItemCount = () => {
if (!cartData?.data || typeof cartData.data !== 'object') {
return 0;
}
// Object.values ile tüm channel array'lerini al ve flat ile birleştir
const allCartItems = Object.values(cartData.data).flat();
return allCartItems.reduce((total, item) => {
return total + (parseInt(item.product_quantity, 10) || 0);
}, 0) || 0;
}, 0);
};
const cartItemCount = getCartItemCount();
const { data: ordersData } = useGetOrdersQuery();
const ordersItemCount = ordersData?.length || 0;
@@ -45,6 +58,7 @@ const NavbarDown = () => {
const { data: favoritesData } = useGetFavoritesQuery();
const favoritesItemCount = favoritesData?.length || 0;
const [profileModalVisible, setProfileModalVisible] = useState(false);
const handleSearch = () => {
if (searchQuery.trim()) {
refetch();
@@ -60,7 +74,7 @@ const NavbarDown = () => {
const toggleSearch = () => {
setSearchVisible(!isSearchVisible);
};
const changeLanguage = (langCode) => {
i18n.changeLanguage(langCode);
localStorage.setItem("preferredLanguage", langCode);
@@ -69,11 +83,10 @@ const NavbarDown = () => {
const handleLogout = async () => {
await logout();
};
useEffect(() => {}, [isAuthenticated]);
const items = [
{
key: "tk",
@@ -115,6 +128,7 @@ const NavbarDown = () => {
),
},
];
const profileItems = [
{
key: "profile",
@@ -125,15 +139,6 @@ const NavbarDown = () => {
</div>
),
},
// {
// key: "address",
// label: (
// <Link to="/addresses">
// <HomeOutlined style={{ marginRight: "10px" }} />
// {t("profile.my_address")}
// </Link>
// ),
// },
{
key: "logout",
label: (
@@ -155,7 +160,6 @@ const NavbarDown = () => {
</li>
<div className={styles.stick}></div>
<li>
{" "}
<Link to={"/brands"}>
<button className={styles.navButton}>
<BrandIcon />
@@ -199,9 +203,6 @@ const NavbarDown = () => {
<LoginModal />
</li>
<div className={styles.stick}></div>
{/* <li>
<SignUpModal />
</li> */}
</>
) : (
<>

View File

@@ -24,8 +24,8 @@ const ImageCarousel = ({
const currentImage =
hasMultipleImages && images[currentIndex]
? images[currentIndex].images_400x400
: images[0]?.images_400x400 || "";
? images[currentIndex].images_1200x1200
: images[0]?.images_1200x1200 || "";
// Auto-slide functionality
useEffect(() => {
@@ -215,7 +215,7 @@ const ImageCarousel = ({
<div className={isDetailView ? styles.fixedFrameContainer : undefined}>
<img
src={currentImage || "/placeholder.svg"}
alt={altText || "Ürün resmi"}
alt={altText || "Product image"}
className={`${styles.productImage} ${
isDetailView ? styles.detailImage : styles.cardImage
}`}
@@ -255,7 +255,7 @@ const ImageCarousel = ({
<div className={styles.modalImageContainer} ref={modalImageRef}>
<img
src={currentImage || "/placeholder.svg"}
alt={altText || "Ürün resmi"}
alt={altText || "Product image"}
className={styles.modalImage}
style={{
transform: `scale(${scale}) rotate(${rotation}deg) translate(${position.x}px, ${position.y}px)`,
@@ -447,7 +447,7 @@ const ImageCarousel = ({
>
<img
src={currentImage || "/placeholder.svg"}
alt={altText || "Ürün resmi"}
alt={altText || "Product image"}
className={`${styles.productImage} ${
isDetailView ? styles.detailImage : styles.cardImage
}`}
@@ -457,7 +457,7 @@ const ImageCarousel = ({
<button
onClick={handlePrev}
className={`${styles.arrowButton} ${styles.leftArrow}`}
aria-label="Önceki resim"
aria-label="Previous image"
>
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -477,7 +477,7 @@ const ImageCarousel = ({
<button
onClick={handleNext}
className={`${styles.arrowButton} ${styles.rightArrow}`}
aria-label="Sonraki resim"
aria-label="Next image"
>
<svg
xmlns="http://www.w3.org/2000/svg"

View File

@@ -22,19 +22,13 @@ import ImageCarousel from "./imageCarousel/index";
// Helper function to strip HTML tags and truncate text
const truncateDescription = (htmlString, maxLength = 80) => {
// Create a temporary div to parse HTML
const tempDiv = document.createElement("div");
tempDiv.innerHTML = htmlString;
// Get text content without HTML tags
const textContent = tempDiv.textContent || tempDiv.innerText || "";
// Truncate the text
const truncatedText =
textContent.length > maxLength
? textContent.substring(0, maxLength).trim() + "..."
: textContent;
return truncatedText;
};
@@ -45,51 +39,70 @@ const ProductCard = ({
onAddToCart,
onToggleFavorite,
isFavorite = false,
descriptionMaxLength = 85, // New prop to control description length
descriptionMaxLength = 85,
}) => {
const { t } = useTranslation();
const navigate = useNavigate();
const [stockErrorModalVisible, setStockErrorModalVisible] = useState(false);
const [addFavorite] = useAddFavoriteMutation();
const [removeFavorite] = useRemoveFavoriteMutation();
const { data: favoriteProducts = [], refetch } = useGetFavoritesQuery();
const { data: favoriteProducts = [] } = useGetFavoritesQuery();
const [isLoading, setIsLoading] = useState(false);
const [localIsFavorite, setLocalIsFavorite] = useState(
favoriteProducts.some((fav) => fav.product?.id === product.id)
);
// Process description
const truncatedDesc = truncateDescription(
product.description,
descriptionMaxLength
);
// ✅ Sadece cache'den oku, yeni request gönderme
const { data: cartData } = useGetCartQuery(undefined, {
selectFromResult: (result) => ({
data: result.data,
}),
refetchOnMountOrArgChange: false, // ✅ Mount'ta yeniden çağırma
refetchOnFocus: false,
refetchOnReconnect: false,
});
const [addToCart] = useAddToCartMutation();
const [updateCartItem] = useUpdateCartItemMutation();
const [removeFromCart] = useRemoveFromCartMutation();
const cartItem = cartData?.data?.find(
(item) => item.product?.id === product.id || item.product_id === product.id
);
const quantity = cartItem?.quantity || cartItem?.product_quantity || 0;
const [localQuantity, setLocalQuantity] = useState(0);
const [pendingQuantity, setPendingQuantity] = useState(localQuantity);
// ✅ Cart data'yı düzgün parse et
const getCartItem = () => {
if (!cartData || typeof cartData !== "object") {
return null;
}
// Eğer data grouped object ise (store bazlı)
const allCartItems = Object.values(cartData).flat();
return allCartItems.find(
(item) =>
item.product?.id === product.id || item.product_id === product.id
);
};
const cartItem = getCartItem();
const [localQuantity, setLocalQuantity] = useState(0);
const [pendingQuantity, setPendingQuantity] = useState(0);
// ✅ Cart item değiştiğinde local state'i güncelle
useEffect(() => {
if (cartItem) {
setLocalQuantity(cartItem.quantity || cartItem.product_quantity || 0);
setPendingQuantity(cartItem.quantity || cartItem.product_quantity || 0);
const qty = cartItem.quantity || cartItem.product_quantity || 0;
setLocalQuantity(qty);
setPendingQuantity(qty);
} else {
setLocalQuantity(0);
setPendingQuantity(0);
}
}, [cartData, cartItem]);
}, [cartItem]); // ✅ Sadece cartItem değişince, cartData değil
// ✅ Favorite state'i güncelle
useEffect(() => {
if (Array.isArray(favoriteProducts)) {
const isFav = favoriteProducts.some(
@@ -102,34 +115,46 @@ const ProductCard = ({
const handleAddToCart = async (event) => {
event.preventDefault();
event.stopPropagation();
if (product.stock <= 0) {
setStockErrorModalVisible(true);
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
setLocalQuantity((prev) => prev - 1);
setPendingQuantity((prev) => prev - 1);
}
};
// ✅ Debounced update - sadece mutation, refetch yok
useEffect(() => {
const updateCart = async () => {
if (pendingQuantity !== quantity && pendingQuantity > 0) {
const currentCartQty =
cartItem?.quantity || cartItem?.product_quantity || 0;
if (pendingQuantity !== currentCartQty && pendingQuantity > 0) {
try {
setIsLoading(true);
await updateCartItem({
productId: product.id,
quantity: pendingQuantity,
}).unwrap();
// ✅ RTK Query invalidatesTags ile otomatik güncellenecek
} catch (error) {
console.error("Failed to update cart item:", error);
setLocalQuantity(quantity);
setPendingQuantity(quantity);
// ✅ Hata varsa önceki değere dön
setLocalQuantity(currentCartQty);
setPendingQuantity(currentCartQty);
} finally {
setIsLoading(false);
}
@@ -138,12 +163,14 @@ const ProductCard = ({
const debouncedUpdate = debounce(updateCart, 300);
if (pendingQuantity !== quantity) {
const currentCartQty =
cartItem?.quantity || cartItem?.product_quantity || 0;
if (pendingQuantity !== currentCartQty) {
debouncedUpdate();
}
return () => debouncedUpdate.cancel();
}, [pendingQuantity, quantity, product.id, updateCartItem]);
}, [pendingQuantity, cartItem, product.id, updateCartItem]);
const handleQuantityIncrease = (event) => {
event.preventDefault();
@@ -167,12 +194,18 @@ 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);
})
@@ -188,24 +221,26 @@ const ProductCard = ({
const handleToggleFavorite = async (event) => {
event.preventDefault();
event.stopPropagation();
if (isLoading) return;
setIsLoading(true);
// ✅ Optimistic update
setLocalIsFavorite(!localIsFavorite);
try {
if (localIsFavorite) {
const result = await removeFavorite(product.id).unwrap();
if (result === "Removed" || result?.status === "success") {
setLocalIsFavorite(false);
}
// ✅ Başarılı - RTK Query otomatik güncelleyecek
} else {
const result = await addFavorite(product.id).unwrap();
if (result === "Added" || result?.status === "success") {
setLocalIsFavorite(true);
}
// ✅ Başarılı - RTK Query otomatik güncelleyecek
}
await refetch();
} catch (error) {
console.error("Failed to toggle favorite:", error);
// ✅ Hata varsa geri al
setLocalIsFavorite(localIsFavorite);
} finally {
setIsLoading(false);
}
@@ -234,8 +269,6 @@ const ProductCard = ({
</div>
<div className={styles.productInfo}>
<h3 className={styles.productName}>{name}</h3>
{/* Simple truncated description */}
<p className={styles.productDescription}>{truncatedDesc}</p>
<div className={styles.priceContainer}>
@@ -252,6 +285,7 @@ const ProductCard = ({
<button
className={styles.favoriteButton}
onClick={handleToggleFavorite}
disabled={isLoading}
>
{localIsFavorite ? <IoMdHeart /> : <IoMdHeartEmpty />}
</button>
@@ -263,6 +297,7 @@ const ProductCard = ({
<button
onClick={handleQuantityDecrease}
className={styles.quantityBtn}
disabled={isLoading}
>
<DecreaseIcon />
</button>
@@ -270,6 +305,7 @@ const ProductCard = ({
<button
onClick={handleQuantityIncrease}
className={styles.quantityBtn}
disabled={isLoading}
>
<IncreaseIcon />
</button>
@@ -278,6 +314,7 @@ const ProductCard = ({
<button
className={styles.addToCartButton}
onClick={handleAddToCart}
disabled={isLoading || product.stock === 0}
>
<FaShoppingCart />
</button>
@@ -287,7 +324,6 @@ const ProductCard = ({
</div>
</div>
{/* Stock Error Modal */}
<Modal
title={t("common.warning")}
open={stockErrorModalVisible}