@storepecker/storefront-core 2.7.0 → 2.9.1

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.
Files changed (63) hide show
  1. package/dist/api/index.cjs +94 -46
  2. package/dist/api/index.d.cts +108 -11
  3. package/dist/api/index.d.ts +108 -11
  4. package/dist/api/index.js +3 -3
  5. package/dist/buy-now-BqVWXyy8.d.cts +197 -0
  6. package/dist/buy-now-DFdnuLjO.d.ts +197 -0
  7. package/dist/{cart-BGIsIZdM.d.ts → cart-DZq1ZEnE.d.ts} +1 -1
  8. package/dist/{cart-CyN2JQTw.d.cts → cart-DwMFBmpC.d.cts} +1 -1
  9. package/dist/checkout/index.cjs +85 -38
  10. package/dist/checkout/index.d.cts +49 -11
  11. package/dist/checkout/index.d.ts +49 -11
  12. package/dist/checkout/index.js +65 -19
  13. package/dist/{chunk-KWYFA2LJ.cjs → chunk-34Y7Y5FU.cjs} +49 -31
  14. package/dist/{chunk-GTV42PDK.cjs → chunk-57UU7IJ2.cjs} +1 -0
  15. package/dist/{chunk-RNGQUWQW.cjs → chunk-H6FJYRO3.cjs} +49 -1
  16. package/dist/{chunk-CHRTGR3G.js → chunk-KCLVR6G5.js} +39 -2
  17. package/dist/{chunk-IWYO22XV.cjs → chunk-NOT6VKXA.cjs} +37 -39
  18. package/dist/{chunk-LCMJYFHC.cjs → chunk-NQZ5GUOG.cjs} +0 -1
  19. package/dist/{chunk-5BT3MH4A.cjs → chunk-NRPK5GCJ.cjs} +11 -3
  20. package/dist/{chunk-K44JZ5NL.cjs → chunk-NSAHGMS7.cjs} +6 -1
  21. package/dist/{chunk-4C4NTH6O.js → chunk-OOFYY6GR.js} +1 -0
  22. package/dist/{chunk-6QHEH5XE.js → chunk-QQHQTBAM.js} +20 -22
  23. package/dist/{chunk-H32TICAM.js → chunk-TH7OAMGC.js} +0 -1
  24. package/dist/{chunk-WFDKKOO7.js → chunk-VAU5OL72.js} +6 -1
  25. package/dist/{chunk-5JD6MRVS.js → chunk-VPTN4YXD.js} +36 -18
  26. package/dist/{chunk-TY5NK7NW.js → chunk-ZAWZ3RB6.js} +9 -2
  27. package/dist/{collections-ycrA2cPL.d.ts → collections-CNh2OGbl.d.ts} +1 -1
  28. package/dist/{collections-8YdINtUf.d.cts → collections-CXgOv5_G.d.cts} +1 -1
  29. package/dist/components/digital-product-download-modal.d.cts +2 -2
  30. package/dist/components/digital-product-download-modal.d.ts +2 -2
  31. package/dist/components/index.d.cts +5 -5
  32. package/dist/components/index.d.ts +5 -5
  33. package/dist/components/share-button.d.cts +1 -1
  34. package/dist/components/share-button.d.ts +1 -1
  35. package/dist/components/theme-data-initializer.d.cts +5 -5
  36. package/dist/components/theme-data-initializer.d.ts +5 -5
  37. package/dist/hooks/index.cjs +592 -30
  38. package/dist/hooks/index.d.cts +183 -5
  39. package/dist/hooks/index.d.ts +183 -5
  40. package/dist/hooks/index.js +569 -11
  41. package/dist/{instagram-CqJBZ-0X.d.ts → instagram-BADLnNQ3.d.ts} +1 -1
  42. package/dist/{instagram-D4JUT4ZU.d.cts → instagram-DalreBu6.d.cts} +1 -1
  43. package/dist/middleware/index.cjs +3 -3
  44. package/dist/middleware/index.js +1 -1
  45. package/dist/models/index.d.cts +7 -6
  46. package/dist/models/index.d.ts +7 -6
  47. package/dist/{orders-C1XZr8tx.d.ts → orders-B3G4CyhH.d.cts} +2 -1
  48. package/dist/{orders-9_scVq_M.d.cts → orders-Bl-Slh72.d.ts} +2 -1
  49. package/dist/{pixelEvents-uiPHbiAQ.d.cts → pixelEvents-BtEO5QAR.d.cts} +5 -4
  50. package/dist/{pixelEvents-D0sH22Er.d.ts → pixelEvents-LsealscG.d.ts} +5 -4
  51. package/dist/{product-CZtFWhxO.d.ts → product-D9liEtl4.d.cts} +1 -0
  52. package/dist/{product-CZtFWhxO.d.cts → product-D9liEtl4.d.ts} +1 -0
  53. package/dist/store/index.cjs +9 -9
  54. package/dist/store/index.d.cts +12 -7
  55. package/dist/store/index.d.ts +12 -7
  56. package/dist/store/index.js +4 -4
  57. package/dist/utils/index.cjs +9 -9
  58. package/dist/utils/index.d.cts +8 -7
  59. package/dist/utils/index.d.ts +8 -7
  60. package/dist/utils/index.js +3 -3
  61. package/dist/{wishlist-Cx9Vrszq.d.cts → wishlist-BakHvIFN.d.cts} +1 -1
  62. package/dist/{wishlist-CRNbfFIx.d.ts → wishlist-Cj0sQxiY.d.ts} +1 -1
  63. package/package.json +1 -1
@@ -1,12 +1,12 @@
1
1
  import { getUserDetails } from '../chunk-WYXT5AAG.js';
2
2
  import { findMatchingVariant, findSimilarVariant, isVariantCombinationAvailable, isColorVariantType } from '../chunk-HEFA67WK.js';
3
- import { useCartStore, useAuthStore } from '../chunk-6QHEH5XE.js';
4
- import { getCart, getProductList, getProductDetail, getWishlist, notifyProductStock, getProductCategories, getCategories } from '../chunk-TY5NK7NW.js';
5
- import { cart_default } from '../chunk-H32TICAM.js';
6
- import { processPayment, fetchAvailableCoupons, applyCheckoutCoupon, removeCheckoutCoupon } from '../chunk-5JD6MRVS.js';
3
+ import { useCartStore, useAuthStore } from '../chunk-QQHQTBAM.js';
4
+ import { getCart, getProductList, getProductDetail, getWishlist, notifyProductStock, getProductCategories, getCategories } from '../chunk-ZAWZ3RB6.js';
5
+ import { cart_default } from '../chunk-TH7OAMGC.js';
6
+ import { processPayment, fetchAvailableCoupons, applyCheckoutCoupon, removeCheckoutCoupon } from '../chunk-VPTN4YXD.js';
7
7
  import { applyCoupon, removeCoupon, getCoupons, getAppliedCoupon } from '../chunk-7M5CVYZJ.js';
8
- import '../chunk-WFDKKOO7.js';
9
- import { getOrders, placeOrder } from '../chunk-CHRTGR3G.js';
8
+ import '../chunk-VAU5OL72.js';
9
+ import { getOrders, placeOrder, buyNowPreview, placeGuestBuyNowOrder, placeBuyNowOrder, publicCheckoutPreview, placePublicOrder } from '../chunk-KCLVR6G5.js';
10
10
  export { useAddressForm } from '../chunk-ICKTXS6B.js';
11
11
  import { getAddresses } from '../chunk-ZGMLOLTC.js';
12
12
  import '../chunk-OSM73ETC.js';
@@ -354,7 +354,8 @@ function useCheckoutPayment(options) {
354
354
  const order = response.data;
355
355
  setOrderSummary(order);
356
356
  processPayment(order, paymentMethod, callbacks);
357
- } catch {
357
+ } catch (error) {
358
+ if (options.onPlaceOrderError?.(error) === true) return;
358
359
  setShowFailureModal(true);
359
360
  } finally {
360
361
  setIsPlacingOrder(false);
@@ -373,6 +374,538 @@ function useCheckoutPayment(options) {
373
374
  placeAndPay
374
375
  };
375
376
  }
377
+ var BUY_NOW_PAYLOAD_KEY = "____bn_pl_";
378
+ var DEBOUNCE_MS = 300;
379
+ function messageForPreviewError(code, fallback, isPreorder) {
380
+ switch (code) {
381
+ case "FEATURE_NOT_AVAILABLE":
382
+ return isPreorder ? "Pre Order isn't available for this store." : "Buy Now isn't available for this store.";
383
+ case "PUBLIC_CHECKOUT_DISABLED":
384
+ return "Guest checkout isn't available for this store. Please log in to continue.";
385
+ case "VARIANT_NOT_FOUND":
386
+ return "This product is no longer available.";
387
+ case "VARIANT_UNAVAILABLE":
388
+ return "This product is currently unavailable.";
389
+ case "INVALID_QUANTITY":
390
+ return "Please choose a valid quantity.";
391
+ case "ADDRESS_NOT_FOUND":
392
+ return "The selected address could not be found. Please pick another.";
393
+ default:
394
+ return fallback || "We couldn't load this item. Please try again.";
395
+ }
396
+ }
397
+ function readStashedItem() {
398
+ if (typeof window === "undefined") return null;
399
+ try {
400
+ const raw = window.sessionStorage.getItem(BUY_NOW_PAYLOAD_KEY);
401
+ if (!raw) return null;
402
+ const parsed = JSON.parse(raw);
403
+ if (!parsed?.variant_id) return null;
404
+ return { ...parsed, quantity: parsed.quantity || 1 };
405
+ } catch {
406
+ return null;
407
+ }
408
+ }
409
+ function useBuyNow(isAuthenticated = true) {
410
+ const [item, setItem] = useState(null);
411
+ const [quantity, setQuantityState] = useState(1);
412
+ const [couponCodes, setCouponCodes] = useState(void 0);
413
+ const [addressId, setAddressIdState] = useState(void 0);
414
+ const [guestAddress, setGuestAddressState] = useState(void 0);
415
+ const [shippingOptionId, setShippingOptionIdState] = useState(void 0);
416
+ const [preview, setPreview] = useState(null);
417
+ const [isLoading, setIsLoading] = useState(true);
418
+ const [isRefreshing, setIsRefreshing] = useState(false);
419
+ const [placingOrder, setPlacingOrder] = useState(false);
420
+ const [notFound, setNotFound] = useState(false);
421
+ const [error, setError] = useState(null);
422
+ const [refreshNonce, setRefreshNonce] = useState(0);
423
+ const debounceRef = useRef();
424
+ const stateRef = useRef({ quantity, couponCodes, addressId, guestAddress, shippingOptionId, preview });
425
+ stateRef.current = { quantity, couponCodes, addressId, guestAddress, shippingOptionId, preview };
426
+ useEffect(() => {
427
+ const stashed = readStashedItem();
428
+ if (!stashed) {
429
+ setNotFound(true);
430
+ setIsLoading(false);
431
+ return;
432
+ }
433
+ setItem(stashed);
434
+ setQuantityState(stashed.quantity || 1);
435
+ }, []);
436
+ const runPreview = useCallback(async (current) => {
437
+ const { quantity: quantity2, couponCodes: couponCodes2, addressId: addressId2, guestAddress: guestAddress2, shippingOptionId: shippingOptionId2 } = stateRef.current;
438
+ const payload = {
439
+ variant_id: current.variant_id,
440
+ quantity: quantity2,
441
+ customization_inputs: current.customization_inputs
442
+ };
443
+ if (couponCodes2 !== void 0) payload.coupon_codes = couponCodes2;
444
+ if (addressId2 !== void 0) payload.address_id = addressId2;
445
+ if (guestAddress2 !== void 0) payload.address = guestAddress2;
446
+ if (shippingOptionId2 !== void 0) payload.shipping_option_id = shippingOptionId2;
447
+ setIsRefreshing(true);
448
+ try {
449
+ const response = await buyNowPreview(payload);
450
+ if (response.data) {
451
+ setPreview(response.data);
452
+ setError(null);
453
+ }
454
+ } catch (err) {
455
+ const data = err?.response?.data;
456
+ setError({
457
+ code: data?.error_code || "INTERNAL_ERROR",
458
+ message: messageForPreviewError(data?.error_code, data?.error, current.is_preorder)
459
+ });
460
+ } finally {
461
+ setIsLoading(false);
462
+ setIsRefreshing(false);
463
+ }
464
+ }, []);
465
+ useEffect(() => {
466
+ if (!item) return;
467
+ if (debounceRef.current) clearTimeout(debounceRef.current);
468
+ debounceRef.current = setTimeout(() => runPreview(item), DEBOUNCE_MS);
469
+ return () => {
470
+ if (debounceRef.current) clearTimeout(debounceRef.current);
471
+ };
472
+ }, [item, quantity, couponCodes, addressId, guestAddress, shippingOptionId, refreshNonce, runPreview]);
473
+ const refresh = useCallback(() => {
474
+ setRefreshNonce((n) => n + 1);
475
+ }, []);
476
+ const clearItem = useCallback(() => {
477
+ try {
478
+ window.sessionStorage.removeItem(BUY_NOW_PAYLOAD_KEY);
479
+ } catch {
480
+ }
481
+ }, []);
482
+ const setQuantity = useCallback((value) => {
483
+ setQuantityState(Math.max(1, value));
484
+ }, []);
485
+ const setAddressId = useCallback((id) => {
486
+ setAddressIdState(id);
487
+ setShippingOptionIdState(void 0);
488
+ }, []);
489
+ const setGuestAddress = useCallback((address) => {
490
+ const prev = stateRef.current.guestAddress;
491
+ const unchanged = prev?.country_obj === address?.country_obj && prev?.state_obj === address?.state_obj && prev?.pincode === address?.pincode;
492
+ if (unchanged) return;
493
+ const destinationChanged = prev?.country_obj !== address?.country_obj || prev?.state_obj !== address?.state_obj;
494
+ setGuestAddressState(address);
495
+ if (destinationChanged) setShippingOptionIdState(void 0);
496
+ }, []);
497
+ const setShippingOptionId = useCallback((id) => {
498
+ setShippingOptionIdState(id);
499
+ }, []);
500
+ const applyCoupon2 = useCallback((code) => {
501
+ setCouponCodes([code]);
502
+ }, []);
503
+ const removeCoupon2 = useCallback(() => {
504
+ setCouponCodes([]);
505
+ }, []);
506
+ const placeOrder2 = useCallback(
507
+ async ({
508
+ isCod,
509
+ phonepeRedirectUrl,
510
+ stripeRedirectUrl,
511
+ tabbyRedirectUrl,
512
+ guest
513
+ }) => {
514
+ if (!item) return;
515
+ const effectiveShippingId = shippingOptionId ?? stateRef.current.preview?.selected_shipping_option_id ?? void 0;
516
+ setPlacingOrder(true);
517
+ try {
518
+ if (!isAuthenticated) {
519
+ if (!guest) throw new Error("MISSING_ADDRESS");
520
+ const payload2 = {
521
+ cart_items: { [item.variant_id]: quantity },
522
+ is_buy_now: true,
523
+ is_cod: !!isCod,
524
+ email: guest.email,
525
+ phone: guest.phone,
526
+ country_code: guest.country_code,
527
+ address: guest.address
528
+ };
529
+ if (couponCodes !== void 0) payload2.coupon_codes = couponCodes;
530
+ if (effectiveShippingId !== void 0 && effectiveShippingId !== null)
531
+ payload2.shipping_option_id = effectiveShippingId;
532
+ if (phonepeRedirectUrl) payload2.phonepe_redirect_url = phonepeRedirectUrl;
533
+ if (stripeRedirectUrl) payload2.stripe_redirect_url = stripeRedirectUrl;
534
+ if (tabbyRedirectUrl) payload2.tabby_redirect_url = tabbyRedirectUrl;
535
+ const response2 = await placeGuestBuyNowOrder(payload2);
536
+ return response2.data;
537
+ }
538
+ if (addressId === void 0) throw new Error("MISSING_ADDRESS");
539
+ const payload = {
540
+ variant_id: item.variant_id,
541
+ quantity,
542
+ address_id: addressId,
543
+ customization_inputs: item.customization_inputs,
544
+ is_cod: !!isCod
545
+ };
546
+ if (couponCodes !== void 0) payload.coupon_codes = couponCodes;
547
+ if (effectiveShippingId !== void 0 && effectiveShippingId !== null)
548
+ payload.shipping_option_id = effectiveShippingId;
549
+ if (phonepeRedirectUrl) payload.phonepe_redirect_url = phonepeRedirectUrl;
550
+ if (stripeRedirectUrl) payload.stripe_redirect_url = stripeRedirectUrl;
551
+ if (tabbyRedirectUrl) payload.tabby_redirect_url = tabbyRedirectUrl;
552
+ const response = await placeBuyNowOrder(payload);
553
+ return response.data;
554
+ } finally {
555
+ setPlacingOrder(false);
556
+ }
557
+ },
558
+ [item, quantity, addressId, couponCodes, shippingOptionId, isAuthenticated]
559
+ );
560
+ return {
561
+ // data
562
+ item,
563
+ preview,
564
+ quantity,
565
+ couponCodes,
566
+ addressId,
567
+ guestAddress,
568
+ shippingOptionId,
569
+ // status
570
+ isLoading,
571
+ isRefreshing,
572
+ placingOrder,
573
+ notFound,
574
+ error,
575
+ missingItems: preview?.missing_items ?? {},
576
+ appliedCoupon: preview?.applied_coupons && Object.keys(preview.applied_coupons).length > 0 ? preview.applied_coupons : null,
577
+ // actions
578
+ setQuantity,
579
+ setAddressId,
580
+ setShippingOptionId,
581
+ applyCoupon: applyCoupon2,
582
+ removeCoupon: removeCoupon2,
583
+ setGuestAddress,
584
+ refresh,
585
+ clearItem,
586
+ placeOrder: placeOrder2
587
+ };
588
+ }
589
+ function useInlineCheckoutPayment(options) {
590
+ const [orderSummary, setOrderSummary] = useState(null);
591
+ const [isPlacingOrder, setIsPlacingOrder] = useState(false);
592
+ const [isConfirmingPayment, setIsConfirmingPayment] = useState(false);
593
+ const [showSuccessModal, setShowSuccessModal] = useState(false);
594
+ const [showFailureModal, setShowFailureModal] = useState(false);
595
+ const isPublic = !options.isAuthenticated;
596
+ const callbacks = {
597
+ onSuccess: (order) => {
598
+ setOrderSummary(order);
599
+ setShowSuccessModal(true);
600
+ options.onClearItem?.();
601
+ options.onSuccess?.(order);
602
+ },
603
+ onFailure: (order) => {
604
+ setOrderSummary(order);
605
+ setShowFailureModal(true);
606
+ options.onFailure?.(order);
607
+ },
608
+ onRedirect: options.onRedirect,
609
+ onStripeModalOpen: options.onStripeModalOpen,
610
+ onCartReset: () => {
611
+ },
612
+ onPaymentStart: () => setIsConfirmingPayment(true),
613
+ onPaymentEnd: () => setIsConfirmingPayment(false)
614
+ };
615
+ const placeAndPay = useCallback(
616
+ async (paymentMethod) => {
617
+ try {
618
+ setIsPlacingOrder(true);
619
+ const isCod = paymentMethod === "cod";
620
+ const guest = isPublic ? options.getGuestContact?.() : void 0;
621
+ if (isPublic && !guest) {
622
+ setShowFailureModal(true);
623
+ return;
624
+ }
625
+ const order = await options.placeOrder({
626
+ isCod,
627
+ phonepeRedirectUrl: options.phonepeRedirectUrl,
628
+ stripeRedirectUrl: options.stripeRedirectUrl,
629
+ tabbyRedirectUrl: options.tabbyRedirectUrl,
630
+ guest
631
+ });
632
+ if (!order) {
633
+ setShowFailureModal(true);
634
+ return;
635
+ }
636
+ setOrderSummary(order);
637
+ processPayment(order, paymentMethod, callbacks, { isPublic });
638
+ } catch (error) {
639
+ if (options.onPlaceOrderError?.(error) === true) return;
640
+ setShowFailureModal(true);
641
+ } finally {
642
+ setIsPlacingOrder(false);
643
+ }
644
+ },
645
+ [
646
+ isPublic,
647
+ options.placeOrder,
648
+ options.getGuestContact,
649
+ options.phonepeRedirectUrl,
650
+ options.stripeRedirectUrl,
651
+ options.tabbyRedirectUrl
652
+ ]
653
+ );
654
+ return {
655
+ orderSummary,
656
+ isPlacingOrder,
657
+ isConfirmingPayment,
658
+ showSuccessModal,
659
+ showFailureModal,
660
+ setShowSuccessModal,
661
+ setShowFailureModal,
662
+ placeAndPay
663
+ };
664
+ }
665
+ var DEBOUNCE_MS2 = 400;
666
+ function messageForPreviewError2(code, fallback) {
667
+ switch (code) {
668
+ case "PUBLIC_CHECKOUT_DISABLED":
669
+ return "Guest checkout isn't available for this store. Please log in to continue.";
670
+ case "INVALID_QUANTITY":
671
+ return "One of the items has an invalid quantity. Please review your cart.";
672
+ case "ADDRESS_NOT_FOUND":
673
+ return "The selected address could not be found. Please pick another.";
674
+ case "PREORDER_DIRECT_ONLY":
675
+ return "A pre-order product is in your cart. Please remove it and purchase it directly with Pre Order.";
676
+ default:
677
+ return fallback || "We couldn't price your cart. Please try again.";
678
+ }
679
+ }
680
+ function readCartItems(cart) {
681
+ if (!cart?.products_quantity) return {};
682
+ return Object.entries(cart.products_quantity).reduce(
683
+ (acc, [id, qty]) => {
684
+ const variantId = Number(id);
685
+ const quantity = Number(qty);
686
+ if (variantId && quantity > 0) acc[variantId] = quantity;
687
+ return acc;
688
+ },
689
+ {}
690
+ );
691
+ }
692
+ function usePublicCheckout() {
693
+ const [cartItems, setCartItems] = useState({});
694
+ const [couponCodes, setCouponCodes] = useState(void 0);
695
+ const [guestAddress, setGuestAddressState] = useState(void 0);
696
+ const [shippingOptionId, setShippingOptionIdState] = useState(
697
+ void 0
698
+ );
699
+ const [isCod, setIsCodState] = useState(false);
700
+ const [preview, setPreview] = useState(null);
701
+ const [isLoading, setIsLoading] = useState(true);
702
+ const [isRefreshing, setIsRefreshing] = useState(false);
703
+ const [placingOrder, setPlacingOrder] = useState(false);
704
+ const [isEmpty, setIsEmpty] = useState(false);
705
+ const [error, setError] = useState(null);
706
+ const [refreshNonce, setRefreshNonce] = useState(0);
707
+ const debounceRef = useRef();
708
+ const stateRef = useRef({
709
+ cartItems,
710
+ couponCodes,
711
+ guestAddress,
712
+ shippingOptionId,
713
+ isCod,
714
+ preview
715
+ });
716
+ stateRef.current = {
717
+ cartItems,
718
+ couponCodes,
719
+ guestAddress,
720
+ shippingOptionId,
721
+ isCod,
722
+ preview
723
+ };
724
+ useEffect(() => {
725
+ const cart = cart_default.get();
726
+ const items = readCartItems(cart);
727
+ if (Object.keys(items).length === 0) {
728
+ setIsEmpty(true);
729
+ setIsLoading(false);
730
+ return;
731
+ }
732
+ setCartItems(items);
733
+ }, []);
734
+ const pruneStaleItems = useCallback(
735
+ (priced) => {
736
+ const missing = priced.missing_items || {};
737
+ const missingIds = Object.keys(missing).map(Number);
738
+ if (missingIds.length === 0) return;
739
+ const pricedIds = new Set((priced.product_variants || []).map((v) => v.id));
740
+ const droppedIds = missingIds.filter((id) => !pricedIds.has(id));
741
+ if (droppedIds.length === 0) return;
742
+ const cart = cart_default.get();
743
+ if (cart) {
744
+ droppedIds.forEach((id) => {
745
+ const variant = cart.product_variants?.find((v) => v.id === id);
746
+ if (variant) cart_default.remove(variant);
747
+ });
748
+ }
749
+ setCartItems((prev) => {
750
+ const next = { ...prev };
751
+ droppedIds.forEach((id) => delete next[id]);
752
+ return next;
753
+ });
754
+ },
755
+ []
756
+ );
757
+ const runPreview = useCallback(async () => {
758
+ const {
759
+ cartItems: cartItems2,
760
+ couponCodes: couponCodes2,
761
+ guestAddress: guestAddress2,
762
+ shippingOptionId: shippingOptionId2,
763
+ isCod: isCod2
764
+ } = stateRef.current;
765
+ if (Object.keys(cartItems2).length === 0) {
766
+ setIsEmpty(true);
767
+ setIsLoading(false);
768
+ return;
769
+ }
770
+ const payload = {
771
+ cart_items: cartItems2,
772
+ is_cod: isCod2
773
+ };
774
+ if (couponCodes2 !== void 0) payload.coupon_codes = couponCodes2;
775
+ if (guestAddress2 !== void 0) payload.address = guestAddress2;
776
+ if (shippingOptionId2 !== void 0) payload.shipping_option_id = shippingOptionId2;
777
+ setIsRefreshing(true);
778
+ try {
779
+ const response = await publicCheckoutPreview(payload);
780
+ if (response.data) {
781
+ setPreview(response.data);
782
+ setError(null);
783
+ pruneStaleItems(response.data);
784
+ }
785
+ } catch (err) {
786
+ const data = err?.response?.data;
787
+ const code = data?.error_code;
788
+ if (code === "CART_EMPTY") {
789
+ cart_default.clear();
790
+ setCartItems({});
791
+ setIsEmpty(true);
792
+ setPreview(null);
793
+ setError(null);
794
+ return;
795
+ }
796
+ setError({
797
+ code: code || "INTERNAL_ERROR",
798
+ message: messageForPreviewError2(code, data?.error)
799
+ });
800
+ } finally {
801
+ setIsLoading(false);
802
+ setIsRefreshing(false);
803
+ }
804
+ }, [pruneStaleItems]);
805
+ useEffect(() => {
806
+ if (isEmpty) return;
807
+ if (Object.keys(cartItems).length === 0) return;
808
+ if (debounceRef.current) clearTimeout(debounceRef.current);
809
+ debounceRef.current = setTimeout(runPreview, DEBOUNCE_MS2);
810
+ return () => {
811
+ if (debounceRef.current) clearTimeout(debounceRef.current);
812
+ };
813
+ }, [
814
+ cartItems,
815
+ couponCodes,
816
+ guestAddress,
817
+ shippingOptionId,
818
+ isCod,
819
+ refreshNonce,
820
+ isEmpty,
821
+ runPreview
822
+ ]);
823
+ const refresh = useCallback(() => setRefreshNonce((n) => n + 1), []);
824
+ const setGuestAddress = useCallback((address) => {
825
+ const prev = stateRef.current.guestAddress;
826
+ const unchanged = prev?.country_obj === address?.country_obj && prev?.state_obj === address?.state_obj && prev?.pincode === address?.pincode;
827
+ if (unchanged) return;
828
+ const destinationChanged = prev?.country_obj !== address?.country_obj || prev?.state_obj !== address?.state_obj;
829
+ setGuestAddressState(address);
830
+ if (destinationChanged) setShippingOptionIdState(void 0);
831
+ }, []);
832
+ const setShippingOptionId = useCallback((id) => {
833
+ setShippingOptionIdState(id);
834
+ }, []);
835
+ const setIsCod = useCallback((value) => setIsCodState(value), []);
836
+ const applyCoupon2 = useCallback((code) => setCouponCodes([code]), []);
837
+ const removeCoupon2 = useCallback(() => setCouponCodes([]), []);
838
+ const clearCart = useCallback(() => {
839
+ cart_default.clear();
840
+ setCartItems({});
841
+ setIsEmpty(true);
842
+ }, []);
843
+ const placeOrder2 = useCallback(
844
+ async ({
845
+ isCod: isCodArg,
846
+ phonepeRedirectUrl,
847
+ stripeRedirectUrl,
848
+ tabbyRedirectUrl,
849
+ guest
850
+ }) => {
851
+ if (!guest) throw new Error("MISSING_ADDRESS");
852
+ const items = stateRef.current.cartItems;
853
+ if (Object.keys(items).length === 0) throw new Error("CART_EMPTY");
854
+ setPlacingOrder(true);
855
+ try {
856
+ const payload = {
857
+ cart_items: items,
858
+ is_cod: !!isCodArg,
859
+ email: guest.email,
860
+ phone: guest.phone,
861
+ country_code: guest.country_code,
862
+ address: guest.address
863
+ };
864
+ if (couponCodes !== void 0) payload.coupon_codes = couponCodes;
865
+ const effectiveShippingId = shippingOptionId ?? stateRef.current.preview?.selected_shipping_option_id ?? void 0;
866
+ if (effectiveShippingId !== void 0 && effectiveShippingId !== null) {
867
+ payload.shipping_option_id = effectiveShippingId;
868
+ }
869
+ if (phonepeRedirectUrl) payload.phonepe_redirect_url = phonepeRedirectUrl;
870
+ if (stripeRedirectUrl) payload.stripe_redirect_url = stripeRedirectUrl;
871
+ if (tabbyRedirectUrl) payload.tabby_redirect_url = tabbyRedirectUrl;
872
+ const response = await placePublicOrder(payload);
873
+ return response.data;
874
+ } finally {
875
+ setPlacingOrder(false);
876
+ }
877
+ },
878
+ [couponCodes, shippingOptionId]
879
+ );
880
+ return {
881
+ // data
882
+ preview,
883
+ cartItems,
884
+ couponCodes,
885
+ guestAddress,
886
+ shippingOptionId,
887
+ isCod,
888
+ isCodEnabled: !!preview?.is_cod_enabled,
889
+ codAmount: Number(preview?.cod_amount || 0),
890
+ // status
891
+ isLoading,
892
+ isRefreshing,
893
+ placingOrder,
894
+ isEmpty,
895
+ error,
896
+ missingItems: preview?.missing_items ?? {},
897
+ appliedCoupon: preview?.applied_coupons && Object.keys(preview.applied_coupons).length > 0 ? preview.applied_coupons : null,
898
+ // actions
899
+ setGuestAddress,
900
+ setShippingOptionId,
901
+ setIsCod,
902
+ applyCoupon: applyCoupon2,
903
+ removeCoupon: removeCoupon2,
904
+ refresh,
905
+ clearCart,
906
+ placeOrder: placeOrder2
907
+ };
908
+ }
376
909
  function useCheckoutCoupon(options) {
377
910
  const [availableCoupons, setAvailableCoupons] = useState([]);
378
911
  const [appliedCoupon, setAppliedCoupon] = useState(null);
@@ -506,8 +1039,9 @@ function useVariantSelector(options) {
506
1039
  };
507
1040
  }
508
1041
  function useShopCheckout(options) {
509
- const { product, onNavigateToCart, onToast } = options;
1042
+ const { product, onNavigateToCart, onToast, onPreorderRejected } = options;
510
1043
  const { addToCart, setCart } = useCartStore();
1044
+ const cart = useCartStore((s) => s.cart);
511
1045
  const isUserAuthenticated = useAuthStore((s) => s.isAuthenticated);
512
1046
  const [isWishlisted, setIsWishlisted] = useState(product.is_wishlisted);
513
1047
  const [isAddedToCart, setIsAddedToCart] = useState(false);
@@ -516,6 +1050,23 @@ function useShopCheckout(options) {
516
1050
  const [showLoginModal, setShowLoginModal] = useState(false);
517
1051
  const [showNotifyMeModal, setShowNotifyMeModal] = useState(false);
518
1052
  const [categories, setCategories] = useState([]);
1053
+ const [cartQuantity, setCartQuantity] = useState(
1054
+ Number(product.cart_quantity) || 0
1055
+ );
1056
+ useEffect(() => {
1057
+ let inCart;
1058
+ if (!isUserAuthenticated) {
1059
+ inCart = Number(cart_default.get()?.products_quantity?.[product.id]) || 0;
1060
+ } else if (cart) {
1061
+ inCart = cart.total_quantity > 0 ? Number(cart.products_quantity?.[product.id]) || 0 : 0;
1062
+ } else if (product.cart_quantity !== void 0) {
1063
+ inCart = Number(product.cart_quantity) || 0;
1064
+ }
1065
+ if (inCart !== void 0) {
1066
+ setCartQuantity(inCart);
1067
+ setIsAddedToCart(inCart > 0);
1068
+ }
1069
+ }, [product.id, product.cart_quantity, cart, isUserAuthenticated]);
519
1070
  useEffect(() => {
520
1071
  const fetchCategories = async () => {
521
1072
  try {
@@ -541,7 +1092,12 @@ function useShopCheckout(options) {
541
1092
  await addToCart([{ variant_id: product.id, quantity }]);
542
1093
  setIsAddedToCart(true);
543
1094
  } catch (error) {
544
- console.log(error);
1095
+ const code = error?.response?.data?.error_code;
1096
+ if (code === "PREORDER_DIRECT_ONLY" && onPreorderRejected) {
1097
+ onPreorderRejected();
1098
+ } else {
1099
+ console.log(error);
1100
+ }
545
1101
  } finally {
546
1102
  setLoading(false);
547
1103
  }
@@ -560,7 +1116,8 @@ function useShopCheckout(options) {
560
1116
  quantity,
561
1117
  addToCart,
562
1118
  setCart,
563
- onNavigateToCart
1119
+ onNavigateToCart,
1120
+ onPreorderRejected
564
1121
  ]);
565
1122
  const handleCustomizationSubmit = useCallback(
566
1123
  async (data) => {
@@ -663,6 +1220,7 @@ function useShopCheckout(options) {
663
1220
  return {
664
1221
  isWishlisted,
665
1222
  isAddedToCart,
1223
+ cartQuantity,
666
1224
  loading,
667
1225
  quantity,
668
1226
  showLoginModal,
@@ -766,4 +1324,4 @@ function useCoupon(options = {}) {
766
1324
  };
767
1325
  }
768
1326
 
769
- export { useAddress, useCart, useCheckoutCoupon, useCheckoutPayment, useCoupon, useGetProductCategories, useGetProductDetails, useGetProducts, useOrders, useProductDetailModal, useServiceFormModal, useShopCheckout, useUserDetails, useVariantSelector, useWishlist };
1327
+ export { BUY_NOW_PAYLOAD_KEY, useAddress, useBuyNow, useCart, useCheckoutCoupon, useCheckoutPayment, useCoupon, useGetProductCategories, useGetProductDetails, useGetProducts, useInlineCheckoutPayment, useOrders, useProductDetailModal, usePublicCheckout, useServiceFormModal, useShopCheckout, useUserDetails, useVariantSelector, useWishlist };
@@ -1,4 +1,4 @@
1
- import { f as ProductDetail } from './product-CZtFWhxO.js';
1
+ import { f as ProductDetail } from './product-D9liEtl4.js';
2
2
 
3
3
  declare namespace Review {
4
4
  interface ReviewPayload {
@@ -1,4 +1,4 @@
1
- import { f as ProductDetail } from './product-CZtFWhxO.cjs';
1
+ import { f as ProductDetail } from './product-D9liEtl4.cjs';
2
2
 
3
3
  declare namespace Review {
4
4
  interface ReviewPayload {
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkGTV42PDK_cjs = require('../chunk-GTV42PDK.cjs');
3
+ var chunk57UU7IJ2_cjs = require('../chunk-57UU7IJ2.cjs');
4
4
  var chunkNE3ZHELZ_cjs = require('../chunk-NE3ZHELZ.cjs');
5
5
  var server = require('next/server');
6
6
  var jwtDecode = require('jwt-decode');
@@ -18,13 +18,13 @@ function middleware(request) {
18
18
  );
19
19
  }
20
20
  }
21
- if (chunkGTV42PDK_cjs.protectedRoutes.includes(request.nextUrl.pathname) && !token) {
21
+ if (chunk57UU7IJ2_cjs.protectedRoutes.includes(request.nextUrl.pathname) && !token) {
22
22
  const response = server.NextResponse.redirect(
23
23
  new URL(`/login?referer=${request.nextUrl.pathname}`, request.url)
24
24
  );
25
25
  return response;
26
26
  }
27
- if (chunkGTV42PDK_cjs.authRoutes.includes(request.nextUrl.pathname) && token) {
27
+ if (chunk57UU7IJ2_cjs.authRoutes.includes(request.nextUrl.pathname) && token) {
28
28
  return server.NextResponse.redirect(
29
29
  new URL(`/?referer=${request.nextUrl.pathname}`, request.url)
30
30
  );
@@ -1,4 +1,4 @@
1
- import { protectedRoutes, authRoutes } from '../chunk-4C4NTH6O.js';
1
+ import { protectedRoutes, authRoutes } from '../chunk-OOFYY6GR.js';
2
2
  import { USER_CRED_TOKEN } from '../chunk-BQ256JKN.js';
3
3
  import { NextResponse } from 'next/server';
4
4
  import { jwtDecode } from 'jwt-decode';