first commit

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

View File

@@ -0,0 +1,63 @@
import {
UCP_CAPABILITIES,
UCP_MCP_PATH,
UCP_REST_BASE_PATH,
UCP_VERSION,
} from "@lib/ucp/ucp"
import { getRequestOrigin } from "@lib/util/site"
export const GET = (request: Request) => {
const origin = getRequestOrigin(request)
const overview = `https://ucp.dev/${UCP_VERSION}/specification/overview/`
const capabilities = Object.fromEntries(
Object.entries(UCP_CAPABILITIES).map(([name, { spec, schema }]) => [
name,
[{ version: UCP_VERSION, spec, schema }],
])
)
return Response.json(
{
ucp: {
version: UCP_VERSION,
services: {
"dev.ucp.shopping": [
{
version: UCP_VERSION,
spec: overview,
transport: "mcp",
endpoint: `${origin}${UCP_MCP_PATH}`,
schema: `https://ucp.dev/${UCP_VERSION}/services/shopping/mcp.openrpc.json`,
},
{
version: UCP_VERSION,
spec: overview,
transport: "rest",
endpoint: `${origin}${UCP_REST_BASE_PATH}`,
schema: `https://ucp.dev/${UCP_VERSION}/services/shopping/rest.openapi.json`,
},
],
},
capabilities: {
...capabilities,
"dev.ucp.shopping.permalink": [
{
version: UCP_VERSION,
spec: `https://ucp.dev/${UCP_VERSION}/specification/permalink`,
schema: `https://ucp.dev/${UCP_VERSION}/schemas/shopping/permalink.json`,
config: { endpoint: `${origin}/buy` },
},
],
},
payment_handlers: {},
},
},
{
headers: {
"Cache-Control": "public, max-age=300",
"Access-Control-Allow-Origin": "*",
},
}
)
}

View File

@@ -0,0 +1,30 @@
import { retrieveCart } from "@lib/data/cart"
import { retrieveCustomer } from "@lib/data/customer"
import PaymentWrapper from "@modules/checkout/components/payment-wrapper"
import CheckoutForm from "@modules/checkout/templates/checkout-form"
import CheckoutSummary from "@modules/checkout/templates/checkout-summary"
import { Metadata } from "next"
import { notFound } from "next/navigation"
export const metadata: Metadata = {
title: "Checkout",
}
export default async function Checkout() {
const cart = await retrieveCart()
if (!cart) {
return notFound()
}
const customer = await retrieveCustomer()
return (
<div className="grid grid-cols-1 small:grid-cols-[1fr_416px] content-container gap-x-40 py-12">
<PaymentWrapper cart={cart}>
<CheckoutForm cart={cart} customer={customer} />
</PaymentWrapper>
<CheckoutSummary cart={cart} />
</div>
)
}

View File

@@ -0,0 +1,43 @@
import LocalizedClientLink from "@modules/common/components/localized-client-link"
import ChevronDown from "@modules/common/icons/chevron-down"
import MedusaCTA from "@modules/layout/components/medusa-cta"
export default function CheckoutLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<div className="w-full bg-white relative small:min-h-screen">
<div className="h-16 bg-white border-b ">
<nav className="flex h-full items-center content-container justify-between">
<LocalizedClientLink
href="/cart"
className="text-small-semi text-ui-fg-base flex items-center gap-x-2 uppercase flex-1 basis-0"
data-testid="back-to-cart-link"
>
<ChevronDown className="rotate-90" size={16} />
<span className="mt-px hidden small:block txt-compact-plus text-ui-fg-subtle hover:text-ui-fg-base ">
Back to shopping cart
</span>
<span className="mt-px block small:hidden txt-compact-plus text-ui-fg-subtle hover:text-ui-fg-base">
Back
</span>
</LocalizedClientLink>
<LocalizedClientLink
href="/"
className="txt-compact-xlarge-plus text-ui-fg-subtle hover:text-ui-fg-base uppercase"
data-testid="store-link"
>
Medusa Store
</LocalizedClientLink>
<div className="flex-1 basis-0" />
</nav>
</div>
<div className="relative" data-testid="checkout-container">{children}</div>
<div className="py-4 w-full flex items-center justify-center">
<MedusaCTA />
</div>
</div>
)
}

View File

@@ -0,0 +1,19 @@
import InteractiveLink from "@modules/common/components/interactive-link"
import { Metadata } from "next"
export const metadata: Metadata = {
title: "404",
description: "Something went wrong",
}
export default async function NotFound() {
return (
<div className="flex flex-col gap-4 items-center justify-center min-h-[calc(100vh-64px)]">
<h1 className="text-2xl-semi text-ui-fg-base">Page not found</h1>
<p className="text-small-regular text-ui-fg-base">
The page you tried to access does not exist.
</p>
<InteractiveLink href="/">Go to frontpage</InteractiveLink>
</div>
)
}

View File

@@ -0,0 +1,38 @@
import { Metadata } from "next"
import { notFound } from "next/navigation"
import AddressBook from "@modules/account/components/address-book"
import { getRegion } from "@lib/data/regions"
import { retrieveCustomer } from "@lib/data/customer"
export const metadata: Metadata = {
title: "Addresses",
description: "View your addresses",
}
export default async function Addresses(props: {
params: Promise<{ countryCode: string }>
}) {
const params = await props.params
const { countryCode } = params
const customer = await retrieveCustomer()
const region = await getRegion(countryCode)
if (!customer || !region) {
notFound()
}
return (
<div className="w-full" data-testid="addresses-page-wrapper">
<div className="mb-8 flex flex-col gap-y-4">
<h1 className="text-2xl-semi">Shipping Addresses</h1>
<p className="text-base-regular">
View and update your shipping addresses, you can add as many as you
like. Saving your addresses will make them available during checkout.
</p>
</div>
<AddressBook customer={customer} region={region} />
</div>
)
}

View File

@@ -0,0 +1,3 @@
export default function Default() {
return null
}

View File

@@ -0,0 +1,9 @@
import Spinner from "@modules/common/icons/spinner"
export default function Loading() {
return (
<div className="flex items-center justify-center w-full h-full text-ui-fg-base">
<Spinner size={36} />
</div>
)
}

View File

@@ -0,0 +1,33 @@
import { retrieveOrder } from "@lib/data/orders"
import OrderDetailsTemplate from "@modules/order/templates/order-details-template"
import { Metadata } from "next"
import { notFound } from "next/navigation"
type Props = {
params: Promise<{ id: string }>
}
export async function generateMetadata(props: Props): Promise<Metadata> {
const params = await props.params
const order = await retrieveOrder(params.id).catch(() => null)
if (!order) {
notFound()
}
return {
title: `Order #${order.display_id}`,
description: `View your order`,
}
}
export default async function OrderDetailPage(props: Props) {
const params = await props.params
const order = await retrieveOrder(params.id).catch(() => null)
if (!order) {
notFound()
}
return <OrderDetailsTemplate order={order} />
}

View File

@@ -0,0 +1,37 @@
import { Metadata } from "next"
import OrderOverview from "@modules/account/components/order-overview"
import { notFound } from "next/navigation"
import { listOrders } from "@lib/data/orders"
import Divider from "@modules/common/components/divider"
import TransferRequestForm from "@modules/account/components/transfer-request-form"
export const metadata: Metadata = {
title: "Orders",
description: "Overview of your previous orders.",
}
export default async function Orders() {
const orders = await listOrders()
if (!orders) {
notFound()
}
return (
<div className="w-full" data-testid="orders-page-wrapper">
<div className="mb-8 flex flex-col gap-y-4">
<h1 className="text-2xl-semi">Orders</h1>
<p className="text-base-regular">
View your previous orders and their status. You can also create
returns or exchanges for your orders if needed.
</p>
</div>
<div>
<OrderOverview orders={orders} />
<Divider className="mb-8 mt-8" />
<TransferRequestForm />
</div>
</div>
)
}

View File

@@ -0,0 +1,22 @@
import { Metadata } from "next"
import Overview from "@modules/account/components/overview"
import { notFound } from "next/navigation"
import { retrieveCustomer } from "@lib/data/customer"
import { listOrders } from "@lib/data/orders"
export const metadata: Metadata = {
title: "Account",
description: "Overview of your account activity.",
}
export default async function OverviewTemplate() {
const customer = await retrieveCustomer().catch(() => null)
const orders = (await listOrders().catch(() => null)) || null
if (!customer) {
notFound()
}
return <Overview customer={customer} orders={orders} />
}

View File

@@ -0,0 +1,51 @@
import { Metadata } from "next"
import ProfilePhone from "@modules/account//components/profile-phone"
import ProfileBillingAddress from "@modules/account/components/profile-billing-address"
import ProfileEmail from "@modules/account/components/profile-email"
import ProfileName from "@modules/account/components/profile-name"
import { notFound } from "next/navigation"
import { listRegions } from "@lib/data/regions"
import { retrieveCustomer } from "@lib/data/customer"
export const metadata: Metadata = {
title: "Profile",
description: "View and edit your Medusa Store profile.",
}
export default async function Profile() {
const customer = await retrieveCustomer()
const regions = await listRegions()
if (!customer || !regions) {
notFound()
}
return (
<div className="w-full" data-testid="profile-page-wrapper">
<div className="mb-8 flex flex-col gap-y-4">
<h1 className="text-2xl-semi">Profile</h1>
<p className="text-base-regular">
View and update your profile information, including your name, email,
and phone number. You can also update your billing address, or change
your password.
</p>
</div>
<div className="flex flex-col gap-y-8 w-full">
<ProfileName customer={customer} />
<Divider />
<ProfileEmail customer={customer} />
<Divider />
<ProfilePhone customer={customer} />
<Divider />
{/* <ProfilePassword customer={customer} />
<Divider /> */}
<ProfileBillingAddress customer={customer} regions={regions} />
</div>
</div>
)
}
const Divider = () => {
return <div className="w-full h-px bg-gray-200" />
}

View File

@@ -0,0 +1 @@
export { default, metadata } from "./page"

View File

@@ -0,0 +1,12 @@
import { Metadata } from "next"
import LoginTemplate from "@modules/account/templates/login-template"
export const metadata: Metadata = {
title: "Sign in",
description: "Sign in to your Medusa Store account.",
}
export default function Login() {
return <LoginTemplate />
}

View File

@@ -0,0 +1,20 @@
import { retrieveCustomer } from "@lib/data/customer"
// TODO: Re-add Toaster component when needed
import AccountLayout from "@modules/account/templates/account-layout"
export default async function AccountPageLayout({
dashboard,
login,
}: {
dashboard?: React.ReactNode
login?: React.ReactNode
}) {
const customer = await retrieveCustomer().catch(() => null)
return (
<AccountLayout customer={customer}>
{customer ? dashboard : login}
{/* TODO: Re-add Toaster component when needed */}
</AccountLayout>
)
}

View File

@@ -0,0 +1,9 @@
import Spinner from "@modules/common/icons/spinner"
export default function Loading() {
return (
<div className="flex items-center justify-center w-full h-full text-ui-fg-base">
<Spinner size={36} />
</div>
)
}

View File

@@ -0,0 +1,103 @@
import { sdk } from "@lib/config"
import { getCartId } from "@lib/data/cookies"
import { getRegion } from "@lib/data/regions"
import { HttpTypes } from "@medusajs/types"
import { activateCart, MAX_LINE_ITEM_QUANTITY } from "@lib/util/server-cart"
import { getRequestOrigin } from "@lib/util/site"
import { isEqual } from "lodash"
import { NextRequest, NextResponse } from "next/server"
const resolveVariantId = async (form: FormData, regionId: string) => {
const productId = form.get("product_id")?.toString()
const selectedOptions: Record<string, string> = {}
form.forEach((value, key) => {
const match = key.match(/^options\[(.+)\]$/)
if (match) {
selectedOptions[match[1]] = value.toString()
}
})
if (!productId || Object.keys(selectedOptions).length === 0) {
return form.get("variant_id")?.toString() || undefined
}
const { product } = await sdk.store.product.retrieve(productId, {
region_id: regionId,
fields: "id,*variants,*variants.options",
})
return product.variants?.find((variant: HttpTypes.StoreProductVariant) =>
isEqual(
Object.fromEntries(
(variant.options ?? []).map((o) => [o.option_id, o.value])
),
selectedOptions
)
)?.id
}
const addLineItem = async (
cartId: string | undefined,
regionId: string,
variantId: string,
quantity: number
) => {
const id =
cartId ?? (await sdk.store.cart.create({ region_id: regionId })).cart.id
await sdk.store.cart.createLineItem(id, { variant_id: variantId, quantity })
return id
}
const errorMessage = (error: unknown) =>
error instanceof Error ? error.message : "Could not add item to cart"
/** No-JavaScript add-to-cart: the product page form posts here. */
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ countryCode: string }> }
) {
const { countryCode } = await params
const region = await getRegion(countryCode)
if (!region) {
return new NextResponse("Unknown country code", { status: 404 })
}
const form = await request.formData()
const quantity = Math.min(
Math.max(parseInt(form.get("quantity")?.toString() ?? "1", 10) || 1, 1),
MAX_LINE_ITEM_QUANTITY
)
let variantId: string | undefined
try {
variantId = await resolveVariantId(form, region.id)
} catch {
return new NextResponse("Product not found", { status: 404 })
}
if (!variantId) {
return new NextResponse("Select a valid product variant", { status: 400 })
}
const existingCartId = await getCartId()
let cartId: string
try {
cartId = await addLineItem(existingCartId, region.id, variantId, quantity)
} catch (error) {
if (!existingCartId) {
return new NextResponse(errorMessage(error), { status: 400 })
}
// The stored cart may be completed or belong to another region.
try {
cartId = await addLineItem(undefined, region.id, variantId, quantity)
} catch (retryError) {
return new NextResponse(errorMessage(retryError), { status: 400 })
}
}
await activateCart(cartId)
return NextResponse.redirect(
`${getRequestOrigin(request)}/${countryCode}/cart`,
303
)
}

View File

@@ -0,0 +1,5 @@
import SkeletonCartPage from "@modules/skeletons/templates/skeleton-cart-page"
export default function Loading() {
return <SkeletonCartPage />
}

View File

@@ -0,0 +1,21 @@
import { Metadata } from "next"
import InteractiveLink from "@modules/common/components/interactive-link"
export const metadata: Metadata = {
title: "404",
description: "Something went wrong",
}
export default function NotFound() {
return (
<div className="flex flex-col items-center justify-center min-h-[calc(100vh-64px)]">
<h1 className="text-2xl-semi text-ui-fg-base">Page not found</h1>
<p className="text-small-regular text-ui-fg-base">
The cart you tried to access does not exist. Clear your cookies and try
again.
</p>
<InteractiveLink href="/">Go to frontpage</InteractiveLink>
</div>
)
}

View File

@@ -0,0 +1,21 @@
import { retrieveCart } from "@lib/data/cart"
import { retrieveCustomer } from "@lib/data/customer"
import CartTemplate from "@modules/cart/templates"
import { Metadata } from "next"
import { notFound } from "next/navigation"
export const metadata: Metadata = {
title: "Cart",
description: "View your cart",
}
export default async function Cart() {
const cart = await retrieveCart().catch((error) => {
console.error(error)
return notFound()
})
const customer = await retrieveCustomer()
return <CartTemplate cart={cart} customer={customer} />
}

View File

@@ -0,0 +1,35 @@
import { sdk } from "@lib/config"
import { activateCart } from "@lib/util/server-cart"
import { getRequestOrigin } from "@lib/util/site"
import { NextResponse } from "next/server"
const NO_STORE = { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" }
/** UCP checkout `continue_url`: hands an agent-built cart to the buyer for payment. */
export async function GET(
request: Request,
{ params }: { params: Promise<{ countryCode: string; cartId: string }> }
) {
const { countryCode, cartId } = await params
try {
const { cart } = await sdk.store.cart.retrieve(cartId, {
fields: "id,completed_at,metadata",
})
if (cart.completed_at || cart.metadata?.ucp_canceled === true) {
throw new Error("Cart is no longer open")
}
} catch {
return new NextResponse("This cart link has expired", {
status: 410,
headers: NO_STORE,
})
}
await activateCart(cartId)
return NextResponse.redirect(
`${getRequestOrigin(request)}/${countryCode}/checkout`,
{ status: 303, headers: NO_STORE }
)
}

View File

@@ -0,0 +1,62 @@
import { Metadata } from "next"
import { notFound } from "next/navigation"
import { getCategoryByHandle } from "@lib/data/categories"
import CategoryTemplate from "@modules/categories/templates"
import { SortOptions } from "@modules/store/components/refinement-list/sort-products"
import { parseOptionValueIds } from "@lib/util/product-option-filters"
type Props = {
params: Promise<{ category: string[]; countryCode: string }>
searchParams: Promise<
Record<string, string | string[] | undefined> & {
sortBy?: SortOptions
page?: string
optionValueIds?: string | string[]
}
>
}
export async function generateMetadata(props: Props): Promise<Metadata> {
const params = await props.params
try {
const productCategory = await getCategoryByHandle(params.category)
const title = productCategory.name + " | Medusa Store"
const description = productCategory.description ?? `${title} category.`
return {
title: `${title} | Medusa Store`,
description,
alternates: {
canonical: `${params.category.join("/")}`,
},
}
} catch {
notFound()
}
}
export default async function CategoryPage(props: Props) {
const searchParams = await props.searchParams
const params = await props.params
const { sortBy, page } = searchParams
const optionValueIds = parseOptionValueIds(searchParams)
const productCategory = await getCategoryByHandle(params.category)
if (!productCategory) {
notFound()
}
return (
<CategoryTemplate
category={productCategory}
sortBy={sortBy}
page={page}
countryCode={params.countryCode}
optionValueIds={optionValueIds}
/>
)
}

View File

@@ -0,0 +1,59 @@
import { Metadata } from "next"
import { notFound } from "next/navigation"
import { getCollectionByHandle } from "@lib/data/collections"
import CollectionTemplate from "@modules/collections/templates"
import { SortOptions } from "@modules/store/components/refinement-list/sort-products"
import { parseOptionValueIds } from "@lib/util/product-option-filters"
type Props = {
params: Promise<{ handle: string; countryCode: string }>
searchParams: Promise<
Record<string, string | string[] | undefined> & {
page?: string
sortBy?: SortOptions
optionValueIds?: string | string[]
}
>
}
export async function generateMetadata(props: Props): Promise<Metadata> {
const params = await props.params
const collection = await getCollectionByHandle(params.handle)
if (!collection) {
notFound()
}
const metadata = {
title: `${collection.title} | Medusa Store`,
description: `${collection.title} collection`,
} as Metadata
return metadata
}
export default async function CollectionPage(props: Props) {
const searchParams = await props.searchParams
const params = await props.params
const { sortBy, page } = searchParams
const optionValueIds = parseOptionValueIds(searchParams)
const collection = await getCollectionByHandle(params.handle).then(
(collection) => collection,
)
if (!collection) {
notFound()
}
return (
<CollectionTemplate
collection={collection}
page={page}
sortBy={sortBy}
countryCode={params.countryCode}
optionValueIds={optionValueIds}
/>
)
}

View File

@@ -0,0 +1,24 @@
import { Metadata } from "next"
import { STORE_NAME } from "@lib/util/site"
import { PlaceholderNotice, PolicyPage } from "@modules/policies/templates"
export const dynamic = "force-static"
export const revalidate = 60
export const metadata: Metadata = {
title: "Contact",
description: `How to contact ${STORE_NAME}.`,
}
export default function ContactPage() {
return (
<PolicyPage title="Contact">
<PlaceholderNotice />
<p>
Questions about an order, shipping or returns? Contact {STORE_NAME}{" "}
customer service and include your order number.
</p>
</PolicyPage>
)
}

View File

@@ -0,0 +1,45 @@
import { Metadata } from "next"
import { listCartOptions, retrieveCart } from "@lib/data/cart"
import { retrieveCustomer } from "@lib/data/customer"
import { getBaseURL } from "@lib/util/env"
import { StoreCartShippingOption } from "@medusajs/types"
import CartMismatchBanner from "@modules/layout/components/cart-mismatch-banner"
import Footer from "@modules/layout/templates/footer"
import Nav from "@modules/layout/templates/nav"
import FreeShippingPriceNudge from "@modules/shipping/components/free-shipping-price-nudge"
export const metadata: Metadata = {
metadataBase: new URL(getBaseURL()),
}
export default async function PageLayout(props: { children: React.ReactNode }) {
const customer = await retrieveCustomer()
const cart = await retrieveCart()
let shippingOptions: StoreCartShippingOption[] = []
if (cart) {
const { shipping_options } = await listCartOptions()
shippingOptions = shipping_options
}
return (
<>
<Nav />
{customer && cart && (
<CartMismatchBanner customer={customer} cart={cart} />
)}
{cart && (
<FreeShippingPriceNudge
variant="popup"
cart={cart}
shippingOptions={shippingOptions}
/>
)}
{props.children}
<Footer />
</>
)
}

View File

@@ -0,0 +1,20 @@
import { Metadata } from "next"
import InteractiveLink from "@modules/common/components/interactive-link"
export const metadata: Metadata = {
title: "404",
description: "Something went wrong",
}
export default function NotFound() {
return (
<div className="flex flex-col gap-4 items-center justify-center min-h-[calc(100vh-64px)]">
<h1 className="text-2xl-semi text-ui-fg-base">Page not found</h1>
<p className="text-small-regular text-ui-fg-base">
The page you tried to access does not exist.
</p>
<InteractiveLink href="/">Go to frontpage</InteractiveLink>
</div>
)
}

View File

@@ -0,0 +1,5 @@
import SkeletonOrderConfirmed from "@modules/skeletons/templates/skeleton-order-confirmed"
export default function Loading() {
return <SkeletonOrderConfirmed />
}

View File

@@ -0,0 +1,23 @@
import { retrieveOrder } from "@lib/data/orders"
import OrderCompletedTemplate from "@modules/order/templates/order-completed-template"
import { Metadata } from "next"
import { notFound } from "next/navigation"
type Props = {
params: Promise<{ id: string }>
}
export const metadata: Metadata = {
title: "Order Confirmed",
description: "You purchase was successful",
}
export default async function OrderConfirmedPage(props: Props) {
const params = await props.params
const order = await retrieveOrder(params.id).catch(() => null)
if (!order) {
return notFound()
}
return <OrderCompletedTemplate order={order} />
}

View File

@@ -0,0 +1,41 @@
import { acceptTransferRequest } from "@lib/data/orders"
import { Heading, Text } from "@modules/common/components/ui"
import TransferImage from "@modules/order/components/transfer-image"
export default async function TransferPage({
params,
}: {
params: Promise<{ id: string; token: string }>
}) {
const { id, token } = await params
const { success, error } = await acceptTransferRequest(id, token)
return (
<div className="flex flex-col gap-y-4 items-start w-2/5 mx-auto mt-10 mb-20">
<TransferImage />
<div className="flex flex-col gap-y-6">
{success && (
<>
<Heading level="h1" className="text-xl text-zinc-900">
Order transfered!
</Heading>
<Text className="text-zinc-600">
Order {id} has been successfully transfered to the new owner.
</Text>
</>
)}
{!success && (
<>
<Text className="text-zinc-600">
There was an error accepting the transfer. Please try again.
</Text>
{error && (
<Text className="text-red-500">Error message: {error}</Text>
)}
</>
)}
</div>
</div>
)
}

View File

@@ -0,0 +1,41 @@
import { declineTransferRequest } from "@lib/data/orders"
import { Heading, Text } from "@modules/common/components/ui"
import TransferImage from "@modules/order/components/transfer-image"
export default async function TransferPage({
params,
}: {
params: Promise<{ id: string; token: string }>
}) {
const { id, token } = await params
const { success, error } = await declineTransferRequest(id, token)
return (
<div className="flex flex-col gap-y-4 items-start w-2/5 mx-auto mt-10 mb-20">
<TransferImage />
<div className="flex flex-col gap-y-6">
{success && (
<>
<Heading level="h1" className="text-xl text-zinc-900">
Order transfer declined!
</Heading>
<Text className="text-zinc-600">
Transfer of order {id} has been successfully declined.
</Text>
</>
)}
{!success && (
<>
<Text className="text-zinc-600">
There was an error declining the transfer. Please try again.
</Text>
{error && (
<Text className="text-red-500">Error message: {error}</Text>
)}
</>
)}
</div>
</div>
)
}

View File

@@ -0,0 +1,38 @@
import { Heading, Text } from "@modules/common/components/ui"
import TransferActions from "@modules/order/components/transfer-actions"
import TransferImage from "@modules/order/components/transfer-image"
export default async function TransferPage({
params,
}: {
params: Promise<{ id: string; token: string }>
}) {
const { id, token } = await params
return (
<div className="flex flex-col gap-y-4 items-start w-2/5 mx-auto mt-10 mb-20">
<TransferImage />
<div className="flex flex-col gap-y-6">
<Heading level="h1" className="text-xl text-zinc-900">
Transfer request for order {id}
</Heading>
<Text className="text-zinc-600">
You&#39;ve received a request to transfer ownership of your order ({id}).
If you agree to this request, you can approve the transfer by clicking
the button below.
</Text>
<div className="w-full h-px bg-zinc-200" />
<Text className="text-zinc-600">
If you accept, the new owner will take over all responsibilities and
permissions associated with this order.
</Text>
<Text className="text-zinc-600">
If you do not recognize this request or wish to retain ownership, no
further action is required.
</Text>
<div className="w-full h-px bg-zinc-200" />
<TransferActions id={id} token={token} />
</div>
</div>
)
}

View File

@@ -0,0 +1,99 @@
import { Metadata } from "next"
import FeaturedProducts from "@modules/home/components/featured-products"
import Hero from "@modules/home/components/hero"
import { listCollections } from "@lib/data/collections"
import { getRegion, listRegions } from "@lib/data/regions"
import { toJsonLd } from "@lib/util/product-structured-data"
import { getSiteOrigin, listCountryCodes, STORE_NAME } from "@lib/util/site"
import { buildRegionsReturnPolicies } from "@lib/util/store-policies"
export const dynamic = "force-static"
export const revalidate = 60
export async function generateMetadata(props: {
params: Promise<{ countryCode: string }>
}): Promise<Metadata> {
const { countryCode } = await props.params
const [origin, regions] = await Promise.all([getSiteOrigin(), listRegions()])
return {
title: "Medusa Next.js Starter Template",
description:
"A performant frontend ecommerce starter template with Next.js 16 and Medusa.",
alternates: {
canonical: `${origin}/${countryCode}`,
languages: {
...Object.fromEntries(
listCountryCodes(regions).map((code) => [
`en-${code.toUpperCase()}`,
`${origin}/${code}`,
])
),
"x-default": origin,
},
},
}
}
export default async function Home(props: {
params: Promise<{ countryCode: string }>
}) {
const params = await props.params
const { countryCode } = params
const region = await getRegion(countryCode)
const { collections } = await listCollections({
fields: "id, handle, title",
})
if (!collections || !region) {
return null
}
const [origin, regions] = await Promise.all([getSiteOrigin(), listRegions()])
const homeUrl = `${origin}/${countryCode}`
const returnPolicies = buildRegionsReturnPolicies(regions)
const structuredData = [
{
"@context": "https://schema.org",
"@type": "Organization",
name: STORE_NAME,
url: origin,
...(returnPolicies.length
? { hasMerchantReturnPolicy: returnPolicies }
: {}),
},
{
"@context": "https://schema.org",
"@type": "WebSite",
name: STORE_NAME,
url: homeUrl,
potentialAction: {
"@type": "SearchAction",
target: {
"@type": "EntryPoint",
urlTemplate: `${homeUrl}/search?q={search_term_string}`,
},
"query-input": "required name=search_term_string",
},
},
]
return (
<>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: toJsonLd(structuredData) }}
/>
<Hero />
<div className="py-12">
<ul className="flex flex-col gap-x-6">
<FeaturedProducts collections={collections} region={region} />
</ul>
</div>
</>
)
}

View File

@@ -0,0 +1,29 @@
import { Metadata } from "next"
import { STORE_NAME } from "@lib/util/site"
import { PlaceholderNotice, PolicyPage } from "@modules/policies/templates"
export const dynamic = "force-static"
export const revalidate = 60
export const metadata: Metadata = {
title: "Privacy policy",
description: `How ${STORE_NAME} collects and uses personal data.`,
}
export default function PrivacyPage() {
return (
<PolicyPage title="Privacy policy">
<PlaceholderNotice />
<p>
{STORE_NAME} collects the information you provide at checkout, such as
your name, email address and shipping address, to process and deliver
your order.
</p>
<p>
Payment details are handled by our payment provider and are not stored
by the store. Cookies are used to keep your cart and sign-in session.
</p>
</PolicyPage>
)
}

View File

@@ -0,0 +1,38 @@
import { listProducts } from "@lib/data/products"
import { getRegion } from "@lib/data/regions"
import { renderProductMarkdown } from "@lib/util/product-markdown"
import { getRequestOrigin } from "@lib/util/site"
const HEADERS = {
"Content-Type": "text/markdown; charset=utf-8",
"Cache-Control": "public, max-age=0, s-maxage=60, stale-while-revalidate=600",
Vary: "Accept",
}
/** Served for `<product-url>.md` and `Accept: text/markdown` via rewrites in next.config.js. */
export async function GET(
request: Request,
{ params }: { params: Promise<{ countryCode: string; handle: string }> }
) {
const { countryCode, handle } = await params
const region = await getRegion(countryCode)
const product = region
? await listProducts({ countryCode, queryParams: { handle } })
.then(({ response }) => response.products[0])
.catch(() => undefined)
: undefined
if (!region || !product) {
return new Response("# Product not found\n", { status: 404, headers: HEADERS })
}
return new Response(
renderProductMarkdown({
product,
region,
origin: getRequestOrigin(request),
countryCode,
}),
{ headers: HEADERS }
)
}

View File

@@ -0,0 +1,145 @@
import { Metadata } from "next"
import { notFound } from "next/navigation"
import { listProducts } from "@lib/data/products"
import { getRegion, listRegions } from "@lib/data/regions"
import ProductTemplate from "@modules/products/templates"
import { HttpTypes } from "@medusajs/types"
import { isVariantInStock } from "@lib/util/inventory"
import {
buildProductStructuredData,
getPricedVariants,
toJsonLd,
} from "@lib/util/product-structured-data"
import { getSiteOrigin, listCountryCodes, STORE_NAME } from "@lib/util/site"
type Props = {
params: Promise<{ countryCode: string; handle: string }>
}
export const dynamic = "force-static"
export const revalidate = 60
export async function generateMetadata(props: Props): Promise<Metadata> {
const params = await props.params
const { handle } = params
const region = await getRegion(params.countryCode)
if (!region) {
notFound()
}
const product = await listProducts({
countryCode: params.countryCode,
queryParams: { handle },
}).then(({ response }) => response.products[0])
if (!product) {
notFound()
}
const [origin, regions] = await Promise.all([getSiteOrigin(), listRegions()])
const path = `/products/${product.handle}`
const productUrl = `${origin}/${params.countryCode}${path}`
const description = product.description || product.title
return {
title: `${product.title} | ${STORE_NAME}`,
description,
alternates: {
canonical: productUrl,
languages: Object.fromEntries(
listCountryCodes(regions).map((code) => [
`en-${code.toUpperCase()}`,
`${origin}/${code}${path}`,
])
),
types: { "text/markdown": `${productUrl}.md` },
},
openGraph: {
title: `${product.title} | ${STORE_NAME}`,
description,
url: productUrl,
images: product.thumbnail ? [product.thumbnail] : [],
},
}
}
const ProductMetaTags = ({
product,
region,
}: {
product: HttpTypes.StoreProduct
region: HttpTypes.StoreRegion
}) => {
const variants = getPricedVariants(product)
const cheapest = variants.reduce<HttpTypes.StoreProductVariant | undefined>(
(min, v) =>
!min ||
v.calculated_price!.calculated_amount! <
min.calculated_price!.calculated_amount!
? v
: min,
undefined
)
const currency = region.currency_code.toUpperCase()
const amount = cheapest?.calculated_price?.calculated_amount?.toFixed(2)
return (
<>
<meta property="og:type" content="product" />
{amount && (
<>
<meta property="product:price:amount" content={amount} />
<meta property="product:price:currency" content={currency} />
<meta property="og:price:amount" content={amount} />
<meta property="og:price:currency" content={currency} />
</>
)}
<meta
property="product:availability"
content={variants.some(isVariantInStock) ? "in stock" : "out of stock"}
/>
</>
)
}
export default async function ProductPage(props: Props) {
const params = await props.params
const region = await getRegion(params.countryCode)
if (!region) {
notFound()
}
const pricedProduct = await listProducts({
countryCode: params.countryCode,
queryParams: { handle: params.handle },
}).then(({ response }) => response.products[0])
if (!pricedProduct) {
notFound()
}
const origin = await getSiteOrigin()
const structuredData = buildProductStructuredData({
product: pricedProduct,
region,
countryCode: params.countryCode,
productUrl: `${origin}/${params.countryCode}/products/${pricedProduct.handle}`,
})
return (
<>
<ProductMetaTags product={pricedProduct} region={region} />
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: toJsonLd(structuredData) }}
/>
<ProductTemplate
product={pricedProduct}
region={region}
countryCode={params.countryCode}
/>
</>
)
}

View File

@@ -0,0 +1,39 @@
import { Metadata } from "next"
import { getStorePolicies } from "@lib/data/store-policies"
import { PoliciesUnavailable, PolicyPage } from "@modules/policies/templates"
export const dynamic = "force-static"
export const revalidate = 60
export const metadata: Metadata = {
title: "Return policy",
description: "How to return items and get a refund.",
}
export default async function ReturnsPage(props: {
params: Promise<{ countryCode: string }>
}) {
const { countryCode } = await props.params
const { current } = await getStorePolicies(countryCode)
return (
<PolicyPage title="Return policy">
{current ? (
<>
<p>
You can return items within {current.returnWindowDays} days of
delivery. Items are returned by mail.
</p>
<p>
{current.freeReturns
? "Return shipping is free."
: "Return shipping costs are paid by the customer."}
</p>
</>
) : (
<PoliciesUnavailable />
)}
</PolicyPage>
)
}

View File

@@ -0,0 +1,72 @@
import { Metadata } from "next"
import { notFound } from "next/navigation"
import { listProducts } from "@lib/data/products"
import { getRegion } from "@lib/data/regions"
import ProductPreview from "@modules/products/components/product-preview"
import SearchForm from "@modules/search/components/search-form"
const RESULT_LIMIT = 24
type Props = {
params: Promise<{ countryCode: string }>
searchParams: Promise<{ q?: string | string[] }>
}
const getQuery = (q?: string | string[]) =>
(Array.isArray(q) ? q[0] : q)?.trim().slice(0, 200) ?? ""
export async function generateMetadata(props: Props): Promise<Metadata> {
const query = getQuery((await props.searchParams).q)
return {
title: query ? `Search results for "${query}"` : "Search",
robots: { index: false, follow: true },
}
}
export default async function SearchPage(props: Props) {
const { countryCode } = await props.params
const query = getQuery((await props.searchParams).q)
const region = await getRegion(countryCode)
if (!region) {
notFound()
}
const { response } = query
? await listProducts({
countryCode,
queryParams: { q: query, limit: RESULT_LIMIT },
})
: { response: { products: [], count: 0 } }
return (
<div className="content-container py-6" data-testid="search-container">
<h1 className="text-2xl-semi mb-6">
{query ? `Search results for "${query}"` : "Search"}
</h1>
<SearchForm countryCode={countryCode} defaultValue={query} className="mb-8 max-w-xl" />
{query && (
<p className="text-small-regular text-ui-fg-subtle mb-6">
{response.count} {response.count === 1 ? "product" : "products"} found
</p>
)}
{query && response.products.length === 0 ? (
<p className="text-ui-fg-subtle">
No products match your search. Try a different keyword.
</p>
) : (
<ul
className="grid grid-cols-2 w-full small:grid-cols-3 medium:grid-cols-4 gap-x-6 gap-y-8"
data-testid="search-results"
>
{response.products.map((product) => (
<li key={product.id}>
<ProductPreview product={product} region={region} />
</li>
))}
</ul>
)}
</div>
)
}

View File

@@ -0,0 +1,42 @@
import { Metadata } from "next"
import { getStorePolicies } from "@lib/data/store-policies"
import {
PoliciesUnavailable,
PolicyPage,
ShippingSummary,
} from "@modules/policies/templates"
export const dynamic = "force-static"
export const revalidate = 60
export const metadata: Metadata = {
title: "Shipping information",
description: "Shipping rates and delivery times.",
}
export default async function ShippingPage(props: {
params: Promise<{ countryCode: string }>
}) {
const { countryCode } = await props.params
const { current, currencyCode } = await getStorePolicies(countryCode)
return (
<PolicyPage title="Shipping information">
{current ? (
<>
<p>
Orders to {countryCode.toUpperCase()} ship with the following rates
and delivery times.
</p>
<ShippingSummary policies={current} currencyCode={currencyCode} />
<p className="text-ui-fg-subtle">
Available shipping methods and final costs are shown at checkout.
</p>
</>
) : (
<PoliciesUnavailable />
)}
</PolicyPage>
)
}

View File

@@ -0,0 +1,23 @@
import { Metadata } from "next"
import { notFound } from "next/navigation"
import { getRegion } from "@lib/data/regions"
import StoreTemplate from "@modules/store/templates"
export const metadata: Metadata = {
title: "Store",
description: "Explore all of our products.",
}
export default async function StorePage(props: {
params: Promise<{ countryCode: string }>
}) {
const { countryCode } = await props.params
const region = await getRegion(countryCode)
if (!region) {
notFound()
}
return <StoreTemplate currencyCode={region.currency_code} />
}

View File

@@ -0,0 +1,29 @@
import { Metadata } from "next"
import { STORE_NAME } from "@lib/util/site"
import { PlaceholderNotice, PolicyPage } from "@modules/policies/templates"
export const dynamic = "force-static"
export const revalidate = 60
export const metadata: Metadata = {
title: "Terms of service",
description: `Terms that apply to purchases from ${STORE_NAME}.`,
}
export default function TermsPage() {
return (
<PolicyPage title="Terms of service">
<PlaceholderNotice />
<p>
By placing an order with {STORE_NAME} you agree to these terms. Prices,
product availability and shipping options are shown on the product
pages and at checkout, and may change without notice.
</p>
<p>
Orders are confirmed by email once payment is received. Returns and
refunds are handled according to our return policy.
</p>
</PolicyPage>
)
}

View File

@@ -0,0 +1,25 @@
import { Metadata } from "next"
import { Suspense } from "react"
import VerifyAccount from "@modules/account/components/verify-account"
export const metadata: Metadata = {
title: "Verify your email",
description: "Verify your email address to complete your registration.",
}
export default function VerifyAccountPage() {
return (
<div className="w-full flex justify-center px-8 py-12">
<Suspense
fallback={
<p className="text-base-regular text-ui-fg-base">
Verifying your email...
</p>
}
>
<VerifyAccount />
</Suspense>
</div>
)
}

View File

@@ -0,0 +1,103 @@
import { sdk } from "@lib/config"
import { submitAdyenPayment } from "@lib/data/adyen"
import { placeOrder } from "@lib/data/cart"
import { getAuthHeaders, setCartId } from "@lib/data/cookies"
import { HttpTypes } from "@medusajs/types"
import { unstable_rethrow } from "next/navigation"
import { NextRequest, NextResponse } from "next/server"
export async function GET(req: NextRequest) {
const { origin, searchParams } = req.nextUrl
const cartId = searchParams.get("cart_id")
const countryCode = searchParams.get("country_code")
const paymentIntent = searchParams.get("payment_intent")
const paymentIntentClientSecret = searchParams.get(
"payment_intent_client_secret"
)
const redirectStatus = searchParams.get("redirect_status")
// Without a country code the middleware resolves the customer's region and
// prefixes it; either way every redirect below stays on this origin.
const prefix = countryCode ? `/${countryCode}` : ""
const rejected = () =>
NextResponse.redirect(`${origin}${prefix}/cart?error=payment_failed`)
// Adyen returns the shopper here after a redirect, for example to their bank's
// authentication page, with the result to submit to the payment session.
const redirectResult = searchParams.get("redirectResult")
if (cartId && redirectResult) {
await setCartId(cartId)
try {
// Redirects to the order confirmation once the payment is authorized.
await submitAdyenPayment({ details: { redirectResult } }, cartId)
} catch (error) {
unstable_rethrow(error)
}
return rejected()
}
if (!cartId || !paymentIntent || !paymentIntentClientSecret) {
return rejected()
}
const cart = await sdk.client
.fetch<HttpTypes.StoreCartResponse>(`/store/carts/${cartId}`, {
method: "GET",
query: { fields: "payment_collection.payment_sessions.data" },
headers: { ...(await getAuthHeaders()) },
cache: "no-store",
})
.then(({ cart }) => cart)
.catch(() => null)
const paymentSession = cart?.payment_collection?.payment_sessions?.find(
(session) => session.data?.id === paymentIntent
)
if (
!paymentSession ||
paymentSession.data?.client_secret !== paymentIntentClientSecret
) {
return rejected()
}
await setCartId(cartId)
// The customer backed out or the bank declined. Stripe puts the PaymentIntent
// back into `requires_payment_method`, so the Payment Element can mount
// against it again — return to the payment step and let them retry.
if (redirectStatus === "failed") {
const params = new URLSearchParams({ step: "payment" })
// Forward Stripe's own return parameters so the checkout step can tell how
// the off-site authorization ended.
for (const key of [
"payment_intent",
"payment_intent_client_secret",
"redirect_status",
]) {
const value = searchParams.get(key)
if (value) {
params.set(key, value)
}
}
return NextResponse.redirect(`${origin}${prefix}/checkout?${params}`)
}
try {
await placeOrder(cartId)
} catch (error) {
unstable_rethrow(error)
return NextResponse.redirect(`${origin}${prefix}/cart?error=order_failed`)
}
// Only reached when the cart did not convert into an order.
return NextResponse.redirect(`${origin}${prefix}/cart?error=order_failed`)
}

View File

@@ -0,0 +1,72 @@
import {
activateCart,
createCartWithItems,
findMissingVariantIds,
MAX_LINE_ITEM_QUANTITY,
resolveRegion,
} from "@lib/util/server-cart"
import { getRequestOrigin } from "@lib/util/site"
import { NextResponse } from "next/server"
const ITEM_PATTERN = /^([A-Za-z0-9._-]+|~[A-Za-z0-9_-]+):([1-9][0-9]*)$/
const NO_STORE = { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" }
const decodeItemId = (token: string) =>
token.startsWith("~")
? Buffer.from(token.slice(1), "base64url").toString("utf8")
: token
const parseItems = (raw: string) => {
const items: { variant_id: string; quantity: number }[] = []
for (const pair of decodeURIComponent(raw).split(",")) {
const match = pair.match(ITEM_PATTERN)
if (!match) {
return null
}
const quantity = Number(match[2])
if (quantity > MAX_LINE_ITEM_QUANTITY) {
return null
}
items.push({ variant_id: decodeItemId(match[1]), quantity })
}
return items.length ? items : null
}
const textResponse = (body: string, status: number) =>
new NextResponse(body, { status, headers: NO_STORE })
/** UCP cart permalink: /buy/{variant_id}:{quantity},... builds a cart and opens checkout. */
export async function GET(
request: Request,
{ params }: { params: Promise<{ items: string }> }
) {
const items = parseItems((await params).items)
if (!items) {
return textResponse("Malformed permalink. Use /buy/{variant_id}:{quantity},...", 400)
}
const country = new URL(request.url).searchParams.get("context/address_country")
const resolved = await resolveRegion(country ?? undefined)
if (!resolved) {
return textResponse("This store does not ship to the requested country", 400)
}
const missing = await findMissingVariantIds(items.map((item) => item.variant_id))
if (missing.length) {
return textResponse(`Unknown items: ${missing.join(", ")}`, 404)
}
let cartId: string
try {
cartId = await createCartWithItems(resolved.region.id, items)
} catch {
return textResponse("One or more items in this link can't be purchased", 400)
}
await activateCart(cartId)
return NextResponse.redirect(
`${getRequestOrigin(request)}/${resolved.countryCode}/checkout`,
{ status: 303, headers: NO_STORE }
)
}

View File

@@ -0,0 +1,27 @@
import { getBaseURL } from "@lib/util/env"
import { Metadata } from "next"
import { Plus_Jakarta_Sans } from "next/font/google"
import "styles/globals.css"
const fontSans = Plus_Jakarta_Sans({
subsets: ["latin", "latin-ext"],
variable: "--font-sans",
display: "swap",
})
export const metadata: Metadata = {
metadataBase: new URL(getBaseURL()),
}
export default function RootLayout(props: { children: React.ReactNode }) {
return (
<html lang="hr" data-mode="light" className={fontSans.variable}>
<head>
<link rel="ucp" href="/.well-known/ucp" />
</head>
<body className="min-h-screen bg-background font-sans antialiased">
<main className="relative">{props.children}</main>
</body>
</html>
)
}

View File

@@ -0,0 +1,72 @@
import { listCategories } from "@lib/data/categories"
import { listCollections } from "@lib/data/collections"
import { listRegions } from "@lib/data/regions"
import { UCP_MCP_PATH, UCP_REST_BASE_PATH } from "@lib/ucp/ucp"
import {
getDefaultCountryCode,
getRequestOrigin,
listCountryCodes,
STORE_NAME,
} from "@lib/util/site"
export async function GET(request: Request) {
const origin = getRequestOrigin(request)
const [regions, categories, { collections }] = await Promise.all([
listRegions(),
listCategories({ fields: "name,handle,parent_category_id", limit: 50 }),
listCollections({ fields: "title,handle", limit: "50" }),
])
const countries = listCountryCodes(regions)
const base = `${origin}/${getDefaultCountryCode(regions)}`
const currencies = Array.from(
new Set(regions.map((r) => r.currency_code?.toUpperCase()).filter(Boolean))
)
const links = [
...categories
.filter((c) => !c.parent_category_id)
.map((c) => `- [${c.name}](${base}/categories/${c.handle})`),
...collections.map((c) => `- [${c.title}](${base}/collections/${c.handle})`),
]
const body = `# ${STORE_NAME}
> Online store. Ships to ${countries.length} countries. Prices in ${currencies.join(", ")}.
URLs are prefixed with a two-letter country code that sets currency and pricing, for example \`${base}\`. Available country codes: ${countries.join(", ")}.
## Shop
- [All products](${base}/store)
${links.join("\n")}
- Search: ${base}/search?q={query}
## Buying
- Product pages contain an add-to-cart form that posts \`variant_id\` and \`quantity\` to ${base}/cart/add.
- Preselect a variant with \`?v_id={variant_id}\` on a product URL.
- Append \`.md\` to a product URL (or send \`Accept: text/markdown\`) for a Markdown version with variant IDs, prices and stock.
- Checkout link: ${origin}/buy/{variant_id}:{quantity},{variant_id}:{quantity}
- [Cart](${base}/cart)
## Policies
- [Shipping information](${base}/shipping)
- [Return policy](${base}/returns)
- [Terms of service](${base}/terms)
- [Privacy policy](${base}/privacy)
- [Contact](${base}/contact)
## For agents
- [Sitemap](${origin}/sitemap.xml)
- [UCP profile](${origin}/.well-known/ucp)
- UCP MCP endpoint: ${origin}${UCP_MCP_PATH}
- UCP REST endpoint: ${origin}${UCP_REST_BASE_PATH}
`
return new Response(body, {
headers: {
"Content-Type": "text/markdown; charset=utf-8",
"Cache-Control": "public, max-age=3600",
},
})
}

View File

@@ -0,0 +1,27 @@
import { ArrowUpRightMini } from "@medusajs/icons"
import { Text } from "@modules/common/components/ui"
import { Metadata } from "next"
import Link from "next/link"
export const metadata: Metadata = {
title: "404",
description: "Something went wrong",
}
export default function NotFound() {
return (
<div className="flex flex-col gap-4 items-center justify-center min-h-[calc(100vh-64px)]">
<h1 className="text-2xl-semi text-ui-fg-base">Page not found</h1>
<p className="text-small-regular text-ui-fg-base">
The page you tried to access does not exist.
</p>
<Link className="flex gap-x-1 items-center group" href="/">
<Text className="text-ui-fg-interactive">Go to frontpage</Text>
<ArrowUpRightMini
className="group-hover:rotate-45 ease-in-out duration-150"
color="var(--fg-interactive)"
/>
</Link>
</div>
)
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 KiB

View File

@@ -0,0 +1,21 @@
import { getSiteOrigin } from "@lib/util/site"
import type { MetadataRoute } from "next"
export default async function robots(): Promise<MetadataRoute.Robots> {
const origin = await getSiteOrigin()
return {
rules: {
userAgent: "*",
allow: "/",
disallow: [
"/*/cart",
"/*/checkout",
"/*/account",
"/*/order/",
"/buy/",
],
},
sitemap: `${origin}/sitemap.xml`,
}
}

View File

@@ -0,0 +1,72 @@
import { sdk } from "@lib/config"
import { listRegions } from "@lib/data/regions"
import { getSiteOrigin, listCountryCodes } from "@lib/util/site"
import type { MetadataRoute } from "next"
const STATIC_PATHS = [
"",
"/store",
"/shipping",
"/returns",
"/terms",
"/privacy",
"/contact",
]
const PAGE_SIZE = 200
type Page<T> = { items: T[]; count: number }
async function listAll<T>(fetchPage: (offset: number) => Promise<Page<T>>) {
const all: T[] = []
for (let offset = 0; ; offset += PAGE_SIZE) {
const { items, count } = await fetchPage(offset)
all.push(...items)
if (offset + PAGE_SIZE >= count || !items.length) {
return all
}
}
}
type Entry = { handle?: string | null; updated_at?: string | Date | null }
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const query = { fields: "handle,updated_at", limit: PAGE_SIZE }
const [origin, regions, products, categories, collections] = await Promise.all([
getSiteOrigin(),
listRegions(),
listAll<Entry>((offset) =>
sdk.store.product
.list({ ...query, offset })
.then((res) => ({ items: res.products, count: res.count }))
),
listAll<Entry>((offset) =>
sdk.store.category
.list({ ...query, offset })
.then((res) => ({ items: res.product_categories, count: res.count }))
),
listAll<Entry>((offset) =>
sdk.store.collection
.list({ ...query, offset })
.then((res) => ({ items: res.collections, count: res.count }))
),
])
const toEntries = (base: string, prefix: string, items: Entry[]) =>
items
.filter((item) => item.handle)
.map((item) => ({
url: `${base}/${prefix}/${item.handle}`,
lastModified: item.updated_at ? new Date(item.updated_at) : undefined,
}))
return listCountryCodes(regions).flatMap((countryCode) => {
const base = `${origin}/${countryCode}`
return [
...STATIC_PATHS.map((path) => ({ url: `${base}${path}` })),
...toEntries(base, "products", products),
...toEntries(base, "categories", categories),
...toEntries(base, "collections", collections),
]
})
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 KiB

View File

@@ -0,0 +1,6 @@
import { handleMcpRequest } from "@lib/ucp/mcp"
export const POST = (request: Request) => handleMcpRequest(request)
export const GET = () =>
new Response("Method Not Allowed", { status: 405, headers: { Allow: "POST" } })

View File

@@ -0,0 +1,15 @@
import { cancelCart, getCart, updateCart } from "@lib/ucp/operations"
import { readJsonBody, toResponse } from "@lib/ucp/ucp"
type Context = { params: Promise<{ cartId: string }> }
export const GET = async (request: Request, { params }: Context) =>
toResponse(await getCart(request, (await params).cartId))
export const PUT = async (request: Request, { params }: Context) =>
toResponse(
await updateCart(request, (await params).cartId, (await readJsonBody(request)) ?? {})
)
export const DELETE = async (request: Request, { params }: Context) =>
toResponse(await cancelCart(request, (await params).cartId))

View File

@@ -0,0 +1,11 @@
import { createCart } from "@lib/ucp/operations"
import { readJsonBody, toResponse } from "@lib/ucp/ucp"
export const POST = async (request: Request) =>
toResponse(
await createCart(
request,
(await readJsonBody(request)) ?? {},
request.headers.get("idempotency-key")
)
)

View File

@@ -0,0 +1,5 @@
import { lookupCatalog } from "@lib/ucp/operations"
import { readJsonBody, toResponse } from "@lib/ucp/ucp"
export const POST = async (request: Request) =>
toResponse(await lookupCatalog(request, (await readJsonBody(request)) ?? {}))

View File

@@ -0,0 +1,5 @@
import { searchCatalog } from "@lib/ucp/operations"
import { readJsonBody, toResponse } from "@lib/ucp/ucp"
export const POST = async (request: Request) =>
toResponse(await searchCatalog(request, (await readJsonBody(request)) ?? {}))

View File

@@ -0,0 +1,7 @@
import { cancelCheckout } from "@lib/ucp/operations"
import { toResponse } from "@lib/ucp/ucp"
export const POST = async (
request: Request,
{ params }: { params: Promise<{ id: string }> }
) => toResponse(await cancelCheckout(request, (await params).id))

View File

@@ -0,0 +1,7 @@
import { completeCheckout } from "@lib/ucp/operations"
import { toResponse } from "@lib/ucp/ucp"
export const POST = async (
request: Request,
{ params }: { params: Promise<{ id: string }> }
) => toResponse(await completeCheckout(request, (await params).id))

View File

@@ -0,0 +1,12 @@
import { getCheckout, updateCheckout } from "@lib/ucp/operations"
import { readJsonBody, toResponse } from "@lib/ucp/ucp"
type Context = { params: Promise<{ id: string }> }
export const GET = async (request: Request, { params }: Context) =>
toResponse(await getCheckout(request, (await params).id))
export const PUT = async (request: Request, { params }: Context) =>
toResponse(
await updateCheckout(request, (await params).id, (await readJsonBody(request)) ?? {})
)

View File

@@ -0,0 +1,11 @@
import { createCheckout } from "@lib/ucp/operations"
import { readJsonBody, toResponse } from "@lib/ucp/ucp"
export const POST = async (request: Request) =>
toResponse(
await createCheckout(
request,
(await readJsonBody(request)) ?? {},
request.headers.get("idempotency-key")
)
)

View File

@@ -0,0 +1,26 @@
import { handleMcpRequest } from "@lib/ucp/mcp"
import { UCP_MCP_PATH, UCP_REST_BASE_PATH, UCP_VERSION } from "@lib/ucp/ucp"
import { getRequestOrigin } from "@lib/util/site"
export const GET = (request: Request) => {
const origin = getRequestOrigin(request)
const base = `${origin}${UCP_REST_BASE_PATH}`
return Response.json({
ucp: { version: UCP_VERSION },
profile: `${origin}/.well-known/ucp`,
mcp: `${origin}${UCP_MCP_PATH}`,
operations: [
`POST ${base}/catalog/search`,
`POST ${base}/catalog/lookup`,
`POST ${base}/cart`,
`GET|PUT|DELETE ${base}/cart/{id}`,
`POST ${base}/checkout-sessions`,
`GET|PUT ${base}/checkout-sessions/{id}`,
`POST ${base}/checkout-sessions/{id}/complete`,
`POST ${base}/checkout-sessions/{id}/cancel`,
],
})
}
// Agents that only know the service URL may probe it with MCP JSON-RPC.
export const POST = (request: Request) => handleMcpRequest(request)

View File

@@ -0,0 +1,71 @@
import React from "react"
import { cn } from "@/lib/utils"
export interface SectionHeaderProps {
kicker?: string
title: string
description?: string
action?: React.ReactNode
className?: string
titleClassName?: string
kickerClassName?: string
}
/**
* SectionHeader / SectionHeader1
* Unificirana komponenta sa podijeljenim zaglavljem:
* - Lijevo: Kicker / oznaka sekcije (npr. "Naši Proizvodi", "Naša Misija")
* - Desno: Veliki naslov i opcioni opis ili CTA
*/
export function SectionHeader({
kicker,
title,
description,
action,
className,
titleClassName,
kickerClassName,
}: SectionHeaderProps) {
return (
<div
className={cn(
"flex flex-col lg:flex-row lg:items-start justify-between gap-6 mb-12 sm:mb-16",
className
)}
>
{/* Left Column: Kicker */}
{kicker && (
<div
className={cn(
"text-sm font-semibold tracking-wide text-muted-foreground uppercase shrink-0 pt-1.5",
kickerClassName
)}
>
{kicker}
</div>
)}
{/* Right Column: Title & Description */}
<div className="max-w-2xl space-y-3">
<h2
className={cn(
"text-3xl sm:text-4xl lg:text-5xl font-medium tracking-tight text-foreground leading-[1.18]",
titleClassName
)}
>
{title}
</h2>
{description && (
<p className="text-base sm:text-lg text-muted-foreground leading-relaxed">
{description}
</p>
)}
{action && <div className="pt-2">{action}</div>}
</div>
</div>
)
}
export const SectionHeader1 = SectionHeader
export default SectionHeader

View 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)
}

View File

@@ -0,0 +1,127 @@
import { CreditCard } from "@medusajs/icons"
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",
]

View 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
}

View File

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

View File

@@ -0,0 +1,473 @@
"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 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"),
},
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"),
}
await updateCart(data)
} catch (e: any) {
return e.message
}
redirect(
`/${formData.get("shipping_address.country_code")}/checkout?step=delivery`
)
}
/**
* Places an order for a cart. If no cart ID is provided, it will use the cart ID from the cookies.
* @param cartId - optional - The ID of the cart to place an order for.
* @returns The cart object if the order was successful, or null if not.
*/
export async function placeOrder(cartId?: string) {
const id = cartId || (await getCartId())
if (!id) {
throw new Error("No existing cart found when placing an order")
}
const headers = {
...(await getAuthHeaders()),
}
const cartRes = await sdk.store.cart
.complete(id, {}, headers)
.then(async (cartRes) => {
const cartCacheTag = await getCacheTag("carts")
revalidateTag(cartCacheTag, { expire: 0 })
return cartRes
})
.catch(medusaError)
if (cartRes?.type === "order") {
const countryCode =
cartRes.order.shipping_address?.country_code?.toLowerCase()
const orderCacheTag = await getCacheTag("orders")
revalidateTag(orderCacheTag, { expire: 0 })
removeCartId()
redirect(`/${countryCode}/order/${cartRes?.order.id}/confirmed`)
}
return cartRes.cart
}
/**
* Updates the countrycode param and revalidates the regions cache
* @param regionId
* @param countryCode
*/
export async function updateRegion(countryCode: string, currentPath: string) {
const cartId = await getCartId()
const region = await getRegion(countryCode)
if (!region) {
throw new Error(`Region not found for country code: ${countryCode}`)
}
if (cartId) {
await updateCart({ region_id: region.id })
const cartCacheTag = await getCacheTag("carts")
revalidateTag(cartCacheTag, { expire: 0 })
}
const regionCacheTag = await getCacheTag("regions")
revalidateTag(regionCacheTag, { expire: 0 })
const productsCacheTag = await getCacheTag("products")
revalidateTag(productsCacheTag, { expire: 0 })
redirect(`/${countryCode}${currentPath}`)
}
export async function listCartOptions() {
const cartId = await getCartId()
const headers = {
...(await getAuthHeaders()),
}
const next = {
...(await getCacheOptions("shippingOptions")),
}
return await sdk.client.fetch<{
shipping_options: HttpTypes.StoreCartShippingOption[]
}>("/store/shipping-options", {
query: { cart_id: cartId },
next,
headers,
cache: "force-cache",
})
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View 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
}

View 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

View 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

View 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}`,
]),
})

View 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)}`)
}
}

View 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()
}

View 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}`

View 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))
}

View 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",
])
)
}

View File

@@ -0,0 +1,3 @@
export const getBaseURL = () => {
return process.env.NEXT_PUBLIC_BASE_URL || "https://localhost:8000"
}

View 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
}

View File

@@ -0,0 +1,6 @@
export const getPercentageDiff = (original: number, calculated: number) => {
const diff = original - calculated
const decrease = (diff / original) * 100
return decrease.toFixed()
}

View 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(),
}
}

View 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)

View 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)
)
}

View 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)
}
}

View 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()
}

View 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
}

View 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)
`
}

View 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 []
}

View 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")

Some files were not shown because too many files have changed in this diff Show More