first commit

This commit is contained in:
Nermin Karic
2026-11-22 21:49:17 +01:00
commit f5e2fcbf98
693 changed files with 82975 additions and 0 deletions

View File

@@ -0,0 +1,82 @@
"use server"
import { sdk } from "@lib/config"
import { isAdyen } from "@lib/constants"
import { HttpTypes } from "@medusajs/types"
import { unstable_rethrow } from "next/navigation"
import { placeOrder } from "./cart"
import { getAuthHeaders, getCartId } from "./cookies"
export type AdyenPaymentResult =
| { resultCode: string; action: Record<string, unknown> }
| { error: string }
const DECLINED_ERROR =
"Your payment was declined. Please try again or use a different payment method."
const GENERIC_ERROR =
"We couldn't process your payment. Please try again or use a different payment method."
const getAdyenSession = async (cartId: string) => {
// The default fields include the payment collection and its sessions. Medusa Cloud's firewall
// rejects a `fields` query that names `payment_collection` more than once, so none is passed.
const { cart } = await sdk.client.fetch<HttpTypes.StoreCartResponse>(
`/store/carts/${cartId}`,
{
method: "GET",
headers: { ...(await getAuthHeaders()) },
cache: "no-store",
}
)
const session = cart.payment_collection?.payment_sessions?.find((s) =>
isAdyen(s.provider_id)
)
return session && { collectionId: cart.payment_collection!.id, session }
}
/**
* Passes the data that Adyen's Drop-in collected to the cart's Adyen payment session,
* then completes the cart, which redirects to the order confirmation once the payment
* is authorized. Otherwise, returns the action Drop-in has to handle, such as a 3D
* Secure challenge, or an error to show.
*/
export async function submitAdyenPayment(
clientData: Record<string, unknown>,
cartId?: string
): Promise<AdyenPaymentResult> {
const id = cartId || (await getCartId())
const current = id ? await getAdyenSession(id) : undefined
if (!id || !current) {
return { error: GENERIC_ERROR }
}
try {
await sdk.store.payment.updatePaymentSession(
current.collectionId,
current.session.id,
{ client_data: clientData },
{},
{ ...(await getAuthHeaders()) }
)
await placeOrder(id)
} catch (error) {
unstable_rethrow(error)
}
const updated = await getAdyenSession(id)
const data = updated?.session.data
if (updated?.session.status === "requires_more" && data?.action) {
return {
resultCode: data.result_code as string,
action: data.action as Record<string, unknown>,
}
}
return {
error: updated?.session.status === "error" ? DECLINED_ERROR : GENERIC_ERROR,
}
}

View File

@@ -0,0 +1,483 @@
"use server"
import { sdk } from "@lib/config"
import medusaError from "@lib/util/medusa-error"
import { HttpTypes } from "@medusajs/types"
import { revalidateTag } from "next/cache"
import { redirect } from "next/navigation"
import {
getAuthHeaders,
getCacheOptions,
getCacheTag,
getCartId,
removeCartId,
setCartId,
} from "./cookies"
import { getRegion } from "./regions"
import { getLocale } from "./locale-actions"
/**
* Retrieves a cart by its ID. If no ID is provided, it will use the cart ID from the cookies.
* @param cartId - optional - The ID of the cart to retrieve.
* @returns The cart object if found, or null if not found.
*/
export async function retrieveCart(cartId?: string, fields?: string) {
const id = cartId || (await getCartId())
fields ??=
"*items, *region, *items.product, *items.variant, *items.thumbnail, *items.metadata, +items.total, *promotions, +shipping_methods.name"
if (!id) {
return null
}
const headers = {
...(await getAuthHeaders()),
}
const next = {
...(await getCacheOptions("carts")),
}
return await sdk.client
.fetch<HttpTypes.StoreCartResponse>(`/store/carts/${id}`, {
method: "GET",
query: {
fields,
},
headers,
next,
cache: "force-cache",
})
.then(({ cart }: { cart: HttpTypes.StoreCart }) => cart)
.catch(() => null)
}
export async function getOrSetCart(countryCode: string) {
const region = await getRegion(countryCode)
if (!region) {
throw new Error(`Region not found for country code: ${countryCode}`)
}
let cart = await retrieveCart(undefined, "id,region_id")
const headers = {
...(await getAuthHeaders()),
}
if (!cart) {
const locale = await getLocale()
const cartResp = await sdk.store.cart.create(
{ region_id: region.id, locale: locale || undefined },
{},
headers
)
cart = cartResp.cart
await setCartId(cart.id)
const cartCacheTag = await getCacheTag("carts")
revalidateTag(cartCacheTag, { expire: 0 })
}
if (cart && cart?.region_id !== region.id) {
await sdk.store.cart.update(cart.id, { region_id: region.id }, {}, headers)
const cartCacheTag = await getCacheTag("carts")
revalidateTag(cartCacheTag, { expire: 0 })
}
return cart
}
export async function updateCart(data: HttpTypes.StoreUpdateCart) {
const cartId = await getCartId()
if (!cartId) {
throw new Error("No existing cart found, please create one before updating")
}
const headers = {
...(await getAuthHeaders()),
}
return sdk.store.cart
.update(cartId, data, {}, headers)
.then(async ({ cart }: { cart: HttpTypes.StoreCart }) => {
const cartCacheTag = await getCacheTag("carts")
revalidateTag(cartCacheTag, { expire: 0 })
const fulfillmentCacheTag = await getCacheTag("fulfillment")
revalidateTag(fulfillmentCacheTag, { expire: 0 })
return cart
})
.catch(medusaError)
}
export async function addToCart({
variantId,
quantity,
countryCode,
}: {
variantId: string
quantity: number
countryCode: string
}) {
if (!variantId) {
throw new Error("Missing variant ID when adding to cart")
}
const cart = await getOrSetCart(countryCode)
if (!cart) {
throw new Error("Error retrieving or creating cart")
}
const headers = {
...(await getAuthHeaders()),
}
await sdk.store.cart
.createLineItem(
cart.id,
{
variant_id: variantId,
quantity,
},
{},
headers
)
.then(async () => {
const cartCacheTag = await getCacheTag("carts")
revalidateTag(cartCacheTag, { expire: 0 })
const fulfillmentCacheTag = await getCacheTag("fulfillment")
revalidateTag(fulfillmentCacheTag, { expire: 0 })
})
.catch(medusaError)
}
export async function updateLineItem({
lineId,
quantity,
}: {
lineId: string
quantity: number
}) {
if (!lineId) {
throw new Error("Missing lineItem ID when updating line item")
}
const cartId = await getCartId()
if (!cartId) {
throw new Error("Missing cart ID when updating line item")
}
const headers = {
...(await getAuthHeaders()),
}
await sdk.store.cart
.updateLineItem(cartId, lineId, { quantity }, {}, headers)
.then(async () => {
const cartCacheTag = await getCacheTag("carts")
revalidateTag(cartCacheTag, { expire: 0 })
const fulfillmentCacheTag = await getCacheTag("fulfillment")
revalidateTag(fulfillmentCacheTag, { expire: 0 })
})
.catch(medusaError)
}
export async function deleteLineItem(lineId: string) {
if (!lineId) {
throw new Error("Missing lineItem ID when deleting line item")
}
const cartId = await getCartId()
if (!cartId) {
throw new Error("Missing cart ID when deleting line item")
}
const headers = {
...(await getAuthHeaders()),
}
await sdk.store.cart
.deleteLineItem(cartId, lineId, {}, headers)
.then(async () => {
const cartCacheTag = await getCacheTag("carts")
revalidateTag(cartCacheTag, { expire: 0 })
const fulfillmentCacheTag = await getCacheTag("fulfillment")
revalidateTag(fulfillmentCacheTag, { expire: 0 })
})
.catch(medusaError)
}
export async function setShippingMethod({
cartId,
shippingMethodId,
}: {
cartId: string
shippingMethodId: string
}) {
const headers = {
...(await getAuthHeaders()),
}
return sdk.store.cart
.addShippingMethod(cartId, { option_id: shippingMethodId }, {}, headers)
.then(async () => {
const cartCacheTag = await getCacheTag("carts")
revalidateTag(cartCacheTag, { expire: 0 })
})
.catch(medusaError)
}
export async function initiatePaymentSession(
cart: HttpTypes.StoreCart,
data: HttpTypes.StoreInitializePaymentSession
) {
const headers = {
...(await getAuthHeaders()),
}
return sdk.store.payment
.initiatePaymentSession(cart, data, {}, headers)
.then(async (resp) => {
const cartCacheTag = await getCacheTag("carts")
revalidateTag(cartCacheTag, { expire: 0 })
return resp
})
.catch(medusaError)
}
export async function applyPromotions(codes: string[]) {
const cartId = await getCartId()
if (!cartId) {
throw new Error("No existing cart found")
}
const headers = {
...(await getAuthHeaders()),
}
return sdk.store.cart
.update(cartId, { promo_codes: codes }, {}, headers)
.then(async () => {
const cartCacheTag = await getCacheTag("carts")
revalidateTag(cartCacheTag, { expire: 0 })
const fulfillmentCacheTag = await getCacheTag("fulfillment")
revalidateTag(fulfillmentCacheTag, { expire: 0 })
})
.catch(medusaError)
}
export async function applyGiftCard(code: string) {
// const cartId = getCartId()
// if (!cartId) return "No cartId cookie found"
// try {
// await updateCart(cartId, { gift_cards: [{ code }] }).then(() => {
// revalidateTag("cart")
// })
// } catch (error: any) {
// throw error
// }
}
export async function removeDiscount(code: string) {
// const cartId = getCartId()
// if (!cartId) return "No cartId cookie found"
// try {
// await deleteDiscount(cartId, code)
// revalidateTag("cart")
// } catch (error: any) {
// throw error
// }
}
export async function removeGiftCard(
codeToRemove: string,
giftCards: any[]
// giftCards: GiftCard[]
) {
// const cartId = getCartId()
// if (!cartId) return "No cartId cookie found"
// try {
// await updateCart(cartId, {
// gift_cards: [...giftCards]
// .filter((gc) => gc.code !== codeToRemove)
// .map((gc) => ({ code: gc.code })),
// }).then(() => {
// revalidateTag("cart")
// })
// } catch (error: any) {
// throw error
// }
}
export async function submitPromotionForm(
currentState: unknown,
formData: FormData
) {
const code = formData.get("code") as string
try {
await applyPromotions([code])
} catch (e: any) {
return e.message
}
}
// TODO: Pass a POJO instead of a form entity here
export async function setAddresses(currentState: unknown, formData: FormData) {
try {
if (!formData) {
throw new Error("No form data found when setting addresses")
}
const cartId = getCartId()
if (!cartId) {
throw new Error("No existing cart found when setting addresses")
}
const isBusiness = formData.get("is_business") === "on"
const companyJib = formData.get("company_jib") as string | null
const companyPdv = formData.get("company_pdv") as string | null
const addressMetadata = isBusiness
? { is_business: true, jib: companyJib, pdv: companyPdv }
: undefined
const data = {
shipping_address: {
first_name: formData.get("shipping_address.first_name"),
last_name: formData.get("shipping_address.last_name"),
address_1: formData.get("shipping_address.address_1"),
address_2: "",
company: formData.get("shipping_address.company"),
postal_code: formData.get("shipping_address.postal_code"),
city: formData.get("shipping_address.city"),
country_code: formData.get("shipping_address.country_code"),
province: formData.get("shipping_address.province"),
phone: formData.get("shipping_address.phone"),
metadata: addressMetadata,
},
email: formData.get("email"),
} as any
const sameAsBilling = formData.get("same_as_billing")
if (sameAsBilling === "on") data.billing_address = data.shipping_address
if (sameAsBilling !== "on")
data.billing_address = {
first_name: formData.get("billing_address.first_name"),
last_name: formData.get("billing_address.last_name"),
address_1: formData.get("billing_address.address_1"),
address_2: "",
company: formData.get("billing_address.company"),
postal_code: formData.get("billing_address.postal_code"),
city: formData.get("billing_address.city"),
country_code: formData.get("billing_address.country_code"),
province: formData.get("billing_address.province"),
phone: formData.get("billing_address.phone"),
metadata: addressMetadata,
}
await updateCart(data)
} catch (e: any) {
return e.message
}
redirect(
`/${formData.get("shipping_address.country_code")}/checkout?step=delivery`
)
}
/**
* Places an order for a cart. If no cart ID is provided, it will use the cart ID from the cookies.
* @param cartId - optional - The ID of the cart to place an order for.
* @returns The cart object if the order was successful, or null if not.
*/
export async function placeOrder(cartId?: string) {
const id = cartId || (await getCartId())
if (!id) {
throw new Error("No existing cart found when placing an order")
}
const headers = {
...(await getAuthHeaders()),
}
const cartRes = await sdk.store.cart
.complete(id, {}, headers)
.then(async (cartRes) => {
const cartCacheTag = await getCacheTag("carts")
revalidateTag(cartCacheTag, { expire: 0 })
return cartRes
})
.catch(medusaError)
if (cartRes?.type === "order") {
const countryCode =
cartRes.order.shipping_address?.country_code?.toLowerCase()
const orderCacheTag = await getCacheTag("orders")
revalidateTag(orderCacheTag, { expire: 0 })
removeCartId()
redirect(`/${countryCode}/order/${cartRes?.order.id}/confirmed`)
}
return cartRes.cart
}
/**
* Updates the countrycode param and revalidates the regions cache
* @param regionId
* @param countryCode
*/
export async function updateRegion(countryCode: string, currentPath: string) {
const cartId = await getCartId()
const region = await getRegion(countryCode)
if (!region) {
throw new Error(`Region not found for country code: ${countryCode}`)
}
if (cartId) {
await updateCart({ region_id: region.id })
const cartCacheTag = await getCacheTag("carts")
revalidateTag(cartCacheTag, { expire: 0 })
}
const regionCacheTag = await getCacheTag("regions")
revalidateTag(regionCacheTag, { expire: 0 })
const productsCacheTag = await getCacheTag("products")
revalidateTag(productsCacheTag, { expire: 0 })
redirect(`/${countryCode}${currentPath}`)
}
export async function listCartOptions() {
const cartId = await getCartId()
const headers = {
...(await getAuthHeaders()),
}
const next = {
...(await getCacheOptions("shippingOptions")),
}
return await sdk.client.fetch<{
shipping_options: HttpTypes.StoreCartShippingOption[]
}>("/store/shipping-options", {
query: { cart_id: cartId },
next,
headers,
cache: "force-cache",
})
}

View File

@@ -0,0 +1,49 @@
import { sdk } from "@lib/config"
import { HttpTypes } from "@medusajs/types"
import { getCacheOptions } from "./cookies"
export const listCategories = async (query?: Record<string, unknown>) => {
const next = {
...(await getCacheOptions("categories")),
}
const limit = query?.limit || 100
return sdk.client
.fetch<{ product_categories: HttpTypes.StoreProductCategory[] }>(
"/store/product-categories",
{
query: {
fields:
"*category_children, *products, *parent_category, *parent_category.parent_category",
limit,
...query,
},
next,
cache: "force-cache",
}
)
.then(({ product_categories }) => product_categories)
}
export const getCategoryByHandle = async (categoryHandle: string[]) => {
const handle = `${categoryHandle.join("/")}`
const next = {
...(await getCacheOptions("categories")),
}
return sdk.client
.fetch<HttpTypes.StoreProductCategoryListResponse>(
`/store/product-categories`,
{
query: {
fields: "*category_children, *products",
handle,
},
next,
cache: "force-cache",
}
)
.then(({ product_categories }) => product_categories[0])
}

View File

@@ -0,0 +1,59 @@
"use server"
import { sdk } from "@lib/config"
import { HttpTypes } from "@medusajs/types"
import { getCacheOptions } from "./cookies"
export const retrieveCollection = async (id: string) => {
const next = {
...(await getCacheOptions("collections")),
}
return await sdk.client
.fetch<{ collection: HttpTypes.StoreCollection }>(
`/store/collections/${id}`,
{
next,
cache: "force-cache",
}
)
.then(({ collection }) => collection)
}
export const listCollections = async (
queryParams: Record<string, string> = {}
): Promise<{ collections: HttpTypes.StoreCollection[]; count: number }> => {
const next = {
...(await getCacheOptions("collections")),
}
queryParams.limit = queryParams.limit || "100"
queryParams.offset = queryParams.offset || "0"
return await sdk.client
.fetch<{ collections: HttpTypes.StoreCollection[]; count: number }>(
"/store/collections",
{
query: queryParams,
next,
cache: "force-cache",
}
)
.then(({ collections }) => ({ collections, count: collections.length }))
}
export const getCollectionByHandle = async (
handle: string
): Promise<HttpTypes.StoreCollection | null> => {
const next = {
...(await getCacheOptions("collections")),
}
return await sdk.client
.fetch<HttpTypes.StoreCollectionListResponse>(`/store/collections`, {
query: { handle, fields: "*products" },
next,
cache: "force-cache",
})
.then(({ collections }) => collections[0] || null)
}

View File

@@ -0,0 +1,140 @@
import "server-only"
import { cookies as nextCookies } from "next/headers"
export const getAuthHeaders = async (): Promise<
{ authorization: string } | Record<string, never>
> => {
try {
const cookies = await nextCookies()
const token = cookies.get("_medusa_jwt")?.value
if (!token) {
return {}
}
return { authorization: `Bearer ${token}` }
} catch {
return {}
}
}
export const getCacheTag = async (tag: string): Promise<string> => {
try {
const cookies = await nextCookies()
const cacheId = cookies.get("_medusa_cache_id")?.value
if (!cacheId) {
return ""
}
return `${tag}-${cacheId}`
} catch {
return ""
}
}
export const getCacheOptions = async (
tag: string
): Promise<{ tags: string[] } | Record<string, never>> => {
if (typeof window !== "undefined") {
return {}
}
const cacheTag = await getCacheTag(tag)
if (!cacheTag) {
return {}
}
return { tags: [`${cacheTag}`] }
}
// `sameSite: "lax"` rather than `"strict"`: the customer returns from a
// redirect-based payment method (iDEAL, Bancontact, ...) via a cross-site
// top-level navigation. A "strict" cookie is withheld on that navigation, so
// the storefront would see a logged-out, cartless visitor and render a 404 for
// the checkout page instead of resuming the order. "lax" is sent on top-level
// GET navigations while still blocking cross-site subrequests.
export const setAuthToken = async (token: string) => {
const cookies = await nextCookies()
cookies.set("_medusa_jwt", token, {
maxAge: 60 * 60 * 24 * 7,
httpOnly: true,
sameSite: "lax",
secure: process.env.NODE_ENV === "production",
})
}
export const removeAuthToken = async () => {
const cookies = await nextCookies()
cookies.set("_medusa_jwt", "", {
maxAge: -1,
})
}
export type PendingCustomer = {
email: string
first_name?: string
last_name?: string
phone?: string
}
// During the email verification flow the customer record isn't created until
// the customer verifies their email and logs in. We temporarily persist the
// extra signup fields in a cookie so they survive the customer leaving to open
// their inbox, and read them back when creating the customer at login.
export const setPendingCustomer = async (customer: PendingCustomer) => {
const cookies = await nextCookies()
cookies.set("_medusa_pending_customer", JSON.stringify(customer), {
maxAge: 60 * 60 * 24,
httpOnly: true,
sameSite: "strict",
secure: process.env.NODE_ENV === "production",
})
}
export const getPendingCustomer = async (): Promise<PendingCustomer | null> => {
const cookies = await nextCookies()
const value = cookies.get("_medusa_pending_customer")?.value
if (!value) {
return null
}
try {
return JSON.parse(value) as PendingCustomer
} catch {
return null
}
}
export const removePendingCustomer = async () => {
const cookies = await nextCookies()
cookies.set("_medusa_pending_customer", "", {
maxAge: -1,
})
}
export const getCartId = async () => {
const cookies = await nextCookies()
return cookies.get("_medusa_cart_id")?.value
}
// See the note on `setAuthToken`: `sameSite: "lax"` so the cart cookie survives
// the cross-site return navigation from a redirect-based payment method.
export const setCartId = async (cartId: string) => {
const cookies = await nextCookies()
cookies.set("_medusa_cart_id", cartId, {
maxAge: 60 * 60 * 24 * 7,
httpOnly: true,
sameSite: "lax",
secure: process.env.NODE_ENV === "production",
})
}
export const removeCartId = async () => {
const cookies = await nextCookies()
cookies.set("_medusa_cart_id", "", {
maxAge: -1,
})
}

View File

@@ -0,0 +1,381 @@
"use server"
import { sdk } from "@lib/config"
import medusaError from "@lib/util/medusa-error"
import { HttpTypes } from "@medusajs/types"
import { FetchError } from "@medusajs/js-sdk"
import { revalidateTag } from "next/cache"
import { redirect } from "next/navigation"
import {
getAuthHeaders,
getCacheOptions,
getCacheTag,
getCartId,
getPendingCustomer,
removeAuthToken,
removeCartId,
removePendingCustomer,
setAuthToken,
setPendingCustomer,
} from "./cookies"
export type CustomerAuthState =
| { state: "error"; error: string }
| { state: "verification_required"; email: string }
| { state: "success" }
| null
// Requests a verification email for the given customer. The request must be
// authenticated with a token tied to the auth identity (the token returned by
// register or by a login that requires verification).
async function requestVerificationEmail(email: string, token: string) {
await sdk.auth.verification.request(
{
entity_id: email,
entity_type: "email",
},
{
authorization: `Bearer ${token}`,
}
)
}
export const retrieveCustomer =
async (): Promise<HttpTypes.StoreCustomer | null> => {
const authHeaders = await getAuthHeaders()
if (!("authorization" in authHeaders)) return null
const headers = {
...authHeaders,
}
const next = {
...(await getCacheOptions("customers")),
}
return await sdk.client
.fetch<{ customer: HttpTypes.StoreCustomer }>(`/store/customers/me`, {
method: "GET",
query: {
fields: "*orders",
},
headers,
next,
cache: "force-cache",
})
.then(({ customer }) => customer)
.catch(() => null)
}
export const updateCustomer = async (body: HttpTypes.StoreUpdateCustomer) => {
const headers = {
...(await getAuthHeaders()),
}
const updateRes = await sdk.store.customer
.update(body, {}, headers)
.then(({ customer }) => customer)
.catch(medusaError)
const cacheTag = await getCacheTag("customers")
revalidateTag(cacheTag, { expire: 0 })
return updateRes
}
export async function signup(
_currentState: unknown,
formData: FormData
): Promise<CustomerAuthState> {
const password = formData.get("password") as string
const customerForm = {
email: formData.get("email") as string,
first_name: formData.get("first_name") as string,
last_name: formData.get("last_name") as string,
phone: formData.get("phone") as string,
}
try {
await sdk.auth.register("customer", "emailpass", {
email: customerForm.email,
password,
})
} catch (error) {
const fetchError = error as FetchError
// An existing identity (for example, an admin user with the same email) is
// expected and handled: the customer can still log in to link a customer
// record. Any other error is surfaced.
if (
fetchError.statusText !== "Unauthorized" ||
fetchError.message !== "Identity with email already exists"
) {
return { state: "error", error: String(error) }
}
}
// Persist the extra signup fields. The customer record is created during
// login, which is deferred until after email verification when the backend
// requires it.
await setPendingCustomer(customerForm)
// Continue by logging in. The login response tells us whether the backend
// requires email verification — we don't need a storefront-side flag.
return completeLogin(customerForm.email, password)
}
export async function login(
_currentState: unknown,
formData: FormData
): Promise<CustomerAuthState> {
const email = formData.get("email") as string
const password = formData.get("password") as string
return completeLogin(email, password)
}
// Logs the customer in and reconciles the customer record. The behavior is
// driven entirely by the backend's login response, so it works whether or not
// email verification is enabled.
async function completeLogin(
email: string,
password: string
): Promise<CustomerAuthState> {
let result: Awaited<ReturnType<typeof sdk.auth.login>>
try {
result = await sdk.auth.login("customer", "emailpass", { email, password })
} catch (error) {
return { state: "error", error: String(error) }
}
// A `location` is returned by third-party auth providers, which this flow
// doesn't support.
if (typeof result === "object" && "location" in result) {
return {
state: "error",
error: "This login method isn't supported by the storefront.",
}
}
// The backend requires email verification and the customer hasn't verified
// yet. Send the verification email and ask them to check their inbox.
if (
typeof result === "object" &&
"verification_required" in result &&
result.verification_required
) {
try {
await requestVerificationEmail(email, result.token)
} catch {
// Ignore: the customer can resend from the verification page.
}
return { state: "verification_required", email }
}
if (typeof result !== "string") {
return {
state: "error",
error: "Authentication requires additional steps that aren't supported.",
}
}
let token = result
// The token may not be tied to a customer record yet — right after
// registration, or after verifying a brand-new account. Ask the backend:
// `/store/customers/me` rejects tokens without a registered actor, so a
// failed retrieve means we still need to create the customer, then log in
// again to obtain a customer-bound token.
const customerExists = await sdk.store.customer
.retrieve({}, { authorization: `Bearer ${token}` })
.then(() => true)
.catch(() => false)
if (!customerExists) {
const pending = await getPendingCustomer()
try {
await sdk.store.customer.create(
{
email,
first_name: pending?.first_name,
last_name: pending?.last_name,
phone: pending?.phone,
},
{},
{ authorization: `Bearer ${token}` }
)
token = (await sdk.auth.login("customer", "emailpass", {
email,
password,
})) as string
} catch (error) {
return { state: "error", error: String(error) }
}
await removePendingCustomer()
}
await setAuthToken(token)
const customerCacheTag = await getCacheTag("customers")
revalidateTag(customerCacheTag, { expire: 0 })
try {
await transferCart()
} catch (error) {
return { state: "error", error: String(error) }
}
return { state: "success" }
}
// Confirms a customer's email using the token from the verification link.
//
// The confirm route doesn't require authentication, so this works even when the
// customer opens the link on a different device than the one they signed up on.
export async function confirmEmailVerification(
token: string
): Promise<{ success: boolean; error?: string }> {
try {
await sdk.auth.verification.confirm({ code: token })
return { success: true }
} catch (error) {
return { success: false, error: String(error) }
}
}
export async function signout(countryCode: string) {
await sdk.auth.logout()
await removeAuthToken()
const customerCacheTag = await getCacheTag("customers")
revalidateTag(customerCacheTag, { expire: 0 })
await removeCartId()
const cartCacheTag = await getCacheTag("carts")
revalidateTag(cartCacheTag, { expire: 0 })
redirect(`/${countryCode}/account`)
}
export async function transferCart() {
const cartId = await getCartId()
if (!cartId) {
return
}
const headers = await getAuthHeaders()
await sdk.store.cart.transferCart(cartId, {}, headers)
const cartCacheTag = await getCacheTag("carts")
revalidateTag(cartCacheTag, { expire: 0 })
}
export const addCustomerAddress = async (
currentState: Record<string, unknown>,
formData: FormData
): Promise<{ success: boolean; error: string | null }> => {
const isDefaultBilling = (currentState.isDefaultBilling as boolean) || false
const isDefaultShipping = (currentState.isDefaultShipping as boolean) || false
const address = {
first_name: formData.get("first_name") as string,
last_name: formData.get("last_name") as string,
company: formData.get("company") as string,
address_1: formData.get("address_1") as string,
address_2: formData.get("address_2") as string,
city: formData.get("city") as string,
postal_code: formData.get("postal_code") as string,
province: formData.get("province") as string,
country_code: formData.get("country_code") as string,
phone: formData.get("phone") as string,
is_default_billing: isDefaultBilling,
is_default_shipping: isDefaultShipping,
}
const headers = {
...(await getAuthHeaders()),
}
return sdk.store.customer
.createAddress(address, {}, headers)
.then(async () => {
const customerCacheTag = await getCacheTag("customers")
revalidateTag(customerCacheTag, { expire: 0 })
return { success: true, error: null }
})
.catch((err) => {
return { success: false, error: err.toString() }
})
}
export const deleteCustomerAddress = async (
addressId: string
): Promise<void> => {
const headers = {
...(await getAuthHeaders()),
}
await sdk.store.customer
.deleteAddress(addressId, headers)
.then(async () => {
const customerCacheTag = await getCacheTag("customers")
revalidateTag(customerCacheTag, { expire: 0 })
return { success: true, error: null }
})
.catch((err) => {
return { success: false, error: err.toString() }
})
}
export const updateCustomerAddress = async (
currentState: Record<string, unknown>,
formData: FormData
): Promise<{ success: boolean; error: string | null }> => {
const addressId =
(currentState.addressId as string) || (formData.get("addressId") as string)
if (!addressId) {
return { success: false, error: "Address ID is required" }
}
const address = {
first_name: formData.get("first_name") as string,
last_name: formData.get("last_name") as string,
company: formData.get("company") as string,
address_1: formData.get("address_1") as string,
address_2: formData.get("address_2") as string,
city: formData.get("city") as string,
postal_code: formData.get("postal_code") as string,
province: formData.get("province") as string,
country_code: formData.get("country_code") as string,
} as HttpTypes.StoreUpdateCustomerAddress
const phone = formData.get("phone") as string
if (phone) {
address.phone = phone
}
const headers = {
...(await getAuthHeaders()),
}
return sdk.store.customer
.updateAddress(addressId, address, {}, headers)
.then(async () => {
const customerCacheTag = await getCacheTag("customers")
revalidateTag(customerCacheTag, { expire: 0 })
return { success: true, error: null }
})
.catch((err) => {
return { success: false, error: err.toString() }
})
}

View File

@@ -0,0 +1,68 @@
"use server"
import { sdk } from "@lib/config"
import { HttpTypes } from "@medusajs/types"
import { getAuthHeaders, getCacheOptions } from "./cookies"
export const listCartShippingMethods = async (cartId: string) => {
const headers = {
...(await getAuthHeaders()),
}
const next = {
...(await getCacheOptions("fulfillment")),
}
return sdk.client
.fetch<HttpTypes.StoreShippingOptionListResponse>(
`/store/shipping-options`,
{
method: "GET",
query: {
cart_id: cartId,
},
headers,
next,
cache: "force-cache",
}
)
.then(({ shipping_options }) => shipping_options)
.catch(() => {
return null
})
}
export const calculatePriceForShippingOption = async (
optionId: string,
cartId: string,
data?: Record<string, unknown>
) => {
const headers = {
...(await getAuthHeaders()),
}
const next = {
...(await getCacheOptions("fulfillment")),
}
const body = { cart_id: cartId, data }
if (data) {
body.data = data
}
return sdk.client
.fetch<{ shipping_option: HttpTypes.StoreCartShippingOption }>(
`/store/shipping-options/${optionId}/calculate`,
{
method: "POST",
body,
headers,
next,
}
)
.then(({ shipping_option }) => shipping_option)
.catch((_e) => {
return null
})
}

View File

@@ -0,0 +1,35 @@
"use server"
import { sdk } from "@lib/config"
export type CreateInquiryPayload = {
name: string
email: string
phone: string
company_name?: string | null
city: string
dimensions?: string | null
message: string
product_id?: string | null
sales_channel_id?: string | null
metadata?: Record<string, unknown> | null
}
export async function submitInquiry(payload: CreateInquiryPayload) {
try {
const res = await sdk.client.fetch<{ inquiry: any }>("/store/inquiries", {
method: "POST",
body: payload,
})
return { success: true, inquiry: res.inquiry }
} catch (error: any) {
console.error("Failed to submit inquiry:", error)
return {
success: false,
error:
error?.message ||
"Došlo je do greške prilikom slanja upita. Molimo pokušajte ponovo ili nas pozovite direktno.",
}
}
}

View File

@@ -0,0 +1,74 @@
"use server"
import { sdk } from "@lib/config"
import { revalidateTag } from "next/cache"
import { cookies as nextCookies } from "next/headers"
import { getAuthHeaders, getCacheTag, getCartId } from "./cookies"
const LOCALE_COOKIE_NAME = "_medusa_locale"
/**
* Gets the current locale from cookies
*/
export const getLocale = async (): Promise<string | null> => {
try {
const cookies = await nextCookies()
return cookies.get(LOCALE_COOKIE_NAME)?.value ?? null
} catch {
return null
}
}
/**
* Sets the locale cookie
*/
export const setLocaleCookie = async (locale: string) => {
const cookies = await nextCookies()
cookies.set(LOCALE_COOKIE_NAME, locale, {
maxAge: 60 * 60 * 24 * 365, // 1 year
httpOnly: false, // Allow client-side access
sameSite: "strict",
secure: process.env.NODE_ENV === "production",
})
}
/**
* Updates the locale preference via SDK and stores in cookie.
* Also updates the cart with the new locale if one exists.
*/
export const updateLocale = async (localeCode: string): Promise<string> => {
await setLocaleCookie(localeCode)
// Update cart with the new locale if a cart exists
const cartId = await getCartId()
if (cartId) {
const headers = {
...(await getAuthHeaders()),
}
await sdk.store.cart.update(cartId, { locale: localeCode }, {}, headers)
const cartCacheTag = await getCacheTag("carts")
if (cartCacheTag) {
revalidateTag(cartCacheTag, { expire: 0 })
}
}
// Revalidate relevant caches to refresh content
const productsCacheTag = await getCacheTag("products")
if (productsCacheTag) {
revalidateTag(productsCacheTag, { expire: 0 })
}
const categoriesCacheTag = await getCacheTag("categories")
if (categoriesCacheTag) {
revalidateTag(categoriesCacheTag, { expire: 0 })
}
const collectionsCacheTag = await getCacheTag("collections")
if (collectionsCacheTag) {
revalidateTag(collectionsCacheTag, { expire: 0 })
}
return localeCode
}

View File

@@ -0,0 +1,28 @@
"use server"
import { sdk } from "@lib/config"
import { getCacheOptions } from "./cookies"
export type Locale = {
code: string
name: string
}
/**
* Fetches available locales from the backend.
* Returns null if the endpoint returns 404 (locales not configured).
*/
export const listLocales = async (): Promise<Locale[] | null> => {
const next = {
...(await getCacheOptions("locales")),
}
return sdk.client
.fetch<{ locales: Locale[] }>(`/store/locales`, {
method: "GET",
next,
cache: "force-cache",
})
.then(({ locales }) => locales)
.catch(() => null)
}

View File

@@ -0,0 +1,9 @@
"use server"
import { cookies as nextCookies } from "next/headers"
import { redirect } from "next/navigation"
export async function resetOnboardingState(orderId: string) {
const cookies = await nextCookies()
cookies.set("_medusa_onboarding", "false", { maxAge: -1 })
redirect(`http://localhost:7001/a/orders/${orderId}`)
}

View File

@@ -0,0 +1,112 @@
"use server"
import { sdk } from "@lib/config"
import medusaError from "@lib/util/medusa-error"
import { getAuthHeaders, getCacheOptions } from "./cookies"
import { HttpTypes } from "@medusajs/types"
export const retrieveOrder = async (id: string) => {
const headers = {
...(await getAuthHeaders()),
}
const next = {
...(await getCacheOptions("orders")),
}
return sdk.client
.fetch<HttpTypes.StoreOrderResponse>(`/store/orders/${id}`, {
method: "GET",
query: {
fields:
"*payment_collections.payments,*items,*items.metadata,*items.variant,*items.product",
},
headers,
next,
cache: "force-cache",
})
.then(({ order }) => order)
.catch((err) => medusaError(err))
}
export const listOrders = async (
limit: number = 10,
offset: number = 0,
filters?: Record<string, unknown>
) => {
const headers = {
...(await getAuthHeaders()),
}
const next = {
...(await getCacheOptions("orders")),
}
return sdk.client
.fetch<HttpTypes.StoreOrderListResponse>(`/store/orders`, {
method: "GET",
query: {
limit,
offset,
order: "-created_at",
fields: "*items,+items.metadata,*items.variant,*items.product",
...filters,
},
headers,
next,
cache: "force-cache",
})
.then(({ orders }) => orders)
.catch((err) => medusaError(err))
}
export const createTransferRequest = async (
state: {
success: boolean
error: string | null
order: HttpTypes.StoreOrder | null
},
formData: FormData
): Promise<{
success: boolean
error: string | null
order: HttpTypes.StoreOrder | null
}> => {
const id = formData.get("order_id") as string
if (!id) {
return { success: false, error: "Order ID is required", order: null }
}
const headers = await getAuthHeaders()
return await sdk.store.order
.requestTransfer(
id,
{},
{
fields: "id, email",
},
headers
)
.then(({ order }) => ({ success: true, error: null, order }))
.catch((err) => ({ success: false, error: err.message, order: null }))
}
export const acceptTransferRequest = async (id: string, token: string) => {
const headers = await getAuthHeaders()
return await sdk.store.order
.acceptTransfer(id, { token }, {}, headers)
.then(({ order }) => ({ success: true, error: null, order }))
.catch((err) => ({ success: false, error: err.message, order: null }))
}
export const declineTransferRequest = async (id: string, token: string) => {
const headers = await getAuthHeaders()
return await sdk.store.order
.declineTransfer(id, { token }, {}, headers)
.then(({ order }) => ({ success: true, error: null, order }))
.catch((err) => ({ success: false, error: err.message, order: null }))
}

View File

@@ -0,0 +1,35 @@
"use server"
import { sdk } from "@lib/config"
import { getAuthHeaders, getCacheOptions } from "./cookies"
import { HttpTypes } from "@medusajs/types"
export const listCartPaymentMethods = async (regionId: string) => {
const headers = {
...(await getAuthHeaders()),
}
const next = {
...(await getCacheOptions("payment_providers")),
revalidate: 60,
}
return sdk.client
.fetch<HttpTypes.StorePaymentProviderListResponse>(
`/store/payment-providers`,
{
method: "GET",
query: { region_id: regionId },
headers,
next,
}
)
.then(({ payment_providers }) =>
payment_providers.sort((a, b) => {
return a.id > b.id ? 1 : -1
})
)
.catch(() => {
return null
})
}

View File

@@ -0,0 +1,151 @@
"use server"
import { sdk } from "@lib/config"
import { OptionValueIds } from "@lib/util/product-option-filters"
import { sortProducts } from "@lib/util/sort-products"
import { HttpTypes } from "@medusajs/types"
import { SortOptions } from "@modules/store/components/refinement-list/sort-products"
import { getAuthHeaders, getCacheOptions } from "./cookies"
import { getRegion, retrieveRegion } from "./regions"
type ProductListQueryParams = (HttpTypes.FindParams &
HttpTypes.StoreProductListParams) & {
options?: string[]
option_value_id?: string | string[]
}
export const listProducts = async ({
pageParam = 1,
queryParams,
countryCode,
regionId,
}: {
pageParam?: number
queryParams?: ProductListQueryParams
countryCode?: string
regionId?: string
}): Promise<{
response: { products: HttpTypes.StoreProduct[]; count: number }
nextPage: number | null
queryParams?: ProductListQueryParams
}> => {
if (!countryCode && !regionId) {
throw new Error("Country code or region ID is required")
}
const limit = queryParams?.limit || 12
const _pageParam = Math.max(pageParam, 1)
const offset = _pageParam === 1 ? 0 : (_pageParam - 1) * limit
let region: HttpTypes.StoreRegion | undefined | null
if (countryCode) {
region = await getRegion(countryCode)
} else {
region = await retrieveRegion(regionId!)
}
if (!region) {
return {
response: { products: [], count: 0 },
nextPage: null,
}
}
const headers = {
...(await getAuthHeaders()),
}
const next = {
...(await getCacheOptions("products")),
}
return sdk.client
.fetch<{ products: HttpTypes.StoreProduct[]; count: number }>(
`/store/products`,
{
method: "GET",
query: {
limit,
offset,
region_id: region?.id,
fields:
"*variants.calculated_price,+variants.inventory_quantity,*variants.images,*variants.options,+metadata,+tags,",
...queryParams,
},
headers,
next,
cache: "force-cache",
}
)
.then(({ products, count }) => {
const nextPage = count > offset + limit ? pageParam + 1 : null
return {
response: {
products,
count,
},
nextPage: nextPage,
queryParams,
}
})
}
/**
* This will fetch 100 products to the Next.js cache and sort them based on the sortBy parameter.
* It will then return the paginated products based on the page and limit parameters.
*/
export const listProductsWithSort = async ({
page = 0,
queryParams,
sortBy = "created_at",
countryCode,
optionValueIds,
}: {
page?: number
queryParams?: ProductListQueryParams
sortBy?: SortOptions
countryCode: string
optionValueIds?: OptionValueIds
}): Promise<{
response: { products: HttpTypes.StoreProduct[]; count: number }
nextPage: number | null
queryParams?: ProductListQueryParams
}> => {
const limit = queryParams?.limit || 12
const optionFilters = Array.from(
new Set((optionValueIds || []).filter(Boolean))
)
const {
response: { products },
} = await listProducts({
pageParam: 0,
queryParams: {
...queryParams,
...(optionFilters.length ? { option_value_id: optionFilters } : {}),
limit: 100,
},
countryCode,
})
const sortedProducts = sortProducts(products, sortBy)
const pageParam = (page - 1) * limit
const filteredCount = products.length
const nextPage = filteredCount > pageParam + limit ? pageParam + limit : null
const paginatedProducts = sortedProducts.slice(pageParam, pageParam + limit)
return {
response: {
products: paginatedProducts,
count: filteredCount,
},
nextPage,
queryParams,
}
}

View File

@@ -0,0 +1,59 @@
"use server"
import { sdk } from "@lib/config"
import { HttpTypes } from "@medusajs/types"
import { getCacheOptions } from "./cookies"
export const listRegions = async () => {
const next = {
...(await getCacheOptions("regions")),
}
return await sdk.client
.fetch<{ regions: HttpTypes.StoreRegion[] }>(`/store/regions`, {
method: "GET",
next,
cache: "force-cache",
})
.then(({ regions }) => regions)
}
export const retrieveRegion = async (id: string) => {
const next = {
...(await getCacheOptions(["regions", id].join("-"))),
}
return await sdk.client
.fetch<{ region: HttpTypes.StoreRegion }>(`/store/regions/${id}`, {
method: "GET",
next,
cache: "force-cache",
})
.then(({ region }) => region)
}
const regionMap = new Map<string, HttpTypes.StoreRegion>()
export const getRegion = async (countryCode: string) => {
if (regionMap.has(countryCode)) {
return regionMap.get(countryCode)
}
const regions = await listRegions()
if (!regions) {
return null
}
regions.forEach((region) => {
region.countries?.forEach((c) => {
regionMap.set(c?.iso_2 ?? "", region)
})
})
const region = countryCode
? regionMap.get(countryCode)
: regionMap.get("us")
return region
}

View File

@@ -0,0 +1,20 @@
"use server"
import { getRegionPolicies, StorePolicies } from "@lib/util/store-policies"
import { listRegions } from "./regions"
export const getStorePolicies = async (countryCode: string) => {
const regions = await listRegions()
const current = regions.find((region) =>
region.countries?.some((country) => country.iso_2 === countryCode.toLowerCase())
)
return {
current: getRegionPolicies(current),
currencyCode: current?.currency_code ?? "",
regions: regions.flatMap((region) => {
const policies = getRegionPolicies(region)
return policies ? [{ id: region.id, name: region.name, policies }] : []
}) as { id: string; name: string; policies: StorePolicies }[],
}
}

View File

@@ -0,0 +1,38 @@
"use server"
import { sdk } from "@lib/config"
import { HttpTypes } from "@medusajs/types"
import { getAuthHeaders, getCacheOptions } from "./cookies"
export const retrieveVariant = async (
variant_id: string
): Promise<HttpTypes.StoreProductVariant | null> => {
const authHeaders = await getAuthHeaders()
if (!authHeaders) return null
const headers = {
...authHeaders,
}
const next = {
...(await getCacheOptions("variants")),
}
return await sdk.client
.fetch<{ variant: HttpTypes.StoreProductVariant }>(
`/store/product-variants/${variant_id}`,
{
method: "GET",
query: {
fields: "*images",
},
headers,
next,
cache: "force-cache",
}
)
.then(({ variant }) => variant)
.catch(() => null)
}