changed order
This commit is contained in:
@@ -5,45 +5,23 @@ export const cartApi = baseApi.injectEndpoints({
|
|||||||
getCart: builder.query({
|
getCart: builder.query({
|
||||||
query: () => `/carts`,
|
query: () => `/carts`,
|
||||||
providesTags: ["cartItems"],
|
providesTags: ["cartItems"],
|
||||||
pollingInterval: 5000,
|
pollingInterval: 0,
|
||||||
refetchOnMountOrArgChange: true,
|
refetchOnMountOrArgChange: 30,
|
||||||
refetchOnFocus: false,
|
refetchOnFocus: false,
|
||||||
refetchOnReconnect: true,
|
refetchOnReconnect: false,
|
||||||
transformResponse: (response) => {
|
transformResponse: (response) => {
|
||||||
if (
|
if (typeof response === "string" &&
|
||||||
typeof response === "string" &&
|
(response.trim().startsWith("<!DOCTYPE") ||
|
||||||
(response.trim().startsWith("<!DOCTYPE") ||
|
response.trim().startsWith("<html"))) {
|
||||||
response.trim().startsWith("<html"))
|
return { message: "error", data: {} };
|
||||||
) {
|
|
||||||
console.error(
|
|
||||||
"Received HTML response instead of JSON:",
|
|
||||||
response.substring(0, 100)
|
|
||||||
);
|
|
||||||
return {
|
|
||||||
message: "error",
|
|
||||||
data: [],
|
|
||||||
errorDetails:
|
|
||||||
"Server returned HTML instead of JSON. The server might be down or experiencing issues.",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (typeof response === "object") {
|
|
||||||
if (response.data) {
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
return { message: "success", data: [] };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof response === "string") {
|
if (typeof response === "object" && response.data) {
|
||||||
try {
|
// DON'T CONVERT - Keep the grouped object structure
|
||||||
const parsed = JSON.parse(response);
|
return response;
|
||||||
return parsed;
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to parse response:", error);
|
|
||||||
return { message: "error", data: [] };
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return { message: "unknown", data: [] };
|
return { message: "success", data: {} };
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
|
||||||
|
|||||||
@@ -12,17 +12,31 @@ export const orderApi = baseApi.injectEndpoints({
|
|||||||
transformResponse: (response) => response.data || null,
|
transformResponse: (response) => response.data || null,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
placeOrder: builder.mutation({
|
placeOrder: builder.mutation({
|
||||||
query: (orderDetails) => {
|
query: (orderDetails) => {
|
||||||
orderDetails.shipping_method = 'standart';
|
orderDetails.shipping_method = 'standart';
|
||||||
orderDetails.delivery_time = '13:00 - 18:00';
|
orderDetails.delivery_time = '13:00 - 18:00';
|
||||||
orderDetails.region = 'ag';
|
orderDetails.region = 'ag';
|
||||||
orderDetails.payment_type_id = 3;
|
// orderDetails.payment_type_id = 3;
|
||||||
|
|
||||||
|
const formData = new URLSearchParams();
|
||||||
|
|
||||||
|
Object.keys(orderDetails).forEach(key => {
|
||||||
|
if (key === 'product_ids' && Array.isArray(orderDetails[key])) {
|
||||||
|
|
||||||
|
orderDetails[key].forEach(id => {
|
||||||
|
formData.append('product_ids[]', id);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
formData.append(key, orderDetails[key]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
url: "/orders",
|
url: "/orders",
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: new URLSearchParams(orderDetails),
|
body: formData,
|
||||||
headers: {
|
headers: {
|
||||||
"Accept": "application/json",
|
"Accept": "application/json",
|
||||||
"Content-Type": "application/x-www-form-urlencoded",
|
"Content-Type": "application/x-www-form-urlencoded",
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ const useDeviceType = () => {
|
|||||||
return deviceType;
|
return deviceType;
|
||||||
};
|
};
|
||||||
|
|
||||||
const Checkout = ({ cartItems, onBackToCart, onPlaceOrder }) => {
|
const Checkout = ({ cartItems, shippingPrice, productIds, onBackToCart, onPlaceOrder }) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
customer_name: "",
|
customer_name: "",
|
||||||
@@ -154,55 +154,57 @@ const Checkout = ({ cartItems, onBackToCart, onPlaceOrder }) => {
|
|||||||
delivery_time: defaultTimeSlot.hour,
|
delivery_time: defaultTimeSlot.hour,
|
||||||
delivery_at: defaultTimeSlot.date,
|
delivery_at: defaultTimeSlot.date,
|
||||||
region: formData.region || "",
|
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(() => {
|
useEffect(() => {
|
||||||
if (onPlaceOrder) {
|
if (onPlaceOrder) {
|
||||||
onPlaceOrder.current = async () => {
|
onPlaceOrder(handlePlaceOrder);
|
||||||
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;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}, [formData, placeOrder, onPlaceOrder]);
|
}, [formData, shippingPrice, productIds]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.checkoutContainer}>
|
<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.formSection}>
|
||||||
<div className={styles.paymentOptions}>
|
<div className={styles.paymentOptions}>
|
||||||
<h3>{t("checkout.paymentMethod")}:</h3>
|
<h3>{t("checkout.paymentMethod")}:</h3>
|
||||||
|
|||||||
@@ -2,31 +2,63 @@ import React from "react";
|
|||||||
import { Home, ShoppingBag, ShoppingCart, Heart, User } from "lucide-react";
|
import { Home, ShoppingBag, ShoppingCart, Heart, User } from "lucide-react";
|
||||||
import { Link, useLocation } from "react-router-dom";
|
import { Link, useLocation } from "react-router-dom";
|
||||||
import styles from "./FooterBar.module.scss";
|
import styles from "./FooterBar.module.scss";
|
||||||
import { useGetCartQuery } from "../../app/api/cartApi"; // Sepet API
|
import { useGetCartQuery } from "../../app/api/cartApi";
|
||||||
import { useGetFavoritesQuery } from "../../app/api/favoritesApi"; // Favori API
|
import { useGetFavoritesQuery } from "../../app/api/favoritesApi";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
const FooterBar = () => {
|
const FooterBar = () => {
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
|
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { data: cartData } = useGetCartQuery();
|
const { data: cartData } = useGetCartQuery();
|
||||||
const { data: favoriteData } = useGetFavoritesQuery();
|
const { data: favoriteData } = useGetFavoritesQuery();
|
||||||
|
|
||||||
|
// 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();
|
||||||
|
|
||||||
const cartCount =
|
return allCartItems.reduce((total, item) => {
|
||||||
cartData?.data?.reduce((total, item) => {
|
return total + (parseInt(item.product_quantity, 10) || 0);
|
||||||
return total + (parseInt(item.product_quantity, 10) || 0);
|
}, 0);
|
||||||
}, 0) || 0;
|
};
|
||||||
|
|
||||||
|
const cartCount = getCartCount();
|
||||||
const favoriteCount = favoriteData?.length || 0;
|
const favoriteCount = favoriteData?.length || 0;
|
||||||
|
|
||||||
const navItems = [
|
const navItems = [
|
||||||
{ id: 1, icon: <Home />, label: t("navbar.home"), count: 0, path: "/" },
|
{ 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: 2,
|
||||||
{ id: 4, icon: <Heart />, label: t("wishtList.likedProducts"), count: favoriteCount, path: "/wishlist" },
|
icon: <ShoppingBag />,
|
||||||
{ id: 5, icon: <User />, label: t("profile.profile"), count: 0, path: "/profile" },
|
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 (
|
return (
|
||||||
@@ -37,11 +69,15 @@ const FooterBar = () => {
|
|||||||
<Link
|
<Link
|
||||||
key={item.id}
|
key={item.id}
|
||||||
to={item.path}
|
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.iconWrapper}>
|
||||||
<div className={styles.icon}>{item.icon}</div>
|
<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>
|
</div>
|
||||||
<span className={styles.label}>{item.label}</span>
|
<span className={styles.label}>{item.label}</span>
|
||||||
</Link>
|
</Link>
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import { useGetOrdersQuery } from "../../app/api/orderApi";
|
|||||||
import { useGetFavoritesQuery } from "../../app/api/favoritesApi";
|
import { useGetFavoritesQuery } from "../../app/api/favoritesApi";
|
||||||
import { useAuth } from "../../context/authContext";
|
import { useAuth } from "../../context/authContext";
|
||||||
import ProfileModal from "../../components/MyProfileModal/index";
|
import ProfileModal from "../../components/MyProfileModal/index";
|
||||||
|
|
||||||
const NavbarDown = () => {
|
const NavbarDown = () => {
|
||||||
const [isSearchVisible, setSearchVisible] = useState(false);
|
const [isSearchVisible, setSearchVisible] = useState(false);
|
||||||
const { t, i18n } = useTranslation();
|
const { t, i18n } = useTranslation();
|
||||||
@@ -34,10 +35,22 @@ const NavbarDown = () => {
|
|||||||
refetchOnMountOrArgChange: false,
|
refetchOnMountOrArgChange: false,
|
||||||
});
|
});
|
||||||
const { isAuthenticated, logout } = useAuth();
|
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);
|
return total + (parseInt(item.product_quantity, 10) || 0);
|
||||||
}, 0) || 0;
|
}, 0);
|
||||||
|
};
|
||||||
|
|
||||||
|
const cartItemCount = getCartItemCount();
|
||||||
|
|
||||||
const { data: ordersData } = useGetOrdersQuery();
|
const { data: ordersData } = useGetOrdersQuery();
|
||||||
const ordersItemCount = ordersData?.length || 0;
|
const ordersItemCount = ordersData?.length || 0;
|
||||||
@@ -45,6 +58,7 @@ const NavbarDown = () => {
|
|||||||
const { data: favoritesData } = useGetFavoritesQuery();
|
const { data: favoritesData } = useGetFavoritesQuery();
|
||||||
const favoritesItemCount = favoritesData?.length || 0;
|
const favoritesItemCount = favoritesData?.length || 0;
|
||||||
const [profileModalVisible, setProfileModalVisible] = useState(false);
|
const [profileModalVisible, setProfileModalVisible] = useState(false);
|
||||||
|
|
||||||
const handleSearch = () => {
|
const handleSearch = () => {
|
||||||
if (searchQuery.trim()) {
|
if (searchQuery.trim()) {
|
||||||
refetch();
|
refetch();
|
||||||
@@ -69,7 +83,6 @@ const NavbarDown = () => {
|
|||||||
|
|
||||||
const handleLogout = async () => {
|
const handleLogout = async () => {
|
||||||
await logout();
|
await logout();
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {}, [isAuthenticated]);
|
useEffect(() => {}, [isAuthenticated]);
|
||||||
@@ -115,6 +128,7 @@ const NavbarDown = () => {
|
|||||||
),
|
),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const profileItems = [
|
const profileItems = [
|
||||||
{
|
{
|
||||||
key: "profile",
|
key: "profile",
|
||||||
@@ -125,15 +139,6 @@ const NavbarDown = () => {
|
|||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
// {
|
|
||||||
// key: "address",
|
|
||||||
// label: (
|
|
||||||
// <Link to="/addresses">
|
|
||||||
// <HomeOutlined style={{ marginRight: "10px" }} />
|
|
||||||
// {t("profile.my_address")}
|
|
||||||
// </Link>
|
|
||||||
// ),
|
|
||||||
// },
|
|
||||||
{
|
{
|
||||||
key: "logout",
|
key: "logout",
|
||||||
label: (
|
label: (
|
||||||
@@ -155,7 +160,6 @@ const NavbarDown = () => {
|
|||||||
</li>
|
</li>
|
||||||
<div className={styles.stick}></div>
|
<div className={styles.stick}></div>
|
||||||
<li>
|
<li>
|
||||||
{" "}
|
|
||||||
<Link to={"/brands"}>
|
<Link to={"/brands"}>
|
||||||
<button className={styles.navButton}>
|
<button className={styles.navButton}>
|
||||||
<BrandIcon />
|
<BrandIcon />
|
||||||
@@ -199,9 +203,6 @@ const NavbarDown = () => {
|
|||||||
<LoginModal />
|
<LoginModal />
|
||||||
</li>
|
</li>
|
||||||
<div className={styles.stick}></div>
|
<div className={styles.stick}></div>
|
||||||
{/* <li>
|
|
||||||
<SignUpModal />
|
|
||||||
</li> */}
|
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -24,8 +24,8 @@ const ImageCarousel = ({
|
|||||||
|
|
||||||
const currentImage =
|
const currentImage =
|
||||||
hasMultipleImages && images[currentIndex]
|
hasMultipleImages && images[currentIndex]
|
||||||
? images[currentIndex].images_400x400
|
? images[currentIndex].images_1200x1200
|
||||||
: images[0]?.images_400x400 || "";
|
: images[0]?.images_1200x1200 || "";
|
||||||
|
|
||||||
// Auto-slide functionality
|
// Auto-slide functionality
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -215,7 +215,7 @@ const ImageCarousel = ({
|
|||||||
<div className={isDetailView ? styles.fixedFrameContainer : undefined}>
|
<div className={isDetailView ? styles.fixedFrameContainer : undefined}>
|
||||||
<img
|
<img
|
||||||
src={currentImage || "/placeholder.svg"}
|
src={currentImage || "/placeholder.svg"}
|
||||||
alt={altText || "Ürün resmi"}
|
alt={altText || "Product image"}
|
||||||
className={`${styles.productImage} ${
|
className={`${styles.productImage} ${
|
||||||
isDetailView ? styles.detailImage : styles.cardImage
|
isDetailView ? styles.detailImage : styles.cardImage
|
||||||
}`}
|
}`}
|
||||||
@@ -255,7 +255,7 @@ const ImageCarousel = ({
|
|||||||
<div className={styles.modalImageContainer} ref={modalImageRef}>
|
<div className={styles.modalImageContainer} ref={modalImageRef}>
|
||||||
<img
|
<img
|
||||||
src={currentImage || "/placeholder.svg"}
|
src={currentImage || "/placeholder.svg"}
|
||||||
alt={altText || "Ürün resmi"}
|
alt={altText || "Product image"}
|
||||||
className={styles.modalImage}
|
className={styles.modalImage}
|
||||||
style={{
|
style={{
|
||||||
transform: `scale(${scale}) rotate(${rotation}deg) translate(${position.x}px, ${position.y}px)`,
|
transform: `scale(${scale}) rotate(${rotation}deg) translate(${position.x}px, ${position.y}px)`,
|
||||||
@@ -447,7 +447,7 @@ const ImageCarousel = ({
|
|||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
src={currentImage || "/placeholder.svg"}
|
src={currentImage || "/placeholder.svg"}
|
||||||
alt={altText || "Ürün resmi"}
|
alt={altText || "Product image"}
|
||||||
className={`${styles.productImage} ${
|
className={`${styles.productImage} ${
|
||||||
isDetailView ? styles.detailImage : styles.cardImage
|
isDetailView ? styles.detailImage : styles.cardImage
|
||||||
}`}
|
}`}
|
||||||
@@ -457,7 +457,7 @@ const ImageCarousel = ({
|
|||||||
<button
|
<button
|
||||||
onClick={handlePrev}
|
onClick={handlePrev}
|
||||||
className={`${styles.arrowButton} ${styles.leftArrow}`}
|
className={`${styles.arrowButton} ${styles.leftArrow}`}
|
||||||
aria-label="Önceki resim"
|
aria-label="Previous image"
|
||||||
>
|
>
|
||||||
<svg
|
<svg
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
@@ -477,7 +477,7 @@ const ImageCarousel = ({
|
|||||||
<button
|
<button
|
||||||
onClick={handleNext}
|
onClick={handleNext}
|
||||||
className={`${styles.arrowButton} ${styles.rightArrow}`}
|
className={`${styles.arrowButton} ${styles.rightArrow}`}
|
||||||
aria-label="Sonraki resim"
|
aria-label="Next image"
|
||||||
>
|
>
|
||||||
<svg
|
<svg
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
|||||||
@@ -22,19 +22,13 @@ import ImageCarousel from "./imageCarousel/index";
|
|||||||
|
|
||||||
// Helper function to strip HTML tags and truncate text
|
// Helper function to strip HTML tags and truncate text
|
||||||
const truncateDescription = (htmlString, maxLength = 80) => {
|
const truncateDescription = (htmlString, maxLength = 80) => {
|
||||||
// Create a temporary div to parse HTML
|
|
||||||
const tempDiv = document.createElement("div");
|
const tempDiv = document.createElement("div");
|
||||||
tempDiv.innerHTML = htmlString;
|
tempDiv.innerHTML = htmlString;
|
||||||
|
|
||||||
// Get text content without HTML tags
|
|
||||||
const textContent = tempDiv.textContent || tempDiv.innerText || "";
|
const textContent = tempDiv.textContent || tempDiv.innerText || "";
|
||||||
|
|
||||||
// Truncate the text
|
|
||||||
const truncatedText =
|
const truncatedText =
|
||||||
textContent.length > maxLength
|
textContent.length > maxLength
|
||||||
? textContent.substring(0, maxLength).trim() + "..."
|
? textContent.substring(0, maxLength).trim() + "..."
|
||||||
: textContent;
|
: textContent;
|
||||||
|
|
||||||
return truncatedText;
|
return truncatedText;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -45,51 +39,70 @@ const ProductCard = ({
|
|||||||
onAddToCart,
|
onAddToCart,
|
||||||
onToggleFavorite,
|
onToggleFavorite,
|
||||||
isFavorite = false,
|
isFavorite = false,
|
||||||
descriptionMaxLength = 85, // New prop to control description length
|
descriptionMaxLength = 85,
|
||||||
}) => {
|
}) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [stockErrorModalVisible, setStockErrorModalVisible] = useState(false);
|
const [stockErrorModalVisible, setStockErrorModalVisible] = useState(false);
|
||||||
const [addFavorite] = useAddFavoriteMutation();
|
const [addFavorite] = useAddFavoriteMutation();
|
||||||
const [removeFavorite] = useRemoveFavoriteMutation();
|
const [removeFavorite] = useRemoveFavoriteMutation();
|
||||||
const { data: favoriteProducts = [], refetch } = useGetFavoritesQuery();
|
const { data: favoriteProducts = [] } = useGetFavoritesQuery();
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [localIsFavorite, setLocalIsFavorite] = useState(
|
const [localIsFavorite, setLocalIsFavorite] = useState(
|
||||||
favoriteProducts.some((fav) => fav.product?.id === product.id)
|
favoriteProducts.some((fav) => fav.product?.id === product.id)
|
||||||
);
|
);
|
||||||
// Process description
|
|
||||||
const truncatedDesc = truncateDescription(
|
const truncatedDesc = truncateDescription(
|
||||||
product.description,
|
product.description,
|
||||||
descriptionMaxLength
|
descriptionMaxLength
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// ✅ Sadece cache'den oku, yeni request gönderme
|
||||||
const { data: cartData } = useGetCartQuery(undefined, {
|
const { data: cartData } = useGetCartQuery(undefined, {
|
||||||
selectFromResult: (result) => ({
|
selectFromResult: (result) => ({
|
||||||
data: result.data,
|
data: result.data,
|
||||||
}),
|
}),
|
||||||
|
refetchOnMountOrArgChange: false, // ✅ Mount'ta yeniden çağırma
|
||||||
|
refetchOnFocus: false,
|
||||||
|
refetchOnReconnect: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
const [addToCart] = useAddToCartMutation();
|
const [addToCart] = useAddToCartMutation();
|
||||||
const [updateCartItem] = useUpdateCartItemMutation();
|
const [updateCartItem] = useUpdateCartItemMutation();
|
||||||
const [removeFromCart] = useRemoveFromCartMutation();
|
const [removeFromCart] = useRemoveFromCartMutation();
|
||||||
|
|
||||||
const cartItem = cartData?.data?.find(
|
// ✅ Cart data'yı düzgün parse et
|
||||||
(item) => item.product?.id === product.id || item.product_id === product.id
|
const getCartItem = () => {
|
||||||
);
|
if (!cartData || typeof cartData !== "object") {
|
||||||
const quantity = cartItem?.quantity || cartItem?.product_quantity || 0;
|
return null;
|
||||||
const [localQuantity, setLocalQuantity] = useState(0);
|
}
|
||||||
const [pendingQuantity, setPendingQuantity] = useState(localQuantity);
|
|
||||||
|
|
||||||
|
// 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(() => {
|
useEffect(() => {
|
||||||
if (cartItem) {
|
if (cartItem) {
|
||||||
setLocalQuantity(cartItem.quantity || cartItem.product_quantity || 0);
|
const qty = cartItem.quantity || cartItem.product_quantity || 0;
|
||||||
setPendingQuantity(cartItem.quantity || cartItem.product_quantity || 0);
|
setLocalQuantity(qty);
|
||||||
|
setPendingQuantity(qty);
|
||||||
} else {
|
} else {
|
||||||
setLocalQuantity(0);
|
setLocalQuantity(0);
|
||||||
setPendingQuantity(0);
|
setPendingQuantity(0);
|
||||||
}
|
}
|
||||||
}, [cartData, cartItem]);
|
}, [cartItem]); // ✅ Sadece cartItem değişince, cartData değil
|
||||||
|
|
||||||
|
// ✅ Favorite state'i güncelle
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (Array.isArray(favoriteProducts)) {
|
if (Array.isArray(favoriteProducts)) {
|
||||||
const isFav = favoriteProducts.some(
|
const isFav = favoriteProducts.some(
|
||||||
@@ -102,34 +115,46 @@ const ProductCard = ({
|
|||||||
const handleAddToCart = async (event) => {
|
const handleAddToCart = async (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
|
|
||||||
if (product.stock <= 0) {
|
if (product.stock <= 0) {
|
||||||
setStockErrorModalVisible(true);
|
setStockErrorModalVisible(true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ✅ Optimistic update
|
||||||
setLocalQuantity((prev) => prev + 1);
|
setLocalQuantity((prev) => prev + 1);
|
||||||
setPendingQuantity((prev) => prev + 1);
|
setPendingQuantity((prev) => prev + 1);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await addToCart({ productId: product.id, quantity: 1 }).unwrap();
|
await addToCart({ productId: product.id, quantity: 1 }).unwrap();
|
||||||
|
// ✅ Başarılı - RTK Query otomatik cache'i güncelleyecek
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to add to cart:", error);
|
console.error("Failed to add to cart:", error);
|
||||||
|
// ✅ Hata varsa geri al
|
||||||
setLocalQuantity((prev) => prev - 1);
|
setLocalQuantity((prev) => prev - 1);
|
||||||
setPendingQuantity((prev) => prev - 1);
|
setPendingQuantity((prev) => prev - 1);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ✅ Debounced update - sadece mutation, refetch yok
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const updateCart = async () => {
|
const updateCart = async () => {
|
||||||
if (pendingQuantity !== quantity && pendingQuantity > 0) {
|
const currentCartQty =
|
||||||
|
cartItem?.quantity || cartItem?.product_quantity || 0;
|
||||||
|
|
||||||
|
if (pendingQuantity !== currentCartQty && pendingQuantity > 0) {
|
||||||
try {
|
try {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
await updateCartItem({
|
await updateCartItem({
|
||||||
productId: product.id,
|
productId: product.id,
|
||||||
quantity: pendingQuantity,
|
quantity: pendingQuantity,
|
||||||
}).unwrap();
|
}).unwrap();
|
||||||
|
// ✅ RTK Query invalidatesTags ile otomatik güncellenecek
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to update cart item:", error);
|
console.error("Failed to update cart item:", error);
|
||||||
setLocalQuantity(quantity);
|
// ✅ Hata varsa önceki değere dön
|
||||||
setPendingQuantity(quantity);
|
setLocalQuantity(currentCartQty);
|
||||||
|
setPendingQuantity(currentCartQty);
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
@@ -138,12 +163,14 @@ const ProductCard = ({
|
|||||||
|
|
||||||
const debouncedUpdate = debounce(updateCart, 300);
|
const debouncedUpdate = debounce(updateCart, 300);
|
||||||
|
|
||||||
if (pendingQuantity !== quantity) {
|
const currentCartQty =
|
||||||
|
cartItem?.quantity || cartItem?.product_quantity || 0;
|
||||||
|
if (pendingQuantity !== currentCartQty) {
|
||||||
debouncedUpdate();
|
debouncedUpdate();
|
||||||
}
|
}
|
||||||
|
|
||||||
return () => debouncedUpdate.cancel();
|
return () => debouncedUpdate.cancel();
|
||||||
}, [pendingQuantity, quantity, product.id, updateCartItem]);
|
}, [pendingQuantity, cartItem, product.id, updateCartItem]);
|
||||||
|
|
||||||
const handleQuantityIncrease = (event) => {
|
const handleQuantityIncrease = (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -167,12 +194,18 @@ const ProductCard = ({
|
|||||||
if (isLoading) return;
|
if (isLoading) return;
|
||||||
|
|
||||||
if (pendingQuantity <= 1) {
|
if (pendingQuantity <= 1) {
|
||||||
|
// ✅ Sıfıra düşünce direkt sil
|
||||||
setPendingQuantity(0);
|
setPendingQuantity(0);
|
||||||
setLocalQuantity(0);
|
setLocalQuantity(0);
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
|
|
||||||
removeFromCart({ productId: product.id })
|
removeFromCart({ productId: product.id })
|
||||||
.unwrap()
|
.unwrap()
|
||||||
|
.then(() => {
|
||||||
|
// ✅ Başarılı - RTK Query cache'i güncelleyecek
|
||||||
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
|
// ✅ Hata varsa geri al
|
||||||
setLocalQuantity(1);
|
setLocalQuantity(1);
|
||||||
setPendingQuantity(1);
|
setPendingQuantity(1);
|
||||||
})
|
})
|
||||||
@@ -188,24 +221,26 @@ const ProductCard = ({
|
|||||||
const handleToggleFavorite = async (event) => {
|
const handleToggleFavorite = async (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
|
|
||||||
if (isLoading) return;
|
if (isLoading) return;
|
||||||
|
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
|
|
||||||
|
// ✅ Optimistic update
|
||||||
|
setLocalIsFavorite(!localIsFavorite);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (localIsFavorite) {
|
if (localIsFavorite) {
|
||||||
const result = await removeFavorite(product.id).unwrap();
|
const result = await removeFavorite(product.id).unwrap();
|
||||||
if (result === "Removed" || result?.status === "success") {
|
// ✅ Başarılı - RTK Query otomatik güncelleyecek
|
||||||
setLocalIsFavorite(false);
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
const result = await addFavorite(product.id).unwrap();
|
const result = await addFavorite(product.id).unwrap();
|
||||||
if (result === "Added" || result?.status === "success") {
|
// ✅ Başarılı - RTK Query otomatik güncelleyecek
|
||||||
setLocalIsFavorite(true);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
await refetch();
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to toggle favorite:", error);
|
console.error("Failed to toggle favorite:", error);
|
||||||
|
// ✅ Hata varsa geri al
|
||||||
|
setLocalIsFavorite(localIsFavorite);
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
@@ -234,8 +269,6 @@ const ProductCard = ({
|
|||||||
</div>
|
</div>
|
||||||
<div className={styles.productInfo}>
|
<div className={styles.productInfo}>
|
||||||
<h3 className={styles.productName}>{name}</h3>
|
<h3 className={styles.productName}>{name}</h3>
|
||||||
|
|
||||||
{/* Simple truncated description */}
|
|
||||||
<p className={styles.productDescription}>{truncatedDesc}</p>
|
<p className={styles.productDescription}>{truncatedDesc}</p>
|
||||||
|
|
||||||
<div className={styles.priceContainer}>
|
<div className={styles.priceContainer}>
|
||||||
@@ -252,6 +285,7 @@ const ProductCard = ({
|
|||||||
<button
|
<button
|
||||||
className={styles.favoriteButton}
|
className={styles.favoriteButton}
|
||||||
onClick={handleToggleFavorite}
|
onClick={handleToggleFavorite}
|
||||||
|
disabled={isLoading}
|
||||||
>
|
>
|
||||||
{localIsFavorite ? <IoMdHeart /> : <IoMdHeartEmpty />}
|
{localIsFavorite ? <IoMdHeart /> : <IoMdHeartEmpty />}
|
||||||
</button>
|
</button>
|
||||||
@@ -263,6 +297,7 @@ const ProductCard = ({
|
|||||||
<button
|
<button
|
||||||
onClick={handleQuantityDecrease}
|
onClick={handleQuantityDecrease}
|
||||||
className={styles.quantityBtn}
|
className={styles.quantityBtn}
|
||||||
|
disabled={isLoading}
|
||||||
>
|
>
|
||||||
<DecreaseIcon />
|
<DecreaseIcon />
|
||||||
</button>
|
</button>
|
||||||
@@ -270,6 +305,7 @@ const ProductCard = ({
|
|||||||
<button
|
<button
|
||||||
onClick={handleQuantityIncrease}
|
onClick={handleQuantityIncrease}
|
||||||
className={styles.quantityBtn}
|
className={styles.quantityBtn}
|
||||||
|
disabled={isLoading}
|
||||||
>
|
>
|
||||||
<IncreaseIcon />
|
<IncreaseIcon />
|
||||||
</button>
|
</button>
|
||||||
@@ -278,6 +314,7 @@ const ProductCard = ({
|
|||||||
<button
|
<button
|
||||||
className={styles.addToCartButton}
|
className={styles.addToCartButton}
|
||||||
onClick={handleAddToCart}
|
onClick={handleAddToCart}
|
||||||
|
disabled={isLoading || product.stock === 0}
|
||||||
>
|
>
|
||||||
<FaShoppingCart />
|
<FaShoppingCart />
|
||||||
</button>
|
</button>
|
||||||
@@ -287,7 +324,6 @@ const ProductCard = ({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Stock Error Modal */}
|
|
||||||
<Modal
|
<Modal
|
||||||
title={t("common.warning")}
|
title={t("common.warning")}
|
||||||
open={stockErrorModalVisible}
|
open={stockErrorModalVisible}
|
||||||
|
|||||||
@@ -85,6 +85,8 @@ export default {
|
|||||||
Writecomment: "Write a comment",
|
Writecomment: "Write a comment",
|
||||||
comment: "Comment",
|
comment: "Comment",
|
||||||
noComment: "There is no comment yet",
|
noComment: "There is no comment yet",
|
||||||
|
processing: "Processing",
|
||||||
|
verifying: "Verifying",
|
||||||
},
|
},
|
||||||
search: {
|
search: {
|
||||||
resultsFor: "Search results for",
|
resultsFor: "Search results for",
|
||||||
|
|||||||
@@ -86,6 +86,8 @@ export default {
|
|||||||
Writecomment: "Написать комментарий",
|
Writecomment: "Написать комментарий",
|
||||||
comment: "Комментарий",
|
comment: "Комментарий",
|
||||||
noComment: "Пока нет комментариев",
|
noComment: "Пока нет комментариев",
|
||||||
|
processing: "Обработка",
|
||||||
|
verifying: "Проверка",
|
||||||
},
|
},
|
||||||
profile: {
|
profile: {
|
||||||
registration: "Регистрация",
|
registration: "Регистрация",
|
||||||
|
|||||||
@@ -85,6 +85,8 @@ export default {
|
|||||||
Writecomment: "Teswir ýaz",
|
Writecomment: "Teswir ýaz",
|
||||||
comment: "Teswir",
|
comment: "Teswir",
|
||||||
noComment: "Bu haryt barada teswir ýazylmandyr",
|
noComment: "Bu haryt barada teswir ýazylmandyr",
|
||||||
|
processing: "Işlenilýär",
|
||||||
|
verifying: "Barlanýar",
|
||||||
},
|
},
|
||||||
search: {
|
search: {
|
||||||
resultsFor: "Gozleg netijesi",
|
resultsFor: "Gozleg netijesi",
|
||||||
|
|||||||
@@ -31,6 +31,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.cartProducts {
|
.cartProducts {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
@@ -39,12 +40,44 @@
|
|||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.storesContainer {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 20px;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.storeSection {
|
||||||
|
display: flex;
|
||||||
|
border-radius: 10px;
|
||||||
|
gap: 16px;
|
||||||
|
|
||||||
|
@media screen and (max-width: 768px) {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.storeHeader {
|
||||||
|
padding: 12px 16px;
|
||||||
|
border-bottom: 1px solid #f0f1f3;
|
||||||
|
|
||||||
|
h3 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #333;
|
||||||
|
@media screen and (max-width: 768px) {
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.cartItemContainer {
|
.cartItemContainer {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
background-color: #fff;
|
|
||||||
border-radius: 10px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.cartItem {
|
.cartItem {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 1.5rem;
|
gap: 1.5rem;
|
||||||
@@ -52,10 +85,15 @@
|
|||||||
padding-bottom: 20px;
|
padding-bottom: 20px;
|
||||||
border-bottom: 1px solid #f0f1f3;
|
border-bottom: 1px solid #f0f1f3;
|
||||||
|
|
||||||
|
&:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
|
||||||
@media screen and (max-width: 720px) {
|
@media screen and (max-width: 720px) {
|
||||||
gap: 0.5rem;
|
gap: 0.5rem;
|
||||||
margin: 0.5rem;
|
margin: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.itemImage {
|
.itemImage {
|
||||||
width: 144px;
|
width: 144px;
|
||||||
height: 144px;
|
height: 144px;
|
||||||
@@ -168,7 +206,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.cartSummary {
|
.storeSummary {
|
||||||
width: 300px;
|
width: 300px;
|
||||||
position: sticky;
|
position: sticky;
|
||||||
top: 5rem;
|
top: 5rem;
|
||||||
@@ -177,9 +215,10 @@
|
|||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 10px;
|
gap: 10px;
|
||||||
min-width: 300px;
|
min-width: 300px;
|
||||||
margin-top: 44.6px;
|
|
||||||
@media screen and (max-width: 1023px) {
|
@media screen and (max-width: 1023px) {
|
||||||
display: none;
|
width: 100%;
|
||||||
|
position: static;
|
||||||
|
margin-top: 16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
h3 {
|
h3 {
|
||||||
@@ -189,10 +228,7 @@
|
|||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.summaryRow span:nth-of-type(2) {
|
|
||||||
color: #888888;
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
.cartContent {
|
.cartContent {
|
||||||
background: white;
|
background: white;
|
||||||
padding: 8px;
|
padding: 8px;
|
||||||
@@ -202,6 +238,11 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.summaryRow span:nth-of-type(2) {
|
||||||
|
color: #888888;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
.summaryRow {
|
.summaryRow {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
@@ -270,7 +311,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// mobile
|
// mobile sticky
|
||||||
.container {
|
.container {
|
||||||
margin-bottom: 25px;
|
margin-bottom: 25px;
|
||||||
position: sticky;
|
position: sticky;
|
||||||
@@ -292,8 +333,6 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
// user-select: none;
|
|
||||||
// -webkit-tap-highlight-color: transparent;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.titleWrapper {
|
.titleWrapper {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useState, useRef, useEffect } from "react";
|
import React, { useState, useRef, useEffect, useMemo } from "react";
|
||||||
import styles from "./CartPage.module.scss";
|
import styles from "./CartPage.module.scss";
|
||||||
import { FaTrashAlt } from "react-icons/fa";
|
import { FaTrashAlt } from "react-icons/fa";
|
||||||
import Checkout from "../../components/Checkout";
|
import Checkout from "../../components/Checkout";
|
||||||
@@ -17,11 +17,9 @@ import { DecreaseIcon, IncreaseIcon } from "../../components/Icons";
|
|||||||
import { debounce } from "lodash";
|
import { debounce } from "lodash";
|
||||||
import Loader from "../../components/Loader/index";
|
import Loader from "../../components/Loader/index";
|
||||||
|
|
||||||
// New component for truncated text
|
|
||||||
const TruncatedDescription = ({ description, maxLength = 100 }) => {
|
const TruncatedDescription = ({ description, maxLength = 100 }) => {
|
||||||
const [isExpanded, setIsExpanded] = useState(false);
|
const [isExpanded, setIsExpanded] = useState(false);
|
||||||
|
|
||||||
// Strip HTML tags for character count
|
|
||||||
const stripHtml = (html) => {
|
const stripHtml = (html) => {
|
||||||
const doc = new DOMParser().parseFromString(html, "text/html");
|
const doc = new DOMParser().parseFromString(html, "text/html");
|
||||||
return doc.body.textContent || "";
|
return doc.body.textContent || "";
|
||||||
@@ -48,14 +46,25 @@ const TruncatedDescription = ({ description, maxLength = 100 }) => {
|
|||||||
const CartPage = () => {
|
const CartPage = () => {
|
||||||
const {
|
const {
|
||||||
data: response = {},
|
data: response = {},
|
||||||
refetch,
|
|
||||||
error,
|
error,
|
||||||
isError,
|
isError,
|
||||||
isLoading,
|
isLoading,
|
||||||
} = useGetCartQuery();
|
} = useGetCartQuery(undefined, {
|
||||||
const cartItems = isError ? [] : response.data || [];
|
refetchOnMountOrArgChange: 30, // ✅ Sadece 30 saniye sonra mount'ta refetch
|
||||||
|
refetchOnFocus: false,
|
||||||
|
refetchOnReconnect: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Handle the new data structure - data is now an object grouped by store
|
||||||
|
const cartData = isError ? {} : (response.data || {});
|
||||||
|
|
||||||
|
// Convert object of arrays to flat array for backward compatibility
|
||||||
|
const cartItems = useMemo(() => {
|
||||||
|
return Object.values(cartData).flat();
|
||||||
|
}, [cartData]);
|
||||||
|
|
||||||
const { t, i18n } = useTranslation();
|
const { t, i18n } = useTranslation();
|
||||||
const [isCheckout, setIsCheckout] = useState(false);
|
const [checkoutStores, setCheckoutStores] = useState({});
|
||||||
const [addToCart] = useAddToCartMutation();
|
const [addToCart] = useAddToCartMutation();
|
||||||
const [removeFromCart] = useRemoveFromCartMutation();
|
const [removeFromCart] = useRemoveFromCartMutation();
|
||||||
const [updateCartItem] = useUpdateCartItemMutation();
|
const [updateCartItem] = useUpdateCartItemMutation();
|
||||||
@@ -69,6 +78,8 @@ const CartPage = () => {
|
|||||||
const [localQuantities, setLocalQuantities] = useState({});
|
const [localQuantities, setLocalQuantities] = useState({});
|
||||||
const [pendingQuantities, setPendingQuantities] = useState({});
|
const [pendingQuantities, setPendingQuantities] = useState({});
|
||||||
const [loadingItems, setLoadingItems] = useState({});
|
const [loadingItems, setLoadingItems] = useState({});
|
||||||
|
const checkoutRefs = useRef({});
|
||||||
|
|
||||||
const modalProps = {
|
const modalProps = {
|
||||||
centered: true,
|
centered: true,
|
||||||
className: styles.cartDeleteModal,
|
className: styles.cartDeleteModal,
|
||||||
@@ -76,10 +87,25 @@ const CartPage = () => {
|
|||||||
width: 400,
|
width: 400,
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleCheckout = () => setIsCheckout(true);
|
// Convert grouped data to stores array
|
||||||
const handleBackToCart = () => setIsCheckout(false);
|
const stores = useMemo(() => {
|
||||||
const checkoutRef = useRef({ current: null });
|
return Object.entries(cartData).map(([storeSlug, items]) => {
|
||||||
|
if (!items || !items.length) return null;
|
||||||
|
|
||||||
|
// Get store info from first item
|
||||||
|
const storeInfo = items[0]?.product?.channel?.[0];
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: storeInfo?.id || storeSlug,
|
||||||
|
name: storeInfo?.name || storeSlug,
|
||||||
|
slug: storeSlug,
|
||||||
|
shipping_price: storeInfo?.shipping_price,
|
||||||
|
items: items
|
||||||
|
};
|
||||||
|
}).filter(Boolean);
|
||||||
|
}, [cartData]);
|
||||||
|
|
||||||
|
// ✅ Initialize local quantities from cart items
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const newLocalQuantities = {};
|
const newLocalQuantities = {};
|
||||||
const newPendingQuantities = {};
|
const newPendingQuantities = {};
|
||||||
@@ -95,17 +121,17 @@ const CartPage = () => {
|
|||||||
setPendingQuantities(newPendingQuantities);
|
setPendingQuantities(newPendingQuantities);
|
||||||
}, [cartItems]);
|
}, [cartItems]);
|
||||||
|
|
||||||
|
// ✅ Debounced update - tek bir useEffect
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
const debouncedUpdates = {};
|
||||||
|
|
||||||
const updateItem = async (productId) => {
|
const updateItem = async (productId) => {
|
||||||
const serverQuantity =
|
const serverItem = cartItems.find((item) => item.product.id === productId);
|
||||||
cartItems.find((item) => item.product.id === productId)
|
const serverQuantity = serverItem ? parseInt(serverItem.product_quantity, 10) : 0;
|
||||||
?.product_quantity || 0;
|
|
||||||
const pendingQuantity = pendingQuantities[productId];
|
const pendingQuantity = pendingQuantities[productId];
|
||||||
|
|
||||||
if (
|
// ✅ Eğer değişiklik yoksa, güncelleme yapma
|
||||||
pendingQuantity === undefined ||
|
if (pendingQuantity === undefined || pendingQuantity === serverQuantity) {
|
||||||
pendingQuantity === parseInt(serverQuantity, 10)
|
|
||||||
) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,11 +146,12 @@ const CartPage = () => {
|
|||||||
quantity: pendingQuantity,
|
quantity: pendingQuantity,
|
||||||
}).unwrap();
|
}).unwrap();
|
||||||
}
|
}
|
||||||
|
// ✅ RTK Query otomatik cache'i güncelleyecek, refetch'e gerek yok
|
||||||
|
|
||||||
refetch();
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to update cart:", error);
|
console.error("Failed to update cart:", error);
|
||||||
|
|
||||||
|
// ✅ Hata durumunda geri al
|
||||||
const originalItem = cartItems.find(
|
const originalItem = cartItems.find(
|
||||||
(item) => item.product.id === productId
|
(item) => item.product.id === productId
|
||||||
);
|
);
|
||||||
@@ -144,12 +171,12 @@ const CartPage = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const debouncedUpdates = {};
|
// ✅ Her productId için debounced update oluştur
|
||||||
Object.keys(pendingQuantities).forEach((productId) => {
|
Object.keys(pendingQuantities).forEach((productId) => {
|
||||||
if (!debouncedUpdates[productId]) {
|
if (!debouncedUpdates[productId]) {
|
||||||
debouncedUpdates[productId] = debounce(
|
debouncedUpdates[productId] = debounce(
|
||||||
() => updateItem(productId),
|
() => updateItem(productId),
|
||||||
300
|
500 // ✅ 500ms debounce (daha stabil)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
debouncedUpdates[productId]();
|
debouncedUpdates[productId]();
|
||||||
@@ -160,7 +187,7 @@ const CartPage = () => {
|
|||||||
debouncedFn.cancel()
|
debouncedFn.cancel()
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
}, [pendingQuantities, cartItems, updateCartItem, removeFromCart, refetch]);
|
}, [pendingQuantities, cartItems, updateCartItem, removeFromCart]);
|
||||||
|
|
||||||
const handleQuantityIncrease = (productId) => (event) => {
|
const handleQuantityIncrease = (productId) => (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -171,9 +198,11 @@ const CartPage = () => {
|
|||||||
const item = cartItems.find((item) => item.product.id === productId);
|
const item = cartItems.find((item) => item.product.id === productId);
|
||||||
if (!item) return;
|
if (!item) return;
|
||||||
|
|
||||||
|
// ✅ Stock kontrolü
|
||||||
if (localQuantities[productId] >= item.product.stock) {
|
if (localQuantities[productId] >= item.product.stock) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const newQuantity = (localQuantities[productId] || 0) + 1;
|
const newQuantity = (localQuantities[productId] || 0) + 1;
|
||||||
setLocalQuantities((prev) => ({
|
setLocalQuantities((prev) => ({
|
||||||
...prev,
|
...prev,
|
||||||
@@ -185,18 +214,6 @@ const CartPage = () => {
|
|||||||
}));
|
}));
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleOrderSubmit = async () => {
|
|
||||||
if (isCheckout && checkoutRef.current) {
|
|
||||||
const success = await checkoutRef.current();
|
|
||||||
if (success) {
|
|
||||||
refetch();
|
|
||||||
setIsCheckout(false);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
setIsCheckout(true);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleQuantityDecrease = (productId) => (event) => {
|
const handleQuantityDecrease = (productId) => (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
@@ -205,10 +222,12 @@ const CartPage = () => {
|
|||||||
|
|
||||||
const currentQuantity = localQuantities[productId] || 0;
|
const currentQuantity = localQuantities[productId] || 0;
|
||||||
|
|
||||||
|
// ✅ 1'den azsa modal göster
|
||||||
if (currentQuantity <= 1) {
|
if (currentQuantity <= 1) {
|
||||||
showDeleteConfirm(productId);
|
showDeleteConfirm(productId);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const newQuantity = currentQuantity - 1;
|
const newQuantity = currentQuantity - 1;
|
||||||
setLocalQuantities((prev) => ({
|
setLocalQuantities((prev) => ({
|
||||||
...prev,
|
...prev,
|
||||||
@@ -220,14 +239,42 @@ const CartPage = () => {
|
|||||||
}));
|
}));
|
||||||
};
|
};
|
||||||
|
|
||||||
const calculateTotal = () => {
|
const calculateStoreTotal = (storeItems) => {
|
||||||
return cartItems.reduce((sum, item) => {
|
return storeItems.reduce((sum, item) => {
|
||||||
const itemPrice = parseFloat(item.product.price_amount) || 0;
|
const itemPrice = parseFloat(item.product.price_amount) || 0;
|
||||||
const itemQuantity = parseInt(item.product_quantity, 10) || 0;
|
const itemQuantity = parseInt(item.product_quantity, 10) || 0;
|
||||||
return sum + itemPrice * itemQuantity;
|
return sum + itemPrice * itemQuantity;
|
||||||
}, 0);
|
}, 0);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
const getStoreShippingPrice = (store) => {
|
||||||
|
return store.shipping_price !== null && store.shipping_price !== undefined
|
||||||
|
? parseFloat(store.shipping_price)
|
||||||
|
: 20;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCheckout = (storeId) => {
|
||||||
|
setCheckoutStores(prev => ({ ...prev, [storeId]: true }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleBackToCart = (storeId) => {
|
||||||
|
setCheckoutStores(prev => ({ ...prev, [storeId]: false }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleOrderSubmit = async (storeId, storeItems) => {
|
||||||
|
if (checkoutStores[storeId] && checkoutRefs.current[storeId]) {
|
||||||
|
const success = await checkoutRefs.current[storeId]();
|
||||||
|
if (success) {
|
||||||
|
// ✅ RTK Query otomatik güncelleyecek, refetch'e gerek yok
|
||||||
|
setCheckoutStores(prev => ({ ...prev, [storeId]: false }));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
handleCheckout(storeId);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleClickOutside = (event) => {
|
const handleClickOutside = (event) => {
|
||||||
if (expandedRef.current && !expandedRef.current.contains(event.target)) {
|
if (expandedRef.current && !expandedRef.current.contains(event.target)) {
|
||||||
@@ -246,8 +293,24 @@ const CartPage = () => {
|
|||||||
|
|
||||||
const handleDeleteConfirm = async () => {
|
const handleDeleteConfirm = async () => {
|
||||||
if (itemToDelete) {
|
if (itemToDelete) {
|
||||||
await removeFromCart({ productId: itemToDelete }).unwrap();
|
try {
|
||||||
refetch();
|
await removeFromCart({ productId: itemToDelete }).unwrap();
|
||||||
|
// ✅ RTK Query otomatik cache'i güncelleyecek
|
||||||
|
|
||||||
|
// ✅ Local state'i de temizle
|
||||||
|
setLocalQuantities((prev) => {
|
||||||
|
const newState = { ...prev };
|
||||||
|
delete newState[itemToDelete];
|
||||||
|
return newState;
|
||||||
|
});
|
||||||
|
setPendingQuantities((prev) => {
|
||||||
|
const newState = { ...prev };
|
||||||
|
delete newState[itemToDelete];
|
||||||
|
return newState;
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to remove item:", error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
setDeleteModalVisible(false);
|
setDeleteModalVisible(false);
|
||||||
setItemToDelete(null);
|
setItemToDelete(null);
|
||||||
@@ -258,17 +321,25 @@ const CartPage = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleEmptyCartConfirm = async () => {
|
const handleEmptyCartConfirm = async () => {
|
||||||
await cleanCart().unwrap();
|
try {
|
||||||
refetch();
|
await cleanCart().unwrap();
|
||||||
|
// ✅ RTK Query otomatik cache'i güncelleyecek
|
||||||
|
|
||||||
|
// ✅ Local state'i temizle
|
||||||
|
setLocalQuantities({});
|
||||||
|
setPendingQuantities({});
|
||||||
|
setCheckoutStores({});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to clean cart:", error);
|
||||||
|
}
|
||||||
setEmptyCartModalVisible(false);
|
setEmptyCartModalVisible(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleButtonClick = () => {
|
const getTotalItemCount = () => {
|
||||||
if (isCheckout) {
|
return cartItems.reduce(
|
||||||
handleOrderSubmit();
|
(sum, item) => sum + parseInt(item.product_quantity, 10),
|
||||||
} else {
|
0
|
||||||
handleCheckout();
|
);
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -296,6 +367,7 @@ const CartPage = () => {
|
|||||||
>
|
>
|
||||||
<p>{t("common.Are_you_sure_you_want_to_empty_the_cart")}</p>
|
<p>{t("common.Are_you_sure_you_want_to_empty_the_cart")}</p>
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<Loader />
|
<Loader />
|
||||||
) : cartItems.length === 0 ? (
|
) : cartItems.length === 0 ? (
|
||||||
@@ -303,118 +375,132 @@ const CartPage = () => {
|
|||||||
) : (
|
) : (
|
||||||
<div className={styles.cartItems}>
|
<div className={styles.cartItems}>
|
||||||
<div className={styles.cartProducts}>
|
<div className={styles.cartProducts}>
|
||||||
{isCheckout ? (
|
<div className={styles.storesContainer}>
|
||||||
<Checkout
|
<div className={styles.cartHeader}>
|
||||||
cartItems={cartItems}
|
<h2>
|
||||||
onBackToCart={handleBackToCart}
|
{t("cart.basket")} ({getTotalItemCount()})
|
||||||
onPlaceOrder={checkoutRef}
|
</h2>
|
||||||
/>
|
<div>
|
||||||
) : (
|
<button
|
||||||
<div className={styles.cartItemContainer}>
|
className={styles.deleteBtn}
|
||||||
<div className={styles.cartHeader}>
|
style={{ padding: "4px 12px" }}
|
||||||
<h2>
|
onClick={showEmptyCartConfirm}
|
||||||
{t("cart.basket")} (
|
>
|
||||||
{cartItems.reduce(
|
<FaTrashAlt /> {t("cart.clearCart")}
|
||||||
(sum, item) => sum + parseInt(item.product_quantity, 10),
|
</button>
|
||||||
0
|
|
||||||
)}
|
|
||||||
)
|
|
||||||
</h2>
|
|
||||||
<div>
|
|
||||||
<button
|
|
||||||
className={styles.deleteBtn}
|
|
||||||
style={{ padding: "4px 12px" }}
|
|
||||||
onClick={showEmptyCartConfirm}
|
|
||||||
>
|
|
||||||
<FaTrashAlt /> {t("cart.clearCart")}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
{cartItems.map((item) => (
|
</div>
|
||||||
<div key={item.id} className={styles.cartItem}>
|
|
||||||
<div className={styles.itemImage}>
|
{stores.map((store) => {
|
||||||
<img
|
const shippingPrice = getStoreShippingPrice(store);
|
||||||
src={item.product.media[0]?.images_400x400}
|
const storeTotal = calculateStoreTotal(store.items);
|
||||||
alt={item.product.name}
|
const totalWithShipping = storeTotal + shippingPrice;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={store.id} className={styles.storeSection}>
|
||||||
|
{checkoutStores[store.id] ? (
|
||||||
|
<Checkout
|
||||||
|
cartItems={store.items}
|
||||||
|
shippingPrice={shippingPrice}
|
||||||
|
productIds={store.items.map(item => item.product.id)}
|
||||||
|
onBackToCart={() => handleBackToCart(store.id)}
|
||||||
|
onPlaceOrder={(placeOrderFn) => {
|
||||||
|
checkoutRefs.current[store.id] = placeOrderFn;
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
) : (
|
||||||
<div className={styles.itemInfo}>
|
<div style={{background:"white"}}>
|
||||||
<div style={{ flex: "1" }}>
|
<div className={styles.storeHeader}>
|
||||||
<h3>{item.product.name}</h3>
|
<h3>{store.name}</h3>
|
||||||
{/* Replace the original description with the TruncatedDescription component */}
|
</div>
|
||||||
<TruncatedDescription
|
<div className={styles.cartItemContainer}>
|
||||||
description={item.product.description}
|
{store.items.map((item) => (
|
||||||
maxLength={150}
|
<div key={item.id} className={styles.cartItem}>
|
||||||
/>
|
<div className={styles.itemImage}>
|
||||||
</div>
|
<img
|
||||||
<div className={styles.priceQuantity}>
|
src={item.product.media[0]?.images_400x400}
|
||||||
<span className={styles.price}>
|
alt={item.product.name}
|
||||||
{(parseFloat(item.product.price_amount) || 0).toFixed(
|
/>
|
||||||
2
|
</div>
|
||||||
)}{" "}
|
<div className={styles.itemInfo}>
|
||||||
m.
|
<div style={{ flex: "1" }}>
|
||||||
</span>
|
<h3>{item.product.name}</h3>
|
||||||
<div className={styles.quantityControls}>
|
<TruncatedDescription
|
||||||
<button
|
description={item.product.description}
|
||||||
onClick={handleQuantityDecrease(item.product.id)}
|
maxLength={150}
|
||||||
className={styles.quantityBtn}
|
/>
|
||||||
disabled={loadingItems[item.product.id]}
|
</div>
|
||||||
>
|
<div className={styles.priceQuantity}>
|
||||||
<DecreaseIcon />
|
<span className={styles.price}>
|
||||||
</button>
|
{(parseFloat(item.product.price_amount) || 0).toFixed(2)} m.
|
||||||
<span>
|
</span>
|
||||||
{localQuantities[item.product.id] !== undefined
|
<div className={styles.quantityControls}>
|
||||||
? localQuantities[item.product.id]
|
<button
|
||||||
: parseInt(item.product_quantity, 10) || 0}
|
onClick={handleQuantityDecrease(item.product.id)}
|
||||||
</span>
|
className={styles.quantityBtn}
|
||||||
<button
|
disabled={loadingItems[item.product.id]}
|
||||||
onClick={handleQuantityIncrease(item.product.id)}
|
>
|
||||||
className={styles.quantityBtn}
|
<DecreaseIcon />
|
||||||
disabled={loadingItems[item.product.id]}
|
</button>
|
||||||
>
|
<span>
|
||||||
<IncreaseIcon />
|
{localQuantities[item.product.id] !== undefined
|
||||||
</button>
|
? localQuantities[item.product.id]
|
||||||
|
: parseInt(item.product_quantity, 10) || 0}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={handleQuantityIncrease(item.product.id)}
|
||||||
|
className={styles.quantityBtn}
|
||||||
|
disabled={loadingItems[item.product.id]}
|
||||||
|
>
|
||||||
|
<IncreaseIcon />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className={styles.deleteBtnContainer}>
|
||||||
|
<button
|
||||||
|
className={styles.deleteBtn}
|
||||||
|
onClick={() => showDeleteConfirm(item.product.id)}
|
||||||
|
>
|
||||||
|
<FaTrashAlt />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.deleteBtnContainer}>
|
)}
|
||||||
<button
|
|
||||||
className={styles.deleteBtn}
|
<div className={styles.storeSummary}>
|
||||||
onClick={() => showDeleteConfirm(item.product.id)}
|
<div className={styles.cartContent}>
|
||||||
>
|
<h3>{store.name} - {t("cart.basket")}:</h3>
|
||||||
<FaTrashAlt />
|
<div className={styles.summaryRow}>
|
||||||
</button>
|
<span>{t("cart.price")}:</span>
|
||||||
|
<span>{storeTotal.toFixed(2)} m.</span>
|
||||||
|
</div>
|
||||||
|
<div className={styles.summaryRow}>
|
||||||
|
<span>{t("cart.delivery")}:</span>
|
||||||
|
<span>{shippingPrice.toFixed(2)} m.</span>
|
||||||
|
</div>
|
||||||
|
<div className={styles.summaryRow}>
|
||||||
|
<span>{t("cart.total")}:</span>
|
||||||
|
<span>{totalWithShipping.toFixed(2)} m.</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => handleOrderSubmit(store.id, store.items)}
|
||||||
|
className={styles.checkoutBtn}
|
||||||
|
>
|
||||||
|
{checkoutStores[store.id] ? t("cart.order") : t("cart.prepareOrders")}
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
);
|
||||||
</div>
|
})}
|
||||||
)}
|
|
||||||
|
|
||||||
<div className={styles.cartSummary}>
|
|
||||||
<div className={styles.cartContent}>
|
|
||||||
<h3> {t("cart.basket")}:</h3>
|
|
||||||
<div className={styles.summaryRow}>
|
|
||||||
<span> {t("cart.price")}:</span>
|
|
||||||
<span>{calculateTotal().toFixed(2)} m.</span>
|
|
||||||
</div>
|
|
||||||
<div className={styles.summaryRow}>
|
|
||||||
<span> {t("cart.delivery")} :</span>
|
|
||||||
<span>0.00 m.</span>
|
|
||||||
</div>
|
|
||||||
<div className={styles.summaryRow}>
|
|
||||||
<span> {t("cart.total")}:</span>
|
|
||||||
<span>{calculateTotal().toFixed(2)} m.</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
onClick={handleButtonClick}
|
|
||||||
className={styles.checkoutBtn}
|
|
||||||
>
|
|
||||||
{isCheckout ? t("cart.order") : t("cart.prepareOrders")}
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className={styles.container}>
|
{/* Mobile sticky summary */}
|
||||||
|
{/* <div className={styles.container}>
|
||||||
<div className={styles.summaryCard} ref={expandedRef}>
|
<div className={styles.summaryCard} ref={expandedRef}>
|
||||||
<div
|
<div
|
||||||
className={`${styles.expandedContent} ${
|
className={`${styles.expandedContent} ${
|
||||||
@@ -423,14 +509,16 @@ const CartPage = () => {
|
|||||||
>
|
>
|
||||||
<div className={styles.details}>
|
<div className={styles.details}>
|
||||||
<div className={styles.row}>
|
<div className={styles.row}>
|
||||||
<span> {t("cart.price")}:</span>
|
<span>{t("cart.price")}:</span>
|
||||||
<span className={styles.amount}>
|
<span className={styles.amount}>
|
||||||
{calculateTotal().toFixed(2)} m.
|
{calculateTotal().toFixed(2)} m.
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.row}>
|
<div className={styles.row}>
|
||||||
<span> {t("cart.delivery")}:</span>
|
<span>{t("cart.delivery")}:</span>
|
||||||
<span className={styles.amount}>0.00 m.</span>
|
<span className={styles.amount}>
|
||||||
|
{stores.reduce((sum, store) => sum + getStoreShippingPrice(store), 0).toFixed(2)} m.
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -451,20 +539,12 @@ const CartPage = () => {
|
|||||||
{t("cart.total")}:
|
{t("cart.total")}:
|
||||||
</span>
|
</span>
|
||||||
<span className={styles.amount}>
|
<span className={styles.amount}>
|
||||||
{calculateTotal().toFixed(2)} m.
|
{(calculateTotal() + stores.reduce((sum, store) => sum + getStoreShippingPrice(store), 0)).toFixed(2)} m.
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className={styles.actionWrapper}>
|
|
||||||
<button
|
|
||||||
onClick={handleButtonClick}
|
|
||||||
className={styles.button}
|
|
||||||
>
|
|
||||||
{isCheckout ? t("cart.order") : t("cart.prepareOrders")}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div> */}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -69,10 +69,20 @@ const ProductPage = ({
|
|||||||
const [updateCartItem] = useUpdateCartItemMutation();
|
const [updateCartItem] = useUpdateCartItemMutation();
|
||||||
const [removeFromCart] = useRemoveFromCartMutation();
|
const [removeFromCart] = useRemoveFromCartMutation();
|
||||||
const [localQuantity, setLocalQuantity] = useState(0);
|
const [localQuantity, setLocalQuantity] = useState(0);
|
||||||
const cartItem = cartData?.data?.find(
|
const getCartItem = () => {
|
||||||
(item) =>
|
if (!cartData?.data || typeof cartData.data !== "object") {
|
||||||
item.product?.id === product?.id || item.product_id === product?.id
|
return null;
|
||||||
);
|
}
|
||||||
|
|
||||||
|
const allCartItems = Object.values(cartData.data).flat();
|
||||||
|
|
||||||
|
return allCartItems.find(
|
||||||
|
(item) =>
|
||||||
|
item.product?.id === product?.id || item.product_id === product?.id
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const cartItem = getCartItem();
|
||||||
const [pendingQuantity, setPendingQuantity] = useState(0);
|
const [pendingQuantity, setPendingQuantity] = useState(0);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
Reference in New Issue
Block a user