web/src/app/layout.jsx

354 lines
10 KiB
React
Raw Normal View History

2024-02-05 01:40:57 +03:30
"use client";
import AppContext from "@ctx/AppContext";
2024-02-16 19:36:30 +03:30
import Chapar from "plugins/Chapar";
2024-02-16 19:53:36 +03:30
import Loading from "plugins/Loading/page";
2024-02-16 18:23:02 +03:30
import BottomSheetAddress from "plugins/bottomSheet/BottomSheetAddress";
import BottomSheetLogOut from "plugins/bottomSheet/BottomSheetLogOut";
2024-02-16 19:36:30 +03:30
import { useEffect, useState } from "react";
import "react-image-gallery/styles/css/image-gallery.css";
2024-02-16 18:23:02 +03:30
import "react-image-lightbox/style.css";
2024-02-16 19:36:30 +03:30
import "react-spring-bottom-sheet/dist/style.css";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import "swiper/css";
import "../../style/fontiran.css";
import "../../style/globals.css";
2024-02-22 20:45:50 +03:30
import Goftino from "plugins/Goftino/page";
export const metadata = {
title: "Acme",
openGraph: {
title: "Acme",
description: "Acme is a...",
},
};
2024-01-10 11:04:28 +03:30
2024-02-05 01:40:57 +03:30
export default function RootLayout({ children }) {
const [cart, setCart] = useState([]);
const [products, setProducts] = useState([]);
2024-02-16 18:23:02 +03:30
const [pager, setPager] = useState([]);
2024-02-05 01:40:57 +03:30
const [navData, setNavData] = useState([]);
const [brands, setBrands] = useState([]);
const [loading, setLoading] = useState(false);
const [closeNavbar, setCloseNavbar] = useState(false);
2024-02-11 17:24:30 +03:30
const [bottomSheetCartOpen, setBottomSheetCartOpen] = useState(false);
const [bottomSheetFilterOpen, setBottomSheetFilterOpen] = useState(false);
const [bottomSheetDiscountOpen, setBottomSheetDiscountOpen] = useState(false);
2024-02-16 18:23:02 +03:30
const [bottomSheetAddressOpen, setBottomSheetAddressOpen] = useState(false);
const [bottomSheetLogOutOpen, setBottomSheetLogOutOpen] = useState(false);
const [bottomSheetDeleteAddressOpen, setBottomSheetDeleteAddressOpen] =
useState(false);
2024-02-11 17:24:30 +03:30
const [checkOutData, setCheckOutData] = useState([]);
2024-02-16 18:23:02 +03:30
const [addressData, setAddressData] = useState([]);
const [profile, setProfile] = useState([]);
const [stopProducts, setStopProducts] = useState(false);
const [pageGetProducts, setPageGetProducts] = useState(0);
const [isMobile, setIsMobile] = useState(false);
const [isOpenLightBox, setIsOpenLightBox] = useState(false);
2024-02-05 01:40:57 +03:30
2024-02-11 17:24:30 +03:30
const AddItemToCart = (
id,
persianName,
cost,
costWithDiscount,
mainImage,
hasDiscount,
maxOrderCount
) => {
2024-02-05 01:40:57 +03:30
setCart((prevCart) => {
// Check if the item is already in the cart
const existingItem = prevCart.find((item) => item.id === id);
2024-02-11 17:24:30 +03:30
let updatedCart;
2024-02-05 01:40:57 +03:30
if (existingItem) {
// If the item is already in the cart, update its count
2024-02-11 17:24:30 +03:30
if (existingItem.count < maxOrderCount) {
updatedCart = prevCart.map((item) =>
item.id === id ? { ...item, count: item.count + 1 } : item
);
} else {
// Notify user if maxOrderCount is exceeded
toast.error(
`
نمیتوانید بیشتراز
${maxOrderCount}
عدد ثبت کنید `,
{
position: "bottom-right",
closeOnClick: true,
}
);
updatedCart = prevCart;
}
2024-02-05 01:40:57 +03:30
} else {
// If the item is not in the cart, add it with a count of 1
2024-02-11 17:24:30 +03:30
updatedCart = [
...prevCart,
{
id,
count: 1,
persianName,
cost,
costWithDiscount,
mainImage,
hasDiscount,
maxOrderCount,
},
];
2024-02-05 01:40:57 +03:30
}
2024-02-11 17:24:30 +03:30
// Store the updated cart in local storage
localStorage.setItem("cart", JSON.stringify(updatedCart));
// Return the updated cart
return updatedCart;
2024-02-05 01:40:57 +03:30
});
};
const RemoveItemFromCart = (id) => {
setCart((prevCart) => {
// Check if the item is already in the cart
const existingItem = prevCart.find((item) => item.id === id);
if (existingItem) {
// If the item is already in the cart
if (existingItem.count === 1) {
// If the item count is 1, remove it from the cart
2024-02-11 17:24:30 +03:30
const updatedCart = prevCart.filter((item) => item.id !== id);
// Store the updated cart in local storage
localStorage.setItem("cart", JSON.stringify(updatedCart));
// Return the updated cart
return updatedCart;
2024-02-05 01:40:57 +03:30
} else {
// If the item count is greater than 1, update its count
2024-02-11 17:24:30 +03:30
const updatedCart = prevCart.map((item) =>
2024-02-05 01:40:57 +03:30
item.id === id ? { ...item, count: item.count - 1 } : item
);
2024-02-11 17:24:30 +03:30
// Store the updated cart in local storage
localStorage.setItem("cart", JSON.stringify(updatedCart));
// Return the updated cart
return updatedCart;
2024-02-05 01:40:57 +03:30
}
} else {
// If the item is not in the cart, do nothing
return prevCart;
}
});
};
const fetchNavData = async (id) => {
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/product/category?sortByMain=true`
);
const post = await res.json();
setNavData(post);
};
const fetchProducts = async (
2024-02-16 18:23:02 +03:30
pageGetProducts,
2024-02-05 01:40:57 +03:30
id,
selectedBrands,
isChecked,
minPrice,
maxPrice,
sort,
2024-02-16 18:23:02 +03:30
isRangePrice,
paginationSay
2024-02-05 01:40:57 +03:30
) => {
const brandIds = selectedBrands?.map((brand) => brand.id);
2024-02-16 18:23:02 +03:30
const queryString = `${`page=${pageGetProducts}`}${
id ? `&categoryId=${id}` : ""
}${
2024-02-05 01:40:57 +03:30
brandIds?.length > 0 ? `&brandIds=${brandIds?.join("&brandIds=")}` : ""
}${isChecked ? `&isActive=${isChecked}` : ""}${
isRangePrice ? `&minPrice=${minPrice}` : ""
}${isRangePrice ? `&maxPrice=${maxPrice}` : ""}${
!!sort ? `&sortBy=${sort}` : ""
}`;
const cleanQueryString = decodeURIComponent(
queryString.replace(/\%20/g, " ")
);
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/product?${cleanQueryString}`
);
const post = await res.json();
2024-02-16 18:23:02 +03:30
if (paginationSay) {
2024-02-16 19:10:32 +03:30
// If it's a paginated request (not the first Page)
2024-02-16 18:23:02 +03:30
window.scrollTo({
top: 0,
behavior: "smooth", // Optional: smooth scrolling behavior
});
console.log();
setProducts(post.products);
setStopProducts(true); // Assuming this stops pagination
}
if (post.length <= 19) {
2024-02-16 19:10:32 +03:30
// If the length of fetched products is less than or equal to 19, indicating the last Page
2024-02-16 18:23:02 +03:30
setStopProducts(true); // Assuming this stops pagination
}
if (!paginationSay && pageGetProducts == 0) {
2024-02-16 19:10:32 +03:30
// If it's not a paginated request and it's the first Page
2024-02-16 18:23:02 +03:30
setProducts(post.products);
setPager(post.pager);
} else if (!paginationSay && pageGetProducts != 0) {
2024-02-16 19:10:32 +03:30
// If it's not a paginated request and it's not the first Page
2024-02-16 18:23:02 +03:30
console.log("kir", products, !!products ? products : [], post.products);
setProducts((data) => [...(data ? data : []), ...post.products]);
}
};
const fetchAddressUser = async () => {
try {
const data = await Chapar.get(
`${process.env.NEXT_PUBLIC_API_URL}/user/address`,
{
headers: {
Authorization: localStorage.getItem("token"),
},
}
);
setAddressData(data);
} catch ({ error, status }) {
toast.error(`${error?.response?.data?.message}`, {
position: "bottom-right",
closeOnClick: true,
});
setLoading(false);
}
};
const fetchUserInfo = async () => {
try {
const data = await Chapar.get(
`${process.env.NEXT_PUBLIC_API_URL}/user/info`,
{
headers: {
Authorization: localStorage.getItem("token"),
},
}
);
setProfile(data);
} catch ({ error, status }) {
localStorage.removeItem("token");
toast.error(`${error?.response?.data?.message}`, {
position: "bottom-right",
closeOnClick: true,
});
}
2024-02-05 01:40:57 +03:30
};
useEffect(() => {
2024-02-11 17:24:30 +03:30
const storedCart = localStorage.getItem("cart");
2024-02-16 18:23:02 +03:30
const token = localStorage.getItem("token");
2024-02-11 17:24:30 +03:30
if (storedCart) {
setCart(JSON.parse(storedCart));
}
2024-02-16 18:23:02 +03:30
if (token) {
fetchUserInfo();
}
2024-02-05 01:40:57 +03:30
fetchNavData();
}, []);
2024-01-10 11:04:28 +03:30
2024-02-16 18:23:02 +03:30
useEffect(() => {
const mediaQuery = window.matchMedia("(max-width: 768px)"); // Adjust the width according to your mobile breakpoint
const checkDeviceType = (mediaQuery) => {
if (mediaQuery.matches) {
setIsMobile(true);
} else {
setIsMobile(false);
}
};
// Initial check
checkDeviceType(mediaQuery);
// Listen for changes in media query
const listener = () => checkDeviceType(mediaQuery);
mediaQuery.addEventListener("change", listener);
// Clean up
return () => {
mediaQuery.removeEventListener("change", listener);
};
}, []);
2024-01-10 11:04:28 +03:30
return (
2024-02-05 01:40:57 +03:30
<AppContext.Provider
value={{
state: {
cart,
products,
navData,
loading,
brands,
closeNavbar,
2024-02-11 17:24:30 +03:30
bottomSheetCartOpen,
bottomSheetFilterOpen,
bottomSheetDiscountOpen,
2024-02-16 18:23:02 +03:30
bottomSheetAddressOpen,
bottomSheetDeleteAddressOpen,
bottomSheetLogOutOpen,
2024-02-11 17:24:30 +03:30
checkOutData,
2024-02-16 18:23:02 +03:30
addressData,
profile,
stopProducts,
pageGetProducts,
pager,
isMobile,
isOpenLightBox,
2024-02-05 01:40:57 +03:30
},
setCart,
setProducts,
setNavData,
setLoading,
setBrands,
2024-02-11 17:24:30 +03:30
setBottomSheetCartOpen,
setBottomSheetFilterOpen,
setBottomSheetDiscountOpen,
2024-02-16 18:23:02 +03:30
setBottomSheetAddressOpen,
setBottomSheetDeleteAddressOpen,
setBottomSheetLogOutOpen,
2024-02-11 17:24:30 +03:30
setCheckOutData,
2024-02-16 18:23:02 +03:30
setStopProducts,
setProfile,
setPageGetProducts,
setPager,
setIsMobile,
setIsOpenLightBox,
2024-02-05 01:40:57 +03:30
AddItemToCart,
RemoveItemFromCart,
fetchNavData,
fetchProducts,
setCloseNavbar,
2024-02-16 18:23:02 +03:30
setAddressData,
fetchAddressUser,
2024-02-05 01:40:57 +03:30
}}
>
<html lang="en">
<body>
{children}
<ToastContainer position="bottom-right" closeOnClick={true} rtl />
<Loading />
2024-02-16 18:23:02 +03:30
<BottomSheetAddress />
<BottomSheetLogOut />
2024-02-22 20:45:50 +03:30
<Goftino />
2024-02-05 01:40:57 +03:30
</body>
</html>
</AppContext.Provider>
2024-01-10 11:04:28 +03:30
);
}