@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.
@@ -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
 
@@ -77,9 +78,10 @@ function normalizeAddToCartLines(lines) {
77
78
  const variant = line.variant;
78
79
  const product = variant.product;
79
80
  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;
81
+ const originalPrice = variant.price?.amount ? Number(variant.price.amount) : 0;
82
+ const finalPrice = variant.finalPrice?.amount === void 0 ? originalPrice : Number(variant.finalPrice?.amount);
83
+ const subtotalAmount = originalPrice * quantity;
84
+ const totalAmount = finalPrice * quantity;
83
85
  return {
84
86
  id: `temp-line-${index}-${variant.id}`,
85
87
  // Temporary ID for pre-cart lines
@@ -93,7 +95,7 @@ function normalizeAddToCartLines(lines) {
93
95
  customAttributes: line.attributes || [],
94
96
  variant: {
95
97
  id: variant.id,
96
- price,
98
+ price: finalPrice,
97
99
  listPrice: variant.compareAtPrice?.amount ? Number(variant.compareAtPrice.amount) : 0,
98
100
  sku: variant.sku || "",
99
101
  name: variant.title || "",
@@ -124,15 +126,16 @@ function createMockCartFromLines(lines, existingCart) {
124
126
  const normalizedLines = normalizeAddToCartLines(lines);
125
127
  const subtotalPrice = normalizedLines.reduce((sum, line) => sum + line.subtotalAmount, 0);
126
128
  const totalPrice = normalizedLines.reduce((sum, line) => sum + line.totalAmount, 0);
129
+ const currency = lines[0]?.variant?.price?.currencyCode;
127
130
  return {
128
131
  id: existingCart?.id || "temp-cart-id",
129
132
  customerId: existingCart?.customerId,
130
133
  email: existingCart?.email,
131
134
  createdAt: existingCart?.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
132
- currency: existingCart?.currency || { code: "USD" },
135
+ currency: existingCart?.currency || { code: currency },
133
136
  taxesIncluded: existingCart?.taxesIncluded,
134
137
  lineItems: normalizedLines,
135
- totallineItemsDiscount: 0,
138
+ totalLineItemsDiscount: 0,
136
139
  orderDiscounts: 0,
137
140
  lineItemsSubtotalPrice: subtotalPrice,
138
141
  subtotalPrice,
@@ -163,22 +166,12 @@ var getQuery = () => {
163
166
  }
164
167
  return theRequest;
165
168
  };
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
169
  var getMatchedMainProductSubTotal = (cartData, variant_list, main_product) => {
177
170
  const isAllStoreVariant = main_product?.all_store_variant ?? false;
178
171
  const matchedList = cartData?.lineItems?.filter((line) => {
179
172
  const { is_gift } = getDiscountEnvAttributeValue(line.customAttributes);
180
173
  return isAllStoreVariant ? !is_gift : variant_list?.find((item) => {
181
- return !is_gift && atobID(line.variantId) === item;
174
+ return !is_gift && shopifyCore.atobID(line.variantId) === item;
182
175
  });
183
176
  });
184
177
  return matchedList?.reduce((acc, line) => {
@@ -404,43 +397,29 @@ var useCalcAutoFreeGift = (cart, autoFreeGiftConfig, customer, lines) => {
404
397
  }
405
398
  return { activeCampaign: null, subtotal: 0 };
406
399
  }, [autoFreeGiftConfig, effectiveCart, tags, dealsType]);
407
- const { qualifyingGift, nextTierGoal } = react.useMemo(() => {
400
+ const { qualifyingTier, nextTierGoal, actualThreshold, currentCurrency } = react.useMemo(() => {
408
401
  if (!activeCampaign || !activeCampaign.rule_result?.spend_get_reward?.gift_product) {
409
- return { qualifyingGift: null, nextTierGoal: null };
402
+ return { qualifyingTier: null, nextTierGoal: null, actualThreshold: 0, currentCurrency: "" };
410
403
  }
411
404
  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)
405
+ const currentCurrency2 = effectiveCart?.currency?.code || "";
406
+ console.log("currentCurrency useCalcAutoFreeGift", effectiveCart, currentCurrency2);
407
+ const getThresholdAmount = (tier) => {
408
+ if (tier.spend_sum_money_multi_markets?.[currentCurrency2]?.value) {
409
+ return Number(tier.spend_sum_money_multi_markets[currentCurrency2].value);
410
+ }
411
+ return Number(tier.spend_sum_money || 0);
441
412
  };
442
- return { qualifyingGift: formattedGift, nextTierGoal: nextGoal || null };
443
- }, [activeCampaign, subtotal]);
413
+ const qualifyingTier2 = [...giftTiers].sort((a, b) => getThresholdAmount(b) - getThresholdAmount(a)).find((tier) => subtotal >= getThresholdAmount(tier));
414
+ const nextGoal = giftTiers.find((tier) => subtotal < getThresholdAmount(tier));
415
+ const actualThreshold2 = qualifyingTier2 ? getThresholdAmount(qualifyingTier2) : 0;
416
+ return {
417
+ qualifyingTier: qualifyingTier2,
418
+ nextTierGoal: nextGoal || null,
419
+ actualThreshold: actualThreshold2,
420
+ currentCurrency: currentCurrency2
421
+ };
422
+ }, [activeCampaign, subtotal, effectiveCart]);
444
423
  const giftHandles = react.useMemo(() => {
445
424
  const giftVariant = autoFreeGiftConfig.map(
446
425
  (item) => item.rule_result?.spend_get_reward?.gift_product?.map(
@@ -456,24 +435,82 @@ var useCalcAutoFreeGift = (cart, autoFreeGiftConfig, customer, lines) => {
456
435
  }
457
436
  return true;
458
437
  }, [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
- });
438
+ const { data: giftProductsResult } = useSWR__default.default(
439
+ shouldFetch ? giftHandles : null,
440
+ async () => {
441
+ const res = await shopifySdk.getProductsByHandles(client, {
442
+ handles: giftHandles,
443
+ locale
444
+ });
445
+ const result = Array.isArray(res) ? res : [];
446
+ giftProductsCache.current = {
447
+ data: result,
448
+ giftHandles: [...giftHandles]
449
+ };
450
+ return result;
451
+ },
452
+ {
453
+ revalidateOnFocus: false
454
+ }
455
+ );
471
456
  const finalGiftProductsResult = react.useMemo(() => {
472
457
  if (giftProductsCache.current && !shouldFetch) {
473
458
  return giftProductsCache.current.data || void 0;
474
459
  }
475
460
  return giftProductsResult;
476
461
  }, [giftProductsResult, shouldFetch]);
462
+ const qualifyingGift = react.useMemo(() => {
463
+ if (!qualifyingTier || !activeCampaign) {
464
+ return null;
465
+ }
466
+ const itemsToAdd = qualifyingTier.reward_list?.map((reward) => {
467
+ if (!reward.variant_list || reward.variant_list.length === 0) {
468
+ return null;
469
+ }
470
+ let selectedGiftProduct = null;
471
+ for (const giftVariant of reward.variant_list) {
472
+ const productInfo = finalGiftProductsResult?.find(
473
+ (p) => p.handle === giftVariant.handle
474
+ );
475
+ if (productInfo) {
476
+ const variantInfo = productInfo.variants?.find((v) => v.sku === giftVariant.sku);
477
+ if (variantInfo?.availableForSale) {
478
+ selectedGiftProduct = giftVariant;
479
+ break;
480
+ }
481
+ }
482
+ }
483
+ if (!selectedGiftProduct) {
484
+ selectedGiftProduct = reward.variant_list[0];
485
+ }
486
+ return {
487
+ variant: {
488
+ id: shopifyCore.btoaID(selectedGiftProduct.variant_id),
489
+ handle: selectedGiftProduct.handle,
490
+ sku: selectedGiftProduct.sku
491
+ },
492
+ quantity: reward?.get_unit || 1,
493
+ attributes: [
494
+ {
495
+ key: CUSTOMER_ATTRIBUTE_KEY,
496
+ value: JSON.stringify({
497
+ is_gift: true,
498
+ rule_id: activeCampaign.rule_id,
499
+ spend_sum_money: actualThreshold,
500
+ // 使用实际的门槛金额(多币种支持)
501
+ currency_code: currentCurrency
502
+ // 记录当前币种
503
+ })
504
+ }
505
+ ]
506
+ };
507
+ }).filter((item) => item !== null);
508
+ const formattedGift = {
509
+ tier: qualifyingTier,
510
+ itemsToAdd
511
+ };
512
+ return formattedGift;
513
+ }, [qualifyingTier, activeCampaign, finalGiftProductsResult, actualThreshold, currentCurrency]);
477
514
  return {
478
515
  qualifyingGift,
479
516
  nextTierGoal,
@@ -520,12 +557,14 @@ var useScriptAutoFreeGift = ({
520
557
  upgrade_multiple2 = 1.2;
521
558
  upgrade_value2 = 40;
522
559
  }
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
- });
560
+ effectiveCart?.lineItems?.forEach(
561
+ ({ customAttributes }) => {
562
+ customAttributes?.forEach(({ key, value }) => {
563
+ if (key === "_amount_upgrade_multiple") upgrade_multiple2 = Number(value) || 1;
564
+ if (key === "_amount_upgrade_value") upgrade_value2 = Number(value) || 0;
565
+ });
566
+ }
567
+ );
529
568
  return [upgrade_multiple2, upgrade_value2];
530
569
  }, [effectiveCart?.lineItems, points_subscribe]);
531
570
  const breakpoints = react.useMemo(() => {
@@ -590,18 +629,24 @@ var useScriptAutoFreeGift = ({
590
629
  const nextLevel = levelIndex > 0 ? sortedLevels[levelIndex - 1] ?? null : null;
591
630
  return [currentLevel, nextLevel];
592
631
  }, [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
- });
632
+ const { data: giftProductsResult } = useSWR__default.default(
633
+ shouldFetch ? giftHandles : null,
634
+ async () => {
635
+ const res = await shopifySdk.getProductsByHandles(client, {
636
+ handles: giftHandles,
637
+ locale
638
+ });
639
+ const result = Array.isArray(res) ? res : [];
640
+ giftProductsCache.current = {
641
+ data: result,
642
+ giftHandles: [...giftHandles]
643
+ };
644
+ return result;
645
+ },
646
+ {
647
+ revalidateOnFocus: false
648
+ }
649
+ );
605
650
  const finalGiftProductsResult = react.useMemo(() => {
606
651
  if (giftProductsCache.current && !shouldFetch) {
607
652
  return giftProductsCache.current.data || void 0;
@@ -634,9 +679,9 @@ var useScriptAutoFreeGift = ({
634
679
  };
635
680
  };
636
681
  var CartContext = react.createContext(null);
637
- function useCartContext() {
682
+ function useCartContext(options) {
638
683
  const context = react.useContext(CartContext);
639
- if (!context) {
684
+ if (!context && true) {
640
685
  throw new Error("useCartContext must be used within a CartProvider");
641
686
  }
642
687
  return context;
@@ -678,11 +723,23 @@ function useAddCartLines(options) {
678
723
  const { mutateCart, metafieldIdentifiers } = useCartContext();
679
724
  const addLines = react.useCallback(
680
725
  async (_key, { arg }) => {
681
- let updatedCart = await shopifySdk.addCartLines(client, {
682
- ...arg,
683
- metafieldIdentifiers,
684
- cookieAdapter: cartCookieAdapter
685
- });
726
+ const { cartId, lines } = arg;
727
+ const id = cartId || cartCookieAdapter?.getCartId(locale);
728
+ let updatedCart;
729
+ if (!id) {
730
+ updatedCart = await shopifySdk.createCart(client, {
731
+ lines,
732
+ metafieldIdentifiers,
733
+ cookieAdapter: cartCookieAdapter
734
+ });
735
+ } else {
736
+ updatedCart = await shopifySdk.addCartLines(client, {
737
+ cartId: id,
738
+ lines,
739
+ metafieldIdentifiers,
740
+ cookieAdapter: cartCookieAdapter
741
+ });
742
+ }
686
743
  if (updatedCart) {
687
744
  const unApplicableCodes = updatedCart.discountCodes.filter((item) => !item.applicable).map((item) => item.code);
688
745
  if (unApplicableCodes.length > 0) {
@@ -729,7 +786,7 @@ var trackAddToCartGA = ({
729
786
  const currencyCode = variant.product?.price?.currencyCode;
730
787
  const totalPrice = lineItems?.reduce(
731
788
  (prev, { variant: variant2 }) => prev.plus(
732
- variant2?.finalPrice?.amount ?? variant2?.compareAtPrice?.amount ?? variant2?.price?.amount ?? 0
789
+ variant2?.finalPrice?.amount === void 0 ? Number(variant2?.price?.amount) || 0 : Number(variant2?.finalPrice?.amount) || 0
733
790
  ),
734
791
  new Decimal2__default.default(0)
735
792
  ).toNumber();
@@ -762,10 +819,10 @@ var trackBuyNowGA = ({
762
819
  return;
763
820
  }
764
821
  const { variant } = lineItems[0];
765
- const currencyCode = variant.price?.currencyCode;
822
+ const currencyCode = variant.product?.price?.currencyCode || variant.price?.currencyCode;
766
823
  const totalPrice = lineItems?.reduce(
767
824
  (prev, { variant: variant2 }) => prev.plus(
768
- variant2?.finalPrice?.amount ?? variant2?.compareAtPrice?.amount ?? (variant2?.price?.amount || 0)
825
+ variant2?.finalPrice?.amount === void 0 ? Number(variant2?.price?.amount) || 0 : Number(variant2?.finalPrice?.amount) || 0
769
826
  ),
770
827
  new Decimal2__default.default(0)
771
828
  ).toNumber();
@@ -839,7 +896,7 @@ function useApplyCartCodes(options) {
839
896
  if (!discountCodes?.length) {
840
897
  throw new Error("Invalid input used for this operation: Miss discountCode");
841
898
  }
842
- const cartId = providedCartId ? void 0 : providedCartId || cart?.id;
899
+ const cartId = providedCartId || cart?.id;
843
900
  if (!cartId) {
844
901
  return void 0;
845
902
  }
@@ -852,12 +909,18 @@ function useApplyCartCodes(options) {
852
909
  cookieAdapter: cartCookieAdapter,
853
910
  metafieldIdentifiers
854
911
  });
912
+ const unApplicableCodes = discountCodes.filter(
913
+ (code) => updatedCart?.discountCodes?.find((item) => item.code === code && !item.applicable)
914
+ );
915
+ if (unApplicableCodes.length) {
916
+ throw new Error(`${unApplicableCodes.join(", ")} is not applicable to the cart`);
917
+ }
855
918
  if (updatedCart) {
856
919
  mutateCart(updatedCart);
857
920
  }
858
921
  return updatedCart;
859
922
  },
860
- [client, locale, cartCookieAdapter, mutateCart, cart]
923
+ [client, locale, cartCookieAdapter, mutateCart, cart, metafieldIdentifiers]
861
924
  );
862
925
  return useSWRMutation__default.default("apply-codes", applyCodes, options);
863
926
  }
@@ -867,7 +930,7 @@ function useRemoveCartCodes(options) {
867
930
  const removeCodes = react.useCallback(
868
931
  async (_key, { arg }) => {
869
932
  const { cartId: providedCartId, discountCodes } = arg;
870
- const cartId = providedCartId ? void 0 : providedCartId || cart?.id;
933
+ const cartId = providedCartId || cart?.id;
871
934
  const codes = cart?.discountCodes?.filter((code) => !!code.applicable) || [];
872
935
  const leftCodes = codes.filter((code) => discountCodes?.length ? !discountCodes.includes(code.code) : code.code).map((code) => code.code);
873
936
  const updatedCart = await shopifySdk.updateCartCodes(client, {
@@ -881,18 +944,74 @@ function useRemoveCartCodes(options) {
881
944
  }
882
945
  return updatedCart;
883
946
  },
884
- [client, locale, cartCookieAdapter, mutateCart, cart]
947
+ [client, locale, cartCookieAdapter, mutateCart, cart, metafieldIdentifiers]
885
948
  );
886
949
  return useSWRMutation__default.default("remove-codes", removeCodes, options);
887
950
  }
888
951
 
952
+ // src/hooks/cart/utils/add-to-cart.ts
953
+ var getLinesWithAttributes = ({
954
+ cart,
955
+ lineItems
956
+ }) => {
957
+ return lineItems.map((line) => {
958
+ const sameLineInCart = cart?.lineItems.find(
959
+ (lineInCart) => lineInCart.variant.sku === line.variant?.sku && lineInCart.product?.handle === line.variant?.product?.handle
960
+ );
961
+ const codeAmountAttribute = sameLineInCart?.customAttributes?.find(
962
+ (attr) => attr.key === CODE_AMOUNT_KEY
963
+ );
964
+ const scriptCodeAmountAttribute = sameLineInCart?.customAttributes?.find(
965
+ (attr) => attr.key === SCRIPT_CODE_AMOUNT_KEY
966
+ );
967
+ let functionAttribute = null;
968
+ try {
969
+ functionAttribute = sameLineInCart?.customAttributes?.find(
970
+ (attr) => attr.key === CUSTOMER_ATTRIBUTE_KEY && JSON.parse(attr.value)?.discounted_amount
971
+ );
972
+ } catch (error) {
973
+ }
974
+ if (codeAmountAttribute || functionAttribute || scriptCodeAmountAttribute) {
975
+ return {
976
+ ...line,
977
+ attributes: [
978
+ ...line.attributes || [],
979
+ codeAmountAttribute,
980
+ functionAttribute,
981
+ scriptCodeAmountAttribute
982
+ ].filter(Boolean)
983
+ };
984
+ }
985
+ return line;
986
+ });
987
+ };
988
+ var getLinesWithFunctionAttributes = (lineItems) => {
989
+ return lineItems.map((line) => {
990
+ let itemAttributes = line.attributes || [];
991
+ const functionEnvAttribute = itemAttributes.find((attr) => attr.key === CUSTOMER_ATTRIBUTE_KEY);
992
+ if (!functionEnvAttribute) {
993
+ itemAttributes = itemAttributes.concat([
994
+ {
995
+ key: CUSTOMER_ATTRIBUTE_KEY,
996
+ value: JSON.stringify({
997
+ is_gift: false,
998
+ discounted_amount: line.variant?.finalPrice?.amount === void 0 ? Number(line.variant?.price?.amount) * (line.quantity || 1) : Number(line.variant?.finalPrice?.amount) * (line.quantity || 1)
999
+ })
1000
+ }
1001
+ ]);
1002
+ }
1003
+ return { ...line, attributes: itemAttributes };
1004
+ });
1005
+ };
1006
+
889
1007
  // src/hooks/cart/use-add-to-cart.ts
890
1008
  function useAddToCart({ withTrack = true } = {}, swrOptions) {
891
- const { client, config, locale, cartCookieAdapter, userAdapter } = useShopify();
892
- const { cart } = useCartContext();
1009
+ const { client, config, locale, cartCookieAdapter, userAdapter, performanceAdapter } = useShopify();
1010
+ const { cart, addCustomAttributes } = useCartContext();
893
1011
  const { trigger: applyCartCodes } = useApplyCartCodes();
894
1012
  const { trigger: removeInvalidCodes } = useRemoveCartCodes();
895
1013
  const { trigger: addCartLines2 } = useAddCartLines();
1014
+ const { trigger: createCart4 } = useCreateCart();
896
1015
  const addToCart = react.useCallback(
897
1016
  async (_key, { arg }) => {
898
1017
  const {
@@ -903,12 +1022,19 @@ function useAddToCart({ withTrack = true } = {}, swrOptions) {
903
1022
  buyerIdentity,
904
1023
  needCreateCart = false,
905
1024
  onCodesInvalid,
906
- replaceExistingCodes
1025
+ replaceExistingCodes,
1026
+ customAttributes
907
1027
  } = arg;
908
1028
  if (!lineItems || lineItems.length === 0) {
909
1029
  return;
910
1030
  }
911
- const lines = lineItems.map((item) => ({
1031
+ performanceAdapter?.addToCartStart();
1032
+ const linesWithAttributes = getLinesWithAttributes({
1033
+ cart,
1034
+ lineItems
1035
+ });
1036
+ const linesWithFunctionAttributes = getLinesWithFunctionAttributes(linesWithAttributes);
1037
+ const lines = linesWithFunctionAttributes.map((item) => ({
912
1038
  merchandiseId: item.variant?.id || "",
913
1039
  quantity: item.quantity || 1,
914
1040
  attributes: item.attributes,
@@ -917,36 +1043,45 @@ function useAddToCart({ withTrack = true } = {}, swrOptions) {
917
1043
  if (lines.length === 0) {
918
1044
  return;
919
1045
  }
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;
1046
+ let cartId = needCreateCart ? void 0 : providedCartId || cart?.id;
1047
+ let resultCart = null;
1048
+ if (!cartId) {
1049
+ resultCart = await createCart4({
1050
+ lines,
1051
+ buyerIdentity,
1052
+ discountCodes,
1053
+ customAttributes
1054
+ });
1055
+ } else {
1056
+ resultCart = await addCartLines2({
1057
+ cartId,
1058
+ lines
1059
+ });
1060
+ console.log("npm addCartLines resultCart", resultCart);
1061
+ if (resultCart && resultCart.discountCodes && resultCart.discountCodes.length > 0) {
1062
+ const unapplicableCodes = resultCart.discountCodes.filter((item) => !item.applicable).map((item) => item.code);
1063
+ if (unapplicableCodes.length > 0) {
1064
+ if (onCodesInvalid) {
1065
+ const handledCart = await onCodesInvalid(resultCart, unapplicableCodes);
1066
+ if (handledCart) {
1067
+ resultCart = handledCart;
1068
+ }
1069
+ } else {
1070
+ await removeInvalidCodes({
1071
+ discountCodes: unapplicableCodes
1072
+ });
937
1073
  }
938
- } else {
939
- await removeInvalidCodes({
940
- discountCodes: unapplicableCodes
941
- });
942
1074
  }
943
1075
  }
944
- }
945
- if (discountCodes && discountCodes.length > 0) {
946
- applyCartCodes({
947
- replaceExistingCodes,
948
- discountCodes
949
- });
1076
+ if (resultCart && discountCodes && discountCodes.length > 0) {
1077
+ applyCartCodes({
1078
+ replaceExistingCodes,
1079
+ discountCodes
1080
+ });
1081
+ }
1082
+ if (customAttributes && customAttributes.length > 0) {
1083
+ addCustomAttributes(customAttributes);
1084
+ }
950
1085
  }
951
1086
  if (withTrack) {
952
1087
  trackAddToCartGA({
@@ -955,9 +1090,24 @@ function useAddToCart({ withTrack = true } = {}, swrOptions) {
955
1090
  });
956
1091
  trackAddToCartFBQ({ lineItems });
957
1092
  }
1093
+ performanceAdapter?.addToCartEnd();
958
1094
  return resultCart;
959
1095
  },
960
- [client, locale, cartCookieAdapter, userAdapter, cart, withTrack]
1096
+ [
1097
+ client,
1098
+ locale,
1099
+ cartCookieAdapter,
1100
+ userAdapter,
1101
+ cart,
1102
+ withTrack,
1103
+ performanceAdapter,
1104
+ createCart4,
1105
+ addCartLines2,
1106
+ applyCartCodes,
1107
+ removeInvalidCodes,
1108
+ addCustomAttributes,
1109
+ config
1110
+ ]
961
1111
  );
962
1112
  return useSWRMutation__default.default("add-to-cart", addToCart, swrOptions);
963
1113
  }
@@ -974,9 +1124,10 @@ function useUpdateCartLines(options) {
974
1124
  if (updatedCart) {
975
1125
  mutateCart(updatedCart);
976
1126
  }
1127
+ console.log("use-update-cart-lines updatedCart", metafieldIdentifiers, updatedCart);
977
1128
  return updatedCart;
978
1129
  },
979
- [client, locale, cartCookieAdapter, mutateCart]
1130
+ [client, locale, cartCookieAdapter, mutateCart, metafieldIdentifiers]
980
1131
  );
981
1132
  return useSWRMutation__default.default("update-cart-lines", updateLines, options);
982
1133
  }
@@ -1015,7 +1166,7 @@ function useRemoveCartLines(options) {
1015
1166
  }
1016
1167
  return updatedCart;
1017
1168
  },
1018
- [client, locale, cartCookieAdapter, mutateCart]
1169
+ [client, locale, cartCookieAdapter, mutateCart, metafieldIdentifiers]
1019
1170
  );
1020
1171
  return useSWRMutation__default.default("remove-cart-lines", removeLines, options);
1021
1172
  }
@@ -1034,7 +1185,7 @@ function useUpdateCartAttributes(mutate, metafieldIdentifiers, options) {
1034
1185
  }
1035
1186
  return updatedCart;
1036
1187
  },
1037
- [client, locale, cartCookieAdapter, mutate]
1188
+ [client, locale, cartCookieAdapter, mutate, metafieldIdentifiers]
1038
1189
  );
1039
1190
  return useSWRMutation__default.default("update-cart-attributes", updateAttributes, options);
1040
1191
  }
@@ -1056,7 +1207,8 @@ function useBuyNow({ withTrack = true } = {}, swrOptions) {
1056
1207
  if (!lineItems || lineItems.length === 0) {
1057
1208
  return;
1058
1209
  }
1059
- const lines = lineItems.map((item) => ({
1210
+ const linesWithFunctionAttributes = getLinesWithFunctionAttributes(lineItems);
1211
+ const lines = linesWithFunctionAttributes.map((item) => ({
1060
1212
  merchandiseId: item.variant?.id || "",
1061
1213
  quantity: item.quantity || 1,
1062
1214
  attributes: item.attributes,
@@ -1174,7 +1326,7 @@ var useCalcOrderDiscount = (cart, orderDiscountConfig, customer) => {
1174
1326
  const isCustomerLoading = react.useMemo(() => !customer ? true : false, [customer]);
1175
1327
  const dealsType = "";
1176
1328
  const { activeCampaign, subtotal } = react.useMemo(() => {
1177
- for (const campaign of orderDiscountConfig) {
1329
+ for (const campaign of orderDiscountConfig || []) {
1178
1330
  const { rule_conditions = [], result_detail } = campaign;
1179
1331
  const { main_product, order_discount_conf } = result_detail || {};
1180
1332
  const isPreCheckPassed = preCheck(rule_conditions, tags, []);
@@ -1204,9 +1356,12 @@ var useCalcOrderDiscount = (cart, orderDiscountConfig, customer) => {
1204
1356
  discountAmount: 0
1205
1357
  };
1206
1358
  }
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));
1359
+ const currentCurrency = cart?.currency?.code || "";
1360
+ console.log("currentCurrency", cart, currentCurrency);
1361
+ const orderDiscountConf = activeCampaign.result_detail.order_discount_conf;
1362
+ const tieredDiscounts = orderDiscountConf.tiered_discounts_markets?.[currentCurrency] || orderDiscountConf.tiered_discounts;
1363
+ const qualifyingTier = [...tieredDiscounts].sort((a, b) => Number(b.amount) - Number(a.amount)).find((tier) => subtotal >= Number(tier.amount));
1364
+ const nextGoal = [...tieredDiscounts].sort((a, b) => Number(a.amount) - Number(b.amount)).find((tier) => subtotal < Number(tier.amount));
1210
1365
  if (!qualifyingTier) {
1211
1366
  return {
1212
1367
  qualifyingDiscount: null,
@@ -1274,12 +1429,10 @@ function useHasPlusMemberInCart({
1274
1429
  };
1275
1430
  }, [cart?.lineItems, plus_monthly_product, plus_annual_product]);
1276
1431
  }
1277
-
1278
- // src/hooks/cart/feature/use-cart-attributes.ts
1279
1432
  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");
1433
+ const inviteCode = shopifySdk.getLocalStorage("inviteCode") || Cookies5__default.default.get("inviteCode");
1434
+ const playModeId = shopifySdk.getLocalStorage("playModeId") || Cookies5__default.default.get("playModeId");
1435
+ const popup = shopifySdk.getLocalStorage("_popup") || Cookies5__default.default.get("_popup");
1283
1436
  if (inviteCode && playModeId) {
1284
1437
  return popup ? [
1285
1438
  { key: "_invite_code", value: inviteCode ? inviteCode : "" },
@@ -1303,8 +1456,6 @@ var useCartAttributes = ({
1303
1456
  memberSetting,
1304
1457
  cart
1305
1458
  });
1306
- console.log("memberSetting", memberSetting);
1307
- console.log("hasPlusMember", hasPlusMember);
1308
1459
  react.useEffect(() => {
1309
1460
  setCurrentUrl(window.location.href);
1310
1461
  }, []);
@@ -1330,7 +1481,7 @@ var useCartAttributes = ({
1330
1481
  return "new_user_login";
1331
1482
  }, [customer]);
1332
1483
  const memberAttributes = react.useMemo(() => {
1333
- return [
1484
+ const attributes = [
1334
1485
  {
1335
1486
  key: "_token",
1336
1487
  value: profile?.token
@@ -1351,17 +1502,28 @@ var useCartAttributes = ({
1351
1502
  value: profile?.token ? "true" : "false"
1352
1503
  }
1353
1504
  ];
1505
+ if (profile?.token) {
1506
+ attributes.push({
1507
+ key: "_login_user",
1508
+ value: "1"
1509
+ });
1510
+ }
1511
+ return attributes;
1354
1512
  }, [profile?.memberType, profile?.token, userType, hasPlusMember]);
1355
1513
  const functionAttributes = react.useMemo(() => {
1356
- return [
1357
- cart?.discountCodes && {
1514
+ const hasFunctionEnvAttribute = cart?.lineItems.some(
1515
+ (item) => item.customAttributes?.some((attr) => attr.key === CUSTOMER_ATTRIBUTE_KEY)
1516
+ );
1517
+ const discountCodes = cart?.discountCodes.map((item) => item.code).filter((code) => code) || [];
1518
+ return hasFunctionEnvAttribute ? [
1519
+ {
1358
1520
  key: "_discounts_function_env",
1359
1521
  value: JSON.stringify({
1360
- discount_code: cart?.discountCodes.map((item) => item.code),
1522
+ discount_code: discountCodes,
1361
1523
  user_tags: customer?.tags || []
1362
1524
  })
1363
1525
  }
1364
- ];
1526
+ ] : [];
1365
1527
  }, [cart]);
1366
1528
  const presellAttributes = react.useMemo(() => {
1367
1529
  return [
@@ -1393,18 +1555,50 @@ var useCartAttributes = ({
1393
1555
  }
1394
1556
  ];
1395
1557
  }, [currentUrl]);
1558
+ const commonAttributes = react.useMemo(
1559
+ () => [
1560
+ ...memberAttributes,
1561
+ ...functionAttributes,
1562
+ ...presellAttributes,
1563
+ ...weightAttributes,
1564
+ ...trackingAttributes,
1565
+ ...getReferralAttributes()
1566
+ ].filter((item) => item?.value),
1567
+ [memberAttributes, functionAttributes, presellAttributes, weightAttributes, trackingAttributes]
1568
+ );
1569
+ const extraAttributesInCart = react.useMemo(() => {
1570
+ const commonAttributeKeys = [
1571
+ // member attributes
1572
+ "_token",
1573
+ "_member_type",
1574
+ "_user_type",
1575
+ "_is_login",
1576
+ "_login_user",
1577
+ // function attributes
1578
+ "_discounts_function_env",
1579
+ // presell attributes
1580
+ "_presale",
1581
+ // weight attributes
1582
+ "_weight",
1583
+ "_app_source_name",
1584
+ // tracking attributes
1585
+ "utm_params",
1586
+ // referral attributes
1587
+ "_invite_code",
1588
+ "_play_mode_id",
1589
+ "_popup"
1590
+ ];
1591
+ return cart?.customAttributes?.filter(
1592
+ (item) => !commonAttributeKeys.includes(item.key)
1593
+ ) || [];
1594
+ }, [cart]);
1396
1595
  return react.useMemo(
1397
1596
  () => ({
1398
- attributes: [
1399
- ...memberAttributes,
1400
- ...functionAttributes,
1401
- ...presellAttributes,
1402
- ...weightAttributes,
1403
- ...trackingAttributes,
1404
- ...getReferralAttributes()
1405
- ].filter((item) => item?.value)
1597
+ attributes: [...commonAttributes, ...extraAttributesInCart].filter(
1598
+ (item) => item?.value
1599
+ )
1406
1600
  }),
1407
- [memberAttributes, functionAttributes, presellAttributes, weightAttributes, trackingAttributes]
1601
+ [commonAttributes, extraAttributesInCart]
1408
1602
  );
1409
1603
  };
1410
1604
  var DEFAULT_MIN = 1;
@@ -1467,7 +1661,7 @@ var useUpdateLineCodeAmountAttributes = ({
1467
1661
  );
1468
1662
  const functionEnvValue = getDiscountEnvAttributeValue(line.customAttributes);
1469
1663
  const hasSameFunctionEnvAttribute = Number(functionEnvValue.discounted_amount) === Number(line.totalAmount);
1470
- if (!hasSameFunctionEnvAttribute && hasFunctionEnvAttribute) {
1664
+ if (!hasSameFunctionEnvAttribute && hasFunctionEnvAttribute && !functionEnvValue.is_gift) {
1471
1665
  attrNeedUpdate.push({
1472
1666
  key: CUSTOMER_ATTRIBUTE_KEY,
1473
1667
  value: JSON.stringify({
@@ -1506,29 +1700,22 @@ var useUpdateLineCodeAmountAttributes = ({
1506
1700
  }).filter(
1507
1701
  ({ attrNeedUpdate, attrNeedDelete }) => attrNeedUpdate.length || attrNeedDelete.length
1508
1702
  ).map(({ line, attrNeedUpdate, attrNeedDelete }) => {
1703
+ let lineId = line.id;
1704
+ let attributes = line.customAttributes || [];
1705
+ if (attrNeedDelete.length) {
1706
+ attributes = attributes.filter(
1707
+ (attr) => !attrNeedDelete.includes(attr.key)
1708
+ );
1709
+ }
1509
1710
  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
- };
1711
+ attributes = attributes.filter(
1712
+ (attr) => !attrNeedUpdate.some((updateAttr) => updateAttr.key === attr.key)
1713
+ ).concat(attrNeedUpdate);
1531
1714
  }
1715
+ return {
1716
+ id: lineId,
1717
+ attributes
1718
+ };
1532
1719
  }),
1533
1720
  [cart?.lineItems, mainProductDiscountCodes]
1534
1721
  );
@@ -1621,8 +1808,9 @@ function useProductsByHandles(options = {}) {
1621
1808
  metafieldIdentifiers
1622
1809
  });
1623
1810
  },
1624
- swrOptions || {
1625
- revalidateOnFocus: false
1811
+ {
1812
+ revalidateOnFocus: false,
1813
+ ...swrOptions
1626
1814
  }
1627
1815
  );
1628
1816
  }
@@ -2251,7 +2439,10 @@ var createInitialValue = () => ({
2251
2439
  freeShippingMethods: [],
2252
2440
  paymentShippingMethods: [],
2253
2441
  nddOverweight: false,
2254
- tddOverweight: false
2442
+ tddOverweight: false,
2443
+ nddCoupon: void 0,
2444
+ tddCoupon: void 0,
2445
+ isLoadingCoupon: false
2255
2446
  },
2256
2447
  selectedPlusMemberProduct: null,
2257
2448
  plusMemberProducts: [],
@@ -2296,15 +2487,29 @@ function usePlusAnnualProductVariant() {
2296
2487
  }, [plusMemberProducts, plusAnnual]);
2297
2488
  return plusAnnualProductVariant;
2298
2489
  }
2299
- function useShippingMethods(options) {
2300
- const {
2301
- variant,
2302
- plusMemberMetafields,
2303
- selectedPlusMemberMode,
2304
- isPlus = false,
2490
+ var useAvailableDeliveryCoupon = ({
2491
+ profile
2492
+ }) => {
2493
+ const { data: availableDeliveryCoupon, isLoading } = useSWR__default.default(
2494
+ profile?.email ? ["/api/multipass/subsrv/v1/prime/delivery_coupons/current/available", profile?.email] : void 0,
2495
+ async ([apiPath]) => {
2496
+ return fetch(apiPath).then((res) => res.json());
2497
+ }
2498
+ );
2499
+ console.log("availableDeliveryCoupon", availableDeliveryCoupon);
2500
+ const { ndd_coupon: nddCoupon, tdd_coupon: tddCoupon } = availableDeliveryCoupon?.data?.data || {};
2501
+ return {
2305
2502
  nddCoupon,
2306
- tddCoupon
2307
- } = options;
2503
+ tddCoupon,
2504
+ isLoading
2505
+ };
2506
+ };
2507
+
2508
+ // src/hooks/member/plus/use-shipping-methods.ts
2509
+ function useShippingMethods(options) {
2510
+ const { variant, plusMemberMetafields, selectedPlusMemberMode, isPlus = false, profile } = options;
2511
+ const { nddCoupon, tddCoupon, isLoading } = useAvailableDeliveryCoupon({ profile });
2512
+ console.log("nddCoupon", nddCoupon);
2308
2513
  const { plus_shipping, shippingMethod } = plusMemberMetafields || {};
2309
2514
  const nddOverweight = react.useMemo(() => {
2310
2515
  return (variant?.weight || 0) > (shippingMethod?.overWeight_ndd || Infinity);
@@ -2314,12 +2519,10 @@ function useShippingMethods(options) {
2314
2519
  }, [shippingMethod?.overWeight_tdd, variant?.weight]);
2315
2520
  const paymentShippingMethods = react.useMemo(() => {
2316
2521
  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
- ) || [];
2522
+ const methods = plus_shipping?.shipping_methods?.filter(({ weight_low, weight_high, __mode, __plus }) => {
2523
+ const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2524
+ return __mode !== "free" /* FREE */ && !__plus && fitWeight;
2525
+ }) || [];
2323
2526
  return methods.map((method) => {
2324
2527
  let disabled = false;
2325
2528
  const selectedFreeMember = selectedPlusMemberMode === "free";
@@ -2346,40 +2549,34 @@ function useShippingMethods(options) {
2346
2549
  ]);
2347
2550
  const nddPrice = react.useMemo(() => {
2348
2551
  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
- );
2552
+ const nddMethod = paymentShippingMethods.find(({ __mode, weight_high, weight_low }) => {
2553
+ const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2554
+ return __mode === "ndd" && fitWeight;
2555
+ });
2355
2556
  return nddMethod?.price || 0;
2356
2557
  }, [variant?.weight, paymentShippingMethods]);
2357
2558
  const tddPrice = react.useMemo(() => {
2358
2559
  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
- );
2560
+ const tddMethod = paymentShippingMethods.find(({ __mode, weight_high, weight_low }) => {
2561
+ const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2562
+ return __mode === "tdd" && fitWeight;
2563
+ });
2365
2564
  return tddMethod?.price || 0;
2366
2565
  }, [variant?.weight, paymentShippingMethods]);
2367
2566
  const freeShippingMethods = react.useMemo(() => {
2368
2567
  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
- }
2568
+ let methods = plus_shipping?.shipping_methods?.filter(({ __mode, __plus, weight_low, weight_high }) => {
2569
+ if (__mode === "free" /* FREE */) {
2570
+ return true;
2381
2571
  }
2382
- ) || [];
2572
+ if (isPlus) {
2573
+ const hasCoupon = isPlus && __mode === "ndd" /* NDD */ && nddCoupon || isPlus && __mode === "tdd" /* TDD */ && (tddCoupon || nddCoupon);
2574
+ const fitWeight = (!weight_low || weight >= weight_low) && (!weight_high || weight <= weight_high);
2575
+ return hasCoupon && fitWeight && !__plus;
2576
+ } else {
2577
+ return __plus;
2578
+ }
2579
+ }) || [];
2383
2580
  if (isPlus) {
2384
2581
  methods = methods.sort((a, b) => {
2385
2582
  if (b.__mode === "free" /* FREE */) return -1;
@@ -2433,7 +2630,10 @@ function useShippingMethods(options) {
2433
2630
  freeShippingMethods,
2434
2631
  paymentShippingMethods,
2435
2632
  nddOverweight,
2436
- tddOverweight
2633
+ tddOverweight,
2634
+ nddCoupon,
2635
+ tddCoupon,
2636
+ isLoadingCoupon: isLoading
2437
2637
  };
2438
2638
  }
2439
2639
  function useShippingMethodAvailableCheck() {
@@ -2538,6 +2738,73 @@ var usePlusMemberDeliveryCodes = ({
2538
2738
  [deliveryData]
2539
2739
  );
2540
2740
  };
2741
+ function useUpdateCartDeliveryOptions(mutate, metafieldIdentifiers, options) {
2742
+ const { client, locale, cartCookieAdapter } = useShopify();
2743
+ const updateDeliveryOptions = react.useCallback(
2744
+ async (_key, { arg }) => {
2745
+ const updatedCart = await shopifySdk.updateCartDeliveryOptions(client, {
2746
+ ...arg,
2747
+ metafieldIdentifiers,
2748
+ cookieAdapter: cartCookieAdapter
2749
+ });
2750
+ console.log("useUpdateCartDeliveryOptions updatedCart", updatedCart);
2751
+ if (updatedCart) {
2752
+ mutate(updatedCart);
2753
+ }
2754
+ return updatedCart;
2755
+ },
2756
+ [client, locale, cartCookieAdapter, mutate, metafieldIdentifiers]
2757
+ );
2758
+ return useSWRMutation__default.default("update-cart-delivery-options", updateDeliveryOptions, options);
2759
+ }
2760
+
2761
+ // src/hooks/member/plus/use-update-plus-member-delivery-options.ts
2762
+ var useUpdatePlusMemberDeliveryOptions = ({
2763
+ options
2764
+ } = {}) => {
2765
+ const { cart: cartContextData, mutateCart, metafieldIdentifiers } = useCartContext();
2766
+ const { trigger: updateCartDeliveryOptions2 } = useUpdateCartDeliveryOptions(
2767
+ mutateCart,
2768
+ metafieldIdentifiers
2769
+ );
2770
+ const handler = react.useCallback(
2771
+ async (_, { arg }) => {
2772
+ const currentCart = arg?.cart || cartContextData;
2773
+ const { deliveryData } = arg;
2774
+ const firstDeliveryGroup = currentCart?.deliveryGroups?.[0];
2775
+ const deliveryGroupId = firstDeliveryGroup?.id;
2776
+ const selectedOptionCode = deliveryData?.deliveryCustomData?.selected_delivery_option?.code;
2777
+ if (!deliveryGroupId || !selectedOptionCode || selectedOptionCode === firstDeliveryGroup?.selectedDeliveryOption?.code) {
2778
+ return null;
2779
+ }
2780
+ const deliveryGroup = currentCart?.deliveryGroups?.find(
2781
+ (group) => group?.id === deliveryGroupId
2782
+ );
2783
+ const matchedOption = deliveryGroup?.deliveryOptions?.find(
2784
+ (option) => option?.code === selectedOptionCode
2785
+ );
2786
+ if (!matchedOption?.handle) {
2787
+ return null;
2788
+ }
2789
+ const deliveryOptions = [
2790
+ {
2791
+ deliveryGroupId,
2792
+ deliveryOptionHandle: matchedOption.handle
2793
+ }
2794
+ ];
2795
+ const updatedCart = await updateCartDeliveryOptions2({
2796
+ selectedDeliveryOptions: deliveryOptions,
2797
+ cartId: currentCart?.id
2798
+ });
2799
+ if (updatedCart && mutateCart) {
2800
+ mutateCart(updatedCart);
2801
+ }
2802
+ return updatedCart;
2803
+ },
2804
+ [cartContextData, updateCartDeliveryOptions2, mutateCart]
2805
+ );
2806
+ return useSWRMutation__default.default("update-cart-delivery-options", handler, options);
2807
+ };
2541
2808
  var usePlusMemberItemCustomAttributes = ({
2542
2809
  deliveryData
2543
2810
  }) => {
@@ -2557,48 +2824,18 @@ var usePlusMemberCheckoutCustomAttributes = ({
2557
2824
  deliveryData,
2558
2825
  product,
2559
2826
  variant,
2560
- customer,
2561
2827
  isShowShippingBenefits
2562
2828
  }) => {
2563
2829
  const { deliveryCustomData } = deliveryData || {};
2564
2830
  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
2831
  return react.useMemo(() => {
2582
2832
  const checkoutCustomAttributes = [
2583
- {
2584
- key: "_token",
2585
- value: profile?.token || ""
2586
- },
2833
+ // _last_url: 付费会员结算完成之后 checkout 有一个继续购买的按钮, 用于跳转到继续购买的页面
2587
2834
  {
2588
2835
  key: "_last_url",
2589
2836
  value: typeof window !== "undefined" ? window.location.origin + window.location.pathname : ""
2590
- },
2591
- {
2592
- key: "_user_type",
2593
- value: userType
2594
2837
  }
2595
2838
  ];
2596
- if (profile) {
2597
- checkoutCustomAttributes.push({
2598
- key: "_login_user",
2599
- value: "1"
2600
- });
2601
- }
2602
2839
  if (deliveryCustomData) {
2603
2840
  checkoutCustomAttributes.push({
2604
2841
  key: "_checkout_delivery_custom",
@@ -2608,12 +2845,6 @@ var usePlusMemberCheckoutCustomAttributes = ({
2608
2845
  })
2609
2846
  });
2610
2847
  }
2611
- if (variant?.metafields?.presell) {
2612
- checkoutCustomAttributes.push({
2613
- key: "_presale",
2614
- value: "true"
2615
- });
2616
- }
2617
2848
  if (isShowShippingBenefits && !isShowShippingBenefits({ variant, product, setting: {} })) {
2618
2849
  checkoutCustomAttributes.push({
2619
2850
  key: "_hide_shipping",
@@ -2621,18 +2852,17 @@ var usePlusMemberCheckoutCustomAttributes = ({
2621
2852
  });
2622
2853
  }
2623
2854
  return checkoutCustomAttributes;
2624
- }, [deliveryCustomData, product, profile, userType, variant, isShowShippingBenefits]);
2855
+ }, [deliveryCustomData, product, profile, variant, isShowShippingBenefits]);
2625
2856
  };
2626
2857
  function useAutoRemovePlusMemberInCart({
2627
- metafields,
2628
- isMonthlyPlus,
2629
- isAnnualPlus
2858
+ cart,
2859
+ profile,
2860
+ memberSetting
2630
2861
  }) {
2631
- const { plus_monthly_product, plus_annual_product } = metafields || {};
2632
- const { cart } = useCartContext();
2862
+ const { plus_monthly_product, plus_annual_product } = memberSetting || {};
2633
2863
  const { trigger: removeCartLines2 } = useRemoveCartLines();
2634
2864
  react.useEffect(() => {
2635
- if (!cart) return;
2865
+ if (!cart || !plus_monthly_product || !plus_annual_product) return;
2636
2866
  const removePlusProduct = async (productType) => {
2637
2867
  if (!productType) return;
2638
2868
  const product = cart.lineItems?.find(
@@ -2644,33 +2874,25 @@ function useAutoRemovePlusMemberInCart({
2644
2874
  });
2645
2875
  }
2646
2876
  };
2647
- if (isMonthlyPlus) {
2877
+ if (profile?.isMonthlyPlus) {
2648
2878
  removePlusProduct(plus_monthly_product);
2649
2879
  }
2650
- if (isAnnualPlus) {
2880
+ if (profile?.isAnnualPlus) {
2651
2881
  removePlusProduct(plus_annual_product);
2652
2882
  }
2653
- }, [
2654
- cart,
2655
- plus_annual_product,
2656
- plus_monthly_product,
2657
- isAnnualPlus,
2658
- isMonthlyPlus,
2659
- removeCartLines2
2660
- ]);
2883
+ }, [cart, plus_annual_product, plus_monthly_product, profile, removeCartLines2]);
2661
2884
  }
2662
- function useAddPlusMemberProductsToCart({
2885
+ function usePlusMemberNeedAddToCart({
2663
2886
  cart,
2664
- memberSetting,
2665
- selectedPlusMemberMode,
2666
- selectedPlusMemberProduct
2887
+ profile
2667
2888
  }) {
2889
+ const { selectedPlusMemberMode, selectedPlusMemberProduct, plusMemberMetafields } = usePlusMemberContext();
2668
2890
  const { hasMonthlyPlus, hasAnnualPlus } = useHasPlusMemberInCart({
2669
- cart,
2670
- memberSetting
2891
+ memberSetting: plusMemberMetafields,
2892
+ cart
2671
2893
  });
2672
2894
  const plusMemberProduct = react.useMemo(() => {
2673
- if (selectedPlusMemberMode === "free" /* FREE */) {
2895
+ if (!selectedPlusMemberProduct || selectedPlusMemberMode === "free" /* FREE */) {
2674
2896
  return void 0;
2675
2897
  }
2676
2898
  if (selectedPlusMemberMode === "monthly" /* MONTHLY */ && hasMonthlyPlus) {
@@ -2679,7 +2901,10 @@ function useAddPlusMemberProductsToCart({
2679
2901
  if (selectedPlusMemberMode === "annual" /* ANNUAL */ && hasAnnualPlus) {
2680
2902
  return void 0;
2681
2903
  }
2682
- if (!selectedPlusMemberProduct) {
2904
+ if (profile?.isMonthlyPlus && selectedPlusMemberMode === "monthly" /* MONTHLY */) {
2905
+ return void 0;
2906
+ }
2907
+ if (profile?.isAnnualPlus && selectedPlusMemberMode === "annual" /* ANNUAL */) {
2683
2908
  return void 0;
2684
2909
  }
2685
2910
  return selectedPlusMemberProduct;
@@ -2698,9 +2923,9 @@ var PlusMemberProvider = ({
2698
2923
  memberSetting,
2699
2924
  initialSelectedPlusMemberMode = "free",
2700
2925
  profile,
2701
- locale,
2702
2926
  children
2703
2927
  }) => {
2928
+ const { locale } = useShopify();
2704
2929
  const [zipCode, setZipCode] = react.useState("");
2705
2930
  const [showTip, setShowTip] = react.useState(false);
2706
2931
  const [selectedPlusMemberMode, setSelectedPlusMemberMode] = react.useState(
@@ -2716,7 +2941,11 @@ var PlusMemberProvider = ({
2716
2941
  const shippingMethodsContext = useShippingMethods({
2717
2942
  variant,
2718
2943
  plusMemberMetafields: memberSetting,
2719
- selectedPlusMemberMode});
2944
+ selectedPlusMemberMode,
2945
+ profile,
2946
+ isPlus: profile?.isPlus || false
2947
+ });
2948
+ console.log("shippingMethodsContext", shippingMethodsContext);
2720
2949
  const plusMemberHandles = react.useMemo(() => {
2721
2950
  return [
2722
2951
  memberSetting?.plus_monthly_product?.handle,
@@ -2971,8 +3200,6 @@ exports.RuleType = RuleType;
2971
3200
  exports.SCRIPT_CODE_AMOUNT_KEY = SCRIPT_CODE_AMOUNT_KEY;
2972
3201
  exports.ShippingMethodMode = ShippingMethodMode;
2973
3202
  exports.SpendMoneyType = SpendMoneyType;
2974
- exports.atobID = atobID;
2975
- exports.btoaID = btoaID;
2976
3203
  exports.checkAttributesUpdateNeeded = checkAttributesUpdateNeeded;
2977
3204
  exports.clearGeoLocationCache = clearGeoLocationCache;
2978
3205
  exports.createMockCartFromLines = createMockCartFromLines;
@@ -2989,7 +3216,6 @@ exports.normalizeAddToCartLines = normalizeAddToCartLines;
2989
3216
  exports.preCheck = preCheck;
2990
3217
  exports.safeParse = safeParse;
2991
3218
  exports.useAddCartLines = useAddCartLines;
2992
- exports.useAddPlusMemberProductsToCart = useAddPlusMemberProductsToCart;
2993
3219
  exports.useAddToCart = useAddToCart;
2994
3220
  exports.useAllBlogs = useAllBlogs;
2995
3221
  exports.useAllCollections = useAllCollections;
@@ -2999,6 +3225,7 @@ exports.useArticle = useArticle;
2999
3225
  exports.useArticles = useArticles;
3000
3226
  exports.useArticlesInBlog = useArticlesInBlog;
3001
3227
  exports.useAutoRemovePlusMemberInCart = useAutoRemovePlusMemberInCart;
3228
+ exports.useAvailableDeliveryCoupon = useAvailableDeliveryCoupon;
3002
3229
  exports.useBlog = useBlog;
3003
3230
  exports.useBuyNow = useBuyNow;
3004
3231
  exports.useCalcAutoFreeGift = useCalcAutoFreeGift;
@@ -3018,6 +3245,7 @@ exports.usePlusMemberCheckoutCustomAttributes = usePlusMemberCheckoutCustomAttri
3018
3245
  exports.usePlusMemberContext = usePlusMemberContext;
3019
3246
  exports.usePlusMemberDeliveryCodes = usePlusMemberDeliveryCodes;
3020
3247
  exports.usePlusMemberItemCustomAttributes = usePlusMemberItemCustomAttributes;
3248
+ exports.usePlusMemberNeedAddToCart = usePlusMemberNeedAddToCart;
3021
3249
  exports.usePlusMonthlyProductVariant = usePlusMonthlyProductVariant;
3022
3250
  exports.usePrice = usePrice;
3023
3251
  exports.useProduct = useProduct;
@@ -3035,6 +3263,7 @@ exports.useSite = useSite;
3035
3263
  exports.useUpdateCartAttributes = useUpdateCartAttributes;
3036
3264
  exports.useUpdateCartLines = useUpdateCartLines;
3037
3265
  exports.useUpdateLineCodeAmountAttributes = useUpdateLineCodeAmountAttributes;
3266
+ exports.useUpdatePlusMemberDeliveryOptions = useUpdatePlusMemberDeliveryOptions;
3038
3267
  exports.useUpdateVariantQuery = useUpdateVariantQuery;
3039
3268
  exports.useVariant = useVariant;
3040
3269
  exports.useVariantMedia = useVariantMedia;