Explorar el Código

serverGraphqlFetch 返回数据类型修改; 删除一些没用的代码;

fogwind hace 1 semana
padre
commit
28eee3cd23
Se han modificado 40 ficheros con 162 adiciones y 1479 borrados
  1. 11 9
      src/actions/addProductToCartAction.ts
  2. 1 1
      src/actions/deleteCartProductAction.ts
  3. 1 1
      src/actions/mergeCartAction.ts
  4. 4 2
      src/app/(checkout)/checkout/_components/CheckoutProducts/CheckoutProducts.tsx
  5. 1 1
      src/app/(checkout)/checkout/_components/ContinueToPay/PaymentMethodContinueTpPay.tsx
  6. 24 23
      src/app/(checkout)/checkout/continuetopay/page.tsx
  7. 6 2
      src/app/(checkout)/checkout/page.tsx
  8. 2 4
      src/app/(checkout)/layout.tsx
  9. 2 2
      src/app/(public)/category/[slug]/[id]/page.tsx
  10. 1 1
      src/app/(public)/error.tsx
  11. 1 1
      src/app/(public)/layout.tsx
  12. 1 1
      src/app/(public)/paymentresult/_components/CancelOrFailure.tsx
  13. 6 2
      src/app/(public)/paymentresult/_components/OrderDetailWrapper.tsx
  14. 17 27
      src/app/(public)/product/[...urlProduct]/page.tsx
  15. 3 4
      src/app/layout.tsx
  16. 5 5
      src/components/catalog/product/RelatedProductsSection.tsx
  17. 0 71
      src/components/catalog/product/VariantSelector.tsx
  18. 1 1
      src/components/catalog/type.ts
  19. 0 84
      src/components/home/ProductCarousel.tsx
  20. 0 68
      src/components/home/RenderThemeCustomization.tsx
  21. 0 146
      src/components/home/ThreeItemGrid.tsx
  22. 0 32
      src/components/theme/product-carousel/index.tsx
  23. 0 52
      src/components/theme/product-carousel/theme.tsx
  24. 0 58
      src/components/theme/ui/grid/ThreeItemGrid.tsx
  25. 0 23
      src/components/theme/ui/grid/ThreeItemsSkeleton.tsx
  26. 1 1
      src/graphql/index.ts
  27. 0 17
      src/graphql/types/index.ts
  28. 0 170
      src/graphql/types/product.types.ts
  29. 1 1
      src/server-service/guestCartTokenService.ts
  30. 1 1
      src/types/cart/type.ts
  31. 0 31
      src/types/category/type.ts
  32. 1 1
      src/types/customer/order.ts
  33. 1 1
      src/types/graphqlFetch/type.ts
  34. 0 20
      src/types/theme/theme-customization.ts
  35. 6 295
      src/types/types.ts
  36. 1 73
      src/utils/bagisto/index.ts
  37. 62 179
      src/utils/helper.ts
  38. 0 28
      src/utils/hooks/getProductReviews.ts
  39. 0 26
      src/utils/hooks/getProductSwatchAndReview.ts
  40. 1 14
      src/utils/hooks/useCache.ts

+ 11 - 9
src/actions/addProductToCartAction.ts

@@ -35,18 +35,20 @@ export async function addProductToCartAction(param:AddToCartVariables) {
             cache: "no-store",
         });
         if(!response.error) {
-            const responseData = response.data.createAddProductInCart?.addProductInCart;
+            const responseData = response.data?.createAddProductInCart?.addProductInCart;
             /** 兜底代码 start*/
             // 游客加购,然后清空购物车,然后刷新页面,然后再加购,然后再刷新页面,购物车会失效,所以添加兜底代码
             // 如果之前的cartToken有效,responseCartId和responseCartToken的值是一样的都是cart id; 否则两者不相等
-            const responseCartId = responseData.id;
-            const responseCartToken = responseData.cartToken;
-            if(!accessToken && responseCartId !== responseCartToken) {
-                await setGuestCookie({
-                    guestCartId: responseCartId,
-                    guestToken: responseCartToken,
-                    isGuest: true
-                });
+            if(responseData) {
+                const responseCartId = responseData.id;
+                const responseCartToken = responseData.cartToken;
+                if(!accessToken && responseCartId !== responseCartToken) {
+                    await setGuestCookie({
+                        guestCartId: responseCartId,
+                        guestToken: responseCartToken,
+                        isGuest: true
+                    });
+                }
             }
             /** 兜底代码 end*/
 

+ 1 - 1
src/actions/deleteCartProductAction.ts

@@ -18,7 +18,7 @@ export async function deleteCartProductAction(cartItemId:number) {
             cache: "no-store",
         });
         if(!response.error) {
-            const resCatData = response.data.createRemoveCartItem?.removeCartItem ?? null;
+            const resCatData = response.data?.createRemoveCartItem?.removeCartItem ?? null;
             
             if(!resCatData || !resCatData?.itemsQty) {
                 // 购物车空了,删除游客cookie

+ 1 - 1
src/actions/mergeCartAction.ts

@@ -33,7 +33,7 @@ export async function mergeCartAction(){
             },
             cache: "no-store",
         });
-        const cartData = response.data.createMergeCart?.mergeCart ?? null;
+        const cartData = response.data?.createMergeCart?.mergeCart ?? null;
         let success = true;
         let msg = "";
         if(response.error) {

+ 4 - 2
src/app/(checkout)/checkout/_components/CheckoutProducts/CheckoutProducts.tsx

@@ -79,6 +79,7 @@ export default function CheckoutProducts({
             if(qty < 1) {
                 showToast("Quantity must be at least 1", "warning");
             } else {
+                overlayLoading.start();
                 const res = await editProductQtyFromCart(Number(item.id),qty);
                 if(!res.error) {
                     if(res.data) {
@@ -91,6 +92,7 @@ export default function CheckoutProducts({
                 } else {
                     showToast(res.msg, "danger");
                 }
+                overlayLoading.stop();
             }
         } else {
             showToast("This product can't change quantity.","warning");
@@ -114,7 +116,7 @@ export default function CheckoutProducts({
                         const baseImage = product.baseImage ? JSON.parse(product.baseImage) : {};
                         return (
                             <div className="relative w-22.5 h-30 flex-none" key={product.id}>
-                                <Image fill src={baseImage.medium_image_url || ''} alt={product.name} />
+                                <Image fill className="object-cover" src={baseImage.medium_image_url || ''} alt={product.name} />
                             </div>
                         )
                     })}
@@ -150,7 +152,7 @@ export default function CheckoutProducts({
                         return (
                             <div key={product.id} className="w-full flex gap-2 mt-4 first:mt-0 pb-4 border-b-1 border-b-[#f0f0f0] last:border-none">
                                 <div className="relative w-33 h-44 flex-none">
-                                    <Image fill src={baseImage.medium_image_url || ''} alt={product.name} />
+                                    <Image fill className="object-cover" src={baseImage.medium_image_url || ''} alt={product.name} />
                                 </div>
                                 <div className="w-full flex flex-col justify-between">
                                     <div className="w-full">

+ 1 - 1
src/app/(checkout)/checkout/_components/ContinueToPay/PaymentMethodContinueTpPay.tsx

@@ -39,7 +39,7 @@ export function PaymentMethodContinueTpPay({
     const router = useRouter();
     const { showToast } = useCustomToast();
     const paymentMethodsData = use(paymentMethodsDataPromise);
-    const paymentMethods =  paymentMethodsData.data.collectionRepayOrderPaymentMethods || [];
+    const paymentMethods =  paymentMethodsData.data?.collectionRepayOrderPaymentMethods || [];
 
     const { paymentRepay, createPaymentCallback } = usePlaceOrder();
 

+ 24 - 23
src/app/(checkout)/checkout/continuetopay/page.tsx

@@ -10,6 +10,7 @@ import { OrderDetailsData } from "@/types/customer/type";
 import { RepayOrderPaymentMethodsData } from "@/types/checkout/type";
 import {PaymentMethodContinueTpPay} from "../_components/ContinueToPay/PaymentMethodContinueTpPay";
 import LoadingPaymentMethod from "../_components/LoadingPaymentMethod";
+import TitleHeader from "@components/layout/navbar/TitleHeader";
 
 // 只能存在一个待支付订单
 export const dynamic = "force-dynamic";
@@ -49,7 +50,7 @@ export default async function ContinueToPay({searchParams}: {
             id: orderid as string
         }
     }); 
-    const orderDetailData = orderDetailResponse.customerOrder;
+    const orderDetailData = orderDetailResponse?.customerOrder;
     if(!orderDetailData  || orderDetailData?.status !== "pending")  {
         redirect('/', RedirectType.replace);
     }
@@ -62,8 +63,9 @@ export default async function ContinueToPay({searchParams}: {
         }
     });
       
-    if(orderDetailError) {
-        return (
+    return (<>
+        <TitleHeader title="Continue To Pay" />
+        {orderDetailError ?
             <div className="box-border px-4 w-full">
             
                 
@@ -79,27 +81,26 @@ export default async function ContinueToPay({searchParams}: {
                     Continue Shopping
                 </Link>
             </div>
-        );
-    }
-    return (
-        <div className="w-full pb-8">
-        
-            <ContinueToPayOrderInfo orderDetail={orderDetailData} />
-           
-            <div className="mt-6 box-border px-4">
-                <h3 className="text-ly-24 font-medium">Payment Method</h3>
+        :
+            <div className="w-full pb-8">
+            
+                <ContinueToPayOrderInfo orderDetail={orderDetailData} />
+            
+                <div className="mt-6 box-border px-4">
+                    <h3 className="text-ly-24 font-medium">Payment Method</h3>
 
+                </div>
+                <Suspense fallback={<LoadingPaymentMethod/>}> 
+                    <PaymentMethodContinueTpPay 
+                        orderId={orderDetailData._id}
+                        orderDetail={orderDetailData}
+                        paymentMethodsDataPromise={paymentMethodsResponse}
+                        defaultPaymentMethod={orderDetailData.payment}
+                    />
+                </Suspense>
+                
             </div>
-            <Suspense fallback={<LoadingPaymentMethod/>}> 
-                <PaymentMethodContinueTpPay 
-                    orderId={orderDetailData._id}
-                    orderDetail={orderDetailData}
-                    paymentMethodsDataPromise={paymentMethodsResponse}
-                    defaultPaymentMethod={orderDetailData.payment}
-                />
-            </Suspense>
-            
-        </div>
-    );
+        }
+    </>);
   
 }

+ 6 - 2
src/app/(checkout)/checkout/page.tsx

@@ -1,9 +1,11 @@
+import { createHash } from "crypto";
 import { redirect, RedirectType } from 'next/navigation';
 import {serverGraphqlFetch} from "@utils/bagisto/index";
 import CheckoutWrapper from "./_components/CheckoutWrapper";
 import { GET_CART_ITEM } from "@/graphql";
 import { auth } from "@/utils/auth/auth-helper";
 import { GetCartItemData } from "@/types/cart/type";
+import TitleHeader from "@components/layout/navbar/TitleHeader";
 
 /**
  * 进入结账页 
@@ -25,13 +27,15 @@ export default async function CheckoutPage() {
     const {data: cartDetailsRes} = await serverGraphqlFetch<GetCartItemData>({
         query: GET_CART_ITEM
     });
-    if(cartDetailsRes.createReadCart === null) {
+    if(!cartDetailsRes || cartDetailsRes.createReadCart === null) {
         redirect('/', RedirectType.replace);
     }
     const cartDetails = cartDetailsRes.createReadCart.readCart;
+    const cartDatahash = createHash('sha256').update(JSON.stringify(cartDetails)).digest('hex');
     return (
         <>
-            <CheckoutWrapper key={cartDetails.grandTotal}
+            <TitleHeader title="Checkout" />
+            <CheckoutWrapper key={cartDatahash}
                 cartDetailData={cartDetails}
                 loginEmail={session?.user?.email || ""}
             />

+ 2 - 4
src/app/(checkout)/layout.tsx

@@ -1,6 +1,6 @@
-import TitleHeader from "@components/layout/navbar/TitleHeader";
+
 import { ReactNode } from "react";
-export default async function RootLayout({
+export default async function CheckoutLayout({
   children,
 }: {
   children: ReactNode;
@@ -8,8 +8,6 @@ export default async function RootLayout({
   return (
     <>
 
-      <TitleHeader title="Checkout" />
-
       <div className="mx-auto w-full">
         {children}
       </div>

+ 2 - 2
src/app/(public)/category/[slug]/[id]/page.tsx

@@ -59,7 +59,7 @@ export async function generateMetadata({
 
   //   const categories = treeData?.treeCategories || [];
   //   const categoryItem = findCategoryBySlug(categories, categorySlug);
-  const categoryItem = categoryData.category;
+  const categoryItem = categoryData?.category;
   if (!categoryItem) return notFound();
 
   const translation = categoryItem.translation;
@@ -110,7 +110,7 @@ export default async function CategoryPage({
       id: Number(categoryId),
     },
   });
-  const categoryItem = categoryData.category;
+  const categoryItem = categoryData?.category;
   if (!categoryItem) return notFound();
 
   console.log("categoryItem +++++++++++", categoryItem);

+ 1 - 1
src/app/(public)/error.tsx

@@ -14,7 +14,7 @@ export default function Error({
 }) {
   const router = useRouter();
   const dispatch = useAppDispatch();
-  let msg = "There was an issue with our storefront. This could be a temporary issue, please try your action again.";
+  let msg = error.message || "There was an issue with our storefront. This could be a temporary issue, please try your action again.";
   if(error.name === 'UnauthorizedError') {
     msg = "Authorization Bearer token is required. Will redirect to Login page.";
   }

+ 1 - 1
src/app/(public)/layout.tsx

@@ -2,7 +2,7 @@ import { ReactNode } from "react";
 import Footer from "@/components/layout/footer";
 import Navbar from "@/components/layout/navbar";
 
-export default async function RootLayout({
+export default async function PublicLayout({
   children,
 }: {
   children: ReactNode;

+ 1 - 1
src/app/(public)/paymentresult/_components/CancelOrFailure.tsx

@@ -19,7 +19,7 @@ export default function CancelOrFailure({
 }) { 
     const dispatch = useAppDispatch();
     const promiseRes = use(orderDetailPromise);
-    const orderDetailRes = promiseRes.data.customerOrder ?? null;
+    const orderDetailRes = promiseRes.data?.customerOrder ?? null;
     const {cancelOrder} = usePlaceOrder();
     const orderId = orderDetailRes?._id;
     const orderStatus = orderDetailRes?.status;

+ 6 - 2
src/app/(public)/paymentresult/_components/OrderDetailWrapper.tsx

@@ -1,6 +1,7 @@
 "use client";
 
 import {use, useEffect} from "react";
+import { redirect, RedirectType } from 'next/navigation';
 import Link from "next/link";
 import Image from "next/image";
 import {FetchGraphqlResult} from "@/types/graphqlFetch/type";
@@ -43,8 +44,11 @@ export default function OrderDetailWrapper({
 
     const {currencies} = useConfig();
     const promiseRes = use(orderDetailPromise);
-    const orderDetailRes = promiseRes.data.customerOrder;
-    const shippingAddress = getAddressFromOrderDetailAddressList(orderDetailRes.addresses,"order_shipping");
+    const orderDetailRes = promiseRes.data?.customerOrder ?? null;
+    if(!orderDetailRes) {
+        redirect('/', RedirectType.replace);
+    }
+    const shippingAddress = getAddressFromOrderDetailAddressList(orderDetailRes?.addresses,"order_shipping");
     let orderCreatedAt = 'Can\'t get order date';
     if(orderDetailRes?.createdAt) {
         const localDate = new Date(orderDetailRes.createdAt);

+ 17 - 27
src/app/(public)/product/[...urlProduct]/page.tsx

@@ -10,7 +10,7 @@ import {
 } from "@/components/common/skeleton/ProductSkeleton";
 import { BASE_SCHEMA_URL, PRODUCT_TYPE } from "@/utils/constants";
 import { GET_PRODUCT_BY_URL_KEY } from "@/graphql";
-import { cachedProductRequest } from "@/utils/hooks/useCache";
+import {serverGraphqlFetch} from "@utils/bagisto/index";
 import {
   ProductOption,
   SingleProductResponse,
@@ -31,30 +31,7 @@ import { formatFlexibleVariants } from "@/utils/variantTools";
 // export const dynamic = 'auto'
 // // 'auto' | 'force-dynamic' | 'error' | 'force-static'
 export const dynamic = "force-dynamic";
-async function getSingleProduct(urlKey: string) {
-  try {
-    const { data: dataById } =
-      await cachedProductRequest<SingleProductResponse>(
-        // urlKey, // 产品名称
-        GET_PRODUCT_BY_URL_KEY, // gql查询语句
-        { urlKey: urlKey },
-      );
 
-    const product = dataById?.product || null;
-
-    return product;
-  } catch (error) {
-    if (error instanceof Error) {
-      console.error("Error fetching product:", {
-        message: error.message,
-        urlKey,
-        graphQLErrors: (error as unknown as Record<string, unknown>)
-          .graphQLErrors,
-      });
-    }
-    return null;
-  }
-}
 //动态路由中的参数 -- params
 export default async function ProductPage({
   params,
@@ -64,8 +41,21 @@ export default async function ProductPage({
 }) {
   const { urlProduct } = await params;
   const fullPath = urlProduct.join("/");
-  const product = await getSingleProduct(fullPath);
-  if (!product) return notFound();
+  
+  const resProductData = await serverGraphqlFetch<SingleProductResponse,{urlKey: string;}>({
+      // urlKey, // 产品名称
+      query: GET_PRODUCT_BY_URL_KEY, // gql查询语句
+      variables:{ 
+        urlKey: fullPath 
+      },
+      takeAuthorization: false,
+      
+  });
+  console.log("productCustomerFeatures----------------------",resProductData);
+  const product = resProductData.data?.product;
+  const fetchProductError = resProductData.error;
+  if (fetchProductError && fetchProductError.extensions.status === 404) return notFound();
+  if(!product) throw new Error(fetchProductError?.message ?? 'Get product data failed');
   // const allReviews: ProductReviewList = await getProductReviews(
   //   String(product._id),
   // );
@@ -75,7 +65,7 @@ export default async function ProductPage({
   // method: "GET",
 // });
 // const allReviews = res?.body?.data;
-console.log("productCustomerFeatures----------------------",product);
+
   const questionTotal = 73;
   // const imageUrl = getImageUrl(product?.baseImageUrl, baseUrl, NOT_IMAGE);
 

+ 3 - 4
src/app/layout.tsx

@@ -101,8 +101,8 @@ export default async function RootLayout({
     tags: ["config-currency-list"]
   });
  
-  const countries = countryResData.countries;
-  const currencyList = currencyResData.currencies?.edges.map((item) => item.node) ?? [];
+  const countries = countryResData?.countries ?? [];
+  const currencyList = currencyResData?.currencies?.edges.map((item) => item.node) ?? [];
   const storeConfig = {
     // 系统默认值
     defaultChannel: defaultChannel,
@@ -119,7 +119,7 @@ export default async function RootLayout({
     query: GET_CART_ITEM
   });
   
-  const cartDetails = cartDetailsRes.createReadCart?.readCart ?? null;
+  const cartDetails = cartDetailsRes?.createReadCart?.readCart ?? null;
   return (
     <html lang="en" suppressHydrationWarning>
       <head>
@@ -163,7 +163,6 @@ export default async function RootLayout({
         </main>
         <div id="modal-root"></div>
         <KernelProvider />
-        {process.env.NODE_ENV} / {process.env.APP_ENV}
         <span aria-hidden="true" data-nx-locale style={__srOnly}>{__lr}</span>
       </body>
     </html>

+ 5 - 5
src/components/catalog/product/RelatedProductsSection.tsx

@@ -1,7 +1,7 @@
 import { GET_RELATED_PRODUCTS } from "@/graphql";
 import { ProductsSection } from "./ProductsSection";
 import { SingleProductResponse } from "@components/catalog/type";
-import { cachedProductRequest } from "@/utils/hooks/useCache";
+import {serverGraphqlFetch} from "@utils/bagisto/index";
 
 export async function RelatedProductsSection({
   fullPath,
@@ -10,14 +10,14 @@ export async function RelatedProductsSection({
 }) {
     async function getRelatedProduct(urlKey: string) {
       try {
-        const {data:dataById} = await cachedProductRequest<SingleProductResponse>(
+        const {data:dataById} = await serverGraphqlFetch<SingleProductResponse,{urlKey:string;first:number;}>({
           // urlKey,
-          GET_RELATED_PRODUCTS,
-          {
+          query:GET_RELATED_PRODUCTS,
+          variables:{
             urlKey: urlKey,
             first: 4,
           }
-        );
+        });
     
         return dataById?.product || null;
       } catch (error) {

+ 0 - 71
src/components/catalog/product/VariantSelector.tsx

@@ -1,71 +0,0 @@
-"use client";
-
-import { AttributeData, AttributeOptionNode } from "@/types/types";
-import { createUrl, getValidTitle } from "@/utils/helper";
-import clsx from "clsx";
-import { usePathname, useRouter, useSearchParams } from "next/navigation";
-
-export function VariantSelector({
-  variants,
-  setUserInteracted,
-}: {
-  variants: AttributeData[];
-  setUserInteracted: React.Dispatch<React.SetStateAction<boolean>>;
-  possibleOptions: Record<string, number[]>;
-}) {
-  const router = useRouter();
-  const pathname = usePathname();
-  const searchParams = useSearchParams();
-  if (!variants?.length) return null;
-
-  return (
-    <>
-      {variants.map((option , index : number) => {
-        const attributeCode = option.code;
-        const _isAlreadySelected = searchParams.has(attributeCode);
-        return (
-          <dl key={`${option.id} + ${index}` } className="mb-8">
-            <dt className="mb-4 text-sm capitalize tracking-wide">
-              {getValidTitle(attributeCode)}
-            </dt>
-
-            <dd className="flex flex-wrap gap-3">
-              {(option.options as AttributeOptionNode[]).map((node) => {
-                const isActive = searchParams.get(attributeCode) === String(node.id);
-                const isAvailable = node?.isValid;
-                const nextParams = new URLSearchParams(searchParams.toString());
-                nextParams.set(attributeCode, String(node.id));
-
-                const optionUrl = createUrl(pathname, nextParams);
-
-                return (
-                  <button
-                    key={node.id}
-                    disabled={!isAvailable}
-                    onClick={() => {
-                      if (!isAvailable) return;
-                      router.replace(optionUrl, { scroll: false });
-                      setUserInteracted(true);
-                    }}
-                    className={clsx(
-                      "flex min-w-[48px] cursor-pointer items-center justify-center rounded-lg bg-neutral-100 px-3.5 py-2.5 text-sm dark:border-neutral-800 dark:bg-neutral-800",
-                      {
-                        "cursor-default ring-2 ring-blue-600 text-blue-600": isActive,
-                        "ring-[0] transition duration-300 ease-in-out hover:scale-110 hover:border-blue-600":
-                          !isActive && isAvailable,
-                        "relative z-10 cursor-not-allowed overflow-hidden bg-neutral-100 text-neutral-500 ring-1 ring-neutral-300 before:absolute before:inset-x-0 before:-z-10 before:h-px before:-rotate-45 before:bg-neutral-300 before:transition-transform dark:bg-neutral-900 dark:text-neutral-400 dark:ring-neutral-700 before:dark:bg-neutral-700":
-                          !isAvailable,
-                      }
-                    )}
-                  >
-                    {node.label || node.adminName}
-                  </button>
-                );
-              })}
-            </dd>
-          </dl>
-        );
-      })}
-    </>
-  );
-}

+ 1 - 1
src/components/catalog/type.ts

@@ -1,5 +1,5 @@
 export interface SingleProductResponse {
-  product: ProductNode;
+  product: ProductNode | null;
 }
 export interface ProductOptionValue {
   code: string;

+ 0 - 84
src/components/home/ProductCarousel.tsx

@@ -1,84 +0,0 @@
-import { FC } from "react";
-import { cachedGraphQLRequest } from "@/utils/hooks/useCache";
-import { ThreeItemGrid } from "./ThreeItemGrid";
-import Theme from "./ProductCarouselTheme";
-import { GET_PRODUCTS } from "@/graphql";
-
-interface ProductCarouselProps {
-  options: {
-    title?: string;
-    filters: Record<string, any>;
-  };
-  itemCount?: number;
-  sortOrder?: number;
-}
-
-const ProductCarousel: FC<ProductCarouselProps> = async ({
-  options,
-  itemCount = 4,
-  sortOrder,
-}) => {
-  const { filters, title } = options;
-
-    const { sort, limit, ...rest } = filters || {};
-    const filterObject: Record<string, string> = {};
-    Object.entries(rest).forEach(([key, value]) => {
-      if (value !== undefined && value !== null) {
-        filterObject[key] = String(value);
-      }
-    });
-    const filterInput =
-      Object.keys(filterObject).length > 0
-        ? JSON.stringify(filterObject)
-        : undefined;
-
-    let sortKey = "CREATED_AT";
-    let reverse = true;
-
-    if (sort === "created_at-desc") {
-      sortKey = "CREATED_AT";
-      reverse = true;
-    } else if (sort === "price-desc") {
-      sortKey = "PRICE";
-      reverse = true;
-    }
-
-    const {data} = await cachedGraphQLRequest<any>(
-      "home",
-      GET_PRODUCTS,
-      {
-        sortKey,
-        filter: filterInput,
-        first: limit ? parseInt(limit, 10) : itemCount,
-        reverse,
-      }
-    );
-
-    const products =
-      data?.products?.edges?.slice(0, 8).map((edge: any) => edge.node) || [];
-
-    if (!products.length) {
-      return null;
-    }
-
-    if (sortOrder === 2) {
-      return (
-        <ThreeItemGrid
-          title={title || "Products"}
-          description="Discover the latest trends! Fresh products just added—shop new styles, tech, and essentials before they're gone."
-          products={products.slice(0, 3)}
-        />
-      );
-    }
-
-    return (
-      <Theme
-        title={title || "Products"}
-        description="Discover the latest trends! Fresh products just added—shop new styles, tech, and essentials before they're gone."
-        products={products}
-      />
-    );
-
-};
-
-export default ProductCarousel;

+ 0 - 68
src/components/home/RenderThemeCustomization.tsx

@@ -1,68 +0,0 @@
-import { FC, Suspense } from "react";
-import { safeParse } from "@utils/helper";
-import { CategoryCarouselOptions, ProductCarouselOptions, ThemeCustomizationResponse } from "@/types/theme/theme-customization";
-import ImageCarousel from "./ImageCarousel";
-import ProductCarousel from "./ProductCarousel";
-import CategoryCarousel from "./CategoryCarousel";
-import { MobileSearchBar } from "@components/layout/navbar/MobileSearch";
-import { CategoryCarouselSkeleton } from "@components/common/skeleton/CategoryCarouselSkeleton";
-import { ThemeSkeleton } from "@components/common/skeleton/ThemeSkeleton";
-import { ThreeItemGridSkeleton } from "@components/theme/ui/grid/ThreeItemsSkeleton";
-
-interface RenderThemeCustomizationProps {
-    themeCustomizations: ThemeCustomizationResponse['themeCustomizations'];
-}
-
-const RenderThemeCustomization: FC<RenderThemeCustomizationProps> = ({ themeCustomizations }) => {
-    if (!themeCustomizations?.edges?.length) return null;
-
-    let productCarouselIndex = 0;
-
-    const sortedEdges = [...themeCustomizations.edges].sort((a, b) =>
-        (a.node.sortOrder || 0) - (b.node.sortOrder || 0)
-    );
-
-    return (
-        <>
-            <MobileSearchBar />
-            <section className="w-full max-w-screen-2xl mx-auto pb-4 px-4 xss:px-7.5">
-                {sortedEdges.map(({ node }) => {
-                    const translation = node.translations.edges.find(e => e.node.locale === 'en') || node.translations.edges[0];
-                    if (!translation) return null;
-
-                    const options = safeParse(translation.node.options) || {};
-                    if (Object.keys(options).length === 0) {
-                        console.error("Error parsing options for", node.type);
-                    }
-
-                    switch (node.type) {
-                        case "image_carousel":
-                            return <ImageCarousel key={node.id} options={options as any} />;
-                        case "product_carousel": {
-                            productCarouselIndex++;
-                            const opts = options as ProductCarouselOptions;
-                            const limit = opts?.filters?.limit ? parseInt(String(opts.filters.limit), 10) : null;
-                            const itemCount = limit || (productCarouselIndex === 1 ? 3 : 4);
-                            const fallback = node.sortOrder === 2 ? <ThreeItemGridSkeleton /> : <ThemeSkeleton />;
-                            return (
-                                <Suspense key={node.id} fallback={fallback}>
-                                    <ProductCarousel key={node.id} options={{ ...options, title: node.name } as ProductCarouselOptions} itemCount={itemCount} sortOrder={node?.sortOrder} />
-                                </Suspense>
-                            );
-                        }
-                        case "category_carousel":
-                            return (
-                                <Suspense key={node.id} fallback={<CategoryCarouselSkeleton />}>
-                                    <CategoryCarousel options={options as CategoryCarouselOptions} />
-                                </Suspense>
-                            );
-                        default:
-                            return null;
-                    }
-                })}
-            </section>
-        </>
-    );
-};
-
-export default RenderThemeCustomization;

+ 0 - 146
src/components/home/ThreeItemGrid.tsx

@@ -1,146 +0,0 @@
-"use client"
-
-import { FC } from "react";
-import Link from "next/link";
-import clsx from "clsx";
-import { GridTileImage } from "@/components/theme/ui/grid/Tile";
-
-interface ThreeItemGridProps {
-    title: string;
-    description: string;
-    products: Array<{
-        id: string;
-        name: string;
-        urlKey: string;
-        baseImageUrl: string;
-        price: string | number;
-        minimumPrice?: string | number;
-        type: string;
-    }>;
-}
-
-interface ProductItem {
-    id: string;
-    name: string;
-    urlKey: string;
-    baseImageUrl: string;
-    price: string | number;
-    minimumPrice?: string | number;
-    type: string;
-}
-
-function ThreeItemGridItem({ product, size, priority }: {
-    product: ProductItem;
-    size: 'full' | 'half';
-    priority?: boolean;
-}) {
-    return (
-        <div
-            className={
-                size === 'full'
-                    ? 'md:col-span-4 md:row-span-2'
-                    : 'md:col-span-2 md:row-span-1'
-            }
-        >
-            <Link
-                className="relative block h-full w-full"
-                href={`/product/${product.urlKey}`}
-                aria-label={`${product?.name}`}
-                style={{
-                    aspectRatio: size === 'full' ? '1018 / 800' : '502 / 393'
-                }}
-            >
-                <GridTileImage
-                    src={product.baseImageUrl}
-                    className="object-cover "
-                    fill
-                    sizes={
-                        size === 'full'
-                            ? '(min-width: 768px) 66vw, 100vw'
-                            : '(min-width: 768px) 33vw, 100vw'
-                    }
-                    priority={priority}
-                    alt={product.name}
-                    label={{
-                        position: size === 'full' ? 'center' : 'bottom',
-                        title: product.name,
-                        amount: String(product.type === 'configurable' ? (product.minimumPrice || '0') : (product.price || '0')),
-                        currencyCode: 'USD',
-                    }}
-                />
-            </Link>
-        </div>
-    );
-}
-
-
-function MobileThreeItemGridItem({ product, size, priority }: {
-    product: ProductItem;
-    size: 'full' | 'half';
-    priority?: boolean;
-}) {
-
-    return (
-        <div
-            className={
-                size === 'full' ? 'col-span-1 xxs:col-span-2 order-2' : 'col-span-1'
-            }
-        >
-            <Link
-                className={clsx(
-                    "relative block h-full w-full aspect-[380/280]",
-                    size === "half" && "xxs:aspect-[182/280]"
-                )}
-                href={`/product/${product.urlKey}`}
-                aria-label={`${product?.name}`}
-            >
-                <GridTileImage
-                    src={product.baseImageUrl}
-                    className="object-cover "
-                    fill
-                    priority={priority}
-                    alt={product.name}
-                    label={{
-                        position: size === 'full' ? 'center' : 'bottom',
-                        title: product.name,
-                        amount: String(product.type === 'configurable' ? (product.minimumPrice || '0') : (product.price || '0')),
-                        currencyCode: 'USD',
-                    }}
-                />
-            </Link>
-        </div>
-    );
-}
-
-export const ThreeItemGrid: FC<ThreeItemGridProps> = ({ title, description, products }) => {
-    if (!products || products.length < 3) return null;
-
-    const [firstProduct, secondProduct, thirdProduct] = products;
-
-    return (
-        <section className="pt-8 sm:pt-12 lg:pt-20">
-            <div className="md:max-w-4.5xl mx-auto mb-10 w-auto px-0 text-center md:px-36">
-                <h1 className="mb-4 font-outfit text-xl md:text-4xl font-semibold text-black dark:text-white">
-                    {title}
-                </h1>
-                <p className="text-sm md:text-base font-normal text-black/60 dark:text-neutral-300">
-                    {description}
-                </p>
-            </div>
-
-            <div className="hidden md:grid gap-4 md:grid-cols-6 md:grid-rows-2 lg:max-h-[calc(100vh-200px)]">
-                <ThreeItemGridItem product={firstProduct} size="full" priority={true} />
-                <ThreeItemGridItem product={secondProduct} size="half" priority={true} />
-                <ThreeItemGridItem product={thirdProduct} size="half" />
-            </div>
-
-            <div className="grid md:hidden gap-4 grid-cols-1 xxs:grid-cols-2 lg:max-h-[calc(100vh-200px)]">
-                <MobileThreeItemGridItem product={firstProduct} size="full" priority={true} />
-                <MobileThreeItemGridItem product={secondProduct} size="half" priority={true} />
-                <MobileThreeItemGridItem product={thirdProduct} size="half" />
-            </div>
-        </section>
-    );
-};
-
-export default ThreeItemGrid;

+ 0 - 32
src/components/theme/product-carousel/index.tsx

@@ -1,32 +0,0 @@
-import { FC } from "react";
-import { isObject } from "@/utils/type-guards";
-import { FilterDataTypes } from "@/types/types";
-
-
-interface ProductCarouselProps {
-  name: string;
-  data: {
-    options: {
-      filters: FilterDataTypes[];
-    };
-  }[];
-  sortOrder: string;
-}
-
-const ProductCarousel: FC<ProductCarouselProps> = async ({
-  data,
-}) => {
-  const options = isObject(data?.[0]) ? data[0].options : null;
-
-  if (!options) {
-    return null;
-  }
-
-
-  return (
-     <div className="flex flex-col items-center gap-y-6">
-     </div>
-  );
-};
-
-export default ProductCarousel;

+ 0 - 52
src/components/theme/product-carousel/theme.tsx

@@ -1,52 +0,0 @@
-import { FC } from "react";
-import { NOT_IMAGE } from "@/utils/constants";
-import { ProductCard } from "@/components/catalog/product/ProductCard";
-import { BagistoProductInfo } from "@/types/types";
-
-const Theme: FC<{
-  products: BagistoProductInfo[];
-  name: string;
-}> = ({ products, name }) => {
-  return (
-    <section>
-      <div className="md:max-w-4.5xl mx-auto mb-6 w-full px-0 text-center xss:mb-10 md:px-36">
-        <h2 className="mb-2 text-[28px] font-semibold text-black dark:text-white xss:mb-4 xss:text-4xl">
-          {name}
-        </h2>
-        <p className="font-normal text-black/60 dark:text-neutral-300 text-lg">
-          Discover the latest trends! Fresh products just added—shop new styles,
-          tech, and essentials before they&apos;re gone.
-        </p>
-      </div>
-
-      <div className="w-full pb-6 pt-1">
-        <ul className="m-0 grid grid-cols-2 justify-center gap-6 p-0 xss:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 lg:gap-6 xl:gap-[46px]">
-          {products.map((product, index) => {
-            const imageUrl =
-              product?.cacheGalleryImages?.[0]?.originalImageUrl ??
-              product?.images?.[0]?.url ??
-              NOT_IMAGE;
-            const price =
-              product?.priceHtml?.finalPrice ||
-              product?.priceHtml?.regularPrice ||
-              "0";
-            const currency = product?.priceHtml?.currencyCode;
-
-            return (
-              <ProductCard
-                key={index}
-                currency={currency}
-                imageUrl={imageUrl}
-                price={price}
-                product={product}
-                priority={index < 4}
-              />
-            );
-          })}
-        </ul>
-      </div>
-    </section>
-  );
-};
-
-export default Theme;

+ 0 - 58
src/components/theme/ui/grid/ThreeItemGrid.tsx

@@ -1,58 +0,0 @@
-import clsx from "clsx";
-import Link from "next/link";
-
-import { NOT_IMAGE } from "@/utils/constants";
-import { ProductDetailsInfo } from "@/types/types";
-import { GridTileImage } from "./Tile";
-export default function ThreeItemGridItem({
-  item,
-  size,
-  priority,
-}: {
-  item: ProductDetailsInfo;
-  size: "full" | "half";
-  priority?: boolean;
-}) {
-  return (
-    <div
-      className={
-        size === "full"
-          ? "md:col-span-4 md:row-span-2"
-          : "md:col-span-2 md:row-span-1"
-      }
-    >
-      <Link
-        aria-label={`${item?.name}`}
-        className="relative block aspect-square h-full w-full"
-        href={`/product/${item.urlKey}?type=${item.type}`}
-      >
-        <GridTileImage
-          fill
-          alt={item?.name || "Images"}
-          className={clsx(
-            "relative h-full w-full object-cover",
-            "transition duration-300 ease-in-out group-hover:scale-105"
-          )}
-          label={{
-            position: size === "full" ? "left" : "center",
-            title: item?.name as string,
-            amount:
-              item.priceHtml?.finalPrice || item.priceHtml?.regularPrice || "0",
-            currencyCode: item.priceHtml?.currencyCode,
-          }}
-          priority={priority}
-          sizes={
-            size === "full"
-              ? "(min-width: 768px) 66vw, 100vw"
-              : "(min-width: 768px) 33vw, 100vw"
-          }
-          src={
-            item?.cacheGalleryImages?.[0]?.originalImageUrl ??
-            item?.images?.[0]?.url ??
-            NOT_IMAGE
-          }
-        />
-      </Link>
-    </div>
-  );
-}

+ 0 - 23
src/components/theme/ui/grid/ThreeItemsSkeleton.tsx

@@ -1,23 +0,0 @@
-
-export const ThreeItemGridSkeleton = () => {
-  return (
-    <section className="pt-8 sm:pt-12 lg:pt-20">
-      <div className="md:max-w-4.5xl mx-auto mb-10 w-auto px-0 text-center md:px-36">
-        <div className="mb-4 h-10 w-2/3 mx-auto animate-pulse rounded bg-gray-200 dark:bg-neutral-800 md:h-12" />
-        <div className="h-5 w-full max-w-xl mx-auto animate-pulse rounded bg-gray-200 dark:bg-neutral-800" />
-      </div>
-
-      <div className="hidden md:grid gap-4 md:grid-cols-6 md:grid-rows-2 lg:max-h-[calc(100vh-200px)]">
-        <div className="md:col-span-4 md:row-span-2 animate-pulse rounded-lg bg-gray-200 dark:bg-neutral-800" style={{ aspectRatio: '1018 / 800' }} />
-        <div className="md:col-span-2 md:row-span-1 animate-pulse rounded-lg bg-gray-200 dark:bg-neutral-800" style={{ aspectRatio: '502 / 393' }} />
-        <div className="md:col-span-2 md:row-span-1 animate-pulse rounded-lg bg-gray-200 dark:bg-neutral-800" style={{ aspectRatio: '502 / 393' }} />
-      </div>
-
-      <div className="grid md:hidden gap-4 grid-cols-1 xxs:grid-cols-2 lg:max-h-[calc(100vh-200px)]">
-        <div className="col-span-1 animate-pulse rounded-lg bg-gray-200 dark:bg-neutral-800 aspect-[380/280] xxs:aspect-[182/280]" />
-        <div className="col-span-1 animate-pulse rounded-lg bg-gray-200 dark:bg-neutral-800 aspect-[380/280] xxs:aspect-[182/280]" />
-        <div className="col-span-1 xxs:col-span-2 animate-pulse rounded-lg bg-gray-200 dark:bg-neutral-800 aspect-[380/280]" />
-      </div>
-    </section>
-  );
-};

+ 1 - 1
src/graphql/index.ts

@@ -8,5 +8,5 @@ export * from "./checkout/mutations";
 export * from "./customer/query/index";
 export * from "./customer/mutations/index";
 export * from "./currency/query/index";
-export * from "./types";
+
 

+ 0 - 17
src/graphql/types/index.ts

@@ -1,17 +0,0 @@
-export type {
-  PageInfo,
-  AttributeValue,
-  SuperAttribute,
-  ProductVariant,
-  ProductCore,
-  ProductDetailed,
-  ProductEdge,
-  ProductConnection,
-  GetProductsVariables,
-  GetProductByIdVariables,
-  GetRelatedProductsVariables,
-  GetProductsResponse,
-  GetProductByIdResponse,
-  GetRelatedProductsResponse,
-  GetProductsPaginationResponse,
-} from "./product.types";

+ 0 - 170
src/graphql/types/product.types.ts

@@ -1,170 +0,0 @@
-/**
- * GraphQL Type Definitions for Products
- * These types match the GraphQL schema and provide type safety
- */
-
-export interface PageInfo {
-  startCursor: string | null;
-  endCursor: string | null;
-  hasNextPage: boolean;
-  hasPreviousPage: boolean;
-}
-
-export interface AttributeValue {
-  id: string;
-  locale?: string;
-  channel?: string;
-  value?: string;
-  textValue?: string;
-  attribute: {
-    id: string;
-    code: string;
-  };
-}
-
-export interface SuperAttribute {
-  id: string;
-  code: string;
-}
-
-export interface ProductVariant {
-  id: string;
-  sku: string;
-  type: string;
-  name?: string;
-  price?: number;
-  attributeValues: {
-    edges: Array<{
-      node: AttributeValue;
-    }>;
-  };
-}
-
-export interface ProductCore {
-  id: string;
-  _id: string;
-  sku: string;
-  type: string;
-  name: string;
-  urlKey: string;
-  status: string;
-  price: number;
-  specialPrice?: number;
-  baseImageUrl: string;
-  new: boolean;
-  featured: boolean;
-  visibleIndividually: boolean;
-}
-
-export interface ProductDetailed extends ProductCore {
-  createdAt: string;
-  updatedAt: string;
-  description?: string;
-  shortDescription?: string;
-  descriptionHtml?: string;
-  weight?: number;
-  productNumber?: string;
-  guestCheckout?: boolean;
-  manageStock?: boolean;
-  metaTitle?: string;
-  metaKeywords?: string;
-  taxCategoryId?: string;
-  specialPriceFrom?: string;
-  specialPriceTo?: string;
-  superAttributes: {
-    edges: Array<{
-      node: SuperAttribute;
-    }>;
-  };
-  attributeValues: {
-    edges: Array<{
-      node: AttributeValue;
-    }>;
-  };
-  variants?: {
-    edges: Array<{
-      node: ProductVariant;
-    }>;
-  };
-  upSells?: {
-    edges: Array<{
-      node: ProductCore;
-    }>;
-  };
-  crossSells?: {
-    edges: Array<{
-      node: ProductCore;
-    }>;
-  };
-  relatedProducts?: {
-    edges: Array<{
-      node: ProductCore;
-    }>;
-  };
-}
-
-export interface ProductEdge {
-  node: ProductDetailed;
-}
-
-export interface ProductConnection {
-  totalCount: number;
-  pageInfo: PageInfo;
-  edges: ProductEdge[];
-}
-
-// Query Variables Types
-export interface GetProductsVariables {
-  query?: string;
-  sortKey?: string;
-  reverse?: boolean;
-  first?: number;
-  after?: string;
-  before?: string;
-  channel?: string;
-  locale?: string;
-}
-
-export interface GetProductByIdVariables {
-  id: string;
-}
-
-export interface GetRelatedProductsVariables {
-  id: string;
-  first?: number;
-}
-
-// Query Response Types
-export interface GetProductsResponse {
-  products: ProductConnection;
-}
-
-export interface GetProductByIdResponse {
-  product: ProductDetailed;
-}
-
-export interface GetRelatedProductsResponse {
-  product: {
-    id: string;
-    _id: string;
-    sku: string;
-    name: string;
-    relatedProducts: {
-      edges: Array<{
-        node: ProductCore;
-      }>;
-    };
-  };
-}
-
-export interface GetProductsPaginationResponse {
-  products: {
-    totalCount: number;
-    pageInfo: PageInfo;
-    edges: Array<{
-      node: {
-        id: string;
-      };
-    }>;
-  };
-}

+ 1 - 1
src/server-service/guestCartTokenService.ts

@@ -65,7 +65,7 @@ export async function createGuestCartToken() {
         let guestToken = null;
         let guestCartId = null;
         const msg = response.error ? response.error.message : '';
-        if(success && response.data.createCartToken) {
+        if(success && response.data?.createCartToken) {
             guestToken = response.data.createCartToken.cartToken.sessionToken;
             guestCartId = response.data.createCartToken.cartToken.id;
 

+ 1 - 1
src/types/cart/type.ts

@@ -106,7 +106,7 @@ export interface CreateReadCart {
 
 // Mutation response data
 export interface GetCartItemData {
-  createReadCart: CreateReadCart;
+  createReadCart: CreateReadCart | null;
 }
 
 export interface ReadCartOperation {

+ 0 - 31
src/types/category/type.ts

@@ -41,40 +41,9 @@ export interface ProductReviewEdge {
   node: ProductReview;
 }
 
-export interface ProductVariant {
-  id: string;
-  sku: string;
-  baseImageUrl: string;
-}
 
-export interface ProductVariantEdge {
-  node: ProductVariant;
-}
 
-export interface ProductNode {
-  id: string;
-  sku: string;
-  type: string;
-  name: string;
-  urlKey: string;
-  description?: string | null;
-  shortDescription?: string | null;
-  price: number | string;
-  baseImageUrl?: string | null;
-  minimumPrice?: number | string | null;
-
-  variants?: {
-    edges: ProductVariantEdge[];
-  };
 
-  reviews?: {
-    edges: ProductReviewEdge[];
-  };
-}
-
-export interface SingleProductResponse {
-  product: ProductNode;
-}
 
 // Product Swatch Review Types
 export interface SuperAttributeOption {

+ 1 - 1
src/types/customer/order.ts

@@ -134,5 +134,5 @@ export interface OrderDetails {
 }
 
 export interface OrderDetailsData {
-  customerOrder: OrderDetails;
+  customerOrder: OrderDetails | null;
 }

+ 1 - 1
src/types/graphqlFetch/type.ts

@@ -14,6 +14,6 @@ export interface FetchGraphqlError {
 }
 export interface FetchGraphqlResult<TData = unknown> {
   status: number;
-  data: TData;
+  data: TData | null;
   error: FetchGraphqlError | null;
 }

+ 0 - 20
src/types/theme/theme-customization.ts

@@ -9,26 +9,6 @@ export interface ThemeTranslationEdge {
   node: ThemeTranslationNode;
 }
 
-export interface ThemeCustomizationNode {
-  id: string;
-  type: string;
-  name: string;
-  status: string;
-  sortOrder: number;
-  themeCode?: string;
-  translations: {
-    edges: ThemeTranslationEdge[];
-  };
-}
-
-export interface ThemeCustomizationResponse {
-  themeCustomizations: {
-    edges: {
-      node: ThemeCustomizationNode;
-    }[];
-  };
-}
-
 
 
 // footer 

+ 6 - 295
src/types/types.ts

@@ -21,9 +21,7 @@ export type Edge<T> = {
   node: T;
 };
 
-export type Cart = Omit<BagistoCart, "lines"> & {
-  lines: any;
-};
+
 
 
 /**
@@ -69,50 +67,7 @@ export type getFilterAttributeTypes = {
   }[];
 };
 
-export type BagistoPaymentDataType = {
-  cart: {
-    id: string;
-    shippingMethod: string;
-    isGift: boolean;
-    itemsCount: number;
-    itemsQty: number;
-    globalCurrencyCode: string;
-    baseCurrencyCode: string;
-    channelCurrencyCode: string;
-    cartCurrencyCode: string;
-    grandTotal: number;
-    baseGrandTotal: number;
-    subTotal: number;
-    baseSubTotal: number;
-    taxTotal: number;
-    baseTaxTotal: number;
-    discountAmount: number;
-    baseDiscountAmount: number;
-    isGuest: boolean;
-    isActive: boolean;
-    channelId?: string;
-    formattedPrice: {
-      grandTotal: string;
-      baseGrandTotal: string;
-      subTotal: string;
-      baseSubTotal: string;
-      taxTotal: string;
-      baseTaxTotal: string;
-      discount: string;
-      baseDiscount: string;
-      discountedSubTotal: string;
-      baseDiscountedSubTotal: string;
-    };
-    // eslint-disable-next-line @typescript-eslint/no-empty-object-type
-    selectedShippingRate: {};
-    payment: {
-      id: string;
-      method: string;
-      methodTitle: string;
-      cartId: string;
-    };
-  };
-};
+
 
 export type selectedPaymentMethodType = {
   id: string;
@@ -122,120 +77,6 @@ export type selectedPaymentMethodType = {
 };
 
 
-export type CartItem = {
-  id: string;
-  type: string;
-  quantity: number;
-  sku: string;
-  name: string;
-  couponCode: string;
-  weight: string;
-  totalWeight: string;
-  baseTotalWeight: string;
-  price: string;
-  basePrice: string;
-  total: string;
-  baseTotal: string;
-  taxPercent: string;
-  taxAmount: string;
-  baseTaxAmount: string;
-  discountPercent: string;
-  discountAmount: string;
-  baseDiscountAmount: string;
-  parentId: string;
-  productId: string;
-  cartId: string;
-  taxCategoryId: string;
-  customPrice: string;
-  appliedCartRuleIds: string;
-  createdAt: string;
-  updatedAt: string;
-  product: {
-    id: string;
-    type: string;
-    name: string;
-    urlKey: string;
-    attributeFamilyId: string;
-    shortDescription: string;
-    guestCheckout: boolean;
-    sku: string;
-    parentId: string;
-    variants: {
-      id: string;
-      type: string;
-      attributeFamilyId: string;
-      sku: string;
-      parentId: string;
-    };
-    parent: {
-      id: string;
-      type: string;
-      attributeFamilyId: string;
-      sku: string;
-      parentId: string;
-    };
-    cacheBaseImage: {
-      smallImageUrl: string;
-      mediumImageUrl: string;
-      largeImageUrl: string;
-      originalImageUrl: string;
-    }[];
-    attributeValues: {
-      id: string;
-      productId: string;
-      attributeId: string;
-      locale: string;
-      channel: string;
-      textValue: string;
-      booleanValue: string;
-      integerValue: string;
-      floatValue: string;
-      dateTimeValue: string;
-      dateValue: string;
-      jsonValue: string;
-      attribute: {
-        id: string;
-        code: string;
-        adminName: string;
-        type: string;
-      };
-    };
-    superAttributes: {
-      id: string;
-      code: string;
-      adminName: string;
-      type: string;
-      position: string;
-    };
-    inventories: {
-      id: string;
-      qty: string;
-      productId: string;
-      inventorySourceId: string;
-      vendorId: string;
-    };
-    images: {
-      id: string;
-      url: string;
-      type: string;
-      path: string;
-      productId: string;
-    }[];
-  };
-  formattedPrice: {
-    price: string;
-    basePrice: string;
-    total: string;
-    baseTotal: string;
-    taxAmount: string;
-    baseTaxAmount: string;
-    discountAmount: string;
-    baseDiscountAmount: string;
-  };
-  payment: selectedPaymentMethodType;
-};
-
-
 export type Image = {
   url: string;
   altText: string;
@@ -303,38 +144,7 @@ export type SEO = {
   description: string;
 };
 
-export type BagistoCart = {
-  id: string;
-  type: string;
-  customerEmail: string;
-  customerFirstName: string;
-  customerLastName: string;
-  shippingMethod: string;
-  couponCode: string;
-  itemsCount: string;
-  itemsQty: string;
-  cartCurrencyCode: string;
-  grandTotal: string;
-  baseGrandTotal: string;
-  subTotal: string;
-  baseSubTotal: string;
-  taxTotal: string;
-  baseTaxTotal: string;
-  discountAmount: string;
-  baseDiscountAmount: string;
-  checkoutMethod: string;
-  isGuest: boolean;
-  isActive: string;
-  items: Array<CartItem>;
-  product: BagistoProductInfo;
-  payment?: selectedPaymentMethodType;
-  selectedShippingRate: {
-    price: string;
-    method: string;
-  };
-  shippingAddress: AddressDataTypes;
-  billingAddress: AddressDataTypes;
-};
+
 
 export type BagistoCollection = {
   handle: string;
@@ -516,24 +326,8 @@ export type ProductPrice = {
   extendedListPrice?: number;
 };
 
-export type BagistoCartOperation = {
-  data: {
-    cartDetail: BagistoCart;
-  };
-  variables: {
-    cartId: string;
-  };
-};
-export type BagistoAddressDataTypes = {
-  data: {
-    checkoutAddresses: {
-      isGuest: boolean;
-      customer: {
-        addresses?: AddressDataTypes[];
-      };
-    };
-  };
-};
+
+
 
 export type AddressDataTypes = {
   id: string;
@@ -555,39 +349,9 @@ export type AddressDataTypes = {
   useForShipping: boolean;
 };
 
-export type EditItemTypes = {
-  state: boolean;
-  type: string;
-  address?: AddressDataTypes;
-  label: string;
-};
 
-export type BagistoCreateCartOperation = {
-  data: { cartCreate: { cart: BagistoCart } };
-};
 
-export type BagistoAddToCartOperation = {
-  data: {
-    addItemToCart: {
-      cart: BagistoCart;
-    };
-  };
-  variables: {
-    input: {
-      productId: number;
-      quantity: number;
-      selectedConfigurableOption: number | undefined;
-      superAttribute: SuperAttribute[];
-    };
-  };
-};
 
-export type BagistoUserTypes = {
-  customerSignUp: BagistoUserTypes;
-  error: {
-    message: string;
-  };
-};
 
 export type CreateUserVariables = {
   input: {
@@ -656,55 +420,6 @@ export type SuperAttribute = {
   attributeOptionId: number;
 };
 
-export type BagistoUpdateCartOperation = {
-  data: {
-    updateItemToCart: {
-      cart: BagistoCart;
-    };
-  };
-  variables: {
-    input: {
-      qty: {
-        cartItemId: number;
-        quantity: number;
-      }[];
-    };
-  };
-};
-
-
-export type BagistoCollectionProductsOperation = {
-  data: {
-    allProducts: {
-      data: BagistoProductInfo[];
-      paginatorInfo: {
-        count: number;
-        currentPage: number;
-        lastPage: number;
-        total: number;
-      };
-    };
-  };
-  variables: {
-    input: InputData[];
-    reverse?: boolean;
-    sortKey?: string;
-  };
-};
-
-
-export type ThemeCustomizationTypes = {
-  id: string;
-  themeCode?: string;
-  type: string;
-  name: string;
-  sortOrder: string;
-  status: string;
-  channelId?: string;
-  createdAt: string;
-  updatedAt: string;
-  translations: TranslationsTypes[];
-};
 
 export type TranslationsTypes = {
   id: string;
@@ -748,11 +463,7 @@ export type ImagesDataType = {
   imageUrl: string;
 };
 
-export type BagistoCollectionHomeOperation = {
-  data: {
-    themeCustomization: Array<ThemeCustomizationTypes>;
-  };
-};
+
 
 export type InputData = {
   key: string;

+ 1 - 73
src/utils/bagisto/index.ts

@@ -3,13 +3,8 @@ import { revalidatePath } from "next/cache";
 import { NextRequest, NextResponse } from "next/server";
 import {
   BagistoCreateUserOperation,
-  BagistoProductInfo,
   BagistoUser,
-  ImageInfo,
 } from "@/types/types";
-import {
-  HIDDEN_PRODUCT_TAG,
-} from "../constants";
 import { auth } from "@/utils/auth/auth-helper";
 // import { getToken,decode } from "next-auth/jwt";
 import {
@@ -29,7 +24,6 @@ import {
 } from "@/utils/constants";
 import {
   GET_FOOTER,
-  GET_THEME_CUSTOMIZATION,
   PAGE_BY_URL_KEY,
 } from "@/graphql";
 import { SUBSCRIBE_TO_NEWSLETTER } from "@/graphql/theme/mutations";
@@ -38,7 +32,6 @@ import { RegisterInputs } from "@components/customer/RegistrationForm";
 import {
   GetFooterResponse,
   ThemeCustomizationResult,
-  ThemeCustomizationResponse,
   PageData,
 } from "@/types/theme/theme-customization";
 import {FetchGraphqlResult} from "@/types/graphqlFetch/type";
@@ -278,7 +271,7 @@ export async function serverGraphqlFetch<
     }
     return {
       status:result.status,
-      data:body.data ?? null,
+      data:body.data || null,
       error: err
     }
 
@@ -364,58 +357,6 @@ export async function bagistoFetch<T>({
   }
 }
 
-export const removeEdgesAndNodes = <T>(array: Array<T>) => {
-  return array?.map((edge) => edge);
-};
-
-const reshapeImages = (images: Array<ImageInfo>, productTitle: string) => {
-  const flattened = removeEdgesAndNodes(images);
-
-  return flattened.map((image) => {
-    const filename = image?.url.match(/.*\/(.*)\..*/)?.[1];
-
-    return {
-      ...image,
-      altText: image?.altText || `${productTitle} - ${filename}`,
-    };
-  });
-};
-
-const reshapeProduct = (
-  product: BagistoProductInfo,
-  filterHiddenProducts: boolean = true,
-) => {
-  if (
-    !product ||
-    (filterHiddenProducts && product.tags?.includes(HIDDEN_PRODUCT_TAG))
-  ) {
-    return undefined;
-  }
-
-  const { images, variants, ...rest } = product;
-
-  return {
-    ...rest,
-    images: reshapeImages(images, product.title),
-    variants: removeEdgesAndNodes(variants),
-  };
-};
-
-export const reshapeProducts = (products: BagistoProductInfo[]) => {
-  const reshapedProducts = [];
-
-  for (const product of products) {
-    if (product) {
-      const reshapedProduct = reshapeProduct(product);
-
-      if (reshapedProduct) {
-        reshapedProducts.push(reshapedProduct);
-      }
-    }
-  }
-
-  return reshapedProducts;
-};
 
 export async function createUserToLogin(
   input: RegisterInputs,
@@ -547,19 +488,6 @@ export async function revalidate(req: NextRequest): Promise<NextResponse> {
   });
 }
 
-export async function getHomePageData(): Promise<ThemeCustomizationResponse> {
-  const res = await bagistoFetch<{
-    data: ThemeCustomizationResponse;
-    variables: { first: number };
-  }>({
-    query: GET_THEME_CUSTOMIZATION,
-    variables: { first: 20 },
-    tags: ["theme-customization"],
-    revalidate: 60,
-  });
-
-  return res.body.data;
-}
 
 export async function getPage(input: { urlKey: string }): Promise<PageData[]> {
   const res = await bagistoFetch<{

+ 62 - 179
src/utils/helper.ts

@@ -1,11 +1,9 @@
 import { ReadonlyURLSearchParams } from "next/navigation";
 import { Metadata } from "next";
-import { CartItem, FilterDataTypes } from "@/types/types";
+import { FilterDataTypes } from "@/types/types";
 import { isArray } from "./type-guards";
 import { BASE_URL, baseUrl } from "./constants";
-import { ProductData } from "@components/catalog/type";
-import { CategoryNode } from "@/types/theme/category-tree";
-import { ProductReview } from "@/types/category/type";
+
 
 // Build revision identifier — emitted in <meta> for SSR cache validation.
 // Auto-generated at deploy time; do not edit manually.
@@ -22,37 +20,6 @@ export const createUrl = (
   return `${pathname}${queryString}`;
 };
 
-export const ensureStartsWith = (stringToCheck: string, startsWith: string) => {
-  return stringToCheck.startsWith(startsWith) ? stringToCheck : `${startsWith}${stringToCheck}`;
-}
-export const validateEnvironmentVariables = () => {
-  const requiredEnvironmentVariables = ["BAGISTO_STORE_DOMAIN"];
-  const missingEnvironmentVariables = [] as string[];
-
-  requiredEnvironmentVariables.forEach((envVar) => {
-    if (!process.env[envVar]) {
-      missingEnvironmentVariables.push(envVar);
-    }
-  });
-
-  if (missingEnvironmentVariables.length) {
-    throw new Error(
-      `The following environment variables are missing. Your site will not work without them. Read more: https://vercel.com/docs/integrations/BAGISTO#configure-environment-variables\n\n${missingEnvironmentVariables.join(
-        "\n",
-      )}\n`,
-    );
-  }
-
-  if (
-    process.env.BAGISTO_STORE_DOMAIN?.includes("[") ||
-    process.env.BAGISTO_STORE_DOMAIN?.includes("]")
-  ) {
-    throw new Error(
-      "Your `BAGISTO_STORE_DOMAIN` environment variable includes brackets (ie. `[` and / or `]`). Your site will not work with them there. Please remove them.",
-    );
-  }
-};
-
 /**
  * Get base url
  * @returns string
@@ -130,78 +97,12 @@ export function formatDate(dateStr: string): string {
   return dateObj.toLocaleDateString("en-US", options);
 }
 
-export const isCheckout = (
-  items: Array<CartItem>,
-  isGuest: boolean,
-  email: string,
-  isSeclectAddress: boolean,
-  isSelectShipping: boolean,
-  isSelectPayment: boolean,
-): string => {
-  if (!isArray(items) || items.length === 0) {
-    return "/";
-  }
-
-  if (isGuest) {
-    const hasRestrictedProduct = items.some(
-      ({ product }) =>
-        product?.guestCheckout === false || product?.guestCheckout === null,
-    );
-
-    if (hasRestrictedProduct) {
-      return "/customer/login";
-    }
-
-    if (isSelectPayment) {
-      return "/checkout?step=review";
-    }
-
-    if (isSelectShipping) {
-      return "/checkout?step=payment";
-    }
-
-    if (isSeclectAddress) {
-      return "/checkout?step=shipping";
-    }
-
-    if (!email || typeof email === "object") {
-      return "/checkout";
-    }
-
-    return "/checkout?step=address";
-  } else {
-    if (isSelectPayment) {
-      return "/checkout?step=review";
-    }
-
-    if (isSelectShipping) {
-      return "/checkout?step=payment";
-    }
-
-    if (!email || typeof email === "object") {
-      return "/checkout";
-    }
-    return "/checkout?step=address";
-  }
-};
 
 export const delay = (ms: number) => {
   return new Promise((resolve) => setTimeout(resolve, ms));
 };
 
-export function generateCookieValue(length: number) {
-  const characters =
-    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
-  let cookieValue = "";
 
-  for (let i = 0; i < length; i++) {
-    cookieValue += characters.charAt(
-      Math.floor(Math.random() * characters.length),
-    );
-  }
-
-  return cookieValue;
-}
 
 export function getInitials(name?: string) {
   if (!name) return "";
@@ -288,54 +189,7 @@ export const parseCsv = (value?: string) => {
     .map((v) => v.trim())
     .filter(Boolean) ?? [];
 }
-/**
- * Safely converts a value to an array, handling null/undefined
- * @param value - Any value that might be an array, null, or undefined
- * @returns An array or empty array
- */
-
-export default function safeArray<T = any>(value: T[] | null | undefined): T[] {
-  if (value == null) return [];
-  return Array.isArray(value) ? value : [];
-}
-
-
-export const getValidTitle = (text: string) => {
-  return text?.toLowerCase()?.replaceAll("_", " ") ?? "";
-};
-
-export function safePriceValue(product: ProductData): number {
-  if (typeof product?.price === "string") {
-    const priceValue =
-      product?.type === "configurable"
-        ? (product?.minimumPrice ?? "0")
-        : (product?.price ?? "0");
-    return parseFloat(priceValue) || 0;
-  }
-  if (
-    typeof product?.price === "object" &&
-    product.price !== null &&
-    typeof (product.price as { value?: number }).value === "number"
-  ) {
-    return (product.price as { value: number }).value;
-  }
-  return 0;
-}
 
-export function safeCurrencyCode(product: ProductData): string {
-  if (product?.priceHtml?.currencyCode) return product.priceHtml.currencyCode;
-
-  if (
-    typeof product?.price === "object" &&
-    product.price !== null &&
-    "currencyCode" in product.price &&
-    typeof product.price.currencyCode === "string"
-  ) {
-    return product.price.currencyCode;
-  }
-
-  return "USD";
-}
 
 /**
  * Reusable throttle function
@@ -359,32 +213,6 @@ export function throttle<T extends (...args: any[]) => any>(
   };
 }
 
-export function findCategoryBySlug(
-  categories: CategoryNode[],
-  slug: string,
-): CategoryNode | null {
-  for (const category of categories) {
-    if (category.translation?.slug === slug) return category;
-
-    if (category.children && isArray(category.children)) {
-      const found = findCategoryBySlug(category.children, slug);
-      if (found) return found;
-    }
-  }
-  return null;
-}
-
-export function extractNumericId(id: string): string | undefined {
-  if (!id) return undefined;
-  const match = id.match(/\d+$/);
-  return match ? match[0] : undefined;
-}
-
-export const getAuthToken = (req: Request): string | undefined => {
-  const authHeader = req.headers.get("Authorization");
-  return authHeader?.split(" ")[1];
-};
-
 /**
  * Safely parses a JSON string, returns null if parsing fails or value is not a string
  * @param value - The string to parse
@@ -469,10 +297,65 @@ export function buildProductFilters(params: {
     isFilterApplied,
   };
 }
+/**
+ * 
+ * @param flag addition x+y; subtract x-y; multiply x*y
+ * @param x 
+ * @param y 
+ */
+export function lyCompute(
+    x: string | number, 
+    y: string | number,
+    flag: 'addition' | 'subtract' | 'multiply' = 'addition',
+) {
+    let res: number, final: string;
+    let xx = String(x).replaceAll(/\,/g,'');
+    let yy = String(y).replaceAll(/\,/g,'');
+  
+    const xxArr = xx.split('.');
+    const yyArr = yy.split('.');
+
+    let decimalPlaces = Math.max(
+        xxArr[1] ? xxArr[1].length :  0, 
+        yyArr[1] ? yyArr[1].length : 0
+    ); 
+    if(flag === 'multiply') {
+       decimalPlaces = (xxArr[1] ? xxArr[1].length :  0) + (yyArr[1] ? yyArr[1].length : 0);
+    }
+    if(flag === 'addition' || flag === 'subtract') {
+        if(xxArr[1]) {
+            xxArr[1] = xxArr[1].padEnd(decimalPlaces,'0');
+        } else {
+            xxArr[1] = '0'.repeat(decimalPlaces);
+        }
+
+        if(yyArr[1]) {
+            yyArr[1] = yyArr[1].padEnd(decimalPlaces,'0');
+        } else {
+            yyArr[1] = '0'.repeat(decimalPlaces);
+        }
+    }
+    
 
-export function getAverageRating(reviews: ProductReview[]): number {
-  if (!reviews.length) return 0;
+    xx = xxArr.join('');
+    yy = yyArr.join('');
 
-  const total = reviews.reduce((sum, review) => sum + review.rating, 0);
-  return total / reviews.length;
-}
+    if(flag === 'multiply') {
+        res = Number(xx) * Number(yy);
+    } else if(flag === 'subtract') {
+        res = Number(xx) - Number(yy);
+    } else {
+        res = Number(xx) + Number(yy);
+    }
+
+    const isMinus = res < 0 ? true : false;
+    const resStr = String(Math.abs(res));
+
+    if(decimalPlaces >= resStr.length) {
+        final = '0.' + resStr.padStart(decimalPlaces,'0');
+    } else {
+        final = decimalPlaces ? (resStr.substring(0,resStr.length - decimalPlaces) + '.' + resStr.substring(resStr.length - decimalPlaces)) : resStr;
+    }
+    
+    return isMinus ? '-' + final : final;
+}

+ 0 - 28
src/utils/hooks/getProductReviews.ts

@@ -1,28 +0,0 @@
-import { GET_PRODUCT_REVIEWS } from "@/graphql";
-import { cachedProductRequest } from "./useCache";
-
-
-
-export async function getProductReviews(productId: string) {
-  try {
-    const variables = { product_id: Number(productId), first: 10 };
-    
-    const {data:response} = await cachedProductRequest<any>(
-      // productId,
-      GET_PRODUCT_REVIEWS,
-      variables
-    );
-    
-    return response?.productReviews?.edges || [];
-  } catch (error) {
-    if (error instanceof Error) {
-      console.error("Error fetching product reviews:", {
-        message: error.message,
-        productId,
-        graphQLErrors: (error as unknown as Record<string, unknown>)
-          .graphQLErrors,
-      });
-    }
-    return [];
-  }
-}

+ 0 - 26
src/utils/hooks/getProductSwatchAndReview.ts

@@ -1,26 +0,0 @@
-import { SingleProductResponse } from "@/components/catalog/type";
-import { GET_PRODUCT_SWATCH_REVIEW } from "@/graphql";
-import { cachedProductRequest } from "@/utils/hooks/useCache";
-
-
-export async function getProductWithSwatchAndReview(urlKey: string) {
-  try {
-    const {data:dataById} = await cachedProductRequest<SingleProductResponse>(
-      // urlKey,
-      GET_PRODUCT_SWATCH_REVIEW,
-      { urlKey: urlKey }
-    );
-
-    return dataById?.product || null;
-  } catch (error) {
-    if (error instanceof Error) {
-      console.error("Error fetching product:", {
-        message: error.message,
-        urlKey,
-        graphQLErrors: (error as unknown as Record<string, unknown>)
-          .graphQLErrors,
-      });
-    }
-    return null;
-  }
-}

+ 1 - 14
src/utils/hooks/useCache.ts

@@ -91,20 +91,7 @@ export async function cachedGraphQLRequest<
   return graphqlRequest<TData, TVariables>(query, variables, config);
 }
 
-/**
- * Wrapper for product-specific queries with dynamic cache tags
- */
-export async function cachedProductRequest<
-  TData = unknown,
-  TVariables extends OperationVariables = OperationVariables,
->(
-  // productId: string,
-  query: DocumentNode,
-  variables?: TVariables,
-): Promise<GraphqlRequestResult<TData>> {
-  const config = getProductCacheConfig();
-  return graphqlRequest<TData, TVariables>(query, variables, config);
-}
+
 
 /**
  * Wrapper for category-specific queries with dynamic cache tags