CartWrapper.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. "use client";
  2. import {useState, useCallback } from "react";
  3. import clsx from "clsx";
  4. import Image from "next/image";
  5. import { useRouter } from 'next/navigation';
  6. import Big from 'big.js';
  7. import { useCustomToast } from "@/utils/hooks/useToast";
  8. import { useAppDispatch } from "@/store/hooks";
  9. import { useAddProduct } from "@utils/hooks/useAddToCart";
  10. import { updateCart, clearCart } from "@/store/slices/cart-slice";
  11. import {useStore} from "@/utils/hooks/useConfig";
  12. import {useLoginModal} from "@/providers/LoginModalProvider";
  13. import type { CartDetail, CartItem } from "@/types/cart/type";
  14. import type { OrderDetails } from "@/types/customer/type";
  15. import { formatCartDetail, formatCartProductOptions } from "@/utils/cartDetailTools";
  16. import { confirmDialog } from "@/components/theme/ui/kernel/confirm/api";
  17. import { overlayLoading } from "@/components/theme/ui/kernel/loading/api";
  18. // import {BonusBuy} from "./BonusBuy";
  19. import CheckoutGiftCardGate from "../../_components/GiftCard/CheckoutGiftCardGate";
  20. import CheckoutVipPlus from "../../_components/VipPlus/CheckoutVipPlus";
  21. import CheckoutCoupon from "../../_components/CheckoutCoupon/CheckoutCoupon";
  22. import { UnpaidOrderSection } from "./UnpaidOrderSection";
  23. import { Price } from "@components/theme/ui/Price";
  24. function computeGrandTotal(cartData: CartDetail) {
  25. // 剔除 运费,丢件险,积分抵扣金额 rewardPointsAmount
  26. const excludeAmount = new Big(cartData.shippingAmount).plus(cartData.shippingInsuranceAmount);
  27. const grandAmount = new Big(cartData.grandTotal).plus(cartData.rewardPointsAmount);
  28. return Big(grandAmount).minus(excludeAmount).toFixed(2);
  29. }
  30. // function computeSaveAmount(cartData: CartDetail) {
  31. // // 优惠金额 礼品卡,plus
  32. // const x = Big(cartData.discountAmount).plus(cartData.giftcardAmount);
  33. // return Big(cartData.vipPlusAmount).plus(x).toFixed(2);
  34. // }
  35. /**
  36. * @todo bonus buy 和快捷支付
  37. */
  38. export function CartWrapper({
  39. cartDetailData,
  40. hasUnPaidOrder,
  41. unpaidOrder
  42. }: {
  43. cartDetailData: CartDetail;
  44. hasUnPaidOrder: boolean;
  45. unpaidOrder: Omit<OrderDetails, 'addresses'> | null;
  46. }) {
  47. const router = useRouter();
  48. const {openLoginModal} = useLoginModal();
  49. const dispatch = useAppDispatch();
  50. const {deleteProductFromCart, editProductQtyFromCart} = useAddProduct();
  51. const { showToast } = useCustomToast();
  52. const {store} = useStore();
  53. const currentCurrencyCode = store.currentCurrency;
  54. const [cartData, setCartData] = useState<CartDetail>(cartDetailData);
  55. const [amountDetailOpen, setAmountDetailOpen] = useState(false);
  56. const freeGiftProducts: CartItem[] = [];
  57. const normalProducts: CartItem[] = [];
  58. cartData.items.edges.forEach((item) => {
  59. // return item.node;
  60. if(item.node.isFreeGift) {
  61. freeGiftProducts.push(item.node);
  62. } else {
  63. normalProducts.push(item.node);
  64. }
  65. });
  66. // 这里的grand total 不包含运费和丢件险和积分抵扣金额
  67. const grandTotal = computeGrandTotal(cartData);
  68. // const saveAmount = computeSaveAmount(cartData);
  69. const toggleAmountDetail = () => {
  70. setAmountDetailOpen(!amountDetailOpen);
  71. };
  72. const dispatchCartStore = useCallback((action: "clear" | "update", payload?:Partial<CartDetail>) => {
  73. if(action === "clear") {
  74. dispatch(clearCart());
  75. } else if(action === "update" && payload) {
  76. dispatch(updateCart(payload));
  77. }
  78. },[dispatch]);
  79. const onCartDataChange = async (paylod: CartDetail, dispatch: boolean = true) => {
  80. if(dispatch) {
  81. dispatchCartStore('update',paylod);
  82. }
  83. setCartData({...paylod});
  84. };
  85. const deleteProduct = async (cartItemId: string) => {
  86. // 删除商品;购物车是否还有商品,没有的话:
  87. // 登录用户 跳转到空购物车页面或首页
  88. // 游客 清除cookie 跳转到首页或空购物车页面
  89. const confirmres = await confirmDialog({
  90. title: "Warning",
  91. content: "Are you sure you want to delete this product.",
  92. });
  93. if(!confirmres) return; // 取消删除
  94. overlayLoading.start();
  95. const res = await deleteProductFromCart(Number(cartItemId));
  96. if(!res.error) {
  97. if(res.data) {
  98. // 调父组件函数
  99. const newCartDetail = formatCartDetail(res.data);
  100. onCartDataChange(newCartDetail,false);
  101. } else {
  102. router.replace('/');
  103. }
  104. } else {
  105. showToast(res.msg, "danger");
  106. }
  107. overlayLoading.stop();
  108. };
  109. const changeProductQty = async (item: CartItem, action: "plus" | "minus") => {
  110. if(item.canChangeQty) {
  111. let qty = item.quantity;
  112. if(action === "plus") {
  113. qty += 1;
  114. }
  115. if(action === "minus") {
  116. qty -= 1;
  117. }
  118. if(qty < 1) {
  119. showToast("Quantity must be at least 1", "warning");
  120. } else {
  121. overlayLoading.start();
  122. const res = await editProductQtyFromCart(Number(item.id),qty);
  123. if(!res.error) {
  124. if(res.data) {
  125. // 调父组件函数
  126. const newCartDetail = formatCartDetail(res.data);
  127. onCartDataChange(newCartDetail,false);
  128. } else {
  129. router.replace('/');
  130. }
  131. } else {
  132. showToast(res.msg, "danger");
  133. }
  134. overlayLoading.stop();
  135. }
  136. } else {
  137. showToast("This product can't change quantity.","warning");
  138. }
  139. };
  140. const toCheckoutPage = () => {
  141. router.push("/checkout");
  142. };
  143. const guestUserLogin = () => {
  144. openLoginModal({
  145. onFinalResult: async (res) => {
  146. if(res.mergeCartSuccess) { // 购物车合并成功
  147. if(res.cartAfterMerge){
  148. const newCartDetail = formatCartDetail(res.cartAfterMerge);
  149. onCartDataChange(newCartDetail,false);
  150. }
  151. } else { // 购物车合并失败
  152. // 三种 情况: 登录成功; 注册成功;
  153. if(res.loginSuccess) {
  154. // 登录成功 需要刷新页面
  155. showToast('You have logged in successfully. But something wrong','danger');
  156. await confirmDialog({
  157. title: "Warning",
  158. content: "You have logged in successfully. But something wrong. You must refresh the page.",
  159. noCancel: true,
  160. });
  161. window.location.reload();
  162. }
  163. if(res.registerSuccess && !res.loginSuccess) {
  164. // 注册成功,去登录
  165. await confirmDialog({
  166. title: "Warning",
  167. content: "You have registered successfully. But something wrong. You have to login.",
  168. noCancel: true,
  169. });
  170. router.replace('/customer/login');
  171. }
  172. }
  173. }
  174. });
  175. };
  176. return (<>
  177. {cartData.isGuest &&
  178. <div className="flex justify-center w-full mt-4">
  179. <div className="box-border flex items-center h-8.5 px-4 text-ly-14 bg-ly-lightgray rounded-sm">
  180. Don't lose your cart! Sync it to Your Email.
  181. <button type="button" onClick={guestUserLogin}>
  182. <span className="font-bold underline">Login</span> or <span className="font-bold underline">Register</span>
  183. </button>
  184. </div>
  185. </div>
  186. }
  187. <div className="flex justify-between items-start max-w-312 w-full mt-6 px-6 mx-auto">
  188. <section className="flex-initial box-border w-190.5">
  189. {(hasUnPaidOrder && unpaidOrder !== null) &&
  190. <div className="w-full mb-6">
  191. <UnpaidOrderSection
  192. orderDetail={unpaidOrder}
  193. />
  194. </div>
  195. }
  196. <div className="box-border w-full pb-4 border-b-1 font-medium text-ly-20">
  197. My Bags({cartData.itemsQty})
  198. </div>
  199. <div className="mt-4 box-border px-4">
  200. {normalProducts.map((product) => {
  201. const baseImage = product.baseImage ? JSON.parse(product.baseImage) : {};
  202. const productOptions = product.options.edges.map((edge) => edge.node);
  203. return (
  204. <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">
  205. <div className="relative w-33 h-44 flex-none">
  206. <Image className="object-cover" fill
  207. src={baseImage.medium_image_url || ''}
  208. alt={product.name}
  209. />
  210. </div>
  211. <div className="w-full flex-1 flex flex-col justify-between">
  212. <div className="w-full">
  213. <div className="flex items-center gap-2 w-full">
  214. <div className="w-full line-clamp-2 text-ly-14 text-ly-placeholder leading-5">
  215. {product.name}
  216. </div>
  217. <button className="flex-none" onClick={() => deleteProduct(product.id)} type="button">
  218. <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>
  219. </button>
  220. </div>
  221. <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">
  222. {formatCartProductOptions(productOptions)}
  223. </div>
  224. </div>
  225. <div className="flex items-center justify-end">
  226. <div className="flex items-center gap-2 mr-3">
  227. {/* <span className="text-ly-14 text-[#d3d3d3] line-through">$200.12</span> */}
  228. <Price className="text-ly-20 font-bold"
  229. amount={product.price}
  230. currencyCode={currentCurrencyCode}
  231. />
  232. </div>
  233. {product.canChangeQty ?
  234. <div className=" flex-none flex border-1 rounded-lg px-2.5 py-1.25 gap-4">
  235. <button className="flex-none" onClick={() => changeProductQty(product,'minus')} type="button">
  236. <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>
  237. </button>
  238. <span className="text-ly-16">{product.quantity}</span>
  239. <button className="flex-none" onClick={() => changeProductQty(product,'plus')} type="button">
  240. <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>
  241. </button>
  242. </div>
  243. :
  244. <span className="text-ly-16">{product.quantity}</span>
  245. }
  246. </div>
  247. </div>
  248. </div>
  249. )
  250. })}
  251. </div>
  252. {freeGiftProducts.length > 0 &&
  253. <div className="w-full box-border mt-6 px-4">
  254. {freeGiftProducts.map((gift) => {
  255. const baseImage = gift.baseImage ? JSON.parse(gift.baseImage) : {};
  256. const productOptions = gift.options.edges.map((edge) => edge.node);
  257. return (
  258. <div key={gift.id} className="flex justify-between gap-2 w-full bg-ly-lightgray box-border p-3 mt-6 first:mt-0">
  259. <div className="relative flex-none w-30 h-30">
  260. <Image className="object-cover" fill
  261. src={baseImage.medium_image_url || ''}
  262. alt={gift.name}
  263. />
  264. </div>
  265. <div className="w-full flex flex-col justify-between">
  266. <div>
  267. <p className="text-ly-12 leading-5 line-clamp-2">
  268. {gift.name}
  269. </p>
  270. <div className="w-full mt-2 text-ly-12 text-ly-placeholder">
  271. {formatCartProductOptions(productOptions)}
  272. </div>
  273. </div>
  274. <p className="flex justify-between items-center">
  275. <span className="text-ly-14 font-bold">{gift.formattedPrice}</span>
  276. <span className="text-ly-12">{gift.quantity}</span>
  277. </p>
  278. </div>
  279. </div>
  280. )
  281. })}
  282. </div>
  283. }
  284. {/* <div className="mt-6 box-border px-4">
  285. <BonusBuy />
  286. </div> */}
  287. </section>
  288. <section className="flex-none box-border w-97.5 ml-4 border-1">
  289. <div className="box-border w-full border-b-1 p-4">
  290. <div className="flex items-center justify-between" onClick={toggleAmountDetail}>
  291. <div className="flex items-center text-ly-20">
  292. {cartData.isVip &&
  293. <Image className="w-17.5 h-6 mr-1"
  294. width={70}
  295. height={24}
  296. src="/image/plus-crown.svg"
  297. alt="Plus Tag"
  298. />
  299. }
  300. Total({cartData.itemsQty}{cartData.itemsQty > 1 ? ' items' : ' item'})
  301. <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>
  302. </div>
  303. <Price className="text-ly-24 font-bold"
  304. amount={grandTotal}
  305. currencyCode={currentCurrencyCode}
  306. />
  307. </div>
  308. <ul className={clsx("w-full mt-6",!amountDetailOpen && "hidden")}>
  309. <li className="flex items-center justify-between text-ly-12 mt-4 first:mt-0">
  310. <span>
  311. Subtotal
  312. </span>
  313. <span>
  314. {cartData.formattedSubtotal}
  315. </span>
  316. </li>
  317. {/* {cartData.earnableRewardPoints > 0 &&
  318. <li className="flex items-center justify-between text-ly-12 mt-4 first:mt-0">
  319. <span>You Earn</span>
  320. <span>{cartData.earnableRewardPoints} Reward Points</span>
  321. </li>
  322. } */}
  323. {cartData.vipPlusAmount !== 0 &&
  324. <li className="flex items-center justify-between text-ly-12 mt-4 first:mt-0">
  325. <span>Vip Plus Fee</span>
  326. <span>{cartData.formattedVipPlusAmount}</span>
  327. </li>
  328. }
  329. {cartData.discountAmount !== 0 &&
  330. <li className="flex items-center justify-between text-ly-12 mt-4 first:mt-0">
  331. <span>Coupon</span>
  332. <span className="flex items-center h-6 px-2 bg-ly-gold text-ly-14">-{cartData.formattedDiscountAmount}</span>
  333. </li>
  334. }
  335. {cartData.vipDiscountAmount !== 0 &&
  336. <li className="flex items-center justify-between text-ly-12 mt-4 first:mt-0">
  337. <span>Plus</span>
  338. <span className="flex items-center h-6 px-2 bg-ly-gold text-ly-14">-{cartData.formattedVipDiscountAmount}</span>
  339. </li>
  340. }
  341. {cartData.giftcardAmount !== 0 &&
  342. <li className="flex items-center justify-between text-ly-12 mt-4 first:mt-0">
  343. <span>Gift Card</span>
  344. <span className="flex items-center h-6 px-2 bg-ly-gold text-ly-14">-{cartData.formattedGiftcardAmount}</span>
  345. </li>
  346. }
  347. </ul>
  348. <p className="mt-2 text-ly-12 leading-5 text-ly-placeholder">
  349. Total is an estimate. Final amount shown at checkout
  350. </p>
  351. </div>
  352. <div className="box-border p-4">
  353. <CheckoutVipPlus
  354. cartData={cartData}
  355. onSwitchVip={onCartDataChange}
  356. />
  357. </div>
  358. <div className="box-border p-4 border-t-1">
  359. <CheckoutCoupon
  360. couponCode={cartData.couponCode || ''}
  361. discountAmount={cartData.formattedDiscountAmount}
  362. onCouponChange={onCartDataChange}
  363. />
  364. </div>
  365. {!cartData.isGuest &&
  366. <div className="box-border p-4 border-t-1">
  367. <CheckoutGiftCardGate
  368. giftcardNumber={cartData.giftcardNumber || ''}
  369. formattedGiftcardAmount={cartData.formattedGiftcardAmount}
  370. onChangeGiftcard={onCartDataChange}
  371. />
  372. </div>
  373. }
  374. <div className="w-full box-border border-t-1 p-4">
  375. <div className="flex justify-between">
  376. {/* <button className="flex justify-center items-center w-41 h-12 bg-[#ffc43a] rounded-3xl" type="button">
  377. <Image width={75} height={24} className="w-18.75 w-6"
  378. src="/image/payment/paypal-logo.svg"
  379. alt="paypal express"
  380. />
  381. </button> */}
  382. <button type="button" onClick={toCheckoutPage}
  383. className="flex justify-center items-center w-full h-12 bg-ly-middlegreen text-white text-ly-16 font-bold rounded-3xl"
  384. >
  385. Check Out
  386. </button>
  387. </div>
  388. </div>
  389. </section>
  390. </div>
  391. </>);
  392. };