medusa-storefront-data 1.0.0 → 2.0.0

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 (109) hide show
  1. package/dist/cookies.d.ts +2 -2
  2. package/dist/cookies.d.ts.map +1 -1
  3. package/dist/edge.d.ts +3 -0
  4. package/dist/edge.d.ts.map +1 -0
  5. package/dist/edge.js +1 -0
  6. package/dist/middleware.d.ts +3 -0
  7. package/dist/middleware.d.ts.map +1 -0
  8. package/dist/middleware.js +1 -0
  9. package/dist/server/cart.d.ts +9 -5
  10. package/dist/server/cart.d.ts.map +1 -1
  11. package/dist/server/cart.js +164 -194
  12. package/dist/server/categories.d.ts +3 -2
  13. package/dist/server/categories.d.ts.map +1 -1
  14. package/dist/server/categories.js +14 -51
  15. package/dist/server/collections.d.ts.map +1 -1
  16. package/dist/server/collections.js +16 -61
  17. package/dist/server/contact.d.ts +34 -0
  18. package/dist/server/contact.d.ts.map +1 -0
  19. package/dist/server/contact.js +57 -0
  20. package/dist/server/customer.d.ts +7 -7
  21. package/dist/server/customer.d.ts.map +1 -1
  22. package/dist/server/customer.js +95 -145
  23. package/dist/server/dynamic-config.d.ts.map +1 -1
  24. package/dist/server/dynamic-config.js +5 -2
  25. package/dist/server/fulfillment.d.ts +4 -3
  26. package/dist/server/fulfillment.d.ts.map +1 -1
  27. package/dist/server/fulfillment.js +16 -41
  28. package/dist/server/guest.d.ts +35 -63
  29. package/dist/server/guest.d.ts.map +1 -1
  30. package/dist/server/guest.js +81 -202
  31. package/dist/server/home.d.ts +15 -0
  32. package/dist/server/home.d.ts.map +1 -0
  33. package/dist/server/home.js +45 -0
  34. package/dist/server/index.d.ts +2 -0
  35. package/dist/server/index.d.ts.map +1 -1
  36. package/dist/server/index.js +2 -0
  37. package/dist/server/locale-actions.d.ts +1 -1
  38. package/dist/server/locale-actions.d.ts.map +1 -1
  39. package/dist/server/locale-actions.js +8 -13
  40. package/dist/server/locales.d.ts +2 -4
  41. package/dist/server/locales.d.ts.map +1 -1
  42. package/dist/server/locales.js +5 -13
  43. package/dist/server/orders.d.ts +5 -11
  44. package/dist/server/orders.d.ts.map +1 -1
  45. package/dist/server/orders.js +126 -267
  46. package/dist/server/payment-details.d.ts +4 -4
  47. package/dist/server/payment-details.d.ts.map +1 -1
  48. package/dist/server/payment-details.js +17 -42
  49. package/dist/server/payment.d.ts +2 -1
  50. package/dist/server/payment.d.ts.map +1 -1
  51. package/dist/server/payment.js +9 -21
  52. package/dist/server/pincode.d.ts +7 -0
  53. package/dist/server/pincode.d.ts.map +1 -0
  54. package/dist/server/pincode.js +30 -0
  55. package/dist/server/products.d.ts +15 -19
  56. package/dist/server/products.d.ts.map +1 -1
  57. package/dist/server/products.js +47 -178
  58. package/dist/server/regions.d.ts +1 -1
  59. package/dist/server/regions.d.ts.map +1 -1
  60. package/dist/server/regions.js +6 -3
  61. package/dist/server/returns.d.ts +4 -4
  62. package/dist/server/returns.d.ts.map +1 -1
  63. package/dist/server/returns.js +50 -154
  64. package/dist/server/swaps.d.ts +3 -3
  65. package/dist/server/swaps.d.ts.map +1 -1
  66. package/dist/server/swaps.js +22 -56
  67. package/dist/server/variants.d.ts.map +1 -1
  68. package/dist/server/variants.js +11 -22
  69. package/dist/server/wishlist.d.ts +11 -0
  70. package/dist/server/wishlist.d.ts.map +1 -0
  71. package/dist/server/wishlist.js +49 -0
  72. package/dist/util/get-locale-header.d.ts +1 -1
  73. package/dist/util/revalidate-cart.d.ts +2 -0
  74. package/dist/util/revalidate-cart.d.ts.map +1 -0
  75. package/dist/util/revalidate-cart.js +8 -0
  76. package/dist/util/sort-products.d.ts +3 -0
  77. package/dist/util/sort-products.d.ts.map +1 -0
  78. package/dist/util/sort-products.js +1 -0
  79. package/dist/util/store-client.d.ts +13 -0
  80. package/dist/util/store-client.d.ts.map +1 -0
  81. package/dist/util/store-client.js +77 -0
  82. package/package.json +95 -37
  83. package/src/edge.ts +2 -0
  84. package/src/middleware.ts +2 -2
  85. package/src/server/cart.ts +214 -267
  86. package/src/server/categories.ts +19 -72
  87. package/src/server/collections.ts +25 -82
  88. package/src/server/contact.ts +92 -0
  89. package/src/server/customer.ts +140 -189
  90. package/src/server/dynamic-config.ts +6 -2
  91. package/src/server/fulfillment.ts +27 -53
  92. package/src/server/guest.ts +159 -276
  93. package/src/server/home.ts +68 -0
  94. package/src/server/index.ts +1 -0
  95. package/src/server/locale-actions.ts +8 -15
  96. package/src/server/locales.ts +6 -18
  97. package/src/server/orders.ts +167 -337
  98. package/src/server/payment-details.ts +24 -52
  99. package/src/server/payment.ts +8 -28
  100. package/src/server/pincode.ts +49 -0
  101. package/src/server/products.ts +72 -235
  102. package/src/server/regions.ts +10 -6
  103. package/src/server/returns.ts +75 -189
  104. package/src/server/swaps.ts +90 -121
  105. package/src/server/variants.ts +9 -28
  106. package/src/util/revalidate-cart.ts +10 -0
  107. package/src/util/sort-products.ts +2 -47
  108. package/src/util/store-client.ts +93 -0
  109. package/src/services/middleware.ts +0 -54
@@ -1,8 +1,10 @@
1
1
  "use server";
2
- import { sdk } from "../config";
2
+ import { medusaCartUpdate } from "medusa-services/cart";
3
3
  import { revalidateTag } from "next/cache";
4
4
  import { cookies as nextCookies } from "next/headers";
5
- import { getAuthHeaders, getCacheTag, getCartId } from "../cookies";
5
+ import { getCartId, getCacheTag } from "../cookies";
6
+ import { getStoreClientOptions } from "../util/store-client";
7
+ import { revalidateCartTags } from "../util/revalidate-cart";
6
8
  const LOCALE_COOKIE_NAME = "_medusa_locale";
7
9
  /**
8
10
  * Gets the current locale from cookies
@@ -29,24 +31,17 @@ export const setLocaleCookie = async (locale) => {
29
31
  });
30
32
  };
31
33
  /**
32
- * Updates the locale preference via SDK and stores in cookie.
34
+ * Updates the locale preference and stores in cookie.
33
35
  * Also updates the cart with the new locale if one exists.
34
36
  */
35
37
  export const updateLocale = async (localeCode) => {
36
38
  await setLocaleCookie(localeCode);
37
- // Update cart with the new locale if a cart exists
38
39
  const cartId = await getCartId();
39
40
  if (cartId) {
40
- const headers = {
41
- ...(await getAuthHeaders()),
42
- };
43
- await sdk.store.cart.update(cartId, { locale: localeCode }, {}, headers);
44
- const cartCacheTag = await getCacheTag("carts");
45
- if (cartCacheTag) {
46
- revalidateTag(cartCacheTag);
47
- }
41
+ const options = await getStoreClientOptions();
42
+ await medusaCartUpdate(cartId, { locale: localeCode }, options);
43
+ await revalidateCartTags();
48
44
  }
49
- // Revalidate relevant caches to refresh content
50
45
  const productsCacheTag = await getCacheTag("products");
51
46
  if (productsCacheTag) {
52
47
  revalidateTag(productsCacheTag);
@@ -1,7 +1,5 @@
1
- export type Locale = {
2
- code: string;
3
- name: string;
4
- };
1
+ import { type StoreLocale } from "medusa-services/locales";
2
+ export type Locale = StoreLocale;
5
3
  /**
6
4
  * Fetches available locales from the backend.
7
5
  * Returns null if the endpoint returns 404 (locales not configured).
@@ -1 +1 @@
1
- {"version":3,"file":"locales.d.ts","sourceRoot":"","sources":["../../src/server/locales.ts"],"names":[],"mappings":"AAKA,MAAM,MAAM,MAAM,GAAG;IACnB,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;CACb,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,WAAW,QAAa,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAa3D,CAAA"}
1
+ {"version":3,"file":"locales.d.ts","sourceRoot":"","sources":["../../src/server/locales.ts"],"names":[],"mappings":"AAEA,OAAO,EAAoB,KAAK,WAAW,EAAE,MAAM,yBAAyB,CAAA;AAG5E,MAAM,MAAM,MAAM,GAAG,WAAW,CAAA;AAEhC;;;GAGG;AACH,eAAO,MAAM,WAAW,QAAa,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAI3D,CAAA"}
@@ -1,20 +1,12 @@
1
1
  "use server";
2
- import { sdk } from "../config";
3
- import { getCacheOptions } from "../cookies";
2
+ import { medusaLocaleList } from "medusa-services/locales";
3
+ import { getStoreClientOptions } from "../util/store-client";
4
4
  /**
5
5
  * Fetches available locales from the backend.
6
6
  * Returns null if the endpoint returns 404 (locales not configured).
7
7
  */
8
8
  export const listLocales = async () => {
9
- const next = {
10
- ...(await getCacheOptions("locales")),
11
- };
12
- return sdk.client
13
- .fetch(`/store/locales`, {
14
- method: "GET",
15
- next,
16
- cache: "force-cache",
17
- })
18
- .then(({ locales }) => locales)
19
- .catch(() => null);
9
+ const options = await getStoreClientOptions();
10
+ const result = await medusaLocaleList(options);
11
+ return result?.locales ?? null;
20
12
  };
@@ -1,5 +1,5 @@
1
1
  import { HttpTypes } from "@medusajs/types";
2
- export declare const retrieveOrder: (id: string) => Promise<any>;
2
+ export declare const retrieveOrder: (id: string) => Promise<HttpTypes.StoreOrder>;
3
3
  export declare const listOrders: (limit?: number, offset?: number, filters?: Record<string, any>) => Promise<HttpTypes.StoreOrder[]>;
4
4
  export declare const createTransferRequest: (state: {
5
5
  success: boolean;
@@ -12,21 +12,21 @@ export declare const createTransferRequest: (state: {
12
12
  }>;
13
13
  export declare const acceptTransferRequest: (id: string, token: string) => Promise<{
14
14
  success: boolean;
15
- error: any;
15
+ error: null;
16
16
  order: HttpTypes.StoreOrder;
17
17
  } | {
18
18
  success: boolean;
19
19
  error: any;
20
- order: any;
20
+ order: null;
21
21
  }>;
22
22
  export declare const declineTransferRequest: (id: string, token: string) => Promise<{
23
23
  success: boolean;
24
- error: any;
24
+ error: null;
25
25
  order: HttpTypes.StoreOrder;
26
26
  } | {
27
27
  success: boolean;
28
28
  error: any;
29
- order: any;
29
+ order: null;
30
30
  }>;
31
31
  export declare const downloadInvoice: (orderId: string) => Promise<{
32
32
  success: boolean;
@@ -37,9 +37,6 @@ export declare const downloadInvoice: (orderId: string) => Promise<{
37
37
  error: any;
38
38
  data?: undefined;
39
39
  }>;
40
- /**
41
- * Cancel an order
42
- */
43
40
  export declare const cancelOrder: (orderId: string, reasonId?: string) => Promise<{
44
41
  success: boolean;
45
42
  error?: undefined;
@@ -47,9 +44,6 @@ export declare const cancelOrder: (orderId: string, reasonId?: string) => Promis
47
44
  success: boolean;
48
45
  error: any;
49
46
  }>;
50
- /**
51
- * Reorder an order (supports both logged-in and guest users)
52
- */
53
47
  export declare const reorderOrder: (orderId: string, skipVariantIds?: string[], forceReorder?: boolean) => Promise<{
54
48
  success: boolean;
55
49
  error: string;
@@ -1 +1 @@
1
- {"version":3,"file":"orders.d.ts","sourceRoot":"","sources":["../../src/server/orders.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAG3C,eAAO,MAAM,aAAa,GAAU,IAAI,MAAM,iBAwE7C,CAAA;AAED,eAAO,MAAM,UAAU,GACrB,QAAO,MAAW,EAClB,SAAQ,MAAU,EAClB,UAAU,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,oCA0B9B,CAAA;AAED,eAAO,MAAM,qBAAqB,GAChC,OAAO;IACL,OAAO,EAAE,OAAO,CAAA;IAChB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,KAAK,EAAE,SAAS,CAAC,UAAU,GAAG,IAAI,CAAA;CACnC,EACD,UAAU,QAAQ,KACjB,OAAO,CAAC;IACT,OAAO,EAAE,OAAO,CAAA;IAChB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,KAAK,EAAE,SAAS,CAAC,UAAU,GAAG,IAAI,CAAA;CACnC,CAoBA,CAAA;AAED,eAAO,MAAM,qBAAqB,GAAU,IAAI,MAAM,EAAE,OAAO,MAAM;;;;;;;;EAOpE,CAAA;AAED,eAAO,MAAM,sBAAsB,GAAU,IAAI,MAAM,EAAE,OAAO,MAAM;;;;;;;;EAOrE,CAAA;AAED,eAAO,MAAM,eAAe,GAAU,SAAS,MAAM;;;;;;;;EAuDpD,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,WAAW,GAAU,SAAS,MAAM,EAAE,WAAW,MAAM;;;;;;EAqGnE,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,YAAY,GAAU,SAAS,MAAM,EAAE,iBAAiB,MAAM,EAAE,EAAE,eAAc,OAAe;;;;;;;;;;;;;;;EAqI3G,CAAA"}
1
+ {"version":3,"file":"orders.d.ts","sourceRoot":"","sources":["../../src/server/orders.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAmC3C,eAAO,MAAM,aAAa,GAAU,IAAI,MAAM,kCA4B7C,CAAA;AAED,eAAO,MAAM,UAAU,GACrB,QAAO,MAAW,EAClB,SAAQ,MAAU,EAClB,UAAU,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,oCAc9B,CAAA;AAED,eAAO,MAAM,qBAAqB,GAChC,OAAO;IACL,OAAO,EAAE,OAAO,CAAA;IAChB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,KAAK,EAAE,SAAS,CAAC,UAAU,GAAG,IAAI,CAAA;CACnC,EACD,UAAU,QAAQ,KACjB,OAAO,CAAC;IACT,OAAO,EAAE,OAAO,CAAA;IAChB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,KAAK,EAAE,SAAS,CAAC,UAAU,GAAG,IAAI,CAAA;CACnC,CAoBA,CAAA;AAED,eAAO,MAAM,qBAAqB,GAAU,IAAI,MAAM,EAAE,OAAO,MAAM;;;WAOpC,SAAS,CAAC,UAAU;;;;;EAKpD,CAAA;AAED,eAAO,MAAM,sBAAsB,GAAU,IAAI,MAAM,EAAE,OAAO,MAAM;;;WAOrC,SAAS,CAAC,UAAU;;;;;EAKpD,CAAA;AAED,eAAO,MAAM,eAAe,GAAU,SAAS,MAAM;;;;;;;;EAyBpD,CAAA;AAED,eAAO,MAAM,WAAW,GAAU,SAAS,MAAM,EAAE,WAAW,MAAM;;;;;;EA2BnE,CAAA;AAED,eAAO,MAAM,YAAY,GACvB,SAAS,MAAM,EACf,iBAAiB,MAAM,EAAE,EACzB,eAAc,OAAe;;;;;;;;;;;;;;;EAkF9B,CAAA"}
@@ -1,152 +1,128 @@
1
1
  "use server";
2
2
  import { cookies } from "next/headers";
3
- import { sdk } from "../config";
4
3
  import medusaError from "../util/medusa-error";
5
- import { getAuthHeaders, getCacheOptions, getCacheTag, setBuyNowCartId, removeBuyNowCartId } from "../cookies";
4
+ import { getCacheTag, setBuyNowCartId, removeBuyNowCartId, } from "../cookies";
6
5
  import { listReturnReasons } from "./returns";
7
6
  import { revalidateTag } from "next/cache";
7
+ import { extractReorderCartId, medusaGuestOrderCancel, medusaGuestOrderReorder, medusaOrderAcceptTransfer, medusaOrderCancel, medusaOrderDeclineTransfer, medusaOrderDownloadInvoice, medusaOrderList, medusaOrderReorder, medusaOrderRequestTransfer, medusaOrderRetrieve, MEDUSA_ORDER_DETAIL_FIELDS, } from "medusa-services/orders";
8
+ import { medusaCartRemoveLineItem, medusaCartRetrieve, medusaCartSkipMerge, medusaCartUpdate, } from "medusa-services/cart";
9
+ import { getGuestStoreClientOptions, getStoreCartClientOptions, getStoreClientOptionsWithToken, } from "../util/store-client";
10
+ function throwOrderError(error) {
11
+ if (error && typeof error === "object" && "response" in error) {
12
+ medusaError(error);
13
+ }
14
+ throw error instanceof Error ? error : new Error(String(error));
15
+ }
8
16
  export const retrieveOrder = async (id) => {
9
17
  const cookieStore = await cookies();
10
18
  const token = cookieStore.get("_medusa_jwt")?.value;
11
- // Check for guest token if regular token is missing
12
19
  const guestToken = !token
13
- ? (cookieStore.get("_medusa_guest_jwt")?.value || cookieStore.get("_medusa_guest_token")?.value)
20
+ ? (cookieStore.get("_medusa_guest_jwt")?.value ||
21
+ cookieStore.get("_medusa_guest_token")?.value)
14
22
  : null;
15
- // Log token details for debugging (only first 20 chars for security)
16
- const next = {
17
- ...(await getCacheOptions("orders")),
18
- };
19
- // If guest user, use the main orders endpoint with guest token to get full details
20
- if (guestToken && !token) {
21
- const publishableKey = process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY;
22
- const requestHeaders = {
23
- "Authorization": `Bearer ${guestToken}`
24
- };
25
- if (publishableKey)
26
- requestHeaders["x-publishable-api-key"] = publishableKey;
27
- const response = await sdk.client.fetch(`/store/orders/${id}`, {
28
- method: "GET",
29
- headers: requestHeaders,
30
- query: {
31
- fields: "id,display_id,customer_id,email,created_at,status,fulfillment_status,payment_status,currency_code,subtotal,shipping_total,tax_total,discount_total,metadata,total,*payment_collections.payments,*items,*items.metadata,*items.variant,*items.variant.images,*items.variant.product,*items.variant.product.thumbnail,*items.variant.product.images,*items.variant.product.variants,*items.product,*items.product.thumbnail,*items.product.images,*items.product.variants,*fulfillments,*fulfillments.items,*fulfillments.location_id,*returns,*returns.items,*cart,*shipping_address,*billing_address,*region,*shipping_methods"
32
- },
33
- cache: "no-store"
34
- });
35
- if (!response || !response.order) {
36
- throw new Error("Order not found or access denied");
23
+ try {
24
+ if (guestToken && !token) {
25
+ const options = await getStoreClientOptionsWithToken(guestToken);
26
+ const { order } = await medusaOrderRetrieve(id, options, {
27
+ fields: MEDUSA_ORDER_DETAIL_FIELDS,
28
+ });
29
+ if (!order) {
30
+ throw new Error("Order not found or access denied");
31
+ }
32
+ return order;
37
33
  }
38
- return response.order;
39
- }
40
- // Regular logged-in user flow
41
- const headers = {
42
- ...(await getAuthHeaders()),
43
- };
44
- return sdk.client
45
- .fetch(`/store/orders/${id}`, {
46
- method: "GET",
47
- query: {
48
- fields: "id,display_id,customer_id,email,created_at,status,fulfillment_status,payment_status,currency_code,subtotal,shipping_total,tax_total,discount_total,metadata,total,*payment_collections.payments,*items,*items.metadata,*items.variant,*items.variant.images,*items.variant.product,*items.variant.product.variants,*items.product,*items.product.variants,*returns,*shipping_address,*billing_address,*region,*shipping_methods",
49
- },
50
- headers,
51
- next,
52
- cache: "no-store", // Changed from "force-cache" to "no-store" to always fetch fresh data
53
- })
54
- .then(({ order }) => {
34
+ const options = await getStoreCartClientOptions();
35
+ const { order } = await medusaOrderRetrieve(id, options, {
36
+ fields: MEDUSA_ORDER_DETAIL_FIELDS,
37
+ });
55
38
  return order;
56
- })
57
- .catch((err) => {
58
- return medusaError(err);
59
- });
39
+ }
40
+ catch (err) {
41
+ throwOrderError(err);
42
+ }
60
43
  };
61
44
  export const listOrders = async (limit = 10, offset = 0, filters) => {
62
- const headers = {
63
- ...(await getAuthHeaders()),
64
- };
65
- const next = {
66
- ...(await getCacheOptions("orders")),
67
- };
68
- return sdk.client
69
- .fetch(`/store/orders`, {
70
- method: "GET",
71
- query: {
45
+ try {
46
+ const options = await getStoreCartClientOptions();
47
+ const { orders } = await medusaOrderList(options, {
72
48
  limit,
73
49
  offset,
74
50
  order: "-created_at",
75
- fields: "*items,+items.metadata,*items.variant,*items.variant.images,*items.product,*returns",
76
51
  ...filters,
77
- },
78
- headers,
79
- next,
80
- cache: "no-store",
81
- })
82
- .then(({ orders }) => orders)
83
- .catch((err) => medusaError(err));
52
+ });
53
+ return orders;
54
+ }
55
+ catch (err) {
56
+ throwOrderError(err);
57
+ }
84
58
  };
85
59
  export const createTransferRequest = async (state, formData) => {
86
60
  const id = formData.get("order_id");
87
61
  if (!id) {
88
62
  return { success: false, error: "Order ID is required", order: null };
89
63
  }
90
- const headers = await getAuthHeaders();
91
- return await sdk.store.order
92
- .requestTransfer(id, {}, {
93
- fields: "id, email",
94
- }, headers)
95
- .then(({ order }) => ({ success: true, error: null, order }))
96
- .catch((err) => ({ success: false, error: err.message, order: null }));
64
+ try {
65
+ const options = await getStoreCartClientOptions();
66
+ const { order } = await medusaOrderRequestTransfer(id, options, {
67
+ fields: "id, email",
68
+ });
69
+ return {
70
+ success: true,
71
+ error: null,
72
+ order: order,
73
+ };
74
+ }
75
+ catch (err) {
76
+ return { success: false, error: err.message, order: null };
77
+ }
97
78
  };
98
79
  export const acceptTransferRequest = async (id, token) => {
99
- const headers = await getAuthHeaders();
100
- return await sdk.store.order
101
- .acceptTransfer(id, { token }, {}, headers)
102
- .then(({ order }) => ({ success: true, error: null, order }))
103
- .catch((err) => ({ success: false, error: err.message, order: null }));
80
+ try {
81
+ const options = await getStoreCartClientOptions();
82
+ const { order } = await medusaOrderAcceptTransfer(id, token, options);
83
+ return {
84
+ success: true,
85
+ error: null,
86
+ order: order,
87
+ };
88
+ }
89
+ catch (err) {
90
+ return { success: false, error: err.message, order: null };
91
+ }
104
92
  };
105
93
  export const declineTransferRequest = async (id, token) => {
106
- const headers = await getAuthHeaders();
107
- return await sdk.store.order
108
- .declineTransfer(id, { token }, {}, headers)
109
- .then(({ order }) => ({ success: true, error: null, order }))
110
- .catch((err) => ({ success: false, error: err.message, order: null }));
94
+ try {
95
+ const options = await getStoreCartClientOptions();
96
+ const { order } = await medusaOrderDeclineTransfer(id, token, options);
97
+ return {
98
+ success: true,
99
+ error: null,
100
+ order: order,
101
+ };
102
+ }
103
+ catch (err) {
104
+ return { success: false, error: err.message, order: null };
105
+ }
111
106
  };
112
107
  export const downloadInvoice = async (orderId) => {
113
108
  try {
114
109
  const cookieStore = await cookies();
115
110
  const token = cookieStore.get("_medusa_jwt")?.value;
116
- // Check for guest token if regular token is missing
117
111
  const guestToken = !token
118
- ? (cookieStore.get("_medusa_guest_jwt")?.value || cookieStore.get("_medusa_guest_token")?.value)
112
+ ? (cookieStore.get("_medusa_guest_jwt")?.value ||
113
+ cookieStore.get("_medusa_guest_token")?.value)
119
114
  : null;
120
- const headers = {
121
- "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,
122
- };
123
- let url = `/store/invoice/download/${orderId}`;
115
+ let arrayBuffer;
124
116
  if (token) {
125
- headers["Cookie"] = `_medusa_jwt=${token}`;
126
- headers["Authorization"] = `Bearer ${token}`;
117
+ const options = await getStoreClientOptionsWithToken(token);
118
+ arrayBuffer = await medusaOrderDownloadInvoice(orderId, options, false);
127
119
  }
128
120
  else if (guestToken) {
129
- // Use guest endpoint and token
130
- url = `/store/guest/invoice/download/${orderId}`;
131
- headers["Cookie"] = `_medusa_guest_jwt=${guestToken}`;
132
- headers["Authorization"] = `Bearer ${guestToken}`;
121
+ const options = await getStoreClientOptionsWithToken(guestToken);
122
+ arrayBuffer = await medusaOrderDownloadInvoice(orderId, options, true);
133
123
  }
134
- const backendUrl = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL || "http://localhost:9000";
135
- const response = await fetch(`${backendUrl}${url}`, {
136
- method: "GET",
137
- headers,
138
- cache: "no-store",
139
- });
140
- if (!response.ok) {
141
- throw new Error(`Failed to download invoice: ${response.status} ${response.statusText}`);
142
- }
143
- const contentType = response.headers.get("content-type");
144
- if (!contentType || !contentType.includes("application/pdf")) {
145
- throw new Error("Server returned non-PDF content");
146
- }
147
- const arrayBuffer = await response.arrayBuffer();
148
- if (arrayBuffer.byteLength === 0) {
149
- throw new Error("Generated PDF is empty");
124
+ else {
125
+ throw new Error("Unauthorized: No valid session found");
150
126
  }
151
127
  const base64 = Buffer.from(arrayBuffer).toString("base64");
152
128
  return { success: true, data: base64 };
@@ -155,210 +131,93 @@ export const downloadInvoice = async (orderId) => {
155
131
  return { success: false, error: error.message };
156
132
  }
157
133
  };
158
- /**
159
- * Cancel an order
160
- */
161
134
  export const cancelOrder = async (orderId, reasonId) => {
162
135
  try {
163
- const authHeaders = await getAuthHeaders();
164
- const cookiesStore = await cookies();
165
- const guestToken = cookiesStore.get("_medusa_guest_jwt")?.value || cookiesStore.get("_medusa_guest_token")?.value;
166
- const publishableKey = process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY;
167
- const backendUrl = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL || "http://localhost:9000";
168
- // 1. Regular logged-in user flow ALWAYS takes priority
169
- const token = cookiesStore.get("_medusa_jwt")?.value;
136
+ const cookieStore = await cookies();
137
+ const token = cookieStore.get("_medusa_jwt")?.value;
138
+ const guestOptions = await getGuestStoreClientOptions();
139
+ let finalReasonId = reasonId;
140
+ if (!finalReasonId) {
141
+ const reasons = await listReturnReasons();
142
+ finalReasonId = reasons.find((r) => r.value === "other")?.id || reasons[0]?.id || "other";
143
+ }
170
144
  if (token) {
171
- let finalReasonId = reasonId;
172
- if (!finalReasonId) {
173
- const reasons = await listReturnReasons();
174
- finalReasonId = reasons.find(r => r.value === "other")?.id || reasons[0]?.id || "other";
175
- }
176
- const headers = {
177
- "Content-Type": "application/json",
178
- "x-publishable-api-key": publishableKey,
179
- "Authorization": `Bearer ${token}`
180
- };
181
- // Try the primary endpoint
182
- let response = await fetch(`${backendUrl}/store/orders/cancel/${orderId}`, {
183
- method: "POST",
184
- headers,
185
- body: JSON.stringify({ reason_id: finalReasonId }),
186
- cache: "no-store",
187
- });
188
- // If the first endpoint fails with 404 or a resolution error, try the alternative format
189
- if (!response.ok) {
190
- const errorData = await response.json().catch(() => ({}));
191
- if (response.status === 404 || (errorData.message && errorData.message.includes("resolve"))) {
192
- const altResponse = await fetch(`${backendUrl}/store/orders/${orderId}/cancel`, {
193
- method: "POST",
194
- headers,
195
- body: JSON.stringify({ reason_id: finalReasonId }),
196
- cache: "no-store",
197
- });
198
- if (altResponse.ok)
199
- return { success: true };
200
- // If both fail, return the error from the second attempt
201
- const altError = await altResponse.json().catch(() => ({ message: "Failed to cancel order" }));
202
- return { success: false, error: altError.message || "Failed to cancel order" };
203
- }
204
- return { success: false, error: errorData.message || "Failed to cancel order" };
205
- }
145
+ const options = await getStoreClientOptionsWithToken(token);
146
+ await medusaOrderCancel(orderId, finalReasonId, options);
206
147
  return { success: true };
207
148
  }
208
- // 2. Only if NOT logged in, check for guest user token
209
- if (guestToken) {
210
- let finalReasonId = reasonId;
211
- if (!finalReasonId) {
212
- const reasons = await listReturnReasons();
213
- finalReasonId = reasons.find(r => r.value === "other")?.id || reasons[0]?.id || "other";
214
- }
215
- // Try guest endpoint
216
- const response = await fetch(`${backendUrl}/store/guest-orders/${orderId}/cancel`, {
217
- method: "POST",
218
- headers: {
219
- "Content-Type": "application/json",
220
- "x-publishable-api-key": publishableKey,
221
- "Authorization": `Bearer ${guestToken}`
222
- },
223
- body: JSON.stringify({ reason_id: finalReasonId }),
224
- cache: "no-store",
225
- });
226
- if (!response.ok) {
227
- // Fallback for guest as well
228
- const altResponse = await fetch(`${backendUrl}/store/guest/orders/${orderId}/cancel`, {
229
- method: "POST",
230
- headers: {
231
- "Content-Type": "application/json",
232
- "x-publishable-api-key": publishableKey,
233
- "Authorization": `Bearer ${guestToken}`
234
- },
235
- body: JSON.stringify({ reason_id: finalReasonId }),
236
- cache: "no-store",
237
- });
238
- if (altResponse.ok)
239
- return { success: true };
240
- return { success: false, error: "Failed to cancel order" };
241
- }
149
+ if (guestOptions) {
150
+ await medusaGuestOrderCancel(orderId, finalReasonId, guestOptions);
242
151
  return { success: true };
243
152
  }
244
- // 3. Neither token found
245
153
  return { success: false, error: "Unauthorized: No valid session found" };
246
154
  }
247
155
  catch (error) {
248
156
  return { success: false, error: error.message };
249
157
  }
250
158
  };
251
- /**
252
- * Reorder an order (supports both logged-in and guest users)
253
- */
254
159
  export const reorderOrder = async (orderId, skipVariantIds, forceReorder = false) => {
255
160
  try {
256
161
  const cookieStore = await cookies();
257
162
  const token = cookieStore.get("_medusa_jwt")?.value;
258
- // Check for guest token if regular token is missing
259
- const guestToken = !token
260
- ? (cookieStore.get("_medusa_guest_jwt")?.value || cookieStore.get("_medusa_guest_token")?.value)
261
- : null;
262
- const publishableKey = process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY;
263
- const backendUrl = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL || "http://localhost:9000";
264
- const headers = {
265
- "Content-Type": "application/json",
266
- "x-publishable-api-key": publishableKey,
267
- };
268
- // Determine the correct endpoint based on user type
269
- let url = `${backendUrl}/store/orders/reorder/${orderId}`;
163
+ const guestOptions = await getGuestStoreClientOptions();
164
+ let result;
270
165
  if (token) {
271
- // IMPORTANT: The Order Management plugin requires an explicit Bearer token
272
- // in the Authorization header to identify actor_id. Using getAuthHeaders()
273
- // alone (which is cookie-based) is not enough for this custom endpoint.
274
- headers["Authorization"] = `Bearer ${token}`;
166
+ const options = await getStoreClientOptionsWithToken(token);
167
+ result = await medusaOrderReorder(orderId, options, { force_reorder: forceReorder });
275
168
  }
276
- else if (guestToken) {
277
- // Use guest reorder endpoint
278
- url = `${backendUrl}/store/guest-orders/${orderId}/reorder`;
279
- headers["Authorization"] = `Bearer ${guestToken}`;
169
+ else if (guestOptions) {
170
+ result = await medusaGuestOrderReorder(orderId, guestOptions, {
171
+ force_reorder: forceReorder,
172
+ });
280
173
  }
281
174
  else {
282
175
  return { success: false, error: "Unauthorized: Please log in to reorder." };
283
176
  }
284
- // Add force_reorder query param if requested
285
- if (forceReorder) {
286
- url += `?force_reorder=true`;
287
- }
288
- // Call the plugin's reorder endpoint (adds all items)
289
- const response = await fetch(url, {
290
- method: "POST",
291
- headers,
292
- cache: "no-store",
293
- });
294
- if (!response.ok) {
295
- const errorBody = await response.json().catch(() => null);
296
- // Handle 409 Conflict - Inventory Issues
297
- if (response.status === 409 && errorBody?.inventory_issues) {
177
+ if (!result.ok) {
178
+ if (result.status === 409 && result.data.inventory_issues) {
298
179
  return {
299
180
  success: false,
300
181
  error: "Inventory issues found",
301
- inventory_issues: errorBody.inventory_issues
182
+ inventory_issues: result.data.inventory_issues,
302
183
  };
303
184
  }
304
- const errorMsg = errorBody?.message || "Failed to reorder";
305
- return { success: false, error: errorMsg };
185
+ return { success: false, error: result.data.message || "Failed to reorder" };
306
186
  }
307
- const data = await response.json();
308
- // Support multiple response formats: data.cart.id, data.id, or data.cart_id
309
- const newCartId = data.cart?.id || data.id || data.cart_id || (data.reorder?.cart_id);
310
- // Set the cart ID in cookies and revalidate
187
+ const data = result.data;
188
+ const newCartId = extractReorderCartId(data);
189
+ const cartOptions = token
190
+ ? await getStoreClientOptionsWithToken(token)
191
+ : guestOptions;
311
192
  if (newCartId) {
312
- // 1. Tag the cart as Buy Now to prevent merging and allow auto-restore,
313
- // and add is_reorder flag to distinguish it
314
193
  try {
315
- await sdk.store.cart.update(newCartId, {
316
- metadata: {
317
- is_reorder: true
318
- }
319
- }, {}, {
320
- ...headers,
321
- cache: "no-store",
322
- });
323
- // 2. Ensure this new cart is not merged with existing ones (CRITICAL for Buy Now flow)
324
- await sdk.client.fetch(`/store/carts/merge/skip`, {
325
- method: "POST",
326
- body: { cart_id: newCartId },
327
- headers: headers,
328
- });
194
+ await medusaCartUpdate(newCartId, { metadata: { is_reorder: true } }, cartOptions);
195
+ await medusaCartSkipMerge(newCartId, cartOptions);
329
196
  }
330
197
  catch (updateErr) {
331
198
  console.error("[Reorder] Error updating cart metadata or skipping merge:", updateErr);
332
199
  }
333
- // FALLBACK: If skipVariantIds were provided but the plugin added everything,
334
- // we manually remove the unwanted items from the new cart.
335
200
  if (skipVariantIds && skipVariantIds.length > 0) {
336
201
  try {
337
- // Fetch the new cart to find line item IDs
338
- const { cart } = await sdk.store.cart.retrieve(newCartId, {}, {
339
- ...headers,
340
- });
341
- if (cart && cart.items) {
342
- const itemsToRemove = cart.items.filter(item => item.variant_id && skipVariantIds.includes(item.variant_id));
343
- // Delete unwanted items one by one
344
- for (const item of itemsToRemove) {
345
- await sdk.store.cart.deleteLineItem(newCartId, item.id, {}, {
346
- ...headers,
347
- });
202
+ const { cart } = await medusaCartRetrieve(newCartId, cartOptions);
203
+ const items = cart.items ?? [];
204
+ for (const item of items) {
205
+ const variantId = item.variant_id;
206
+ const lineId = item.id;
207
+ if (variantId &&
208
+ lineId &&
209
+ skipVariantIds.includes(variantId)) {
210
+ await medusaCartRemoveLineItem(newCartId, lineId, cartOptions);
348
211
  }
349
212
  }
350
213
  }
351
214
  catch (removeErr) {
352
215
  console.error("[Reorder] Error removing skipped items:", removeErr);
353
- // We continue anyway since the cart is created
354
216
  }
355
217
  }
356
- // Use buy_now_cart_id instead of overwriting main cart
357
218
  await removeBuyNowCartId();
358
219
  await setBuyNowCartId(newCartId);
359
- // Revalidate standard carts tag
360
220
  revalidateTag("carts");
361
- // Also revalidate specific cache tag if available
362
221
  const cartCacheTag = await getCacheTag("carts");
363
222
  if (cartCacheTag)
364
223
  revalidateTag(cartCacheTag);
@@ -1,5 +1,5 @@
1
- export declare const listPaymentDetails: () => Promise<any>;
2
- export declare const createPaymentDetail: (type: "upi" | "bank" | "card", detail_json: Record<string, string>) => Promise<any>;
3
- export declare const makeDefaultPaymentDetail: (id: string) => Promise<any>;
4
- export declare const deletePaymentDetail: (id: string) => Promise<any>;
1
+ export declare const listPaymentDetails: () => Promise<import("medusa-services/payment").StorePaymentDetail[]>;
2
+ export declare const createPaymentDetail: (type: "upi" | "bank" | "card", detail_json: Record<string, string>) => Promise<Record<string, unknown>>;
3
+ export declare const makeDefaultPaymentDetail: (id: string) => Promise<Record<string, unknown>>;
4
+ export declare const deletePaymentDetail: (id: string) => Promise<void>;
5
5
  //# sourceMappingURL=payment-details.d.ts.map