first commit
This commit is contained in:
39
apps/suman-bosna/src/lib/config.ts
Normal file
39
apps/suman-bosna/src/lib/config.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { getLocaleHeader } from "@lib/util/get-locale-header"
|
||||
import Medusa, { FetchArgs, FetchInput } from "@medusajs/js-sdk"
|
||||
|
||||
// Defaults to standard port for Medusa server
|
||||
let MEDUSA_BACKEND_URL = "http://localhost:9000"
|
||||
|
||||
if (process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL) {
|
||||
MEDUSA_BACKEND_URL = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL
|
||||
}
|
||||
|
||||
export const sdk = new Medusa({
|
||||
baseUrl: MEDUSA_BACKEND_URL,
|
||||
debug: process.env.NODE_ENV === "development",
|
||||
publishableKey: process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,
|
||||
})
|
||||
|
||||
const originalFetch = sdk.client.fetch.bind(sdk.client)
|
||||
|
||||
sdk.client.fetch = async <T>(
|
||||
input: FetchInput,
|
||||
init?: FetchArgs
|
||||
): Promise<T> => {
|
||||
const headers = init?.headers ?? {}
|
||||
let localeHeader: Record<string, string | null> | undefined
|
||||
try {
|
||||
localeHeader = await getLocaleHeader()
|
||||
headers["x-medusa-locale"] ??= localeHeader["x-medusa-locale"]
|
||||
} catch {}
|
||||
|
||||
const newHeaders = {
|
||||
...localeHeader,
|
||||
...headers,
|
||||
}
|
||||
init = {
|
||||
...init,
|
||||
headers: newHeaders,
|
||||
}
|
||||
return originalFetch(input, init)
|
||||
}
|
||||
127
apps/suman-bosna/src/lib/constants.tsx
Normal file
127
apps/suman-bosna/src/lib/constants.tsx
Normal file
@@ -0,0 +1,127 @@
|
||||
import { CreditCard } from "lucide-react"
|
||||
import Bancontact from "@modules/common/icons/bancontact"
|
||||
import Ideal from "@modules/common/icons/ideal"
|
||||
import PayPal from "@modules/common/icons/paypal"
|
||||
import React from "react"
|
||||
|
||||
/* Map of payment provider_id to their title and icon. Add in any payment providers you want to use. */
|
||||
export const paymentInfoMap: Record<
|
||||
string,
|
||||
{ title: string; icon: React.JSX.Element }
|
||||
> = {
|
||||
pp_stripe_stripe: {
|
||||
title: "Credit card",
|
||||
icon: <CreditCard />,
|
||||
},
|
||||
"pp_stripe-ideal_stripe": {
|
||||
title: "iDeal",
|
||||
icon: <Ideal />,
|
||||
},
|
||||
"pp_stripe-bancontact_stripe": {
|
||||
title: "Bancontact",
|
||||
icon: <Bancontact />,
|
||||
},
|
||||
pp_paypal_paypal: {
|
||||
title: "PayPal",
|
||||
icon: <PayPal />,
|
||||
},
|
||||
pp_system_default: {
|
||||
title: "Manual Payment",
|
||||
icon: <CreditCard />,
|
||||
},
|
||||
// Add more payment providers here
|
||||
}
|
||||
|
||||
/*
|
||||
* Medusa Payments registers one provider per payment account, with the ID
|
||||
* `pp_medusa-payments_{account}`, where `{account}` is the Medusa Cloud payment account ID.
|
||||
*/
|
||||
const MEDUSA_PAYMENTS_PREFIX = "pp_medusa-payments_"
|
||||
|
||||
const medusaPaymentsInfo = {
|
||||
title: "Credit card",
|
||||
icon: <CreditCard />,
|
||||
}
|
||||
|
||||
/*
|
||||
* Adyen registers its provider with the ID `pp_adyen_{id}`, where `{id}` is the ID set in
|
||||
* `medusa-config.ts`. Its Drop-in offers cards, Apple Pay, and Google Pay.
|
||||
*/
|
||||
const ADYEN_PREFIX = "pp_adyen_"
|
||||
|
||||
const adyenInfo = {
|
||||
title: "Card, Apple Pay, or Google Pay",
|
||||
icon: <CreditCard />,
|
||||
}
|
||||
|
||||
export const getPaymentInfo = (providerId?: string) => {
|
||||
if (!providerId) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
if (isMedusaPayments(providerId)) {
|
||||
return medusaPaymentsInfo
|
||||
}
|
||||
|
||||
if (isAdyen(providerId)) {
|
||||
return adyenInfo
|
||||
}
|
||||
|
||||
return paymentInfoMap[providerId]
|
||||
}
|
||||
|
||||
export const isAdyen = (providerId?: string) => {
|
||||
return !!providerId?.startsWith(ADYEN_PREFIX)
|
||||
}
|
||||
|
||||
export const isMedusaPayments = (providerId?: string) => {
|
||||
return !!providerId?.startsWith(MEDUSA_PAYMENTS_PREFIX)
|
||||
}
|
||||
|
||||
// Medusa Payments returns the Stripe account that holds the payment, which Stripe.js has to be initialized with.
|
||||
// It isn't derived from the provider ID, as non-production environments take payments with a sandbox account.
|
||||
export const getMedusaPaymentsAccount = (paymentSession?: {
|
||||
provider_id: string
|
||||
data?: Record<string, unknown>
|
||||
}) => {
|
||||
const account = paymentSession?.data?.stripe_account
|
||||
return isMedusaPayments(paymentSession?.provider_id) &&
|
||||
typeof account === "string"
|
||||
? account
|
||||
: undefined
|
||||
}
|
||||
|
||||
// This only checks if it is native stripe or medusa payments for card payments, it ignores the other stripe-based providers
|
||||
export const isStripeLike = (providerId?: string) => {
|
||||
return providerId?.startsWith("pp_stripe_") || isMedusaPayments(providerId)
|
||||
}
|
||||
|
||||
export const isPaypal = (providerId?: string) => {
|
||||
return providerId?.startsWith("pp_paypal")
|
||||
}
|
||||
export const isManual = (providerId?: string) => {
|
||||
return providerId?.startsWith("pp_system_default")
|
||||
}
|
||||
|
||||
// Add currencies that don't need to be divided by 100
|
||||
export const noDivisionCurrencies = [
|
||||
"krw",
|
||||
"jpy",
|
||||
"vnd",
|
||||
"clp",
|
||||
"pyg",
|
||||
"xaf",
|
||||
"xof",
|
||||
"bif",
|
||||
"djf",
|
||||
"gnf",
|
||||
"kmf",
|
||||
"mga",
|
||||
"rwf",
|
||||
"xpf",
|
||||
"htg",
|
||||
"vuv",
|
||||
"xag",
|
||||
"xdr",
|
||||
"xau",
|
||||
]
|
||||
34
apps/suman-bosna/src/lib/context/modal-context.tsx
Normal file
34
apps/suman-bosna/src/lib/context/modal-context.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
"use client"
|
||||
|
||||
import React, { createContext, useContext } from "react"
|
||||
|
||||
interface ModalContext {
|
||||
close: () => void
|
||||
}
|
||||
|
||||
const ModalContext = createContext<ModalContext | null>(null)
|
||||
|
||||
interface ModalProviderProps {
|
||||
children?: React.ReactNode
|
||||
close: () => void
|
||||
}
|
||||
|
||||
export const ModalProvider = ({ children, close }: ModalProviderProps) => {
|
||||
return (
|
||||
<ModalContext.Provider
|
||||
value={{
|
||||
close,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</ModalContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export const useModal = () => {
|
||||
const context = useContext(ModalContext)
|
||||
if (context === null) {
|
||||
throw new Error("useModal must be used within a ModalProvider")
|
||||
}
|
||||
return context
|
||||
}
|
||||
82
apps/suman-bosna/src/lib/data/adyen.ts
Normal file
82
apps/suman-bosna/src/lib/data/adyen.ts
Normal 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,
|
||||
}
|
||||
}
|
||||
483
apps/suman-bosna/src/lib/data/cart.ts
Normal file
483
apps/suman-bosna/src/lib/data/cart.ts
Normal 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",
|
||||
})
|
||||
}
|
||||
49
apps/suman-bosna/src/lib/data/categories.ts
Normal file
49
apps/suman-bosna/src/lib/data/categories.ts
Normal 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])
|
||||
}
|
||||
59
apps/suman-bosna/src/lib/data/collections.ts
Normal file
59
apps/suman-bosna/src/lib/data/collections.ts
Normal 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)
|
||||
}
|
||||
140
apps/suman-bosna/src/lib/data/cookies.ts
Normal file
140
apps/suman-bosna/src/lib/data/cookies.ts
Normal 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,
|
||||
})
|
||||
}
|
||||
381
apps/suman-bosna/src/lib/data/customer.ts
Normal file
381
apps/suman-bosna/src/lib/data/customer.ts
Normal 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() }
|
||||
})
|
||||
}
|
||||
68
apps/suman-bosna/src/lib/data/fulfillment.ts
Normal file
68
apps/suman-bosna/src/lib/data/fulfillment.ts
Normal 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
|
||||
})
|
||||
}
|
||||
35
apps/suman-bosna/src/lib/data/inquiries.ts
Normal file
35
apps/suman-bosna/src/lib/data/inquiries.ts
Normal 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.",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
74
apps/suman-bosna/src/lib/data/locale-actions.ts
Normal file
74
apps/suman-bosna/src/lib/data/locale-actions.ts
Normal 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
|
||||
}
|
||||
28
apps/suman-bosna/src/lib/data/locales.ts
Normal file
28
apps/suman-bosna/src/lib/data/locales.ts
Normal 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)
|
||||
}
|
||||
9
apps/suman-bosna/src/lib/data/onboarding.ts
Normal file
9
apps/suman-bosna/src/lib/data/onboarding.ts
Normal 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}`)
|
||||
}
|
||||
112
apps/suman-bosna/src/lib/data/orders.ts
Normal file
112
apps/suman-bosna/src/lib/data/orders.ts
Normal 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 }))
|
||||
}
|
||||
35
apps/suman-bosna/src/lib/data/payment.ts
Normal file
35
apps/suman-bosna/src/lib/data/payment.ts
Normal 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
|
||||
})
|
||||
}
|
||||
151
apps/suman-bosna/src/lib/data/products.ts
Normal file
151
apps/suman-bosna/src/lib/data/products.ts
Normal 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,
|
||||
}
|
||||
}
|
||||
59
apps/suman-bosna/src/lib/data/regions.ts
Normal file
59
apps/suman-bosna/src/lib/data/regions.ts
Normal 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
|
||||
}
|
||||
20
apps/suman-bosna/src/lib/data/store-policies.ts
Normal file
20
apps/suman-bosna/src/lib/data/store-policies.ts
Normal 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 }[],
|
||||
}
|
||||
}
|
||||
38
apps/suman-bosna/src/lib/data/variants.ts
Normal file
38
apps/suman-bosna/src/lib/data/variants.ts
Normal 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)
|
||||
}
|
||||
29
apps/suman-bosna/src/lib/hooks/use-in-view.tsx
Normal file
29
apps/suman-bosna/src/lib/hooks/use-in-view.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import { RefObject, useEffect, useState } from "react"
|
||||
|
||||
export const useIntersection = (
|
||||
element: RefObject<HTMLDivElement | null>,
|
||||
rootMargin: string
|
||||
) => {
|
||||
const [isVisible, setState] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!element.current) {
|
||||
return
|
||||
}
|
||||
|
||||
const el = element.current
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
setState(entry.isIntersecting)
|
||||
},
|
||||
{ rootMargin }
|
||||
)
|
||||
|
||||
observer.observe(el)
|
||||
|
||||
return () => observer.unobserve(el)
|
||||
}, [element, rootMargin])
|
||||
|
||||
return isVisible
|
||||
}
|
||||
31
apps/suman-bosna/src/lib/hooks/use-search-settled.tsx
Normal file
31
apps/suman-bosna/src/lib/hooks/use-search-settled.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
"use client"
|
||||
|
||||
import { useInstantSearch } from "react-instantsearch"
|
||||
|
||||
/**
|
||||
* Whether the results InstantSearch is holding belong to the current query and
|
||||
* refinements. Until they do, `items` still carries the previous search's hits,
|
||||
* so rendering them shows stale products for a moment.
|
||||
*
|
||||
* `__isArtificial` is the flag InstantSearch puts on the placeholder results it
|
||||
* renders before its first response. It isn't part of the public types — hence
|
||||
* the cast — but it's the library's own signal, used the same way inside
|
||||
* `connectInfiniteHits`.
|
||||
*/
|
||||
export function useSearchSettled() {
|
||||
const { status, results } = useInstantSearch()
|
||||
|
||||
const isSearching = status !== "idle" && status !== "error"
|
||||
const hasNoResultsYet = Boolean(
|
||||
(results as unknown as { __isArtificial?: boolean } | undefined)
|
||||
?.__isArtificial
|
||||
)
|
||||
|
||||
return {
|
||||
isSearching,
|
||||
hasNoResultsYet,
|
||||
isSettled: !isSearching && !hasNoResultsYet,
|
||||
}
|
||||
}
|
||||
|
||||
export default useSearchSettled
|
||||
46
apps/suman-bosna/src/lib/hooks/use-toggle-state.tsx
Normal file
46
apps/suman-bosna/src/lib/hooks/use-toggle-state.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import { useState } from "react"
|
||||
|
||||
export type StateType = [boolean, () => void, () => void, () => void] & {
|
||||
state: boolean
|
||||
open: () => void
|
||||
close: () => void
|
||||
toggle: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param initialState - boolean
|
||||
* @returns An array like object with `state`, `open`, `close`, and `toggle` properties
|
||||
* to allow both object and array destructuring
|
||||
*
|
||||
* ```
|
||||
* const [showModal, openModal, closeModal, toggleModal] = useToggleState()
|
||||
* // or
|
||||
* const { state, open, close, toggle } = useToggleState()
|
||||
* ```
|
||||
*/
|
||||
|
||||
const useToggleState = (initialState = false) => {
|
||||
const [state, setState] = useState<boolean>(initialState)
|
||||
|
||||
const close = () => {
|
||||
setState(false)
|
||||
}
|
||||
|
||||
const open = () => {
|
||||
setState(true)
|
||||
}
|
||||
|
||||
const toggle = () => {
|
||||
setState((state) => !state)
|
||||
}
|
||||
|
||||
const hookData = [state, open, close, toggle] as StateType
|
||||
hookData.state = state
|
||||
hookData.open = open
|
||||
hookData.close = close
|
||||
hookData.toggle = toggle
|
||||
return hookData
|
||||
}
|
||||
|
||||
export default useToggleState
|
||||
57
apps/suman-bosna/src/lib/search-client.ts
Normal file
57
apps/suman-bosna/src/lib/search-client.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import {
|
||||
createInstantSearchAdapter,
|
||||
type MedusaSdkLike,
|
||||
} from "@medusajs/instantsearch-adapter"
|
||||
|
||||
import { sdk } from "@lib/config"
|
||||
|
||||
export const PRODUCT_INDEX_NAME = "product"
|
||||
|
||||
/**
|
||||
* The currencies the product index holds prices in, one field set each. Keep
|
||||
* in sync with `PRICE_CURRENCIES` in the backend's `src/search/product.ts`.
|
||||
*/
|
||||
export const SEARCH_PRICE_CURRENCIES = ["eur", "usd"]
|
||||
|
||||
export type PriceField =
|
||||
| "min_price"
|
||||
| "max_price"
|
||||
| "original_price"
|
||||
| "on_sale"
|
||||
|
||||
/**
|
||||
* The indexed currency to read prices in for a region. A region whose currency
|
||||
* the index doesn't hold falls back to the first one, so the listing still
|
||||
* shows a price rather than none.
|
||||
*/
|
||||
export const indexedCurrency = (currencyCode: string) => {
|
||||
const code = currencyCode.toLowerCase()
|
||||
return SEARCH_PRICE_CURRENCIES.includes(code)
|
||||
? code
|
||||
: SEARCH_PRICE_CURRENCIES[0]
|
||||
}
|
||||
|
||||
export const priceAttribute = (field: PriceField, currencyCode: string) =>
|
||||
`${field}_${indexedCurrency(currencyCode)}`
|
||||
|
||||
/**
|
||||
* Shared by the navbar search drawer and the store listing. An empty query
|
||||
* searches rather than short-circuiting, which is what the listing needs to
|
||||
* show every product before anything is refined.
|
||||
*/
|
||||
export const { searchClient } = createInstantSearchAdapter({
|
||||
sdk: sdk as unknown as MedusaSdkLike,
|
||||
path: "/store/search",
|
||||
additionalSearchParameters: {
|
||||
search_options: {
|
||||
match_strategy: "last",
|
||||
},
|
||||
},
|
||||
// Range widgets read `facets_stats`, which the adapter only produces for
|
||||
// fields listed here. The price fields are declared with a `stats` facet on
|
||||
// the index, which is what makes the stats available at all.
|
||||
numericAttributes: SEARCH_PRICE_CURRENCIES.flatMap((currency) => [
|
||||
`min_price_${currency}`,
|
||||
`max_price_${currency}`,
|
||||
]),
|
||||
})
|
||||
236
apps/suman-bosna/src/lib/ucp/mcp.ts
Normal file
236
apps/suman-bosna/src/lib/ucp/mcp.ts
Normal file
@@ -0,0 +1,236 @@
|
||||
import "server-only"
|
||||
import {
|
||||
cancelCart,
|
||||
cancelCheckout,
|
||||
completeCheckout,
|
||||
createCart,
|
||||
createCheckout,
|
||||
getCart,
|
||||
getCheckout,
|
||||
lookupCatalog,
|
||||
searchCatalog,
|
||||
updateCart,
|
||||
updateCheckout,
|
||||
} from "./operations"
|
||||
import { STORE_NAME } from "@lib/util/site"
|
||||
import { UcpResult } from "./ucp"
|
||||
|
||||
const SUPPORTED_PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26"]
|
||||
|
||||
type Args = Record<string, unknown>
|
||||
type JsonRpcId = string | number | null
|
||||
|
||||
const object = (properties: Record<string, unknown>, required: string[] = []) => ({
|
||||
type: "object",
|
||||
properties,
|
||||
required,
|
||||
})
|
||||
|
||||
const meta = object({
|
||||
"ucp-agent": object({ profile: { type: "string" } }),
|
||||
"idempotency-key": { type: "string" },
|
||||
})
|
||||
const id = { type: "string", description: "Cart or checkout session ID" }
|
||||
const context = object({
|
||||
address_country: { type: "string", description: "ISO 3166-1 alpha-2 country code" },
|
||||
})
|
||||
const lineItems = {
|
||||
type: "array",
|
||||
items: object(
|
||||
{
|
||||
item: object({ id: { type: "string", description: "Variant ID" } }, ["id"]),
|
||||
quantity: { type: "integer", minimum: 1, maximum: 100 },
|
||||
},
|
||||
["item", "quantity"]
|
||||
),
|
||||
}
|
||||
const checkoutInput = object({
|
||||
cart_id: { type: "string" },
|
||||
line_items: lineItems,
|
||||
buyer: object({
|
||||
email: { type: "string" },
|
||||
first_name: { type: "string" },
|
||||
last_name: { type: "string" },
|
||||
}),
|
||||
fulfillment: object({
|
||||
methods: {
|
||||
type: "array",
|
||||
items: object({
|
||||
type: { type: "string", enum: ["shipping"] },
|
||||
destinations: {
|
||||
type: "array",
|
||||
items: object({
|
||||
first_name: { type: "string" },
|
||||
last_name: { type: "string" },
|
||||
street_address: { type: "string" },
|
||||
extended_address: { type: "string" },
|
||||
address_locality: { type: "string" },
|
||||
address_region: { type: "string" },
|
||||
postal_code: { type: "string" },
|
||||
address_country: { type: "string" },
|
||||
}),
|
||||
},
|
||||
}),
|
||||
},
|
||||
}),
|
||||
context,
|
||||
})
|
||||
|
||||
const idempotencyKey = (args: Args) => {
|
||||
const key = (args.meta as Args | undefined)?.["idempotency-key"]
|
||||
return typeof key === "string" ? key : null
|
||||
}
|
||||
const nested = (args: Args, key: string) => (args[key] ?? {}) as Args
|
||||
const idArg = (args: Args) => (typeof args.id === "string" ? args.id : "")
|
||||
|
||||
type Tool = {
|
||||
description: string
|
||||
inputSchema: Record<string, unknown>
|
||||
run: (request: Request, args: Args) => Promise<UcpResult>
|
||||
}
|
||||
|
||||
const TOOLS: Record<string, Tool> = {
|
||||
search_catalog: {
|
||||
description: "Search the store's products by keyword. Returns products with variants, prices in minor units and availability.",
|
||||
inputSchema: object({
|
||||
meta,
|
||||
catalog: object({
|
||||
query: { type: "string" },
|
||||
pagination: object({ limit: { type: "integer" }, cursor: { type: "string" } }),
|
||||
context,
|
||||
}),
|
||||
}),
|
||||
run: (request, args) => searchCatalog(request, nested(args, "catalog")),
|
||||
},
|
||||
lookup_catalog: {
|
||||
description: "Look up products by product ID, variant ID or product handle.",
|
||||
inputSchema: object(
|
||||
{ meta, catalog: object({ ids: { type: "array", items: { type: "string" } }, context }, ["ids"]) },
|
||||
["catalog"]
|
||||
),
|
||||
run: (request, args) => lookupCatalog(request, nested(args, "catalog")),
|
||||
},
|
||||
get_product: {
|
||||
description: "Get one product by product ID, variant ID or handle.",
|
||||
inputSchema: object({ meta, catalog: object({ id: { type: "string" }, context }, ["id"]) }, ["catalog"]),
|
||||
run: (request, args) => {
|
||||
const catalog = nested(args, "catalog")
|
||||
return lookupCatalog(request, { ...catalog, ids: [catalog.id] })
|
||||
},
|
||||
},
|
||||
create_cart: {
|
||||
description: "Create a cart with line items (variant IDs and quantities).",
|
||||
inputSchema: object({ meta, cart: object({ line_items: lineItems, context }, ["line_items"]) }, ["cart"]),
|
||||
run: (request, args) => createCart(request, nested(args, "cart"), idempotencyKey(args)),
|
||||
},
|
||||
get_cart: {
|
||||
description: "Get a cart by ID.",
|
||||
inputSchema: object({ meta, id }, ["id"]),
|
||||
run: (request, args) => getCart(request, idArg(args)),
|
||||
},
|
||||
update_cart: {
|
||||
description: "Replace a cart's line items.",
|
||||
inputSchema: object({ meta, id, cart: object({ line_items: lineItems }, ["line_items"]) }, ["id", "cart"]),
|
||||
run: (request, args) => updateCart(request, idArg(args), nested(args, "cart")),
|
||||
},
|
||||
cancel_cart: {
|
||||
description: "Cancel a cart.",
|
||||
inputSchema: object({ meta, id }, ["id"]),
|
||||
run: (request, args) => cancelCart(request, idArg(args)),
|
||||
},
|
||||
create_checkout: {
|
||||
description:
|
||||
"Start a checkout from line items or an existing cart_id, with buyer email and shipping address. Payment is completed by the buyer at the returned continue_url.",
|
||||
inputSchema: object({ meta, checkout: checkoutInput }, ["checkout"]),
|
||||
run: (request, args) => createCheckout(request, nested(args, "checkout"), idempotencyKey(args)),
|
||||
},
|
||||
get_checkout: {
|
||||
description: "Get a checkout session by ID, including the order once the buyer has paid.",
|
||||
inputSchema: object({ meta, id }, ["id"]),
|
||||
run: (request, args) => getCheckout(request, idArg(args)),
|
||||
},
|
||||
update_checkout: {
|
||||
description: "Update a checkout session's line items, buyer or shipping address.",
|
||||
inputSchema: object({ meta, id, checkout: checkoutInput }, ["id", "checkout"]),
|
||||
run: (request, args) => updateCheckout(request, idArg(args), nested(args, "checkout")),
|
||||
},
|
||||
complete_checkout: {
|
||||
description:
|
||||
"Request completion. This store requires the buyer to pay at continue_url, so open sessions return requires_escalation.",
|
||||
inputSchema: object({ meta, id, checkout: { type: "object" } }, ["id"]),
|
||||
run: (request, args) => completeCheckout(request, idArg(args)),
|
||||
},
|
||||
cancel_checkout: {
|
||||
description: "Cancel a checkout session.",
|
||||
inputSchema: object({ meta, id }, ["id"]),
|
||||
run: (request, args) => cancelCheckout(request, idArg(args)),
|
||||
},
|
||||
}
|
||||
|
||||
const rpcResult = (id: JsonRpcId, result: unknown) =>
|
||||
Response.json({ jsonrpc: "2.0", id, result }, { headers: { "Cache-Control": "no-store" } })
|
||||
|
||||
const rpcError = (id: JsonRpcId, code: number, message: string, status = 200) =>
|
||||
Response.json(
|
||||
{ jsonrpc: "2.0", id, error: { code, message } },
|
||||
{ status, headers: { "Cache-Control": "no-store" } }
|
||||
)
|
||||
|
||||
/** Handles a stateless MCP Streamable HTTP POST with JSON (not SSE) responses. */
|
||||
export const handleMcpRequest = async (request: Request): Promise<Response> => {
|
||||
let message: Record<string, unknown>
|
||||
try {
|
||||
message = await request.json()
|
||||
} catch {
|
||||
return rpcError(null, -32700, "Parse error", 400)
|
||||
}
|
||||
if (!message || typeof message !== "object" || Array.isArray(message)) {
|
||||
return rpcError(null, -32600, "Invalid request: send a single JSON-RPC message", 400)
|
||||
}
|
||||
|
||||
const rpcId = (message.id ?? null) as JsonRpcId
|
||||
if (message.id === undefined) {
|
||||
return new Response(null, { status: 202 })
|
||||
}
|
||||
|
||||
const params = (message.params ?? {}) as Args
|
||||
|
||||
switch (message.method) {
|
||||
case "initialize": {
|
||||
const requested = params.protocolVersion
|
||||
return rpcResult(rpcId, {
|
||||
protocolVersion:
|
||||
typeof requested === "string" && SUPPORTED_PROTOCOL_VERSIONS.includes(requested)
|
||||
? requested
|
||||
: SUPPORTED_PROTOCOL_VERSIONS[0],
|
||||
capabilities: { tools: { listChanged: false } },
|
||||
serverInfo: { name: `${STORE_NAME} UCP`, version: "1.0.0" },
|
||||
instructions:
|
||||
"Universal Commerce Protocol shopping tools. Prices are in minor currency units. Checkout hands payment off to the buyer via continue_url.",
|
||||
})
|
||||
}
|
||||
case "ping":
|
||||
return rpcResult(rpcId, {})
|
||||
case "tools/list":
|
||||
return rpcResult(rpcId, {
|
||||
tools: Object.entries(TOOLS).map(([name, { description, inputSchema }]) => ({
|
||||
name,
|
||||
description,
|
||||
inputSchema,
|
||||
})),
|
||||
})
|
||||
case "tools/call": {
|
||||
const tool = typeof params.name === "string" ? TOOLS[params.name] : undefined
|
||||
if (!tool) return rpcError(rpcId, -32602, `Unknown tool: ${String(params.name)}`)
|
||||
|
||||
const { status, body } = await tool.run(request, (params.arguments ?? {}) as Args)
|
||||
return rpcResult(rpcId, {
|
||||
content: [{ type: "text", text: JSON.stringify(body) }],
|
||||
structuredContent: body,
|
||||
isError: status >= 400,
|
||||
})
|
||||
}
|
||||
default:
|
||||
return rpcError(rpcId, -32601, `Method not found: ${String(message.method)}`)
|
||||
}
|
||||
}
|
||||
547
apps/suman-bosna/src/lib/ucp/operations.ts
Normal file
547
apps/suman-bosna/src/lib/ucp/operations.ts
Normal file
@@ -0,0 +1,547 @@
|
||||
import "server-only"
|
||||
import { sdk } from "@lib/config"
|
||||
import { listRegions } from "@lib/data/regions"
|
||||
import { createCartWithItems, resolveRegion } from "@lib/util/server-cart"
|
||||
import { getRequestOrigin } from "@lib/util/site"
|
||||
import {
|
||||
cartContinueUrl,
|
||||
cartCountryCode,
|
||||
parseLineItems,
|
||||
toUcpLineItems,
|
||||
toUcpProduct,
|
||||
toUcpTotals,
|
||||
UCP_CART_FIELDS,
|
||||
UCP_PRODUCT_FIELDS,
|
||||
ucpError,
|
||||
ucpResult,
|
||||
UcpResult,
|
||||
} from "./ucp"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
|
||||
type Input = Record<string, unknown>
|
||||
|
||||
const CATALOG_SEARCH = "dev.ucp.shopping.catalog.search"
|
||||
const CATALOG_LOOKUP = "dev.ucp.shopping.catalog.lookup"
|
||||
const CART = "dev.ucp.shopping.cart"
|
||||
const CHECKOUT = "dev.ucp.shopping.checkout"
|
||||
|
||||
const MAX_SEARCH_LIMIT = 50
|
||||
const MAX_LOOKUP_IDS = 50
|
||||
const IDEMPOTENCY_TTL_MS = 10 * 60 * 1000
|
||||
const CANCELED_KEY = "ucp_canceled"
|
||||
|
||||
const asObject = (value: unknown): Input =>
|
||||
value && typeof value === "object" && !Array.isArray(value) ? (value as Input) : {}
|
||||
|
||||
const asString = (value: unknown) =>
|
||||
typeof value === "string" && value.trim() ? value.trim() : undefined
|
||||
|
||||
const contextCountry = (input: Input) => asString(asObject(input.context).address_country)
|
||||
|
||||
const unsupportedCountry = (name: Parameters<typeof ucpError>[0]) =>
|
||||
ucpError(name, 400, "unsupported_country", "This store doesn't sell to that country")
|
||||
|
||||
const invalidLineItems = (name: Parameters<typeof ucpError>[0]) =>
|
||||
ucpError(
|
||||
name,
|
||||
400,
|
||||
"invalid_request",
|
||||
"line_items must be an array of { item: { id }, quantity } with quantity 1-100"
|
||||
)
|
||||
|
||||
const itemUnavailable = (name: Parameters<typeof ucpError>[0]) =>
|
||||
ucpError(name, 422, "item_unavailable", "One or more items don't exist or can't be purchased")
|
||||
|
||||
const MAX_IDEMPOTENCY_ENTRIES = 500
|
||||
const idempotentResults = new Map<string, { expiresAt: number; value: Promise<unknown> }>()
|
||||
|
||||
/**
|
||||
* Runs `operation` once per idempotency key for 10 minutes. Kept in process
|
||||
* memory, so retries must reach the same server instance to be deduplicated.
|
||||
*/
|
||||
export const withIdempotency = <T>(
|
||||
key: string | null | undefined,
|
||||
scope: string,
|
||||
operation: () => Promise<T>
|
||||
): Promise<T> => {
|
||||
if (!key) {
|
||||
return operation()
|
||||
}
|
||||
|
||||
const cacheKey = `${scope}:${key}`
|
||||
const now = Date.now()
|
||||
const hit = idempotentResults.get(cacheKey)
|
||||
if (hit && hit.expiresAt > now) {
|
||||
return hit.value as Promise<T>
|
||||
}
|
||||
|
||||
if (idempotentResults.size >= MAX_IDEMPOTENCY_ENTRIES) {
|
||||
idempotentResults.forEach((entry, entryKey) => {
|
||||
if (entry.expiresAt <= now) idempotentResults.delete(entryKey)
|
||||
})
|
||||
if (idempotentResults.size >= MAX_IDEMPOTENCY_ENTRIES) {
|
||||
idempotentResults.delete(idempotentResults.keys().next().value!)
|
||||
}
|
||||
}
|
||||
|
||||
const value = operation()
|
||||
idempotentResults.set(cacheKey, { expiresAt: now + IDEMPOTENCY_TTL_MS, value })
|
||||
value.catch(() => idempotentResults.delete(cacheKey))
|
||||
return value
|
||||
}
|
||||
|
||||
// Catalog
|
||||
|
||||
export const searchCatalog = async (request: Request, input: Input): Promise<UcpResult> => {
|
||||
const query = asString(input.query)?.slice(0, 200)
|
||||
const pagination = asObject(input.pagination)
|
||||
const limit = Math.min(Math.max(Number(pagination.limit) || 20, 1), MAX_SEARCH_LIMIT)
|
||||
const offset = Math.max(parseInt(String(pagination.cursor ?? "0"), 10) || 0, 0)
|
||||
|
||||
const resolved = await resolveRegion(contextCountry(input))
|
||||
if (!resolved) return unsupportedCountry(CATALOG_SEARCH)
|
||||
|
||||
const { products, count } = await sdk.store.product.list({
|
||||
...(query ? { q: query } : {}),
|
||||
limit,
|
||||
offset,
|
||||
region_id: resolved.region.id,
|
||||
fields: UCP_PRODUCT_FIELDS,
|
||||
})
|
||||
|
||||
const base = `${getRequestOrigin(request)}/${resolved.countryCode}/products`
|
||||
const nextOffset = offset + products.length
|
||||
|
||||
return ucpResult(CATALOG_SEARCH, {
|
||||
products: products.map((product) =>
|
||||
toUcpProduct(product, resolved.region.currency_code, `${base}/${product.handle}`)
|
||||
),
|
||||
pagination: {
|
||||
has_next_page: nextOffset < count,
|
||||
cursor: nextOffset < count ? String(nextOffset) : undefined,
|
||||
total_count: count,
|
||||
},
|
||||
messages: [],
|
||||
})
|
||||
}
|
||||
|
||||
export const lookupCatalog = async (request: Request, input: Input): Promise<UcpResult> => {
|
||||
const ids = Array.isArray(input.ids)
|
||||
? input.ids.filter((id): id is string => typeof id === "string" && id.length > 0)
|
||||
: []
|
||||
if (!ids.length || ids.length > MAX_LOOKUP_IDS) {
|
||||
return ucpError(
|
||||
CATALOG_LOOKUP,
|
||||
400,
|
||||
"invalid_request",
|
||||
`"ids" must contain 1-${MAX_LOOKUP_IDS} identifiers`
|
||||
)
|
||||
}
|
||||
|
||||
const resolved = await resolveRegion(contextCountry(input))
|
||||
if (!resolved) return unsupportedCountry(CATALOG_LOOKUP)
|
||||
|
||||
const variantIds = ids.filter((id) => id.startsWith("variant_"))
|
||||
const handles = ids.filter((id) => !id.startsWith("prod_") && !id.startsWith("variant_"))
|
||||
const variantProductIds = variantIds.length
|
||||
? await sdk.client
|
||||
.fetch<{ variants: { product_id?: string | null }[] }>("/store/product-variants", {
|
||||
query: { id: variantIds, fields: "id,product_id", limit: MAX_LOOKUP_IDS },
|
||||
})
|
||||
.then(({ variants }) => variants.map((v) => v.product_id).filter((id): id is string => !!id))
|
||||
: []
|
||||
const productIds = Array.from(
|
||||
new Set([...ids.filter((id) => id.startsWith("prod_")), ...variantProductIds])
|
||||
)
|
||||
const common = { region_id: resolved.region.id, fields: UCP_PRODUCT_FIELDS, limit: MAX_LOOKUP_IDS }
|
||||
|
||||
const results = await Promise.all([
|
||||
productIds.length ? sdk.store.product.list({ ...common, id: productIds }) : null,
|
||||
handles.length ? sdk.store.product.list({ ...common, handle: handles }) : null,
|
||||
])
|
||||
|
||||
const products = new Map<string, HttpTypes.StoreProduct>()
|
||||
for (const result of results) {
|
||||
result?.products.forEach((product) => products.set(product.id, product))
|
||||
}
|
||||
|
||||
const found = new Set<string>()
|
||||
for (const product of Array.from(products.values())) {
|
||||
found.add(product.id)
|
||||
if (product.handle) found.add(product.handle)
|
||||
product.variants?.forEach((variant) => found.add(variant.id))
|
||||
}
|
||||
|
||||
const base = `${getRequestOrigin(request)}/${resolved.countryCode}/products`
|
||||
|
||||
return ucpResult(CATALOG_LOOKUP, {
|
||||
products: Array.from(products.values()).map((product) =>
|
||||
toUcpProduct(product, resolved.region.currency_code, `${base}/${product.handle}`)
|
||||
),
|
||||
messages: ids
|
||||
.filter((id) => !found.has(id))
|
||||
.map((id) => ({
|
||||
type: "info",
|
||||
code: "not_found",
|
||||
content: `No product or variant found for "${id}"`,
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
// Cart
|
||||
|
||||
const retrieveCart = async (cartId: string) => {
|
||||
try {
|
||||
const { cart } = await sdk.store.cart.retrieve(cartId, { fields: UCP_CART_FIELDS })
|
||||
return cart
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const isCanceled = (cart: HttpTypes.StoreCart) => cart.metadata?.[CANCELED_KEY] === true
|
||||
|
||||
const retrieveOpenCart = async (cartId: string) => {
|
||||
const cart = await retrieveCart(cartId)
|
||||
return cart && !cart.completed_at && !isCanceled(cart) ? cart : null
|
||||
}
|
||||
|
||||
const syncLineItems = async (
|
||||
cart: HttpTypes.StoreCart,
|
||||
items: { variant_id: string; quantity: number }[]
|
||||
) => {
|
||||
const desired = new Map(items.map((item) => [item.variant_id, item.quantity]))
|
||||
const existing = new Map((cart.items ?? []).map((line) => [line.variant_id, line]))
|
||||
|
||||
for (const [variantId, line] of Array.from(existing)) {
|
||||
const quantity = variantId ? desired.get(variantId) : undefined
|
||||
if (quantity === undefined) {
|
||||
await sdk.store.cart.deleteLineItem(cart.id, line.id)
|
||||
} else if (quantity !== line.quantity) {
|
||||
await sdk.store.cart.updateLineItem(cart.id, line.id, { quantity })
|
||||
}
|
||||
}
|
||||
for (const [variantId, quantity] of Array.from(desired)) {
|
||||
if (!existing.has(variantId)) {
|
||||
await sdk.store.cart.createLineItem(cart.id, { variant_id: variantId, quantity })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const toUcpCartBody = (request: Request, cart: HttpTypes.StoreCart) => ({
|
||||
id: cart.id,
|
||||
currency: cart.currency_code.toUpperCase(),
|
||||
line_items: toUcpLineItems(cart),
|
||||
totals: toUcpTotals(cart),
|
||||
continue_url: cartContinueUrl(getRequestOrigin(request), cart),
|
||||
messages: [],
|
||||
})
|
||||
|
||||
const cartNotFound = () => ucpError(CART, 404, "not_found", "Cart not found")
|
||||
|
||||
export const createCart = async (
|
||||
request: Request,
|
||||
input: Input,
|
||||
idempotencyKey?: string | null
|
||||
): Promise<UcpResult> => {
|
||||
const items = parseLineItems(input.line_items ?? [])
|
||||
if (!items) return invalidLineItems(CART)
|
||||
|
||||
const resolved = await resolveRegion(contextCountry(input))
|
||||
if (!resolved) return unsupportedCountry(CART)
|
||||
|
||||
let cartId: string
|
||||
try {
|
||||
cartId = await withIdempotency(idempotencyKey, "cart", () =>
|
||||
createCartWithItems(resolved.region.id, items)
|
||||
)
|
||||
} catch {
|
||||
return itemUnavailable(CART)
|
||||
}
|
||||
|
||||
const cart = await retrieveCart(cartId)
|
||||
return cart ? ucpResult(CART, toUcpCartBody(request, cart), 201) : cartNotFound()
|
||||
}
|
||||
|
||||
export const getCart = async (request: Request, cartId: string): Promise<UcpResult> => {
|
||||
const cart = await retrieveOpenCart(cartId)
|
||||
return cart ? ucpResult(CART, toUcpCartBody(request, cart)) : cartNotFound()
|
||||
}
|
||||
|
||||
export const updateCart = async (
|
||||
request: Request,
|
||||
cartId: string,
|
||||
input: Input
|
||||
): Promise<UcpResult> => {
|
||||
const items = parseLineItems(input.line_items)
|
||||
if (!items) return invalidLineItems(CART)
|
||||
|
||||
const cart = await retrieveOpenCart(cartId)
|
||||
if (!cart) return cartNotFound()
|
||||
|
||||
try {
|
||||
await syncLineItems(cart, items)
|
||||
} catch {
|
||||
return itemUnavailable(CART)
|
||||
}
|
||||
|
||||
const updated = await retrieveCart(cart.id)
|
||||
return updated ? ucpResult(CART, toUcpCartBody(request, updated)) : cartNotFound()
|
||||
}
|
||||
|
||||
export const cancelCart = async (request: Request, cartId: string): Promise<UcpResult> => {
|
||||
const cart = await retrieveOpenCart(cartId)
|
||||
if (!cart) return cartNotFound()
|
||||
|
||||
await sdk.store.cart.update(cart.id, { metadata: { ...cart.metadata, [CANCELED_KEY]: true } })
|
||||
return ucpResult(CART, {
|
||||
...toUcpCartBody(request, cart),
|
||||
continue_url: undefined,
|
||||
messages: [{ type: "info", code: "canceled", content: "Cart canceled" }],
|
||||
})
|
||||
}
|
||||
|
||||
// Checkout
|
||||
|
||||
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
|
||||
const firstItem = (value: unknown) => asObject(Array.isArray(value) ? value[0] : undefined)
|
||||
|
||||
const firstDestination = (input: Input) =>
|
||||
firstItem(firstItem(asObject(input.fulfillment).methods).destinations)
|
||||
|
||||
const applyCheckoutDetails = async (
|
||||
cart: HttpTypes.StoreCart,
|
||||
input: Input
|
||||
): Promise<UcpResult | null> => {
|
||||
const buyer = asObject(input.buyer)
|
||||
const destination = firstDestination(input)
|
||||
|
||||
const update: HttpTypes.StoreUpdateCart = {}
|
||||
|
||||
const email = asString(buyer.email)
|
||||
if (email) {
|
||||
if (!EMAIL_PATTERN.test(email)) {
|
||||
return ucpError(CHECKOUT, 400, "invalid_email", "buyer.email is not a valid email address")
|
||||
}
|
||||
update.email = email
|
||||
}
|
||||
|
||||
const countryCode = asString(destination.address_country)?.toLowerCase()
|
||||
if (countryCode) {
|
||||
const inCartRegion = cart.region?.countries?.some((c) => c.iso_2 === countryCode)
|
||||
if (!inCartRegion) {
|
||||
const regions = await listRegions()
|
||||
const region = regions.find((r) => r.countries?.some((c) => c.iso_2 === countryCode))
|
||||
if (!region) return unsupportedCountry(CHECKOUT)
|
||||
update.region_id = region.id
|
||||
}
|
||||
|
||||
update.shipping_address = {
|
||||
first_name: asString(destination.first_name) ?? asString(buyer.first_name),
|
||||
last_name: asString(destination.last_name) ?? asString(buyer.last_name),
|
||||
address_1: asString(destination.street_address),
|
||||
address_2: asString(destination.extended_address),
|
||||
city: asString(destination.address_locality),
|
||||
province: asString(destination.address_region),
|
||||
postal_code: asString(destination.postal_code),
|
||||
phone: asString(destination.phone_number) ?? asString(buyer.phone_number),
|
||||
country_code: countryCode,
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(update).length) {
|
||||
await sdk.store.cart.update(cart.id, update)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// Only call for carts with `completed_at` set: completing an already-completed
|
||||
// cart returns its existing order (the Store API cart route doesn't expose it).
|
||||
const findOrder = async (cartId: string) => {
|
||||
try {
|
||||
const result = await sdk.store.cart.complete(cartId, { fields: "id,display_id" })
|
||||
return result.type === "order" ? result.order : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const toUcpCheckoutBody = async (request: Request, cart: HttpTypes.StoreCart) => {
|
||||
const origin = getRequestOrigin(request)
|
||||
const countryCode = cartCountryCode(cart)
|
||||
const base = `${origin}/${countryCode}`
|
||||
const address = cart.shipping_address
|
||||
|
||||
const missing = [
|
||||
!cart.email && { path: "$.buyer.email", content: "Buyer email is required" },
|
||||
!address?.address_1 && {
|
||||
path: "$.fulfillment.methods[0].destinations[0]",
|
||||
content: "A shipping destination is required",
|
||||
},
|
||||
].filter(Boolean) as { path: string; content: string }[]
|
||||
|
||||
const order = cart.completed_at ? await findOrder(cart.id) : null
|
||||
const status = isCanceled(cart)
|
||||
? "canceled"
|
||||
: order
|
||||
? "completed"
|
||||
: missing.length
|
||||
? "incomplete"
|
||||
: "requires_escalation"
|
||||
const isOpen = status === "incomplete" || status === "requires_escalation"
|
||||
|
||||
return {
|
||||
id: cart.id,
|
||||
status,
|
||||
currency: cart.currency_code.toUpperCase(),
|
||||
line_items: toUcpLineItems(cart),
|
||||
totals: toUcpTotals(cart),
|
||||
buyer: cart.email ? { email: cart.email } : undefined,
|
||||
fulfillment: address?.address_1
|
||||
? {
|
||||
methods: [
|
||||
{
|
||||
type: "shipping",
|
||||
destinations: [
|
||||
{
|
||||
first_name: address.first_name ?? undefined,
|
||||
last_name: address.last_name ?? undefined,
|
||||
street_address: address.address_1,
|
||||
extended_address: address.address_2 ?? undefined,
|
||||
address_locality: address.city ?? undefined,
|
||||
address_region: address.province ?? undefined,
|
||||
postal_code: address.postal_code ?? undefined,
|
||||
address_country: address.country_code?.toUpperCase(),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
: undefined,
|
||||
links: [
|
||||
{ type: "terms_of_service", url: `${base}/terms` },
|
||||
{ type: "privacy_policy", url: `${base}/privacy` },
|
||||
{ type: "refund_policy", url: `${base}/returns` },
|
||||
{ type: "shipping_policy", url: `${base}/shipping` },
|
||||
],
|
||||
order: order
|
||||
? { id: order.id, permalink_url: `${base}/order/${order.id}/confirmed` }
|
||||
: undefined,
|
||||
continue_url: isOpen ? cartContinueUrl(origin, cart) : undefined,
|
||||
messages: isOpen
|
||||
? [
|
||||
...missing.map(({ path, content }) => ({
|
||||
type: "error",
|
||||
code: "missing",
|
||||
path,
|
||||
content,
|
||||
severity: "recoverable",
|
||||
})),
|
||||
{
|
||||
type: "error",
|
||||
code: "payment_required",
|
||||
content:
|
||||
"This store doesn't accept payment through the API. The buyer selects delivery and pays at continue_url.",
|
||||
severity: "requires_buyer_input",
|
||||
},
|
||||
]
|
||||
: [],
|
||||
}
|
||||
}
|
||||
|
||||
const checkoutNotFound = () => ucpError(CHECKOUT, 404, "not_found", "Checkout session not found")
|
||||
|
||||
export const createCheckout = async (
|
||||
request: Request,
|
||||
input: Input,
|
||||
idempotencyKey?: string | null
|
||||
): Promise<UcpResult> => {
|
||||
const destinationCountry = asString(firstDestination(input).address_country)
|
||||
|
||||
let cartId = asString(input.cart_id)
|
||||
if (cartId) {
|
||||
if (!(await retrieveOpenCart(cartId))) {
|
||||
return ucpError(CHECKOUT, 404, "not_found", "Cart not found")
|
||||
}
|
||||
} else {
|
||||
const items = parseLineItems(input.line_items)
|
||||
if (!items?.length) return invalidLineItems(CHECKOUT)
|
||||
|
||||
const resolved = await resolveRegion(destinationCountry ?? contextCountry(input))
|
||||
if (!resolved) return unsupportedCountry(CHECKOUT)
|
||||
|
||||
try {
|
||||
cartId = await withIdempotency(idempotencyKey, "checkout", () =>
|
||||
createCartWithItems(resolved.region.id, items)
|
||||
)
|
||||
} catch {
|
||||
return itemUnavailable(CHECKOUT)
|
||||
}
|
||||
}
|
||||
|
||||
const cart = await retrieveOpenCart(cartId)
|
||||
if (!cart) return checkoutNotFound()
|
||||
|
||||
const error = await applyCheckoutDetails(cart, input)
|
||||
if (error) return error
|
||||
|
||||
const updated = await retrieveCart(cart.id)
|
||||
return updated
|
||||
? ucpResult(CHECKOUT, await toUcpCheckoutBody(request, updated), 201)
|
||||
: checkoutNotFound()
|
||||
}
|
||||
|
||||
export const getCheckout = async (request: Request, id: string): Promise<UcpResult> => {
|
||||
const cart = await retrieveCart(id)
|
||||
return cart ? ucpResult(CHECKOUT, await toUcpCheckoutBody(request, cart)) : checkoutNotFound()
|
||||
}
|
||||
|
||||
export const updateCheckout = async (
|
||||
request: Request,
|
||||
id: string,
|
||||
input: Input
|
||||
): Promise<UcpResult> => {
|
||||
const cart = await retrieveOpenCart(id)
|
||||
if (!cart) return checkoutNotFound()
|
||||
|
||||
if (input.line_items !== undefined) {
|
||||
const items = parseLineItems(input.line_items)
|
||||
if (!items?.length) return invalidLineItems(CHECKOUT)
|
||||
try {
|
||||
await syncLineItems(cart, items)
|
||||
} catch {
|
||||
return itemUnavailable(CHECKOUT)
|
||||
}
|
||||
}
|
||||
|
||||
const error = await applyCheckoutDetails(cart, input)
|
||||
if (error) return error
|
||||
|
||||
const updated = await retrieveCart(cart.id)
|
||||
return updated
|
||||
? ucpResult(CHECKOUT, await toUcpCheckoutBody(request, updated))
|
||||
: checkoutNotFound()
|
||||
}
|
||||
|
||||
/**
|
||||
* Payment can't be taken through the API, so completing an open session
|
||||
* returns it unchanged with `requires_escalation` and a `continue_url`.
|
||||
*/
|
||||
export const completeCheckout = (request: Request, id: string) => getCheckout(request, id)
|
||||
|
||||
export const cancelCheckout = async (request: Request, id: string): Promise<UcpResult> => {
|
||||
const cart = await retrieveCart(id)
|
||||
if (!cart) return checkoutNotFound()
|
||||
if (cart.completed_at) {
|
||||
return ucpError(CHECKOUT, 409, "already_completed", "This checkout has already been completed")
|
||||
}
|
||||
|
||||
if (!isCanceled(cart)) {
|
||||
await sdk.store.cart.update(cart.id, { metadata: { ...cart.metadata, [CANCELED_KEY]: true } })
|
||||
}
|
||||
const updated = await retrieveCart(cart.id)
|
||||
return updated
|
||||
? ucpResult(CHECKOUT, await toUcpCheckoutBody(request, updated))
|
||||
: checkoutNotFound()
|
||||
}
|
||||
203
apps/suman-bosna/src/lib/ucp/ucp.ts
Normal file
203
apps/suman-bosna/src/lib/ucp/ucp.ts
Normal file
@@ -0,0 +1,203 @@
|
||||
import { isVariantInStock } from "@lib/util/inventory"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
|
||||
export const UCP_VERSION = "2026-08-25"
|
||||
export const UCP_REST_BASE_PATH = "/ucp/v1"
|
||||
export const UCP_MCP_PATH = "/ucp/mcp"
|
||||
|
||||
const capability = (path: string, schema: string) => ({
|
||||
spec: `https://ucp.dev/${UCP_VERSION}/specification/shopping/${path}`,
|
||||
schema: `https://ucp.dev/${UCP_VERSION}/schemas/shopping/${schema}.json`,
|
||||
})
|
||||
|
||||
export const UCP_CAPABILITIES = {
|
||||
"dev.ucp.shopping.catalog.search": capability("catalog/search", "catalog_search"),
|
||||
"dev.ucp.shopping.catalog.lookup": capability("catalog/lookup", "catalog_lookup"),
|
||||
"dev.ucp.shopping.cart": capability("cart", "cart"),
|
||||
"dev.ucp.shopping.checkout": capability("checkout", "checkout"),
|
||||
} as const
|
||||
|
||||
export type CapabilityName = keyof typeof UCP_CAPABILITIES
|
||||
|
||||
export type UcpResult = { status: number; body: Record<string, unknown> }
|
||||
|
||||
export const UCP_PRODUCT_FIELDS =
|
||||
"id,title,handle,description,thumbnail,*images,*options,*variants,+variants.inventory_quantity,+variants.manage_inventory,+variants.allow_backorder,*variants.calculated_price,*variants.options"
|
||||
|
||||
export const UCP_CART_FIELDS =
|
||||
"id,email,currency_code,region_id,completed_at,metadata,*items,+items.subtotal,+items.total,item_subtotal,discount_total,shipping_total,tax_total,total,*region.countries,*shipping_address"
|
||||
|
||||
const minorUnitDigits = (currency: string) =>
|
||||
new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions()
|
||||
.maximumFractionDigits ?? 2
|
||||
|
||||
/** Converts a Medusa amount (major units) to UCP minor units. */
|
||||
export const toMinorUnits = (amount: number | null | undefined, currencyCode: string) =>
|
||||
Math.round((amount ?? 0) * 10 ** minorUnitDigits(currencyCode.toUpperCase()))
|
||||
|
||||
const toMoney = (amount: number | null | undefined, currencyCode: string) => ({
|
||||
amount: toMinorUnits(amount, currencyCode),
|
||||
currency: currencyCode.toUpperCase(),
|
||||
})
|
||||
|
||||
export const ucpResult = (
|
||||
name: CapabilityName,
|
||||
body: Record<string, unknown>,
|
||||
status = 200
|
||||
): UcpResult => ({
|
||||
status,
|
||||
body: {
|
||||
ucp: {
|
||||
version: UCP_VERSION,
|
||||
status: status < 400 ? "success" : "error",
|
||||
capabilities: { [name]: [{ version: UCP_VERSION }] },
|
||||
...(name === "dev.ucp.shopping.checkout" ? { payment_handlers: {} } : {}),
|
||||
},
|
||||
...body,
|
||||
},
|
||||
})
|
||||
|
||||
export const ucpError = (
|
||||
name: CapabilityName,
|
||||
status: number,
|
||||
code: string,
|
||||
content: string
|
||||
): UcpResult =>
|
||||
ucpResult(
|
||||
name,
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
type: "error",
|
||||
code,
|
||||
content,
|
||||
severity: status >= 500 ? "recoverable" : "unrecoverable",
|
||||
},
|
||||
],
|
||||
},
|
||||
status
|
||||
)
|
||||
|
||||
export const toResponse = ({ status, body }: UcpResult) =>
|
||||
Response.json(body, { status, headers: { "Cache-Control": "no-store" } })
|
||||
|
||||
export const readJsonBody = async (
|
||||
request: Request
|
||||
): Promise<Record<string, unknown> | null> => {
|
||||
try {
|
||||
const body = await request.json()
|
||||
return body && typeof body === "object" && !Array.isArray(body) ? body : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const toUcpProduct = (
|
||||
product: HttpTypes.StoreProduct,
|
||||
currencyCode: string,
|
||||
productUrl: string
|
||||
) => {
|
||||
const optionTitles = new Map(
|
||||
(product.options ?? []).map((option) => [option.id, option.title])
|
||||
)
|
||||
const variants = (product.variants ?? []).filter(
|
||||
(variant) => variant.calculated_price?.calculated_amount != null
|
||||
)
|
||||
const amounts = variants.map((v) => v.calculated_price!.calculated_amount!)
|
||||
|
||||
return {
|
||||
id: product.id,
|
||||
handle: product.handle,
|
||||
title: product.title,
|
||||
description: product.description ?? "",
|
||||
url: productUrl,
|
||||
media: (product.images ?? []).map((image) => ({
|
||||
type: "image",
|
||||
url: image.url,
|
||||
alt_text: product.title,
|
||||
})),
|
||||
price_range: amounts.length
|
||||
? {
|
||||
min: toMoney(Math.min(...amounts), currencyCode),
|
||||
max: toMoney(Math.max(...amounts), currencyCode),
|
||||
}
|
||||
: undefined,
|
||||
variants: variants.map((variant) => {
|
||||
const available = isVariantInStock(variant)
|
||||
return {
|
||||
id: variant.id,
|
||||
sku: variant.sku ?? undefined,
|
||||
title: variant.title ?? product.title,
|
||||
url: `${productUrl}?v_id=${variant.id}`,
|
||||
price: toMoney(variant.calculated_price!.calculated_amount, currencyCode),
|
||||
availability: { available, status: available ? "in_stock" : "out_of_stock" },
|
||||
options: (variant.options ?? []).map((value) => ({
|
||||
name: optionTitles.get(value.option_id ?? "") ?? "",
|
||||
value: value.value,
|
||||
})),
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
export const toUcpLineItems = (cart: HttpTypes.StoreCart) =>
|
||||
(cart.items ?? []).map((item) => ({
|
||||
id: item.id,
|
||||
item: {
|
||||
id: item.variant_id,
|
||||
title: [item.product_title, item.variant_title].filter(Boolean).join(" - "),
|
||||
price: toMinorUnits(item.unit_price, cart.currency_code),
|
||||
},
|
||||
quantity: item.quantity,
|
||||
totals: [
|
||||
{ type: "subtotal", amount: toMinorUnits(item.subtotal, cart.currency_code) },
|
||||
{ type: "total", amount: toMinorUnits(item.total, cart.currency_code) },
|
||||
],
|
||||
}))
|
||||
|
||||
export const toUcpTotals = (cart: HttpTypes.StoreCart) => [
|
||||
{ type: "subtotal", amount: toMinorUnits(cart.item_subtotal, cart.currency_code) },
|
||||
{ type: "discount", amount: toMinorUnits(cart.discount_total, cart.currency_code) },
|
||||
{ type: "fulfillment", amount: toMinorUnits(cart.shipping_total, cart.currency_code) },
|
||||
{ type: "tax", amount: toMinorUnits(cart.tax_total, cart.currency_code) },
|
||||
{ type: "total", amount: toMinorUnits(cart.total, cart.currency_code) },
|
||||
]
|
||||
|
||||
const MAX_LINE_ITEMS = 50
|
||||
const MAX_QUANTITY = 100
|
||||
|
||||
/** Validates a UCP `line_items` array into Medusa variant/quantity pairs. */
|
||||
export const parseLineItems = (
|
||||
value: unknown
|
||||
): { variant_id: string; quantity: number }[] | null => {
|
||||
if (!Array.isArray(value) || value.length > MAX_LINE_ITEMS) {
|
||||
return null
|
||||
}
|
||||
|
||||
const items: { variant_id: string; quantity: number }[] = []
|
||||
for (const entry of value) {
|
||||
const id = entry?.item?.id
|
||||
const quantity = entry?.quantity
|
||||
if (
|
||||
typeof id !== "string" ||
|
||||
!id ||
|
||||
!Number.isInteger(quantity) ||
|
||||
quantity < 1 ||
|
||||
quantity > MAX_QUANTITY
|
||||
) {
|
||||
return null
|
||||
}
|
||||
items.push({ variant_id: id, quantity })
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
export const cartCountryCode = (cart: HttpTypes.StoreCart) =>
|
||||
(
|
||||
cart.shipping_address?.country_code ??
|
||||
cart.region?.countries?.[0]?.iso_2 ??
|
||||
""
|
||||
).toLowerCase()
|
||||
|
||||
export const cartContinueUrl = (origin: string, cart: HttpTypes.StoreCart) =>
|
||||
`${origin}/${cartCountryCode(cart)}/cart/resume/${cart.id}`
|
||||
6
apps/suman-bosna/src/lib/util/cart-events.ts
Normal file
6
apps/suman-bosna/src/lib/util/cart-events.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export const CART_UPDATED_EVENT = "medusa:cart-updated"
|
||||
|
||||
/** Lets client-loaded cart UI refresh after a mutation on statically rendered pages. */
|
||||
export const notifyCartUpdated = () => {
|
||||
window.dispatchEvent(new Event(CART_UPDATED_EVENT))
|
||||
}
|
||||
28
apps/suman-bosna/src/lib/util/compare-addresses.ts
Normal file
28
apps/suman-bosna/src/lib/util/compare-addresses.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { isEqual, pick } from "lodash"
|
||||
|
||||
export default function compareAddresses(address1: object, address2: object) {
|
||||
return isEqual(
|
||||
pick(address1, [
|
||||
"first_name",
|
||||
"last_name",
|
||||
"address_1",
|
||||
"company",
|
||||
"postal_code",
|
||||
"city",
|
||||
"country_code",
|
||||
"province",
|
||||
"phone",
|
||||
]),
|
||||
pick(address2, [
|
||||
"first_name",
|
||||
"last_name",
|
||||
"address_1",
|
||||
"company",
|
||||
"postal_code",
|
||||
"city",
|
||||
"country_code",
|
||||
"province",
|
||||
"phone",
|
||||
])
|
||||
)
|
||||
}
|
||||
3
apps/suman-bosna/src/lib/util/env.ts
Normal file
3
apps/suman-bosna/src/lib/util/env.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export const getBaseURL = () => {
|
||||
return process.env.NEXT_PUBLIC_BASE_URL || "https://localhost:8000"
|
||||
}
|
||||
8
apps/suman-bosna/src/lib/util/get-locale-header.ts
Normal file
8
apps/suman-bosna/src/lib/util/get-locale-header.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { getLocale } from "@lib/data/locale-actions"
|
||||
|
||||
export async function getLocaleHeader() {
|
||||
const locale = await getLocale()
|
||||
return {
|
||||
"x-medusa-locale": locale,
|
||||
} as const
|
||||
}
|
||||
6
apps/suman-bosna/src/lib/util/get-percentage-diff.ts
Normal file
6
apps/suman-bosna/src/lib/util/get-percentage-diff.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export const getPercentageDiff = (original: number, calculated: number) => {
|
||||
const diff = original - calculated
|
||||
const decrease = (diff / original) * 100
|
||||
|
||||
return decrease.toFixed()
|
||||
}
|
||||
90
apps/suman-bosna/src/lib/util/get-product-price.ts
Normal file
90
apps/suman-bosna/src/lib/util/get-product-price.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { getPercentageDiff } from "./get-percentage-diff"
|
||||
import { convertToLocale } from "./money"
|
||||
|
||||
type VariantWithPrice = HttpTypes.StoreProductVariant & {
|
||||
calculated_price?: {
|
||||
calculated_amount: number
|
||||
original_amount: number
|
||||
currency_code: string
|
||||
calculated_price: {
|
||||
price_list_type: string
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const getPricesForVariant = (variant: VariantWithPrice) => {
|
||||
if (!variant?.calculated_price?.calculated_amount) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
calculated_price_number: variant.calculated_price.calculated_amount,
|
||||
calculated_price: convertToLocale({
|
||||
amount: variant.calculated_price.calculated_amount,
|
||||
currency_code: variant.calculated_price.currency_code,
|
||||
}),
|
||||
original_price_number: variant.calculated_price.original_amount,
|
||||
original_price: convertToLocale({
|
||||
amount: variant.calculated_price.original_amount,
|
||||
currency_code: variant.calculated_price.currency_code,
|
||||
}),
|
||||
currency_code: variant.calculated_price.currency_code,
|
||||
price_type: variant.calculated_price.calculated_price.price_list_type,
|
||||
percentage_diff: getPercentageDiff(
|
||||
variant.calculated_price.original_amount,
|
||||
variant.calculated_price.calculated_amount
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
export function getProductPrice({
|
||||
product,
|
||||
variantId,
|
||||
}: {
|
||||
product: HttpTypes.StoreProduct
|
||||
variantId?: string
|
||||
}) {
|
||||
if (!product || !product.id) {
|
||||
throw new Error("No product provided")
|
||||
}
|
||||
|
||||
const cheapestPrice = () => {
|
||||
if (!product || !product.variants?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const cheapestVariant = (product.variants as VariantWithPrice[])
|
||||
.filter((v) => !!v.calculated_price)
|
||||
.sort((a, b) => {
|
||||
return (
|
||||
(a.calculated_price?.calculated_amount ?? 0) -
|
||||
(b.calculated_price?.calculated_amount ?? 0)
|
||||
)
|
||||
})[0]
|
||||
|
||||
return getPricesForVariant(cheapestVariant)
|
||||
}
|
||||
|
||||
const variantPrice = () => {
|
||||
if (!product || !variantId) {
|
||||
return null
|
||||
}
|
||||
|
||||
const variant = product.variants?.find(
|
||||
(v) => v.id === variantId || v.sku === variantId
|
||||
) as VariantWithPrice | undefined
|
||||
|
||||
if (!variant) {
|
||||
return null
|
||||
}
|
||||
|
||||
return getPricesForVariant(variant)
|
||||
}
|
||||
|
||||
return {
|
||||
product,
|
||||
cheapestPrice: cheapestPrice(),
|
||||
variantPrice: variantPrice(),
|
||||
}
|
||||
}
|
||||
9
apps/suman-bosna/src/lib/util/inventory.ts
Normal file
9
apps/suman-bosna/src/lib/util/inventory.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
|
||||
export const isVariantInStock = (
|
||||
variant: HttpTypes.StoreProductVariant | undefined
|
||||
) =>
|
||||
!!variant &&
|
||||
(!variant.manage_inventory ||
|
||||
!!variant.allow_backorder ||
|
||||
(variant.inventory_quantity ?? 0) > 0)
|
||||
11
apps/suman-bosna/src/lib/util/isEmpty.ts
Normal file
11
apps/suman-bosna/src/lib/util/isEmpty.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
export const isObject = (input: unknown) => input instanceof Object
|
||||
export const isArray = (input: unknown) => Array.isArray(input)
|
||||
export const isEmpty = (input: unknown) => {
|
||||
return (
|
||||
input === null ||
|
||||
input === undefined ||
|
||||
(isObject(input) && Object.keys(input as Record<string, unknown>).length === 0) ||
|
||||
(isArray(input) && (input as unknown[]).length === 0) ||
|
||||
(typeof input === "string" && input.trim().length === 0)
|
||||
)
|
||||
}
|
||||
33
apps/suman-bosna/src/lib/util/medusa-error.ts
Normal file
33
apps/suman-bosna/src/lib/util/medusa-error.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
type MedusaError = {
|
||||
response?: {
|
||||
data: { message?: string } | string
|
||||
status: number
|
||||
headers: unknown
|
||||
}
|
||||
request?: unknown
|
||||
message?: string
|
||||
config?: { url: string; baseURL: string }
|
||||
}
|
||||
|
||||
export default function medusaError(error: unknown): never {
|
||||
const err = error as MedusaError
|
||||
if (err.response) {
|
||||
const u = new URL(err.config?.url ?? "", err.config?.baseURL ?? "")
|
||||
console.error("Resource:", u.toString())
|
||||
console.error("Response data:", err.response.data)
|
||||
console.error("Status code:", err.response.status)
|
||||
console.error("Headers:", err.response.headers)
|
||||
|
||||
const data = err.response.data
|
||||
const message =
|
||||
typeof data === "object" && data !== null
|
||||
? data.message || String(data)
|
||||
: data
|
||||
|
||||
throw new Error(message.charAt(0).toUpperCase() + message.slice(1) + ".")
|
||||
} else if (err.request) {
|
||||
throw new Error("No response received: " + String(err.request))
|
||||
} else {
|
||||
throw new Error("Error setting up the request: " + err.message)
|
||||
}
|
||||
}
|
||||
26
apps/suman-bosna/src/lib/util/money.ts
Normal file
26
apps/suman-bosna/src/lib/util/money.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { isEmpty } from "./isEmpty"
|
||||
|
||||
type ConvertToLocaleParams = {
|
||||
amount: number
|
||||
currency_code: string
|
||||
minimumFractionDigits?: number
|
||||
maximumFractionDigits?: number
|
||||
locale?: string
|
||||
}
|
||||
|
||||
export const convertToLocale = ({
|
||||
amount,
|
||||
currency_code,
|
||||
minimumFractionDigits,
|
||||
maximumFractionDigits,
|
||||
locale = "en-US",
|
||||
}: ConvertToLocaleParams) => {
|
||||
return currency_code && !isEmpty(currency_code)
|
||||
? new Intl.NumberFormat(locale, {
|
||||
style: "currency",
|
||||
currency: currency_code,
|
||||
minimumFractionDigits,
|
||||
maximumFractionDigits,
|
||||
}).format(amount)
|
||||
: amount.toString()
|
||||
}
|
||||
21
apps/suman-bosna/src/lib/util/payment-error.ts
Normal file
21
apps/suman-bosna/src/lib/util/payment-error.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import type { StripeError } from "@stripe/stripe-js"
|
||||
|
||||
const GENERIC_PAYMENT_ERROR =
|
||||
"We couldn't process your payment. Please try again or use a different payment method."
|
||||
|
||||
// Only card and validation errors are meant for customers, others describe our setup, so they're logged instead.
|
||||
export const getPaymentErrorMessage = (error?: Partial<StripeError> | null) => {
|
||||
if (!error) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (
|
||||
(error.type === "card_error" || error.type === "validation_error") &&
|
||||
error.message
|
||||
) {
|
||||
return error.message
|
||||
}
|
||||
|
||||
console.error("Payment failed", error)
|
||||
return GENERIC_PAYMENT_ERROR
|
||||
}
|
||||
77
apps/suman-bosna/src/lib/util/product-markdown.ts
Normal file
77
apps/suman-bosna/src/lib/util/product-markdown.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { isVariantInStock } from "./inventory"
|
||||
import { convertToLocale } from "./money"
|
||||
import { getPricedVariants } from "./product-structured-data"
|
||||
import { formatDayRange, getRegionPolicies } from "./store-policies"
|
||||
|
||||
export const renderProductMarkdown = ({
|
||||
product,
|
||||
region,
|
||||
origin,
|
||||
countryCode,
|
||||
}: {
|
||||
product: HttpTypes.StoreProduct
|
||||
region: HttpTypes.StoreRegion
|
||||
origin: string
|
||||
countryCode: string
|
||||
}) => {
|
||||
const base = `${origin}/${countryCode}`
|
||||
const productUrl = `${base}/products/${product.handle}`
|
||||
const currency = region.currency_code
|
||||
const policies = getRegionPolicies(region)
|
||||
const optionTitles = new Map(
|
||||
(product.options ?? []).map((option) => [option.id, option.title])
|
||||
)
|
||||
|
||||
const policyLines = policies
|
||||
? `
|
||||
- Shipping: ${
|
||||
policies.shippingRate === 0
|
||||
? "free"
|
||||
: convertToLocale({ amount: policies.shippingRate, currency_code: currency })
|
||||
}, ships in ${formatDayRange(policies.handlingDays)} business days, delivery ${formatDayRange(policies.transitDays)} business days
|
||||
- Returns: within ${policies.returnWindowDays} days of delivery, ${
|
||||
policies.freeReturns ? "free return shipping" : "return shipping paid by the customer"
|
||||
}`
|
||||
: ""
|
||||
|
||||
const variants = getPricedVariants(product)
|
||||
const variantRows = variants.map((variant) => {
|
||||
const options = (variant.options ?? [])
|
||||
.map((value) => `${optionTitles.get(value.option_id ?? "") ?? "Option"}: ${value.value}`)
|
||||
.join(", ")
|
||||
const price = convertToLocale({
|
||||
amount: variant.calculated_price!.calculated_amount!,
|
||||
currency_code: currency,
|
||||
})
|
||||
const stock = isVariantInStock(variant) ? "In stock" : "Out of stock"
|
||||
return `| ${options || variant.title} | ${variant.sku ?? ""} | ${price} | ${stock} | \`${variant.id}\` |`
|
||||
})
|
||||
|
||||
return `# ${product.title}
|
||||
|
||||
${product.description ?? ""}
|
||||
|
||||
- URL: ${productUrl}
|
||||
- Availability: ${variants.some(isVariantInStock) ? "In stock" : "Out of stock"}${policyLines}
|
||||
|
||||
## Variants
|
||||
|
||||
| Options | SKU | Price | Availability | Variant ID |
|
||||
| --- | --- | --- | --- | --- |
|
||||
${variantRows.join("\n")}
|
||||
|
||||
## Buy
|
||||
|
||||
- Add to cart: POST \`variant_id={variant_id}&quantity={n}\` (form-encoded) to ${base}/cart/add
|
||||
- Checkout link: ${origin}/buy/{variant_id}:{quantity}?context/address_country=${countryCode.toUpperCase()}
|
||||
|
||||
## Policies
|
||||
|
||||
- [Shipping information](${base}/shipping)
|
||||
- [Return policy](${base}/returns)
|
||||
- [Terms of service](${base}/terms)
|
||||
- [Privacy policy](${base}/privacy)
|
||||
- [Contact](${base}/contact)
|
||||
`
|
||||
}
|
||||
26
apps/suman-bosna/src/lib/util/product-option-filters.ts
Normal file
26
apps/suman-bosna/src/lib/util/product-option-filters.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
export const OPTION_VALUE_QUERY_KEY = "optionValueIds"
|
||||
|
||||
export type OptionValueIds = string[]
|
||||
|
||||
export const parseOptionValueIds = (
|
||||
searchParams: URLSearchParams | Record<string, string | string[] | undefined>
|
||||
): OptionValueIds => {
|
||||
if (typeof (searchParams as URLSearchParams).getAll === "function") {
|
||||
const values = (searchParams as URLSearchParams).getAll(OPTION_VALUE_QUERY_KEY)
|
||||
return Array.from(new Set(values.filter(Boolean)))
|
||||
}
|
||||
|
||||
const paramValue = (
|
||||
searchParams as Record<string, string | string[] | undefined>
|
||||
)[OPTION_VALUE_QUERY_KEY]
|
||||
|
||||
if (Array.isArray(paramValue)) {
|
||||
return Array.from(new Set(paramValue.filter(Boolean)))
|
||||
}
|
||||
|
||||
if (typeof paramValue === "string" && paramValue.length > 0) {
|
||||
return paramValue.split(",").filter(Boolean)
|
||||
}
|
||||
|
||||
return []
|
||||
}
|
||||
107
apps/suman-bosna/src/lib/util/product-structured-data.ts
Normal file
107
apps/suman-bosna/src/lib/util/product-structured-data.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { isVariantInStock } from "./inventory"
|
||||
import { STORE_NAME } from "./site"
|
||||
import {
|
||||
buildReturnPolicy,
|
||||
buildShippingDetails,
|
||||
getRegionPolicies,
|
||||
} from "./store-policies"
|
||||
|
||||
const SCHEMA_IN_STOCK = "https://schema.org/InStock"
|
||||
const SCHEMA_OUT_OF_STOCK = "https://schema.org/OutOfStock"
|
||||
|
||||
export const getPricedVariants = (product: HttpTypes.StoreProduct) =>
|
||||
(product.variants ?? []).filter(
|
||||
(variant) => variant.calculated_price?.calculated_amount != null
|
||||
)
|
||||
|
||||
export const buildProductStructuredData = ({
|
||||
product,
|
||||
region,
|
||||
countryCode,
|
||||
productUrl,
|
||||
}: {
|
||||
product: HttpTypes.StoreProduct
|
||||
region: HttpTypes.StoreRegion
|
||||
countryCode: string
|
||||
productUrl: string
|
||||
}) => {
|
||||
const currency = region.currency_code.toUpperCase()
|
||||
const images = (product.images ?? [])
|
||||
.map((image) => image.url)
|
||||
.filter(Boolean)
|
||||
if (!images.length && product.thumbnail) {
|
||||
images.push(product.thumbnail)
|
||||
}
|
||||
const description = product.description || product.title
|
||||
const brand = { "@type": "Brand", name: STORE_NAME }
|
||||
const policies = getRegionPolicies(region)
|
||||
const optionTitles = new Map(
|
||||
(product.options ?? []).map((option) => [option.id, option.title])
|
||||
)
|
||||
|
||||
const buildOffer = (variant: HttpTypes.StoreProductVariant, url: string) => ({
|
||||
"@type": "Offer",
|
||||
url,
|
||||
sku: variant.sku || undefined,
|
||||
price: variant.calculated_price!.calculated_amount!.toFixed(2),
|
||||
priceCurrency: currency,
|
||||
availability: isVariantInStock(variant)
|
||||
? SCHEMA_IN_STOCK
|
||||
: SCHEMA_OUT_OF_STOCK,
|
||||
itemCondition: "https://schema.org/NewCondition",
|
||||
...(policies
|
||||
? {
|
||||
shippingDetails: buildShippingDetails(policies, countryCode, currency),
|
||||
hasMerchantReturnPolicy: buildReturnPolicy(policies, countryCode),
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
|
||||
const variants = getPricedVariants(product)
|
||||
|
||||
if (variants.length <= 1) {
|
||||
return {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Product",
|
||||
name: product.title,
|
||||
description,
|
||||
image: images,
|
||||
brand,
|
||||
sku: variants[0]?.sku || undefined,
|
||||
url: productUrl,
|
||||
offers: variants[0] ? buildOffer(variants[0], productUrl) : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "ProductGroup",
|
||||
name: product.title,
|
||||
description,
|
||||
image: images,
|
||||
brand,
|
||||
url: productUrl,
|
||||
productGroupID: product.id,
|
||||
variesBy: (product.options ?? []).map((option) => option.title),
|
||||
hasVariant: variants.map((variant) => {
|
||||
const variantUrl = `${productUrl}?v_id=${variant.id}`
|
||||
return {
|
||||
"@type": "Product",
|
||||
name: `${product.title} - ${variant.title}`,
|
||||
sku: variant.sku || undefined,
|
||||
image: variant.images?.[0]?.url || images[0],
|
||||
additionalProperty: (variant.options ?? []).map((value) => ({
|
||||
"@type": "PropertyValue",
|
||||
name: optionTitles.get(value.option_id ?? ""),
|
||||
value: value.value,
|
||||
})),
|
||||
offers: buildOffer(variant, variantUrl),
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/** Serializes JSON-LD for a `<script>` tag without allowing `</script>` breakouts. */
|
||||
export const toJsonLd = (data: unknown) =>
|
||||
JSON.stringify(data).replace(/</g, "\\u003c")
|
||||
5
apps/suman-bosna/src/lib/util/product.ts
Normal file
5
apps/suman-bosna/src/lib/util/product.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { HttpTypes } from "@medusajs/types";
|
||||
|
||||
export const isSimpleProduct = (product: HttpTypes.StoreProduct): boolean => {
|
||||
return product.options?.length === 1 && product.options[0].values?.length === 1;
|
||||
}
|
||||
5
apps/suman-bosna/src/lib/util/repeat.ts
Normal file
5
apps/suman-bosna/src/lib/util/repeat.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
const repeat = (times: number) => {
|
||||
return Array.from(Array(times).keys())
|
||||
}
|
||||
|
||||
export default repeat
|
||||
53
apps/suman-bosna/src/lib/util/server-cart.ts
Normal file
53
apps/suman-bosna/src/lib/util/server-cart.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import "server-only"
|
||||
import { sdk } from "@lib/config"
|
||||
import { getCacheTag, setCartId } from "@lib/data/cookies"
|
||||
import { listRegions } from "@lib/data/regions"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { revalidateTag } from "next/cache"
|
||||
import { getDefaultCountryCode } from "./site"
|
||||
|
||||
export const MAX_LINE_ITEM_QUANTITY = 100
|
||||
|
||||
/** Stores the cart in the shopper's cookie and clears cached cart reads. */
|
||||
export const activateCart = async (cartId: string) => {
|
||||
await setCartId(cartId)
|
||||
const cartCacheTag = await getCacheTag("carts")
|
||||
if (cartCacheTag) {
|
||||
revalidateTag(cartCacheTag, { expire: 0 })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the region from an explicit country code, falling back to the
|
||||
* store's default country only when none was requested.
|
||||
*/
|
||||
export const resolveRegion = async (
|
||||
countryCode?: string
|
||||
): Promise<{ countryCode: string; region: HttpTypes.StoreRegion } | null> => {
|
||||
const regions = await listRegions()
|
||||
const code = countryCode?.toLowerCase() || getDefaultCountryCode(regions)
|
||||
const region = regions.find((r) => r.countries?.some((c) => c.iso_2 === code))
|
||||
return code && region ? { countryCode: code, region } : null
|
||||
}
|
||||
|
||||
export const createCartWithItems = async (
|
||||
regionId: string,
|
||||
items: { variant_id: string; quantity: number }[]
|
||||
) => {
|
||||
const { cart } = await sdk.store.cart.create({ region_id: regionId })
|
||||
for (const item of items) {
|
||||
await sdk.store.cart.createLineItem(cart.id, item)
|
||||
}
|
||||
return cart.id
|
||||
}
|
||||
|
||||
/** Returns the requested variant IDs that don't exist in the store's sales channel. */
|
||||
export const findMissingVariantIds = async (variantIds: string[]) => {
|
||||
const { variants } = await sdk.client.fetch<{
|
||||
variants: { id: string }[]
|
||||
}>("/store/product-variants", {
|
||||
query: { id: variantIds, fields: "id", limit: variantIds.length },
|
||||
})
|
||||
const found = new Set(variants.map((variant) => variant.id))
|
||||
return variantIds.filter((id) => !found.has(id))
|
||||
}
|
||||
51
apps/suman-bosna/src/lib/util/site.ts
Normal file
51
apps/suman-bosna/src/lib/util/site.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import "server-only"
|
||||
import { headers } from "next/headers"
|
||||
import siteConfig from "@/config/site.json"
|
||||
|
||||
export const STORE_NAME = siteConfig.name
|
||||
|
||||
export const DEFAULT_COUNTRY_CODE = (
|
||||
process.env.NEXT_PUBLIC_DEFAULT_REGION || siteConfig.countryCode
|
||||
).toLowerCase()
|
||||
|
||||
const configuredUrl = () => process.env.NEXT_PUBLIC_BASE_URL?.replace(/\/$/, "")
|
||||
|
||||
const originFromHeaders = (get: (name: string) => string | null) => {
|
||||
const host = (get("x-forwarded-host") ?? get("host"))?.split(",")[0].trim()
|
||||
if (!host) {
|
||||
return undefined
|
||||
}
|
||||
const proto = get("x-forwarded-proto")?.split(",")[0].trim() || "https"
|
||||
return `${proto}://${host}`
|
||||
}
|
||||
|
||||
export const getRequestOrigin = (request: Request): string =>
|
||||
configuredUrl() ||
|
||||
originFromHeaders((name) => request.headers.get(name)) ||
|
||||
new URL(request.url).origin
|
||||
|
||||
/** Origin for absolute URLs in server components (canonical, JSON-LD, OpenGraph). */
|
||||
export const getSiteOrigin = async (): Promise<string> => {
|
||||
const configured = configuredUrl()
|
||||
if (configured) {
|
||||
return configured
|
||||
}
|
||||
const requestHeaders = await headers()
|
||||
return originFromHeaders((name) => requestHeaders.get(name)) || "http://localhost:8000"
|
||||
}
|
||||
|
||||
export const listCountryCodes = (
|
||||
regions: { countries?: { iso_2?: string | null }[] | null }[]
|
||||
): string[] =>
|
||||
regions.flatMap((region) =>
|
||||
(region.countries ?? [])
|
||||
.map((country) => country.iso_2?.toLowerCase())
|
||||
.filter((code): code is string => Boolean(code))
|
||||
)
|
||||
|
||||
export const getDefaultCountryCode = (
|
||||
regions: { countries?: { iso_2?: string | null }[] | null }[]
|
||||
) => {
|
||||
const codes = listCountryCodes(regions)
|
||||
return codes.includes(DEFAULT_COUNTRY_CODE) ? DEFAULT_COUNTRY_CODE : codes[0]
|
||||
}
|
||||
50
apps/suman-bosna/src/lib/util/sort-products.ts
Normal file
50
apps/suman-bosna/src/lib/util/sort-products.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { SortOptions } from "@modules/store/components/refinement-list/sort-products"
|
||||
|
||||
interface MinPricedProduct extends HttpTypes.StoreProduct {
|
||||
_minPrice?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to sort products by price until the store API supports sorting by price
|
||||
* @param products
|
||||
* @param sortBy
|
||||
* @returns products sorted by price
|
||||
*/
|
||||
export function sortProducts(
|
||||
products: HttpTypes.StoreProduct[],
|
||||
sortBy: SortOptions
|
||||
): HttpTypes.StoreProduct[] {
|
||||
const sortedProducts = products as MinPricedProduct[]
|
||||
|
||||
if (["price_asc", "price_desc"].includes(sortBy)) {
|
||||
// Precompute the minimum price for each product
|
||||
sortedProducts.forEach((product) => {
|
||||
if (product.variants && product.variants.length > 0) {
|
||||
product._minPrice = Math.min(
|
||||
...product.variants.map(
|
||||
(variant) => variant?.calculated_price?.calculated_amount || 0
|
||||
)
|
||||
)
|
||||
} else {
|
||||
product._minPrice = Infinity
|
||||
}
|
||||
})
|
||||
|
||||
// Sort products based on the precomputed minimum prices
|
||||
sortedProducts.sort((a, b) => {
|
||||
const diff = a._minPrice! - b._minPrice!
|
||||
return sortBy === "price_asc" ? diff : -diff
|
||||
})
|
||||
}
|
||||
|
||||
if (sortBy === "created_at") {
|
||||
sortedProducts.sort((a, b) => {
|
||||
return (
|
||||
new Date(b.created_at!).getTime() - new Date(a.created_at!).getTime()
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
return sortedProducts
|
||||
}
|
||||
103
apps/suman-bosna/src/lib/util/store-policies.ts
Normal file
103
apps/suman-bosna/src/lib/util/store-policies.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
|
||||
export type StorePolicies = {
|
||||
returnWindowDays: number
|
||||
freeReturns: boolean
|
||||
shippingRate: number
|
||||
handlingDays: { min: number; max: number }
|
||||
transitDays: { min: number; max: number }
|
||||
}
|
||||
|
||||
const toNumber = (value: unknown) => {
|
||||
const number =
|
||||
typeof value === "string" && value.trim() === "" ? NaN : Number(value)
|
||||
return Number.isFinite(number) && number >= 0 ? number : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the store policy keys set on a region's metadata in Medusa Admin.
|
||||
* Returns null when any value is missing or invalid, so callers omit policy
|
||||
* data instead of publishing guesses.
|
||||
*/
|
||||
export const getRegionPolicies = (
|
||||
region: Pick<HttpTypes.StoreRegion, "metadata"> | null | undefined
|
||||
): StorePolicies | null => {
|
||||
const metadata = region?.metadata ?? {}
|
||||
const values = {
|
||||
returnWindowDays: toNumber(metadata.return_window_days),
|
||||
shippingRate: toNumber(metadata.shipping_rate),
|
||||
handlingMin: toNumber(metadata.handling_days_min),
|
||||
handlingMax: toNumber(metadata.handling_days_max),
|
||||
transitMin: toNumber(metadata.transit_days_min),
|
||||
transitMax: toNumber(metadata.transit_days_max),
|
||||
}
|
||||
if (Object.values(values).some((value) => value === null)) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
returnWindowDays: values.returnWindowDays!,
|
||||
freeReturns:
|
||||
metadata.free_returns === true || metadata.free_returns === "true",
|
||||
shippingRate: values.shippingRate!,
|
||||
handlingDays: { min: values.handlingMin!, max: values.handlingMax! },
|
||||
transitDays: { min: values.transitMin!, max: values.transitMax! },
|
||||
}
|
||||
}
|
||||
|
||||
const businessDays = (range: { min: number; max: number }) => ({
|
||||
"@type": "QuantitativeValue",
|
||||
minValue: range.min,
|
||||
maxValue: range.max,
|
||||
unitCode: "DAY",
|
||||
})
|
||||
|
||||
export const buildShippingDetails = (
|
||||
policies: StorePolicies,
|
||||
countryCode: string,
|
||||
currencyCode: string
|
||||
) => ({
|
||||
"@type": "OfferShippingDetails",
|
||||
shippingRate: {
|
||||
"@type": "MonetaryAmount",
|
||||
value: policies.shippingRate,
|
||||
currency: currencyCode.toUpperCase(),
|
||||
},
|
||||
shippingDestination: {
|
||||
"@type": "DefinedRegion",
|
||||
addressCountry: countryCode.toUpperCase(),
|
||||
},
|
||||
deliveryTime: {
|
||||
"@type": "ShippingDeliveryTime",
|
||||
handlingTime: businessDays(policies.handlingDays),
|
||||
transitTime: businessDays(policies.transitDays),
|
||||
},
|
||||
})
|
||||
|
||||
export const buildReturnPolicy = (
|
||||
policies: StorePolicies,
|
||||
countryCode: string
|
||||
) => ({
|
||||
"@type": "MerchantReturnPolicy",
|
||||
applicableCountry: countryCode.toUpperCase(),
|
||||
returnPolicyCategory: "https://schema.org/MerchantReturnFiniteReturnWindow",
|
||||
merchantReturnDays: policies.returnWindowDays,
|
||||
returnMethod: "https://schema.org/ReturnByMail",
|
||||
returnFees: policies.freeReturns
|
||||
? "https://schema.org/FreeReturn"
|
||||
: "https://schema.org/ReturnFeesCustomerResponsibility",
|
||||
})
|
||||
|
||||
export const buildRegionsReturnPolicies = (regions: HttpTypes.StoreRegion[]) =>
|
||||
regions.flatMap((region) => {
|
||||
const policies = getRegionPolicies(region)
|
||||
if (!policies) {
|
||||
return []
|
||||
}
|
||||
return (region.countries ?? [])
|
||||
.filter((country) => country.iso_2)
|
||||
.map((country) => buildReturnPolicy(policies, country.iso_2!))
|
||||
})
|
||||
|
||||
export const formatDayRange = ({ min, max }: { min: number; max: number }) =>
|
||||
min === max ? `${min}` : `${min}-${max}`
|
||||
7
apps/suman-bosna/src/lib/utils.ts
Normal file
7
apps/suman-bosna/src/lib/utils.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user