online cart
This commit is contained in:
@@ -1,3 +1,4 @@
|
|||||||
|
import { useState } from "react";
|
||||||
import { useGetProfile } from "@/app/[name]/(Profile)/profile/hooks/userProfileData";
|
import { useGetProfile } from "@/app/[name]/(Profile)/profile/hooks/userProfileData";
|
||||||
import { useReceiptStore } from "@/zustand/receiptStore";
|
import { useReceiptStore } from "@/zustand/receiptStore";
|
||||||
import {
|
import {
|
||||||
@@ -10,6 +11,9 @@ import {
|
|||||||
export const useCart = () => {
|
export const useCart = () => {
|
||||||
const { isSuccess } = useGetProfile();
|
const { isSuccess } = useGetProfile();
|
||||||
const { clear, increment, decrement, items } = useReceiptStore();
|
const { clear, increment, decrement, items } = useReceiptStore();
|
||||||
|
const [loadingItems, setLoadingItems] = useState<Set<string | number>>(
|
||||||
|
new Set()
|
||||||
|
);
|
||||||
const { mutate: mutateIncrementCart } = useIncrementCart();
|
const { mutate: mutateIncrementCart } = useIncrementCart();
|
||||||
const { mutate: mutateDecrementCart } = useDecrementCart();
|
const { mutate: mutateDecrementCart } = useDecrementCart();
|
||||||
const { mutate: mutateClearCart } = useClearCart();
|
const { mutate: mutateClearCart } = useClearCart();
|
||||||
@@ -17,7 +21,23 @@ export const useCart = () => {
|
|||||||
|
|
||||||
const addToCart = (id: string | number) => {
|
const addToCart = (id: string | number) => {
|
||||||
if (isSuccess) {
|
if (isSuccess) {
|
||||||
mutateIncrementCart(id);
|
setLoadingItems((prev) => new Set(prev).add(id));
|
||||||
|
mutateIncrementCart(id, {
|
||||||
|
onSuccess: () => {
|
||||||
|
setLoadingItems((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
next.delete(id);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
setLoadingItems((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
next.delete(id);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
increment(id);
|
increment(id);
|
||||||
}
|
}
|
||||||
@@ -25,7 +45,23 @@ export const useCart = () => {
|
|||||||
|
|
||||||
const removeFromCart = (id: string | number) => {
|
const removeFromCart = (id: string | number) => {
|
||||||
if (isSuccess) {
|
if (isSuccess) {
|
||||||
mutateDecrementCart(id);
|
setLoadingItems((prev) => new Set(prev).add(id));
|
||||||
|
mutateDecrementCart(id, {
|
||||||
|
onSuccess: () => {
|
||||||
|
setLoadingItems((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
next.delete(id);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
setLoadingItems((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
next.delete(id);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
decrement(id);
|
decrement(id);
|
||||||
}
|
}
|
||||||
@@ -41,12 +77,23 @@ export const useCart = () => {
|
|||||||
|
|
||||||
const getCartItems = () => {
|
const getCartItems = () => {
|
||||||
if (isSuccess) {
|
if (isSuccess) {
|
||||||
return cartItems;
|
if (!cartItems?.data?.items) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
return cartItems.data.items.reduce((acc, item) => {
|
||||||
|
acc[item.foodId] = { quantity: item.quantity };
|
||||||
|
return acc;
|
||||||
|
}, {} as Record<string | number, { quantity: number }>);
|
||||||
} else {
|
} else {
|
||||||
return items;
|
return items;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const isItemLoading = (id: string | number) => {
|
||||||
|
if (!isSuccess) return false;
|
||||||
|
return loadingItems.has(id);
|
||||||
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
items: getCartItems(),
|
items: getCartItems(),
|
||||||
increment,
|
increment,
|
||||||
@@ -55,5 +102,6 @@ export const useCart = () => {
|
|||||||
addToCart,
|
addToCart,
|
||||||
removeFromCart,
|
removeFromCart,
|
||||||
clearCart,
|
clearCart,
|
||||||
|
isItemLoading,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,27 +1,43 @@
|
|||||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import * as api from "../service/CartService";
|
import * as api from "../service/CartService";
|
||||||
|
|
||||||
export const useBulkCart = () => {
|
export const useBulkCart = () => {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: api.bulkCart,
|
mutationFn: api.bulkCart,
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["cart-items"] });
|
||||||
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useIncrementCart = () => {
|
export const useIncrementCart = () => {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: api.increment,
|
mutationFn: api.increment,
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["cart-items"] });
|
||||||
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useDecrementCart = () => {
|
export const useDecrementCart = () => {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: api.decrement,
|
mutationFn: api.decrement,
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["cart-items"] });
|
||||||
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useClearCart = () => {
|
export const useClearCart = () => {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: api.clear,
|
mutationFn: api.clear,
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["cart-items"] });
|
||||||
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { api } from "@/config/axios";
|
import { api } from "@/config/axios";
|
||||||
import { BulkCartItem } from "../types/Types";
|
import { BulkCartItem, CartResponse } from "../types/Types";
|
||||||
|
|
||||||
export const bulkCart = async (params: BulkCartItem) => {
|
export const bulkCart = async (params: BulkCartItem) => {
|
||||||
const { data } = await api.post("/public/cart/items/bulk", params);
|
const { data } = await api.post("/public/cart/items/bulk", params);
|
||||||
@@ -21,7 +21,7 @@ export const clear = async () => {
|
|||||||
return data;
|
return data;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getCartItems = async () => {
|
export const getCartItems = async (): Promise<CartResponse> => {
|
||||||
const { data } = await api.get("/public/cart");
|
const { data } = await api.get<CartResponse>("/public/cart");
|
||||||
return data;
|
return data;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,36 @@
|
|||||||
|
import { BaseResponse } from "@/app/[name]/(Main)/types/Types";
|
||||||
|
|
||||||
export type BulkCartItem = {
|
export type BulkCartItem = {
|
||||||
items: {
|
items: {
|
||||||
foodId: string;
|
foodId: string;
|
||||||
quantity: number;
|
quantity: number;
|
||||||
}[];
|
}[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export interface CartItem {
|
||||||
|
foodId: string;
|
||||||
|
foodTitle: string;
|
||||||
|
quantity: number;
|
||||||
|
price: number;
|
||||||
|
discount: number;
|
||||||
|
totalPrice: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CartData {
|
||||||
|
userId: string;
|
||||||
|
restaurantId: string;
|
||||||
|
restaurantName: string;
|
||||||
|
items: CartItem[];
|
||||||
|
deliveryFee: number;
|
||||||
|
subTotal: number;
|
||||||
|
itemsDiscount: number;
|
||||||
|
couponDiscount: number;
|
||||||
|
totalDiscount: number;
|
||||||
|
tax: number;
|
||||||
|
total: number;
|
||||||
|
totalItems: number;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CartResponse = BaseResponse<CartData>;
|
||||||
|
|||||||
@@ -4,18 +4,28 @@ import { memo, useMemo } from "react";
|
|||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import PlusIcon from "@/components/icons/PlusIcon";
|
import PlusIcon from "@/components/icons/PlusIcon";
|
||||||
import MinusIcon from "@/components/icons/MinusIcon";
|
import MinusIcon from "@/components/icons/MinusIcon";
|
||||||
import { useReceiptStore } from "@/zustand/receiptStore";
|
import { useCart } from "@/app/[name]/(Dialogs)/cart/hook/useCart";
|
||||||
import { motion } from "framer-motion";
|
import { motion } from "framer-motion";
|
||||||
import type { Food } from "@/app/[name]/(Main)/types/Types";
|
import type { Food } from "@/app/[name]/(Main)/types/Types";
|
||||||
|
import { Refresh } from "iconsax-react";
|
||||||
|
import { useGetProfile } from "@/app/[name]/(Profile)/profile/hooks/userProfileData";
|
||||||
|
|
||||||
interface MenuItemProps {
|
interface MenuItemProps {
|
||||||
food: Food;
|
food: Food;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MenuItem = ({ food }: MenuItemProps) => {
|
const MenuItem = ({ food }: MenuItemProps) => {
|
||||||
|
const { isSuccess } = useGetProfile();
|
||||||
|
const { items, addToCart, removeFromCart, isItemLoading } = useCart();
|
||||||
|
const isLoading = isItemLoading(food.id);
|
||||||
|
|
||||||
const quantity = useReceiptStore(state => state.items[food.id]?.quantity || 0);
|
const quantity = useMemo(() => {
|
||||||
const increment = useReceiptStore(state => state.increment);
|
const item = items?.[food.id];
|
||||||
const decrement = useReceiptStore(state => state.decrement);
|
if (item && typeof item === 'object' && 'quantity' in item) {
|
||||||
|
return item.quantity || 0;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}, [items, food.id]);
|
||||||
|
|
||||||
const fallbackImage = "/assets/images/food-preview.png";
|
const fallbackImage = "/assets/images/food-preview.png";
|
||||||
const resolvedImage = useMemo(() => {
|
const resolvedImage = useMemo(() => {
|
||||||
@@ -28,17 +38,37 @@ const MenuItem = ({ food }: MenuItemProps) => {
|
|||||||
return fallbackImage;
|
return fallbackImage;
|
||||||
}, [food.image, food.images]);
|
}, [food.image, food.images]);
|
||||||
|
|
||||||
const foodName = food.name || food.title || food.foodName || 'بدون نام';
|
const foodName = useMemo(
|
||||||
const foodDescription = food.description || food.desc || food.content || '';
|
() => food.name || food.title || food.foodName || 'بدون نام',
|
||||||
|
[food.name, food.title, food.foodName]
|
||||||
|
);
|
||||||
|
|
||||||
|
const foodDescription = useMemo(
|
||||||
|
() => food.description || food.desc || food.content || '',
|
||||||
|
[food.description, food.desc, food.content]
|
||||||
|
);
|
||||||
|
|
||||||
|
const formattedPrice = useMemo(
|
||||||
|
() => (food.price ? food.price.toLocaleString('fa-IR') : '0'),
|
||||||
|
[food.price]
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleAddToCart = () => {
|
||||||
|
addToCart(food.id);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemoveFromCart = () => {
|
||||||
|
removeFromCart(food.id);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex gap-4 w-full h-full">
|
<div className="flex gap-4 w-full h-full">
|
||||||
<Image
|
<Image
|
||||||
className="rounded-xl w-28 h-28"
|
className="rounded-xl w-28 h-28 object-cover"
|
||||||
src={resolvedImage}
|
src={resolvedImage}
|
||||||
height={100}
|
height={112}
|
||||||
width={100}
|
width={112}
|
||||||
alt="Food image"
|
alt={foodName}
|
||||||
/>
|
/>
|
||||||
<div className="w-full inline-flex flex-col justify-between">
|
<div className="w-full inline-flex flex-col justify-between">
|
||||||
<div>
|
<div>
|
||||||
@@ -53,25 +83,44 @@ const MenuItem = ({ food }: MenuItemProps) => {
|
|||||||
</div>
|
</div>
|
||||||
<div className="inline-flex gap-2 justify-between w-full items-center">
|
<div className="inline-flex gap-2 justify-between w-full items-center">
|
||||||
<span className="w-full text-sm mt-1" dir="ltr">
|
<span className="w-full text-sm mt-1" dir="ltr">
|
||||||
{food.price ? food.price.toLocaleString('fa-IR') : '0'} T
|
{formattedPrice} T
|
||||||
</span>
|
</span>
|
||||||
<motion.div
|
<motion.div
|
||||||
whileTap={{ scale: 1.05 }}
|
whileTap={{ scale: 1.05 }}
|
||||||
className="bg-background active:drop-shadow-xs max-w-[115px] rounded-md w-full h-8 inline-flex p-1 justify-between items-center gap-2"
|
className="bg-background active:drop-shadow-xs max-w-[115px] rounded-md w-full h-8 inline-flex p-1 justify-between items-center gap-2 relative overflow-hidden"
|
||||||
>
|
>
|
||||||
|
{isSuccess && isLoading && (
|
||||||
|
<motion.div
|
||||||
|
className="absolute inset-0 bg-background/80 flex items-center justify-center z-10"
|
||||||
|
initial={{ opacity: 0 }}
|
||||||
|
animate={{ opacity: 1 }}
|
||||||
|
exit={{ opacity: 0 }}
|
||||||
|
>
|
||||||
|
<motion.div
|
||||||
|
animate={{ rotateZ: [0, 360] }}
|
||||||
|
transition={{ duration: 1.2, repeat: Infinity, ease: 'linear' }}
|
||||||
|
>
|
||||||
|
<Refresh className="text-foreground" size={20} />
|
||||||
|
</motion.div>
|
||||||
|
</motion.div>
|
||||||
|
)}
|
||||||
{quantity <= 0 ? (
|
{quantity <= 0 ? (
|
||||||
<button
|
<button
|
||||||
onClick={() => increment(food.id)}
|
onClick={handleAddToCart}
|
||||||
className="inline-flex w-full justify-center items-center gap-2"
|
disabled={isSuccess && isLoading}
|
||||||
|
className="inline-flex w-full justify-center items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
>
|
>
|
||||||
<PlusIcon />
|
<PlusIcon />
|
||||||
<div className="text-sm2 pt-0.5 font-normal text-foreground">افزودن</div>
|
<div className="text-sm2 pt-0.5 font-normal text-foreground">
|
||||||
|
افزودن
|
||||||
|
</div>
|
||||||
</button>
|
</button>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<button
|
<button
|
||||||
onClick={() => increment(food.id)}
|
onClick={handleAddToCart}
|
||||||
className="bg-container hover:bg-container/60 active:bg-container/30 rounded-sm p-2"
|
disabled={isSuccess && isLoading}
|
||||||
|
className="bg-container hover:bg-container/60 active:bg-container/30 rounded-sm p-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
>
|
>
|
||||||
<PlusIcon className="text-foreground" />
|
<PlusIcon className="text-foreground" />
|
||||||
</button>
|
</button>
|
||||||
@@ -84,11 +133,10 @@ const MenuItem = ({ food }: MenuItemProps) => {
|
|||||||
>
|
>
|
||||||
{quantity}
|
{quantity}
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={() => decrement(food.id)}
|
onClick={handleRemoveFromCart}
|
||||||
className="bg-container hover:bg-container/60 active:bg-container/30 rounded-sm p-2"
|
disabled={isSuccess && isLoading}
|
||||||
|
className="bg-container hover:bg-container/60 active:bg-container/30 rounded-sm p-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
>
|
>
|
||||||
<MinusIcon className="text-foreground" />
|
<MinusIcon className="text-foreground" />
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -51,15 +51,19 @@ const StepOtp = ({ phone, slug }: Props) => {
|
|||||||
}
|
}
|
||||||
return undefined
|
return undefined
|
||||||
}).filter((item): item is { foodId: string; quantity: number } => item !== undefined)
|
}).filter((item): item is { foodId: string; quantity: number } => item !== undefined)
|
||||||
mutateBulkCart({ items: bulkCartItems }, {
|
if (!!bulkCartItems.length) {
|
||||||
onSuccess: () => {
|
mutateBulkCart({ items: bulkCartItems }, {
|
||||||
clear()
|
onSuccess: () => {
|
||||||
window.location.href = `/${slug}`
|
clear()
|
||||||
},
|
window.location.href = `/${slug}`
|
||||||
onError: (error) => {
|
},
|
||||||
toast(extractErrorMessage(error), 'error')
|
onError: (error) => {
|
||||||
}
|
toast(extractErrorMessage(error), 'error')
|
||||||
})
|
}
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
window.location.href = `/${slug}`
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
window.location.href = `/${slug}`
|
window.location.href = `/${slug}`
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user