| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440 |
- "use client";
- import {useState, useCallback } from "react";
- import clsx from "clsx";
- import Image from "next/image";
- import { useRouter } from 'next/navigation';
- import Big from 'big.js';
- import { useCustomToast } from "@/utils/hooks/useToast";
- import { useAppDispatch } from "@/store/hooks";
- import { useAddProduct } from "@utils/hooks/useAddToCart";
- import { updateCart, clearCart } from "@/store/slices/cart-slice";
- import {useStore} from "@/utils/hooks/useConfig";
- import {useLoginModal} from "@/providers/LoginModalProvider";
- import type { CartDetail, CartItem } from "@/types/cart/type";
- import type { OrderDetails } from "@/types/customer/type";
- import { formatCartDetail, formatCartProductOptions } from "@/utils/cartDetailTools";
- import { confirmDialog } from "@/components/theme/ui/kernel/confirm/api";
- import { overlayLoading } from "@/components/theme/ui/kernel/loading/api";
- // import {BonusBuy} from "./BonusBuy";
- import CheckoutGiftCardGate from "../../_components/GiftCard/CheckoutGiftCardGate";
- import CheckoutVipPlus from "../../_components/VipPlus/CheckoutVipPlus";
- import CheckoutCoupon from "../../_components/CheckoutCoupon/CheckoutCoupon";
- import { UnpaidOrderSection } from "./UnpaidOrderSection";
- import { Price } from "@components/theme/ui/Price";
- function computeGrandTotal(cartData: CartDetail) {
- // 剔除 运费,丢件险,积分抵扣金额 rewardPointsAmount
- const excludeAmount = new Big(cartData.shippingAmount).plus(cartData.shippingInsuranceAmount);
- const grandAmount = new Big(cartData.grandTotal).plus(cartData.rewardPointsAmount);
- return Big(grandAmount).minus(excludeAmount).toFixed(2);
- }
- // function computeSaveAmount(cartData: CartDetail) {
- // // 优惠金额 礼品卡,plus
- // const x = Big(cartData.discountAmount).plus(cartData.giftcardAmount);
- // return Big(cartData.vipPlusAmount).plus(x).toFixed(2);
- // }
- /**
- * @todo bonus buy 和快捷支付
- */
- export function CartWrapper({
- cartDetailData,
- hasUnPaidOrder,
- unpaidOrder
- }: {
- cartDetailData: CartDetail;
- hasUnPaidOrder: boolean;
- unpaidOrder: Omit<OrderDetails, 'addresses'> | null;
- }) {
- const router = useRouter();
- const {openLoginModal} = useLoginModal();
- const dispatch = useAppDispatch();
- const {deleteProductFromCart, editProductQtyFromCart} = useAddProduct();
- const { showToast } = useCustomToast();
- const {store} = useStore();
- const currentCurrencyCode = store.currentCurrency;
- const [cartData, setCartData] = useState<CartDetail>(cartDetailData);
- const [amountDetailOpen, setAmountDetailOpen] = useState(false);
- const freeGiftProducts: CartItem[] = [];
- const normalProducts: CartItem[] = [];
- cartData.items.edges.forEach((item) => {
- // return item.node;
- if(item.node.isFreeGift) {
- freeGiftProducts.push(item.node);
- } else {
- normalProducts.push(item.node);
- }
- });
- // 这里的grand total 不包含运费和丢件险和积分抵扣金额
- const grandTotal = computeGrandTotal(cartData);
- // const saveAmount = computeSaveAmount(cartData);
- const toggleAmountDetail = () => {
- setAmountDetailOpen(!amountDetailOpen);
- };
- const dispatchCartStore = useCallback((action: "clear" | "update", payload?:Partial<CartDetail>) => {
- if(action === "clear") {
- dispatch(clearCart());
- } else if(action === "update" && payload) {
- dispatch(updateCart(payload));
- }
- },[dispatch]);
- const onCartDataChange = async (paylod: CartDetail, dispatch: boolean = true) => {
- if(dispatch) {
- dispatchCartStore('update',paylod);
- }
- setCartData({...paylod});
- };
- const deleteProduct = async (cartItemId: string) => {
- // 删除商品;购物车是否还有商品,没有的话:
- // 登录用户 跳转到空购物车页面或首页
- // 游客 清除cookie 跳转到首页或空购物车页面
- const confirmres = await confirmDialog({
- title: "Warning",
- content: "Are you sure you want to delete this product.",
- });
- if(!confirmres) return; // 取消删除
- overlayLoading.start();
- const res = await deleteProductFromCart(Number(cartItemId));
- if(!res.error) {
- if(res.data) {
- // 调父组件函数
- const newCartDetail = formatCartDetail(res.data);
- onCartDataChange(newCartDetail,false);
- } else {
- router.replace('/');
- }
- } else {
- showToast(res.msg, "danger");
- }
- overlayLoading.stop();
- };
-
- const changeProductQty = async (item: CartItem, action: "plus" | "minus") => {
- if(item.canChangeQty) {
- let qty = item.quantity;
- if(action === "plus") {
- qty += 1;
- }
- if(action === "minus") {
- qty -= 1;
- }
- 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) {
- // 调父组件函数
- const newCartDetail = formatCartDetail(res.data);
- onCartDataChange(newCartDetail,false);
- } else {
- router.replace('/');
- }
- } else {
- showToast(res.msg, "danger");
- }
- overlayLoading.stop();
- }
- } else {
- showToast("This product can't change quantity.","warning");
- }
- };
- const toCheckoutPage = () => {
- router.push("/checkout");
- };
- const guestUserLogin = () => {
- openLoginModal({
- onFinalResult: async (res) => {
- if(res.mergeCartSuccess) { // 购物车合并成功
- if(res.cartAfterMerge){
- const newCartDetail = formatCartDetail(res.cartAfterMerge);
- onCartDataChange(newCartDetail,false);
- }
-
- } else { // 购物车合并失败
- // 三种 情况: 登录成功; 注册成功;
- if(res.loginSuccess) {
- // 登录成功 需要刷新页面
- showToast('You have logged in successfully. But something wrong','danger');
- await confirmDialog({
- title: "Warning",
- content: "You have logged in successfully. But something wrong. You must refresh the page.",
- noCancel: true,
- });
- window.location.reload();
- }
- if(res.registerSuccess && !res.loginSuccess) {
- // 注册成功,去登录
- await confirmDialog({
- title: "Warning",
- content: "You have registered successfully. But something wrong. You have to login.",
- noCancel: true,
- });
- router.replace('/customer/login');
- }
- }
- }
- });
- };
-
- return (<>
- {cartData.isGuest &&
- <div className="flex justify-center w-full mt-4">
- <div className="box-border flex items-center h-8.5 px-4 text-ly-14 bg-ly-lightgray rounded-sm">
- Don't lose your cart! Sync it to Your Email.
- <button type="button" onClick={guestUserLogin}>
- <span className="font-bold underline">Login</span> or <span className="font-bold underline">Register</span>
- </button>
- </div>
- </div>
- }
- <div className="flex justify-between items-start max-w-312 w-full mt-6 px-6 mx-auto">
- <section className="flex-initial box-border w-190.5">
-
- {(hasUnPaidOrder && unpaidOrder !== null) &&
- <div className="w-full mb-6">
- <UnpaidOrderSection
- orderDetail={unpaidOrder}
- />
- </div>
- }
-
- <div className="box-border w-full pb-4 border-b-1 font-medium text-ly-20">
- My Bags({cartData.itemsQty})
- </div>
- <div className="mt-4 box-border px-4">
- {normalProducts.map((product) => {
- const baseImage = product.baseImage ? JSON.parse(product.baseImage) : {};
- const productOptions = product.options.edges.map((edge) => edge.node);
- return (
- <div key={product.id} className="w-full flex gap-4 mt-6 first:mt-0 pb-6 border-b-1 border-b-[#f0f0f0] last:border-none">
- <div className="relative w-33 h-44 flex-none">
- <Image className="object-cover" fill
- src={baseImage.medium_image_url || ''}
- alt={product.name}
- />
- </div>
- <div className="w-full flex-1 flex flex-col justify-between">
- <div className="w-full">
- <div className="flex items-center gap-2 w-full">
- <div className="w-full line-clamp-2 text-ly-14 text-ly-placeholder leading-5">
- {product.name}
- </div>
- <button className="flex-none" onClick={() => deleteProduct(product.id)} type="button">
- <svg className="w-6 h-6" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" width="16" height="16" viewBox="0 0 16 16" fill="none"><path stroke="rgba(166, 166, 166, 1)" strokeWidth="1" d="M5 4.00008L5.4 1.66675L10.6 1.66675L11 4.00008"></path><path stroke="rgba(166, 166, 166, 1)" strokeWidth="1" strokeLinecap="square" d="M2 4L14 4"></path><path d="M12.3332 4L11.6665 14.3333L4.33317 14.3333L3.6665 4L12.3332 4Z" stroke="rgba(166, 166, 166, 1)" strokeWidth="1" strokeLinecap="round" ></path><path stroke="rgba(166, 166, 166, 1)" strokeWidth="1" strokeLinecap="square" d="M6.3335 11.6666L9.66683 11.6666"></path></svg>
- </button>
- </div>
- <div className="w-full max-w-115 mt-2 text-ly-14 border-1 rounded-sm border-[#d9d9d9] px-2.5 py-1.5 leading-5">
- {formatCartProductOptions(productOptions)}
- </div>
- </div>
- <div className="flex items-center justify-end">
- <div className="flex items-center gap-2 mr-3">
- {/* <span className="text-ly-14 text-[#d3d3d3] line-through">$200.12</span> */}
- <Price className="text-ly-20 font-bold"
- amount={product.price}
- currencyCode={currentCurrencyCode}
- />
- </div>
- {product.canChangeQty ?
- <div className=" flex-none flex border-1 rounded-lg px-2.5 py-1.25 gap-4">
- <button className="flex-none" onClick={() => changeProductQty(product,'minus')} type="button">
- <svg className="w-4 h-4" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" width="16" height="16" viewBox="0 0 16 16" fill="none"><path stroke="rgba(0, 0, 0, 1)" strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="square" d="M3.33301 8L12.6663 8"></path></svg>
- </button>
- <span className="text-ly-16">{product.quantity}</span>
- <button className="flex-none" onClick={() => changeProductQty(product,'plus')} type="button">
- <svg className="w-4 h-4" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" width="16" height="16" viewBox="0 0 16 16" fill="none"><path stroke="rgba(0, 0, 0, 1)" strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="square" d="M8.02001 3.3335L8.00781 12.6668"></path><path stroke="rgba(0, 0, 0, 1)" strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="square" d="M3.33301 8L12.6663 8"></path></svg>
- </button>
- </div>
- :
-
- <span className="text-ly-16">{product.quantity}</span>
- }
-
- </div>
- </div>
- </div>
-
- )
- })}
- </div>
-
- {freeGiftProducts.length > 0 &&
- <div className="w-full box-border mt-6 px-4">
- {freeGiftProducts.map((gift) => {
- const baseImage = gift.baseImage ? JSON.parse(gift.baseImage) : {};
- const productOptions = gift.options.edges.map((edge) => edge.node);
- return (
- <div key={gift.id} className="flex justify-between gap-2 w-full bg-ly-lightgray box-border p-3 mt-6 first:mt-0">
- <div className="relative flex-none w-30 h-30">
- <Image className="object-cover" fill
- src={baseImage.medium_image_url || ''}
- alt={gift.name}
- />
- </div>
-
- <div className="w-full flex flex-col justify-between">
- <div>
- <p className="text-ly-12 leading-5 line-clamp-2">
- {gift.name}
- </p>
- <div className="w-full mt-2 text-ly-12 text-ly-placeholder">
- {formatCartProductOptions(productOptions)}
- </div>
- </div>
- <p className="flex justify-between items-center">
- <span className="text-ly-14 font-bold">{gift.formattedPrice}</span>
- <span className="text-ly-12">{gift.quantity}</span>
- </p>
- </div>
- </div>
- )
- })}
- </div>
- }
-
- {/* <div className="mt-6 box-border px-4">
- <BonusBuy />
- </div> */}
- </section>
- <section className="flex-none box-border w-97.5 ml-4 border-1">
- <div className="box-border w-full border-b-1 p-4">
- <div className="flex items-center justify-between" onClick={toggleAmountDetail}>
- <div className="flex items-center text-ly-20">
- {cartData.isVip &&
- <Image className="w-17.5 h-6 mr-1"
- width={70}
- height={24}
- src="/image/plus-crown.svg"
- alt="Plus Tag"
- />
- }
- Total({cartData.itemsQty}{cartData.itemsQty > 1 ? ' items' : ' item'})
- <svg className={clsx("w-6 h-6 ml-1", amountDetailOpen && "-rotate-180")} xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24" fill="none"><path stroke="rgba(0, 0, 0, 1)" strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="square" d="M18 9L12 15L6 9"></path></svg>
- </div>
- <Price className="text-ly-24 font-bold"
- amount={grandTotal}
- currencyCode={currentCurrencyCode}
- />
- </div>
- <ul className={clsx("w-full mt-6",!amountDetailOpen && "hidden")}>
- <li className="flex items-center justify-between text-ly-12 mt-4 first:mt-0">
- <span>
- Subtotal
- </span>
- <span>
- {cartData.formattedSubtotal}
- </span>
- </li>
- {/* {cartData.earnableRewardPoints > 0 &&
- <li className="flex items-center justify-between text-ly-12 mt-4 first:mt-0">
- <span>You Earn</span>
- <span>{cartData.earnableRewardPoints} Reward Points</span>
- </li>
- } */}
- {cartData.vipPlusAmount !== 0 &&
- <li className="flex items-center justify-between text-ly-12 mt-4 first:mt-0">
- <span>Vip Plus Fee</span>
- <span>{cartData.formattedVipPlusAmount}</span>
- </li>
- }
- {cartData.discountAmount !== 0 &&
- <li className="flex items-center justify-between text-ly-12 mt-4 first:mt-0">
- <span>Coupon</span>
- <span className="flex items-center h-6 px-2 bg-ly-gold text-ly-14">-{cartData.formattedDiscountAmount}</span>
- </li>
- }
- {cartData.vipDiscountAmount !== 0 &&
- <li className="flex items-center justify-between text-ly-12 mt-4 first:mt-0">
- <span>Plus</span>
- <span className="flex items-center h-6 px-2 bg-ly-gold text-ly-14">-{cartData.formattedVipDiscountAmount}</span>
- </li>
- }
- {cartData.giftcardAmount !== 0 &&
- <li className="flex items-center justify-between text-ly-12 mt-4 first:mt-0">
- <span>Gift Card</span>
- <span className="flex items-center h-6 px-2 bg-ly-gold text-ly-14">-{cartData.formattedGiftcardAmount}</span>
- </li>
- }
- </ul>
- <p className="mt-2 text-ly-12 leading-5 text-ly-placeholder">
- Total is an estimate. Final amount shown at checkout
- </p>
- </div>
- <div className="box-border p-4">
- <CheckoutVipPlus
- cartData={cartData}
- onSwitchVip={onCartDataChange}
- />
- </div>
- <div className="box-border p-4 border-t-1">
- <CheckoutCoupon
- couponCode={cartData.couponCode || ''}
- discountAmount={cartData.formattedDiscountAmount}
- onCouponChange={onCartDataChange}
- />
- </div>
- {!cartData.isGuest &&
- <div className="box-border p-4 border-t-1">
- <CheckoutGiftCardGate
- giftcardNumber={cartData.giftcardNumber || ''}
- formattedGiftcardAmount={cartData.formattedGiftcardAmount}
- onChangeGiftcard={onCartDataChange}
- />
- </div>
- }
- <div className="w-full box-border border-t-1 p-4">
-
- <div className="flex justify-between">
- {/* <button className="flex justify-center items-center w-41 h-12 bg-[#ffc43a] rounded-3xl" type="button">
- <Image width={75} height={24} className="w-18.75 w-6"
- src="/image/payment/paypal-logo.svg"
- alt="paypal express"
- />
- </button> */}
- <button type="button" onClick={toCheckoutPage}
- className="flex justify-center items-center w-full h-12 bg-ly-middlegreen text-white text-ly-16 font-bold rounded-3xl"
- >
- Check Out
- </button>
- </div>
- </div>
- </section>
- </div>
- </>);
- };
|