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

View File

@@ -0,0 +1,5 @@
import { HttpTypes } from "@medusajs/types";
export const isSimpleProduct = (product: HttpTypes.StoreProduct): boolean => {
return product.options?.length === 1 && product.options[0].values?.length === 1;
}

View File

@@ -0,0 +1,5 @@
const repeat = (times: number) => {
return Array.from(Array(times).keys())
}
export default repeat

View File

@@ -0,0 +1,53 @@
import "server-only"
import { sdk } from "@lib/config"
import { getCacheTag, setCartId } from "@lib/data/cookies"
import { listRegions } from "@lib/data/regions"
import { HttpTypes } from "@medusajs/types"
import { revalidateTag } from "next/cache"
import { getDefaultCountryCode } from "./site"
export const MAX_LINE_ITEM_QUANTITY = 100
/** Stores the cart in the shopper's cookie and clears cached cart reads. */
export const activateCart = async (cartId: string) => {
await setCartId(cartId)
const cartCacheTag = await getCacheTag("carts")
if (cartCacheTag) {
revalidateTag(cartCacheTag, { expire: 0 })
}
}
/**
* Resolves the region from an explicit country code, falling back to the
* store's default country only when none was requested.
*/
export const resolveRegion = async (
countryCode?: string
): Promise<{ countryCode: string; region: HttpTypes.StoreRegion } | null> => {
const regions = await listRegions()
const code = countryCode?.toLowerCase() || getDefaultCountryCode(regions)
const region = regions.find((r) => r.countries?.some((c) => c.iso_2 === code))
return code && region ? { countryCode: code, region } : null
}
export const createCartWithItems = async (
regionId: string,
items: { variant_id: string; quantity: number }[]
) => {
const { cart } = await sdk.store.cart.create({ region_id: regionId })
for (const item of items) {
await sdk.store.cart.createLineItem(cart.id, item)
}
return cart.id
}
/** Returns the requested variant IDs that don't exist in the store's sales channel. */
export const findMissingVariantIds = async (variantIds: string[]) => {
const { variants } = await sdk.client.fetch<{
variants: { id: string }[]
}>("/store/product-variants", {
query: { id: variantIds, fields: "id", limit: variantIds.length },
})
const found = new Set(variants.map((variant) => variant.id))
return variantIds.filter((id) => !found.has(id))
}

View File

@@ -0,0 +1,51 @@
import "server-only"
import { headers } from "next/headers"
import siteConfig from "@/config/site.json"
export const STORE_NAME = siteConfig.name
export const DEFAULT_COUNTRY_CODE = (
process.env.NEXT_PUBLIC_DEFAULT_REGION || siteConfig.countryCode
).toLowerCase()
const configuredUrl = () => process.env.NEXT_PUBLIC_BASE_URL?.replace(/\/$/, "")
const originFromHeaders = (get: (name: string) => string | null) => {
const host = (get("x-forwarded-host") ?? get("host"))?.split(",")[0].trim()
if (!host) {
return undefined
}
const proto = get("x-forwarded-proto")?.split(",")[0].trim() || "https"
return `${proto}://${host}`
}
export const getRequestOrigin = (request: Request): string =>
configuredUrl() ||
originFromHeaders((name) => request.headers.get(name)) ||
new URL(request.url).origin
/** Origin for absolute URLs in server components (canonical, JSON-LD, OpenGraph). */
export const getSiteOrigin = async (): Promise<string> => {
const configured = configuredUrl()
if (configured) {
return configured
}
const requestHeaders = await headers()
return originFromHeaders((name) => requestHeaders.get(name)) || "http://localhost:8000"
}
export const listCountryCodes = (
regions: { countries?: { iso_2?: string | null }[] | null }[]
): string[] =>
regions.flatMap((region) =>
(region.countries ?? [])
.map((country) => country.iso_2?.toLowerCase())
.filter((code): code is string => Boolean(code))
)
export const getDefaultCountryCode = (
regions: { countries?: { iso_2?: string | null }[] | null }[]
) => {
const codes = listCountryCodes(regions)
return codes.includes(DEFAULT_COUNTRY_CODE) ? DEFAULT_COUNTRY_CODE : codes[0]
}

View File

@@ -0,0 +1,50 @@
import { HttpTypes } from "@medusajs/types"
import { SortOptions } from "@modules/store/components/refinement-list/sort-products"
interface MinPricedProduct extends HttpTypes.StoreProduct {
_minPrice?: number
}
/**
* Helper function to sort products by price until the store API supports sorting by price
* @param products
* @param sortBy
* @returns products sorted by price
*/
export function sortProducts(
products: HttpTypes.StoreProduct[],
sortBy: SortOptions
): HttpTypes.StoreProduct[] {
const sortedProducts = products as MinPricedProduct[]
if (["price_asc", "price_desc"].includes(sortBy)) {
// Precompute the minimum price for each product
sortedProducts.forEach((product) => {
if (product.variants && product.variants.length > 0) {
product._minPrice = Math.min(
...product.variants.map(
(variant) => variant?.calculated_price?.calculated_amount || 0
)
)
} else {
product._minPrice = Infinity
}
})
// Sort products based on the precomputed minimum prices
sortedProducts.sort((a, b) => {
const diff = a._minPrice! - b._minPrice!
return sortBy === "price_asc" ? diff : -diff
})
}
if (sortBy === "created_at") {
sortedProducts.sort((a, b) => {
return (
new Date(b.created_at!).getTime() - new Date(a.created_at!).getTime()
)
})
}
return sortedProducts
}

View File

@@ -0,0 +1,103 @@
import { HttpTypes } from "@medusajs/types"
export type StorePolicies = {
returnWindowDays: number
freeReturns: boolean
shippingRate: number
handlingDays: { min: number; max: number }
transitDays: { min: number; max: number }
}
const toNumber = (value: unknown) => {
const number =
typeof value === "string" && value.trim() === "" ? NaN : Number(value)
return Number.isFinite(number) && number >= 0 ? number : null
}
/**
* Reads the store policy keys set on a region's metadata in Medusa Admin.
* Returns null when any value is missing or invalid, so callers omit policy
* data instead of publishing guesses.
*/
export const getRegionPolicies = (
region: Pick<HttpTypes.StoreRegion, "metadata"> | null | undefined
): StorePolicies | null => {
const metadata = region?.metadata ?? {}
const values = {
returnWindowDays: toNumber(metadata.return_window_days),
shippingRate: toNumber(metadata.shipping_rate),
handlingMin: toNumber(metadata.handling_days_min),
handlingMax: toNumber(metadata.handling_days_max),
transitMin: toNumber(metadata.transit_days_min),
transitMax: toNumber(metadata.transit_days_max),
}
if (Object.values(values).some((value) => value === null)) {
return null
}
return {
returnWindowDays: values.returnWindowDays!,
freeReturns:
metadata.free_returns === true || metadata.free_returns === "true",
shippingRate: values.shippingRate!,
handlingDays: { min: values.handlingMin!, max: values.handlingMax! },
transitDays: { min: values.transitMin!, max: values.transitMax! },
}
}
const businessDays = (range: { min: number; max: number }) => ({
"@type": "QuantitativeValue",
minValue: range.min,
maxValue: range.max,
unitCode: "DAY",
})
export const buildShippingDetails = (
policies: StorePolicies,
countryCode: string,
currencyCode: string
) => ({
"@type": "OfferShippingDetails",
shippingRate: {
"@type": "MonetaryAmount",
value: policies.shippingRate,
currency: currencyCode.toUpperCase(),
},
shippingDestination: {
"@type": "DefinedRegion",
addressCountry: countryCode.toUpperCase(),
},
deliveryTime: {
"@type": "ShippingDeliveryTime",
handlingTime: businessDays(policies.handlingDays),
transitTime: businessDays(policies.transitDays),
},
})
export const buildReturnPolicy = (
policies: StorePolicies,
countryCode: string
) => ({
"@type": "MerchantReturnPolicy",
applicableCountry: countryCode.toUpperCase(),
returnPolicyCategory: "https://schema.org/MerchantReturnFiniteReturnWindow",
merchantReturnDays: policies.returnWindowDays,
returnMethod: "https://schema.org/ReturnByMail",
returnFees: policies.freeReturns
? "https://schema.org/FreeReturn"
: "https://schema.org/ReturnFeesCustomerResponsibility",
})
export const buildRegionsReturnPolicies = (regions: HttpTypes.StoreRegion[]) =>
regions.flatMap((region) => {
const policies = getRegionPolicies(region)
if (!policies) {
return []
}
return (region.countries ?? [])
.filter((country) => country.iso_2)
.map((country) => buildReturnPolicy(policies, country.iso_2!))
})
export const formatDayRange = ({ min, max }: { min: number; max: number }) =>
min === max ? `${min}` : `${min}-${max}`