@pradip1995/commerce-core 1.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 (82) hide show
  1. package/README.md +15 -0
  2. package/package.json +70 -0
  3. package/src/analytics/ga4-ecommerce.ts +96 -0
  4. package/src/config.ts +36 -0
  5. package/src/constants.tsx +84 -0
  6. package/src/context/modal-context.tsx +40 -0
  7. package/src/context/wishlist-context.tsx +96 -0
  8. package/src/data/cart/abandoned.ts +111 -0
  9. package/src/data/cart/buyNow.ts +184 -0
  10. package/src/data/cart/checkout.ts +487 -0
  11. package/src/data/cart/index.ts +7 -0
  12. package/src/data/cart/mutations.ts +189 -0
  13. package/src/data/cart/promotions.ts +121 -0
  14. package/src/data/cart/region.ts +66 -0
  15. package/src/data/cart/retrieve.ts +162 -0
  16. package/src/data/categories.ts +90 -0
  17. package/src/data/collections.ts +109 -0
  18. package/src/data/contact.ts +143 -0
  19. package/src/data/cookies.ts +170 -0
  20. package/src/data/customer-registration.ts +365 -0
  21. package/src/data/customer.ts +638 -0
  22. package/src/data/dynamic-config.ts +420 -0
  23. package/src/data/fulfillment.ts +95 -0
  24. package/src/data/guest.ts +357 -0
  25. package/src/data/locale-actions.ts +74 -0
  26. package/src/data/locales.ts +28 -0
  27. package/src/data/newsletter.ts +41 -0
  28. package/src/data/notifications.ts +22 -0
  29. package/src/data/onboarding.ts +9 -0
  30. package/src/data/orders.ts +500 -0
  31. package/src/data/payment-details.ts +68 -0
  32. package/src/data/payment.ts +32 -0
  33. package/src/data/products.ts +424 -0
  34. package/src/data/regions.ts +64 -0
  35. package/src/data/returns.ts +305 -0
  36. package/src/data/reviews.ts +279 -0
  37. package/src/data/swaps.ts +154 -0
  38. package/src/data/variants.ts +38 -0
  39. package/src/data/wishlist.ts +292 -0
  40. package/src/domain/cart/abandoned-carts.ts +49 -0
  41. package/src/domain/cart/buy-now.ts +15 -0
  42. package/src/domain/cart/checkout.ts +25 -0
  43. package/src/domain/cart/index.ts +8 -0
  44. package/src/domain/cart/metadata.ts +21 -0
  45. package/src/domain/cart/payment.ts +21 -0
  46. package/src/domain/cart/phone.ts +17 -0
  47. package/src/domain/cart/reorder.ts +19 -0
  48. package/src/domain/cart/validation.ts +43 -0
  49. package/src/domain/product/pricing.ts +49 -0
  50. package/src/domain/product/variant-selection.ts +193 -0
  51. package/src/firebase.ts +48 -0
  52. package/src/hooks/index.ts +8 -0
  53. package/src/hooks/use-add-to-cart.ts +63 -0
  54. package/src/hooks/use-cart.ts +132 -0
  55. package/src/hooks/use-checkout.ts +62 -0
  56. package/src/hooks/use-in-view.tsx +29 -0
  57. package/src/hooks/use-product-actions.ts +190 -0
  58. package/src/hooks/use-product-reviews.ts +18 -0
  59. package/src/hooks/use-product-variant.ts +142 -0
  60. package/src/hooks/use-server-action.ts +30 -0
  61. package/src/hooks/use-toggle-state.tsx +46 -0
  62. package/src/hooks/use-wishlist.ts +3 -0
  63. package/src/theme/inline-vars.ts +12 -0
  64. package/src/types/account.ts +21 -0
  65. package/src/types/cart.ts +13 -0
  66. package/src/types/home.ts +52 -0
  67. package/src/types/layout.ts +29 -0
  68. package/src/types/product-card.ts +17 -0
  69. package/src/util/compare-addresses.ts +28 -0
  70. package/src/util/env.ts +3 -0
  71. package/src/util/get-locale-header.ts +8 -0
  72. package/src/util/get-percentage-diff.ts +6 -0
  73. package/src/util/get-product-price.ts +78 -0
  74. package/src/util/google-oauth.ts +28 -0
  75. package/src/util/isEmpty.ts +11 -0
  76. package/src/util/medusa-error.ts +18 -0
  77. package/src/util/money.ts +26 -0
  78. package/src/util/order-status.tsx +179 -0
  79. package/src/util/product.ts +431 -0
  80. package/src/util/repeat.ts +5 -0
  81. package/src/util/returns.ts +71 -0
  82. package/src/util/sort-products.ts +48 -0
@@ -0,0 +1,424 @@
1
+ "use server"
2
+
3
+ import { sdk } from "@core/config"
4
+ import { sortProducts } from "@core/util/sort-products"
5
+ import { HttpTypes } from "@medusajs/types"
6
+ import { SortOptions } from "@modules/store/components/refinement-list/sort-products"
7
+ import { getAuthHeaders, getCacheOptions } from "./cookies"
8
+ import { getRegion, retrieveRegion } from "./regions"
9
+ import Color from "color"
10
+
11
+ export const listProducts = async ({
12
+ pageParam = 1,
13
+ queryParams,
14
+ countryCode,
15
+ regionId,
16
+ }: {
17
+ pageParam?: number
18
+ queryParams?: HttpTypes.FindParams & HttpTypes.StoreProductListParams
19
+ countryCode?: string
20
+ regionId?: string
21
+ }): Promise<{
22
+ response: { products: HttpTypes.StoreProduct[]; count: number }
23
+ nextPage: number | null
24
+ queryParams?: HttpTypes.FindParams & HttpTypes.StoreProductListParams
25
+ }> => {
26
+ if (!countryCode && !regionId) {
27
+ throw new Error("Country code or region ID is required")
28
+ }
29
+
30
+ const limit = queryParams?.limit || 12
31
+ const _pageParam = Math.max(pageParam, 1)
32
+ const offset = _pageParam === 1 ? 0 : (_pageParam - 1) * limit
33
+
34
+ let region: HttpTypes.StoreRegion | undefined | null
35
+
36
+ if (countryCode) {
37
+ region = await getRegion(countryCode)
38
+ } else {
39
+ region = await retrieveRegion(regionId!)
40
+ }
41
+
42
+ if (!region) {
43
+ return {
44
+ response: { products: [], count: 0 },
45
+ nextPage: null,
46
+ }
47
+ }
48
+
49
+ const headers = {
50
+ ...(await getAuthHeaders()),
51
+ }
52
+
53
+ const next = {
54
+ ...(await getCacheOptions("products")),
55
+ }
56
+
57
+ // 1. Standard Medusa query parameters
58
+ const standardQuery: any = {
59
+ limit,
60
+ offset,
61
+ region_id: region?.id,
62
+ fields:
63
+ "*variants.calculated_price,+variants.inventory_quantity,*variants.images,+variants.metadata,+variants.options,+metadata,+tags,+average_rating,+total_rating_count,+total_rating_sum,",
64
+ }
65
+
66
+ // 2. Identify advanced filters that require the product-helper API
67
+ const advancedFilterKeys = [
68
+ "metadata",
69
+ "min_price",
70
+ "max_price",
71
+ "q",
72
+ "collection_id",
73
+ "category_id",
74
+ "tags",
75
+ "option_value",
76
+ "gender",
77
+ "color",
78
+ "material",
79
+ "style",
80
+ "brand",
81
+ "type",
82
+ "product_type",
83
+ "order",
84
+ ]
85
+
86
+ const hasAdvancedFilters = !!(
87
+ queryParams &&
88
+ Object.keys(queryParams).some(
89
+ (key) =>
90
+ advancedFilterKeys.includes(key) && (queryParams as any)[key] !== undefined
91
+ )
92
+ )
93
+
94
+ const endpoint = hasAdvancedFilters
95
+ ? "/store/product-helper/products"
96
+ : "/store/products"
97
+
98
+ let finalQuery: any = { ...standardQuery }
99
+
100
+ if (hasAdvancedFilters) {
101
+ // We use URLSearchParams to ensure correct formatting and handle repeated keys if needed
102
+ const params = new URLSearchParams()
103
+
104
+ // 1. Add standard params
105
+ params.append("limit", limit.toString())
106
+ params.append("offset", offset.toString())
107
+ if (region?.id) params.append("region_id", region.id)
108
+
109
+ // Use '*' for helper endpoint to let it resolve necessary relations
110
+ params.append("fields", "*")
111
+
112
+ // 2. Map queryParams
113
+ for (const [key, value] of Object.entries(queryParams || {})) {
114
+ if (
115
+ [
116
+ "metadata",
117
+ "min_price",
118
+ "max_price",
119
+ "limit",
120
+ "offset",
121
+ "region_id",
122
+ "fields",
123
+ ].includes(key)
124
+ )
125
+ continue
126
+
127
+ const values = Array.isArray(value) ? value : [value]
128
+ const lowerKey = key.toLowerCase()
129
+
130
+ if (lowerKey === "color") {
131
+ // Map 'color' filter to 'option_value' which backend understands for variants
132
+ values.forEach((v) => params.append("option_value[]", String(v)))
133
+ } else if (
134
+ ["material", "gender", "product_type", "type", "style", "brand"].includes(
135
+ lowerKey
136
+ )
137
+ ) {
138
+ // Map these to metadata as they are defined as metadata in your config
139
+ const metaKey = lowerKey === "type" ? "product_type" : lowerKey
140
+ values.forEach((v) => params.append(`metadata[${metaKey}]`, String(v)))
141
+ } else {
142
+ // Standard mapping for others (tags, collection_id, etc.)
143
+ if (Array.isArray(value)) {
144
+ value.forEach((v) => params.append(`${key}[]`, String(v)))
145
+ } else if (value !== undefined && value !== null) {
146
+ params.append(key, String(value))
147
+ }
148
+ }
149
+ }
150
+
151
+ // 3. Map price filters (min_price -> price_min, max_price -> price_max)
152
+ if ((queryParams as any).min_price)
153
+ params.append("price_min", String((queryParams as any).min_price))
154
+ if ((queryParams as any).max_price)
155
+ params.append("price_max", String((queryParams as any).max_price))
156
+
157
+ // 4. Map metadata filters to metadata[key] format
158
+ if ((queryParams as any).metadata) {
159
+ for (const [key, value] of Object.entries((queryParams as any).metadata)) {
160
+ const values = Array.isArray(value) ? value : [value]
161
+
162
+ values.forEach((v) => {
163
+ if (key.toLowerCase() === "color") {
164
+ // Map color in metadata to option_value[]
165
+ params.append("option_value[]", String(v))
166
+ } else {
167
+ // Standard metadata format: metadata[key]=value
168
+ params.append(`metadata[${key}]`, String(v))
169
+ }
170
+ })
171
+ }
172
+ }
173
+
174
+ finalQuery = params
175
+ } else {
176
+ // Standard endpoint - only merge known safe Medusa keys from queryParams
177
+ // to avoid "Unrecognized fields" errors
178
+ const safeKeys = [
179
+ "order",
180
+ "id",
181
+ "handle",
182
+ "status",
183
+ "created_at",
184
+ "updated_at",
185
+ "type_id",
186
+ ]
187
+ for (const key of safeKeys) {
188
+ if (queryParams && (queryParams as any)[key]) {
189
+ finalQuery[key] = (queryParams as any)[key]
190
+ }
191
+ }
192
+ }
193
+
194
+ // Use the appended query string to avoid SDK's default serialization issues with brackets
195
+ const requestUrl = hasAdvancedFilters
196
+ ? `${endpoint}?${finalQuery.toString()}`
197
+ : endpoint
198
+
199
+ return sdk.client
200
+ .fetch<{ products: HttpTypes.StoreProduct[]; count: number }>(requestUrl, {
201
+ method: "GET",
202
+ query: hasAdvancedFilters ? undefined : finalQuery,
203
+ headers,
204
+ next: {
205
+ ...next,
206
+ revalidate: 0, // Disable Next.js cache for now to show logs
207
+ },
208
+ cache: "no-store", // Ensure it hits backend every time for testing
209
+ })
210
+ .then(({ products, count }) => {
211
+ const nextPage = count > offset + limit ? _pageParam + 1 : null
212
+
213
+ if (products && products.length > 0) {
214
+ }
215
+
216
+ return {
217
+ response: {
218
+ products: products || [],
219
+ count: count || 0,
220
+ },
221
+ nextPage: nextPage,
222
+ queryParams,
223
+ }
224
+ })
225
+ .catch((error) => {
226
+ throw error
227
+ })
228
+ }
229
+
230
+ /**
231
+ * This will fetch 100 products to the Next.js cache and sort them based on the sortBy parameter.
232
+ * It will then return the paginated products based on the page and limit parameters.
233
+ */
234
+ export const listProductsWithSort = async ({
235
+ page = 1,
236
+ queryParams,
237
+ sortBy = "created_at_desc",
238
+ countryCode,
239
+ }: {
240
+ page?: number
241
+ queryParams?: HttpTypes.FindParams & HttpTypes.StoreProductParams
242
+ sortBy?: SortOptions
243
+ countryCode: string
244
+ }): Promise<{
245
+ response: { products: HttpTypes.StoreProduct[]; count: number }
246
+ nextPage: number | null
247
+ queryParams?: HttpTypes.FindParams & HttpTypes.StoreProductParams
248
+ }> => {
249
+ const limit = queryParams?.limit || 12
250
+
251
+ // Directly fetch from backend with correct pagination
252
+ // This ensures the backend terminal logs the specific request
253
+ const {
254
+ response: { products, count },
255
+ } = await listProducts({
256
+ pageParam: page,
257
+ queryParams: {
258
+ ...queryParams,
259
+ limit,
260
+ },
261
+ countryCode,
262
+ })
263
+
264
+ // Sorting is now handled natively by the backend API via the 'order' query param.
265
+ const finalProducts = products
266
+
267
+ const nextPage = count > page * limit ? page + 1 : null
268
+
269
+ return {
270
+ response: {
271
+ products: finalProducts,
272
+ count,
273
+ },
274
+ nextPage,
275
+ queryParams,
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Fetch products that have a specific tag value
281
+ */
282
+ export async function getProductsByTag({
283
+ tagValue,
284
+ limit = 12,
285
+ countryCode,
286
+ }: {
287
+ tagValue: string
288
+ limit?: number
289
+ countryCode: string
290
+ }) {
291
+ try {
292
+ const result = await listProducts({
293
+ queryParams: { tags: [tagValue], limit },
294
+ countryCode,
295
+ })
296
+
297
+ return result.response.products
298
+ } catch (error) {
299
+ console.error("Error fetching products by tag:", error)
300
+ return []
301
+ }
302
+ }
303
+
304
+ /**
305
+ * Fetch dynamic filter options from the backend API
306
+ */
307
+ export const getDynamicFilters = async (countryCode: string) => {
308
+ const backendUrl = process.env.MEDUSA_BACKEND_URL || "http://localhost:9000"
309
+ const publishableKey = process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY
310
+
311
+ try {
312
+ if (!publishableKey)
313
+ return { genders: [], productTypes: [], materials: [], colors: [] }
314
+
315
+ const response = await fetch(`${backendUrl}/store/product-helper/filters`, {
316
+ method: "GET",
317
+ headers: {
318
+ "Content-Type": "application/json",
319
+ "x-publishable-api-key": publishableKey,
320
+ },
321
+ cache: "no-store",
322
+ })
323
+
324
+ if (!response.ok) {
325
+ return { genders: [], productTypes: [], materials: [], colors: [] }
326
+ }
327
+
328
+ const data = await response.json()
329
+
330
+ const formatLabel = (str: string) => {
331
+ return str
332
+ .split(/[_-]/)
333
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
334
+ .join(" ")
335
+ }
336
+
337
+ const metadata = data.metadata || {}
338
+ const variantOptions = data.variant_options || []
339
+
340
+ // Gather all unique colors from all possible sources
341
+ const colorSet = new Set<string>()
342
+
343
+ // 1. From variant options (check all options with title 'color')
344
+ variantOptions.forEach((o: any) => {
345
+ if (
346
+ o.option_title.toLowerCase() === "color" ||
347
+ o.option_title.toLowerCase() === "colour"
348
+ ) {
349
+ o.values?.forEach((v: string) => {
350
+ if (v) colorSet.add(v.trim().toLowerCase())
351
+ })
352
+ }
353
+ })
354
+
355
+ // 2. From metadata colors (handle newline/comma separated values)
356
+ if (metadata.color) {
357
+ metadata.color.forEach((c: string) => {
358
+ if (c) {
359
+ const parts = c
360
+ .split(/[,/\n\r]+/)
361
+ .map((s) => s.trim())
362
+ .filter(Boolean)
363
+ parts.forEach((p) => colorSet.add(p.toLowerCase()))
364
+ }
365
+ })
366
+ }
367
+
368
+ return {
369
+ genders: (metadata.gender || []).sort().map((g: string) => ({
370
+ value: g,
371
+ label: formatLabel(g),
372
+ })),
373
+ productTypes: (data.product_types || [])
374
+ .sort((a: any, b: any) => a.label.localeCompare(b.label))
375
+ .map((t: any) => ({
376
+ value: t.label,
377
+ label: formatLabel(t.label),
378
+ })),
379
+ materials: (metadata.material || []).sort().map((m: string) => ({
380
+ value: m,
381
+ label: formatLabel(m),
382
+ })),
383
+ colors: Array.from(colorSet)
384
+ .sort()
385
+ .map((c: string) => {
386
+ let hex = ""
387
+ try {
388
+ // Try to resolve color hex code using the Color library
389
+ hex = Color(c.replace(/\s+/g, "").toLowerCase()).hex()
390
+ } catch (e) {
391
+ try {
392
+ hex = Color(c.toLowerCase()).hex()
393
+ } catch (e2) {
394
+ // No hex found
395
+ }
396
+ }
397
+ return {
398
+ value: c,
399
+ label: formatLabel(c),
400
+ hex,
401
+ }
402
+ }),
403
+ }
404
+ } catch (error) {
405
+ console.error("Error fetching dynamic filters:", error)
406
+ return { genders: [], productTypes: [], materials: [], colors: [] }
407
+ }
408
+ }
409
+
410
+ /**
411
+ * Fetch a single product by its handle
412
+ */
413
+ export async function getProductByHandle(handle: string) {
414
+ const result = await sdk.store.product.list(
415
+ {
416
+ handle,
417
+ fields:
418
+ "*variants.calculated_price,+variants.inventory_quantity,+variants.manage_inventory,+variants.allow_backorder,*variants.options,*options,*options.values,*images,*thumbnail,+metadata",
419
+ },
420
+ { next: { tags: ["products"] } }
421
+ )
422
+
423
+ return result.products[0]
424
+ }
@@ -0,0 +1,64 @@
1
+ "use server"
2
+
3
+ import { sdk } from "@core/config"
4
+ import medusaError from "@core/util/medusa-error"
5
+ import { HttpTypes } from "@medusajs/types"
6
+ import { getCacheOptions } from "./cookies"
7
+
8
+ export const listRegions = async () => {
9
+ const next = {
10
+ ...(await getCacheOptions("regions")),
11
+ }
12
+
13
+ return sdk.client
14
+ .fetch<{ regions: HttpTypes.StoreRegion[] }>(`/store/regions`, {
15
+ method: "GET",
16
+ next,
17
+ cache: "force-cache",
18
+ })
19
+ .then(({ regions }) => regions)
20
+ .catch(medusaError)
21
+ }
22
+
23
+ export const retrieveRegion = async (id: string) => {
24
+ const next = {
25
+ ...(await getCacheOptions(["regions", id].join("-"))),
26
+ }
27
+
28
+ return sdk.client
29
+ .fetch<{ region: HttpTypes.StoreRegion }>(`/store/regions/${id}`, {
30
+ method: "GET",
31
+ next,
32
+ cache: "force-cache",
33
+ })
34
+ .then(({ region }) => region)
35
+ .catch(medusaError)
36
+ }
37
+
38
+ const regionMap = new Map<string, HttpTypes.StoreRegion>()
39
+
40
+ export const getRegion = async (countryCode: string) => {
41
+ try {
42
+ if (regionMap.has(countryCode)) {
43
+ return regionMap.get(countryCode)
44
+ }
45
+
46
+ const regions = await listRegions()
47
+
48
+ if (!regions) {
49
+ return null
50
+ }
51
+
52
+ regions.forEach((region) => {
53
+ region.countries?.forEach((c) => {
54
+ regionMap.set(c?.iso_2 ?? "", region)
55
+ })
56
+ })
57
+
58
+ const region = countryCode ? regionMap.get(countryCode) : regionMap.get("us")
59
+
60
+ return region
61
+ } catch (e: any) {
62
+ return null
63
+ }
64
+ }