@anker-in/shopify-react 0.1.1-beta.4 → 0.1.1-beta.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,10 @@
1
1
  import { createContext, useMemo, useRef, useState, useEffect, useCallback, useContext } from 'react';
2
2
  import useSWRMutation from 'swr/mutation';
3
- import { getProductsByHandles, createCart, updateCartCodes, addCartLines, updateCartLines, removeCartLines, updateCartAttributes, getProduct, getAllProducts, getCollection, getAllCollections, getCollections, getBlog, getAllBlogs, getArticle, getArticles, getArticlesInBlog, getLocalStorage, setLocalStorage } from '@anker-in/shopify-sdk';
3
+ import { getProductsByHandles, createCart, updateCartCodes, addCartLines, updateCartLines, removeCartLines, updateCartAttributes, getLocalStorage, getProduct, getAllProducts, getCollection, getAllCollections, getCollections, getBlog, getAllBlogs, getArticle, getArticles, getArticlesInBlog, setLocalStorage, updateCartDeliveryOptions } from '@anker-in/shopify-sdk';
4
4
  import Cookies5 from 'js-cookie';
5
5
  import { jsx } from 'react/jsx-runtime';
6
6
  import Decimal2 from 'decimal.js';
7
+ import { atobID, btoaID } from '@anker-in/shopify-core';
7
8
  import useSWR from 'swr';
8
9
  import { useRequest } from 'ahooks';
9
10
 
@@ -60,6 +61,7 @@ var CUSTOMER_ATTRIBUTE_KEY = "_discounts_function_env";
60
61
  var CUSTOMER_SCRIPT_GIFT_KEY = "_giveaway_gradient_gifts";
61
62
  var CODE_AMOUNT_KEY = "_sku_code_money";
62
63
  var SCRIPT_CODE_AMOUNT_KEY = "_code_money";
64
+ var MEMBER_PRICE_ATTRIBUTE_KEY = "_member_price";
63
65
  var MAIN_PRODUCT_CODE = ["WS24", "WSTD", "WS7D", "WSCP", "WSPE", "WSPD"];
64
66
 
65
67
  // src/hooks/cart/utils/normalize-add-to-cart-lines.ts
@@ -68,9 +70,10 @@ function normalizeAddToCartLines(lines) {
68
70
  const variant = line.variant;
69
71
  const product = variant.product;
70
72
  const quantity = line.quantity || 1;
71
- const price = variant.finalPrice?.amount ? Number(variant.finalPrice.amount) : variant.compareAtPrice?.amount ? Number(variant.compareAtPrice.amount) : variant.price?.amount ? Number(variant.price.amount) : 0;
72
- const subtotalAmount = price * quantity;
73
- const totalAmount = subtotalAmount;
73
+ const originalPrice = variant.price?.amount ? Number(variant.price.amount) : 0;
74
+ const finalPrice = variant.finalPrice?.amount === void 0 ? originalPrice : Number(variant.finalPrice?.amount);
75
+ const subtotalAmount = originalPrice * quantity;
76
+ const totalAmount = finalPrice * quantity;
74
77
  return {
75
78
  id: `temp-line-${index}-${variant.id}`,
76
79
  // Temporary ID for pre-cart lines
@@ -84,7 +87,7 @@ function normalizeAddToCartLines(lines) {
84
87
  customAttributes: line.attributes || [],
85
88
  variant: {
86
89
  id: variant.id,
87
- price,
90
+ price: finalPrice,
88
91
  listPrice: variant.compareAtPrice?.amount ? Number(variant.compareAtPrice.amount) : 0,
89
92
  sku: variant.sku || "",
90
93
  name: variant.title || "",
@@ -115,15 +118,16 @@ function createMockCartFromLines(lines, existingCart) {
115
118
  const normalizedLines = normalizeAddToCartLines(lines);
116
119
  const subtotalPrice = normalizedLines.reduce((sum, line) => sum + line.subtotalAmount, 0);
117
120
  const totalPrice = normalizedLines.reduce((sum, line) => sum + line.totalAmount, 0);
121
+ const currency = lines[0]?.variant?.price?.currencyCode;
118
122
  return {
119
123
  id: existingCart?.id || "temp-cart-id",
120
124
  customerId: existingCart?.customerId,
121
125
  email: existingCart?.email,
122
126
  createdAt: existingCart?.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
123
- currency: existingCart?.currency || { code: "USD" },
127
+ currency: existingCart?.currency || { code: currency },
124
128
  taxesIncluded: existingCart?.taxesIncluded,
125
129
  lineItems: normalizedLines,
126
- totallineItemsDiscount: 0,
130
+ totalLineItemsDiscount: 0,
127
131
  orderDiscounts: 0,
128
132
  lineItemsSubtotalPrice: subtotalPrice,
129
133
  subtotalPrice,
@@ -154,16 +158,6 @@ var getQuery = () => {
154
158
  }
155
159
  return theRequest;
156
160
  };
157
- function atobID(id) {
158
- if (id && typeof id === "string" && id.includes("/")) {
159
- return id.split("/").pop()?.split("?")?.shift();
160
- } else {
161
- return id;
162
- }
163
- }
164
- function btoaID(id, type = "ProductVariant") {
165
- return `gid://shopify/${type}/${id}`;
166
- }
167
161
  var getMatchedMainProductSubTotal = (cartData, variant_list, main_product) => {
168
162
  const isAllStoreVariant = main_product?.all_store_variant ?? false;
169
163
  const matchedList = cartData?.lineItems?.filter((line) => {
@@ -395,43 +389,29 @@ var useCalcAutoFreeGift = (cart, autoFreeGiftConfig, customer, lines) => {
395
389
  }
396
390
  return { activeCampaign: null, subtotal: 0 };
397
391
  }, [autoFreeGiftConfig, effectiveCart, tags, dealsType]);
398
- const { qualifyingGift, nextTierGoal } = useMemo(() => {
392
+ const { qualifyingTier, nextTierGoal, actualThreshold, currentCurrency } = useMemo(() => {
399
393
  if (!activeCampaign || !activeCampaign.rule_result?.spend_get_reward?.gift_product) {
400
- return { qualifyingGift: null, nextTierGoal: null };
394
+ return { qualifyingTier: null, nextTierGoal: null, actualThreshold: 0, currentCurrency: "" };
401
395
  }
402
396
  const giftTiers = activeCampaign.rule_result.spend_get_reward.gift_product;
403
- const qualifyingTier = [...giftTiers].sort((a, b) => Number(b.spend_sum_money) - Number(a.spend_sum_money)).find((tier) => subtotal >= Number(tier.spend_sum_money));
404
- const nextGoal = giftTiers.find((tier) => subtotal < Number(tier.spend_sum_money));
405
- if (!qualifyingTier) {
406
- return { qualifyingGift: null, nextTierGoal: nextGoal || null };
407
- }
408
- const formattedGift = {
409
- tier: qualifyingTier,
410
- itemsToAdd: qualifyingTier.reward_list?.map((reward) => {
411
- const giftProduct = reward?.variant_list?.[0];
412
- if (!giftProduct) return null;
413
- return {
414
- variant: {
415
- id: btoaID(giftProduct.variant_id),
416
- handle: giftProduct.handle,
417
- sku: giftProduct.sku
418
- },
419
- quantity: reward?.get_unit || 1,
420
- attributes: [
421
- {
422
- key: CUSTOMER_ATTRIBUTE_KEY,
423
- value: JSON.stringify({
424
- is_gift: true,
425
- rule_id: activeCampaign.rule_id,
426
- spend_sum_money: qualifyingTier.spend_sum_money
427
- })
428
- }
429
- ]
430
- };
431
- }).filter((item) => item !== null)
397
+ const currentCurrency2 = effectiveCart?.currency?.code || "";
398
+ console.log("currentCurrency useCalcAutoFreeGift", effectiveCart, currentCurrency2);
399
+ const getThresholdAmount = (tier) => {
400
+ if (tier.spend_sum_money_multi_markets?.[currentCurrency2]?.value) {
401
+ return Number(tier.spend_sum_money_multi_markets[currentCurrency2].value);
402
+ }
403
+ return Number(tier.spend_sum_money || 0);
432
404
  };
433
- return { qualifyingGift: formattedGift, nextTierGoal: nextGoal || null };
434
- }, [activeCampaign, subtotal]);
405
+ const qualifyingTier2 = [...giftTiers].sort((a, b) => getThresholdAmount(b) - getThresholdAmount(a)).find((tier) => subtotal >= getThresholdAmount(tier));
406
+ const nextGoal = giftTiers.find((tier) => subtotal < getThresholdAmount(tier));
407
+ const actualThreshold2 = qualifyingTier2 ? getThresholdAmount(qualifyingTier2) : 0;
408
+ return {
409
+ qualifyingTier: qualifyingTier2,
410
+ nextTierGoal: nextGoal || null,
411
+ actualThreshold: actualThreshold2,
412
+ currentCurrency: currentCurrency2
413
+ };
414
+ }, [activeCampaign, subtotal, effectiveCart]);
435
415
  const giftHandles = useMemo(() => {
436
416
  const giftVariant = autoFreeGiftConfig.map(
437
417
  (item) => item.rule_result?.spend_get_reward?.gift_product?.map(
@@ -447,24 +427,82 @@ var useCalcAutoFreeGift = (cart, autoFreeGiftConfig, customer, lines) => {
447
427
  }
448
428
  return true;
449
429
  }, [giftHandles]);
450
- const { data: giftProductsResult } = useSWR(shouldFetch ? giftHandles : null, async () => {
451
- const res = await getProductsByHandles(client, {
452
- handles: giftHandles,
453
- locale
454
- });
455
- const result = Array.isArray(res) ? res : [];
456
- giftProductsCache.current = {
457
- data: result,
458
- giftHandles: [...giftHandles]
459
- };
460
- return result;
461
- });
430
+ const { data: giftProductsResult } = useSWR(
431
+ shouldFetch ? giftHandles : null,
432
+ async () => {
433
+ const res = await getProductsByHandles(client, {
434
+ handles: giftHandles,
435
+ locale
436
+ });
437
+ const result = Array.isArray(res) ? res : [];
438
+ giftProductsCache.current = {
439
+ data: result,
440
+ giftHandles: [...giftHandles]
441
+ };
442
+ return result;
443
+ },
444
+ {
445
+ revalidateOnFocus: false
446
+ }
447
+ );
462
448
  const finalGiftProductsResult = useMemo(() => {
463
449
  if (giftProductsCache.current && !shouldFetch) {
464
450
  return giftProductsCache.current.data || void 0;
465
451
  }
466
452
  return giftProductsResult;
467
453
  }, [giftProductsResult, shouldFetch]);
454
+ const qualifyingGift = useMemo(() => {
455
+ if (!qualifyingTier || !activeCampaign) {
456
+ return null;
457
+ }
458
+ const itemsToAdd = qualifyingTier.reward_list?.map((reward) => {
459
+ if (!reward.variant_list || reward.variant_list.length === 0) {
460
+ return null;
461
+ }
462
+ let selectedGiftProduct = null;
463
+ for (const giftVariant of reward.variant_list) {
464
+ const productInfo = finalGiftProductsResult?.find(
465
+ (p) => p.handle === giftVariant.handle
466
+ );
467
+ if (productInfo) {
468
+ const variantInfo = productInfo.variants?.find((v) => v.sku === giftVariant.sku);
469
+ if (variantInfo?.availableForSale) {
470
+ selectedGiftProduct = giftVariant;
471
+ break;
472
+ }
473
+ }
474
+ }
475
+ if (!selectedGiftProduct) {
476
+ selectedGiftProduct = reward.variant_list[0];
477
+ }
478
+ return {
479
+ variant: {
480
+ id: btoaID(selectedGiftProduct.variant_id),
481
+ handle: selectedGiftProduct.handle,
482
+ sku: selectedGiftProduct.sku
483
+ },
484
+ quantity: reward?.get_unit || 1,
485
+ attributes: [
486
+ {
487
+ key: CUSTOMER_ATTRIBUTE_KEY,
488
+ value: JSON.stringify({
489
+ is_gift: true,
490
+ rule_id: activeCampaign.rule_id,
491
+ spend_sum_money: actualThreshold,
492
+ // 使用实际的门槛金额(多币种支持)
493
+ currency_code: currentCurrency
494
+ // 记录当前币种
495
+ })
496
+ }
497
+ ]
498
+ };
499
+ }).filter((item) => item !== null);
500
+ const formattedGift = {
501
+ tier: qualifyingTier,
502
+ itemsToAdd
503
+ };
504
+ return formattedGift;
505
+ }, [qualifyingTier, activeCampaign, finalGiftProductsResult, actualThreshold, currentCurrency]);
468
506
  return {
469
507
  qualifyingGift,
470
508
  nextTierGoal,
@@ -511,12 +549,14 @@ var useScriptAutoFreeGift = ({
511
549
  upgrade_multiple2 = 1.2;
512
550
  upgrade_value2 = 40;
513
551
  }
514
- effectiveCart?.lineItems?.forEach(({ customAttributes }) => {
515
- customAttributes?.forEach(({ key, value }) => {
516
- if (key === "_amount_upgrade_multiple") upgrade_multiple2 = Number(value) || 1;
517
- if (key === "_amount_upgrade_value") upgrade_value2 = Number(value) || 0;
518
- });
519
- });
552
+ effectiveCart?.lineItems?.forEach(
553
+ ({ customAttributes }) => {
554
+ customAttributes?.forEach(({ key, value }) => {
555
+ if (key === "_amount_upgrade_multiple") upgrade_multiple2 = Number(value) || 1;
556
+ if (key === "_amount_upgrade_value") upgrade_value2 = Number(value) || 0;
557
+ });
558
+ }
559
+ );
520
560
  return [upgrade_multiple2, upgrade_value2];
521
561
  }, [effectiveCart?.lineItems, points_subscribe]);
522
562
  const breakpoints = useMemo(() => {
@@ -581,18 +621,24 @@ var useScriptAutoFreeGift = ({
581
621
  const nextLevel = levelIndex > 0 ? sortedLevels[levelIndex - 1] ?? null : null;
582
622
  return [currentLevel, nextLevel];
583
623
  }, [breakpoints, involvedSubTotal, involvedLines.length]);
584
- const { data: giftProductsResult } = useSWR(shouldFetch ? giftHandles : null, async () => {
585
- const res = await getProductsByHandles(client, {
586
- handles: giftHandles,
587
- locale
588
- });
589
- const result = Array.isArray(res) ? res : [];
590
- giftProductsCache.current = {
591
- data: result,
592
- giftHandles: [...giftHandles]
593
- };
594
- return result;
595
- });
624
+ const { data: giftProductsResult } = useSWR(
625
+ shouldFetch ? giftHandles : null,
626
+ async () => {
627
+ const res = await getProductsByHandles(client, {
628
+ handles: giftHandles,
629
+ locale
630
+ });
631
+ const result = Array.isArray(res) ? res : [];
632
+ giftProductsCache.current = {
633
+ data: result,
634
+ giftHandles: [...giftHandles]
635
+ };
636
+ return result;
637
+ },
638
+ {
639
+ revalidateOnFocus: false
640
+ }
641
+ );
596
642
  const finalGiftProductsResult = useMemo(() => {
597
643
  if (giftProductsCache.current && !shouldFetch) {
598
644
  return giftProductsCache.current.data || void 0;
@@ -625,9 +671,9 @@ var useScriptAutoFreeGift = ({
625
671
  };
626
672
  };
627
673
  var CartContext = createContext(null);
628
- function useCartContext() {
674
+ function useCartContext(options) {
629
675
  const context = useContext(CartContext);
630
- if (!context) {
676
+ if (!context && true) {
631
677
  throw new Error("useCartContext must be used within a CartProvider");
632
678
  }
633
679
  return context;
@@ -669,11 +715,23 @@ function useAddCartLines(options) {
669
715
  const { mutateCart, metafieldIdentifiers } = useCartContext();
670
716
  const addLines = useCallback(
671
717
  async (_key, { arg }) => {
672
- let updatedCart = await addCartLines(client, {
673
- ...arg,
674
- metafieldIdentifiers,
675
- cookieAdapter: cartCookieAdapter
676
- });
718
+ const { cartId, lines } = arg;
719
+ const id = cartId || cartCookieAdapter?.getCartId(locale);
720
+ let updatedCart;
721
+ if (!id) {
722
+ updatedCart = await createCart(client, {
723
+ lines,
724
+ metafieldIdentifiers,
725
+ cookieAdapter: cartCookieAdapter
726
+ });
727
+ } else {
728
+ updatedCart = await addCartLines(client, {
729
+ cartId: id,
730
+ lines,
731
+ metafieldIdentifiers,
732
+ cookieAdapter: cartCookieAdapter
733
+ });
734
+ }
677
735
  if (updatedCart) {
678
736
  const unApplicableCodes = updatedCart.discountCodes.filter((item) => !item.applicable).map((item) => item.code);
679
737
  if (unApplicableCodes.length > 0) {
@@ -720,7 +778,7 @@ var trackAddToCartGA = ({
720
778
  const currencyCode = variant.product?.price?.currencyCode;
721
779
  const totalPrice = lineItems?.reduce(
722
780
  (prev, { variant: variant2 }) => prev.plus(
723
- variant2?.finalPrice?.amount ?? variant2?.compareAtPrice?.amount ?? variant2?.price?.amount ?? 0
781
+ variant2?.finalPrice?.amount === void 0 ? Number(variant2?.price?.amount) || 0 : Number(variant2?.finalPrice?.amount) || 0
724
782
  ),
725
783
  new Decimal2(0)
726
784
  ).toNumber();
@@ -753,10 +811,10 @@ var trackBuyNowGA = ({
753
811
  return;
754
812
  }
755
813
  const { variant } = lineItems[0];
756
- const currencyCode = variant.price?.currencyCode;
814
+ const currencyCode = variant.product?.price?.currencyCode || variant.price?.currencyCode;
757
815
  const totalPrice = lineItems?.reduce(
758
816
  (prev, { variant: variant2 }) => prev.plus(
759
- variant2?.finalPrice?.amount ?? variant2?.compareAtPrice?.amount ?? (variant2?.price?.amount || 0)
817
+ variant2?.finalPrice?.amount === void 0 ? Number(variant2?.price?.amount) || 0 : Number(variant2?.finalPrice?.amount) || 0
760
818
  ),
761
819
  new Decimal2(0)
762
820
  ).toNumber();
@@ -830,7 +888,7 @@ function useApplyCartCodes(options) {
830
888
  if (!discountCodes?.length) {
831
889
  throw new Error("Invalid input used for this operation: Miss discountCode");
832
890
  }
833
- const cartId = providedCartId ? void 0 : providedCartId || cart?.id;
891
+ const cartId = providedCartId || cart?.id;
834
892
  if (!cartId) {
835
893
  return void 0;
836
894
  }
@@ -843,12 +901,18 @@ function useApplyCartCodes(options) {
843
901
  cookieAdapter: cartCookieAdapter,
844
902
  metafieldIdentifiers
845
903
  });
904
+ const unApplicableCodes = discountCodes.filter(
905
+ (code) => updatedCart?.discountCodes?.find((item) => item.code === code && !item.applicable)
906
+ );
907
+ if (unApplicableCodes.length) {
908
+ throw new Error(`${unApplicableCodes.join(", ")} is not applicable to the cart`);
909
+ }
846
910
  if (updatedCart) {
847
911
  mutateCart(updatedCart);
848
912
  }
849
913
  return updatedCart;
850
914
  },
851
- [client, locale, cartCookieAdapter, mutateCart, cart]
915
+ [client, locale, cartCookieAdapter, mutateCart, cart, metafieldIdentifiers]
852
916
  );
853
917
  return useSWRMutation("apply-codes", applyCodes, options);
854
918
  }
@@ -858,7 +922,7 @@ function useRemoveCartCodes(options) {
858
922
  const removeCodes = useCallback(
859
923
  async (_key, { arg }) => {
860
924
  const { cartId: providedCartId, discountCodes } = arg;
861
- const cartId = providedCartId ? void 0 : providedCartId || cart?.id;
925
+ const cartId = providedCartId || cart?.id;
862
926
  const codes = cart?.discountCodes?.filter((code) => !!code.applicable) || [];
863
927
  const leftCodes = codes.filter((code) => discountCodes?.length ? !discountCodes.includes(code.code) : code.code).map((code) => code.code);
864
928
  const updatedCart = await updateCartCodes(client, {
@@ -872,18 +936,105 @@ function useRemoveCartCodes(options) {
872
936
  }
873
937
  return updatedCart;
874
938
  },
875
- [client, locale, cartCookieAdapter, mutateCart, cart]
939
+ [client, locale, cartCookieAdapter, mutateCart, cart, metafieldIdentifiers]
876
940
  );
877
941
  return useSWRMutation("remove-codes", removeCodes, options);
878
942
  }
943
+ var initSameLinesAttributes = ({
944
+ cart,
945
+ line
946
+ }) => {
947
+ const sameLineInCart = cart?.lineItems.find(
948
+ (lineInCart) => lineInCart.variant.sku === line.variant?.sku && lineInCart.product?.handle === line.variant?.product?.handle
949
+ );
950
+ const codeAmountAttribute = sameLineInCart?.customAttributes?.find(
951
+ (attr) => attr.key === CODE_AMOUNT_KEY
952
+ );
953
+ const scriptCodeAmountAttribute = sameLineInCart?.customAttributes?.find(
954
+ (attr) => attr.key === SCRIPT_CODE_AMOUNT_KEY
955
+ );
956
+ let functionAttribute = null;
957
+ try {
958
+ functionAttribute = sameLineInCart?.customAttributes?.find(
959
+ (attr) => attr.key === CUSTOMER_ATTRIBUTE_KEY && JSON.parse(attr.value)?.discounted_amount
960
+ );
961
+ } catch (error) {
962
+ }
963
+ if (codeAmountAttribute || functionAttribute || scriptCodeAmountAttribute) {
964
+ return {
965
+ ...line,
966
+ attributes: [
967
+ ...line.attributes || [],
968
+ codeAmountAttribute,
969
+ functionAttribute,
970
+ scriptCodeAmountAttribute
971
+ ].filter(Boolean)
972
+ };
973
+ }
974
+ return line;
975
+ };
976
+ var initDiscountAttributes = ({ line }) => {
977
+ let itemAttributes = line.attributes || [];
978
+ const functionEnvAttribute = itemAttributes.find((attr) => attr.key === CUSTOMER_ATTRIBUTE_KEY);
979
+ if (!functionEnvAttribute) {
980
+ itemAttributes = itemAttributes.concat([
981
+ {
982
+ key: CUSTOMER_ATTRIBUTE_KEY,
983
+ value: JSON.stringify({
984
+ is_gift: false,
985
+ discounted_amount: line.variant?.finalPrice?.amount === void 0 ? Number(line.variant?.price?.amount) * (line.quantity || 1) : Number(line.variant?.finalPrice?.amount) * (line.quantity || 1)
986
+ })
987
+ }
988
+ ]);
989
+ }
990
+ const memberPriceAttribute = itemAttributes.find(
991
+ (attr) => attr.key === MEMBER_PRICE_ATTRIBUTE_KEY
992
+ );
993
+ const coupon = line.coupon;
994
+ if (!memberPriceAttribute && coupon) {
995
+ itemAttributes = itemAttributes.concat([
996
+ {
997
+ key: MEMBER_PRICE_ATTRIBUTE_KEY,
998
+ value: JSON.stringify({ code: coupon.code })
999
+ }
1000
+ ]);
1001
+ }
1002
+ const couponDiscountAttribute = itemAttributes.find(
1003
+ (attr) => attr.key === CODE_AMOUNT_KEY || attr.key === SCRIPT_CODE_AMOUNT_KEY
1004
+ );
1005
+ if (!couponDiscountAttribute && coupon && Number(coupon?.amount) > 0) {
1006
+ itemAttributes = itemAttributes.concat([
1007
+ {
1008
+ key: CODE_AMOUNT_KEY,
1009
+ value: new Decimal2(coupon.amount).times(line.quantity || 1).toString()
1010
+ },
1011
+ {
1012
+ key: SCRIPT_CODE_AMOUNT_KEY,
1013
+ value: new Decimal2(coupon.amount).times(line.quantity || 1).toString()
1014
+ }
1015
+ ]);
1016
+ }
1017
+ return { ...line, attributes: itemAttributes };
1018
+ };
1019
+ var getLinesWithAttributes = ({
1020
+ cart,
1021
+ lineItems
1022
+ }) => {
1023
+ return lineItems.map((line) => {
1024
+ const sameLine = initSameLinesAttributes({ cart, line });
1025
+ const functionLine = initDiscountAttributes({ line: sameLine });
1026
+ return functionLine;
1027
+ });
1028
+ };
879
1029
 
880
1030
  // src/hooks/cart/use-add-to-cart.ts
881
1031
  function useAddToCart({ withTrack = true } = {}, swrOptions) {
882
- const { client, config, locale, cartCookieAdapter, userAdapter } = useShopify();
883
- const { cart } = useCartContext();
1032
+ const { client, config, locale, cartCookieAdapter, userAdapter, performanceAdapter } = useShopify();
1033
+ const { cart, addCustomAttributes } = useCartContext();
884
1034
  const { trigger: applyCartCodes } = useApplyCartCodes();
885
1035
  const { trigger: removeInvalidCodes } = useRemoveCartCodes();
886
1036
  const { trigger: addCartLines2 } = useAddCartLines();
1037
+ const { trigger: createCart4 } = useCreateCart();
887
1038
  const addToCart = useCallback(
888
1039
  async (_key, { arg }) => {
889
1040
  const {
@@ -894,12 +1045,15 @@ function useAddToCart({ withTrack = true } = {}, swrOptions) {
894
1045
  buyerIdentity,
895
1046
  needCreateCart = false,
896
1047
  onCodesInvalid,
897
- replaceExistingCodes
1048
+ replaceExistingCodes,
1049
+ customAttributes
898
1050
  } = arg;
899
1051
  if (!lineItems || lineItems.length === 0) {
900
1052
  return;
901
1053
  }
902
- const lines = lineItems.map((item) => ({
1054
+ performanceAdapter?.addToCartStart();
1055
+ const linesWithFunctionAttributes = getLinesWithAttributes({ cart, lineItems });
1056
+ const lines = linesWithFunctionAttributes.map((item) => ({
903
1057
  merchandiseId: item.variant?.id || "",
904
1058
  quantity: item.quantity || 1,
905
1059
  attributes: item.attributes,
@@ -908,36 +1062,45 @@ function useAddToCart({ withTrack = true } = {}, swrOptions) {
908
1062
  if (lines.length === 0) {
909
1063
  return;
910
1064
  }
911
- const cartId = needCreateCart ? void 0 : providedCartId || cart?.id;
912
- let resultCart = await addCartLines2({
913
- cartId,
914
- lines,
915
- buyerIdentity
916
- });
917
- if (!resultCart) {
918
- return void 0;
919
- }
920
- console.log("npm addCartLines resultCart", resultCart);
921
- if (resultCart.discountCodes && resultCart.discountCodes.length > 0) {
922
- const unapplicableCodes = resultCart.discountCodes.filter((item) => !item.applicable).map((item) => item.code);
923
- if (unapplicableCodes.length > 0) {
924
- if (onCodesInvalid) {
925
- const handledCart = await onCodesInvalid(resultCart, unapplicableCodes);
926
- if (handledCart) {
927
- resultCart = handledCart;
1065
+ let cartId = needCreateCart ? void 0 : providedCartId || cart?.id;
1066
+ let resultCart = null;
1067
+ if (!cartId) {
1068
+ resultCart = await createCart4({
1069
+ lines,
1070
+ buyerIdentity,
1071
+ discountCodes,
1072
+ customAttributes
1073
+ });
1074
+ } else {
1075
+ resultCart = await addCartLines2({
1076
+ cartId,
1077
+ lines
1078
+ });
1079
+ console.log("npm addCartLines resultCart", resultCart);
1080
+ if (resultCart && resultCart.discountCodes && resultCart.discountCodes.length > 0) {
1081
+ const unapplicableCodes = resultCart.discountCodes.filter((item) => !item.applicable).map((item) => item.code);
1082
+ if (unapplicableCodes.length > 0) {
1083
+ if (onCodesInvalid) {
1084
+ const handledCart = await onCodesInvalid(resultCart, unapplicableCodes);
1085
+ if (handledCart) {
1086
+ resultCart = handledCart;
1087
+ }
1088
+ } else {
1089
+ await removeInvalidCodes({
1090
+ discountCodes: unapplicableCodes
1091
+ });
928
1092
  }
929
- } else {
930
- await removeInvalidCodes({
931
- discountCodes: unapplicableCodes
932
- });
933
1093
  }
934
1094
  }
935
- }
936
- if (discountCodes && discountCodes.length > 0) {
937
- applyCartCodes({
938
- replaceExistingCodes,
939
- discountCodes
940
- });
1095
+ if (resultCart && discountCodes && discountCodes.length > 0) {
1096
+ applyCartCodes({
1097
+ replaceExistingCodes,
1098
+ discountCodes
1099
+ });
1100
+ }
1101
+ if (customAttributes && customAttributes.length > 0) {
1102
+ addCustomAttributes(customAttributes);
1103
+ }
941
1104
  }
942
1105
  if (withTrack) {
943
1106
  trackAddToCartGA({
@@ -946,9 +1109,24 @@ function useAddToCart({ withTrack = true } = {}, swrOptions) {
946
1109
  });
947
1110
  trackAddToCartFBQ({ lineItems });
948
1111
  }
1112
+ performanceAdapter?.addToCartEnd();
949
1113
  return resultCart;
950
1114
  },
951
- [client, locale, cartCookieAdapter, userAdapter, cart, withTrack]
1115
+ [
1116
+ client,
1117
+ locale,
1118
+ cartCookieAdapter,
1119
+ userAdapter,
1120
+ cart,
1121
+ withTrack,
1122
+ performanceAdapter,
1123
+ createCart4,
1124
+ addCartLines2,
1125
+ applyCartCodes,
1126
+ removeInvalidCodes,
1127
+ addCustomAttributes,
1128
+ config
1129
+ ]
952
1130
  );
953
1131
  return useSWRMutation("add-to-cart", addToCart, swrOptions);
954
1132
  }
@@ -965,9 +1143,10 @@ function useUpdateCartLines(options) {
965
1143
  if (updatedCart) {
966
1144
  mutateCart(updatedCart);
967
1145
  }
1146
+ console.log("use-update-cart-lines updatedCart", metafieldIdentifiers, updatedCart);
968
1147
  return updatedCart;
969
1148
  },
970
- [client, locale, cartCookieAdapter, mutateCart]
1149
+ [client, locale, cartCookieAdapter, mutateCart, metafieldIdentifiers]
971
1150
  );
972
1151
  return useSWRMutation("update-cart-lines", updateLines, options);
973
1152
  }
@@ -1006,7 +1185,7 @@ function useRemoveCartLines(options) {
1006
1185
  }
1007
1186
  return updatedCart;
1008
1187
  },
1009
- [client, locale, cartCookieAdapter, mutateCart]
1188
+ [client, locale, cartCookieAdapter, mutateCart, metafieldIdentifiers]
1010
1189
  );
1011
1190
  return useSWRMutation("remove-cart-lines", removeLines, options);
1012
1191
  }
@@ -1025,7 +1204,7 @@ function useUpdateCartAttributes(mutate, metafieldIdentifiers, options) {
1025
1204
  }
1026
1205
  return updatedCart;
1027
1206
  },
1028
- [client, locale, cartCookieAdapter, mutate]
1207
+ [client, locale, cartCookieAdapter, mutate, metafieldIdentifiers]
1029
1208
  );
1030
1209
  return useSWRMutation("update-cart-attributes", updateAttributes, options);
1031
1210
  }
@@ -1047,12 +1226,15 @@ function useBuyNow({ withTrack = true } = {}, swrOptions) {
1047
1226
  if (!lineItems || lineItems.length === 0) {
1048
1227
  return;
1049
1228
  }
1050
- const lines = lineItems.map((item) => ({
1229
+ const linesWithFunctionAttributes = getLinesWithAttributes({
1230
+ lineItems
1231
+ });
1232
+ const lines = linesWithFunctionAttributes.map((item) => ({
1051
1233
  merchandiseId: item.variant?.id || "",
1052
1234
  quantity: item.quantity || 1,
1053
1235
  attributes: item.attributes,
1054
1236
  sellingPlanId: item.sellingPlanId
1055
- })).filter((item) => item.merchandiseId && item.quantity);
1237
+ })).filter((item) => item.merchandiseId);
1056
1238
  if (lines.length === 0) {
1057
1239
  return;
1058
1240
  }
@@ -1107,17 +1289,41 @@ function useCalcGiftsFromLines({
1107
1289
  lines
1108
1290
  });
1109
1291
  const allGiftLines = useMemo(() => {
1110
- const functionGiftLines = functionGift.qualifyingGift?.itemsToAdd || [];
1111
- const scriptGiftLines = scriptGift.freeGiftLevel ? scriptGift.freeGiftLevel.giveawayProducts.map((product) => {
1112
- const giftProduct = scriptGift.giftProductsResult?.find(
1113
- (p) => p.handle === product.handle
1292
+ const functionGiftLines = (functionGift.qualifyingGift?.itemsToAdd || []).map((item) => {
1293
+ const product = functionGift.giftProductsResult?.find(
1294
+ (product2) => product2.handle === item.variant.handle
1114
1295
  );
1115
- const variant = giftProduct?.variants?.[0];
1296
+ const variants = product?.variants;
1297
+ const variant = Array.isArray(variants) ? variants.find((v) => v.sku === item.variant.sku) : void 0;
1298
+ if (!variant) {
1299
+ console.warn(
1300
+ `Function gift: Variant not found for handle=${item.variant.handle}, sku=${item.variant.sku}`
1301
+ );
1302
+ return null;
1303
+ }
1116
1304
  return {
1117
1305
  variant: {
1118
- id: variant?.id || "",
1119
- handle: product.handle,
1120
- sku: product.sku
1306
+ ...variant,
1307
+ product
1308
+ },
1309
+ quantity: item.quantity ?? 1,
1310
+ attributes: item.attributes
1311
+ };
1312
+ }).filter((item) => item !== null);
1313
+ const scriptGiftLines = scriptGift.freeGiftLevel ? scriptGift.freeGiftLevel.giveawayProducts.map((item) => {
1314
+ const product = scriptGift.giftProductsResult?.find(
1315
+ (product2) => product2.handle === item.handle
1316
+ );
1317
+ const variants = product?.variants;
1318
+ const variant = Array.isArray(variants) ? variants.find((v) => v.sku === item.sku) : void 0;
1319
+ if (!variant) {
1320
+ console.warn(`Script gift: Variant not found for handle=${item.handle}, sku=${item.sku}`);
1321
+ return null;
1322
+ }
1323
+ return {
1324
+ variant: {
1325
+ ...variant,
1326
+ product
1121
1327
  },
1122
1328
  quantity: 1,
1123
1329
  attributes: [
@@ -1127,10 +1333,11 @@ function useCalcGiftsFromLines({
1127
1333
  }
1128
1334
  ]
1129
1335
  };
1130
- }).filter((item) => item.variant.id) : [];
1336
+ }).filter((item) => item !== null) : [];
1131
1337
  return [...functionGiftLines, ...scriptGiftLines];
1132
1338
  }, [
1133
1339
  functionGift.qualifyingGift,
1340
+ functionGift.giftProductsResult,
1134
1341
  scriptGift.freeGiftLevel,
1135
1342
  scriptGift.giftProductsResult,
1136
1343
  scriptGiveawayKey
@@ -1165,7 +1372,7 @@ var useCalcOrderDiscount = (cart, orderDiscountConfig, customer) => {
1165
1372
  const isCustomerLoading = useMemo(() => !customer ? true : false, [customer]);
1166
1373
  const dealsType = "";
1167
1374
  const { activeCampaign, subtotal } = useMemo(() => {
1168
- for (const campaign of orderDiscountConfig) {
1375
+ for (const campaign of orderDiscountConfig || []) {
1169
1376
  const { rule_conditions = [], result_detail } = campaign;
1170
1377
  const { main_product, order_discount_conf } = result_detail || {};
1171
1378
  const isPreCheckPassed = preCheck(rule_conditions, tags, []);
@@ -1195,9 +1402,12 @@ var useCalcOrderDiscount = (cart, orderDiscountConfig, customer) => {
1195
1402
  discountAmount: 0
1196
1403
  };
1197
1404
  }
1198
- const tieredDiscounts = activeCampaign.result_detail.order_discount_conf.tiered_discounts;
1199
- const qualifyingTier = [...tieredDiscounts].reverse().find((tier) => subtotal >= Number(tier.amount));
1200
- const nextGoal = tieredDiscounts.find((tier) => subtotal < Number(tier.amount));
1405
+ const currentCurrency = cart?.currency?.code || "";
1406
+ console.log("currentCurrency", cart, currentCurrency);
1407
+ const orderDiscountConf = activeCampaign.result_detail.order_discount_conf;
1408
+ const tieredDiscounts = orderDiscountConf.tiered_discounts_markets?.[currentCurrency] || orderDiscountConf.tiered_discounts;
1409
+ const qualifyingTier = [...tieredDiscounts].sort((a, b) => Number(b.amount) - Number(a.amount)).find((tier) => subtotal >= Number(tier.amount));
1410
+ const nextGoal = [...tieredDiscounts].sort((a, b) => Number(a.amount) - Number(b.amount)).find((tier) => subtotal < Number(tier.amount));
1201
1411
  if (!qualifyingTier) {
1202
1412
  return {
1203
1413
  qualifyingDiscount: null,
@@ -1265,12 +1475,10 @@ function useHasPlusMemberInCart({
1265
1475
  };
1266
1476
  }, [cart?.lineItems, plus_monthly_product, plus_annual_product]);
1267
1477
  }
1268
-
1269
- // src/hooks/cart/feature/use-cart-attributes.ts
1270
1478
  var getReferralAttributes = () => {
1271
- const inviteCode = Cookies5.get("invite_code");
1272
- const playModeId = Cookies5.get("playModeId");
1273
- const popup = Cookies5.get("_popup");
1479
+ const inviteCode = getLocalStorage("inviteCode") || Cookies5.get("inviteCode");
1480
+ const playModeId = getLocalStorage("playModeId") || Cookies5.get("playModeId");
1481
+ const popup = getLocalStorage("_popup") || Cookies5.get("_popup");
1274
1482
  if (inviteCode && playModeId) {
1275
1483
  return popup ? [
1276
1484
  { key: "_invite_code", value: inviteCode ? inviteCode : "" },
@@ -1294,8 +1502,6 @@ var useCartAttributes = ({
1294
1502
  memberSetting,
1295
1503
  cart
1296
1504
  });
1297
- console.log("memberSetting", memberSetting);
1298
- console.log("hasPlusMember", hasPlusMember);
1299
1505
  useEffect(() => {
1300
1506
  setCurrentUrl(window.location.href);
1301
1507
  }, []);
@@ -1321,7 +1527,7 @@ var useCartAttributes = ({
1321
1527
  return "new_user_login";
1322
1528
  }, [customer]);
1323
1529
  const memberAttributes = useMemo(() => {
1324
- return [
1530
+ const attributes = [
1325
1531
  {
1326
1532
  key: "_token",
1327
1533
  value: profile?.token
@@ -1342,17 +1548,28 @@ var useCartAttributes = ({
1342
1548
  value: profile?.token ? "true" : "false"
1343
1549
  }
1344
1550
  ];
1551
+ if (profile?.token) {
1552
+ attributes.push({
1553
+ key: "_login_user",
1554
+ value: "1"
1555
+ });
1556
+ }
1557
+ return attributes;
1345
1558
  }, [profile?.memberType, profile?.token, userType, hasPlusMember]);
1346
1559
  const functionAttributes = useMemo(() => {
1347
- return [
1348
- cart?.discountCodes && {
1560
+ const hasFunctionEnvAttribute = cart?.lineItems.some(
1561
+ (item) => item.customAttributes?.some((attr) => attr.key === CUSTOMER_ATTRIBUTE_KEY)
1562
+ );
1563
+ const discountCodes = cart?.discountCodes.map((item) => item.code).filter((code) => code) || [];
1564
+ return hasFunctionEnvAttribute ? [
1565
+ {
1349
1566
  key: "_discounts_function_env",
1350
1567
  value: JSON.stringify({
1351
- discount_code: cart?.discountCodes.map((item) => item.code),
1568
+ discount_code: discountCodes,
1352
1569
  user_tags: customer?.tags || []
1353
1570
  })
1354
1571
  }
1355
- ];
1572
+ ] : [];
1356
1573
  }, [cart]);
1357
1574
  const presellAttributes = useMemo(() => {
1358
1575
  return [
@@ -1384,18 +1601,50 @@ var useCartAttributes = ({
1384
1601
  }
1385
1602
  ];
1386
1603
  }, [currentUrl]);
1604
+ const commonAttributes = useMemo(
1605
+ () => [
1606
+ ...memberAttributes,
1607
+ ...functionAttributes,
1608
+ ...presellAttributes,
1609
+ ...weightAttributes,
1610
+ ...trackingAttributes,
1611
+ ...getReferralAttributes()
1612
+ ].filter((item) => item?.value),
1613
+ [memberAttributes, functionAttributes, presellAttributes, weightAttributes, trackingAttributes]
1614
+ );
1615
+ const extraAttributesInCart = useMemo(() => {
1616
+ const commonAttributeKeys = [
1617
+ // member attributes
1618
+ "_token",
1619
+ "_member_type",
1620
+ "_user_type",
1621
+ "_is_login",
1622
+ "_login_user",
1623
+ // function attributes
1624
+ "_discounts_function_env",
1625
+ // presell attributes
1626
+ "_presale",
1627
+ // weight attributes
1628
+ "_weight",
1629
+ "_app_source_name",
1630
+ // tracking attributes
1631
+ "utm_params",
1632
+ // referral attributes
1633
+ "_invite_code",
1634
+ "_play_mode_id",
1635
+ "_popup"
1636
+ ];
1637
+ return cart?.customAttributes?.filter(
1638
+ (item) => !commonAttributeKeys.includes(item.key)
1639
+ ) || [];
1640
+ }, [cart]);
1387
1641
  return useMemo(
1388
1642
  () => ({
1389
- attributes: [
1390
- ...memberAttributes,
1391
- ...functionAttributes,
1392
- ...presellAttributes,
1393
- ...weightAttributes,
1394
- ...trackingAttributes,
1395
- ...getReferralAttributes()
1396
- ].filter((item) => item?.value)
1643
+ attributes: [...commonAttributes, ...extraAttributesInCart].filter(
1644
+ (item) => item?.value
1645
+ )
1397
1646
  }),
1398
- [memberAttributes, functionAttributes, presellAttributes, weightAttributes, trackingAttributes]
1647
+ [commonAttributes, extraAttributesInCart]
1399
1648
  );
1400
1649
  };
1401
1650
  var DEFAULT_MIN = 1;
@@ -1458,7 +1707,7 @@ var useUpdateLineCodeAmountAttributes = ({
1458
1707
  );
1459
1708
  const functionEnvValue = getDiscountEnvAttributeValue(line.customAttributes);
1460
1709
  const hasSameFunctionEnvAttribute = Number(functionEnvValue.discounted_amount) === Number(line.totalAmount);
1461
- if (!hasSameFunctionEnvAttribute && hasFunctionEnvAttribute) {
1710
+ if (!hasSameFunctionEnvAttribute && hasFunctionEnvAttribute && !functionEnvValue.is_gift) {
1462
1711
  attrNeedUpdate.push({
1463
1712
  key: CUSTOMER_ATTRIBUTE_KEY,
1464
1713
  value: JSON.stringify({
@@ -1497,29 +1746,22 @@ var useUpdateLineCodeAmountAttributes = ({
1497
1746
  }).filter(
1498
1747
  ({ attrNeedUpdate, attrNeedDelete }) => attrNeedUpdate.length || attrNeedDelete.length
1499
1748
  ).map(({ line, attrNeedUpdate, attrNeedDelete }) => {
1749
+ let lineId = line.id;
1750
+ let attributes = line.customAttributes || [];
1751
+ if (attrNeedDelete.length) {
1752
+ attributes = attributes.filter(
1753
+ (attr) => !attrNeedDelete.includes(attr.key)
1754
+ );
1755
+ }
1500
1756
  if (attrNeedUpdate.length) {
1501
- return {
1502
- id: line.id,
1503
- attributes: [
1504
- ...line.customAttributes?.filter(
1505
- (attr) => !attrNeedUpdate.some((updateAttr) => updateAttr.key === attr.key)
1506
- ) || [],
1507
- ...attrNeedUpdate
1508
- ]
1509
- };
1510
- } else if (attrNeedDelete.length) {
1511
- return {
1512
- id: line.id,
1513
- attributes: line.customAttributes?.filter(
1514
- (attr) => !attrNeedDelete.includes(attr.key)
1515
- ) || []
1516
- };
1517
- } else {
1518
- return {
1519
- id: line.id,
1520
- attributes: line.customAttributes || []
1521
- };
1757
+ attributes = attributes.filter(
1758
+ (attr) => !attrNeedUpdate.some((updateAttr) => updateAttr.key === attr.key)
1759
+ ).concat(attrNeedUpdate);
1522
1760
  }
1761
+ return {
1762
+ id: lineId,
1763
+ attributes
1764
+ };
1523
1765
  }),
1524
1766
  [cart?.lineItems, mainProductDiscountCodes]
1525
1767
  );
@@ -1612,8 +1854,9 @@ function useProductsByHandles(options = {}) {
1612
1854
  metafieldIdentifiers
1613
1855
  });
1614
1856
  },
1615
- swrOptions || {
1616
- revalidateOnFocus: false
1857
+ {
1858
+ revalidateOnFocus: false,
1859
+ ...swrOptions
1617
1860
  }
1618
1861
  );
1619
1862
  }
@@ -2242,7 +2485,10 @@ var createInitialValue = () => ({
2242
2485
  freeShippingMethods: [],
2243
2486
  paymentShippingMethods: [],
2244
2487
  nddOverweight: false,
2245
- tddOverweight: false
2488
+ tddOverweight: false,
2489
+ nddCoupon: void 0,
2490
+ tddCoupon: void 0,
2491
+ isLoadingCoupon: false
2246
2492
  },
2247
2493
  selectedPlusMemberProduct: null,
2248
2494
  plusMemberProducts: [],
@@ -2287,15 +2533,29 @@ function usePlusAnnualProductVariant() {
2287
2533
  }, [plusMemberProducts, plusAnnual]);
2288
2534
  return plusAnnualProductVariant;
2289
2535
  }
2290
- function useShippingMethods(options) {
2291
- const {
2292
- variant,
2293
- plusMemberMetafields,
2294
- selectedPlusMemberMode,
2295
- isPlus = false,
2536
+ var useAvailableDeliveryCoupon = ({
2537
+ profile
2538
+ }) => {
2539
+ const { data: availableDeliveryCoupon, isLoading } = useSWR(
2540
+ profile?.email ? ["/api/multipass/subsrv/v1/prime/delivery_coupons/current/available", profile?.email] : void 0,
2541
+ async ([apiPath]) => {
2542
+ return fetch(apiPath).then((res) => res.json());
2543
+ }
2544
+ );
2545
+ console.log("availableDeliveryCoupon", availableDeliveryCoupon);
2546
+ const { ndd_coupon: nddCoupon, tdd_coupon: tddCoupon } = availableDeliveryCoupon?.data?.data || {};
2547
+ return {
2296
2548
  nddCoupon,
2297
- tddCoupon
2298
- } = options;
2549
+ tddCoupon,
2550
+ isLoading
2551
+ };
2552
+ };
2553
+
2554
+ // src/hooks/member/plus/use-shipping-methods.ts
2555
+ function useShippingMethods(options) {
2556
+ const { variant, plusMemberMetafields, selectedPlusMemberMode, isPlus = false, profile } = options;
2557
+ const { nddCoupon, tddCoupon, isLoading } = useAvailableDeliveryCoupon({ profile });
2558
+ console.log("nddCoupon", nddCoupon);
2299
2559
  const { plus_shipping, shippingMethod } = plusMemberMetafields || {};
2300
2560
  const nddOverweight = useMemo(() => {
2301
2561
  return (variant?.weight || 0) > (shippingMethod?.overWeight_ndd || Infinity);
@@ -2305,12 +2565,10 @@ function useShippingMethods(options) {
2305
2565
  }, [shippingMethod?.overWeight_tdd, variant?.weight]);
2306
2566
  const paymentShippingMethods = useMemo(() => {
2307
2567
  const weight = variant?.weight || 0;
2308
- const methods = plus_shipping?.shipping_methods?.filter(
2309
- ({ weight_low, weight_high, __mode, __plus }) => {
2310
- const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2311
- return __mode !== "free" /* FREE */ && !__plus && fitWeight;
2312
- }
2313
- ) || [];
2568
+ const methods = plus_shipping?.shipping_methods?.filter(({ weight_low, weight_high, __mode, __plus }) => {
2569
+ const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2570
+ return __mode !== "free" /* FREE */ && !__plus && fitWeight;
2571
+ }) || [];
2314
2572
  return methods.map((method) => {
2315
2573
  let disabled = false;
2316
2574
  const selectedFreeMember = selectedPlusMemberMode === "free";
@@ -2337,40 +2595,34 @@ function useShippingMethods(options) {
2337
2595
  ]);
2338
2596
  const nddPrice = useMemo(() => {
2339
2597
  const weight = variant?.weight || 0;
2340
- const nddMethod = paymentShippingMethods.find(
2341
- ({ __mode, weight_high, weight_low }) => {
2342
- const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2343
- return __mode === "ndd" && fitWeight;
2344
- }
2345
- );
2598
+ const nddMethod = paymentShippingMethods.find(({ __mode, weight_high, weight_low }) => {
2599
+ const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2600
+ return __mode === "ndd" && fitWeight;
2601
+ });
2346
2602
  return nddMethod?.price || 0;
2347
2603
  }, [variant?.weight, paymentShippingMethods]);
2348
2604
  const tddPrice = useMemo(() => {
2349
2605
  const weight = variant?.weight || 0;
2350
- const tddMethod = paymentShippingMethods.find(
2351
- ({ __mode, weight_high, weight_low }) => {
2352
- const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2353
- return __mode === "tdd" && fitWeight;
2354
- }
2355
- );
2606
+ const tddMethod = paymentShippingMethods.find(({ __mode, weight_high, weight_low }) => {
2607
+ const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2608
+ return __mode === "tdd" && fitWeight;
2609
+ });
2356
2610
  return tddMethod?.price || 0;
2357
2611
  }, [variant?.weight, paymentShippingMethods]);
2358
2612
  const freeShippingMethods = useMemo(() => {
2359
2613
  const weight = variant?.weight || 0;
2360
- let methods = plus_shipping?.shipping_methods?.filter(
2361
- ({ __mode, __plus, weight_low, weight_high }) => {
2362
- if (__mode === "free" /* FREE */) {
2363
- return true;
2364
- }
2365
- if (isPlus) {
2366
- const hasCoupon = isPlus && __mode === "ndd" /* NDD */ && nddCoupon || isPlus && __mode === "tdd" /* TDD */ && (tddCoupon || nddCoupon);
2367
- const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2368
- return hasCoupon && fitWeight && !__plus;
2369
- } else {
2370
- return __plus;
2371
- }
2614
+ let methods = plus_shipping?.shipping_methods?.filter(({ __mode, __plus, weight_low, weight_high }) => {
2615
+ if (__mode === "free" /* FREE */) {
2616
+ return true;
2372
2617
  }
2373
- ) || [];
2618
+ if (isPlus) {
2619
+ const hasCoupon = isPlus && __mode === "ndd" /* NDD */ && nddCoupon || isPlus && __mode === "tdd" /* TDD */ && (tddCoupon || nddCoupon);
2620
+ const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2621
+ return hasCoupon && fitWeight && !__plus;
2622
+ } else {
2623
+ return __plus;
2624
+ }
2625
+ }) || [];
2374
2626
  if (isPlus) {
2375
2627
  methods = methods.sort((a, b) => {
2376
2628
  if (b.__mode === "free" /* FREE */) return -1;
@@ -2424,7 +2676,10 @@ function useShippingMethods(options) {
2424
2676
  freeShippingMethods,
2425
2677
  paymentShippingMethods,
2426
2678
  nddOverweight,
2427
- tddOverweight
2679
+ tddOverweight,
2680
+ nddCoupon,
2681
+ tddCoupon,
2682
+ isLoadingCoupon: isLoading
2428
2683
  };
2429
2684
  }
2430
2685
  function useShippingMethodAvailableCheck() {
@@ -2529,6 +2784,73 @@ var usePlusMemberDeliveryCodes = ({
2529
2784
  [deliveryData]
2530
2785
  );
2531
2786
  };
2787
+ function useUpdateCartDeliveryOptions(mutate, metafieldIdentifiers, options) {
2788
+ const { client, locale, cartCookieAdapter } = useShopify();
2789
+ const updateDeliveryOptions = useCallback(
2790
+ async (_key, { arg }) => {
2791
+ const updatedCart = await updateCartDeliveryOptions(client, {
2792
+ ...arg,
2793
+ metafieldIdentifiers,
2794
+ cookieAdapter: cartCookieAdapter
2795
+ });
2796
+ console.log("useUpdateCartDeliveryOptions updatedCart", updatedCart);
2797
+ if (updatedCart) {
2798
+ mutate(updatedCart);
2799
+ }
2800
+ return updatedCart;
2801
+ },
2802
+ [client, locale, cartCookieAdapter, mutate, metafieldIdentifiers]
2803
+ );
2804
+ return useSWRMutation("update-cart-delivery-options", updateDeliveryOptions, options);
2805
+ }
2806
+
2807
+ // src/hooks/member/plus/use-update-plus-member-delivery-options.ts
2808
+ var useUpdatePlusMemberDeliveryOptions = ({
2809
+ options
2810
+ } = {}) => {
2811
+ const { cart: cartContextData, mutateCart, metafieldIdentifiers } = useCartContext();
2812
+ const { trigger: updateCartDeliveryOptions2 } = useUpdateCartDeliveryOptions(
2813
+ mutateCart,
2814
+ metafieldIdentifiers
2815
+ );
2816
+ const handler = useCallback(
2817
+ async (_, { arg }) => {
2818
+ const currentCart = arg?.cart || cartContextData;
2819
+ const { deliveryData } = arg;
2820
+ const firstDeliveryGroup = currentCart?.deliveryGroups?.[0];
2821
+ const deliveryGroupId = firstDeliveryGroup?.id;
2822
+ const selectedOptionCode = deliveryData?.deliveryCustomData?.selected_delivery_option?.code;
2823
+ if (!deliveryGroupId || !selectedOptionCode || selectedOptionCode === firstDeliveryGroup?.selectedDeliveryOption?.code) {
2824
+ return null;
2825
+ }
2826
+ const deliveryGroup = currentCart?.deliveryGroups?.find(
2827
+ (group) => group?.id === deliveryGroupId
2828
+ );
2829
+ const matchedOption = deliveryGroup?.deliveryOptions?.find(
2830
+ (option) => option?.code === selectedOptionCode
2831
+ );
2832
+ if (!matchedOption?.handle) {
2833
+ return null;
2834
+ }
2835
+ const deliveryOptions = [
2836
+ {
2837
+ deliveryGroupId,
2838
+ deliveryOptionHandle: matchedOption.handle
2839
+ }
2840
+ ];
2841
+ const updatedCart = await updateCartDeliveryOptions2({
2842
+ selectedDeliveryOptions: deliveryOptions,
2843
+ cartId: currentCart?.id
2844
+ });
2845
+ if (updatedCart && mutateCart) {
2846
+ mutateCart(updatedCart);
2847
+ }
2848
+ return updatedCart;
2849
+ },
2850
+ [cartContextData, updateCartDeliveryOptions2, mutateCart]
2851
+ );
2852
+ return useSWRMutation("update-cart-delivery-options", handler, options);
2853
+ };
2532
2854
  var usePlusMemberItemCustomAttributes = ({
2533
2855
  deliveryData
2534
2856
  }) => {
@@ -2548,48 +2870,18 @@ var usePlusMemberCheckoutCustomAttributes = ({
2548
2870
  deliveryData,
2549
2871
  product,
2550
2872
  variant,
2551
- customer,
2552
2873
  isShowShippingBenefits
2553
2874
  }) => {
2554
2875
  const { deliveryCustomData } = deliveryData || {};
2555
2876
  const { profile } = usePlusMemberContext();
2556
- const userType = useMemo(() => {
2557
- const customerInfo = customer;
2558
- if (!customerInfo) {
2559
- return "new_user_unlogin";
2560
- }
2561
- if (customer) {
2562
- const { orders = {} } = customer;
2563
- const edgesLength = orders?.edges?.length;
2564
- if (edgesLength === 1) {
2565
- return "old_user_orders_once";
2566
- } else if (edgesLength && edgesLength > 1) {
2567
- return "old_user_orders_twice";
2568
- }
2569
- }
2570
- return "new_user_login";
2571
- }, [customer]);
2572
2877
  return useMemo(() => {
2573
2878
  const checkoutCustomAttributes = [
2574
- {
2575
- key: "_token",
2576
- value: profile?.token || ""
2577
- },
2879
+ // _last_url: 付费会员结算完成之后 checkout 有一个继续购买的按钮, 用于跳转到继续购买的页面
2578
2880
  {
2579
2881
  key: "_last_url",
2580
2882
  value: typeof window !== "undefined" ? window.location.origin + window.location.pathname : ""
2581
- },
2582
- {
2583
- key: "_user_type",
2584
- value: userType
2585
2883
  }
2586
2884
  ];
2587
- if (profile) {
2588
- checkoutCustomAttributes.push({
2589
- key: "_login_user",
2590
- value: "1"
2591
- });
2592
- }
2593
2885
  if (deliveryCustomData) {
2594
2886
  checkoutCustomAttributes.push({
2595
2887
  key: "_checkout_delivery_custom",
@@ -2599,12 +2891,6 @@ var usePlusMemberCheckoutCustomAttributes = ({
2599
2891
  })
2600
2892
  });
2601
2893
  }
2602
- if (variant?.metafields?.presell) {
2603
- checkoutCustomAttributes.push({
2604
- key: "_presale",
2605
- value: "true"
2606
- });
2607
- }
2608
2894
  if (isShowShippingBenefits && !isShowShippingBenefits({ variant, product, setting: {} })) {
2609
2895
  checkoutCustomAttributes.push({
2610
2896
  key: "_hide_shipping",
@@ -2612,18 +2898,17 @@ var usePlusMemberCheckoutCustomAttributes = ({
2612
2898
  });
2613
2899
  }
2614
2900
  return checkoutCustomAttributes;
2615
- }, [deliveryCustomData, product, profile, userType, variant, isShowShippingBenefits]);
2901
+ }, [deliveryCustomData, product, profile, variant, isShowShippingBenefits]);
2616
2902
  };
2617
2903
  function useAutoRemovePlusMemberInCart({
2618
- metafields,
2619
- isMonthlyPlus,
2620
- isAnnualPlus
2904
+ cart,
2905
+ profile,
2906
+ memberSetting
2621
2907
  }) {
2622
- const { plus_monthly_product, plus_annual_product } = metafields || {};
2623
- const { cart } = useCartContext();
2908
+ const { plus_monthly_product, plus_annual_product } = memberSetting || {};
2624
2909
  const { trigger: removeCartLines2 } = useRemoveCartLines();
2625
2910
  useEffect(() => {
2626
- if (!cart) return;
2911
+ if (!cart || !plus_monthly_product || !plus_annual_product) return;
2627
2912
  const removePlusProduct = async (productType) => {
2628
2913
  if (!productType) return;
2629
2914
  const product = cart.lineItems?.find(
@@ -2635,33 +2920,25 @@ function useAutoRemovePlusMemberInCart({
2635
2920
  });
2636
2921
  }
2637
2922
  };
2638
- if (isMonthlyPlus) {
2923
+ if (profile?.isMonthlyPlus) {
2639
2924
  removePlusProduct(plus_monthly_product);
2640
2925
  }
2641
- if (isAnnualPlus) {
2926
+ if (profile?.isAnnualPlus) {
2642
2927
  removePlusProduct(plus_annual_product);
2643
2928
  }
2644
- }, [
2645
- cart,
2646
- plus_annual_product,
2647
- plus_monthly_product,
2648
- isAnnualPlus,
2649
- isMonthlyPlus,
2650
- removeCartLines2
2651
- ]);
2929
+ }, [cart, plus_annual_product, plus_monthly_product, profile, removeCartLines2]);
2652
2930
  }
2653
- function useAddPlusMemberProductsToCart({
2931
+ function usePlusMemberNeedAddToCart({
2654
2932
  cart,
2655
- memberSetting,
2656
- selectedPlusMemberMode,
2657
- selectedPlusMemberProduct
2933
+ profile
2658
2934
  }) {
2935
+ const { selectedPlusMemberMode, selectedPlusMemberProduct, plusMemberMetafields } = usePlusMemberContext();
2659
2936
  const { hasMonthlyPlus, hasAnnualPlus } = useHasPlusMemberInCart({
2660
- cart,
2661
- memberSetting
2937
+ memberSetting: plusMemberMetafields,
2938
+ cart
2662
2939
  });
2663
2940
  const plusMemberProduct = useMemo(() => {
2664
- if (selectedPlusMemberMode === "free" /* FREE */) {
2941
+ if (!selectedPlusMemberProduct || selectedPlusMemberMode === "free" /* FREE */) {
2665
2942
  return void 0;
2666
2943
  }
2667
2944
  if (selectedPlusMemberMode === "monthly" /* MONTHLY */ && hasMonthlyPlus) {
@@ -2670,7 +2947,10 @@ function useAddPlusMemberProductsToCart({
2670
2947
  if (selectedPlusMemberMode === "annual" /* ANNUAL */ && hasAnnualPlus) {
2671
2948
  return void 0;
2672
2949
  }
2673
- if (!selectedPlusMemberProduct) {
2950
+ if (profile?.isMonthlyPlus && selectedPlusMemberMode === "monthly" /* MONTHLY */) {
2951
+ return void 0;
2952
+ }
2953
+ if (profile?.isAnnualPlus && selectedPlusMemberMode === "annual" /* ANNUAL */) {
2674
2954
  return void 0;
2675
2955
  }
2676
2956
  return selectedPlusMemberProduct;
@@ -2689,9 +2969,9 @@ var PlusMemberProvider = ({
2689
2969
  memberSetting,
2690
2970
  initialSelectedPlusMemberMode = "free",
2691
2971
  profile,
2692
- locale,
2693
2972
  children
2694
2973
  }) => {
2974
+ const { locale } = useShopify();
2695
2975
  const [zipCode, setZipCode] = useState("");
2696
2976
  const [showTip, setShowTip] = useState(false);
2697
2977
  const [selectedPlusMemberMode, setSelectedPlusMemberMode] = useState(
@@ -2707,7 +2987,11 @@ var PlusMemberProvider = ({
2707
2987
  const shippingMethodsContext = useShippingMethods({
2708
2988
  variant,
2709
2989
  plusMemberMetafields: memberSetting,
2710
- selectedPlusMemberMode});
2990
+ selectedPlusMemberMode,
2991
+ profile,
2992
+ isPlus: profile?.isPlus || false
2993
+ });
2994
+ console.log("shippingMethodsContext", shippingMethodsContext);
2711
2995
  const plusMemberHandles = useMemo(() => {
2712
2996
  return [
2713
2997
  memberSetting?.plus_monthly_product?.handle,
@@ -2944,6 +3228,6 @@ function clearGeoLocationCache(cacheKey = "geoLocation") {
2944
3228
  }
2945
3229
  }
2946
3230
 
2947
- export { BuyRuleType, CODE_AMOUNT_KEY, CUSTOMER_ATTRIBUTE_KEY, CUSTOMER_SCRIPT_GIFT_KEY, DeliveryPlusType, MAIN_PRODUCT_CODE, OrderBasePriceType, OrderDiscountType, PLUS_MEMBER_TYPE, PlusMemberContext, PlusMemberMode, PlusMemberProvider, PriceBasePriceType, PriceDiscountType, RuleType, SCRIPT_CODE_AMOUNT_KEY, ShippingMethodMode, SpendMoneyType, atobID, btoaID, checkAttributesUpdateNeeded, clearGeoLocationCache, createMockCartFromLines, currencyCodeMapping, defaultSWRMutationConfiguration, formatFunctionAutoFreeGift, formatScriptAutoFreeGift, getCachedGeoLocation, getDiscountEnvAttributeValue, getMatchedMainProductSubTotal, getQuery, getReferralAttributes, normalizeAddToCartLines, preCheck, safeParse, useAddCartLines, useAddPlusMemberProductsToCart, useAddToCart, useAllBlogs, useAllCollections, useAllProducts, useApplyCartCodes, useArticle, useArticles, useArticlesInBlog, useAutoRemovePlusMemberInCart, useBlog, useBuyNow, useCalcAutoFreeGift, useCalcGiftsFromLines, useCalcOrderDiscount, useCartAttributes, useCartItemQuantityLimit, useCollection, useCollections, useCreateCart, useExposure, useGeoLocation, useHasPlusMemberInCart, useIntersection, usePlusAnnualProductVariant, usePlusMemberCheckoutCustomAttributes, usePlusMemberContext, usePlusMemberDeliveryCodes, usePlusMemberItemCustomAttributes, usePlusMonthlyProductVariant, usePrice, useProduct, useProductUrl, useProductsByHandles, useRemoveCartCodes, useRemoveCartLines, useReplaceCartPlusMember, useScriptAutoFreeGift, useSearch, useSelectedOptions, useShippingMethodAvailableCheck, useShippingMethods, useSite, useUpdateCartAttributes, useUpdateCartLines, useUpdateLineCodeAmountAttributes, useUpdateVariantQuery, useVariant, useVariantMedia };
3231
+ export { BuyRuleType, CODE_AMOUNT_KEY, CUSTOMER_ATTRIBUTE_KEY, CUSTOMER_SCRIPT_GIFT_KEY, DeliveryPlusType, MAIN_PRODUCT_CODE, MEMBER_PRICE_ATTRIBUTE_KEY, OrderBasePriceType, OrderDiscountType, PLUS_MEMBER_TYPE, PlusMemberContext, PlusMemberMode, PlusMemberProvider, PriceBasePriceType, PriceDiscountType, RuleType, SCRIPT_CODE_AMOUNT_KEY, ShippingMethodMode, SpendMoneyType, checkAttributesUpdateNeeded, clearGeoLocationCache, createMockCartFromLines, currencyCodeMapping, defaultSWRMutationConfiguration, formatFunctionAutoFreeGift, formatScriptAutoFreeGift, getCachedGeoLocation, getDiscountEnvAttributeValue, getMatchedMainProductSubTotal, getQuery, getReferralAttributes, normalizeAddToCartLines, preCheck, safeParse, useAddCartLines, useAddToCart, useAllBlogs, useAllCollections, useAllProducts, useApplyCartCodes, useArticle, useArticles, useArticlesInBlog, useAutoRemovePlusMemberInCart, useAvailableDeliveryCoupon, useBlog, useBuyNow, useCalcAutoFreeGift, useCalcGiftsFromLines, useCalcOrderDiscount, useCartAttributes, useCartItemQuantityLimit, useCollection, useCollections, useCreateCart, useExposure, useGeoLocation, useHasPlusMemberInCart, useIntersection, usePlusAnnualProductVariant, usePlusMemberCheckoutCustomAttributes, usePlusMemberContext, usePlusMemberDeliveryCodes, usePlusMemberItemCustomAttributes, usePlusMemberNeedAddToCart, usePlusMonthlyProductVariant, usePrice, useProduct, useProductUrl, useProductsByHandles, useRemoveCartCodes, useRemoveCartLines, useReplaceCartPlusMember, useScriptAutoFreeGift, useSearch, useSelectedOptions, useShippingMethodAvailableCheck, useShippingMethods, useSite, useUpdateCartAttributes, useUpdateCartLines, useUpdateLineCodeAmountAttributes, useUpdatePlusMemberDeliveryOptions, useUpdateVariantQuery, useVariant, useVariantMedia };
2948
3232
  //# sourceMappingURL=index.mjs.map
2949
3233
  //# sourceMappingURL=index.mjs.map