@anker-in/shopify-react 0.1.1-beta.1 → 0.1.1-beta.11

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.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createContext, useMemo, useContext, useRef, useState, useEffect, useCallback } from 'react';
2
- import { createShopifyClient, getProductsByHandles, createCart, updateCartCodes, addCartLines, updateCartLines, removeCartLines, updateCartAttributes, getProduct, getAllProducts, getCollection, getAllCollections, getCollections, getBlog, getAllBlogs, getArticle, getArticles, getArticlesInBlog, getLocalStorage, getCart, setLocalStorage } from '@anker-in/shopify-sdk';
2
+ import { createShopifyClient, getProductsByHandles, createCart, updateCartCodes, addCartLines, updateCartLines, removeCartLines, updateCartAttributes, getProduct, getAllProducts, getCollection, getAllCollections, getCollections, getBlog, getAllBlogs, getArticle, getArticles, getArticlesInBlog, getLocalStorage, getCart, setLocalStorage, updateCartDeliveryOptions } from '@anker-in/shopify-sdk';
3
3
  export { ShopifyConfig, clearLocalStorage, createShopifyClient, getLocalStorage, removeLocalStorage, setLocalStorage } from '@anker-in/shopify-sdk';
4
4
  import Cookies5 from 'js-cookie';
5
5
  import { jsx } from 'react/jsx-runtime';
@@ -134,6 +134,81 @@ var CODE_AMOUNT_KEY = "_sku_code_money";
134
134
  var SCRIPT_CODE_AMOUNT_KEY = "_code_money";
135
135
  var MAIN_PRODUCT_CODE = ["WS24", "WSTD", "WS7D", "WSCP", "WSPE", "WSPD"];
136
136
 
137
+ // src/hooks/cart/utils/normalize-add-to-cart-lines.ts
138
+ function normalizeAddToCartLines(lines) {
139
+ return lines.filter((line) => line.variant?.id).map((line, index) => {
140
+ const variant = line.variant;
141
+ const product = variant.product;
142
+ const quantity = line.quantity || 1;
143
+ const price = variant.finalPrice?.amount ? Number(variant.finalPrice.amount) : variant.compareAtPrice?.amount ? Number(variant.compareAtPrice.amount) : variant.price?.amount ? Number(variant.price.amount) : 0;
144
+ const subtotalAmount = price * quantity;
145
+ const totalAmount = subtotalAmount;
146
+ return {
147
+ id: `temp-line-${index}-${variant.id}`,
148
+ // Temporary ID for pre-cart lines
149
+ name: product?.title || variant.title || "",
150
+ quantity,
151
+ variantId: variant.id,
152
+ productId: product?.id || variant.id.split("/").slice(0, -2).join("/"),
153
+ totalAmount,
154
+ subtotalAmount,
155
+ discountAllocations: [],
156
+ customAttributes: line.attributes || [],
157
+ variant: {
158
+ id: variant.id,
159
+ price,
160
+ listPrice: variant.compareAtPrice?.amount ? Number(variant.compareAtPrice.amount) : 0,
161
+ sku: variant.sku || "",
162
+ name: variant.title || "",
163
+ image: variant.image ? {
164
+ url: variant.image.url,
165
+ altText: variant.image.altText || void 0
166
+ } : void 0,
167
+ requiresShipping: false,
168
+ // Default value, not available in NormalizedProductVariant
169
+ availableForSale: variant.availableForSale ?? true,
170
+ quantityAvailable: variant.quantityAvailable ?? 0,
171
+ currentlyNotInStock: false,
172
+ // Default value, will be updated when added to cart
173
+ weight: variant.weight,
174
+ metafields: variant.metafields
175
+ },
176
+ product,
177
+ path: product?.handle ? `/products/${product.handle}` : "",
178
+ discounts: [],
179
+ options: variant.selectedOptions?.map((opt) => ({
180
+ name: opt.name,
181
+ value: opt.value
182
+ }))
183
+ };
184
+ });
185
+ }
186
+ function createMockCartFromLines(lines, existingCart) {
187
+ const normalizedLines = normalizeAddToCartLines(lines);
188
+ const subtotalPrice = normalizedLines.reduce((sum, line) => sum + line.subtotalAmount, 0);
189
+ const totalPrice = normalizedLines.reduce((sum, line) => sum + line.totalAmount, 0);
190
+ return {
191
+ id: existingCart?.id || "temp-cart-id",
192
+ customerId: existingCart?.customerId,
193
+ email: existingCart?.email,
194
+ createdAt: existingCart?.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
195
+ currency: existingCart?.currency || { code: "USD" },
196
+ taxesIncluded: existingCart?.taxesIncluded,
197
+ lineItems: normalizedLines,
198
+ totalLineItemsDiscount: 0,
199
+ orderDiscounts: 0,
200
+ lineItemsSubtotalPrice: subtotalPrice,
201
+ subtotalPrice,
202
+ totalPrice,
203
+ totalTaxAmount: 0,
204
+ discountCodes: existingCart?.discountCodes || [],
205
+ discountAllocations: [],
206
+ url: existingCart?.url || "",
207
+ ready: true,
208
+ customAttributes: existingCart?.customAttributes
209
+ };
210
+ }
211
+
137
212
  // src/hooks/cart/utils/index.ts
138
213
  var getQuery = () => {
139
214
  const url = typeof window !== "undefined" ? window.location.search : "";
@@ -173,25 +248,25 @@ var getMatchedMainProductSubTotal = (cartData, variant_list, main_product) => {
173
248
  return acc + (main_product?.spend_money_type === 1 /* ORIGIN_PRICE */ ? Number(line.subtotalAmount) || 0 : Number(line.totalAmount) || 0);
174
249
  }, 0) || 0;
175
250
  };
176
- var getDiscountEnvAttributeValue = (attributes = []) => {
177
- const attr = attributes.find((attr2) => attr2.key === CUSTOMER_ATTRIBUTE_KEY);
178
- return safeParseJson(attr?.value ?? "") ?? {};
179
- };
180
- var isAttributesEqual = (attrs1 = [], attrs2 = []) => {
181
- if (attrs1.length !== attrs2.length) return false;
182
- const sorted1 = [...attrs1].sort((a, b) => a.key.localeCompare(b.key));
183
- const sorted2 = [...attrs2].sort((a, b) => a.key.localeCompare(b.key));
184
- return sorted1.every(
185
- (attr, i) => attr.key === sorted2[i]?.key && attr.value === sorted2[i]?.value
186
- );
187
- };
188
- var safeParseJson = (str) => {
251
+ var safeParse = (str) => {
189
252
  try {
190
253
  return JSON.parse(str);
191
254
  } catch (err) {
192
255
  return {};
193
256
  }
194
257
  };
258
+ var getDiscountEnvAttributeValue = (attributes = []) => {
259
+ const attr = attributes.find((attr2) => attr2.key === CUSTOMER_ATTRIBUTE_KEY);
260
+ return safeParse(attr?.value ?? "") ?? {};
261
+ };
262
+ var checkAttributesUpdateNeeded = (oldAttributes, newAttributes, customAttributesNeedRemove) => {
263
+ return oldAttributes.some((attr) => {
264
+ const newAttr = newAttributes.find((newAttr2) => newAttr2.key === attr.key);
265
+ return newAttr ? newAttr.value !== attr.value : true;
266
+ }) || newAttributes.some((attr) => !oldAttributes.some((oldAttr) => oldAttr.key === attr.key)) || customAttributesNeedRemove.some(
267
+ (removeAttr) => oldAttributes.some((oldAttr) => oldAttr.key === removeAttr.key)
268
+ );
269
+ };
195
270
  var containsAll = (source, requiredItems = []) => {
196
271
  if (!requiredItems?.length) return true;
197
272
  const sourceSet = new Set(source);
@@ -358,12 +433,18 @@ var formatFunctionAutoFreeGift = ({
358
433
  };
359
434
  return result;
360
435
  };
361
- var useCalcAutoFreeGift = (cart, autoFreeGiftConfig, customer) => {
436
+ var useCalcAutoFreeGift = (cart, autoFreeGiftConfig, customer, lines) => {
362
437
  const tags = useMemo(() => customer?.tags || [], [customer?.tags]);
363
438
  const isCustomerLoading = useMemo(() => !customer ? true : false, [customer]);
364
439
  const dealsType = "";
365
440
  const { client, locale } = useShopify();
366
441
  const giftProductsCache = useRef(null);
442
+ const effectiveCart = useMemo(() => {
443
+ if (lines && lines.length > 0) {
444
+ return createMockCartFromLines(lines, cart);
445
+ }
446
+ return cart;
447
+ }, [lines, cart]);
367
448
  const { activeCampaign, subtotal } = useMemo(() => {
368
449
  for (const campaign of autoFreeGiftConfig) {
369
450
  const { rule_conditions = [], rule_result } = campaign;
@@ -371,7 +452,7 @@ var useCalcAutoFreeGift = (cart, autoFreeGiftConfig, customer) => {
371
452
  const isPreCheckPassed = preCheck(rule_conditions, tags, []);
372
453
  if (isPreCheckPassed && spend_get_reward) {
373
454
  const matchedSubtotal = getMatchedMainProductSubTotal(
374
- cart,
455
+ effectiveCart,
375
456
  spend_get_reward.main_product?.variant_list?.map((v) => v.variant_id) || [],
376
457
  {
377
458
  spend_money_type: spend_get_reward.main_product?.spend_money_type || 1,
@@ -385,13 +466,13 @@ var useCalcAutoFreeGift = (cart, autoFreeGiftConfig, customer) => {
385
466
  }
386
467
  }
387
468
  return { activeCampaign: null, subtotal: 0 };
388
- }, [autoFreeGiftConfig, cart, tags, dealsType]);
469
+ }, [autoFreeGiftConfig, effectiveCart, tags, dealsType]);
389
470
  const { qualifyingGift, nextTierGoal } = useMemo(() => {
390
471
  if (!activeCampaign || !activeCampaign.rule_result?.spend_get_reward?.gift_product) {
391
472
  return { qualifyingGift: null, nextTierGoal: null };
392
473
  }
393
474
  const giftTiers = activeCampaign.rule_result.spend_get_reward.gift_product;
394
- const qualifyingTier = [...giftTiers].reverse().find((tier) => subtotal >= Number(tier.spend_sum_money));
475
+ const qualifyingTier = [...giftTiers].sort((a, b) => Number(b.spend_sum_money) - Number(a.spend_sum_money)).find((tier) => subtotal >= Number(tier.spend_sum_money));
395
476
  const nextGoal = giftTiers.find((tier) => subtotal < Number(tier.spend_sum_money));
396
477
  if (!qualifyingTier) {
397
478
  return { qualifyingGift: null, nextTierGoal: nextGoal || null };
@@ -468,18 +549,33 @@ var useScriptAutoFreeGift = ({
468
549
  campaign,
469
550
  _giveaway,
470
551
  cart,
471
- locale: providedLocale
552
+ locale: providedLocale,
553
+ lines
472
554
  }) => {
473
555
  const { client, locale: contextLocale } = useShopify();
474
556
  const locale = providedLocale || contextLocale;
475
557
  const [points_subscribe, set_points_subscribe] = useState(false);
476
558
  const giftProductsCache = useRef(null);
559
+ const effectiveCart = useMemo(() => {
560
+ if (lines && lines.length > 0) {
561
+ return createMockCartFromLines(lines, cart);
562
+ }
563
+ return cart;
564
+ }, [lines, cart]);
477
565
  useEffect(() => {
478
566
  if (locale === "au") {
479
567
  const isPointsSubscribe = Cookies5.get("points_subscribe");
480
568
  set_points_subscribe(!!isPointsSubscribe);
481
569
  }
482
570
  }, [locale]);
571
+ const isActivityAvailable = useMemo(() => {
572
+ if (!campaign) return false;
573
+ const query = getQuery();
574
+ const utmCampaign = Cookies5.get("utm_campaign") || query?.utm_campaign;
575
+ if (campaign.activityAvailableQuery && !utmCampaign?.includes(campaign.activityAvailableQuery))
576
+ return false;
577
+ return true;
578
+ }, [campaign]);
483
579
  const [upgrade_multiple, upgrade_value] = useMemo(() => {
484
580
  let upgrade_multiple2 = 1;
485
581
  let upgrade_value2 = 0;
@@ -487,17 +583,17 @@ var useScriptAutoFreeGift = ({
487
583
  upgrade_multiple2 = 1.2;
488
584
  upgrade_value2 = 40;
489
585
  }
490
- cart?.lineItems?.forEach(({ customAttributes }) => {
586
+ effectiveCart?.lineItems?.forEach(({ customAttributes }) => {
491
587
  customAttributes?.forEach(({ key, value }) => {
492
588
  if (key === "_amount_upgrade_multiple") upgrade_multiple2 = Number(value) || 1;
493
589
  if (key === "_amount_upgrade_value") upgrade_value2 = Number(value) || 0;
494
590
  });
495
591
  });
496
592
  return [upgrade_multiple2, upgrade_value2];
497
- }, [cart?.lineItems, points_subscribe]);
593
+ }, [effectiveCart?.lineItems, points_subscribe]);
498
594
  const breakpoints = useMemo(() => {
499
- if (!campaign) return [];
500
- return (campaign.breakpoints || []).map((item) => ({
595
+ if (!isActivityAvailable) return [];
596
+ return (campaign?.breakpoints || []).map((item) => ({
501
597
  breakpoint: new Decimal2(item.breakpoint).minus(new Decimal2(upgrade_value)).dividedBy(new Decimal2(upgrade_multiple)).toFixed(2, Decimal2.ROUND_DOWN),
502
598
  giveawayProducts: item.giveawayProducts || []
503
599
  }));
@@ -521,25 +617,26 @@ var useScriptAutoFreeGift = ({
521
617
  return true;
522
618
  }, [giftHandles]);
523
619
  const involvedLines = useMemo(() => {
524
- if (!campaign) return [];
525
- return (cart?.lineItems || []).filter((line) => {
620
+ if (!isActivityAvailable) return [];
621
+ return (effectiveCart?.lineItems || []).filter((line) => {
526
622
  const isNotGift = line?.totalAmount && Number(line.totalAmount) > 0 && line.customAttributes?.every(
527
623
  (item) => item.key !== _giveaway
528
624
  );
529
625
  const hasCampaignTag = line.product?.tags?.some(
530
- (tag) => campaign.includeTags?.includes(tag.trim()) && line.variant?.availableForSale
626
+ (tag) => campaign?.includeTags?.includes(tag.trim()) && line.variant?.availableForSale
531
627
  );
532
628
  return isNotGift && hasCampaignTag;
533
629
  });
534
- }, [cart?.lineItems, campaign, _giveaway]);
630
+ }, [effectiveCart?.lineItems, isActivityAvailable, _giveaway]);
535
631
  const involvedSubTotal = useMemo(() => {
536
- if (!campaign) return new Decimal2(0);
632
+ if (!isActivityAvailable) return new Decimal2(0);
537
633
  return involvedLines.reduce((prev, item) => {
538
- const amount = campaign.useTotalAmount ? item.totalAmount : item.subtotalAmount;
634
+ const amount = campaign?.useTotalAmount ? item.totalAmount : item.subtotalAmount;
539
635
  return new Decimal2(prev).plus(new Decimal2(amount || 0));
540
636
  }, new Decimal2(0));
541
- }, [involvedLines, campaign]);
637
+ }, [involvedLines, isActivityAvailable]);
542
638
  const [freeGiftLevel, nextFreeGiftLevel] = useMemo(() => {
639
+ if (!isActivityAvailable) return [null, null];
543
640
  const sortedLevels = [...breakpoints].sort(
544
641
  (a, b) => Number(b.breakpoint) - Number(a.breakpoint)
545
642
  );
@@ -683,8 +780,12 @@ var trackAddToCartGA = ({
683
780
  }
684
781
  const { variant } = lineItems[0];
685
782
  const currencyCode = variant.product?.price?.currencyCode;
686
- const price = variant.compareAtPrice?.amount ?? (variant.price?.amount || 0);
687
- const totalPrice = lineItems?.reduce((prev, { variant: variant2 }) => prev.plus(variant2?.finalPrice?.amount ?? price), new Decimal2(0)).toNumber();
783
+ const totalPrice = lineItems?.reduce(
784
+ (prev, { variant: variant2 }) => prev.plus(
785
+ variant2?.finalPrice?.amount ?? variant2?.compareAtPrice?.amount ?? variant2?.price?.amount ?? 0
786
+ ),
787
+ new Decimal2(0)
788
+ ).toNumber();
688
789
  gaTrack({
689
790
  event: "ga4Event",
690
791
  event_name: "add_to_cart",
@@ -699,7 +800,7 @@ var trackAddToCartGA = ({
699
800
  item_brand: gtmParams?.brand || "",
700
801
  item_category: variant2?.product?.productType || "",
701
802
  item_variant: variant2?.title || variant2?.title,
702
- price,
803
+ price: variant2?.compareAtPrice?.amount ?? variant2?.price?.amount,
703
804
  quantity: quantity || 1
704
805
  })),
705
806
  ...gtmParams?.ga4Params
@@ -714,9 +815,12 @@ var trackBeginCheckoutGA = ({
714
815
  if (!lineItems.length) {
715
816
  return;
716
817
  }
717
- const { variant } = lineItems[0] || {};
718
- const price = variant?.compareAtPrice?.amount ?? (variant?.price?.amount || 0);
719
- const totalPrice = lineItems?.reduce((prev, { variant: variant2 }) => prev.plus(variant2?.finalPrice?.amount ?? price), new Decimal2(0)).toNumber();
818
+ const totalPrice = lineItems?.reduce(
819
+ (prev, { variant }) => prev.plus(
820
+ variant?.finalPrice?.amount ?? variant?.compareAtPrice?.amount ?? variant?.price?.amount ?? 0
821
+ ),
822
+ new Decimal2(0)
823
+ ).toNumber();
720
824
  gaTrack({
721
825
  event: "ga4Event",
722
826
  event_name: "begin_checkout",
@@ -731,7 +835,7 @@ var trackBeginCheckoutGA = ({
731
835
  item_brand: gtmParams?.brand || "",
732
836
  item_category: item.variant?.product?.productType,
733
837
  item_variant: item.variant?.title,
734
- price,
838
+ price: item.variant?.compareAtPrice?.amount ?? item.variant?.price?.amount,
735
839
  quantity: item.quantity || 1
736
840
  })),
737
841
  ...gtmParams?.ga4Params
@@ -747,8 +851,12 @@ var trackBuyNowGA = ({
747
851
  }
748
852
  const { variant } = lineItems[0];
749
853
  const currencyCode = variant.price?.currencyCode;
750
- const price = variant.compareAtPrice?.amount ?? (variant.price?.amount || 0);
751
- const totalPrice = lineItems?.reduce((prev, { variant: variant2 }) => prev.plus(variant2?.finalPrice?.amount ?? price), new Decimal2(0)).toNumber();
854
+ const totalPrice = lineItems?.reduce(
855
+ (prev, { variant: variant2 }) => prev.plus(
856
+ variant2?.finalPrice?.amount ?? variant2?.compareAtPrice?.amount ?? (variant2?.price?.amount || 0)
857
+ ),
858
+ new Decimal2(0)
859
+ ).toNumber();
752
860
  gaTrack({
753
861
  event: "ga4Event",
754
862
  event_name: "begin_checkout",
@@ -763,7 +871,7 @@ var trackBuyNowGA = ({
763
871
  item_brand: gtmParams?.brand || "",
764
872
  item_category: item.variant?.product?.productType || "",
765
873
  item_variant: item.variant?.title,
766
- price,
874
+ price: item.variant?.compareAtPrice?.amount ?? item.variant?.price?.amount,
767
875
  quantity: item.quantity || 1
768
876
  })),
769
877
  ...gtmParams?.ga4Params
@@ -906,6 +1014,7 @@ function useAddToCart({ withTrack = true } = {}, swrOptions) {
906
1014
  if (!resultCart) {
907
1015
  return void 0;
908
1016
  }
1017
+ console.log("npm addCartLines resultCart", resultCart);
909
1018
  if (resultCart.discountCodes && resultCart.discountCodes.length > 0) {
910
1019
  const unapplicableCodes = resultCart.discountCodes.filter((item) => !item.applicable).map((item) => item.code);
911
1020
  if (unapplicableCodes.length > 0) {
@@ -1079,6 +1188,60 @@ function useBuyNow({ withTrack = true } = {}, swrOptions) {
1079
1188
  );
1080
1189
  return useSWRMutation("buy-now", buyNow, swrOptions);
1081
1190
  }
1191
+ function useCalcGiftsFromLines({
1192
+ lines,
1193
+ customer,
1194
+ scriptGiveawayKey = CUSTOMER_SCRIPT_GIFT_KEY
1195
+ }) {
1196
+ const { locale } = useShopify();
1197
+ const { cart, autoFreeGiftConfig, gradientGiftsConfig } = useCartContext();
1198
+ const functionGift = useCalcAutoFreeGift(cart, autoFreeGiftConfig || [], customer, lines);
1199
+ const scriptGift = useScriptAutoFreeGift({
1200
+ campaign: gradientGiftsConfig || null,
1201
+ _giveaway: scriptGiveawayKey,
1202
+ cart,
1203
+ locale,
1204
+ lines
1205
+ });
1206
+ const allGiftLines = useMemo(() => {
1207
+ const functionGiftLines = functionGift.qualifyingGift?.itemsToAdd || [];
1208
+ const scriptGiftLines = scriptGift.freeGiftLevel ? scriptGift.freeGiftLevel.giveawayProducts.map((product) => {
1209
+ const giftProduct = scriptGift.giftProductsResult?.find(
1210
+ (p) => p.handle === product.handle
1211
+ );
1212
+ const variant = giftProduct?.variants?.[0];
1213
+ return {
1214
+ variant: {
1215
+ id: variant?.id || "",
1216
+ handle: product.handle,
1217
+ sku: product.sku
1218
+ },
1219
+ quantity: 1,
1220
+ attributes: [
1221
+ {
1222
+ key: scriptGiveawayKey,
1223
+ value: "true"
1224
+ }
1225
+ ]
1226
+ };
1227
+ }).filter((item) => item.variant.id) : [];
1228
+ return [...functionGiftLines, ...scriptGiftLines];
1229
+ }, [
1230
+ functionGift.qualifyingGift,
1231
+ scriptGift.freeGiftLevel,
1232
+ scriptGift.giftProductsResult,
1233
+ scriptGiveawayKey
1234
+ ]);
1235
+ const hasGifts = useMemo(() => {
1236
+ return allGiftLines.length > 0;
1237
+ }, [allGiftLines]);
1238
+ return {
1239
+ functionGift,
1240
+ scriptGift,
1241
+ allGiftLines,
1242
+ hasGifts
1243
+ };
1244
+ }
1082
1245
 
1083
1246
  // src/hooks/cart/types/order-discount.ts
1084
1247
  var OrderDiscountType = /* @__PURE__ */ ((OrderDiscountType2) => {
@@ -1228,8 +1391,6 @@ var useCartAttributes = ({
1228
1391
  memberSetting,
1229
1392
  cart
1230
1393
  });
1231
- console.log("memberSetting", memberSetting);
1232
- console.log("hasPlusMember", hasPlusMember);
1233
1394
  useEffect(() => {
1234
1395
  setCurrentUrl(window.location.href);
1235
1396
  }, []);
@@ -1255,7 +1416,7 @@ var useCartAttributes = ({
1255
1416
  return "new_user_login";
1256
1417
  }, [customer]);
1257
1418
  const memberAttributes = useMemo(() => {
1258
- return [
1419
+ const attributes = [
1259
1420
  {
1260
1421
  key: "_token",
1261
1422
  value: profile?.token
@@ -1274,19 +1435,34 @@ var useCartAttributes = ({
1274
1435
  {
1275
1436
  key: "_is_login",
1276
1437
  value: profile?.token ? "true" : "false"
1438
+ },
1439
+ {
1440
+ key: "_last_url",
1441
+ value: typeof window !== "undefined" ? window.location.origin + window.location.pathname : ""
1277
1442
  }
1278
1443
  ];
1444
+ if (profile?.token) {
1445
+ attributes.push({
1446
+ key: "_login_user",
1447
+ value: "1"
1448
+ });
1449
+ }
1450
+ return attributes;
1279
1451
  }, [profile?.memberType, profile?.token, userType, hasPlusMember]);
1280
1452
  const functionAttributes = useMemo(() => {
1281
- return [
1282
- cart?.discountCodes && {
1453
+ const hasFunctionEnvAttribute = cart?.lineItems.some(
1454
+ (item) => item.customAttributes?.some((attr) => attr.key === CUSTOMER_ATTRIBUTE_KEY)
1455
+ );
1456
+ const discountCodes = cart?.discountCodes.map((item) => item.code).filter((code) => code) || [];
1457
+ return hasFunctionEnvAttribute ? [
1458
+ {
1283
1459
  key: "_discounts_function_env",
1284
1460
  value: JSON.stringify({
1285
- discount_code: cart?.discountCodes.map((item) => item.code),
1461
+ discount_code: discountCodes,
1286
1462
  user_tags: customer?.tags || []
1287
1463
  })
1288
1464
  }
1289
- ];
1465
+ ] : [];
1290
1466
  }, [cart]);
1291
1467
  const presellAttributes = useMemo(() => {
1292
1468
  return [
@@ -2463,6 +2639,69 @@ var usePlusMemberDeliveryCodes = ({
2463
2639
  [deliveryData]
2464
2640
  );
2465
2641
  };
2642
+ function useUpdateCartDeliveryOptions(mutate, metafieldIdentifiers, options) {
2643
+ const { client, locale, cartCookieAdapter } = useShopify();
2644
+ const updateDeliveryOptions = useCallback(
2645
+ async (_key, { arg }) => {
2646
+ const updatedCart = await updateCartDeliveryOptions(client, {
2647
+ ...arg,
2648
+ metafieldIdentifiers,
2649
+ cookieAdapter: cartCookieAdapter
2650
+ });
2651
+ console.log("useUpdateCartDeliveryOptions updatedCart", updatedCart);
2652
+ if (updatedCart) {
2653
+ mutate(updatedCart);
2654
+ }
2655
+ return updatedCart;
2656
+ },
2657
+ [client, locale, cartCookieAdapter, mutate]
2658
+ );
2659
+ return useSWRMutation("update-cart-delivery-options", updateDeliveryOptions, options);
2660
+ }
2661
+
2662
+ // src/hooks/member/plus/use-update-plus-member-delivery-options.ts
2663
+ var useUpdatePlusMemberDeliveryOptions = ({
2664
+ options
2665
+ }) => {
2666
+ const { cart, mutateCart: mutate, metafieldIdentifiers } = useCartContext();
2667
+ const { trigger: updateCartDeliveryOptions2, isMutating } = useUpdateCartDeliveryOptions(
2668
+ mutate,
2669
+ metafieldIdentifiers
2670
+ );
2671
+ const handler = useCallback(
2672
+ async (_, { arg }) => {
2673
+ const { deliveryData } = arg;
2674
+ const firstDeliveryGroup = cart?.deliveryGroups?.[0];
2675
+ const deliveryGroupId = firstDeliveryGroup?.id;
2676
+ const selectedOptionCode = deliveryData?.deliveryCustomData?.selected_delivery_option?.code;
2677
+ if (!deliveryGroupId || !selectedOptionCode || selectedOptionCode === firstDeliveryGroup?.selectedDeliveryOption?.code) {
2678
+ return null;
2679
+ }
2680
+ const deliveryGroup = cart?.deliveryGroups?.find((group) => group?.id === deliveryGroupId);
2681
+ const matchedOption = deliveryGroup?.deliveryOptions?.find(
2682
+ (option) => option?.code === selectedOptionCode
2683
+ );
2684
+ if (!matchedOption?.handle) {
2685
+ return null;
2686
+ }
2687
+ const deliveryOptions = [
2688
+ {
2689
+ deliveryGroupId,
2690
+ deliveryOptionHandle: matchedOption.handle
2691
+ }
2692
+ ];
2693
+ const updatedCart = await updateCartDeliveryOptions2({
2694
+ selectedDeliveryOptions: deliveryOptions
2695
+ });
2696
+ if (updatedCart && mutate) {
2697
+ mutate(updatedCart);
2698
+ }
2699
+ return updatedCart;
2700
+ },
2701
+ [cart, updateCartDeliveryOptions2, mutate]
2702
+ );
2703
+ return useSWRMutation("update-cart-delivery-options", handler, options);
2704
+ };
2466
2705
  var usePlusMemberItemCustomAttributes = ({
2467
2706
  deliveryData
2468
2707
  }) => {
@@ -2482,48 +2721,12 @@ var usePlusMemberCheckoutCustomAttributes = ({
2482
2721
  deliveryData,
2483
2722
  product,
2484
2723
  variant,
2485
- customer,
2486
2724
  isShowShippingBenefits
2487
2725
  }) => {
2488
2726
  const { deliveryCustomData } = deliveryData || {};
2489
2727
  const { profile } = usePlusMemberContext();
2490
- const userType = useMemo(() => {
2491
- const customerInfo = customer;
2492
- if (!customerInfo) {
2493
- return "new_user_unlogin";
2494
- }
2495
- if (customer) {
2496
- const { orders = {} } = customer;
2497
- const edgesLength = orders?.edges?.length;
2498
- if (edgesLength === 1) {
2499
- return "old_user_orders_once";
2500
- } else if (edgesLength && edgesLength > 1) {
2501
- return "old_user_orders_twice";
2502
- }
2503
- }
2504
- return "new_user_login";
2505
- }, [customer]);
2506
2728
  return useMemo(() => {
2507
- const checkoutCustomAttributes = [
2508
- {
2509
- key: "_token",
2510
- value: profile?.token || ""
2511
- },
2512
- {
2513
- key: "_last_url",
2514
- value: typeof window !== "undefined" ? window.location.origin + window.location.pathname : ""
2515
- },
2516
- {
2517
- key: "_user_type",
2518
- value: userType
2519
- }
2520
- ];
2521
- if (profile) {
2522
- checkoutCustomAttributes.push({
2523
- key: "_login_user",
2524
- value: "1"
2525
- });
2526
- }
2729
+ const checkoutCustomAttributes = [];
2527
2730
  if (deliveryCustomData) {
2528
2731
  checkoutCustomAttributes.push({
2529
2732
  key: "_checkout_delivery_custom",
@@ -2533,12 +2736,6 @@ var usePlusMemberCheckoutCustomAttributes = ({
2533
2736
  })
2534
2737
  });
2535
2738
  }
2536
- if (variant?.metafields?.presell) {
2537
- checkoutCustomAttributes.push({
2538
- key: "_presale",
2539
- value: "true"
2540
- });
2541
- }
2542
2739
  if (isShowShippingBenefits && !isShowShippingBenefits({ variant, product, setting: {} })) {
2543
2740
  checkoutCustomAttributes.push({
2544
2741
  key: "_hide_shipping",
@@ -2546,18 +2743,17 @@ var usePlusMemberCheckoutCustomAttributes = ({
2546
2743
  });
2547
2744
  }
2548
2745
  return checkoutCustomAttributes;
2549
- }, [deliveryCustomData, product, profile, userType, variant, isShowShippingBenefits]);
2746
+ }, [deliveryCustomData, product, profile, variant, isShowShippingBenefits]);
2550
2747
  };
2551
2748
  function useAutoRemovePlusMemberInCart({
2552
- metafields,
2553
- isMonthlyPlus,
2554
- isAnnualPlus
2749
+ cart,
2750
+ profile,
2751
+ memberSetting
2555
2752
  }) {
2556
- const { plus_monthly_product, plus_annual_product } = metafields || {};
2557
- const { cart } = useCartContext();
2753
+ const { plus_monthly_product, plus_annual_product } = memberSetting || {};
2558
2754
  const { trigger: removeCartLines2 } = useRemoveCartLines();
2559
2755
  useEffect(() => {
2560
- if (!cart) return;
2756
+ if (!cart || !plus_monthly_product || !plus_annual_product) return;
2561
2757
  const removePlusProduct = async (productType) => {
2562
2758
  if (!productType) return;
2563
2759
  const product = cart.lineItems?.find(
@@ -2569,26 +2765,53 @@ function useAutoRemovePlusMemberInCart({
2569
2765
  });
2570
2766
  }
2571
2767
  };
2572
- if (isMonthlyPlus) {
2768
+ if (profile?.isMonthlyPlus) {
2573
2769
  removePlusProduct(plus_monthly_product);
2574
2770
  }
2575
- if (isAnnualPlus) {
2771
+ if (profile?.isAnnualPlus) {
2576
2772
  removePlusProduct(plus_annual_product);
2577
2773
  }
2774
+ }, [cart, plus_annual_product, plus_monthly_product, profile, removeCartLines2]);
2775
+ }
2776
+ function useAddPlusMemberProductsToCart({
2777
+ cart,
2778
+ profile
2779
+ }) {
2780
+ const { selectedPlusMemberMode, selectedPlusMemberProduct, plusMemberMetafields } = usePlusMemberContext();
2781
+ const { hasMonthlyPlus, hasAnnualPlus } = useHasPlusMemberInCart({
2782
+ memberSetting: plusMemberMetafields,
2783
+ cart
2784
+ });
2785
+ const plusMemberProduct = useMemo(() => {
2786
+ if (!selectedPlusMemberProduct || selectedPlusMemberMode === "free" /* FREE */) {
2787
+ return void 0;
2788
+ }
2789
+ if (selectedPlusMemberMode === "monthly" /* MONTHLY */ && hasMonthlyPlus) {
2790
+ return void 0;
2791
+ }
2792
+ if (selectedPlusMemberMode === "annual" /* ANNUAL */ && hasAnnualPlus) {
2793
+ return void 0;
2794
+ }
2795
+ if (profile?.isMonthlyPlus && selectedPlusMemberMode === "monthly" /* MONTHLY */) {
2796
+ return void 0;
2797
+ }
2798
+ if (!profile?.isAnnualPlus && selectedPlusMemberMode === "annual" /* ANNUAL */) {
2799
+ return void 0;
2800
+ }
2801
+ return selectedPlusMemberProduct;
2578
2802
  }, [
2579
- cart,
2580
- plus_annual_product,
2581
- plus_monthly_product,
2582
- isAnnualPlus,
2583
- isMonthlyPlus,
2584
- removeCartLines2
2803
+ selectedPlusMemberMode,
2804
+ selectedPlusMemberProduct?.variant,
2805
+ selectedPlusMemberProduct?.product,
2806
+ hasMonthlyPlus,
2807
+ hasAnnualPlus
2585
2808
  ]);
2809
+ return plusMemberProduct;
2586
2810
  }
2587
2811
  var PlusMemberProvider = ({
2588
2812
  variant,
2589
2813
  product,
2590
- shopCommon,
2591
- metafields,
2814
+ memberSetting,
2592
2815
  initialSelectedPlusMemberMode = "free",
2593
2816
  profile,
2594
2817
  locale,
@@ -2608,14 +2831,14 @@ var PlusMemberProvider = ({
2608
2831
  const [deleteMarginBottom, setDeleteMarginBottom] = useState(false);
2609
2832
  const shippingMethodsContext = useShippingMethods({
2610
2833
  variant,
2611
- plusMemberMetafields: metafields,
2834
+ plusMemberMetafields: memberSetting,
2612
2835
  selectedPlusMemberMode});
2613
2836
  const plusMemberHandles = useMemo(() => {
2614
2837
  return [
2615
- metafields?.plus_monthly_product?.handle,
2616
- metafields?.plus_annual_product?.handle
2838
+ memberSetting?.plus_monthly_product?.handle,
2839
+ memberSetting?.plus_annual_product?.handle
2617
2840
  ].filter(Boolean);
2618
- }, [metafields]);
2841
+ }, [memberSetting]);
2619
2842
  const { data: plusMemberProducts = [] } = useProductsByHandles({
2620
2843
  handles: plusMemberHandles
2621
2844
  });
@@ -2623,25 +2846,24 @@ var PlusMemberProvider = ({
2623
2846
  if (selectedPlusMemberMode === "free" /* FREE */) {
2624
2847
  return null;
2625
2848
  }
2626
- const handle = selectedPlusMemberMode === "monthly" /* MONTHLY */ ? metafields?.plus_monthly_product?.handle : metafields?.plus_annual_product?.handle;
2627
- const sku = selectedPlusMemberMode === "monthly" /* MONTHLY */ ? metafields?.plus_monthly_product?.sku : metafields?.plus_annual_product?.sku;
2849
+ const handle = selectedPlusMemberMode === "monthly" /* MONTHLY */ ? memberSetting?.plus_monthly_product?.handle : memberSetting?.plus_annual_product?.handle;
2850
+ const sku = selectedPlusMemberMode === "monthly" /* MONTHLY */ ? memberSetting?.plus_monthly_product?.sku : memberSetting?.plus_annual_product?.sku;
2628
2851
  const product2 = plusMemberProducts?.find((p) => p.handle === handle);
2629
2852
  const variant2 = product2?.variants?.find((v) => v.sku === sku);
2630
2853
  return product2 && variant2 ? { product: product2, variant: variant2 } : null;
2631
- }, [plusMemberProducts, metafields, selectedPlusMemberMode]);
2854
+ }, [plusMemberProducts, memberSetting, selectedPlusMemberMode]);
2632
2855
  return /* @__PURE__ */ jsx(
2633
2856
  PlusMemberContext.Provider,
2634
2857
  {
2635
2858
  value: {
2636
2859
  variant,
2637
- shopCommon,
2638
2860
  zipCode,
2639
2861
  setZipCode,
2640
2862
  allowNextDayDelivery,
2641
2863
  setAllowNextDayDelivery,
2642
2864
  allowThirdDayDelivery,
2643
2865
  setAllowThirdDayDelivery,
2644
- plusMemberMetafields: metafields,
2866
+ plusMemberMetafields: memberSetting,
2645
2867
  selectedPlusMemberMode,
2646
2868
  setSelectedPlusMemberMode,
2647
2869
  showAreaCheckModal,
@@ -2860,6 +3082,9 @@ function CartProvider({
2860
3082
  }) {
2861
3083
  const { client, cartCookieAdapter } = useShopify();
2862
3084
  const [customAttributes, setCustomAttributes] = useState([]);
3085
+ const [customAttributesNeedDelete, setCustomAttributesNeedDelete] = useState(
3086
+ []
3087
+ );
2863
3088
  const [isCodeChanging, setIsCodeChanging] = useState(false);
2864
3089
  const [loadingState, setLoadingState] = useState({
2865
3090
  editLineQuantityLoading: false,
@@ -2890,7 +3115,11 @@ function CartProvider({
2890
3115
  useRequest(
2891
3116
  () => {
2892
3117
  const newAttributes = [...attributes, ...customAttributes];
2893
- const needUpdate = cart && !isAttributesEqual(cart.customAttributes, newAttributes);
3118
+ const needUpdate = cart && !checkAttributesUpdateNeeded(
3119
+ cart.customAttributes,
3120
+ newAttributes,
3121
+ customAttributesNeedDelete
3122
+ );
2894
3123
  if (needUpdate) {
2895
3124
  return updateAttributes({ attributes: newAttributes });
2896
3125
  } else {
@@ -2911,11 +3140,12 @@ function CartProvider({
2911
3140
  isCartLoading: isCartLoading || isCodeChanging,
2912
3141
  setLoadingState
2913
3142
  });
2914
- const removeCustomAttributes = useCallback((attributes2) => {
2915
- setCustomAttributes(
2916
- (prev) => prev.filter((attr) => !attributes2.some((a) => a.key === attr.key))
2917
- );
2918
- }, []);
3143
+ const removeCustomAttributes = useCallback(
3144
+ (attributes2) => {
3145
+ setCustomAttributesNeedDelete(attributes2);
3146
+ },
3147
+ [setCustomAttributesNeedDelete]
3148
+ );
2919
3149
  const addCustomAttributes = useCallback(
2920
3150
  (attributes2) => {
2921
3151
  const sameAttributes = attributes2.filter(
@@ -3002,6 +3232,7 @@ function CartProvider({
3002
3232
  isCodeChanging,
3003
3233
  setIsCodeChanging,
3004
3234
  autoFreeGiftConfig,
3235
+ gradientGiftsConfig,
3005
3236
  setLoadingState,
3006
3237
  loadingState,
3007
3238
  // function满赠
@@ -3025,6 +3256,7 @@ function CartProvider({
3025
3256
  locale,
3026
3257
  isCodeChanging,
3027
3258
  autoFreeGiftConfig,
3259
+ gradientGiftsConfig,
3028
3260
  loadingState,
3029
3261
  // function满赠
3030
3262
  functionAutoFreeGift,
@@ -3048,6 +3280,6 @@ function useCartContext() {
3048
3280
  return context;
3049
3281
  }
3050
3282
 
3051
- export { BuyRuleType, CODE_AMOUNT_KEY, CUSTOMER_ATTRIBUTE_KEY, CUSTOMER_SCRIPT_GIFT_KEY, CartProvider, DeliveryPlusType, MAIN_PRODUCT_CODE, OrderBasePriceType, OrderDiscountType, PLUS_MEMBER_TYPE, PlusMemberContext, PlusMemberMode, PlusMemberProvider, PriceBasePriceType, PriceDiscountType, RuleType, SCRIPT_CODE_AMOUNT_KEY, ShippingMethodMode, ShopifyContext, ShopifyProvider, SpendMoneyType, atobID, browserCartCookieAdapter, browserCookieAdapter, btoaID, clearGeoLocationCache, currencyCodeMapping, defaultSWRMutationConfiguration, formatFunctionAutoFreeGift, formatScriptAutoFreeGift, gaTrack, getCachedGeoLocation, getDiscountEnvAttributeValue, getMatchedMainProductSubTotal, getQuery, getReferralAttributes, isAttributesEqual, preCheck, safeParseJson, trackAddToCartFBQ, trackAddToCartGA, trackBeginCheckoutGA, trackBuyNowFBQ, trackBuyNowGA, useAddCartLines, useAddToCart, useAllBlogs, useAllCollections, useAllProducts, useApplyCartCodes, useArticle, useArticles, useArticlesInBlog, useAutoRemovePlusMemberInCart, useBlog, useBuyNow, useCalcAutoFreeGift, useCalcOrderDiscount, useCartAttributes, useCartContext, 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, useShopify, useSite, useUpdateCartAttributes, useUpdateCartLines, useUpdateLineCodeAmountAttributes, useUpdateVariantQuery, useVariant, useVariantMedia };
3283
+ export { BuyRuleType, CODE_AMOUNT_KEY, CUSTOMER_ATTRIBUTE_KEY, CUSTOMER_SCRIPT_GIFT_KEY, CartProvider, DeliveryPlusType, MAIN_PRODUCT_CODE, OrderBasePriceType, OrderDiscountType, PLUS_MEMBER_TYPE, PlusMemberContext, PlusMemberMode, PlusMemberProvider, PriceBasePriceType, PriceDiscountType, RuleType, SCRIPT_CODE_AMOUNT_KEY, ShippingMethodMode, ShopifyContext, ShopifyProvider, SpendMoneyType, atobID, browserCartCookieAdapter, browserCookieAdapter, btoaID, checkAttributesUpdateNeeded, clearGeoLocationCache, createMockCartFromLines, currencyCodeMapping, defaultSWRMutationConfiguration, formatFunctionAutoFreeGift, formatScriptAutoFreeGift, gaTrack, getCachedGeoLocation, getDiscountEnvAttributeValue, getMatchedMainProductSubTotal, getQuery, getReferralAttributes, normalizeAddToCartLines, preCheck, safeParse, trackAddToCartFBQ, trackAddToCartGA, trackBeginCheckoutGA, trackBuyNowFBQ, trackBuyNowGA, useAddCartLines, useAddPlusMemberProductsToCart, useAddToCart, useAllBlogs, useAllCollections, useAllProducts, useApplyCartCodes, useArticle, useArticles, useArticlesInBlog, useAutoRemovePlusMemberInCart, useBlog, useBuyNow, useCalcAutoFreeGift, useCalcGiftsFromLines, useCalcOrderDiscount, useCartAttributes, useCartContext, 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, useShopify, useSite, useUpdateCartAttributes, useUpdateCartLines, useUpdateLineCodeAmountAttributes, useUpdatePlusMemberDeliveryOptions, useUpdateVariantQuery, useVariant, useVariantMedia };
3052
3284
  //# sourceMappingURL=index.mjs.map
3053
3285
  //# sourceMappingURL=index.mjs.map