first commit
This commit is contained in:
3
apps/suman-hrvatska/.prettierrc.json
Normal file
3
apps/suman-hrvatska/.prettierrc.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"semi": false
|
||||
}
|
||||
9
apps/suman-hrvatska/AGENTS.md
Normal file
9
apps/suman-hrvatska/AGENTS.md
Normal file
@@ -0,0 +1,9 @@
|
||||
<!-- BEGIN:nextjs-agent-rules -->
|
||||
|
||||
# This is NOT the Next.js you know
|
||||
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
|
||||
|
||||
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
|
||||
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
1
apps/suman-hrvatska/CLAUDE.md
Normal file
1
apps/suman-hrvatska/CLAUDE.md
Normal file
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
40
apps/suman-hrvatska/check-env-variables.js
Normal file
40
apps/suman-hrvatska/check-env-variables.js
Normal file
@@ -0,0 +1,40 @@
|
||||
const c = require("ansi-colors");
|
||||
|
||||
const requiredEnvs = [
|
||||
{
|
||||
key: "NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY",
|
||||
// TODO: we need a good doc to point this to
|
||||
description:
|
||||
"Learn how to create a publishable key: https://docs.medusajs.com/v2/resources/storefront-development/publishable-api-keys",
|
||||
},
|
||||
];
|
||||
|
||||
function checkEnvVariables() {
|
||||
const missingEnvs = requiredEnvs.filter(function (env) {
|
||||
c;
|
||||
return !process.env[env.key];
|
||||
});
|
||||
|
||||
if (missingEnvs.length > 0) {
|
||||
console.error(
|
||||
c.red.bold("\n🚫 Error: Missing required environment variables\n")
|
||||
);
|
||||
|
||||
missingEnvs.forEach(function (env) {
|
||||
console.error(c.yellow(` ${c.bold(env.key)}`));
|
||||
if (env.description) {
|
||||
console.error(c.dim(` ${env.description}\n`));
|
||||
}
|
||||
});
|
||||
|
||||
console.error(
|
||||
c.yellow(
|
||||
"\nPlease set these variables in your .env file or environment before starting the application.\n"
|
||||
)
|
||||
);
|
||||
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = checkEnvVariables;
|
||||
31
apps/suman-hrvatska/eslint.config.mjs
Normal file
31
apps/suman-hrvatska/eslint.config.mjs
Normal file
@@ -0,0 +1,31 @@
|
||||
import { defineConfig, globalIgnores } from "eslint/config"
|
||||
import nextVitals from "eslint-config-next/core-web-vitals"
|
||||
import nextTs from "eslint-config-next/typescript"
|
||||
|
||||
export default defineConfig([
|
||||
...nextVitals,
|
||||
...nextTs,
|
||||
{
|
||||
rules: {
|
||||
"react-hooks/set-state-in-effect": "warn",
|
||||
"react-hooks/refs": "warn",
|
||||
"@typescript-eslint/no-unused-vars": [
|
||||
"error",
|
||||
{
|
||||
argsIgnorePattern: "^_",
|
||||
varsIgnorePattern: "^_",
|
||||
caughtErrorsIgnorePattern: "^_",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
globalIgnores([
|
||||
".next/**",
|
||||
"out/**",
|
||||
"build/**",
|
||||
"next-env.d.ts",
|
||||
"*.config.js",
|
||||
"check-env-variables.js",
|
||||
"next-sitemap.js",
|
||||
]),
|
||||
])
|
||||
7
apps/suman-hrvatska/next-env.d.ts
vendored
Normal file
7
apps/suman-hrvatska/next-env.d.ts
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
import "./.next/dev/types/routes.d.ts";
|
||||
import "./.next/dev/types/root-params.d.ts";
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||
79
apps/suman-hrvatska/next.config.js
Normal file
79
apps/suman-hrvatska/next.config.js
Normal file
@@ -0,0 +1,79 @@
|
||||
const checkEnvVariables = require("./check-env-variables")
|
||||
|
||||
checkEnvVariables()
|
||||
|
||||
/**
|
||||
* Medusa Cloud-related environment variables
|
||||
*/
|
||||
const S3_HOSTNAME = process.env.MEDUSA_CLOUD_S3_HOSTNAME
|
||||
const S3_PATHNAME = process.env.MEDUSA_CLOUD_S3_PATHNAME
|
||||
|
||||
/**
|
||||
* @type {import('next').NextConfig}
|
||||
*/
|
||||
const nextConfig = {
|
||||
reactStrictMode: true,
|
||||
async headers() {
|
||||
return [
|
||||
{
|
||||
source: "/:path*",
|
||||
headers: [{ key: "Link", value: '</.well-known/ucp>; rel="ucp"' }],
|
||||
},
|
||||
{
|
||||
source: "/:countryCode/products/:handle",
|
||||
headers: [{ key: "Vary", value: "Accept" }],
|
||||
},
|
||||
]
|
||||
},
|
||||
async rewrites() {
|
||||
return {
|
||||
beforeFiles: [
|
||||
{
|
||||
source: "/:countryCode/products/:handle([^/.]+).md",
|
||||
destination: "/:countryCode/products/:handle/markdown",
|
||||
},
|
||||
{
|
||||
source: "/:countryCode/products/:handle([^/.]+)",
|
||||
has: [{ type: "header", key: "accept", value: ".*text/markdown.*" }],
|
||||
destination: "/:countryCode/products/:handle/markdown",
|
||||
},
|
||||
],
|
||||
}
|
||||
},
|
||||
logging: {
|
||||
fetches: {
|
||||
fullUrl: true,
|
||||
},
|
||||
},
|
||||
typescript: {
|
||||
ignoreBuildErrors: true,
|
||||
},
|
||||
images: {
|
||||
unoptimized: true,
|
||||
remotePatterns: [
|
||||
{
|
||||
protocol: "http",
|
||||
hostname: "localhost",
|
||||
},
|
||||
{
|
||||
protocol: "https",
|
||||
hostname: "*.s3.*.amazonaws.com",
|
||||
},
|
||||
{
|
||||
protocol: "https",
|
||||
hostname: "*.s3.amazonaws.com",
|
||||
},
|
||||
...(S3_HOSTNAME && S3_PATHNAME
|
||||
? [
|
||||
{
|
||||
protocol: "https",
|
||||
hostname: S3_HOSTNAME,
|
||||
pathname: S3_PATHNAME,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
module.exports = nextConfig
|
||||
61
apps/suman-hrvatska/package.json
Normal file
61
apps/suman-hrvatska/package.json
Normal file
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"name": "@dtc/suman-hrvatska",
|
||||
"version": "1.0.3",
|
||||
"private": true,
|
||||
"author": "Kasper Fabricius Kristensen <kasper@medusajs.com> & Victor Gerbrands <victor@medusajs.com> (https://www.medusajs.com)",
|
||||
"description": "Next.js Starter to be used with Medusa V2",
|
||||
"keywords": [
|
||||
"medusa-storefront"
|
||||
],
|
||||
"scripts": {
|
||||
"dev": "next dev -p 8002",
|
||||
"build": "next build",
|
||||
"start": "next start -p 8002",
|
||||
"lint": "eslint .",
|
||||
"analyze": "ANALYZE=true next build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@adyen/adyen-web": "^6.46.0",
|
||||
"@headlessui/react": "^2.2.0",
|
||||
"@medusajs/icons": "2.22.3",
|
||||
"@medusajs/instantsearch-adapter": "2.22.3",
|
||||
"@medusajs/js-sdk": "2.22.3",
|
||||
"@medusajs/ui-preset": "2.22.3",
|
||||
"@radix-ui/react-accordion": "^1.2.3",
|
||||
"@radix-ui/react-slider": "^1.4.7",
|
||||
"@stripe/react-stripe-js": "^5.3.0",
|
||||
"@stripe/stripe-js": "^8.2.0",
|
||||
"clsx": "^2.1.1",
|
||||
"instantsearch.js": "4.113.0",
|
||||
"lodash": "^4.17.21",
|
||||
"next": "16.3.8",
|
||||
"pg": "^8.11.3",
|
||||
"qs": "^6.12.1",
|
||||
"react": "19.0.5",
|
||||
"react-country-flag": "^3.1.0",
|
||||
"react-dom": "19.0.5",
|
||||
"react-instantsearch": "^7.46.0",
|
||||
"server-only": "^0.0.1",
|
||||
"tailwindcss-radix": "^2.8.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.17.5",
|
||||
"@medusajs/types": "2.22.3",
|
||||
"@types/lodash": "^4.14.195",
|
||||
"@types/node": "17.0.21",
|
||||
"@types/pg": "^8.11.0",
|
||||
"@types/react": "19.0.5",
|
||||
"@types/react-dom": "19.0.5",
|
||||
"@types/react-instantsearch-dom": "^6.12.3",
|
||||
"ansi-colors": "^4.1.3",
|
||||
"autoprefixer": "^10.4.2",
|
||||
"babel-loader": "^8.2.3",
|
||||
"eslint": "^9.13.0",
|
||||
"eslint-config-next": "16.3.8",
|
||||
"postcss": "^8.4.8",
|
||||
"prettier": "^2.8.8",
|
||||
"tailwindcss": "^3.0.23",
|
||||
"typescript": "^5.3.2"
|
||||
},
|
||||
"packageManager": "npm@11.19.0"
|
||||
}
|
||||
6
apps/suman-hrvatska/postcss.config.js
Normal file
6
apps/suman-hrvatska/postcss.config.js
Normal file
@@ -0,0 +1,6 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
BIN
apps/suman-hrvatska/public/favicon.ico
Normal file
BIN
apps/suman-hrvatska/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
BIN
apps/suman-hrvatska/public/logo.png
Normal file
BIN
apps/suman-hrvatska/public/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 60 KiB |
63
apps/suman-hrvatska/src/app/.well-known/ucp/route.ts
Normal file
63
apps/suman-hrvatska/src/app/.well-known/ucp/route.ts
Normal 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": "*",
|
||||
},
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export default function Default() {
|
||||
return null
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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} />
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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} />
|
||||
}
|
||||
@@ -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" />
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { default, metadata } from "./page"
|
||||
@@ -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 />
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import SkeletonCartPage from "@modules/skeletons/templates/skeleton-cart-page"
|
||||
|
||||
export default function Loading() {
|
||||
return <SkeletonCartPage />
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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} />
|
||||
}
|
||||
@@ -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 }
|
||||
)
|
||||
}
|
||||
@@ -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}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -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}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
45
apps/suman-hrvatska/src/app/[countryCode]/(main)/layout.tsx
Normal file
45
apps/suman-hrvatska/src/app/[countryCode]/(main)/layout.tsx
Normal 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 />
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import SkeletonOrderConfirmed from "@modules/skeletons/templates/skeleton-order-confirmed"
|
||||
|
||||
export default function Loading() {
|
||||
return <SkeletonOrderConfirmed />
|
||||
}
|
||||
@@ -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} />
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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'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>
|
||||
)
|
||||
}
|
||||
99
apps/suman-hrvatska/src/app/[countryCode]/(main)/page.tsx
Normal file
99
apps/suman-hrvatska/src/app/[countryCode]/(main)/page.tsx
Normal 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>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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 }
|
||||
)
|
||||
}
|
||||
@@ -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}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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} />
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
103
apps/suman-hrvatska/src/app/api/payment-return/route.ts
Normal file
103
apps/suman-hrvatska/src/app/api/payment-return/route.ts
Normal 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`)
|
||||
}
|
||||
72
apps/suman-hrvatska/src/app/buy/[items]/route.ts
Normal file
72
apps/suman-hrvatska/src/app/buy/[items]/route.ts
Normal 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 }
|
||||
)
|
||||
}
|
||||
27
apps/suman-hrvatska/src/app/layout.tsx
Normal file
27
apps/suman-hrvatska/src/app/layout.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
72
apps/suman-hrvatska/src/app/llms.txt/route.ts
Normal file
72
apps/suman-hrvatska/src/app/llms.txt/route.ts
Normal 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",
|
||||
},
|
||||
})
|
||||
}
|
||||
27
apps/suman-hrvatska/src/app/not-found.tsx
Normal file
27
apps/suman-hrvatska/src/app/not-found.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
BIN
apps/suman-hrvatska/src/app/opengraph-image.jpg
Normal file
BIN
apps/suman-hrvatska/src/app/opengraph-image.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 229 KiB |
21
apps/suman-hrvatska/src/app/robots.ts
Normal file
21
apps/suman-hrvatska/src/app/robots.ts
Normal 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`,
|
||||
}
|
||||
}
|
||||
72
apps/suman-hrvatska/src/app/sitemap.ts
Normal file
72
apps/suman-hrvatska/src/app/sitemap.ts
Normal 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),
|
||||
]
|
||||
})
|
||||
}
|
||||
BIN
apps/suman-hrvatska/src/app/twitter-image.jpg
Normal file
BIN
apps/suman-hrvatska/src/app/twitter-image.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 229 KiB |
6
apps/suman-hrvatska/src/app/ucp/mcp/route.ts
Normal file
6
apps/suman-hrvatska/src/app/ucp/mcp/route.ts
Normal 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" } })
|
||||
15
apps/suman-hrvatska/src/app/ucp/v1/cart/[cartId]/route.ts
Normal file
15
apps/suman-hrvatska/src/app/ucp/v1/cart/[cartId]/route.ts
Normal 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))
|
||||
11
apps/suman-hrvatska/src/app/ucp/v1/cart/route.ts
Normal file
11
apps/suman-hrvatska/src/app/ucp/v1/cart/route.ts
Normal 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")
|
||||
)
|
||||
)
|
||||
@@ -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)) ?? {}))
|
||||
@@ -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)) ?? {}))
|
||||
@@ -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))
|
||||
@@ -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))
|
||||
@@ -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)) ?? {})
|
||||
)
|
||||
@@ -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")
|
||||
)
|
||||
)
|
||||
26
apps/suman-hrvatska/src/app/ucp/v1/route.ts
Normal file
26
apps/suman-hrvatska/src/app/ucp/v1/route.ts
Normal 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)
|
||||
71
apps/suman-hrvatska/src/components/ui/section-header.tsx
Normal file
71
apps/suman-hrvatska/src/components/ui/section-header.tsx
Normal 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
|
||||
|
||||
39
apps/suman-hrvatska/src/lib/config.ts
Normal file
39
apps/suman-hrvatska/src/lib/config.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { getLocaleHeader } from "@lib/util/get-locale-header"
|
||||
import Medusa, { FetchArgs, FetchInput } from "@medusajs/js-sdk"
|
||||
|
||||
// Defaults to standard port for Medusa server
|
||||
let MEDUSA_BACKEND_URL = "http://localhost:9000"
|
||||
|
||||
if (process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL) {
|
||||
MEDUSA_BACKEND_URL = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL
|
||||
}
|
||||
|
||||
export const sdk = new Medusa({
|
||||
baseUrl: MEDUSA_BACKEND_URL,
|
||||
debug: process.env.NODE_ENV === "development",
|
||||
publishableKey: process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,
|
||||
})
|
||||
|
||||
const originalFetch = sdk.client.fetch.bind(sdk.client)
|
||||
|
||||
sdk.client.fetch = async <T>(
|
||||
input: FetchInput,
|
||||
init?: FetchArgs
|
||||
): Promise<T> => {
|
||||
const headers = init?.headers ?? {}
|
||||
let localeHeader: Record<string, string | null> | undefined
|
||||
try {
|
||||
localeHeader = await getLocaleHeader()
|
||||
headers["x-medusa-locale"] ??= localeHeader["x-medusa-locale"]
|
||||
} catch {}
|
||||
|
||||
const newHeaders = {
|
||||
...localeHeader,
|
||||
...headers,
|
||||
}
|
||||
init = {
|
||||
...init,
|
||||
headers: newHeaders,
|
||||
}
|
||||
return originalFetch(input, init)
|
||||
}
|
||||
127
apps/suman-hrvatska/src/lib/constants.tsx
Normal file
127
apps/suman-hrvatska/src/lib/constants.tsx
Normal 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",
|
||||
]
|
||||
34
apps/suman-hrvatska/src/lib/context/modal-context.tsx
Normal file
34
apps/suman-hrvatska/src/lib/context/modal-context.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
"use client"
|
||||
|
||||
import React, { createContext, useContext } from "react"
|
||||
|
||||
interface ModalContext {
|
||||
close: () => void
|
||||
}
|
||||
|
||||
const ModalContext = createContext<ModalContext | null>(null)
|
||||
|
||||
interface ModalProviderProps {
|
||||
children?: React.ReactNode
|
||||
close: () => void
|
||||
}
|
||||
|
||||
export const ModalProvider = ({ children, close }: ModalProviderProps) => {
|
||||
return (
|
||||
<ModalContext.Provider
|
||||
value={{
|
||||
close,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</ModalContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export const useModal = () => {
|
||||
const context = useContext(ModalContext)
|
||||
if (context === null) {
|
||||
throw new Error("useModal must be used within a ModalProvider")
|
||||
}
|
||||
return context
|
||||
}
|
||||
82
apps/suman-hrvatska/src/lib/data/adyen.ts
Normal file
82
apps/suman-hrvatska/src/lib/data/adyen.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
"use server"
|
||||
|
||||
import { sdk } from "@lib/config"
|
||||
import { isAdyen } from "@lib/constants"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { unstable_rethrow } from "next/navigation"
|
||||
import { placeOrder } from "./cart"
|
||||
import { getAuthHeaders, getCartId } from "./cookies"
|
||||
|
||||
export type AdyenPaymentResult =
|
||||
| { resultCode: string; action: Record<string, unknown> }
|
||||
| { error: string }
|
||||
|
||||
const DECLINED_ERROR =
|
||||
"Your payment was declined. Please try again or use a different payment method."
|
||||
const GENERIC_ERROR =
|
||||
"We couldn't process your payment. Please try again or use a different payment method."
|
||||
|
||||
const getAdyenSession = async (cartId: string) => {
|
||||
// The default fields include the payment collection and its sessions. Medusa Cloud's firewall
|
||||
// rejects a `fields` query that names `payment_collection` more than once, so none is passed.
|
||||
const { cart } = await sdk.client.fetch<HttpTypes.StoreCartResponse>(
|
||||
`/store/carts/${cartId}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: { ...(await getAuthHeaders()) },
|
||||
cache: "no-store",
|
||||
}
|
||||
)
|
||||
|
||||
const session = cart.payment_collection?.payment_sessions?.find((s) =>
|
||||
isAdyen(s.provider_id)
|
||||
)
|
||||
|
||||
return session && { collectionId: cart.payment_collection!.id, session }
|
||||
}
|
||||
|
||||
/**
|
||||
* Passes the data that Adyen's Drop-in collected to the cart's Adyen payment session,
|
||||
* then completes the cart, which redirects to the order confirmation once the payment
|
||||
* is authorized. Otherwise, returns the action Drop-in has to handle, such as a 3D
|
||||
* Secure challenge, or an error to show.
|
||||
*/
|
||||
export async function submitAdyenPayment(
|
||||
clientData: Record<string, unknown>,
|
||||
cartId?: string
|
||||
): Promise<AdyenPaymentResult> {
|
||||
const id = cartId || (await getCartId())
|
||||
const current = id ? await getAdyenSession(id) : undefined
|
||||
|
||||
if (!id || !current) {
|
||||
return { error: GENERIC_ERROR }
|
||||
}
|
||||
|
||||
try {
|
||||
await sdk.store.payment.updatePaymentSession(
|
||||
current.collectionId,
|
||||
current.session.id,
|
||||
{ client_data: clientData },
|
||||
{},
|
||||
{ ...(await getAuthHeaders()) }
|
||||
)
|
||||
|
||||
await placeOrder(id)
|
||||
} catch (error) {
|
||||
unstable_rethrow(error)
|
||||
}
|
||||
|
||||
const updated = await getAdyenSession(id)
|
||||
const data = updated?.session.data
|
||||
|
||||
if (updated?.session.status === "requires_more" && data?.action) {
|
||||
return {
|
||||
resultCode: data.result_code as string,
|
||||
action: data.action as Record<string, unknown>,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
error: updated?.session.status === "error" ? DECLINED_ERROR : GENERIC_ERROR,
|
||||
}
|
||||
}
|
||||
473
apps/suman-hrvatska/src/lib/data/cart.ts
Normal file
473
apps/suman-hrvatska/src/lib/data/cart.ts
Normal 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",
|
||||
})
|
||||
}
|
||||
49
apps/suman-hrvatska/src/lib/data/categories.ts
Normal file
49
apps/suman-hrvatska/src/lib/data/categories.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { sdk } from "@lib/config"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { getCacheOptions } from "./cookies"
|
||||
|
||||
export const listCategories = async (query?: Record<string, unknown>) => {
|
||||
const next = {
|
||||
...(await getCacheOptions("categories")),
|
||||
}
|
||||
|
||||
const limit = query?.limit || 100
|
||||
|
||||
return sdk.client
|
||||
.fetch<{ product_categories: HttpTypes.StoreProductCategory[] }>(
|
||||
"/store/product-categories",
|
||||
{
|
||||
query: {
|
||||
fields:
|
||||
"*category_children, *products, *parent_category, *parent_category.parent_category",
|
||||
limit,
|
||||
...query,
|
||||
},
|
||||
next,
|
||||
cache: "force-cache",
|
||||
}
|
||||
)
|
||||
.then(({ product_categories }) => product_categories)
|
||||
}
|
||||
|
||||
export const getCategoryByHandle = async (categoryHandle: string[]) => {
|
||||
const handle = `${categoryHandle.join("/")}`
|
||||
|
||||
const next = {
|
||||
...(await getCacheOptions("categories")),
|
||||
}
|
||||
|
||||
return sdk.client
|
||||
.fetch<HttpTypes.StoreProductCategoryListResponse>(
|
||||
`/store/product-categories`,
|
||||
{
|
||||
query: {
|
||||
fields: "*category_children, *products",
|
||||
handle,
|
||||
},
|
||||
next,
|
||||
cache: "force-cache",
|
||||
}
|
||||
)
|
||||
.then(({ product_categories }) => product_categories[0])
|
||||
}
|
||||
59
apps/suman-hrvatska/src/lib/data/collections.ts
Normal file
59
apps/suman-hrvatska/src/lib/data/collections.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
"use server"
|
||||
|
||||
import { sdk } from "@lib/config"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { getCacheOptions } from "./cookies"
|
||||
|
||||
export const retrieveCollection = async (id: string) => {
|
||||
const next = {
|
||||
...(await getCacheOptions("collections")),
|
||||
}
|
||||
|
||||
return await sdk.client
|
||||
.fetch<{ collection: HttpTypes.StoreCollection }>(
|
||||
`/store/collections/${id}`,
|
||||
{
|
||||
next,
|
||||
cache: "force-cache",
|
||||
}
|
||||
)
|
||||
.then(({ collection }) => collection)
|
||||
}
|
||||
|
||||
export const listCollections = async (
|
||||
queryParams: Record<string, string> = {}
|
||||
): Promise<{ collections: HttpTypes.StoreCollection[]; count: number }> => {
|
||||
const next = {
|
||||
...(await getCacheOptions("collections")),
|
||||
}
|
||||
|
||||
queryParams.limit = queryParams.limit || "100"
|
||||
queryParams.offset = queryParams.offset || "0"
|
||||
|
||||
return await sdk.client
|
||||
.fetch<{ collections: HttpTypes.StoreCollection[]; count: number }>(
|
||||
"/store/collections",
|
||||
{
|
||||
query: queryParams,
|
||||
next,
|
||||
cache: "force-cache",
|
||||
}
|
||||
)
|
||||
.then(({ collections }) => ({ collections, count: collections.length }))
|
||||
}
|
||||
|
||||
export const getCollectionByHandle = async (
|
||||
handle: string
|
||||
): Promise<HttpTypes.StoreCollection | null> => {
|
||||
const next = {
|
||||
...(await getCacheOptions("collections")),
|
||||
}
|
||||
|
||||
return await sdk.client
|
||||
.fetch<HttpTypes.StoreCollectionListResponse>(`/store/collections`, {
|
||||
query: { handle, fields: "*products" },
|
||||
next,
|
||||
cache: "force-cache",
|
||||
})
|
||||
.then(({ collections }) => collections[0] || null)
|
||||
}
|
||||
140
apps/suman-hrvatska/src/lib/data/cookies.ts
Normal file
140
apps/suman-hrvatska/src/lib/data/cookies.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
import "server-only"
|
||||
import { cookies as nextCookies } from "next/headers"
|
||||
|
||||
export const getAuthHeaders = async (): Promise<
|
||||
{ authorization: string } | Record<string, never>
|
||||
> => {
|
||||
try {
|
||||
const cookies = await nextCookies()
|
||||
const token = cookies.get("_medusa_jwt")?.value
|
||||
|
||||
if (!token) {
|
||||
return {}
|
||||
}
|
||||
|
||||
return { authorization: `Bearer ${token}` }
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
export const getCacheTag = async (tag: string): Promise<string> => {
|
||||
try {
|
||||
const cookies = await nextCookies()
|
||||
const cacheId = cookies.get("_medusa_cache_id")?.value
|
||||
|
||||
if (!cacheId) {
|
||||
return ""
|
||||
}
|
||||
|
||||
return `${tag}-${cacheId}`
|
||||
} catch {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
export const getCacheOptions = async (
|
||||
tag: string
|
||||
): Promise<{ tags: string[] } | Record<string, never>> => {
|
||||
if (typeof window !== "undefined") {
|
||||
return {}
|
||||
}
|
||||
|
||||
const cacheTag = await getCacheTag(tag)
|
||||
|
||||
if (!cacheTag) {
|
||||
return {}
|
||||
}
|
||||
|
||||
return { tags: [`${cacheTag}`] }
|
||||
}
|
||||
|
||||
// `sameSite: "lax"` rather than `"strict"`: the customer returns from a
|
||||
// redirect-based payment method (iDEAL, Bancontact, ...) via a cross-site
|
||||
// top-level navigation. A "strict" cookie is withheld on that navigation, so
|
||||
// the storefront would see a logged-out, cartless visitor and render a 404 for
|
||||
// the checkout page instead of resuming the order. "lax" is sent on top-level
|
||||
// GET navigations while still blocking cross-site subrequests.
|
||||
export const setAuthToken = async (token: string) => {
|
||||
const cookies = await nextCookies()
|
||||
cookies.set("_medusa_jwt", token, {
|
||||
maxAge: 60 * 60 * 24 * 7,
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
})
|
||||
}
|
||||
|
||||
export const removeAuthToken = async () => {
|
||||
const cookies = await nextCookies()
|
||||
cookies.set("_medusa_jwt", "", {
|
||||
maxAge: -1,
|
||||
})
|
||||
}
|
||||
|
||||
export type PendingCustomer = {
|
||||
email: string
|
||||
first_name?: string
|
||||
last_name?: string
|
||||
phone?: string
|
||||
}
|
||||
|
||||
// During the email verification flow the customer record isn't created until
|
||||
// the customer verifies their email and logs in. We temporarily persist the
|
||||
// extra signup fields in a cookie so they survive the customer leaving to open
|
||||
// their inbox, and read them back when creating the customer at login.
|
||||
export const setPendingCustomer = async (customer: PendingCustomer) => {
|
||||
const cookies = await nextCookies()
|
||||
cookies.set("_medusa_pending_customer", JSON.stringify(customer), {
|
||||
maxAge: 60 * 60 * 24,
|
||||
httpOnly: true,
|
||||
sameSite: "strict",
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
})
|
||||
}
|
||||
|
||||
export const getPendingCustomer = async (): Promise<PendingCustomer | null> => {
|
||||
const cookies = await nextCookies()
|
||||
const value = cookies.get("_medusa_pending_customer")?.value
|
||||
|
||||
if (!value) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(value) as PendingCustomer
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const removePendingCustomer = async () => {
|
||||
const cookies = await nextCookies()
|
||||
cookies.set("_medusa_pending_customer", "", {
|
||||
maxAge: -1,
|
||||
})
|
||||
}
|
||||
|
||||
export const getCartId = async () => {
|
||||
const cookies = await nextCookies()
|
||||
return cookies.get("_medusa_cart_id")?.value
|
||||
}
|
||||
|
||||
// See the note on `setAuthToken`: `sameSite: "lax"` so the cart cookie survives
|
||||
// the cross-site return navigation from a redirect-based payment method.
|
||||
export const setCartId = async (cartId: string) => {
|
||||
const cookies = await nextCookies()
|
||||
cookies.set("_medusa_cart_id", cartId, {
|
||||
maxAge: 60 * 60 * 24 * 7,
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
})
|
||||
}
|
||||
|
||||
export const removeCartId = async () => {
|
||||
const cookies = await nextCookies()
|
||||
cookies.set("_medusa_cart_id", "", {
|
||||
maxAge: -1,
|
||||
})
|
||||
}
|
||||
381
apps/suman-hrvatska/src/lib/data/customer.ts
Normal file
381
apps/suman-hrvatska/src/lib/data/customer.ts
Normal file
@@ -0,0 +1,381 @@
|
||||
"use server"
|
||||
|
||||
import { sdk } from "@lib/config"
|
||||
import medusaError from "@lib/util/medusa-error"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { FetchError } from "@medusajs/js-sdk"
|
||||
import { revalidateTag } from "next/cache"
|
||||
import { redirect } from "next/navigation"
|
||||
import {
|
||||
getAuthHeaders,
|
||||
getCacheOptions,
|
||||
getCacheTag,
|
||||
getCartId,
|
||||
getPendingCustomer,
|
||||
removeAuthToken,
|
||||
removeCartId,
|
||||
removePendingCustomer,
|
||||
setAuthToken,
|
||||
setPendingCustomer,
|
||||
} from "./cookies"
|
||||
|
||||
export type CustomerAuthState =
|
||||
| { state: "error"; error: string }
|
||||
| { state: "verification_required"; email: string }
|
||||
| { state: "success" }
|
||||
| null
|
||||
|
||||
// Requests a verification email for the given customer. The request must be
|
||||
// authenticated with a token tied to the auth identity (the token returned by
|
||||
// register or by a login that requires verification).
|
||||
async function requestVerificationEmail(email: string, token: string) {
|
||||
await sdk.auth.verification.request(
|
||||
{
|
||||
entity_id: email,
|
||||
entity_type: "email",
|
||||
},
|
||||
{
|
||||
authorization: `Bearer ${token}`,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export const retrieveCustomer =
|
||||
async (): Promise<HttpTypes.StoreCustomer | null> => {
|
||||
const authHeaders = await getAuthHeaders()
|
||||
|
||||
if (!("authorization" in authHeaders)) return null
|
||||
|
||||
const headers = {
|
||||
...authHeaders,
|
||||
}
|
||||
|
||||
const next = {
|
||||
...(await getCacheOptions("customers")),
|
||||
}
|
||||
|
||||
return await sdk.client
|
||||
.fetch<{ customer: HttpTypes.StoreCustomer }>(`/store/customers/me`, {
|
||||
method: "GET",
|
||||
query: {
|
||||
fields: "*orders",
|
||||
},
|
||||
headers,
|
||||
next,
|
||||
cache: "force-cache",
|
||||
})
|
||||
.then(({ customer }) => customer)
|
||||
.catch(() => null)
|
||||
}
|
||||
|
||||
export const updateCustomer = async (body: HttpTypes.StoreUpdateCustomer) => {
|
||||
const headers = {
|
||||
...(await getAuthHeaders()),
|
||||
}
|
||||
|
||||
const updateRes = await sdk.store.customer
|
||||
.update(body, {}, headers)
|
||||
.then(({ customer }) => customer)
|
||||
.catch(medusaError)
|
||||
|
||||
const cacheTag = await getCacheTag("customers")
|
||||
revalidateTag(cacheTag, { expire: 0 })
|
||||
|
||||
return updateRes
|
||||
}
|
||||
|
||||
export async function signup(
|
||||
_currentState: unknown,
|
||||
formData: FormData
|
||||
): Promise<CustomerAuthState> {
|
||||
const password = formData.get("password") as string
|
||||
const customerForm = {
|
||||
email: formData.get("email") as string,
|
||||
first_name: formData.get("first_name") as string,
|
||||
last_name: formData.get("last_name") as string,
|
||||
phone: formData.get("phone") as string,
|
||||
}
|
||||
|
||||
try {
|
||||
await sdk.auth.register("customer", "emailpass", {
|
||||
email: customerForm.email,
|
||||
password,
|
||||
})
|
||||
} catch (error) {
|
||||
const fetchError = error as FetchError
|
||||
// An existing identity (for example, an admin user with the same email) is
|
||||
// expected and handled: the customer can still log in to link a customer
|
||||
// record. Any other error is surfaced.
|
||||
if (
|
||||
fetchError.statusText !== "Unauthorized" ||
|
||||
fetchError.message !== "Identity with email already exists"
|
||||
) {
|
||||
return { state: "error", error: String(error) }
|
||||
}
|
||||
}
|
||||
|
||||
// Persist the extra signup fields. The customer record is created during
|
||||
// login, which is deferred until after email verification when the backend
|
||||
// requires it.
|
||||
await setPendingCustomer(customerForm)
|
||||
|
||||
// Continue by logging in. The login response tells us whether the backend
|
||||
// requires email verification — we don't need a storefront-side flag.
|
||||
return completeLogin(customerForm.email, password)
|
||||
}
|
||||
|
||||
export async function login(
|
||||
_currentState: unknown,
|
||||
formData: FormData
|
||||
): Promise<CustomerAuthState> {
|
||||
const email = formData.get("email") as string
|
||||
const password = formData.get("password") as string
|
||||
|
||||
return completeLogin(email, password)
|
||||
}
|
||||
|
||||
// Logs the customer in and reconciles the customer record. The behavior is
|
||||
// driven entirely by the backend's login response, so it works whether or not
|
||||
// email verification is enabled.
|
||||
async function completeLogin(
|
||||
email: string,
|
||||
password: string
|
||||
): Promise<CustomerAuthState> {
|
||||
let result: Awaited<ReturnType<typeof sdk.auth.login>>
|
||||
|
||||
try {
|
||||
result = await sdk.auth.login("customer", "emailpass", { email, password })
|
||||
} catch (error) {
|
||||
return { state: "error", error: String(error) }
|
||||
}
|
||||
|
||||
// A `location` is returned by third-party auth providers, which this flow
|
||||
// doesn't support.
|
||||
if (typeof result === "object" && "location" in result) {
|
||||
return {
|
||||
state: "error",
|
||||
error: "This login method isn't supported by the storefront.",
|
||||
}
|
||||
}
|
||||
|
||||
// The backend requires email verification and the customer hasn't verified
|
||||
// yet. Send the verification email and ask them to check their inbox.
|
||||
if (
|
||||
typeof result === "object" &&
|
||||
"verification_required" in result &&
|
||||
result.verification_required
|
||||
) {
|
||||
try {
|
||||
await requestVerificationEmail(email, result.token)
|
||||
} catch {
|
||||
// Ignore: the customer can resend from the verification page.
|
||||
}
|
||||
return { state: "verification_required", email }
|
||||
}
|
||||
|
||||
if (typeof result !== "string") {
|
||||
return {
|
||||
state: "error",
|
||||
error: "Authentication requires additional steps that aren't supported.",
|
||||
}
|
||||
}
|
||||
|
||||
let token = result
|
||||
|
||||
// The token may not be tied to a customer record yet — right after
|
||||
// registration, or after verifying a brand-new account. Ask the backend:
|
||||
// `/store/customers/me` rejects tokens without a registered actor, so a
|
||||
// failed retrieve means we still need to create the customer, then log in
|
||||
// again to obtain a customer-bound token.
|
||||
const customerExists = await sdk.store.customer
|
||||
.retrieve({}, { authorization: `Bearer ${token}` })
|
||||
.then(() => true)
|
||||
.catch(() => false)
|
||||
|
||||
if (!customerExists) {
|
||||
const pending = await getPendingCustomer()
|
||||
|
||||
try {
|
||||
await sdk.store.customer.create(
|
||||
{
|
||||
email,
|
||||
first_name: pending?.first_name,
|
||||
last_name: pending?.last_name,
|
||||
phone: pending?.phone,
|
||||
},
|
||||
{},
|
||||
{ authorization: `Bearer ${token}` }
|
||||
)
|
||||
|
||||
token = (await sdk.auth.login("customer", "emailpass", {
|
||||
email,
|
||||
password,
|
||||
})) as string
|
||||
} catch (error) {
|
||||
return { state: "error", error: String(error) }
|
||||
}
|
||||
|
||||
await removePendingCustomer()
|
||||
}
|
||||
|
||||
await setAuthToken(token)
|
||||
|
||||
const customerCacheTag = await getCacheTag("customers")
|
||||
revalidateTag(customerCacheTag, { expire: 0 })
|
||||
|
||||
try {
|
||||
await transferCart()
|
||||
} catch (error) {
|
||||
return { state: "error", error: String(error) }
|
||||
}
|
||||
|
||||
return { state: "success" }
|
||||
}
|
||||
|
||||
// Confirms a customer's email using the token from the verification link.
|
||||
//
|
||||
// The confirm route doesn't require authentication, so this works even when the
|
||||
// customer opens the link on a different device than the one they signed up on.
|
||||
export async function confirmEmailVerification(
|
||||
token: string
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
await sdk.auth.verification.confirm({ code: token })
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
return { success: false, error: String(error) }
|
||||
}
|
||||
}
|
||||
|
||||
export async function signout(countryCode: string) {
|
||||
await sdk.auth.logout()
|
||||
|
||||
await removeAuthToken()
|
||||
|
||||
const customerCacheTag = await getCacheTag("customers")
|
||||
revalidateTag(customerCacheTag, { expire: 0 })
|
||||
|
||||
await removeCartId()
|
||||
|
||||
const cartCacheTag = await getCacheTag("carts")
|
||||
revalidateTag(cartCacheTag, { expire: 0 })
|
||||
|
||||
redirect(`/${countryCode}/account`)
|
||||
}
|
||||
|
||||
export async function transferCart() {
|
||||
const cartId = await getCartId()
|
||||
|
||||
if (!cartId) {
|
||||
return
|
||||
}
|
||||
|
||||
const headers = await getAuthHeaders()
|
||||
|
||||
await sdk.store.cart.transferCart(cartId, {}, headers)
|
||||
|
||||
const cartCacheTag = await getCacheTag("carts")
|
||||
revalidateTag(cartCacheTag, { expire: 0 })
|
||||
}
|
||||
|
||||
export const addCustomerAddress = async (
|
||||
currentState: Record<string, unknown>,
|
||||
formData: FormData
|
||||
): Promise<{ success: boolean; error: string | null }> => {
|
||||
const isDefaultBilling = (currentState.isDefaultBilling as boolean) || false
|
||||
const isDefaultShipping = (currentState.isDefaultShipping as boolean) || false
|
||||
|
||||
const address = {
|
||||
first_name: formData.get("first_name") as string,
|
||||
last_name: formData.get("last_name") as string,
|
||||
company: formData.get("company") as string,
|
||||
address_1: formData.get("address_1") as string,
|
||||
address_2: formData.get("address_2") as string,
|
||||
city: formData.get("city") as string,
|
||||
postal_code: formData.get("postal_code") as string,
|
||||
province: formData.get("province") as string,
|
||||
country_code: formData.get("country_code") as string,
|
||||
phone: formData.get("phone") as string,
|
||||
is_default_billing: isDefaultBilling,
|
||||
is_default_shipping: isDefaultShipping,
|
||||
}
|
||||
|
||||
const headers = {
|
||||
...(await getAuthHeaders()),
|
||||
}
|
||||
|
||||
return sdk.store.customer
|
||||
.createAddress(address, {}, headers)
|
||||
.then(async () => {
|
||||
const customerCacheTag = await getCacheTag("customers")
|
||||
revalidateTag(customerCacheTag, { expire: 0 })
|
||||
return { success: true, error: null }
|
||||
})
|
||||
.catch((err) => {
|
||||
return { success: false, error: err.toString() }
|
||||
})
|
||||
}
|
||||
|
||||
export const deleteCustomerAddress = async (
|
||||
addressId: string
|
||||
): Promise<void> => {
|
||||
const headers = {
|
||||
...(await getAuthHeaders()),
|
||||
}
|
||||
|
||||
await sdk.store.customer
|
||||
.deleteAddress(addressId, headers)
|
||||
.then(async () => {
|
||||
const customerCacheTag = await getCacheTag("customers")
|
||||
revalidateTag(customerCacheTag, { expire: 0 })
|
||||
return { success: true, error: null }
|
||||
})
|
||||
.catch((err) => {
|
||||
return { success: false, error: err.toString() }
|
||||
})
|
||||
}
|
||||
|
||||
export const updateCustomerAddress = async (
|
||||
currentState: Record<string, unknown>,
|
||||
formData: FormData
|
||||
): Promise<{ success: boolean; error: string | null }> => {
|
||||
const addressId =
|
||||
(currentState.addressId as string) || (formData.get("addressId") as string)
|
||||
|
||||
if (!addressId) {
|
||||
return { success: false, error: "Address ID is required" }
|
||||
}
|
||||
|
||||
const address = {
|
||||
first_name: formData.get("first_name") as string,
|
||||
last_name: formData.get("last_name") as string,
|
||||
company: formData.get("company") as string,
|
||||
address_1: formData.get("address_1") as string,
|
||||
address_2: formData.get("address_2") as string,
|
||||
city: formData.get("city") as string,
|
||||
postal_code: formData.get("postal_code") as string,
|
||||
province: formData.get("province") as string,
|
||||
country_code: formData.get("country_code") as string,
|
||||
} as HttpTypes.StoreUpdateCustomerAddress
|
||||
|
||||
const phone = formData.get("phone") as string
|
||||
|
||||
if (phone) {
|
||||
address.phone = phone
|
||||
}
|
||||
|
||||
const headers = {
|
||||
...(await getAuthHeaders()),
|
||||
}
|
||||
|
||||
return sdk.store.customer
|
||||
.updateAddress(addressId, address, {}, headers)
|
||||
.then(async () => {
|
||||
const customerCacheTag = await getCacheTag("customers")
|
||||
revalidateTag(customerCacheTag, { expire: 0 })
|
||||
return { success: true, error: null }
|
||||
})
|
||||
.catch((err) => {
|
||||
return { success: false, error: err.toString() }
|
||||
})
|
||||
}
|
||||
68
apps/suman-hrvatska/src/lib/data/fulfillment.ts
Normal file
68
apps/suman-hrvatska/src/lib/data/fulfillment.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
"use server"
|
||||
|
||||
import { sdk } from "@lib/config"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { getAuthHeaders, getCacheOptions } from "./cookies"
|
||||
|
||||
export const listCartShippingMethods = async (cartId: string) => {
|
||||
const headers = {
|
||||
...(await getAuthHeaders()),
|
||||
}
|
||||
|
||||
const next = {
|
||||
...(await getCacheOptions("fulfillment")),
|
||||
}
|
||||
|
||||
return sdk.client
|
||||
.fetch<HttpTypes.StoreShippingOptionListResponse>(
|
||||
`/store/shipping-options`,
|
||||
{
|
||||
method: "GET",
|
||||
query: {
|
||||
cart_id: cartId,
|
||||
},
|
||||
headers,
|
||||
next,
|
||||
cache: "force-cache",
|
||||
}
|
||||
)
|
||||
.then(({ shipping_options }) => shipping_options)
|
||||
.catch(() => {
|
||||
return null
|
||||
})
|
||||
}
|
||||
|
||||
export const calculatePriceForShippingOption = async (
|
||||
optionId: string,
|
||||
cartId: string,
|
||||
data?: Record<string, unknown>
|
||||
) => {
|
||||
const headers = {
|
||||
...(await getAuthHeaders()),
|
||||
}
|
||||
|
||||
const next = {
|
||||
...(await getCacheOptions("fulfillment")),
|
||||
}
|
||||
|
||||
const body = { cart_id: cartId, data }
|
||||
|
||||
if (data) {
|
||||
body.data = data
|
||||
}
|
||||
|
||||
return sdk.client
|
||||
.fetch<{ shipping_option: HttpTypes.StoreCartShippingOption }>(
|
||||
`/store/shipping-options/${optionId}/calculate`,
|
||||
{
|
||||
method: "POST",
|
||||
body,
|
||||
headers,
|
||||
next,
|
||||
}
|
||||
)
|
||||
.then(({ shipping_option }) => shipping_option)
|
||||
.catch((_e) => {
|
||||
return null
|
||||
})
|
||||
}
|
||||
74
apps/suman-hrvatska/src/lib/data/locale-actions.ts
Normal file
74
apps/suman-hrvatska/src/lib/data/locale-actions.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
"use server"
|
||||
|
||||
import { sdk } from "@lib/config"
|
||||
import { revalidateTag } from "next/cache"
|
||||
import { cookies as nextCookies } from "next/headers"
|
||||
import { getAuthHeaders, getCacheTag, getCartId } from "./cookies"
|
||||
|
||||
const LOCALE_COOKIE_NAME = "_medusa_locale"
|
||||
|
||||
/**
|
||||
* Gets the current locale from cookies
|
||||
*/
|
||||
export const getLocale = async (): Promise<string | null> => {
|
||||
try {
|
||||
const cookies = await nextCookies()
|
||||
return cookies.get(LOCALE_COOKIE_NAME)?.value ?? null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the locale cookie
|
||||
*/
|
||||
export const setLocaleCookie = async (locale: string) => {
|
||||
const cookies = await nextCookies()
|
||||
cookies.set(LOCALE_COOKIE_NAME, locale, {
|
||||
maxAge: 60 * 60 * 24 * 365, // 1 year
|
||||
httpOnly: false, // Allow client-side access
|
||||
sameSite: "strict",
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the locale preference via SDK and stores in cookie.
|
||||
* Also updates the cart with the new locale if one exists.
|
||||
*/
|
||||
export const updateLocale = async (localeCode: string): Promise<string> => {
|
||||
await setLocaleCookie(localeCode)
|
||||
|
||||
// Update cart with the new locale if a cart exists
|
||||
const cartId = await getCartId()
|
||||
if (cartId) {
|
||||
const headers = {
|
||||
...(await getAuthHeaders()),
|
||||
}
|
||||
|
||||
await sdk.store.cart.update(cartId, { locale: localeCode }, {}, headers)
|
||||
|
||||
const cartCacheTag = await getCacheTag("carts")
|
||||
if (cartCacheTag) {
|
||||
revalidateTag(cartCacheTag, { expire: 0 })
|
||||
}
|
||||
}
|
||||
|
||||
// Revalidate relevant caches to refresh content
|
||||
const productsCacheTag = await getCacheTag("products")
|
||||
if (productsCacheTag) {
|
||||
revalidateTag(productsCacheTag, { expire: 0 })
|
||||
}
|
||||
|
||||
const categoriesCacheTag = await getCacheTag("categories")
|
||||
if (categoriesCacheTag) {
|
||||
revalidateTag(categoriesCacheTag, { expire: 0 })
|
||||
}
|
||||
|
||||
const collectionsCacheTag = await getCacheTag("collections")
|
||||
if (collectionsCacheTag) {
|
||||
revalidateTag(collectionsCacheTag, { expire: 0 })
|
||||
}
|
||||
|
||||
return localeCode
|
||||
}
|
||||
28
apps/suman-hrvatska/src/lib/data/locales.ts
Normal file
28
apps/suman-hrvatska/src/lib/data/locales.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
"use server"
|
||||
|
||||
import { sdk } from "@lib/config"
|
||||
import { getCacheOptions } from "./cookies"
|
||||
|
||||
export type Locale = {
|
||||
code: string
|
||||
name: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches available locales from the backend.
|
||||
* Returns null if the endpoint returns 404 (locales not configured).
|
||||
*/
|
||||
export const listLocales = async (): Promise<Locale[] | null> => {
|
||||
const next = {
|
||||
...(await getCacheOptions("locales")),
|
||||
}
|
||||
|
||||
return sdk.client
|
||||
.fetch<{ locales: Locale[] }>(`/store/locales`, {
|
||||
method: "GET",
|
||||
next,
|
||||
cache: "force-cache",
|
||||
})
|
||||
.then(({ locales }) => locales)
|
||||
.catch(() => null)
|
||||
}
|
||||
9
apps/suman-hrvatska/src/lib/data/onboarding.ts
Normal file
9
apps/suman-hrvatska/src/lib/data/onboarding.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
"use server"
|
||||
import { cookies as nextCookies } from "next/headers"
|
||||
import { redirect } from "next/navigation"
|
||||
|
||||
export async function resetOnboardingState(orderId: string) {
|
||||
const cookies = await nextCookies()
|
||||
cookies.set("_medusa_onboarding", "false", { maxAge: -1 })
|
||||
redirect(`http://localhost:7001/a/orders/${orderId}`)
|
||||
}
|
||||
112
apps/suman-hrvatska/src/lib/data/orders.ts
Normal file
112
apps/suman-hrvatska/src/lib/data/orders.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
"use server"
|
||||
|
||||
import { sdk } from "@lib/config"
|
||||
import medusaError from "@lib/util/medusa-error"
|
||||
import { getAuthHeaders, getCacheOptions } from "./cookies"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
|
||||
export const retrieveOrder = async (id: string) => {
|
||||
const headers = {
|
||||
...(await getAuthHeaders()),
|
||||
}
|
||||
|
||||
const next = {
|
||||
...(await getCacheOptions("orders")),
|
||||
}
|
||||
|
||||
return sdk.client
|
||||
.fetch<HttpTypes.StoreOrderResponse>(`/store/orders/${id}`, {
|
||||
method: "GET",
|
||||
query: {
|
||||
fields:
|
||||
"*payment_collections.payments,*items,*items.metadata,*items.variant,*items.product",
|
||||
},
|
||||
headers,
|
||||
next,
|
||||
cache: "force-cache",
|
||||
})
|
||||
.then(({ order }) => order)
|
||||
.catch((err) => medusaError(err))
|
||||
}
|
||||
|
||||
export const listOrders = async (
|
||||
limit: number = 10,
|
||||
offset: number = 0,
|
||||
filters?: Record<string, unknown>
|
||||
) => {
|
||||
const headers = {
|
||||
...(await getAuthHeaders()),
|
||||
}
|
||||
|
||||
const next = {
|
||||
...(await getCacheOptions("orders")),
|
||||
}
|
||||
|
||||
return sdk.client
|
||||
.fetch<HttpTypes.StoreOrderListResponse>(`/store/orders`, {
|
||||
method: "GET",
|
||||
query: {
|
||||
limit,
|
||||
offset,
|
||||
order: "-created_at",
|
||||
fields: "*items,+items.metadata,*items.variant,*items.product",
|
||||
...filters,
|
||||
},
|
||||
headers,
|
||||
next,
|
||||
cache: "force-cache",
|
||||
})
|
||||
.then(({ orders }) => orders)
|
||||
.catch((err) => medusaError(err))
|
||||
}
|
||||
|
||||
export const createTransferRequest = async (
|
||||
state: {
|
||||
success: boolean
|
||||
error: string | null
|
||||
order: HttpTypes.StoreOrder | null
|
||||
},
|
||||
formData: FormData
|
||||
): Promise<{
|
||||
success: boolean
|
||||
error: string | null
|
||||
order: HttpTypes.StoreOrder | null
|
||||
}> => {
|
||||
const id = formData.get("order_id") as string
|
||||
|
||||
if (!id) {
|
||||
return { success: false, error: "Order ID is required", order: null }
|
||||
}
|
||||
|
||||
const headers = await getAuthHeaders()
|
||||
|
||||
return await sdk.store.order
|
||||
.requestTransfer(
|
||||
id,
|
||||
{},
|
||||
{
|
||||
fields: "id, email",
|
||||
},
|
||||
headers
|
||||
)
|
||||
.then(({ order }) => ({ success: true, error: null, order }))
|
||||
.catch((err) => ({ success: false, error: err.message, order: null }))
|
||||
}
|
||||
|
||||
export const acceptTransferRequest = async (id: string, token: string) => {
|
||||
const headers = await getAuthHeaders()
|
||||
|
||||
return await sdk.store.order
|
||||
.acceptTransfer(id, { token }, {}, headers)
|
||||
.then(({ order }) => ({ success: true, error: null, order }))
|
||||
.catch((err) => ({ success: false, error: err.message, order: null }))
|
||||
}
|
||||
|
||||
export const declineTransferRequest = async (id: string, token: string) => {
|
||||
const headers = await getAuthHeaders()
|
||||
|
||||
return await sdk.store.order
|
||||
.declineTransfer(id, { token }, {}, headers)
|
||||
.then(({ order }) => ({ success: true, error: null, order }))
|
||||
.catch((err) => ({ success: false, error: err.message, order: null }))
|
||||
}
|
||||
35
apps/suman-hrvatska/src/lib/data/payment.ts
Normal file
35
apps/suman-hrvatska/src/lib/data/payment.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
"use server"
|
||||
|
||||
import { sdk } from "@lib/config"
|
||||
import { getAuthHeaders, getCacheOptions } from "./cookies"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
|
||||
export const listCartPaymentMethods = async (regionId: string) => {
|
||||
const headers = {
|
||||
...(await getAuthHeaders()),
|
||||
}
|
||||
|
||||
const next = {
|
||||
...(await getCacheOptions("payment_providers")),
|
||||
revalidate: 60,
|
||||
}
|
||||
|
||||
return sdk.client
|
||||
.fetch<HttpTypes.StorePaymentProviderListResponse>(
|
||||
`/store/payment-providers`,
|
||||
{
|
||||
method: "GET",
|
||||
query: { region_id: regionId },
|
||||
headers,
|
||||
next,
|
||||
}
|
||||
)
|
||||
.then(({ payment_providers }) =>
|
||||
payment_providers.sort((a, b) => {
|
||||
return a.id > b.id ? 1 : -1
|
||||
})
|
||||
)
|
||||
.catch(() => {
|
||||
return null
|
||||
})
|
||||
}
|
||||
151
apps/suman-hrvatska/src/lib/data/products.ts
Normal file
151
apps/suman-hrvatska/src/lib/data/products.ts
Normal file
@@ -0,0 +1,151 @@
|
||||
"use server"
|
||||
|
||||
import { sdk } from "@lib/config"
|
||||
import { OptionValueIds } from "@lib/util/product-option-filters"
|
||||
import { sortProducts } from "@lib/util/sort-products"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { SortOptions } from "@modules/store/components/refinement-list/sort-products"
|
||||
import { getAuthHeaders, getCacheOptions } from "./cookies"
|
||||
import { getRegion, retrieveRegion } from "./regions"
|
||||
|
||||
type ProductListQueryParams = (HttpTypes.FindParams &
|
||||
HttpTypes.StoreProductListParams) & {
|
||||
options?: string[]
|
||||
option_value_id?: string | string[]
|
||||
}
|
||||
|
||||
export const listProducts = async ({
|
||||
pageParam = 1,
|
||||
queryParams,
|
||||
countryCode,
|
||||
regionId,
|
||||
}: {
|
||||
pageParam?: number
|
||||
queryParams?: ProductListQueryParams
|
||||
countryCode?: string
|
||||
regionId?: string
|
||||
}): Promise<{
|
||||
response: { products: HttpTypes.StoreProduct[]; count: number }
|
||||
nextPage: number | null
|
||||
queryParams?: ProductListQueryParams
|
||||
}> => {
|
||||
if (!countryCode && !regionId) {
|
||||
throw new Error("Country code or region ID is required")
|
||||
}
|
||||
|
||||
const limit = queryParams?.limit || 12
|
||||
const _pageParam = Math.max(pageParam, 1)
|
||||
const offset = _pageParam === 1 ? 0 : (_pageParam - 1) * limit
|
||||
|
||||
let region: HttpTypes.StoreRegion | undefined | null
|
||||
|
||||
if (countryCode) {
|
||||
region = await getRegion(countryCode)
|
||||
} else {
|
||||
region = await retrieveRegion(regionId!)
|
||||
}
|
||||
|
||||
if (!region) {
|
||||
return {
|
||||
response: { products: [], count: 0 },
|
||||
nextPage: null,
|
||||
}
|
||||
}
|
||||
|
||||
const headers = {
|
||||
...(await getAuthHeaders()),
|
||||
}
|
||||
|
||||
const next = {
|
||||
...(await getCacheOptions("products")),
|
||||
}
|
||||
|
||||
return sdk.client
|
||||
.fetch<{ products: HttpTypes.StoreProduct[]; count: number }>(
|
||||
`/store/products`,
|
||||
{
|
||||
method: "GET",
|
||||
query: {
|
||||
limit,
|
||||
offset,
|
||||
region_id: region?.id,
|
||||
fields:
|
||||
"*variants.calculated_price,+variants.inventory_quantity,*variants.images,*variants.options,+metadata,+tags,",
|
||||
...queryParams,
|
||||
},
|
||||
headers,
|
||||
next,
|
||||
cache: "force-cache",
|
||||
}
|
||||
)
|
||||
.then(({ products, count }) => {
|
||||
const nextPage = count > offset + limit ? pageParam + 1 : null
|
||||
|
||||
return {
|
||||
response: {
|
||||
products,
|
||||
count,
|
||||
},
|
||||
nextPage: nextPage,
|
||||
queryParams,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* This will fetch 100 products to the Next.js cache and sort them based on the sortBy parameter.
|
||||
* It will then return the paginated products based on the page and limit parameters.
|
||||
*/
|
||||
export const listProductsWithSort = async ({
|
||||
page = 0,
|
||||
queryParams,
|
||||
sortBy = "created_at",
|
||||
countryCode,
|
||||
optionValueIds,
|
||||
}: {
|
||||
page?: number
|
||||
queryParams?: ProductListQueryParams
|
||||
sortBy?: SortOptions
|
||||
countryCode: string
|
||||
optionValueIds?: OptionValueIds
|
||||
}): Promise<{
|
||||
response: { products: HttpTypes.StoreProduct[]; count: number }
|
||||
nextPage: number | null
|
||||
queryParams?: ProductListQueryParams
|
||||
}> => {
|
||||
const limit = queryParams?.limit || 12
|
||||
const optionFilters = Array.from(
|
||||
new Set((optionValueIds || []).filter(Boolean))
|
||||
)
|
||||
|
||||
const {
|
||||
response: { products },
|
||||
} = await listProducts({
|
||||
pageParam: 0,
|
||||
queryParams: {
|
||||
...queryParams,
|
||||
...(optionFilters.length ? { option_value_id: optionFilters } : {}),
|
||||
limit: 100,
|
||||
},
|
||||
countryCode,
|
||||
})
|
||||
|
||||
const sortedProducts = sortProducts(products, sortBy)
|
||||
|
||||
const pageParam = (page - 1) * limit
|
||||
|
||||
const filteredCount = products.length
|
||||
|
||||
const nextPage = filteredCount > pageParam + limit ? pageParam + limit : null
|
||||
|
||||
const paginatedProducts = sortedProducts.slice(pageParam, pageParam + limit)
|
||||
|
||||
return {
|
||||
response: {
|
||||
products: paginatedProducts,
|
||||
count: filteredCount,
|
||||
},
|
||||
nextPage,
|
||||
queryParams,
|
||||
}
|
||||
}
|
||||
59
apps/suman-hrvatska/src/lib/data/regions.ts
Normal file
59
apps/suman-hrvatska/src/lib/data/regions.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
"use server"
|
||||
|
||||
import { sdk } from "@lib/config"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
import { getCacheOptions } from "./cookies"
|
||||
|
||||
export const listRegions = async () => {
|
||||
const next = {
|
||||
...(await getCacheOptions("regions")),
|
||||
}
|
||||
|
||||
return await sdk.client
|
||||
.fetch<{ regions: HttpTypes.StoreRegion[] }>(`/store/regions`, {
|
||||
method: "GET",
|
||||
next,
|
||||
cache: "force-cache",
|
||||
})
|
||||
.then(({ regions }) => regions)
|
||||
}
|
||||
|
||||
export const retrieveRegion = async (id: string) => {
|
||||
const next = {
|
||||
...(await getCacheOptions(["regions", id].join("-"))),
|
||||
}
|
||||
|
||||
return await sdk.client
|
||||
.fetch<{ region: HttpTypes.StoreRegion }>(`/store/regions/${id}`, {
|
||||
method: "GET",
|
||||
next,
|
||||
cache: "force-cache",
|
||||
})
|
||||
.then(({ region }) => region)
|
||||
}
|
||||
|
||||
const regionMap = new Map<string, HttpTypes.StoreRegion>()
|
||||
|
||||
export const getRegion = async (countryCode: string) => {
|
||||
if (regionMap.has(countryCode)) {
|
||||
return regionMap.get(countryCode)
|
||||
}
|
||||
|
||||
const regions = await listRegions()
|
||||
|
||||
if (!regions) {
|
||||
return null
|
||||
}
|
||||
|
||||
regions.forEach((region) => {
|
||||
region.countries?.forEach((c) => {
|
||||
regionMap.set(c?.iso_2 ?? "", region)
|
||||
})
|
||||
})
|
||||
|
||||
const region = countryCode
|
||||
? regionMap.get(countryCode)
|
||||
: regionMap.get("us")
|
||||
|
||||
return region
|
||||
}
|
||||
20
apps/suman-hrvatska/src/lib/data/store-policies.ts
Normal file
20
apps/suman-hrvatska/src/lib/data/store-policies.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
"use server"
|
||||
|
||||
import { getRegionPolicies, StorePolicies } from "@lib/util/store-policies"
|
||||
import { listRegions } from "./regions"
|
||||
|
||||
export const getStorePolicies = async (countryCode: string) => {
|
||||
const regions = await listRegions()
|
||||
const current = regions.find((region) =>
|
||||
region.countries?.some((country) => country.iso_2 === countryCode.toLowerCase())
|
||||
)
|
||||
|
||||
return {
|
||||
current: getRegionPolicies(current),
|
||||
currencyCode: current?.currency_code ?? "",
|
||||
regions: regions.flatMap((region) => {
|
||||
const policies = getRegionPolicies(region)
|
||||
return policies ? [{ id: region.id, name: region.name, policies }] : []
|
||||
}) as { id: string; name: string; policies: StorePolicies }[],
|
||||
}
|
||||
}
|
||||
38
apps/suman-hrvatska/src/lib/data/variants.ts
Normal file
38
apps/suman-hrvatska/src/lib/data/variants.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
"use server"
|
||||
|
||||
import { sdk } from "@lib/config"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
|
||||
import { getAuthHeaders, getCacheOptions } from "./cookies"
|
||||
|
||||
export const retrieveVariant = async (
|
||||
variant_id: string
|
||||
): Promise<HttpTypes.StoreProductVariant | null> => {
|
||||
const authHeaders = await getAuthHeaders()
|
||||
|
||||
if (!authHeaders) return null
|
||||
|
||||
const headers = {
|
||||
...authHeaders,
|
||||
}
|
||||
|
||||
const next = {
|
||||
...(await getCacheOptions("variants")),
|
||||
}
|
||||
|
||||
return await sdk.client
|
||||
.fetch<{ variant: HttpTypes.StoreProductVariant }>(
|
||||
`/store/product-variants/${variant_id}`,
|
||||
{
|
||||
method: "GET",
|
||||
query: {
|
||||
fields: "*images",
|
||||
},
|
||||
headers,
|
||||
next,
|
||||
cache: "force-cache",
|
||||
}
|
||||
)
|
||||
.then(({ variant }) => variant)
|
||||
.catch(() => null)
|
||||
}
|
||||
29
apps/suman-hrvatska/src/lib/hooks/use-in-view.tsx
Normal file
29
apps/suman-hrvatska/src/lib/hooks/use-in-view.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import { RefObject, useEffect, useState } from "react"
|
||||
|
||||
export const useIntersection = (
|
||||
element: RefObject<HTMLDivElement | null>,
|
||||
rootMargin: string
|
||||
) => {
|
||||
const [isVisible, setState] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!element.current) {
|
||||
return
|
||||
}
|
||||
|
||||
const el = element.current
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
setState(entry.isIntersecting)
|
||||
},
|
||||
{ rootMargin }
|
||||
)
|
||||
|
||||
observer.observe(el)
|
||||
|
||||
return () => observer.unobserve(el)
|
||||
}, [element, rootMargin])
|
||||
|
||||
return isVisible
|
||||
}
|
||||
31
apps/suman-hrvatska/src/lib/hooks/use-search-settled.tsx
Normal file
31
apps/suman-hrvatska/src/lib/hooks/use-search-settled.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
"use client"
|
||||
|
||||
import { useInstantSearch } from "react-instantsearch"
|
||||
|
||||
/**
|
||||
* Whether the results InstantSearch is holding belong to the current query and
|
||||
* refinements. Until they do, `items` still carries the previous search's hits,
|
||||
* so rendering them shows stale products for a moment.
|
||||
*
|
||||
* `__isArtificial` is the flag InstantSearch puts on the placeholder results it
|
||||
* renders before its first response. It isn't part of the public types — hence
|
||||
* the cast — but it's the library's own signal, used the same way inside
|
||||
* `connectInfiniteHits`.
|
||||
*/
|
||||
export function useSearchSettled() {
|
||||
const { status, results } = useInstantSearch()
|
||||
|
||||
const isSearching = status !== "idle" && status !== "error"
|
||||
const hasNoResultsYet = Boolean(
|
||||
(results as unknown as { __isArtificial?: boolean } | undefined)
|
||||
?.__isArtificial
|
||||
)
|
||||
|
||||
return {
|
||||
isSearching,
|
||||
hasNoResultsYet,
|
||||
isSettled: !isSearching && !hasNoResultsYet,
|
||||
}
|
||||
}
|
||||
|
||||
export default useSearchSettled
|
||||
46
apps/suman-hrvatska/src/lib/hooks/use-toggle-state.tsx
Normal file
46
apps/suman-hrvatska/src/lib/hooks/use-toggle-state.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import { useState } from "react"
|
||||
|
||||
export type StateType = [boolean, () => void, () => void, () => void] & {
|
||||
state: boolean
|
||||
open: () => void
|
||||
close: () => void
|
||||
toggle: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param initialState - boolean
|
||||
* @returns An array like object with `state`, `open`, `close`, and `toggle` properties
|
||||
* to allow both object and array destructuring
|
||||
*
|
||||
* ```
|
||||
* const [showModal, openModal, closeModal, toggleModal] = useToggleState()
|
||||
* // or
|
||||
* const { state, open, close, toggle } = useToggleState()
|
||||
* ```
|
||||
*/
|
||||
|
||||
const useToggleState = (initialState = false) => {
|
||||
const [state, setState] = useState<boolean>(initialState)
|
||||
|
||||
const close = () => {
|
||||
setState(false)
|
||||
}
|
||||
|
||||
const open = () => {
|
||||
setState(true)
|
||||
}
|
||||
|
||||
const toggle = () => {
|
||||
setState((state) => !state)
|
||||
}
|
||||
|
||||
const hookData = [state, open, close, toggle] as StateType
|
||||
hookData.state = state
|
||||
hookData.open = open
|
||||
hookData.close = close
|
||||
hookData.toggle = toggle
|
||||
return hookData
|
||||
}
|
||||
|
||||
export default useToggleState
|
||||
57
apps/suman-hrvatska/src/lib/search-client.ts
Normal file
57
apps/suman-hrvatska/src/lib/search-client.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import {
|
||||
createInstantSearchAdapter,
|
||||
type MedusaSdkLike,
|
||||
} from "@medusajs/instantsearch-adapter"
|
||||
|
||||
import { sdk } from "@lib/config"
|
||||
|
||||
export const PRODUCT_INDEX_NAME = "product"
|
||||
|
||||
/**
|
||||
* The currencies the product index holds prices in, one field set each. Keep
|
||||
* in sync with `PRICE_CURRENCIES` in the backend's `src/search/product.ts`.
|
||||
*/
|
||||
export const SEARCH_PRICE_CURRENCIES = ["eur", "usd"]
|
||||
|
||||
export type PriceField =
|
||||
| "min_price"
|
||||
| "max_price"
|
||||
| "original_price"
|
||||
| "on_sale"
|
||||
|
||||
/**
|
||||
* The indexed currency to read prices in for a region. A region whose currency
|
||||
* the index doesn't hold falls back to the first one, so the listing still
|
||||
* shows a price rather than none.
|
||||
*/
|
||||
export const indexedCurrency = (currencyCode: string) => {
|
||||
const code = currencyCode.toLowerCase()
|
||||
return SEARCH_PRICE_CURRENCIES.includes(code)
|
||||
? code
|
||||
: SEARCH_PRICE_CURRENCIES[0]
|
||||
}
|
||||
|
||||
export const priceAttribute = (field: PriceField, currencyCode: string) =>
|
||||
`${field}_${indexedCurrency(currencyCode)}`
|
||||
|
||||
/**
|
||||
* Shared by the navbar search drawer and the store listing. An empty query
|
||||
* searches rather than short-circuiting, which is what the listing needs to
|
||||
* show every product before anything is refined.
|
||||
*/
|
||||
export const { searchClient } = createInstantSearchAdapter({
|
||||
sdk: sdk as unknown as MedusaSdkLike,
|
||||
path: "/store/search",
|
||||
additionalSearchParameters: {
|
||||
search_options: {
|
||||
match_strategy: "last",
|
||||
},
|
||||
},
|
||||
// Range widgets read `facets_stats`, which the adapter only produces for
|
||||
// fields listed here. The price fields are declared with a `stats` facet on
|
||||
// the index, which is what makes the stats available at all.
|
||||
numericAttributes: SEARCH_PRICE_CURRENCIES.flatMap((currency) => [
|
||||
`min_price_${currency}`,
|
||||
`max_price_${currency}`,
|
||||
]),
|
||||
})
|
||||
236
apps/suman-hrvatska/src/lib/ucp/mcp.ts
Normal file
236
apps/suman-hrvatska/src/lib/ucp/mcp.ts
Normal file
@@ -0,0 +1,236 @@
|
||||
import "server-only"
|
||||
import {
|
||||
cancelCart,
|
||||
cancelCheckout,
|
||||
completeCheckout,
|
||||
createCart,
|
||||
createCheckout,
|
||||
getCart,
|
||||
getCheckout,
|
||||
lookupCatalog,
|
||||
searchCatalog,
|
||||
updateCart,
|
||||
updateCheckout,
|
||||
} from "./operations"
|
||||
import { STORE_NAME } from "@lib/util/site"
|
||||
import { UcpResult } from "./ucp"
|
||||
|
||||
const SUPPORTED_PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26"]
|
||||
|
||||
type Args = Record<string, unknown>
|
||||
type JsonRpcId = string | number | null
|
||||
|
||||
const object = (properties: Record<string, unknown>, required: string[] = []) => ({
|
||||
type: "object",
|
||||
properties,
|
||||
required,
|
||||
})
|
||||
|
||||
const meta = object({
|
||||
"ucp-agent": object({ profile: { type: "string" } }),
|
||||
"idempotency-key": { type: "string" },
|
||||
})
|
||||
const id = { type: "string", description: "Cart or checkout session ID" }
|
||||
const context = object({
|
||||
address_country: { type: "string", description: "ISO 3166-1 alpha-2 country code" },
|
||||
})
|
||||
const lineItems = {
|
||||
type: "array",
|
||||
items: object(
|
||||
{
|
||||
item: object({ id: { type: "string", description: "Variant ID" } }, ["id"]),
|
||||
quantity: { type: "integer", minimum: 1, maximum: 100 },
|
||||
},
|
||||
["item", "quantity"]
|
||||
),
|
||||
}
|
||||
const checkoutInput = object({
|
||||
cart_id: { type: "string" },
|
||||
line_items: lineItems,
|
||||
buyer: object({
|
||||
email: { type: "string" },
|
||||
first_name: { type: "string" },
|
||||
last_name: { type: "string" },
|
||||
}),
|
||||
fulfillment: object({
|
||||
methods: {
|
||||
type: "array",
|
||||
items: object({
|
||||
type: { type: "string", enum: ["shipping"] },
|
||||
destinations: {
|
||||
type: "array",
|
||||
items: object({
|
||||
first_name: { type: "string" },
|
||||
last_name: { type: "string" },
|
||||
street_address: { type: "string" },
|
||||
extended_address: { type: "string" },
|
||||
address_locality: { type: "string" },
|
||||
address_region: { type: "string" },
|
||||
postal_code: { type: "string" },
|
||||
address_country: { type: "string" },
|
||||
}),
|
||||
},
|
||||
}),
|
||||
},
|
||||
}),
|
||||
context,
|
||||
})
|
||||
|
||||
const idempotencyKey = (args: Args) => {
|
||||
const key = (args.meta as Args | undefined)?.["idempotency-key"]
|
||||
return typeof key === "string" ? key : null
|
||||
}
|
||||
const nested = (args: Args, key: string) => (args[key] ?? {}) as Args
|
||||
const idArg = (args: Args) => (typeof args.id === "string" ? args.id : "")
|
||||
|
||||
type Tool = {
|
||||
description: string
|
||||
inputSchema: Record<string, unknown>
|
||||
run: (request: Request, args: Args) => Promise<UcpResult>
|
||||
}
|
||||
|
||||
const TOOLS: Record<string, Tool> = {
|
||||
search_catalog: {
|
||||
description: "Search the store's products by keyword. Returns products with variants, prices in minor units and availability.",
|
||||
inputSchema: object({
|
||||
meta,
|
||||
catalog: object({
|
||||
query: { type: "string" },
|
||||
pagination: object({ limit: { type: "integer" }, cursor: { type: "string" } }),
|
||||
context,
|
||||
}),
|
||||
}),
|
||||
run: (request, args) => searchCatalog(request, nested(args, "catalog")),
|
||||
},
|
||||
lookup_catalog: {
|
||||
description: "Look up products by product ID, variant ID or product handle.",
|
||||
inputSchema: object(
|
||||
{ meta, catalog: object({ ids: { type: "array", items: { type: "string" } }, context }, ["ids"]) },
|
||||
["catalog"]
|
||||
),
|
||||
run: (request, args) => lookupCatalog(request, nested(args, "catalog")),
|
||||
},
|
||||
get_product: {
|
||||
description: "Get one product by product ID, variant ID or handle.",
|
||||
inputSchema: object({ meta, catalog: object({ id: { type: "string" }, context }, ["id"]) }, ["catalog"]),
|
||||
run: (request, args) => {
|
||||
const catalog = nested(args, "catalog")
|
||||
return lookupCatalog(request, { ...catalog, ids: [catalog.id] })
|
||||
},
|
||||
},
|
||||
create_cart: {
|
||||
description: "Create a cart with line items (variant IDs and quantities).",
|
||||
inputSchema: object({ meta, cart: object({ line_items: lineItems, context }, ["line_items"]) }, ["cart"]),
|
||||
run: (request, args) => createCart(request, nested(args, "cart"), idempotencyKey(args)),
|
||||
},
|
||||
get_cart: {
|
||||
description: "Get a cart by ID.",
|
||||
inputSchema: object({ meta, id }, ["id"]),
|
||||
run: (request, args) => getCart(request, idArg(args)),
|
||||
},
|
||||
update_cart: {
|
||||
description: "Replace a cart's line items.",
|
||||
inputSchema: object({ meta, id, cart: object({ line_items: lineItems }, ["line_items"]) }, ["id", "cart"]),
|
||||
run: (request, args) => updateCart(request, idArg(args), nested(args, "cart")),
|
||||
},
|
||||
cancel_cart: {
|
||||
description: "Cancel a cart.",
|
||||
inputSchema: object({ meta, id }, ["id"]),
|
||||
run: (request, args) => cancelCart(request, idArg(args)),
|
||||
},
|
||||
create_checkout: {
|
||||
description:
|
||||
"Start a checkout from line items or an existing cart_id, with buyer email and shipping address. Payment is completed by the buyer at the returned continue_url.",
|
||||
inputSchema: object({ meta, checkout: checkoutInput }, ["checkout"]),
|
||||
run: (request, args) => createCheckout(request, nested(args, "checkout"), idempotencyKey(args)),
|
||||
},
|
||||
get_checkout: {
|
||||
description: "Get a checkout session by ID, including the order once the buyer has paid.",
|
||||
inputSchema: object({ meta, id }, ["id"]),
|
||||
run: (request, args) => getCheckout(request, idArg(args)),
|
||||
},
|
||||
update_checkout: {
|
||||
description: "Update a checkout session's line items, buyer or shipping address.",
|
||||
inputSchema: object({ meta, id, checkout: checkoutInput }, ["id", "checkout"]),
|
||||
run: (request, args) => updateCheckout(request, idArg(args), nested(args, "checkout")),
|
||||
},
|
||||
complete_checkout: {
|
||||
description:
|
||||
"Request completion. This store requires the buyer to pay at continue_url, so open sessions return requires_escalation.",
|
||||
inputSchema: object({ meta, id, checkout: { type: "object" } }, ["id"]),
|
||||
run: (request, args) => completeCheckout(request, idArg(args)),
|
||||
},
|
||||
cancel_checkout: {
|
||||
description: "Cancel a checkout session.",
|
||||
inputSchema: object({ meta, id }, ["id"]),
|
||||
run: (request, args) => cancelCheckout(request, idArg(args)),
|
||||
},
|
||||
}
|
||||
|
||||
const rpcResult = (id: JsonRpcId, result: unknown) =>
|
||||
Response.json({ jsonrpc: "2.0", id, result }, { headers: { "Cache-Control": "no-store" } })
|
||||
|
||||
const rpcError = (id: JsonRpcId, code: number, message: string, status = 200) =>
|
||||
Response.json(
|
||||
{ jsonrpc: "2.0", id, error: { code, message } },
|
||||
{ status, headers: { "Cache-Control": "no-store" } }
|
||||
)
|
||||
|
||||
/** Handles a stateless MCP Streamable HTTP POST with JSON (not SSE) responses. */
|
||||
export const handleMcpRequest = async (request: Request): Promise<Response> => {
|
||||
let message: Record<string, unknown>
|
||||
try {
|
||||
message = await request.json()
|
||||
} catch {
|
||||
return rpcError(null, -32700, "Parse error", 400)
|
||||
}
|
||||
if (!message || typeof message !== "object" || Array.isArray(message)) {
|
||||
return rpcError(null, -32600, "Invalid request: send a single JSON-RPC message", 400)
|
||||
}
|
||||
|
||||
const rpcId = (message.id ?? null) as JsonRpcId
|
||||
if (message.id === undefined) {
|
||||
return new Response(null, { status: 202 })
|
||||
}
|
||||
|
||||
const params = (message.params ?? {}) as Args
|
||||
|
||||
switch (message.method) {
|
||||
case "initialize": {
|
||||
const requested = params.protocolVersion
|
||||
return rpcResult(rpcId, {
|
||||
protocolVersion:
|
||||
typeof requested === "string" && SUPPORTED_PROTOCOL_VERSIONS.includes(requested)
|
||||
? requested
|
||||
: SUPPORTED_PROTOCOL_VERSIONS[0],
|
||||
capabilities: { tools: { listChanged: false } },
|
||||
serverInfo: { name: `${STORE_NAME} UCP`, version: "1.0.0" },
|
||||
instructions:
|
||||
"Universal Commerce Protocol shopping tools. Prices are in minor currency units. Checkout hands payment off to the buyer via continue_url.",
|
||||
})
|
||||
}
|
||||
case "ping":
|
||||
return rpcResult(rpcId, {})
|
||||
case "tools/list":
|
||||
return rpcResult(rpcId, {
|
||||
tools: Object.entries(TOOLS).map(([name, { description, inputSchema }]) => ({
|
||||
name,
|
||||
description,
|
||||
inputSchema,
|
||||
})),
|
||||
})
|
||||
case "tools/call": {
|
||||
const tool = typeof params.name === "string" ? TOOLS[params.name] : undefined
|
||||
if (!tool) return rpcError(rpcId, -32602, `Unknown tool: ${String(params.name)}`)
|
||||
|
||||
const { status, body } = await tool.run(request, (params.arguments ?? {}) as Args)
|
||||
return rpcResult(rpcId, {
|
||||
content: [{ type: "text", text: JSON.stringify(body) }],
|
||||
structuredContent: body,
|
||||
isError: status >= 400,
|
||||
})
|
||||
}
|
||||
default:
|
||||
return rpcError(rpcId, -32601, `Method not found: ${String(message.method)}`)
|
||||
}
|
||||
}
|
||||
547
apps/suman-hrvatska/src/lib/ucp/operations.ts
Normal file
547
apps/suman-hrvatska/src/lib/ucp/operations.ts
Normal file
@@ -0,0 +1,547 @@
|
||||
import "server-only"
|
||||
import { sdk } from "@lib/config"
|
||||
import { listRegions } from "@lib/data/regions"
|
||||
import { createCartWithItems, resolveRegion } from "@lib/util/server-cart"
|
||||
import { getRequestOrigin } from "@lib/util/site"
|
||||
import {
|
||||
cartContinueUrl,
|
||||
cartCountryCode,
|
||||
parseLineItems,
|
||||
toUcpLineItems,
|
||||
toUcpProduct,
|
||||
toUcpTotals,
|
||||
UCP_CART_FIELDS,
|
||||
UCP_PRODUCT_FIELDS,
|
||||
ucpError,
|
||||
ucpResult,
|
||||
UcpResult,
|
||||
} from "./ucp"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
|
||||
type Input = Record<string, unknown>
|
||||
|
||||
const CATALOG_SEARCH = "dev.ucp.shopping.catalog.search"
|
||||
const CATALOG_LOOKUP = "dev.ucp.shopping.catalog.lookup"
|
||||
const CART = "dev.ucp.shopping.cart"
|
||||
const CHECKOUT = "dev.ucp.shopping.checkout"
|
||||
|
||||
const MAX_SEARCH_LIMIT = 50
|
||||
const MAX_LOOKUP_IDS = 50
|
||||
const IDEMPOTENCY_TTL_MS = 10 * 60 * 1000
|
||||
const CANCELED_KEY = "ucp_canceled"
|
||||
|
||||
const asObject = (value: unknown): Input =>
|
||||
value && typeof value === "object" && !Array.isArray(value) ? (value as Input) : {}
|
||||
|
||||
const asString = (value: unknown) =>
|
||||
typeof value === "string" && value.trim() ? value.trim() : undefined
|
||||
|
||||
const contextCountry = (input: Input) => asString(asObject(input.context).address_country)
|
||||
|
||||
const unsupportedCountry = (name: Parameters<typeof ucpError>[0]) =>
|
||||
ucpError(name, 400, "unsupported_country", "This store doesn't sell to that country")
|
||||
|
||||
const invalidLineItems = (name: Parameters<typeof ucpError>[0]) =>
|
||||
ucpError(
|
||||
name,
|
||||
400,
|
||||
"invalid_request",
|
||||
"line_items must be an array of { item: { id }, quantity } with quantity 1-100"
|
||||
)
|
||||
|
||||
const itemUnavailable = (name: Parameters<typeof ucpError>[0]) =>
|
||||
ucpError(name, 422, "item_unavailable", "One or more items don't exist or can't be purchased")
|
||||
|
||||
const MAX_IDEMPOTENCY_ENTRIES = 500
|
||||
const idempotentResults = new Map<string, { expiresAt: number; value: Promise<unknown> }>()
|
||||
|
||||
/**
|
||||
* Runs `operation` once per idempotency key for 10 minutes. Kept in process
|
||||
* memory, so retries must reach the same server instance to be deduplicated.
|
||||
*/
|
||||
export const withIdempotency = <T>(
|
||||
key: string | null | undefined,
|
||||
scope: string,
|
||||
operation: () => Promise<T>
|
||||
): Promise<T> => {
|
||||
if (!key) {
|
||||
return operation()
|
||||
}
|
||||
|
||||
const cacheKey = `${scope}:${key}`
|
||||
const now = Date.now()
|
||||
const hit = idempotentResults.get(cacheKey)
|
||||
if (hit && hit.expiresAt > now) {
|
||||
return hit.value as Promise<T>
|
||||
}
|
||||
|
||||
if (idempotentResults.size >= MAX_IDEMPOTENCY_ENTRIES) {
|
||||
idempotentResults.forEach((entry, entryKey) => {
|
||||
if (entry.expiresAt <= now) idempotentResults.delete(entryKey)
|
||||
})
|
||||
if (idempotentResults.size >= MAX_IDEMPOTENCY_ENTRIES) {
|
||||
idempotentResults.delete(idempotentResults.keys().next().value!)
|
||||
}
|
||||
}
|
||||
|
||||
const value = operation()
|
||||
idempotentResults.set(cacheKey, { expiresAt: now + IDEMPOTENCY_TTL_MS, value })
|
||||
value.catch(() => idempotentResults.delete(cacheKey))
|
||||
return value
|
||||
}
|
||||
|
||||
// Catalog
|
||||
|
||||
export const searchCatalog = async (request: Request, input: Input): Promise<UcpResult> => {
|
||||
const query = asString(input.query)?.slice(0, 200)
|
||||
const pagination = asObject(input.pagination)
|
||||
const limit = Math.min(Math.max(Number(pagination.limit) || 20, 1), MAX_SEARCH_LIMIT)
|
||||
const offset = Math.max(parseInt(String(pagination.cursor ?? "0"), 10) || 0, 0)
|
||||
|
||||
const resolved = await resolveRegion(contextCountry(input))
|
||||
if (!resolved) return unsupportedCountry(CATALOG_SEARCH)
|
||||
|
||||
const { products, count } = await sdk.store.product.list({
|
||||
...(query ? { q: query } : {}),
|
||||
limit,
|
||||
offset,
|
||||
region_id: resolved.region.id,
|
||||
fields: UCP_PRODUCT_FIELDS,
|
||||
})
|
||||
|
||||
const base = `${getRequestOrigin(request)}/${resolved.countryCode}/products`
|
||||
const nextOffset = offset + products.length
|
||||
|
||||
return ucpResult(CATALOG_SEARCH, {
|
||||
products: products.map((product) =>
|
||||
toUcpProduct(product, resolved.region.currency_code, `${base}/${product.handle}`)
|
||||
),
|
||||
pagination: {
|
||||
has_next_page: nextOffset < count,
|
||||
cursor: nextOffset < count ? String(nextOffset) : undefined,
|
||||
total_count: count,
|
||||
},
|
||||
messages: [],
|
||||
})
|
||||
}
|
||||
|
||||
export const lookupCatalog = async (request: Request, input: Input): Promise<UcpResult> => {
|
||||
const ids = Array.isArray(input.ids)
|
||||
? input.ids.filter((id): id is string => typeof id === "string" && id.length > 0)
|
||||
: []
|
||||
if (!ids.length || ids.length > MAX_LOOKUP_IDS) {
|
||||
return ucpError(
|
||||
CATALOG_LOOKUP,
|
||||
400,
|
||||
"invalid_request",
|
||||
`"ids" must contain 1-${MAX_LOOKUP_IDS} identifiers`
|
||||
)
|
||||
}
|
||||
|
||||
const resolved = await resolveRegion(contextCountry(input))
|
||||
if (!resolved) return unsupportedCountry(CATALOG_LOOKUP)
|
||||
|
||||
const variantIds = ids.filter((id) => id.startsWith("variant_"))
|
||||
const handles = ids.filter((id) => !id.startsWith("prod_") && !id.startsWith("variant_"))
|
||||
const variantProductIds = variantIds.length
|
||||
? await sdk.client
|
||||
.fetch<{ variants: { product_id?: string | null }[] }>("/store/product-variants", {
|
||||
query: { id: variantIds, fields: "id,product_id", limit: MAX_LOOKUP_IDS },
|
||||
})
|
||||
.then(({ variants }) => variants.map((v) => v.product_id).filter((id): id is string => !!id))
|
||||
: []
|
||||
const productIds = Array.from(
|
||||
new Set([...ids.filter((id) => id.startsWith("prod_")), ...variantProductIds])
|
||||
)
|
||||
const common = { region_id: resolved.region.id, fields: UCP_PRODUCT_FIELDS, limit: MAX_LOOKUP_IDS }
|
||||
|
||||
const results = await Promise.all([
|
||||
productIds.length ? sdk.store.product.list({ ...common, id: productIds }) : null,
|
||||
handles.length ? sdk.store.product.list({ ...common, handle: handles }) : null,
|
||||
])
|
||||
|
||||
const products = new Map<string, HttpTypes.StoreProduct>()
|
||||
for (const result of results) {
|
||||
result?.products.forEach((product) => products.set(product.id, product))
|
||||
}
|
||||
|
||||
const found = new Set<string>()
|
||||
for (const product of Array.from(products.values())) {
|
||||
found.add(product.id)
|
||||
if (product.handle) found.add(product.handle)
|
||||
product.variants?.forEach((variant) => found.add(variant.id))
|
||||
}
|
||||
|
||||
const base = `${getRequestOrigin(request)}/${resolved.countryCode}/products`
|
||||
|
||||
return ucpResult(CATALOG_LOOKUP, {
|
||||
products: Array.from(products.values()).map((product) =>
|
||||
toUcpProduct(product, resolved.region.currency_code, `${base}/${product.handle}`)
|
||||
),
|
||||
messages: ids
|
||||
.filter((id) => !found.has(id))
|
||||
.map((id) => ({
|
||||
type: "info",
|
||||
code: "not_found",
|
||||
content: `No product or variant found for "${id}"`,
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
// Cart
|
||||
|
||||
const retrieveCart = async (cartId: string) => {
|
||||
try {
|
||||
const { cart } = await sdk.store.cart.retrieve(cartId, { fields: UCP_CART_FIELDS })
|
||||
return cart
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const isCanceled = (cart: HttpTypes.StoreCart) => cart.metadata?.[CANCELED_KEY] === true
|
||||
|
||||
const retrieveOpenCart = async (cartId: string) => {
|
||||
const cart = await retrieveCart(cartId)
|
||||
return cart && !cart.completed_at && !isCanceled(cart) ? cart : null
|
||||
}
|
||||
|
||||
const syncLineItems = async (
|
||||
cart: HttpTypes.StoreCart,
|
||||
items: { variant_id: string; quantity: number }[]
|
||||
) => {
|
||||
const desired = new Map(items.map((item) => [item.variant_id, item.quantity]))
|
||||
const existing = new Map((cart.items ?? []).map((line) => [line.variant_id, line]))
|
||||
|
||||
for (const [variantId, line] of Array.from(existing)) {
|
||||
const quantity = variantId ? desired.get(variantId) : undefined
|
||||
if (quantity === undefined) {
|
||||
await sdk.store.cart.deleteLineItem(cart.id, line.id)
|
||||
} else if (quantity !== line.quantity) {
|
||||
await sdk.store.cart.updateLineItem(cart.id, line.id, { quantity })
|
||||
}
|
||||
}
|
||||
for (const [variantId, quantity] of Array.from(desired)) {
|
||||
if (!existing.has(variantId)) {
|
||||
await sdk.store.cart.createLineItem(cart.id, { variant_id: variantId, quantity })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const toUcpCartBody = (request: Request, cart: HttpTypes.StoreCart) => ({
|
||||
id: cart.id,
|
||||
currency: cart.currency_code.toUpperCase(),
|
||||
line_items: toUcpLineItems(cart),
|
||||
totals: toUcpTotals(cart),
|
||||
continue_url: cartContinueUrl(getRequestOrigin(request), cart),
|
||||
messages: [],
|
||||
})
|
||||
|
||||
const cartNotFound = () => ucpError(CART, 404, "not_found", "Cart not found")
|
||||
|
||||
export const createCart = async (
|
||||
request: Request,
|
||||
input: Input,
|
||||
idempotencyKey?: string | null
|
||||
): Promise<UcpResult> => {
|
||||
const items = parseLineItems(input.line_items ?? [])
|
||||
if (!items) return invalidLineItems(CART)
|
||||
|
||||
const resolved = await resolveRegion(contextCountry(input))
|
||||
if (!resolved) return unsupportedCountry(CART)
|
||||
|
||||
let cartId: string
|
||||
try {
|
||||
cartId = await withIdempotency(idempotencyKey, "cart", () =>
|
||||
createCartWithItems(resolved.region.id, items)
|
||||
)
|
||||
} catch {
|
||||
return itemUnavailable(CART)
|
||||
}
|
||||
|
||||
const cart = await retrieveCart(cartId)
|
||||
return cart ? ucpResult(CART, toUcpCartBody(request, cart), 201) : cartNotFound()
|
||||
}
|
||||
|
||||
export const getCart = async (request: Request, cartId: string): Promise<UcpResult> => {
|
||||
const cart = await retrieveOpenCart(cartId)
|
||||
return cart ? ucpResult(CART, toUcpCartBody(request, cart)) : cartNotFound()
|
||||
}
|
||||
|
||||
export const updateCart = async (
|
||||
request: Request,
|
||||
cartId: string,
|
||||
input: Input
|
||||
): Promise<UcpResult> => {
|
||||
const items = parseLineItems(input.line_items)
|
||||
if (!items) return invalidLineItems(CART)
|
||||
|
||||
const cart = await retrieveOpenCart(cartId)
|
||||
if (!cart) return cartNotFound()
|
||||
|
||||
try {
|
||||
await syncLineItems(cart, items)
|
||||
} catch {
|
||||
return itemUnavailable(CART)
|
||||
}
|
||||
|
||||
const updated = await retrieveCart(cart.id)
|
||||
return updated ? ucpResult(CART, toUcpCartBody(request, updated)) : cartNotFound()
|
||||
}
|
||||
|
||||
export const cancelCart = async (request: Request, cartId: string): Promise<UcpResult> => {
|
||||
const cart = await retrieveOpenCart(cartId)
|
||||
if (!cart) return cartNotFound()
|
||||
|
||||
await sdk.store.cart.update(cart.id, { metadata: { ...cart.metadata, [CANCELED_KEY]: true } })
|
||||
return ucpResult(CART, {
|
||||
...toUcpCartBody(request, cart),
|
||||
continue_url: undefined,
|
||||
messages: [{ type: "info", code: "canceled", content: "Cart canceled" }],
|
||||
})
|
||||
}
|
||||
|
||||
// Checkout
|
||||
|
||||
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
|
||||
const firstItem = (value: unknown) => asObject(Array.isArray(value) ? value[0] : undefined)
|
||||
|
||||
const firstDestination = (input: Input) =>
|
||||
firstItem(firstItem(asObject(input.fulfillment).methods).destinations)
|
||||
|
||||
const applyCheckoutDetails = async (
|
||||
cart: HttpTypes.StoreCart,
|
||||
input: Input
|
||||
): Promise<UcpResult | null> => {
|
||||
const buyer = asObject(input.buyer)
|
||||
const destination = firstDestination(input)
|
||||
|
||||
const update: HttpTypes.StoreUpdateCart = {}
|
||||
|
||||
const email = asString(buyer.email)
|
||||
if (email) {
|
||||
if (!EMAIL_PATTERN.test(email)) {
|
||||
return ucpError(CHECKOUT, 400, "invalid_email", "buyer.email is not a valid email address")
|
||||
}
|
||||
update.email = email
|
||||
}
|
||||
|
||||
const countryCode = asString(destination.address_country)?.toLowerCase()
|
||||
if (countryCode) {
|
||||
const inCartRegion = cart.region?.countries?.some((c) => c.iso_2 === countryCode)
|
||||
if (!inCartRegion) {
|
||||
const regions = await listRegions()
|
||||
const region = regions.find((r) => r.countries?.some((c) => c.iso_2 === countryCode))
|
||||
if (!region) return unsupportedCountry(CHECKOUT)
|
||||
update.region_id = region.id
|
||||
}
|
||||
|
||||
update.shipping_address = {
|
||||
first_name: asString(destination.first_name) ?? asString(buyer.first_name),
|
||||
last_name: asString(destination.last_name) ?? asString(buyer.last_name),
|
||||
address_1: asString(destination.street_address),
|
||||
address_2: asString(destination.extended_address),
|
||||
city: asString(destination.address_locality),
|
||||
province: asString(destination.address_region),
|
||||
postal_code: asString(destination.postal_code),
|
||||
phone: asString(destination.phone_number) ?? asString(buyer.phone_number),
|
||||
country_code: countryCode,
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(update).length) {
|
||||
await sdk.store.cart.update(cart.id, update)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// Only call for carts with `completed_at` set: completing an already-completed
|
||||
// cart returns its existing order (the Store API cart route doesn't expose it).
|
||||
const findOrder = async (cartId: string) => {
|
||||
try {
|
||||
const result = await sdk.store.cart.complete(cartId, { fields: "id,display_id" })
|
||||
return result.type === "order" ? result.order : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const toUcpCheckoutBody = async (request: Request, cart: HttpTypes.StoreCart) => {
|
||||
const origin = getRequestOrigin(request)
|
||||
const countryCode = cartCountryCode(cart)
|
||||
const base = `${origin}/${countryCode}`
|
||||
const address = cart.shipping_address
|
||||
|
||||
const missing = [
|
||||
!cart.email && { path: "$.buyer.email", content: "Buyer email is required" },
|
||||
!address?.address_1 && {
|
||||
path: "$.fulfillment.methods[0].destinations[0]",
|
||||
content: "A shipping destination is required",
|
||||
},
|
||||
].filter(Boolean) as { path: string; content: string }[]
|
||||
|
||||
const order = cart.completed_at ? await findOrder(cart.id) : null
|
||||
const status = isCanceled(cart)
|
||||
? "canceled"
|
||||
: order
|
||||
? "completed"
|
||||
: missing.length
|
||||
? "incomplete"
|
||||
: "requires_escalation"
|
||||
const isOpen = status === "incomplete" || status === "requires_escalation"
|
||||
|
||||
return {
|
||||
id: cart.id,
|
||||
status,
|
||||
currency: cart.currency_code.toUpperCase(),
|
||||
line_items: toUcpLineItems(cart),
|
||||
totals: toUcpTotals(cart),
|
||||
buyer: cart.email ? { email: cart.email } : undefined,
|
||||
fulfillment: address?.address_1
|
||||
? {
|
||||
methods: [
|
||||
{
|
||||
type: "shipping",
|
||||
destinations: [
|
||||
{
|
||||
first_name: address.first_name ?? undefined,
|
||||
last_name: address.last_name ?? undefined,
|
||||
street_address: address.address_1,
|
||||
extended_address: address.address_2 ?? undefined,
|
||||
address_locality: address.city ?? undefined,
|
||||
address_region: address.province ?? undefined,
|
||||
postal_code: address.postal_code ?? undefined,
|
||||
address_country: address.country_code?.toUpperCase(),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
: undefined,
|
||||
links: [
|
||||
{ type: "terms_of_service", url: `${base}/terms` },
|
||||
{ type: "privacy_policy", url: `${base}/privacy` },
|
||||
{ type: "refund_policy", url: `${base}/returns` },
|
||||
{ type: "shipping_policy", url: `${base}/shipping` },
|
||||
],
|
||||
order: order
|
||||
? { id: order.id, permalink_url: `${base}/order/${order.id}/confirmed` }
|
||||
: undefined,
|
||||
continue_url: isOpen ? cartContinueUrl(origin, cart) : undefined,
|
||||
messages: isOpen
|
||||
? [
|
||||
...missing.map(({ path, content }) => ({
|
||||
type: "error",
|
||||
code: "missing",
|
||||
path,
|
||||
content,
|
||||
severity: "recoverable",
|
||||
})),
|
||||
{
|
||||
type: "error",
|
||||
code: "payment_required",
|
||||
content:
|
||||
"This store doesn't accept payment through the API. The buyer selects delivery and pays at continue_url.",
|
||||
severity: "requires_buyer_input",
|
||||
},
|
||||
]
|
||||
: [],
|
||||
}
|
||||
}
|
||||
|
||||
const checkoutNotFound = () => ucpError(CHECKOUT, 404, "not_found", "Checkout session not found")
|
||||
|
||||
export const createCheckout = async (
|
||||
request: Request,
|
||||
input: Input,
|
||||
idempotencyKey?: string | null
|
||||
): Promise<UcpResult> => {
|
||||
const destinationCountry = asString(firstDestination(input).address_country)
|
||||
|
||||
let cartId = asString(input.cart_id)
|
||||
if (cartId) {
|
||||
if (!(await retrieveOpenCart(cartId))) {
|
||||
return ucpError(CHECKOUT, 404, "not_found", "Cart not found")
|
||||
}
|
||||
} else {
|
||||
const items = parseLineItems(input.line_items)
|
||||
if (!items?.length) return invalidLineItems(CHECKOUT)
|
||||
|
||||
const resolved = await resolveRegion(destinationCountry ?? contextCountry(input))
|
||||
if (!resolved) return unsupportedCountry(CHECKOUT)
|
||||
|
||||
try {
|
||||
cartId = await withIdempotency(idempotencyKey, "checkout", () =>
|
||||
createCartWithItems(resolved.region.id, items)
|
||||
)
|
||||
} catch {
|
||||
return itemUnavailable(CHECKOUT)
|
||||
}
|
||||
}
|
||||
|
||||
const cart = await retrieveOpenCart(cartId)
|
||||
if (!cart) return checkoutNotFound()
|
||||
|
||||
const error = await applyCheckoutDetails(cart, input)
|
||||
if (error) return error
|
||||
|
||||
const updated = await retrieveCart(cart.id)
|
||||
return updated
|
||||
? ucpResult(CHECKOUT, await toUcpCheckoutBody(request, updated), 201)
|
||||
: checkoutNotFound()
|
||||
}
|
||||
|
||||
export const getCheckout = async (request: Request, id: string): Promise<UcpResult> => {
|
||||
const cart = await retrieveCart(id)
|
||||
return cart ? ucpResult(CHECKOUT, await toUcpCheckoutBody(request, cart)) : checkoutNotFound()
|
||||
}
|
||||
|
||||
export const updateCheckout = async (
|
||||
request: Request,
|
||||
id: string,
|
||||
input: Input
|
||||
): Promise<UcpResult> => {
|
||||
const cart = await retrieveOpenCart(id)
|
||||
if (!cart) return checkoutNotFound()
|
||||
|
||||
if (input.line_items !== undefined) {
|
||||
const items = parseLineItems(input.line_items)
|
||||
if (!items?.length) return invalidLineItems(CHECKOUT)
|
||||
try {
|
||||
await syncLineItems(cart, items)
|
||||
} catch {
|
||||
return itemUnavailable(CHECKOUT)
|
||||
}
|
||||
}
|
||||
|
||||
const error = await applyCheckoutDetails(cart, input)
|
||||
if (error) return error
|
||||
|
||||
const updated = await retrieveCart(cart.id)
|
||||
return updated
|
||||
? ucpResult(CHECKOUT, await toUcpCheckoutBody(request, updated))
|
||||
: checkoutNotFound()
|
||||
}
|
||||
|
||||
/**
|
||||
* Payment can't be taken through the API, so completing an open session
|
||||
* returns it unchanged with `requires_escalation` and a `continue_url`.
|
||||
*/
|
||||
export const completeCheckout = (request: Request, id: string) => getCheckout(request, id)
|
||||
|
||||
export const cancelCheckout = async (request: Request, id: string): Promise<UcpResult> => {
|
||||
const cart = await retrieveCart(id)
|
||||
if (!cart) return checkoutNotFound()
|
||||
if (cart.completed_at) {
|
||||
return ucpError(CHECKOUT, 409, "already_completed", "This checkout has already been completed")
|
||||
}
|
||||
|
||||
if (!isCanceled(cart)) {
|
||||
await sdk.store.cart.update(cart.id, { metadata: { ...cart.metadata, [CANCELED_KEY]: true } })
|
||||
}
|
||||
const updated = await retrieveCart(cart.id)
|
||||
return updated
|
||||
? ucpResult(CHECKOUT, await toUcpCheckoutBody(request, updated))
|
||||
: checkoutNotFound()
|
||||
}
|
||||
203
apps/suman-hrvatska/src/lib/ucp/ucp.ts
Normal file
203
apps/suman-hrvatska/src/lib/ucp/ucp.ts
Normal file
@@ -0,0 +1,203 @@
|
||||
import { isVariantInStock } from "@lib/util/inventory"
|
||||
import { HttpTypes } from "@medusajs/types"
|
||||
|
||||
export const UCP_VERSION = "2026-08-25"
|
||||
export const UCP_REST_BASE_PATH = "/ucp/v1"
|
||||
export const UCP_MCP_PATH = "/ucp/mcp"
|
||||
|
||||
const capability = (path: string, schema: string) => ({
|
||||
spec: `https://ucp.dev/${UCP_VERSION}/specification/shopping/${path}`,
|
||||
schema: `https://ucp.dev/${UCP_VERSION}/schemas/shopping/${schema}.json`,
|
||||
})
|
||||
|
||||
export const UCP_CAPABILITIES = {
|
||||
"dev.ucp.shopping.catalog.search": capability("catalog/search", "catalog_search"),
|
||||
"dev.ucp.shopping.catalog.lookup": capability("catalog/lookup", "catalog_lookup"),
|
||||
"dev.ucp.shopping.cart": capability("cart", "cart"),
|
||||
"dev.ucp.shopping.checkout": capability("checkout", "checkout"),
|
||||
} as const
|
||||
|
||||
export type CapabilityName = keyof typeof UCP_CAPABILITIES
|
||||
|
||||
export type UcpResult = { status: number; body: Record<string, unknown> }
|
||||
|
||||
export const UCP_PRODUCT_FIELDS =
|
||||
"id,title,handle,description,thumbnail,*images,*options,*variants,+variants.inventory_quantity,+variants.manage_inventory,+variants.allow_backorder,*variants.calculated_price,*variants.options"
|
||||
|
||||
export const UCP_CART_FIELDS =
|
||||
"id,email,currency_code,region_id,completed_at,metadata,*items,+items.subtotal,+items.total,item_subtotal,discount_total,shipping_total,tax_total,total,*region.countries,*shipping_address"
|
||||
|
||||
const minorUnitDigits = (currency: string) =>
|
||||
new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions()
|
||||
.maximumFractionDigits ?? 2
|
||||
|
||||
/** Converts a Medusa amount (major units) to UCP minor units. */
|
||||
export const toMinorUnits = (amount: number | null | undefined, currencyCode: string) =>
|
||||
Math.round((amount ?? 0) * 10 ** minorUnitDigits(currencyCode.toUpperCase()))
|
||||
|
||||
const toMoney = (amount: number | null | undefined, currencyCode: string) => ({
|
||||
amount: toMinorUnits(amount, currencyCode),
|
||||
currency: currencyCode.toUpperCase(),
|
||||
})
|
||||
|
||||
export const ucpResult = (
|
||||
name: CapabilityName,
|
||||
body: Record<string, unknown>,
|
||||
status = 200
|
||||
): UcpResult => ({
|
||||
status,
|
||||
body: {
|
||||
ucp: {
|
||||
version: UCP_VERSION,
|
||||
status: status < 400 ? "success" : "error",
|
||||
capabilities: { [name]: [{ version: UCP_VERSION }] },
|
||||
...(name === "dev.ucp.shopping.checkout" ? { payment_handlers: {} } : {}),
|
||||
},
|
||||
...body,
|
||||
},
|
||||
})
|
||||
|
||||
export const ucpError = (
|
||||
name: CapabilityName,
|
||||
status: number,
|
||||
code: string,
|
||||
content: string
|
||||
): UcpResult =>
|
||||
ucpResult(
|
||||
name,
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
type: "error",
|
||||
code,
|
||||
content,
|
||||
severity: status >= 500 ? "recoverable" : "unrecoverable",
|
||||
},
|
||||
],
|
||||
},
|
||||
status
|
||||
)
|
||||
|
||||
export const toResponse = ({ status, body }: UcpResult) =>
|
||||
Response.json(body, { status, headers: { "Cache-Control": "no-store" } })
|
||||
|
||||
export const readJsonBody = async (
|
||||
request: Request
|
||||
): Promise<Record<string, unknown> | null> => {
|
||||
try {
|
||||
const body = await request.json()
|
||||
return body && typeof body === "object" && !Array.isArray(body) ? body : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const toUcpProduct = (
|
||||
product: HttpTypes.StoreProduct,
|
||||
currencyCode: string,
|
||||
productUrl: string
|
||||
) => {
|
||||
const optionTitles = new Map(
|
||||
(product.options ?? []).map((option) => [option.id, option.title])
|
||||
)
|
||||
const variants = (product.variants ?? []).filter(
|
||||
(variant) => variant.calculated_price?.calculated_amount != null
|
||||
)
|
||||
const amounts = variants.map((v) => v.calculated_price!.calculated_amount!)
|
||||
|
||||
return {
|
||||
id: product.id,
|
||||
handle: product.handle,
|
||||
title: product.title,
|
||||
description: product.description ?? "",
|
||||
url: productUrl,
|
||||
media: (product.images ?? []).map((image) => ({
|
||||
type: "image",
|
||||
url: image.url,
|
||||
alt_text: product.title,
|
||||
})),
|
||||
price_range: amounts.length
|
||||
? {
|
||||
min: toMoney(Math.min(...amounts), currencyCode),
|
||||
max: toMoney(Math.max(...amounts), currencyCode),
|
||||
}
|
||||
: undefined,
|
||||
variants: variants.map((variant) => {
|
||||
const available = isVariantInStock(variant)
|
||||
return {
|
||||
id: variant.id,
|
||||
sku: variant.sku ?? undefined,
|
||||
title: variant.title ?? product.title,
|
||||
url: `${productUrl}?v_id=${variant.id}`,
|
||||
price: toMoney(variant.calculated_price!.calculated_amount, currencyCode),
|
||||
availability: { available, status: available ? "in_stock" : "out_of_stock" },
|
||||
options: (variant.options ?? []).map((value) => ({
|
||||
name: optionTitles.get(value.option_id ?? "") ?? "",
|
||||
value: value.value,
|
||||
})),
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
export const toUcpLineItems = (cart: HttpTypes.StoreCart) =>
|
||||
(cart.items ?? []).map((item) => ({
|
||||
id: item.id,
|
||||
item: {
|
||||
id: item.variant_id,
|
||||
title: [item.product_title, item.variant_title].filter(Boolean).join(" - "),
|
||||
price: toMinorUnits(item.unit_price, cart.currency_code),
|
||||
},
|
||||
quantity: item.quantity,
|
||||
totals: [
|
||||
{ type: "subtotal", amount: toMinorUnits(item.subtotal, cart.currency_code) },
|
||||
{ type: "total", amount: toMinorUnits(item.total, cart.currency_code) },
|
||||
],
|
||||
}))
|
||||
|
||||
export const toUcpTotals = (cart: HttpTypes.StoreCart) => [
|
||||
{ type: "subtotal", amount: toMinorUnits(cart.item_subtotal, cart.currency_code) },
|
||||
{ type: "discount", amount: toMinorUnits(cart.discount_total, cart.currency_code) },
|
||||
{ type: "fulfillment", amount: toMinorUnits(cart.shipping_total, cart.currency_code) },
|
||||
{ type: "tax", amount: toMinorUnits(cart.tax_total, cart.currency_code) },
|
||||
{ type: "total", amount: toMinorUnits(cart.total, cart.currency_code) },
|
||||
]
|
||||
|
||||
const MAX_LINE_ITEMS = 50
|
||||
const MAX_QUANTITY = 100
|
||||
|
||||
/** Validates a UCP `line_items` array into Medusa variant/quantity pairs. */
|
||||
export const parseLineItems = (
|
||||
value: unknown
|
||||
): { variant_id: string; quantity: number }[] | null => {
|
||||
if (!Array.isArray(value) || value.length > MAX_LINE_ITEMS) {
|
||||
return null
|
||||
}
|
||||
|
||||
const items: { variant_id: string; quantity: number }[] = []
|
||||
for (const entry of value) {
|
||||
const id = entry?.item?.id
|
||||
const quantity = entry?.quantity
|
||||
if (
|
||||
typeof id !== "string" ||
|
||||
!id ||
|
||||
!Number.isInteger(quantity) ||
|
||||
quantity < 1 ||
|
||||
quantity > MAX_QUANTITY
|
||||
) {
|
||||
return null
|
||||
}
|
||||
items.push({ variant_id: id, quantity })
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
export const cartCountryCode = (cart: HttpTypes.StoreCart) =>
|
||||
(
|
||||
cart.shipping_address?.country_code ??
|
||||
cart.region?.countries?.[0]?.iso_2 ??
|
||||
""
|
||||
).toLowerCase()
|
||||
|
||||
export const cartContinueUrl = (origin: string, cart: HttpTypes.StoreCart) =>
|
||||
`${origin}/${cartCountryCode(cart)}/cart/resume/${cart.id}`
|
||||
6
apps/suman-hrvatska/src/lib/util/cart-events.ts
Normal file
6
apps/suman-hrvatska/src/lib/util/cart-events.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export const CART_UPDATED_EVENT = "medusa:cart-updated"
|
||||
|
||||
/** Lets client-loaded cart UI refresh after a mutation on statically rendered pages. */
|
||||
export const notifyCartUpdated = () => {
|
||||
window.dispatchEvent(new Event(CART_UPDATED_EVENT))
|
||||
}
|
||||
28
apps/suman-hrvatska/src/lib/util/compare-addresses.ts
Normal file
28
apps/suman-hrvatska/src/lib/util/compare-addresses.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { isEqual, pick } from "lodash"
|
||||
|
||||
export default function compareAddresses(address1: object, address2: object) {
|
||||
return isEqual(
|
||||
pick(address1, [
|
||||
"first_name",
|
||||
"last_name",
|
||||
"address_1",
|
||||
"company",
|
||||
"postal_code",
|
||||
"city",
|
||||
"country_code",
|
||||
"province",
|
||||
"phone",
|
||||
]),
|
||||
pick(address2, [
|
||||
"first_name",
|
||||
"last_name",
|
||||
"address_1",
|
||||
"company",
|
||||
"postal_code",
|
||||
"city",
|
||||
"country_code",
|
||||
"province",
|
||||
"phone",
|
||||
])
|
||||
)
|
||||
}
|
||||
3
apps/suman-hrvatska/src/lib/util/env.ts
Normal file
3
apps/suman-hrvatska/src/lib/util/env.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export const getBaseURL = () => {
|
||||
return process.env.NEXT_PUBLIC_BASE_URL || "https://localhost:8000"
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user