@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.
@@ -6,6 +6,7 @@ var shopifySdk = require('@anker-in/shopify-sdk');
6
6
  var Cookies5 = require('js-cookie');
7
7
  var jsxRuntime = require('react/jsx-runtime');
8
8
  var Decimal2 = require('decimal.js');
9
+ var shopifyCore = require('@anker-in/shopify-core');
9
10
  var useSWR = require('swr');
10
11
  var ahooks = require('ahooks');
11
12
 
@@ -69,6 +70,7 @@ var CUSTOMER_ATTRIBUTE_KEY = "_discounts_function_env";
69
70
  var CUSTOMER_SCRIPT_GIFT_KEY = "_giveaway_gradient_gifts";
70
71
  var CODE_AMOUNT_KEY = "_sku_code_money";
71
72
  var SCRIPT_CODE_AMOUNT_KEY = "_code_money";
73
+ var MEMBER_PRICE_ATTRIBUTE_KEY = "_member_price";
72
74
  var MAIN_PRODUCT_CODE = ["WS24", "WSTD", "WS7D", "WSCP", "WSPE", "WSPD"];
73
75
 
74
76
  // src/hooks/cart/utils/normalize-add-to-cart-lines.ts
@@ -77,9 +79,10 @@ function normalizeAddToCartLines(lines) {
77
79
  const variant = line.variant;
78
80
  const product = variant.product;
79
81
  const quantity = line.quantity || 1;
80
- const price = variant.finalPrice?.amount ? Number(variant.finalPrice.amount) : variant.compareAtPrice?.amount ? Number(variant.compareAtPrice.amount) : variant.price?.amount ? Number(variant.price.amount) : 0;
81
- const subtotalAmount = price * quantity;
82
- const totalAmount = subtotalAmount;
82
+ const originalPrice = variant.price?.amount ? Number(variant.price.amount) : 0;
83
+ const finalPrice = variant.finalPrice?.amount === void 0 ? originalPrice : Number(variant.finalPrice?.amount);
84
+ const subtotalAmount = originalPrice * quantity;
85
+ const totalAmount = finalPrice * quantity;
83
86
  return {
84
87
  id: `temp-line-${index}-${variant.id}`,
85
88
  // Temporary ID for pre-cart lines
@@ -93,7 +96,7 @@ function normalizeAddToCartLines(lines) {
93
96
  customAttributes: line.attributes || [],
94
97
  variant: {
95
98
  id: variant.id,
96
- price,
99
+ price: finalPrice,
97
100
  listPrice: variant.compareAtPrice?.amount ? Number(variant.compareAtPrice.amount) : 0,
98
101
  sku: variant.sku || "",
99
102
  name: variant.title || "",
@@ -124,15 +127,16 @@ function createMockCartFromLines(lines, existingCart) {
124
127
  const normalizedLines = normalizeAddToCartLines(lines);
125
128
  const subtotalPrice = normalizedLines.reduce((sum, line) => sum + line.subtotalAmount, 0);
126
129
  const totalPrice = normalizedLines.reduce((sum, line) => sum + line.totalAmount, 0);
130
+ const currency = lines[0]?.variant?.price?.currencyCode;
127
131
  return {
128
132
  id: existingCart?.id || "temp-cart-id",
129
133
  customerId: existingCart?.customerId,
130
134
  email: existingCart?.email,
131
135
  createdAt: existingCart?.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
132
- currency: existingCart?.currency || { code: "USD" },
136
+ currency: existingCart?.currency || { code: currency },
133
137
  taxesIncluded: existingCart?.taxesIncluded,
134
138
  lineItems: normalizedLines,
135
- totallineItemsDiscount: 0,
139
+ totalLineItemsDiscount: 0,
136
140
  orderDiscounts: 0,
137
141
  lineItemsSubtotalPrice: subtotalPrice,
138
142
  subtotalPrice,
@@ -163,22 +167,12 @@ var getQuery = () => {
163
167
  }
164
168
  return theRequest;
165
169
  };
166
- function atobID(id) {
167
- if (id && typeof id === "string" && id.includes("/")) {
168
- return id.split("/").pop()?.split("?")?.shift();
169
- } else {
170
- return id;
171
- }
172
- }
173
- function btoaID(id, type = "ProductVariant") {
174
- return `gid://shopify/${type}/${id}`;
175
- }
176
170
  var getMatchedMainProductSubTotal = (cartData, variant_list, main_product) => {
177
171
  const isAllStoreVariant = main_product?.all_store_variant ?? false;
178
172
  const matchedList = cartData?.lineItems?.filter((line) => {
179
173
  const { is_gift } = getDiscountEnvAttributeValue(line.customAttributes);
180
174
  return isAllStoreVariant ? !is_gift : variant_list?.find((item) => {
181
- return !is_gift && atobID(line.variantId) === item;
175
+ return !is_gift && shopifyCore.atobID(line.variantId) === item;
182
176
  });
183
177
  });
184
178
  return matchedList?.reduce((acc, line) => {
@@ -404,43 +398,29 @@ var useCalcAutoFreeGift = (cart, autoFreeGiftConfig, customer, lines) => {
404
398
  }
405
399
  return { activeCampaign: null, subtotal: 0 };
406
400
  }, [autoFreeGiftConfig, effectiveCart, tags, dealsType]);
407
- const { qualifyingGift, nextTierGoal } = react.useMemo(() => {
401
+ const { qualifyingTier, nextTierGoal, actualThreshold, currentCurrency } = react.useMemo(() => {
408
402
  if (!activeCampaign || !activeCampaign.rule_result?.spend_get_reward?.gift_product) {
409
- return { qualifyingGift: null, nextTierGoal: null };
403
+ return { qualifyingTier: null, nextTierGoal: null, actualThreshold: 0, currentCurrency: "" };
410
404
  }
411
405
  const giftTiers = activeCampaign.rule_result.spend_get_reward.gift_product;
412
- const qualifyingTier = [...giftTiers].sort((a, b) => Number(b.spend_sum_money) - Number(a.spend_sum_money)).find((tier) => subtotal >= Number(tier.spend_sum_money));
413
- const nextGoal = giftTiers.find((tier) => subtotal < Number(tier.spend_sum_money));
414
- if (!qualifyingTier) {
415
- return { qualifyingGift: null, nextTierGoal: nextGoal || null };
416
- }
417
- const formattedGift = {
418
- tier: qualifyingTier,
419
- itemsToAdd: qualifyingTier.reward_list?.map((reward) => {
420
- const giftProduct = reward?.variant_list?.[0];
421
- if (!giftProduct) return null;
422
- return {
423
- variant: {
424
- id: btoaID(giftProduct.variant_id),
425
- handle: giftProduct.handle,
426
- sku: giftProduct.sku
427
- },
428
- quantity: reward?.get_unit || 1,
429
- attributes: [
430
- {
431
- key: CUSTOMER_ATTRIBUTE_KEY,
432
- value: JSON.stringify({
433
- is_gift: true,
434
- rule_id: activeCampaign.rule_id,
435
- spend_sum_money: qualifyingTier.spend_sum_money
436
- })
437
- }
438
- ]
439
- };
440
- }).filter((item) => item !== null)
406
+ const currentCurrency2 = effectiveCart?.currency?.code || "";
407
+ console.log("currentCurrency useCalcAutoFreeGift", effectiveCart, currentCurrency2);
408
+ const getThresholdAmount = (tier) => {
409
+ if (tier.spend_sum_money_multi_markets?.[currentCurrency2]?.value) {
410
+ return Number(tier.spend_sum_money_multi_markets[currentCurrency2].value);
411
+ }
412
+ return Number(tier.spend_sum_money || 0);
441
413
  };
442
- return { qualifyingGift: formattedGift, nextTierGoal: nextGoal || null };
443
- }, [activeCampaign, subtotal]);
414
+ const qualifyingTier2 = [...giftTiers].sort((a, b) => getThresholdAmount(b) - getThresholdAmount(a)).find((tier) => subtotal >= getThresholdAmount(tier));
415
+ const nextGoal = giftTiers.find((tier) => subtotal < getThresholdAmount(tier));
416
+ const actualThreshold2 = qualifyingTier2 ? getThresholdAmount(qualifyingTier2) : 0;
417
+ return {
418
+ qualifyingTier: qualifyingTier2,
419
+ nextTierGoal: nextGoal || null,
420
+ actualThreshold: actualThreshold2,
421
+ currentCurrency: currentCurrency2
422
+ };
423
+ }, [activeCampaign, subtotal, effectiveCart]);
444
424
  const giftHandles = react.useMemo(() => {
445
425
  const giftVariant = autoFreeGiftConfig.map(
446
426
  (item) => item.rule_result?.spend_get_reward?.gift_product?.map(
@@ -456,24 +436,82 @@ var useCalcAutoFreeGift = (cart, autoFreeGiftConfig, customer, lines) => {
456
436
  }
457
437
  return true;
458
438
  }, [giftHandles]);
459
- const { data: giftProductsResult } = useSWR__default.default(shouldFetch ? giftHandles : null, async () => {
460
- const res = await shopifySdk.getProductsByHandles(client, {
461
- handles: giftHandles,
462
- locale
463
- });
464
- const result = Array.isArray(res) ? res : [];
465
- giftProductsCache.current = {
466
- data: result,
467
- giftHandles: [...giftHandles]
468
- };
469
- return result;
470
- });
439
+ const { data: giftProductsResult } = useSWR__default.default(
440
+ shouldFetch ? giftHandles : null,
441
+ async () => {
442
+ const res = await shopifySdk.getProductsByHandles(client, {
443
+ handles: giftHandles,
444
+ locale
445
+ });
446
+ const result = Array.isArray(res) ? res : [];
447
+ giftProductsCache.current = {
448
+ data: result,
449
+ giftHandles: [...giftHandles]
450
+ };
451
+ return result;
452
+ },
453
+ {
454
+ revalidateOnFocus: false
455
+ }
456
+ );
471
457
  const finalGiftProductsResult = react.useMemo(() => {
472
458
  if (giftProductsCache.current && !shouldFetch) {
473
459
  return giftProductsCache.current.data || void 0;
474
460
  }
475
461
  return giftProductsResult;
476
462
  }, [giftProductsResult, shouldFetch]);
463
+ const qualifyingGift = react.useMemo(() => {
464
+ if (!qualifyingTier || !activeCampaign) {
465
+ return null;
466
+ }
467
+ const itemsToAdd = qualifyingTier.reward_list?.map((reward) => {
468
+ if (!reward.variant_list || reward.variant_list.length === 0) {
469
+ return null;
470
+ }
471
+ let selectedGiftProduct = null;
472
+ for (const giftVariant of reward.variant_list) {
473
+ const productInfo = finalGiftProductsResult?.find(
474
+ (p) => p.handle === giftVariant.handle
475
+ );
476
+ if (productInfo) {
477
+ const variantInfo = productInfo.variants?.find((v) => v.sku === giftVariant.sku);
478
+ if (variantInfo?.availableForSale) {
479
+ selectedGiftProduct = giftVariant;
480
+ break;
481
+ }
482
+ }
483
+ }
484
+ if (!selectedGiftProduct) {
485
+ selectedGiftProduct = reward.variant_list[0];
486
+ }
487
+ return {
488
+ variant: {
489
+ id: shopifyCore.btoaID(selectedGiftProduct.variant_id),
490
+ handle: selectedGiftProduct.handle,
491
+ sku: selectedGiftProduct.sku
492
+ },
493
+ quantity: reward?.get_unit || 1,
494
+ attributes: [
495
+ {
496
+ key: CUSTOMER_ATTRIBUTE_KEY,
497
+ value: JSON.stringify({
498
+ is_gift: true,
499
+ rule_id: activeCampaign.rule_id,
500
+ spend_sum_money: actualThreshold,
501
+ // 使用实际的门槛金额(多币种支持)
502
+ currency_code: currentCurrency
503
+ // 记录当前币种
504
+ })
505
+ }
506
+ ]
507
+ };
508
+ }).filter((item) => item !== null);
509
+ const formattedGift = {
510
+ tier: qualifyingTier,
511
+ itemsToAdd
512
+ };
513
+ return formattedGift;
514
+ }, [qualifyingTier, activeCampaign, finalGiftProductsResult, actualThreshold, currentCurrency]);
477
515
  return {
478
516
  qualifyingGift,
479
517
  nextTierGoal,
@@ -520,12 +558,14 @@ var useScriptAutoFreeGift = ({
520
558
  upgrade_multiple2 = 1.2;
521
559
  upgrade_value2 = 40;
522
560
  }
523
- effectiveCart?.lineItems?.forEach(({ customAttributes }) => {
524
- customAttributes?.forEach(({ key, value }) => {
525
- if (key === "_amount_upgrade_multiple") upgrade_multiple2 = Number(value) || 1;
526
- if (key === "_amount_upgrade_value") upgrade_value2 = Number(value) || 0;
527
- });
528
- });
561
+ effectiveCart?.lineItems?.forEach(
562
+ ({ customAttributes }) => {
563
+ customAttributes?.forEach(({ key, value }) => {
564
+ if (key === "_amount_upgrade_multiple") upgrade_multiple2 = Number(value) || 1;
565
+ if (key === "_amount_upgrade_value") upgrade_value2 = Number(value) || 0;
566
+ });
567
+ }
568
+ );
529
569
  return [upgrade_multiple2, upgrade_value2];
530
570
  }, [effectiveCart?.lineItems, points_subscribe]);
531
571
  const breakpoints = react.useMemo(() => {
@@ -590,18 +630,24 @@ var useScriptAutoFreeGift = ({
590
630
  const nextLevel = levelIndex > 0 ? sortedLevels[levelIndex - 1] ?? null : null;
591
631
  return [currentLevel, nextLevel];
592
632
  }, [breakpoints, involvedSubTotal, involvedLines.length]);
593
- const { data: giftProductsResult } = useSWR__default.default(shouldFetch ? giftHandles : null, async () => {
594
- const res = await shopifySdk.getProductsByHandles(client, {
595
- handles: giftHandles,
596
- locale
597
- });
598
- const result = Array.isArray(res) ? res : [];
599
- giftProductsCache.current = {
600
- data: result,
601
- giftHandles: [...giftHandles]
602
- };
603
- return result;
604
- });
633
+ const { data: giftProductsResult } = useSWR__default.default(
634
+ shouldFetch ? giftHandles : null,
635
+ async () => {
636
+ const res = await shopifySdk.getProductsByHandles(client, {
637
+ handles: giftHandles,
638
+ locale
639
+ });
640
+ const result = Array.isArray(res) ? res : [];
641
+ giftProductsCache.current = {
642
+ data: result,
643
+ giftHandles: [...giftHandles]
644
+ };
645
+ return result;
646
+ },
647
+ {
648
+ revalidateOnFocus: false
649
+ }
650
+ );
605
651
  const finalGiftProductsResult = react.useMemo(() => {
606
652
  if (giftProductsCache.current && !shouldFetch) {
607
653
  return giftProductsCache.current.data || void 0;
@@ -634,9 +680,9 @@ var useScriptAutoFreeGift = ({
634
680
  };
635
681
  };
636
682
  var CartContext = react.createContext(null);
637
- function useCartContext() {
683
+ function useCartContext(options) {
638
684
  const context = react.useContext(CartContext);
639
- if (!context) {
685
+ if (!context && true) {
640
686
  throw new Error("useCartContext must be used within a CartProvider");
641
687
  }
642
688
  return context;
@@ -678,11 +724,23 @@ function useAddCartLines(options) {
678
724
  const { mutateCart, metafieldIdentifiers } = useCartContext();
679
725
  const addLines = react.useCallback(
680
726
  async (_key, { arg }) => {
681
- let updatedCart = await shopifySdk.addCartLines(client, {
682
- ...arg,
683
- metafieldIdentifiers,
684
- cookieAdapter: cartCookieAdapter
685
- });
727
+ const { cartId, lines } = arg;
728
+ const id = cartId || cartCookieAdapter?.getCartId(locale);
729
+ let updatedCart;
730
+ if (!id) {
731
+ updatedCart = await shopifySdk.createCart(client, {
732
+ lines,
733
+ metafieldIdentifiers,
734
+ cookieAdapter: cartCookieAdapter
735
+ });
736
+ } else {
737
+ updatedCart = await shopifySdk.addCartLines(client, {
738
+ cartId: id,
739
+ lines,
740
+ metafieldIdentifiers,
741
+ cookieAdapter: cartCookieAdapter
742
+ });
743
+ }
686
744
  if (updatedCart) {
687
745
  const unApplicableCodes = updatedCart.discountCodes.filter((item) => !item.applicable).map((item) => item.code);
688
746
  if (unApplicableCodes.length > 0) {
@@ -729,7 +787,7 @@ var trackAddToCartGA = ({
729
787
  const currencyCode = variant.product?.price?.currencyCode;
730
788
  const totalPrice = lineItems?.reduce(
731
789
  (prev, { variant: variant2 }) => prev.plus(
732
- variant2?.finalPrice?.amount ?? variant2?.compareAtPrice?.amount ?? variant2?.price?.amount ?? 0
790
+ variant2?.finalPrice?.amount === void 0 ? Number(variant2?.price?.amount) || 0 : Number(variant2?.finalPrice?.amount) || 0
733
791
  ),
734
792
  new Decimal2__default.default(0)
735
793
  ).toNumber();
@@ -762,10 +820,10 @@ var trackBuyNowGA = ({
762
820
  return;
763
821
  }
764
822
  const { variant } = lineItems[0];
765
- const currencyCode = variant.price?.currencyCode;
823
+ const currencyCode = variant.product?.price?.currencyCode || variant.price?.currencyCode;
766
824
  const totalPrice = lineItems?.reduce(
767
825
  (prev, { variant: variant2 }) => prev.plus(
768
- variant2?.finalPrice?.amount ?? variant2?.compareAtPrice?.amount ?? (variant2?.price?.amount || 0)
826
+ variant2?.finalPrice?.amount === void 0 ? Number(variant2?.price?.amount) || 0 : Number(variant2?.finalPrice?.amount) || 0
769
827
  ),
770
828
  new Decimal2__default.default(0)
771
829
  ).toNumber();
@@ -839,7 +897,7 @@ function useApplyCartCodes(options) {
839
897
  if (!discountCodes?.length) {
840
898
  throw new Error("Invalid input used for this operation: Miss discountCode");
841
899
  }
842
- const cartId = providedCartId ? void 0 : providedCartId || cart?.id;
900
+ const cartId = providedCartId || cart?.id;
843
901
  if (!cartId) {
844
902
  return void 0;
845
903
  }
@@ -852,12 +910,18 @@ function useApplyCartCodes(options) {
852
910
  cookieAdapter: cartCookieAdapter,
853
911
  metafieldIdentifiers
854
912
  });
913
+ const unApplicableCodes = discountCodes.filter(
914
+ (code) => updatedCart?.discountCodes?.find((item) => item.code === code && !item.applicable)
915
+ );
916
+ if (unApplicableCodes.length) {
917
+ throw new Error(`${unApplicableCodes.join(", ")} is not applicable to the cart`);
918
+ }
855
919
  if (updatedCart) {
856
920
  mutateCart(updatedCart);
857
921
  }
858
922
  return updatedCart;
859
923
  },
860
- [client, locale, cartCookieAdapter, mutateCart, cart]
924
+ [client, locale, cartCookieAdapter, mutateCart, cart, metafieldIdentifiers]
861
925
  );
862
926
  return useSWRMutation__default.default("apply-codes", applyCodes, options);
863
927
  }
@@ -867,7 +931,7 @@ function useRemoveCartCodes(options) {
867
931
  const removeCodes = react.useCallback(
868
932
  async (_key, { arg }) => {
869
933
  const { cartId: providedCartId, discountCodes } = arg;
870
- const cartId = providedCartId ? void 0 : providedCartId || cart?.id;
934
+ const cartId = providedCartId || cart?.id;
871
935
  const codes = cart?.discountCodes?.filter((code) => !!code.applicable) || [];
872
936
  const leftCodes = codes.filter((code) => discountCodes?.length ? !discountCodes.includes(code.code) : code.code).map((code) => code.code);
873
937
  const updatedCart = await shopifySdk.updateCartCodes(client, {
@@ -881,18 +945,105 @@ function useRemoveCartCodes(options) {
881
945
  }
882
946
  return updatedCart;
883
947
  },
884
- [client, locale, cartCookieAdapter, mutateCart, cart]
948
+ [client, locale, cartCookieAdapter, mutateCart, cart, metafieldIdentifiers]
885
949
  );
886
950
  return useSWRMutation__default.default("remove-codes", removeCodes, options);
887
951
  }
952
+ var initSameLinesAttributes = ({
953
+ cart,
954
+ line
955
+ }) => {
956
+ const sameLineInCart = cart?.lineItems.find(
957
+ (lineInCart) => lineInCart.variant.sku === line.variant?.sku && lineInCart.product?.handle === line.variant?.product?.handle
958
+ );
959
+ const codeAmountAttribute = sameLineInCart?.customAttributes?.find(
960
+ (attr) => attr.key === CODE_AMOUNT_KEY
961
+ );
962
+ const scriptCodeAmountAttribute = sameLineInCart?.customAttributes?.find(
963
+ (attr) => attr.key === SCRIPT_CODE_AMOUNT_KEY
964
+ );
965
+ let functionAttribute = null;
966
+ try {
967
+ functionAttribute = sameLineInCart?.customAttributes?.find(
968
+ (attr) => attr.key === CUSTOMER_ATTRIBUTE_KEY && JSON.parse(attr.value)?.discounted_amount
969
+ );
970
+ } catch (error) {
971
+ }
972
+ if (codeAmountAttribute || functionAttribute || scriptCodeAmountAttribute) {
973
+ return {
974
+ ...line,
975
+ attributes: [
976
+ ...line.attributes || [],
977
+ codeAmountAttribute,
978
+ functionAttribute,
979
+ scriptCodeAmountAttribute
980
+ ].filter(Boolean)
981
+ };
982
+ }
983
+ return line;
984
+ };
985
+ var initDiscountAttributes = ({ line }) => {
986
+ let itemAttributes = line.attributes || [];
987
+ const functionEnvAttribute = itemAttributes.find((attr) => attr.key === CUSTOMER_ATTRIBUTE_KEY);
988
+ if (!functionEnvAttribute) {
989
+ itemAttributes = itemAttributes.concat([
990
+ {
991
+ key: CUSTOMER_ATTRIBUTE_KEY,
992
+ value: JSON.stringify({
993
+ is_gift: false,
994
+ discounted_amount: line.variant?.finalPrice?.amount === void 0 ? Number(line.variant?.price?.amount) * (line.quantity || 1) : Number(line.variant?.finalPrice?.amount) * (line.quantity || 1)
995
+ })
996
+ }
997
+ ]);
998
+ }
999
+ const memberPriceAttribute = itemAttributes.find(
1000
+ (attr) => attr.key === MEMBER_PRICE_ATTRIBUTE_KEY
1001
+ );
1002
+ const coupon = line.coupon;
1003
+ if (!memberPriceAttribute && coupon) {
1004
+ itemAttributes = itemAttributes.concat([
1005
+ {
1006
+ key: MEMBER_PRICE_ATTRIBUTE_KEY,
1007
+ value: JSON.stringify({ code: coupon.code })
1008
+ }
1009
+ ]);
1010
+ }
1011
+ const couponDiscountAttribute = itemAttributes.find(
1012
+ (attr) => attr.key === CODE_AMOUNT_KEY || attr.key === SCRIPT_CODE_AMOUNT_KEY
1013
+ );
1014
+ if (!couponDiscountAttribute && coupon && Number(coupon?.amount) > 0) {
1015
+ itemAttributes = itemAttributes.concat([
1016
+ {
1017
+ key: CODE_AMOUNT_KEY,
1018
+ value: new Decimal2__default.default(coupon.amount).times(line.quantity || 1).toString()
1019
+ },
1020
+ {
1021
+ key: SCRIPT_CODE_AMOUNT_KEY,
1022
+ value: new Decimal2__default.default(coupon.amount).times(line.quantity || 1).toString()
1023
+ }
1024
+ ]);
1025
+ }
1026
+ return { ...line, attributes: itemAttributes };
1027
+ };
1028
+ var getLinesWithAttributes = ({
1029
+ cart,
1030
+ lineItems
1031
+ }) => {
1032
+ return lineItems.map((line) => {
1033
+ const sameLine = initSameLinesAttributes({ cart, line });
1034
+ const functionLine = initDiscountAttributes({ line: sameLine });
1035
+ return functionLine;
1036
+ });
1037
+ };
888
1038
 
889
1039
  // src/hooks/cart/use-add-to-cart.ts
890
1040
  function useAddToCart({ withTrack = true } = {}, swrOptions) {
891
- const { client, config, locale, cartCookieAdapter, userAdapter } = useShopify();
892
- const { cart } = useCartContext();
1041
+ const { client, config, locale, cartCookieAdapter, userAdapter, performanceAdapter } = useShopify();
1042
+ const { cart, addCustomAttributes } = useCartContext();
893
1043
  const { trigger: applyCartCodes } = useApplyCartCodes();
894
1044
  const { trigger: removeInvalidCodes } = useRemoveCartCodes();
895
1045
  const { trigger: addCartLines2 } = useAddCartLines();
1046
+ const { trigger: createCart4 } = useCreateCart();
896
1047
  const addToCart = react.useCallback(
897
1048
  async (_key, { arg }) => {
898
1049
  const {
@@ -903,12 +1054,15 @@ function useAddToCart({ withTrack = true } = {}, swrOptions) {
903
1054
  buyerIdentity,
904
1055
  needCreateCart = false,
905
1056
  onCodesInvalid,
906
- replaceExistingCodes
1057
+ replaceExistingCodes,
1058
+ customAttributes
907
1059
  } = arg;
908
1060
  if (!lineItems || lineItems.length === 0) {
909
1061
  return;
910
1062
  }
911
- const lines = lineItems.map((item) => ({
1063
+ performanceAdapter?.addToCartStart();
1064
+ const linesWithFunctionAttributes = getLinesWithAttributes({ cart, lineItems });
1065
+ const lines = linesWithFunctionAttributes.map((item) => ({
912
1066
  merchandiseId: item.variant?.id || "",
913
1067
  quantity: item.quantity || 1,
914
1068
  attributes: item.attributes,
@@ -917,36 +1071,45 @@ function useAddToCart({ withTrack = true } = {}, swrOptions) {
917
1071
  if (lines.length === 0) {
918
1072
  return;
919
1073
  }
920
- const cartId = needCreateCart ? void 0 : providedCartId || cart?.id;
921
- let resultCart = await addCartLines2({
922
- cartId,
923
- lines,
924
- buyerIdentity
925
- });
926
- if (!resultCart) {
927
- return void 0;
928
- }
929
- console.log("npm addCartLines resultCart", resultCart);
930
- if (resultCart.discountCodes && resultCart.discountCodes.length > 0) {
931
- const unapplicableCodes = resultCart.discountCodes.filter((item) => !item.applicable).map((item) => item.code);
932
- if (unapplicableCodes.length > 0) {
933
- if (onCodesInvalid) {
934
- const handledCart = await onCodesInvalid(resultCart, unapplicableCodes);
935
- if (handledCart) {
936
- resultCart = handledCart;
1074
+ let cartId = needCreateCart ? void 0 : providedCartId || cart?.id;
1075
+ let resultCart = null;
1076
+ if (!cartId) {
1077
+ resultCart = await createCart4({
1078
+ lines,
1079
+ buyerIdentity,
1080
+ discountCodes,
1081
+ customAttributes
1082
+ });
1083
+ } else {
1084
+ resultCart = await addCartLines2({
1085
+ cartId,
1086
+ lines
1087
+ });
1088
+ console.log("npm addCartLines resultCart", resultCart);
1089
+ if (resultCart && resultCart.discountCodes && resultCart.discountCodes.length > 0) {
1090
+ const unapplicableCodes = resultCart.discountCodes.filter((item) => !item.applicable).map((item) => item.code);
1091
+ if (unapplicableCodes.length > 0) {
1092
+ if (onCodesInvalid) {
1093
+ const handledCart = await onCodesInvalid(resultCart, unapplicableCodes);
1094
+ if (handledCart) {
1095
+ resultCart = handledCart;
1096
+ }
1097
+ } else {
1098
+ await removeInvalidCodes({
1099
+ discountCodes: unapplicableCodes
1100
+ });
937
1101
  }
938
- } else {
939
- await removeInvalidCodes({
940
- discountCodes: unapplicableCodes
941
- });
942
1102
  }
943
1103
  }
944
- }
945
- if (discountCodes && discountCodes.length > 0) {
946
- applyCartCodes({
947
- replaceExistingCodes,
948
- discountCodes
949
- });
1104
+ if (resultCart && discountCodes && discountCodes.length > 0) {
1105
+ applyCartCodes({
1106
+ replaceExistingCodes,
1107
+ discountCodes
1108
+ });
1109
+ }
1110
+ if (customAttributes && customAttributes.length > 0) {
1111
+ addCustomAttributes(customAttributes);
1112
+ }
950
1113
  }
951
1114
  if (withTrack) {
952
1115
  trackAddToCartGA({
@@ -955,9 +1118,24 @@ function useAddToCart({ withTrack = true } = {}, swrOptions) {
955
1118
  });
956
1119
  trackAddToCartFBQ({ lineItems });
957
1120
  }
1121
+ performanceAdapter?.addToCartEnd();
958
1122
  return resultCart;
959
1123
  },
960
- [client, locale, cartCookieAdapter, userAdapter, cart, withTrack]
1124
+ [
1125
+ client,
1126
+ locale,
1127
+ cartCookieAdapter,
1128
+ userAdapter,
1129
+ cart,
1130
+ withTrack,
1131
+ performanceAdapter,
1132
+ createCart4,
1133
+ addCartLines2,
1134
+ applyCartCodes,
1135
+ removeInvalidCodes,
1136
+ addCustomAttributes,
1137
+ config
1138
+ ]
961
1139
  );
962
1140
  return useSWRMutation__default.default("add-to-cart", addToCart, swrOptions);
963
1141
  }
@@ -974,9 +1152,10 @@ function useUpdateCartLines(options) {
974
1152
  if (updatedCart) {
975
1153
  mutateCart(updatedCart);
976
1154
  }
1155
+ console.log("use-update-cart-lines updatedCart", metafieldIdentifiers, updatedCart);
977
1156
  return updatedCart;
978
1157
  },
979
- [client, locale, cartCookieAdapter, mutateCart]
1158
+ [client, locale, cartCookieAdapter, mutateCart, metafieldIdentifiers]
980
1159
  );
981
1160
  return useSWRMutation__default.default("update-cart-lines", updateLines, options);
982
1161
  }
@@ -1015,7 +1194,7 @@ function useRemoveCartLines(options) {
1015
1194
  }
1016
1195
  return updatedCart;
1017
1196
  },
1018
- [client, locale, cartCookieAdapter, mutateCart]
1197
+ [client, locale, cartCookieAdapter, mutateCart, metafieldIdentifiers]
1019
1198
  );
1020
1199
  return useSWRMutation__default.default("remove-cart-lines", removeLines, options);
1021
1200
  }
@@ -1034,7 +1213,7 @@ function useUpdateCartAttributes(mutate, metafieldIdentifiers, options) {
1034
1213
  }
1035
1214
  return updatedCart;
1036
1215
  },
1037
- [client, locale, cartCookieAdapter, mutate]
1216
+ [client, locale, cartCookieAdapter, mutate, metafieldIdentifiers]
1038
1217
  );
1039
1218
  return useSWRMutation__default.default("update-cart-attributes", updateAttributes, options);
1040
1219
  }
@@ -1056,12 +1235,15 @@ function useBuyNow({ withTrack = true } = {}, swrOptions) {
1056
1235
  if (!lineItems || lineItems.length === 0) {
1057
1236
  return;
1058
1237
  }
1059
- const lines = lineItems.map((item) => ({
1238
+ const linesWithFunctionAttributes = getLinesWithAttributes({
1239
+ lineItems
1240
+ });
1241
+ const lines = linesWithFunctionAttributes.map((item) => ({
1060
1242
  merchandiseId: item.variant?.id || "",
1061
1243
  quantity: item.quantity || 1,
1062
1244
  attributes: item.attributes,
1063
1245
  sellingPlanId: item.sellingPlanId
1064
- })).filter((item) => item.merchandiseId && item.quantity);
1246
+ })).filter((item) => item.merchandiseId);
1065
1247
  if (lines.length === 0) {
1066
1248
  return;
1067
1249
  }
@@ -1116,17 +1298,41 @@ function useCalcGiftsFromLines({
1116
1298
  lines
1117
1299
  });
1118
1300
  const allGiftLines = react.useMemo(() => {
1119
- const functionGiftLines = functionGift.qualifyingGift?.itemsToAdd || [];
1120
- const scriptGiftLines = scriptGift.freeGiftLevel ? scriptGift.freeGiftLevel.giveawayProducts.map((product) => {
1121
- const giftProduct = scriptGift.giftProductsResult?.find(
1122
- (p) => p.handle === product.handle
1301
+ const functionGiftLines = (functionGift.qualifyingGift?.itemsToAdd || []).map((item) => {
1302
+ const product = functionGift.giftProductsResult?.find(
1303
+ (product2) => product2.handle === item.variant.handle
1123
1304
  );
1124
- const variant = giftProduct?.variants?.[0];
1305
+ const variants = product?.variants;
1306
+ const variant = Array.isArray(variants) ? variants.find((v) => v.sku === item.variant.sku) : void 0;
1307
+ if (!variant) {
1308
+ console.warn(
1309
+ `Function gift: Variant not found for handle=${item.variant.handle}, sku=${item.variant.sku}`
1310
+ );
1311
+ return null;
1312
+ }
1125
1313
  return {
1126
1314
  variant: {
1127
- id: variant?.id || "",
1128
- handle: product.handle,
1129
- sku: product.sku
1315
+ ...variant,
1316
+ product
1317
+ },
1318
+ quantity: item.quantity ?? 1,
1319
+ attributes: item.attributes
1320
+ };
1321
+ }).filter((item) => item !== null);
1322
+ const scriptGiftLines = scriptGift.freeGiftLevel ? scriptGift.freeGiftLevel.giveawayProducts.map((item) => {
1323
+ const product = scriptGift.giftProductsResult?.find(
1324
+ (product2) => product2.handle === item.handle
1325
+ );
1326
+ const variants = product?.variants;
1327
+ const variant = Array.isArray(variants) ? variants.find((v) => v.sku === item.sku) : void 0;
1328
+ if (!variant) {
1329
+ console.warn(`Script gift: Variant not found for handle=${item.handle}, sku=${item.sku}`);
1330
+ return null;
1331
+ }
1332
+ return {
1333
+ variant: {
1334
+ ...variant,
1335
+ product
1130
1336
  },
1131
1337
  quantity: 1,
1132
1338
  attributes: [
@@ -1136,10 +1342,11 @@ function useCalcGiftsFromLines({
1136
1342
  }
1137
1343
  ]
1138
1344
  };
1139
- }).filter((item) => item.variant.id) : [];
1345
+ }).filter((item) => item !== null) : [];
1140
1346
  return [...functionGiftLines, ...scriptGiftLines];
1141
1347
  }, [
1142
1348
  functionGift.qualifyingGift,
1349
+ functionGift.giftProductsResult,
1143
1350
  scriptGift.freeGiftLevel,
1144
1351
  scriptGift.giftProductsResult,
1145
1352
  scriptGiveawayKey
@@ -1174,7 +1381,7 @@ var useCalcOrderDiscount = (cart, orderDiscountConfig, customer) => {
1174
1381
  const isCustomerLoading = react.useMemo(() => !customer ? true : false, [customer]);
1175
1382
  const dealsType = "";
1176
1383
  const { activeCampaign, subtotal } = react.useMemo(() => {
1177
- for (const campaign of orderDiscountConfig) {
1384
+ for (const campaign of orderDiscountConfig || []) {
1178
1385
  const { rule_conditions = [], result_detail } = campaign;
1179
1386
  const { main_product, order_discount_conf } = result_detail || {};
1180
1387
  const isPreCheckPassed = preCheck(rule_conditions, tags, []);
@@ -1204,9 +1411,12 @@ var useCalcOrderDiscount = (cart, orderDiscountConfig, customer) => {
1204
1411
  discountAmount: 0
1205
1412
  };
1206
1413
  }
1207
- const tieredDiscounts = activeCampaign.result_detail.order_discount_conf.tiered_discounts;
1208
- const qualifyingTier = [...tieredDiscounts].reverse().find((tier) => subtotal >= Number(tier.amount));
1209
- const nextGoal = tieredDiscounts.find((tier) => subtotal < Number(tier.amount));
1414
+ const currentCurrency = cart?.currency?.code || "";
1415
+ console.log("currentCurrency", cart, currentCurrency);
1416
+ const orderDiscountConf = activeCampaign.result_detail.order_discount_conf;
1417
+ const tieredDiscounts = orderDiscountConf.tiered_discounts_markets?.[currentCurrency] || orderDiscountConf.tiered_discounts;
1418
+ const qualifyingTier = [...tieredDiscounts].sort((a, b) => Number(b.amount) - Number(a.amount)).find((tier) => subtotal >= Number(tier.amount));
1419
+ const nextGoal = [...tieredDiscounts].sort((a, b) => Number(a.amount) - Number(b.amount)).find((tier) => subtotal < Number(tier.amount));
1210
1420
  if (!qualifyingTier) {
1211
1421
  return {
1212
1422
  qualifyingDiscount: null,
@@ -1274,12 +1484,10 @@ function useHasPlusMemberInCart({
1274
1484
  };
1275
1485
  }, [cart?.lineItems, plus_monthly_product, plus_annual_product]);
1276
1486
  }
1277
-
1278
- // src/hooks/cart/feature/use-cart-attributes.ts
1279
1487
  var getReferralAttributes = () => {
1280
- const inviteCode = Cookies5__default.default.get("invite_code");
1281
- const playModeId = Cookies5__default.default.get("playModeId");
1282
- const popup = Cookies5__default.default.get("_popup");
1488
+ const inviteCode = shopifySdk.getLocalStorage("inviteCode") || Cookies5__default.default.get("inviteCode");
1489
+ const playModeId = shopifySdk.getLocalStorage("playModeId") || Cookies5__default.default.get("playModeId");
1490
+ const popup = shopifySdk.getLocalStorage("_popup") || Cookies5__default.default.get("_popup");
1283
1491
  if (inviteCode && playModeId) {
1284
1492
  return popup ? [
1285
1493
  { key: "_invite_code", value: inviteCode ? inviteCode : "" },
@@ -1303,8 +1511,6 @@ var useCartAttributes = ({
1303
1511
  memberSetting,
1304
1512
  cart
1305
1513
  });
1306
- console.log("memberSetting", memberSetting);
1307
- console.log("hasPlusMember", hasPlusMember);
1308
1514
  react.useEffect(() => {
1309
1515
  setCurrentUrl(window.location.href);
1310
1516
  }, []);
@@ -1330,7 +1536,7 @@ var useCartAttributes = ({
1330
1536
  return "new_user_login";
1331
1537
  }, [customer]);
1332
1538
  const memberAttributes = react.useMemo(() => {
1333
- return [
1539
+ const attributes = [
1334
1540
  {
1335
1541
  key: "_token",
1336
1542
  value: profile?.token
@@ -1351,17 +1557,28 @@ var useCartAttributes = ({
1351
1557
  value: profile?.token ? "true" : "false"
1352
1558
  }
1353
1559
  ];
1560
+ if (profile?.token) {
1561
+ attributes.push({
1562
+ key: "_login_user",
1563
+ value: "1"
1564
+ });
1565
+ }
1566
+ return attributes;
1354
1567
  }, [profile?.memberType, profile?.token, userType, hasPlusMember]);
1355
1568
  const functionAttributes = react.useMemo(() => {
1356
- return [
1357
- cart?.discountCodes && {
1569
+ const hasFunctionEnvAttribute = cart?.lineItems.some(
1570
+ (item) => item.customAttributes?.some((attr) => attr.key === CUSTOMER_ATTRIBUTE_KEY)
1571
+ );
1572
+ const discountCodes = cart?.discountCodes.map((item) => item.code).filter((code) => code) || [];
1573
+ return hasFunctionEnvAttribute ? [
1574
+ {
1358
1575
  key: "_discounts_function_env",
1359
1576
  value: JSON.stringify({
1360
- discount_code: cart?.discountCodes.map((item) => item.code),
1577
+ discount_code: discountCodes,
1361
1578
  user_tags: customer?.tags || []
1362
1579
  })
1363
1580
  }
1364
- ];
1581
+ ] : [];
1365
1582
  }, [cart]);
1366
1583
  const presellAttributes = react.useMemo(() => {
1367
1584
  return [
@@ -1393,18 +1610,50 @@ var useCartAttributes = ({
1393
1610
  }
1394
1611
  ];
1395
1612
  }, [currentUrl]);
1613
+ const commonAttributes = react.useMemo(
1614
+ () => [
1615
+ ...memberAttributes,
1616
+ ...functionAttributes,
1617
+ ...presellAttributes,
1618
+ ...weightAttributes,
1619
+ ...trackingAttributes,
1620
+ ...getReferralAttributes()
1621
+ ].filter((item) => item?.value),
1622
+ [memberAttributes, functionAttributes, presellAttributes, weightAttributes, trackingAttributes]
1623
+ );
1624
+ const extraAttributesInCart = react.useMemo(() => {
1625
+ const commonAttributeKeys = [
1626
+ // member attributes
1627
+ "_token",
1628
+ "_member_type",
1629
+ "_user_type",
1630
+ "_is_login",
1631
+ "_login_user",
1632
+ // function attributes
1633
+ "_discounts_function_env",
1634
+ // presell attributes
1635
+ "_presale",
1636
+ // weight attributes
1637
+ "_weight",
1638
+ "_app_source_name",
1639
+ // tracking attributes
1640
+ "utm_params",
1641
+ // referral attributes
1642
+ "_invite_code",
1643
+ "_play_mode_id",
1644
+ "_popup"
1645
+ ];
1646
+ return cart?.customAttributes?.filter(
1647
+ (item) => !commonAttributeKeys.includes(item.key)
1648
+ ) || [];
1649
+ }, [cart]);
1396
1650
  return react.useMemo(
1397
1651
  () => ({
1398
- attributes: [
1399
- ...memberAttributes,
1400
- ...functionAttributes,
1401
- ...presellAttributes,
1402
- ...weightAttributes,
1403
- ...trackingAttributes,
1404
- ...getReferralAttributes()
1405
- ].filter((item) => item?.value)
1652
+ attributes: [...commonAttributes, ...extraAttributesInCart].filter(
1653
+ (item) => item?.value
1654
+ )
1406
1655
  }),
1407
- [memberAttributes, functionAttributes, presellAttributes, weightAttributes, trackingAttributes]
1656
+ [commonAttributes, extraAttributesInCart]
1408
1657
  );
1409
1658
  };
1410
1659
  var DEFAULT_MIN = 1;
@@ -1467,7 +1716,7 @@ var useUpdateLineCodeAmountAttributes = ({
1467
1716
  );
1468
1717
  const functionEnvValue = getDiscountEnvAttributeValue(line.customAttributes);
1469
1718
  const hasSameFunctionEnvAttribute = Number(functionEnvValue.discounted_amount) === Number(line.totalAmount);
1470
- if (!hasSameFunctionEnvAttribute && hasFunctionEnvAttribute) {
1719
+ if (!hasSameFunctionEnvAttribute && hasFunctionEnvAttribute && !functionEnvValue.is_gift) {
1471
1720
  attrNeedUpdate.push({
1472
1721
  key: CUSTOMER_ATTRIBUTE_KEY,
1473
1722
  value: JSON.stringify({
@@ -1506,29 +1755,22 @@ var useUpdateLineCodeAmountAttributes = ({
1506
1755
  }).filter(
1507
1756
  ({ attrNeedUpdate, attrNeedDelete }) => attrNeedUpdate.length || attrNeedDelete.length
1508
1757
  ).map(({ line, attrNeedUpdate, attrNeedDelete }) => {
1758
+ let lineId = line.id;
1759
+ let attributes = line.customAttributes || [];
1760
+ if (attrNeedDelete.length) {
1761
+ attributes = attributes.filter(
1762
+ (attr) => !attrNeedDelete.includes(attr.key)
1763
+ );
1764
+ }
1509
1765
  if (attrNeedUpdate.length) {
1510
- return {
1511
- id: line.id,
1512
- attributes: [
1513
- ...line.customAttributes?.filter(
1514
- (attr) => !attrNeedUpdate.some((updateAttr) => updateAttr.key === attr.key)
1515
- ) || [],
1516
- ...attrNeedUpdate
1517
- ]
1518
- };
1519
- } else if (attrNeedDelete.length) {
1520
- return {
1521
- id: line.id,
1522
- attributes: line.customAttributes?.filter(
1523
- (attr) => !attrNeedDelete.includes(attr.key)
1524
- ) || []
1525
- };
1526
- } else {
1527
- return {
1528
- id: line.id,
1529
- attributes: line.customAttributes || []
1530
- };
1766
+ attributes = attributes.filter(
1767
+ (attr) => !attrNeedUpdate.some((updateAttr) => updateAttr.key === attr.key)
1768
+ ).concat(attrNeedUpdate);
1531
1769
  }
1770
+ return {
1771
+ id: lineId,
1772
+ attributes
1773
+ };
1532
1774
  }),
1533
1775
  [cart?.lineItems, mainProductDiscountCodes]
1534
1776
  );
@@ -1621,8 +1863,9 @@ function useProductsByHandles(options = {}) {
1621
1863
  metafieldIdentifiers
1622
1864
  });
1623
1865
  },
1624
- swrOptions || {
1625
- revalidateOnFocus: false
1866
+ {
1867
+ revalidateOnFocus: false,
1868
+ ...swrOptions
1626
1869
  }
1627
1870
  );
1628
1871
  }
@@ -2251,7 +2494,10 @@ var createInitialValue = () => ({
2251
2494
  freeShippingMethods: [],
2252
2495
  paymentShippingMethods: [],
2253
2496
  nddOverweight: false,
2254
- tddOverweight: false
2497
+ tddOverweight: false,
2498
+ nddCoupon: void 0,
2499
+ tddCoupon: void 0,
2500
+ isLoadingCoupon: false
2255
2501
  },
2256
2502
  selectedPlusMemberProduct: null,
2257
2503
  plusMemberProducts: [],
@@ -2296,15 +2542,29 @@ function usePlusAnnualProductVariant() {
2296
2542
  }, [plusMemberProducts, plusAnnual]);
2297
2543
  return plusAnnualProductVariant;
2298
2544
  }
2299
- function useShippingMethods(options) {
2300
- const {
2301
- variant,
2302
- plusMemberMetafields,
2303
- selectedPlusMemberMode,
2304
- isPlus = false,
2545
+ var useAvailableDeliveryCoupon = ({
2546
+ profile
2547
+ }) => {
2548
+ const { data: availableDeliveryCoupon, isLoading } = useSWR__default.default(
2549
+ profile?.email ? ["/api/multipass/subsrv/v1/prime/delivery_coupons/current/available", profile?.email] : void 0,
2550
+ async ([apiPath]) => {
2551
+ return fetch(apiPath).then((res) => res.json());
2552
+ }
2553
+ );
2554
+ console.log("availableDeliveryCoupon", availableDeliveryCoupon);
2555
+ const { ndd_coupon: nddCoupon, tdd_coupon: tddCoupon } = availableDeliveryCoupon?.data?.data || {};
2556
+ return {
2305
2557
  nddCoupon,
2306
- tddCoupon
2307
- } = options;
2558
+ tddCoupon,
2559
+ isLoading
2560
+ };
2561
+ };
2562
+
2563
+ // src/hooks/member/plus/use-shipping-methods.ts
2564
+ function useShippingMethods(options) {
2565
+ const { variant, plusMemberMetafields, selectedPlusMemberMode, isPlus = false, profile } = options;
2566
+ const { nddCoupon, tddCoupon, isLoading } = useAvailableDeliveryCoupon({ profile });
2567
+ console.log("nddCoupon", nddCoupon);
2308
2568
  const { plus_shipping, shippingMethod } = plusMemberMetafields || {};
2309
2569
  const nddOverweight = react.useMemo(() => {
2310
2570
  return (variant?.weight || 0) > (shippingMethod?.overWeight_ndd || Infinity);
@@ -2314,12 +2574,10 @@ function useShippingMethods(options) {
2314
2574
  }, [shippingMethod?.overWeight_tdd, variant?.weight]);
2315
2575
  const paymentShippingMethods = react.useMemo(() => {
2316
2576
  const weight = variant?.weight || 0;
2317
- const methods = plus_shipping?.shipping_methods?.filter(
2318
- ({ weight_low, weight_high, __mode, __plus }) => {
2319
- const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2320
- return __mode !== "free" /* FREE */ && !__plus && fitWeight;
2321
- }
2322
- ) || [];
2577
+ const methods = plus_shipping?.shipping_methods?.filter(({ weight_low, weight_high, __mode, __plus }) => {
2578
+ const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2579
+ return __mode !== "free" /* FREE */ && !__plus && fitWeight;
2580
+ }) || [];
2323
2581
  return methods.map((method) => {
2324
2582
  let disabled = false;
2325
2583
  const selectedFreeMember = selectedPlusMemberMode === "free";
@@ -2346,40 +2604,34 @@ function useShippingMethods(options) {
2346
2604
  ]);
2347
2605
  const nddPrice = react.useMemo(() => {
2348
2606
  const weight = variant?.weight || 0;
2349
- const nddMethod = paymentShippingMethods.find(
2350
- ({ __mode, weight_high, weight_low }) => {
2351
- const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2352
- return __mode === "ndd" && fitWeight;
2353
- }
2354
- );
2607
+ const nddMethod = paymentShippingMethods.find(({ __mode, weight_high, weight_low }) => {
2608
+ const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2609
+ return __mode === "ndd" && fitWeight;
2610
+ });
2355
2611
  return nddMethod?.price || 0;
2356
2612
  }, [variant?.weight, paymentShippingMethods]);
2357
2613
  const tddPrice = react.useMemo(() => {
2358
2614
  const weight = variant?.weight || 0;
2359
- const tddMethod = paymentShippingMethods.find(
2360
- ({ __mode, weight_high, weight_low }) => {
2361
- const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2362
- return __mode === "tdd" && fitWeight;
2363
- }
2364
- );
2615
+ const tddMethod = paymentShippingMethods.find(({ __mode, weight_high, weight_low }) => {
2616
+ const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2617
+ return __mode === "tdd" && fitWeight;
2618
+ });
2365
2619
  return tddMethod?.price || 0;
2366
2620
  }, [variant?.weight, paymentShippingMethods]);
2367
2621
  const freeShippingMethods = react.useMemo(() => {
2368
2622
  const weight = variant?.weight || 0;
2369
- let methods = plus_shipping?.shipping_methods?.filter(
2370
- ({ __mode, __plus, weight_low, weight_high }) => {
2371
- if (__mode === "free" /* FREE */) {
2372
- return true;
2373
- }
2374
- if (isPlus) {
2375
- const hasCoupon = isPlus && __mode === "ndd" /* NDD */ && nddCoupon || isPlus && __mode === "tdd" /* TDD */ && (tddCoupon || nddCoupon);
2376
- const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2377
- return hasCoupon && fitWeight && !__plus;
2378
- } else {
2379
- return __plus;
2380
- }
2623
+ let methods = plus_shipping?.shipping_methods?.filter(({ __mode, __plus, weight_low, weight_high }) => {
2624
+ if (__mode === "free" /* FREE */) {
2625
+ return true;
2381
2626
  }
2382
- ) || [];
2627
+ if (isPlus) {
2628
+ const hasCoupon = isPlus && __mode === "ndd" /* NDD */ && nddCoupon || isPlus && __mode === "tdd" /* TDD */ && (tddCoupon || nddCoupon);
2629
+ const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2630
+ return hasCoupon && fitWeight && !__plus;
2631
+ } else {
2632
+ return __plus;
2633
+ }
2634
+ }) || [];
2383
2635
  if (isPlus) {
2384
2636
  methods = methods.sort((a, b) => {
2385
2637
  if (b.__mode === "free" /* FREE */) return -1;
@@ -2433,7 +2685,10 @@ function useShippingMethods(options) {
2433
2685
  freeShippingMethods,
2434
2686
  paymentShippingMethods,
2435
2687
  nddOverweight,
2436
- tddOverweight
2688
+ tddOverweight,
2689
+ nddCoupon,
2690
+ tddCoupon,
2691
+ isLoadingCoupon: isLoading
2437
2692
  };
2438
2693
  }
2439
2694
  function useShippingMethodAvailableCheck() {
@@ -2538,6 +2793,73 @@ var usePlusMemberDeliveryCodes = ({
2538
2793
  [deliveryData]
2539
2794
  );
2540
2795
  };
2796
+ function useUpdateCartDeliveryOptions(mutate, metafieldIdentifiers, options) {
2797
+ const { client, locale, cartCookieAdapter } = useShopify();
2798
+ const updateDeliveryOptions = react.useCallback(
2799
+ async (_key, { arg }) => {
2800
+ const updatedCart = await shopifySdk.updateCartDeliveryOptions(client, {
2801
+ ...arg,
2802
+ metafieldIdentifiers,
2803
+ cookieAdapter: cartCookieAdapter
2804
+ });
2805
+ console.log("useUpdateCartDeliveryOptions updatedCart", updatedCart);
2806
+ if (updatedCart) {
2807
+ mutate(updatedCart);
2808
+ }
2809
+ return updatedCart;
2810
+ },
2811
+ [client, locale, cartCookieAdapter, mutate, metafieldIdentifiers]
2812
+ );
2813
+ return useSWRMutation__default.default("update-cart-delivery-options", updateDeliveryOptions, options);
2814
+ }
2815
+
2816
+ // src/hooks/member/plus/use-update-plus-member-delivery-options.ts
2817
+ var useUpdatePlusMemberDeliveryOptions = ({
2818
+ options
2819
+ } = {}) => {
2820
+ const { cart: cartContextData, mutateCart, metafieldIdentifiers } = useCartContext();
2821
+ const { trigger: updateCartDeliveryOptions2 } = useUpdateCartDeliveryOptions(
2822
+ mutateCart,
2823
+ metafieldIdentifiers
2824
+ );
2825
+ const handler = react.useCallback(
2826
+ async (_, { arg }) => {
2827
+ const currentCart = arg?.cart || cartContextData;
2828
+ const { deliveryData } = arg;
2829
+ const firstDeliveryGroup = currentCart?.deliveryGroups?.[0];
2830
+ const deliveryGroupId = firstDeliveryGroup?.id;
2831
+ const selectedOptionCode = deliveryData?.deliveryCustomData?.selected_delivery_option?.code;
2832
+ if (!deliveryGroupId || !selectedOptionCode || selectedOptionCode === firstDeliveryGroup?.selectedDeliveryOption?.code) {
2833
+ return null;
2834
+ }
2835
+ const deliveryGroup = currentCart?.deliveryGroups?.find(
2836
+ (group) => group?.id === deliveryGroupId
2837
+ );
2838
+ const matchedOption = deliveryGroup?.deliveryOptions?.find(
2839
+ (option) => option?.code === selectedOptionCode
2840
+ );
2841
+ if (!matchedOption?.handle) {
2842
+ return null;
2843
+ }
2844
+ const deliveryOptions = [
2845
+ {
2846
+ deliveryGroupId,
2847
+ deliveryOptionHandle: matchedOption.handle
2848
+ }
2849
+ ];
2850
+ const updatedCart = await updateCartDeliveryOptions2({
2851
+ selectedDeliveryOptions: deliveryOptions,
2852
+ cartId: currentCart?.id
2853
+ });
2854
+ if (updatedCart && mutateCart) {
2855
+ mutateCart(updatedCart);
2856
+ }
2857
+ return updatedCart;
2858
+ },
2859
+ [cartContextData, updateCartDeliveryOptions2, mutateCart]
2860
+ );
2861
+ return useSWRMutation__default.default("update-cart-delivery-options", handler, options);
2862
+ };
2541
2863
  var usePlusMemberItemCustomAttributes = ({
2542
2864
  deliveryData
2543
2865
  }) => {
@@ -2557,48 +2879,18 @@ var usePlusMemberCheckoutCustomAttributes = ({
2557
2879
  deliveryData,
2558
2880
  product,
2559
2881
  variant,
2560
- customer,
2561
2882
  isShowShippingBenefits
2562
2883
  }) => {
2563
2884
  const { deliveryCustomData } = deliveryData || {};
2564
2885
  const { profile } = usePlusMemberContext();
2565
- const userType = react.useMemo(() => {
2566
- const customerInfo = customer;
2567
- if (!customerInfo) {
2568
- return "new_user_unlogin";
2569
- }
2570
- if (customer) {
2571
- const { orders = {} } = customer;
2572
- const edgesLength = orders?.edges?.length;
2573
- if (edgesLength === 1) {
2574
- return "old_user_orders_once";
2575
- } else if (edgesLength && edgesLength > 1) {
2576
- return "old_user_orders_twice";
2577
- }
2578
- }
2579
- return "new_user_login";
2580
- }, [customer]);
2581
2886
  return react.useMemo(() => {
2582
2887
  const checkoutCustomAttributes = [
2583
- {
2584
- key: "_token",
2585
- value: profile?.token || ""
2586
- },
2888
+ // _last_url: 付费会员结算完成之后 checkout 有一个继续购买的按钮, 用于跳转到继续购买的页面
2587
2889
  {
2588
2890
  key: "_last_url",
2589
2891
  value: typeof window !== "undefined" ? window.location.origin + window.location.pathname : ""
2590
- },
2591
- {
2592
- key: "_user_type",
2593
- value: userType
2594
2892
  }
2595
2893
  ];
2596
- if (profile) {
2597
- checkoutCustomAttributes.push({
2598
- key: "_login_user",
2599
- value: "1"
2600
- });
2601
- }
2602
2894
  if (deliveryCustomData) {
2603
2895
  checkoutCustomAttributes.push({
2604
2896
  key: "_checkout_delivery_custom",
@@ -2608,12 +2900,6 @@ var usePlusMemberCheckoutCustomAttributes = ({
2608
2900
  })
2609
2901
  });
2610
2902
  }
2611
- if (variant?.metafields?.presell) {
2612
- checkoutCustomAttributes.push({
2613
- key: "_presale",
2614
- value: "true"
2615
- });
2616
- }
2617
2903
  if (isShowShippingBenefits && !isShowShippingBenefits({ variant, product, setting: {} })) {
2618
2904
  checkoutCustomAttributes.push({
2619
2905
  key: "_hide_shipping",
@@ -2621,18 +2907,17 @@ var usePlusMemberCheckoutCustomAttributes = ({
2621
2907
  });
2622
2908
  }
2623
2909
  return checkoutCustomAttributes;
2624
- }, [deliveryCustomData, product, profile, userType, variant, isShowShippingBenefits]);
2910
+ }, [deliveryCustomData, product, profile, variant, isShowShippingBenefits]);
2625
2911
  };
2626
2912
  function useAutoRemovePlusMemberInCart({
2627
- metafields,
2628
- isMonthlyPlus,
2629
- isAnnualPlus
2913
+ cart,
2914
+ profile,
2915
+ memberSetting
2630
2916
  }) {
2631
- const { plus_monthly_product, plus_annual_product } = metafields || {};
2632
- const { cart } = useCartContext();
2917
+ const { plus_monthly_product, plus_annual_product } = memberSetting || {};
2633
2918
  const { trigger: removeCartLines2 } = useRemoveCartLines();
2634
2919
  react.useEffect(() => {
2635
- if (!cart) return;
2920
+ if (!cart || !plus_monthly_product || !plus_annual_product) return;
2636
2921
  const removePlusProduct = async (productType) => {
2637
2922
  if (!productType) return;
2638
2923
  const product = cart.lineItems?.find(
@@ -2644,33 +2929,25 @@ function useAutoRemovePlusMemberInCart({
2644
2929
  });
2645
2930
  }
2646
2931
  };
2647
- if (isMonthlyPlus) {
2932
+ if (profile?.isMonthlyPlus) {
2648
2933
  removePlusProduct(plus_monthly_product);
2649
2934
  }
2650
- if (isAnnualPlus) {
2935
+ if (profile?.isAnnualPlus) {
2651
2936
  removePlusProduct(plus_annual_product);
2652
2937
  }
2653
- }, [
2654
- cart,
2655
- plus_annual_product,
2656
- plus_monthly_product,
2657
- isAnnualPlus,
2658
- isMonthlyPlus,
2659
- removeCartLines2
2660
- ]);
2938
+ }, [cart, plus_annual_product, plus_monthly_product, profile, removeCartLines2]);
2661
2939
  }
2662
- function useAddPlusMemberProductsToCart({
2940
+ function usePlusMemberNeedAddToCart({
2663
2941
  cart,
2664
- memberSetting,
2665
- selectedPlusMemberMode,
2666
- selectedPlusMemberProduct
2942
+ profile
2667
2943
  }) {
2944
+ const { selectedPlusMemberMode, selectedPlusMemberProduct, plusMemberMetafields } = usePlusMemberContext();
2668
2945
  const { hasMonthlyPlus, hasAnnualPlus } = useHasPlusMemberInCart({
2669
- cart,
2670
- memberSetting
2946
+ memberSetting: plusMemberMetafields,
2947
+ cart
2671
2948
  });
2672
2949
  const plusMemberProduct = react.useMemo(() => {
2673
- if (selectedPlusMemberMode === "free" /* FREE */) {
2950
+ if (!selectedPlusMemberProduct || selectedPlusMemberMode === "free" /* FREE */) {
2674
2951
  return void 0;
2675
2952
  }
2676
2953
  if (selectedPlusMemberMode === "monthly" /* MONTHLY */ && hasMonthlyPlus) {
@@ -2679,7 +2956,10 @@ function useAddPlusMemberProductsToCart({
2679
2956
  if (selectedPlusMemberMode === "annual" /* ANNUAL */ && hasAnnualPlus) {
2680
2957
  return void 0;
2681
2958
  }
2682
- if (!selectedPlusMemberProduct) {
2959
+ if (profile?.isMonthlyPlus && selectedPlusMemberMode === "monthly" /* MONTHLY */) {
2960
+ return void 0;
2961
+ }
2962
+ if (profile?.isAnnualPlus && selectedPlusMemberMode === "annual" /* ANNUAL */) {
2683
2963
  return void 0;
2684
2964
  }
2685
2965
  return selectedPlusMemberProduct;
@@ -2698,9 +2978,9 @@ var PlusMemberProvider = ({
2698
2978
  memberSetting,
2699
2979
  initialSelectedPlusMemberMode = "free",
2700
2980
  profile,
2701
- locale,
2702
2981
  children
2703
2982
  }) => {
2983
+ const { locale } = useShopify();
2704
2984
  const [zipCode, setZipCode] = react.useState("");
2705
2985
  const [showTip, setShowTip] = react.useState(false);
2706
2986
  const [selectedPlusMemberMode, setSelectedPlusMemberMode] = react.useState(
@@ -2716,7 +2996,11 @@ var PlusMemberProvider = ({
2716
2996
  const shippingMethodsContext = useShippingMethods({
2717
2997
  variant,
2718
2998
  plusMemberMetafields: memberSetting,
2719
- selectedPlusMemberMode});
2999
+ selectedPlusMemberMode,
3000
+ profile,
3001
+ isPlus: profile?.isPlus || false
3002
+ });
3003
+ console.log("shippingMethodsContext", shippingMethodsContext);
2720
3004
  const plusMemberHandles = react.useMemo(() => {
2721
3005
  return [
2722
3006
  memberSetting?.plus_monthly_product?.handle,
@@ -2959,6 +3243,7 @@ exports.CUSTOMER_ATTRIBUTE_KEY = CUSTOMER_ATTRIBUTE_KEY;
2959
3243
  exports.CUSTOMER_SCRIPT_GIFT_KEY = CUSTOMER_SCRIPT_GIFT_KEY;
2960
3244
  exports.DeliveryPlusType = DeliveryPlusType;
2961
3245
  exports.MAIN_PRODUCT_CODE = MAIN_PRODUCT_CODE;
3246
+ exports.MEMBER_PRICE_ATTRIBUTE_KEY = MEMBER_PRICE_ATTRIBUTE_KEY;
2962
3247
  exports.OrderBasePriceType = OrderBasePriceType;
2963
3248
  exports.OrderDiscountType = OrderDiscountType;
2964
3249
  exports.PLUS_MEMBER_TYPE = PLUS_MEMBER_TYPE;
@@ -2971,8 +3256,6 @@ exports.RuleType = RuleType;
2971
3256
  exports.SCRIPT_CODE_AMOUNT_KEY = SCRIPT_CODE_AMOUNT_KEY;
2972
3257
  exports.ShippingMethodMode = ShippingMethodMode;
2973
3258
  exports.SpendMoneyType = SpendMoneyType;
2974
- exports.atobID = atobID;
2975
- exports.btoaID = btoaID;
2976
3259
  exports.checkAttributesUpdateNeeded = checkAttributesUpdateNeeded;
2977
3260
  exports.clearGeoLocationCache = clearGeoLocationCache;
2978
3261
  exports.createMockCartFromLines = createMockCartFromLines;
@@ -2989,7 +3272,6 @@ exports.normalizeAddToCartLines = normalizeAddToCartLines;
2989
3272
  exports.preCheck = preCheck;
2990
3273
  exports.safeParse = safeParse;
2991
3274
  exports.useAddCartLines = useAddCartLines;
2992
- exports.useAddPlusMemberProductsToCart = useAddPlusMemberProductsToCart;
2993
3275
  exports.useAddToCart = useAddToCart;
2994
3276
  exports.useAllBlogs = useAllBlogs;
2995
3277
  exports.useAllCollections = useAllCollections;
@@ -2999,6 +3281,7 @@ exports.useArticle = useArticle;
2999
3281
  exports.useArticles = useArticles;
3000
3282
  exports.useArticlesInBlog = useArticlesInBlog;
3001
3283
  exports.useAutoRemovePlusMemberInCart = useAutoRemovePlusMemberInCart;
3284
+ exports.useAvailableDeliveryCoupon = useAvailableDeliveryCoupon;
3002
3285
  exports.useBlog = useBlog;
3003
3286
  exports.useBuyNow = useBuyNow;
3004
3287
  exports.useCalcAutoFreeGift = useCalcAutoFreeGift;
@@ -3018,6 +3301,7 @@ exports.usePlusMemberCheckoutCustomAttributes = usePlusMemberCheckoutCustomAttri
3018
3301
  exports.usePlusMemberContext = usePlusMemberContext;
3019
3302
  exports.usePlusMemberDeliveryCodes = usePlusMemberDeliveryCodes;
3020
3303
  exports.usePlusMemberItemCustomAttributes = usePlusMemberItemCustomAttributes;
3304
+ exports.usePlusMemberNeedAddToCart = usePlusMemberNeedAddToCart;
3021
3305
  exports.usePlusMonthlyProductVariant = usePlusMonthlyProductVariant;
3022
3306
  exports.usePrice = usePrice;
3023
3307
  exports.useProduct = useProduct;
@@ -3035,6 +3319,7 @@ exports.useSite = useSite;
3035
3319
  exports.useUpdateCartAttributes = useUpdateCartAttributes;
3036
3320
  exports.useUpdateCartLines = useUpdateCartLines;
3037
3321
  exports.useUpdateLineCodeAmountAttributes = useUpdateLineCodeAmountAttributes;
3322
+ exports.useUpdatePlusMemberDeliveryOptions = useUpdatePlusMemberDeliveryOptions;
3038
3323
  exports.useUpdateVariantQuery = useUpdateVariantQuery;
3039
3324
  exports.useVariant = useVariant;
3040
3325
  exports.useVariantMedia = useVariantMedia;