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,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,106 @@
import { Metadata } from "next"
import Hero from "@modules/home/components/hero"
import PartnersTicker from "@modules/home/components/partners-ticker"
import ProductShowcase from "@modules/home/components/product-showcase"
import MissionSection from "@modules/home/components/mission-section"
import CtaBanner from "@modules/home/components/cta-banner"
import LatestNews from "@modules/home/components/latest-news"
import FaqSection from "@modules/home/components/faq-section"
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"
import siteConfig from "@/config/site.json"
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: siteConfig.title,
description: siteConfig.description,
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 />
<PartnersTicker />
<ProductShowcase />
<MissionSection />
<CtaBanner />
<LatestNews />
<FaqSection />
</>
)
}

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