import { varietyName } from "./varieties";
/**
* Adresse und Schlüssel des Backends stehen bewusst nicht mehr fest im Build.
* Sonst gehört jedes Image zu genau einer Umgebung, und ein Adresswechsel
* heißt neu bauen, hochladen, neu ausrollen.
*
* Auf dem Server kommen die Werte aus der Umgebung, im Browser aus zwei
* -Tags, die das Layout mitschickt. Damit passt ein Image für Heimnetz,
* Testsystem und Produktion.
*/
function meta(name: string): string | undefined {
return document.querySelector(`meta[name="${name}"]`)?.content || undefined;
}
export function medusaConfig(): { url: string; key: string } {
if (typeof document !== "undefined") {
return {
url: meta("medusa-backend-url") ?? "",
key: meta("medusa-publishable-key") ?? "",
};
}
const env = typeof process !== "undefined" ? process.env : ({} as Record);
return {
// Innerhalb des Containers geht es direkt zum Backend, ohne den Umweg
// über den Reverse Proxy. Fehlt der Wert, gilt die öffentliche Adresse.
url: env.MEDUSA_INTERNAL_URL || env.PUBLIC_MEDUSA_BACKEND_URL || import.meta.env.PUBLIC_MEDUSA_BACKEND_URL || "",
key: env.PUBLIC_MEDUSA_PUBLISHABLE_KEY || import.meta.env.PUBLIC_MEDUSA_PUBLISHABLE_KEY || "",
};
}
export async function medusaFetch(path: string, init?: RequestInit) {
const { url: BACKEND_URL, key: PUBLISHABLE_KEY } = medusaConfig();
const res = await fetch(`${BACKEND_URL}${path}`, {
...init,
headers: {
"Content-Type": "application/json",
"x-publishable-api-key": PUBLISHABLE_KEY,
...init?.headers,
},
});
const body = await res.json().catch(() => ({}));
if (!res.ok) {
throw new Error(body?.message || `Medusa request failed: ${path} (${res.status})`);
}
return body;
}
export interface ShopShippingOption {
id: string;
name: string;
description: string | null;
/** Grundpreis in Euro, ohne die Schwellenregel. */
amount: number;
}
export interface ShopSettings {
/** Schwelle für kostenfreien Versand in Euro, `null` wenn es keine gibt. */
freeShippingThreshold: number | null;
/** Die Versandarten, die der Shop anbietet, nach Preis sortiert. */
shippingOptions: ShopShippingOption[];
}
// Der Wert steht auf jeder Shop-Seite und ändert sich fast nie. Ohne diesen
// kurzen Puffer liefe je Seitenaufruf eine eigene Anfrage an Medusa.
let settingsCache: { wert: ShopSettings; bis: number } | null = null;
const SETTINGS_TTL_MS = 60_000;
/**
* Die Shop-Einstellungen aus dem Backend.
*
* Fällt still auf "keine Schwelle" zurück, wenn das Backend nicht antwortet:
* lieber gar kein Versprechen als eines, das gerade nicht belegt ist.
*/
export async function getShopSettings(): Promise {
if (settingsCache && settingsCache.bis > Date.now()) return settingsCache.wert;
try {
const data = await medusaFetch("/store/shop-settings");
const schwelle = Number(data?.free_shipping_threshold);
const wert: ShopSettings = {
freeShippingThreshold: Number.isFinite(schwelle) && schwelle > 0 ? schwelle : null,
shippingOptions: Array.isArray(data?.shipping_options)
? data.shipping_options.map((option: any) => ({
id: option.id,
name: option.name,
description: option.description ?? null,
amount: option.amount,
}))
: [],
};
settingsCache = { wert, bis: Date.now() + SETTINGS_TTL_MS };
return wert;
} catch {
return { freeShippingThreshold: null, shippingOptions: [] };
}
}
export interface MedusaVariant {
id: string;
title: string;
calculated_price?: { calculated_amount: number; currency_code: string };
metadata?: {
net_weight_grams?: number;
/** Nur am Abo-Produkt: "monthly" | "quarterly" | "biannual". */
subscription_interval?: string;
/** Nur am Abo-Produkt: Glasgröße, z. B. "250 Gramm". */
subscription_size?: string;
} | null;
thumbnail?: string | null;
}
export interface MedusaProduct {
id: string;
title: string;
/** Claim unter dem Titel, z. B. "Lakritz trifft Honig." */
subtitle?: string | null;
handle: string;
description: string | null;
thumbnail: string | null;
images?: { id: string; url: string }[];
variants: MedusaVariant[];
/** `subscription: true` markiert das Abo-Produkt. */
metadata?: {
/** Zeile über dem Titel statt des Kategorienamens, z. B. "Honig. Aber Anders." */
label?: string;
delivery_time?: string;
subscription?: boolean;
/** Hilfsartikel: gehört nicht ins Sortiment. */
hidden?: boolean;
/** Nur am Abo: "once" oder "per_delivery" — wie beim Geschenk der Versand berechnet wird. */
gift_shipping?: "once" | "per_delivery";
/** Bienenpatenschaft: braucht Namen für Urkunde und Etikett. */
sponsorship?: boolean;
} | null;
categories?: { id: string; name: string; rank: number }[];
options?: { id: string; title: string }[];
}
// Pulls in the custom metadata (delivery time, net fill weight) and the
// real Medusa product categories on top of the default product/variant
// fields.
const PRODUCT_FIELDS =
"*variants.calculated_price,+metadata,+variants.metadata,+variants.thumbnail,+categories.name,+categories.rank";
export async function listProducts(regionId?: string): Promise {
const params = new URLSearchParams({ fields: PRODUCT_FIELDS });
if (regionId) params.set("region_id", regionId);
const data = await medusaFetch(`/store/products?${params}`);
// Hilfsartikel wie der Versandanteil eines Geschenk-Abos gehören nicht ins
// Sortiment — sie werden nur automatisch mitverkauft.
return (data.products as MedusaProduct[]).filter((product) => !product.metadata?.hidden);
}
/**
* Der Artikel, über den der Versandanteil weiterer Geschenk-Pakete
* berechnet wird. `null`, wenn er nicht eingerichtet ist — dann wird nichts
* berechnet und der Shop verspricht es auch nicht.
*/
export async function getGiftShippingSurcharge(
regionId?: string
): Promise<{ variantId: string; amount: number } | null> {
const produkt = await getProductByHandle("versandanteil-geschenk-abo", regionId);
const variante = produkt?.variants?.[0];
const betrag = variante?.calculated_price?.calculated_amount;
if (!variante || betrag == null) return null;
return { variantId: variante.id, amount: betrag };
}
export async function getProductByHandle(handle: string, regionId?: string): Promise {
const params = new URLSearchParams({ handle, fields: PRODUCT_FIELDS });
if (regionId) params.set("region_id", regionId);
const data = await medusaFetch(`/store/products?${params}`);
return data.products[0] ?? null;
}
export interface MedusaRegion {
id: string;
currency_code: string;
}
export async function getDefaultRegion(): Promise {
const data = await medusaFetch("/store/regions");
return data.regions[0];
}
/** Glasgrößen, die im Abo wählbar sind. Spiegelt HONEY_SIZES im Backend. */
export const SUBSCRIPTION_SIZES = ["250 Gramm", "500 Gramm"] as const;
export interface HoneyVariety {
variantId: string;
/** Der volle Katalogtitel. */
productTitle: string;
/** Der kurze Sortenname aus dem Briefing — das, was angezeigt wird. */
name: string;
size: string;
}
/**
* Honigsorten je Glasgröße, für die Sortenauswahl im Abo.
*
* Leitet sich aus dem normalen Katalog ab statt aus einer gepflegten Liste:
* kommt eine Sorte dazu, steht sie automatisch im Abo zur Wahl.
*/
export async function listHoneyVarieties(regionId?: string): Promise {
const products = await listProducts(regionId);
const varieties: HoneyVariety[] = [];
for (const product of products) {
const isHoney = (product.categories ?? []).some((category) => category.name === "Honig");
if (!isHoney) continue;
for (const variant of product.variants) {
if (!SUBSCRIPTION_SIZES.includes(variant.title as any)) continue;
varieties.push({
variantId: variant.id,
productTitle: product.title,
name: varietyName(product.title),
size: variant.title,
});
}
}
return varieties.sort((a, b) => a.name.localeCompare(b.name, "de"));
}