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

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
 
@@ -68,9 +69,10 @@ function normalizeAddToCartLines(lines) {
68
69
  const variant = line.variant;
69
70
  const product = variant.product;
70
71
  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;
72
+ const originalPrice = variant.price?.amount ? Number(variant.price.amount) : 0;
73
+ const finalPrice = variant.finalPrice?.amount === void 0 ? originalPrice : Number(variant.finalPrice?.amount);
74
+ const subtotalAmount = originalPrice * quantity;
75
+ const totalAmount = finalPrice * quantity;
74
76
  return {
75
77
  id: `temp-line-${index}-${variant.id}`,
76
78
  // Temporary ID for pre-cart lines
@@ -84,7 +86,7 @@ function normalizeAddToCartLines(lines) {
84
86
  customAttributes: line.attributes || [],
85
87
  variant: {
86
88
  id: variant.id,
87
- price,
89
+ price: finalPrice,
88
90
  listPrice: variant.compareAtPrice?.amount ? Number(variant.compareAtPrice.amount) : 0,
89
91
  sku: variant.sku || "",
90
92
  name: variant.title || "",
@@ -115,15 +117,16 @@ function createMockCartFromLines(lines, existingCart) {
115
117
  const normalizedLines = normalizeAddToCartLines(lines);
116
118
  const subtotalPrice = normalizedLines.reduce((sum, line) => sum + line.subtotalAmount, 0);
117
119
  const totalPrice = normalizedLines.reduce((sum, line) => sum + line.totalAmount, 0);
120
+ const currency = lines[0]?.variant?.price?.currencyCode;
118
121
  return {
119
122
  id: existingCart?.id || "temp-cart-id",
120
123
  customerId: existingCart?.customerId,
121
124
  email: existingCart?.email,
122
125
  createdAt: existingCart?.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
123
- currency: existingCart?.currency || { code: "USD" },
126
+ currency: existingCart?.currency || { code: currency },
124
127
  taxesIncluded: existingCart?.taxesIncluded,
125
128
  lineItems: normalizedLines,
126
- totallineItemsDiscount: 0,
129
+ totalLineItemsDiscount: 0,
127
130
  orderDiscounts: 0,
128
131
  lineItemsSubtotalPrice: subtotalPrice,
129
132
  subtotalPrice,
@@ -154,16 +157,6 @@ var getQuery = () => {
154
157
  }
155
158
  return theRequest;
156
159
  };
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
160
  var getMatchedMainProductSubTotal = (cartData, variant_list, main_product) => {
168
161
  const isAllStoreVariant = main_product?.all_store_variant ?? false;
169
162
  const matchedList = cartData?.lineItems?.filter((line) => {
@@ -395,43 +388,29 @@ var useCalcAutoFreeGift = (cart, autoFreeGiftConfig, customer, lines) => {
395
388
  }
396
389
  return { activeCampaign: null, subtotal: 0 };
397
390
  }, [autoFreeGiftConfig, effectiveCart, tags, dealsType]);
398
- const { qualifyingGift, nextTierGoal } = useMemo(() => {
391
+ const { qualifyingTier, nextTierGoal, actualThreshold, currentCurrency } = useMemo(() => {
399
392
  if (!activeCampaign || !activeCampaign.rule_result?.spend_get_reward?.gift_product) {
400
- return { qualifyingGift: null, nextTierGoal: null };
393
+ return { qualifyingTier: null, nextTierGoal: null, actualThreshold: 0, currentCurrency: "" };
401
394
  }
402
395
  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)
396
+ const currentCurrency2 = effectiveCart?.currency?.code || "";
397
+ console.log("currentCurrency useCalcAutoFreeGift", effectiveCart, currentCurrency2);
398
+ const getThresholdAmount = (tier) => {
399
+ if (tier.spend_sum_money_multi_markets?.[currentCurrency2]?.value) {
400
+ return Number(tier.spend_sum_money_multi_markets[currentCurrency2].value);
401
+ }
402
+ return Number(tier.spend_sum_money || 0);
432
403
  };
433
- return { qualifyingGift: formattedGift, nextTierGoal: nextGoal || null };
434
- }, [activeCampaign, subtotal]);
404
+ const qualifyingTier2 = [...giftTiers].sort((a, b) => getThresholdAmount(b) - getThresholdAmount(a)).find((tier) => subtotal >= getThresholdAmount(tier));
405
+ const nextGoal = giftTiers.find((tier) => subtotal < getThresholdAmount(tier));
406
+ const actualThreshold2 = qualifyingTier2 ? getThresholdAmount(qualifyingTier2) : 0;
407
+ return {
408
+ qualifyingTier: qualifyingTier2,
409
+ nextTierGoal: nextGoal || null,
410
+ actualThreshold: actualThreshold2,
411
+ currentCurrency: currentCurrency2
412
+ };
413
+ }, [activeCampaign, subtotal, effectiveCart]);
435
414
  const giftHandles = useMemo(() => {
436
415
  const giftVariant = autoFreeGiftConfig.map(
437
416
  (item) => item.rule_result?.spend_get_reward?.gift_product?.map(
@@ -447,24 +426,82 @@ var useCalcAutoFreeGift = (cart, autoFreeGiftConfig, customer, lines) => {
447
426
  }
448
427
  return true;
449
428
  }, [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
- });
429
+ const { data: giftProductsResult } = useSWR(
430
+ shouldFetch ? giftHandles : null,
431
+ async () => {
432
+ const res = await getProductsByHandles(client, {
433
+ handles: giftHandles,
434
+ locale
435
+ });
436
+ const result = Array.isArray(res) ? res : [];
437
+ giftProductsCache.current = {
438
+ data: result,
439
+ giftHandles: [...giftHandles]
440
+ };
441
+ return result;
442
+ },
443
+ {
444
+ revalidateOnFocus: false
445
+ }
446
+ );
462
447
  const finalGiftProductsResult = useMemo(() => {
463
448
  if (giftProductsCache.current && !shouldFetch) {
464
449
  return giftProductsCache.current.data || void 0;
465
450
  }
466
451
  return giftProductsResult;
467
452
  }, [giftProductsResult, shouldFetch]);
453
+ const qualifyingGift = useMemo(() => {
454
+ if (!qualifyingTier || !activeCampaign) {
455
+ return null;
456
+ }
457
+ const itemsToAdd = qualifyingTier.reward_list?.map((reward) => {
458
+ if (!reward.variant_list || reward.variant_list.length === 0) {
459
+ return null;
460
+ }
461
+ let selectedGiftProduct = null;
462
+ for (const giftVariant of reward.variant_list) {
463
+ const productInfo = finalGiftProductsResult?.find(
464
+ (p) => p.handle === giftVariant.handle
465
+ );
466
+ if (productInfo) {
467
+ const variantInfo = productInfo.variants?.find((v) => v.sku === giftVariant.sku);
468
+ if (variantInfo?.availableForSale) {
469
+ selectedGiftProduct = giftVariant;
470
+ break;
471
+ }
472
+ }
473
+ }
474
+ if (!selectedGiftProduct) {
475
+ selectedGiftProduct = reward.variant_list[0];
476
+ }
477
+ return {
478
+ variant: {
479
+ id: btoaID(selectedGiftProduct.variant_id),
480
+ handle: selectedGiftProduct.handle,
481
+ sku: selectedGiftProduct.sku
482
+ },
483
+ quantity: reward?.get_unit || 1,
484
+ attributes: [
485
+ {
486
+ key: CUSTOMER_ATTRIBUTE_KEY,
487
+ value: JSON.stringify({
488
+ is_gift: true,
489
+ rule_id: activeCampaign.rule_id,
490
+ spend_sum_money: actualThreshold,
491
+ // 使用实际的门槛金额(多币种支持)
492
+ currency_code: currentCurrency
493
+ // 记录当前币种
494
+ })
495
+ }
496
+ ]
497
+ };
498
+ }).filter((item) => item !== null);
499
+ const formattedGift = {
500
+ tier: qualifyingTier,
501
+ itemsToAdd
502
+ };
503
+ return formattedGift;
504
+ }, [qualifyingTier, activeCampaign, finalGiftProductsResult, actualThreshold, currentCurrency]);
468
505
  return {
469
506
  qualifyingGift,
470
507
  nextTierGoal,
@@ -511,12 +548,14 @@ var useScriptAutoFreeGift = ({
511
548
  upgrade_multiple2 = 1.2;
512
549
  upgrade_value2 = 40;
513
550
  }
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
- });
551
+ effectiveCart?.lineItems?.forEach(
552
+ ({ customAttributes }) => {
553
+ customAttributes?.forEach(({ key, value }) => {
554
+ if (key === "_amount_upgrade_multiple") upgrade_multiple2 = Number(value) || 1;
555
+ if (key === "_amount_upgrade_value") upgrade_value2 = Number(value) || 0;
556
+ });
557
+ }
558
+ );
520
559
  return [upgrade_multiple2, upgrade_value2];
521
560
  }, [effectiveCart?.lineItems, points_subscribe]);
522
561
  const breakpoints = useMemo(() => {
@@ -581,18 +620,24 @@ var useScriptAutoFreeGift = ({
581
620
  const nextLevel = levelIndex > 0 ? sortedLevels[levelIndex - 1] ?? null : null;
582
621
  return [currentLevel, nextLevel];
583
622
  }, [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
- });
623
+ const { data: giftProductsResult } = useSWR(
624
+ shouldFetch ? giftHandles : null,
625
+ async () => {
626
+ const res = await getProductsByHandles(client, {
627
+ handles: giftHandles,
628
+ locale
629
+ });
630
+ const result = Array.isArray(res) ? res : [];
631
+ giftProductsCache.current = {
632
+ data: result,
633
+ giftHandles: [...giftHandles]
634
+ };
635
+ return result;
636
+ },
637
+ {
638
+ revalidateOnFocus: false
639
+ }
640
+ );
596
641
  const finalGiftProductsResult = useMemo(() => {
597
642
  if (giftProductsCache.current && !shouldFetch) {
598
643
  return giftProductsCache.current.data || void 0;
@@ -625,9 +670,9 @@ var useScriptAutoFreeGift = ({
625
670
  };
626
671
  };
627
672
  var CartContext = createContext(null);
628
- function useCartContext() {
673
+ function useCartContext(options) {
629
674
  const context = useContext(CartContext);
630
- if (!context) {
675
+ if (!context && true) {
631
676
  throw new Error("useCartContext must be used within a CartProvider");
632
677
  }
633
678
  return context;
@@ -669,11 +714,23 @@ function useAddCartLines(options) {
669
714
  const { mutateCart, metafieldIdentifiers } = useCartContext();
670
715
  const addLines = useCallback(
671
716
  async (_key, { arg }) => {
672
- let updatedCart = await addCartLines(client, {
673
- ...arg,
674
- metafieldIdentifiers,
675
- cookieAdapter: cartCookieAdapter
676
- });
717
+ const { cartId, lines } = arg;
718
+ const id = cartId || cartCookieAdapter?.getCartId(locale);
719
+ let updatedCart;
720
+ if (!id) {
721
+ updatedCart = await createCart(client, {
722
+ lines,
723
+ metafieldIdentifiers,
724
+ cookieAdapter: cartCookieAdapter
725
+ });
726
+ } else {
727
+ updatedCart = await addCartLines(client, {
728
+ cartId: id,
729
+ lines,
730
+ metafieldIdentifiers,
731
+ cookieAdapter: cartCookieAdapter
732
+ });
733
+ }
677
734
  if (updatedCart) {
678
735
  const unApplicableCodes = updatedCart.discountCodes.filter((item) => !item.applicable).map((item) => item.code);
679
736
  if (unApplicableCodes.length > 0) {
@@ -720,7 +777,7 @@ var trackAddToCartGA = ({
720
777
  const currencyCode = variant.product?.price?.currencyCode;
721
778
  const totalPrice = lineItems?.reduce(
722
779
  (prev, { variant: variant2 }) => prev.plus(
723
- variant2?.finalPrice?.amount ?? variant2?.compareAtPrice?.amount ?? variant2?.price?.amount ?? 0
780
+ variant2?.finalPrice?.amount === void 0 ? Number(variant2?.price?.amount) || 0 : Number(variant2?.finalPrice?.amount) || 0
724
781
  ),
725
782
  new Decimal2(0)
726
783
  ).toNumber();
@@ -753,10 +810,10 @@ var trackBuyNowGA = ({
753
810
  return;
754
811
  }
755
812
  const { variant } = lineItems[0];
756
- const currencyCode = variant.price?.currencyCode;
813
+ const currencyCode = variant.product?.price?.currencyCode || variant.price?.currencyCode;
757
814
  const totalPrice = lineItems?.reduce(
758
815
  (prev, { variant: variant2 }) => prev.plus(
759
- variant2?.finalPrice?.amount ?? variant2?.compareAtPrice?.amount ?? (variant2?.price?.amount || 0)
816
+ variant2?.finalPrice?.amount === void 0 ? Number(variant2?.price?.amount) || 0 : Number(variant2?.finalPrice?.amount) || 0
760
817
  ),
761
818
  new Decimal2(0)
762
819
  ).toNumber();
@@ -830,7 +887,7 @@ function useApplyCartCodes(options) {
830
887
  if (!discountCodes?.length) {
831
888
  throw new Error("Invalid input used for this operation: Miss discountCode");
832
889
  }
833
- const cartId = providedCartId ? void 0 : providedCartId || cart?.id;
890
+ const cartId = providedCartId || cart?.id;
834
891
  if (!cartId) {
835
892
  return void 0;
836
893
  }
@@ -843,12 +900,18 @@ function useApplyCartCodes(options) {
843
900
  cookieAdapter: cartCookieAdapter,
844
901
  metafieldIdentifiers
845
902
  });
903
+ const unApplicableCodes = discountCodes.filter(
904
+ (code) => updatedCart?.discountCodes?.find((item) => item.code === code && !item.applicable)
905
+ );
906
+ if (unApplicableCodes.length) {
907
+ throw new Error(`${unApplicableCodes.join(", ")} is not applicable to the cart`);
908
+ }
846
909
  if (updatedCart) {
847
910
  mutateCart(updatedCart);
848
911
  }
849
912
  return updatedCart;
850
913
  },
851
- [client, locale, cartCookieAdapter, mutateCart, cart]
914
+ [client, locale, cartCookieAdapter, mutateCart, cart, metafieldIdentifiers]
852
915
  );
853
916
  return useSWRMutation("apply-codes", applyCodes, options);
854
917
  }
@@ -858,7 +921,7 @@ function useRemoveCartCodes(options) {
858
921
  const removeCodes = useCallback(
859
922
  async (_key, { arg }) => {
860
923
  const { cartId: providedCartId, discountCodes } = arg;
861
- const cartId = providedCartId ? void 0 : providedCartId || cart?.id;
924
+ const cartId = providedCartId || cart?.id;
862
925
  const codes = cart?.discountCodes?.filter((code) => !!code.applicable) || [];
863
926
  const leftCodes = codes.filter((code) => discountCodes?.length ? !discountCodes.includes(code.code) : code.code).map((code) => code.code);
864
927
  const updatedCart = await updateCartCodes(client, {
@@ -872,18 +935,74 @@ function useRemoveCartCodes(options) {
872
935
  }
873
936
  return updatedCart;
874
937
  },
875
- [client, locale, cartCookieAdapter, mutateCart, cart]
938
+ [client, locale, cartCookieAdapter, mutateCart, cart, metafieldIdentifiers]
876
939
  );
877
940
  return useSWRMutation("remove-codes", removeCodes, options);
878
941
  }
879
942
 
943
+ // src/hooks/cart/utils/add-to-cart.ts
944
+ var getLinesWithAttributes = ({
945
+ cart,
946
+ lineItems
947
+ }) => {
948
+ return lineItems.map((line) => {
949
+ const sameLineInCart = cart?.lineItems.find(
950
+ (lineInCart) => lineInCart.variant.sku === line.variant?.sku && lineInCart.product?.handle === line.variant?.product?.handle
951
+ );
952
+ const codeAmountAttribute = sameLineInCart?.customAttributes?.find(
953
+ (attr) => attr.key === CODE_AMOUNT_KEY
954
+ );
955
+ const scriptCodeAmountAttribute = sameLineInCart?.customAttributes?.find(
956
+ (attr) => attr.key === SCRIPT_CODE_AMOUNT_KEY
957
+ );
958
+ let functionAttribute = null;
959
+ try {
960
+ functionAttribute = sameLineInCart?.customAttributes?.find(
961
+ (attr) => attr.key === CUSTOMER_ATTRIBUTE_KEY && JSON.parse(attr.value)?.discounted_amount
962
+ );
963
+ } catch (error) {
964
+ }
965
+ if (codeAmountAttribute || functionAttribute || scriptCodeAmountAttribute) {
966
+ return {
967
+ ...line,
968
+ attributes: [
969
+ ...line.attributes || [],
970
+ codeAmountAttribute,
971
+ functionAttribute,
972
+ scriptCodeAmountAttribute
973
+ ].filter(Boolean)
974
+ };
975
+ }
976
+ return line;
977
+ });
978
+ };
979
+ var getLinesWithFunctionAttributes = (lineItems) => {
980
+ return lineItems.map((line) => {
981
+ let itemAttributes = line.attributes || [];
982
+ const functionEnvAttribute = itemAttributes.find((attr) => attr.key === CUSTOMER_ATTRIBUTE_KEY);
983
+ if (!functionEnvAttribute) {
984
+ itemAttributes = itemAttributes.concat([
985
+ {
986
+ key: CUSTOMER_ATTRIBUTE_KEY,
987
+ value: JSON.stringify({
988
+ is_gift: false,
989
+ discounted_amount: line.variant?.finalPrice?.amount === void 0 ? Number(line.variant?.price?.amount) * (line.quantity || 1) : Number(line.variant?.finalPrice?.amount) * (line.quantity || 1)
990
+ })
991
+ }
992
+ ]);
993
+ }
994
+ return { ...line, attributes: itemAttributes };
995
+ });
996
+ };
997
+
880
998
  // src/hooks/cart/use-add-to-cart.ts
881
999
  function useAddToCart({ withTrack = true } = {}, swrOptions) {
882
- const { client, config, locale, cartCookieAdapter, userAdapter } = useShopify();
883
- const { cart } = useCartContext();
1000
+ const { client, config, locale, cartCookieAdapter, userAdapter, performanceAdapter } = useShopify();
1001
+ const { cart, addCustomAttributes } = useCartContext();
884
1002
  const { trigger: applyCartCodes } = useApplyCartCodes();
885
1003
  const { trigger: removeInvalidCodes } = useRemoveCartCodes();
886
1004
  const { trigger: addCartLines2 } = useAddCartLines();
1005
+ const { trigger: createCart4 } = useCreateCart();
887
1006
  const addToCart = useCallback(
888
1007
  async (_key, { arg }) => {
889
1008
  const {
@@ -894,12 +1013,19 @@ function useAddToCart({ withTrack = true } = {}, swrOptions) {
894
1013
  buyerIdentity,
895
1014
  needCreateCart = false,
896
1015
  onCodesInvalid,
897
- replaceExistingCodes
1016
+ replaceExistingCodes,
1017
+ customAttributes
898
1018
  } = arg;
899
1019
  if (!lineItems || lineItems.length === 0) {
900
1020
  return;
901
1021
  }
902
- const lines = lineItems.map((item) => ({
1022
+ performanceAdapter?.addToCartStart();
1023
+ const linesWithAttributes = getLinesWithAttributes({
1024
+ cart,
1025
+ lineItems
1026
+ });
1027
+ const linesWithFunctionAttributes = getLinesWithFunctionAttributes(linesWithAttributes);
1028
+ const lines = linesWithFunctionAttributes.map((item) => ({
903
1029
  merchandiseId: item.variant?.id || "",
904
1030
  quantity: item.quantity || 1,
905
1031
  attributes: item.attributes,
@@ -908,36 +1034,45 @@ function useAddToCart({ withTrack = true } = {}, swrOptions) {
908
1034
  if (lines.length === 0) {
909
1035
  return;
910
1036
  }
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;
1037
+ let cartId = needCreateCart ? void 0 : providedCartId || cart?.id;
1038
+ let resultCart = null;
1039
+ if (!cartId) {
1040
+ resultCart = await createCart4({
1041
+ lines,
1042
+ buyerIdentity,
1043
+ discountCodes,
1044
+ customAttributes
1045
+ });
1046
+ } else {
1047
+ resultCart = await addCartLines2({
1048
+ cartId,
1049
+ lines
1050
+ });
1051
+ console.log("npm addCartLines resultCart", resultCart);
1052
+ if (resultCart && resultCart.discountCodes && resultCart.discountCodes.length > 0) {
1053
+ const unapplicableCodes = resultCart.discountCodes.filter((item) => !item.applicable).map((item) => item.code);
1054
+ if (unapplicableCodes.length > 0) {
1055
+ if (onCodesInvalid) {
1056
+ const handledCart = await onCodesInvalid(resultCart, unapplicableCodes);
1057
+ if (handledCart) {
1058
+ resultCart = handledCart;
1059
+ }
1060
+ } else {
1061
+ await removeInvalidCodes({
1062
+ discountCodes: unapplicableCodes
1063
+ });
928
1064
  }
929
- } else {
930
- await removeInvalidCodes({
931
- discountCodes: unapplicableCodes
932
- });
933
1065
  }
934
1066
  }
935
- }
936
- if (discountCodes && discountCodes.length > 0) {
937
- applyCartCodes({
938
- replaceExistingCodes,
939
- discountCodes
940
- });
1067
+ if (resultCart && discountCodes && discountCodes.length > 0) {
1068
+ applyCartCodes({
1069
+ replaceExistingCodes,
1070
+ discountCodes
1071
+ });
1072
+ }
1073
+ if (customAttributes && customAttributes.length > 0) {
1074
+ addCustomAttributes(customAttributes);
1075
+ }
941
1076
  }
942
1077
  if (withTrack) {
943
1078
  trackAddToCartGA({
@@ -946,9 +1081,24 @@ function useAddToCart({ withTrack = true } = {}, swrOptions) {
946
1081
  });
947
1082
  trackAddToCartFBQ({ lineItems });
948
1083
  }
1084
+ performanceAdapter?.addToCartEnd();
949
1085
  return resultCart;
950
1086
  },
951
- [client, locale, cartCookieAdapter, userAdapter, cart, withTrack]
1087
+ [
1088
+ client,
1089
+ locale,
1090
+ cartCookieAdapter,
1091
+ userAdapter,
1092
+ cart,
1093
+ withTrack,
1094
+ performanceAdapter,
1095
+ createCart4,
1096
+ addCartLines2,
1097
+ applyCartCodes,
1098
+ removeInvalidCodes,
1099
+ addCustomAttributes,
1100
+ config
1101
+ ]
952
1102
  );
953
1103
  return useSWRMutation("add-to-cart", addToCart, swrOptions);
954
1104
  }
@@ -965,9 +1115,10 @@ function useUpdateCartLines(options) {
965
1115
  if (updatedCart) {
966
1116
  mutateCart(updatedCart);
967
1117
  }
1118
+ console.log("use-update-cart-lines updatedCart", metafieldIdentifiers, updatedCart);
968
1119
  return updatedCart;
969
1120
  },
970
- [client, locale, cartCookieAdapter, mutateCart]
1121
+ [client, locale, cartCookieAdapter, mutateCart, metafieldIdentifiers]
971
1122
  );
972
1123
  return useSWRMutation("update-cart-lines", updateLines, options);
973
1124
  }
@@ -1006,7 +1157,7 @@ function useRemoveCartLines(options) {
1006
1157
  }
1007
1158
  return updatedCart;
1008
1159
  },
1009
- [client, locale, cartCookieAdapter, mutateCart]
1160
+ [client, locale, cartCookieAdapter, mutateCart, metafieldIdentifiers]
1010
1161
  );
1011
1162
  return useSWRMutation("remove-cart-lines", removeLines, options);
1012
1163
  }
@@ -1025,7 +1176,7 @@ function useUpdateCartAttributes(mutate, metafieldIdentifiers, options) {
1025
1176
  }
1026
1177
  return updatedCart;
1027
1178
  },
1028
- [client, locale, cartCookieAdapter, mutate]
1179
+ [client, locale, cartCookieAdapter, mutate, metafieldIdentifiers]
1029
1180
  );
1030
1181
  return useSWRMutation("update-cart-attributes", updateAttributes, options);
1031
1182
  }
@@ -1047,7 +1198,8 @@ function useBuyNow({ withTrack = true } = {}, swrOptions) {
1047
1198
  if (!lineItems || lineItems.length === 0) {
1048
1199
  return;
1049
1200
  }
1050
- const lines = lineItems.map((item) => ({
1201
+ const linesWithFunctionAttributes = getLinesWithFunctionAttributes(lineItems);
1202
+ const lines = linesWithFunctionAttributes.map((item) => ({
1051
1203
  merchandiseId: item.variant?.id || "",
1052
1204
  quantity: item.quantity || 1,
1053
1205
  attributes: item.attributes,
@@ -1165,7 +1317,7 @@ var useCalcOrderDiscount = (cart, orderDiscountConfig, customer) => {
1165
1317
  const isCustomerLoading = useMemo(() => !customer ? true : false, [customer]);
1166
1318
  const dealsType = "";
1167
1319
  const { activeCampaign, subtotal } = useMemo(() => {
1168
- for (const campaign of orderDiscountConfig) {
1320
+ for (const campaign of orderDiscountConfig || []) {
1169
1321
  const { rule_conditions = [], result_detail } = campaign;
1170
1322
  const { main_product, order_discount_conf } = result_detail || {};
1171
1323
  const isPreCheckPassed = preCheck(rule_conditions, tags, []);
@@ -1195,9 +1347,12 @@ var useCalcOrderDiscount = (cart, orderDiscountConfig, customer) => {
1195
1347
  discountAmount: 0
1196
1348
  };
1197
1349
  }
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));
1350
+ const currentCurrency = cart?.currency?.code || "";
1351
+ console.log("currentCurrency", cart, currentCurrency);
1352
+ const orderDiscountConf = activeCampaign.result_detail.order_discount_conf;
1353
+ const tieredDiscounts = orderDiscountConf.tiered_discounts_markets?.[currentCurrency] || orderDiscountConf.tiered_discounts;
1354
+ const qualifyingTier = [...tieredDiscounts].sort((a, b) => Number(b.amount) - Number(a.amount)).find((tier) => subtotal >= Number(tier.amount));
1355
+ const nextGoal = [...tieredDiscounts].sort((a, b) => Number(a.amount) - Number(b.amount)).find((tier) => subtotal < Number(tier.amount));
1201
1356
  if (!qualifyingTier) {
1202
1357
  return {
1203
1358
  qualifyingDiscount: null,
@@ -1265,12 +1420,10 @@ function useHasPlusMemberInCart({
1265
1420
  };
1266
1421
  }, [cart?.lineItems, plus_monthly_product, plus_annual_product]);
1267
1422
  }
1268
-
1269
- // src/hooks/cart/feature/use-cart-attributes.ts
1270
1423
  var getReferralAttributes = () => {
1271
- const inviteCode = Cookies5.get("invite_code");
1272
- const playModeId = Cookies5.get("playModeId");
1273
- const popup = Cookies5.get("_popup");
1424
+ const inviteCode = getLocalStorage("inviteCode") || Cookies5.get("inviteCode");
1425
+ const playModeId = getLocalStorage("playModeId") || Cookies5.get("playModeId");
1426
+ const popup = getLocalStorage("_popup") || Cookies5.get("_popup");
1274
1427
  if (inviteCode && playModeId) {
1275
1428
  return popup ? [
1276
1429
  { key: "_invite_code", value: inviteCode ? inviteCode : "" },
@@ -1294,8 +1447,6 @@ var useCartAttributes = ({
1294
1447
  memberSetting,
1295
1448
  cart
1296
1449
  });
1297
- console.log("memberSetting", memberSetting);
1298
- console.log("hasPlusMember", hasPlusMember);
1299
1450
  useEffect(() => {
1300
1451
  setCurrentUrl(window.location.href);
1301
1452
  }, []);
@@ -1321,7 +1472,7 @@ var useCartAttributes = ({
1321
1472
  return "new_user_login";
1322
1473
  }, [customer]);
1323
1474
  const memberAttributes = useMemo(() => {
1324
- return [
1475
+ const attributes = [
1325
1476
  {
1326
1477
  key: "_token",
1327
1478
  value: profile?.token
@@ -1342,17 +1493,28 @@ var useCartAttributes = ({
1342
1493
  value: profile?.token ? "true" : "false"
1343
1494
  }
1344
1495
  ];
1496
+ if (profile?.token) {
1497
+ attributes.push({
1498
+ key: "_login_user",
1499
+ value: "1"
1500
+ });
1501
+ }
1502
+ return attributes;
1345
1503
  }, [profile?.memberType, profile?.token, userType, hasPlusMember]);
1346
1504
  const functionAttributes = useMemo(() => {
1347
- return [
1348
- cart?.discountCodes && {
1505
+ const hasFunctionEnvAttribute = cart?.lineItems.some(
1506
+ (item) => item.customAttributes?.some((attr) => attr.key === CUSTOMER_ATTRIBUTE_KEY)
1507
+ );
1508
+ const discountCodes = cart?.discountCodes.map((item) => item.code).filter((code) => code) || [];
1509
+ return hasFunctionEnvAttribute ? [
1510
+ {
1349
1511
  key: "_discounts_function_env",
1350
1512
  value: JSON.stringify({
1351
- discount_code: cart?.discountCodes.map((item) => item.code),
1513
+ discount_code: discountCodes,
1352
1514
  user_tags: customer?.tags || []
1353
1515
  })
1354
1516
  }
1355
- ];
1517
+ ] : [];
1356
1518
  }, [cart]);
1357
1519
  const presellAttributes = useMemo(() => {
1358
1520
  return [
@@ -1384,18 +1546,50 @@ var useCartAttributes = ({
1384
1546
  }
1385
1547
  ];
1386
1548
  }, [currentUrl]);
1549
+ const commonAttributes = useMemo(
1550
+ () => [
1551
+ ...memberAttributes,
1552
+ ...functionAttributes,
1553
+ ...presellAttributes,
1554
+ ...weightAttributes,
1555
+ ...trackingAttributes,
1556
+ ...getReferralAttributes()
1557
+ ].filter((item) => item?.value),
1558
+ [memberAttributes, functionAttributes, presellAttributes, weightAttributes, trackingAttributes]
1559
+ );
1560
+ const extraAttributesInCart = useMemo(() => {
1561
+ const commonAttributeKeys = [
1562
+ // member attributes
1563
+ "_token",
1564
+ "_member_type",
1565
+ "_user_type",
1566
+ "_is_login",
1567
+ "_login_user",
1568
+ // function attributes
1569
+ "_discounts_function_env",
1570
+ // presell attributes
1571
+ "_presale",
1572
+ // weight attributes
1573
+ "_weight",
1574
+ "_app_source_name",
1575
+ // tracking attributes
1576
+ "utm_params",
1577
+ // referral attributes
1578
+ "_invite_code",
1579
+ "_play_mode_id",
1580
+ "_popup"
1581
+ ];
1582
+ return cart?.customAttributes?.filter(
1583
+ (item) => !commonAttributeKeys.includes(item.key)
1584
+ ) || [];
1585
+ }, [cart]);
1387
1586
  return useMemo(
1388
1587
  () => ({
1389
- attributes: [
1390
- ...memberAttributes,
1391
- ...functionAttributes,
1392
- ...presellAttributes,
1393
- ...weightAttributes,
1394
- ...trackingAttributes,
1395
- ...getReferralAttributes()
1396
- ].filter((item) => item?.value)
1588
+ attributes: [...commonAttributes, ...extraAttributesInCart].filter(
1589
+ (item) => item?.value
1590
+ )
1397
1591
  }),
1398
- [memberAttributes, functionAttributes, presellAttributes, weightAttributes, trackingAttributes]
1592
+ [commonAttributes, extraAttributesInCart]
1399
1593
  );
1400
1594
  };
1401
1595
  var DEFAULT_MIN = 1;
@@ -1458,7 +1652,7 @@ var useUpdateLineCodeAmountAttributes = ({
1458
1652
  );
1459
1653
  const functionEnvValue = getDiscountEnvAttributeValue(line.customAttributes);
1460
1654
  const hasSameFunctionEnvAttribute = Number(functionEnvValue.discounted_amount) === Number(line.totalAmount);
1461
- if (!hasSameFunctionEnvAttribute && hasFunctionEnvAttribute) {
1655
+ if (!hasSameFunctionEnvAttribute && hasFunctionEnvAttribute && !functionEnvValue.is_gift) {
1462
1656
  attrNeedUpdate.push({
1463
1657
  key: CUSTOMER_ATTRIBUTE_KEY,
1464
1658
  value: JSON.stringify({
@@ -1497,29 +1691,22 @@ var useUpdateLineCodeAmountAttributes = ({
1497
1691
  }).filter(
1498
1692
  ({ attrNeedUpdate, attrNeedDelete }) => attrNeedUpdate.length || attrNeedDelete.length
1499
1693
  ).map(({ line, attrNeedUpdate, attrNeedDelete }) => {
1694
+ let lineId = line.id;
1695
+ let attributes = line.customAttributes || [];
1696
+ if (attrNeedDelete.length) {
1697
+ attributes = attributes.filter(
1698
+ (attr) => !attrNeedDelete.includes(attr.key)
1699
+ );
1700
+ }
1500
1701
  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
- };
1702
+ attributes = attributes.filter(
1703
+ (attr) => !attrNeedUpdate.some((updateAttr) => updateAttr.key === attr.key)
1704
+ ).concat(attrNeedUpdate);
1522
1705
  }
1706
+ return {
1707
+ id: lineId,
1708
+ attributes
1709
+ };
1523
1710
  }),
1524
1711
  [cart?.lineItems, mainProductDiscountCodes]
1525
1712
  );
@@ -1612,8 +1799,9 @@ function useProductsByHandles(options = {}) {
1612
1799
  metafieldIdentifiers
1613
1800
  });
1614
1801
  },
1615
- swrOptions || {
1616
- revalidateOnFocus: false
1802
+ {
1803
+ revalidateOnFocus: false,
1804
+ ...swrOptions
1617
1805
  }
1618
1806
  );
1619
1807
  }
@@ -2242,7 +2430,10 @@ var createInitialValue = () => ({
2242
2430
  freeShippingMethods: [],
2243
2431
  paymentShippingMethods: [],
2244
2432
  nddOverweight: false,
2245
- tddOverweight: false
2433
+ tddOverweight: false,
2434
+ nddCoupon: void 0,
2435
+ tddCoupon: void 0,
2436
+ isLoadingCoupon: false
2246
2437
  },
2247
2438
  selectedPlusMemberProduct: null,
2248
2439
  plusMemberProducts: [],
@@ -2287,15 +2478,29 @@ function usePlusAnnualProductVariant() {
2287
2478
  }, [plusMemberProducts, plusAnnual]);
2288
2479
  return plusAnnualProductVariant;
2289
2480
  }
2290
- function useShippingMethods(options) {
2291
- const {
2292
- variant,
2293
- plusMemberMetafields,
2294
- selectedPlusMemberMode,
2295
- isPlus = false,
2481
+ var useAvailableDeliveryCoupon = ({
2482
+ profile
2483
+ }) => {
2484
+ const { data: availableDeliveryCoupon, isLoading } = useSWR(
2485
+ profile?.email ? ["/api/multipass/subsrv/v1/prime/delivery_coupons/current/available", profile?.email] : void 0,
2486
+ async ([apiPath]) => {
2487
+ return fetch(apiPath).then((res) => res.json());
2488
+ }
2489
+ );
2490
+ console.log("availableDeliveryCoupon", availableDeliveryCoupon);
2491
+ const { ndd_coupon: nddCoupon, tdd_coupon: tddCoupon } = availableDeliveryCoupon?.data?.data || {};
2492
+ return {
2296
2493
  nddCoupon,
2297
- tddCoupon
2298
- } = options;
2494
+ tddCoupon,
2495
+ isLoading
2496
+ };
2497
+ };
2498
+
2499
+ // src/hooks/member/plus/use-shipping-methods.ts
2500
+ function useShippingMethods(options) {
2501
+ const { variant, plusMemberMetafields, selectedPlusMemberMode, isPlus = false, profile } = options;
2502
+ const { nddCoupon, tddCoupon, isLoading } = useAvailableDeliveryCoupon({ profile });
2503
+ console.log("nddCoupon", nddCoupon);
2299
2504
  const { plus_shipping, shippingMethod } = plusMemberMetafields || {};
2300
2505
  const nddOverweight = useMemo(() => {
2301
2506
  return (variant?.weight || 0) > (shippingMethod?.overWeight_ndd || Infinity);
@@ -2305,12 +2510,10 @@ function useShippingMethods(options) {
2305
2510
  }, [shippingMethod?.overWeight_tdd, variant?.weight]);
2306
2511
  const paymentShippingMethods = useMemo(() => {
2307
2512
  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
- ) || [];
2513
+ const methods = plus_shipping?.shipping_methods?.filter(({ weight_low, weight_high, __mode, __plus }) => {
2514
+ const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2515
+ return __mode !== "free" /* FREE */ && !__plus && fitWeight;
2516
+ }) || [];
2314
2517
  return methods.map((method) => {
2315
2518
  let disabled = false;
2316
2519
  const selectedFreeMember = selectedPlusMemberMode === "free";
@@ -2337,40 +2540,34 @@ function useShippingMethods(options) {
2337
2540
  ]);
2338
2541
  const nddPrice = useMemo(() => {
2339
2542
  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
- );
2543
+ const nddMethod = paymentShippingMethods.find(({ __mode, weight_high, weight_low }) => {
2544
+ const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2545
+ return __mode === "ndd" && fitWeight;
2546
+ });
2346
2547
  return nddMethod?.price || 0;
2347
2548
  }, [variant?.weight, paymentShippingMethods]);
2348
2549
  const tddPrice = useMemo(() => {
2349
2550
  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
- );
2551
+ const tddMethod = paymentShippingMethods.find(({ __mode, weight_high, weight_low }) => {
2552
+ const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2553
+ return __mode === "tdd" && fitWeight;
2554
+ });
2356
2555
  return tddMethod?.price || 0;
2357
2556
  }, [variant?.weight, paymentShippingMethods]);
2358
2557
  const freeShippingMethods = useMemo(() => {
2359
2558
  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
- }
2559
+ let methods = plus_shipping?.shipping_methods?.filter(({ __mode, __plus, weight_low, weight_high }) => {
2560
+ if (__mode === "free" /* FREE */) {
2561
+ return true;
2372
2562
  }
2373
- ) || [];
2563
+ if (isPlus) {
2564
+ const hasCoupon = isPlus && __mode === "ndd" /* NDD */ && nddCoupon || isPlus && __mode === "tdd" /* TDD */ && (tddCoupon || nddCoupon);
2565
+ const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2566
+ return hasCoupon && fitWeight && !__plus;
2567
+ } else {
2568
+ return __plus;
2569
+ }
2570
+ }) || [];
2374
2571
  if (isPlus) {
2375
2572
  methods = methods.sort((a, b) => {
2376
2573
  if (b.__mode === "free" /* FREE */) return -1;
@@ -2424,7 +2621,10 @@ function useShippingMethods(options) {
2424
2621
  freeShippingMethods,
2425
2622
  paymentShippingMethods,
2426
2623
  nddOverweight,
2427
- tddOverweight
2624
+ tddOverweight,
2625
+ nddCoupon,
2626
+ tddCoupon,
2627
+ isLoadingCoupon: isLoading
2428
2628
  };
2429
2629
  }
2430
2630
  function useShippingMethodAvailableCheck() {
@@ -2529,6 +2729,73 @@ var usePlusMemberDeliveryCodes = ({
2529
2729
  [deliveryData]
2530
2730
  );
2531
2731
  };
2732
+ function useUpdateCartDeliveryOptions(mutate, metafieldIdentifiers, options) {
2733
+ const { client, locale, cartCookieAdapter } = useShopify();
2734
+ const updateDeliveryOptions = useCallback(
2735
+ async (_key, { arg }) => {
2736
+ const updatedCart = await updateCartDeliveryOptions(client, {
2737
+ ...arg,
2738
+ metafieldIdentifiers,
2739
+ cookieAdapter: cartCookieAdapter
2740
+ });
2741
+ console.log("useUpdateCartDeliveryOptions updatedCart", updatedCart);
2742
+ if (updatedCart) {
2743
+ mutate(updatedCart);
2744
+ }
2745
+ return updatedCart;
2746
+ },
2747
+ [client, locale, cartCookieAdapter, mutate, metafieldIdentifiers]
2748
+ );
2749
+ return useSWRMutation("update-cart-delivery-options", updateDeliveryOptions, options);
2750
+ }
2751
+
2752
+ // src/hooks/member/plus/use-update-plus-member-delivery-options.ts
2753
+ var useUpdatePlusMemberDeliveryOptions = ({
2754
+ options
2755
+ } = {}) => {
2756
+ const { cart: cartContextData, mutateCart, metafieldIdentifiers } = useCartContext();
2757
+ const { trigger: updateCartDeliveryOptions2 } = useUpdateCartDeliveryOptions(
2758
+ mutateCart,
2759
+ metafieldIdentifiers
2760
+ );
2761
+ const handler = useCallback(
2762
+ async (_, { arg }) => {
2763
+ const currentCart = arg?.cart || cartContextData;
2764
+ const { deliveryData } = arg;
2765
+ const firstDeliveryGroup = currentCart?.deliveryGroups?.[0];
2766
+ const deliveryGroupId = firstDeliveryGroup?.id;
2767
+ const selectedOptionCode = deliveryData?.deliveryCustomData?.selected_delivery_option?.code;
2768
+ if (!deliveryGroupId || !selectedOptionCode || selectedOptionCode === firstDeliveryGroup?.selectedDeliveryOption?.code) {
2769
+ return null;
2770
+ }
2771
+ const deliveryGroup = currentCart?.deliveryGroups?.find(
2772
+ (group) => group?.id === deliveryGroupId
2773
+ );
2774
+ const matchedOption = deliveryGroup?.deliveryOptions?.find(
2775
+ (option) => option?.code === selectedOptionCode
2776
+ );
2777
+ if (!matchedOption?.handle) {
2778
+ return null;
2779
+ }
2780
+ const deliveryOptions = [
2781
+ {
2782
+ deliveryGroupId,
2783
+ deliveryOptionHandle: matchedOption.handle
2784
+ }
2785
+ ];
2786
+ const updatedCart = await updateCartDeliveryOptions2({
2787
+ selectedDeliveryOptions: deliveryOptions,
2788
+ cartId: currentCart?.id
2789
+ });
2790
+ if (updatedCart && mutateCart) {
2791
+ mutateCart(updatedCart);
2792
+ }
2793
+ return updatedCart;
2794
+ },
2795
+ [cartContextData, updateCartDeliveryOptions2, mutateCart]
2796
+ );
2797
+ return useSWRMutation("update-cart-delivery-options", handler, options);
2798
+ };
2532
2799
  var usePlusMemberItemCustomAttributes = ({
2533
2800
  deliveryData
2534
2801
  }) => {
@@ -2548,48 +2815,18 @@ var usePlusMemberCheckoutCustomAttributes = ({
2548
2815
  deliveryData,
2549
2816
  product,
2550
2817
  variant,
2551
- customer,
2552
2818
  isShowShippingBenefits
2553
2819
  }) => {
2554
2820
  const { deliveryCustomData } = deliveryData || {};
2555
2821
  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
2822
  return useMemo(() => {
2573
2823
  const checkoutCustomAttributes = [
2574
- {
2575
- key: "_token",
2576
- value: profile?.token || ""
2577
- },
2824
+ // _last_url: 付费会员结算完成之后 checkout 有一个继续购买的按钮, 用于跳转到继续购买的页面
2578
2825
  {
2579
2826
  key: "_last_url",
2580
2827
  value: typeof window !== "undefined" ? window.location.origin + window.location.pathname : ""
2581
- },
2582
- {
2583
- key: "_user_type",
2584
- value: userType
2585
2828
  }
2586
2829
  ];
2587
- if (profile) {
2588
- checkoutCustomAttributes.push({
2589
- key: "_login_user",
2590
- value: "1"
2591
- });
2592
- }
2593
2830
  if (deliveryCustomData) {
2594
2831
  checkoutCustomAttributes.push({
2595
2832
  key: "_checkout_delivery_custom",
@@ -2599,12 +2836,6 @@ var usePlusMemberCheckoutCustomAttributes = ({
2599
2836
  })
2600
2837
  });
2601
2838
  }
2602
- if (variant?.metafields?.presell) {
2603
- checkoutCustomAttributes.push({
2604
- key: "_presale",
2605
- value: "true"
2606
- });
2607
- }
2608
2839
  if (isShowShippingBenefits && !isShowShippingBenefits({ variant, product, setting: {} })) {
2609
2840
  checkoutCustomAttributes.push({
2610
2841
  key: "_hide_shipping",
@@ -2612,18 +2843,17 @@ var usePlusMemberCheckoutCustomAttributes = ({
2612
2843
  });
2613
2844
  }
2614
2845
  return checkoutCustomAttributes;
2615
- }, [deliveryCustomData, product, profile, userType, variant, isShowShippingBenefits]);
2846
+ }, [deliveryCustomData, product, profile, variant, isShowShippingBenefits]);
2616
2847
  };
2617
2848
  function useAutoRemovePlusMemberInCart({
2618
- metafields,
2619
- isMonthlyPlus,
2620
- isAnnualPlus
2849
+ cart,
2850
+ profile,
2851
+ memberSetting
2621
2852
  }) {
2622
- const { plus_monthly_product, plus_annual_product } = metafields || {};
2623
- const { cart } = useCartContext();
2853
+ const { plus_monthly_product, plus_annual_product } = memberSetting || {};
2624
2854
  const { trigger: removeCartLines2 } = useRemoveCartLines();
2625
2855
  useEffect(() => {
2626
- if (!cart) return;
2856
+ if (!cart || !plus_monthly_product || !plus_annual_product) return;
2627
2857
  const removePlusProduct = async (productType) => {
2628
2858
  if (!productType) return;
2629
2859
  const product = cart.lineItems?.find(
@@ -2635,33 +2865,25 @@ function useAutoRemovePlusMemberInCart({
2635
2865
  });
2636
2866
  }
2637
2867
  };
2638
- if (isMonthlyPlus) {
2868
+ if (profile?.isMonthlyPlus) {
2639
2869
  removePlusProduct(plus_monthly_product);
2640
2870
  }
2641
- if (isAnnualPlus) {
2871
+ if (profile?.isAnnualPlus) {
2642
2872
  removePlusProduct(plus_annual_product);
2643
2873
  }
2644
- }, [
2645
- cart,
2646
- plus_annual_product,
2647
- plus_monthly_product,
2648
- isAnnualPlus,
2649
- isMonthlyPlus,
2650
- removeCartLines2
2651
- ]);
2874
+ }, [cart, plus_annual_product, plus_monthly_product, profile, removeCartLines2]);
2652
2875
  }
2653
- function useAddPlusMemberProductsToCart({
2876
+ function usePlusMemberNeedAddToCart({
2654
2877
  cart,
2655
- memberSetting,
2656
- selectedPlusMemberMode,
2657
- selectedPlusMemberProduct
2878
+ profile
2658
2879
  }) {
2880
+ const { selectedPlusMemberMode, selectedPlusMemberProduct, plusMemberMetafields } = usePlusMemberContext();
2659
2881
  const { hasMonthlyPlus, hasAnnualPlus } = useHasPlusMemberInCart({
2660
- cart,
2661
- memberSetting
2882
+ memberSetting: plusMemberMetafields,
2883
+ cart
2662
2884
  });
2663
2885
  const plusMemberProduct = useMemo(() => {
2664
- if (selectedPlusMemberMode === "free" /* FREE */) {
2886
+ if (!selectedPlusMemberProduct || selectedPlusMemberMode === "free" /* FREE */) {
2665
2887
  return void 0;
2666
2888
  }
2667
2889
  if (selectedPlusMemberMode === "monthly" /* MONTHLY */ && hasMonthlyPlus) {
@@ -2670,7 +2892,10 @@ function useAddPlusMemberProductsToCart({
2670
2892
  if (selectedPlusMemberMode === "annual" /* ANNUAL */ && hasAnnualPlus) {
2671
2893
  return void 0;
2672
2894
  }
2673
- if (!selectedPlusMemberProduct) {
2895
+ if (profile?.isMonthlyPlus && selectedPlusMemberMode === "monthly" /* MONTHLY */) {
2896
+ return void 0;
2897
+ }
2898
+ if (profile?.isAnnualPlus && selectedPlusMemberMode === "annual" /* ANNUAL */) {
2674
2899
  return void 0;
2675
2900
  }
2676
2901
  return selectedPlusMemberProduct;
@@ -2689,9 +2914,9 @@ var PlusMemberProvider = ({
2689
2914
  memberSetting,
2690
2915
  initialSelectedPlusMemberMode = "free",
2691
2916
  profile,
2692
- locale,
2693
2917
  children
2694
2918
  }) => {
2919
+ const { locale } = useShopify();
2695
2920
  const [zipCode, setZipCode] = useState("");
2696
2921
  const [showTip, setShowTip] = useState(false);
2697
2922
  const [selectedPlusMemberMode, setSelectedPlusMemberMode] = useState(
@@ -2707,7 +2932,11 @@ var PlusMemberProvider = ({
2707
2932
  const shippingMethodsContext = useShippingMethods({
2708
2933
  variant,
2709
2934
  plusMemberMetafields: memberSetting,
2710
- selectedPlusMemberMode});
2935
+ selectedPlusMemberMode,
2936
+ profile,
2937
+ isPlus: profile?.isPlus || false
2938
+ });
2939
+ console.log("shippingMethodsContext", shippingMethodsContext);
2711
2940
  const plusMemberHandles = useMemo(() => {
2712
2941
  return [
2713
2942
  memberSetting?.plus_monthly_product?.handle,
@@ -2944,6 +3173,6 @@ function clearGeoLocationCache(cacheKey = "geoLocation") {
2944
3173
  }
2945
3174
  }
2946
3175
 
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 };
3176
+ 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, 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
3177
  //# sourceMappingURL=index.mjs.map
2949
3178
  //# sourceMappingURL=index.mjs.map